Merge f-ling32-sycl-ren (e8b28c7588): SYCL MLA expanded prefill + KDA value-column scan, STRATA_L32_* switch names, register entries

This commit is contained in:
Niko1221 committed 2026-12-03 04:32:51 +01:00
commit ddae5fef68
21 files changed
+1572 -31

No files matched your search

+4 -1
View File
@@ -487,7 +487,7 @@ Off unless you set them. The last column says where each one is described.
| `STRATA_WATCHDOG_S` | text | NVIDIA and AMD, Intel Arc | [DETAILS.md](DETAILS.md) |
| `STRATA_WDDM_BUDGET` | number | AMD, Intel Arc | [AMD_HIP.md](AMD_HIP.md) |
## Switches that go back to earlier behaviour (185)
## Switches that go back to earlier behaviour (188)
These behaviours are on by default. Setting the switch returns the earlier behaviour; the notes in the register say which
version made it the default.
@@ -589,8 +589,11 @@ version made it the default.
| `STRATA_L32_BIGSLOTS` | on / off | NVIDIA and AMD | - | - |
| `STRATA_L32_BUFFERED` | on / off | NVIDIA and AMD | - | - |
| `STRATA_L32_GATE_ROWS` | on / off | NVIDIA and AMD | - | - |
| `STRATA_L32_KDA_SEQ` | number | Intel Arc | - | - |
| `STRATA_L32_LAZY_KV` | on / off | NVIDIA and AMD | - | - |
| `STRATA_L32_MLA_EXPANDED` | on / off | NVIDIA and AMD | - | - |
| `STRATA_L32_MLA_EXP_MODE` | number | Intel Arc | - | - |
| `STRATA_L32_MLA_FD_ORIG` | on / off | Intel Arc | - | - |
| `STRATA_L32_MTP_FLOOR` | on / off | NVIDIA and AMD | - | - |
| `STRATA_L32_MTP_GROUPED` | on / off | NVIDIA and AMD | - | - |
| `STRATA_L32_MTP_PLAIN` | on / off | NVIDIA and AMD | - | - |
@@ -24,6 +24,13 @@
#include <unordered_map>
#include <vector>
// profiling build (-DSTRATA_SY_PROFILE, see sycl/ling32_sy.hpp sy::launch): the queues record kernel times; the normal build is unchanged
#ifdef STRATA_SY_PROFILE
#define STRATA_SY_QUEUE_PROPS sycl::property_list{sycl::property::queue::in_order(), sycl::property::queue::enable_profiling()}
#else
#define STRATA_SY_QUEUE_PROPS sycl::property_list{sycl::property::queue::in_order()}
#endif
#ifndef STRATA_USE_SYCL
#define STRATA_USE_SYCL 1
#endif
@@ -71,7 +78,7 @@ struct Runtime {
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)};
auto* s = new Stream{sycl::queue(devs[i]->ctx, devs[i]->dev, STRATA_SY_QUEUE_PROPS), static_cast<int>(i)};
devs[i]->def = s;
streams.push_back(s);
}
@@ -341,7 +348,7 @@ inline cudaError_t cudaMemsetAsync(void* p, int v, size_t n, cudaStream_t s = nu
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()};
auto* st = new strata::sy::Stream{sycl::queue(ds.ctx, ds.dev, STRATA_SY_QUEUE_PROPS), strata::sy::cur_dev()};
{ std::lock_guard<std::mutex> g(strata::sy::rt().mu); strata::sy::rt().streams.push_back(st); }
*s = st;
});
+6
View File
@@ -154,6 +154,12 @@ if(LING32_SYCL)
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_mla_exp_test ${_tests_dir}/ling32_sy_mla_exp_test.cpp) # L32-SY-MLA: expanded-form MLA prefill against the absorbed pipeline
target_link_libraries(ling32_sy_mla_exp_test PRIVATE ling32_gpu)
add_test(NAME ling32_sy_mla_exp_test COMMAND ling32_sy_mla_exp_test)
add_executable(ling32_sy_kda_test ${_tests_dir}/ling32_sy_kda_test.cpp) # L32-SY-MLA: the chunk-parallel KDA prefill scan against the sequential recurrence, with timings
target_link_libraries(ling32_sy_kda_test PRIVATE ling32_gpu)
add_test(NAME ling32_sy_kda_test COMMAND ling32_sy_kda_test skip-big)
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)
set_source_files_properties(${_tests_dir}/ling32_vision_gpu_test.cu PROPERTIES LANGUAGE CXX) # L32-SY-VISION: the GPU picture encoder against the golden set (the CUDA test, compiled as C++ against the shim; run by hand)
+1 -1
View File
@@ -1257,7 +1257,7 @@ bool Ling32Engine::init(GpuModel& model, const EngineOptions& o, std::string& er
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");
if (opt.mla_expanded && !gpu::mla_exp_ok(128, 64, 128, 512)) off(opt.mla_expanded, "--mla-prefill expanded (needs the XMX engines)"); // the joint_matrix kernel of sycl/ling32_sy_k_mla_exp.cpp
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).
+6
View File
@@ -1800,6 +1800,12 @@ int main(int argc, char** argv) {
const char* ev = std::getenv("STRATA_L32_MLA_EXPANDED"); // =0: back to the absorbed form without a rebuild
if (!(ev && ev[0] == '0')) { o.mla_expanded = true; o.mla_exp_min_n = 1024; }
}
#if defined(STRATA_USE_SYCL)
if (!o.mla_prefill_set && !o.mla_expanded) { // Intel Battlemage (XMX): the expanded-form MLA prefill (joint_matrix, hi/lo fp16 splits, about fp32) for every prefill chunk; the absorbed original kernel is far slower there
const char* ev = std::getenv("STRATA_L32_MLA_EXPANDED"); // =0: back to the absorbed form without a rebuild
if (!(ev && ev[0] == '0') && gpu::mla_exp_ok(128, 64, 128, 512)) { o.mla_expanded = true; o.mla_exp_min_n = 32; }
}
#endif
#if defined(STRATA_USE_HIP)
{ // gfx12: the expanded-form WMMA MLA for prefill chunks is the default (owner decision 2026-12-02, after the R9700 goldens); gfx11 and the other AMD cards keep the absorbed kernel
cudaDeviceProp dpx{};
+60
View File
@@ -21,6 +21,16 @@
#include <sycl/sycl.hpp>
#include <cstdint>
#ifdef STRATA_SY_PROFILE
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
#endif
namespace strata::ling32::gpu::sy {
@@ -52,15 +62,65 @@ struct Blk {
};
// 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).
#ifdef STRATA_SY_PROFILE
// per-kernel profile (profiling build only): every launch records its sycl::event under "caller:line"; the totals are printed at exit (STRATA_SY_PROF_TOP lines, default 40)
struct ProfLog {
std::mutex m;
std::vector<std::pair<std::string, sycl::event>> ev;
std::vector<int> gridsum;
~ProfLog() {}
};
inline ProfLog& prof_log() { static ProfLog* p = new ProfLog(); return *p; }
inline void prof_dump() {
ProfLog& L = prof_log();
std::map<std::string, std::pair<double, long>> agg;
double total = 0;
for (auto& e : L.ev) {
try {
e.second.wait();
const double ns = static_cast<double>(e.second.get_profiling_info<sycl::info::event_profiling::command_end>() - e.second.get_profiling_info<sycl::info::event_profiling::command_start>());
auto& a = agg[e.first]; a.first += ns; a.second += 1; total += ns;
} catch (...) {}
}
std::vector<std::pair<std::string, std::pair<double, long>>> v(agg.begin(), agg.end());
std::sort(v.begin(), v.end(), [](auto& a, auto& b) { return a.second.first > b.second.first; });
const char* t = std::getenv("STRATA_SY_PROF_TOP");
const size_t top = t ? static_cast<size_t>(std::atoi(t)) : 40;
std::printf("SYPROF kernel time total %.1f ms over %zu launches\n", total / 1e6, L.ev.size());
for (size_t i = 0; i < v.size() && i < top; ++i)
std::printf("SYPROF %8.1f ms %5.1f %% %7ld launches %9.1f us each %s\n", v[i].second.first / 1e6, 100.0 * v[i].second.first / (total > 0 ? total : 1), v[i].second.second, v[i].second.first / 1e3 / static_cast<double>(v[i].second.second), v[i].first.c_str());
std::fflush(stdout);
}
inline void prof_record(const char* fn, int line, sycl::event e) {
ProfLog& L = prof_log();
std::lock_guard<std::mutex> g(L.m);
static bool reg = (std::atexit(prof_dump), true);
(void)reg;
L.ev.emplace_back(std::string(fn) + ":" + std::to_string(line), e);
}
#endif
template <class F>
#ifdef STRATA_SY_PROFILE
inline void launch(cudaStream_t s, int grid, int block, size_t smem, F f, const char* pfn = __builtin_FUNCTION(), int pline = __builtin_LINE()) {
#else
inline void launch(cudaStream_t s, int grid, int block, size_t smem, F f) {
#endif
auto& q = strata::sy::queue_of(s);
#ifdef STRATA_SY_PROFILE
prof_record(pfn, pline, q.submit([&](sycl::handler& h) {
#else
q.submit([&](sycl::handler& h) {
#endif
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());
});
#ifdef STRATA_SY_PROFILE
}));
#else
});
#endif
}
// ---------------------------------------------------------------------------------------------------- shared device primitives (ports of ling32_dev.cuh; helper owners extend, never fork)
+171 -3
View File
@@ -187,6 +187,7 @@ void launch_step(float* S, const float* qn, const float* kn, const float* vc, co
// 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;
using float4 = sycl::float4;
template <int HD, int CH>
constexpr size_t kda_chunk_scr_floats() { return 3ull * CH * HD + 2ull * CH * CH + CH + HD; }
@@ -359,6 +360,154 @@ void launch_chunk_seq(float* S, const float* vc, const float* g_raw, int gs, con
});
}
// ---------------------------------------------------------------------------------------------- the chunk scan split over the value columns (launch_chunk_seq2)
// The delta-rule state update is independent per value column v given the state-independent chunk tiles of launch_chunk_pre, so the serial scan of a head runs as HD / 32 work-groups (one per 32 value columns),
// each with G sub-groups: sub-group g owns the key rows d in [g HD / G, (g + 1) HD / G) of the state of its 32 columns (HD / G floats per lane, registers), lanes are the columns. Per chunk: the partial sums over
// d of kE s (for U) and qE s (for the output) are exchanged through shared memory, every sub-group then computes U (8 steps) and the output row of its column redundantly, and updates its rows of the state.
// The gated RMS norm of the output needs a whole row (all columns): the scan writes the raw output O into out, launch_chunk_norm normalises it in place. The chunk tiles of the next chunk are loaded into
// registers before the compute of the current one and stored into the other shared-memory buffer after it (two barriers per chunk). The summation order over d differs from launch_chunk_seq (partial sums per
// key-row group), the result is the same function in fp32 (the forward and kernel tests compare against the reference).
template <int HD, int CH, int G>
void launch_chunk_seq2(float* S, const float* vc, float* out, int N, int H, const float* scr, cudaStream_t st) {
constexpr int VT = 32, NVT = HD / VT, NT = VT * G, DPT = HD / G, FL = static_cast<int>(kda_chunk_scr_floats<HD, CH>());
constexpr int TAIL = 2 * CH * CH + CH + HD; // A, Aq, b, eGl: contiguous in the scratch
constexpr int BUF = 3 * CH * HD + TAIL + CH * VT; // kE, qE, k, A, Aq, b, eGl, vc of one chunk
constexpr int NKQ4 = 3 * CH * HD / 4, PKQ = (NKQ4 + NT - 1) / NT, TAIL4 = TAIL / 4, PVC = (CH * VT + NT - 1) / NT;
static_assert(TAIL % 4 == 0 && FL % 4 == 0 && HD % (4 * G) == 0, "KDA chunk scan: tile sizes must be multiples of 4");
const size_t smem = (2ull * BUF + static_cast<size_t>(G) * 16 * VT) * sizeof(float);
sy::launch(st, H * NVT, NT, smem, [=](sy::Blk b, char* smemp) {
float* buf0 = reinterpret_cast<float*>(smemp);
float* buf1 = buf0 + BUF;
float* part = buf1 + BUF; // [G][16][VT]: partial sums of kE s (0..7) and qE s (8..15)
const int h = b.bid() % H, vt = b.bid() / H, tid = b.tid(), g = tid >> 5, lane = tid & 31, C = H * HD;
const int v = vt * VT + lane;
float s[DPT];
float* Sh = S + static_cast<size_t>(h) * HD * HD;
for (int j = 0; j < DPT; ++j) s[j] = Sh[static_cast<size_t>(g * DPT + j) * HD + v];
const int nch = (N + CH - 1) / CH;
// chunk tiles -> registers (kq: kE, qE, k as float4; tail: A, Aq, b, eGl; vcr: the 32 value columns of this work-group)
float4 kq[PKQ], tl;
float vcr[PVC];
auto fetch = [&](int ci) {
const float* src = scr + (static_cast<size_t>(ci) * H + h) * FL;
const int s0 = ci * CH, c = sycl::min(CH, N - s0);
for (int i = 0; i < PKQ; ++i) {
const int u = tid + i * NT;
if (u < NKQ4) kq[i] = *reinterpret_cast<const float4*>(src + 4 * u);
}
if (tid < TAIL4) tl = *reinterpret_cast<const float4*>(src + 3 * CH * HD + 4 * tid);
for (int i = 0; i < PVC; ++i) {
const int u = tid + i * NT, t = u / VT, l = u % VT;
vcr[i] = (u < CH * VT && t < c) ? vc[static_cast<size_t>(s0 + t) * C + h * HD + vt * VT + l] : 0.0f;
}
};
auto stash = [&](float* dst) {
for (int i = 0; i < PKQ; ++i) {
const int u = tid + i * NT;
if (u < NKQ4) *reinterpret_cast<float4*>(dst + 4 * u) = kq[i];
}
if (tid < TAIL4) *reinterpret_cast<float4*>(dst + 3 * CH * HD + 4 * tid) = tl;
for (int i = 0; i < PVC; ++i) {
const int u = tid + i * NT;
if (u < CH * VT) dst[3 * CH * HD + TAIL + u] = vcr[i];
}
};
fetch(0);
stash(buf0);
b.sync();
for (int ci = 0; ci < nch; ++ci) {
const float* cb = (ci & 1) ? buf1 : buf0;
const int s0 = ci * CH, c = sycl::min(CH, N - s0);
if (ci + 1 < nch) fetch(ci + 1);
const float* kEb = cb;
const float* qEb = cb + CH * HD;
const float* kb = cb + 2 * CH * HD;
const float* Ab = cb + 3 * CH * HD;
const float* Aqb = Ab + CH * CH;
const float* bb = Aqb + CH * CH;
const float* eGlb = bb + CH;
const float* vcb = cb + 3 * CH * HD + TAIL;
// partial sums over the key rows of this sub-group (rows t >= c hold stale tiles: never used)
float accd[CH], O[CH];
for (int t = 0; t < CH; ++t) { accd[t] = 0.0f; O[t] = 0.0f; }
for (int j4 = 0; j4 < DPT / 4; ++j4) {
const int d0 = g * DPT + j4 * 4;
for (int t = 0; t < CH; ++t) {
const float4 ke = *reinterpret_cast<const float4*>(kEb + t * HD + d0);
const float4 qe = *reinterpret_cast<const float4*>(qEb + t * HD + d0);
float a = accd[t], o = O[t];
a += ke.x() * s[4 * j4]; o += qe.x() * s[4 * j4];
a += ke.y() * s[4 * j4 + 1]; o += qe.y() * s[4 * j4 + 1];
a += ke.z() * s[4 * j4 + 2]; o += qe.z() * s[4 * j4 + 2];
a += ke.w() * s[4 * j4 + 3]; o += qe.w() * s[4 * j4 + 3];
accd[t] = a;
O[t] = o;
}
}
for (int t = 0; t < CH; ++t) {
part[(g * 16 + t) * VT + lane] = accd[t];
part[(g * 16 + CH + t) * VT + lane] = O[t];
}
b.sync();
for (int t = 0; t < CH; ++t) {
float a = part[t * VT + lane], o = part[(CH + t) * VT + lane];
for (int gg = 1; gg < G; ++gg) {
a += part[(gg * 16 + t) * VT + lane];
o += part[(gg * 16 + CH + t) * VT + lane];
}
accd[t] = a;
O[t] = o;
}
float U[CH];
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 += Ab[t * CH + i] * U[i];
const float bt = bb[t];
U[t] = bt * (vcb[t * VT + lane] - accd[t]) - bt * sub;
}
}
for (int t = 0; t < CH; ++t)
if (t < c) {
float o = O[t];
for (int i = 0; i <= t; ++i) o += Aqb[t * CH + i] * U[i];
O[t] = o;
if (g == 0) out[static_cast<size_t>(s0 + t) * C + h * HD + v] = o;
}
for (int j4 = 0; j4 < DPT / 4; ++j4) {
const int d0 = g * DPT + j4 * 4;
const float4 eg = *reinterpret_cast<const float4*>(eGlb + d0);
float a0 = eg.x() * s[4 * j4], a1 = eg.y() * s[4 * j4 + 1], a2 = eg.z() * s[4 * j4 + 2], a3 = eg.w() * s[4 * j4 + 3];
for (int i = 0; i < CH; ++i)
if (i < c) {
const float4 kv = *reinterpret_cast<const float4*>(kb + i * HD + d0);
a0 += kv.x() * U[i]; a1 += kv.y() * U[i]; a2 += kv.z() * U[i]; a3 += kv.w() * U[i];
}
s[4 * j4] = a0; s[4 * j4 + 1] = a1; s[4 * j4 + 2] = a2; s[4 * j4 + 3] = a3;
}
if (ci + 1 < nch) stash((ci & 1) ? buf0 : buf1);
b.sync();
}
for (int j = 0; j < DPT; ++j) Sh[static_cast<size_t>(g * DPT + j) * HD + v] = s[j];
});
}
// out[tok][h][v] = O r o_norm[v] sigmoid(g): the gated RMS norm over the whole row of the raw output the scan left in out (same expressions as launch_chunk_seq)
template <int HD>
void launch_chunk_norm(const float* g_raw, int gs, const float* o_norm, float eps, float* out, int N, int H, cudaStream_t st) {
sy::launch(st, N * H, HD, 40 * sizeof(float), [=](sy::Blk b, char* smemp) {
float* sm = reinterpret_cast<float*>(smemp);
const int tok = b.bid() % N, h = b.bid() / N, v = b.tid(), C = H * HD;
const size_t o_i = static_cast<size_t>(tok) * C + h * HD + v;
const float o = out[o_i];
const float ss = block_sum(b, o * o, sm);
const float r = 1.0f / sycl::sqrt(ss / static_cast<float>(HD) + eps);
out[o_i] = o * r * o_norm[v] * sigmoidf(g_raw[static_cast<size_t>(tok) * gs + h * HD + v]);
});
}
[[noreturn]] void bad_hd(int hd) {
std::fprintf(stderr, "ling32: KDA head dim %d is not built (64, 128)\n", hd);
std::abort();
@@ -366,6 +515,8 @@ void launch_chunk_seq(float* S, const float* vc, const float* g_raw, int gs, con
} // namespace
int g_sy_kda_seq_mode = -1; // tests / tuning: see kda_step (-1: STRATA_L32_KDA_SEQ, default 8)
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);
@@ -405,9 +556,26 @@ void kda_step(float* S, const float* qn, const float* kn, const float* vc, const
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);
static const int env_mode = std::getenv("STRATA_L32_KDA_SEQ") ? std::atoi(std::getenv("STRATA_L32_KDA_SEQ")) : -1;
if (g_sy_kda_seq_mode < 0) g_sy_kda_seq_mode = env_mode >= 0 ? env_mode : 8;
const int mode = g_sy_kda_seq_mode; // 0: the one-column-per-lane scan (launch_chunk_seq), 4 / 8: the scan split over the value columns with 4 / 8 key-row groups (launch_chunk_seq2) + the norm kernel
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);
if (mode == 0) launch_chunk_seq<128, kChunk>(S, vc, g_raw, gs, o_norm, eps, out, N, H, scratch, s);
else {
if (mode == 4) launch_chunk_seq2<128, kChunk, 4>(S, vc, out, N, H, scratch, s);
else launch_chunk_seq2<128, kChunk, 8>(S, vc, out, N, H, scratch, s);
launch_chunk_norm<128>(g_raw, gs, o_norm, eps, out, N, H, 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);
if (mode == 0) launch_chunk_seq<64, kChunk>(S, vc, g_raw, gs, o_norm, eps, out, N, H, scratch, s);
else {
if (mode == 4) launch_chunk_seq2<64, kChunk, 4>(S, vc, out, N, H, scratch, s);
else launch_chunk_seq2<64, kChunk, 8>(S, vc, out, N, H, scratch, s);
launch_chunk_norm<64>(g_raw, gs, o_norm, eps, out, N, H, 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);
@@ -0,0 +1,572 @@
// src/ling32/sycl/ling32_sy_k_mla_exp.cpp - EXPANDED-form MLA attention for long prefill chunks on Intel GPUs (SYCL), the port of ling32_mla_exp.cu. Owner: L32-SY-MLA.
//
// The absorbed form (q_abs . c, 576-deep scores, 512-wide value) costs 2 x (576 + 512) flops per (query, key, head); the expanded form projects the latent cache once per chunk into per-head keys
// K_nope = c . wk_b^T (128 wide) and values V = c . wv_b^T (128 wide) and runs attention with 192-deep scores (128 nope + 64 rope, the rope part is the shared k_pe) and a 128-wide value: 640 flops
// per pair (3.4x fewer), plus the projection. Numerics as in the CUDA kernel: every fp32 operand is split into fp16 hi + lo (x = hi + lo / 2048, hi = fp16(x), lo = fp16((x - hi) 2048)); a product is
// hi hi + (hi lo + lo hi) / 2048 accumulated in fp32 (~2^-22 per product, like an fp32 FMA chain). The BF16 weights are converted once to fp16 x 256 (exact) in the packed (VNNI-2) layout of the B operand.
//
// Structure (all kernels use 16-wide sub-groups; the matrix products are joint_matrix 8x16x16 on Battlemage / PVC, and a plain per-lane loop with the SAME tile layout everywhere else, so the logic
// is testable on any Intel GPU; mla_exp_ok() only says yes when the XMX engines exist, unless STRATA_L32_MLA_EXP_MODE=1 forces the plain loop for tests). joint_matrix_apply is not used anywhere (the offline
// compiler crashes on it in kernels of this size): accumulators are only filled, accumulated by mad and stored to shared memory; the combination of the main and the cross (lo) product and every
// rescale happen in plain code on the stored tiles.
// convert bf16 wk_b / wv_b [H][128][512] -> fp16 x 256 packed [H][256 k-pairs][128 outputs x 2] (element (k, n) at (k >> 1) * 256 + 2 n + (k & 1))
// qprep q [N][H][192] fp32 -> hi / lo planes [H][NP][192] fp16 (rows beyond N zero), NP = N rounded up to kBM
// proj per slab of S keys: grid (S / 16, H), 256 threads = 16 sub-groups, sub-group w = 16 of the 256 outputs (K_nope for w < 8, V for w >= 8) x 16 keys: main = c_hi W, cross = c_lo W over K = 512.
// Output: K planes (hi, lo) packed as B operand [H][96 d-pairs][S keys x 2] (rows 0..63 K_nope, 64..95 k_pe from the cache), V planes packed [H][S / 2 key-pairs][128 dims x 2].
// attn per slab: grid (NP / 32, H), 128 threads, sub-group w = (M tile w & 3 of 8 query rows) x (key half / dim half w >> 2). Per tile of 32 keys: K, V tiles to shared memory; scores
// S = Q K^T (3 DPAS per product, main and cross accumulators stored to shared memory); online softmax in plain code (4 threads per row), P as hi / lo A tiles; the products P V of the tile
// (fresh accumulators, stored through a small per-sub-group scratch) are added to the O state kept in registers (lane = column, 8 rows); (O, m, l) go to global memory between slabs.
// final out = O / l * sigmoid(gate)
// A row's arithmetic depends only on its own keys in 32-key tiles counted from key 0, so the result does not depend on the chunking of the prompt.
#include "ling32_sy.hpp"
#include <algorithm>
#include <cfloat>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <type_traits>
#if __has_include(<sycl/ext/oneapi/matrix/matrix.hpp>)
#include <sycl/ext/oneapi/matrix/matrix.hpp>
#define L32X_HAVE_JM 1
#else
#define L32X_HAVE_JM 0
#endif
#if L32X_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 L32X_PASS_JM16 1
#endif
#endif
#ifndef L32X_PASS_JM16
#define L32X_PASS_JM16 0
#endif
#ifndef L32X_SKIP
#define L32X_SKIP 0 // bisect aid for compiler crashes: 1 = no projection body, 2 = no attention body
#endif
namespace strata::ling32::gpu {
namespace {
constexpr int kNope = 128, kRope = 64, kQK = 192, kVD = 128, kR = 512;
constexpr int kBM = 32; // query rows per attention work-group
constexpr int kBK = 32; // keys per attention tile
constexpr int kAttThreads = 128;
constexpr int kProjThreads = 256;
constexpr int kLdK = 72; // halves per packed K row (32 keys x 2 + 8)
constexpr int kLdV = 264; // halves per packed V row (128 dims x 2 + 8)
constexpr int kLdP = 40; // halves per P row (32 keys + 8)
constexpr int kLdS = 36; // floats per score row
constexpr int kLdA = 72; // projection: halves per A row (64 + 8)
constexpr int kPK = 16; // projection: keys per work-group
constexpr int kLdR = 264; // projection: floats per result row (256 + 8)
constexpr float kInv2048 = 1.0f / 2048.0f;
constexpr float kNeg = -3.0e38f;
using sy::f2h;
using sy::h2f;
inline void split_h(float x, uint16_t& hi, uint16_t& lo) {
hi = f2h(x);
lo = f2h((x - h2f(hi)) * 2048.0f);
}
inline uint32_t pack2(uint16_t lo16, uint16_t hi16) { return static_cast<uint32_t>(lo16) | (static_cast<uint32_t>(hi16) << 16); }
#if L32X_PASS_JM16
namespace jm = sycl::ext::oneapi::experimental::matrix;
#endif
// ---------------------------------------------------------------------------------------------------- 8x16x16 tile operations: joint_matrix (J = true) or a plain per-lane loop with the same layout (J = false)
// accumulator 8 x 16 fp32 (logical element (row, col)); A operand 8 x 16 halves row-major; B operand 16 x 16 halves in the packed (VNNI-2) layout: element (k, n) at (k >> 1) * ld + 2 n + (k & 1)
template <bool J> struct Acc;
template <> struct Acc<false> { float v[8]; }; // lane = column, element i = row i
#if L32X_PASS_JM16
template <> struct Acc<true> { jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16> m; };
#endif
template <bool J> struct AOp;
template <> struct AOp<false> { const uint16_t* p; int ld; };
template <bool J> struct BOp;
template <> struct BOp<false> { const uint16_t* p; int ld; };
#if L32X_PASS_JM16
template <> struct AOp<true> { jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::a, 8, 16, jm::layout::row_major> m; };
template <> struct BOp<true> { jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, 16, jm::layout::ext_intel_packed> m; };
#endif
template <bool J> inline void acc_fill(const sy::Blk& b, Acc<J>& c, float x) {
if constexpr (J) {
#if L32X_PASS_JM16
jm::joint_matrix_fill(b.it.get_sub_group(), c.m, x);
#endif
} else {
for (int i = 0; i < 8; ++i) c.v[i] = x;
}
}
template <bool J, sycl::access::address_space AS> inline void acc_store(const sy::Blk& b, Acc<J>& c, float* p, int ld) {
if constexpr (J) {
#if L32X_PASS_JM16
auto mp = sycl::address_space_cast<AS, sycl::access::decorated::no>(p);
jm::joint_matrix_store(b.it.get_sub_group(), c.m, mp, ld, jm::layout::row_major);
#endif
} else {
const int ln = b.lane();
for (int i = 0; i < 8; ++i) p[static_cast<size_t>(i) * ld + ln] = c.v[i];
}
}
template <bool J, sycl::access::address_space AS> inline void a_load(const sy::Blk& b, AOp<J>& a, const uint16_t* p, int ld) {
if constexpr (J) {
#if L32X_PASS_JM16
auto mp = sycl::address_space_cast<AS, sycl::access::decorated::no>(const_cast<sycl::half*>(reinterpret_cast<const sycl::half*>(p)));
jm::joint_matrix_load(b.it.get_sub_group(), a.m, mp, ld);
#endif
} else {
a.p = p;
a.ld = ld;
}
}
template <bool J, sycl::access::address_space AS> inline void b_load(const sy::Blk& b, BOp<J>& bm, const uint16_t* p, int ld) {
if constexpr (J) {
#if L32X_PASS_JM16
auto mp = sycl::address_space_cast<AS, sycl::access::decorated::no>(const_cast<sycl::half*>(reinterpret_cast<const sycl::half*>(p)));
jm::joint_matrix_load(b.it.get_sub_group(), bm.m, mp, ld);
#endif
} else {
bm.p = p;
bm.ld = ld;
}
}
template <bool J> inline void mad(const sy::Blk& b, Acc<J>& c, const AOp<J>& a, const BOp<J>& bm) {
if constexpr (J) {
#if L32X_PASS_JM16
jm::joint_matrix_mad(b.it.get_sub_group(), c.m, a.m, bm.m, c.m);
#endif
} else {
const int ln = b.lane();
for (int i = 0; i < 8; ++i) {
float s = 0.0f;
for (int k = 0; k < 16; ++k) s += h2f(a.p[i * a.ld + k]) * h2f(bm.p[(k >> 1) * bm.ld + ln * 2 + (k & 1)]);
c.v[i] += s;
}
}
}
constexpr auto kLoc = sycl::access::address_space::local_space;
constexpr auto kGlb = sycl::access::address_space::global_space;
// kernel launch with 16-wide sub-groups
template <class F>
inline void launch16(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) [[sycl::reqd_sub_group_size(16)]] {
f(sy::Blk{it}, lm.get_multi_ptr<sycl::access::decorated::no>().get());
});
});
}
// ---------------------------------------------------------------------------------------------------- weights: BF16 [H][128][512] -> fp16 x 256, packed [H][256][256]
void convert_weights(const uint16_t* in, size_t n, uint16_t* out, cudaStream_t s) {
const size_t per_head = static_cast<size_t>(kNope) * kR;
auto& q = strata::sy::queue_of(s);
if (n % per_head != 0) { // a model with other head dimensions (the small test fixtures): the expanded form is not available there (mla_exp_ok geometry), a plain conversion keeps the engine's buffers valid
q.submit([&](sycl::handler& h) {
h.parallel_for(sycl::range<1>(n), [=](sycl::id<1> id) {
const float f = sycl::bit_cast<float>(static_cast<uint32_t>(in[id[0]]) << 16) * 256.0f;
out[id[0]] = f2h(f);
});
});
return;
}
q.submit([&](sycl::handler& h) {
h.parallel_for(sycl::range<1>(n), [=](sycl::id<1> id) {
const size_t i = id[0], hh = i / per_head, rem = i - hh * per_head;
const int d = static_cast<int>(rem / kR), k = static_cast<int>(rem % kR);
const float f = sycl::bit_cast<float>(static_cast<uint32_t>(in[i]) << 16) * 256.0f;
out[hh * per_head + static_cast<size_t>(k >> 1) * 256 + d * 2 + (k & 1)] = f2h(f);
});
});
}
// ---------------------------------------------------------------------------------------------------- q -> hi / lo planes [H][NP][192]
void qprep(const float* q, uint16_t* Qh, uint16_t* Ql, int N, int NP, int H, cudaStream_t s) {
launch16(s, NP, kProjThreads, 0, [=](sy::Blk b, char*) {
const int t = b.bid();
for (int idx = b.tid(); idx < H * kQK; idx += kProjThreads) {
const int h = idx / kQK, d = idx - h * kQK;
uint16_t hi = 0, lo = 0;
if (t < N) split_h(q[(static_cast<size_t>(t) * H + h) * kQK + d], hi, lo);
const size_t o = (static_cast<size_t>(h) * NP + t) * kQK + d;
Qh[o] = hi;
Ql[o] = lo;
}
});
}
// ---------------------------------------------------------------------------------------------------- projection of a slab of keys
template <bool K>
void proj(const float* cache, int lat_stride, const uint16_t* wk16, const uint16_t* wv16, uint32_t* Kh, uint32_t* Kl, uint32_t* Vh, uint32_t* Vl, int H, int S, int k0, int nvalid, cudaStream_t s) {
constexpr bool J = K && (L32X_PASS_JM16 != 0);
constexpr bool kDead = (!K && (L32X_PASS_JM16 != 0)) || (L32X_SKIP & 1); // the plain-loop instance is never run in a joint_matrix pass (and the offline compiler need not compile it)
const int gx = (nvalid + kPK - 1) / kPK;
const size_t smem = static_cast<size_t>(2 * kPK * kLdA) * 2 + static_cast<size_t>(2 * kPK) * kLdR * 4;
launch16(s, gx * H, kProjThreads, smem, [cache, lat_stride, wk16, wv16, Kh, Kl, Vh, Vl, H, S, k0, nvalid, gx](sy::Blk b, char* sm) { // explicit captures: the host and the device pass must capture the same set (the dead-instance stub does not use them)
if constexpr (kDead) return;
else {
uint16_t* Ah = reinterpret_cast<uint16_t*>(sm); // [16 keys][kLdA] hi of the latent chunk
uint16_t* Al = Ah + kPK * kLdA; // lo
float* R = reinterpret_cast<float*>(sm + static_cast<size_t>(2 * kPK * kLdA) * 2); // [16 keys][kLdR]: main (hi) products
float* RX = R + kPK * kLdR; // cross (lo) products
const int bx = b.bid() % gx, h = b.bid() / gx, tid = b.tid(), w = tid >> 4, kb = bx * kPK;
const uint16_t* W = (w < 8 ? wk16 : wv16) + static_cast<size_t>(h) * 65536 + (w & 7) * 32; // packed [256 k-pairs][256 halves]; this sub-group's 16 outputs
// joint_matrix variables are declared once at the top of the kernel
Acc<J> a0, a1, x0, x1;
AOp<J> ah, al;
BOp<J> bm;
acc_fill<J>(b, a0, 0.0f);
acc_fill<J>(b, a1, 0.0f);
acc_fill<J>(b, x0, 0.0f);
acc_fill<J>(b, x1, 0.0f);
for (int kc = 0; kc < kR / 64; ++kc) {
b.sync();
{ // 16 keys x 64 floats of this k chunk, split into hi / lo (4 floats per thread)
const int key = tid >> 4, c4 = tid & 15;
float v[4];
if (kb + key < nvalid) {
const float* src = cache + static_cast<size_t>(k0 + kb + key) * lat_stride + kc * 64 + c4 * 4;
for (int e = 0; e < 4; ++e) v[e] = src[e];
} else {
for (int e = 0; e < 4; ++e) v[e] = 0.0f;
}
for (int e = 0; e < 4; ++e) {
uint16_t hi, lo;
split_h(v[e], hi, lo);
Ah[key * kLdA + c4 * 4 + e] = hi;
Al[key * kLdA + c4 * 4 + e] = lo;
}
}
b.sync();
for (int ks = 0; ks < 4; ++ks) {
b_load<J, kGlb>(b, bm, W + static_cast<size_t>(kc * 32 + ks * 8) * 256, 256);
a_load<J, kLoc>(b, ah, Ah + ks * 16, kLdA);
a_load<J, kLoc>(b, al, Al + ks * 16, kLdA);
mad<J>(b, a0, ah, bm);
mad<J>(b, x0, al, bm);
a_load<J, kLoc>(b, ah, Ah + 8 * kLdA + ks * 16, kLdA);
a_load<J, kLoc>(b, al, Al + 8 * kLdA + ks * 16, kLdA);
mad<J>(b, a1, ah, bm);
mad<J>(b, x1, al, bm);
}
}
acc_store<J, kLoc>(b, a0, R + w * 16, kLdR);
acc_store<J, kLoc>(b, a1, R + 8 * kLdR + w * 16, kLdR);
acc_store<J, kLoc>(b, x0, RX + w * 16, kLdR);
acc_store<J, kLoc>(b, x1, RX + 8 * kLdR + w * 16, kLdR);
b.sync();
// (main + cross / 2048) / 256 = the projected value; split again into the hi / lo planes of the attention
auto val = [&](int key, int col) { return (R[key * kLdR + col] + RX[key * kLdR + col] * kInv2048) * (1.0f / 256.0f); };
uint32_t* kh = Kh + static_cast<size_t>(h) * 96 * S;
uint32_t* kl = Kl + static_cast<size_t>(h) * 96 * S;
for (int u = tid; u < 64 * kPK; u += kProjThreads) { // K_nope: word (d pair p, key) = (d = 2p | d = 2p + 1 << 16)
const int key = u & (kPK - 1), p = u / kPK;
uint16_t h0, l0, h1, l1;
split_h(val(key, 2 * p), h0, l0);
split_h(val(key, 2 * p + 1), h1, l1);
kh[static_cast<size_t>(p) * S + kb + key] = pack2(h0, h1);
kl[static_cast<size_t>(p) * S + kb + key] = pack2(l0, l1);
}
uint32_t* vh = Vh + static_cast<size_t>(h) * (S / 2) * kVD;
uint32_t* vl = Vl + static_cast<size_t>(h) * (S / 2) * kVD;
for (int u = tid; u < (kPK / 2) * kVD; u += kProjThreads) { // V: word (key pair m, dim) = (key = 2m | key = 2m + 1 << 16)
const int dim = u & 127, m = u >> 7;
uint16_t h0, l0, h1, l1;
split_h(val(2 * m, kNope + dim), h0, l0);
split_h(val(2 * m + 1, kNope + dim), h1, l1);
vh[static_cast<size_t>((kb >> 1) + m) * kVD + dim] = pack2(h0, h1);
vl[static_cast<size_t>((kb >> 1) + m) * kVD + dim] = pack2(l0, l1);
}
for (int u = tid; u < kPK * 32; u += kProjThreads) { // k_pe (shared by the heads) -> d pairs 64 .. 95
const int key = u & (kPK - 1), p = u / kPK;
float r0 = 0.0f, r1 = 0.0f;
if (kb + key < nvalid) {
const float* src = cache + static_cast<size_t>(k0 + kb + key) * lat_stride + kR + 2 * p;
r0 = src[0];
r1 = src[1];
}
uint16_t h0, l0, h1, l1;
split_h(r0, h0, l0);
split_h(r1, h1, l1);
kh[static_cast<size_t>(64 + p) * S + kb + key] = pack2(h0, h1);
kl[static_cast<size_t>(64 + p) * S + kb + key] = pack2(l0, l1);
}
}
});
}
// ---------------------------------------------------------------------------------------------------- attention over one slab
inline constexpr size_t attn_smem_bytes() {
// K hi / lo [96][kLdK], V hi / lo [16][kLdV], P hi / lo [kBM][kLdP], scores main / cross [kBM][kLdS] (aliased by the PV scratch: 8 sub-groups x 2 x 128 floats), corr [kBM]
return static_cast<size_t>(2) * 96 * kLdK * 2 + static_cast<size_t>(2) * 16 * kLdV * 2 + static_cast<size_t>(2) * kBM * kLdP * 2 + static_cast<size_t>(2) * kBM * kLdS * 4 + kBM * 4 + 64;
}
template <bool K>
void attn(const uint16_t* Qh, const uint16_t* Ql, const uint32_t* Kh, const uint32_t* Kl, const uint32_t* Vh, const uint32_t* Vl, float* Oacc, float* ML, int N, int NP, int H, int pos0, int k0, int S, int nk_valid,
int first, float scale, cudaStream_t s) {
constexpr bool J = K && (L32X_PASS_JM16 != 0);
constexpr bool kDead = (!K && (L32X_PASS_JM16 != 0)) || (L32X_SKIP & 2);
const int nbx = NP / kBM;
launch16(s, nbx * H, kAttThreads, attn_smem_bytes(), [Qh, Ql, Kh, Kl, Vh, Vl, Oacc, ML, N, NP, H, pos0, k0, S, nk_valid, first, scale, nbx](sy::Blk b, char* sm) {
if constexpr (kDead) return;
else {
uint16_t* sKh = reinterpret_cast<uint16_t*>(sm); // [96][kLdK]
uint16_t* sKl = sKh + 96 * kLdK;
uint16_t* sVh = sKl + 96 * kLdK; // [16][kLdV]
uint16_t* sVl = sVh + 16 * kLdV;
uint16_t* sPh = sVl + 16 * kLdV; // [kBM][kLdP]
uint16_t* sPl = sPh + kBM * kLdP;
float* sS = reinterpret_cast<float*>(sPl + kBM * kLdP); // [kBM][kLdS] scores, main products
float* sX = sS + kBM * kLdS; // cross products
float* sCorr = sX + kBM * kLdS; // [kBM]
const int bx = b.bid() % nbx, h = b.bid() / nbx, tid = b.tid(), w = tid >> 4, lane = b.lane();
const int row0 = bx * kBM;
const int t_last = std::min(N - 1, row0 + kBM - 1);
const int nvis = std::min(nk_valid, pos0 + t_last + 1 - k0);
const int ntiles = nvis > 0 ? (nvis + kBK - 1) / kBK : 0;
if (ntiles == 0 && !first) return;
const int mt = w & 3, nd = w >> 2; // M tile (8 rows) and key half (scores) / dim half (PV)
const int srow = tid >> 2, spart = tid & 3; // softmax: row, 8 keys
float* scr = sS + w * 256; // PV scratch of this sub-group: main [8][16], cross [8][16] (aliases the scores, dead during the PV)
const size_t qrow = static_cast<size_t>(h) * NP + row0 + mt * 8;
const uint16_t* qh = Qh + qrow * kQK;
const uint16_t* ql = Ql + qrow * kQK;
// joint_matrix variables are declared once at the top of the kernel
Acc<J> c1, cx, pa, px;
AOp<J> ah, al;
BOp<J> bh, bl;
float m_run = kNeg, l_run = 0.0f;
float o[4][8]; // O state: dims nd * 64 + 16 j + lane of rows mt * 8 + i
const size_t obase = (static_cast<size_t>(row0 + mt * 8) * H + h) * kVD + nd * 64 + lane;
const size_t ldo = static_cast<size_t>(H) * kVD;
if (first) {
for (int j = 0; j < 4; ++j)
for (int i = 0; i < 8; ++i) o[j][i] = 0.0f;
} else {
for (int j = 0; j < 4; ++j)
for (int i = 0; i < 8; ++i) o[j][i] = Oacc[obase + i * ldo + j * 16];
const size_t ri = (static_cast<size_t>(row0 + srow) * H + h) * 2;
m_run = ML[ri];
l_run = ML[ri + 1];
}
const int qpos = pos0 + row0 + srow; // position of this thread's softmax row
const bool qvalid = row0 + srow < N;
for (int j = 0; j < ntiles; ++j) {
b.sync(); // the tile buffers of the previous tile are free
// ---- K / V tile (hi, lo) into shared memory: K rows d-pair r, keys 32 j .. 32 j + 31 (64 halves); V is 16 key-pair rows of 256 halves, contiguous
{
const sycl::uint4* gkh = reinterpret_cast<const sycl::uint4*>(Kh + static_cast<size_t>(h) * 96 * S);
const sycl::uint4* gkl = reinterpret_cast<const sycl::uint4*>(Kl + static_cast<size_t>(h) * 96 * S);
for (int u = tid; u < 96 * 8; u += kAttThreads) {
const int r = u >> 3, c = u & 7; // 8 chunks of 16 B = 32 words = 32 keys per row
const size_t g = (static_cast<size_t>(r) * S + kBK * j) / 4 + c;
*reinterpret_cast<sycl::uint4*>(sKh + r * kLdK + c * 8) = gkh[g];
*reinterpret_cast<sycl::uint4*>(sKl + r * kLdK + c * 8) = gkl[g];
}
const sycl::uint4* gvh = reinterpret_cast<const sycl::uint4*>(Vh + (static_cast<size_t>(h) * (S / 2) + 16 * j) * kVD);
const sycl::uint4* gvl = reinterpret_cast<const sycl::uint4*>(Vl + (static_cast<size_t>(h) * (S / 2) + 16 * j) * kVD);
for (int u = tid; u < 16 * 32; u += kAttThreads) { // 16 rows x 32 chunks of 16 B
const int r = u >> 5, c = u & 31;
*reinterpret_cast<sycl::uint4*>(sVh + r * kLdV + c * 8) = gvh[u];
*reinterpret_cast<sycl::uint4*>(sVl + r * kLdV + c * 8) = gvl[u];
}
}
b.sync();
// ---- scores of this sub-group's 8 rows against 16 keys (key half nd)
acc_fill<J>(b, c1, 0.0f);
acc_fill<J>(b, cx, 0.0f);
for (int ks = 0; ks < kQK / 16; ++ks) {
a_load<J, kGlb>(b, ah, qh + ks * 16, kQK);
a_load<J, kGlb>(b, al, ql + ks * 16, kQK);
b_load<J, kLoc>(b, bh, sKh + ks * 8 * kLdK + nd * 32, kLdK);
b_load<J, kLoc>(b, bl, sKl + ks * 8 * kLdK + nd * 32, kLdK);
mad<J>(b, c1, ah, bh);
mad<J>(b, cx, ah, bl);
mad<J>(b, cx, al, bh);
}
acc_store<J, kLoc>(b, c1, sS + mt * 8 * kLdS + nd * 16, kLdS);
acc_store<J, kLoc>(b, cx, sX + mt * 8 * kLdS + nd * 16, kLdS);
b.sync();
// ---- online softmax: thread = (row srow, 8 keys spart * 8 ..)
{
float sv[8];
float mx = kNeg;
for (int e = 0; e < 8; ++e) {
const int key = spart * 8 + e;
const int kl_ = kBK * j + key; // key index in the slab
const bool vis = qvalid && kl_ < nk_valid && k0 + kl_ <= qpos;
sv[e] = vis ? (sS[srow * kLdS + key] + sX[srow * kLdS + key] * kInv2048) * scale : kNeg;
mx = sycl::fmax(mx, sv[e]);
}
mx = sycl::fmax(mx, b.shfl_xor(mx, 1));
mx = sycl::fmax(mx, b.shfl_xor(mx, 2));
const float mn = sycl::fmax(m_run, mx);
float corr, ps = 0.0f;
if (mn <= -1.0e38f) {
corr = 1.0f;
for (int e = 0; e < 8; ++e) sv[e] = 0.0f;
} else {
corr = (m_run <= -1.0e38f) ? 0.0f : sycl::exp(m_run - mn);
for (int e = 0; e < 8; ++e) sv[e] = (sv[e] > -1.0e38f) ? sycl::exp(sv[e] - mn) : 0.0f;
}
for (int e = 0; e < 8; ++e) ps += sv[e];
ps += b.shfl_xor(ps, 1);
ps += b.shfl_xor(ps, 2);
l_run = l_run * corr + ps;
m_run = mn;
for (int e = 0; e < 8; ++e) {
uint16_t hi, lo;
split_h(sv[e], hi, lo);
sPh[srow * kLdP + spart * 8 + e] = hi;
sPl[srow * kLdP + spart * 8 + e] = lo;
}
if (spart == 0) sCorr[srow] = corr;
}
b.sync();
// ---- O = O corr + P V (rows mt * 8 .., dims nd * 64 ..): fresh products per 16-dim tile, added to the state in plain code
float cr[8];
for (int i = 0; i < 8; ++i) cr[i] = sCorr[mt * 8 + i];
for (int jj = 0; jj < 4; ++jj) {
acc_fill<J>(b, pa, 0.0f);
acc_fill<J>(b, px, 0.0f);
for (int ks = 0; ks < kBK / 16; ++ks) {
a_load<J, kLoc>(b, ah, sPh + mt * 8 * kLdP + ks * 16, kLdP);
a_load<J, kLoc>(b, al, sPl + mt * 8 * kLdP + ks * 16, kLdP);
b_load<J, kLoc>(b, bh, sVh + ks * 8 * kLdV + (nd * 64 + jj * 16) * 2, kLdV);
b_load<J, kLoc>(b, bl, sVl + ks * 8 * kLdV + (nd * 64 + jj * 16) * 2, kLdV);
mad<J>(b, pa, ah, bh);
mad<J>(b, px, ah, bl);
mad<J>(b, px, al, bh);
}
acc_store<J, kLoc>(b, pa, scr, 16);
acc_store<J, kLoc>(b, px, scr + 128, 16);
b.warp_sync();
for (int i = 0; i < 8; ++i) o[jj][i] = o[jj][i] * cr[i] + (scr[i * 16 + lane] + scr[128 + i * 16 + lane] * kInv2048);
b.warp_sync();
}
}
// ---- state out: O, m, l
for (int jj = 0; jj < 4; ++jj)
for (int i = 0; i < 8; ++i) Oacc[obase + i * ldo + jj * 16] = o[jj][i];
if (spart == 0) {
const size_t ri = (static_cast<size_t>(row0 + srow) * H + h) * 2;
ML[ri] = m_run;
ML[ri + 1] = l_run;
}
}
});
}
// out[t][h][v] = O / l * sigmoid(gate[t][h]). grid (N * H), 128 threads
void finalize(const float* Oacc, const float* ML, const float* gate, float* out, int N, int H, cudaStream_t s) {
launch16(s, N * H, kVD, 0, [=](sy::Blk b, char*) {
const size_t th = static_cast<size_t>(b.bid());
const float l = ML[th * 2 + 1];
const float mult = l > 0.0f ? 1.0f / l : 0.0f;
const float gv = 1.0f / (1.0f + sycl::exp(-gate[th]));
out[th * kVD + b.tid()] = Oacc[th * kVD + b.tid()] * mult * gv;
});
}
// which flavour runs here: 2 = joint_matrix (Battlemage, PVC, Lunar Lake), 1 = plain loops (any device, when forced: STRATA_L32_MLA_EXP_MODE=1), 0 = not available
int exp_mode(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 mode = 0;
const char* e = std::getenv("STRATA_L32_MLA_EXP_MODE");
const int env = e ? std::atoi(e) : -1; // 0 off, 1 force plain loops, else auto
#if L32X_HAVE_JM
namespace exo = sycl::ext::oneapi::experimental;
switch (strata::sy::queue_of(s).get_device().get_info<exo::info::device::architecture>()) {
case exo::architecture::intel_gpu_bmg_g21:
case exo::architecture::intel_gpu_bmg_g31:
case exo::architecture::intel_gpu_pvc:
case exo::architecture::intel_gpu_lnl_m: mode = 2; break;
default: break;
}
#endif
if (env == 0) mode = 0;
else if (env == 1 && mode == 0) mode = 1;
done[dev] = true;
cache[dev] = mode;
return mode;
}
} // namespace
bool mla_exp_ok(int nope, int rope, int vhead, int kv_lora) { return nope == kNope && rope == kRope && vhead == kVD && kv_lora == kR && exp_mode(0) != 0; }
// workspace for chunks of up to nmax tokens, H heads, slab keys per slab: K planes (hi, lo) [H][96][S] words, V planes [H][S / 2][128] words, Q planes [H][NP][192] halves, O state [NP][H][128], m / l [NP][H][2]
size_t mla_exp_workspace_bytes(int nmax, int H, int slab) {
const size_t np = (static_cast<size_t>(nmax) + kBM - 1) / kBM * kBM;
const size_t kv = static_cast<size_t>(H) * slab * (2 * 96 + 2 * (kVD / 2)) * 4;
const size_t qp = static_cast<size_t>(H) * np * kQK * 2 * 2;
const size_t st = np * H * (kVD + 2) * 4;
return kv + qp + st + 4096;
}
void mla_exp_convert_weights(const uint16_t* bf16_in, size_t n, uint16_t* fp16_out, cudaStream_t s) { convert_weights(bf16_in, n, fp16_out, s); }
// q [N][H][192] (nope then rope), cache fp32 [kv][lat_stride] (c 512 then k_pe 64), out [N][H][128] (already times sigmoid(gate)). pos0 = cache position of token 0; the keys are 0 .. pos0 + N - 1.
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) {
if (slab <= 0 || (slab % 64) != 0) {
std::fprintf(stderr, "ling32: expanded MLA slab must be a multiple of 64\n");
std::abort();
}
const int mode = exp_mode(s);
if (mode == 0) {
std::fprintf(stderr, "ling32 (SYCL): the expanded MLA prefill needs XMX (or STRATA_L32_MLA_EXP_MODE=1 for the plain-loop test mode)\n");
std::abort();
}
const int NP = (N + kBM - 1) / kBM * kBM;
char* p = static_cast<char*>(ws);
auto carve = [&](size_t bytes) { char* r = p; p += (bytes + 255) / 256 * 256; return r; };
const size_t kplane = static_cast<size_t>(H) * 96 * slab * 4, vplane = static_cast<size_t>(H) * (slab / 2) * kVD * 4, qplane = static_cast<size_t>(H) * NP * kQK * 2;
uint32_t* Kh = reinterpret_cast<uint32_t*>(carve(kplane));
uint32_t* Kl = reinterpret_cast<uint32_t*>(carve(kplane));
uint32_t* Vh = reinterpret_cast<uint32_t*>(carve(vplane));
uint32_t* Vl = reinterpret_cast<uint32_t*>(carve(vplane));
uint16_t* Qh = reinterpret_cast<uint16_t*>(carve(qplane));
uint16_t* Ql = reinterpret_cast<uint16_t*>(carve(qplane));
float* Oacc = reinterpret_cast<float*>(carve(static_cast<size_t>(NP) * H * kVD * 4));
float* ML = reinterpret_cast<float*>(carve(static_cast<size_t>(NP) * H * 2 * 4));
if (static_cast<size_t>(p - static_cast<char*>(ws)) > ws_bytes) {
std::fprintf(stderr, "ling32: expanded MLA workspace too small\n");
std::abort();
}
qprep(q, Qh, Ql, N, NP, H, s);
const int total = pos0 + N;
for (int k0 = 0; k0 < total; k0 += slab) {
const int nvalid = std::min(slab, total - k0);
if (mode == 2) {
proj<true>(cache, lat_stride, wk16, wv16, Kh, Kl, Vh, Vl, H, slab, k0, nvalid, s);
attn<true>(Qh, Ql, Kh, Kl, Vh, Vl, Oacc, ML, N, NP, H, pos0, k0, slab, nvalid, k0 == 0 ? 1 : 0, scale, s);
} else {
proj<false>(cache, lat_stride, wk16, wv16, Kh, Kl, Vh, Vl, H, slab, k0, nvalid, s);
attn<false>(Qh, Ql, Kh, Kl, Vh, Vl, Oacc, ML, N, NP, H, pos0, k0, slab, nvalid, k0 == 0 ? 1 : 0, scale, s);
}
}
finalize(Oacc, ML, gate, out, N, H, s);
}
} // namespace strata::ling32::gpu
@@ -259,7 +259,7 @@ void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int
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
static const bool force_orig = std::getenv("STRATA_L32_MLA_FD_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);
}
@@ -273,10 +273,10 @@ void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int
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
static const int rb_env = std::getenv("STRATA_L32_MLA_FD_RB") ? std::atoi(std::getenv("STRATA_L32_MLA_FD_RB")) : 1; // tuning switches: rows per QK batch (1, 2)
static const int ns_env = std::getenv("STRATA_L32_MLA_FD_NS") ? std::min(kFdMaxSplits, std::max(1, std::atoi(std::getenv("STRATA_L32_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)
static const int pvu_env = std::getenv("STRATA_L32_MLA_FD_PVU") ? std::atoi(std::getenv("STRATA_L32_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)
@@ -14,9 +14,5 @@ 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
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash
# L32-SY-MLA: bash engine/src/ling32/sycl/tools/devlink.sh - configures a bmg_g31-only build dir, compiles only the mla_exp object, then runs the AOT device link of that one object (fast IGC crash check, seconds instead of minutes)
set +u
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
cd "$(cd "$(dirname "$0")/../../../../.." && pwd)" || exit 2
bld=bld_dl
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=intel_gpu_bmg_g31 -DPython3_EXECUTABLE=$HOME/l32sy/venv/bin/python 2>&1 | tail -1
ninja -C $bld CMakeFiles/ling32_gpu.dir/sycl/ling32_sy_k_mla_exp.cpp.o 2>&1 | grep -E "error|FAILED" | cut -c1-300 | head -20
cd $bld
icpx -fsycl -fsycl-targets=intel_gpu_bmg_g31 -fsycl-link CMakeFiles/ling32_gpu.dir/sycl/ling32_sy_k_mla_exp.cpp.o -o /tmp/l32_mlaexp_devlink.o > /tmp/l32_mlaexp_dl.txt 2>&1
echo "devlink rc=$?"
grep -nE 'warning|rror|Segm|Retry' /tmp/l32_mlaexp_dl.txt | sed -e 's/strata::ling32::gpu::(anonymous namespace):://g' | cut -c1-400 | head -20
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
# L32-SY-MLA: bash engine/src/ling32/sycl/tools/devlink2.sh "<extra -D flags>" [target, default intel_gpu_bmg_g31]
# compiles only ling32_sy_k_mla_exp.cpp with the given defines (the flags of the CMake build dir bld_dl, made by devlink.sh) and runs the AOT device link of that object: a seconds-long crash check of IGC / ocloc
set +u
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
cd "$(cd "$(dirname "$0")/../../../../.." && pwd)" || exit 2
bld=bld_dl
defs="$1"
tgt=${2:-intel_gpu_bmg_g31}
obj=CMakeFiles/ling32_gpu.dir/sycl/ling32_sy_k_mla_exp.cpp.o
cmd=$(ninja -C $bld -t commands $obj | tail -1)
cmd=${cmd/-o $obj/-o /tmp/l32x_variant.o}
( cd $bld && eval "$cmd $defs" ) 2>&1 | grep -E "error" | cut -c1-300 | head -5
( cd $bld && icpx -fsycl -fsycl-targets=$tgt -fsycl-link /tmp/l32x_variant.o -o /tmp/l32x_variant_link.o > /tmp/l32x_variant_dl.txt 2>&1; echo "defs [$defs] devlink rc=$?" )
grep -cE "Segm" /tmp/l32x_variant_dl.txt
@@ -0,0 +1,20 @@
#!/bin/bash
# L32-SY-MLA: bash engine/src/ling32/sycl/tools/fwd_exp_a750.sh (inside a built tree, bld/): forward tests f32 / q8 / wide with the expanded-form MLA prefill ON (--mla-exp --kda-seq 4: the 12-token fixture prompt
# takes the prefill path) next to the same runs without it, in the plain-loop mode of a device without XMX (STRATA_L32_MLA_EXP_MODE=1; on a Battlemage the joint_matrix kernel runs and the variable is not needed).
set +u
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
cd "$(cd "$(dirname "$0")/../../../../.." && pwd)/bld" || exit 2
export ONEAPI_DEVICE_SELECTOR=level_zero:gpu
ctest -R 'make_fixture|make_ref|make_wide|make_wide_ref' 2>&1 | tail -3
ids=5,17,100,42,7,300,12,9,33,2,64,201
export STRATA_L32_MLA_EXP_MODE=${STRATA_L32_MLA_EXP_MODE:-1}
run() { # label fixture refdir extra...
label=$1; fx=$2; rf=$3; shift 3
echo "===== forward $label"
./ling32_forward_test $fx $rf $ids "$@" 2>&1 | grep -E "layer [0-9]+ \(MLA|logits vs|token-by-token|PASS|FAIL|not available" | cut -c1-200
}
run "f32 --kda-seq 4 (absorbed MLA, control)" ling32_fixture.strata ref --kda-seq 4
run "f32 --kda-seq 4 --mla-exp" ling32_fixture.strata ref --kda-seq 4 --mla-exp
run "q8 --kda-seq 4 --mla-exp" ling32_fixture.strata ref --q8 --kda-seq 4 --mla-exp
run "wide --kda-seq 4 (control)" ling32_wide.strata ref_wide --kda-seq 4
run "wide --kda-seq 4 --mla-exp" ling32_wide.strata ref_wide --kda-seq 4 --mla-exp
+122
View File
@@ -0,0 +1,122 @@
// L32-SY-MLA: compiler probe, which joint_matrix construct crashes ocloc / IGC for a Battlemage target. Compile only (never run):
// icpx -fsycl -fsycl-targets=intel_gpu_bmg_g31 -O3 -DCASE=n jm_probe.cpp -o /tmp/jm_probe_n (jm_probe.sh does all cases)
// CASE 0 baseline (A, B from shared memory, result stored to shared memory), 1 B packed from global, 2 A from global, 3 accumulator loaded from global, 4 accumulator stored to global,
// 5 joint_matrix_apply of two accumulators, 6 joint_matrix_apply of one accumulator with shared-memory reads in the lambda, 7 acc apply2 + store with the full set of the projection kernel
#include <sycl/sycl.hpp>
#include <sycl/ext/oneapi/matrix/matrix.hpp>
#ifndef CASE
#define CASE 0
#endif
namespace jm = sycl::ext::oneapi::experimental::matrix;
constexpr auto kLoc = sycl::access::address_space::local_space;
constexpr auto kGlb = sycl::access::address_space::global_space;
template <class F> inline void ap1(sycl::sub_group sg, jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16>& c, F f) {
int r = 0;
jm::joint_matrix_apply(sg, c, [&](float& x) { f(x, r); ++r; });
}
template <class F> inline void ap2(sycl::sub_group sg, jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16>& c, jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16>& d, F f) {
int r = 0;
jm::joint_matrix_apply(sg, c, d, [&](float& x, float& y) { f(x, y, r); ++r; });
}
int main() {
sycl::queue q;
sycl::half* gA = sycl::malloc_device<sycl::half>(8 * 16 * 64, q);
sycl::half* gB = sycl::malloc_device<sycl::half>(16 * 16 * 64, q);
float* gC = sycl::malloc_device<float>(8 * 16 * 64, q);
q.submit([&](sycl::handler& h) {
sycl::local_accessor<sycl::half, 1> lm(sycl::range<1>(8 * 80 + 8 * 80 + 8 * 16 * 2), h);
h.parallel_for(sycl::nd_range<1>(16, 16), [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(16)]] {
auto sg = it.get_sub_group();
sycl::half* l = lm.get_multi_ptr<sycl::access::decorated::no>().get();
sycl::half* lA = l;
sycl::half* lB = l + 8 * 80;
float* lC = reinterpret_cast<float*>(l + 16 * 80);
auto pAl = sycl::address_space_cast<kLoc, sycl::access::decorated::no>(lA);
auto pBl = sycl::address_space_cast<kLoc, sycl::access::decorated::no>(lB);
auto pAg = sycl::address_space_cast<kGlb, sycl::access::decorated::no>(gA);
auto pBg = sycl::address_space_cast<kGlb, sycl::access::decorated::no>(gB);
auto pCl = sycl::address_space_cast<kLoc, sycl::access::decorated::no>(lC);
auto pCg = sycl::address_space_cast<kGlb, sycl::access::decorated::no>(gC);
jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16> c, x;
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::a, 8, 16, jm::layout::row_major> a;
jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, 16, jm::layout::ext_intel_packed> b;
#if CASE == 3
jm::joint_matrix_load(sg, c, pCg, 128, jm::layout::row_major);
#else
jm::joint_matrix_fill(sg, c, 0.0f);
#endif
jm::joint_matrix_fill(sg, x, 0.0f);
#if CASE == 2
jm::joint_matrix_load(sg, a, pAg, 192);
#else
jm::joint_matrix_load(sg, a, pAl, 80);
#endif
#if CASE == 1 || CASE == 7
jm::joint_matrix_load(sg, b, pBg, 256);
#else
jm::joint_matrix_load(sg, b, pBl, 80);
#endif
jm::joint_matrix_mad(sg, c, a, b, c);
jm::joint_matrix_mad(sg, x, a, b, x);
#if CASE == 8
ap1(sg, c, [&](float& p, int r) { p *= static_cast<float>(lA[r]); });
#endif
#if CASE == 9
ap2(sg, c, x, [&](float& p, float& q, int) { p = (p + q * 0.00048828125f) * 0.5f; });
#endif
#if CASE == 10
for (int i = 0; i < 4; ++i) {
jm::joint_matrix_load(sg, a, pAl, 80);
jm::joint_matrix_mad(sg, c, a, b, c);
}
ap1(sg, c, [&](float& p, int r) { p *= static_cast<float>(lA[r]); });
#endif
#if CASE == 11
for (int i = 0; i < 4; ++i) {
jm::joint_matrix_load(sg, a, pAl, 80);
jm::joint_matrix_load(sg, b, pBl, 80);
jm::joint_matrix_mad(sg, c, a, b, c);
jm::joint_matrix_mad(sg, x, a, b, x);
}
ap2(sg, c, x, [&](float& p, float& q, int) { p = (p + q * 0.00048828125f) * 0.5f; });
#endif
#if CASE == 12 || CASE == 13 || CASE == 14
for (int i = 0; i < 4; ++i) {
sycl::group_barrier(it.get_group());
lA[it.get_local_id(0) + i] = static_cast<sycl::half>(i);
sycl::group_barrier(it.get_group());
#if CASE == 13
jm::joint_matrix_load(sg, b, pBg + i * 256, 256);
#endif
jm::joint_matrix_load(sg, a, pAl, 80);
jm::joint_matrix_mad(sg, c, a, b, c);
jm::joint_matrix_mad(sg, x, a, b, x);
}
#if CASE == 14
ap1(sg, c, [&](float& p, int r) { p *= static_cast<float>(lA[r]); });
#else
ap2(sg, c, x, [&](float& p, float& q, int) { p = (p + q * 0.00048828125f) * 0.5f; });
#endif
#endif
#if CASE == 5 || CASE == 7
jm::joint_matrix_apply(sg, c, x, [&](float& p, float& r) { p = (p + r * 0.00048828125f) * 0.5f; });
#endif
#if CASE == 6
int row = 0;
jm::joint_matrix_apply(sg, c, [&](float& p) { p *= static_cast<float>(lA[row]); ++row; });
#endif
#if CASE == 4
jm::joint_matrix_store(sg, c, pCg, 128, jm::layout::row_major);
#else
jm::joint_matrix_store(sg, c, pCl, 16, jm::layout::row_major);
sycl::group_barrier(sg);
gC[it.get_local_id(0)] = lC[it.get_local_id(0)];
#endif
});
});
q.wait();
return 0;
}
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
# L32-SY-MLA: compiles the joint_matrix probe cases for a Battlemage target (compile only) and prints which ones crash the offline compiler. bash jm_probe.sh [target]
set +u
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
here=$(cd "$(dirname "$0")" && pwd)
tgt=${1:-intel_gpu_bmg_g31}
for c in 12 13 14; do
icpx -fsycl -fsycl-targets=$tgt -O3 -DCASE=$c "$here/jm_probe.cpp" -o /tmp/l32_jm_probe_$c > /tmp/l32_jm_probe_$c.txt 2>&1
echo "case $c rc=$? segv=$(grep -c Segm /tmp/l32_jm_probe_$c.txt) errors=$(grep -c 'error' /tmp/l32_jm_probe_$c.txt)"
done
+17
View File
@@ -0,0 +1,17 @@
#!/bin/bash
# L32-SY-MLA: bash engine/src/ling32/sycl/tools/kda_a750.sh (after l32sy_build.sh build): the KDA chunk-scan checks on the A750 box: ctest of the kernel / model / forward / kda tests, then the forward tests with the chunk
# path forced (--kda-seq 4) for every scan mode (STRATA_L32_KDA_SEQ = 0 one column per lane, 4 / 8 the scan split over the value columns).
set +u
. /opt/intel/oneapi/setvars.sh >/dev/null 2>&1
cd "$(cd "$(dirname "$0")/../../../../.." && pwd)/bld" || exit 2
export ONEAPI_DEVICE_SELECTOR=level_zero:gpu
ctest -R 'make|kernel_test|model_test|forward_test|kda_test' 2>&1 | tail -22
ids=5,17,100,42,7,300,12,9,33,2,64,201
for m in 0 4 8; do
echo "===== forward wide --kda-seq 4, scan mode $m"
STRATA_L32_KDA_SEQ=$m ./ling32_forward_test ling32_wide.strata ref_wide $ids --kda-seq 4 2>&1 | grep -E "logits vs|token-by-token|PASS|FAIL" | cut -c1-200
echo "===== forward f32 --kda-seq 4, scan mode $m"
STRATA_L32_KDA_SEQ=$m ./ling32_forward_test ling32_fixture.strata ref $ids --kda-seq 4 2>&1 | grep -E "logits vs|token-by-token|PASS|FAIL" | cut -c1-200
done
echo "===== forward q8 --kda-seq 4, scan mode 8"
STRATA_L32_KDA_SEQ=8 ./ling32_forward_test ling32_fixture.strata ref $ids --q8 --kda-seq 4 2>&1 | grep -E "logits vs|token-by-token|PASS|FAIL" | cut -c1-200
@@ -53,6 +53,7 @@ int main(int argc, char** argv) {
bool q8 = false, tc = false, graph = false, e2e = false, trunk_only = false, lat16 = false, mla_exp = false;
int mla_kernel = 0; // --mla K: the MLA attention kernel (1 simt, 2 tensor cores split, 3 tensor cores fast)
int n_layers_test = 0; // --layers K: only the first K layers (with --trunk-only: the real file on a card too small for the experts)
int kda_seq = 0; // --kda-seq K: batches of more than K tokens take the chunk-parallel KDA and the expanded MLA (the 12-token fixture prompt is below the default 16)
for (int i = 4; i < argc; ++i) {
q8 = q8 || std::string(argv[i]) == "--q8";
tc = tc || std::string(argv[i]) == "--tc";
@@ -63,6 +64,7 @@ int main(int argc, char** argv) {
mla_exp = mla_exp || std::string(argv[i]) == "--mla-exp"; // the expanded-form MLA prefill (needs the fp32 latent cache; chunks of more than kda_seq_max_n tokens)
if (std::string(argv[i]) == "--layers" && i + 1 < argc) n_layers_test = std::atoi(argv[i + 1]);
if (std::string(argv[i]) == "--mla" && i + 1 < argc) mla_kernel = std::atoi(argv[i + 1]);
if (std::string(argv[i]) == "--kda-seq" && i + 1 < argc) kda_seq = std::atoi(argv[i + 1]);
} // --e2e: long prompt, chunked, logits only
const int T = static_cast<int>(ids.size());
Ling32File f;
@@ -86,6 +88,7 @@ int main(int argc, char** argv) {
eo.latent = lat16 ? strata::ling32::LatentFmt::F16 : strata::ling32::LatentFmt::F32; // --lat16: the fp16 latent cache (looser tolerances)
eo.max_tokens = 64;
eo.mla_kernel = mla_kernel;
if (kda_seq > 0) { eo.kda_seq_max_n = kda_seq; eo.graph_max_n = kda_seq; } // the expanded MLA needs N above both
if (mla_exp) { eo.mla_expanded = true; eo.mla_prefill_kernel = 2; eo.mla_exp_slab = 64; if (eo.mla_kernel == 0) eo.mla_kernel = 2; }
eo.lookahead = !trunk_only;
eo.capture = true;
+20 -14
View File
@@ -816,6 +816,24 @@ void bench_batches() {
}
}
// the route + grouped-experts cases at the real batch sizes; only_chunk: just the 16384-pair case (L32MOE_ONLY_CHUNK=1, to run the largest case alone)
static void run_big_section(bool only_chunk) {
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);
if (!only_chunk) {
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);
}
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; }
@@ -830,6 +848,7 @@ int main(int argc, char** argv) {
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; }
if (std::getenv("L32MOE_ONLY_CHUNK")) { run_big_section(true); std::printf("%s (%d failed)\n", g_fail ? "FAIL" : "PASS", g_fail); return g_fail ? 1 : 0; }
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});
@@ -864,20 +883,7 @@ int main(int argc, char** argv) {
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);
}
run_big_section(false);
std::printf("%s (%d failed)\n", g_fail ? "FAIL" : "PASS", g_fail);
return g_fail ? 1 : 0;
}
+125
View File
@@ -0,0 +1,125 @@
// tests/ling32/ling32_sy_kda_test.cpp - the SYCL chunk-parallel KDA prefill scan (sycl/ling32_sy_k_kda.cpp): the scan split over the value columns (modes 4 and 8, launch_chunk_seq2 + launch_chunk_norm) and the
// one-column-per-lane scan (mode 0, launch_chunk_seq) against the sequential recurrence (kda_step without chunking), outputs and final state, at head dim 64 and 128 and N = 40 / 100 (no multiple of the chunk);
// then, at the real shape (32 heads, head dim 128, 2048 tokens), the accuracy of every mode and the time of the pre + scan (+ norm) launches. usage: ling32_sy_kda_test [skip-big]
#include "ling32_kernels.hpp"
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
using namespace strata::ling32::gpu;
namespace strata::ling32::gpu {
extern int g_sy_kda_seq_mode;
}
namespace {
int g_fail = 0;
void check(bool ok, const std::string& what, double v) {
std::printf(" %-110s %s (%.3g)\n", what.c_str(), ok ? "ok" : "FAIL", v);
if (!ok) ++g_fail;
}
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);
}
std::vector<float> down(const float* d, size_t n) {
std::vector<float> h(n);
cudaMemcpy(h.data(), d, n * 4, cudaMemcpyDeviceToHost);
return h;
}
double now_ms() { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
struct Case {
int H, hd, N, C;
std::vector<float> qn, kn, vc, fr, gr, br, Al, db, on, S0;
float *dq, *dk, *dv, *df, *dg, *dbeta, *dA, *ddb, *don, *dout, *dS, *dscr;
size_t scr_floats;
Case(int H_, int hd_, int N_, unsigned seed) : H(H_), hd(hd_), N(N_), C(H_ * hd_) {
std::mt19937 rng(seed);
auto rnd = [&](size_t n, float lo, float hi) {
std::vector<float> v(n);
for (auto& x : v) x = lo + (hi - lo) * ((rng() & 0xFFFF) / 65535.0f);
return v;
};
const float ks = 1.0f / std::sqrt(static_cast<float>(hd));
qn = rnd(size_t(N) * C, -ks, ks); kn = rnd(size_t(N) * C, -ks, ks); vc = rnd(size_t(N) * C, -1.f, 1.f); fr = rnd(size_t(N) * C, -1.f, 1.f); gr = rnd(size_t(N) * C, -1.f, 1.f);
br = rnd(size_t(N) * H, -1.f, 1.f); Al = rnd(H, -1.f, 0.f); db = rnd(C, -0.5f, 0.5f); on = rnd(hd, 0.5f, 1.5f); S0 = rnd(size_t(H) * hd * hd, -0.05f, 0.05f);
dq = up(qn); dk = up(kn); dv = up(vc); df = up(fr); dg = up(gr); dbeta = up(br); dA = up(Al); ddb = up(db); don = up(on); dS = up(S0);
cudaMalloc(reinterpret_cast<void**>(&dout), size_t(N) * C * 4);
scr_floats = kda_chunk_scratch_floats(N, H, hd);
cudaMalloc(reinterpret_cast<void**>(&dscr), scr_floats * 4);
}
void run(bool chunked, int mode, std::vector<float>& o, std::vector<float>& st) {
g_sy_kda_seq_mode = mode;
cudaMemcpy(dS, S0.data(), S0.size() * 4, cudaMemcpyHostToDevice);
kda_step(dS, dq, dk, dv, df, C, dg, C, dbeta, dA, ddb, don, -5.0f, 1e-6f, dout, N, H, hd, chunked, 0, nullptr, chunked ? dscr : nullptr, chunked ? scr_floats : 0);
cudaDeviceSynchronize();
o = down(dout, size_t(N) * C);
st = down(dS, S0.size());
}
double time_ms(int mode, int reps) {
g_sy_kda_seq_mode = mode;
auto once = [&] { kda_step(dS, dq, dk, dv, df, C, dg, C, dbeta, dA, ddb, don, -5.0f, 1e-6f, dout, N, H, hd, true, 0, nullptr, dscr, scr_floats); };
once();
cudaDeviceSynchronize();
const double t0 = now_ms();
for (int i = 0; i < reps; ++i) once();
cudaDeviceSynchronize();
return (now_ms() - t0) / reps;
}
~Case() { cudaFree(dq); cudaFree(dk); cudaFree(dv); cudaFree(df); cudaFree(dg); cudaFree(dbeta); cudaFree(dA); cudaFree(ddb); cudaFree(don); cudaFree(dout); cudaFree(dS); cudaFree(dscr); }
};
double relerr(const std::vector<float>& x, const std::vector<float>& y) {
double num = 0, den = 0;
for (size_t i = 0; i < x.size(); ++i) {
if (!std::isfinite(x[i])) return 1e30;
num = std::fmax(num, std::fabs(double(x[i]) - y[i]));
den += double(y[i]) * y[i];
}
return num / (std::sqrt(den / x.size()) + 1e-30);
}
} // namespace
int main(int argc, char** argv) {
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);
std::printf("device: %s\n", prop.name);
bool big = true;
for (int i = 1; i < argc; ++i)
if (std::string(argv[i]) == "skip-big") big = false;
for (int hd : {64, 128})
for (int N : {40, 100}) {
Case c(2, hd, N, 7 + hd + N);
std::vector<float> o_ref, s_ref;
c.run(false, 0, o_ref, s_ref);
for (int mode : {0, 4, 8}) {
std::vector<float> o, st;
c.run(true, mode, o, st);
const double e = std::fmax(relerr(o, o_ref), relerr(st, s_ref));
check(e < 2e-4, "KDA chunk scan mode " + std::to_string(mode) + " hd " + std::to_string(hd) + " N " + std::to_string(N) + ": max rel error vs the sequential recurrence (outputs and state)", e);
}
}
if (big) {
Case c(32, 128, 2048, 99);
std::vector<float> o_ref, s_ref;
c.run(false, 0, o_ref, s_ref);
for (int mode : {0, 4, 8}) {
std::vector<float> o, st;
c.run(true, mode, o, st);
const double e = std::fmax(relerr(o, o_ref), relerr(st, s_ref));
check(e < 2e-4, "KDA chunk scan mode " + std::to_string(mode) + " at 32 heads, hd 128, N 2048: max rel error vs the sequential recurrence", e);
}
for (int mode : {0, 4, 8}) std::printf(" chunk path (pre + scan%s) mode %d, 32 heads, hd 128, 2048 tokens: %.3f ms per call\n", mode ? " + norm" : "", mode, c.time_ms(mode, mode == 0 ? 3 : 10));
}
std::printf(g_fail ? "FAIL (%d failures)\n" : "PASS (0 failures)\n", g_fail);
return g_fail ? 1 : 0;
}
@@ -0,0 +1,167 @@
// tests/ling32/ling32_sy_mla_exp_test.cpp - the expanded-form MLA prefill on SYCL (sycl/ling32_sy_k_mla_exp.cpp) against the engine's absorbed pipeline (mla_qabs + mla_attn original kernel + mla_out) on random data
// of the real geometry (H heads, nope 128, rope 64, vhead 128, kv_lora 512, fp32 latent cache), for several (tokens, position) shapes and slab sizes. Port of ling32_mla_exp_test.cu.
// ling32_sy_mla_exp_test [full] [bench] "full": also the big cases (H = 32, 300 tokens at position 3000); "bench": times a 2048-token chunk at 16384 context against the absorbed path
// On a device without XMX the test needs STRATA_L32_MLA_EXP_MODE=1 (plain loops, slow); it skips otherwise.
#include "ling32_kernels.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
using namespace strata::ling32::gpu;
namespace {
int g_fail = 0;
void check(bool ok, const char* what, double v) {
std::printf(" %-100s %s (%.3g)\n", what, ok ? "ok" : "FAIL", v);
if (!ok) ++g_fail;
}
uint16_t f2bf(float f) { uint32_t u; std::memcpy(&u, &f, 4); u += 0x7fffu + ((u >> 16) & 1u); return static_cast<uint16_t>(u >> 16); }
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);
}
template <class T> T* up(const std::vector<T>& h) {
T* p = dalloc<T>(h.size());
cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice);
return p;
}
template <class F> double time_ms(F f, int reps) {
f();
cudaDeviceSynchronize();
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < reps; ++i) f();
cudaDeviceSynchronize();
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / reps;
}
struct Data {
int H, kv_cap;
std::vector<float> q, cache, gate;
std::vector<uint16_t> wk, wv;
float *dq, *dcache, *dgate;
uint16_t *dwk, *dwv, *dwk16, *dwv16;
};
Data make_data(int H, int N_cap, int kv_cap, unsigned seed) {
Data d;
d.H = H;
d.kv_cap = kv_cap;
const int NOPE = 128, ROPE = 64, QW = NOPE + ROPE, R = 512, W = R + ROPE, V = 128;
std::mt19937 rng(seed);
std::normal_distribution<float> nd(0.f, 1.f);
d.q.resize(static_cast<size_t>(N_cap) * H * QW);
d.cache.resize(static_cast<size_t>(kv_cap) * W);
d.gate.resize(static_cast<size_t>(N_cap) * H);
d.wk.resize(static_cast<size_t>(H) * NOPE * R);
d.wv.resize(static_cast<size_t>(H) * V * R);
for (auto& v : d.q) v = nd(rng) * 0.5f;
for (auto& v : d.cache) v = nd(rng);
for (auto& v : d.gate) v = nd(rng);
for (auto& v : d.wk) v = f2bf(nd(rng) * 0.06f);
for (auto& v : d.wv) v = f2bf(nd(rng) * 0.06f);
d.dq = up(d.q); d.dcache = up(d.cache); d.dgate = up(d.gate);
d.dwk = up(d.wk); d.dwv = up(d.wv);
d.dwk16 = dalloc<uint16_t>(d.wk.size()); d.dwv16 = dalloc<uint16_t>(d.wv.size());
mla_exp_convert_weights(d.dwk, d.wk.size(), d.dwk16, 0);
mla_exp_convert_weights(d.dwv, d.wv.size(), d.dwv16, 0);
cudaDeviceSynchronize();
return d;
}
void run_case(const Data& d, int N, int pos0, int slab) {
const int H = d.H, NOPE = 128, ROPE = 64, R = 512, W = R + ROPE, V = 128;
const float scale = 1.0f / std::sqrt(192.0f);
float* qabs = dalloc<float>(static_cast<size_t>(N) * H * R);
float* ctx = dalloc<float>(static_cast<size_t>(N) * H * R);
float* ref = dalloc<float>(static_cast<size_t>(N) * H * V);
float* out = dalloc<float>(static_cast<size_t>(N) * H * V);
int* dpos = dalloc<int>(1);
cudaMemcpy(dpos, &pos0, 4, cudaMemcpyHostToDevice);
mla_qabs(d.dq, d.dwk, qabs, N, H, NOPE, ROPE, R, 0);
mla_attn(qabs, d.dq, d.dcache, dpos, ctx, N, H, NOPE, ROPE, R, scale, true, 0);
mla_out(ctx, d.dwv, d.dgate, ref, N, H, V, R, 0);
const size_t eb = mla_exp_workspace_bytes(N, H, slab);
void* ews = dalloc<char>(eb);
mla_exp_prefill(d.dq, d.dcache, W, d.dwk16, d.dwv16, d.dgate, out, N, H, pos0, scale, ews, eb, slab, 0);
cudaDeviceSynchronize();
std::vector<float> r(static_cast<size_t>(N) * H * V), o(r.size());
cudaMemcpy(r.data(), ref, r.size() * 4, cudaMemcpyDeviceToHost);
cudaMemcpy(o.data(), out, r.size() * 4, cudaMemcpyDeviceToHost);
double md = 0, mr = 0;
bool finite = true;
for (size_t i = 0; i < r.size(); ++i) {
if (!std::isfinite(o[i])) finite = false;
md = std::max(md, static_cast<double>(std::fabs(o[i] - r[i])));
mr = std::max(mr, static_cast<double>(std::fabs(r[i])));
}
char buf[160];
std::snprintf(buf, sizeof(buf), "H=%d N=%d pos0=%d slab=%d: expanded vs absorbed fp32 scalar (max |ref| %.3f)", H, N, pos0, slab, mr);
check(finite && md < 2e-5 * std::max(1.0, mr), buf, md);
cudaFree(qabs); cudaFree(ctx); cudaFree(ref); cudaFree(out); cudaFree(dpos); cudaFree(ews);
}
} // namespace
int main(int argc, char** argv) {
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);
std::printf("device: %s\n", prop.name);
bool full = false, bench = false;
for (int i = 1; i < argc; ++i) {
if (std::string(argv[i]) == "full") full = true;
if (std::string(argv[i]) == "bench") bench = true;
}
if (!mla_exp_ok(128, 64, 128, 512)) {
std::printf("no XMX on this device (STRATA_L32_MLA_EXP_MODE=1 forces the plain-loop mode): skipped\n");
return 0;
}
{
Data d = make_data(4, 96, 1500, 11);
run_case(d, 40, 0, 64); // first chunk
run_case(d, 70, 0, 256);
run_case(d, 96, 1000, 128); // later chunk: keys of earlier chunks in several slabs
run_case(d, 33, 1400, 512);
run_case(d, 17, 63, 64); // ragged edges
}
{
Data d = make_data(32, 300, full ? 3600 : 800, 5); // the real head count
run_case(d, 129, 0, 2048);
run_case(d, 100, 700, 128);
if (full) run_case(d, 300, 3000, 1024);
}
if (bench) {
const int H = 32, N = 2048, pos0 = 14336, W = 576, R = 512, NOPE = 128, ROPE = 64, V = 128;
Data d = make_data(H, N, pos0 + N, 3);
const float scale = 1.0f / std::sqrt(192.0f);
float* out = dalloc<float>(static_cast<size_t>(N) * H * V);
for (int slab : {1024, 2048, 4096}) {
const size_t eb = mla_exp_workspace_bytes(N, H, slab);
void* ews = dalloc<char>(eb);
const double t = time_ms([&] { mla_exp_prefill(d.dq, d.dcache, W, d.dwk16, d.dwv16, d.dgate, out, N, H, pos0, scale, ews, eb, slab, 0); }, 2);
std::printf(" expanded, N=%d context=%d slab %d keys (workspace %.0f MB): %.2f ms\n", N, pos0 + N, slab, eb / 1048576.0, t);
cudaFree(ews);
}
if (std::getenv("STRATA_L32_MLA_EXP_ABS")) { // the absorbed path (slow: minutes at this size)
float* qabs = dalloc<float>(static_cast<size_t>(N) * H * R);
float* ctx = dalloc<float>(static_cast<size_t>(N) * H * R);
float* ref = dalloc<float>(static_cast<size_t>(N) * H * V);
int* dpos = dalloc<int>(1);
cudaMemcpy(dpos, &pos0, 4, cudaMemcpyHostToDevice);
const double t = time_ms([&] {
mla_qabs(d.dq, d.dwk, qabs, N, H, NOPE, ROPE, R, 0);
mla_attn(qabs, d.dq, d.dcache, dpos, ctx, N, H, NOPE, ROPE, R, scale, true, 0);
mla_out(ctx, d.dwv, d.dgate, ref, N, H, V, R, 0);
}, 1);
std::printf(" absorbed original path (qabs + attention + out): %.2f ms\n", t);
}
}
std::printf(g_fail ? "FAIL (%d failures)\n" : "PASS (0 failures)\n", g_fail);
return g_fail ? 1 : 0;
}
+228 -2
View File
@@ -34640,6 +34640,40 @@
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_L32_KDA_SEQ",
"backends": [
"sycl"
],
"reads": [
{
"file": "engine/src/ling32/sycl/ling32_sy_k_kda.cpp",
"line": 559,
"backend": "sycl",
"fn": "getenv"
},
{
"file": "engine/src/ling32/sycl/ling32_sy_k_kda.cpp",
"line": 559,
"backend": "sycl",
"fn": "getenv"
}
],
"parse": "int",
"default_state": null,
"code_default": null,
"engine_sets": [],
"engine_defaults": [],
"launch_files": [],
"launch_sets": [],
"launch_reads": [],
"doc_mentions": [],
"status": "rollback",
"owner": "L32-SY-MLA",
"note": "SYCL KDA chunk scan of prefill batches (N > 16): 0 = the old one-column-per-lane scan, 4 or 8 = the scan split over the value columns with 4 / 8 key-row groups (default 8).",
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_L32_KDA_SEQ2",
"backends": [
@@ -34921,6 +34955,12 @@
"line": 1800,
"backend": "cuda-hip",
"fn": "getenv"
},
{
"file": "engine/src/ling32/ling32_main.cpp",
"line": 1805,
"backend": "cuda-hip",
"fn": "getenv"
}
],
"parse": "flag",
@@ -34943,6 +34983,164 @@
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_L32_MLA_EXP_MODE",
"backends": [
"sycl"
],
"reads": [
{
"file": "engine/src/ling32/sycl/ling32_sy_k_mla_exp.cpp",
"line": 495,
"backend": "sycl",
"fn": "getenv"
}
],
"parse": "int",
"default_state": null,
"code_default": "-1",
"engine_sets": [],
"engine_defaults": [],
"launch_files": [],
"launch_sets": [],
"launch_reads": [],
"doc_mentions": [],
"status": "rollback",
"owner": "L32-SY-MLA",
"note": "SYCL expanded-form MLA prefill kernel: 0 = never available (absorbed form), 1 = force its plain-loop mode on a device without XMX (tests), unset = by device (Battlemage / PVC XMX).",
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_L32_MLA_FD_NS",
"backends": [
"sycl"
],
"reads": [
{
"file": "engine/src/ling32/sycl/ling32_sy_k_mla_fd.cpp",
"line": 277,
"backend": "sycl",
"fn": "getenv"
},
{
"file": "engine/src/ling32/sycl/ling32_sy_k_mla_fd.cpp",
"line": 277,
"backend": "sycl",
"fn": "getenv"
}
],
"parse": "int",
"default_state": null,
"code_default": null,
"engine_sets": [],
"engine_defaults": [],
"launch_files": [],
"launch_sets": [],
"launch_reads": [],
"doc_mentions": [],
"status": "research",
"owner": "L32-SY-MLA",
"note": "SYCL MLA flash-decoding: number of context slices (default 48, 1..128), tuning.",
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_L32_MLA_FD_ORIG",
"backends": [
"sycl"
],
"reads": [
{
"file": "engine/src/ling32/sycl/ling32_sy_k_mla_fd.cpp",
"line": 262,
"backend": "sycl",
"fn": "getenv"
}
],
"parse": "flag",
"default_state": "off",
"code_default": null,
"engine_sets": [],
"engine_defaults": [],
"launch_files": [],
"launch_sets": [],
"launch_reads": [],
"doc_mentions": [],
"status": "rollback",
"owner": "L32-SY-MLA",
"note": "SYCL MLA decode attention: set = the original per-head kernel instead of the flash-decoding kernel (A/B).",
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_L32_MLA_FD_PVU",
"backends": [
"sycl"
],
"reads": [
{
"file": "engine/src/ling32/sycl/ling32_sy_k_mla_fd.cpp",
"line": 279,
"backend": "sycl",
"fn": "getenv"
},
{
"file": "engine/src/ling32/sycl/ling32_sy_k_mla_fd.cpp",
"line": 279,
"backend": "sycl",
"fn": "getenv"
}
],
"parse": "int",
"default_state": null,
"code_default": null,
"engine_sets": [],
"engine_defaults": [],
"launch_files": [],
"launch_sets": [],
"launch_reads": [],
"doc_mentions": [],
"status": "research",
"owner": "L32-SY-MLA",
"note": "SYCL MLA flash-decoding: V rows in flight per thread (1, 2 or 4; default 1), tuning.",
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_L32_MLA_FD_RB",
"backends": [
"sycl"
],
"reads": [
{
"file": "engine/src/ling32/sycl/ling32_sy_k_mla_fd.cpp",
"line": 276,
"backend": "sycl",
"fn": "getenv"
},
{
"file": "engine/src/ling32/sycl/ling32_sy_k_mla_fd.cpp",
"line": 276,
"backend": "sycl",
"fn": "getenv"
}
],
"parse": "int",
"default_state": null,
"code_default": null,
"engine_sets": [],
"engine_defaults": [],
"launch_files": [],
"launch_sets": [],
"launch_reads": [],
"doc_mentions": [],
"status": "research",
"owner": "L32-SY-MLA",
"note": "SYCL MLA flash-decoding: key rows per QK batch (1 or 2; default 1), tuning.",
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_L32_MOE_DEC",
"backends": [
@@ -65707,6 +65905,34 @@
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_SY_PROF_TOP",
"backends": [
"sycl"
],
"reads": [
{
"file": "engine/src/ling32/sycl/ling32_sy.hpp",
"line": 87,
"backend": "sycl",
"fn": "getenv"
}
],
"parse": "int",
"default_state": null,
"code_default": "40",
"engine_sets": [],
"engine_defaults": [],
"launch_files": [],
"launch_sets": [],
"launch_reads": [],
"doc_mentions": [],
"status": "research",
"owner": "L32-SYCL",
"note": "SYCL profiling build (-DSTRATA_SY_PROFILE): how many kernels the exit report lists (default 40).",
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_SY_RELAXED_LIMITS",
"backends": [
@@ -65715,7 +65941,7 @@
"reads": [
{
"file": "engine/include/strata/sycl_compat/cuda_runtime.h",
"line": 62,
"line": 69,
"backend": "cuda-hip",
"fn": "getenv"
}
@@ -65748,7 +65974,7 @@
"reads": [
{
"file": "engine/include/strata/sycl_compat/cuda_runtime.h",
"line": 158,
"line": 165,
"backend": "cuda-hip",
"fn": "getenv"
}