scratch: + KDA scan

This commit is contained in:
Niko1221 committed 2026-12-03 03:59:50 +01:00
commit 8c8ed5cd0b
7 files changed
+405 -19

No files matched your search

@@ -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;
});
+3
View File
@@ -157,6 +157,9 @@ if(LING32_SYCL)
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)
+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: LING32_SY_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("LING32_SY_KDA_SEQ") ? std::atoi(std::getenv("LING32_SY_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);
+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 (LING32_SY_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"
LING32_SY_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"
LING32_SY_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"
LING32_SY_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
+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;
}