okami.mom/strata

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

Niko1221Merge f-142b-amd into f-142bb930bc8b

main
13.4 KiB284 linesraw
1// Standalone HIP INT8 QSA query-LDS-swizzle component probe.
2// Adapted from the cell-probability probe; input generation and full-byte dump are unchanged.
3// Build/link in the project with strata_kernels + hip::host (or its HIP runtime target).
4// Usage: gfx906_qsa_query_swizzle_probe [nq=32] [ctx=65536] [reps=20] [output.bin] [--masked-pages]
5// Output path may instead be supplied by STRATA_QSA_PROBE_OUT. It is required.
6// Run candidate environment settings in SEPARATE processes: the dispatcher caches them.
7// No prompt-attention entry point, architecture skip, model loading, or repository writes.
8#include "strata/kernels/qsa.hpp"
9#include "strata/kernels/qsa_decode_attn.hpp"
10
11#include <hip/hip_runtime.h>
12
13#include <algorithm>
14#include <cerrno>
15#include <cmath>
16#include <cstdint>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <exception>
21#include <limits>
22#include <numeric>
23#include <vector>
24
25namespace k = strata::kernels;
26namespace {
27constexpr int64_t kBatch = 32;
28constexpr size_t kGuard = 64;
29constexpr uint64_t kSeed = 0x7161736150524f42ull;
30
31[[noreturn]] void fail(const char* why) {
32    std::fprintf(stderr, "qsa_query_swizzle_probe: %s\n", why);
33    std::exit(2);
34}
35void ck(hipError_t e, const char* what) {
36    if (e != hipSuccess) {
37        std::fprintf(stderr, "%s: %s\n", what, hipGetErrorString(e));
38        std::exit(2);
39    }
40}
41#define HIP_CHECK(x) ck((x), #x)
42
43// Fixed integer generator and exact binary fractions avoid library-dependent
44// normal distributions and never inspect the candidate environment setting.
45struct Rng {
46    uint64_t state = kSeed;
47    uint32_t next() {
48        state ^= state >> 12;
49        state ^= state << 25;
50        state ^= state >> 27;
51        return uint32_t((state * 2685821657736338717ull) >> 32);
52    }
53    size_t below(size_t n) { return size_t(next()) % n; }
54    template <class T> void shuffle(std::vector<T>& v) {
55        for (size_t n = v.size(); n > 1; --n) std::swap(v[n - 1], v[below(n)]);
56    }
57};
58
59template <class T> struct Device {
60    T* p = nullptr;
61    explicit Device(size_t n) { HIP_CHECK(hipMalloc(reinterpret_cast<void**>(&p), n * sizeof(T))); }
62    explicit Device(const std::vector<T>& v) : Device(v.size()) {
63        HIP_CHECK(hipMemcpy(p, v.data(), v.size() * sizeof(T), hipMemcpyHostToDevice));
64    }
65    ~Device() { if (p) (void) hipFree(p); }
66    Device(const Device&) = delete;
67    Device& operator=(const Device&) = delete;
68};
69
70uint64_t hash_bytes(uint64_t hash, const void* ptr, size_t bytes) {
71    const auto* p = static_cast<const unsigned char*>(ptr);
72    for (size_t i = 0; i < bytes; ++i) hash = (hash ^ p[i]) * 1099511628211ull;
73    return hash;
74}
75template <class T> void hash_vector(uint64_t& hash, const std::vector<T>& v) {
76    hash = hash_bytes(hash, v.data(), v.size() * sizeof(T));
77}
78int64_t positive(const char* text) {
79    errno = 0;
80    char* end = nullptr;
81    const long long n = std::strtoll(text, &end, 10);
82    if (errno || end == text || *end || n <= 0 || n > INT32_MAX)
83        fail("nq, ctx, and reps must be positive int32 values");
84    return int64_t(n);
85}
86const char* env(const char* name) {
87    const char* value = std::getenv(name);
88    return value ? value : "<unset>";
89}
90
91std::vector<float> read_checked(const Device<float>& storage, size_t count) {
92    std::vector<float> host(count + 2 * kGuard);
93    HIP_CHECK(hipMemcpy(host.data(), storage.p, host.size() * sizeof(float), hipMemcpyDeviceToHost));
94    for (size_t i = 0; i < host.size(); ++i) {
95        if (i >= kGuard && i < kGuard + count) {
96            if (!std::isfinite(host[i])) {
97                std::fprintf(stderr, "nonfinite or unwritten output at float %zu\n", i - kGuard);
98                fail("output check failed");
99            }
100        } else {
101            uint32_t bits;
102            std::memcpy(&bits, &host[i], sizeof(bits));
103            if (bits != UINT32_MAX) fail("output guard changed");
104        }
105    }
106    return std::vector<float>(host.begin() + kGuard, host.begin() + kGuard + count);
107}
108
109int run(int64_t nq, int64_t ctx, int reps, const char* output, bool masked) {
110    if (ctx < nq) fail("ctx must be >= nq (query positions are ctx-nq through ctx-1)");
111    const char* lane = std::getenv("STRATA_ATTN_LANECELL");
112    if (lane && lane[0] == '1') fail("unset STRATA_ATTN_LANECELL or set it to 0 for this probe");
113    static_assert(sizeof(float) == 4 && std::numeric_limits<float>::is_iec559,
114                  "probe requires IEEE binary32 output");
115    const k::QsaShapes s = k::qsa_real_shapes();
116    // Match prefill.cpp: use the model's actual 4-cell page layout.
117    if (s.n_head != 24 || s.n_head_kv != 2 || s.head_dim != 256 || s.page_size != 4)
118        fail("unexpected model geometry");
119    const int64_t hd = s.head_dim, nh = s.n_head, nkvh = s.n_head_kv, ps = s.page_size;
120    const int64_t pages = (ctx + ps - 1) / ps, rows = pages * nkvh * ps;
121    const int64_t cap = k::qsa_selection_width(ctx, s);
122    const size_t count = size_t(nq) * size_t(nh * hd);
123    Rng rng;
124    std::vector<int8_t> kq(size_t(rows * hd)), vq(kq.size());
125    std::vector<uint16_t> ks(size_t(rows * (hd / 64))), vs(ks.size());
126    for (auto* v : {&kq, &vq})
127        for (auto& x : *v) x = int8_t(int(rng.next() % 255) - 127);
128    // Positive finite binary16 scales, directly encoded: [2^-8, 2^-5).
129    for (auto* v : {&ks, &vs})
130        for (auto& x : *v) x = uint16_t(0x1c00u + rng.next() % 0x0c00u);
131    std::vector<int32_t> table(size_t(pages), 0);
132    std::iota(table.begin(), table.end(), 0);
133    rng.shuffle(table);
134    const auto physical = table;
135    if (masked)
136        for (int64_t page = 1; page < pages; page += 3) table[size_t(page)] = -1;
137
138    // The decode kernel reads ids[c0+t] only for t<n_here, and returns before
139    // reading IDs for empty chunks. Unused row slots are nevertheless zeroed;
140    // a final 64-cell initialized guard also avoids an exact allocation end.
141    // cap remains the actual row stride; no per-row padding is passed as cap.
142    std::vector<int32_t> ids(size_t(nq * cap) + kGuard, 0);
143    std::vector<int32_t> steps(size_t(nq * k::kStepCount), 0);
144    std::vector<float> query(count);
145    for (auto& x : query) x = float(int(rng.next() % 4096) - 2048) * (1.0f / 1024.0f);
146    std::vector<int32_t> old_cells;
147    for (int64_t i = 0; i < nq; ++i) {
148        const int64_t pos = ctx - nq + i, nkv = pos + 1;
149        const int64_t width = k::qsa_selection_width(nkv, s);
150        k::qsa_step_fill(steps.data() + i * k::kStepCount, pos, s);
151        int32_t* sel = ids.data() + i * cap;
152        if (width == nkv) {
153            std::iota(sel, sel + width, 0);
154        } else {
155            // Same selection pattern as qsa_prompt_attn_parity: a recent
156            // 512-cell window plus a sorted older set drifting ~3% per query.
157            constexpr int64_t recent = 512;
158            const int64_t older = width - recent;
159            if (int64_t(old_cells.size()) != older) {
160                std::vector<int32_t> all(size_t(nkv - recent), 0);
161                std::iota(all.begin(), all.end(), 0);
162                rng.shuffle(all);
163                old_cells.assign(all.begin(), all.begin() + older);
164            } else {
165                for (int64_t r = 0; r < older / 32; ++r) {
166                    const int32_t cell = int32_t(rng.below(size_t(nkv - recent)));
167                    if (std::find(old_cells.begin(), old_cells.end(), cell) == old_cells.end())
168                        old_cells[rng.below(size_t(older))] = cell;
169                }
170            }
171            std::copy(old_cells.begin(), old_cells.end(), sel);
172            std::iota(sel + older, sel + width, int32_t(nkv - recent));
173            std::sort(sel, sel + width);
174        }
175        bool valid_page = false;
176        for (int64_t c = 0; c < width; ++c) {
177            if (sel[c] < 0 || sel[c] >= nkv || (c && sel[c - 1] >= sel[c]))
178                fail("selection must be unique, sorted, and causal");
179            valid_page |= table[size_t(sel[c] / ps)] >= 0;
180        }
181        // Restore a selected logical page if necessary, never allow an
182        // all-masked query to make a vacuous zero-output equality check pass.
183        if (!valid_page) {
184            const size_t page = size_t(sel[0] / ps);
185            table[page] = physical[page];
186        }
187    }
188    size_t masked_selected = 0;
189    for (int64_t i = 0; i < nq; ++i)
190        for (int32_t c = 0; c < steps[size_t(i * k::kStepCount + k::kStepWidth)]; ++c)
191            masked_selected += table[size_t(ids[size_t(i * cap + c)] / ps)] < 0;
192    uint64_t input_hash = 14695981039346656037ull;
193    hash_vector(input_hash, kq); hash_vector(input_hash, vq);
194    hash_vector(input_hash, ks); hash_vector(input_hash, vs);
195    hash_vector(input_hash, table); hash_vector(input_hash, ids);
196    hash_vector(input_hash, steps); hash_vector(input_hash, query);
197
198    Device<int8_t> dk(kq), dv(vq);
199    Device<uint16_t> dks(ks), dvs(vs);
200    Device<int32_t> dtable(table), dids(ids), dsteps(steps);
201    Device<float> dq(query), dout(count + 2 * kGuard);
202    const uint64_t stride = k::qsa_decode_attn_scratch_floats(cap, s);
203    Device<float> scratch(size_t(std::min(kBatch, nq)) * size_t(stride));
204    k::QsaAttnPools pools;
205    pools.k_q = dk.p; pools.v_q = dv.p; pools.k_scale = dks.p; pools.v_scale = dvs.p;
206    pools.page_table = dtable.p;
207    HIP_CHECK(hipMemset(dout.p, 0xff, (count + 2 * kGuard) * sizeof(float)));
208    HIP_CHECK(hipMemset(scratch.p, 0xff, size_t(std::min(kBatch, nq)) * size_t(stride) * sizeof(float)));
209    auto launch = [&] {
210        for (int64_t t = 0; t < nq; t += kBatch)
211            k::qsa_decode_attn_batch(dq.p + t * nh * hd, pools, dids.p + t * cap,
212                dsteps.p + t * k::kStepCount, cap, s, scratch.p, dout.p + kGuard + t * nh * hd,
213                std::min(kBatch, nq - t), nullptr);
214        HIP_CHECK(hipGetLastError());
215    };
216    launch();
217    HIP_CHECK(hipDeviceSynchronize());
218    const auto first = read_checked(dout, count);
219    constexpr int warmups = 3;
220    for (int i = 0; i < warmups; ++i) launch();
221    HIP_CHECK(hipDeviceSynchronize());
222    hipEvent_t begin = nullptr, end = nullptr;
223    HIP_CHECK(hipEventCreate(&begin)); HIP_CHECK(hipEventCreate(&end));
224    std::vector<float> times(size_t(reps), 0.0f);
225    for (int i = 0; i < reps; ++i) {
226        // Excluded from event duration; the last timed invocation must also
227        // overwrite every logical output element instead of inheriting it.
228        HIP_CHECK(hipMemsetAsync(dout.p + kGuard, 0xff, count * sizeof(float), nullptr));
229        HIP_CHECK(hipEventRecord(begin, nullptr));
230        launch();
231        HIP_CHECK(hipEventRecord(end, nullptr));
232        HIP_CHECK(hipEventSynchronize(end));
233        HIP_CHECK(hipEventElapsedTime(&times[size_t(i)], begin, end));
234    }
235    const auto result = read_checked(dout, count);
236    if (std::memcmp(first.data(), result.data(), count * sizeof(float)) != 0)
237        fail("first and final invocation differ byte-for-byte within this process");
238    const uint64_t output_hash = hash_bytes(14695981039346656037ull, result.data(), count * sizeof(float));
239    std::FILE* file = std::fopen(output, "wb");
240    if (!file) fail("cannot open output file");
241    const size_t written = std::fwrite(result.data(), sizeof(float), count, file);
242    const int close_status = std::fclose(file);
243    if (written != count || close_status != 0) fail("cannot write complete output file");
244    std::sort(times.begin(), times.end());
245    const float median = reps % 2 ? times[size_t(reps / 2)]
246        : 0.5f * (times[size_t(reps / 2 - 1)] + times[size_t(reps / 2)]);
247    int device = 0;
248    hipDeviceProp_t prop{};
249    HIP_CHECK(hipGetDevice(&device)); HIP_CHECK(hipGetDeviceProperties(&prop, device));
250    std::printf("device=%s arch=%s nq=%lld ctx=%lld cap=%lld page_size=%lld batch=%lld reps=%d warmups=%d\n",
251        prop.name, prop.gcnArchName, (long long)nq, (long long)ctx, (long long)cap,
252        (long long)ps, (long long)kBatch, reps, warmups);
253    std::printf("QUERY_SWIZZLE=%s LANECELL=%s seed=%016llx masked_pages=%zu masked_selected=%zu\n",
254        env("STRATA_GFX906_ATTN_QUERY_SWIZZLE"), env("STRATA_ATTN_LANECELL"), (unsigned long long)kSeed,
255        size_t(std::count(table.begin(), table.end(), -1)), masked_selected);
256    std::printf("INPUT_FNV1A64=%016llx OUTPUT_FNV1A64=%016llx output_floats=%zu output_bytes=%zu\n",
257        (unsigned long long)input_hash, (unsigned long long)output_hash, count, count * sizeof(float));
258    std::printf("PASS finite_written_guards_and_repeat median_ms=%.6f min_ms=%.6f max_ms=%.6f us_per_query=%.6f output=%s\n",
259        median, times.front(), times.back(), double(median) * 1000.0 / double(nq), output);
260    HIP_CHECK(hipEventDestroy(begin)); HIP_CHECK(hipEventDestroy(end));
261    return 0;
262}
263}  // namespace
264
265int main(int argc, char** argv) {
266    try {
267        std::vector<const char*> args;
268        bool masked = false;
269        for (int i = 1; i < argc; ++i) {
270            if (std::strcmp(argv[i], "--masked-pages") == 0) masked = true;
271            else args.push_back(argv[i]);
272        }
273        if (args.size() > 4) fail("usage: probe [nq] [ctx] [reps] [output.bin] [--masked-pages]");
274        const int64_t nq = args.size() > 0 ? positive(args[0]) : 32;
275        const int64_t ctx = args.size() > 1 ? positive(args[1]) : 65536;
276        const int reps = args.size() > 2 ? int(positive(args[2])) : 20;
277        const char* output = args.size() > 3 ? args[3] : std::getenv("STRATA_QSA_PROBE_OUT");
278        if (!output || !*output) fail("pass output.bin as fourth positional argument or set STRATA_QSA_PROBE_OUT");
279        return run(nq, ctx, reps, output, masked);
280    } catch (const std::exception& e) {
281        std::fprintf(stderr, "qsa_query_swizzle_probe: %s\n", e.what());
282        return 2;
283    }
284}