ling32 sycl: KDA chunk scan split over the value columns (launch_chunk_seq2 + launch_chunk_norm), standalone test and A750 / B70 checks

The serial scan of a head over the chunks of 8 tokens ran as one work-group per head with one value column per lane and the 128-float state column in registers (spills on Xe). The state update is independent per value column, so the scan now runs as HD / 32 work-groups per head (32 columns each), G sub-groups per work-group, each owning HD / G key rows of the state in registers (lanes are the columns); the partial sums over d of kE s and qE s are exchanged through shared memory per chunk, U and the output row are computed redundantly per sub-group, the next chunk's tiles are prefetched into registers and stored into the other shared-memory buffer (two barriers per chunk). The gated RMS norm needs the whole row, so the scan writes the raw output into out and launch_chunk_norm normalises it in place (same expressions). Mode switch LING32_SY_KDA_SEQ: 0 the old scan, 4 / 8 the new one with 4 / 8 key-row groups (default 8); the decode / verify / snapshot path (launch_step, N <= 16) is untouched, state layout and final state are the same.

ling32_sy_kda_test: chunk scan modes against the sequential recurrence (hd 64 / 128, N 40 / 100, and 32 heads x 2048 tokens: max rel error <= 2.9e-5, gate 2e-4) and timings. A750: pre + scan for 32 heads, hd 128, 2048 tokens 141.6 ms (old) -> 77.3 ms (4 groups) -> 44.0 ms (8 groups). Forward tests f32 / q8 / wide with --kda-seq 4 pass in every mode (top-1 12 / 12, KL 4.3e-12 vs 4.2e-12 old).
This commit is contained in:
Niko1221 committed 2026-12-03 03:51:31 +01:00
1 parent 92365c07a8
commit c7f2967a16
5 files changed
+319 -3

No files matched your search

+3
View File
@@ -154,6 +154,9 @@ 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_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)
+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
@@ -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;
+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;
}