mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-04 07:18:50 +00:00
Merge f-ling32-sycl-mla (flash-decoding MLA attention for SYCL) into f-ling32-sycl
This commit is contained in:
commit
efddd28358
4 files changed
+388
-1
No files matched your search
@@ -151,6 +151,9 @@ if(LING32_SYCL)
|
||||
add_executable(ling32_moe_sy_test ${_tests_dir}/ling32_moe_sy_test.cpp) # L32-SY-MOE: routed experts, router, swiglu, combine against their CPU models
|
||||
target_link_libraries(ling32_moe_sy_test PRIVATE ling32_gpu)
|
||||
add_test(NAME ling32_moe_sy_test COMMAND ling32_moe_sy_test ${_tests_dir}/data)
|
||||
add_executable(ling32_sy_mla_fd_test ${_tests_dir}/ling32_sy_mla_fd_test.cpp) # L32-SY-MLA: flash-decoding MLA attention against the original kernel
|
||||
target_link_libraries(ling32_sy_mla_fd_test PRIVATE ling32_gpu)
|
||||
add_test(NAME ling32_sy_mla_fd_test COMMAND ling32_sy_mla_fd_test)
|
||||
add_executable(ling32_sy_bench ${_tests_dir}/ling32_sy_bench.cpp) # decode-step kernel cost model at the real shapes (not a ctest entry)
|
||||
target_link_libraries(ling32_sy_bench PRIVATE ling32_gpu)
|
||||
if(Python3_FOUND)
|
||||
|
||||
@@ -181,8 +181,9 @@ void mla_qabs(const float* q, const uint16_t* wk_b, float* qabs, int N, int H, i
|
||||
});
|
||||
}
|
||||
|
||||
// (L32-SY-MLA: this is now mla_attn_orig; mla_attn itself is the dispatcher in ling32_sy_k_mla_fd.cpp)
|
||||
// absorbed attention over the latent cache (online softmax, 256 keys per step). grid (N, H), block 256; smem (kv_lora + rope + 256) floats
|
||||
void mla_attn(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) {
|
||||
void mla_attn_orig(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, bool cache_f32_b, cudaStream_t s) {
|
||||
constexpr int kAttBlk = 256;
|
||||
const int cache_f32 = cache_f32_b ? 1 : 0;
|
||||
const size_t smem = (static_cast<size_t>(kv_lora) + rope + kAttBlk + 40) * sizeof(float);
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
// src/ling32/sycl/ling32_sy_k_mla_fd.cpp - absorbed MLA decode attention as flash-decoding (split over the context, then a reduction), fp32 latent cache.
|
||||
// Owner: L32-SY-MLA. The original kernel (ling32_sy_k_mla.cpp, mla_attn_orig) runs one work-group per (token, head): the 32 heads read the same latent rows 32 times, one row per thread, 5 GB/s.
|
||||
// Here one work-group serves kFdHG = 8 heads over a slice of the context, reading each latent row once for K and again for V (K and V are the same data; the second read is L1/L2 hot):
|
||||
// stage 1 grid (N tokens x H/8 head groups x kFdSplits slices), 256 threads (8 sub-groups). Per tile of 32 rows:
|
||||
// QK a sub-group owns 4 rows (2 batches of 2): the lanes cover the 576 floats of a row (4 x float4 + a float2), q of the 8 heads is in SLM, the 16 (head, row) partial sums per
|
||||
// lane are reduced over the 32 lanes with a reduce-scatter butterfly (16 shuffles per batch).
|
||||
// softmax sub-group w = head w, lane = row (online: running max m, sum l, rescale factor corr).
|
||||
// PV thread = (4 output columns, row parity), 8 heads x 4 accumulators in registers, one float4 of V per 32 FMA.
|
||||
// the two row parities are summed at the end and the un-normalised partial (acc, m, l) goes to a scratch buffer.
|
||||
// stage 2 grid (N x H x 4), 128 threads: combine the slices of a head with the usual max/sum merge, divide by the total l.
|
||||
// The split count is fixed (the launcher cannot see the context length: d_pos0 is on the device); a slice is ceil(L / kFdSplits) rows rounded up to a multiple of 32, so a short context
|
||||
// uses few slices and the remaining work-groups return at once. Summation order differs from the original kernel (not bit-exact, within 1e-5, see ling32_sy_mla_fd_test).
|
||||
#include "ling32_sy.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cfloat>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
|
||||
namespace strata::ling32::gpu {
|
||||
namespace {
|
||||
|
||||
constexpr int kFdHG = 8; // heads per work-group (= sub-groups per work-group)
|
||||
constexpr int kFdRows = 32; // rows per tile
|
||||
constexpr int kFdThreads = 256;
|
||||
constexpr int kFdW = 576; // kv_lora 512 + rope 64
|
||||
constexpr int kFdKv = 512;
|
||||
constexpr int kFdMaxSplits = 128; // scratch size; the split count in use is a launcher argument (default kFdSplitsDef)
|
||||
constexpr int kFdSplitsDef = 48;
|
||||
constexpr int kFdMaxN = 16; // tokens per call served by this path (spec spans); larger N (prompt chunks) stays on the original kernel
|
||||
|
||||
using f4 = sycl::float4;
|
||||
using f2 = sycl::float2;
|
||||
|
||||
struct FdScratch {
|
||||
float* part = nullptr; // [N][H][ns][512]
|
||||
float* ml = nullptr; // [N][H][ns][2]
|
||||
};
|
||||
FdScratch& fd_scratch(int H) {
|
||||
static std::mutex mu;
|
||||
static std::map<std::pair<int, int>, FdScratch> tabs;
|
||||
std::lock_guard<std::mutex> g(mu);
|
||||
const auto key = std::make_pair(strata::sy::cur_dev(), H);
|
||||
auto it = tabs.find(key);
|
||||
if (it != tabs.end()) return it->second;
|
||||
FdScratch sc;
|
||||
const size_t np = static_cast<size_t>(kFdMaxN) * H * kFdMaxSplits * kFdKv * sizeof(float), nm = static_cast<size_t>(kFdMaxN) * H * kFdMaxSplits * 2 * sizeof(float);
|
||||
if (cudaMalloc(reinterpret_cast<void**>(&sc.part), np) != cudaSuccess || cudaMalloc(reinterpret_cast<void**>(&sc.ml), nm) != cudaSuccess) {
|
||||
std::fprintf(stderr, "ling32 (SYCL): cannot allocate the MLA flash-decoding scratch (%zu bytes)\n", np + nm);
|
||||
std::abort();
|
||||
}
|
||||
return tabs.emplace(key, sc).first->second;
|
||||
}
|
||||
|
||||
// reduce-scatter step: v[0..2n) -> v[0..n); lane bit `mask` selects which half the lane keeps, the partner (lane ^ mask) sends the other half
|
||||
template <int NN>
|
||||
inline void rs_step(const sy::Blk& b, float* v, int mask) {
|
||||
const bool up = (b.lane() & mask) != 0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NN; ++i) {
|
||||
const float keep = up ? v[i + NN] : v[i];
|
||||
const float give = up ? v[i] : v[i + NN];
|
||||
v[i] = keep + b.shfl_xor(give, mask);
|
||||
}
|
||||
}
|
||||
|
||||
// slice length (rows) of a context of L rows
|
||||
inline int fd_chunk(int L, int ns) { return (((L + ns - 1) / ns) + (kFdRows - 1)) & ~(kFdRows - 1); }
|
||||
|
||||
template <int RB, int PVU>
|
||||
void fd_stage1(const float* qabs, const float* q, const float* cache, const int* d_pos0, float* part, float* ml, int N, int H, int nope, int rope, float scale, int ns, cudaStream_t s) {
|
||||
const int NHG = H / kFdHG;
|
||||
const size_t smem = (static_cast<size_t>(kFdHG) * kFdW + kFdRows * kFdHG + 16) * sizeof(float);
|
||||
sy::launch(s, N * NHG * ns, kFdThreads, smem, [=](sy::Blk b, char* smemp) {
|
||||
float* qs = reinterpret_cast<float*>(smemp); // [8][576]; reused for the final row-parity merge
|
||||
float* S = qs + kFdHG * kFdW; // [32 rows][8 heads]: scores, then probabilities
|
||||
float* corr = S + kFdRows * kFdHG; // [8]
|
||||
const int bid = b.bid(), hg = bid % NHG, sp = (bid / NHG) % ns, t = bid / (NHG * ns);
|
||||
const int L = *d_pos0 + t + 1;
|
||||
const int cs = fd_chunk(L, ns), start = sp * cs;
|
||||
if (start >= L) return;
|
||||
const int end = sycl::min(L, start + cs);
|
||||
const int tid = b.tid(), lane = b.lane(), w = b.warp();
|
||||
for (int idx = tid; idx < kFdHG * kFdW; idx += kFdThreads) {
|
||||
const int hh = idx / kFdW, k = idx - hh * kFdW;
|
||||
const size_t th = static_cast<size_t>(t) * H + hg * kFdHG + hh;
|
||||
qs[idx] = k < kFdKv ? qabs[th * kFdKv + k] : q[th * (nope + rope) + nope + (k - kFdKv)];
|
||||
}
|
||||
b.sync();
|
||||
|
||||
float m = -FLT_MAX, l = 0.0f; // running state of head w (uniform over the sub-group)
|
||||
const int cg = tid & 127, rh = tid >> 7; // PV: columns 4cg..4cg+3, rows of parity rh
|
||||
float acc[kFdHG][4];
|
||||
#pragma unroll
|
||||
for (int hh = 0; hh < kFdHG; ++hh)
|
||||
#pragma unroll
|
||||
for (int c = 0; c < 4; ++c) acc[hh][c] = 0.0f;
|
||||
|
||||
for (int r0 = start; r0 < end; r0 += kFdRows) {
|
||||
const int n = sycl::min(kFdRows, end - r0);
|
||||
// ---- QK: RB rows per batch, 4 / RB batches per sub-group
|
||||
#pragma unroll 1
|
||||
for (int bt = 0; bt < 4 / RB; ++bt) {
|
||||
const int ri0 = w * 4 + bt * RB;
|
||||
f4 kv[RB][4];
|
||||
f2 kr[RB];
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < RB; ++rb) {
|
||||
const float* rp = cache + static_cast<size_t>(r0 + sycl::min(ri0 + rb, n - 1)) * kFdW;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) kv[rb][j] = *reinterpret_cast<const f4*>(rp + 4 * lane + 128 * j);
|
||||
kr[rb] = *reinterpret_cast<const f2*>(rp + kFdKv + 2 * lane);
|
||||
}
|
||||
float a[RB * kFdHG];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RB * kFdHG; ++i) a[i] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int hh = 0; hh < kFdHG; ++hh) {
|
||||
const float* qh = qs + hh * kFdW;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
const f4 qv = *reinterpret_cast<const f4*>(qh + 4 * lane + 128 * j);
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < RB; ++rb) {
|
||||
float x = a[hh * RB + rb];
|
||||
x = sycl::fma(qv.x(), kv[rb][j].x(), x);
|
||||
x = sycl::fma(qv.y(), kv[rb][j].y(), x);
|
||||
x = sycl::fma(qv.z(), kv[rb][j].z(), x);
|
||||
x = sycl::fma(qv.w(), kv[rb][j].w(), x);
|
||||
a[hh * RB + rb] = x;
|
||||
}
|
||||
}
|
||||
const f2 qr = *reinterpret_cast<const f2*>(qh + kFdKv + 2 * lane);
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < RB; ++rb) {
|
||||
float x = a[hh * RB + rb];
|
||||
x = sycl::fma(qr.x(), kr[rb].x(), x);
|
||||
x = sycl::fma(qr.y(), kr[rb].y(), x);
|
||||
a[hh * RB + rb] = x;
|
||||
}
|
||||
}
|
||||
// reduce-scatter of the RB * 8 sums over the 32 lanes; lane then holds the sum for index (lane >> (5 - rounds)) & (NV - 1)
|
||||
if (RB == 2) {
|
||||
rs_step<8>(b, a, 16);
|
||||
rs_step<4>(b, a, 8);
|
||||
rs_step<2>(b, a, 4);
|
||||
rs_step<1>(b, a, 2);
|
||||
} else {
|
||||
rs_step<4>(b, a, 16);
|
||||
rs_step<2>(b, a, 8);
|
||||
rs_step<1>(b, a, 4);
|
||||
a[0] += b.shfl_xor(a[0], 2);
|
||||
}
|
||||
const float tot = a[0] + b.shfl_xor(a[0], 1);
|
||||
if ((lane & 1) == 0 && (RB == 2 || (lane & 2) == 0)) {
|
||||
const int idx = RB == 2 ? ((lane >> 1) & 15) : ((lane >> 2) & 7); // original index hh * RB + rb
|
||||
S[(ri0 + (idx % RB)) * kFdHG + (idx / RB)] = tot * scale;
|
||||
}
|
||||
}
|
||||
b.sync();
|
||||
// ---- online softmax: sub-group w = head w, lane = row
|
||||
{
|
||||
const float sc = lane < n ? S[lane * kFdHG + w] : -FLT_MAX;
|
||||
const float tm = b.warp_max(sc);
|
||||
const float mn = sycl::fmax(m, tm);
|
||||
const float cr = sycl::exp(m - mn);
|
||||
const float p = lane < n ? sycl::exp(sc - mn) : 0.0f;
|
||||
const float ps = sy::warp_sum_xor(b, p);
|
||||
l = l * cr + ps;
|
||||
m = mn;
|
||||
S[lane * kFdHG + w] = p;
|
||||
if (lane == 0) corr[w] = cr;
|
||||
}
|
||||
b.sync();
|
||||
// ---- PV
|
||||
{
|
||||
const f4 c0 = *reinterpret_cast<const f4*>(corr), c1 = *reinterpret_cast<const f4*>(corr + 4);
|
||||
const float cr[kFdHG] = {c0.x(), c0.y(), c0.z(), c0.w(), c1.x(), c1.y(), c1.z(), c1.w()};
|
||||
#pragma unroll
|
||||
for (int hh = 0; hh < kFdHG; ++hh)
|
||||
#pragma unroll
|
||||
for (int c = 0; c < 4; ++c) acc[hh][c] *= cr[hh];
|
||||
// rows rr = rh, rh + 2, ... of the tile, PVU at a time with their V loads issued first; rows >= n are clamped to a valid row and have p = 0
|
||||
#pragma unroll 1
|
||||
for (int u = 0; 2 * u + rh < n; u += PVU) {
|
||||
f4 vv[PVU];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < PVU; ++i) vv[i] = *reinterpret_cast<const f4*>(cache + static_cast<size_t>(r0 + sycl::min(rh + 2 * (u + i), n - 1)) * kFdW + 4 * cg);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < PVU; ++i) {
|
||||
const int rr = rh + 2 * (u + i);
|
||||
const f4 p0 = *reinterpret_cast<const f4*>(S + rr * kFdHG), p1 = *reinterpret_cast<const f4*>(S + rr * kFdHG + 4);
|
||||
const float pp[kFdHG] = {p0.x(), p0.y(), p0.z(), p0.w(), p1.x(), p1.y(), p1.z(), p1.w()};
|
||||
#pragma unroll
|
||||
for (int hh = 0; hh < kFdHG; ++hh) {
|
||||
acc[hh][0] = sycl::fma(pp[hh], vv[i].x(), acc[hh][0]);
|
||||
acc[hh][1] = sycl::fma(pp[hh], vv[i].y(), acc[hh][1]);
|
||||
acc[hh][2] = sycl::fma(pp[hh], vv[i].z(), acc[hh][2]);
|
||||
acc[hh][3] = sycl::fma(pp[hh], vv[i].w(), acc[hh][3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
b.sync();
|
||||
}
|
||||
// ---- merge the two row parities (through SLM) and write the partial
|
||||
if (rh == 1) {
|
||||
for (int hh = 0; hh < kFdHG; ++hh)
|
||||
for (int c = 0; c < 4; ++c) qs[hh * kFdKv + 4 * cg + c] = acc[hh][c];
|
||||
}
|
||||
b.sync();
|
||||
if (rh == 0) {
|
||||
for (int hh = 0; hh < kFdHG; ++hh) {
|
||||
const size_t th = static_cast<size_t>(t) * H + hg * kFdHG + hh;
|
||||
f4 o;
|
||||
o.x() = acc[hh][0] + qs[hh * kFdKv + 4 * cg];
|
||||
o.y() = acc[hh][1] + qs[hh * kFdKv + 4 * cg + 1];
|
||||
o.z() = acc[hh][2] + qs[hh * kFdKv + 4 * cg + 2];
|
||||
o.w() = acc[hh][3] + qs[hh * kFdKv + 4 * cg + 3];
|
||||
*reinterpret_cast<f4*>(part + (th * ns + sp) * kFdKv + 4 * cg) = o;
|
||||
}
|
||||
}
|
||||
if (lane == 0) {
|
||||
const size_t th = static_cast<size_t>(t) * H + hg * kFdHG + w;
|
||||
ml[(th * ns + sp) * 2] = m;
|
||||
ml[(th * ns + sp) * 2 + 1] = l;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void fd_stage2(const float* part, const float* ml, const int* d_pos0, float* ctx, int N, int H, int ns, cudaStream_t s) {
|
||||
sy::launch(s, N * H * 4, 128, 2 * kFdMaxSplits * sizeof(float), [=](sy::Blk b, char* smemp) {
|
||||
float* sm = reinterpret_cast<float*>(smemp);
|
||||
const int tid = b.tid(), q4 = b.bid() & 3, th = b.bid() >> 2, t = th / H;
|
||||
const int L = *d_pos0 + t + 1, cs = fd_chunk(L, ns), nact = (L + cs - 1) / cs;
|
||||
for (int i = tid; i < nact * 2; i += 128) sm[i] = ml[static_cast<size_t>(th) * ns * 2 + i];
|
||||
b.sync();
|
||||
float gm = -FLT_MAX;
|
||||
for (int i = 0; i < nact; ++i) gm = sycl::fmax(gm, sm[2 * i]);
|
||||
float tot = 0.0f, o = 0.0f;
|
||||
const int col = q4 * 128 + tid;
|
||||
for (int i = 0; i < nact; ++i) {
|
||||
const float wgt = sycl::exp(sm[2 * i] - gm);
|
||||
tot += wgt * sm[2 * i + 1];
|
||||
o += wgt * part[(static_cast<size_t>(th) * ns + i) * kFdKv + col];
|
||||
}
|
||||
ctx[static_cast<size_t>(th) * kFdKv + col] = o / tot;
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// the dispatcher behind the engine's mla_attn (declared in ling32_kernels.hpp): the original per-head kernel is mla_attn_orig in ling32_sy_k_mla.cpp
|
||||
void mla_attn_orig(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, bool cache_f32_b, cudaStream_t s);
|
||||
bool mla_attn_fd_supported(int N, int H, int rope, int kv_lora, bool cache_f32);
|
||||
void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, cudaStream_t s, int stages);
|
||||
|
||||
void mla_attn(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, bool cache_f32_b, cudaStream_t s) {
|
||||
// the context length is on the device (d_pos0), so the choice is by geometry only; at a short context the flash kernel costs about the same as the original (slices beyond L return at once)
|
||||
static const bool force_orig = std::getenv("LING32_SY_MLA_ORIG") != nullptr; // A/B switch
|
||||
if (!force_orig && mla_attn_fd_supported(N, H, rope, kv_lora, cache_f32_b)) mla_attn_fd(qabs, q, cache, d_pos0, ctx, N, H, nope, rope, kv_lora, scale, s, 3);
|
||||
else mla_attn_orig(qabs, q, cache, d_pos0, ctx, N, H, nope, rope, kv_lora, scale, cache_f32_b, s);
|
||||
}
|
||||
|
||||
// true when the flash-decoding kernel can serve this call (geometry and cache format); the caller falls back to mla_attn_orig otherwise
|
||||
bool mla_attn_fd_supported(int N, int H, int rope, int kv_lora, bool cache_f32) { return cache_f32 && N >= 1 && N <= kFdMaxN && kv_lora == kFdKv && rope == kFdW - kFdKv && H % kFdHG == 0; }
|
||||
|
||||
void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, cudaStream_t s, int stages) {
|
||||
if (!mla_attn_fd_supported(N, H, rope, kv_lora, true)) {
|
||||
std::fprintf(stderr, "ling32 (SYCL): mla_attn_fd called with an unsupported geometry\n");
|
||||
std::abort();
|
||||
}
|
||||
const FdScratch& sc = fd_scratch(H);
|
||||
static const int rb_env = std::getenv("LING32_SY_MLA_FD_RB") ? std::atoi(std::getenv("LING32_SY_MLA_FD_RB")) : 1; // tuning switches: rows per QK batch (1, 2)
|
||||
static const int ns_env = std::getenv("LING32_SY_MLA_FD_NS") ? std::min(kFdMaxSplits, std::max(1, std::atoi(std::getenv("LING32_SY_MLA_FD_NS")))) : kFdSplitsDef; // slices
|
||||
const int ns = ns_env;
|
||||
static const int pvu_env = std::getenv("LING32_SY_MLA_FD_PVU") ? std::atoi(std::getenv("LING32_SY_MLA_FD_PVU")) : 1; // and PV rows in flight (1, 2, 4)
|
||||
if (stages & 1) {
|
||||
const float* cf = static_cast<const float*>(cache);
|
||||
#define L32_FD_S1(RB_, PVU_) fd_stage1<RB_, PVU_>(qabs, q, cf, d_pos0, sc.part, sc.ml, N, H, nope, rope, scale, ns, s)
|
||||
if (rb_env == 1) { if (pvu_env == 4) L32_FD_S1(1, 4); else if (pvu_env == 2) L32_FD_S1(1, 2); else L32_FD_S1(1, 1); }
|
||||
else { if (pvu_env == 4) L32_FD_S1(2, 4); else if (pvu_env == 2) L32_FD_S1(2, 2); else L32_FD_S1(2, 1); }
|
||||
#undef L32_FD_S1
|
||||
}
|
||||
if (stages & 2) fd_stage2(sc.part, sc.ml, d_pos0, ctx, N, H, ns, s);
|
||||
}
|
||||
|
||||
} // namespace strata::ling32::gpu
|
||||
@@ -0,0 +1,93 @@
|
||||
// tests/ling32/ling32_sy_mla_fd_test.cpp - the flash-decoding MLA attention (sycl/ling32_sy_k_mla_fd.cpp) against the original per-head kernel (mla_attn_orig, ling32_sy_k_mla.cpp).
|
||||
// Real geometry (32 heads, nope 128, rope 64, kv_lora 512), fp32 latent cache. Contexts 1, 2, 31, 32, 33, 64, 257, 1024, 8192, 32768, 131072 with N = 1, and spans of N = 3 and 16 tokens (each token sees its own prefix);
|
||||
// three score regimes (flat, normal, peaked) so that the softmax merge across slices is exercised with very different maxima.
|
||||
// The summation order changes, so the result is not bit-exact: it must stay within 1e-5 absolute and relative (relative against max(|ref|, 0.1)). Prints the timing of both kernels as well.
|
||||
// usage: ling32_sy_mla_fd_test exit 0 = pass
|
||||
#include "ling32_kernels.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
using namespace strata::ling32;
|
||||
using namespace strata::ling32::gpu;
|
||||
|
||||
namespace strata::ling32::gpu {
|
||||
void mla_attn_orig(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, bool cache_f32_b, cudaStream_t s);
|
||||
bool mla_attn_fd_supported(int N, int H, int rope, int kv_lora, bool cache_f32);
|
||||
void mla_attn_fd(const float* qabs, const float* q, const void* cache, const int* d_pos0, float* ctx, int N, int H, int nope, int rope, int kv_lora, float scale, cudaStream_t s, int stages);
|
||||
} // namespace strata::ling32::gpu
|
||||
|
||||
namespace {
|
||||
template <class T> T* up(const std::vector<T>& h) {
|
||||
void* p = nullptr;
|
||||
if (cudaMalloc(&p, h.size() * sizeof(T)) != cudaSuccess) { std::fprintf(stderr, "alloc failed\n"); std::exit(1); }
|
||||
cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice);
|
||||
return static_cast<T*>(p);
|
||||
}
|
||||
double now_ms() { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
const int H = 32, nope = 128, rope = 64, kvl = 512, W = kvl + rope;
|
||||
const float scale = 1.0f / std::sqrt(static_cast<float>(nope + rope));
|
||||
std::mt19937 rng(11);
|
||||
int fails = 0;
|
||||
struct Case { int ctx, N; float qs; const char* what; };
|
||||
const Case cases[] = {{1, 1, 0.1f, "flat"}, {2, 1, 0.1f, "flat"}, {31, 1, 0.3f, "normal"}, {32, 1, 0.3f, "normal"}, {33, 1, 0.3f, "normal"}, {64, 1, 0.3f, "normal"},
|
||||
{257, 1, 0.1f, "flat"}, {1024, 1, 0.3f, "normal"}, {1024, 1, 1.5f, "peaked"}, {8192, 1, 0.1f, "flat"}, {8192, 1, 0.3f, "normal"}, {8192, 1, 1.5f, "peaked"},
|
||||
{32768, 1, 0.3f, "normal"}, {131072, 1, 0.3f, "normal"}, {3000, 3, 0.3f, "normal"}, {1000, 16, 0.3f, "normal"}, {97, 16, 1.5f, "peaked"}};
|
||||
for (const Case& c : cases) {
|
||||
const int ctx = c.ctx, N = c.N, rows = ctx + 8;
|
||||
std::vector<float> cache(static_cast<size_t>(rows) * W), qabs(static_cast<size_t>(N) * H * kvl), q(static_cast<size_t>(N) * H * (nope + rope));
|
||||
std::uniform_real_distribution<float> du(-1.0f, 1.0f);
|
||||
for (auto& v : cache) v = du(rng);
|
||||
for (auto& v : qabs) v = du(rng) * c.qs;
|
||||
for (auto& v : q) v = du(rng) * c.qs;
|
||||
const int p0 = ctx - N; // the last token sees ctx rows
|
||||
float *dc = up(cache), *dqa = up(qabs), *dq = up(q);
|
||||
int* dp = up(std::vector<int>{p0});
|
||||
std::vector<float> z(static_cast<size_t>(N) * H * kvl, 0.0f);
|
||||
float *o_ref = up(z), *o_fd = up(z);
|
||||
mla_attn_orig(dqa, dq, dc, dp, o_ref, N, H, nope, rope, kvl, scale, true, 0);
|
||||
mla_attn_fd(dqa, dq, dc, dp, o_fd, N, H, nope, rope, kvl, scale, 0, 3);
|
||||
cudaDeviceSynchronize();
|
||||
std::vector<float> a(z.size()), bb(z.size());
|
||||
cudaMemcpy(a.data(), o_ref, a.size() * 4, cudaMemcpyDeviceToHost);
|
||||
cudaMemcpy(bb.data(), o_fd, bb.size() * 4, cudaMemcpyDeviceToHost);
|
||||
double mabs = 0, mrel = 0;
|
||||
bool bad = false;
|
||||
for (size_t i = 0; i < a.size(); ++i) {
|
||||
if (!std::isfinite(bb[i])) bad = true;
|
||||
const double d = std::fabs(static_cast<double>(a[i]) - bb[i]);
|
||||
mabs = std::max(mabs, d);
|
||||
mrel = std::max(mrel, d / std::max(std::fabs(static_cast<double>(a[i])), 0.1));
|
||||
}
|
||||
const bool ok = !bad && mabs <= 1e-5 && mrel <= 1e-5; // mrel: relative to max(|ref|, 0.1)
|
||||
if (!ok) ++fails;
|
||||
// timing (N = 1 cases only)
|
||||
double t_ref = 0, t_fd = 0, t_s1 = 0;
|
||||
if (N == 1) {
|
||||
const int reps = ctx >= 32768 ? 5 : (ctx >= 1024 ? 20 : 50);
|
||||
double t0 = now_ms();
|
||||
for (int i = 0; i < reps; ++i) mla_attn_orig(dqa, dq, dc, dp, o_ref, N, H, nope, rope, kvl, scale, true, 0);
|
||||
cudaDeviceSynchronize();
|
||||
t_ref = (now_ms() - t0) / reps;
|
||||
t0 = now_ms();
|
||||
for (int i = 0; i < reps; ++i) mla_attn_fd(dqa, dq, dc, dp, o_fd, N, H, nope, rope, kvl, scale, 0, 3);
|
||||
cudaDeviceSynchronize();
|
||||
t_fd = (now_ms() - t0) / reps;
|
||||
t0 = now_ms();
|
||||
for (int i = 0; i < reps; ++i) mla_attn_fd(dqa, dq, dc, dp, o_fd, N, H, nope, rope, kvl, scale, 0, 1);
|
||||
cudaDeviceSynchronize();
|
||||
t_s1 = (now_ms() - t0) / reps;
|
||||
}
|
||||
std::printf("ctx %5d N %2d %-6s max abs %.3e max rel %.3e orig %.3f ms fd %.3f ms (stage 1 alone %.3f) %s\n", ctx, N, c.what, mabs, mrel, t_ref, t_fd, t_s1, ok ? "ok" : "FAIL");
|
||||
cudaFree(dc); cudaFree(dqa); cudaFree(dq); cudaFree(dp); cudaFree(o_ref); cudaFree(o_fd);
|
||||
}
|
||||
std::printf(fails ? "ling32_sy_mla_fd_test: %d FAILED\n" : "ling32_sy_mla_fd_test: all ok (%d)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
Reference in new issue
Block a user