Merge f-151-amd (d9070189c) into f-split-int2

Conflicts with 148-amd's gfx12 WMMA default resolved: STRATA_HIP_WMMA unset = gfx12 on every call (148-amd), 0 = off, 1 = forced (also gfx11), auto = gfx12 with n_q >= STRATA_HIP_WMMA_MIN_Q; failed launch falls back to the FP32 kernel; the 96-slot ring follows the same state; the opt-in hint is gone.
This commit is contained in:
Niko1221 committed 2026-10-18 09:34:20 +02:00
commit 58f81f20e3
13 files changed
+593 -158

No files matched your search

+4
View File
@@ -817,6 +817,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
add_test(NAME hip_prefill_hcd_exact_parity COMMAND hip_prefill_hcd_exact_parity)
set_tests_properties(hip_prefill_hcd_exact_parity PROPERTIES SKIP_RETURN_CODE 77)
list(APPEND _strata_hip_tests hip_prefill_hcd_exact_parity)
# the HC write-back kernel timed at the prompt path's shapes with an output checksum (not a ctest; STRATA_GRW_V picks a variant)
add_executable(hip_prefill_gr_write_bench tests/hip/prefill_gr_write_bench.cpp)
target_link_libraries(hip_prefill_gr_write_bench PRIVATE strata_prefill strata_hip_runtime)
# S6: the AMD fast router against the portable kernel, bitwise
add_executable(hip_router_fast tests/hip/router_fast.cpp)
target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime)
@@ -960,6 +963,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_include_directories(iq_multi_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(iq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME iq_multi_parity COMMAND iq_multi_parity)
set_tests_properties(iq_multi_parity PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1") # the Q4_K / Q5_K / Q8_0 Split path against the old kernels
# the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise (GPU,
# synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906)
if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906)
+20
View File
@@ -440,6 +440,26 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39
(default 156 and 156), reasoning 25/30 (24 and 26), agent 6/6, needles at 32K and 125K x three depths 6/6, CJK 8/8, tool calls 5/5. Prompt speed,
interleaved pairs on a quiet R9700, Q2_0 32 GB: see the 148-amd table below. The first-token KL against the FP16 prompt path cannot rank it (0.0296 against 0.0280 for the old
kernel, a paired difference of +0.0016 +- 0.0026): on a 2-bit pack any change of the prompt numerics, even `--prefill 4096`, moves the first token by about 0.025.
- `STRATA_HIP_WMMA=auto`: the same kernel, chosen per call: on a gfx12 card with int8 KV and a prompt batch of
`STRATA_HIP_WMMA_MIN_Q` (64) or more queries it runs the matrix-core kernel, everything else the FP32 one (`=1` forces it
on every call and on gfx11, `=0` keeps the FP32 kernel; unset is the gfx12 default above: the matrix-core kernel on every call). A launch error switches the matrix-core
kernel off for the rest of the process and the FP32 kernel runs (before, the engine exited). Kernel timing on an R9700
(`hip_prompt_attn_wmma`, context 1.5K-32K, 64-2,048 queries): 6.9-8.4x the FP32 kernel at every shape, error against FP64
3e-6 of the output scale (FP32: 2e-6). Engine, Q2_0 pack, 6 interleaved pairs, equal slots, fixed flags
(`--pcie-frac 0 --adapt-every 0`, `STRATA_PREFILL_CPU_SHARE=0`, `STRATA_ROUTE_TAIL_SKIP=0`): 20K prompt x1.46 (`=1`) /
x1.54 (`auto`), 4K x1.33 / x1.34 (6/6 pairs; the noise arm of that run read +6.4-6.9%, so read them as +40-50% and
+30%); the 8-token answers were the default's in every run.
- The first prompt after a start pays two one-time hipBLAS library loads (the first BF16 product 1.2 s, the first FP16
product 1.0 s on an R9700 with the gfx120X wheel's hipBLASLt 1.2.0; `STRATA_COLD_TRACE=1` times the first 80 dense
projections to show them). The engine now runs one tiny BF16 and one tiny FP16 product on a thread of its own while the
expert arena loads, so the first request does not carry them (`STRATA_PREFILL_WARM=0` turns it off; the outputs go to
scratch buffers, nothing changes; start-up time is the same, the arena load takes longer than the thread). First
721-token prompt after the 33-token warm request, 5 interleaved pairs: 154 -> 673 tok/s. The next 4K prompt reads
~1,090 tok/s either way (the "cold" first-prompt numbers above are about this).
- Ship status of `tools/hip/gfx1201-hipblaslt-*.txt`: the gfx120X wheel's hipBLASLt is 1.2.0 (version number 100200); the
tables here are 100202 and 100500, so the engine says "version mismatch ... using hipBLASEx" and runs plain hipBLAS. A
table tuned on the R9700 for 100200 (32 rows, `tune_hipblaslt`) measured within noise end to end (20K prompt x1.035 vs
a noise arm x1.031), so none is shipped: the dense projections are ~10% of a 20K prompt here.
- The prompt path's QSA top-k picks its kernel by the blocks a query actually has, not the cache's capacity (#337,
bsorensen110): the same ids, on by default with AMD (NVIDIA keeps its capacity rule: there the 64K prompts read
1-3% slower with it). `STRATA_SELECT_WMMA=1` (opt-in, gfx12) adds #337's
+8
View File
@@ -340,6 +340,14 @@ move on a Threadripper PRO 3975WX + R9700 (14.5 ms, +0.4%, 5 pairs); no case rea
reach, and the expert cache holds the rest, giving slots back as the context grows. It needs one GPU, an expert
profile, the whole K/V in VRAM (no KV streaming) and every expert in RAM (not the resident low-RAM mode); otherwise,
and with `--batch`, `--vram-elastic` or `--peer-device`, the engine says so and stays off.
On HIP (ROCm 6+) it runs through hipMemAddressReserve / hipMemCreate / hipMemMap (2 MiB chunks; the card must report
virtual memory management, `STRATA_HIP_VMM=0` turns it off); until then every AMD card printed "--kv-grow is off".
Radeon AI PRO R9700 with `--vram-reserve-mib 17084` (a 16 GB card), Q2_0 pack, `--max-context 196608`, 5 interleaved pairs:
expert-cache slots 6,213 -> 7,968 and decode 96.3 -> 98.5 tok/s (x1.023, 5/5; the noise arm read x0.999); at
`--max-context 262144` the default engine finds no VRAM left for the cache on that budget and does not start, `--kv-grow`
starts with 7,877 slots (94.4 tok/s). Prompts of 20K and 60K tokens through the growing K/V read as fast as without it
(x1.002, x1.001) and gave identical answers. At contexts up to 128K the K/V is small and nothing changes; it pays on cards of
about 24 GB or less with contexts of 128K and more.
- `--host-core last` (or `STRATA_HOST_CORE=last`, Windows): the host thread runs on the last physical core and the
workers take the first. Windows sends a GPU's interrupts to the first core, where a host spinning on the GPU's flags
waits for them (`--host-core first` is the default; the startup log names the cores). It leaves a hybrid CPU as it
+4
View File
@@ -117,6 +117,10 @@ helped (~360 MB at 3.3K tokens). The rows it computes round like a different MMQ
bit-identical to the default's (it is repeatable: same prompt, same output), which is why it is **opt-in**:
`STRATA_PREFILL_HELP=1` turns it on. Native packs on the MMQ prompt path only (not with the fused prompt kernels,
`STRATA_PF_FUSED=1`, nor with `--peer-device`). With it on, `STRATA_PREFILL_HELP_FRAC=f` fixes the share.
On two Radeon AI PRO R9700 (each limited to 16 GB with `--vram-reserve-mib 17084`, Q2_0 pack, layer split auto, 5 interleaved pairs,
noise arm within 0.2%), `STRATA_PREFILL_HELP=1` gave prompt tok/s without -> with: 700 tokens 638 -> 672 (x1.053, 5/5), 1.5K 839 -> 809
(x0.964), 3K 1,105 -> 929 (x0.840), 6K 1,284 -> 1,211 (x0.943): the PCIe 4.0 x16 links of this box (28.4 GB/s each) make the share lose
from 1.5K tokens up, so it stays off (`STRATA_PREFILL_HELP_FRAC` was not tuned for it).
The engine flags behind it: `--layer-split K1[,K2..]|auto` and `--split-device D1[,D2..]` (the later stages'
devices; default the next visible ones). `--layer-split K --split-device 0` runs both stages on one card sharing
@@ -43,5 +43,8 @@ bool qsa_decode_attn_split(const float* q, const QsaAttnPools& pools, const int3
void* stream);
/// Tests: the int8-KV kernel on INT8 tensor cores (1), v2 (0), or as STRATA_PROMPT_ATTN_IMMA says (-1).
void qsa_prompt_attn_set_imma(int on);
/// HIP: STRATA_HIP_WMMA asks for the matrix-core prompt attention (=1 or =auto) and this device is a gfx11 / gfx12 matrix-core part
/// that has not switched it off after a failed launch. The prompt path's 96-slot expert ring follows it. False off HIP.
bool qsa_prompt_attn_matrix_cores_requested();
} // namespace strata::kernels
+6
View File
@@ -45,6 +45,12 @@ struct PrefillStats {
namespace strata::core { class MtpDrafter; }
namespace strata::prefill {
/// HIP: one tiny BF16 and one tiny FP16 product on a private handle, so the first prompt does not pay hipBLAS's one-time
/// library loads (about 2.5 s on an R9700); once per device, later calls wait for the first and return. Safe to call from a
/// thread before the expert arena loads. STRATA_PREFILL_WARM=0 makes it a no-op. Nothing on CUDA / SYCL.
void warm_gemm_libraries(int device);
class Prefill {
public:
/// E-9: the draft layer's K/V for prompt cells [cell0, cell0 + n) from their final residual rows `R_rows`
+148 -1
View File
@@ -151,7 +151,153 @@ VmmChunk VmmRange::unmap(int64_t i) {
} // namespace strata::core
#else // HIP: no virtual memory here; the elastic K/V stays off
#else // not CUDA
// HIP (ROCm 6+): the same elastic range through hipMemAddressReserve / hipMemCreate / hipMemMap / hipMemSetAccess. Available
// only where the device reports virtual memory management support (STRATA_HIP_VMM=0 turns it off): --kv-grow stays off
// otherwise, as before. Everything else (Metal, gfx906, ROCm older than 6): no virtual memory, the elastic K/V stays off.
#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
#include <hip/hip_runtime.h>
#include <hip/hip_version.h>
#include <cstdio>
#include <cstdlib>
#include <mutex>
#endif
#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && defined(HIP_VERSION_MAJOR) && HIP_VERSION_MAJOR >= 6
namespace strata::core {
namespace {
struct Api {
bool ok = false;
uint64_t gran = 0;
int dev = -1;
};
void fail(const char* what, hipError_t e) {
static int n = 0;
if (n++ < 8) std::fprintf(stderr, "strata: HIP virtual memory: %s failed: %s\n", what, hipGetErrorString(e));
(void) hipGetLastError();
}
hipMemAllocationProp alloc_prop(int dev) {
hipMemAllocationProp p{};
p.type = hipMemAllocationTypePinned;
p.requestedHandleType = hipMemHandleTypeNone;
p.location.type = hipMemLocationTypeDevice;
p.location.id = dev;
return p;
}
const Api& api() {
static Api& a = *new Api; // never destroyed: the K/V pools and the cache release their chunks from static destructors
static std::once_flag once;
std::call_once(once, [] {
const char* off = std::getenv("STRATA_HIP_VMM");
if (off != nullptr && off[0] == '0') return;
if (hipGetDevice(&a.dev) != hipSuccess) { (void) hipGetLastError(); return; }
int vmm = 0;
if (hipDeviceGetAttribute(&vmm, hipDeviceAttributeVirtualMemoryManagementSupported, a.dev) != hipSuccess || !vmm) {
(void) hipGetLastError();
return;
}
const hipMemAllocationProp prop = alloc_prop(a.dev);
size_t g = 0;
if (hipMemGetAllocationGranularity(&g, &prop, hipMemAllocationGranularityMinimum) != hipSuccess || g == 0) {
(void) hipGetLastError();
return;
}
// gfx1201 reports a 4 KiB minimum granularity; the elastic range works in 2 MiB chunks like CUDA's (any multiple of the minimum)
const uint64_t want = 2ull << 20;
a.gran = g >= want ? g : (want + g - 1) / g * g;
a.ok = true;
});
return a;
}
} // namespace
bool vmm_available() { return api().ok; }
uint64_t vmm_granularity() { return api().ok ? api().gran : 0; }
VmmChunk vmm_chunk_new() {
const Api& a = api();
if (!a.ok) return 0;
const hipMemAllocationProp prop = alloc_prop(a.dev);
hipMemGenericAllocationHandle_t h = nullptr;
if (const hipError_t e = hipMemCreate(&h, (size_t) a.gran, &prop, 0); e != hipSuccess) { fail("hipMemCreate", e); return 0; }
return (VmmChunk) (uintptr_t) h;
}
void vmm_chunk_free(VmmChunk h) {
if (h != 0 && api().ok) (void) hipMemRelease((hipMemGenericAllocationHandle_t) (uintptr_t) h);
}
bool VmmRange::reserve(uint64_t bytes) {
release();
const Api& a = api();
if (!a.ok || bytes == 0) return false;
const uint64_t n = (bytes + a.gran - 1) / a.gran;
void* p = nullptr;
if (const hipError_t e = hipMemAddressReserve(&p, (size_t) (n * a.gran), 0, nullptr, 0); e != hipSuccess) { fail("hipMemAddressReserve", e); return false; }
base_ = (unsigned long long) (uintptr_t) p;
h_.assign((size_t) n, 0);
return true;
}
void VmmRange::release() {
if (base_ == 0) return;
const Api& a = api();
for (int64_t i = 0; i < chunks(); ++i) vmm_chunk_free(unmap(i));
(void) hipMemAddressFree((void*) (uintptr_t) base_, (size_t) ((uint64_t) h_.size() * a.gran));
base_ = 0;
h_.clear();
}
int64_t VmmRange::mapped_count() const {
int64_t n = 0;
for (const VmmChunk h : h_) n += h != 0;
return n;
}
bool VmmRange::map_one(int64_t i, VmmChunk h) {
const Api& a = api();
if (const hipError_t e = hipMemMap((void*) (uintptr_t) (base_ + (uint64_t) i * a.gran), (size_t) a.gran, 0,
(hipMemGenericAllocationHandle_t) (uintptr_t) h, 0);
e != hipSuccess) {
fail("hipMemMap", e);
return false;
}
h_[(size_t) i] = h;
return true;
}
bool VmmRange::set_access(int64_t lo, int64_t hi) {
if (hi <= lo) return true;
const Api& a = api();
hipMemAccessDesc d{};
d.location.type = hipMemLocationTypeDevice;
d.location.id = a.dev;
d.flags = hipMemAccessFlagsProtReadWrite;
const hipError_t e = hipMemSetAccess((void*) (uintptr_t) (base_ + (uint64_t) lo * a.gran), (size_t) ((uint64_t) (hi - lo) * a.gran),
&d, 1);
const bool ok = e == hipSuccess;
if (!ok) fail("hipMemSetAccess", e);
return ok;
}
bool VmmRange::commit_run(int64_t lo, int64_t hi) {
if (set_access(lo, hi)) return true;
for (int64_t c = lo; c < hi; ++c) vmm_chunk_free(unmap(c));
return false;
}
VmmChunk VmmRange::unmap(int64_t i) {
if (!mapped(i)) return 0;
const Api& a = api();
const VmmChunk h = h_[(size_t) i];
if (hipMemUnmap((void*) (uintptr_t) (base_ + (uint64_t) i * a.gran), (size_t) a.gran) != hipSuccess) { (void) hipGetLastError(); return 0; }
h_[(size_t) i] = 0;
return h;
}
} // namespace strata::core
#else
namespace strata::core {
bool vmm_available() { return false; }
@@ -168,3 +314,4 @@ VmmChunk VmmRange::unmap(int64_t) { return 0; }
} // namespace strata::core
#endif
#endif
+148 -125
View File
@@ -808,6 +808,11 @@ template<int TY> struct Split;
// per-entry ones, which call Fmt<TY>::dot per column exactly as before #242 (the launchers test kSplit at compile
// time, so the multi kernels are never instantiated for a type without a Split).
template<int TY> inline constexpr bool kSplit = false;
// The K-quant / Q8_0 / Q5_1 formats (UD-Q4_K_XL) have Split traits (SplitK below), but their decode-once multi kernels
// run only with STRATA_KQ_SPLIT=1 until the A/B on the measured cards decides (bitwise the old kernels either way).
template<int TY> inline constexpr bool kq_type = (TY == 12 || TY == 13 || TY == 8); // not Q5_1: its Split apply is not bitwise the old dot (FMA contraction), see notes-151-amd
inline bool g_kq_split = [] { const char* v = std::getenv("STRATA_KQ_SPLIT"); return v != nullptr && v[0] == '1'; }();
template<int TY> inline bool split_off() { return kq_type<TY> && !g_kq_split; }
template<int TY> inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 18 || TY == 21 || TY == 22 || TY == 29);
template<> inline constexpr bool kSplit<16> = true;
@@ -1185,6 +1190,141 @@ template<> struct Split<42> { // Q2_0
return r.d2 * d8 * sumi;
}
};
template<int TY> struct S27;
template<> struct S27<12> { // Q4_K
struct W { int v[2]; uint16_t aux[2]; half2 dm; };
__device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
const block_q4_K* b = (const block_q4_K*) vbq + kbx;
W r;
const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
const int* q4 = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
r.v[0] = q4[0];
r.v[1] = q4[4];
k_scale_min(b->scales, bq8_offset, r.aux);
r.dm = b->dm;
return r;
}
__device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
int u[2 * QR4_K];
float d8[QR4_K];
#pragma unroll
for (int i = 0; i < QR4_K; ++i) {
const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
d8[i] = __low2float(bq8i->ds);
const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
u[2 * i + 0] = q8[0];
u[2 * i + 1] = q8[4];
}
const uint8_t* sc = (const uint8_t*) r.aux;
const uint8_t* m = sc + 2;
return vec_dot_q4_K_q8_1_impl_vmmq(r.v, u, sc, m, r.dm, d8);
}
};
template<> struct S27<13> { // Q5_K
struct W { int vl[2]; int vh[2]; uint16_t aux[2]; half2 dm; };
__device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
const block_q5_K* b = (const block_q5_K*) vbq + kbx;
W r;
const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
const int* ql = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
const int* qh = (const int*) (b->qh + 4 * ((iqs / 2) % 4));
r.vl[0] = ql[0];
r.vl[1] = ql[4];
r.vh[0] = qh[0] >> bq8_offset;
r.vh[1] = qh[4] >> bq8_offset;
k_scale_min(b->scales, bq8_offset, r.aux);
r.dm = b->dm;
return r;
}
__device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
int u[2 * QR5_K];
float d8[QR5_K];
#pragma unroll
for (int i = 0; i < QR5_K; ++i) {
const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
d8[i] = __low2float(bq8i->ds);
const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
u[2 * i + 0] = q8[0];
u[2 * i + 1] = q8[4];
}
const uint8_t* sc = (const uint8_t*) r.aux;
const uint8_t* m = sc + 2;
return vec_dot_q5_K_q8_1_impl_vmmq(r.vl, r.vh, u, sc, m, r.dm, d8);
}
};
template<> struct S27<7> { // Q5_1
struct W { int vl[VDR_Q5_1]; int qh; half2 dm; };
__device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
const block_q5_1* b = (const block_q5_1*) vbq + kbx;
W r;
#pragma unroll
for (int i = 0; i < VDR_Q5_1; ++i) r.vl[i] = get_int_b4(b->qs, iqs + i);
r.qh = get_int_b4(b->qh, 0);
r.dm = b->dm;
return r;
}
__device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
int sumi = 0, sumu = 0;
#pragma unroll
for (int i = 0; i < VDR_Q5_1; ++i) {
const int vl = r.vl[i];
const int vh = r.qh >> (4 * (iqs + i));
const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1);
int vi0 = (vl >> 0) & 0x0F0F0F0F;
vi0 |= (vh << 4) & 0x00000010;
vi0 |= (vh << 11) & 0x00001000;
vi0 |= (vh << 18) & 0x00100000;
vi0 |= (vh << 25) & 0x10000000;
sumi = ggml_cuda_dp4a(vi0, u0, sumi);
int vi1 = (vl >> 4) & 0x0F0F0F0F;
vi1 |= (vh >> 12) & 0x00000010;
vi1 |= (vh >> 5) & 0x00001000;
vi1 |= (vh << 2) & 0x00100000;
vi1 |= (vh << 9) & 0x10000000;
sumi = ggml_cuda_dp4a(vi1, u1, sumi);
sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
}
const float2 dm5 = __half22float2(r.dm);
const float d8 = __low2float(bq8_1->ds);
return sumi * (dm5.x * d8) + sumu * (dm5.y * d8);
}
};
template<> struct S27<8> { // Q8_0
struct W { int q[VDR_Q8_0]; float d; };
__device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
const block_q8_0* b = (const block_q8_0*) vbq + kbx;
W r;
#pragma unroll
for (int i = 0; i < VDR_Q8_0; ++i) r.q[i] = get_int_b2(b->qs, iqs + i);
r.d = __half2float(b->d);
return r;
}
__device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
int sumi = 0;
#pragma unroll
for (int i = 0; i < VDR_Q8_0; ++i) sumi = ggml_cuda_dp4a(r.q[i], get_int_b4(bq8_1->qs, iqs + i), sumi);
const float d8_1 = __low2float(bq8_1->ds);
return r.d * d8_1 * ((float) sumi);
}
};
// K-quants and Q5_1 / Q8_0 (UD-Q4_K_XL): the S27 load / apply (below the same file used them first for the V2K
// grouped kernels) as Split traits, so the generic multi-column kernels decode a weight once per call for these
// formats too. Bitwise the old per-column Fmt<TY>::dot (the S27 apply is that dot's own expression; iq_multi_parity).
// STRATA_OLD_IQ_MMVQ=1 keeps the old kernels; STRATA_KQ_SPLIT=0 keeps them for these four formats only.
template<int TY> struct SplitK : S27<TY> {
template<bool STAGE_GRID = false>
__device__ static typename S27<TY>::W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
return S27<TY>::load(vbq, kbx, iqs);
}
};
template<> inline constexpr bool kSplit<12> = true;
template<> inline constexpr bool kSplit<13> = true;
template<> inline constexpr bool kSplit<8> = true;
template<> struct Split<12> : SplitK<12> {};
template<> struct Split<13> : SplitK<13> {};
template<> struct Split<8> : SplitK<8> {};
template<> inline constexpr bool kSplit<40> = true;
template<> struct Split<40> { // NVFP4: vec_dot_nvfp4_q8_1's two 16-value sub-blocks, weights decoded once per call
struct W { int2 v0[2], v1[2]; float sc[2]; };
@@ -2909,7 +3049,7 @@ int d_qk(int t) {
}
bool gu_split(int t) {
switch (t) {
#define STRATA_SP(T) case T: return kSplit<T>;
#define STRATA_SP(T) case T: return kSplit<T> && !split_off<T>();
STRATA_GU_FMTS(STRATA_SP)
#undef STRATA_SP
default: return false;
@@ -2971,7 +3111,7 @@ void launch_mmvq(const uint8_t* W, size_t rb, const block_q8_1* X, float* y, int
cudaStream_t s) {
const dim3 grid((unsigned) ((n_out + 3) / 4)), block(32, 4);
if constexpr (!kSplit<TY>) mmvq_kernel<TY><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);
else if (g_old_kernels) mmvq_kernel<TY><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);
else if (g_old_kernels || split_off<TY>()) mmvq_kernel<TY><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);
else if constexpr (kStageIqGrid<TY>) {
if (!g_stage_grid_mmvq) {
launch_mmvq_multi_nc<TY, false>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);
@@ -3333,125 +3473,6 @@ void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t
// words re-read per column). Each Fmt<TY>::dot is split into S27<TY>::load (everything that depends on the weight) and
// apply (the activation words and the same integer / float expression), the same impl functions, so a row's lane-strided
// k order, its terms and warp_sum are the old kernels': every output is bitwise the old one's (iq harness, memcmp).
template<int TY> struct S27;
template<> struct S27<12> { // Q4_K
struct W { int v[2]; uint16_t aux[2]; half2 dm; };
__device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
const block_q4_K* b = (const block_q4_K*) vbq + kbx;
W r;
const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
const int* q4 = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
r.v[0] = q4[0];
r.v[1] = q4[4];
k_scale_min(b->scales, bq8_offset, r.aux);
r.dm = b->dm;
return r;
}
__device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
int u[2 * QR4_K];
float d8[QR4_K];
#pragma unroll
for (int i = 0; i < QR4_K; ++i) {
const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
d8[i] = __low2float(bq8i->ds);
const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
u[2 * i + 0] = q8[0];
u[2 * i + 1] = q8[4];
}
const uint8_t* sc = (const uint8_t*) r.aux;
const uint8_t* m = sc + 2;
return vec_dot_q4_K_q8_1_impl_vmmq(r.v, u, sc, m, r.dm, d8);
}
};
template<> struct S27<13> { // Q5_K
struct W { int vl[2]; int vh[2]; uint16_t aux[2]; half2 dm; };
__device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
const block_q5_K* b = (const block_q5_K*) vbq + kbx;
W r;
const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
const int* ql = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
const int* qh = (const int*) (b->qh + 4 * ((iqs / 2) % 4));
r.vl[0] = ql[0];
r.vl[1] = ql[4];
r.vh[0] = qh[0] >> bq8_offset;
r.vh[1] = qh[4] >> bq8_offset;
k_scale_min(b->scales, bq8_offset, r.aux);
r.dm = b->dm;
return r;
}
__device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
int u[2 * QR5_K];
float d8[QR5_K];
#pragma unroll
for (int i = 0; i < QR5_K; ++i) {
const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
d8[i] = __low2float(bq8i->ds);
const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
u[2 * i + 0] = q8[0];
u[2 * i + 1] = q8[4];
}
const uint8_t* sc = (const uint8_t*) r.aux;
const uint8_t* m = sc + 2;
return vec_dot_q5_K_q8_1_impl_vmmq(r.vl, r.vh, u, sc, m, r.dm, d8);
}
};
template<> struct S27<7> { // Q5_1
struct W { int vl[VDR_Q5_1]; int qh; half2 dm; };
__device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
const block_q5_1* b = (const block_q5_1*) vbq + kbx;
W r;
#pragma unroll
for (int i = 0; i < VDR_Q5_1; ++i) r.vl[i] = get_int_b4(b->qs, iqs + i);
r.qh = get_int_b4(b->qh, 0);
r.dm = b->dm;
return r;
}
__device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
int sumi = 0, sumu = 0;
#pragma unroll
for (int i = 0; i < VDR_Q5_1; ++i) {
const int vl = r.vl[i];
const int vh = r.qh >> (4 * (iqs + i));
const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1);
int vi0 = (vl >> 0) & 0x0F0F0F0F;
vi0 |= (vh << 4) & 0x00000010;
vi0 |= (vh << 11) & 0x00001000;
vi0 |= (vh << 18) & 0x00100000;
vi0 |= (vh << 25) & 0x10000000;
sumi = ggml_cuda_dp4a(vi0, u0, sumi);
int vi1 = (vl >> 4) & 0x0F0F0F0F;
vi1 |= (vh >> 12) & 0x00000010;
vi1 |= (vh >> 5) & 0x00001000;
vi1 |= (vh << 2) & 0x00100000;
vi1 |= (vh << 9) & 0x10000000;
sumi = ggml_cuda_dp4a(vi1, u1, sumi);
sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
}
const float2 dm5 = __half22float2(r.dm);
const float d8 = __low2float(bq8_1->ds);
return sumi * (dm5.x * d8) + sumu * (dm5.y * d8);
}
};
template<> struct S27<8> { // Q8_0
struct W { int q[VDR_Q8_0]; float d; };
__device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
const block_q8_0* b = (const block_q8_0*) vbq + kbx;
W r;
#pragma unroll
for (int i = 0; i < VDR_Q8_0; ++i) r.q[i] = get_int_b2(b->qs, iqs + i);
r.d = __half2float(b->d);
return r;
}
__device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
int sumi = 0;
#pragma unroll
for (int i = 0; i < VDR_Q8_0; ++i) sumi = ggml_cuda_dp4a(r.q[i], get_int_b4(bq8_1->qs, iqs + i), sumi);
const float d8_1 = __low2float(bq8_1->ds);
return r.d * d8_1 * ((float) sumi);
}
};
template<int TG, bool LX, int RPW, bool TS>
__global__ void __launch_bounds__(256) s27_gu_kernel(const unsigned long long* __restrict__ grp_ptr,
@@ -3792,7 +3813,7 @@ void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, con
// (qk 128, ipb 8: 160 dots at n_embd 2560) take the full-warp multi kernel, as before the sub-16 kernels.
const bool g_no_sub16_gu = ::strata::kernels::g_no_sub16_gu || (L.n_embd / Fmt<TG>::qk) * Fmt<TG>::ipb != 80;
if constexpr (!kSplit<TG>) native_gu_kernel<TG><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
else if (g_old_kernels) native_gu_kernel<TG><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
else if (g_old_kernels || split_off<TG>()) native_gu_kernel<TG><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
else if constexpr (kStageIqGrid<TG>) {
if (!g_stage_grid || ((TG == 18 || TG == 21) && !stage_tables_on())) {
if (g_no_sub16_gu) native_gu_multi_kernel<TG, false, false><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
@@ -3837,7 +3858,9 @@ bool launch_gu_swiglu(const NativeExpertLayout& L, int64_t gy, cudaStream_t s, c
if constexpr (!kSplit<TG>) {
return false;
} else {
if (g_old_kernels || g_no_sub16_gu || L.n_embd != 2560 || L.n_ff % 32 != 0 || L.n_ff <= 0) return false;
if (g_old_kernels || split_off<TG>() || g_no_sub16_gu || L.n_embd != 2560 || L.n_ff % 32 != 0 || L.n_ff <= 0) return false;
// the 16-lane rows assume 80 dots a row (as launch_gu): the 256-value K-quants have 160
if (kq_type<TG> && (L.n_embd / Fmt<TG>::qk) * Fmt<TG>::ipb != 80) return false;
const dim3 grid((unsigned) (L.n_ff / 32), (unsigned) gy);
bool stage = false;
if constexpr (kStageIqGrid<TG>) stage = g_stage_grid && !((TG == 18 || TG == 21) && !stage_tables_on());
@@ -3856,7 +3879,7 @@ void launch_down(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, c
const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, const NativeExpertLayout& L,
float* out) {
if constexpr (!kSplit<TD>) native_down_kernel<TD><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
else if (g_old_kernels) native_down_kernel<TD><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
else if (g_old_kernels || split_off<TD>()) native_down_kernel<TD><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
else if (g_no_sub16_gu) native_down_multi_kernel<TD, false><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
else native_down_multi_kernel<TD, true><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
}
@@ -4812,7 +4835,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
const bool v1 = g_grouped_v1;
const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups;
const int gu_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_embd == 2560 && gu_split(L.gu_type) &&
gu_qk(L.gu_type) != 128) ? 16 : GU_ROWS; // qk 128 (APR trellis): no sub-16 rows, see launch_gu
gu_qk(L.gu_type) != 128 && L.gu_type != 12 && L.gu_type != 13) ? 16 : GU_ROWS; // qk 128 (APR trellis): no sub-16 rows, see launch_gu
const dim3 ggu((unsigned) ((2 * L.n_ff + gu_rows - 1) / gu_rows), (unsigned) gy);
#if STRATA_EXP_LAYOUTS
#if defined(STRATA_HIP_GFX906)
+59 -24
View File
@@ -14,6 +14,7 @@
#include <algorithm>
#include <cmath>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -2176,32 +2177,61 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float*
}
// gfx12 (RDNA4): on by default (148-amd; STRATA_HIP_WMMA=0 turns it off). gfx11 (RDNA3 / RDNA3.5): only on request
// (STRATA_HIP_WMMA=1). The output differs from the old kernel's in its last bits (FP32-level accuracy, another summation
// order): teacher-forced KL against the old kernel 0.0003 (28 prompts) / 0.0014 (8 long documents) on an R9700.
bool hip_wmma_usable() {
static const int env = [] { // -1 unset, 0 off, 1 on
// (STRATA_HIP_WMMA=1). STRATA_HIP_WMMA=auto (151-amd) takes the matrix-core kernel on a gfx12 card for a batch of
// STRATA_HIP_WMMA_MIN_Q (64) or more queries and keeps the FP32 kernel for smaller calls. The output differs from the
// old kernel's in its last bits (FP32-level accuracy, another summation order): teacher-forced KL against the old kernel
// 0.0003 (28 prompts) / 0.0014 (8 long documents) on an R9700. A launch that fails switches the path off for the rest of
// the process (the caller then runs the FP32 kernel) instead of ending it.
int hip_wmma_mode_env() { // -1 unset (the arch default), 0 off, 1 forced, 2 auto
static const int mode = [] {
const char* e = std::getenv("STRATA_HIP_WMMA");
return e == nullptr || e[0] == '\0' ? -1 : (e[0] == '1' ? 1 : 0);
if (e == nullptr || e[0] == '\0') return -1;
if (e[0] == '1') return 1;
if (!std::strcmp(e, "auto")) return 2;
return 0;
}();
if (env == 0) return false;
static int arch[64] = {}; // 0 unknown, 1 gfx12, 2 other, 3 gfx11 matrix cores
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; }
return mode;
}
std::atomic<bool> g_wmma_failed{false};
// the device's class: 1 gfx11 matrix-core part, 2 gfx12 (RDNA4), 3 anything else
int hip_wmma_arch(int dev) {
static int arch[64] = {};
if (dev < 0 || dev >= 64) return 3;
if (arch[dev] == 0) {
hipDeviceProp_t prop{};
if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; }
arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 1
: strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName) ? 3 : 2;
if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return 3; }
arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 2
: strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName) ? 1 : 3;
const int mode = hip_wmma_mode_env();
static bool told = false;
if (!told && (env == 1 || arch[dev] == 1)) {
if (!told && (mode >= 1 || arch[dev] == 2)) {
told = true;
const bool on = arch[dev] == 1 || (arch[dev] == 3 && env == 1);
std::fprintf(stderr, "strata: %sthe prompt attention on matrix cores %s (%s)%s\n", env == 1 ? "STRATA_HIP_WMMA: " : "",
on ? "on" : "unavailable", prop.gcnArchName,
env == 1 ? "" : " by default; STRATA_HIP_WMMA=0 turns it off");
const bool on = arch[dev] == 2 || (arch[dev] == 1 && mode >= 1);
std::fprintf(stderr, "strata: %sthe prompt attention on matrix cores %s (%s)%s\n", mode >= 1 ? "STRATA_HIP_WMMA: " : "",
!on ? "unavailable" : (mode == 2 ? "chosen per call" : "on"), prop.gcnArchName,
mode >= 1 ? "" : " by default; STRATA_HIP_WMMA=0 turns it off");
}
}
return arch[dev] == 1 || (arch[dev] == 3 && env == 1);
return arch[dev];
}
// auto: where the matrix-core kernel beats the FP32 one. Measured on the R9700 (gfx1201) only; the gfx11 parts take
// it only when forced with =1.
bool hip_wmma_auto_pick(int arch, int64_t n_q, int64_t cap) {
if (arch != 2) return false;
static const int64_t min_q = [] { const char* e = std::getenv("STRATA_HIP_WMMA_MIN_Q"); return e ? (int64_t) std::atoll(e) : (int64_t) 64; }();
static const int64_t min_cap = [] { const char* e = std::getenv("STRATA_HIP_WMMA_MIN_CAP"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();
return n_q >= min_q && cap >= min_cap;
}
bool hip_wmma_usable(int64_t n_q, int64_t cap) {
const int mode = hip_wmma_mode_env();
if (mode == 0 || g_wmma_failed.load(std::memory_order_relaxed)) return false;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) { (void) hipGetLastError(); return false; }
const int arch = hip_wmma_arch(dev);
if (arch == 3) return false;
if (mode == 1) return true;
if (mode == 2) return hip_wmma_auto_pick(arch, n_q, cap);
return arch == 2; // unset: the gfx12 default
}
bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
@@ -2222,8 +2252,9 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids,
}
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "qsa_prompt_attn_batch (wmma): %s\n", cudaGetErrorString(e));
std::exit(1);
std::fprintf(stderr, "qsa_prompt_attn_batch (wmma): %s; the FP32 prompt attention runs from here on\n", cudaGetErrorString(e));
g_wmma_failed.store(true);
return false;
}
return true;
}
@@ -2286,15 +2317,19 @@ bool qsa_decode_attn_split(const float* q, const QsaAttnPools& pools, const int3
#endif
}
void qsa_prompt_attn_set_imma(int on) { g_pa_imma = on < 0 ? -1 : (on ? 1 : 0); }
bool qsa_hip_wmma_active() {
bool qsa_prompt_attn_matrix_cores_requested() {
#if defined(__HIPCC__)
return hip_wmma_usable();
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) { (void) hipGetLastError(); return false; }
const int mode = hip_wmma_mode_env(), arch = hip_wmma_arch(dev);
return mode != 0 && arch != 3 && !g_wmma_failed.load(std::memory_order_relaxed) && (mode >= 1 || arch == 2);
#else
return false;
#endif
}
bool qsa_hip_wmma_active() { return qsa_prompt_attn_matrix_cores_requested(); }
bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) {
if (n_q <= 0) return true;
@@ -2335,7 +2370,7 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
(void) turing; (void) volta;
if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&
pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&
cap > 0 && ids && steps && pools.page_table && hip_wmma_usable())
cap > 0 && ids && steps && pools.page_table && hip_wmma_usable(n_q, cap))
return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream);
return false;
#endif
+15 -2
View File
@@ -62,10 +62,14 @@ const char* name_of(int t) {
case 23: return "IQ4_XS";
case 29: return "IQ1_M";
case 42: return "Q2_0";
case 12: return "Q4_K";
case 13: return "Q5_K";
case 7: return "Q5_1";
case 8: return "Q8_0";
default: return "?";
}
}
int block_values(int t) { return t == 20 ? 32 : t == 42 ? 64 : 256; }
int block_values(int t) { return (t == 20 || t == 7 || t == 8) ? 32 : t == 42 ? 64 : 256; }
// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block
std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) {
@@ -82,6 +86,10 @@ std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& r
} else {
const uint16_t h = (uint16_t) ((sgn(rng) == 0 ? 0x8000 : 0) | (ex(rng) << 10) | man(rng)); // 2^-13 .. 2^-6
std::memcpy(&w[o], &h, 2);
if (t == 12 || t == 13 || t == 7) { // Q4_K / Q5_K (d, dmin) and Q5_1 (d, m): the second half is finite too
const uint16_t h2 = (uint16_t) ((sgn(rng) == 0 ? 0x8000 : 0) | (ex(rng) << 10) | man(rng));
std::memcpy(&w[o + 2], &h2, 2);
}
}
}
return w;
@@ -409,7 +417,7 @@ int main(int argc, char** argv) {
cudaStream_t s;
ck(cudaStreamCreate(&s), "stream");
std::mt19937 rng(18);
for (int t : {16, 17, 18, 20, 21, 22, 23, 29, 42}) {
for (int t : {16, 17, 18, 20, 21, 22, 23, 29, 42, 12, 13, 7, 8}) {
check_mmvq(t, 2560, 67, s, rng); // the model's n_embd; 67 rows: a partial block of 4 rows
check_mmvq(t, 1024, 5, s, rng);
}
@@ -417,6 +425,11 @@ int main(int argc, char** argv) {
for (int dt : {20, 42}) check_grouped(gu, dt, 2560, 640, s, rng); // the model's shape
check_grouped(gu, 23, 1024, 512, s, rng); // IQ4_XS down needs n_ff % 256 == 0
}
// UD-Q4_K_XL (run with STRATA_KQ_SPLIT=1 to compare the Split path with the old kernels; STRATA_EXPERT_V2K=0 / 1 picks
// the generic multi kernel or the V2K one on gfx12: both are bitwise the old kernels)
for (int gu : {12, 13})
for (int dt : {7, 8}) check_grouped(gu, dt, 2560, 640, s, rng);
for (int gu : {12, 13}) check_grouped(gu, 13, 2048, 512, s, rng); // Qwen3.6-35B-A3B's geometry
check_q8_1_finite(s, rng);
if (do_bench) bench(s, rng);
std::printf("iq_multi_parity: %d failures\n", g_fail);
+88 -6
View File
@@ -308,9 +308,10 @@ inline int ring_budget_slots() {
inline int ring_slots(size_t T) {
const char* v = std::getenv("STRATA_PREFILL_RING");
#if defined(STRATA_USE_HIP)
// S6: with the RDNA4 matrix-core attention (the gfx12 default since 148-amd; STRATA_HIP_WMMA=1 elsewhere) a 96-slot
// ring: measured with it, 9070 XT 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same)
if (!v && g_ring_override <= 0 && strata::kernels::qsa_hip_wmma_active()) return (int64_t) T >= stream_all_min() ? 96 : STAGE;
// S6: with the matrix-core attention (the gfx12 default since 148-amd; STRATA_HIP_WMMA=1 or auto elsewhere / forced, on a card that
// has it) a 96-slot ring: measured with it, 9070 XT 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same)
static const bool wmma = strata::kernels::qsa_prompt_attn_matrix_cores_requested();
if (!v && g_ring_override <= 0 && wmma) return (int64_t) T >= stream_all_min() ? 96 : STAGE;
#endif
// the byte budget as this pack's slots: 1024 fused / 384 not on Q2_0, fewer on a pack with bigger blobs. The
// unpinned arm stays a slot count (96): it was measured where the host copies are the limit, and there the ring
@@ -1275,6 +1276,58 @@ uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) {
}
}
// The first BF16 and the first FP16 GEMM of a process each pay a one-time library / code-object load in hipBLAS (1.2 s and
// 1.0 s on an R9700, hipBLASLt 1.2.0: STRATA_COLD_TRACE), which the first prompt then carries (a 700-token prompt: 5.9 s,
// 3.5 s of it these). One tiny product of each type, on a handle and stream of its own, moves that cost out of the first
// request; generate.cpp starts it on a thread before the expert arena loads, so it costs no start-up time, and
// Prefill::init waits for it. The outputs go to scratch buffers of their own, so no later result changes.
// STRATA_PREFILL_WARM=0 turns it off.
void warm_gemm_libraries(int device) {
static const bool off = [] { const char* e = std::getenv("STRATA_PREFILL_WARM"); return e != nullptr && e[0] == '0'; }();
if (off) return;
#if defined(STRATA_USE_HIP)
static std::mutex mu;
static unsigned done_mask = 0; // per device: each card loads its own code objects
if (device < 0 || device >= 32) return;
std::lock_guard<std::mutex> lk(mu);
if (done_mask & (1u << device)) return;
done_mask |= 1u << device;
int prev = 0;
if (cudaGetDevice(&prev) != cudaSuccess) { (void) cudaGetLastError(); return; }
if (prev != device && cudaSetDevice(device) != cudaSuccess) { (void) cudaGetLastError(); return; }
const auto t0 = std::chrono::steady_clock::now();
constexpr int64_t T = 64, Nn = 64, K = 320;
uint16_t *x = nullptr, *w = nullptr;
float* y = nullptr;
cudaStream_t st = nullptr;
bool ok = cudaStreamCreate(&st) == cudaSuccess && cudaMalloc((void**) &x, (size_t) T * K * 2) == cudaSuccess &&
cudaMalloc((void**) &w, (size_t) Nn * K * 2) == cudaSuccess && cudaMalloc((void**) &y, (size_t) T * Nn * 4) == cudaSuccess;
if (ok) {
Gemm gm;
std::string err;
ok = gm.init((void*) st, T * K, err);
if (ok) {
cudaMemsetAsync(x, 0, (size_t) T * K * 2, st);
cudaMemsetAsync(w, 0, (size_t) Nn * K * 2, st);
gm.bf16(x, w, y, T, Nn, K);
gm.f16(x, w, y, T, Nn, K);
cudaStreamSynchronize(st);
}
}
(void) cudaGetLastError();
if (x) cudaFree(x);
if (w) cudaFree(w);
if (y) cudaFree(y);
if (st) cudaStreamDestroy(st);
if (prev != device) cudaSetDevice(prev);
if (ok)
std::fprintf(stderr, "strata prefill: warmed the BF16 and FP16 GEMM libraries on GPU %d in %.0f ms (STRATA_PREFILL_WARM=0 skips)\n",
device, std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());
#else
(void) device;
#endif
}
bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss,
core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk,
void* stream, std::string& err, void* borrow, uint64_t borrow_bytes, bool borrow_spill) {
@@ -1466,6 +1519,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co
std::to_string(o.failed_bytes >> 20) + " MiB)";
return false;
}
{ int wd = 0; if (cudaGetDevice(&wd) == cudaSuccess) warm_gemm_libraries(wd); else (void) cudaGetLastError(); }
return true;
}
@@ -2341,10 +2395,32 @@ const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::s
if (!r) err = v.name(suffix) + " is missing";
return r;
}
// STRATA_COLD_TRACE=1 (diagnostic): the wall time of the first 80 dense projections of the process, each synchronized, to show
// which first calls pay a one-time cost (library / code object loads).
struct ColdTrace {
bool on; int n = 0; std::chrono::steady_clock::time_point t0;
ColdTrace() { const char* e = std::getenv("STRATA_COLD_TRACE"); on = e != nullptr && e[0] == '1'; }
bool begin() {
if (!on || n >= 80) return false;
cudaDeviceSynchronize();
t0 = std::chrono::steady_clock::now();
return true;
}
void end(const char* what, const std::string& name, int64_t T, int64_t N, int64_t K) {
cudaDeviceSynchronize();
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
++n;
std::fprintf(stderr, "strata cold-trace: #%d %s %s T=%lld N=%lld K=%lld %.2f ms\n", n, what, name.c_str(), (long long) T,
(long long) N, (long long) K, ms);
}
};
ColdTrace g_cold;
bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name,
std::string& err, int64_t ldy = 0, int64_t ldx = 0) {
if (!w->native_data) { err = "prefill: " + name + " has no native GGUF blocks (run with --native)"; return false; }
const bool ct = g_cold.begin();
gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy, 0.0f, ldx);
if (ct) g_cold.end("native", name, T, w->ne1, w->ne0);
return true;
}
bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name,
@@ -2366,7 +2442,9 @@ bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y,
strata::kernels::hc_q8_to_bf16(w->data, w->q8_scale, scratch, (long long) w->elements, stream);
wb = scratch;
}
const bool ct = g_cold.begin();
gm.bf16(X, wb, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx, x_f16);
if (ct) g_cold.end("bf16", name, T, w->ne1, w->ne0);
if (X_lo) gm.bf16(X_lo, wb, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f);
return true;
}
@@ -2379,12 +2457,12 @@ namespace {
// host's expert grouping, or for an expert's copy) lands on the phase that was waiting. Events are reused: the marks
// are folded at every MoE layer's host sync, after which all of them have completed.
enum PfPhase { kPfStart, kPfHc, kPfGdn, kPfQsa, kPfQsaIdx, kPfQsaSel, kPfQsaAttn, kPfRouter, kPfHostGroup, kPfGather,
kPfWaitCopy, kPfDequant, kPfGemmGU, kPfGemmD, kPfCombine, kPfPle, kPfKvStage, kPfGdnConv, kPfGdnRec, kPfGdnOut,
kPfWaitCopy, kPfDequant, kPfGemmGU, kPfGemmD, kPfCombine, kPfPle, kPfKvStage, kPfGdnConv, kPfGdnRec, kPfGdnOut, kPfHcWrite,
kPfCount };
const char* const kPfNames[kPfCount] = {"embed+steps", "hc read", "gdn", "qsa proj", "qsa indexer", "qsa select",
"qsa attn", "router+shared", "host grouping", "gather", "wait copy", "dequant",
"gemm gate/up", "gemm down", "combine", "ple", "kv stage", "gdn conv+gates",
"gdn recurrence", "gdn out proj"};
"gdn recurrence", "gdn out proj", "hc write"};
struct PfTimer {
bool on = std::getenv("STRATA_PREFILL_TIMING") != nullptr;
std::vector<cudaEvent_t> ev;
@@ -2966,7 +3044,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (l > LB) pf_step("reading the prompt (batched, step sync): the experts and the rest of layer", l - 1);
core::progress_at("reading the prompt (batched): layer", l, p0); // #251: a stall names layer and chunk
const core::LayerView v(*m.wt, l);
if (l == std::max<int64_t>(LB, 1) && !ple_land()) return false; // the PLE rows, read from layer 1 on
if (l == std::max<int64_t>(LB, 1)) { // the PLE rows, read from layer 1 on (a wait for the SSD read of the first chunk lands on "ple")
pt.mark(kPfPle, cs);
if (!ple_land()) return false;
}
// ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows)
if (l == 1 && ple_on && ple_batch) {
// the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value
@@ -4659,6 +4740,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}
}
}
pt.mark(kPfHcWrite, cs); // the write-back (and the next half's norm) on its own line; it used to be charged to the phase before
// ---- the hyper-connection write of this half; F-2: fused with the next half's norm when nothing else
// touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a
// control vector)
+6
View File
@@ -2116,6 +2116,10 @@ strata::kernels::cpu::PoolAffinity measure_pool_affinity(strata::core::ExpertSou
return take_p ? cpu::PoolAffinity::PCores : cpu::PoolAffinity::All;
}
// HIP: the thread that warms hipBLAS's libraries while the expert arena loads (see warm_gemm_libraries); joined at exit.
std::thread g_warm_thr;
struct WarmJoin { ~WarmJoin() { if (g_warm_thr.joinable()) g_warm_thr.join(); } } g_warm_join;
// 0.1.42, CUDA single-GPU serve, no --pcie-frac: the share refined from what the CPU pool measures in the first decode
// windows. The balance share of the missed experts is link / (link + CPU rate). The link is the start-up probe; the CPU
// rate is the expert bytes over the pool's wall time per missed expert (ExpertDispatch::ms_run / multi_misses), which the
@@ -5373,6 +5377,8 @@ int main(int argc, char** argv) {
const char* name = named && p.name[0] ? p.name : "(an unnamed GPU)";
#if defined(STRATA_USE_HIP)
std::fprintf(stderr, "strata generate: GPU %d: %s (%s)\n", dev, name, named ? p.gcnArchName : "?");
// the first prompt's one-time hipBLAS library loads (about 2.5 s), done on a thread while the expert arena loads
if (named) g_warm_thr = std::thread([dev] { strata::prefill::warm_gemm_libraries(dev); });
// (RDNA4's matrix-core prompt attention is the default since 148-amd: the engine says so once, at its first prompt;
// STRATA_HIP_WMMA=0 turns it off.)
#if defined(_WIN32)
+84
View File
@@ -0,0 +1,84 @@
// tests/hip/prefill_gr_write_bench.cpp - the hyper-connection write-back (gr_write_norm_rs: R += bo * 2 sigmoid(inj / 4), then the next
// half's norm row scale and BF16 image) timed at the prompt path's shapes, with the bytes it moves, and a checksum of its
// outputs so a variant can be compared bit for bit (run twice with STRATA_GRW_V=0 / 1).
// gr_write_bench [T=16384] [reps=20]
#include "strata/prefill/kernels.hpp"
#include <cuda_runtime.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
namespace {
constexpr int N = 2560, HC = 4, D = N * HC;
bool ck(cudaError_t e, const char* what) {
if (e != cudaSuccess) { std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e)); return false; }
return true;
}
uint64_t fnv(const void* p, size_t n, uint64_t h = 1469598103934665603ull) {
const uint8_t* b = (const uint8_t*) p;
for (size_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; }
return h;
}
} // namespace
int main(int argc, char** argv) {
const int64_t T = argc > 1 ? std::atoll(argv[1]) : 16384;
const int reps = argc > 2 ? std::atoi(argv[2]) : 20;
std::mt19937 rng(7);
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<float> R0((size_t) T * D), bo((size_t) T * N), inj((size_t) T * HC), w((size_t) HC * N);
for (auto& v : R0) v = nd(rng);
for (auto& v : bo) v = nd(rng);
for (auto& v : inj) v = nd(rng);
for (auto& v : w) v = 0.5f + 0.1f * nd(rng);
float *dR = nullptr, *dR0 = nullptr, *dbo = nullptr, *dinj = nullptr, *dw = nullptr, *drs = nullptr;
uint16_t* dx = nullptr;
bool ok = ck(cudaMalloc(&dR, R0.size() * 4), "R") && ck(cudaMalloc(&dR0, R0.size() * 4), "R0") &&
ck(cudaMalloc(&dbo, bo.size() * 4), "bo") && ck(cudaMalloc(&dinj, inj.size() * 4), "inj") &&
ck(cudaMalloc(&dw, w.size() * 4), "w") && ck(cudaMalloc(&drs, (size_t) T * HC * 4), "rs") &&
ck(cudaMalloc(&dx, (size_t) T * D * 2), "xn16");
if (!ok) return 2;
cudaMemcpy(dR0, R0.data(), R0.size() * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dbo, bo.data(), bo.size() * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dinj, inj.data(), inj.size() * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dw, w.data(), w.size() * 4, cudaMemcpyHostToDevice);
cudaStream_t s;
cudaStreamCreate(&s);
// one reference pass for the checksum
cudaMemcpy(dR, dR0, R0.size() * 4, cudaMemcpyDeviceToDevice);
strata::prefill::gr_write_norm_rs(dR, dbo, dinj, HC, dw, 1e-6f, drs, dx, T, s, nullptr, D, false);
cudaStreamSynchronize(s);
std::vector<float> oR(R0.size()), ors((size_t) T * HC);
std::vector<uint16_t> ox((size_t) T * D);
cudaMemcpy(oR.data(), dR, oR.size() * 4, cudaMemcpyDeviceToHost);
cudaMemcpy(ors.data(), drs, ors.size() * 4, cudaMemcpyDeviceToHost);
cudaMemcpy(ox.data(), dx, ox.size() * 2, cudaMemcpyDeviceToHost);
std::printf("checksum R %016llx rs %016llx xn16 %016llx\n", (unsigned long long) fnv(oR.data(), oR.size() * 4),
(unsigned long long) fnv(ors.data(), ors.size() * 4), (unsigned long long) fnv(ox.data(), ox.size() * 2));
cudaEvent_t e0, e1;
cudaEventCreate(&e0);
cudaEventCreate(&e1);
float best = 1e30f, sum = 0;
for (int r = 0; r < reps; ++r) {
cudaMemcpy(dR, dR0, R0.size() * 4, cudaMemcpyDeviceToDevice);
cudaStreamSynchronize(s);
cudaEventRecord(e0, s);
strata::prefill::gr_write_norm_rs(dR, dbo, dinj, HC, dw, 1e-6f, drs, dx, T, s, nullptr, D, false);
cudaEventRecord(e1, s);
cudaEventSynchronize(e1);
float ms = 0;
cudaEventElapsedTime(&ms, e0, e1);
best = ms < best ? ms : best;
sum += ms;
}
// bytes: R read + write, bo read (x4 rows, from cache after the first), inj, w, rs, xn16 write
const double gb = ((double) T * D * 4 * 2 + (double) T * N * 4 + (double) T * D * 2) / 1e9;
std::printf("gr_write_norm_rs T=%lld: best %.3f ms, mean %.3f ms, %.0f GB/s at best (%.2f GB moved, bo counted once)\n",
(long long) T, best, sum / reps, gb / (best * 1e-3), gb);
return 0;
}