okami.mom/strata

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

Niko1221Merge branch 'f-1402-y' into f-14025af104b51

main
24.7 KiB482 linesraw
1// src/kernels/kv_hybrid_parity.cpp - hybrid K8V4 KV against host references (GPU, no model).
2//
3// Exercises the EXACT composed calls the engine's hybrid path makes (layer.cpp / prefill.cpp): the q8/q4
4// append and gather kernels invoked with the unused half's pointers folded onto the used pool, and the
5// fused decode attention's KV_MODE 3 (INT8 K, rotated Q4_0 V) followed by the output's inverse Hadamard.
6//   1. K: INT8 codes + FP16 scales bitwise vs the host reference (kv_q8.hpp's rules);
7//   2. V: after fwht256, Q4_0 blocks bitwise vs the host reference (kv_q4.hpp's rules, PR #21);
8//   3. the composed gathers bitwise vs the host dequantization of those codes;
9//   4. qsa_decode_attn<3> + output fwht vs a host attention over the SAME dequantized K/V (fp32 math), and
10//      bounded against the fp32-true attention from the unquantized K/V.
11#define DPCT_PROFILING_ENABLED
12#include <sycl/sycl.hpp>
13#include <dpct/dpct.hpp>
14#include "strata/kernels/f16_bits.hpp"
15#include "strata/kernels/kv_q4.hpp"
16#include "strata/kernels/kv_q8.hpp"
17#include "strata/kernels/qsa.hpp"
18#include "strata/kernels/qsa_decode_attn.hpp"
19#include "strata/kernels/qsa_prompt_attn.hpp"
20
21#include <algorithm>
22#include <cmath>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <random>
27#include <vector>
28
29namespace k = strata::kernels;
30
31namespace {
32int g_fail = 0;
33void ck(dpct::err0 e, const char *w) {
34    /*
35    DPCT1009: SYCL reports errors using exceptions and does not use error
36    codes. Please replace the "get_error_string_dummy(...)" with a real
37    error-handling function.
38    */
39}
40template <typename T> T* dalloc(size_t n) {
41    T* p = nullptr;
42    ck(DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(
43                            n * sizeof(T) + 64, dpct::get_in_order_queue())),
44       "malloc");
45    ck(DPCT_CHECK_ERROR(
46           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(p, 0, n * sizeof(T) + 64).wait()),
47       "memset");
48    return p;
49}
50
51// kv_q4_parity.cpp's exact CPU references.
52void fwht256_host_reference(float* x) {
53    constexpr int n = 256;
54    for (int s = 1; s < n; s *= 2) {
55        for (int i = 0; i < n; i += 2 * s) {
56            for (int j = 0; j < s; ++j) {
57                const float u = x[i + j];
58                const float v = x[i + j + s];
59                x[i + j]     = u + v;
60                x[i + j + s] = u - v;
61            }
62        }
63    }
64    const float scale = 1.0f / 16.0f;
65    for (int i = 0; i < n; ++i) x[i] *= scale;
66}
67void quantize_block_q4_0_host(const float* x, k::block_q4_0& blk) {
68    float amax = 0.0f, max_val = 0.0f;
69    for (int i = 0; i < 32; ++i) {
70        const float v = x[i];
71        if (amax < std::fabs(v)) { amax = std::fabs(v); max_val = v; }
72    }
73    const float d = max_val / -8.0f;
74    const float id = d != 0.0f ? 1.0f / d : 0.0f;
75    blk.d = k::f16_from_f32(d);
76    for (int i = 0; i < 16; ++i) {
77        const int q0 = (int) (x[i] * id + 8.5f);
78        const int q1 = (int) (x[i + 16] * id + 8.5f);
79        const uint8_t xi0 = (uint8_t) std::min(15, std::max(0, q0));
80        const uint8_t xi1 = (uint8_t) std::min(15, std::max(0, q1));
81        blk.qs[i] = xi0 | (xi1 << 4);
82    }
83}
84}  // namespace
85
86int main() {
87    // SYCL port: qsa_prompt_attn's tensor-core (mma.sync PTX) kernel is not ported; on SYCL the prompt attention this
88    // test's last step checks exists as the XMX kernel (opt-in in the engine, where the FP32 fallback is faster).
89    // Test the kernel the port has, unless the caller chose (STRATA_PROMPT_ATTN_XMX=0 shows the refusal).
90    setenv("STRATA_PROMPT_ATTN_XMX", "1", 0);
91    std::printf("=== Running kv_hybrid_parity test ===\n");
92    k::QsaShapes s = k::qsa_real_shapes();
93    s.page_size = 64;
94    const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP;
95    const int QH = (int) s.n_head, PER = QH / H;   // query heads per KV head
96    const int pages = 24, cells = pages * P;   // n_chunks >= n_head: the batched merge overlaps queries below that
97    std::mt19937 rng(17);
98    std::normal_distribution<float> nd(0.0f, 1.0f);
99
100    std::vector<int32_t> table(pages);
101    for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages;
102    int32_t* d_table = dalloc<int32_t>(pages);
103    /*
104    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
105    in the original code the source host memory is pageable memory. If the
106    memory is not pageable, call wait() on event return by memcpy API to ensure
107    synchronization behavior.
108    */
109    ck(DPCT_CHECK_ERROR(
110           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_table, table.data(), pages * 4).wait()),
111       "table");
112
113    std::vector<float> K((size_t) cells * H * D), V((size_t) cells * H * D);
114    for (auto& x : K) x = nd(rng) * 0.5f;
115    for (auto& x : V) x = nd(rng) * 0.5f;
116
117    // ---- host reference: K in INT8 (kv_q8.hpp), rotated V in Q4_0 (kv_q4.hpp)
118    std::vector<int8_t> rk((size_t) cells * H * D);
119    std::vector<uint16_t> rk_s((size_t) cells * H * G);
120    for (int c = 0; c < cells; ++c)
121        for (int h = 0; h < H; ++h)
122            for (int g = 0; g < G; ++g) {
123                float amax = 0.0f;
124                for (int t = 0; t < k::KV_Q8_GROUP; ++t)
125                    amax = std::max(amax, std::fabs(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t]));
126                const uint16_t sb = k::f16_from_f32(amax / 127.0f);
127                const float sf = k::f32_from_f16(sb);
128                for (int t = 0; t < k::KV_Q8_GROUP; ++t) {
129                    int q = 0;
130                    if (sf > 0.0f) {
131                        q = (int) std::nearbyint(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] / sf);   // rn: ties to even, as the kernel
132                        q = std::max(-127, std::min(127, q));
133                    }
134                    rk[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] = (int8_t) q;
135                }
136                rk_s[((size_t) c * H + h) * G + g] = sb;
137            }
138    std::vector<float> Vrot((size_t) cells * H * D);
139    std::memcpy(Vrot.data(), V.data(), V.size() * 4);
140    for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vrot.data() + (size_t) c * D);
141    std::vector<k::block_q4_0> rv4((size_t) cells * H * (D / 32));
142    for (int c = 0; c < cells; ++c)
143        for (int h = 0; h < H; ++h)
144            for (int b = 0; b < D / 32; ++b)
145                quantize_block_q4_0_host(&Vrot[((size_t) c * H + h) * D + b * 32],
146                                         rv4[((size_t) c * H + h) * (D / 32) + b]);
147
148    // ---- device: one cell appended through the COMPOSED hybrid calls, then gathered
149    const int64_t q4_row = (int64_t) k::kv_q4_bytes_per_head(D);
150    int8_t* d_kq = dalloc<int8_t>((size_t) cells * H * D);
151    uint16_t* d_ks = dalloc<uint16_t>((size_t) cells * H * G);
152    uint8_t* d_v4 = dalloc<uint8_t>((size_t) cells * H * q4_row);
153    float *d_kcur = dalloc<float>((size_t) H * D), *d_vcur = dalloc<float>((size_t) H * D);
154    int32_t* d_step = dalloc<int32_t>(k::kStepCount);
155
156    int append_bad = 0, gather_bad = 0;
157    for (int c = 0; c < cells; ++c) {
158        ck(DPCT_CHECK_ERROR(
159               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
160                   .memcpy(d_kcur, &K[(size_t)c * H * D], (size_t)H * D * 4)
161                   .wait()),
162           "kcur");
163        ck(DPCT_CHECK_ERROR(
164               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
165                   .memcpy(d_vcur, &V[(size_t)c * H * D], (size_t)H * D * 4)
166                   .wait()),
167           "vcur");
168        int32_t step[k::kStepCount];
169        k::qsa_step_fill(step, c, s);
170        /*
171        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
172        assuming in the original code the source host memory is pageable memory.
173        If the memory is not pageable, call wait() on event return by memcpy API
174        to ensure synchronization behavior.
175        */
176        ck(DPCT_CHECK_ERROR(
177               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_step, step, sizeof step).wait()),
178           "step");
179        // exactly what qsa_layer's hybrid branch does
180        k::fwht256_inplace_cuda(d_vcur, H, nullptr);
181        k::kv_append_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_step, d_kcur, d_kcur, s, nullptr, nullptr);
182        k::kv_append_q4_step(d_v4, d_v4, d_table, d_step, d_vcur, d_vcur, s, nullptr, nullptr);
183        /*
184        DPCT1010: SYCL uses exceptions to report errors and does not use
185        the error codes. The cudaGetLastError function call was replaced with 0.
186        You need to rewrite this code.
187        */
188        ck(0 != 0 ? 0 : 0, "append");
189    }
190    ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
191       "append sync");
192
193    std::vector<int8_t> hk((size_t) cells * H * D);
194    std::vector<uint16_t> hks((size_t) cells * H * G);
195    std::vector<uint8_t> hv4((size_t) cells * H * q4_row);
196    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
197                            .memcpy(hk.data(), d_kq, hk.size())
198                            .wait()),
199       "kq");
200    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
201                            .memcpy(hks.data(), d_ks, hks.size() * 2)
202                            .wait()),
203       "ks");
204    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
205                            .memcpy(hv4.data(), d_v4, hv4.size())
206                            .wait()),
207       "v4");
208    // the pools are PHYSICAL (page, head, slot); the reference is by LOGICAL cell - compare through the table
209    const k::block_q4_0* hv4b = reinterpret_cast<const k::block_q4_0*>(hv4.data());
210    for (int c = 0; c < cells; ++c) {
211        const long long row = ((long long) table[c / P] * H);
212        for (int h = 0; h < H; ++h) {
213            const long long r = (row + h) * P + c % P;
214            for (int d = 0; d < D; ++d)
215                if (hk[(size_t) r * D + d] != rk[((size_t) c * H + h) * D + d]) ++append_bad;
216            for (int g = 0; g < G; ++g)
217                if (hks[(size_t) r * G + g] != rk_s[((size_t) c * H + h) * G + g]) ++append_bad;
218            for (int b = 0; b < D / 32; ++b) {
219                const k::block_q4_0& got = hv4b[(size_t) r * (D / 32) + b];
220                if (got.d != rv4[((size_t) c * H + h) * (D / 32) + b].d ||
221                    std::memcmp(got.qs, rv4[((size_t) c * H + h) * (D / 32) + b].qs, 16) != 0) ++append_bad;
222            }
223        }
224    }
225    std::printf("[1/3] composed appends: %s (%d bad values of %zu K / %zu V)\n",
226                append_bad == 0 ? "PASS" : "FAIL", append_bad, hk.size(), rv4.size());
227
228    // gather every cell (ids = all, ascending - the identity selection for width = cells)
229    std::vector<int32_t> ids(cells);
230    for (int i = 0; i < cells; ++i) ids[i] = i;
231    int32_t* d_ids = dalloc<int32_t>(cells);
232    /*
233    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
234    in the original code the source host memory is pageable memory. If the
235    memory is not pageable, call wait() on event return by memcpy API to ensure
236    synchronization behavior.
237    */
238    ck(DPCT_CHECK_ERROR(
239           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_ids, ids.data(), cells * 4).wait()),
240       "ids");
241    int32_t step[k::kStepCount];
242    k::qsa_step_fill(step, cells - 1, s);
243    step[k::kStepWidth] = cells;   // select everything
244    /*
245    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
246    in the original code the source host memory is pageable memory. If the
247    memory is not pageable, call wait() on event return by memcpy API to ensure
248    synchronization behavior.
249    */
250    ck(DPCT_CHECK_ERROR(
251           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_step, step, sizeof step).wait()),
252       "step2");
253    uint16_t *d_ksc = dalloc<uint16_t>((size_t) cells * H * D), *d_vsc = dalloc<uint16_t>((size_t) cells * H * D);
254    k::kv_gather_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_ids, d_step, cells, s, d_ksc, d_ksc, nullptr);
255    k::kv_gather_q4_step(d_v4, d_v4, d_table, d_ids, d_step, cells, s, d_vsc, d_vsc, nullptr);
256    ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
257       "gather sync");
258    std::vector<uint16_t> h_ksc((size_t) cells * H * D), h_vsc((size_t) cells * H * D);
259    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
260                            .memcpy(h_ksc.data(), d_ksc, h_ksc.size() * 2)
261                            .wait()),
262       "ksc");
263    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
264                            .memcpy(h_vsc.data(), d_vsc, h_vsc.size() * 2)
265                            .wait()),
266       "vsc");
267    for (int c = 0; c < cells; ++c)
268        for (int h = 0; h < H; ++h)
269            for (int d = 0; d < D; ++d) {
270                const float kref = k::f32_from_f16(k::f16_from_f32(
271                    (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP])));
272                if (k::f32_from_f16(h_ksc[((size_t) c * H + h) * D + d]) != kref) ++gather_bad;
273                const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32];
274                const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8);
275                const float vref = k::f32_from_f16(k::f16_from_f32((float) nib * k::f32_from_f16(b.d)));
276                if (k::f32_from_f16(h_vsc[((size_t) c * H + h) * D + d]) != vref) ++gather_bad;
277            }
278    std::printf("[2/3] composed gathers: %s (%d bad of %zu)\n",
279                gather_bad == 0 ? "PASS" : "FAIL", gather_bad, h_ksc.size());
280
281    // ---- attention: qsa_decode_attn KV_MODE 3 over the hybrid pools + output fwht, vs fp32 references
282    std::vector<float> q((size_t) QH * D);
283    for (auto& x : q) x = nd(rng);
284    float* d_q = dalloc<float>(q.size());
285    /*
286    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
287    in the original code the source host memory is pageable memory. If the
288    memory is not pageable, call wait() on event return by memcpy API to ensure
289    synchronization behavior.
290    */
291    ck(DPCT_CHECK_ERROR(
292           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_q, q.data(), q.size() * 4).wait()),
293       "q");
294    k::QsaAttnPools pools;
295    pools.k_q = d_kq; pools.k_scale = d_ks; pools.v_q4 = d_v4; pools.page_table = d_table;
296    float* d_scr = dalloc<float>(k::qsa_decode_attn_scratch_floats(cells, s) + 16);
297    float* d_attn = dalloc<float>((size_t) QH * D);
298    k::qsa_decode_attn_step(d_q, pools, d_ids, d_step, cells, s, d_scr, d_attn, nullptr);
299    k::fwht256_inplace_cuda(d_attn, QH, nullptr);   // the engine's inverse rotation of the output
300    ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
301       "attn sync");
302    std::vector<float> h_attn((size_t) QH * D);
303    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
304                            .memcpy(h_attn.data(), d_attn, h_attn.size() * 4)
305                            .wait()),
306       "attn");
307
308    // reference A: attention over the SAME dequantized K/V (isolates the kernel; fp32 host math)
309    // reference B: attention over the TRUE unquantized K/V (bounds the format's error)
310    auto host_attn = [&](const std::vector<float>& Keq, const std::vector<float>& Veq, std::vector<float>& out) {
311        out.assign((size_t) QH * D, 0.0f);
312        for (int h = 0; h < QH; ++h) {
313            const int kvh = h / PER;
314            std::vector<float> sc(cells);
315            float m = -1e30f;
316            for (int c = 0; c < cells; ++c) {
317                float d_ = 0.0f;
318                for (int t = 0; t < D; ++t)
319                    d_ += q[(size_t) h * D + t] * Keq[((size_t) c * H + kvh) * D + t];
320                sc[c] = d_ / std::sqrt((float) D);
321                m = std::max(m, sc[c]);
322            }
323            float l = 0.0f;
324            for (int c = 0; c < cells; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; }
325            for (int c = 0; c < cells; ++c)
326                for (int t = 0; t < D; ++t) out[(size_t) h * D + t] += sc[c] / l * Veq[((size_t) c * H + kvh) * D + t];
327        }
328    };
329    std::vector<float> Kdq((size_t) cells * H * D), Vdq((size_t) cells * H * D);
330    for (int c = 0; c < cells; ++c)
331        for (int h = 0; h < H; ++h)
332            for (int d = 0; d < D; ++d) {
333                Kdq[((size_t) c * H + h) * D + d] =
334                    (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP]);
335                const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32];
336                const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8);
337                Vdq[((size_t) c * H + h) * D + d] = (float) nib * k::f32_from_f16(b.d);
338            }
339    // un-rotate the dequantized V (the kernel returns the output in the UNROTATED domain)
340    std::vector<float> Vdq_un(Vdq.size());
341    std::memcpy(Vdq_un.data(), Vdq.data(), Vdq.size() * 4);
342    for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vdq_un.data() + (size_t) c * D);
343
344    // ---- batched form with TWO queries and per-query step arrays (the verify.cpp window's exact call)
345    {
346        const int nq = 2;
347        std::vector<float> q2((size_t) nq * QH * D);
348        for (auto& x : q2) x = nd(rng);
349        float* d_q2 = dalloc<float>(q2.size());
350        /*
351        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
352        assuming in the original code the source host memory is pageable memory.
353        If the memory is not pageable, call wait() on event return by memcpy API
354        to ensure synchronization behavior.
355        */
356        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_q2, q2.data(),
357                                                              q2.size() * 4).wait()),
358           "q2");
359        // the batched kernel indexes ids[z * cap + ...]: one FULL selection per query
360        std::vector<int32_t> ids2((size_t) nq * cells);
361        for (int i = 0; i < nq; ++i) for (int c = 0; c < cells; ++c) ids2[(size_t) i * cells + c] = c;
362        int32_t* d_ids2 = dalloc<int32_t>((size_t) nq * cells);
363        /*
364        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
365        assuming in the original code the source host memory is pageable memory.
366        If the memory is not pageable, call wait() on event return by memcpy API
367        to ensure synchronization behavior.
368        */
369        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
370               d_ids2, ids2.data(), ids2.size() * 4).wait()),
371           "ids2");
372        int32_t* d_steps2 = dalloc<int32_t>(nq * k::kStepCount);
373        for (int i = 0; i < nq; ++i) {
374            int32_t st2[k::kStepCount];
375            k::qsa_step_fill(st2, cells - 1 - i, s);
376            st2[k::kStepWidth] = cells - i;   // slightly different widths, as verify's windows have
377            /*
378            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
379            assuming in the original code the source host memory is pageable
380            memory. If the memory is not pageable, call wait() on event return
381            by memcpy API to ensure synchronization behavior.
382            */
383            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
384                   d_steps2 + i * k::kStepCount, st2, sizeof st2).wait()),
385               "steps2");
386        }
387        float* d_scr2 = dalloc<float>(k::qsa_decode_attn_scratch_floats(cells, s) * nq + 64);
388        float* d_at2 = dalloc<float>((size_t) nq * QH * D);
389        k::qsa_decode_attn_batch(d_q2, pools, d_ids2, d_steps2, cells, s, d_scr2, d_at2, nq, nullptr);
390        k::fwht256_inplace_cuda(d_at2, (int64_t) nq * QH, nullptr);
391        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
392           "attn2 sync");
393        std::vector<float> h_at2((size_t) nq * QH * D);
394        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
395                                .memcpy(h_at2.data(), d_at2, h_at2.size() * 4)
396                                .wait()),
397           "at2");
398        double max_b = 0.0;
399        double per_q[2] = {0.0, 0.0};
400        for (int i = 0; i < nq; ++i)
401            for (int h = 0; h < QH; ++h) {
402                // reference over the cells this query's width selects (ids are ascending: the first width)
403                const int w = cells - i;
404                std::vector<float> sc(w);
405                float m = -1e30f;
406                for (int c = 0; c < w; ++c) {
407                    float d_ = 0.0f;
408                    for (int t = 0; t < D; ++t)
409                        d_ += q2[((size_t) i * QH + h) * D + t] * Kdq[((size_t) c * H + h / PER) * D + t];
410                    sc[c] = d_ / std::sqrt((float) D);
411                    m = std::max(m, sc[c]);
412                }
413                float l = 0.0f;
414                for (int c = 0; c < w; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; }
415                for (int d = 0; d < D; ++d) {
416                    float acc = 0.0f;
417                    for (int c = 0; c < w; ++c)
418                        acc += sc[c] / l * Vdq_un[((size_t) c * H + h / PER) * D + d];   // dim d only
419                    const double e = (double) std::fabs(h_at2[((size_t) i * QH + h) * D + d] - acc);
420                    max_b = std::max(max_b, e);
421                    per_q[i] = std::max(per_q[i], e);
422                }
423            }
424        const bool bok = max_b < 5e-3;
425        std::printf("       (per-query max: q0 %.2e, q1 %.2e)\n", per_q[0], per_q[1]);
426        std::printf("[4/4] mode-3 BATCHED attention (verify's form): %s (vs dequant ref %.2e)\n",
427                    bok ? "PASS" : "FAIL", max_b);
428        if (!bok) g_fail = 1;
429    }
430
431    std::vector<float> ref_deq, ref_true;
432    host_attn(Kdq, Vdq_un, ref_deq);
433    host_attn(K, V, ref_true);
434    double max_deq = 0.0, max_true = 0.0;
435    for (size_t i = 0; i < h_attn.size(); ++i) {
436        max_deq = std::max(max_deq, (double) std::fabs(h_attn[i] - ref_deq[i]));
437        max_true = std::max(max_true, (double) std::fabs(h_attn[i] - ref_true[i]));
438    }
439    // The tensor-core prompt path (qsa_prompt_attn, 0.1.22+) takes hybrid pools as KV_MODE 3: INT8 K, and V
440    // dequantized from its q4_0 blocks to fp16 at gather. Its summation order differs from the old kernel's
441    // (accuracy-level, not bitwise - qsa_prompt_attn.hpp says the same of its int8 mode), so: tolerance check
442    // against the SAME dequant reference, output un-rotated exactly as prefill.cpp does.
443    {
444        float* d_at4 = dalloc<float>((size_t) QH * D);
445        const bool took = k::qsa_prompt_attn_batch(d_q, pools, d_ids, d_step, cells, s, d_at4, 1, nullptr);
446        if (!took) {
447#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
448            // AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runs
449            std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n");
450#else
451            std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n");
452            g_fail = 1;
453#endif
454        } else {
455            k::fwht256_inplace_cuda(d_at4, QH, nullptr);
456            ck(DPCT_CHECK_ERROR(
457                   dpct::get_current_device().queues_wait_and_throw()),
458               "at4 sync");
459            std::vector<float> h_at4((size_t) QH * D);
460            ck(DPCT_CHECK_ERROR(
461                   (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
462                       .memcpy(h_at4.data(), d_at4, h_at4.size() * 4)
463                       .wait()),
464               "at4");
465            double max_p = 0.0;
466            for (size_t i = 0; i < h_at4.size(); ++i)
467                max_p = std::max(max_p, (double) std::fabs(h_at4[i] - ref_deq[i]));
468            const bool pok = max_p < 1e-2;
469            std::printf("[5/5] qsa_prompt_attn mode 3 (tensor cores): %s (vs dequant ref %.2e)\n",
470                        pok ? "PASS" : "FAIL", max_p);
471            if (!pok) g_fail = 1;
472        }
473    }
474
475    const bool attn_ok = max_deq < 5e-3;   // fp32 kernel math vs fp64-ish host accumulation
476    std::printf("[3/3] mode-3 attention + output fwht: %s (vs dequant ref %.2e, vs true fp32 %.2e)\n",
477                attn_ok ? "PASS" : "FAIL", max_deq, max_true);
478
479    const bool ok = append_bad == 0 && gather_bad == 0 && attn_ok && g_fail == 0;
480    std::printf("=== kv_hybrid_parity: %s ===\n", ok ? "ALL PASS" : "FAILED");
481    return ok ? 0 : 1;
482}