okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Trial2 merge f-0291-pr-intel (2b4d43bac)5438023a6

main
26.0 KiB495 linesraw
1// src/kernels/qsa_prompt_attn_parity.cpp - perf-review D-1: the tensor-core prompt attention (qsa_prompt_attn.hpp)
2// against the FP32 kernel it replaces (`qsa_decode_attn_batch`) and an FP64 host reference (GPU, synthetic, no model).
3//
4// Int8, FP16 and Q4_0 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051
5// widest, a recent window plus older cells that drift slowly from one query to the next, so neighbours share most
6// of them as they do in a real prompt; short contexts take every cell). Checks:
7//   1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math);
8//   2. the new and old outputs agree to a relative 1e-4 of the output scale;
9// then times both over a prompt chunk (the old one in batches of 32, as prefill.cpp calls it).
10// HIP builds (S6): the same checks for the RDNA4 matrix-core kernel (STRATA_HIP_WMMA), skipped (77) off gfx12.
11// Usage: qsa_prompt_attn_parity [context=32768] [queries=2048] [reps=5]
12#define DPCT_PROFILING_ENABLED
13#include <sycl/sycl.hpp>
14#include <dpct/dpct.hpp>
15#include "strata/kernels/qsa.hpp"
16#include "strata/kernels/qsa_decode_attn.hpp"
17#include "strata/kernels/qsa_prompt_attn.hpp"
18#include "strata/kernels/kv_q4.hpp"
19
20#include <algorithm>
21#include <cmath>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25#include <random>
26#include <vector>
27
28namespace k = strata::kernels;
29namespace strata::kernels {   // SYCL port: the prompt path's per-cell attention (qsa_decode_attn.dp.cpp)
30void qsa_prompt_attn_percell(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
31                             int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream);
32}
33
34namespace {
35void ck(dpct::err0 e, const char *w) {
36    /*
37    DPCT1009: SYCL reports errors using exceptions and does not use error
38    codes. Please replace the "get_error_string_dummy(...)" with a real
39    error-handling function.
40    */
41}
42template <typename T> T* up(const std::vector<T>& h) {
43    T* d = nullptr;
44    ck(DPCT_CHECK_ERROR(
45           d = (T *)sycl::malloc_device(h.size() * sizeof(T) + 64,
46                                        dpct::get_in_order_queue())),
47       "malloc");
48    /*
49    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
50    in the original code the source host memory is pageable memory. If the
51    memory is not pageable, call wait() on event return by memcpy API to ensure
52    synchronization behavior.
53    */
54    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
55           d, h.data(), h.size() * sizeof(T)).wait()),
56       "upload");
57    return d;
58}
59float h2f(uint16_t b) {
60    sycl::half h; *reinterpret_cast<uint16_t *>(&h) = b;
61    return sycl::vec<sycl::half, 1>(h)
62        .convert<float, sycl::rounding_mode::automatic>()[0];
63}
64uint16_t f2h(float f) {
65    sycl::half h =
66        sycl::vec<float, 1>(f)
67            .convert<sycl::half, sycl::rounding_mode::automatic>()[0];
68    return *reinterpret_cast<uint16_t *>(&h);
69}
70
71int run(int fmt, int64_t ctx, int64_t nq, int reps) {   // fmt 1 int8, 0 fp16, 2 q4_0
72#if !defined(__HIPCC__) && !defined(STRATA_USE_HIP)
73    if (fmt == 2) {   // mode 4 (Q4_0 KV) runs on sm_80 and newer only: below that the dispatcher keeps the old kernel
74        int dev = 0, major = 0;
75        ck(DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()), "device");
76        ck(DPCT_CHECK_ERROR(major = dpct::get_device(dev).get_major_version()),
77           "cc");
78        if (major < 8) {
79            std::printf("SKIP q4_0 ctx %lld: the tensor-core kernel takes Q4_0 KV on sm_80+ only (this device: sm_%d)\n",
80                        (long long) ctx, major);
81            return 0;
82        }
83    }
84#endif
85    const k::QsaShapes s = k::qsa_real_shapes();
86    const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
87    const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;
88    std::mt19937 rng(1234 + fmt);
89    std::normal_distribution<float> nd(0.f, 1.f);
90    std::uniform_int_distribution<int> code(-127, 127);
91    std::uniform_real_distribution<float> sc(0.005f, 0.03f);
92    // pools; page table a shuffled permutation (the readers must follow it)
93    std::vector<int8_t> kq, vq;
94    std::vector<uint16_t> ks, vs, kh, vh;
95    std::vector<uint8_t> k4, v4;   // q4_0: 8 blocks of {fp16 d, 16 code bytes} per row (kv_q4.hpp)
96    constexpr int64_t B4 = 18, ROW4 = 8 * B4;
97    if (fmt == 2) {
98        std::uniform_int_distribution<int> byte(0, 255);
99        // the scales as a q4_0 pool holds them: signed (ggml's d = max / -8) and spread over two decades, so a chunk's
100        // cells mix signs and magnitudes (a positive-only bound on them overflowed FP16 on real K/V)
101        std::uniform_real_distribution<float> lg(std::log(0.01f), std::log(1.0f));
102        auto sc4 = [&](std::mt19937& r) { return std::exp(lg(r)) * (byte(r) & 1 ? -1.0f : 1.0f); };
103        k4.resize(rows * ROW4); v4.resize(rows * ROW4);
104        for (auto* pool : {&k4, &v4})
105            for (int64_t b = 0; b < rows * 8; ++b) {
106                const uint16_t d = f2h(sc4(rng));
107                std::memcpy(pool->data() + b * B4, &d, 2);
108                for (int j = 0; j < 16; ++j) (*pool)[b * B4 + 2 + j] = (uint8_t) byte(rng);
109            }
110    } else if (fmt == 1) {
111        kq.resize(rows * HD); vq.resize(rows * HD); ks.resize(rows * 4); vs.resize(rows * 4);
112        for (auto& x : kq) x = (int8_t) code(rng);
113        for (auto& x : vq) x = (int8_t) code(rng);
114        for (auto& x : ks) x = f2h(sc(rng));
115        for (auto& x : vs) x = f2h(sc(rng));
116    } else {
117        kh.resize(rows * HD); vh.resize(rows * HD);
118        for (auto& x : kh) x = f2h(nd(rng) * 1.5f);
119        for (auto& x : vh) x = f2h(nd(rng));
120    }
121    std::vector<int32_t> table(pages);
122    for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;
123    std::shuffle(table.begin(), table.end(), rng);
124    if (const char* mask = std::getenv("QA_MASK_PAGES")) {
125        const bool all = std::strcmp(mask, "all") == 0;
126        for (size_t i = 0; i < table.size(); ++i)
127            if (all || i % 7 == 0) table[i] = -1;
128    }
129    // queries at positions ctx - nq .. ctx - 1
130    const int64_t cap = k::qsa_selection_width(ctx, s);
131    std::vector<int32_t> ids((size_t) (nq * cap), 0), steps((size_t) (nq * k::kStepCount), 0);
132    std::vector<float> q((size_t) (nq * NH * HD));
133    for (auto& x : q) x = nd(rng) * 2.0f;
134    std::vector<int32_t> old_cells;
135    for (int64_t i = 0; i < nq; ++i) {
136        const int64_t pos = ctx - nq + i, nkv = pos + 1;
137        const int64_t w = k::qsa_selection_width(nkv, s);
138        int32_t* sel = ids.data() + i * cap;
139        steps[i * k::kStepCount + k::kStepWidth] = (int32_t) w;
140        if (w == nkv) {
141            for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c;
142            continue;
143        }
144        if (std::getenv("QA_BLOCK4")) {   // the engine's selections are whole blocks of four cells (idx_block): 128 recent blocks + random older ones, then the tail cells
145            std::mt19937 r3((unsigned) (i / 4) * 2654435761u + 7);
146            const int64_t nbk = nkv / 4, take = std::min<int64_t>(nbk, w / 4);
147            std::vector<int32_t> blocks;
148            for (int64_t b = std::max<int64_t>(0, nbk - 128); b < nbk; ++b) blocks.push_back((int32_t) b);
149            std::vector<int32_t> rest;
150            for (int64_t b = 0; b < std::max<int64_t>(0, nbk - 128); ++b) rest.push_back((int32_t) b);
151            std::shuffle(rest.begin(), rest.end(), r3);
152            for (int64_t b = 0; (int64_t) blocks.size() < take && b < (int64_t) rest.size(); ++b) blocks.push_back(rest[b]);
153            std::sort(blocks.begin(), blocks.end());
154            std::vector<int32_t> v;
155            for (int32_t b : blocks) for (int r = 0; r < 4; ++r) v.push_back(b * 4 + r);
156            for (int64_t c = nbk * 4; c < nkv; ++c) v.push_back((int32_t) c);
157            steps[i * k::kStepCount + k::kStepWidth] = (int32_t) v.size();
158            std::copy(v.begin(), v.end(), sel);
159            continue;
160        }
161        const int64_t recent = 512, older = w - recent;
162        if ((int64_t) old_cells.size() != older) {   // the older cells: a set that drifts ~3% per query
163            std::vector<int32_t> all((size_t) (nkv - recent));
164            for (int64_t c = 0; c < nkv - recent; ++c) all[c] = (int32_t) c;
165            std::shuffle(all.begin(), all.end(), rng);
166            old_cells.assign(all.begin(), all.begin() + older);
167        } else {
168            std::uniform_int_distribution<int64_t> pick(0, older - 1), any(0, nkv - recent - 1);
169            for (int r = 0; r < older / 32; ++r) {
170                const int32_t c = (int32_t) any(rng);
171                if (std::find(old_cells.begin(), old_cells.end(), c) == old_cells.end()) old_cells[pick(rng)] = c;
172            }
173        }
174        std::vector<int32_t> v(old_cells);
175        for (int64_t c = nkv - recent; c < nkv; ++c) v.push_back((int32_t) c);
176        std::sort(v.begin(), v.end());
177        std::copy(v.begin(), v.end(), sel);
178    }
179    // QA_SAME=1 (S23 probe): every query reads the same first-w cells - the best case of any K/V sharing between queries
180    // (all loads hit the caches); QA_SAME=2: query i reads a window of w cells at i / 4 * 64 (neighbours share ~90%)
181    if (const char* sm = std::getenv("QA_SAME")) {
182        const int mode = std::atoi(sm);
183        for (int64_t i = 0; i < nq; ++i) {
184            const int64_t w = steps[i * k::kStepCount + k::kStepWidth], nkv = ctx - nq + i + 1;
185            if (w == nkv) continue;
186            if (mode == 3 || mode == 4) {   // 3: w random cells per query (no overlap beyond chance); 4: a 4-query group shares
187                // one random set of w - 512 cells (the union of 4 queries = 1x), the last 512 cells recent
188                std::mt19937 r3((unsigned) (mode == 3 ? i : i / 4) * 2654435761u + 7);
189                std::vector<int32_t> all((size_t) (nkv - 512));
190                for (int64_t c = 0; c < nkv - 512; ++c) all[c] = (int32_t) c;
191                std::shuffle(all.begin(), all.end(), r3);
192                std::vector<int32_t> v(all.begin(), all.begin() + (w - 512));
193                for (int64_t c = nkv - 512; c < nkv; ++c) v.push_back((int32_t) c);
194                std::sort(v.begin(), v.end());
195                std::copy(v.begin(), v.end(), ids.data() + i * cap);
196                continue;
197            }
198            const int64_t base = mode == 1 ? 0 : std::min<int64_t>(i / 4 * 64, nkv - w);
199            for (int64_t c = 0; c < w; ++c) ids[i * cap + c] = (int32_t) (base + c);
200        }
201    }
202    // QA_DUMP=<file> QA_LAYER=n (S23 probe): the engine's own selections (STRATA_QSA_DUMP records {layer, pos0, T, cap} +
203    // T*cap cells): the last record of that layer, whose T must be nq and pos0 + T ctx
204    if (const char* df = std::getenv("QA_DUMP")) {
205        const int want = std::getenv("QA_LAYER") ? std::atoi(std::getenv("QA_LAYER")) : 3;
206        std::FILE* f = std::fopen(df, "rb");
207        if (!f) { std::fprintf(stderr, "QA_DUMP: cannot open\n"); std::exit(2); }
208        int32_t h[4];
209        long at = -1;
210        while (std::fread(h, 4, 4, f) == 4) {
211            const long data = std::ftell(f);
212            if (h[0] == want && h[2] == nq && h[1] + h[2] == ctx && h[3] == cap) at = data;
213            std::fseek(f, (long) h[2] * h[3] * 4, SEEK_CUR);
214        }
215        if (at < 0) { std::fprintf(stderr, "QA_DUMP: no record for layer %d, T %lld, ctx %lld\n", want, (long long) nq, (long long) ctx); std::exit(2); }
216        std::fseek(f, at, SEEK_SET);
217        if (std::fread(ids.data(), 4, ids.size(), f) != ids.size()) std::exit(2);
218        std::fclose(f);
219        for (int grp : {2, 4, 8, 16}) {   // the union of `grp` neighbouring queries' cells against grp x the width
220            double su = 0, sw = 0;
221            for (int64_t i0 = 0; i0 + grp <= nq; i0 += grp * 16) {
222                std::vector<int32_t> u;
223                for (int g2 = 0; g2 < grp; ++g2) {
224                    const int64_t w = steps[(i0 + g2) * k::kStepCount + k::kStepWidth];
225                    u.insert(u.end(), ids.begin() + (i0 + g2) * cap, ids.begin() + (i0 + g2) * cap + w);
226                    sw += (double) w;
227                }
228                std::sort(u.begin(), u.end());
229                su += (double) (std::unique(u.begin(), u.end()) - u.begin());
230            }
231            std::printf("QA_DUMP overlap: %d-query groups read %.2fx the cells of one query (%.1f%% of %d x)\n", grp,
232                        su * grp / sw, 100.0 * su / sw, grp);
233        }
234    }
235    k::QsaAttnPools pl;
236    if (fmt == 2) { pl.k_q4 = up(k4); pl.v_q4 = up(v4); }
237    else if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }
238    else { pl.k_pool = up(kh); pl.v_pool = up(vh); }
239    // a q4_0 value: block d / 32 of the row, element j = d % 32 in the low nibble of byte j (j < 16), else the high
240    // nibble of byte j - 16, minus 8, times the block's scale
241    auto q4v = [&](const std::vector<uint8_t>& pool, int64_t row, int64_t d) {
242        const uint8_t* blk = pool.data() + row * ROW4 + (d / 32) * B4;
243        uint16_t sc;
244        std::memcpy(&sc, blk, 2);
245        const int j = (int) (d % 32);
246        const int code = j < 16 ? (blk[2 + j] & 0x0F) : (blk[2 + j - 16] >> 4);
247        return (double) (code - 8) * h2f(sc);
248    };
249    pl.page_table = up(table);
250    const int32_t* d_ids = up(ids);
251    const int32_t* d_steps = up(steps);
252    const float* d_q = up(q);
253    float *d_old = nullptr, *d_new = nullptr, *scratch = nullptr;
254    const int64_t batch = 32;
255    ck(DPCT_CHECK_ERROR(d_old = (float *)sycl::malloc_device(
256                            nq * NH * HD * 4, dpct::get_in_order_queue())),
257       "malloc");
258    ck(DPCT_CHECK_ERROR(d_new = (float *)sycl::malloc_device(
259                            nq * NH * HD * 4, dpct::get_in_order_queue())),
260       "malloc");
261    ck(DPCT_CHECK_ERROR(
262           scratch = (float *)sycl::malloc_device(
263               batch * k::qsa_decode_attn_scratch_floats(cap, s) * 4,
264               dpct::get_in_order_queue())),
265       "malloc");
266    auto old_run = [&]() {
267        for (int64_t t0 = 0; t0 < nq; t0 += batch)
268            k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap, s,
269                                     scratch, d_old + t0 * NH * HD, std::min(batch, nq - t0), nullptr);
270    };
271    float* d_pc = nullptr;   // SYCL port: qsa_prompt_attn_percell's output
272    ck(DPCT_CHECK_ERROR(d_pc = (float *)sycl::malloc_device(nq * NH * HD * 4, dpct::get_in_order_queue())), "malloc");
273    auto pc_run = [&]() {
274        for (int64_t t0 = 0; t0 < nq; t0 += batch)
275            k::qsa_prompt_attn_percell(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap, s,
276                                       scratch, d_pc + t0 * NH * HD, std::min(batch, nq - t0), nullptr);
277    };
278    bool refused = false;   // SYCL port: the XMX kernel takes int8 and FP16 pools; the per-cell check runs anyway
279    auto new_run = [&]() {
280        if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nq, nullptr)) {
281            if (!refused) std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools: per-cell check only\n");
282            refused = true;
283        }
284    };
285    old_run();
286    new_run();
287    pc_run();
288    ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
289       "run");
290    std::vector<float> o((size_t) (nq * NH * HD)), nw(o.size()), pcw(o.size());
291    ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(pcw.data(), d_pc, pcw.size() * 4).wait()), "down");
292    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
293                            .memcpy(o.data(), d_old, o.size() * 4)
294                            .wait()),
295       "down");
296    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
297                            .memcpy(nw.data(), d_new, nw.size() * 4)
298                            .wait()),
299       "down");
300    if (refused) nw = o;   // SYCL port: nothing of the XMX kernel to compare
301    {
302        uint64_t hh = 1469598103934665603ull;
303        for (float x : o) { uint32_t u; std::memcpy(&u, &x, 4); hh = (hh ^ u) * 1099511628211ull; }
304        std::printf("FP32HASH %016llx\n", (unsigned long long) hh);
305    }
306    {   // a hash of the new kernel's output bits (bitwise A/B of two builds / switches)
307        uint64_t hh = 1469598103934665603ull;
308        for (float x : nw) { uint32_t u; std::memcpy(&u, &x, 4); hh = (hh ^ u) * 1099511628211ull; }
309        std::printf("NEWHASH %016llx\n", (unsigned long long) hh);
310    }
311    // 1. FP64 reference on a sample of queries
312    double err_old = 0, err_new = 0, err_pc = 0, ref_scale = 0;
313    for (int64_t i = 0; i < nq; i += std::max<int64_t>(1, nq / 16)) {
314        const int64_t w = steps[i * k::kStepCount + k::kStepWidth];
315        const int32_t* sel = ids.data() + i * cap;
316        for (int64_t h = 0; h < NH; ++h) {
317            const int64_t kvh = h / (NH / NKV);
318            std::vector<double> sco((size_t) w);
319            double mx = -1e300;
320            for (int64_t c = 0; c < w; ++c) {
321                const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;
322                if (table[cell / PS] < 0) {
323                    sco[c] = -INFINITY;
324                    continue;
325                }
326                double a = 0;
327                for (int64_t d = 0; d < HD; ++d) {
328                    const double kv = fmt == 2 ? q4v(k4, row, d)
329                                      : fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]);
330                    a += (double) q[(i * NH + h) * HD + d] * kv;
331                }
332                sco[c] = a / 16.0;
333                mx = std::max(mx, sco[c]);
334            }
335            double l = 0;
336            for (auto& x : sco) { x = std::exp(x - mx); l += x; }
337            for (int64_t d = 0; d < HD; ++d) {
338                double a = 0;
339                for (int64_t c = 0; c < w; ++c) {
340                    const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;
341                    if (table[cell / PS] < 0) continue;
342                    const double vv = fmt == 2 ? q4v(v4, row, d)
343                                      : fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]);
344                    a += sco[c] * vv;
345                }
346                const double r = l > 0 ? a / l : 0.0;
347                const size_t at = (size_t) ((i * NH + h) * HD + d);
348                if (std::getenv("PARITY_DUMP2") && fmt == 1 && i == 0 && h == 0 && d == 0) {
349                    for (int c = 0; c < 4; ++c) for (int n = 0; n < 6; ++n) {
350                        const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + 0) * PS + cell % PS;
351                        double a2 = 0;
352                        for (int64_t dd = 0; dd < HD; ++dd) a2 += (double) q[(i * NH + n) * HD + dd] * ((double) kq[row * HD + dd] * h2f(ks[row * 4 + dd / 64]));
353                        std::printf("S c%d n%d ref %.5f new %.5f\n", c, n, a2 / 16.0 * 1.4426950408889634, (double) nw[c * 16 + n]);
354                    }
355                }
356                if (std::getenv("PARITY_DUMP") && i == 0 && (d == 3 || d == 70))
357                    std::printf("dump h%lld d%lld ref %.5f old %.5f new %.5f\n", (long long) h, (long long) d, r, (double) o[at], (double) nw[at]);
358                ref_scale = std::max(ref_scale, std::fabs(r));
359                err_old = std::max(err_old, std::fabs(o[at] - r));
360                err_new = std::max(err_new, std::fabs(nw[at] - r));
361                err_pc = std::max(err_pc, std::fabs(pcw[at] - r));
362            }
363        }
364    }
365    // 2. new vs old everywhere
366    double diff = 0, scale = 0, diff_pc = 0;
367    for (size_t i = 0; i < o.size(); ++i) {
368        diff = std::max(diff, (double) std::fabs(o[i] - nw[i]));
369        diff_pc = std::max(diff_pc, (double) std::fabs(o[i] - pcw[i]));
370        scale = std::max(scale, (double) std::fabs(o[i]));
371    }
372    // 3. speed
373    dpct::event_ptr e0, e1;
374    e0 = new sycl::event();
375    e1 = new sycl::event();
376    float ms_old = 0, ms_new = 0;
377    dpct::sync_barrier(e0);
378    for (int r = 0; r < reps; ++r) old_run();
379    dpct::sync_barrier(e1);
380    ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "time");
381    ms_old =
382        (e1->get_profiling_info<sycl::info::event_profiling::command_end>() -
383         e0->get_profiling_info<sycl::info::event_profiling::command_start>()) /
384        1000000.0f;
385    dpct::sync_barrier(e0);
386    for (int r = 0; r < reps; ++r) new_run();
387    dpct::sync_barrier(e1);
388    ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "time");
389    ms_new =
390        (e1->get_profiling_info<sycl::info::event_profiling::command_end>() -
391         e0->get_profiling_info<sycl::info::event_profiling::command_start>()) /
392        1000000.0f;
393    float ms_pc = 0;
394    dpct::sync_barrier(e0);
395    for (int r = 0; r < reps; ++r) pc_run();
396    dpct::sync_barrier(e1);
397    ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "time");
398    ms_pc = (e1->get_profiling_info<sycl::info::event_profiling::command_end>() -
399             e0->get_profiling_info<sycl::info::event_profiling::command_start>()) / 1000000.0f;
400    // SYCL port: the per-cell kernel - FP32 like the warp kernel, another summation order
401    const bool ok_pc = err_pc <= std::max(4.0 * err_old, 1e-6 * ref_scale) && diff_pc <= 1e-4 * scale;
402    std::printf("%s %s per-cell: vs FP64 %.3g (warp kernel %.3g), vs the warp kernel %.2g of scale; %.3f -> %.3f ms per chunk (%.2fx)\n",
403                ok_pc ? "PASS" : "FAIL", fmt == 2 ? "q4_0" : fmt == 1 ? "int8" : "fp16", err_pc, err_old, diff_pc / scale,
404                ms_old / reps, ms_pc / reps, ms_old / ms_pc);
405    sycl::free((void *)d_pc, dpct::get_in_order_queue());
406    if (std::getenv("QA_FP32_GRAPH")) {
407        auto* queue = &dpct::get_in_order_queue();
408        constexpr int calls = 32;
409        dpct::experimental::command_graph_ptr graph;
410        dpct::experimental::begin_recording(queue);
411        for (int i = 0; i < calls; ++i) old_run();
412        dpct::experimental::end_recording(queue, &graph);
413        auto executable = graph->finalize();
414        delete graph;
415        std::vector<double> times;
416        for (int i = 0; i < 20; ++i) {
417            auto begin = queue->ext_oneapi_submit_barrier();
418            queue->ext_oneapi_graph(executable);
419            auto end = queue->ext_oneapi_submit_barrier();
420            end.wait_and_throw();
421            if (i >= 5)
422                times.push_back(double(
423                    end.get_profiling_info<sycl::info::event_profiling::command_end>() -
424                    begin.get_profiling_info<sycl::info::event_profiling::command_start>()) / 1000 / calls);
425        }
426        std::sort(times.begin(), times.end());
427        std::printf("DECODEGRAPH fmt=%d ctx=%lld nq=%lld us=%.3f\n",
428                    fmt, (long long) ctx, (long long) nq, times[times.size() / 2]);
429    }
430    const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale) && ok_pc;
431    const bool ok2 = diff <= 1e-4 * scale;
432    std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of "
433                "scale); %.3f -> %.3f ms per chunk (%.2fx)\n",
434                ok1 && ok2 ? "PASS" : "FAIL", fmt == 2 ? "q4_0" : fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old,
435                err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new);
436    sycl::free((void *)d_ids, dpct::get_in_order_queue());
437        sycl::free((void *)d_steps, dpct::get_in_order_queue());
438        sycl::free((void *)d_q, dpct::get_in_order_queue());
439        sycl::free((void *)d_old, dpct::get_in_order_queue());
440        sycl::free((void *)d_new, dpct::get_in_order_queue());
441    sycl::free((void *)scratch, dpct::get_in_order_queue());
442    sycl::free((void *)pl.k_q, dpct::get_in_order_queue());
443        sycl::free((void *)pl.v_q, dpct::get_in_order_queue());
444        sycl::free((void *)pl.k_scale, dpct::get_in_order_queue());
445        sycl::free((void *)pl.v_scale, dpct::get_in_order_queue());
446    sycl::free((void *)pl.k_pool, dpct::get_in_order_queue());
447        sycl::free((void *)pl.v_pool, dpct::get_in_order_queue());
448        sycl::free((void *)pl.page_table, dpct::get_in_order_queue());
449    sycl::free((void *)pl.k_q4, dpct::get_in_order_queue());
450        sycl::free((void *)pl.v_q4, dpct::get_in_order_queue());
451    return ok1 && ok2 ? 0 : 1;
452}
453}  // namespace
454
455int main(int argc, char** argv) {
456    setenv("STRATA_PROMPT_ATTN_XMX", "1", 0);   // SYCL port: the batched kernel under test is the XMX one (opt-in in the engine)
457#if defined(__HIP_PLATFORM_AMD__)
458    // S6: on AMD the kernel under test is the RDNA4 matrix-core one (opt-in in the engine); other cards skip
459    {
460        int dev = 0;
461        hipDeviceProp_t prop{};
462        if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return 2;
463        if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0 && std::strncmp(prop.gcnArchName, "gfx11", 5) != 0) {
464            std::printf("SKIP: %s is not gfx11 / gfx12 (the matrix-core prompt attention)\n", prop.gcnArchName);
465            return 77;
466        }
467#if defined(_WIN32)
468        _putenv_s("STRATA_HIP_WMMA", "1");
469#else
470        setenv("STRATA_HIP_WMMA", "1", 1);
471#endif
472    }
473#endif
474    const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768;
475    const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048;
476    const int reps = argc > 3 ? std::atoi(argv[3]) : 5;
477    const bool int8_only = argc > 4 && std::strcmp(argv[4], "--int8-only") == 0;
478    if (argc > 4 && !int8_only) {
479        std::fprintf(stderr, "usage: qsa_prompt_attn_parity [context] [queries] [reps] [--int8-only]\n");
480        return 2;
481    }
482    int fails = 0;
483    fails += run(1, ctx, nq, reps);
484#if !defined(__HIP_PLATFORM_AMD__)
485    if (!int8_only) {
486        fails += run(0, ctx, nq, reps);   // FP16 KV: the RDNA4 kernel takes int8 KV only
487        fails += run(2, ctx, nq, reps);   // Q4_0 KV (mode 4)
488        fails += run(2, 1500, std::min<int64_t>(nq, 1500), reps);
489    }
490#endif
491    fails += run(1, 1500, std::min<int64_t>(nq, 1500), reps);   // short context: the selection is every cell
492    fails += run(1, 2100, std::min<int64_t>(nq, 256), reps);    // the identity-to-sparse edge
493    std::printf("FAILURES: %d\n", fails);
494    return fails;
495}