Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

perf(gfx906): add guarded opt-in query LDS swizzle for batched QSA

Andrey Bash94bf9e58703b
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ac4895992..a02445b00 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1608,3 +1608,8 @@ if(STRATA_HIP_GFX906)
endif()
set_source_files_properties(${_strata_cu} PROPERTIES LANGUAGE HIP)
endif()
+
+if(STRATA_HIP_GFX906)
+ add_executable(gfx906_qsa_query_swizzle_probe bench/gfx906_qsa_query_swizzle_probe.cpp)
+ target_link_libraries(gfx906_qsa_query_swizzle_probe PRIVATE strata_kernels ${_strata_gpu_runtime_target})
+endif()
diff --git a/bench/gfx906_qsa_query_swizzle_probe.cpp b/bench/gfx906_qsa_query_swizzle_probe.cpp
new file mode 100644
index 000000000..da4d8bf04
--- /dev/null
+++ b/bench/gfx906_qsa_query_swizzle_probe.cpp
@@ -0,0 +1,284 @@
+// Standalone HIP INT8 QSA query-LDS-swizzle component probe.
+// Adapted from the cell-probability probe; input generation and full-byte dump are unchanged.
+// Build/link in the project with strata_kernels + hip::host (or its HIP runtime target).
+// Usage: gfx906_qsa_query_swizzle_probe [nq=32] [ctx=65536] [reps=20] [output.bin] [--masked-pages]
+// Output path may instead be supplied by STRATA_QSA_PROBE_OUT. It is required.
+// Run candidate environment settings in SEPARATE processes: the dispatcher caches them.
+// No prompt-attention entry point, architecture skip, model loading, or repository writes.
+#include "strata/kernels/qsa.hpp"
+#include "strata/kernels/qsa_decode_attn.hpp"
+
+#include <hip/hip_runtime.h>
+
+#include <algorithm>
+#include <cerrno>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <exception>
+#include <limits>
+#include <numeric>
+#include <vector>
+
+namespace k = strata::kernels;
+namespace {
+constexpr int64_t kBatch = 32;
+constexpr size_t kGuard = 64;
+constexpr uint64_t kSeed = 0x7161736150524f42ull;
+
+[[noreturn]] void fail(const char* why) {
+ std::fprintf(stderr, "qsa_query_swizzle_probe: %s\n", why);
+ std::exit(2);
+}
+void ck(hipError_t e, const char* what) {
+ if (e != hipSuccess) {
+ std::fprintf(stderr, "%s: %s\n", what, hipGetErrorString(e));
+ std::exit(2);
+ }
+}
+#define HIP_CHECK(x) ck((x), #x)
+
+// Fixed integer generator and exact binary fractions avoid library-dependent
+// normal distributions and never inspect the candidate environment setting.
+struct Rng {
+ uint64_t state = kSeed;
+ uint32_t next() {
+ state ^= state >> 12;
+ state ^= state << 25;
+ state ^= state >> 27;
+ return uint32_t((state * 2685821657736338717ull) >> 32);
+ }
+ size_t below(size_t n) { return size_t(next()) % n; }
+ template <class T> void shuffle(std::vector<T>& v) {
+ for (size_t n = v.size(); n > 1; --n) std::swap(v[n - 1], v[below(n)]);
+ }
+};
+
+template <class T> struct Device {
+ T* p = nullptr;
+ explicit Device(size_t n) { HIP_CHECK(hipMalloc(reinterpret_cast<void**>(&p), n * sizeof(T))); }
+ explicit Device(const std::vector<T>& v) : Device(v.size()) {
+ HIP_CHECK(hipMemcpy(p, v.data(), v.size() * sizeof(T), hipMemcpyHostToDevice));
+ }
+ ~Device() { if (p) (void) hipFree(p); }
+ Device(const Device&) = delete;
+ Device& operator=(const Device&) = delete;
+};
+
+uint64_t hash_bytes(uint64_t hash, const void* ptr, size_t bytes) {
+ const auto* p = static_cast<const unsigned char*>(ptr);
+ for (size_t i = 0; i < bytes; ++i) hash = (hash ^ p[i]) * 1099511628211ull;
+ return hash;
+}
+template <class T> void hash_vector(uint64_t& hash, const std::vector<T>& v) {
+ hash = hash_bytes(hash, v.data(), v.size() * sizeof(T));
+}
+int64_t positive(const char* text) {
+ errno = 0;
+ char* end = nullptr;
+ const long long n = std::strtoll(text, &end, 10);
+ if (errno || end == text || *end || n <= 0 || n > INT32_MAX)
+ fail("nq, ctx, and reps must be positive int32 values");
+ return int64_t(n);
+}
+const char* env(const char* name) {
+ const char* value = std::getenv(name);
+ return value ? value : "<unset>";
+}
+
+std::vector<float> read_checked(const Device<float>& storage, size_t count) {
+ std::vector<float> host(count + 2 * kGuard);
+ HIP_CHECK(hipMemcpy(host.data(), storage.p, host.size() * sizeof(float), hipMemcpyDeviceToHost));
+ for (size_t i = 0; i < host.size(); ++i) {
+ if (i >= kGuard && i < kGuard + count) {
+ if (!std::isfinite(host[i])) {
+ std::fprintf(stderr, "nonfinite or unwritten output at float %zu\n", i - kGuard);
+ fail("output check failed");
+ }
+ } else {
+ uint32_t bits;
+ std::memcpy(&bits, &host[i], sizeof(bits));
+ if (bits != UINT32_MAX) fail("output guard changed");
+ }
+ }
+ return std::vector<float>(host.begin() + kGuard, host.begin() + kGuard + count);
+}
+
+int run(int64_t nq, int64_t ctx, int reps, const char* output, bool masked) {
+ if (ctx < nq) fail("ctx must be >= nq (query positions are ctx-nq through ctx-1)");
+ const char* lane = std::getenv("STRATA_ATTN_LANECELL");
+ if (lane && lane[0] == '1') fail("unset STRATA_ATTN_LANECELL or set it to 0 for this probe");
+ static_assert(sizeof(float) == 4 && std::numeric_limits<float>::is_iec559,
+ "probe requires IEEE binary32 output");
+ const k::QsaShapes s = k::qsa_real_shapes();
+ // Match prefill.cpp: use the model's actual 4-cell page layout.
+ if (s.n_head != 24 || s.n_head_kv != 2 || s.head_dim != 256 || s.page_size != 4)
+ fail("unexpected model geometry");
+ const int64_t hd = s.head_dim, nh = s.n_head, nkvh = s.n_head_kv, ps = s.page_size;
+ const int64_t pages = (ctx + ps - 1) / ps, rows = pages * nkvh * ps;
+ const int64_t cap = k::qsa_selection_width(ctx, s);
+ const size_t count = size_t(nq) * size_t(nh * hd);
+ Rng rng;
+ std::vector<int8_t> kq(size_t(rows * hd)), vq(kq.size());
+ std::vector<uint16_t> ks(size_t(rows * (hd / 64))), vs(ks.size());
+ for (auto* v : {&kq, &vq})
+ for (auto& x : *v) x = int8_t(int(rng.next() % 255) - 127);
+ // Positive finite binary16 scales, directly encoded: [2^-8, 2^-5).
+ for (auto* v : {&ks, &vs})
+ for (auto& x : *v) x = uint16_t(0x1c00u + rng.next() % 0x0c00u);
+ std::vector<int32_t> table(size_t(pages), 0);
+ std::iota(table.begin(), table.end(), 0);
+ rng.shuffle(table);
+ const auto physical = table;
+ if (masked)
+ for (int64_t page = 1; page < pages; page += 3) table[size_t(page)] = -1;
+
+ // The decode kernel reads ids[c0+t] only for t<n_here, and returns before
+ // reading IDs for empty chunks. Unused row slots are nevertheless zeroed;
+ // a final 64-cell initialized guard also avoids an exact allocation end.
+ // cap remains the actual row stride; no per-row padding is passed as cap.
+ std::vector<int32_t> ids(size_t(nq * cap) + kGuard, 0);
+ std::vector<int32_t> steps(size_t(nq * k::kStepCount), 0);
+ std::vector<float> query(count);
+ for (auto& x : query) x = float(int(rng.next() % 4096) - 2048) * (1.0f / 1024.0f);
+ std::vector<int32_t> old_cells;
+ for (int64_t i = 0; i < nq; ++i) {
+ const int64_t pos = ctx - nq + i, nkv = pos + 1;
+ const int64_t width = k::qsa_selection_width(nkv, s);
+ k::qsa_step_fill(steps.data() + i * k::kStepCount, pos, s);
+ int32_t* sel = ids.data() + i * cap;
+ if (width == nkv) {
+ std::iota(sel, sel + width, 0);
+ } else {
+ // Same selection pattern as qsa_prompt_attn_parity: a recent
+ // 512-cell window plus a sorted older set drifting ~3% per query.
+ constexpr int64_t recent = 512;
+ const int64_t older = width - recent;
+ if (int64_t(old_cells.size()) != older) {
+ std::vector<int32_t> all(size_t(nkv - recent), 0);
+ std::iota(all.begin(), all.end(), 0);
+ rng.shuffle(all);
+ old_cells.assign(all.begin(), all.begin() + older);
+ } else {
+ for (int64_t r = 0; r < older / 32; ++r) {
+ const int32_t cell = int32_t(rng.below(size_t(nkv - recent)));
+ if (std::find(old_cells.begin(), old_cells.end(), cell) == old_cells.end())
+ old_cells[rng.below(size_t(older))] = cell;
+ }
+ }
+ std::copy(old_cells.begin(), old_cells.end(), sel);
+ std::iota(sel + older, sel + width, int32_t(nkv - recent));
+ std::sort(sel, sel + width);
+ }
+ bool valid_page = false;
+ for (int64_t c = 0; c < width; ++c) {
+ if (sel[c] < 0 || sel[c] >= nkv || (c && sel[c - 1] >= sel[c]))
+ fail("selection must be unique, sorted, and causal");
+ valid_page |= table[size_t(sel[c] / ps)] >= 0;
+ }
+ // Restore a selected logical page if necessary, never allow an
+ // all-masked query to make a vacuous zero-output equality check pass.
+ if (!valid_page) {
+ const size_t page = size_t(sel[0] / ps);
+ table[page] = physical[page];
+ }
+ }
+ size_t masked_selected = 0;
+ for (int64_t i = 0; i < nq; ++i)
+ for (int32_t c = 0; c < steps[size_t(i * k::kStepCount + k::kStepWidth)]; ++c)
+ masked_selected += table[size_t(ids[size_t(i * cap + c)] / ps)] < 0;
+ uint64_t input_hash = 14695981039346656037ull;
+ hash_vector(input_hash, kq); hash_vector(input_hash, vq);
+ hash_vector(input_hash, ks); hash_vector(input_hash, vs);
+ hash_vector(input_hash, table); hash_vector(input_hash, ids);
+ hash_vector(input_hash, steps); hash_vector(input_hash, query);
+
+ Device<int8_t> dk(kq), dv(vq);
+ Device<uint16_t> dks(ks), dvs(vs);
+ Device<int32_t> dtable(table), dids(ids), dsteps(steps);
+ Device<float> dq(query), dout(count + 2 * kGuard);
+ const uint64_t stride = k::qsa_decode_attn_scratch_floats(cap, s);
+ Device<float> scratch(size_t(std::min(kBatch, nq)) * size_t(stride));
+ k::QsaAttnPools pools;
+ pools.k_q = dk.p; pools.v_q = dv.p; pools.k_scale = dks.p; pools.v_scale = dvs.p;
+ pools.page_table = dtable.p;
+ HIP_CHECK(hipMemset(dout.p, 0xff, (count + 2 * kGuard) * sizeof(float)));
+ HIP_CHECK(hipMemset(scratch.p, 0xff, size_t(std::min(kBatch, nq)) * size_t(stride) * sizeof(float)));
+ auto launch = [&] {
+ for (int64_t t = 0; t < nq; t += kBatch)
+ k::qsa_decode_attn_batch(dq.p + t * nh * hd, pools, dids.p + t * cap,
+ dsteps.p + t * k::kStepCount, cap, s, scratch.p, dout.p + kGuard + t * nh * hd,
+ std::min(kBatch, nq - t), nullptr);
+ HIP_CHECK(hipGetLastError());
+ };
+ launch();
+ HIP_CHECK(hipDeviceSynchronize());
+ const auto first = read_checked(dout, count);
+ constexpr int warmups = 3;
+ for (int i = 0; i < warmups; ++i) launch();
+ HIP_CHECK(hipDeviceSynchronize());
+ hipEvent_t begin = nullptr, end = nullptr;
+ HIP_CHECK(hipEventCreate(&begin)); HIP_CHECK(hipEventCreate(&end));
+ std::vector<float> times(size_t(reps), 0.0f);
+ for (int i = 0; i < reps; ++i) {
+ // Excluded from event duration; the last timed invocation must also
+ // overwrite every logical output element instead of inheriting it.
+ HIP_CHECK(hipMemsetAsync(dout.p + kGuard, 0xff, count * sizeof(float), nullptr));
+ HIP_CHECK(hipEventRecord(begin, nullptr));
+ launch();
+ HIP_CHECK(hipEventRecord(end, nullptr));
+ HIP_CHECK(hipEventSynchronize(end));
+ HIP_CHECK(hipEventElapsedTime(&times[size_t(i)], begin, end));
+ }
+ const auto result = read_checked(dout, count);
+ if (std::memcmp(first.data(), result.data(), count * sizeof(float)) != 0)
+ fail("first and final invocation differ byte-for-byte within this process");
+ const uint64_t output_hash = hash_bytes(14695981039346656037ull, result.data(), count * sizeof(float));
+ std::FILE* file = std::fopen(output, "wb");
+ if (!file) fail("cannot open output file");
+ const size_t written = std::fwrite(result.data(), sizeof(float), count, file);
+ const int close_status = std::fclose(file);
+ if (written != count || close_status != 0) fail("cannot write complete output file");
+ std::sort(times.begin(), times.end());
+ const float median = reps % 2 ? times[size_t(reps / 2)]
+ : 0.5f * (times[size_t(reps / 2 - 1)] + times[size_t(reps / 2)]);
+ int device = 0;
+ hipDeviceProp_t prop{};
+ HIP_CHECK(hipGetDevice(&device)); HIP_CHECK(hipGetDeviceProperties(&prop, device));
+ std::printf("device=%s arch=%s nq=%lld ctx=%lld cap=%lld page_size=%lld batch=%lld reps=%d warmups=%d\n",
+ prop.name, prop.gcnArchName, (long long)nq, (long long)ctx, (long long)cap,
+ (long long)ps, (long long)kBatch, reps, warmups);
+ std::printf("QUERY_SWIZZLE=%s LANECELL=%s seed=%016llx masked_pages=%zu masked_selected=%zu\n",
+ env("STRATA_GFX906_ATTN_QUERY_SWIZZLE"), env("STRATA_ATTN_LANECELL"), (unsigned long long)kSeed,
+ size_t(std::count(table.begin(), table.end(), -1)), masked_selected);
+ std::printf("INPUT_FNV1A64=%016llx OUTPUT_FNV1A64=%016llx output_floats=%zu output_bytes=%zu\n",
+ (unsigned long long)input_hash, (unsigned long long)output_hash, count, count * sizeof(float));
+ std::printf("PASS finite_written_guards_and_repeat median_ms=%.6f min_ms=%.6f max_ms=%.6f us_per_query=%.6f output=%s\n",
+ median, times.front(), times.back(), double(median) * 1000.0 / double(nq), output);
+ HIP_CHECK(hipEventDestroy(begin)); HIP_CHECK(hipEventDestroy(end));
+ return 0;
+}
+} // namespace
+
+int main(int argc, char** argv) {
+ try {
+ std::vector<const char*> args;
+ bool masked = false;
+ for (int i = 1; i < argc; ++i) {
+ if (std::strcmp(argv[i], "--masked-pages") == 0) masked = true;
+ else args.push_back(argv[i]);
+ }
+ if (args.size() > 4) fail("usage: probe [nq] [ctx] [reps] [output.bin] [--masked-pages]");
+ const int64_t nq = args.size() > 0 ? positive(args[0]) : 32;
+ const int64_t ctx = args.size() > 1 ? positive(args[1]) : 65536;
+ const int reps = args.size() > 2 ? int(positive(args[2])) : 20;
+ const char* output = args.size() > 3 ? args[3] : std::getenv("STRATA_QSA_PROBE_OUT");
+ if (!output || !*output) fail("pass output.bin as fourth positional argument or set STRATA_QSA_PROBE_OUT");
+ return run(nq, ctx, reps, output, masked);
+ } catch (const std::exception& e) {
+ std::fprintf(stderr, "qsa_query_swizzle_probe: %s\n", e.what());
+ return 2;
+ }
+}
diff --git a/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md
new file mode 100644
index 000000000..38c5de499
--- /dev/null
+++ b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md
@@ -0,0 +1,104 @@
+# QSA query LDS swizzle qualification
+
+8 October 2026
+
+## Conclusion
+
+The opt-in gfx906 query-LDS swizzle improves the measured INT8 batched-QSA component by **14.646806%** on the final clean upstream patch. It preserves every output byte in the tested component cases. One isolated full-model comparison at 65,536 input tokens and 1,024 generated tokens measures **1.185195% higher prompt throughput** and **1.048564% lower request latency**, with all generated token IDs equal.
+
+These results support a narrowly scoped, default-off upstream proposal. They do not establish a general speedup across workloads, model-level equivalence beyond the tested pairs, or production readiness.
+
+## Change and dispatch scope
+
+The change permutes only the shared-memory query layout in `attn_chunk_kernel`: `q(d) = d XOR ((d >> 3) & 4)`. The scoring loads invert the permutation. The mapping is bijective and self-inverse over the 256 dimensions, preserves 16-byte load alignment and the 12 KiB query tile, and leaves the logical floating-point operands and operation order unchanged. Score reduction, softmax, value accumulation and merge code are unchanged.
+
+Enable with `STRATA_GFX906_ATTN_QUERY_SWIZZLE=1`; the default is off. The runtime guard requires the calling thread's current device to be exactly gfx906, allowing normal architecture-feature suffixes, with a 64-lane wavefront. It checks the current device on each eligible dispatch, caches properties per thread and last device ordinal, and fails closed on HIP errors.
+
+The opt-in applies to INT8 pools in `qsa_decode_attn_batch`, including PREFILL, VERIFY and MTP calls with `n_q=1`. A main model using k8v4 can still reach this path through its INT8 MTP drafter. `qsa_decode_attn_step`, other pool formats, lane-cell scoring and other GPU/default paths retain their existing dispatch.
+
+## Component evidence
+
+The final parity matrix covers both gfx906 GPUs, both the hardened experimental build and the clean upstream build, both flag states, and these three geometries:
+
+| Queries | Context | Page masking | Output bytes per run |
+|---:|---:|---|---:|
+| 1 | 4 | None | 24,576 |
+| 33 | 4,096 | Masked pages | 811,008 |
+| 32 | 65,536 | None | 786,432 |
+
+All **24 runs**, representing 12 on/off comparisons across the four build/device combinations, match raw output bytes for their geometry. The probe uses deterministic inputs, shuffled physical pages, finite/output-write checks and output canaries. These checks cover the tested inputs; they are not a general memory-safety proof. The source-extracted host guard test passes **31 mock-HIP checks**, including architecture rejection, device changes, API failures, recovery and independent thread caches.
+
+The final clean-build timing screen uses GPU 0, `n_q=32`, context 65,536, unmasked pages and separate A/B/B/A processes with 50 repetitions per run. A is flag off; B is flag on. Each value below is a run's measured median for the batched attention component, including chunk and merge.
+
+| Run | A1 | B1 | B2 | A2 |
+|---|---:|---:|---:|---:|
+| Median ms | 1.188960 | 1.036240 | 1.036560 | 1.187439 |
+
+Throughput gain is `(mean(A medians) / mean(B medians) - 1) × 100 = 14.646806%`. This is an A/B/B/A component screen, not a model benchmark or a confidence interval.
+
+The initial experimental component screen measured 14.791570%, below the predeclared 20% gate. That gate did **not** pass. An explicit cost-benefit exception allowed one bounded 64K/1,024-output model comparison because the layout change was small and the measured component benefit was stable. The final clean-build screen also remains below 20%.
+
+## Compiled kernel audit
+
+The compiled baseline and swizzled kernels retain 24 `ds_read_b128` query reads each. The resource comparison is:
+
+| Property | Baseline | Swizzled |
+|---|---:|---:|
+| Encoded static instructions | 1,000 | 1,005 |
+| VGPRs | 41 | 42 |
+| SGPRs | 42 | 42 |
+| Total LDS bytes | 15,872 | 15,872 |
+| Reported occupancy, waves per SIMD | 4 | 4 |
+| Scratch bytes | 0 | 0 |
+| SGPR / VGPR spills | 0 / 0 | 0 / 0 |
+
+An earlier instruction-count script included an ellipsis line and reported 1,001/1,006; the encoded-instruction counts above correct that error. The bank-layout analysis motivates the change, but measured speedup is not a direct hardware bank-conflict-counter measurement.
+
+Guard hardening preserves the entire disassembled device text, all 10 function symbols, addresses and machine encodings, and the emitted AMDGPU resource notes relative to the qualified experimental kernel. Only the input-object pathname was removed for comparison. HSACO file hashes differ; the differing bytes outside those inspected views have not been located, so no precise cause is claimed. This audit compares pre-hardening and hardened experimental builds; it does not assert whole-binary identity with rebased upstream main.
+
+## Isolated QSA full-model result
+
+Both arms use the same experimental HC + grouped-MMQ + PR #1525 dequantization stack; only the QSA query-swizzle flag changes. Fresh native processes use INT8 KV, no prompt reuse, a 65,536-token code prompt and 1,024 output tokens. Sampling is temperature 0, top-p 1, top-k 1, seed 12345. The candidate was run before the control.
+
+| Metric | QSA off | QSA on | Change |
+|---|---:|---:|---:|
+| Prompt throughput, tokens/s | 617.712871 | 625.033976 | +1.185195% |
+| Native prompt time, s | 106.0946 | 104.8519 | −1.171313% |
+| Request wall time, s | 126.382110 | 125.056913 | −1.048564% |
+| Generation throughput, tokens/s | 50.537205 | 50.748591 | +0.418279% |
+
+All 1,024 token IDs match; speculative accepted/offered counts also match at 648/872. This is one matched pair, recorded before final host-guard hardening. The later ISA audit establishes unchanged device code across that hardening; the fresh combined-stack tests below exercise the final hardened engine. The small generation-throughput movement is noise-scale and does not establish a generation improvement.
+
+## Combined stack result against the stable baseline
+
+These fresh comparisons measure the complete HC + grouped-MMQ + PR #1525 dequantization + QSA candidate against the stable engine. They cannot attribute the combined gain to QSA alone. The component and isolated/full-stack percentages must not be added.
+
+| Code prompt | Stable PP, tokens/s | Combined PP, tokens/s | PP change | Request latency change | TG change |
+|---|---:|---:|---:|---:|---:|
+| 4,096 tokens | 347.622402 | 368.640369 | +6.046206% | −2.343515% | +0.188068% |
+| 65,536 tokens | 597.968207 | 624.674728 | +4.466211% | −3.664980% | +0.376379% |
+
+Each context has one matched pair with 1,024 output tokens and all token IDs equal within the pair. These use the final hardened candidate engine. The 4K pair ran control then candidate; the 64K pair ran candidate then control. Generation changes are noise-scale. The stable service was restored after the tests; the candidate was not deployed to production.
+
+For all model tables, PP is the reported full prompt-token count divided by native prompt time; the last prompt token executes in the first decode window. TG is actual output count divided by native decode time. Request wall time is measured separately from model loading. No cross-quantization quality or equal-token claim is made.
+
+## Provenance and limits
+
+- Hardware scope: two gfx906 wave64 GPUs; the runtime reports AMD Radeon Pro VII. Results are specific to the tested hardware and pinned build stack.
+- Model: `Qwen3.8-Flash-Next-GSQ-RCO-abliterated-IQ3_XXS-Q2_0`, engine version 0.1.40, INT8 KV. The configured capacity is 204,800 tokens; the new QSA candidate was tested only at the prompt lengths reported above.
+- Experimental source HEAD: `f152172332693c933b8a3104ce193d8a4315c2b4`, plus campaign changes. It is a separate source scope from the clean PR.
+- Pinned llama.cpp revision: `3cf03257f219afbe7334045ff7c6a06ac68c627d`.
+- Clean upstream base: `fb58e0dbc8399662c0e47c76578c6e878b14f6cf`.
+- Final clean patch SHA-256: `9c81295b8cdf8354fe0e5bc6de36a547199becd1a8fc2a79daabf2b9da9548c6`.
+- Final clean probe SHA-256: `a5723bfd34720b690a4031a978ecdfd8c65a35a26cf4ba0471fa4e969570882d`.
+- Pre-hardening model-engine SHA-256 used for the isolated QSA pair: `1d9fb9de4e5f5d63fd30257e4077caafa46dde61b5c4d4ac045a3a0f63b78d42`.
+- Final hardened model-engine SHA-256: `3d2650fe62fdea24679ac90401eac505b541ccc47886e59885a639c438cb4c17`.
+- Stable model-engine SHA-256: `ce794788d64313236bbc24b47a3f8e06c841034afaf4e19a2fc5ffd84e337f14`.
+- Build image digest: `sha256:bccb7ee7e7a78274519db9a43ba63c34ddd2e74bb60f8764a8f50aaee1f2c646`. The clean probe uses Release, HIP gfx906, portable/native-expert settings, and grouped-MMQ build options disabled. No floating-point compiler-policy change is part of the QSA patch.
+- Compiler verified in that image: AMD Clang `23.0.0git`, ROCm llvm-project revision `46fcb339fb61119b337f973c7ca9e710a319fdd0`, patched revision `440716f8b87be9d8e20ed910e10e5b6d14d57cf6`. The ROCm distribution version is unrecorded because its version file is empty.
+
+The clean rebased PR has component and host-guard validation; the full-model comparisons belong to the experimental stack. No full-model run on rebased main, new 200K test, new API qualification, CI pass or production deployment is claimed. Earlier HC/MMQ 200K and API qualification does not qualify this new QSA candidate.
+
+The overlap review found no direct duplicate, but upstream PR #1402 introduces a third kernel-template argument `G`, conflicting with this patch's third boolean argument. The two changes require coordination before merging. PR #1535 concerns the separate top-k work.
+
+Evidence reviewed: final component/model/combined receipts, build receipts, the final clean patch, and the source/ISA and hardened-ISA audit records.
diff --git a/bench/results/2026-10-08-gfx906-qsa-query-swizzle/results.json b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/results.json
new file mode 100644
index 000000000..e3b84fa7a
--- /dev/null
+++ b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/results.json
@@ -0,0 +1,519 @@
+{
+ "component": {
+ "parity": [
+ {
+ "tag": "hardened-build-gpu0-nq1-ctx4-mask0-mode0",
+ "build": "hardened-build",
+ "gpu": 0,
+ "mode": 0,
+ "nq": 1,
+ "ctx": 4,
+ "masked": false,
+ "bytes": 24576,
+ "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f",
+ "median_ms": 0.03056
+ },
+ {
+ "tag": "hardened-build-gpu0-nq1-ctx4-mask0-mode1",
+ "build": "hardened-build",
+ "gpu": 0,
+ "mode": 1,
+ "nq": 1,
+ "ctx": 4,
+ "masked": false,
+ "bytes": 24576,
+ "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f",
+ "median_ms": 0.03056
+ },
+ {
+ "tag": "hardened-build-gpu0-nq33-ctx4096-mask1-mode0",
+ "build": "hardened-build",
+ "gpu": 0,
+ "mode": 0,
+ "nq": 33,
+ "ctx": 4096,
+ "masked": true,
+ "bytes": 811008,
+ "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8",
+ "median_ms": 1.02304
+ },
+ {
+ "tag": "hardened-build-gpu0-nq33-ctx4096-mask1-mode1",
+ "build": "hardened-build",
+ "gpu": 0,
+ "mode": 1,
+ "nq": 33,
+ "ctx": 4096,
+ "masked": true,
+ "bytes": 811008,
+ "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8",
+ "median_ms": 0.96928
+ },
+ {
+ "tag": "hardened-build-gpu0-nq32-ctx65536-mask0-mode0",
+ "build": "hardened-build",
+ "gpu": 0,
+ "mode": 0,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.188
+ },
+ {
+ "tag": "hardened-build-gpu0-nq32-ctx65536-mask0-mode1",
+ "build": "hardened-build",
+ "gpu": 0,
+ "mode": 1,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.03792
+ },
+ {
+ "tag": "hardened-build-gpu1-nq1-ctx4-mask0-mode0",
+ "build": "hardened-build",
+ "gpu": 1,
+ "mode": 0,
+ "nq": 1,
+ "ctx": 4,
+ "masked": false,
+ "bytes": 24576,
+ "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f",
+ "median_ms": 0.03088
+ },
+ {
+ "tag": "hardened-build-gpu1-nq1-ctx4-mask0-mode1",
+ "build": "hardened-build",
+ "gpu": 1,
+ "mode": 1,
+ "nq": 1,
+ "ctx": 4,
+ "masked": false,
+ "bytes": 24576,
+ "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f",
+ "median_ms": 0.03088
+ },
+ {
+ "tag": "hardened-build-gpu1-nq33-ctx4096-mask1-mode0",
+ "build": "hardened-build",
+ "gpu": 1,
+ "mode": 0,
+ "nq": 33,
+ "ctx": 4096,
+ "masked": true,
+ "bytes": 811008,
+ "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8",
+ "median_ms": 1.02272
+ },
+ {
+ "tag": "hardened-build-gpu1-nq33-ctx4096-mask1-mode1",
+ "build": "hardened-build",
+ "gpu": 1,
+ "mode": 1,
+ "nq": 33,
+ "ctx": 4096,
+ "masked": true,
+ "bytes": 811008,
+ "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8",
+ "median_ms": 0.96688
+ },
+ {
+ "tag": "hardened-build-gpu1-nq32-ctx65536-mask0-mode0",
+ "build": "hardened-build",
+ "gpu": 1,
+ "mode": 0,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.186721
+ },
+ {
+ "tag": "hardened-build-gpu1-nq32-ctx65536-mask0-mode1",
+ "build": "hardened-build",
+ "gpu": 1,
+ "mode": 1,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.03312
+ },
+ {
+ "tag": "clean-pr-build-gpu0-nq1-ctx4-mask0-mode0",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 0,
+ "nq": 1,
+ "ctx": 4,
+ "masked": false,
+ "bytes": 24576,
+ "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f",
+ "median_ms": 0.03056
+ },
+ {
+ "tag": "clean-pr-build-gpu0-nq1-ctx4-mask0-mode1",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 1,
+ "nq": 1,
+ "ctx": 4,
+ "masked": false,
+ "bytes": 24576,
+ "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f",
+ "median_ms": 0.03056
+ },
+ {
+ "tag": "clean-pr-build-gpu0-nq33-ctx4096-mask1-mode0",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 0,
+ "nq": 33,
+ "ctx": 4096,
+ "masked": true,
+ "bytes": 811008,
+ "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8",
+ "median_ms": 1.02512
+ },
+ {
+ "tag": "clean-pr-build-gpu0-nq33-ctx4096-mask1-mode1",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 1,
+ "nq": 33,
+ "ctx": 4096,
+ "masked": true,
+ "bytes": 811008,
+ "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8",
+ "median_ms": 0.97328
+ },
+ {
+ "tag": "clean-pr-build-gpu0-nq32-ctx65536-mask0-mode0",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 0,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.19024
+ },
+ {
+ "tag": "clean-pr-build-gpu0-nq32-ctx65536-mask0-mode1",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 1,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.03744
+ },
+ {
+ "tag": "clean-pr-build-gpu1-nq1-ctx4-mask0-mode0",
+ "build": "clean-pr-build",
+ "gpu": 1,
+ "mode": 0,
+ "nq": 1,
+ "ctx": 4,
+ "masked": false,
+ "bytes": 24576,
+ "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f",
+ "median_ms": 0.03056
+ },
+ {
+ "tag": "clean-pr-build-gpu1-nq1-ctx4-mask0-mode1",
+ "build": "clean-pr-build",
+ "gpu": 1,
+ "mode": 1,
+ "nq": 1,
+ "ctx": 4,
+ "masked": false,
+ "bytes": 24576,
+ "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f",
+ "median_ms": 0.03072
+ },
+ {
+ "tag": "clean-pr-build-gpu1-nq33-ctx4096-mask1-mode0",
+ "build": "clean-pr-build",
+ "gpu": 1,
+ "mode": 0,
+ "nq": 33,
+ "ctx": 4096,
+ "masked": true,
+ "bytes": 811008,
+ "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8",
+ "median_ms": 1.022081
+ },
+ {
+ "tag": "clean-pr-build-gpu1-nq33-ctx4096-mask1-mode1",
+ "build": "clean-pr-build",
+ "gpu": 1,
+ "mode": 1,
+ "nq": 33,
+ "ctx": 4096,
+ "masked": true,
+ "bytes": 811008,
+ "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8",
+ "median_ms": 0.96704
+ },
+ {
+ "tag": "clean-pr-build-gpu1-nq32-ctx65536-mask0-mode0",
+ "build": "clean-pr-build",
+ "gpu": 1,
+ "mode": 0,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.188481
+ },
+ {
+ "tag": "clean-pr-build-gpu1-nq32-ctx65536-mask0-mode1",
+ "build": "clean-pr-build",
+ "gpu": 1,
+ "mode": 1,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.0328
+ }
+ ],
+ "timing": [
+ {
+ "tag": "timing-A1",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 0,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.18896
+ },
+ {
+ "tag": "timing-B1",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 1,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.03624
+ },
+ {
+ "tag": "timing-B2",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 1,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.03656
+ },
+ {
+ "tag": "timing-A2",
+ "build": "clean-pr-build",
+ "gpu": 0,
+ "mode": 0,
+ "nq": 32,
+ "ctx": 65536,
+ "masked": false,
+ "bytes": 786432,
+ "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2",
+ "median_ms": 1.187439
+ }
+ ],
+ "component_throughput_gain_pct": 14.646806252412215,
+ "passed": true,
+ "production_restore": {
+ "passed": true
+ }
+ },
+ "model/summary.json": {
+ "results": [
+ {
+ "tag": "code65536-B1",
+ "passed": true,
+ "prompt_tokens": 65536,
+ "actual_outputs": 1024,
+ "PP": 625.033976494465,
+ "TG": 50.74859128055942,
+ "prompt_ms": 104851.9,
+ "decode_ms": 20177.9,
+ "request_wall_s": 125.05691278600716,
+ "accepted": 648,
+ "offered": 872,
+ "sampling": {
+ "temperature": 0,
+ "top_p": 1,
+ "top_k": 1,
+ "seed": 12345
+ },
+ "output_ids_sha256": "186fecea5448e82653f96f6d88abac69b05ad7665d375f6de5930952ed506b70"
+ },
+ {
+ "tag": "code65536-A1",
+ "passed": true,
+ "prompt_tokens": 65536,
+ "actual_outputs": 1024,
+ "PP": 617.7128713431221,
+ "TG": 50.537204562167176,
+ "prompt_ms": 106094.6,
+ "decode_ms": 20262.3,
+ "request_wall_s": 126.38210993001121,
+ "accepted": 648,
+ "offered": 872,
+ "sampling": {
+ "temperature": 0,
+ "top_p": 1,
+ "top_k": 1,
+ "seed": 12345
+ },
+ "output_ids_sha256": "186fecea5448e82653f96f6d88abac69b05ad7665d375f6de5930952ed506b70"
+ }
+ ],
+ "decision": {
+ "micro_20pct_gate_passed": false,
+ "exception": "bounded cost-benefit qualification of stable14.79pct exact component improvement with tiny layout change",
+ "PP_gain_pct": 1.1851954995570013,
+ "prompt_latency_reduction_pct": 1.1713131488313322,
+ "request_latency_reduction_pct": 1.0485638708974898,
+ "TG_change_pct": 0.41827940469523206,
+ "all1024_output_ids_equal": true,
+ "qualified_single_pair": true
+ },
+ "production_api_restored": true,
+ "finished_utc": "2026-10-08T22:23:53.765633+00:00"
+ },
+ "combined-final/summary.json": {
+ "results": [
+ {
+ "tag": "code4096-production",
+ "passed": true,
+ "prompt_tokens": 4096,
+ "actual_outputs": 1024,
+ "PP": 347.622401955376,
+ "TG": 55.877810943101764,
+ "prompt_ms": 11782.9,
+ "decode_ms": 18325.7,
+ "request_wall_s": 30.113095285007148,
+ "accepted": 684,
+ "offered": 855,
+ "sampling": {
+ "temperature": 0,
+ "top_p": 1,
+ "top_k": 1,
+ "seed": 12345
+ },
+ "output_ids_sha256": "0af681458e937914e536b7a5b78531d638fd9742da28a04e9c0c9443b0c57abd"
+ },
+ {
+ "tag": "code4096-combined",
+ "passed": true,
+ "prompt_tokens": 4096,
+ "actual_outputs": 1024,
+ "PP": 368.64036864036865,
+ "TG": 55.98289897382909,
+ "prompt_ms": 11111.1,
+ "decode_ms": 18291.3,
+ "request_wall_s": 29.407390481006587,
+ "accepted": 684,
+ "offered": 855,
+ "sampling": {
+ "temperature": 0,
+ "top_p": 1,
+ "top_k": 1,
+ "seed": 12345
+ },
+ "output_ids_sha256": "0af681458e937914e536b7a5b78531d638fd9742da28a04e9c0c9443b0c57abd"
+ },
+ {
+ "tag": "code65536-combined",
+ "passed": true,
+ "prompt_tokens": 65536,
+ "actual_outputs": 1024,
+ "PP": 624.6747280106604,
+ "TG": 50.71214912541352,
+ "prompt_ms": 104912.2,
+ "decode_ms": 20192.4,
+ "request_wall_s": 125.13095494700246,
+ "accepted": 648,
+ "offered": 872,
+ "sampling": {
+ "temperature": 0,
+ "top_p": 1,
+ "top_k": 1,
+ "seed": 12345
+ },
+ "output_ids_sha256": "186fecea5448e82653f96f6d88abac69b05ad7665d375f6de5930952ed506b70"
+ },
+ {
+ "tag": "code65536-production",
+ "passed": true,
+ "prompt_tokens": 65536,
+ "actual_outputs": 1024,
+ "PP": 597.9682073910243,
+ "TG": 50.52199482938959,
+ "prompt_ms": 109597.8,
+ "decode_ms": 20268.4,
+ "request_wall_s": 129.89145007400657,
+ "accepted": 648,
+ "offered": 872,
+ "sampling": {
+ "temperature": 0,
+ "top_p": 1,
+ "top_k": 1,
+ "seed": 12345
+ },
+ "output_ids_sha256": "186fecea5448e82653f96f6d88abac69b05ad7665d375f6de5930952ed506b70"
+ }
+ ],
+ "decision": {
+ "4096": {
+ "PP_gain_pct": 6.0462060462060485,
+ "request_latency_reduction_pct": 2.343514664704427,
+ "TG_change_pct": 0.1880675512402119,
+ "all1024_output_ids_equal": true
+ },
+ "65536": {
+ "PP_gain_pct": 4.4662107934063,
+ "request_latency_reduction_pct": 3.664979584331207,
+ "TG_change_pct": 0.3763792317901693,
+ "all1024_output_ids_equal": true
+ }
+ },
+ "production_api_restored": true,
+ "finished_utc": "2026-10-08T22:52:40.940327+00:00"
+ },
+ "hardened-build/build.json": {
+ "exit_code": 0,
+ "patch_sha256": "2c9e370619a8bc24304c161857c77d5b453a58549c6326e4d1ee7888d8c20344",
+ "binaries": {
+ "strata": "3d2650fe62fdea24679ac90401eac505b541ccc47886e59885a639c438cb4c17",
+ "gfx906_qsa_query_swizzle_probe": "9ddc0446706a1f6f4f283869196eecc36176ae7819f28661fcdf681fd5cbe528"
+ }
+ },
+ "clean-pr-build/build.json": {
+ "exit_code": 0,
+ "upstream_base": "fb58e0dbc8399662c0e47c76578c6e878b14f6cf",
+ "source_sha256": "db957776b99f66d9f695832adc5302631a97036d717d2bd9bd7d4ff5ff154f85",
+ "probe_sha256": "a5723bfd34720b690a4031a978ecdfd8c65a35a26cf4ba0471fa4e969570882d"
+ }
+}
diff --git a/bench/test_gfx906_qsa_query_swizzle_guard.py b/bench/test_gfx906_qsa_query_swizzle_guard.py
new file mode 100644
index 000000000..813ce7843
--- /dev/null
+++ b/bench/test_gfx906_qsa_query_swizzle_guard.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python3
+"""Compile the production host guard with mock HIP calls; no GPU or HIP SDK needed.
+
+The helper and dispatch expression are extracted from their single production
+definition so this test cannot accidentally validate a copied implementation.
+Run from any directory with Python 3 and a C++17 compiler (CXX, default c++).
+"""
+import os
+from pathlib import Path
+import re
+import shlex
+import subprocess
+import tempfile
+
+
+ROOT = Path(__file__).resolve().parents[1]
+source = (ROOT / "src/kernels/cuda/qsa_decode_attn.cu").read_text()
+start = source.index("bool query_swizzle_gfx906_device() {")
+end = source.index("\n}\n", start) + 3
+guard = source[start:end]
+dispatch = re.search(r"^ const bool use_query_swizzle = .*;", source, re.MULTILINE)
+if dispatch is None or "if (use_query_swizzle) {" not in source:
+ raise RuntimeError("production query-swizzle dispatch changed; update the test")
+
+prefix = r'''
+#include "strata/kernels/gfx_arch.hpp"
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <initializer_list>
+#include <thread>
+using strata::kernels::gfx_arch_is;
+constexpr int hipSuccess = 0;
+struct hipDeviceProp_t { char gcnArchName[64]; int warpSize; };
+struct Mock {
+ int device = 0, device_calls = 0, property_calls = 0, clear_calls = 0;
+ bool fail_device = false, fail_properties = false;
+};
+thread_local Mock mock;
+int hipGetDevice(int* device) {
+ ++mock.device_calls;
+ *device = mock.device;
+ return mock.fail_device ? 1 : hipSuccess;
+}
+int hipGetDeviceProperties(hipDeviceProp_t* prop, int device) {
+ ++mock.property_calls;
+ if (mock.fail_properties) return 1;
+ static const char* names[] = {
+ "gfx906", "gfx908", "gfx906:sramecc-:xnack-", "gfx9060",
+ "gfx906", "", "gfx906-other", "gfx906"
+ };
+ if (device < 0 || device >= 8) return 1;
+ std::strcpy(prop->gcnArchName, names[device]);
+ prop->warpSize = device == 4 ? 32 : 64;
+ return hipSuccess;
+}
+int hipGetLastError() { ++mock.clear_calls; return hipSuccess; }
+int checks = 0;
+void require(bool condition, const char* message) {
+ ++checks;
+ if (!condition) { std::fprintf(stderr, "FAIL: %s\n", message); std::exit(1); }
+}
+'''
+
+tests = r'''
+int main() {
+ require(!active(false, false, 1), "opt-in off");
+ require(!active(true, true, 1), "lane-cell wins");
+ for (int mode : {0, 2, 3}) require(!active(true, false, mode), "other pool modes");
+ require(mock.device_calls == 0 && mock.property_calls == 0, "inactive dispatch makes no HIP queries");
+ require(active(true, false, 1), "gfx906 wave64 accepted");
+ require(active(true, false, 1), "same-device cache accepted");
+ require(mock.device_calls == 2 && mock.property_calls == 1, "ordinal checked each time, properties cached");
+ mock.device = 1;
+ require(!active(true, false, 1), "gfx908 rejected after device switch");
+ require(!active(true, false, 1) && mock.property_calls == 2, "unsupported result cached");
+ mock.device = 0;
+ require(active(true, false, 1) && mock.property_calls == 3, "switch back refreshes properties");
+ mock.device = 2;
+ require(active(true, false, 1), "exact gfx906 name with feature suffix accepted");
+ for (int device : {3, 4, 5, 6}) {
+ mock.device = device;
+ require(!active(true, false, 1), "lookalike name, wave32, or empty name rejected");
+ }
+ mock.device = 0;
+ require(active(true, false, 1), "restore supported device");
+ int properties = mock.property_calls, clears = mock.clear_calls;
+ mock.fail_device = true;
+ require(!active(true, false, 1), "current-device API error fails closed");
+ require(mock.property_calls == properties && mock.clear_calls == clears + 1, "device error avoids property query");
+ mock.fail_device = false;
+ require(active(true, false, 1) && mock.property_calls == properties + 1, "device error invalidates cache");
+ mock.device = -1;
+ require(!active(true, false, 1), "negative ordinal fails closed");
+ mock.device = 0;
+ require(active(true, false, 1) && mock.property_calls == properties + 2, "invalid ordinal invalidates cache");
+ mock.device = 7;
+ mock.fail_properties = true;
+ properties = mock.property_calls;
+ clears = mock.clear_calls;
+ require(!active(true, false, 1), "property API error cannot reuse another device's cached approval");
+ require(!active(true, false, 1), "repeated property failure stays closed");
+ require(mock.property_calls == properties + 2 && mock.clear_calls == clears + 2, "property errors remain retryable");
+ mock.fail_properties = false;
+ require(active(true, false, 1) && mock.property_calls == properties + 3, "property query recovers");
+ mock.device = 0;
+ require(active(true, false, 1), "parent thread caches ordinal zero");
+ std::thread other([] {
+ require(active(true, false, 1) && mock.property_calls == 1, "new thread independently queries the same ordinal");
+ mock.device = 1;
+ require(!active(true, false, 1), "other thread caches an unsupported ordinal");
+ });
+ other.join();
+ properties = mock.property_calls;
+ require(active(true, false, 1) && mock.property_calls == properties, "other thread cannot replace parent cache");
+ std::printf("PASS query-swizzle host guard: %d checks (mock HIP, no GPU)\n", checks);
+}
+'''
+
+program = prefix + guard + "\nbool active(bool query_swizzle, bool lane_cell, int kv_mode) {\n"
+program += dispatch.group(0) + "\n return use_query_swizzle;\n}\n" + tests
+with tempfile.TemporaryDirectory(prefix="qsa-swizzle-guard-") as directory:
+ cpp = Path(directory) / "guard_test.cpp"
+ binary = Path(directory) / "guard_test"
+ cpp.write_text(program)
+ command = shlex.split(os.environ.get("CXX", "c++"))
+ command += ["-std=c++17", "-Wall", "-Wextra", "-Werror", "-pthread", "-I", str(ROOT / "include"),
+ str(cpp), "-o", str(binary)]
+ subprocess.run(command, check=True)
+ subprocess.run([str(binary)], check=True)
diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu
index 2df091366..fa7896087 100644
--- a/src/kernels/cuda/qsa_decode_attn.cu
+++ b/src/kernels/cuda/qsa_decode_attn.cu
@@ -2,6 +2,9 @@
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/kv_q8.hpp"
#include "strata/kernels/kv_q4.hpp"
+#if defined(STRATA_HIP_GFX906)
+#include "strata/kernels/gfx_arch.hpp"
+#endif
#include <cuda_fp16.h>
#include <cuda_runtime.h>
@@ -81,7 +84,7 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo
} else load8_q4(p, value, row, d0, out);
}
-template <int KV_MODE, bool LANE_CELL = false>
+template <int KV_MODE, bool LANE_CELL = false, bool QUERY_SWIZZLE = false>
__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ step, int n_kv_heads,
@@ -108,7 +111,15 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
return;
}
- for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
+ // Opt-in gfx906 batched attention: a bijective XOR of query dimensions in LDS only. It swaps the two
+ // float4 halves of lanes whose bit 2 is set, retaining 16-byte alignment and the 12 KB tile.
+ // The scoring reads undo this permutation; FP operands and operation order are unchanged.
+ static_assert(!QUERY_SWIZZLE || !LANE_CELL, "query swizzle is for warp scoring only");
+ for (int i = t; i < G * HD; i += THREADS) {
+ const int d = i % HD;
+ const int sd = QUERY_SWIZZLE ? (d ^ ((d >> 3) & 4)) : d;
+ sq[i / HD][sd] = q[(size_t) (kvh * G) * HD + i];
+ }
if (t < CHUNK) {
long long r = -1;
if (t < n_here) {
@@ -166,8 +177,9 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
#pragma unroll
for (int h = 0; h < G; ++h) {
- const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
- const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
+ const int qflip = QUERY_SWIZZLE ? (lane & 4) : 0;
+ const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + qflip]);
+ const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + (qflip ^ 4)]);
float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
s = warp_sum(s);
@@ -482,6 +494,34 @@ __global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict_
attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f;
}
+#if defined(STRATA_HIP_GFX906)
+// The compat backend can target other architectures. Check the calling thread's current device,
+// caching only its last ordinal so a layer split or another thread cannot reuse the wrong answer.
+bool query_swizzle_gfx906_device() {
+ static thread_local int cached_device = -1;
+ static thread_local bool cached_supported = false;
+ int device = -1;
+ if (hipGetDevice(&device) != hipSuccess || device < 0) {
+ cached_device = -1;
+ cached_supported = false;
+ (void) hipGetLastError();
+ return false;
+ }
+ if (device != cached_device) {
+ cached_device = -1;
+ cached_supported = false;
+ hipDeviceProp_t prop{};
+ if (hipGetDeviceProperties(&prop, device) != hipSuccess) {
+ (void) hipGetLastError();
+ return false;
+ }
+ cached_supported = gfx_arch_is(prop.gcnArchName, "gfx906") && prop.warpSize == 64;
+ cached_device = device;
+ }
+ return cached_supported;
+}
+#endif
+
#if defined(STRATA_ATTN_PRE75_BUILT)
// CUDA: the current device is below sm_75; HIP: it is gfx103x (per device: a layer split can mix cards).
// STRATA_ATTN_PRE75=0 turns PR #540's kernel off (A/B); on HIP =1 also runs it on another wave32 card.
@@ -546,6 +586,19 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3
cudaStream_t st = (cudaStream_t) stream;
// S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions)
static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();
+#if defined(STRATA_HIP_GFX906)
+ static const bool query_swizzle = [] {
+ const char* v = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE"); return v && v[0] == '1';
+ }();
+ const bool use_query_swizzle = query_swizzle && !lane_cell && kv_mode == 1 && query_swizzle_gfx906_device();
+ static const bool query_swizzle_trace = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE_TRACE") != nullptr;
+ static thread_local bool query_swizzle_said = false;
+ if (query_swizzle_trace && !query_swizzle_said) {
+ query_swizzle_said = true;
+ std::fprintf(stderr, "strata attn-query-swizzle: active=%d nq=%lld cap=%lld kv_mode=%d lane_cell=%d\n",
+ use_query_swizzle, (long long) n_q, (long long) cap, kv_mode, lane_cell);
+ }
+#endif
#define STRATA_ATTN_LC(M) attn_chunk_kernel<M, true><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride)
if (lane_cell) {
if (kv_mode == 3) STRATA_ATTN_LC(3);
@@ -554,6 +607,15 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3
else STRATA_ATTN_LC(0);
} else
#undef STRATA_ATTN_LC
+#if defined(STRATA_HIP_GFX906)
+ // Opt-in INT8 batched attention: prefill, verification and MTP (including n_q=1).
+ // Other pool formats and lane-cell scoring keep their paths; qsa_decode_attn_step is unchanged.
+ // A k8v4 model's MTP drafter uses INT8 pools and can therefore take this path.
+ if (use_query_swizzle) {
+ attn_chunk_kernel<1, false, true><<<grid, THREADS, 0, st>>>(q, pools, ids, steps,
+ (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
+ } else
+#endif
if (kv_mode == 3)
STRATA_ATTN_CHUNK(3)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);