Merge perf-PR group sm75 (f-145-pp-sm75)
This commit is contained in:
commit
df6262f270
27 files changed
+2244
-137
No files matched your search
@@ -452,6 +452,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
||||
SKIP_RETURN_CODE 77)
|
||||
set_tests_properties(qsa_merge_daily_parity_daily PROPERTIES ENVIRONMENT "STRATA_ATTN_DAILY=1"
|
||||
SKIP_RETURN_CODE 77)
|
||||
# the prompt path's block scores on the thread-per-head kernel (Turing) against the warp kernel, bitwise
|
||||
add_executable(qsa_scores_parity src/kernels/qsa_scores_parity.cpp)
|
||||
target_include_directories(qsa_scores_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
|
||||
target_link_libraries(qsa_scores_parity PRIVATE strata_kernels CUDA::cudart)
|
||||
add_test(NAME qsa_scores_parity COMMAND qsa_scores_parity)
|
||||
set_tests_properties(qsa_scores_parity PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "STRATA_SCORES_THREAD=1")
|
||||
endif()
|
||||
# QSAROWS (docs/QSAROWS.md): what the T rows of a verification window cost in a QSA layer's decode kernels at a long
|
||||
# context (block scores, top-k, attention over each row's selection, indexer append), row by row; GPU, synthetic, no
|
||||
@@ -483,6 +489,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
||||
add_test(NAME qsa_select_bench_fp32_tiled COMMAND qsa_select_bench 131072 256 3 262144)
|
||||
set_tests_properties(qsa_select_bench_fp32_tiled PROPERTIES ENVIRONMENT "STRATA_QSA_WARP=1;STRATA_SELECT_SIMT=1")
|
||||
endif()
|
||||
if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) # the prompt attention on a recorded selection (STRATA_QSA_DUMP)
|
||||
add_executable(pa_bench tests/cuda/pa_bench.cpp)
|
||||
target_include_directories(pa_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
|
||||
target_link_libraries(pa_bench PRIVATE strata_kernels CUDA::cudart)
|
||||
endif()
|
||||
# plan v0.3 P6: llama.cpp's block layouts and codebook grids for the i-quant formats (MIT, third_party/ggml)
|
||||
target_include_directories(strata_kernels PRIVATE third_party/ggml)
|
||||
# Match the pinned llama.cpp CUDA arithmetic contract for this adapter only.
|
||||
|
||||
@@ -2240,3 +2240,22 @@ unless noted; the gain is small on these two cards and larger on the Turing card
|
||||
`STRATA_DEQUANT_WIDE` (the wide dequantization of Q4_K / Q5_K / Q6_K / IQ4_XS for the prompt's dense weights) is now on by default on
|
||||
sm_86 as well as sm_61: bit-exact, and the time to the first token of a 150 / 300 / 450-token prompt fell 11-15% on the RTX 3060 and 6-10% on the RTX A4000 (5 of 5 pairs each).
|
||||
`STRATA_DEQUANT_WIDE=0` turns it off.
|
||||
|
||||
### RTX 20 (Turing, sm_75) kernel series (opt-in, 0.1.45)
|
||||
|
||||
Kernels by rafatxf (#2069-#2072, #2093, #2220-#2222), imanu86 (#2081) and xrip (#1821) for compute capability 7.5. They were measured
|
||||
on one RTX 2080 Ti (decode +5..6 % at 4K-32K, prompts at depth up to +30 %, per the PRs) and are bitwise equal to the kernels they
|
||||
replace, but nobody on the team has an sm_75 card to confirm them, so they are off until asked for:
|
||||
|
||||
`STRATA_SM75_PERF=1` turns on every bitwise Turing kernel below on a 7.5 card (no other card is ever affected). Each has its own
|
||||
variable, which wins in both directions (`=0` off, `=1` on): `STRATA_SM75_IL` (interleaved small-batch matvec table),
|
||||
`STRATA_SM75_EXP` (expert layout mode 4), `STRATA_GR_UP75` / `STRATA_GR_DOWN_TG` (hyper-connection read), `STRATA_SCORES_HALVE`
|
||||
and `STRATA_TOPK_SPLIT` (decode QSA selection), `STRATA_TOPK_SAMPLE` (prompt top-k, one read of the scores), `STRATA_ATTN_V3`
|
||||
(decode attention), `STRATA_Q2_WARP` (Q2_0 matvec), `STRATA_FUSE_WAIT=2` and `STRATA_QIL` (fewer launches per decode layer),
|
||||
`STRATA_TC_SM75` (BF16 dequant, 16-byte stores), `STRATA_PA_V1_PREFETCH` (prompt attention v1 prefetch),
|
||||
`STRATA_SCORES_THREAD` (#1825: the prompt path's thread-per-head block scorer, bitwise the warp kernel's scores; `=1` takes it on any
|
||||
CUDA card, where it measured +1..3 % prompt speed on a Tesla P100 at 30-60K tokens, so it is not a default there).
|
||||
|
||||
Options that change answers (other summation order) are separate and explicit: `STRATA_SELECT_SIMT=1|2` (FP32 tiled block scorer,
|
||||
KL 0.01 against the warp scorer per #2071), `STRATA_PA_V2T=1` (v2 prompt attention, #2092/#2146), `STRATA_PF_FUSED=1
|
||||
STRATA_PF_FUSED_SM75=1` (fused int8 prompt experts for the Q2_0 pack, #2145; only on a 7.5 card, sm_80+ is unchanged), `STRATA_BF16_TC=1` with `STRATA_XN_F16` (#2091).
|
||||
@@ -0,0 +1,46 @@
|
||||
// strata/core/sm75_series.hpp - the Turing (RTX 20, compute capability 7.5) kernel series: one opt-in switch.
|
||||
//
|
||||
// The Turing kernels of PRs #2069-#2072, #2081, #2091-#2093, #2145-#2146, #2220-#2223, #1821 were measured on one RTX
|
||||
// 2080 Ti (and a CMP 50HX) and are bitwise equal to the kernels they replace. We have no sm_75 card to confirm them, so
|
||||
// they are ON ONLY WHEN ASKED FOR:
|
||||
//
|
||||
// STRATA_SM75_PERF=1 turns on every bitwise Turing kernel of the series on a compute capability 7.5 card.
|
||||
//
|
||||
// Each kernel keeps the author's own switch, which wins over STRATA_SM75_PERF in both directions (=0 off, =1 on, on any
|
||||
// card where the PR said so for tests). Nothing here changes a card that is not a 7.5: the check is the card's compute
|
||||
// capability (STRATA_EMULATE_CC=75 counts, so a 75-virtual build on an sm_86 card runs the series for tests).
|
||||
//
|
||||
// The numerics-changing Turing options are NOT part of this switch and keep their own explicit opt-ins:
|
||||
// STRATA_SELECT_SIMT=1|2 (FP32 tiled block scorer), STRATA_PA_V2T=1 (v2 prompt attention), STRATA_PF_FUSED_SM75=1
|
||||
// (fused int8 prompt experts), STRATA_BF16_TC=1 (FP16 tensor-core projections).
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/emulate.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace strata {
|
||||
|
||||
/// STRATA_SM75_PERF=1 (read once)
|
||||
inline bool sm75_series() {
|
||||
static const bool on = [] {
|
||||
const char* e = std::getenv("STRATA_SM75_PERF");
|
||||
return e != nullptr && std::atoi(e) != 0;
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
/// the device (raw cudaDevAttrComputeCapabilityMajor / Minor) is a Turing card, or emulates one (STRATA_EMULATE_CC=75)
|
||||
inline bool is_sm75(int major, int minor) { return cc_major_of(major) == 7 && cc_minor_of(minor) == 5; }
|
||||
|
||||
/// the default of a bitwise Turing kernel switch: on for a Turing card when STRATA_SM75_PERF=1
|
||||
inline bool sm75_default(int major, int minor) { return is_sm75(major, minor) && sm75_series(); }
|
||||
|
||||
/// a Turing switch with its own variable: `name` set means 0 off / anything else on (Turing only); unset follows the series
|
||||
inline bool sm75_switch(const char* name, int major, int minor) {
|
||||
if (!is_sm75(major, minor)) return false;
|
||||
const char* v = std::getenv(name);
|
||||
return v != nullptr ? std::atoi(v) != 0 : sm75_series();
|
||||
}
|
||||
|
||||
} // namespace strata
|
||||
@@ -0,0 +1,25 @@
|
||||
// include/strata/core/tc_sm75.hpp - sm_75 (RTX 20 / Turing) tensor-core paths.
|
||||
//
|
||||
// Turing has no tf32 MMA and no cp.async, so three of this engine's prompt-path kernels are compiled out below
|
||||
// sm_80 and fall back to slower paths (see `qsa_prompt_attn.cu`, `qsa_select.cu`). It does have fp16 MMA
|
||||
// (m16n8k8; m16n8k16 is sm_80+) and cuBLAS has no bf16 GEMM kernel below sm_80 - it runs an FFMA one, which
|
||||
// measured 19.5% of the prompt's GPU time on a 2x2080 Ti. These switches select the Turing paths.
|
||||
//
|
||||
// **ONLY sm_75 IS EVER AFFECTED.** The predicate below answers true for compute capability 7.5 and for nothing
|
||||
// else: cc 7.0/7.2 (Volta) keeps its own behaviour, and every cc >= 8 keeps the paths the engine was written
|
||||
// with. A machine that is not a 2080 Ti cannot be moved onto them by an environment variable.
|
||||
// The kernels themselves are gated a second time, at compile time, by `__CUDA_ARCH__ == 750`.
|
||||
//
|
||||
// 0.1.45: the Turing paths are opt-in (nobody here has an sm_75 card to confirm them): STRATA_SM75_PERF=1
|
||||
// (sm75_series.hpp) turns them on, STRATA_TC_SM75=0 / 1 forces this one off / on (still only on a 7.5 card).
|
||||
#pragma once
|
||||
|
||||
#include "strata/core/sm75_series.hpp"
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
inline bool tc_sm75_enabled(int cc_major, int cc_minor) {
|
||||
return strata::sm75_switch("STRATA_TC_SM75", cc_major, cc_minor); // 7.5 and only 7.5 - never another SM model
|
||||
}
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -147,6 +147,8 @@ constexpr int native_q8_1_il_cp(int ncols) { return ncols <= 2 ? 2 : ncols <= 4
|
||||
std::size_t native_q8_1_il_bytes(int n_in, int ncols);
|
||||
// Writes the interleaved copy of 2..4 columns of plain q8_1 blocks (native_quantize_q8_1's, or a fused producer's)
|
||||
// to x_il (native_q8_1_il_bytes): the same values in the same bytes.
|
||||
/// native_quantize_q8_1 and native_q8_1_interleave in one launch (CUDA): the same bytes in both buffers.
|
||||
void native_quantize_q8_1_il(const float* x, void* x_q8_1, void* x_il, int n_in, int ncols, void* stream);
|
||||
void native_q8_1_interleave(const void* x_q8_1, void* x_il, int n_in, int ncols, void* stream);
|
||||
// True when native_mmvq_il runs its own kernel for this call (IQ4_XS, Q4_K, Q5_K, Q6_K, 2-4 columns, the exact layout).
|
||||
bool native_mmvq_il_supported(int ggml_type, int ncols, int n_out);
|
||||
|
||||
@@ -35,8 +35,12 @@ public:
|
||||
/// Y[T, N] (fp32, row stride ldy) = X[T, K] (bf16, row-major) . W[N, K]^T (bf16, row-major). `beta` = 1 adds.
|
||||
/// Below sm_80 (no BF16 tensor cores): Volta converts both to FP16 and runs the FP16 tensor-core GEMM (Turing with
|
||||
/// STRATA_BF16_TC=1), Pascal widens both to fp32 (cublasSgemm); see gemm.cu.
|
||||
/// `x_f16`: X holds, instead of BF16, the FP16 values the Turing tensor-core path would convert it to
|
||||
/// (prefill's xn16 with its f16img writers): that path skips the conversion; any other converts back.
|
||||
void bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0,
|
||||
float beta = 0.0f, int64_t ldx = 0);
|
||||
float beta = 0.0f, int64_t ldx = 0, bool x_f16 = false);
|
||||
/// true when bf16() runs its products through FP16 tensor cores here (Turing, STRATA_BF16_TC): where X may be FP16
|
||||
bool bf16_converts_x() const;
|
||||
|
||||
/// S (STRATA_HCD_EXACT): the HC down projection (N 320, K 10240) by the WMMA kernel that reproduces hipBLASLt's
|
||||
/// solution 1176 / 1177 bit for bit; false (nothing launched) unless hipBLASLt would take one of those for this
|
||||
|
||||
@@ -16,10 +16,10 @@ namespace strata::prefill {
|
||||
/// xn[t, c*2560 + d] = R[t,c,d] * rsqrt(mean_d R[t,c,:]^2 + eps) * w_norm[c*2560 + d]; also its BF16 image.
|
||||
/// `xn16_lo` (null: none) takes bf16(x - xn16): W.xn16 + W.xn16_lo is the product with ~16 mantissa bits of x.
|
||||
void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream,
|
||||
uint16_t* xn16_lo = nullptr);
|
||||
uint16_t* xn16_lo = nullptr, bool f16img = false);
|
||||
/// F-1: gr_norm without its FP32 output: the row scales rs[t*4 + c] and the BF16 image; gr_mix_r then reads R.
|
||||
void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream,
|
||||
uint16_t* xn16_lo = nullptr, int64_t ldx = 0); // ldx: xn16's token stride (0 = 10240)
|
||||
uint16_t* xn16_lo = nullptr, int64_t ldx = 0, bool f16img = false); // ldx: xn16's token stride (0 = 10240)
|
||||
/// gr_mix with xn recomputed from R, rs and w_norm exactly as gr_norm computes it (the same bits).
|
||||
void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16,
|
||||
int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr);
|
||||
@@ -31,13 +31,13 @@ bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const
|
||||
float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream);
|
||||
void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps,
|
||||
float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr,
|
||||
int64_t ldx = 0);
|
||||
int64_t ldx = 0, bool f16img = false);
|
||||
/// S23 (STRATA_CVEC_FUSE=1): gr_write, then the control vector (v_l = layer l's direction row, *s_l its scale,
|
||||
/// *on the request flag, mode 0 project / 1 add; cvec_kernel's arithmetic), then gr_norm_rs with the next half's
|
||||
/// norm - one pass over R, the same bits as the three kernels.
|
||||
void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l,
|
||||
const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs,
|
||||
uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr, int64_t ldx = 0);
|
||||
uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr, int64_t ldx = 0, bool f16img = false);
|
||||
/// lo16[t, k] = bf16(silu(lo[t, k] / hc))
|
||||
void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr);
|
||||
/// The BF16-weight GEMMs' activation image (gr_* kernels, to_bf16) in FP16 instead of BF16, on the current device.
|
||||
|
||||
+57
-8
@@ -1,5 +1,6 @@
|
||||
// src/core/verify.cpp - see include/strata/core/verify.hpp.
|
||||
#include "strata/core/batch_rows.hpp"
|
||||
#include "strata/core/sm75_series.hpp"
|
||||
#include "strata/kernels/gfx_arch.hpp"
|
||||
#include "strata/core/verify.hpp"
|
||||
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
|
||||
@@ -271,6 +272,25 @@ bool head_mix_multi_enabled() {
|
||||
// copy_rows_from_mapped_after): same reads, same values, one kernel node fewer each. A dependent kernel costs ~2.4 us in a
|
||||
// gfx1201 graph whatever it does; measured on gfx12 only, so it is on there by default. STRATA_FUSE_WAIT=0 / 1 forces it
|
||||
// off / on (HIP builds; a CUDA build never fuses).
|
||||
// the Turing series (STRATA_SM75_PERF=1, sm75_series.hpp) defaults of the CUDA build's switches below, read per device
|
||||
bool device_is_sm75() {
|
||||
#if defined(STRATA_USE_HIP)
|
||||
return false;
|
||||
#else
|
||||
static int per_dev[64]; // 0 unknown, 1 no, 2 yes
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
|
||||
if (!per_dev[dev]) {
|
||||
int maj = 0, mnr = 0;
|
||||
const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
|
||||
cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
|
||||
if (!ok) cudaGetLastError();
|
||||
per_dev[dev] = ok && strata::sm75_default(maj, mnr) ? 2 : 1; // a Turing card with STRATA_SM75_PERF=1
|
||||
}
|
||||
return per_dev[dev] == 2;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool fuse_wait_on() {
|
||||
#if defined(STRATA_USE_HIP)
|
||||
static const int env = [] {
|
||||
@@ -287,7 +307,21 @@ bool fuse_wait_on() {
|
||||
}
|
||||
return per_dev[dev] == 2;
|
||||
#else
|
||||
return false;
|
||||
// CUDA: STRATA_FUSE_WAIT=1 folds both waits (the plan's and the CPU rows'), =2 only the plan's, =0 neither. Turing
|
||||
// default 2 (RTX 2080 Ti, Flash-Next Q2_0, two runs each: +0.6..+1.4 % decode); the rows' version makes every row
|
||||
// block of the copy poll the flag over PCIe and was -1.5 % there, so it stays opt-in.
|
||||
static const int env = [] { const char* v = std::getenv("STRATA_FUSE_WAIT"); return v != nullptr ? std::atoi(v) : -1; }();
|
||||
if (env >= 0) return env == 1 || env == 2;
|
||||
return device_is_sm75();
|
||||
#endif
|
||||
}
|
||||
// 143-amdk's rows version of the folded wait (copy_rows_from_mapped_after): HIP with fuse_wait_on, CUDA STRATA_FUSE_WAIT=1
|
||||
bool fuse_rows_on() {
|
||||
#if defined(STRATA_USE_HIP)
|
||||
return fuse_wait_on();
|
||||
#else
|
||||
static const bool on = [] { const char* v = std::getenv("STRATA_FUSE_WAIT"); return v != nullptr && std::atoi(v) == 1; }();
|
||||
return on;
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1226,6 +1260,22 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
stamp(l, 1, grp);
|
||||
float* xm = mixed_ + tb * N;
|
||||
bool il_ready = false; // xil_ holds xq_'s interleaved copy (reset whenever xq_ is rewritten)
|
||||
// a projection input's q8_1 blocks and their interleaved copy in one launch (native_quantize_q8_1_il, the same
|
||||
// bytes): Turing default (+0.5..+1 % decode, two launches fewer per GDN layer and per QSA layer); STRATA_QIL=0 / 1
|
||||
// forces it off / on
|
||||
auto quant_in = [&](const float* x, int n_in) {
|
||||
#if !defined(STRATA_USE_HIP)
|
||||
static const int qil_env = [] { const char* v = std::getenv("STRATA_QIL"); return v != nullptr ? std::atoi(v) : -1; }();
|
||||
const bool qil = qil_env >= 0 ? qil_env != 0 : device_is_sm75();
|
||||
if (qil && n >= 2 && n <= 4 && g_mmvq_il()) {
|
||||
strata::kernels::native_quantize_q8_1_il(x, xq_, xil_, n_in, n, cs);
|
||||
il_ready = true;
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
native_quantize_q8_1(x, xq_, n_in, n, cs);
|
||||
il_ready = false;
|
||||
};
|
||||
auto mm = [&](const WeightRef* w, float* out, int n_in, int n_out) {
|
||||
if (g_mmvq_il() && strata::kernels::native_mmvq_il_supported(w->native_type, n, n_out)) {
|
||||
if (!il_ready && n >= 2) { // one column reads the plain q8_1 blocks
|
||||
@@ -1263,7 +1313,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
(int) HV, n, side_);
|
||||
if (cudaEventRecord(mjoin_, side_) != cudaSuccess) { err = "verify: the GDN gates' branch could not join"; return false; }
|
||||
}
|
||||
if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs);
|
||||
if (!q8_attn) quant_in(xm, (int) N);
|
||||
if (side_proj) { // the gate projection (compute-bound for i-quants) beside qkv and the conv
|
||||
// the branch reads F4's interleaved copy too (written on cs before the fork; bitwise native_mmvq's
|
||||
// output), and qkv is recorded before the branch's launch, so its grid is dispatched first and the
|
||||
@@ -1370,8 +1420,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
stamp(l, 6, grp);
|
||||
// STRATA_QFUSE: done above by gdn_step_norm_multi - but a batch's per-slot recurrence passes it no q8_1
|
||||
// destination (#1139: the out-projection read stale bytes), so that case quantizes here as without it
|
||||
if (!g_qfuse() || batch_rec_) native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs);
|
||||
il_ready = false;
|
||||
if (!g_qfuse() || batch_rec_) quant_in(y_ + (size_t) tb * ZV, (int) ZV);
|
||||
else il_ready = false;
|
||||
mm(wout, bo_ + tb * N, (int) ZV, (int) N);
|
||||
} else {
|
||||
// ======================= QSA =======================
|
||||
@@ -1418,7 +1468,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
return e == nullptr || std::atoi(e) != 0;
|
||||
}();
|
||||
const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && (!st.kv_q4 || qb_q4);
|
||||
if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs);
|
||||
if (!q8_attn) quant_in(xm, (int) N);
|
||||
// STRATA_DF_BRANCH: the query side (q and its norm/RoPE/rotation on side 0, the indexer query on side 1)
|
||||
// beside the K/V side; the indexer query joins before the block scores, the query before attention
|
||||
const bool qbr = br && qb;
|
||||
@@ -1740,8 +1790,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
qsa_gate_apply_f32(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, s, attn32_ + t * NH * HD, cs);
|
||||
}
|
||||
stamp(l, 14, grp);
|
||||
native_quantize_q8_1(attn32_ + tb * NH * HD, xq_, (int) (NH * HD), n, cs);
|
||||
il_ready = false;
|
||||
quant_in(attn32_ + tb * NH * HD, (int) (NH * HD));
|
||||
mm(wo, bo_ + tb * N, (int) (NH * HD), (int) N);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
@@ -1965,7 +2014,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
copy_or_zero_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N,
|
||||
skip_ + grp, ring, cs);
|
||||
} else {
|
||||
const bool fuse_rows = fuse_wait_on() && !prof_on_ && !remote_opt_ && dec_batch && m_bal_ == nullptr; // 143-amdk
|
||||
const bool fuse_rows = fuse_rows_on() && !prof_on_ && !remote_opt_ && dec_batch && m_bal_ == nullptr; // 143-amdk
|
||||
if (!fuse_rows) {
|
||||
if (m_bal_ != nullptr) // set_pcie_balance: ... and ends as it waits for the CPU's rows
|
||||
wait_flag_ge_stamped(m_flag_, ring, m_bal_ + ((l - lb_) * 2 + grp) * 4 + 2, nullptr, cs);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// Arithmetic transcribed from ggml/src/ggml-quants.c at the pinned llama.cpp (MIT License, Copyright (c) 2023-2026
|
||||
// The ggml authors): dequantize_row_q2_0/q4_0/q5_0/q8_0/q3_K/q4_K/q5_K/q6_K/iq4_nl/iq4_xs.
|
||||
#include "strata/kernels/dequant_bf16.hpp"
|
||||
#include "strata/core/tc_sm75.hpp"
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
|
||||
#include <cuda_fp16.h>
|
||||
@@ -166,13 +167,28 @@ __device__ __forceinline__ void group32(const uint8_t* row_blocks, int gi_in_row
|
||||
}
|
||||
}
|
||||
|
||||
template <int TYPE, typename T>
|
||||
/// `VEC` (fork, Daily be4cf1c, sm_75 only): the group is dequantised into a register buffer and flushed with 16-byte
|
||||
/// stores. The plain form writes each element where it is computed, which for a warp means 32 store instructions
|
||||
/// whose lanes are 64 bytes apart - 32 two-byte transactions per instruction. **The values are identical** (the
|
||||
/// same arithmetic, the same order), only the stores are wider; the Turing build measured this kernel at 18% of the
|
||||
/// row's bandwidth. (0.1.42's Q8_0 kernel below already writes coalesced and is left as it is.)
|
||||
template <int TYPE, typename T, bool VEC>
|
||||
__global__ void dequant_kernel(const uint8_t* __restrict__ blocks, int64_t row_bytes, int64_t row0, int64_t rows,
|
||||
int64_t groups_per_row, int64_t ld, T* __restrict__ out) {
|
||||
const int64_t g = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (g >= rows * groups_per_row) return;
|
||||
const int64_t r = g / groups_per_row, gi = g % groups_per_row;
|
||||
group32<TYPE>(blocks + (row0 + r) * row_bytes, (int) gi, out + r * ld + gi * 32);
|
||||
T* dst = out + r * ld + gi * 32;
|
||||
if constexpr (!VEC) {
|
||||
group32<TYPE>(blocks + (row0 + r) * row_bytes, (int) gi, dst);
|
||||
} else {
|
||||
__align__(16) T buf[32]; // the uint4 flush below reads it as 16-byte vectors
|
||||
group32<TYPE>(blocks + (row0 + r) * row_bytes, (int) gi, buf);
|
||||
// 32 elements: 64 B for the 16-bit forms (4 x uint4), 128 B for the float one (8 x uint4)
|
||||
constexpr int CHUNKS = (sizeof(T) == 2 ? 4 : 8);
|
||||
#pragma unroll
|
||||
for (int c = 0; c < CHUNKS; ++c) reinterpret_cast<uint4*>(dst)[c] = reinterpret_cast<const uint4*>(buf)[c];
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the wide kernels: a thread per 8 values (Pascal, sm_61) --------------------------------------------------------
|
||||
@@ -359,7 +375,19 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t co
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "dequant launch: %s\n", cudaGetErrorString(e)); std::exit(1); }
|
||||
return;
|
||||
}
|
||||
#define STRATA_DQ(TY) dequant_kernel<TY, T><<<grid, 256, 0, st>>>(p, row_bytes, row0, rows, gpr, ld, out); break
|
||||
// sm_75 (and only cc 7.5) takes the vectorised-store form when every group's 32 outputs start on 16 bytes (an
|
||||
// aligned `out` and a row stride of whole 16-byte units); every other SM model keeps the plain kernel
|
||||
int dev = 0, cmaj = 0, cmin = 0;
|
||||
const bool vec = (reinterpret_cast<uintptr_t>(out) & 15) == 0 && ((uint64_t) ld * sizeof(T)) % 16 == 0 &&
|
||||
cudaGetDevice(&dev) == cudaSuccess &&
|
||||
cudaDeviceGetAttribute(&cmaj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
|
||||
cudaDeviceGetAttribute(&cmin, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess &&
|
||||
strata::core::tc_sm75_enabled(cmaj, cmin);
|
||||
if (!vec) cudaGetLastError();
|
||||
#define STRATA_DQ(TY) \
|
||||
if (vec) dequant_kernel<TY, T, true><<<grid, 256, 0, st>>>(p, row_bytes, row0, rows, gpr, ld, out); \
|
||||
else dequant_kernel<TY, T, false><<<grid, 256, 0, st>>>(p, row_bytes, row0, rows, gpr, ld, out); \
|
||||
break
|
||||
switch (type) {
|
||||
case 2: STRATA_DQ(2);
|
||||
case 6: STRATA_DQ(6);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp.
|
||||
#include "strata/core/emulate.hpp"
|
||||
#include "strata/core/sm75_series.hpp"
|
||||
#include "strata/kernels/q8_1_finite.hpp" // #606: q8_1_ds
|
||||
#include "strata/core/geometry.hpp"
|
||||
#include "strata/kernels/fused_gr.hpp"
|
||||
@@ -428,6 +429,102 @@ __global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) {
|
||||
if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE
|
||||
}
|
||||
|
||||
// Turing (sm_75): gr_up_multi_kernel's rows, sums and epilogue with the latency taken out of the warp's chain. A warp's
|
||||
// 8 rows of w_up are all loaded before any dot (was: one row's load after the previous row's epilogue: ~9k of the
|
||||
// warp's ~22k cycles were waits on memory, ncu on an RTX 2080 Ti); a token's 8 activations per lane are read from
|
||||
// shared memory once for the 8 rows; and the 8 rows' xor reductions run interleaved (8 independent shuffles per stage
|
||||
// instead of one chain of 5 per row). A row's last 8 chunks (lanes 0-7 of gr_up_multi_kernel) are held 4 rows to a
|
||||
// uint4 - lane 8 i + j holds chunk 32 + j of row i - and their dot is shuffled to lane j before it is added, so lane j
|
||||
// still sums its two dots in gr_up_multi_kernel's order. Every row's lane sums, xor tree and epilogue are
|
||||
// gr_up_multi_kernel's: the same bits. STRATA_GR_UP75=0 keeps gr_up_multi_kernel.
|
||||
template <int MAX_T = kFusedGrMaxT, bool EXACT_T = false>
|
||||
__global__ void __launch_bounds__(THREADS, 4) gr_up75_kernel(GrMulti m) {
|
||||
constexpr int RPW = HC * UPM_COLS / WARPS; // 8 rows per warp: row r = warp + WARPS i -> stream i / 2
|
||||
static_assert(RPW == 8 && UPM_COLS == 2 * WARPS && HC == 4 && LR / 8 - 32 == 8, "geometry");
|
||||
__shared__ __align__(16) float lo[MAX_T][LR];
|
||||
__shared__ float g[MAX_T][HC][UPM_COLS];
|
||||
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
const int T = EXACT_T ? MAX_T : m.T;
|
||||
const int d0 = blockIdx.x * UPM_COLS;
|
||||
const int tj = lane & 7, ti = lane >> 3; // tail: chunk 32 + tj of row 4 b + ti
|
||||
float mine[RPW];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RPW; ++i) mine[i] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int bt = 0; bt < 2; ++bt) { // two batches of 4 rows: 4 loads in flight, registers for 4 blocks
|
||||
uint4 wa[4], wt;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const int r = 4 * bt + i, c = r >> 1, dd = warp + WARPS * (r & 1), row = c * N + d0 + dd;
|
||||
wa[i] = __ldg(reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) row * LR) + lane);
|
||||
}
|
||||
{
|
||||
const int r = 4 * bt + ti, c = r >> 1, dd = warp + WARPS * (r & 1), row = c * N + d0 + dd;
|
||||
wt = __ldg(reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) row * LR) + 32 + tj);
|
||||
}
|
||||
if (bt == 0) {
|
||||
for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR];
|
||||
__syncthreads();
|
||||
}
|
||||
#pragma unroll 1
|
||||
for (int k = 0; k < T; ++k) {
|
||||
const float4* la = reinterpret_cast<const float4*>(lo[k] + lane * 8);
|
||||
const float4* lb = reinterpret_cast<const float4*>(lo[k] + (32 + tj) * 8);
|
||||
const float tb = dot8u(unpack8(wt), lb[0], lb[1]);
|
||||
const float4 x0 = la[0], x1 = la[1];
|
||||
float p[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const float b = __shfl_sync(0xffffffffu, tb, i * 8 + tj);
|
||||
float acc = dot8u(unpack8(wa[i]), x0, x1);
|
||||
if (lane < 8) acc += b;
|
||||
p[i] = acc;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) p[i] += __shfl_xor_sync(0xffffffffu, p[i], o);
|
||||
}
|
||||
if (lane == k) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) mine[4 * bt + i] = p[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lane < T) {
|
||||
const FusedGrArgs& a = m.a[lane];
|
||||
const bool apply = a.apply;
|
||||
float rv[RPW], wn[RPW], bo[RPW];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RPW; ++i) {
|
||||
const int c = i >> 1, dd = warp + WARPS * (i & 1), row = c * N + d0 + dd;
|
||||
rv[i] = a.R[row];
|
||||
wn[i] = a.w_norm[row];
|
||||
bo[i] = apply ? a.bo_prev[d0 + dd] : 0.0f;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RPW; ++i) {
|
||||
const int c = i >> 1, dd = warp + WARPS * (i & 1), row = c * N + d0 + dd;
|
||||
float x0 = rv[i];
|
||||
if (apply) {
|
||||
x0 = fmaf(bo[i], 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC), x0);
|
||||
a.R_out[row] = x0;
|
||||
}
|
||||
const float x = x0 * wn[i] * a.rs[c];
|
||||
g[lane][c][dd] = x * sigmoidf_(mine[i]);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
for (int i = t; i < T * UPM_COLS; i += THREADS) {
|
||||
const int k = i / UPM_COLS, col = i - k * UPM_COLS;
|
||||
float s = 0.0f;
|
||||
#pragma unroll
|
||||
for (int c = 0; c < HC; ++c) s += g[k][c][col];
|
||||
m.a[k].mixed[d0 + col] = s / (float) HC;
|
||||
}
|
||||
if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE, as gr_up_multi_kernel
|
||||
}
|
||||
|
||||
|
||||
// 143-amdk (STRATA_QFUSE_HC): gr_up_multi_kernel with 32 columns a block (512 threads, 80 blocks, the same 8 rows a warp), so a block owns a whole
|
||||
// q8_1 group of `mixed` and writes its image itself. STRATA_QFUSE's version (16 columns a block) needs a counter, two fences and a last block
|
||||
@@ -853,10 +950,10 @@ __device__ __forceinline__ float dot8v(const uint4 w, const float4 x0, const flo
|
||||
}
|
||||
|
||||
// Stage tile `h` of every token into `buf`: [T][2 planes][160 chunks] float4, plane 0 = floats 0-3 of a chunk.
|
||||
__device__ __forceinline__ void stage_htile(const GrMulti& m, int T, int h, float4* buf, int t) {
|
||||
__device__ __forceinline__ void stage_htile(const GrMulti& m, int T, int h, float4* buf, int t, int k0 = 0) {
|
||||
for (int i = t; i < T * (H_TILE / 4); i += THREADS) {
|
||||
const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4); // s4: float4 of the tile, chunk s4/2, half s4&1
|
||||
const float* src = m.xn + (size_t) k * D + (size_t) h * H_TILE + (size_t) s4 * 4;
|
||||
const float* src = m.xn + (size_t) (k0 + k) * D + (size_t) h * H_TILE + (size_t) s4 * 4;
|
||||
cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src);
|
||||
}
|
||||
}
|
||||
@@ -866,6 +963,9 @@ __global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) {
|
||||
extern __shared__ __align__(16) float4 hbuf[]; // 2 buffers x [T][2][160] float4
|
||||
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
const int T = EXACT_T ? MAX_T : m.T;
|
||||
// sm_75: a launch of EXACT_T groups of MAX_T tokens, one per blockIdx.y (gridDim.y 1: the whole launch); every
|
||||
// (row, token) is summed by one warp exactly as before - only more blocks share the card (#down-tg)
|
||||
const int k0 = EXACT_T ? (int) blockIdx.y * MAX_T : 0;
|
||||
const bool inject_block = blockIdx.x == DOWN_BLOCKS;
|
||||
const int row = inject_block ? warp : blockIdx.x * WARPS + warp;
|
||||
const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC));
|
||||
@@ -880,9 +980,9 @@ __global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < HQ; ++q) wv[q] = __ldg(w4 + lane + 32 * q);
|
||||
}
|
||||
stage_htile(m, T, 0, hbuf, t);
|
||||
stage_htile(m, T, 0, hbuf, t, k0);
|
||||
cp_async_commit();
|
||||
stage_htile(m, T, 1, hbuf + buf_f4, t);
|
||||
stage_htile(m, T, 1, hbuf + buf_f4, t, k0);
|
||||
cp_async_commit();
|
||||
#pragma unroll 1
|
||||
for (int h = 0; h < N_HTILES; ++h) {
|
||||
@@ -909,7 +1009,7 @@ __global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) {
|
||||
}
|
||||
}
|
||||
__syncthreads(); // every warp is done with buffer h & 1
|
||||
if (h + 2 < N_HTILES) stage_htile(m, T, h + 2, hbuf + (h & 1) * buf_f4, t);
|
||||
if (h + 2 < N_HTILES) stage_htile(m, T, h + 2, hbuf + (h & 1) * buf_f4, t, k0);
|
||||
cp_async_commit(); // an empty group at the end keeps the wait counts simple
|
||||
if (h + 1 < N_HTILES) {
|
||||
#pragma unroll
|
||||
@@ -925,10 +1025,10 @@ __global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) {
|
||||
for (int k = 0; k < MAX_T; ++k) {
|
||||
if ((!EXACT_T && k >= T) || lane != k) continue;
|
||||
if (inject_block) {
|
||||
m.a[k].inject_out[row] = s[k];
|
||||
m.a[k0 + k].inject_out[row] = s[k];
|
||||
} else {
|
||||
const float x = s[k] / (float) HC;
|
||||
m.a[k].lo[row] = x / (1.0f + __expf(-x));
|
||||
m.a[k0 + k].lo[row] = x / (1.0f + __expf(-x));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1085,6 +1185,50 @@ bool qfuse_hc_local() {
|
||||
static const bool on = [] { const char* e = std::getenv("STRATA_QFUSE_HC_LOCAL"); return e == nullptr || std::atoi(e) != 0; }();
|
||||
return on;
|
||||
}
|
||||
// Turing: gr_up75_kernel for 3+ tokens (bitwise gr_up_multi_kernel; fused_gr_bench cold on an RTX 2080 Ti, up incl. a
|
||||
// stamp: T 3 27.3 -> 24.6 us, T 4 33.2 -> 28.7, T 6 46.6 -> 36.6); STRATA_GR_UP75=0 / 1 forces it off / on
|
||||
bool up75_on() {
|
||||
#if defined(__HIPCC__)
|
||||
return false;
|
||||
#else
|
||||
static const int env = [] { const char* v = std::getenv("STRATA_GR_UP75"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
|
||||
if (env >= 0) return env != 0;
|
||||
static int per_dev[64]; // 0 unknown, 1 no, 2 yes
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
|
||||
if (!per_dev[dev]) {
|
||||
int major = 0, minor = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
per_dev[dev] = strata::sm75_default(major, minor) ? 2 : 1; // Turing, STRATA_SM75_PERF=1
|
||||
}
|
||||
return per_dev[dev] == 2;
|
||||
#endif
|
||||
}
|
||||
// sm_75: the staged down kernel's tokens per block (gridDim.y = ct / tg), 0 = one block row for all of them.
|
||||
// STRATA_GR_DOWN_TG=n forces n where it divides the launch (0 = off).
|
||||
int down_tg(int ct) {
|
||||
#if defined(__HIPCC__)
|
||||
(void) ct;
|
||||
return 0;
|
||||
#else
|
||||
static const int env = [] { const char* v = std::getenv("STRATA_GR_DOWN_TG"); return v ? std::atoi(v) : -1; }();
|
||||
if (ct < 2) return 0;
|
||||
if (env >= 0) return env > 0 && env <= 3 && ct % env == 0 ? env : 0;
|
||||
// fused_gr_bench cold on an RTX 2080 Ti (down incl. a stamp): T 4 29.1 -> 27.3 us, T 6 38.5 -> 32.2 with pairs;
|
||||
// one token per block is slower at every T (the weights are read from L2 once per group)
|
||||
static int per_dev[64]; // 0 unknown, 1 no, 2 sm_75
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return 0;
|
||||
if (!per_dev[dev]) {
|
||||
int major = 0, minor = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
per_dev[dev] = strata::sm75_default(major, minor) ? 2 : 1; // Turing, STRATA_SM75_PERF=1
|
||||
}
|
||||
return per_dev[dev] == 2 && (ct == 4 || ct == 6) ? 2 : 0;
|
||||
#endif
|
||||
}
|
||||
void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) {
|
||||
const int n_tok = m.T;
|
||||
const bool q8w = m.a[0].s_down != nullptr; // STRATA_HC_REQ8: w_down / w_up hold int8 codes
|
||||
@@ -1132,6 +1276,14 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long
|
||||
if (staged) {
|
||||
// #783 PR-g (stuchapin909): a launch of exactly ct <= 6 tokens is its own instantiation, the loop bounds
|
||||
// are compile-time (the same sums in the same order); STRATA_NO_MULTI_GR=1 keeps the generic kernels
|
||||
const int tg = down_tg(ct);
|
||||
if (exact_t && tg > 0 && tg < ct) {
|
||||
const dim3 grid(DOWN_BLOCKS + 1, (unsigned) (ct / tg));
|
||||
const size_t sm_g = (size_t) tg * per_tok;
|
||||
if (tg == 1) gr_down_staged_kernel<1, true><<<grid, THREADS, sm_g, st>>>(c);
|
||||
else if (tg == 2) gr_down_staged_kernel<2, true><<<grid, THREADS, sm_g, st>>>(c);
|
||||
else gr_down_staged_kernel<3, true><<<grid, THREADS, sm_g, st>>>(c);
|
||||
} else
|
||||
if (exact_t && ct == 1) gr_down_staged_kernel<1, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c);
|
||||
else if (exact_t && ct == 2) gr_down_staged_kernel<2, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c);
|
||||
else if (exact_t && ct == 3) gr_down_staged_kernel<3, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c);
|
||||
@@ -1183,6 +1335,16 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long
|
||||
case 6: gr_up_multi_kernel<6, true, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
default: gr_up_multi_kernel<kFusedGrMaxT, false, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
}
|
||||
} else if (n_tok >= 3 && up75_on()) { // T 1-2: gr_up_multi_kernel is as fast or faster (fused_gr_bench, cold)
|
||||
switch (no_multi_gr ? kFusedGrMaxT : n_tok) {
|
||||
case 1: gr_up75_kernel<1, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
case 2: gr_up75_kernel<2, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
case 3: gr_up75_kernel<3, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
case 4: gr_up75_kernel<4, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
case 5: gr_up75_kernel<5, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
case 6: gr_up75_kernel<6, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
default: gr_up75_kernel<kFusedGrMaxT, false><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
}
|
||||
} else
|
||||
switch (no_multi_gr ? kFusedGrMaxT : n_tok) {
|
||||
case 1: gr_up_multi_kernel<1, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// MIT license, third_party/ggml/LICENSE). The block structs and codebook grids come from its ggml-common.h,
|
||||
// included unchanged.
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
#include "strata/core/sm75_series.hpp"
|
||||
#include "strata/kernels/gfx_arch.hpp"
|
||||
#include "strata/kernels/dp4a.hpp"
|
||||
#include "strata/kernels/q8_1_finite.hpp"
|
||||
@@ -4178,13 +4179,32 @@ int exp_mode() {
|
||||
// IQ4_XS 328 -> 261 us, bitwise equal); STRATA_SM61_TABLE=0 keeps the CUDA layout
|
||||
const char* sm61 = std::getenv("STRATA_SM61_TABLE");
|
||||
const bool p40 = major == 6 && minor == 1 && (sm61 == nullptr || std::atoi(sm61) != 0);
|
||||
per_dev[dev] = 1 + ((major == 7 && minor == 0 && sm70 != nullptr && std::atoi(sm70) != 0) || p100 || p40 ? 8 : kExpModeDefault);
|
||||
// Turing (sm_75): mode 4 (native_expert_bench, real Q2_0 rows of Flash-Next, bitwise equal to mode 0 on an RTX
|
||||
// 2080 Ti: 10 experts x 1 entry 47.3 -> 41.4 us, 30 x 1 120.2 -> 100.2 us); the down projection keeps the CUDA
|
||||
// layout in windows of 4+ tokens (sm75_down_em below). STRATA_SM75_EXP=0 keeps the CUDA layout.
|
||||
// (off unless STRATA_SM75_PERF=1; STRATA_SM75_EXP=0 / 1 forces it off / on)
|
||||
const bool turing = strata::sm75_switch("STRATA_SM75_EXP", major, minor);
|
||||
per_dev[dev] = 1 + ((major == 7 && minor == 0 && sm70 != nullptr && std::atoi(sm70) != 0) || p100 || p40 ? 8 : turing ? 4 : kExpModeDefault);
|
||||
}
|
||||
return per_dev[dev] - 1;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only
|
||||
#if STRATA_EXP_LAYOUTS && !defined(__HIPCC__)
|
||||
// The down projection's mode on Turing's default: mode 4 is slower than the CUDA layout once groups have 3+ entries
|
||||
// (12 x 3: 36.5 -> 40.8 us, 16 x 4: 56.9 -> 68.9) - windows of 4+ tokens (cap_groups > 30) keep mode 0 there.
|
||||
int sm75_down_em(int em0, int64_t cap_groups) {
|
||||
if (em0 != 4 || g_exp_mode >= 0 || std::getenv("STRATA_EXP_MODE") != nullptr || cap_groups <= 30) return em0;
|
||||
int dev = 0, major = 0, minor = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess) return em0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
return strata::is_sm75(major, minor) ? 0 : em0;
|
||||
}
|
||||
#else
|
||||
int sm75_down_em(int em0, int64_t) { return em0; }
|
||||
#endif
|
||||
|
||||
void native_expert_set_mode(int mode, int phase) {
|
||||
#if STRATA_EXP_LAYOUTS
|
||||
@@ -4395,7 +4415,8 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
|
||||
const int d_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_ff == 640) ? (L.d_type == 20 || L.d_type == 40 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8;
|
||||
const dim3 gd((unsigned) ((L.n_embd + d_rows - 1) / d_rows), (unsigned) gy);
|
||||
#if STRATA_EXP_LAYOUTS
|
||||
if ((em0 == 7 || em0 == 8) && (L.d_type == 20 || L.d_type == 42)) {
|
||||
const int em0d = sm75_down_em(em0, cap_groups);
|
||||
if ((em0d == 7 || em0d == 8) && (L.d_type == 20 || L.d_type == 42)) {
|
||||
const dim3 gl((unsigned) ((L.n_embd + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);
|
||||
const size_t sh = (size_t) LDS_NT * (size_t) (L.n_ff / 32) * sizeof(block_q8_1);
|
||||
if (L.d_type == 20) native_down_lds_kernel<20><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
|
||||
@@ -4403,7 +4424,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
|
||||
check("native_expert_grouped/down");
|
||||
return;
|
||||
}
|
||||
const int em = em0 >= 5 ? kExpFallback : em0;
|
||||
const int em = em0d >= 5 ? kExpFallback : em0d;
|
||||
const dim3 gd_amd((unsigned) ((L.n_embd + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);
|
||||
#define STRATA_D_AMD(T) \
|
||||
case T: if (em == 1) native_down_amd_kernel<T, 1><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include "strata/kernels/q8_1_finite.hpp"
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
#include "strata/kernels/gfx_arch.hpp"
|
||||
#include "strata/core/sm75_series.hpp"
|
||||
#include "s26_tsum.cuh"
|
||||
#if !defined(__HIPCC__)
|
||||
#include "q8_1_il.cuh"
|
||||
@@ -1756,6 +1757,33 @@ __global__ void native_q8_1_interleave_kernel(const Q81Block* __restrict__ y, in
|
||||
if (p == 0) dl[std::size_t(b) * cp + c] = __low2float(blk.ds);
|
||||
}
|
||||
|
||||
// native_quantize_q8_1_kernel and native_q8_1_interleave_kernel in one launch: the same q8_1 blocks, and the
|
||||
// interleaved copy's ints and scales (an int is four codes, gathered from lanes 4p..4p+3 with two shuffles).
|
||||
__global__ void native_quantize_q8_1_il_kernel(const float* __restrict__ x, Q81Block* __restrict__ y,
|
||||
int* __restrict__ bm, int* __restrict__ pm, float* __restrict__ dl,
|
||||
int n_in, int n_total, int cp) {
|
||||
const int i = int(blockIdx.x) * QUANT_THREADS + int(threadIdx.x);
|
||||
if (i >= n_total) return; // n_total is a multiple of 32: only whole warps return
|
||||
const float xi = x[i];
|
||||
const float amax = warp_max(fabsf(xi));
|
||||
const float sum = warp_sum(xi);
|
||||
const float d = q8_1_finite(amax / 127.0f);
|
||||
const int8_t q = q8_1_quant(xi, d, amax);
|
||||
y[i / Q8K].qs[i % Q8K] = q;
|
||||
const auto ds = q8_1_ds(d, sum);
|
||||
if (i % Q8K == 0) y[i / Q8K].ds = ds;
|
||||
const int lane = int(threadIdx.x) & 31;
|
||||
unsigned v = unsigned(uint8_t(q)) << (8 * (lane & 3));
|
||||
v |= __shfl_xor_sync(0xffffffffu, v, 1);
|
||||
v |= __shfl_xor_sync(0xffffffffu, v, 2);
|
||||
const int nb = n_in / Q8K, c = i / n_in, b = (i - c * n_in) / Q8K, pp = lane >> 2;
|
||||
if ((lane & 3) == 0) {
|
||||
bm[(std::size_t(b) * 8 + pp) * cp + c] = int(v);
|
||||
pm[(std::size_t(pp) * nb + b) * cp + c] = int(v);
|
||||
}
|
||||
if (lane == 0) dl[std::size_t(b) * cp + c] = __low2float(ds);
|
||||
}
|
||||
|
||||
#endif // !__HIPCC__
|
||||
|
||||
void validate_shape(int n_in, int ncols, int block_elems = Q8K) {
|
||||
@@ -2395,6 +2423,73 @@ void native_q5_k_f32(const void* weights, const float* x, void* scratch_q8_1,
|
||||
native_q5_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Turing: Q2_0 one to four columns with one warp per RPW rows. The exact layout gives each row four warps, a chunk of
|
||||
// a 64-weight block per thread and a cross-warp reduction; at the engine's 2560 inputs (40 blocks a row) 48 of the 128
|
||||
// threads have no chunk and the reduction is most of the time (QSA attn_q 2560x12288 at 3 columns: 80 us, 110 GB/s on
|
||||
// an RTX 2080 Ti). Here lane l runs the chunks of the exact kernel's threads l, 32+l, 64+l and 96+l in their loop
|
||||
// order, adds the four sums as warp 0 adds the other warps' partials, then the same warp_sum: every output is bit for
|
||||
// bit native_q2_0_mmvq_kernel's (one column) and launch_multi's exact layout (two to four). 80 -> 31 us at three
|
||||
// columns, 37 -> 25 us at one. STRATA_Q2_WARP=0 keeps the old kernels; =1 takes this one on any CUDA card.
|
||||
constexpr int kQ20WarpRows = 4;
|
||||
template <int NCOLS>
|
||||
__global__ void __launch_bounds__(WARPS * WARP) q2_0_warp_rows_kernel(const Q20Block* __restrict__ w,
|
||||
const Q81Block* __restrict__ x,
|
||||
float* __restrict__ y, int n_in, int n_out) {
|
||||
using F = Q20Traits;
|
||||
constexpr int RPW = kQ20WarpRows;
|
||||
static_assert(F::T == 2 && F::BPI == WARPS * WARP / 2, "the lanes play the exact layout's threads");
|
||||
const int lane = int(threadIdx.x) & (WARP - 1);
|
||||
const int row0 = (int(blockIdx.x) * WARPS + int(threadIdx.x) / WARP) * RPW;
|
||||
if (row0 >= n_out) return;
|
||||
const int bpr = n_in / F::DIV, x_stride = n_in / Q8K;
|
||||
float acc[NCOLS][RPW];
|
||||
#pragma unroll
|
||||
for (int v = 0; v < WARPS; ++v) { // the exact kernel's thread WARP * v + lane
|
||||
const int tid = WARP * v + lane;
|
||||
const int kqs = F::kqs(tid);
|
||||
float tmp[NCOLS][RPW] = {};
|
||||
for (int kbx = tid / F::T; kbx < bpr; kbx += F::BPI) {
|
||||
const int kby = kbx * F::KBY;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RPW; ++i) {
|
||||
if (row0 + i < n_out) {
|
||||
const F::W wv = F::load(w + std::size_t(row0 + i) * bpr + kbx, kqs);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NCOLS; ++j) tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NCOLS; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RPW; ++i) acc[j][i] = v == 0 ? tmp[j][i] : acc[j][i] + tmp[j][i];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NCOLS; ++j)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RPW; ++i) {
|
||||
const float sum = warp_sum(acc[j][i]);
|
||||
if (lane == i && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = sum;
|
||||
}
|
||||
}
|
||||
bool q2_0_warp_rows_on() {
|
||||
static int on[16] = {}; // by device ordinal: 0 unknown, 1 yes, -1 no
|
||||
static const int env = [] { const char* v = std::getenv("STRATA_Q2_WARP"); return v ? (v[0] == '0' ? 0 : 1) : -1; }();
|
||||
if (env >= 0) return env == 1;
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return false;
|
||||
if (on[dev] == 0) {
|
||||
int maj = 0, mnr = 0;
|
||||
const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
|
||||
cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
|
||||
if (!ok) cudaGetLastError();
|
||||
on[dev] = ok && strata::sm75_default(maj, mnr) ? 1 : -1; // Turing only, with STRATA_SM75_PERF=1
|
||||
}
|
||||
return on[dev] > 0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
int n_in, int n_out, int ncols, void* stream) {
|
||||
validate_shape(n_in, ncols, 64);
|
||||
@@ -2404,6 +2499,24 @@ void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
validate_pointer(y);
|
||||
validate_stream(stream);
|
||||
STRATA_WAVE_MMVQ(Q20Traits)
|
||||
#if !defined(__HIPCC__)
|
||||
// one column always (bitwise the single-column kernel); two to four only where the exact layout is the one in use
|
||||
if (ncols <= 4 && (ncols == 1 || g_multi_exact) && q2_0_warp_rows_on()) {
|
||||
const auto* w = static_cast<const Q20Block*>(weights);
|
||||
const auto* x = static_cast<const Q81Block*>(x_q8_1);
|
||||
const auto s = static_cast<cudaStream_t>(stream);
|
||||
const int warps = (n_out + kQ20WarpRows - 1) / kQ20WarpRows;
|
||||
const unsigned blocks = unsigned((warps + WARPS - 1) / WARPS);
|
||||
switch (ncols) {
|
||||
case 1: q2_0_warp_rows_kernel<1><<<blocks, WARPS * WARP, 0, s>>>(w, x, y, n_in, n_out); break;
|
||||
case 2: q2_0_warp_rows_kernel<2><<<blocks, WARPS * WARP, 0, s>>>(w, x, y, n_in, n_out); break;
|
||||
case 3: q2_0_warp_rows_kernel<3><<<blocks, WARPS * WARP, 0, s>>>(w, x, y, n_in, n_out); break;
|
||||
default: q2_0_warp_rows_kernel<4><<<blocks, WARPS * WARP, 0, s>>>(w, x, y, n_in, n_out); break;
|
||||
}
|
||||
launch_check();
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (ncols > 1) {
|
||||
launch_multi<Q20Traits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
|
||||
launch_check();
|
||||
@@ -2734,6 +2847,23 @@ std::size_t native_q8_1_il_bytes(int n_in, int ncols) {
|
||||
return std::size_t(n_in / Q8K) * std::size_t(native_q8_1_il_cp(ncols)) * (16 * sizeof(int) + sizeof(float));
|
||||
}
|
||||
|
||||
void native_quantize_q8_1_il(const float* x, void* x_q8_1, void* x_il, int n_in, int ncols, void* stream) {
|
||||
validate_shape(n_in, ncols);
|
||||
if (ncols < 2 || ncols > 4) throw std::invalid_argument("native_quantize_q8_1_il requires 2 <= ncols <= 4");
|
||||
validate_pointer(x);
|
||||
validate_pointer(x_q8_1);
|
||||
validate_pointer(x_il);
|
||||
validate_stream(stream);
|
||||
const int cp = native_q8_1_il_cp(ncols);
|
||||
const Q81IlParts parts = q8_1_il_parts(x_il, n_in, ncols);
|
||||
const int n_total = n_in * ncols;
|
||||
native_quantize_q8_1_il_kernel<<<unsigned((n_total + QUANT_THREADS - 1) / QUANT_THREADS), QUANT_THREADS, 0,
|
||||
static_cast<cudaStream_t>(stream)>>>(
|
||||
x, static_cast<Q81Block*>(x_q8_1), const_cast<int*>(parts.bm), const_cast<int*>(parts.pm),
|
||||
const_cast<float*>(parts.d), n_in, n_total, cp);
|
||||
launch_check();
|
||||
}
|
||||
|
||||
void native_q8_1_interleave(const void* x_q8_1, void* x_il, int n_in, int ncols, void* stream) {
|
||||
validate_shape(n_in, ncols);
|
||||
if (ncols < 2 || ncols > 4) throw std::invalid_argument("native_q8_1_interleave requires 2 <= ncols <= 4");
|
||||
@@ -2808,6 +2938,17 @@ constexpr IlRows kIlRows_86[] = {
|
||||
{14, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 2}, {0, 0, 1, 1, 1}}}, // Q6_K
|
||||
{11, {{1, 2, 2, 2, 2}, {1, 1, 1, 2, 2}, {1, 1, 1, 1, 1}}}, // Q3_K (two runs; 2560x10240 at 4 columns 120 -> 70 us)
|
||||
};
|
||||
// Turing (sm_75): read off mmvq_il_parity --bench --emit-table on an RTX 2080 Ti 22 GB (SM 1650 MHz), the same 3% rule.
|
||||
// The plain multi-column kernels are bound by dp4a throughput on Turing from 2 columns on (IQ4_XS 2560x10240 at 4
|
||||
// columns 81.1 -> 37.4 us, the Q5_K head 1671 -> 1045 us); bitwise equal to native_mmvq. No one-column table here:
|
||||
// the engine's dedicated single-column kernels (native_q3_k_mmvq) sum in another order, and the gain was 0.5%.
|
||||
constexpr IlRows kIlRows_75[] = {
|
||||
{23, {{2, 2, 2, 2, 2}, {2, 2, 4, 2, 4}, {2, 2, 2, 2, 2}}}, // IQ4_XS
|
||||
{12, {{0, 4, 2, 4, 4}, {1, 2, 2, 2, 2}, {1, 2, 2, 2, 2}}}, // Q4_K
|
||||
{13, {{0, 4, 2, 2, 4}, {1, 4, 2, 2, 2}, {1, 1, 2, 2, 2}}}, // Q5_K
|
||||
{14, {{0, 0, 1, 2, 1}, {0, 2, 2, 4, 4}, {0, 4, 4, 4, 4}}}, // Q6_K
|
||||
{11, {{1, 2, 4, 4, 4}, {1, 2, 4, 4, 4}, {1, 2, 2, 2, 2}}}, // Q3_K
|
||||
};
|
||||
// One column: rows a warp by n_out class, 0 = native_mmvq's single-column kernels (STRATA_MMVQ_IL_T1=0 turns this off).
|
||||
struct Il1Rows { int type; uint8_t r[5]; };
|
||||
constexpr Il1Rows kIl1Rows_86[] = {
|
||||
@@ -2834,6 +2975,7 @@ struct IlArch { int cc; const IlRows* t; size_t n; };
|
||||
constexpr IlArch kIlArch[] = {
|
||||
{60, kIlRows_60, sizeof(kIlRows_60) / sizeof(IlRows)}, // Pascal GP100: measured on a Tesla P100
|
||||
{61, kIlRows_61, sizeof(kIlRows_61) / sizeof(IlRows)}, // Pascal with dp4a: measured on a Tesla P40
|
||||
{75, kIlRows_75, sizeof(kIlRows_75) / sizeof(IlRows)}, // Turing: measured on an RTX 2080 Ti
|
||||
{70, kIlRows_70, sizeof(kIlRows_70) / sizeof(IlRows)}, // Volta: PR 1401, measured on a V100-SXM2
|
||||
{86, kIlRows_86, sizeof(kIlRows_86) / sizeof(IlRows)}, // 143-dense: RTX A4000 with the real shapes (Q3_K added)
|
||||
};
|
||||
@@ -2913,11 +3055,13 @@ void native_mmvq_il_tune(int rows) { g_tune_rows = rows; }
|
||||
|
||||
namespace {
|
||||
// sm_80 and newer (measured on sm_86 and sm_120), Volta (sm_70) and Pascal (sm_60, sm_61), each with its own table
|
||||
// above; Turing keeps native_mmvq's kernels unchanged
|
||||
// above; Turing keeps native_mmvq's kernels unless STRATA_SM75_PERF=1 (kIlRows_75)
|
||||
// Volta (PR 1401): opt-in with STRATA_SM70_TABLE=1 until the author confirms on a V100 with the final code
|
||||
bool sm70_opt_in() { const char* v = std::getenv("STRATA_SM70_TABLE"); return v != nullptr && std::atoi(v) != 0; }
|
||||
// Pascal (sm_60, GP100): the same interleaved kernels (bitwise equal to native_mmvq's, mmvq_il_parity), its own table
|
||||
// kIlRows_60. STRATA_SM60_TABLE=0 keeps native_mmvq's kernels on a P100; any other value (or unset) uses the table.
|
||||
// STRATA_SM75_IL=0 / 1 forces the table off / on; unset it follows STRATA_SM75_PERF=1 (Turing only)
|
||||
bool sm75_il_on(int major, int minor) { return strata::sm75_switch("STRATA_SM75_IL", major, minor); }
|
||||
bool sm60_table_on() { const char* v = std::getenv("STRATA_SM60_TABLE"); return v == nullptr || std::atoi(v) != 0; }
|
||||
// Pascal (sm_61: Tesla P40 / P4, GTX 10 series; native dp4a): the same interleaved kernels (bitwise equal to
|
||||
// native_mmvq's, mmvq_il_parity), its own table kIlRows_61. STRATA_SM61_TABLE=0 keeps native_mmvq's kernels.
|
||||
@@ -2931,8 +3075,8 @@ bool il_arch_ok() {
|
||||
int minor = 0;
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
ok[dev] = (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
|
||||
(major >= 8 || (major == 7 && minor == 0 && sm70_opt_in()) || (major == 6 && minor == 0 && sm60_table_on()) ||
|
||||
(major == 6 && minor == 1 && sm61_table_on()))) ? 1 : -1;
|
||||
(major >= 8 || (major == 7 && minor == 0 && sm70_opt_in()) || (major == 7 && minor == 5 && sm75_il_on(major, minor)) ||
|
||||
(major == 6 && minor == 0 && sm60_table_on()) || (major == 6 && minor == 1 && sm61_table_on()))) ? 1 : -1;
|
||||
}
|
||||
return ok[dev] > 0;
|
||||
}
|
||||
@@ -2970,6 +3114,9 @@ void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, cons
|
||||
|
||||
#else // HIP: no interleaved path
|
||||
std::size_t native_q8_1_il_bytes(int n_in, int ncols) { return native_q8_1_bytes(n_in, ncols) * 2; }
|
||||
void native_quantize_q8_1_il(const float*, void*, void*, int, int, void*) {
|
||||
throw std::invalid_argument("native_quantize_q8_1_il is CUDA only");
|
||||
}
|
||||
void native_q8_1_interleave(const void*, void*, int, int, void*) {
|
||||
throw std::invalid_argument("native_q8_1_interleave is CUDA only");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp.
|
||||
#include "strata/kernels/qsa_decode_attn.hpp"
|
||||
#include "strata/core/sm75_series.hpp"
|
||||
#include "strata/core/geometry.hpp"
|
||||
#include "strata/kernels/kv_q8.hpp"
|
||||
#include "strata/kernels/kv_q4.hpp"
|
||||
@@ -325,6 +326,131 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_rows_kernel(const float* _
|
||||
part_acc, part_m, part_l, n_chunks, cap, scratch_stride);
|
||||
}
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
// Turing (INT8 pools): attn_chunk_kernel<1> bit for bit, rearranged for the SM's shared-memory pipe, which the
|
||||
// default kernel saturates (its time grew with the queries even with the SMs half empty). Three changes, none to an
|
||||
// operand or the order of an operation:
|
||||
// - the lane's slice of the 12 query heads (8 dimensions each) is read from shared memory once, into registers,
|
||||
// instead of two 16-byte reads per head per cell (with a two-way bank conflict at lane * 8);
|
||||
// - the 12 heads' lane sums are reduced with reduce12_gfx906 (16 shuffles, each sum warp_sum's pairs) instead of
|
||||
// 12 warp_sums (60 shuffles);
|
||||
// - the probabilities are stored cell-major, so the value loop reads a cell's 12 as three 16-byte broadcasts.
|
||||
// RTX 2080 Ti, 2051 selected cells: 1 / 2 / 3 / 4 queries 51.6 / 78.5 / 110 / 146 -> 34.5 / 41.0 / 73.0 / 84.9 us
|
||||
// (with the merge); 600 cells 45.9 / 74.6 / 105 / 137 -> 28.6 / 32.8 / 33.5 / 33.3 us. STRATA_ATTN_V3=0 keeps the
|
||||
// default kernel; =1 takes this one on any CUDA card.
|
||||
__global__ void __launch_bounds__(THREADS) attn_chunk_q8_v3_kernel(const float* __restrict__ q, QsaAttnPools p,
|
||||
const int32_t* __restrict__ ids,
|
||||
const int32_t* __restrict__ step, int n_kv_heads,
|
||||
int page_size, float scale, float* __restrict__ part_acc,
|
||||
float* __restrict__ part_m, float* __restrict__ part_l,
|
||||
int n_chunks, int cap = 0, long long scratch_stride = 0) {
|
||||
q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
|
||||
ids += (size_t) blockIdx.z * (size_t) cap;
|
||||
step += (size_t) blockIdx.z * kStepCount;
|
||||
part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
|
||||
part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
|
||||
part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
|
||||
__shared__ __align__(16) float sq[G][HD];
|
||||
__shared__ __align__(16) float spt[CHUNK][G]; // cell-major: one cell's 12 heads are 3 float4
|
||||
__shared__ long long srow[CHUNK];
|
||||
const int n_ids = __ldg(step + kStepWidth);
|
||||
const int chunk = blockIdx.x, kvh = blockIdx.y;
|
||||
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
const int c0 = chunk * CHUNK;
|
||||
const int n_here = min(CHUNK, n_ids - c0);
|
||||
const int slot = kvh * n_chunks + chunk;
|
||||
if (n_here <= 0) {
|
||||
if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
|
||||
return;
|
||||
}
|
||||
// stored with the gfx906 swizzle (the two float4 halves of lanes with bit 2 swapped): fewer conflicts on the one read
|
||||
for (int i = t; i < G * HD; i += THREADS) {
|
||||
const int d = i % HD;
|
||||
sq[i / HD][d ^ ((d >> 3) & 4)] = q[(size_t) (kvh * G) * HD + i];
|
||||
}
|
||||
if (t < CHUNK) {
|
||||
long long r = -1;
|
||||
if (t < n_here) {
|
||||
const int cell = ids[c0 + t];
|
||||
const long long page = (long long) p.page_table[cell / page_size];
|
||||
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
|
||||
}
|
||||
srow[t] = r;
|
||||
}
|
||||
__syncthreads();
|
||||
float qr[G][8];
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h) {
|
||||
const int qflip = lane & 4;
|
||||
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)]);
|
||||
qr[h][0] = qa.x; qr[h][1] = qa.y; qr[h][2] = qa.z; qr[h][3] = qa.w;
|
||||
qr[h][4] = qb.x; qr[h][5] = qb.y; qr[h][6] = qb.z; qr[h][7] = qb.w;
|
||||
}
|
||||
for (int c = warp; c < CHUNK; c += WARPS) {
|
||||
if (c >= n_here || srow[c] < 0) {
|
||||
if (lane < G) spt[c][lane] = -FLT_MAX;
|
||||
continue;
|
||||
}
|
||||
float k8[8];
|
||||
load8<1>(p, false, srow[c], lane * 8, k8);
|
||||
float part[16];
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h)
|
||||
part[h] = k8[0] * qr[h][0] + k8[1] * qr[h][1] + k8[2] * qr[h][2] + k8[3] * qr[h][3] +
|
||||
k8[4] * qr[h][4] + k8[5] * qr[h][5] + k8[6] * qr[h][6] + k8[7] * qr[h][7];
|
||||
#pragma unroll
|
||||
for (int h = G; h < 16; ++h) part[h] = 0.0f;
|
||||
const float score = reduce12_gfx906(part, lane);
|
||||
const int head = reduce12_head_of_lane(lane);
|
||||
if ((lane & 1) == 0 && head < G) spt[c][head] = score * scale;
|
||||
}
|
||||
__syncthreads();
|
||||
for (int h = warp; h < G; h += WARPS) {
|
||||
const float a = spt[lane][h], b = spt[lane + 32][h];
|
||||
const float m = warp_max(fmaxf(a, b));
|
||||
const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
|
||||
const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
|
||||
spt[lane][h] = ea;
|
||||
spt[lane + 32][h] = eb;
|
||||
const float l = warp_sum(ea + eb);
|
||||
if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
|
||||
}
|
||||
__syncthreads();
|
||||
float acc[G];
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
|
||||
for (int c = 0; c < n_here; ++c) {
|
||||
if (srow[c] < 0) continue; // masked above, weight 0
|
||||
const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]));
|
||||
const float v = (float) p.v_q[srow[c] * HD + t] * sc;
|
||||
const float4 p0 = *reinterpret_cast<const float4*>(&spt[c][0]);
|
||||
const float4 p1 = *reinterpret_cast<const float4*>(&spt[c][4]);
|
||||
const float4 p2 = *reinterpret_cast<const float4*>(&spt[c][8]);
|
||||
const float pr[G] = {p0.x, p0.y, p0.z, p0.w, p1.x, p1.y, p1.z, p1.w, p2.x, p2.y, p2.z, p2.w};
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h) acc[h] = fmaf(pr[h], v, acc[h]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
|
||||
}
|
||||
bool attn_v3_on() {
|
||||
static int on[16] = {}; // by device ordinal: 0 unknown, 1 yes, -1 no
|
||||
static const int env = [] { const char* v = std::getenv("STRATA_ATTN_V3"); return v ? (v[0] == '0' ? 0 : 1) : -1; }();
|
||||
if (env >= 0) return env == 1;
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return false;
|
||||
if (on[dev] == 0) {
|
||||
int maj = 0, mnr = 0;
|
||||
const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
|
||||
cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
|
||||
if (!ok) cudaGetLastError();
|
||||
on[dev] = ok && strata::sm75_default(maj, mnr) ? 1 : -1; // Turing only, with STRATA_SM75_PERF=1
|
||||
}
|
||||
return on[dev] > 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
// PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel
|
||||
// above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk. It
|
||||
// uses more registers (80 vs 38 on sm_70), so on CUDA it runs on cards below sm_75 only, and exists only in the
|
||||
@@ -874,6 +1000,12 @@ void launch_chunks_batch(const float* q, const QsaAttnPools& pools, const int32_
|
||||
(int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
|
||||
}
|
||||
} else
|
||||
#endif
|
||||
#if !defined(__HIPCC__)
|
||||
if (kernel < 0 && kv_mode == 1 && attn_v3_on()) // (the parity harness names its kernel: never the environment)
|
||||
attn_chunk_q8_v3_kernel<<<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_SEL(3, pre)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv,
|
||||
@@ -1061,6 +1193,12 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32
|
||||
const float scale = 1.0f / sqrtf((float) HD);
|
||||
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv);
|
||||
cudaStream_t st = (cudaStream_t) stream;
|
||||
#if !defined(__HIPCC__)
|
||||
if (kv_mode == 1 && attn_v3_on())
|
||||
attn_chunk_q8_v3_kernel<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
|
||||
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
|
||||
else
|
||||
#endif
|
||||
if (kv_mode == 3)
|
||||
STRATA_ATTN_CHUNK(3)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
|
||||
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp.
|
||||
#include "strata/core/emulate.hpp"
|
||||
#include "strata/core/sm75_series.hpp"
|
||||
#include "strata/core/geometry.hpp"
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
@@ -85,7 +86,7 @@ __device__ __forceinline__ uint32_t pack_h2(float lo_k, float hi_k) { // eleme
|
||||
// KV_MODE 4 (Q4_0 K and V, `--kv q4_0`): mode 1 with a scale per 32 values - each q4_0 block's codes enter as exact
|
||||
// int8 (code - 8) and its fp16 scale is applied in FP32, as mode 1's are; the caller rotates q and un-rotates the
|
||||
// output (kv_q4.hpp).
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, bool PF = false>
|
||||
struct Smem {
|
||||
using KElem = typename std::conditional<KV_MODE == 0, __half, int8_t>::type;
|
||||
using VElem = typename std::conditional<KV_MODE == 1 || KV_MODE == 4, int8_t, __half>::type;
|
||||
@@ -94,8 +95,11 @@ struct Smem {
|
||||
static constexpr int NG = KV_MODE == 4 ? HD / QK4_0 : 4; // scale groups per row (q4_0: 8 of 32, else 4 of 64)
|
||||
__half qh[16][QS];
|
||||
__half ql[16][QS];
|
||||
KElem k[CH][KROW];
|
||||
VElem v[CH][VROW];
|
||||
// int8 K/V (mode 1): K is read only by the scores and V only by p.v, so they share one buffer - V is stored over K
|
||||
// after the scores (prompt_attn_kernel). 37.9 -> 29.2 KB: two blocks fit an SM's 64 KB on Turing instead of one.
|
||||
struct Rows { KElem k[CH][KROW]; VElem v[CH][VROW]; };
|
||||
struct SharedRows { union { KElem k[CH][KROW]; VElem v[CH][VROW]; }; };
|
||||
typename std::conditional<KV_MODE == 1 && PF, SharedRows, Rows>::type kv;
|
||||
float ks[CH][NG];
|
||||
float vs[CH][NG];
|
||||
float s[16][CH + 1];
|
||||
@@ -106,14 +110,14 @@ struct Smem {
|
||||
long long row[CH];
|
||||
};
|
||||
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, bool PF = false>
|
||||
__global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __restrict__ q, QsaAttnPools p,
|
||||
const int32_t* __restrict__ ids,
|
||||
const int32_t* __restrict__ steps, int n_kv_heads,
|
||||
int page_size, float scale_log2, float* __restrict__ attn,
|
||||
int cap) {
|
||||
extern __shared__ __align__(16) unsigned char smem_raw[];
|
||||
Smem<KV_MODE>& S = *reinterpret_cast<Smem<KV_MODE>*>(smem_raw);
|
||||
Smem<KV_MODE, PF>& S = *reinterpret_cast<Smem<KV_MODE, PF>*>(smem_raw);
|
||||
const int qi = blockIdx.x, kvh = blockIdx.y;
|
||||
const int n_head = n_kv_heads * G;
|
||||
q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
|
||||
@@ -148,8 +152,51 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
|
||||
|
||||
// int8 K/V: the next chunk's rows are loaded into registers while this chunk computes (Turing has no cp.async, and
|
||||
// at 1 block per SM the gather's latency was the kernel's largest stall), then stored to shared memory exactly as
|
||||
// the gather below stores them: the same bytes in the same places, the same arithmetic after.
|
||||
constexpr bool PREFETCH = KV_MODE == 1 && PF;
|
||||
constexpr int KP = HD / 16; // 16-byte pieces per int8 row
|
||||
constexpr int PPT = PREFETCH ? CH * KP / THREADS : 1; // pieces per thread
|
||||
static_assert(!PREFETCH || (CH * KP) % THREADS == 0 && CH * 4 == THREADS, "prefetch layout");
|
||||
uint4 pk[PPT], pv[PPT];
|
||||
float pa = 0.0f, pb = 0.0f;
|
||||
auto row_of = [&](int c0, int c) -> long long { // as S.row below; -1 past the chunk's cells
|
||||
if (c >= min(CH, n - c0)) return -1;
|
||||
const int cell = ids[c0 + c];
|
||||
const long long page = (long long) p.page_table[cell / page_size];
|
||||
return (page * n_kv_heads + kvh) * page_size + (cell % page_size);
|
||||
};
|
||||
auto fetch = [&](int c0) {
|
||||
if constexpr (PREFETCH) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PPT; ++j) {
|
||||
const int i = t + j * THREADS, c = i / KP, pc = i % KP;
|
||||
const long long r = row_of(c0, c);
|
||||
pk[j] = r >= 0 ? __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc) : make_uint4(0, 0, 0, 0);
|
||||
pv[j] = r >= 0 ? __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc) : make_uint4(0, 0, 0, 0);
|
||||
}
|
||||
const int c = t / 4, g = t % 4;
|
||||
const long long r = row_of(c0, c);
|
||||
pa = r >= 0 ? __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g])) : 0.0f;
|
||||
pb = r >= 0 ? __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g])) : 0.0f;
|
||||
}
|
||||
};
|
||||
if constexpr (PREFETCH) fetch(0);
|
||||
|
||||
for (int c0 = 0; c0 < n; c0 += CH) {
|
||||
const int nh = min(CH, n - c0);
|
||||
if constexpr (PREFETCH) {
|
||||
__syncthreads(); // the previous chunk's p.v is done with k, v, s
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PPT; ++j) {
|
||||
const int i = t + j * THREADS, c = i / KP, pc = i % KP;
|
||||
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.kv.k[c][0]) + pc * 16) = pk[j];
|
||||
}
|
||||
S.ks[t / 4][t % 4] = pa;
|
||||
S.vs[t / 4][t % 4] = pb;
|
||||
__syncthreads();
|
||||
} else {
|
||||
if (t < CH) {
|
||||
long long r = -1;
|
||||
if (t < nh) {
|
||||
@@ -189,7 +236,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
|
||||
__vsub4((w[2] >> 4) & 0x0F0F0F0Fu, 0x08080808u),
|
||||
__vsub4((w[3] >> 4) & 0x0F0F0F0Fu, 0x08080808u));
|
||||
}
|
||||
int8_t* dst = kv == 0 ? &S.k[c][b * QK4_0] : &S.v[c][b * QK4_0];
|
||||
int8_t* dst = kv == 0 ? &S.kv.k[c][b * QK4_0] : &S.kv.v[c][b * QK4_0];
|
||||
reinterpret_cast<uint4*>(dst)[0] = lo;
|
||||
reinterpret_cast<uint4*>(dst)[1] = hi;
|
||||
(kv == 0 ? S.ks : S.vs)[c][b] = d;
|
||||
@@ -206,7 +253,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
|
||||
else // modes 1 and 3: the K side is INT8
|
||||
kx = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc);
|
||||
}
|
||||
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.k[c][0]) + pc * 16) = kx;
|
||||
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.kv.k[c][0]) + pc * 16) = kx;
|
||||
}
|
||||
if constexpr (KV_MODE == 3) { // V: dequantize the row's q4_0 blocks straight into the fp16 V row
|
||||
constexpr int BLKS = HD / QK4_0;
|
||||
@@ -215,14 +262,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
|
||||
const int c = i / BLKS, b = i % BLKS;
|
||||
const long long r = S.row[c];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0);
|
||||
for (int j = 0; j < QK4_0; ++j) S.kv.v[c][b * QK4_0 + j] = __half(0);
|
||||
if (r >= 0) {
|
||||
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + r * BYTES) + b;
|
||||
const float d = __half2float(__ushort_as_half(blk->d));
|
||||
#pragma unroll
|
||||
for (int j = 0; j < QK4_0 / 2; ++j) {
|
||||
S.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d);
|
||||
S.v[c][b * QK4_0 + j + QK4_0 / 2] =
|
||||
S.kv.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d);
|
||||
S.kv.v[c][b * QK4_0 + j + QK4_0 / 2] =
|
||||
__float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d);
|
||||
}
|
||||
}
|
||||
@@ -239,7 +286,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
|
||||
else
|
||||
vx = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + pc);
|
||||
}
|
||||
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.v[c][0]) + pc * 16) = vx;
|
||||
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.kv.v[c][0]) + pc * 16) = vx;
|
||||
}
|
||||
}
|
||||
for (int i = t; i < CH * 4; i += THREADS) {
|
||||
@@ -262,6 +309,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
// scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per scale group (64 dims; q4_0's 32)
|
||||
constexpr int NG = Smem<KV_MODE>::NG, KPG = HD / 16 / NG; // groups per row, 16-dim MMA steps per group
|
||||
#pragma unroll
|
||||
@@ -284,11 +332,11 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
|
||||
al[2] = *reinterpret_cast<const uint32_t*>(&S.ql[gid][k0 + 2 * tig + 8]);
|
||||
al[3] = *reinterpret_cast<const uint32_t*>(&S.ql[gid + 8][k0 + 2 * tig + 8]);
|
||||
if constexpr (KV_MODE != 0) { // modes 1 and 3: the K side is INT8 codes
|
||||
b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.k[cb + gid][k0 + 2 * tig]));
|
||||
b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.k[cb + gid][k0 + 2 * tig + 8]));
|
||||
b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.kv.k[cb + gid][k0 + 2 * tig]));
|
||||
b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.kv.k[cb + gid][k0 + 2 * tig + 8]));
|
||||
} else {
|
||||
b[0] = *reinterpret_cast<const uint32_t*>(&S.k[cb + gid][k0 + 2 * tig]);
|
||||
b[1] = *reinterpret_cast<const uint32_t*>(&S.k[cb + gid][k0 + 2 * tig + 8]);
|
||||
b[0] = *reinterpret_cast<const uint32_t*>(&S.kv.k[cb + gid][k0 + 2 * tig]);
|
||||
b[1] = *reinterpret_cast<const uint32_t*>(&S.kv.k[cb + gid][k0 + 2 * tig + 8]);
|
||||
}
|
||||
mma16816(tg, ah, b);
|
||||
#ifndef D1_NO_QLO
|
||||
@@ -308,6 +356,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
|
||||
S.s[gid + 8][c + 1] = c + 1 < nh ? sc[3] * qdown : -INFINITY;
|
||||
}
|
||||
__syncthreads();
|
||||
if constexpr (PREFETCH) { // the scores are done with K: V goes over it (read after the softmax's barrier)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PPT; ++j) {
|
||||
const int i = t + j * THREADS, c = i / KP, pc = i % KP;
|
||||
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.kv.v[c][0]) + pc * 16) = pv[j];
|
||||
}
|
||||
if (c0 + CH < n) fetch(c0 + CH); // the next chunk's rows, in flight while this one finishes
|
||||
}
|
||||
// online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp)
|
||||
{
|
||||
constexpr int PER = CH / 8;
|
||||
@@ -385,13 +441,13 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __res
|
||||
const int d = warp * 64 + j * 8 + gid;
|
||||
uint32_t b[2];
|
||||
if constexpr (KV_MODE == 1 || KV_MODE == 4) {
|
||||
const uint32_t x0 = (uint8_t) S.v[cA][d] | ((uint32_t) (uint8_t) S.v[cA + 1][d] << 8);
|
||||
const uint32_t x1 = (uint8_t) S.v[cB][d] | ((uint32_t) (uint8_t) S.v[cB + 1][d] << 8);
|
||||
const uint32_t x0 = (uint8_t) S.kv.v[cA][d] | ((uint32_t) (uint8_t) S.kv.v[cA + 1][d] << 8);
|
||||
const uint32_t x1 = (uint8_t) S.kv.v[cB][d] | ((uint32_t) (uint8_t) S.kv.v[cB + 1][d] << 8);
|
||||
b[0] = i8x2_to_h2(x0);
|
||||
b[1] = i8x2_to_h2(x1);
|
||||
} else {
|
||||
const __half2 h0 = __halves2half2(S.v[cA][d], S.v[cA + 1][d]);
|
||||
const __half2 h1 = __halves2half2(S.v[cB][d], S.v[cB + 1][d]);
|
||||
const __half2 h0 = __halves2half2(S.kv.v[cA][d], S.kv.v[cA + 1][d]);
|
||||
const __half2 h1 = __halves2half2(S.kv.v[cB][d], S.kv.v[cB + 1][d]);
|
||||
b[0] = *reinterpret_cast<const uint32_t*>(&h0);
|
||||
b[1] = *reinterpret_cast<const uint32_t*>(&h1);
|
||||
}
|
||||
@@ -441,13 +497,27 @@ struct Smem2 {
|
||||
float lsum[16];
|
||||
float mrow[16];
|
||||
};
|
||||
// Turing (register staging): one stage - the next chunk's pieces wait in registers until this chunk's p.v is done -
|
||||
// and the q.k partials of cell group nt (8 cells) in the 512 bytes of the warp's own K slice that held those cells
|
||||
// (read by then), so a block takes ~19.7 KB and three fit a Turing SM (one did, at 45.6 KB: four warps on four
|
||||
// schedulers, every latency exposed)
|
||||
struct Smem2T {
|
||||
int8_t kv[1][4][2][CH2][64];
|
||||
float sc[1][4][2][CH2];
|
||||
float p[16][CH2 + 1];
|
||||
float qmax[4];
|
||||
float alpha[16];
|
||||
float lsum[16];
|
||||
float mrow[16];
|
||||
};
|
||||
|
||||
__device__ __forceinline__ int swz(int cell, int byte) { // byte offset of (cell, byte) in a stage slice
|
||||
return cell * 64 + ((((byte >> 4) ^ (cell >> 1)) & 3) << 4) + (byte & 15);
|
||||
}
|
||||
__device__ __forceinline__ void cp_async16(void* smem, const void* gmem, bool valid) {
|
||||
#if !STRATA_PA_SM80
|
||||
__trap();
|
||||
(void) smem; (void) gmem; (void) valid;
|
||||
__trap(); // not reached on Turing (the register-staged pipeline replaces it there)
|
||||
#else
|
||||
const unsigned sa = (unsigned) __cvta_generic_to_shared(smem);
|
||||
asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(sa), "l"(gmem), "r"(valid ? 16 : 0));
|
||||
@@ -470,7 +540,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
|
||||
int page_size, float scale_log2,
|
||||
float* __restrict__ attn, int cap) {
|
||||
extern __shared__ __align__(16) unsigned char smem_raw[];
|
||||
#if STRATA_PA_SM80
|
||||
Smem2& S = *reinterpret_cast<Smem2*>(smem_raw);
|
||||
#define PA2_PART(w, r, c) S.part[w][r][c]
|
||||
#else
|
||||
Smem2T& S = *reinterpret_cast<Smem2T*>(smem_raw);
|
||||
// the partial of (row r, cell c) of warp w: cell group c / 8's 512 bytes of w's K slice, [row][cell % 8]
|
||||
#define PA2_PART(w, r, c) reinterpret_cast<const float*>(&S.kv[0][w][0][0][0])[((c) >> 3) * 128 + (r) * 8 + ((c) & 7)]
|
||||
#endif
|
||||
const int qi = blockIdx.x, kvh = blockIdx.y;
|
||||
const int n_head = n_kv_heads * G;
|
||||
q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
|
||||
@@ -519,6 +596,19 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
|
||||
const long long page = (long long) __ldg(p.page_table + cell / page_size);
|
||||
return (page * n_kv_heads + kvh) * page_size + (cell % page_size);
|
||||
};
|
||||
#if !STRATA_PA_SM80
|
||||
// Turing (no cp.async): the warp's next pieces wait in registers and are stored into their stage after this
|
||||
// chunk's p.v (store_stage) - the same bytes in the same places as the cp.async pipeline
|
||||
uint4 rk[4], rv[4];
|
||||
auto store_stage = [&](int st) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3;
|
||||
*reinterpret_cast<uint4*>(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16)) = rk[j];
|
||||
*reinterpret_cast<uint4*>(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16)) = rv[j];
|
||||
}
|
||||
};
|
||||
#endif
|
||||
auto issue = [&](long long r, int st, float& ksr, float& vsr) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
@@ -526,8 +616,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
|
||||
const long long rr = __shfl_sync(0xffffffffu, r, cell);
|
||||
const bool ok = rr >= 0;
|
||||
const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0;
|
||||
#if STRATA_PA_SM80
|
||||
cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok);
|
||||
cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok);
|
||||
#else
|
||||
(void) st;
|
||||
rk[j] = ok ? __ldg(reinterpret_cast<const uint4*>(p.k_q + off)) : make_uint4(0, 0, 0, 0);
|
||||
rv[j] = ok ? __ldg(reinterpret_cast<const uint4*>(p.v_q + off)) : make_uint4(0, 0, 0, 0);
|
||||
#endif
|
||||
}
|
||||
ksr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.k_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;
|
||||
vsr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.v_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;
|
||||
@@ -535,6 +631,9 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
|
||||
float ksn, vsn;
|
||||
issue(row_of(cell_of(lane)), 0, ksn, vsn);
|
||||
cp_async_commit();
|
||||
#if !STRATA_PA_SM80
|
||||
store_stage(0);
|
||||
#endif
|
||||
S.sc[0][warp][0][lane] = ksn;
|
||||
S.sc[0][warp][1][lane] = vsn;
|
||||
long long r_next = row_of(cell_of(CH2 + lane));
|
||||
@@ -545,9 +644,13 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
|
||||
for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
|
||||
|
||||
for (int ci = 0; ci < n_chunks; ++ci) {
|
||||
const int st = ci & 1, c0 = ci * CH2;
|
||||
#if STRATA_PA_SM80
|
||||
const int st = ci & 1, nst = st ^ 1, c0 = ci * CH2;
|
||||
#else
|
||||
const int st = 0, nst = 0, c0 = ci * CH2;
|
||||
#endif
|
||||
const bool more = ci + 1 < n_chunks;
|
||||
if (more) issue(r_next, st ^ 1, ksn, vsn);
|
||||
if (more) issue(r_next, nst, ksn, vsn);
|
||||
cp_async_commit();
|
||||
r_next = row_of(cell_next2);
|
||||
cell_next2 = cell_of((ci + 3) * CH2 + lane);
|
||||
@@ -570,10 +673,19 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
|
||||
}
|
||||
const int c = nt * 8 + 2 * tig;
|
||||
const float s0 = S.sc[st][warp][0][c], s1 = S.sc[st][warp][0][c + 1];
|
||||
#if STRATA_PA_SM80
|
||||
S.part[warp][gid][c] = tg[0] * s0;
|
||||
S.part[warp][gid][c + 1] = tg[1] * s1;
|
||||
S.part[warp][gid + 8][c] = tg[2] * s0;
|
||||
S.part[warp][gid + 8][c + 1] = tg[3] * s1;
|
||||
#else
|
||||
__syncwarp(); // every lane has read the group's cells: their 512 bytes take its partials
|
||||
float* pp = reinterpret_cast<float*>(&S.kv[0][warp][0][0][0]) + nt * 128;
|
||||
pp[gid * 8 + 2 * tig] = tg[0] * s0;
|
||||
pp[gid * 8 + 2 * tig + 1] = tg[1] * s1;
|
||||
pp[(gid + 8) * 8 + 2 * tig] = tg[2] * s0;
|
||||
pp[(gid + 8) * 8 + 2 * tig + 1] = tg[3] * s1;
|
||||
#endif
|
||||
}
|
||||
__syncthreads();
|
||||
// online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread
|
||||
@@ -583,7 +695,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
const int c = sub * 4 + j;
|
||||
x[j] = c0 + c < n ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown
|
||||
x[j] = c0 + c < n ? (((PA2_PART(0, r, c) + PA2_PART(1, r, c)) + PA2_PART(2, r, c)) + PA2_PART(3, r, c)) * qdown
|
||||
: -INFINITY;
|
||||
mx = fmaxf(mx, x[j]);
|
||||
}
|
||||
@@ -662,8 +774,11 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
|
||||
}
|
||||
}
|
||||
if (more) {
|
||||
S.sc[st ^ 1][warp][0][lane] = ksn;
|
||||
S.sc[st ^ 1][warp][1][lane] = vsn;
|
||||
S.sc[nst][warp][0][lane] = ksn;
|
||||
S.sc[nst][warp][1][lane] = vsn;
|
||||
#if !STRATA_PA_SM80
|
||||
store_stage(nst);
|
||||
#endif
|
||||
}
|
||||
__syncwarp();
|
||||
}
|
||||
@@ -679,6 +794,7 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __
|
||||
}
|
||||
}
|
||||
|
||||
#undef PA2_PART
|
||||
__global__ void __launch_bounds__(THREADS) decode_attn_i8_split_kernel(const float* __restrict__ q, QsaAttnPools p,
|
||||
const int32_t* __restrict__ ids,
|
||||
const int32_t* __restrict__ steps, int n_kv_heads,
|
||||
@@ -927,10 +1043,16 @@ __global__ void __launch_bounds__(HD) decode_attn_merge_kernel(const float* __re
|
||||
bool launch_i8(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, cudaStream_t st) {
|
||||
static bool attr[64] = {}; // the shared-memory opt-in is per device (a layer split runs this on several)
|
||||
static int t75[64] = {}; // 1: Turing (the kernel's single-stage layout, Smem2T), 2: not
|
||||
int dev = 0;
|
||||
cudaGetDevice(&dev);
|
||||
const int bytes = (int) sizeof(Smem2);
|
||||
if (dev < 0 || dev >= 64) return false;
|
||||
if (!t75[dev]) {
|
||||
int major = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
t75[dev] = strata::cc_major_of(major) < 8 ? 1 : 2; // STRATA_EMULATE_CC counts
|
||||
}
|
||||
const int bytes = (int) (t75[dev] == 1 ? sizeof(Smem2T) : sizeof(Smem2));
|
||||
if (!attr[dev]) {
|
||||
if (cudaFuncSetAttribute(prompt_attn_i8_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
cudaSuccess) {
|
||||
@@ -1302,16 +1424,16 @@ bool launch_i8v3(const float* q, const QsaAttnPools& pools, const int32_t* ids,
|
||||
return true;
|
||||
}
|
||||
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, bool PF = false>
|
||||
bool launch(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, cudaStream_t st) {
|
||||
static bool attr[64] = {}; // per device, as above
|
||||
int dev = 0;
|
||||
cudaGetDevice(&dev);
|
||||
const int bytes = (int) sizeof(Smem<KV_MODE>);
|
||||
const int bytes = (int) sizeof(Smem<KV_MODE, PF>);
|
||||
if (dev < 0 || dev >= 64) return false;
|
||||
if (!attr[dev]) {
|
||||
if (cudaFuncSetAttribute(prompt_attn_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
if (cudaFuncSetAttribute(prompt_attn_kernel<KV_MODE, PF>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
return false;
|
||||
@@ -1321,7 +1443,7 @@ bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const
|
||||
const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
|
||||
for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
|
||||
const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
|
||||
prompt_attn_kernel<KV_MODE><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
|
||||
prompt_attn_kernel<KV_MODE, PF><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
|
||||
q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
|
||||
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
|
||||
}
|
||||
@@ -2132,7 +2254,7 @@ void qsa_prompt_attn_set_imma(int on) { g_pa_imma = on < 0 ? -1 : (on ? 1 : 0);
|
||||
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;
|
||||
bool volta = false, turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards)
|
||||
bool volta = false, turing = false, t75 = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards)
|
||||
{ // sm_75 or newer: the MMA above compiles for both. sm_80+ runs the cp.async kernel (launch_i8); Turing has
|
||||
// no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order). An older card
|
||||
// keeps the old kernel.
|
||||
@@ -2158,6 +2280,7 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
if (cc[dev] < 70) return false;
|
||||
volta = cc[dev] < 75; // sm_70: the m8n8k4 kernel (STRATA_PA_VOLTA); STRATA_QSA_WARP=1 still forces the old one
|
||||
turing = cc[dev] < 80;
|
||||
t75 = cc[dev] == 75; // a Turing card, or one run as such (STRATA_EMULATE_CC=75, STRATA_QSA_WARP=1)
|
||||
}
|
||||
#if defined(__HIPCC__)
|
||||
// the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV
|
||||
@@ -2177,8 +2300,13 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4");
|
||||
return v != nullptr && v[0] == '0';
|
||||
}();
|
||||
// sm_80+ only: on Turing mode 4 would run as pairs of m16n8k8 MMAs, which no parity run has checked yet
|
||||
if (q4_off || turing || pools.v_q4 == nullptr) return false;
|
||||
// Turing runs mode 4 as pairs of m16n8k8 MMAs (another summation order than the FP32 kernel it replaces): manual
|
||||
// opt-in STRATA_PROMPT_ATTN_Q4_TC=1 (#1581, c3c: qsa_prompt_attn_parity at 4096/512 and 1500/512 on an RTX 2080 Super).
|
||||
static const bool q4_tc = [] {
|
||||
const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4_TC");
|
||||
return v != nullptr && v[0] == '1';
|
||||
}();
|
||||
if (q4_off || volta || (turing && !q4_tc) || pools.v_q4 == nullptr) return false;
|
||||
return launch<4>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
}
|
||||
if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 V
|
||||
@@ -2193,13 +2321,22 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
// exist before sm_80.
|
||||
static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;
|
||||
if (volta) return launch70<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
if (v1 || turing) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
// Turing: v2 with register staging instead of cp.async, opt-in (STRATA_PA_V2T=1) until measured
|
||||
static const bool v2t = [] { const char* e = std::getenv("STRATA_PA_V2T"); return e != nullptr && e[0] == '1'; }();
|
||||
if (v1 || (turing && !v2t)) {
|
||||
// #1821 (xrip): v1 with the next chunk's rows prefetched in registers and K/V sharing one buffer (two blocks an
|
||||
// SM), the same bits. STRATA_PA_V1_PREFETCH=0 / 1 forces it off / on; unset: a Turing card with
|
||||
// STRATA_SM75_PERF=1.
|
||||
static const int pf_env = [] { const char* e = std::getenv("STRATA_PA_V1_PREFETCH"); return e ? (std::atoi(e) != 0 ? 1 : 0) : -1; }();
|
||||
if (pf_env == 1 || (pf_env < 0 && t75 && strata::sm75_series())) return launch<1, true>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
}
|
||||
// STRATA_PROMPT_ATTN_IMMA=1 (opt-in, sm_80+): both products on INT8 tensor cores (prompt_attn_i8v3_kernel)
|
||||
if (g_pa_imma < 0) {
|
||||
const char* v = std::getenv("STRATA_PROMPT_ATTN_IMMA");
|
||||
g_pa_imma = v != nullptr && v[0] == '1' ? 1 : 0;
|
||||
}
|
||||
if (g_pa_imma == 1) return launch_i8v3(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
if (g_pa_imma == 1 && !turing) return launch_i8v3(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
}
|
||||
if (!pools.k_pool || !pools.v_pool) return false;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp.
|
||||
#include "strata/core/emulate.hpp"
|
||||
#include "strata/core/sm75_series.hpp"
|
||||
#include "strata/core/geometry.hpp"
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
@@ -596,6 +597,102 @@ static bool block_scores_simt(const float* pooled, const float* dead, const floa
|
||||
return true;
|
||||
}
|
||||
|
||||
// block_scores_simt_kernel with larger tiles (QT queries x NB blocks, RI x CJ products per thread) and the next K
|
||||
// chunk's loads in registers while the current one is used. Every (row, block) dot is the same fmaf chain over
|
||||
// k = 0..127 from 0, and the relu sum over the heads in the same order: the same bits as block_scores_simt_kernel.
|
||||
// STRATA_SELECT_SIMT=2.
|
||||
constexpr int S2_KC = 32;
|
||||
template <int QT, int NB>
|
||||
__global__ void __launch_bounds__(256, 1) block_scores_simt2_kernel(const float* __restrict__ pooled,
|
||||
const float* __restrict__ q_idx,
|
||||
const int32_t* __restrict__ steps, int64_t nq,
|
||||
int64_t max_blocks, int64_t reach,
|
||||
float* __restrict__ out) {
|
||||
constexpr int ROWS = QT * IDX_HEADS, RI = ROWS / 16, CJ = NB / 16, QS = ROWS + 4, KS = NB + 4;
|
||||
constexpr int QL = ROWS * S2_KC / 4 / 256, KL = NB * S2_KC / 4 / 256; // float4 loads per thread
|
||||
static_assert(RI % 4 == 0 && CJ % 4 == 0 && QL >= 1 && KL >= 1, "tile");
|
||||
__shared__ __align__(16) float Qs[S2_KC][QS];
|
||||
__shared__ __align__(16) float Ks[S2_KC][KS];
|
||||
const int64_t q0 = (int64_t) blockIdx.y * QT, b0 = (int64_t) blockIdx.x * NB;
|
||||
const int64_t qlast = (q0 + QT < nq ? q0 + QT : nq) - 1;
|
||||
if (b0 >= steps[qlast * kStepCount + kStepNBid]) return; // n_bid rises with the position
|
||||
const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4;
|
||||
float acc[RI][CJ];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RI; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CJ; ++j) acc[i][j] = 0.0f;
|
||||
float4 qv[QL], kv[KL];
|
||||
auto load = [&](int kc) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < QL; ++i) {
|
||||
const int idx = tid + i * 256, r = idx >> 3, k4 = idx & 7;
|
||||
qv[i] = make_float4(0.f, 0.f, 0.f, 0.f);
|
||||
if (q0 + (r >> 2) < nq)
|
||||
qv[i] = *reinterpret_cast<const float4*>(q_idx + (q0 * IDX_HEADS + r) * IDX_DIM + kc + k4 * 4);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < KL; ++i) {
|
||||
const int idx = tid + i * 256, c = idx >> 3, k4 = idx & 7;
|
||||
kv[i] = make_float4(0.f, 0.f, 0.f, 0.f);
|
||||
if (b0 + c < reach) kv[i] = *reinterpret_cast<const float4*>(pooled + (b0 + c) * IDX_DIM + kc + k4 * 4);
|
||||
}
|
||||
};
|
||||
load(0);
|
||||
#pragma unroll 1
|
||||
for (int kc = 0; kc < IDX_DIM; kc += S2_KC) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < QL; ++i) {
|
||||
const int idx = tid + i * 256, r = idx >> 3, k4 = idx & 7;
|
||||
Qs[k4 * 4 + 0][r] = qv[i].x; Qs[k4 * 4 + 1][r] = qv[i].y; Qs[k4 * 4 + 2][r] = qv[i].z; Qs[k4 * 4 + 3][r] = qv[i].w;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < KL; ++i) {
|
||||
const int idx = tid + i * 256, c = idx >> 3, k4 = idx & 7;
|
||||
Ks[k4 * 4 + 0][c] = kv[i].x; Ks[k4 * 4 + 1][c] = kv[i].y; Ks[k4 * 4 + 2][c] = kv[i].z; Ks[k4 * 4 + 3][c] = kv[i].w;
|
||||
}
|
||||
__syncthreads();
|
||||
if (kc + S2_KC < IDX_DIM) load(kc + S2_KC); // in flight during this chunk's products
|
||||
#pragma unroll 4
|
||||
for (int k = 0; k < S2_KC; ++k) {
|
||||
float qr[RI], kr[CJ];
|
||||
#pragma unroll
|
||||
for (int m = 0; m < RI / 4; ++m) {
|
||||
const float4 a = *reinterpret_cast<const float4*>(&Qs[k][ty * RI + 4 * m]);
|
||||
qr[4 * m] = a.x; qr[4 * m + 1] = a.y; qr[4 * m + 2] = a.z; qr[4 * m + 3] = a.w;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int g = 0; g < CJ / 4; ++g) {
|
||||
const float4 b = *reinterpret_cast<const float4*>(&Ks[k][g * 64 + tx * 4]);
|
||||
kr[4 * g] = b.x; kr[4 * g + 1] = b.y; kr[4 * g + 2] = b.z; kr[4 * g + 3] = b.w;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < RI; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CJ; ++j) acc[i][j] = fmaf(qr[i], kr[j], acc[i][j]);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
#pragma unroll
|
||||
for (int qi = 0; qi < RI / 4; ++qi) {
|
||||
const int64_t q = q0 + ty * (RI / 4) + qi;
|
||||
if (q >= nq) continue;
|
||||
const int64_t n_bid = steps[q * kStepCount + kStepNBid];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CJ; ++j) {
|
||||
const int64_t b = b0 + (j >> 2) * 64 + tx * 4 + (j & 3);
|
||||
if (b >= n_bid || b >= max_blocks) continue;
|
||||
float sc = 0.0f;
|
||||
#pragma unroll
|
||||
for (int h = 0; h < IDX_HEADS; ++h) {
|
||||
const float d = acc[qi * 4 + h][j];
|
||||
sc += d > 0.0f ? d : 0.0f;
|
||||
}
|
||||
out[q * max_blocks + b] = sc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the same top-k with each query's keys read once: 1,024 threads hold up to TK_PER consecutive blocks' keys in
|
||||
// registers (contexts up to 4 * 1024 * TK_PER cells), per-warp histograms, block-wide scans. The selection rule is
|
||||
// block_topk_kernel's (radix threshold, ties to the lowest index, cells ascending): identical ids.
|
||||
@@ -754,9 +851,13 @@ __global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __res
|
||||
// lowest index): identical ids.
|
||||
// campaign3: also compiled on HIP (gfx11: plain shared/atomic code, no sm_90 features; the dispatch still needs
|
||||
// reach > fit, i.e. the deep contexts where the ref radix was the only option on AMD).
|
||||
constexpr int TS_MAXQ = 4096;
|
||||
__device__ int g_tk_fail[TS_MAXQ]; // block_topk_sample_kernel: 1 = the query is block_topk_wide_kernel<true>'s
|
||||
template <bool ONLY_FAILED = false>
|
||||
__global__ void __launch_bounds__(TK_T) block_topk_wide_kernel(const float* __restrict__ scores,
|
||||
const int32_t* __restrict__ steps, int64_t max_blocks,
|
||||
int64_t cap, int32_t* __restrict__ ids) {
|
||||
if (ONLY_FAILED && !g_tk_fail[blockIdx.x]) return;
|
||||
__shared__ int hist[TK_T / 32][256];
|
||||
__shared__ int s_gt[TK_T / 32], s_eq[TK_T / 32];
|
||||
__shared__ int s_digit, s_above;
|
||||
@@ -1136,6 +1237,91 @@ int scores_thread_arch() {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
// ---- prompt calls on cards without the tensor-core scorer (Turing): block_scores_kernel's scores, BITWISE, with a
|
||||
// thread per (query, head) instead of a warp per (query, block). There a warp spends 20 shuffles and five 512-byte
|
||||
// loads per score; here a lane holds its query head (128 floats) in registers, every lane of the warp reads the same
|
||||
// key from shared memory (a broadcast), and the 4-value partials are added in the tree lane 0 of the xor-shuffle sum
|
||||
// computes: partial g covers values 4g..4g+3, level o adds g and g + o. Float addition is commutative, so the same
|
||||
// pairs in the same tree give the same bits. The heads are then summed 0..3 from 0.0f as there. Blocks < n_bid only:
|
||||
// the tail block n_bid (the `dead` key, +1e9) is block_scores_tail_kernel's.
|
||||
constexpr int TS_Q = 64; // queries per CTA (8 per warp, a lane per query head)
|
||||
constexpr int TS_KB = 32; // key blocks per shared-memory tile
|
||||
constexpr int TS_BR = 512; // key blocks per CTA
|
||||
|
||||
__device__ __forceinline__ float ts_part(const float4 k4, const float4 q4) {
|
||||
return k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; // block_scores_kernel's per-lane expression
|
||||
}
|
||||
|
||||
__global__ void __launch_bounds__(256, 1) block_scores_thread_kernel(const float* __restrict__ pooled,
|
||||
const float* __restrict__ q_idx,
|
||||
const int32_t* __restrict__ steps, int64_t nq,
|
||||
int64_t max_blocks, int64_t reach,
|
||||
float* __restrict__ out) {
|
||||
__shared__ __align__(16) float4 ks[TS_KB][IDX_DIM / 4];
|
||||
__shared__ float so[TS_Q][TS_KB + 1];
|
||||
__shared__ int64_t s_nbid[TS_Q];
|
||||
// Four lanes per query, lane j (0..3) one quarter of the tree for all four heads: the partials c[j] of lane 0's
|
||||
// xor-shuffle sum combine groups j, j+16, j+8, j+24, j+4, j+20, j+12, j+28, and only then do the quarters meet
|
||||
// (c0 + c2, c1 + c3, then their sum) - two shuffles here. A key load now feeds four heads: four times fewer
|
||||
// shared-memory loads per FMA (the kernel was bound by the MIO pipe, ncu: mio_throttle first).
|
||||
constexpr int QG[8] = {0, 16, 8, 24, 4, 20, 12, 28};
|
||||
const int t = threadIdx.x, lane = t & 31;
|
||||
const int ql = (t >> 5) * 8 + (lane >> 2), j4 = lane & 3; // this lane's query (in the CTA) and quarter
|
||||
const int64_t q0 = (int64_t) blockIdx.y * TS_Q, qi = q0 + ql;
|
||||
if (t < TS_Q) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : -1;
|
||||
float4 qv[IDX_HEADS][8];
|
||||
{
|
||||
const float4* src = reinterpret_cast<const float4*>(q_idx + (qi < nq ? qi : 0) * IDX_HEADS * IDX_DIM);
|
||||
#pragma unroll
|
||||
for (int h = 0; h < IDX_HEADS; ++h)
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 8; ++m) qv[h][m] = src[h * (IDX_DIM / 4) + j4 + QG[m]];
|
||||
}
|
||||
__syncthreads();
|
||||
int64_t top = -1; // the largest n_bid of the CTA's queries: blocks at or past it are never written here
|
||||
for (int i = 0; i < TS_Q; ++i) top = s_nbid[i] > top ? s_nbid[i] : top;
|
||||
const int64_t b_lo = (int64_t) blockIdx.x * TS_BR;
|
||||
int64_t b_hi = b_lo + TS_BR;
|
||||
if (b_hi > reach) b_hi = reach;
|
||||
if (b_hi > top) b_hi = top;
|
||||
if (b_hi > max_blocks) b_hi = max_blocks;
|
||||
for (int64_t b0 = b_lo; b0 < b_hi; b0 += TS_KB) {
|
||||
const int nb = (int) (b_hi - b0 < TS_KB ? b_hi - b0 : TS_KB);
|
||||
__syncthreads(); // the previous tile's reads of ks and so are done
|
||||
for (int i = t; i < nb * (IDX_DIM / 4); i += blockDim.x)
|
||||
ks[i / (IDX_DIM / 4)][i % (IDX_DIM / 4)] = reinterpret_cast<const float4*>(pooled + (b0 + i / (IDX_DIM / 4)) * IDX_DIM)[i % (IDX_DIM / 4)];
|
||||
__syncthreads();
|
||||
for (int j = 0; j < nb; ++j) {
|
||||
float4 kk[8];
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 8; ++m) kk[m] = ks[j][j4 + QG[m]];
|
||||
float e[IDX_HEADS];
|
||||
#pragma unroll
|
||||
for (int h = 0; h < IDX_HEADS; ++h) {
|
||||
const float c = ((ts_part(kk[0], qv[h][0]) + ts_part(kk[1], qv[h][1])) +
|
||||
(ts_part(kk[2], qv[h][2]) + ts_part(kk[3], qv[h][3]))) +
|
||||
((ts_part(kk[4], qv[h][4]) + ts_part(kk[5], qv[h][5])) +
|
||||
(ts_part(kk[6], qv[h][6]) + ts_part(kk[7], qv[h][7])));
|
||||
const float d = c + __shfl_xor_sync(0xffffffffu, c, 2); // lane 0: c0 + c2, lane 1: c1 + c3
|
||||
e[h] = d + __shfl_xor_sync(0xffffffffu, d, 1); // lane 0: (c0 + c2) + (c1 + c3)
|
||||
}
|
||||
if (j4 == 0) {
|
||||
float score = 0.0f;
|
||||
#pragma unroll
|
||||
for (int h = 0; h < IDX_HEADS; ++h) score += e[h] > 0.0f ? e[h] : 0.0f;
|
||||
so[ql][j] = score;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
for (int i = t; i < TS_Q * nb; i += blockDim.x) {
|
||||
const int q = i / nb, j = i % nb;
|
||||
if (b0 + j < s_nbid[q]) out[(q0 + q) * max_blocks + b0 + j] = so[q][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
// ---- the decode top-k on a thread-block cluster (sm_90+; S19). One CTA per query (block_topk_reg_kernel, or
|
||||
// block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to
|
||||
@@ -1390,6 +1576,136 @@ bool qsa_block_scores_slots(const float* const* pooled, const float* const* dead
|
||||
return true;
|
||||
}
|
||||
|
||||
// block_scores_multi_kernel with the warp sums as one recursive-halving reduction. A (query, head) dot is a lane's
|
||||
// 4-term product summed over the 32 lanes by an xor butterfly (offsets 16, 8, 4, 2, 1): 5 shuffles per value, 20 per
|
||||
// (block, query) - on Turing the decode scorer's time grew with the window's queries (420K cells: 117 / 265 / 509 us
|
||||
// for 1 / 3 / 6 queries), the shuffles, not the keys. Here the V = 4 x queries values (padded to a power of 2) are
|
||||
// reduced together: at offset o each lane keeps half of its values and adds its partner's copy of them - the pair
|
||||
// (lane l, lane l ^ o) the butterfly adds for that value at that offset, so every value's additions are the
|
||||
// butterfly's, operand for operand (float addition commutes): the same bits, with V - 1 shuffles plus the plain
|
||||
// butterfly's remaining stages instead of 5 V. Lane l ends with value (l >> (5 - log2 V)); the query's 4 heads are
|
||||
// then gathered by its head-0 lane and summed in block_scores_multi_kernel's order. STRATA_SCORES_HALVE=0: the old kernel.
|
||||
template <int V>
|
||||
__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_halve_kernel(const float* __restrict__ pooled,
|
||||
const float* __restrict__ dead,
|
||||
const float* __restrict__ q_idx,
|
||||
const int32_t* __restrict__ steps, int nq,
|
||||
int64_t max_blocks, float* __restrict__ out) {
|
||||
constexpr int NQ = V / IDX_HEADS; // query slots (nq <= NQ)
|
||||
constexpr int LV = V == 4 ? 2 : V == 8 ? 3 : V == 16 ? 4 : 5, SH = 5 - LV;
|
||||
static_assert(V == 4 || V == 8 || V == 16 || V == 32, "V");
|
||||
__shared__ __align__(16) float qs[NQ * IDX_HEADS * IDX_DIM];
|
||||
__shared__ int64_t s_nkv[NQ], s_nbid[NQ];
|
||||
if (threadIdx.x < NQ) {
|
||||
s_nkv[threadIdx.x] = threadIdx.x < nq ? steps[threadIdx.x * kStepCount + kStepNKv] : 0;
|
||||
s_nbid[threadIdx.x] = threadIdx.x < nq ? steps[threadIdx.x * kStepCount + kStepNBid] : -1;
|
||||
}
|
||||
__syncthreads();
|
||||
int64_t top = 0;
|
||||
for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top;
|
||||
if ((int64_t) blockIdx.x * SCORE_WARPS > top) return; // CTA-uniform (as block_scores_multi_kernel's early exit)
|
||||
for (int i = threadIdx.x; i < NQ * IDX_HEADS * IDX_DIM; i += blockDim.x)
|
||||
qs[i] = i < nq * IDX_HEADS * IDX_DIM ? q_idx[i] : 0.0f;
|
||||
__syncthreads();
|
||||
const int lane = threadIdx.x & 31;
|
||||
const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS;
|
||||
const float4 kd = *reinterpret_cast<const float4*>(dead + lane * 4);
|
||||
// up to 4 queries: the lane's query values in registers (read once, not once per block from shared memory: the
|
||||
// shared-memory reads were the kernel's limit, ncu mio_throttle)
|
||||
constexpr bool QREG = V <= 16;
|
||||
float4 qr[QREG ? V : 1];
|
||||
if constexpr (QREG) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < V; ++i) qr[i] = *reinterpret_cast<const float4*>(qs + (i >> 2) * IDX_HEADS * IDX_DIM + (i & 3) * IDX_DIM + lane * 4);
|
||||
}
|
||||
int s_nbid_r[NQ]; // n_bid < 2^31
|
||||
#pragma unroll
|
||||
for (int qi = 0; qi < NQ; ++qi) s_nbid_r[qi] = (int) s_nbid[qi];
|
||||
for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) {
|
||||
const float4 kp = *reinterpret_cast<const float4*>(pooled + b * IDX_DIM + lane * 4);
|
||||
float v[V];
|
||||
#pragma unroll
|
||||
for (int qi = 0; qi < NQ; ++qi) {
|
||||
const float4 k4 = (b == s_nbid_r[qi]) ? kd : kp;
|
||||
const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4;
|
||||
#pragma unroll
|
||||
for (int h = 0; h < IDX_HEADS; ++h) {
|
||||
float4 q4;
|
||||
if constexpr (QREG) q4 = qr[qi * IDX_HEADS + h];
|
||||
else q4 = *reinterpret_cast<const float4*>(q + h * IDX_DIM);
|
||||
v[qi * IDX_HEADS + h] = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;
|
||||
}
|
||||
}
|
||||
// recursive halving over offsets 16, 8, ... while more than one value is left, then the plain butterfly
|
||||
int cnt = V;
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) {
|
||||
if (cnt > 1) {
|
||||
const int half = cnt >> 1;
|
||||
const bool hi = (lane & o) != 0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < V / 2; ++i) {
|
||||
if (i < half) {
|
||||
const float send = hi ? v[i] : v[i + half];
|
||||
const float keep = hi ? v[i + half] : v[i];
|
||||
const float recv = __shfl_xor_sync(0xffffffffu, send, o);
|
||||
v[i] = keep + recv;
|
||||
}
|
||||
}
|
||||
cnt = half;
|
||||
} else {
|
||||
v[0] += __shfl_xor_sync(0xffffffffu, v[0], o);
|
||||
}
|
||||
}
|
||||
// lane l holds value j = l >> SH = qi * 4 + h; the head-0 lane of each query gathers heads 1-3
|
||||
const int j = lane >> SH, qi = j >> 2;
|
||||
const float d1 = __shfl_sync(0xffffffffu, v[0], (lane + (1 << SH)) & 31);
|
||||
const float d2 = __shfl_sync(0xffffffffu, v[0], (lane + (2 << SH)) & 31);
|
||||
const float d3 = __shfl_sync(0xffffffffu, v[0], (lane + (3 << SH)) & 31);
|
||||
if ((j & 3) == 0 && (lane & ((1 << SH) - 1)) == 0 && qi < nq && b <= s_nbid_r[qi & (NQ - 1)]) {
|
||||
const float d[4] = {v[0], d1, d2, d3};
|
||||
float score = 0.0f;
|
||||
#pragma unroll
|
||||
for (int h = 0; h < IDX_HEADS; ++h) score += d[h] > 0.0f ? d[h] : 0.0f;
|
||||
if (b == s_nbid_r[qi & (NQ - 1)] && s_nkv[qi] % R != 0) score += 1e9f;
|
||||
out[qi * max_blocks + b] = score;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// #1825: the prompt path's thread-per-head scorer (bitwise the warp kernel's scores). Default: Turing with
|
||||
// STRATA_SM75_PERF=1 (the P100 gain measured here is +1..3% at 30-60K tokens, under the 3% bar for a new default);
|
||||
// STRATA_SCORES_THREAD=1 turns it on, =0 off, on any CUDA card
|
||||
bool scores_thread_on() {
|
||||
static const int env = [] { const char* v = std::getenv("STRATA_SCORES_THREAD"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
|
||||
if (env >= 0) return env != 0;
|
||||
static int ok[64] = {}; // 0 unknown, 1 yes, 2 no
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
|
||||
if (ok[dev] == 0) {
|
||||
int major = 0, minor = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
ok[dev] = strata::sm75_default(major, minor) ? 1 : 2; // Turing, STRATA_SM75_PERF=1
|
||||
}
|
||||
return ok[dev] == 1;
|
||||
}
|
||||
|
||||
bool scores_halve_on() {
|
||||
static const int env = [] { const char* v = std::getenv("STRATA_SCORES_HALVE"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
|
||||
if (env >= 0) return env != 0;
|
||||
static int ok[64] = {}; // 0 unknown, 1 yes, 2 no
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
|
||||
if (ok[dev] == 0) {
|
||||
int major = 0, minor = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
ok[dev] = strata::sm75_default(major, minor) ? 1 : 2; // Turing, STRATA_SM75_PERF=1
|
||||
}
|
||||
return ok[dev] == 1;
|
||||
}
|
||||
|
||||
void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
|
||||
int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
|
||||
if (nq <= 0) return;
|
||||
@@ -1402,6 +1718,25 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx
|
||||
// QSAROWS: STRATA_QSA_ROWS=1 (exactly) takes block_scores_rows_kernel for calls of up to 4 queries - the same bits
|
||||
static const bool rows_env = [] { const char* v = std::getenv("STRATA_QSA_ROWS"); return v != nullptr && v[0] == '1' && v[1] == '\0'; }();
|
||||
if (rows_env && qsa_block_scores_rows(pooled, dead, q_idx, steps, nq, max_blocks, s, scores, stream)) return;
|
||||
if (scores_halve_on()) { // Turing: block_scores_halve_kernel, the same bits
|
||||
const cudaStream_t st = (cudaStream_t) stream;
|
||||
if (nq <= 1) block_scores_halve_kernel<4><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, (int) nq, max_blocks, scores);
|
||||
else if (nq <= 2) block_scores_halve_kernel<8><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, (int) nq, max_blocks, scores);
|
||||
else if (nq <= 4) block_scores_halve_kernel<16><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, (int) nq, max_blocks, scores);
|
||||
else { // 5-8 queries: two calls of up to 4 (the register form; each query's scores are its own)
|
||||
block_scores_halve_kernel<16><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, 4, max_blocks, scores);
|
||||
const int rest = (int) nq - 4;
|
||||
const float* q2 = q_idx + 4 * IDX_HEADS * IDX_DIM;
|
||||
const int32_t* st2 = steps + 4 * kStepCount;
|
||||
float* sc2 = scores + 4 * max_blocks;
|
||||
if (rest <= 1) block_scores_halve_kernel<4><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q2, st2, rest, max_blocks, sc2);
|
||||
else if (rest <= 2) block_scores_halve_kernel<8><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q2, st2, rest, max_blocks, sc2);
|
||||
else block_scores_halve_kernel<16><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q2, st2, rest, max_blocks, sc2);
|
||||
}
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores halve: %s\n", cudaGetErrorString(e)); std::exit(1); }
|
||||
return;
|
||||
}
|
||||
block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, (int) nq,
|
||||
max_blocks, scores, scores_early_exit());
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
@@ -1437,6 +1772,18 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx
|
||||
}
|
||||
return;
|
||||
}
|
||||
#else
|
||||
// prompt calls (an active-block count): the thread-per-head kernel, the same bits (opt-in: scores_thread_on); else the
|
||||
// warp kernel below
|
||||
if (active_blocks > 0 && scores_thread_on()) {
|
||||
const dim3 tgrid((unsigned) ((reach + TS_BR - 1) / TS_BR), (unsigned) ((nq + TS_Q - 1) / TS_Q));
|
||||
block_scores_thread_kernel<<<tgrid, 256, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq, max_blocks, reach,
|
||||
scores);
|
||||
block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores thread: %s\n", cudaGetErrorString(e)); std::exit(1); }
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
const dim3 grid((unsigned) ((reach + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq);
|
||||
block_scores_kernel<<<grid, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, max_blocks,
|
||||
@@ -1529,12 +1876,33 @@ bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_
|
||||
if (cc_major[dev] < 8) {
|
||||
// no TF32 tensor cores: the FP32 tiled kernel, opt-in (STRATA_SELECT_SIMT=1): its sum order differs from the
|
||||
// warp kernel's, so the default stays the caller's warp kernel and the output bytes stay the same
|
||||
static const bool simt = [] {
|
||||
// STRATA_SELECT_SIMT=2: block_scores_simt2_kernel (the same bits as =1, larger tiles)
|
||||
static const int simt = [] {
|
||||
const char* v = std::getenv("STRATA_SELECT_SIMT");
|
||||
return v != nullptr && v[0] == '1';
|
||||
return v == nullptr ? 0 : v[0] == '1' ? 1 : v[0] == '2' ? 2 : 0;
|
||||
}();
|
||||
if (!simt) return false;
|
||||
const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
|
||||
if (simt == 2) {
|
||||
// STRATA_SIMT2_TILE=2: 64 x 64 tiles (measured slower: 400K 3.00 vs 2.82 ms)
|
||||
static const int tile = [] { const char* v = std::getenv("STRATA_SIMT2_TILE"); return v ? std::atoi(v) : 1; }();
|
||||
if (tile != 2) {
|
||||
const dim3 grid((unsigned) ((reach + 127) / 128), (unsigned) ((nq + 31) / 32));
|
||||
if (grid.y > 65535) return false;
|
||||
block_scores_simt2_kernel<32, 128><<<grid, 256, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq,
|
||||
max_blocks, reach, scores);
|
||||
} else {
|
||||
const dim3 grid((unsigned) ((reach + 63) / 64), (unsigned) ((nq + 63) / 64));
|
||||
if (grid.y > 65535) return false;
|
||||
block_scores_simt2_kernel<64, 64><<<grid, 256, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq,
|
||||
max_blocks, reach, scores);
|
||||
}
|
||||
block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks,
|
||||
scores);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores (simt): %s\n", cudaGetErrorString(e)); std::exit(1); }
|
||||
return true;
|
||||
}
|
||||
return block_scores_simt(pooled, dead, q_idx, steps, nq, max_blocks, reach, scores, (cudaStream_t) stream,
|
||||
false);
|
||||
}
|
||||
@@ -1659,6 +2027,471 @@ bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t n
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
// ---- the decode top-k split over many CTAs, for cards without thread-block clusters (Turing: a decode window's 1-6
|
||||
// queries ran block_topk_wide_kernel on 1-6 SMs, ~230 us a call at 420K cells, RTX 2080 Ti). A query's blocks are
|
||||
// cut into chunks of SP_CH; six launches: four radix passes (each chunk adds its 8-bit histogram to the query's global
|
||||
// one), a count of each chunk's cells above / at the threshold, and the emit. Each pass's CTAs take the previous
|
||||
// digit from the complete histogram with block_topk_kernel's rule (the largest digit whose cells at or above it reach
|
||||
// the width; 0 when none) - pure functions of integer counts, so every CTA finds the same digit, and the threshold,
|
||||
// `above` and the emitted cells are block_topk_kernel's: identical ids. STRATA_TOPK_SPLIT=0 keeps the wide kernel.
|
||||
constexpr int SP_T = 256, SP_W = SP_T / 32, SP_CH = 2048, SP_MAXQ = 16, SP_MAXCH = 512;
|
||||
__device__ int g_sp_hist[SP_MAXQ][4][256];
|
||||
__device__ int g_sp_state[5][SP_MAXQ][2]; // after p digits: prefix, above
|
||||
__device__ int g_sp_cnt[SP_MAXQ][SP_MAXCH][2]; // per chunk: cells above the threshold, cells at it
|
||||
|
||||
// the digit of pass `p` from its complete histogram: block_topk_kernel's scan as a parallel suffix sum
|
||||
__device__ void sp_digit(const int* __restrict__ h, int width, int above, int& digit, int& above_out, int* s_buf) {
|
||||
const int t = threadIdx.x;
|
||||
// s_buf[d] = sum of h[d'] for d' > d (exclusive suffix), d in 0..255
|
||||
const int v = h[t];
|
||||
int x = v; // inclusive suffix scan over t = 255..0: reverse index r = 255 - t
|
||||
const int lane = t & 31, w = t >> 5;
|
||||
__shared__ int s_w[SP_W];
|
||||
// scan in reverse order: thread t holds element r = 255 - t
|
||||
int e = h[255 - t];
|
||||
for (int o = 1; o < 32; o <<= 1) { const int y = __shfl_up_sync(0xffffffffu, e, o); if (lane >= o) e += y; }
|
||||
if (lane == 31) s_w[w] = e;
|
||||
__syncthreads();
|
||||
int add = 0;
|
||||
for (int i = 0; i < w; ++i) add += s_w[i];
|
||||
e += add; // inclusive suffix sum of h from 255 down to r = 255 - t
|
||||
(void) x; (void) v;
|
||||
s_buf[255 - t] = e; // s_buf[r] = sum_{d >= r} h[d]
|
||||
__syncthreads();
|
||||
// the scan picks the largest d in 1..255 with above + sum_{d' >= d} h >= width, else 0
|
||||
__shared__ int s_best;
|
||||
if (t == 0) s_best = 0;
|
||||
__syncthreads();
|
||||
if (t >= 1 && above + s_buf[t] >= width) atomicMax(&s_best, t);
|
||||
__syncthreads();
|
||||
const int d = s_best;
|
||||
digit = d;
|
||||
above_out = above + (d == 255 ? 0 : s_buf[d + 1]); // cells strictly above digit d (the scan's cum)
|
||||
if (d == 0) above_out = above + s_buf[1];
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
template <int P>
|
||||
__global__ void __launch_bounds__(SP_T) topk_split_hist_kernel(const float* __restrict__ scores,
|
||||
const int32_t* __restrict__ steps, int64_t max_blocks) {
|
||||
__shared__ int hist[SP_W][256];
|
||||
__shared__ int s_buf[256];
|
||||
const int q = blockIdx.y, t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
const int32_t* st = steps + (int64_t) q * kStepCount;
|
||||
const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
|
||||
if (n_kv <= width) return;
|
||||
const int64_t nb = n_bid + 1, b0 = (int64_t) blockIdx.x * SP_CH;
|
||||
uint32_t prefix = 0;
|
||||
int above = 0;
|
||||
if (P > 0) {
|
||||
const int pa = g_sp_state[P - 1][q][0], ab = g_sp_state[P - 1][q][1];
|
||||
int d, ab2;
|
||||
sp_digit(g_sp_hist[q][P - 1], (int) width, ab, d, ab2, s_buf);
|
||||
prefix = (uint32_t) pa | ((uint32_t) d << (24 - 8 * (P - 1)));
|
||||
above = ab2;
|
||||
if (blockIdx.x == 0 && t == 0) { g_sp_state[P][q][0] = (int) prefix; g_sp_state[P][q][1] = above; }
|
||||
} else if (blockIdx.x == 0 && t == 0) {
|
||||
g_sp_state[0][q][0] = 0; g_sp_state[0][q][1] = 0;
|
||||
}
|
||||
if (P == 4 || b0 >= nb) return;
|
||||
constexpr int shift = 24 - 8 * (P < 4 ? P : 0);
|
||||
const uint32_t hi_mask = P == 0 ? 0u : (0xffffffffu << (shift + 8));
|
||||
for (int i = lane; i < 256; i += 32) hist[warp][i] = 0;
|
||||
__syncwarp();
|
||||
const float* sc = scores + (int64_t) q * max_blocks;
|
||||
const int64_t b1 = b0 + SP_CH < nb ? b0 + SP_CH : nb;
|
||||
for (int64_t b = b0 + t; b < b1; b += SP_T) {
|
||||
const int w = b < n_bid ? R : (int) (n_kv - n_bid * R);
|
||||
if (w == 0) continue;
|
||||
const uint32_t k = order_key(sc[b]);
|
||||
if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(k >> shift) & 255], w);
|
||||
}
|
||||
__syncthreads();
|
||||
int s = 0;
|
||||
for (int w2 = 0; w2 < SP_W; ++w2) s += hist[w2][t];
|
||||
if (s) atomicAdd(&g_sp_hist[q][P][t], s);
|
||||
}
|
||||
|
||||
// the threshold from pass 3's histogram, then each chunk's cells above / at it
|
||||
__global__ void __launch_bounds__(SP_T) topk_split_count_kernel(const float* __restrict__ scores,
|
||||
const int32_t* __restrict__ steps, int64_t max_blocks) {
|
||||
__shared__ int s_buf[256];
|
||||
__shared__ int s_r[2][SP_W];
|
||||
const int q = blockIdx.y, t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
const int32_t* st = steps + (int64_t) q * kStepCount;
|
||||
const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
|
||||
if (n_kv <= width) return;
|
||||
const int pa = g_sp_state[3][q][0], ab = g_sp_state[3][q][1];
|
||||
int d, ab2;
|
||||
sp_digit(g_sp_hist[q][3], (int) width, ab, d, ab2, s_buf);
|
||||
const uint32_t thr = (uint32_t) pa | (uint32_t) d;
|
||||
if (blockIdx.x == 0 && t == 0) { g_sp_state[4][q][0] = (int) thr; g_sp_state[4][q][1] = ab2; }
|
||||
const int64_t nb = n_bid + 1, b0 = (int64_t) blockIdx.x * SP_CH;
|
||||
const int64_t b1 = b0 + SP_CH < nb ? b0 + SP_CH : nb;
|
||||
const float* sc = scores + (int64_t) q * max_blocks;
|
||||
int gt = 0, eq = 0;
|
||||
for (int64_t b = b0 + t; b < b1; b += SP_T) {
|
||||
const int w = b < n_bid ? R : (int) (n_kv - n_bid * R);
|
||||
if (w == 0) continue;
|
||||
const uint32_t k = order_key(sc[b]);
|
||||
if (k > thr) gt += w;
|
||||
else if (k == thr) eq += w;
|
||||
}
|
||||
for (int o = 16; o > 0; o >>= 1) {
|
||||
gt += __shfl_xor_sync(0xffffffffu, gt, o);
|
||||
eq += __shfl_xor_sync(0xffffffffu, eq, o);
|
||||
}
|
||||
if (lane == 0) { s_r[0][warp] = gt; s_r[1][warp] = eq; }
|
||||
__syncthreads();
|
||||
if (t == 0) {
|
||||
int g2 = 0, e2 = 0;
|
||||
for (int w2 = 0; w2 < SP_W; ++w2) { g2 += s_r[0][w2]; e2 += s_r[1][w2]; }
|
||||
g_sp_cnt[q][blockIdx.x][0] = g2;
|
||||
g_sp_cnt[q][blockIdx.x][1] = e2;
|
||||
}
|
||||
}
|
||||
|
||||
// the emit: block_topk_wide_kernel's within a chunk, offset by the chunks before it
|
||||
__global__ void __launch_bounds__(SP_T) topk_split_emit_kernel(const float* __restrict__ scores,
|
||||
const int32_t* __restrict__ steps, int64_t max_blocks,
|
||||
int64_t cap, int32_t* __restrict__ ids) {
|
||||
__shared__ int s_gt[SP_W], s_eq[SP_W];
|
||||
__shared__ int s_sel0, s_eqb0;
|
||||
const int q = blockIdx.y, t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
const int32_t* st = steps + (int64_t) q * kStepCount;
|
||||
const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
|
||||
int32_t* out = ids + (int64_t) q * cap;
|
||||
const int64_t nb = n_bid + 1, b0 = (int64_t) blockIdx.x * SP_CH;
|
||||
if (n_kv <= width) { // everything is selected: the identity, ascending
|
||||
const int64_t c0 = b0 * R, c1 = (b0 + SP_CH) * R < n_kv ? (b0 + SP_CH) * R : n_kv;
|
||||
for (int64_t j = c0 + t; j < c1; j += SP_T) out[j] = (int32_t) j;
|
||||
return;
|
||||
}
|
||||
if (b0 >= nb) return;
|
||||
const uint32_t thr = (uint32_t) g_sp_state[4][q][0];
|
||||
const int eq_budget = (int) (width - g_sp_state[4][q][1]);
|
||||
if (t == 0) { // the cells the chunks before this one select / hold at thr
|
||||
int sel = 0, eqb = 0;
|
||||
for (int c = 0; c < (int) blockIdx.x; ++c) {
|
||||
const int g2 = g_sp_cnt[q][c][0], e2 = g_sp_cnt[q][c][1];
|
||||
const int take = eq_budget - eqb < 0 ? 0 : (eq_budget - eqb > e2 ? e2 : eq_budget - eqb);
|
||||
sel += g2 + take;
|
||||
eqb += e2;
|
||||
}
|
||||
s_sel0 = sel;
|
||||
s_eqb0 = eqb;
|
||||
}
|
||||
const int64_t b1 = b0 + SP_CH < nb ? b0 + SP_CH : nb;
|
||||
const int64_t per = (SP_CH / 32) / SP_W; // rows of 32 blocks per warp
|
||||
const int64_t w0 = b0 + (int64_t) warp * 32 * per, w1 = w0 + 32 * per < b1 ? w0 + 32 * per : b1;
|
||||
const float* sc = scores + (int64_t) q * max_blocks;
|
||||
auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
|
||||
int gt = 0, eq = 0;
|
||||
for (int64_t b = w0 + lane; b < w1; b += 32) {
|
||||
const int w = weight(b);
|
||||
if (w == 0) continue;
|
||||
const uint32_t k = order_key(sc[b]);
|
||||
if (k > thr) gt += w;
|
||||
else if (k == thr) eq += w;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) {
|
||||
gt += __shfl_xor_sync(0xffffffffu, gt, o);
|
||||
eq += __shfl_xor_sync(0xffffffffu, eq, o);
|
||||
}
|
||||
if (lane == 0) { s_gt[warp] = gt; s_eq[warp] = eq; }
|
||||
__syncthreads();
|
||||
if (t == 0) {
|
||||
int eb = s_eqb0, sb = s_sel0;
|
||||
for (int w2 = 0; w2 < SP_W; ++w2) {
|
||||
const int g2 = s_gt[w2], e2 = s_eq[w2];
|
||||
const int take = eq_budget - eb < 0 ? 0 : (eq_budget - eb > e2 ? e2 : eq_budget - eb);
|
||||
s_gt[w2] = sb;
|
||||
s_eq[w2] = eb;
|
||||
sb += g2 + take;
|
||||
eb += e2;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
int run_sel = s_gt[warp], run_eq = s_eq[warp];
|
||||
for (int64_t r0 = w0; r0 < w1; r0 += 32) {
|
||||
const int64_t b = r0 + lane;
|
||||
const int w = b < w1 ? weight(b) : 0;
|
||||
const uint32_t k = w ? order_key(sc[b]) : 0u;
|
||||
const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0;
|
||||
if (__ballot_sync(0xffffffffu, (my_gt | my_eq) != 0) == 0u) continue;
|
||||
int pe = my_eq;
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 32; o <<= 1) {
|
||||
const int y = __shfl_up_sync(0xffffffffu, pe, o);
|
||||
if (lane >= o) pe += y;
|
||||
}
|
||||
const int left = eq_budget - (run_eq + pe - my_eq);
|
||||
const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left);
|
||||
const int my_sel = my_gt + take;
|
||||
int ps = my_sel;
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 32; o <<= 1) {
|
||||
const int y = __shfl_up_sync(0xffffffffu, ps, o);
|
||||
if (lane >= o) ps += y;
|
||||
}
|
||||
int32_t* dst = out + run_sel + ps - my_sel;
|
||||
for (int c = 0; c < my_sel; ++c) dst[c] = (int32_t) (b * R + c);
|
||||
run_eq += __shfl_sync(0xffffffffu, pe, 31);
|
||||
run_sel += __shfl_sync(0xffffffffu, ps, 31);
|
||||
}
|
||||
}
|
||||
|
||||
bool topk_split_device() {
|
||||
static int ok[64] = {}; // 0 unknown, 1 yes, 2 no
|
||||
static const int env = [] { const char* v = std::getenv("STRATA_TOPK_SPLIT"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
|
||||
if (env == 0) return false;
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
|
||||
if (ok[dev] == 0) {
|
||||
int major = 0, minor = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
ok[dev] = (env == 1 || strata::sm75_default(major, minor)) ? 1 : 2; // Turing, STRATA_SM75_PERF=1
|
||||
}
|
||||
return ok[dev] == 1;
|
||||
}
|
||||
|
||||
bool qsa_block_topk_split(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
|
||||
int32_t* ids, cudaStream_t s) {
|
||||
const int64_t nch = (max_blocks + SP_CH - 1) / SP_CH;
|
||||
if (nq < 1 || nq > SP_MAXQ || nch > SP_MAXCH) return false;
|
||||
static void* hist_ptr[64] = {};
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
|
||||
if (hist_ptr[dev] == nullptr && cudaGetSymbolAddress(&hist_ptr[dev], g_sp_hist) != cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
hist_ptr[dev] = nullptr;
|
||||
return false;
|
||||
}
|
||||
if (cudaMemsetAsync(hist_ptr[dev], 0, (size_t) nq * 4 * 256 * sizeof(int), s) != cudaSuccess) return false;
|
||||
const dim3 grid((unsigned) nch, (unsigned) nq);
|
||||
topk_split_hist_kernel<0><<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
|
||||
topk_split_hist_kernel<1><<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
|
||||
topk_split_hist_kernel<2><<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
|
||||
topk_split_hist_kernel<3><<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
|
||||
topk_split_count_kernel<<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
|
||||
topk_split_emit_kernel<<<grid, SP_T, 0, s>>>(scores, steps, max_blocks, cap, ids);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
// ---- the prompt path's top-k with one full read of the scores (Turing). block_topk_wide_kernel reads a query's scores
|
||||
// six times (four radix passes, a count, the emit); past ~90K cells that is DRAM traffic (256 queries at 400K: 0.6 GB a
|
||||
// layer, ~1.5 ms on an RTX 2080 Ti). Here a CTA first reads every 32nd block and takes the KS-th largest of those keys
|
||||
// as a bound LB, then reads all blocks once and keeps the ones with key >= LB in shared memory. When those hold at
|
||||
// least `width` cells, the width-th largest cell key (block_topk_kernel's threshold) is >= LB, so every block at or
|
||||
// above the threshold is a candidate: the threshold, `above` and the tie budget computed over the candidates with
|
||||
// block_topk_kernel's rule are the reference's, and the candidates sorted by block emit the reference's cells in its
|
||||
// order. Otherwise (too few cells above LB, or more than SM_CAP candidates) the query is flagged and
|
||||
// block_topk_wide_kernel<true> runs it. STRATA_TOPK_SAMPLE=0 keeps the wide kernel alone.
|
||||
constexpr int TS_STRIDE = 32, TS_CAP = 4096;
|
||||
|
||||
__device__ __forceinline__ int ts_block_scan(int v, int* s_w) { // exclusive scan over the CTA's TK_T threads
|
||||
const int t = threadIdx.x, lane = t & 31, w = t >> 5;
|
||||
int x = v;
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 32; o <<= 1) { const int y = __shfl_up_sync(0xffffffffu, x, o); if (lane >= o) x += y; }
|
||||
if (lane == 31) s_w[w] = x;
|
||||
__syncthreads();
|
||||
if (w == 0) {
|
||||
int y = lane < TK_T / 32 ? s_w[lane] : 0;
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 32; o <<= 1) { const int z = __shfl_up_sync(0xffffffffu, y, o); if (lane >= o) y += z; }
|
||||
if (lane < TK_T / 32) s_w[lane] = y; // inclusive warp totals
|
||||
}
|
||||
__syncthreads();
|
||||
const int base = w > 0 ? s_w[w - 1] : 0;
|
||||
const int r = base + x - v;
|
||||
__syncthreads();
|
||||
return r;
|
||||
}
|
||||
|
||||
__global__ void __launch_bounds__(TK_T) block_topk_sample_kernel(const float* __restrict__ scores,
|
||||
const int32_t* __restrict__ steps, int64_t max_blocks,
|
||||
int64_t cap, int32_t* __restrict__ ids) {
|
||||
__shared__ uint32_t s_key[TS_CAP];
|
||||
__shared__ int32_t s_idx[TS_CAP];
|
||||
__shared__ int hist[256];
|
||||
__shared__ int s_w[TK_T / 32];
|
||||
__shared__ int s_cnt, s_cells, s_digit, s_above;
|
||||
const int64_t qi = blockIdx.x;
|
||||
const int32_t* st = steps + qi * kStepCount;
|
||||
const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
|
||||
int32_t* out = ids + qi * cap;
|
||||
const int t = threadIdx.x;
|
||||
if (n_kv <= width) {
|
||||
if (t == 0) g_tk_fail[qi] = 0;
|
||||
for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j;
|
||||
return;
|
||||
}
|
||||
const float* sc = scores + qi * max_blocks;
|
||||
const int64_t nb = n_bid + 1;
|
||||
auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
|
||||
const int ns = (int) ((nb + TS_STRIDE - 1) / TS_STRIDE);
|
||||
if (ns > TS_CAP) { if (t == 0) g_tk_fail[qi] = 1; return; }
|
||||
// 1. the bound: the KS-th largest of every 32nd block's key (a block without cells counts as the smallest key)
|
||||
for (int i = t; i < ns; i += TK_T) {
|
||||
const int64_t b = (int64_t) i * TS_STRIDE;
|
||||
s_key[i] = weight(b) ? order_key(sc[b]) : 0u;
|
||||
}
|
||||
const int ks_want = (int) (2 * ((width + R * TS_STRIDE - 1) / (R * TS_STRIDE)) + 16);
|
||||
int need = ks_want < ns ? ks_want : ns;
|
||||
uint32_t prefix = 0;
|
||||
for (int shift = 24; shift >= 0; shift -= 8) {
|
||||
for (int i = t; i < 256; i += TK_T) hist[i] = 0;
|
||||
__syncthreads();
|
||||
const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
|
||||
for (int i = t; i < ns; i += TK_T) {
|
||||
const uint32_t k = s_key[i];
|
||||
if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[(k >> shift) & 255], 1);
|
||||
}
|
||||
__syncthreads();
|
||||
if (t == 0) {
|
||||
int cum = 0, d = 255;
|
||||
for (; d > 0; --d) {
|
||||
if (cum + hist[d] >= need) break;
|
||||
cum += hist[d];
|
||||
}
|
||||
s_digit = d;
|
||||
s_above = need - cum;
|
||||
}
|
||||
__syncthreads();
|
||||
prefix |= (uint32_t) s_digit << shift;
|
||||
need = s_above;
|
||||
__syncthreads();
|
||||
}
|
||||
const uint32_t lb = prefix;
|
||||
// 2. one read of every block: the candidates (key >= LB) and their cells
|
||||
if (t == 0) { s_cnt = 0; s_cells = 0; }
|
||||
__syncthreads();
|
||||
for (int64_t b = t; b < nb; b += TK_T) {
|
||||
const int w = weight(b);
|
||||
if (w == 0) continue;
|
||||
const uint32_t k = order_key(sc[b]);
|
||||
if (k >= lb) {
|
||||
const int pos = atomicAdd(&s_cnt, 1);
|
||||
if (pos < TS_CAP) { s_key[pos] = k; s_idx[pos] = (int32_t) b; }
|
||||
atomicAdd(&s_cells, w);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
const int n = s_cnt;
|
||||
if (n > TS_CAP || s_cells < width) { // the bound was too low or too high: the wide kernel takes this query
|
||||
if (t == 0) g_tk_fail[qi] = 1;
|
||||
return;
|
||||
}
|
||||
if (t == 0) g_tk_fail[qi] = 0;
|
||||
// 3. block_topk_kernel's threshold over the candidates (weighted)
|
||||
prefix = 0;
|
||||
int above = 0;
|
||||
for (int shift = 24; shift >= 0; shift -= 8) {
|
||||
for (int i = t; i < 256; i += TK_T) hist[i] = 0;
|
||||
__syncthreads();
|
||||
const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
|
||||
for (int i = t; i < n; i += TK_T) {
|
||||
const uint32_t k = s_key[i];
|
||||
if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[(k >> shift) & 255], weight(s_idx[i]));
|
||||
}
|
||||
__syncthreads();
|
||||
if (t == 0) {
|
||||
int cum = above, d = 255;
|
||||
for (; d > 0; --d) {
|
||||
if (cum + hist[d] >= width) break;
|
||||
cum += hist[d];
|
||||
}
|
||||
s_digit = d;
|
||||
s_above = cum;
|
||||
}
|
||||
__syncthreads();
|
||||
prefix |= (uint32_t) s_digit << shift;
|
||||
above = s_above;
|
||||
__syncthreads();
|
||||
}
|
||||
const uint32_t thr = prefix;
|
||||
const int eq_budget = (int) (width - above);
|
||||
// 4. the candidates in block order (bitonic sort; padding sorts last)
|
||||
int n2 = 1;
|
||||
while (n2 < n) n2 <<= 1;
|
||||
for (int i = n + t; i < n2; i += TK_T) { s_idx[i] = 0x7fffffff; s_key[i] = 0u; }
|
||||
__syncthreads();
|
||||
for (int kk = 2; kk <= n2; kk <<= 1) {
|
||||
for (int j = kk >> 1; j > 0; j >>= 1) {
|
||||
for (int i = t; i < n2; i += TK_T) {
|
||||
const int p = i ^ j;
|
||||
if (p > i) {
|
||||
const bool up = (i & kk) == 0;
|
||||
const int a = s_idx[i], b = s_idx[p];
|
||||
if ((a > b) == up) {
|
||||
s_idx[i] = b; s_idx[p] = a;
|
||||
const uint32_t ka = s_key[i]; s_key[i] = s_key[p]; s_key[p] = ka;
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
// 5. the emit: cells above thr, and the first eq_budget cells at thr, in block order
|
||||
constexpr int PER = TS_CAP / TK_T; // candidates per thread, consecutive
|
||||
int eqc[PER], gtc[PER];
|
||||
int my_eq = 0;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < PER; ++r) {
|
||||
const int i = t * PER + r;
|
||||
const int w = i < n ? weight(s_idx[i]) : 0;
|
||||
const uint32_t k = s_key[i < n ? i : 0];
|
||||
gtc[r] = (i < n && k > thr) ? w : 0;
|
||||
eqc[r] = (i < n && k == thr) ? w : 0;
|
||||
my_eq += eqc[r];
|
||||
}
|
||||
int eq_before = ts_block_scan(my_eq, s_w);
|
||||
int sel[PER], my_sel = 0;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < PER; ++r) {
|
||||
const int left = eq_budget - eq_before;
|
||||
const int take = left < 0 ? 0 : (left > eqc[r] ? eqc[r] : left);
|
||||
sel[r] = gtc[r] + take;
|
||||
my_sel += sel[r];
|
||||
eq_before += eqc[r];
|
||||
}
|
||||
int pos = ts_block_scan(my_sel, s_w);
|
||||
#pragma unroll
|
||||
for (int r = 0; r < PER; ++r) {
|
||||
const int i = t * PER + r;
|
||||
if (sel[r] > 0) {
|
||||
const int64_t b = s_idx[i];
|
||||
for (int c = 0; c < sel[r]; ++c) out[pos + c] = (int32_t) (b * R + c);
|
||||
}
|
||||
pos += sel[r];
|
||||
}
|
||||
}
|
||||
|
||||
// The prompt path's one-read top-k: STRATA_TOPK_SAMPLE=0 / 1 forces it off / on for any card; unset it is a Turing kernel
|
||||
// of the series (STRATA_SM75_PERF=1). (As submitted in #2093 it was on for every CUDA card; same ids, but only measured
|
||||
// on an RTX 2080 Ti, so the other cards keep the wide kernel.)
|
||||
bool topk_sample_on() {
|
||||
static const int env = [] { const char* v = std::getenv("STRATA_TOPK_SAMPLE"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
|
||||
if (env >= 0) return env != 0;
|
||||
static int ok[64] = {}; // 0 unknown, 1 yes, 2 no
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
|
||||
if (ok[dev] == 0) {
|
||||
int major = 0, minor = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
ok[dev] = strata::sm75_default(major, minor) ? 1 : 2;
|
||||
}
|
||||
return ok[dev] == 1;
|
||||
}
|
||||
#endif
|
||||
|
||||
void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
|
||||
const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) {
|
||||
// keys in registers when every query's blocks fit (contexts up to ~135K cells), else (CUDA) the same threads
|
||||
@@ -1674,6 +2507,16 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64
|
||||
}();
|
||||
if (cluster && !old && nq <= CL_MAXQ && qsa_block_topk_cluster(scores, steps, nq, max_blocks, cap, s, ids, stream))
|
||||
return;
|
||||
#endif
|
||||
#if !defined(__HIPCC__)
|
||||
// Turing decode (a window's few queries, no block count): the split kernels above; the same ids
|
||||
if (!old && active_blocks <= 0 && max_blocks >= 16384 && s.idx_block == R &&
|
||||
cap >= qsa_selection_width(kTopkMaxCells, s) && topk_split_device() &&
|
||||
qsa_block_topk_split(scores, steps, nq, max_blocks, cap, ids, (cudaStream_t) stream)) {
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk (split): %s\n", cudaGetErrorString(e)); std::exit(1); }
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
// the blocks a query can have: the call's active count when the caller knows it (the prompt path), else the capacity.
|
||||
// Decode (no count) keeps the capacity rule and the original register width: nothing changes there.
|
||||
@@ -1724,9 +2567,15 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64
|
||||
const char* v = std::getenv("STRATA_TOPK_STREAM");
|
||||
return v == nullptr || v[0] != '0';
|
||||
}();
|
||||
if (reach > fit || (turing_wide && counted && reach > 22528)) // past the register kernel's reach, or Turing's band
|
||||
block_topk_wide_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
|
||||
else
|
||||
if (reach > fit || (turing_wide && counted && reach > 22528)) { // past the register kernel's reach, or Turing's band
|
||||
#if !defined(__HIPCC__)
|
||||
if (counted && nq <= TS_MAXQ && reach > 28672 && topk_sample_on()) { // one read of the scores (below ~115K cells the wide kernel is as fast)
|
||||
block_topk_sample_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
|
||||
block_topk_wide_kernel<true><<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
|
||||
} else
|
||||
#endif
|
||||
block_topk_wide_kernel<false><<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
|
||||
} else
|
||||
if (reach <= (int64_t) TK_T * TK_PER)
|
||||
block_topk_reg_kernel<TK_PER><<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
|
||||
else
|
||||
|
||||
@@ -324,10 +324,16 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2
|
||||
cudaFree(d_im);
|
||||
const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale) && ok_im;
|
||||
const bool ok2 = diff <= 1e-4 * scale;
|
||||
uint64_t sum = 1469598103934665603ull; // the new kernel's output bits: two builds of it compare by this
|
||||
for (float f : nw) {
|
||||
uint32_t b;
|
||||
std::memcpy(&b, &f, 4);
|
||||
sum = (sum ^ b) * 1099511628211ull;
|
||||
}
|
||||
std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of "
|
||||
"scale); %.3f -> %.3f ms per chunk (%.2fx)\n",
|
||||
"scale); %.3f -> %.3f ms per chunk (%.2fx); new output checksum %016llx\n",
|
||||
ok1 && ok2 ? "PASS" : "FAIL", fmt == 2 ? "q4_0" : fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old,
|
||||
err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new);
|
||||
err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new, (unsigned long long) sum);
|
||||
cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new);
|
||||
cudaFree(scratch);
|
||||
cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale);
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// The prompt path's block scores on the thread-per-head kernel (an active-block count) against block_scores_kernel
|
||||
// (no count, more than 8 queries), every score of blocks 0..n_bid bitwise; then the time of each. GPU, synthetic.
|
||||
#include "strata/kernels/qsa.hpp"
|
||||
#include "strata/kernels/qsa_select.hpp"
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace k = strata::kernels;
|
||||
namespace {
|
||||
void ck(cudaError_t e) {
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e));
|
||||
std::exit(2);
|
||||
}
|
||||
}
|
||||
// ctx: the last query's position + 1; queries: a prompt chunk ending there; mode 0 normal values, 1 wide magnitudes
|
||||
// and exact zeros, 2 small integers (many ties and cancellations)
|
||||
struct Case { int64_t ctx, queries; int mode; bool time; };
|
||||
bool check(Case c) {
|
||||
const auto s = k::qsa_real_shapes();
|
||||
const int64_t D = s.idx_dim, H = s.idx_n_head, max_blocks = c.ctx / s.idx_block + 2;
|
||||
std::mt19937 rng(91731 + (unsigned) c.ctx + 7 * (unsigned) c.queries + 101 * (unsigned) c.mode);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_int_distribution<int> small(-3, 3), expo(-20, 20), coin(0, 9);
|
||||
auto value = [&] {
|
||||
if (c.mode == 1) return coin(rng) == 0 ? 0.f : std::ldexp(nd(rng), expo(rng));
|
||||
if (c.mode == 2) return (float) small(rng);
|
||||
return nd(rng);
|
||||
};
|
||||
std::vector<float> pooled((size_t) (max_blocks * D)), dead((size_t) D), q((size_t) (c.queries * H * D));
|
||||
for (auto& v : pooled) v = value();
|
||||
for (auto& v : dead) v = value();
|
||||
for (auto& v : q) v = value();
|
||||
std::vector<int32_t> steps((size_t) (c.queries * k::kStepCount));
|
||||
for (int64_t i = 0; i < c.queries; ++i) {
|
||||
int32_t* st = steps.data() + i * k::kStepCount;
|
||||
const int64_t pos = c.ctx - c.queries + i;
|
||||
st[k::kStepPos] = (int32_t) pos;
|
||||
st[k::kStepNKv] = (int32_t) (pos + 1);
|
||||
st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);
|
||||
st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);
|
||||
}
|
||||
const int64_t active = steps[(size_t) ((c.queries - 1) * k::kStepCount + k::kStepNBid)] + 1;
|
||||
float *dp = nullptr, *dd = nullptr, *dq = nullptr, *da = nullptr, *db = nullptr;
|
||||
int32_t* dt = nullptr;
|
||||
const size_t n_out = (size_t) (c.queries * max_blocks);
|
||||
ck(cudaMalloc(&dp, pooled.size() * 4)); ck(cudaMalloc(&dd, dead.size() * 4)); ck(cudaMalloc(&dq, q.size() * 4));
|
||||
ck(cudaMalloc(&dt, steps.size() * 4)); ck(cudaMalloc(&da, n_out * 4)); ck(cudaMalloc(&db, n_out * 4));
|
||||
ck(cudaMemcpy(dp, pooled.data(), pooled.size() * 4, cudaMemcpyHostToDevice));
|
||||
ck(cudaMemcpy(dd, dead.data(), dead.size() * 4, cudaMemcpyHostToDevice));
|
||||
ck(cudaMemcpy(dq, q.data(), q.size() * 4, cudaMemcpyHostToDevice));
|
||||
ck(cudaMemcpy(dt, steps.data(), steps.size() * 4, cudaMemcpyHostToDevice));
|
||||
ck(cudaMemset(da, 0x7f, n_out * 4)); // different fill in each: an unwritten score cannot match by chance
|
||||
ck(cudaMemset(db, 0x3e, n_out * 4));
|
||||
k::qsa_block_scores(dp, dd, dq, dt, c.queries, max_blocks, s, da, nullptr); // block_scores_kernel
|
||||
k::qsa_block_scores(dp, dd, dq, dt, c.queries, max_blocks, s, db, nullptr, active); // the thread kernel
|
||||
ck(cudaDeviceSynchronize());
|
||||
std::vector<uint32_t> a(n_out), b(n_out);
|
||||
ck(cudaMemcpy(a.data(), da, n_out * 4, cudaMemcpyDeviceToHost));
|
||||
ck(cudaMemcpy(b.data(), db, n_out * 4, cudaMemcpyDeviceToHost));
|
||||
bool ok = true;
|
||||
int64_t checked = 0;
|
||||
for (int64_t i = 0; i < c.queries && ok; ++i) {
|
||||
const int64_t n_bid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)];
|
||||
for (int64_t j = 0; j <= n_bid; ++j, ++checked) {
|
||||
const size_t at = (size_t) (i * max_blocks + j);
|
||||
if (a[at] != b[at]) {
|
||||
float fa, fb;
|
||||
std::memcpy(&fa, &a[at], 4); std::memcpy(&fb, &b[at], 4);
|
||||
std::fprintf(stderr, "FAIL ctx=%lld queries=%lld mode=%d query=%lld block=%lld: %.9g vs %.9g\n",
|
||||
(long long) c.ctx, (long long) c.queries, c.mode, (long long) i, (long long) j, fa, fb);
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ok) std::printf("ok ctx=%7lld queries=%5lld mode=%d: %lld scores identical\n", (long long) c.ctx,
|
||||
(long long) c.queries, c.mode, (long long) checked);
|
||||
if (ok && c.time) {
|
||||
cudaEvent_t e0, e1, e2;
|
||||
ck(cudaEventCreate(&e0)); ck(cudaEventCreate(&e1)); ck(cudaEventCreate(&e2));
|
||||
constexpr int N = 5;
|
||||
ck(cudaEventRecord(e0));
|
||||
for (int r = 0; r < N; ++r) k::qsa_block_scores(dp, dd, dq, dt, c.queries, max_blocks, s, da, nullptr);
|
||||
ck(cudaEventRecord(e1));
|
||||
for (int r = 0; r < N; ++r) k::qsa_block_scores(dp, dd, dq, dt, c.queries, max_blocks, s, db, nullptr, active);
|
||||
ck(cudaEventRecord(e2));
|
||||
ck(cudaEventSynchronize(e2));
|
||||
float t_old = 0.f, t_new = 0.f;
|
||||
ck(cudaEventElapsedTime(&t_old, e0, e1)); ck(cudaEventElapsedTime(&t_new, e1, e2));
|
||||
std::printf(" time per call: warp kernel %.2f ms, thread kernel %.2f ms (%.2fx)\n", t_old / N, t_new / N,
|
||||
t_old / t_new);
|
||||
cudaEventDestroy(e0); cudaEventDestroy(e1); cudaEventDestroy(e2);
|
||||
}
|
||||
ck(cudaFree(dp)); ck(cudaFree(dd)); ck(cudaFree(dq)); ck(cudaFree(dt)); ck(cudaFree(da)); ck(cudaFree(db));
|
||||
return ok;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
int devices = 0;
|
||||
if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
|
||||
std::puts("SKIP: no CUDA device");
|
||||
return 77;
|
||||
}
|
||||
const Case cases[] = {
|
||||
{1111, 9, 0, false}, {1111, 64, 1, false}, {8192, 65, 0, false}, {8195, 200, 2, false},
|
||||
{32768, 256, 0, false}, {32771, 1000, 1, false}, {131072, 64, 2, false}, {131075, 333, 0, false},
|
||||
{262144, 129, 1, false}, {40000, 2048, 0, true}, {140000, 1024, 0, true}, {200000, 1024, 0, true},
|
||||
};
|
||||
for (const auto c : cases) if (!check(c)) return 1;
|
||||
std::puts("PASS: block scores of the thread kernel bitwise identical to block_scores_kernel");
|
||||
return 0;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
#include <cstring>
|
||||
// src/kernels/qsa_select_bench.cpp - the prompt path's QSA selection (qsa_select.hpp) timed per stage, block scores
|
||||
// (the warp kernel and the fast one: tensor cores, or the FP32 tiled kernel on CUDA below sm_80) and top-k, for a batch of consecutive queries at a given context, and
|
||||
// the two scorers compared: score difference and how many selections differ (GPU, synthetic, no model).
|
||||
@@ -13,6 +14,7 @@
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
@@ -69,6 +71,28 @@ int main(int argc, char** argv) {
|
||||
ck(cudaMalloc(&ids_old, (size_t) (nq * cap) * 4), "malloc");
|
||||
ck(cudaMalloc(&ids_new, (size_t) (nq * cap) * 4), "malloc");
|
||||
const int64_t active = steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1;
|
||||
if (std::getenv("QSA_BENCH_DECODE")) { // a decode window's call: no block count (block_scores_multi_kernel)
|
||||
auto run_dec = [&] { k::qsa_block_scores(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_old, nullptr, -1); };
|
||||
run_dec();
|
||||
ck(cudaDeviceSynchronize(), "sync");
|
||||
cudaEvent_t a0, a1;
|
||||
cudaEventCreate(&a0); cudaEventCreate(&a1);
|
||||
cudaEventRecord(a0);
|
||||
for (int r = 0; r < reps; ++r) run_dec();
|
||||
cudaEventRecord(a1); cudaEventSynchronize(a1);
|
||||
float ms = 0; cudaEventElapsedTime(&ms, a0, a1);
|
||||
std::vector<float> h((size_t) (nq * max_blocks));
|
||||
ck(cudaMemcpy(h.data(), sc_old, h.size() * 4, cudaMemcpyDeviceToHost), "down");
|
||||
unsigned long long x = 1469598103934665603ull;
|
||||
for (int64_t i = 0; i < nq; ++i) {
|
||||
const int64_t nbid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)];
|
||||
for (int64_t j = 0; j <= nbid; ++j) { uint32_t u; std::memcpy(&u, &h[(size_t) (i * max_blocks + j)], 4); x = (x ^ u) * 1099511628211ull; }
|
||||
}
|
||||
const double gb = (double) active * 512.0 / 1e9;
|
||||
std::printf("decode scores ctx %lld, %lld queries: %.1f us (%.0f GB/s of pooled keys), hash %016llx\n", (long long) ctx,
|
||||
(long long) nq, 1e3 * ms / reps, gb / (ms / reps / 1e3), x);
|
||||
return 0;
|
||||
}
|
||||
auto run_old = [&] { k::qsa_block_scores(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_old, nullptr, active); };
|
||||
// a device without the tensor-core scorer (HIP other than gfx12): time the warp scorer and the top-k only
|
||||
const bool have_tc = k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, 1, max_blocks, s, sc_new, nullptr, active);
|
||||
@@ -92,6 +116,18 @@ int main(int argc, char** argv) {
|
||||
std::vector<int32_t> ia((size_t) (nq * cap)), ib(ia.size());
|
||||
ck(cudaMemcpy(a.data(), sc_old, a.size() * 4, cudaMemcpyDeviceToHost), "down");
|
||||
ck(cudaMemcpy(b.data(), sc_new, b.size() * 4, cudaMemcpyDeviceToHost), "down");
|
||||
if (std::getenv("QSA_BENCH_HASH")) { // the fast scorer's bytes (compare STRATA_SELECT_SIMT=1 and =2)
|
||||
unsigned long long h = 1469598103934665603ull;
|
||||
for (int64_t i = 0; i < nq; ++i) {
|
||||
const int64_t nbid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)];
|
||||
for (int64_t j = 0; j < nbid; ++j) {
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &b[(size_t) (i * max_blocks + j)], 4);
|
||||
h = (h ^ u) * 1099511628211ull;
|
||||
}
|
||||
}
|
||||
std::printf("fast scores hash %016llx\n", h);
|
||||
}
|
||||
ck(cudaMemcpy(ia.data(), ids_old, ia.size() * 4, cudaMemcpyDeviceToHost), "down");
|
||||
ck(cudaMemcpy(ib.data(), ids_new, ib.size() * 4, cudaMemcpyDeviceToHost), "down");
|
||||
std::vector<int32_t> ir(ia.size());
|
||||
|
||||
+34
-3
@@ -907,8 +907,19 @@ bool Gemm::rdna2_sgemm(const uint16_t* X, const uint16_t* W, float* Y, int64_t T
|
||||
}
|
||||
#endif
|
||||
|
||||
bool Gemm::bf16_converts_x() const {
|
||||
#if defined(__HIPCC__) || defined(STRATA_EXPERIMENTAL_SM60)
|
||||
return false;
|
||||
#else
|
||||
return bf16_path() == 1;
|
||||
#endif
|
||||
}
|
||||
__global__ void f16_to_bf16_kernel(const __half* __restrict__ in, uint16_t* __restrict__ out, int64_t n) {
|
||||
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i < n) out[i] = (uint16_t) (__float_as_uint(__half2float(in[i])) >> 16); // exact: the value was a BF16
|
||||
}
|
||||
void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,
|
||||
float beta, int64_t ldx) {
|
||||
float beta, int64_t ldx, bool x_f16) {
|
||||
if (T <= 0 || N <= 0) return;
|
||||
if (ldy <= 0) ldy = N;
|
||||
if (ldx <= K) ldx = 0;
|
||||
@@ -998,14 +1009,34 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64
|
||||
bf16_to_f16(W + n0 * K, tc_w_, nn * K, (cudaStream_t) stream_);
|
||||
for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
|
||||
const int64_t n = std::min<int64_t>(x_rows, T - t0);
|
||||
bf16_to_f16(X + t0 * K, tc_x_, n * K, (cudaStream_t) stream_);
|
||||
f16(tc_x_, tc_w_, Y + t0 * ldy + n0, n, nn, K, ldy, beta);
|
||||
if (x_f16) { // already the converted values (the same slices: the same GEMMs)
|
||||
f16(X + t0 * K, tc_w_, Y + t0 * ldy + n0, n, nn, K, ldy, beta);
|
||||
} else {
|
||||
bf16_to_f16(X + t0 * K, tc_x_, n * K, (cudaStream_t) stream_);
|
||||
f16(tc_x_, tc_w_, Y + t0 * ldy + n0, n, nn, K, ldy, beta);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#if !defined(__HIPCC__)
|
||||
if (x_f16) { // not the tensor-core path after all (one output row, or no room): X back to BF16, a slice at a time
|
||||
const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
|
||||
if (!grow(tc_x_, tc_x_elems_, x_rows * K)) {
|
||||
std::fprintf(stderr, "prefill gemm: no GPU memory for converting an FP16 image back to BF16\n");
|
||||
std::exit(1);
|
||||
}
|
||||
for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
|
||||
const int64_t n = std::min<int64_t>(x_rows, T - t0);
|
||||
f16_to_bf16_kernel<<<(unsigned) ((n * K + 255) / 256), 256, 0, (cudaStream_t) stream_>>>(
|
||||
reinterpret_cast<const __half*>(X + t0 * K), tc_x_, n * K);
|
||||
bf16(tc_x_, W, Y + t0 * ldy, n, N, K, ldy, beta, 0, false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
// Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T].
|
||||
ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W,
|
||||
|
||||
+27
-16
@@ -42,6 +42,7 @@ __device__ __forceinline__ uint16_t bf(float f) {
|
||||
__device__ __forceinline__ uint16_t bf_lo(float f, uint16_t hi) { return bf(f - __uint_as_float((uint32_t) hi << 16)); }
|
||||
__device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); }
|
||||
__device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); }
|
||||
}
|
||||
// A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then
|
||||
// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504). A NaN stays NaN (fminf/fmaxf
|
||||
// would make it -65504 and hide where it came from); finite values below 65504 round exactly as before.
|
||||
@@ -66,6 +67,15 @@ __device__ __forceinline__ uint16_t hf_sat(float f) {
|
||||
#endif
|
||||
return hf(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f));
|
||||
}
|
||||
|
||||
// Turing's FP16 image of the hyper-connection's xn16 (gemm.cu's bf16_to_f16_kernel applied to a BF16 value): the
|
||||
// writers store what the BF16 tensor-core path would convert, so the GEMM reads it without a conversion pass
|
||||
__device__ __forceinline__ uint16_t bf_to_hf_conv(uint16_t b) {
|
||||
float f = __uint_as_float((uint32_t) b << 16);
|
||||
if (f > 65504.0f && !isinf(f)) f = 65504.0f;
|
||||
else if (f < -65504.0f && !isinf(f)) f = -65504.0f;
|
||||
return __half_as_ushort(__float2half_rn(f));
|
||||
}
|
||||
// The prompt path's 16-bit activation image for the BF16-weight GEMMs: BF16, or FP16 where the GEMM library is fast
|
||||
// only in FP16 (prompt_f16() in gemm.cu: rocBLAS on gfx103x). Set once per device before the first prompt.
|
||||
#if defined(__HIPCC__) // HIP only (#835): the CUDA kernels stay exactly as they were, they never read the flag
|
||||
@@ -96,7 +106,8 @@ unsigned blocks_for(int64_t n, int t = 256) { return (unsigned) ((n + t - 1) / t
|
||||
|
||||
// ---------------------------------------------------------------- hyper-connection
|
||||
__global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps,
|
||||
float* __restrict__ xn, uint16_t* __restrict__ xn16, uint16_t* __restrict__ xn16_lo) {
|
||||
float* __restrict__ xn, uint16_t* __restrict__ xn16, uint16_t* __restrict__ xn16_lo,
|
||||
int f16img) {
|
||||
__shared__ float sh[32];
|
||||
const int64_t row = blockIdx.x; // t * 4 + c
|
||||
const int c = (int) (row % HC);
|
||||
@@ -108,7 +119,7 @@ __global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restr
|
||||
const float v = r[d] * rs * w[c * N + d];
|
||||
xn[row * N + d] = v;
|
||||
const uint16_t h = act16(v);
|
||||
xn16[row * N + d] = h;
|
||||
xn16[row * N + d] = f16img ? bf_to_hf_conv(h) : h;
|
||||
if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h);
|
||||
}
|
||||
}
|
||||
@@ -116,7 +127,7 @@ __global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restr
|
||||
// so the FP32 copy of the normalized rows (T x 10240 floats) is neither written nor read
|
||||
__global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps,
|
||||
float* __restrict__ rs_out, uint16_t* __restrict__ xn16,
|
||||
uint16_t* __restrict__ xn16_lo, int64_t ldx) {
|
||||
uint16_t* __restrict__ xn16_lo, int64_t ldx, int f16img) {
|
||||
__shared__ float sh[32];
|
||||
const int64_t row = blockIdx.x; // t * 4 + c
|
||||
const int c = (int) (row % HC);
|
||||
@@ -129,7 +140,7 @@ __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __re
|
||||
for (int d = threadIdx.x; d < N; d += blockDim.x) {
|
||||
const float v = r[d] * rs * w[c * N + d];
|
||||
const uint16_t h = act16(v);
|
||||
xn16[xo + d] = h;
|
||||
xn16[xo + d] = f16img ? bf_to_hf_conv(h) : h;
|
||||
if (xn16_lo) xn16_lo[xo + d] = bf_lo(v, h);
|
||||
}
|
||||
}
|
||||
@@ -163,7 +174,7 @@ __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict
|
||||
const float* __restrict__ inj, int64_t inj_ld,
|
||||
const float* __restrict__ w, float eps,
|
||||
float* __restrict__ rs_out, uint16_t* __restrict__ xn16,
|
||||
uint16_t* __restrict__ xn16_lo, int64_t ldx) {
|
||||
uint16_t* __restrict__ xn16_lo, int64_t ldx, int f16img) {
|
||||
__shared__ float sh[32];
|
||||
const int64_t row = blockIdx.x; // t * 4 + c
|
||||
const int64_t t = row / HC;
|
||||
@@ -188,7 +199,7 @@ __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict
|
||||
for (int d = threadIdx.x; d < N; d += 256, ++k) {
|
||||
const float x = v[k] * rs * w[c * N + d];
|
||||
const uint16_t h = act16(x);
|
||||
xn16[xo + d] = h;
|
||||
xn16[xo + d] = f16img ? bf_to_hf_conv(h) : h;
|
||||
if (xn16_lo) xn16_lo[xo + d] = bf_lo(x, h);
|
||||
}
|
||||
}
|
||||
@@ -200,7 +211,7 @@ __global__ void __launch_bounds__(256) gr_write_cvec_norm_rs_kernel(
|
||||
float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, int64_t inj_ld,
|
||||
const float* __restrict__ v_l, const float* __restrict__ s_l, const int* __restrict__ on, int mode,
|
||||
const float* __restrict__ w, float eps, float* __restrict__ rs_out, uint16_t* __restrict__ xn16,
|
||||
uint16_t* __restrict__ xn16_lo, int64_t ldx) {
|
||||
uint16_t* __restrict__ xn16_lo, int64_t ldx, int f16img) {
|
||||
__shared__ float sh[32];
|
||||
__shared__ float part[8];
|
||||
const int64_t row = blockIdx.x; // t * 4 + c
|
||||
@@ -250,7 +261,7 @@ __global__ void __launch_bounds__(256) gr_write_cvec_norm_rs_kernel(
|
||||
for (int d = threadIdx.x; d < N; d += 256, ++k) {
|
||||
const float y = x[k] * rs * w[c * N + d];
|
||||
const uint16_t h = act16(y);
|
||||
xn16[t * ldx + (int64_t) c * N + d] = h;
|
||||
xn16[t * ldx + (int64_t) c * N + d] = f16img ? bf_to_hf_conv(h) : h;
|
||||
if (xn16_lo) xn16_lo[t * ldx + (int64_t) c * N + d] = bf_lo(y, h);
|
||||
}
|
||||
}
|
||||
@@ -2361,14 +2372,14 @@ void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo
|
||||
}
|
||||
|
||||
void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream,
|
||||
uint16_t* xn16_lo) {
|
||||
gr_norm_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, xn, xn16, xn16_lo);
|
||||
uint16_t* xn16_lo, bool f16img) {
|
||||
gr_norm_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, xn, xn16, xn16_lo, f16img ? 1 : 0);
|
||||
check("gr_norm");
|
||||
}
|
||||
void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream,
|
||||
uint16_t* xn16_lo, int64_t ldx) {
|
||||
uint16_t* xn16_lo, int64_t ldx, bool f16img) {
|
||||
gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo,
|
||||
ldx > 0 ? ldx : D);
|
||||
ldx > 0 ? ldx : D, f16img ? 1 : 0);
|
||||
check("gr_norm_rs");
|
||||
}
|
||||
void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16,
|
||||
@@ -2409,17 +2420,17 @@ bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const
|
||||
#endif
|
||||
}
|
||||
void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps,
|
||||
float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) {
|
||||
float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx, bool f16img) {
|
||||
gr_write_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, w_norm_next, eps,
|
||||
rs, xn16, xn16_lo,
|
||||
ldx > 0 ? ldx : D);
|
||||
ldx > 0 ? ldx : D, f16img ? 1 : 0);
|
||||
check("gr_write_norm_rs");
|
||||
}
|
||||
void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l,
|
||||
const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs,
|
||||
uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) {
|
||||
uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx, bool f16img) {
|
||||
gr_write_cvec_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(
|
||||
R, bo, inj, inj_ld, v_l, s_l, on, mode, w_norm_next, eps, rs, xn16, xn16_lo, ldx > 0 ? ldx : D);
|
||||
R, bo, inj, inj_ld, v_l, s_l, on, mode, w_norm_next, eps, rs, xn16, xn16_lo, ldx > 0 ? ldx : D, f16img ? 1 : 0);
|
||||
check("gr_write_cvec_norm_rs");
|
||||
}
|
||||
void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) {
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
// activations are stored in it (perm32), and a lane's two B registers (h = 0 and 1) are adjacent: one 8-byte load.
|
||||
#include "strata/prefill/moe_fused.hpp"
|
||||
#include "strata/kernels/gfx_arch.hpp"
|
||||
#include "strata/core/emulate.hpp"
|
||||
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
@@ -194,6 +195,26 @@ __device__ __forceinline__ void mma_s8(int (&d)[4], const uint32_t (&a)[4], uint
|
||||
: "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3])
|
||||
: "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1), "r"(0));
|
||||
}
|
||||
#elif defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750
|
||||
// Turing (STRATA_PF_FUSED_SM75): no cp.async - the stages are filled by plain copies (the same bytes; the barriers
|
||||
// around them stay) - and no m16n8k32 with s8 operands: it is four m8n8k16, rows g / g + 8 by k 0-15 / 16-31 (the
|
||||
// m16n8k32 fragments: a[0] / a[1] rows g / g + 8 at k 4 tig.., a[2] / a[3] the same at k 16 + 4 tig.., b0 / b1 the
|
||||
// two k halves). The int32 sums are exact in any order: the same d as the sm_80 instruction.
|
||||
__device__ __forceinline__ void cp16(void* dst, const void* src) { *(uint4*) dst = __ldg((const uint4*) src); }
|
||||
__device__ __forceinline__ void cp4(void* dst, const void* src) { *(uint32_t*) dst = __ldg((const uint32_t*) src); }
|
||||
__device__ __forceinline__ void cp_commit() {}
|
||||
template <int N> __device__ __forceinline__ void cp_wait() {}
|
||||
__device__ __forceinline__ void mma8_s8(int& c0, int& c1, uint32_t a, uint32_t b) {
|
||||
asm("mma.sync.aligned.m8n8k16.row.col.s32.s8.s8.s32 {%0,%1}, {%2}, {%3}, {%0,%1};\n"
|
||||
: "+r"(c0), "+r"(c1) : "r"(a), "r"(b));
|
||||
}
|
||||
__device__ __forceinline__ void mma_s8(int (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {
|
||||
d[0] = d[1] = d[2] = d[3] = 0;
|
||||
mma8_s8(d[0], d[1], a[0], b0);
|
||||
mma8_s8(d[0], d[1], a[2], b1);
|
||||
mma8_s8(d[2], d[3], a[1], b0);
|
||||
mma8_s8(d[2], d[3], a[3], b1);
|
||||
}
|
||||
#endif
|
||||
|
||||
// One work item = (tile of up to 64 routed rows of expert e, a block of 256 weight rows); a persistent grid walks
|
||||
@@ -206,7 +227,7 @@ template <bool GU>
|
||||
__global__ void __launch_bounds__(THREADS, 1)
|
||||
expert_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src,
|
||||
uint8_t* __restrict__ out, float* __restrict__ dm) {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750
|
||||
constexpr int NKB = GU ? 40 : 10; // 64-weight blocks along K
|
||||
constexpr int NFB = GU ? 5 : 10; // weight-row blocks per tile
|
||||
constexpr int CODE_LD = GU ? 640 : 160; // code bytes per weight row
|
||||
@@ -625,11 +646,13 @@ const DevInfo& dev_info() {
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
|
||||
d.cc = 10 * major + minor;
|
||||
if (d.cc < 80) return d;
|
||||
// the device code of this card's arch must have the kernels (a build without an sm_80+ target has an empty body)
|
||||
d.cc = 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor); // STRATA_EMULATE_CC counts (tests)
|
||||
// Turing (sm_75): the same kernels with plain copies and m8n8k16 MMAs, opt-in (STRATA_PF_FUSED_SM75=1)
|
||||
static const bool sm75 = [] { const char* v = std::getenv("STRATA_PF_FUSED_SM75"); return v != nullptr && v[0] == '1'; }();
|
||||
if (d.cc < 75 || (d.cc < 80 && !sm75)) { d.cc = d.cc < 80 ? 0 : d.cc; return d; }
|
||||
// the device code of this card's arch must have the kernels (a build without an sm_75+ target has an empty body)
|
||||
cudaFuncAttributes fa{};
|
||||
if (cudaFuncGetAttributes(&fa, expert_kernel<true>) != cudaSuccess || fa.ptxVersion < 80) {
|
||||
if (cudaFuncGetAttributes(&fa, expert_kernel<true>) != cudaSuccess || fa.ptxVersion < (d.cc >= 80 ? 80 : 75)) {
|
||||
cudaGetLastError();
|
||||
d.cc = 0;
|
||||
return d;
|
||||
@@ -649,7 +672,7 @@ const DevInfo& dev_info() {
|
||||
} // namespace
|
||||
|
||||
bool built() { return true; }
|
||||
bool available() { return dev_info().cc >= 80; }
|
||||
bool available() { return dev_info().cc >= 75; }
|
||||
// 0.1.36: on by default for the Q2_0 pack (+13-23% prompts on an RTX 5070; teacher-forced against the FP16 path as
|
||||
// close as MMQ at 8K and closer at 32K: phaseA-tests s18-tf); STRATA_PF_FUSED=0 keeps MMQ. The native packs' kernels
|
||||
// (moe_fused_iq) stay opt-in: STRATA_PF_FUSED=1 (requested()).
|
||||
|
||||
+126
-22
@@ -21,6 +21,7 @@
|
||||
// (SwiGLU, H to int8 per 32 features; down into the per-slot rows) are moe_fused.cu's.
|
||||
#include "strata/prefill/moe_fused_iq.hpp"
|
||||
#include "strata/kernels/gfx_arch.hpp"
|
||||
#include "strata/core/emulate.hpp"
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#include "moe_f16_common.cuh"
|
||||
@@ -63,6 +64,14 @@ constexpr int WLD = 80; // bytes per decoded weight row of a sta
|
||||
__host__ __device__ constexpr int tile_rows(int ww) { return 256 / ww; }
|
||||
__host__ __device__ constexpr int weight_rows(int ww) { return 64 * ww; }
|
||||
constexpr int ASTAGES = 4; // cp.async depth of the activations (64 values of K a stage)
|
||||
// Turing: 2 (its copies are plain loads, so depth buys nothing, and 4 does not fit its 64 KB of shared memory)
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
||||
constexpr int ASTAGES_DEV = 2;
|
||||
constexpr bool T75_DEV = true; // the Q2_0 stage epilogue in native_kernel: fewer instructions, its sums in another order
|
||||
#else
|
||||
constexpr int ASTAGES_DEV = ASTAGES;
|
||||
constexpr bool T75_DEV = false;
|
||||
#endif
|
||||
constexpr int GU_ROWS_K = 2560, D_ROWS_K = 640; // K of gate/up (n_embd) and of down (n_ff)
|
||||
|
||||
// the formats (ggml type ids)
|
||||
@@ -96,8 +105,8 @@ __host__ __device__ constexpr int grid_bytes(int t) {
|
||||
return t == T_IQ2_XXS ? 256 * 8 : t == T_IQ2_XS ? 512 * 8 : t == T_IQ2_S ? 1024 * 8 : t == T_IQ3_XXS ? 256 * 4
|
||||
: t == T_IQ3_S ? 512 * 4 : 0;
|
||||
}
|
||||
__host__ __device__ constexpr size_t smem_bytes(int t, int ww) {
|
||||
return (size_t) 2 * weight_rows(ww) * (WLD + 16) + (size_t) ASTAGES * tile_rows(ww) * AB +
|
||||
__host__ __device__ constexpr size_t smem_bytes(int t, int ww, int astages = ASTAGES) {
|
||||
return (size_t) 2 * weight_rows(ww) * (WLD + 16) + (size_t) astages * tile_rows(ww) * AB +
|
||||
(size_t) tile_rows(ww) * 4 + grid_bytes(t);
|
||||
}
|
||||
|
||||
@@ -169,8 +178,41 @@ __device__ __forceinline__ void ldsm4(uint32_t (&r)[4], const void* p) {
|
||||
: "memory");
|
||||
}
|
||||
|
||||
#elif defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750
|
||||
// Turing (STRATA_PF_FUSED_SM75): plain copies instead of cp.async (the same bytes; the barriers around them stay), and
|
||||
// the s8 MMAs as m8n8k16 - m16n8k32 is four (rows g / g + 8 by k 0-15 / 16-31), m16n8k16 two (rows g / g + 8), each
|
||||
// pair starting from MAGIC. The int32 sums are exact in any order: the same d as the sm_80 instructions.
|
||||
__device__ __forceinline__ void cp16(void* dst, const void* src) { *(uint4*) dst = __ldg((const uint4*) src); }
|
||||
__device__ __forceinline__ void cp_commit() {}
|
||||
__device__ __forceinline__ void pf_l2(const void* p) { asm volatile("prefetch.global.L2 [%0];\n" ::"l"(p)); }
|
||||
template <int N> __device__ __forceinline__ void cp_wait() {}
|
||||
__device__ __forceinline__ void mma8_s8(int& c0, int& c1, uint32_t a, uint32_t b) {
|
||||
asm("mma.sync.aligned.m8n8k16.row.col.s32.s8.s8.s32 {%0,%1}, {%2}, {%3}, {%0,%1};\n"
|
||||
: "+r"(c0), "+r"(c1) : "r"(a), "r"(b));
|
||||
}
|
||||
__device__ __forceinline__ void mma8_s8_c(int& d0, int& d1, uint32_t a, uint32_t b, int c) {
|
||||
asm("mma.sync.aligned.m8n8k16.row.col.s32.s8.s8.s32 {%0,%1}, {%2}, {%3}, {%4,%4};\n"
|
||||
: "=r"(d0), "=r"(d1) : "r"(a), "r"(b), "r"(c));
|
||||
}
|
||||
__device__ __forceinline__ void mma32(int (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {
|
||||
mma8_s8_c(d[0], d[1], a[0], b0, MAGIC);
|
||||
mma8_s8(d[0], d[1], a[2], b1);
|
||||
mma8_s8_c(d[2], d[3], a[1], b0, MAGIC);
|
||||
mma8_s8(d[2], d[3], a[3], b1);
|
||||
}
|
||||
__device__ __forceinline__ void mma16(int (&d)[4], uint32_t a0, uint32_t a1, uint32_t b0) {
|
||||
mma8_s8_c(d[0], d[1], a0, b0, MAGIC);
|
||||
mma8_s8_c(d[2], d[3], a1, b0, MAGIC);
|
||||
}
|
||||
__device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; }
|
||||
__device__ __forceinline__ void ldsm4(uint32_t (&r)[4], const void* p) {
|
||||
asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
|
||||
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
|
||||
: "r"((unsigned) __cvta_generic_to_shared(p))
|
||||
: "memory");
|
||||
}
|
||||
#endif
|
||||
#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800) || defined(__HIPCC__)
|
||||
#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750) || defined(__HIPCC__)
|
||||
#if defined(__HIPCC__)
|
||||
__device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; }
|
||||
#endif
|
||||
@@ -435,7 +477,7 @@ template <int WT, bool GU, int WW>
|
||||
__global__ void __launch_bounds__(THREADS, 1)
|
||||
native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act,
|
||||
const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750
|
||||
constexpr int TR = tile_rows(WW), WR = weight_rows(WW);
|
||||
constexpr int WT_BYTES = WR * WLD, WS_FLOATS = WR * 4, ACT_STAGE = TR * AB;
|
||||
constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K
|
||||
@@ -446,8 +488,8 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_
|
||||
extern __shared__ __align__(16) uint8_t smem[];
|
||||
uint8_t* wt = smem; // [2][WR][WLD] decoded int8 weights
|
||||
float* ws = (float*) (smem + 2 * WT_BYTES); // [2][WR][4] their scales per 16 values
|
||||
uint8_t* stages = (uint8_t*) (ws + 2 * WS_FLOATS); // [ASTAGES][TR][AB] activations
|
||||
int* srow = (int*) (stages + ASTAGES * ACT_STAGE); // [TR] the activation row of each tile row
|
||||
uint8_t* stages = (uint8_t*) (ws + 2 * WS_FLOATS); // [ASTAGES_DEV][TR][AB] activations
|
||||
int* srow = (int*) (stages + ASTAGES_DEV * ACT_STAGE); // [TR] the activation row of each tile row
|
||||
uint8_t* sgrid = (uint8_t*) (srow + TR); // the codebook
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g = lane >> 2, tig = lane & 3;
|
||||
@@ -483,17 +525,20 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_
|
||||
const uint8_t* wrow = GU ? blob + ((ur & 8) ? geo.up_off : 0) +
|
||||
(size_t) (fb * (WR / 2) + 8 * (ur >> 4) + (ur & 7)) * geo.gu_row
|
||||
: blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row;
|
||||
// gate/up in Q2_0 (64-value blocks): a block per stage, as the down rows read theirs
|
||||
constexpr bool GU256 = GU && WT != T_Q2_0;
|
||||
auto unit = [&](int s) -> const uint8_t* { // the block of stage s's sub-block
|
||||
if (GU) return wrow + (s >> 2) * BS;
|
||||
if (GU256) return wrow + (s >> 2) * BS;
|
||||
return WT == T_IQ4_NL ? wrow + (2 * s + uj) * BS : wrow + s * BS;
|
||||
};
|
||||
auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; };
|
||||
auto sub = [&](int s) { return GU256 ? 2 * (s & 3) + uj : uj; };
|
||||
// the weight bytes into L2 ahead of the register loads (one stage ahead only - less than a DRAM round trip):
|
||||
// gate/up PF super-blocks ahead (the row's two threads take a block's first and last line), down the whole row
|
||||
// slice at once (180 or 360 bytes a row)
|
||||
constexpr int PF = 2;
|
||||
constexpr int SBB = WT == T_Q2_0 ? 4 * BS : BS; // bytes per 256 values of a row
|
||||
auto prefetch_sb = [&](int sb) {
|
||||
if (dec && sb < GU_ROWS_K / 256) pf_l2(wrow + sb * BS + (uj ? BS - 1 : 0));
|
||||
if (dec && sb < GU_ROWS_K / 256) pf_l2(wrow + sb * SBB + (uj ? SBB - 1 : 0));
|
||||
};
|
||||
if (GU) {
|
||||
#pragma unroll
|
||||
@@ -507,7 +552,7 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_
|
||||
// the rows past the item's end are not loaded: a warp entirely past it skips the products, and the columns
|
||||
// of a partial one are never written (no reduction mixes columns)
|
||||
auto load_act = [&](int s) {
|
||||
uint8_t* st = stages + (s % ASTAGES) * ACT_STAGE;
|
||||
uint8_t* st = stages + (s % ASTAGES_DEV) * ACT_STAGE;
|
||||
for (int c = tid; c < TR * 5; c += THREADS) {
|
||||
const int r = c / 5, q = c % 5;
|
||||
if (r < nrows) cp16(st + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + s * AB + q * 16);
|
||||
@@ -524,7 +569,7 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_
|
||||
*(float2*) (ws + buf * WS_FLOATS + ur * 4 + 2 * uj) = make_float2(s0, s1);
|
||||
};
|
||||
#pragma unroll
|
||||
for (int s = 0; s < ASTAGES - 1; ++s) {
|
||||
for (int s = 0; s < ASTAGES_DEV - 1; ++s) {
|
||||
if (s < NS) load_act(s);
|
||||
cp_commit();
|
||||
}
|
||||
@@ -542,21 +587,47 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;
|
||||
for (int s = 0; s < NS; ++s) {
|
||||
cp_wait<ASTAGES - 2>();
|
||||
cp_wait<ASTAGES_DEV - 2>();
|
||||
__syncthreads();
|
||||
if (s + ASTAGES - 1 < NS) load_act(s + ASTAGES - 1);
|
||||
if (s + ASTAGES_DEV - 1 < NS) load_act(s + ASTAGES_DEV - 1);
|
||||
cp_commit();
|
||||
if (GU && (s & 3) == 0) prefetch_sb((s >> 2) + PF);
|
||||
if (on0) {
|
||||
const uint8_t* W = wt + (s & 1) * WT_BYTES;
|
||||
const float* S = ws + (s & 1) * WS_FLOATS;
|
||||
const uint8_t* sa = stages + (s % ASTAGES) * ACT_STAGE;
|
||||
const uint8_t* sa = stages + (s % ASTAGES_DEV) * ACT_STAGE;
|
||||
// the stage's scales: per weight row 4 (per 16 values), per routed row 2 (per 32)
|
||||
float2 dx[2][2]; // [n8 tile][column 2 tig + cc]
|
||||
#pragma unroll
|
||||
for (int n = 0; n < 2; ++n)
|
||||
#pragma unroll
|
||||
for (int cc = 0; cc < 2; ++cc) dx[n][cc] = *(const float2*) (sa + (nb0 + 8 * n + 2 * tig + cc) * AB + 64);
|
||||
if constexpr (WT == T_Q2_0 && T75_DEV) {
|
||||
// Turing, Q2_0: one d per 64 values, so the stage's two halves share their weight scale - each row's dot
|
||||
// is d (dx_0 dot_0 + dx_1 dot_1): the activation scales per half, then d once
|
||||
uint32_t bq0[4], bq1[4]; // the two halves' {n0 0-15, n0 16-31, n1 0-15, n1 16-31}
|
||||
ldsm4(bq0, sa + b_off);
|
||||
ldsm4(bq1, sa + b_off + 32);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
uint32_t a0[4], a1[4];
|
||||
ldsm4(a0, W + a_off + 16 * i * WLD);
|
||||
ldsm4(a1, W + a_off + 16 * i * WLD + 32);
|
||||
const float wa = S[(64 * wf + 16 * i + g) * 4], wb = S[(64 * wf + 16 * i + 8 + g) * 4];
|
||||
#pragma unroll
|
||||
for (int n = 0; n < 2; ++n) {
|
||||
if (n == 1 && !on1) break;
|
||||
int d0[4], d1[4];
|
||||
mma32(d0, a0, bq0[2 * n], bq0[2 * n + 1]);
|
||||
mma32(d1, a1, bq1[2 * n], bq1[2 * n + 1]);
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
const float t = fmaf(dx[n][q & 1].y, dotf(d1[q]), dx[n][q & 1].x * dotf(d0[q]));
|
||||
acc[i][n][q] = fmaf(q < 2 ? wa : wb, t, acc[i][n][q]);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else
|
||||
#pragma unroll
|
||||
for (int h = 0; h < 2; ++h) { // the stage's two 32-value halves
|
||||
uint32_t bq[4]; // {n0 bytes 0-15, n0 16-31, n1 0-15, n1 16-31}
|
||||
@@ -1114,20 +1185,33 @@ unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); }
|
||||
struct DevInfo {
|
||||
bool done = false, ok = false;
|
||||
bool w12 = false; // gfx12 (RDNA4): the native kernels only - the Q2_0 pack's (moe_fused.cu) are not ported there
|
||||
bool t75 = false; // Turing (STRATA_PF_FUSED_SM75): the Q2_0 / Q2_0 layers only (what was set up and checked there)
|
||||
int sms = 0, occ = 1;
|
||||
};
|
||||
std::mutex g_mu;
|
||||
DevInfo g_dev[32];
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
// the activation stages of native_kernel on the current device: its ASTAGES_DEV (2 below sm_80)
|
||||
int host_astages() {
|
||||
static int per[64] = {};
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return ASTAGES; }
|
||||
if (!per[dev]) {
|
||||
int major = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
per[dev] = strata::cc_major_of(major) < 8 ? 2 : ASTAGES;
|
||||
}
|
||||
return per[dev];
|
||||
}
|
||||
template <int T, bool GU, int WW> bool setup_ww(int& occ) {
|
||||
cudaFuncAttributes fa{};
|
||||
if (cudaFuncGetAttributes(&fa, native_kernel<T, GU, WW>) != cudaSuccess || fa.ptxVersion < 80) return false;
|
||||
if (cudaFuncGetAttributes(&fa, native_kernel<T, GU, WW>) != cudaSuccess || fa.ptxVersion < 75) return false;
|
||||
if (cudaFuncSetAttribute(native_kernel<T, GU, WW>, cudaFuncAttributeMaxDynamicSharedMemorySize,
|
||||
(int) smem_bytes(T, WW)) != cudaSuccess)
|
||||
(int) smem_bytes(T, WW, host_astages())) != cudaSuccess)
|
||||
return false;
|
||||
int o = 0;
|
||||
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_kernel<T, GU, WW>, THREADS, smem_bytes(T, WW)) !=
|
||||
if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_kernel<T, GU, WW>, THREADS, smem_bytes(T, WW, host_astages())) !=
|
||||
cudaSuccess || o < 1)
|
||||
return false;
|
||||
occ = std::min(occ, o);
|
||||
@@ -1201,14 +1285,26 @@ const DevInfo& dev_info() {
|
||||
return d;
|
||||
}
|
||||
#else
|
||||
int major = 0;
|
||||
int major = 0, minor = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
major = strata::cc_major_of(major); // STRATA_EMULATE_CC counts (tests)
|
||||
minor = strata::cc_minor_of(minor);
|
||||
cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
|
||||
if (major < 8) return d;
|
||||
// Turing (sm_75): the same kernels with plain copies and m8n8k16 MMAs, opt-in (STRATA_PF_FUSED_SM75=1)
|
||||
static const bool sm75 = [] { const char* v = std::getenv("STRATA_PF_FUSED_SM75"); return v != nullptr && v[0] == '1'; }();
|
||||
if (major < 8 && !(major == 7 && minor == 5 && sm75)) return d;
|
||||
int occ = 1 << 20;
|
||||
if (major < 8) { // Turing: the canonical Q2_0 pack's kernels (the codebook formats' do not fit 64 KB at 4 warps a row)
|
||||
d.t75 = true;
|
||||
d.ok = setup_one<T_Q2_0, true>(occ) && setup_one<T_Q2_0, false>(occ);
|
||||
d.occ = d.ok ? occ : 1;
|
||||
cudaGetLastError();
|
||||
return d;
|
||||
}
|
||||
d.ok = setup_one<T_IQ2_XXS, true>(occ) && setup_one<T_IQ2_XS, true>(occ) && setup_one<T_IQ2_S, true>(occ) &&
|
||||
setup_one<T_IQ3_XXS, true>(occ) && setup_one<T_IQ3_S, true>(occ) && setup_one<T_IQ4_XS, true>(occ) &&
|
||||
setup_one<T_Q2_0, false>(occ) && setup_one<T_IQ4_NL, false>(occ);
|
||||
setup_one<T_Q2_0, false>(occ) && setup_one<T_IQ4_NL, false>(occ); // (Q2_0 gate/up is the Turing opt-in's only)
|
||||
d.occ = d.ok ? occ : 1;
|
||||
cudaGetLastError();
|
||||
#endif
|
||||
@@ -1231,6 +1327,9 @@ bool f16_gu(int t) {
|
||||
bool f16_d(int t) { return t == T_Q2_0 || t == T_IQ4_NL || t == T_Q8_0; }
|
||||
bool gu_covered(int t) {
|
||||
return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS
|
||||
#if !defined(__HIPCC__)
|
||||
|| (t == T_Q2_0 && dev_info().t75) // the canonical Q2_0 pack's gate/up: Turing opt-in only (sm_80+ keeps MMQ for it)
|
||||
#endif
|
||||
#if defined(__HIPCC__)
|
||||
|| ((t == T_Q4_K || t == T_Q5_K) && kq_on()) // the gfx11 kernels only
|
||||
#endif
|
||||
@@ -1254,13 +1353,16 @@ bool d_covered_on(int t, const DevInfo& d) {
|
||||
return d_covered(t);
|
||||
}
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
int host_astages() { return ASTAGES; } // (#2145 defines it for CUDA above; HIP keeps the one depth)
|
||||
#endif
|
||||
template <int T, bool GU>
|
||||
void launch(int ww, unsigned grid, const Batch& b, const NativeGeom& g, const Tables& tb, const void* act,
|
||||
const int32_t* src, void* out, float* dm, cudaStream_t s) {
|
||||
const uint8_t* a = (const uint8_t*) act;
|
||||
uint8_t* o = (uint8_t*) out;
|
||||
if (ww == 4) native_kernel<T, GU, 4><<<grid, THREADS, smem_bytes(T, 4), s>>>(b, g, tb, a, src, o, dm);
|
||||
else native_kernel<T, GU, 2><<<grid, THREADS, smem_bytes(T, 2), s>>>(b, g, tb, a, src, o, dm);
|
||||
if (ww == 4) native_kernel<T, GU, 4><<<grid, THREADS, smem_bytes(T, 4, host_astages()), s>>>(b, g, tb, a, src, o, dm);
|
||||
else native_kernel<T, GU, 2><<<grid, THREADS, smem_bytes(T, 2, host_astages()), s>>>(b, g, tb, a, src, o, dm);
|
||||
}
|
||||
|
||||
// The work item's shape for a layer of `n` routed rows over `n_expert` experts: 128 routed rows when an expert has
|
||||
@@ -1301,6 +1403,7 @@ bool native_supported(int gu_type, int d_type) {
|
||||
if (env < 0 && gu_type != T_IQ3_S && gu_type != T_IQ3_XXS) return false; // default: only these two
|
||||
const DevInfo& d = dev_info();
|
||||
if (!d.ok || !d_covered_on(d_type, d)) return false;
|
||||
if (d.t75 && (gu_type != T_Q2_0 || d_type != T_Q2_0)) return false;
|
||||
if (env < 0) return d.w12;
|
||||
return requested() || d.w12;
|
||||
}
|
||||
@@ -1410,6 +1513,7 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n
|
||||
case T_IQ2_S: launch<T_IQ2_S, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
|
||||
case T_IQ3_XXS: launch<T_IQ3_XXS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
|
||||
case T_IQ3_S: launch<T_IQ3_S, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
|
||||
case T_Q2_0: launch<T_Q2_0, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
|
||||
default: launch<T_IQ4_XS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
|
||||
}
|
||||
if (g.d_type == T_Q2_0) launch<T_Q2_0, false>(ww, g_d, b, g, tb, ha, src, nullptr, dm, s);
|
||||
|
||||
+26
-12
@@ -873,6 +873,7 @@ struct Prefill::Impl {
|
||||
float* mixed = nullptr;
|
||||
uint16_t *mixed_bf = nullptr, *mixed_h = nullptr;
|
||||
bool f16_io = false; // HIP, STRATA_HIP_PROMPT_F16=1: this stage's 16-bit GEMMs run FP16 in and out (set in init)
|
||||
bool xn_f16 = false; // Turing, BF16 on FP16 tensor cores: xn16 written as the FP16 values the GEMM would convert
|
||||
uint16_t *xn16_lo = nullptr, *lo16_lo = nullptr, *mixed_bf_lo = nullptr; // bf16x2(): the BF16 GEMMs' low parts
|
||||
float* bo = nullptr;
|
||||
// GDN
|
||||
@@ -1386,6 +1387,10 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co
|
||||
set_act_f16(m.f16_io);
|
||||
static const bool f16_range = std::getenv("STRATA_F16_RANGE") != nullptr; // what reaches FP16's range
|
||||
if (f16_range) { set_f16_range(true); gemm_set_f16_range(true); }
|
||||
// the hyper-connection's xn16 straight as the FP16 the tensor-core GEMM reads (its two readers then skip the
|
||||
// conversion pass; the same values): STRATA_XN_F16=0 keeps the BF16 image
|
||||
static const bool xn_env = [] { const char* e = std::getenv("STRATA_XN_F16"); return e == nullptr || e[0] != '0'; }();
|
||||
m.xn_f16 = xn_env && !m.f16_io && m.gemm.bf16_converts_x();
|
||||
}
|
||||
if (!carve(T, &o)) {
|
||||
size_t fb = 0, tb = 0;
|
||||
@@ -2252,7 +2257,7 @@ bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y
|
||||
}
|
||||
bool bf16_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, const uint16_t* X_lo = nullptr, int64_t ldx = 0,
|
||||
void* stream = nullptr) {
|
||||
void* stream = nullptr, bool x_f16 = false) {
|
||||
if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; }
|
||||
const uint16_t* wb = (const uint16_t*) w->data;
|
||||
if (w->q8_scale != nullptr) {
|
||||
@@ -2269,7 +2274,7 @@ 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;
|
||||
}
|
||||
gm.bf16(X, wb, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx);
|
||||
gm.bf16(X, wb, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx, x_f16);
|
||||
if (X_lo) gm.bf16(X_lo, wb, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f);
|
||||
return true;
|
||||
}
|
||||
@@ -2946,8 +2951,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
// the xn16 token stride of this chunk (the writers of both halves and of the fused write-backs use it)
|
||||
const int64_t ldx = hc_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) && !gr_unfused() &&
|
||||
!m.xn16_lo ? D + XN_PAD : D;
|
||||
if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo);
|
||||
else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo, ldx);
|
||||
const bool xf16 = m.xn_f16 && !m.xn16_lo && ldx == D; // xn16 holds FP16 (its writers and readers below)
|
||||
if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo, xf16);
|
||||
else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo, ldx, xf16);
|
||||
normed = false;
|
||||
bool hcd = false;
|
||||
bool hdown = false;
|
||||
@@ -2964,7 +2970,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
}
|
||||
hcd = true;
|
||||
}
|
||||
if (!hcd && !hdown && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, ldx != D ? ldx : 0, m.cs)) return false;
|
||||
if (!hcd && !hdown && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, ldx != D ? ldx : 0, m.cs, xf16)) return false;
|
||||
gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo);
|
||||
bool upmixed = false;
|
||||
if (wu->q8_scale == nullptr && hc_upmix() && T >= std::max(pf_switch_min_t(), hc_upmix_min_t()) && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo &&
|
||||
@@ -2994,7 +3000,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
}
|
||||
}
|
||||
if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo, 0, m.cs)) return false;
|
||||
if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, ldx != D ? ldx : 0, m.cs)) return false;
|
||||
if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, ldx != D ? ldx : 0, m.cs, xf16)) return false;
|
||||
if (upmixed) {
|
||||
} else if (gr_unfused()) {
|
||||
gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo);
|
||||
@@ -3224,11 +3230,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
}
|
||||
// STRATA_QSA_DUMP=<file>: append every QSA layer's selected cells for the prompt's last
|
||||
// STRATA_QSA_DUMP_LAST (4096) positions - records of int32 {qsa layer, pos0, T, cap} + T*cap cells,
|
||||
// for tools/qsa_locality.py (how local the sparse attention's reads are: the KV-streaming question)
|
||||
// for tools/qsa_locality.py (how local the sparse attention's reads are: the KV-streaming question).
|
||||
// STRATA_QSA_DUMP_LAYER=i: QSA layer i only; STRATA_QSA_DUMP_STEPS=1: each record then ends with the
|
||||
// T * kStepCount steps too (tests/cuda/pa_bench.cpp replays such a record)
|
||||
if (static const char* dump = std::getenv("STRATA_QSA_DUMP"); dump != nullptr) {
|
||||
static const long long last = std::getenv("STRATA_QSA_DUMP_LAST")
|
||||
? std::atoll(std::getenv("STRATA_QSA_DUMP_LAST")) : 4096;
|
||||
if (p0 + T > pos0 + n - last) {
|
||||
static const int only = std::getenv("STRATA_QSA_DUMP_LAYER") ? std::atoi(std::getenv("STRATA_QSA_DUMP_LAYER")) : -1;
|
||||
if (p0 + T > pos0 + n - last && (only < 0 || only == (int) qsa_index)) {
|
||||
std::vector<int32_t> h((size_t) (T * m.cap));
|
||||
cudaMemcpyAsync(h.data(), m.sel_ids, h.size() * 4, cudaMemcpyDeviceToHost, m.cs);
|
||||
cudaStreamSynchronize(m.cs);
|
||||
@@ -3236,6 +3245,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
const int32_t hdr[4] = {(int32_t) qsa_index, (int32_t) p0, (int32_t) T, (int32_t) m.cap};
|
||||
std::fwrite(hdr, 4, 4, f);
|
||||
std::fwrite(h.data(), 4, h.size(), f);
|
||||
if (std::getenv("STRATA_QSA_DUMP_STEPS")) {
|
||||
std::vector<int32_t> sv((size_t) (T * strata::kernels::kStepCount));
|
||||
cudaMemcpy(sv.data(), m.steps_dev, sv.size() * 4, cudaMemcpyDeviceToHost);
|
||||
std::fwrite(sv.data(), 4, sv.size(), f);
|
||||
}
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
@@ -4519,10 +4533,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
cudaMemcpyAsync(Rc, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToDevice, m.cs);
|
||||
gr_write(Rc, m.bo, m.inj, HC, T, m.cs);
|
||||
strata::kernels::cvec_apply(Rc, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);
|
||||
gr_norm_rs(Rc, (const float*) wnn->data, EPS, rc, xc, T, m.cs, nullptr, D);
|
||||
gr_norm_rs(Rc, (const float*) wnn->data, EPS, rc, xc, T, m.cs, nullptr, D, xf16);
|
||||
gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on,
|
||||
strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs,
|
||||
m.xn16, T, m.cs, m.xn16_lo, ldx);
|
||||
m.xn16, T, m.cs, m.xn16_lo, ldx, xf16);
|
||||
std::vector<float> a((size_t) T * D), b((size_t) T * D), ra((size_t) T * HC), rb((size_t) T * HC);
|
||||
std::vector<uint16_t> xa((size_t) T * D), xb((size_t) T * D);
|
||||
cudaMemcpyAsync(a.data(), m.R, a.size() * 4, cudaMemcpyDeviceToHost, m.cs);
|
||||
@@ -4541,11 +4555,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
|
||||
} else
|
||||
gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on,
|
||||
strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, m.xn16,
|
||||
T, m.cs, m.xn16_lo, ldx);
|
||||
T, m.cs, m.xn16_lo, ldx, xf16);
|
||||
normed = true;
|
||||
} else if (wnn) {
|
||||
gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs,
|
||||
m.xn16_lo, ldx);
|
||||
m.xn16_lo, ldx, xf16);
|
||||
normed = true;
|
||||
} else {
|
||||
gr_write(m.R, m.bo, m.inj, HC, T, m.cs);
|
||||
|
||||
@@ -743,8 +743,11 @@ inline bool staged_gemm(sycl::queue& q, void* handle, const uint16_t* W, int lda
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// (#2091, CUDA Turing only) no FP16 activation image on this backend
|
||||
bool Gemm::bf16_converts_x() const { return false; }
|
||||
|
||||
void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,
|
||||
float beta, int64_t ldx) {
|
||||
float beta, int64_t ldx, bool /*x_f16*/) {
|
||||
if (T <= 0 || N <= 0) return;
|
||||
if (ldy <= 0) ldy = N;
|
||||
if (ldx <= K) ldx = 0;
|
||||
|
||||
@@ -2278,7 +2278,7 @@ void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo
|
||||
}
|
||||
|
||||
void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream,
|
||||
uint16_t* xn16_lo) {
|
||||
uint16_t* xn16_lo, bool /*f16img: the Turing FP16 image of xn16 (CUDA only)*/) {
|
||||
{
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
@@ -2297,7 +2297,7 @@ void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t
|
||||
check("gr_norm");
|
||||
}
|
||||
void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream,
|
||||
uint16_t* xn16_lo, int64_t ldx) {
|
||||
uint16_t* xn16_lo, int64_t ldx, bool /*f16img*/) {
|
||||
{
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
@@ -2360,7 +2360,8 @@ bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const
|
||||
#endif
|
||||
}
|
||||
void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps,
|
||||
float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) {
|
||||
float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx,
|
||||
bool /*f16img*/) {
|
||||
{
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
@@ -2387,7 +2388,7 @@ void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_l
|
||||
}
|
||||
void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l,
|
||||
const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs,
|
||||
uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) {
|
||||
uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx, bool /*f16img*/) {
|
||||
{
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// pa_bench - the prompt path's sparse attention (qsa_prompt_attn_batch) on a recorded selection: a STRATA_QSA_DUMP
|
||||
// record of one QSA layer and chunk (int32 {layer, p0, T, cap}, T * cap cells, then T * kStepCount steps, written
|
||||
// with STRATA_QSA_DUMP_STEPS=1), random q and int8 K/V (the values do not change the work), one page per 4 cells.
|
||||
// usage: pa_bench DUMP [reps] - prints the median time and a hash of the output (for A/B of kernel variants)
|
||||
#include "strata/kernels/qsa.hpp"
|
||||
#include "strata/kernels/qsa_decode_attn.hpp"
|
||||
#include "strata/kernels/qsa_prompt_attn.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", #x, cudaGetErrorString(e_)); return 1; } } while (0)
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 2) { std::fprintf(stderr, "usage: pa_bench DUMP [reps]\n"); return 2; }
|
||||
const int reps = argc > 2 ? std::atoi(argv[2]) : 5;
|
||||
std::FILE* f = std::fopen(argv[1], "rb");
|
||||
if (!f) { std::perror(argv[1]); return 1; }
|
||||
int32_t hdr[4];
|
||||
if (std::fread(hdr, 4, 4, f) != 4) return 1;
|
||||
const int64_t p0 = hdr[1], T = hdr[2], cap = hdr[3];
|
||||
std::vector<int32_t> ids((size_t) (T * cap)), steps((size_t) (T * strata::kernels::kStepCount));
|
||||
if (std::fread(ids.data(), 4, ids.size(), f) != ids.size() || std::fread(steps.data(), 4, steps.size(), f) != steps.size()) {
|
||||
std::fprintf(stderr, "short dump (written without STRATA_QSA_DUMP_STEPS?)\n");
|
||||
return 1;
|
||||
}
|
||||
std::fclose(f);
|
||||
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
|
||||
const int64_t cells = p0 + T, HD = s.head_dim, KVH = s.n_head_kv, NH = s.n_head;
|
||||
const int64_t pages = (cells + s.page_size - 1) / s.page_size;
|
||||
std::printf("layer %d p0 %lld T %lld cap %lld, %lld cells, %lld heads / %lld KV heads x %lld\n", hdr[0], (long long) p0,
|
||||
(long long) T, (long long) cap, (long long) cells, (long long) NH, (long long) KVH, (long long) HD);
|
||||
std::mt19937 rng(7);
|
||||
std::normal_distribution<float> nd(0.0f, 1.0f);
|
||||
std::uniform_int_distribution<int> u8(-127, 127);
|
||||
std::vector<float> q((size_t) (T * NH * HD));
|
||||
for (auto& x : q) x = nd(rng);
|
||||
const size_t kv_n = (size_t) (pages * KVH * s.page_size * HD);
|
||||
std::vector<int8_t> kq(kv_n), vq(kv_n);
|
||||
for (auto& x : kq) x = (int8_t) u8(rng);
|
||||
for (auto& x : vq) x = (int8_t) u8(rng);
|
||||
const size_t sc_n = (size_t) (pages * KVH * s.page_size * (HD / 64));
|
||||
std::vector<uint16_t> ks(sc_n), vs(sc_n);
|
||||
for (size_t i = 0; i < sc_n; ++i) { ks[i] = 0x2000 + (uint16_t) (i % 512); vs[i] = 0x2000 + (uint16_t) ((i * 7) % 512); }
|
||||
std::vector<int32_t> pt((size_t) pages);
|
||||
for (int64_t i = 0; i < pages; ++i) pt[(size_t) i] = (int32_t) i;
|
||||
|
||||
float *dq, *dattn;
|
||||
int8_t *dk, *dv;
|
||||
uint16_t *dks, *dvs;
|
||||
int32_t *dids, *dsteps, *dpt;
|
||||
CK(cudaMalloc(&dq, q.size() * 4));
|
||||
CK(cudaMalloc(&dattn, (size_t) (T * NH * HD) * 4));
|
||||
CK(cudaMalloc(&dk, kv_n));
|
||||
CK(cudaMalloc(&dv, kv_n));
|
||||
CK(cudaMalloc(&dks, sc_n * 2));
|
||||
CK(cudaMalloc(&dvs, sc_n * 2));
|
||||
CK(cudaMalloc(&dids, ids.size() * 4));
|
||||
CK(cudaMalloc(&dsteps, steps.size() * 4));
|
||||
CK(cudaMalloc(&dpt, pt.size() * 4));
|
||||
CK(cudaMemcpy(dq, q.data(), q.size() * 4, cudaMemcpyHostToDevice));
|
||||
CK(cudaMemcpy(dk, kq.data(), kv_n, cudaMemcpyHostToDevice));
|
||||
CK(cudaMemcpy(dv, vq.data(), kv_n, cudaMemcpyHostToDevice));
|
||||
CK(cudaMemcpy(dks, ks.data(), sc_n * 2, cudaMemcpyHostToDevice));
|
||||
CK(cudaMemcpy(dvs, vs.data(), sc_n * 2, cudaMemcpyHostToDevice));
|
||||
CK(cudaMemcpy(dids, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice));
|
||||
CK(cudaMemcpy(dsteps, steps.data(), steps.size() * 4, cudaMemcpyHostToDevice));
|
||||
CK(cudaMemcpy(dpt, pt.data(), pt.size() * 4, cudaMemcpyHostToDevice));
|
||||
strata::kernels::QsaAttnPools pools;
|
||||
pools.k_q = dk; pools.v_q = dv; pools.k_scale = dks; pools.v_scale = dvs; pools.page_table = dpt;
|
||||
cudaStream_t st;
|
||||
CK(cudaStreamCreate(&st));
|
||||
cudaEvent_t e0, e1;
|
||||
CK(cudaEventCreate(&e0));
|
||||
CK(cudaEventCreate(&e1));
|
||||
std::vector<float> ms;
|
||||
for (int r = 0; r < reps + 1; ++r) {
|
||||
CK(cudaEventRecord(e0, st));
|
||||
if (!strata::kernels::qsa_prompt_attn_batch(dq, pools, dids, dsteps, cap, s, dattn, T, st)) {
|
||||
std::fprintf(stderr, "qsa_prompt_attn_batch declined\n");
|
||||
return 1;
|
||||
}
|
||||
CK(cudaEventRecord(e1, st));
|
||||
CK(cudaEventSynchronize(e1));
|
||||
float t = 0;
|
||||
CK(cudaEventElapsedTime(&t, e0, e1));
|
||||
if (r > 0) ms.push_back(t);
|
||||
}
|
||||
std::sort(ms.begin(), ms.end());
|
||||
std::vector<float> out((size_t) (T * NH * HD));
|
||||
CK(cudaMemcpy(out.data(), dattn, out.size() * 4, cudaMemcpyDeviceToHost));
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
for (float x : out) { uint32_t b; std::memcpy(&b, &x, 4); h = (h ^ b) * 1099511628211ull; }
|
||||
double ss = 0;
|
||||
for (float x : out) ss += (double) x * x;
|
||||
std::printf("prompt attention: median %.3f ms (min %.3f) over %d; output hash %016llx, rms %.6g\n", ms[ms.size() / 2],
|
||||
ms[0], reps, (unsigned long long) h, std::sqrt(ss / (double) out.size()));
|
||||
if (const char* o = std::getenv("PA_BENCH_OUT")) { // the output, for an accuracy comparison of two variants
|
||||
if (std::FILE* g = std::fopen(o, "wb")) { std::fwrite(out.data(), 4, out.size(), g); std::fclose(g); }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -666,7 +666,9 @@ int main(int argc, char** argv) {
|
||||
{GGML_TYPE_Q5_K, GGML_TYPE_Q5_1, "Q5_K / Q5_1"}, {GGML_TYPE_Q5_K, GGML_TYPE_Q8_0, "Q5_K / Q8_0"},
|
||||
// the Coder IQ1_M pack's other pairs (appended: the default timing set takes pairs 0, 1, 4, 3 by index)
|
||||
{GGML_TYPE_IQ2_S, GGML_TYPE_IQ4_NL, "IQ2_S / IQ4_NL"}, {GGML_TYPE_IQ3_XXS, GGML_TYPE_Q2_0, "IQ3_XXS / Q2_0"},
|
||||
{GGML_TYPE_IQ3_S, GGML_TYPE_Q2_0, "IQ3_S / Q2_0"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_IQ4_NL, "IQ4_XS / IQ4_NL"}};
|
||||
{GGML_TYPE_IQ3_S, GGML_TYPE_Q2_0, "IQ3_S / Q2_0"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_IQ4_NL, "IQ4_XS / IQ4_NL"},
|
||||
// the canonical Q2_0 pack (gate/up and down Q2_0; CUDA)
|
||||
{GGML_TYPE_Q2_0, GGML_TYPE_Q2_0, "Q2_0 / Q2_0"}};
|
||||
const char* only = nullptr; // --only=NAME: the pairs whose name contains NAME
|
||||
for (int i = 1; i < argc; ++i)
|
||||
if (std::strncmp(argv[i], "--only=", 7) == 0) only = argv[i] + 7;
|
||||
@@ -688,14 +690,22 @@ int main(int argc, char** argv) {
|
||||
ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
|
||||
for (const Pair& p : pairs) {
|
||||
if (only ? std::string(p.name).find(only) == std::string::npos : p.gu == GGML_TYPE_Q4_K || p.gu == GGML_TYPE_Q5_K) continue;
|
||||
if (!fused::native_supported((int) p.gu, (int) p.d))
|
||||
if (!fused::native_supported((int) p.gu, (int) p.d)) {
|
||||
// the canonical Q2_0 pack's Q2_0 gate/up is the Turing opt-in's (STRATA_PF_FUSED_SM75=1), and on Turing that is
|
||||
// the only pair set up: skip what this device does not take (--only=NAME still insists)
|
||||
const bool turing_pair = p.gu == GGML_TYPE_Q2_0 && p.d == GGML_TYPE_Q2_0;
|
||||
int major = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, 0);
|
||||
if ((major < 8 || turing_pair) && !only) { std::printf("%s: not set up on this device (skipped)\n", p.name); continue; }
|
||||
throw std::runtime_error(std::string(p.name) + ": not covered by the native kernels");
|
||||
}
|
||||
if (ref) reference_part(p, s);
|
||||
}
|
||||
if (timing) {
|
||||
// the IQ2_XS pack's layers (34 of 48 IQ2_S / Q2_0, 11 IQ2_XXS / Q2_0), the IQ3_S pack's most common, IQ3_XXS's
|
||||
for (const Pair& p : only ? pairs : std::vector<Pair>{pairs[0], pairs[1], pairs[4], pairs[3]}) {
|
||||
if (only && std::string(p.name).find(only) == std::string::npos) continue;
|
||||
if (!fused::native_supported((int) p.gu, (int) p.d)) continue; // (Turing: the Q2_0 pair only)
|
||||
for (int T : chunks) timing_part(p, T, s);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user