Merge branch 'f-139b-old' into f-139-rel
# Conflicts: # setup.py
This commit is contained in:
commit
bd34d0d87e
65 files changed
+6759
-123
No files matched your search
+12
-2
@@ -212,7 +212,7 @@ std::string gpu_arch_problem(int ordinal) {
|
||||
}
|
||||
|
||||
std::string device_code_error() {
|
||||
#if defined(STRATA_USE_HIP)
|
||||
#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
|
||||
return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point
|
||||
#else
|
||||
// every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all
|
||||
@@ -263,7 +263,17 @@ DeviceInfo device_info(int ordinal) {
|
||||
// supported arch is enforced by CMake; RUNNING on an older card is caught here, because a binary can be carried
|
||||
// to a machine with an older card and would otherwise silently take whatever path the driver chose. The HIP
|
||||
// backend checks the card against the architectures the binary was compiled for (and wave32).
|
||||
#if defined(STRATA_USE_HIP)
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// AMD gfx906 (the STRATA_HIP_GFX906 compat build, not STRATA_USE_HIP): the build targets one gfx arch
|
||||
// (CMAKE_HIP_ARCHITECTURES, wave64); a card of another arch fails at the first kernel launch with
|
||||
// hipErrorInvalidDeviceFunction. gcnArchName says which it is.
|
||||
{
|
||||
std::string arch(p.gcnArchName);
|
||||
if (const size_t colon = arch.find(':'); colon != std::string::npos) arch.resize(colon);
|
||||
d.arch = arch;
|
||||
}
|
||||
if (p.gcnArchName[0] != 0) d.name += std::string(" (") + p.gcnArchName + ")";
|
||||
#elif defined(STRATA_USE_HIP)
|
||||
d.arch = base_arch(p.gcnArchName);
|
||||
if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1);
|
||||
#else
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
// src/core/expert_cache.cpp - R4's slot storage and residency table. Read the header first.
|
||||
#include "strata/core/expert_cache.hpp"
|
||||
|
||||
// #533's segmented cache uses CUDA's virtual memory management (cuMem*): not on HIP, neither the RDNA backend nor
|
||||
// the gfx906 compat build (PR #638), which compiles this file as HIP without STRATA_USE_HIP
|
||||
#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
|
||||
#define STRATA_EC_NO_VMM 1
|
||||
#endif
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
#if !defined(STRATA_USE_HIP)
|
||||
#if !defined(STRATA_EC_NO_VMM)
|
||||
#include <cuda.h> // #533: the virtual memory management types (the functions come through the runtime's entry points)
|
||||
#endif
|
||||
|
||||
@@ -148,7 +154,7 @@ ExpertCache::~ExpertCache() { close(); }
|
||||
// ---- #533: the segmented arena (--vram-elastic). The driver API's virtual memory functions, looked up through the
|
||||
// runtime (no link against the driver library): one address range for the whole arena, backed by physical segments,
|
||||
// and the tail's segments unmapped / mapped again later. Nothing here runs unless a segment size was set.
|
||||
#if !defined(STRATA_USE_HIP)
|
||||
#if !defined(STRATA_EC_NO_VMM)
|
||||
namespace {
|
||||
struct Vmm {
|
||||
CUresult (CUDAAPI* device_get)(CUdevice*, int) = nullptr;
|
||||
@@ -227,7 +233,7 @@ bool map_segment(const Vmm& v, int dev, CUdeviceptr va, size_t bytes, unsigned l
|
||||
#endif
|
||||
|
||||
bool ExpertCache::open_segmented(uint64_t want, std::string& err) {
|
||||
#if defined(STRATA_USE_HIP)
|
||||
#if defined(STRATA_EC_NO_VMM)
|
||||
(void) want;
|
||||
err = "ExpertCache: --vram-elastic (a segmented expert cache) is CUDA-only for now";
|
||||
return false;
|
||||
@@ -280,7 +286,7 @@ bool ExpertCache::open_segmented(uint64_t want, std::string& err) {
|
||||
}
|
||||
|
||||
void ExpertCache::release_segmented() {
|
||||
#if !defined(STRATA_USE_HIP)
|
||||
#if !defined(STRATA_EC_NO_VMM)
|
||||
const Vmm& v = vmm();
|
||||
if (base_ != nullptr) cudaDeviceSynchronize();
|
||||
const CUdeviceptr va = reinterpret_cast<CUdeviceptr>(base_);
|
||||
@@ -318,7 +324,7 @@ bool ExpertCache::shrink(int64_t keep_bytes, std::string& err) {
|
||||
err = "the expert cache is not segmented (the engine needs --vram-elastic)";
|
||||
return false;
|
||||
}
|
||||
#if defined(STRATA_USE_HIP)
|
||||
#if defined(STRATA_EC_NO_VMM)
|
||||
(void) keep_bytes;
|
||||
return false;
|
||||
#else
|
||||
@@ -352,7 +358,7 @@ bool ExpertCache::grow(int64_t want_bytes, std::string& err) {
|
||||
err = "the expert cache is not segmented (the engine needs --vram-elastic)";
|
||||
return false;
|
||||
}
|
||||
#if defined(STRATA_USE_HIP)
|
||||
#if defined(STRATA_EC_NO_VMM)
|
||||
(void) want_bytes;
|
||||
return false;
|
||||
#else
|
||||
|
||||
@@ -387,6 +387,34 @@ if (db != nullptr && g_publish_kernel) {
|
||||
// write idempotent across replays of the same graph - a captured literal would ring the same number
|
||||
// forever and the host would never see a change.
|
||||
strata::kernels::doorbell_ring(db->d_seq, stream); } return true;}
|
||||
// The verify window's routing: n tokens' logits in one BF16 projection and their top-k in one launch, each token
|
||||
// bitwise what `moe_route` gives it (the projection is the same kernel per column, the top-k kernel is per token).
|
||||
// Anything else (a native router, the canonical BF16 GEMVs, a doorbell) takes the per-token `moe_route`.
|
||||
bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
|
||||
const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err) {
|
||||
using namespace strata::kernels;
|
||||
const bool batched = native_bf16_projections && !(native_router_enabled() && g.n_expert == 512 && k == 10) &&
|
||||
!std::getenv("STRATA_ROUTE_PER_TOKEN");
|
||||
if (!batched || n == 1) {
|
||||
for (int t = 0; t < n; ++t) {
|
||||
MoEBuffers mb = b;
|
||||
mb.logits = logits + t * g.n_expert; mb.ids = ids + t * k; mb.weights = weights + t * k;
|
||||
if (!moe_route(tables, g, layer, k, mb, x + t * g.n_embd, stream, err, nullptr)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const LayerView v(tables, layer);
|
||||
const WeightRef* w_router = v.get("ffn_gate_inp.weight");
|
||||
if (w_router == nullptr) { err = v.name("ffn_gate_inp.weight") + " is missing"; return false; }
|
||||
if (std::getenv("STRATA_ROUTE_PROJ_PER_TOKEN"))
|
||||
for (int t = 0; t < n; ++t)
|
||||
bf16_gemv_fp32_mmvf(x + t * g.n_embd, (const uint16_t*) w_router->data, logits + t * g.n_expert, g.n_embd,
|
||||
g.n_expert, stream);
|
||||
else
|
||||
bf16_gemv_fp32_mmvf_cols(x, (const uint16_t*) w_router->data, logits, g.n_embd, g.n_expert, n, stream);
|
||||
router_top10(logits, n, (int) g.n_expert, (int) k, ids, weights, stream);
|
||||
return true;
|
||||
}
|
||||
bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b, const float* x, void* stream, std::string& err) { using namespace strata::kernels; const LayerView v(tables, layer); const WeightRef* w_ginp = v.get("ffn_gate_inp_shexp.weight"); const WeightRef* w_sgate = v.get("ffn_gate_shexp.weight"); const WeightRef* w_sup = v.get("ffn_up_shexp.weight"); const WeightRef* w_sdown = v.get("ffn_down_shexp.weight"); const char* missing = !w_ginp ? "ffn_gate_inp_shexp.weight" : !w_sgate ? "ffn_gate_shexp.weight" : !w_sup ? "ffn_up_shexp.weight" : !w_sdown ? "ffn_down_shexp.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; }
|
||||
// ---- the shared expert. Its three weights are quantized, so they need their planes.
|
||||
SForm f_gate, f_up, f_down; if (!sform_of(*w_sgate, f_gate, v.name("ffn_gate_shexp.weight"), err)) return false; if (!sform_of(*w_sup, f_up, v.name("ffn_up_shexp.weight"), err)) return false; if (!sform_of(*w_sdown, f_down, v.name("ffn_down_shexp.weight"), err)) return false; Planes p_gate, p_up, p_down; if (!plane_ptrs(*w_sgate, v.name("ffn_gate_shexp.weight"), p_gate, err)) return false; if (!plane_ptrs(*w_sup, v.name("ffn_up_shexp.weight"), p_up, err)) return false; if (!plane_ptrs(*w_sdown, v.name("ffn_down_shexp.weight"), p_down, err)) return false;
|
||||
|
||||
+2
-2
@@ -452,7 +452,7 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::
|
||||
std::mutex err_mu;
|
||||
std::string err;
|
||||
const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
|
||||
std::vector<wchar_t> wpath((size_t) std::max(wide, 1), L'\0');
|
||||
std::vector<wchar_t> wpath((size_t) (std::max)(wide, 1), L'\0');
|
||||
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
|
||||
auto worker = [&]() {
|
||||
HANDLE h = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
@@ -520,7 +520,7 @@ bool experts_unbuffered(const std::vector<std::string>& files, uint64_t arena_by
|
||||
uint64_t seed = (uint64_t) GetTickCount64() * 6364136223846793005ull + 1442695040888963407ull;
|
||||
for (const std::string& f : files) {
|
||||
const int wide = MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, nullptr, 0);
|
||||
std::vector<wchar_t> w((size_t) std::max(wide, 1), L'\0');
|
||||
std::vector<wchar_t> w((size_t) (std::max)(wide, 1), L'\0');
|
||||
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, w.data(), wide);
|
||||
HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS,
|
||||
nullptr);
|
||||
|
||||
@@ -801,6 +801,15 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
NE, n, cs);
|
||||
native_router_top10_multi(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, cs);
|
||||
} catch (const std::exception& e) { err = "verify router: " + std::string(e.what()); return false; }
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
} else if (dec_batch) {
|
||||
// gfx906: the Coder's 256-expert router (the native router is 512 x 10 only) for the whole window in one
|
||||
// multi-column BF16 projection and one top-k, bitwise the per-token calls (route_window_parity); ~3 ms
|
||||
// of a ~55 ms verify window on 2x MI50. STRATA_ROUTE_PER_TOKEN=1: the per-token calls.
|
||||
if (!moe_route_window(wt, g, l, K, ss.moe, mixed_ + tb * N, logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n,
|
||||
cs, err))
|
||||
return false;
|
||||
#endif
|
||||
} else
|
||||
for (int t = tb; t < te; ++t) {
|
||||
MoEBuffers mb = ss.moe;
|
||||
|
||||
@@ -712,7 +712,11 @@ int down_chunk(bool staged, int* tile_out) {
|
||||
// the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and
|
||||
// the up kernel below still sees every token of the batch in one launch.
|
||||
#if defined(__HIPCC__)
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
const bool small_tile = false; // gfx906: 64 KiB LDS, the 2560 tile as before (8 tokens slice into launches)
|
||||
#else
|
||||
const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile
|
||||
#endif
|
||||
#else
|
||||
int cc_maj = 0, cc_min = 0;
|
||||
cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
@@ -759,10 +763,26 @@ int down_chunk(bool staged, int* tile_out) {
|
||||
// many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection.
|
||||
// kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi
|
||||
// takes first).
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m); // below, with the AMD fast path
|
||||
__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m);
|
||||
} // namespace
|
||||
static bool gr_fast();
|
||||
namespace {
|
||||
#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;
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// gfx906: the latency-hidden norm/up (STRATA_GR_FAST=0: off) - the same sums in the same order as the kernels
|
||||
// they replace (gr_parity checks the multi-token read against single-token calls bitwise)
|
||||
const bool fast = gr_fast();
|
||||
if (variant >= kHcSplit) gr_norm_split_kernel<<<dim3((unsigned) n_tok, HC), THREADS, 0, st>>>(m);
|
||||
else if (fast) gr_norm_fast_kernel<<<n_tok, THREADS, 0, st>>>(m);
|
||||
else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m);
|
||||
#else
|
||||
if (variant >= kHcSplit) gr_norm_split_kernel<<<dim3((unsigned) n_tok, HC), THREADS, 0, st>>>(m);
|
||||
else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m);
|
||||
#endif
|
||||
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st);
|
||||
const bool staged = variant >= kHcStaged;
|
||||
int tv = 2560;
|
||||
@@ -796,6 +816,10 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long
|
||||
}
|
||||
}
|
||||
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st);
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
if (fast) gr_up_fast_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
|
||||
else
|
||||
#endif
|
||||
gr_up_multi_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
|
||||
}
|
||||
|
||||
@@ -811,8 +835,230 @@ int env_variant() {
|
||||
// per device: the variant `fused_gr_check` chose (0 = not checked yet)
|
||||
std::atomic<int> g_variant[64];
|
||||
|
||||
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// ---- AMD fast path (STRATA_GR_FAST, default 1; 0 = the old kernels): the same arithmetic per value in the same order, latency
|
||||
// hidden. gr_norm: one block per token (as before) but a thread's 10 float4 of R / bo / w_norm are loaded
|
||||
// before any is used, and xn stays in registers until rs is known (was: store, then re-read the 40 KB).
|
||||
// gr_up: a warp's 8 rows of w_up and their epilogue inputs are loaded before the dots (was: one row's load chain
|
||||
// after another).
|
||||
constexpr int NQ = D / (THREADS * 4); // 10 float4 per thread
|
||||
static_assert(D % (THREADS * 4) == 0, "whole float4 per thread");
|
||||
__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m) {
|
||||
__shared__ float part[WARPS][HC];
|
||||
__shared__ float s_rs[HC];
|
||||
const FusedGrArgs& a = m.a[blockIdx.x];
|
||||
float* xn = m.xn + (size_t) blockIdx.x * D;
|
||||
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
float gw[HC];
|
||||
#pragma unroll
|
||||
for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
|
||||
float4 r[NQ], g[NQ];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NQ; ++k) {
|
||||
const int i = t * 4 + k * THREADS * 4;
|
||||
r[k] = *reinterpret_cast<const float4*>(a.R + i);
|
||||
g[k] = *reinterpret_cast<const float4*>(a.w_norm + i);
|
||||
}
|
||||
if (a.apply) {
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NQ; ++k) {
|
||||
const int i = t * 4 + k * THREADS * 4, c = i / N, d = i - c * N;
|
||||
const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + d);
|
||||
r[k].x = fmaf(b.x, gw[c], r[k].x); r[k].y = fmaf(b.y, gw[c], r[k].y);
|
||||
r[k].z = fmaf(b.z, gw[c], r[k].z); r[k].w = fmaf(b.w, gw[c], r[k].w);
|
||||
}
|
||||
}
|
||||
float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f};
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NQ; ++k) {
|
||||
const int i = t * 4 + k * THREADS * 4, c = i / N;
|
||||
const float sq = r[k].x * r[k].x + r[k].y * r[k].y + r[k].z * r[k].z + r[k].w * r[k].w;
|
||||
#pragma unroll
|
||||
for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq;
|
||||
r[k] = make_float4(r[k].x * g[k].x, r[k].y * g[k].y, r[k].z * g[k].z, r[k].w * g[k].w);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int c = 0; c < HC; ++c) {
|
||||
const float v = warp_sum(ss[c]);
|
||||
if (lane == 0) part[warp][c] = v;
|
||||
}
|
||||
__syncthreads();
|
||||
if (t < HC) {
|
||||
float s = 0.0f;
|
||||
for (int w = 0; w < WARPS; ++w) s += part[w][t];
|
||||
s_rs[t] = rsqrtf(s / (float) N + a.eps);
|
||||
a.rs[t] = s_rs[t];
|
||||
}
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NQ; ++k) {
|
||||
const int i = t * 4 + k * THREADS * 4;
|
||||
const float sr = s_rs[i / N];
|
||||
*reinterpret_cast<float4*>(xn + i) = make_float4(r[k].x * sr, r[k].y * sr, r[k].z * sr, r[k].w * sr);
|
||||
}
|
||||
}
|
||||
// gr_up: 8 lanes per row instead of a 32-lane warp. Lane j holds the old lanes j, j+8, j+16, j+24 (and chunk
|
||||
// 32+j, the old lane j's second chunk): the xor tree's stages 16 and 8 are its own adds (a + b == b + a), stages
|
||||
// 4, 2, 1 are shuffles inside the 8 - the same tree, bitwise the same sum, 3 shuffles a token instead of 5 and no
|
||||
// idle lanes on the tail chunks. A block's 64 rows are 2 passes of 32 groups, their weights loaded up front.
|
||||
__device__ __forceinline__ float xor8(float v) {
|
||||
#pragma unroll
|
||||
for (int o = 4; o > 0; o >>= 1) v += __shfl_xor(v, o, 64);
|
||||
return v;
|
||||
}
|
||||
__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m) {
|
||||
__shared__ __align__(16) float lo[kFusedGrMaxT][LR];
|
||||
__shared__ float g[kFusedGrMaxT][HC][UPM_COLS];
|
||||
const int t = threadIdx.x, j = t & 7, grp = t >> 3;
|
||||
const int T = m.T;
|
||||
const int d0 = blockIdx.x * UPM_COLS;
|
||||
static_assert(LR == 40 * 8 && HC * UPM_COLS == 64 && THREADS == 256, "geometry");
|
||||
uint4 w[2][5];
|
||||
float rv[2] = {0.0f, 0.0f}, wn[2] = {0.0f, 0.0f}, rsc[2] = {0.0f, 0.0f}, bo[2] = {0.0f, 0.0f}, ip[2] = {0.0f, 0.0f};
|
||||
const bool apply = j < T && m.a[j < T ? j : 0].apply;
|
||||
#pragma unroll
|
||||
for (int p = 0; p < 2; ++p) {
|
||||
const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;
|
||||
const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR);
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) w[p][q] = __ldg(w4 + j + 8 * q);
|
||||
w[p][4] = __ldg(w4 + 32 + j);
|
||||
if (j < T) {
|
||||
const FusedGrArgs& a = m.a[j];
|
||||
rv[p] = a.R[i];
|
||||
wn[p] = a.w_norm[i];
|
||||
rsc[p] = a.rs[c];
|
||||
if (apply) { bo[p] = a.bo_prev[d0 + dd]; ip[p] = a.inj_prev[c]; }
|
||||
}
|
||||
}
|
||||
for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR];
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int p = 0; p < 2; ++p) {
|
||||
const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;
|
||||
float mine = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) {
|
||||
if (k >= T) break;
|
||||
const float* l = lo[k];
|
||||
const float p0 = dot8(w[p][0], l + j * 8) + dot8(w[p][4], l + (32 + j) * 8); // old lane j
|
||||
const float p1 = dot8(w[p][1], l + (j + 8) * 8); // old lane j + 8
|
||||
const float p2 = dot8(w[p][2], l + (j + 16) * 8); // old lane j + 16
|
||||
const float p3 = dot8(w[p][3], l + (j + 24) * 8); // old lane j + 24
|
||||
const float s = xor8((p0 + p2) + (p1 + p3)); // stage 16: (j, j+16), (j+8, j+24); stage 8; then 4, 2, 1
|
||||
if (j == k) mine = s;
|
||||
}
|
||||
if (j < T) {
|
||||
float x0 = rv[p];
|
||||
if (apply) {
|
||||
x0 = fmaf(bo[p], 2.0f * sigmoidf_(ip[p] / (float) HC), x0);
|
||||
m.a[j].R_out[i] = x0;
|
||||
}
|
||||
const float x = x0 * wn[p] * rsc[p];
|
||||
g[j][c][dd] = x * sigmoidf_(mine);
|
||||
}
|
||||
}
|
||||
__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;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// ---- AMD: `gr_down_multi` split along K. The CUDA kernel is one warp per row of w_down (320 + 4 rows), 41
|
||||
// blocks: on a 60-CU gfx906 that left most of the card idle and read the 6.5 MB matrix at ~100 GB/s. Here a block
|
||||
// is 8 wavefronts = 8 rows of one K-slice of 2048 (the slice of every token's xn staged in LDS once), 41 x 5
|
||||
// blocks, and a second kernel adds the 5 slice sums in a fixed order and runs the epilogue. A token's result does
|
||||
// not depend on how many tokens share the window (each column is reduced on its own).
|
||||
constexpr int GS_SL = 2048; // K per slice
|
||||
constexpr int GS_S = D / GS_SL; // 5 slices
|
||||
constexpr int GS_ROWS = LR + HC; // 324: the down rows, then the inject rows
|
||||
constexpr int GS_WAVES = 8;
|
||||
static_assert(D % GS_SL == 0 && GS_SL == 64 * 8 * 4, "a lane takes 4 chunks of 8 per slice");
|
||||
// the slice sums: a module-scope device array is per device by construction, and needs no allocation during a
|
||||
// graph capture
|
||||
__device__ float g_gr_part[GS_S * kFusedGrMaxT * GS_ROWS];
|
||||
__global__ void __launch_bounds__(GS_WAVES * 64) gr_down_split_kernel(GrMulti m) {
|
||||
float* part = g_gr_part;
|
||||
extern __shared__ __align__(16) float tile[]; // [T][GS_SL]
|
||||
const int t = threadIdx.x, lane = t & 63, wave = t >> 6;
|
||||
const int T = m.T, sl = blockIdx.y;
|
||||
const bool inject_block = blockIdx.x == DOWN_BLOCKS;
|
||||
const int row = inject_block ? wave : blockIdx.x * GS_WAVES + wave;
|
||||
const bool active = !(inject_block && (m.a[0].w_inject == nullptr || wave >= HC));
|
||||
const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D;
|
||||
const uint4* w4 = reinterpret_cast<const uint4*>(wrow) + sl * (GS_SL / 8);
|
||||
uint4 wv[4];
|
||||
if (active) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) wv[q] = __ldg(w4 + lane + 64 * q);
|
||||
}
|
||||
const float4* src4 = reinterpret_cast<const float4*>(m.xn);
|
||||
float4* tile4 = reinterpret_cast<float4*>(tile);
|
||||
for (int i = t; i < T * (GS_SL / 4); i += GS_WAVES * 64) {
|
||||
const int k = i / (GS_SL / 4), off = i - k * (GS_SL / 4);
|
||||
tile4[i] = src4[((size_t) k * D + (size_t) sl * GS_SL) / 4 + off];
|
||||
}
|
||||
__syncthreads();
|
||||
if (!active) return;
|
||||
float acc[kFusedGrMaxT];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
const int j = lane + 64 * q;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k)
|
||||
if (k < T) acc[k] += dot8(wv[q], tile + k * GS_SL + j * 8);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) {
|
||||
if (k >= T) break;
|
||||
float v = acc[k];
|
||||
#pragma unroll
|
||||
for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64);
|
||||
if (lane == 0) part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + (inject_block ? LR + row : row)] = v;
|
||||
}
|
||||
}
|
||||
__global__ void gr_down_finish_kernel(GrMulti m) {
|
||||
const float* part = g_gr_part;
|
||||
const int i = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
const int k = i / GS_ROWS, r = i - k * GS_ROWS;
|
||||
if (k >= m.T) return;
|
||||
const bool inject = r >= LR;
|
||||
if (inject && m.a[0].w_inject == nullptr) return;
|
||||
float s = 0.0f;
|
||||
#pragma unroll
|
||||
for (int sl = 0; sl < GS_S; ++sl) s += part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + r];
|
||||
if (inject) {
|
||||
m.a[k].inject_out[r - LR] = s;
|
||||
} else {
|
||||
const float x = s / (float) HC;
|
||||
m.a[k].lo[r] = x / (1.0f + __expf(-x));
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
int g_gr_fast = -1; // fused_gr_set_fast (the bench); -1 = STRATA_GR_FAST
|
||||
static bool gr_fast() {
|
||||
static const bool env = [] { const char* v = std::getenv("STRATA_GR_FAST"); return v ? std::atoi(v) != 0 : true; }();
|
||||
return g_gr_fast >= 0 ? g_gr_fast != 0 : env;
|
||||
}
|
||||
#else
|
||||
int g_gr_fast = -1;
|
||||
#endif
|
||||
void fused_gr_set_fast(int on) { g_gr_fast = on; }
|
||||
|
||||
void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf,
|
||||
int stamp_i0) {
|
||||
if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) {
|
||||
@@ -875,6 +1121,31 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
|
||||
}
|
||||
return;
|
||||
}
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// gfx906, opt-in STRATA_GR_SPLIT=1: the latency-hidden norm/up (STRATA_GR_FAST) with the K-split down (~3% faster
|
||||
// per verify window). Its fixed-order finish sums the K slices in another order than the single-token
|
||||
// fused_gr_read, so the multi-token read is then no longer bitwise equal to T single-token calls (gr_parity's
|
||||
// contract); off by default for that reason.
|
||||
static const bool split_on = std::getenv("STRATA_GR_SPLIT") && std::string(std::getenv("STRATA_GR_SPLIT")) == "1";
|
||||
if (split_on) {
|
||||
const bool fast = gr_fast();
|
||||
if (fast) gr_norm_fast_kernel<<<n_tok, THREADS, 0, st>>>(m);
|
||||
else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m);
|
||||
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream);
|
||||
gr_down_split_kernel<<<dim3(DOWN_BLOCKS + 1, GS_S), GS_WAVES * 64, (size_t) n_tok * GS_SL * sizeof(float), st>>>(
|
||||
m);
|
||||
gr_down_finish_kernel<<<(unsigned) ((n_tok * GS_ROWS + 255) / 256), 256, 0, st>>>(m);
|
||||
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream);
|
||||
if (fast) gr_up_fast_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
|
||||
else gr_up_multi_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e));
|
||||
std::exit(1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
// the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check accepted
|
||||
launch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <type_traits>
|
||||
|
||||
namespace strata::kernels {
|
||||
namespace {
|
||||
@@ -40,6 +41,18 @@ __device__ __forceinline__ uint32_t unpack_ksigns(const uint8_t v) {
|
||||
return s * 0x01010101;
|
||||
}
|
||||
__device__ __forceinline__ int2 get_int_from_table_16(const int& q4, const int8_t* table) {
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// AMD: llama.cpp's HIP lookup (vecdotq.cuh) - v_perm_b32 takes 3-bit byte indices, so the low and high halves
|
||||
// of the table are looked up and the index MSB picks between them: 4 perms per 8 values.
|
||||
const uint32_t* v32 = reinterpret_cast<const uint32_t*>(table);
|
||||
const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;
|
||||
const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);
|
||||
const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);
|
||||
const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);
|
||||
const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);
|
||||
return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),
|
||||
(int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));
|
||||
#else
|
||||
const uint32_t* table32 = (const uint32_t*) table;
|
||||
uint32_t tmp[2];
|
||||
const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1));
|
||||
@@ -51,6 +64,7 @@ __device__ __forceinline__ int2 get_int_from_table_16(const int& q4, const int8_
|
||||
tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift);
|
||||
}
|
||||
return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531));
|
||||
#endif
|
||||
}
|
||||
#define ggml_cuda_dp4a(a, b, c) STRATA_DP4A((a), (b), (c))
|
||||
|
||||
@@ -1212,6 +1226,16 @@ __device__ void dq_q2_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int i = part * 8 + j;
|
||||
const int code = (x[b].qs[i / 4] >> ((i % 4) * 2)) & 3;
|
||||
#if defined(__HIPCC__) && defined(__gfx1012__) && HIP_VERSION_MAJOR < 7
|
||||
// HIP 5.7 on RDNA1 folds the half path's negative scale times +0
|
||||
// to +0. Preserve the scale's sign, as the FP32/CPU paths do.
|
||||
if constexpr (std::is_same_v<dst_t, __half>) {
|
||||
if (code == 1) {
|
||||
yy[b * 64 + i] = __ushort_as_half(__half_as_ushort(x[b].d) & 0x8000u);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
yy[b * 64 + i] = cvt<dst_t>(d * (float) (code - 1));
|
||||
}
|
||||
}
|
||||
@@ -1533,6 +1557,560 @@ size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) {
|
||||
return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255);
|
||||
}
|
||||
|
||||
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// ---- AMD layouts for the grouped native experts (STRATA_EXP_MODE; 0 = the CUDA one above).
|
||||
// 1 (W64): a row per 64-lane wavefront - 4x the wavefronts, ~1-2 calls per lane, a 64-lane butterfly.
|
||||
// 2 (R2): a 32-lane logical warp computes TWO rows in one loop - two independent load chains in flight.
|
||||
// Either way a (row, entry) sum does not depend on the window size.
|
||||
template<int TY>
|
||||
__device__ __forceinline__ float row_dot64(const uint8_t* row, const block_q8_1* x, int nb, int lane) {
|
||||
using F = Fmt<TY>;
|
||||
float s = 0.0f;
|
||||
for (int k = lane; k < nb * F::ipb; k += 64) {
|
||||
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
|
||||
s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int o = 32; o > 0; o >>= 1) s += __shfl_xor(s, o, 64);
|
||||
return s;
|
||||
}
|
||||
template<int TY>
|
||||
__device__ __forceinline__ void row_dot2(const uint8_t* r0, const uint8_t* r1, const block_q8_1* x, int nb, int lane,
|
||||
float& o0, float& o1) {
|
||||
using F = Fmt<TY>;
|
||||
float s0 = 0.0f, s1 = 0.0f;
|
||||
for (int k = lane; k < nb * F::ipb; k += 32) {
|
||||
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
|
||||
const block_q8_1* xk = x + kbx * (F::qk / 32);
|
||||
const float a = F::dot(r0, xk, kbx, iqs);
|
||||
const float b = F::dot(r1, xk, kbx, iqs);
|
||||
s0 += a;
|
||||
s1 += b;
|
||||
}
|
||||
o0 = warp_sum(s0);
|
||||
o1 = warp_sum(s1);
|
||||
}
|
||||
template<int TY, int NR>
|
||||
__device__ __forceinline__ void row_dotn(const uint8_t* const* r, const block_q8_1* x, int nb, int lane, float* o) {
|
||||
using F = Fmt<TY>;
|
||||
float acc[NR];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NR; ++i) acc[i] = 0.0f;
|
||||
for (int k = lane; k < nb * F::ipb; k += 32) {
|
||||
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
|
||||
const block_q8_1* xk = x + kbx * (F::qk / 32);
|
||||
float d[NR];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NR; ++i) d[i] = F::dot(r[i], xk, kbx, iqs);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NR; ++i) acc[i] += d[i];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NR; ++i) o[i] = warp_sum(acc[i]);
|
||||
}
|
||||
template<int TG, int MODE>
|
||||
__global__ void __launch_bounds__(256) native_gu_amd_kernel(const unsigned long long* __restrict__ grp_ptr,
|
||||
const int32_t* __restrict__ grp_start,
|
||||
const int32_t* __restrict__ n_groups,
|
||||
const int32_t* __restrict__ ent_tok,
|
||||
const block_q8_1* __restrict__ xq, NativeExpertLayout L,
|
||||
float* __restrict__ gate, float* __restrict__ up) {
|
||||
const int g = blockIdx.y;
|
||||
if (g >= *n_groups) return;
|
||||
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
|
||||
const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
|
||||
const int e0 = grp_start[g], e1 = grp_start[g + 1];
|
||||
const int nrow = 2 * (int) L.n_ff;
|
||||
auto wrow = [&](int row) -> const uint8_t* {
|
||||
const bool is_up = row >= L.n_ff;
|
||||
return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;
|
||||
};
|
||||
auto put = [&](int row, int e, float v) {
|
||||
const bool is_up = row >= L.n_ff;
|
||||
(is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;
|
||||
};
|
||||
if constexpr (MODE == 1) {
|
||||
const int lane = threadIdx.x & 63, row = blockIdx.x * 4 + (threadIdx.x >> 6);
|
||||
if (row >= nrow) return;
|
||||
const uint8_t* wr = wrow(row);
|
||||
for (int e = e0; e < e1; ++e) {
|
||||
const float v = row_dot64<TG>(wr, xq + (size_t) ent_tok[e] * xb, nb, lane);
|
||||
if (lane == 0) put(row, e, v);
|
||||
}
|
||||
} else if constexpr (MODE == 4) {
|
||||
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
|
||||
const int row0 = blockIdx.x * 32 + warp;
|
||||
if (row0 >= nrow) return;
|
||||
const uint8_t* w[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) w[i] = wrow(row0 + 8 * i < nrow ? row0 + 8 * i : row0);
|
||||
for (int e = e0; e < e1; ++e) {
|
||||
float o[4];
|
||||
row_dotn<TG, 4>(w, xq + (size_t) ent_tok[e] * xb, nb, lane, o);
|
||||
if (lane == 0)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) if (row0 + 8 * i < nrow) put(row0 + 8 * i, e, o[i]);
|
||||
}
|
||||
} else {
|
||||
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
|
||||
const int row0 = blockIdx.x * 16 + warp, row1 = row0 + 8;
|
||||
if (row0 >= nrow) return;
|
||||
const bool two = row1 < nrow;
|
||||
const uint8_t* w0 = wrow(row0);
|
||||
const uint8_t* w1 = wrow(two ? row1 : row0);
|
||||
for (int e = e0; e < e1; ++e) {
|
||||
float a, b;
|
||||
row_dot2<TG>(w0, w1, xq + (size_t) ent_tok[e] * xb, nb, lane, a, b);
|
||||
if (lane == 0) { put(row0, e, a); if (two) put(row1, e, b); }
|
||||
}
|
||||
}
|
||||
}
|
||||
template<int TD, int MODE>
|
||||
__global__ void __launch_bounds__(256) native_down_amd_kernel(const unsigned long long* __restrict__ grp_ptr,
|
||||
const int32_t* __restrict__ grp_start,
|
||||
const int32_t* __restrict__ n_groups,
|
||||
const int32_t* __restrict__ ent_dst,
|
||||
const block_q8_1* __restrict__ hq, NativeExpertLayout L,
|
||||
float* __restrict__ out) {
|
||||
const int g = blockIdx.y;
|
||||
if (g >= *n_groups) return;
|
||||
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
|
||||
const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
|
||||
const int e0 = grp_start[g], e1 = grp_start[g + 1];
|
||||
const int nrow = (int) L.n_embd;
|
||||
if constexpr (MODE == 1) {
|
||||
const int lane = threadIdx.x & 63, r = blockIdx.x * 4 + (threadIdx.x >> 6);
|
||||
if (r >= nrow) return;
|
||||
const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row;
|
||||
for (int e = e0; e < e1; ++e) {
|
||||
const float v = row_dot64<TD>(wr, hq + (size_t) e * hb, nb, lane);
|
||||
if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v;
|
||||
}
|
||||
} else if constexpr (MODE == 4) {
|
||||
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
|
||||
const int r0 = blockIdx.x * 32 + warp;
|
||||
if (r0 >= nrow) return;
|
||||
const uint8_t* w[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) w[i] = blob + L.down_off + (size_t) (r0 + 8 * i < nrow ? r0 + 8 * i : r0) * L.d_row;
|
||||
for (int e = e0; e < e1; ++e) {
|
||||
float o[4];
|
||||
row_dotn<TD, 4>(w, hq + (size_t) e * hb, nb, lane, o);
|
||||
if (lane == 0)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) if (r0 + 8 * i < nrow) out[(size_t) ent_dst[e] * L.n_embd + r0 + 8 * i] = o[i];
|
||||
}
|
||||
} else {
|
||||
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
|
||||
const int r0 = blockIdx.x * 16 + warp, r1 = r0 + 8;
|
||||
if (r0 >= nrow) return;
|
||||
const bool two = r1 < nrow;
|
||||
const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;
|
||||
const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;
|
||||
for (int e = e0; e < e1; ++e) {
|
||||
float a, b;
|
||||
row_dot2<TD>(w0, w1, hq + (size_t) e * hb, nb, lane, a, b);
|
||||
if (lane == 0) {
|
||||
out[(size_t) ent_dst[e] * L.n_embd + r0] = a;
|
||||
if (two) out[(size_t) ent_dst[e] * L.n_embd + r1] = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// ---- 5 (LDS): gate/up of the grid formats (IQ2_S, IQ3_XXS, IQ3_S) with the codebook grid and the group's q8_1
|
||||
// activations in LDS. The bench showed gate/up compute-bound, not bandwidth-bound (T = 2 costs ~1.8x T = 1 on the
|
||||
// same weights, 110-130 GB/s): each call issues its grid lookups and eight activation loads through the vector
|
||||
// memory path after the weight load. Same calls, same lane-strided k, same R2 row pairs, same warp_sum: the
|
||||
// output is bitwise the mode-2 one.
|
||||
template<int TY> struct GridOf;
|
||||
template<> struct GridOf<22> { using T = uint64_t; static constexpr int N = 1024; __device__ static const T* src() { return iq2s_grid; } };
|
||||
template<> struct GridOf<18> { using T = uint32_t; static constexpr int N = 256; __device__ static const T* src() { return iq3xxs_grid; } };
|
||||
template<> struct GridOf<21> { using T = uint32_t; static constexpr int N = 512; __device__ static const T* src() { return iq3s_grid; } };
|
||||
template<> struct GridOf<23> { using T = uint32_t; static constexpr int N = 1; __device__ static const T* src() { return iq3s_grid; } }; // IQ4_XS: no grid
|
||||
|
||||
// SG = 1 (mode 6): the signs without byte-SIMD ops, which gfx906 lacks (strata_vcmpne4 / strata_vsub4 unpack to
|
||||
// ~12 word ops each). m = the sign nibble as 0x00/0xff bytes; (g ^ m) is g or -g-1 per byte, so
|
||||
// dp4a(g ^ m, u) - dp4a(m, u) = sum(s g u) exactly - the same integers, the same floats.
|
||||
__device__ __forceinline__ int nib_mask(uint32_t n) {
|
||||
const uint32_t b = __umul24(n & 0xFu, 0x204081u) & 0x01010101u;
|
||||
return (int) ((b << 8) - b);
|
||||
}
|
||||
template<int TY, int SG> struct DotG;
|
||||
template<int SG> struct DotG<22, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
|
||||
const uint64_t* grid) {
|
||||
const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;
|
||||
const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
|
||||
const uint8_t* qs = (const uint8_t*) &qs_packed;
|
||||
const int qh = bq2->qh[iqs / 2];
|
||||
const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
|
||||
const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
|
||||
const int ls0 = bq2->scales[iqs / 2] & 0x0F;
|
||||
const int ls1 = bq2->scales[iqs / 2] >> 4;
|
||||
int sumi0 = 0, sumi1 = 0;
|
||||
#pragma unroll
|
||||
for (int l0 = 0; l0 < 8; l0 += 2) {
|
||||
const int* grid_pos = (const int*) (grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
|
||||
const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
|
||||
const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
|
||||
int& acc = l0 < 4 ? sumi0 : sumi1;
|
||||
if constexpr (SG == 1) {
|
||||
const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);
|
||||
acc = ggml_cuda_dp4a(grid_pos[0] ^ m0, u0, acc);
|
||||
acc = ggml_cuda_dp4a(grid_pos[1] ^ m1, u1, acc);
|
||||
acc -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
|
||||
} else {
|
||||
const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
|
||||
const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
|
||||
const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0);
|
||||
const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1);
|
||||
acc = ggml_cuda_dp4a(grid_l, u0, acc);
|
||||
acc = ggml_cuda_dp4a(grid_h, u1, acc);
|
||||
}
|
||||
}
|
||||
const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;
|
||||
const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);
|
||||
return d * sumi;
|
||||
} };
|
||||
template<int SG> struct DotG<18, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
|
||||
const uint32_t* grid) {
|
||||
const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
|
||||
const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
|
||||
const uint8_t* q3 = (const uint8_t*) &q3_packed;
|
||||
const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
|
||||
int sumi = 0;
|
||||
#pragma unroll
|
||||
for (int l0 = 0; l0 < 8; l0 += 2) {
|
||||
const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]);
|
||||
const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
|
||||
const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
|
||||
const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
|
||||
if constexpr (SG == 1) {
|
||||
const int m0 = nib_mask(signs), m1 = nib_mask(signs >> 4);
|
||||
sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);
|
||||
sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);
|
||||
sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
|
||||
} else {
|
||||
const int signs0 = __vcmpne4(signs & 0x08040201, 0);
|
||||
const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
|
||||
const int signs1 = __vcmpne4(signs & 0x80402010, 0);
|
||||
const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
|
||||
sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
|
||||
sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
|
||||
}
|
||||
}
|
||||
const int ls = aux32 >> 28;
|
||||
sumi = (ls * sumi + sumi / 2) / 2;
|
||||
const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
|
||||
return d * sumi;
|
||||
} };
|
||||
template<int SG> struct DotG<21, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
|
||||
const uint32_t* grid) {
|
||||
const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
|
||||
const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
|
||||
const uint8_t* qs = (const uint8_t*) &qs_packed;
|
||||
const int qh = bq3->qh[iqs / 2];
|
||||
const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
|
||||
const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
|
||||
int sumi = 0;
|
||||
#pragma unroll
|
||||
for (int l0 = 0; l0 < 8; l0 += 2) {
|
||||
const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
|
||||
grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
|
||||
const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
|
||||
const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
|
||||
if constexpr (SG == 1) {
|
||||
const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);
|
||||
sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);
|
||||
sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);
|
||||
sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
|
||||
} else {
|
||||
const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
|
||||
const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
|
||||
const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
|
||||
const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
|
||||
sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
|
||||
sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
|
||||
}
|
||||
}
|
||||
sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
|
||||
const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
|
||||
return d * sumi;
|
||||
} };
|
||||
|
||||
template<int SG> struct DotG<23, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
|
||||
const uint32_t*) { return vec_dot_iq4_xs_q8_1(vbq, bq8_1, kbx, iqs); } };
|
||||
|
||||
constexpr int LDS_RB = 64; // gate/up rows per block (4 R2 passes of 16)
|
||||
constexpr int LDS_NT = 4; // entries whose activations sit in LDS at once
|
||||
|
||||
template<int TG, int SG, bool TI = false>
|
||||
__global__ void __launch_bounds__(256) native_gu_lds_kernel(const unsigned long long* __restrict__ grp_ptr,
|
||||
const int32_t* __restrict__ grp_start,
|
||||
const int32_t* __restrict__ n_groups,
|
||||
const int32_t* __restrict__ ent_tok,
|
||||
const block_q8_1* __restrict__ xq, NativeExpertLayout L,
|
||||
float* __restrict__ gate, float* __restrict__ up) {
|
||||
using GT = typename GridOf<TG>::T;
|
||||
using F = Fmt<TG>;
|
||||
__shared__ GT sgrid[GridOf<TG>::N];
|
||||
extern __shared__ int sx_raw[]; // LDS_NT tokens x xb blocks of q8_1 (36 bytes = 9 ints each)
|
||||
const int g = blockIdx.y;
|
||||
if (g >= *n_groups) return; // uniform over the block
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const GT* gsrc = GridOf<TG>::src();
|
||||
for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];
|
||||
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
|
||||
const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32);
|
||||
const int e0 = grp_start[g], e1 = grp_start[g + 1];
|
||||
const int nrow = 2 * (int) L.n_ff;
|
||||
const block_q8_1* sx = (const block_q8_1*) sx_raw;
|
||||
auto wrow = [&](int row) -> const uint8_t* {
|
||||
const bool is_up = row >= L.n_ff;
|
||||
return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;
|
||||
};
|
||||
auto put = [&](int row, int e, float v) {
|
||||
const bool is_up = row >= L.n_ff;
|
||||
(is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;
|
||||
};
|
||||
for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
|
||||
const int cn = min(LDS_NT, e1 - c0);
|
||||
__syncthreads();
|
||||
for (int j = 0; j < cn; ++j) {
|
||||
const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);
|
||||
for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int p = 0; p < LDS_RB / 16; ++p) {
|
||||
const int row0 = blockIdx.x * LDS_RB + p * 16 + warp, row1 = row0 + 8;
|
||||
if (row0 >= nrow) break;
|
||||
const bool two = row1 < nrow;
|
||||
const uint8_t* w0 = wrow(row0);
|
||||
const uint8_t* w1 = wrow(two ? row1 : row0);
|
||||
if constexpr (TI) { // mode 7: the tokens inside the k loop - one weight load per k for all of them
|
||||
auto pass = [&](auto ntc) {
|
||||
constexpr int NTC = decltype(ntc)::value;
|
||||
float s0[NTC], s1[NTC];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
|
||||
for (int k = lane; k < nb * F::ipb; k += 32) {
|
||||
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NTC; ++j) {
|
||||
const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);
|
||||
const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);
|
||||
const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);
|
||||
s0[j] += a;
|
||||
s1[j] += b;
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NTC; ++j) {
|
||||
const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
|
||||
if (lane == 0) { put(row0, c0 + j, a); if (two) put(row1, c0 + j, b); }
|
||||
}
|
||||
};
|
||||
switch (cn) {
|
||||
case 1: pass(std::integral_constant<int, 1>{}); break;
|
||||
case 2: pass(std::integral_constant<int, 2>{}); break;
|
||||
case 3: pass(std::integral_constant<int, 3>{}); break;
|
||||
default: pass(std::integral_constant<int, 4>{}); break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for (int j = 0; j < cn; ++j) {
|
||||
const block_q8_1* x = sx + (size_t) j * xb;
|
||||
float s0 = 0.0f, s1 = 0.0f;
|
||||
for (int k = lane; k < nb * F::ipb; k += 32) {
|
||||
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
|
||||
const block_q8_1* xk = x + kbx * (F::qk / 32);
|
||||
const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);
|
||||
const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);
|
||||
s0 += a;
|
||||
s1 += b;
|
||||
}
|
||||
s0 = warp_sum(s0);
|
||||
s1 = warp_sum(s1);
|
||||
if (lane == 0) { put(row0, c0 + j, s0); if (two) put(row1, c0 + j, s1); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 7 (down): the group's q8_1 h rows in LDS, the tokens inside the k loop, the R2 row pairs of mode 2 -
|
||||
// the same per-(row, entry) sums in the same order: bitwise the mode-2 output.
|
||||
template<int TD>
|
||||
__global__ void __launch_bounds__(256) native_down_lds_kernel(const unsigned long long* __restrict__ grp_ptr,
|
||||
const int32_t* __restrict__ grp_start,
|
||||
const int32_t* __restrict__ n_groups,
|
||||
const int32_t* __restrict__ ent_dst,
|
||||
const block_q8_1* __restrict__ hq, NativeExpertLayout L,
|
||||
float* __restrict__ out) {
|
||||
using F = Fmt<TD>;
|
||||
extern __shared__ int sh_raw[]; // LDS_NT entries x hb blocks of q8_1
|
||||
const int g = blockIdx.y;
|
||||
if (g >= *n_groups) return;
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
|
||||
const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32);
|
||||
const int e0 = grp_start[g], e1 = grp_start[g + 1];
|
||||
const int nrow = (int) L.n_embd;
|
||||
const block_q8_1* sh = (const block_q8_1*) sh_raw;
|
||||
for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
|
||||
const int cn = min(LDS_NT, e1 - c0);
|
||||
__syncthreads();
|
||||
{
|
||||
const int* src = (const int*) (hq + (size_t) c0 * hb); // the chunk's entries are contiguous
|
||||
for (int i = tid; i < cn * hb * 9; i += 256) sh_raw[i] = src[i];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int p = 0; p < LDS_RB / 16; ++p) {
|
||||
const int r0 = blockIdx.x * LDS_RB + p * 16 + warp, r1 = r0 + 8;
|
||||
if (r0 >= nrow) break;
|
||||
const bool two = r1 < nrow;
|
||||
const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;
|
||||
const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;
|
||||
auto pass = [&](auto ntc) {
|
||||
constexpr int NTC = decltype(ntc)::value;
|
||||
float s0[NTC], s1[NTC];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
|
||||
for (int k = lane; k < nb * F::ipb; k += 32) {
|
||||
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NTC; ++j) {
|
||||
const block_q8_1* xk = sh + (size_t) j * hb + kbx * (F::qk / 32);
|
||||
const float a = F::dot(w0, xk, kbx, iqs);
|
||||
const float b = F::dot(w1, xk, kbx, iqs);
|
||||
s0[j] += a;
|
||||
s1[j] += b;
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NTC; ++j) {
|
||||
const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
|
||||
if (lane == 0) {
|
||||
out[(size_t) ent_dst[c0 + j] * L.n_embd + r0] = a;
|
||||
if (two) out[(size_t) ent_dst[c0 + j] * L.n_embd + r1] = b;
|
||||
}
|
||||
}
|
||||
};
|
||||
switch (cn) {
|
||||
case 1: pass(std::integral_constant<int, 1>{}); break;
|
||||
case 2: pass(std::integral_constant<int, 2>{}); break;
|
||||
case 3: pass(std::integral_constant<int, 3>{}); break;
|
||||
default: pass(std::integral_constant<int, 4>{}); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 8: mode 7's gate/up with SwiGLU and the q8_1 quantization in the epilogue. A block takes h rows
|
||||
// [r0, r0 + 32): gate rows r0.. and up rows r0.. (64 weight rows, the same per-(row, entry) sums as mode 7), so
|
||||
// one 32-lane warp per entry holds exactly one q8_1 block of h and runs quantize_q8_1_kernel's own code on it -
|
||||
// bitwise the separate kernels' hq, two launches fewer per call.
|
||||
template<int TG>
|
||||
__global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned long long* __restrict__ grp_ptr,
|
||||
const int32_t* __restrict__ grp_start,
|
||||
const int32_t* __restrict__ n_groups,
|
||||
const int32_t* __restrict__ ent_tok,
|
||||
const block_q8_1* __restrict__ xq, NativeExpertLayout L,
|
||||
block_q8_1* __restrict__ hq) {
|
||||
using GT = typename GridOf<TG>::T;
|
||||
using F = Fmt<TG>;
|
||||
__shared__ GT sgrid[GridOf<TG>::N];
|
||||
__shared__ float res[LDS_NT][64];
|
||||
extern __shared__ int sx_raw[];
|
||||
const int g = blockIdx.y;
|
||||
if (g >= *n_groups) return;
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const GT* gsrc = GridOf<TG>::src();
|
||||
for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];
|
||||
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
|
||||
const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32), hb = (int) (L.n_ff / 32);
|
||||
const int e0 = grp_start[g], e1 = grp_start[g + 1];
|
||||
const int r0 = blockIdx.x * 32;
|
||||
const block_q8_1* sx = (const block_q8_1*) sx_raw;
|
||||
auto wrow = [&](int i) -> const uint8_t* { // i < 32: gate row r0 + i, else up row r0 + i - 32
|
||||
return blob + (i < 32 ? (size_t) 0 : L.up_off) + (size_t) (r0 + (i & 31)) * L.gu_row;
|
||||
};
|
||||
for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
|
||||
const int cn = min(LDS_NT, e1 - c0);
|
||||
__syncthreads();
|
||||
for (int j = 0; j < cn; ++j) {
|
||||
const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);
|
||||
for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int p = 0; p < 4; ++p) {
|
||||
const int i0 = p * 16 + warp, i1 = i0 + 8;
|
||||
const uint8_t* w0 = wrow(i0);
|
||||
const uint8_t* w1 = wrow(i1);
|
||||
auto pass = [&](auto ntc) {
|
||||
constexpr int NTC = decltype(ntc)::value;
|
||||
float s0[NTC], s1[NTC];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
|
||||
for (int k = lane; k < nb * F::ipb; k += 32) {
|
||||
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NTC; ++j) {
|
||||
const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);
|
||||
const float a = DotG<TG, 1>::f(w0, xk, kbx, iqs, sgrid);
|
||||
const float b = DotG<TG, 1>::f(w1, xk, kbx, iqs, sgrid);
|
||||
s0[j] += a;
|
||||
s1[j] += b;
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NTC; ++j) {
|
||||
const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
|
||||
if (lane == 0) { res[j][i0] = a; res[j][i1] = b; }
|
||||
}
|
||||
};
|
||||
switch (cn) {
|
||||
case 1: pass(std::integral_constant<int, 1>{}); break;
|
||||
case 2: pass(std::integral_constant<int, 2>{}); break;
|
||||
case 3: pass(std::integral_constant<int, 3>{}); break;
|
||||
default: pass(std::integral_constant<int, 4>{}); break;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (warp < cn) { // swiglu_entries_kernel + quantize_q8_1_kernel, one block of 32 h values per entry
|
||||
const float gg = res[warp][lane], uu = res[warp][32 + lane];
|
||||
const float xi = (gg / (1.0f + __expf(-gg))) * uu;
|
||||
float amax = fabsf(xi), sum = xi;
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) {
|
||||
amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
|
||||
sum += __shfl_xor_sync(0xffffffffu, sum, o);
|
||||
}
|
||||
const float d = amax / 127.0f;
|
||||
const int8_t q = amax == 0.0f ? 0 : roundf(xi / d);
|
||||
block_q8_1* y = hq + (size_t) (c0 + warp) * hb + blockIdx.x;
|
||||
y->qs[lane] = q;
|
||||
if (lane == 0) y->ds = make_half2(d, sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int g_exp_mode = -1; // native_expert_set_mode (the bench); -1 = STRATA_EXP_MODE, default 7
|
||||
int exp_mode() {
|
||||
static const int m = [] { const char* v = std::getenv("STRATA_EXP_MODE"); return v ? std::atoi(v) : 7; }();
|
||||
return g_exp_mode >= 0 ? g_exp_mode : m;
|
||||
}
|
||||
#endif
|
||||
int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only
|
||||
|
||||
void native_expert_set_mode(int mode, int phase) {
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
g_exp_mode = mode;
|
||||
#else
|
||||
(void) mode;
|
||||
#endif
|
||||
g_exp_phase = phase;
|
||||
}
|
||||
|
||||
namespace {
|
||||
bool g_grouped_v1 = env_on("STRATA_GROUPED_V1");
|
||||
} // namespace
|
||||
@@ -1555,15 +2133,76 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
|
||||
const bool v1 = g_grouped_v1;
|
||||
const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups;
|
||||
const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) gy);
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
const int em0 = exp_mode();
|
||||
#endif
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
const bool fused_gu = em0 == 8 && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) &&
|
||||
L.n_ff % 32 == 0;
|
||||
if (fused_gu && g_exp_phase != 2) {
|
||||
const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups);
|
||||
const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);
|
||||
switch (L.gu_type) {
|
||||
case 18: native_gu_fused_kernel<18><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
|
||||
case 21: native_gu_fused_kernel<21><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
|
||||
case 23: native_gu_fused_kernel<23><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
|
||||
default: native_gu_fused_kernel<22><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
|
||||
}
|
||||
check("native_expert_grouped/gu fused");
|
||||
}
|
||||
if (g_exp_phase != 2 && !fused_gu) {
|
||||
#else
|
||||
if (g_exp_phase != 2) {
|
||||
#endif
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23);
|
||||
if (lds_gu) {
|
||||
const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);
|
||||
const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);
|
||||
switch (L.gu_type) {
|
||||
case 18: if (em0 >= 7) native_gu_lds_kernel<18, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<18, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<18, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
|
||||
case 21: if (em0 >= 7) native_gu_lds_kernel<21, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<21, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<21, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
|
||||
case 23: if (em0 >= 7) native_gu_lds_kernel<23, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<23, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
|
||||
default: if (em0 >= 7) native_gu_lds_kernel<22, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<22, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<22, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
|
||||
}
|
||||
} else {
|
||||
const int em = exp_mode() >= 5 ? 2 : exp_mode();
|
||||
const dim3 ggu_amd((unsigned) ((2 * L.n_ff + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);
|
||||
#define STRATA_GU_AMD(T) \
|
||||
case T: if (em == 1) native_gu_amd_kernel<T, 1><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \
|
||||
else if (em == 4) native_gu_amd_kernel<T, 4><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \
|
||||
else native_gu_amd_kernel<T, 2><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
|
||||
// the AMD layouts cover the IQ packs' gate/up types; Unsloth's Q4_K / Q5_K take the CUDA layout below
|
||||
const bool amd_gu = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 ||
|
||||
L.gu_type == 23 || L.gu_type == 29 || L.gu_type == 42;
|
||||
if ((em == 1 || em == 2 || em == 4) && amd_gu) {
|
||||
switch (L.gu_type) {
|
||||
STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23)
|
||||
STRATA_GU_AMD(29) STRATA_GU_AMD(42)
|
||||
}
|
||||
} else
|
||||
#undef STRATA_GU_AMD
|
||||
#endif
|
||||
switch (L.gu_type) {
|
||||
#define STRATA_GU(T) case T: launch_gu<T>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
|
||||
STRATA_GU_FMTS(STRATA_GU)
|
||||
#undef STRATA_GU
|
||||
default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1);
|
||||
}
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
}
|
||||
#endif
|
||||
check("native_expert_grouped/gu");
|
||||
const long long nh = (long long) cap_entries * L.n_ff;
|
||||
if (v1) {
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// gfx906: the separate SwiGLU and q8_1 passes stay the default (the A/B baseline); the RDNA one-pass
|
||||
// kernel (bitwise the same) with STRATA_HIP_SWIGLU_FUSED=1
|
||||
static const bool sw_fused = env_on("STRATA_HIP_SWIGLU_FUSED");
|
||||
const bool sw_v1 = v1 || !sw_fused;
|
||||
#else
|
||||
const bool sw_v1 = v1;
|
||||
#endif
|
||||
if (sw_v1) {
|
||||
swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh);
|
||||
quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh);
|
||||
} else {
|
||||
@@ -1571,7 +2210,33 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
|
||||
(int) L.n_ff, hq);
|
||||
}
|
||||
check("native_expert_grouped/swiglu");
|
||||
}
|
||||
if (g_exp_phase == 1) return;
|
||||
const dim3 gd((unsigned) ((L.n_embd + 7) / 8), (unsigned) gy);
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
if ((em0 == 7 || em0 == 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);
|
||||
else native_down_lds_kernel<42><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
|
||||
check("native_expert_grouped/down");
|
||||
return;
|
||||
}
|
||||
const int em = exp_mode() >= 5 ? 2 : exp_mode();
|
||||
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); \
|
||||
else if (em == 4) native_down_amd_kernel<T, 4><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \
|
||||
else native_down_amd_kernel<T, 2><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
|
||||
// the AMD layouts cover the IQ packs' down types; the others (Unsloth's Q4_K / Q5_K / Q5_1 / Q8_0) take the
|
||||
// CUDA layout below
|
||||
if ((em == 1 || em == 2 || em == 4) && (L.d_type == 20 || L.d_type == 23 || L.d_type == 42)) {
|
||||
switch (L.d_type) {
|
||||
STRATA_D_AMD(20) STRATA_D_AMD(23) STRATA_D_AMD(42)
|
||||
}
|
||||
} else
|
||||
#undef STRATA_D_AMD
|
||||
#endif
|
||||
switch (L.d_type) {
|
||||
#define STRATA_DOWN(T) case T: launch_down<T>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
|
||||
STRATA_D_FMTS(STRATA_DOWN)
|
||||
|
||||
@@ -183,4 +183,17 @@ void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
|
||||
}
|
||||
|
||||
|
||||
|
||||
void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols,
|
||||
void* stream) {
|
||||
// columns contiguous: the existing multi-row kernel (weight read once, each output bitwise its one-row call),
|
||||
// up to 8 rows per launch
|
||||
for (int c0 = 0; c0 < ncols; c0 += 8) {
|
||||
const int nc = ncols - c0 < 8 ? ncols - c0 : 8;
|
||||
if (nc == 1) bf16_gemv_fp32_mmvf(x + (size_t) c0 * n_in, w, y + (size_t) c0 * n_out, n_in, n_out, stream);
|
||||
else bf16_gemv_fp32_mmvf_multi(x + (size_t) c0 * n_in, n_in, w, y + (size_t) c0 * n_out, n_out, n_in, n_out, nc,
|
||||
stream);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -32,6 +32,7 @@
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
@@ -418,6 +419,17 @@ __device__ __align__(4) int8_t iq4nl_values[16] = {
|
||||
};
|
||||
|
||||
__device__ __forceinline__ int2 iq4_table_lookup(int q4) {
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// AMD: llama.cpp's HIP lookup (see iq_kernels.cu get_int_from_table_16): 4 v_perm_b32 per 8 values
|
||||
const uint32_t* v32 = reinterpret_cast<const uint32_t*>(iq4nl_values);
|
||||
const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;
|
||||
const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);
|
||||
const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);
|
||||
const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);
|
||||
const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);
|
||||
return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),
|
||||
(int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));
|
||||
#else
|
||||
const uint32_t* table32 = reinterpret_cast<const uint32_t*>(iq4nl_values);
|
||||
uint32_t tmp[2];
|
||||
const uint32_t low_high_selection_indices = 0x32103210 | ((q4 & 0x88888888) >> 1);
|
||||
@@ -429,6 +441,7 @@ __device__ __forceinline__ int2 iq4_table_lookup(int q4) {
|
||||
tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift);
|
||||
}
|
||||
return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531));
|
||||
#endif
|
||||
}
|
||||
|
||||
// Exact pinned vec_dot_iq4_xs_q8_1: a lane consumes one 32-element subblock,
|
||||
@@ -1099,6 +1112,77 @@ void launch_check() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// ---- AMD (wave64) layout: one wavefront per R rows, four wavefronts per block, the row's blocks strided over the
|
||||
// 64 lanes exactly as the CUDA kernels stride them over a block (kbx = lane / T, stride 64 / T), and a 64-lane
|
||||
// butterfly instead of the LDS partials and __syncthreads of the one-block-per-row layout: on gfx906 a block per
|
||||
// 2 KB row spent most of its time being launched and joined. The SAME kernel serves every column count 1..8, so a
|
||||
// column's sums do not depend on how many columns (verify tokens) ride along. STRATA_MMVQ_WAVE=0: the CUDA layout.
|
||||
bool g_wave_off = std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0";
|
||||
template<typename F, int NCOLS, int R>
|
||||
__launch_bounds__(256)
|
||||
__global__ void native_mmvq_wave_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
|
||||
float* __restrict__ y, int n_in, int n_out) {
|
||||
constexpr int BPIW = 64 / F::T;
|
||||
static_assert(64 % F::T == 0, "a block's threads must tile the wavefront");
|
||||
const int lane = int(threadIdx.x) & 63;
|
||||
const int row0 = (int(blockIdx.x) * 4 + (int(threadIdx.x) >> 6)) * R;
|
||||
if (row0 >= n_out) return;
|
||||
const int blocks_per_row = n_in / F::DIV;
|
||||
const int x_stride = n_in / Q8K;
|
||||
const int kqs = F::kqs(lane);
|
||||
float tmp[NCOLS][R] = {};
|
||||
for (int kbx = lane / F::T; kbx < blocks_per_row; kbx += BPIW) {
|
||||
const int kby = kbx * F::KBY;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < R; ++i) {
|
||||
if (row0 + i < n_out) {
|
||||
const typename F::W wv = F::load(w + std::size_t(row0 + i) * blocks_per_row + 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 < R; ++i) {
|
||||
float v = tmp[j][i];
|
||||
#pragma unroll
|
||||
for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64);
|
||||
if (lane == 0 && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = v;
|
||||
}
|
||||
}
|
||||
template<typename F, int NCOLS>
|
||||
void wave_launch_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) {
|
||||
const auto* w = static_cast<const typename F::Block*>(weights);
|
||||
const auto* x = static_cast<const Q81Block*>(x_q8_1);
|
||||
constexpr int R = 1;
|
||||
const unsigned blocks = unsigned((std::size_t(n_out) + 4 * R - 1) / (4 * R));
|
||||
native_mmvq_wave_kernel<F, NCOLS, R><<<blocks, 256, 0, s>>>(w, x, y, n_in, n_out);
|
||||
}
|
||||
template<typename F>
|
||||
void wave_launch(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
|
||||
const auto s = static_cast<cudaStream_t>(stream);
|
||||
switch (ncols) {
|
||||
case 1: wave_launch_n<F, 1>(weights, x_q8_1, y, n_in, n_out, s); break;
|
||||
case 2: wave_launch_n<F, 2>(weights, x_q8_1, y, n_in, n_out, s); break;
|
||||
case 3: wave_launch_n<F, 3>(weights, x_q8_1, y, n_in, n_out, s); break;
|
||||
case 4: wave_launch_n<F, 4>(weights, x_q8_1, y, n_in, n_out, s); break;
|
||||
case 5: wave_launch_n<F, 5>(weights, x_q8_1, y, n_in, n_out, s); break;
|
||||
case 6: wave_launch_n<F, 6>(weights, x_q8_1, y, n_in, n_out, s); break;
|
||||
case 7: wave_launch_n<F, 7>(weights, x_q8_1, y, n_in, n_out, s); break;
|
||||
case 8: wave_launch_n<F, 8>(weights, x_q8_1, y, n_in, n_out, s); break;
|
||||
default: throw std::invalid_argument("native MMVQ (wave) requires 1 <= ncols <= 8");
|
||||
}
|
||||
}
|
||||
#define STRATA_WAVE_MMVQ(...) \
|
||||
if (!g_wave_off) { wave_launch<__VA_ARGS__>(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); return; }
|
||||
#else
|
||||
#define STRATA_WAVE_MMVQ(...)
|
||||
#endif
|
||||
|
||||
template<typename Weight, int Qi>
|
||||
void small_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
int n_in, int n_out, int ncols, void* stream) {
|
||||
@@ -1108,6 +1192,7 @@ void small_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
validate_pointer(x_q8_1);
|
||||
validate_pointer(y);
|
||||
validate_stream(stream);
|
||||
STRATA_WAVE_MMVQ(SmallTraits<Weight, Qi>)
|
||||
if (ncols > 1) {
|
||||
launch_multi<SmallTraits<Weight, Qi>>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
|
||||
launch_check();
|
||||
@@ -1172,6 +1257,7 @@ void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
validate_pointer(x_q8_1);
|
||||
validate_pointer(y);
|
||||
validate_stream(stream);
|
||||
STRATA_WAVE_MMVQ(Q5KTraits)
|
||||
if (ncols > 1) {
|
||||
launch_multi<Q5KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
|
||||
launch_check();
|
||||
@@ -1212,6 +1298,7 @@ void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
validate_pointer(x_q8_1);
|
||||
validate_pointer(y);
|
||||
validate_stream(stream);
|
||||
STRATA_WAVE_MMVQ(Q20Traits)
|
||||
if (ncols > 1) {
|
||||
launch_multi<Q20Traits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
|
||||
launch_check();
|
||||
@@ -1251,6 +1338,7 @@ void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
validate_pointer(x_q8_1);
|
||||
validate_pointer(y);
|
||||
validate_stream(stream);
|
||||
STRATA_WAVE_MMVQ(Q3KTraits)
|
||||
if (ncols > 1) {
|
||||
launch_multi<Q3KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
|
||||
launch_check();
|
||||
@@ -1290,6 +1378,7 @@ void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
validate_pointer(x_q8_1);
|
||||
validate_pointer(y);
|
||||
validate_stream(stream);
|
||||
STRATA_WAVE_MMVQ(IQ4XSTraits)
|
||||
if (ncols > 1) {
|
||||
launch_multi<IQ4XSTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
|
||||
launch_check();
|
||||
@@ -1329,6 +1418,7 @@ void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
validate_pointer(x_q8_1);
|
||||
validate_pointer(y);
|
||||
validate_stream(stream);
|
||||
STRATA_WAVE_MMVQ(Q4KTraits)
|
||||
if (ncols > 1) {
|
||||
launch_multi<Q4KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
|
||||
launch_check();
|
||||
@@ -1368,6 +1458,7 @@ void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y,
|
||||
validate_pointer(x_q8_1);
|
||||
validate_pointer(y);
|
||||
validate_stream(stream);
|
||||
STRATA_WAVE_MMVQ(Q6KTraits)
|
||||
if (ncols > 1) {
|
||||
launch_multi<Q6KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
|
||||
launch_check();
|
||||
|
||||
@@ -181,6 +181,217 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
|
||||
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
|
||||
}
|
||||
|
||||
// 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 it runs on cards below sm_75 only, and exists only in the experimental
|
||||
// build (-DSTRATA_EXPERIMENTAL_SM60=ON): the ready-made engine keeps exactly the kernel above.
|
||||
#if defined(STRATA_EXPERIMENTAL_SM60)
|
||||
// The 12 heads' lane sums (`part[12..15]` zero), reduce-scattered with warp_sum's pairing order (xor 16, 8, 4, 2, 1):
|
||||
// every output adds the same two operands at every level, so each sum is bit for bit warp_sum's (float add commutes),
|
||||
// for 16 shuffles instead of 12 x 5. Lane l ends holding head head_of_lane(l); lanes l and l^1 agree.
|
||||
__device__ __forceinline__ float reduce12(const float (&part)[16], int lane) {
|
||||
float r8[8];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const bool hi = (lane & 16) != 0;
|
||||
r8[i] = (hi ? part[i + 8] : part[i]) + __shfl_xor_sync(0xffffffffu, hi ? part[i] : part[i + 8], 16);
|
||||
}
|
||||
float r4[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const bool hi = (lane & 8) != 0;
|
||||
r4[i] = (hi ? r8[i + 4] : r8[i]) + __shfl_xor_sync(0xffffffffu, hi ? r8[i] : r8[i + 4], 8);
|
||||
}
|
||||
float r2[2];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
const bool hi = (lane & 4) != 0;
|
||||
r2[i] = (hi ? r4[i + 2] : r4[i]) + __shfl_xor_sync(0xffffffffu, hi ? r4[i] : r4[i + 2], 4);
|
||||
}
|
||||
const bool hi2 = (lane & 2) != 0;
|
||||
const float r1 = (hi2 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi2 ? r2[0] : r2[1], 2);
|
||||
return r1 + __shfl_xor_sync(0xffffffffu, r1, 1);
|
||||
}
|
||||
__device__ __forceinline__ int head_of_lane(int lane) {
|
||||
return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1);
|
||||
}
|
||||
|
||||
// One V element of pool row `row`, dimension `d` (the value loop's own thread index), per KV format.
|
||||
template <int KV_MODE>
|
||||
__device__ __forceinline__ float load_v1(const QsaAttnPools& p, long long row, int d) {
|
||||
if constexpr (KV_MODE == 0) {
|
||||
return __half2float(__ushort_as_half(p.v_pool[row * HD + d]));
|
||||
} else if constexpr (KV_MODE == 1) {
|
||||
const float sc = __half2float(__ushort_as_half(p.v_scale[row * (HD / KV_Q8_GROUP) + d / KV_Q8_GROUP]));
|
||||
return (float) p.v_q[row * HD + d] * sc;
|
||||
} else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
|
||||
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
|
||||
const int b = d / QK4_0;
|
||||
const int rem = d % QK4_0;
|
||||
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
|
||||
const float dd = __half2float(__ushort_as_half(blk->d));
|
||||
const int j = rem < 16 ? rem : (rem - 16);
|
||||
const uint8_t byte = blk->qs[j];
|
||||
const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
|
||||
return (float) nibble * dd;
|
||||
}
|
||||
}
|
||||
|
||||
template <int KV_MODE>
|
||||
__global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(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) {
|
||||
// batched form: query blockIdx.z, with its own q row, selection, step and scratch
|
||||
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]; // 12 KB: this KV head's query heads (dead once the scores are done)
|
||||
__shared__ float sp[G][CHUNK]; // scores
|
||||
__shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot)
|
||||
// probabilities, cell-major: the value loop reads one cell's 12 as three float4. They are first written after the
|
||||
// __syncthreads that ends the score phase, the last reader of sq, so they share its storage (64 x 12 of its 256 x 12
|
||||
// floats) and the block's shared memory stays what it was before the cell-major layout.
|
||||
float (*const spt)[G] = reinterpret_cast<float (*)[G]>(&sq[0][0]);
|
||||
static_assert(CHUNK * G <= G * HD, "spt must fit in sq");
|
||||
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;
|
||||
}
|
||||
for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = 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];
|
||||
// a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
|
||||
// (score -FLT_MAX, weight 0) instead of being read from before the pool.
|
||||
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
|
||||
}
|
||||
srow[t] = r;
|
||||
}
|
||||
__syncthreads();
|
||||
// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. NC cells per step
|
||||
// (warp + 8 * (i + j)): a lane's q slice comes out of shared memory once for all of them, which cuts the traffic
|
||||
// that bounds this phase (24 x 16 B per lane per cell, against the FMAs) by NC; every dot product is the same
|
||||
// expression as for a single cell, so the scores are unchanged.
|
||||
constexpr int NC = 2; // 4 measured slower on a V100 (the registers cost occupancy)
|
||||
const int hd = head_of_lane(lane);
|
||||
for (int i = 0; i < CHUNK / WARPS; i += NC) {
|
||||
int cc[NC];
|
||||
bool all_ok = true;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NC; ++j) {
|
||||
cc[j] = warp + WARPS * (i + j);
|
||||
all_ok = all_ok && cc[j] < n_here && srow[cc[j]] >= 0;
|
||||
}
|
||||
if (all_ok) {
|
||||
float kk[NC][8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NC; ++j) load8<KV_MODE>(p, false, srow[cc[j]], lane * 8, kk[j]);
|
||||
float pp[NC][16];
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h) {
|
||||
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
|
||||
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NC; ++j)
|
||||
pp[j][h] = kk[j][0] * qa.x + kk[j][1] * qa.y + kk[j][2] * qa.z + kk[j][3] * qa.w +
|
||||
kk[j][4] * qb.x + kk[j][5] * qb.y + kk[j][6] * qb.z + kk[j][7] * qb.w;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NC; ++j) {
|
||||
#pragma unroll
|
||||
for (int h = G; h < 16; ++h) pp[j][h] = 0.0f;
|
||||
const float sj = reduce12(pp[j], lane);
|
||||
if ((lane & 1) == 0 && hd < G) sp[hd][cc[j]] = sj * scale;
|
||||
}
|
||||
} else {
|
||||
for (int k = 0; k < NC; ++k) { // a masked or out-of-range cell in the group: one cell at a time
|
||||
const int c = cc[k];
|
||||
if (c >= n_here || srow[c] < 0) {
|
||||
if (lane < G) sp[lane][c] = -FLT_MAX;
|
||||
continue;
|
||||
}
|
||||
float k8[8];
|
||||
load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
|
||||
float part[16];
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h) {
|
||||
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
|
||||
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
|
||||
part[h] = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
|
||||
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int h = G; h < 16; ++h) part[h] = 0.0f;
|
||||
const float s = reduce12(part, lane);
|
||||
if ((lane & 1) == 0 && hd < G) sp[hd][c] = s * scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
// per-head chunk max and exp-sum: warp w handles heads w and w+8.
|
||||
for (int h = warp; h < G; h += WARPS) {
|
||||
const float a = sp[h][lane], b = sp[h][lane + 32];
|
||||
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();
|
||||
// values: thread t owns dimension t for all 12 heads.
|
||||
float acc[G];
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
|
||||
// One cell's 12 weights (three broadcast float4 loads) into the 12 accumulators; the cells are folded in
|
||||
// ascending order, so the sums are the plain loop's, bit for bit.
|
||||
const auto fold = [&](int c, float v) {
|
||||
const float4* w4 = reinterpret_cast<const float4*>(spt[c]);
|
||||
const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2];
|
||||
acc[0] = fmaf(w0.x, v, acc[0]); acc[1] = fmaf(w0.y, v, acc[1]);
|
||||
acc[2] = fmaf(w0.z, v, acc[2]); acc[3] = fmaf(w0.w, v, acc[3]);
|
||||
acc[4] = fmaf(w1.x, v, acc[4]); acc[5] = fmaf(w1.y, v, acc[5]);
|
||||
acc[6] = fmaf(w1.z, v, acc[6]); acc[7] = fmaf(w1.w, v, acc[7]);
|
||||
acc[8] = fmaf(w2.x, v, acc[8]); acc[9] = fmaf(w2.y, v, acc[9]);
|
||||
acc[10] = fmaf(w2.z, v, acc[10]); acc[11] = fmaf(w2.w, v, acc[11]);
|
||||
};
|
||||
int c = 0;
|
||||
// four cells at a time with their V loads issued together (the loop was one dependent load chain per cell);
|
||||
// a group holding a masked cell (page -1, rare) leaves this loop and the scalar one below finishes the chunk.
|
||||
for (; c + 4 <= n_here; c += 4) {
|
||||
const long long r0 = srow[c], r1 = srow[c + 1], r2 = srow[c + 2], r3 = srow[c + 3];
|
||||
if ((r0 | r1 | r2 | r3) < 0) break;
|
||||
const float v0 = load_v1<KV_MODE>(p, r0, t), v1 = load_v1<KV_MODE>(p, r1, t);
|
||||
const float v2 = load_v1<KV_MODE>(p, r2, t), v3 = load_v1<KV_MODE>(p, r3, t);
|
||||
fold(c, v0);
|
||||
fold(c + 1, v1);
|
||||
fold(c + 2, v2);
|
||||
fold(c + 3, v3);
|
||||
}
|
||||
for (; c < n_here; ++c) {
|
||||
if (srow[c] < 0) continue; // masked above, weight 0
|
||||
fold(c, load_v1<KV_MODE>(p, srow[c], t));
|
||||
}
|
||||
#pragma unroll
|
||||
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
|
||||
}
|
||||
#endif // STRATA_EXPERIMENTAL_SM60
|
||||
|
||||
__global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict__ part_acc,
|
||||
const float* __restrict__ part_m,
|
||||
const float* __restrict__ part_l, int n_chunks,
|
||||
@@ -206,6 +417,34 @@ __global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict_
|
||||
attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f;
|
||||
}
|
||||
|
||||
#if defined(STRATA_EXPERIMENTAL_SM60)
|
||||
// the current device is below sm_75 (per device: a layer split can mix cards); STRATA_ATTN_PRE75=0 turns PR #540's
|
||||
// kernel off (A/B)
|
||||
bool pre75_attn() {
|
||||
static const bool off = [] {
|
||||
const char* e = std::getenv("STRATA_ATTN_PRE75");
|
||||
return e != nullptr && e[0] == '0';
|
||||
}();
|
||||
static int cc[64] = {};
|
||||
int dev = 0;
|
||||
if (off) return false;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
|
||||
if (cc[dev] == 0) {
|
||||
int major = 0, minor = 0;
|
||||
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
return false;
|
||||
}
|
||||
cc[dev] = 10 * major + minor;
|
||||
}
|
||||
return cc[dev] < 75;
|
||||
}
|
||||
#define STRATA_ATTN_CHUNK(M) (pre75_attn() ? attn_chunk_kernel_pre75<M> : attn_chunk_kernel<M>)
|
||||
#else
|
||||
#define STRATA_ATTN_CHUNK(M) attn_chunk_kernel<M>
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
|
||||
@@ -228,16 +467,16 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
|
||||
cudaStream_t st = (cudaStream_t) stream;
|
||||
if (kv_mode == 3)
|
||||
attn_chunk_kernel<3><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
|
||||
STRATA_ATTN_CHUNK(3)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
|
||||
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
|
||||
else if (kv_mode == 2)
|
||||
attn_chunk_kernel<2><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
|
||||
STRATA_ATTN_CHUNK(2)<<<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 if (kv_mode == 1)
|
||||
attn_chunk_kernel<1><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
|
||||
STRATA_ATTN_CHUNK(1)<<<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
|
||||
attn_chunk_kernel<0><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
|
||||
STRATA_ATTN_CHUNK(0)<<<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);
|
||||
attn_merge_kernel<<<dim3((unsigned) s.n_head, (unsigned) n_q), HD, 0, st>>>(part_acc, part_m, part_l, n_chunks,
|
||||
attn, stride);
|
||||
@@ -276,17 +515,17 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32
|
||||
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv);
|
||||
cudaStream_t st = (cudaStream_t) stream;
|
||||
if (kv_mode == 3)
|
||||
attn_chunk_kernel<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);
|
||||
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);
|
||||
else if (kv_mode == 2)
|
||||
attn_chunk_kernel<2><<<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);
|
||||
STRATA_ATTN_CHUNK(2)<<<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 if (kv_mode == 1)
|
||||
attn_chunk_kernel<1><<<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);
|
||||
STRATA_ATTN_CHUNK(1)<<<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
|
||||
attn_chunk_kernel<0><<<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);
|
||||
STRATA_ATTN_CHUNK(0)<<<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);
|
||||
attn_merge_kernel<<<(unsigned) s.n_head, HD, 0, st>>>(part_acc, part_m, part_l, n_chunks, attn);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) {
|
||||
|
||||
@@ -736,6 +736,391 @@ bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// PR #600: compiled only into the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON), the one build that runs on a
|
||||
// Volta card; the ready-made engine has none of it (no extra kernels to load, the same code as before).
|
||||
#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
|
||||
// ---- sm_70 (Volta): v1's structure on mma.m8n8k4 ------------------------------------------------------------------
|
||||
// Volta's tensor cores only have m8n8k4 (FP16 in, FP32 accumulate): per warp FOUR independent 8x8x4 products, one per
|
||||
// quad-pair (QP q = lanes 4q..4q+3 and 4q+16..4q+19; thread j = (lane & 3) + 4 * (lane >> 4) within it). Layout, measured on
|
||||
// a V100 (tools-free microtest, and equal to turbomind's SM70_MMA_884): the thread holds row j of A (k 0..3 as two
|
||||
// registers) and column j of B (k 0..3); C register i is row (lane & 1) + 4 * (lane >> 4) + 2 * ((i >> 1) & 1),
|
||||
// column (lane & 2) + 4 * (i >> 2) + (i & 1) of its QP's 8x8 tile.
|
||||
// q.k: warp w owns dims [64w, 64w+64) = int8 scale group w; QP q takes cells 8q..8q+7 of the 32-cell chunk; 16 k-steps
|
||||
// of 4 dims, two 8-row blocks (12 heads + 4 zero rows), q as hi + lo halves. The warp's partial (times the
|
||||
// cells' K scale) goes to S.part[w]; the softmax adds the four groups in a fixed order (deterministic).
|
||||
// p.v: warp w owns dims [64w, 64w+64) again; QP q takes the 16 dims 64w+16q.. (two n-tiles of 8); k = the 32 cells in
|
||||
// steps of 4; p carries the V scale (as v1) and is split into hi + lo halves.
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 && __CUDA_ARCH__ < 750
|
||||
#define STRATA_PA_VOLTA 1
|
||||
#else
|
||||
#define STRATA_PA_VOLTA 0
|
||||
#endif
|
||||
|
||||
__device__ __forceinline__ void mma884(float* c, uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1) {
|
||||
#if STRATA_PA_VOLTA
|
||||
asm volatile("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, "
|
||||
"{%0,%1,%2,%3,%4,%5,%6,%7};\n"
|
||||
: "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]), "+f"(c[4]), "+f"(c[5]), "+f"(c[6]), "+f"(c[7])
|
||||
: "r"(a0), "r"(a1), "r"(b0), "r"(b1));
|
||||
#else
|
||||
__trap(); // m8n8k4 is a Volta instruction; the host only launches this kernel on sm_70
|
||||
#endif
|
||||
}
|
||||
|
||||
template <int KV_MODE>
|
||||
struct Smem70 {
|
||||
using KElem = typename std::conditional<KV_MODE == 0, __half, int8_t>::type;
|
||||
using VElem = typename std::conditional<KV_MODE == 1, int8_t, __half>::type;
|
||||
static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16;
|
||||
static constexpr int VROW = KV_MODE == 1 ? HD + 16 : HD + 8;
|
||||
__half qh[16][QS];
|
||||
__half ql[16][QS];
|
||||
KElem k[CH][KROW];
|
||||
VElem v[CH][VROW];
|
||||
float ks[CH][4];
|
||||
float vs[CH][4];
|
||||
float part[4][16][CH + 4]; // q.k per dim group (scaled by the cell's K scale)
|
||||
float s[16][CH + 4]; // the chunk's probabilities
|
||||
float qmax[THREADS / 32];
|
||||
float alpha[16];
|
||||
float lsum[16];
|
||||
float mrow[16];
|
||||
long long row[CH];
|
||||
};
|
||||
|
||||
template <int KV_MODE>
|
||||
__global__ void __launch_bounds__(THREADS) prompt_attn_v70_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[];
|
||||
Smem70<KV_MODE>& S = *reinterpret_cast<Smem70<KV_MODE>*>(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;
|
||||
attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
|
||||
ids += (size_t) qi * cap;
|
||||
const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
|
||||
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
const int qp = (lane >> 2) & 3, jj = (lane & 3) + 4 * (lane >> 4); // quad-pair, thread within it
|
||||
const int crow = (lane & 1) + 4 * (lane >> 4); // C row of register 0 (+2 per register pair)
|
||||
const int ccol = lane & 2; // C column of register 0 (+4 per half, +1 per reg)
|
||||
|
||||
// q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the
|
||||
// lo halves stay out of FP16's subnormal range), then split into hi + lo halves
|
||||
float qm = 0.0f;
|
||||
for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
|
||||
if (lane == 0) S.qmax[warp] = qm;
|
||||
__syncthreads();
|
||||
qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
|
||||
int qe = 0;
|
||||
if (qm > 0.0f) frexpf(qm, &qe); // qm < 2^qe
|
||||
const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
|
||||
for (int i = t; i < 16 * HD; i += THREADS) {
|
||||
const int h = i / HD, d = i % HD;
|
||||
const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f;
|
||||
const __half hi = __float2half_rn(x);
|
||||
S.qh[h][d] = hi;
|
||||
S.ql[h][d] = __float2half_rn(x - __half2float(hi));
|
||||
}
|
||||
if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
|
||||
|
||||
float acc[2][2][8];
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < 2; ++rb)
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 2; ++nt)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) acc[rb][nt][i] = 0.0f;
|
||||
|
||||
for (int c0 = 0; c0 < n; c0 += CH) {
|
||||
const int nh = min(CH, n - c0);
|
||||
if (t < CH) {
|
||||
long long r = -1;
|
||||
if (t < nh) {
|
||||
const int cell = ids[c0 + t];
|
||||
const long long page = (long long) p.page_table[cell / page_size];
|
||||
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
|
||||
}
|
||||
S.row[t] = r;
|
||||
}
|
||||
__syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s
|
||||
// gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16)
|
||||
// and their scales
|
||||
{
|
||||
constexpr int KPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::KElem) / 16; // per K row
|
||||
for (int i = t; i < CH * KPIECES; i += THREADS) {
|
||||
const int c = i / KPIECES, pc = i % KPIECES;
|
||||
const long long r = S.row[c];
|
||||
uint4 kx = make_uint4(0, 0, 0, 0);
|
||||
if (r >= 0) {
|
||||
if constexpr (KV_MODE == 0)
|
||||
kx = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + pc);
|
||||
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;
|
||||
}
|
||||
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;
|
||||
constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
|
||||
for (int i = t; i < CH * BLKS; i += THREADS) {
|
||||
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);
|
||||
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] =
|
||||
__float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
constexpr int VPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::VElem) / 16; // per V row
|
||||
for (int i = t; i < CH * VPIECES; i += THREADS) {
|
||||
const int c = i / VPIECES, pc = i % VPIECES;
|
||||
const long long r = S.row[c];
|
||||
uint4 vx = make_uint4(0, 0, 0, 0);
|
||||
if (r >= 0) {
|
||||
if constexpr (KV_MODE == 1)
|
||||
vx = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc);
|
||||
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;
|
||||
}
|
||||
}
|
||||
for (int i = t; i < CH * 4; i += THREADS) {
|
||||
const int c = i / 4, g = i % 4;
|
||||
const long long r = S.row[c];
|
||||
float a = 0.0f, b = 0.0f;
|
||||
if (r >= 0) {
|
||||
if constexpr (KV_MODE == 1) {
|
||||
a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
|
||||
b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g]));
|
||||
} else if constexpr (KV_MODE == 3) { // K as int8, V dequantized to fp16 (scale 1)
|
||||
a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
|
||||
b = 1.0f;
|
||||
} else {
|
||||
a = b = 1.0f;
|
||||
}
|
||||
}
|
||||
S.ks[c][g] = a;
|
||||
S.vs[c][g] = b;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
// scores: warp w = dim group w (64 dims), QP q = cells 8q..8q+7
|
||||
{
|
||||
float tg[2][8];
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < 2; ++rb)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) tg[rb][i] = 0.0f;
|
||||
const int cell_b = qp * 8 + jj;
|
||||
#pragma unroll
|
||||
for (int ks = 0; ks < 16; ++ks) {
|
||||
const int d0 = warp * 64 + ks * 4;
|
||||
uint32_t b0, b1;
|
||||
if constexpr (KV_MODE != 0) { // modes 1 and 3: the K side is INT8 codes, exact in FP16
|
||||
const uint32_t raw = *reinterpret_cast<const uint32_t*>(&S.k[cell_b][d0]);
|
||||
b0 = i8x2_to_h2(raw & 0xffffu);
|
||||
b1 = i8x2_to_h2(raw >> 16);
|
||||
} else {
|
||||
const uint2 raw = *reinterpret_cast<const uint2*>(&S.k[cell_b][d0]);
|
||||
b0 = raw.x;
|
||||
b1 = raw.y;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < 2; ++rb) {
|
||||
const uint2 ah = *reinterpret_cast<const uint2*>(&S.qh[rb * 8 + jj][d0]);
|
||||
const uint2 al = *reinterpret_cast<const uint2*>(&S.ql[rb * 8 + jj][d0]);
|
||||
mma884(tg[rb], ah.x, ah.y, b0, b1);
|
||||
mma884(tg[rb], al.x, al.y, b0, b1);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < 2; ++rb)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const int row = rb * 8 + crow + 2 * ((i >> 1) & 1);
|
||||
const int cell = qp * 8 + ccol + 4 * (i >> 2) + (i & 1);
|
||||
S.part[warp][row][cell] = tg[rb][i] * S.ks[cell][warp];
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
// 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;
|
||||
const int r = t >> 3, sub = t & 7;
|
||||
float x[PER], mx = -INFINITY;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PER; ++j) {
|
||||
const int c = sub * PER + j;
|
||||
const float sum4 = ((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c];
|
||||
x[j] = c < nh ? sum4 * qdown : -INFINITY;
|
||||
mx = fmaxf(mx, x[j]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
|
||||
const float m_old = S.mrow[r];
|
||||
const float m_new = fmaxf(m_old, mx);
|
||||
float sum = 0.0f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < PER; ++j) {
|
||||
const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
|
||||
S.s[r][sub * PER + j] = e;
|
||||
sum += e;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
|
||||
__syncwarp();
|
||||
if (sub == 0) {
|
||||
const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
|
||||
S.alpha[r] = a;
|
||||
S.lsum[r] = fmaf(S.lsum[r], a, sum);
|
||||
S.mrow[r] = m_new;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
__syncthreads();
|
||||
// p.v: warp w owns dims [64w, 64w+64) (int8 scale group w), QP q its 16 dims 64w+16q..; the V scale is folded
|
||||
// into p relative to the chunk's largest, times 2^14 (as v1)
|
||||
{
|
||||
float vmax = 0.0f;
|
||||
#pragma unroll
|
||||
for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]);
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
|
||||
const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
|
||||
float tmp[2][2][8];
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < 2; ++rb)
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 2; ++nt)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i) tmp[rb][nt][i] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int ks = 0; ks < CH / 4; ++ks) {
|
||||
const int c0 = ks * 4;
|
||||
float w[4];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e) w[e] = S.vs[c0 + e][warp] * vup;
|
||||
uint2 ah[2], al[2];
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < 2; ++rb) {
|
||||
const float4 pv = *reinterpret_cast<const float4*>(&S.s[rb * 8 + jj][c0]);
|
||||
const float p0 = pv.x * w[0], p1 = pv.y * w[1], p2 = pv.z * w[2], p3 = pv.w * w[3];
|
||||
ah[rb].x = pack_h2(p0, p1);
|
||||
ah[rb].y = pack_h2(p2, p3);
|
||||
const float2 f01 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].x));
|
||||
const float2 f23 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].y));
|
||||
al[rb].x = pack_h2(p0 - f01.x, p1 - f01.y);
|
||||
al[rb].y = pack_h2(p2 - f23.x, p3 - f23.y);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 2; ++nt) {
|
||||
const int d = warp * 64 + qp * 16 + nt * 8 + jj;
|
||||
uint32_t b0, b1;
|
||||
if constexpr (KV_MODE == 1) {
|
||||
const uint32_t x0 = (uint8_t) S.v[c0][d] | ((uint32_t) (uint8_t) S.v[c0 + 1][d] << 8);
|
||||
const uint32_t x1 = (uint8_t) S.v[c0 + 2][d] | ((uint32_t) (uint8_t) S.v[c0 + 3][d] << 8);
|
||||
b0 = i8x2_to_h2(x0);
|
||||
b1 = i8x2_to_h2(x1);
|
||||
} else {
|
||||
const __half2 h0 = __halves2half2(S.v[c0][d], S.v[c0 + 1][d]);
|
||||
const __half2 h1 = __halves2half2(S.v[c0 + 2][d], S.v[c0 + 3][d]);
|
||||
b0 = *reinterpret_cast<const uint32_t*>(&h0);
|
||||
b1 = *reinterpret_cast<const uint32_t*>(&h1);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < 2; ++rb) {
|
||||
mma884(tmp[rb][nt], ah[rb].x, ah[rb].y, b0, b1);
|
||||
mma884(tmp[rb][nt], al[rb].x, al[rb].y, b0, b1);
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < 2; ++rb) {
|
||||
float a_[2];
|
||||
a_[0] = S.alpha[rb * 8 + crow];
|
||||
a_[1] = S.alpha[rb * 8 + crow + 2];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 2; ++nt)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 8; ++i)
|
||||
acc[rb][nt][i] = fmaf(acc[rb][nt][i], a_[(i >> 1) & 1], tmp[rb][nt][i] * vdown);
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int rb = 0; rb < 2; ++rb)
|
||||
#pragma unroll
|
||||
for (int h = 0; h < 2; ++h) {
|
||||
const int row = rb * 8 + crow + 2 * h;
|
||||
if (row >= G) continue;
|
||||
const float l = S.lsum[row];
|
||||
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 2; ++nt)
|
||||
#pragma unroll
|
||||
for (int hh = 0; hh < 2; ++hh) {
|
||||
const int i = hh * 4 + h * 2; // registers i, i+1: row h, columns ccol + 4 * hh + {0, 1}
|
||||
const int d = warp * 64 + qp * 16 + nt * 8 + ccol + 4 * hh;
|
||||
*reinterpret_cast<float2*>(attn + (size_t) row * HD + d) =
|
||||
make_float2(acc[rb][nt][i] * inv, acc[rb][nt][i + 1] * inv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <int KV_MODE>
|
||||
bool launch70(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] = {};
|
||||
int dev = 0;
|
||||
cudaGetDevice(&dev);
|
||||
const int bytes = (int) sizeof(Smem70<KV_MODE>);
|
||||
if (dev < 0 || dev >= 64) return false;
|
||||
if (!attr[dev]) {
|
||||
if (cudaFuncSetAttribute(prompt_attn_v70_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
|
||||
cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
return false;
|
||||
}
|
||||
attr[dev] = true;
|
||||
}
|
||||
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_v70_kernel<KV_MODE><<<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);
|
||||
}
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "qsa_prompt_attn_batch (sm_70): %s\n", cudaGetErrorString(e));
|
||||
std::exit(1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#else // AMD, or a build without STRATA_EXPERIMENTAL_SM60: no m8n8k4 kernel (the caller keeps the old one)
|
||||
template <int KV_MODE>
|
||||
bool launch70(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, float*,
|
||||
int64_t, cudaStream_t) {
|
||||
return false;
|
||||
}
|
||||
#endif // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of
|
||||
// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims
|
||||
@@ -1022,11 +1407,14 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids,
|
||||
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 turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards)
|
||||
bool volta = false, turing = 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.
|
||||
// #371: the compute capability with its minor - sm_70 (V100) has no m16n8k8 (the kernels trap below sm_75)
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
return false; // gfx906: the tensor-core and WMMA kernels are not for it; the FP32 kernel runs
|
||||
#endif
|
||||
static int cc[64] = {};
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
|
||||
@@ -1042,13 +1430,14 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 75
|
||||
: 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor);
|
||||
}
|
||||
if (cc[dev] < 75) return false;
|
||||
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;
|
||||
}
|
||||
#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
|
||||
// matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel
|
||||
(void) turing;
|
||||
(void) turing; (void) volta;
|
||||
if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&
|
||||
pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&
|
||||
cap > 0 && ids && steps && pools.page_table && hip_wmma_usable())
|
||||
@@ -1069,6 +1458,7 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
}
|
||||
if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 V
|
||||
if (!pools.k_scale) return false;
|
||||
if (volta) return launch70<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
}
|
||||
if (pools.k_q != nullptr) {
|
||||
@@ -1077,10 +1467,12 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
// for how far the model amplifies an FP32-level change. Turing always takes it: v2's cp.async does not
|
||||
// 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);
|
||||
return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
}
|
||||
if (!pools.k_pool || !pools.v_pool) return false;
|
||||
if (volta) return launch70<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
}
|
||||
|
||||
|
||||
@@ -186,6 +186,83 @@ __global__ void router_top10_kernel(const float* __restrict__ logits, int n_toke
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// AMD (wave64): the same routing in ONE wavefront per token. The block-wide kernel above spends its time in
|
||||
// barriers - 10 selection passes with two __syncthreads each over 8 logical warps - not in arithmetic (43 us per
|
||||
// token on gfx906). Here every lane holds up to RW_PER probabilities in registers and each pass is a 64-lane
|
||||
// butterfly argmax: no LDS round trip, no block barrier. Bit-identical to the kernel above: fmaxf trees are
|
||||
// exact, the exponentials and the (float) products are the same expressions, the sum stays one serial ascending
|
||||
// scan, and the argmax keeps the lowest index on a tie (a total order, so the butterfly's association is free).
|
||||
constexpr int RW_PER = 8; // n_expert <= 64 * 8
|
||||
__global__ void __launch_bounds__(64) router_top10_wave_kernel(const float* __restrict__ logits, int n_tokens,
|
||||
int n_expert, int k, int* __restrict__ ids,
|
||||
float* __restrict__ weights) {
|
||||
__shared__ double s_ex[64 * RW_PER];
|
||||
__shared__ double s_sum;
|
||||
const int t = blockIdx.x;
|
||||
if (t >= n_tokens) return;
|
||||
const int lane = threadIdx.x;
|
||||
const float* l = logits + (size_t) t * n_expert;
|
||||
float lv[RW_PER];
|
||||
float mx = -INFINITY;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < RW_PER; ++j) {
|
||||
const int e = lane + 64 * j;
|
||||
lv[j] = e < n_expert ? l[e] : -INFINITY;
|
||||
mx = fmaxf(mx, lv[j]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int off = 32; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 64));
|
||||
#pragma unroll
|
||||
for (int j = 0; j < RW_PER; ++j) {
|
||||
const int e = lane + 64 * j;
|
||||
if (e < n_expert) s_ex[e] = exp((double) lv[j] - (double) mx);
|
||||
}
|
||||
__syncthreads();
|
||||
if (lane == 0) {
|
||||
double sum = 0.0;
|
||||
for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
|
||||
s_sum = sum;
|
||||
}
|
||||
__syncthreads();
|
||||
const float inv = (float) (1.0 / s_sum);
|
||||
float p[RW_PER];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < RW_PER; ++j) {
|
||||
const int e = lane + 64 * j;
|
||||
p[j] = e < n_expert ? (float) (s_ex[e] * inv) : -INFINITY;
|
||||
}
|
||||
unsigned taken = 0;
|
||||
for (int i = 0; i < k; ++i) {
|
||||
float bv = -INFINITY;
|
||||
int bi = n_expert;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < RW_PER; ++j) {
|
||||
const int e = lane + 64 * j;
|
||||
if (e >= n_expert || (taken >> j & 1u)) continue;
|
||||
if (p[j] > bv || (p[j] == bv && e < bi)) { bv = p[j]; bi = e; }
|
||||
}
|
||||
#pragma unroll
|
||||
for (int off = 32; off > 0; off >>= 1) {
|
||||
const float ov = __shfl_xor(bv, off, 64);
|
||||
const int oi = __shfl_xor(bi, off, 64);
|
||||
if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
|
||||
}
|
||||
if (bi >= n_expert) break;
|
||||
if ((bi & 63) == lane) taken |= 1u << (bi >> 6);
|
||||
if (lane == 0) { ids[(size_t) t * k + i] = bi; weights[(size_t) t * k + i] = bv; }
|
||||
}
|
||||
if (lane == 0) {
|
||||
double s = 0.0;
|
||||
for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];
|
||||
const double sc = fmax(s, 6.103515625e-05); // 2**-14
|
||||
for (int i = 0; i < k; ++i)
|
||||
weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);
|
||||
}
|
||||
}
|
||||
#endif // STRATA_HIP_GFX906
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
// ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel
|
||||
// above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64
|
||||
@@ -346,7 +423,13 @@ void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* i
|
||||
void* stream) {
|
||||
#if defined(__HIPCC__)
|
||||
{
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// gfx906 (wave64): the one-wavefront kernel below stays the default; the S6 kernel is wave32-shaped and only
|
||||
// runs here on request (STRATA_HIP_ROUTER_FAST=1) until it is measured on this card
|
||||
static const bool old = std::getenv("STRATA_HIP_ROUTER_FAST") == nullptr;
|
||||
#else
|
||||
static const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr;
|
||||
#endif
|
||||
if (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) {
|
||||
launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
@@ -375,6 +458,19 @@ void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* i
|
||||
RT_MAX_THREADS * 64);
|
||||
std::exit(1);
|
||||
}
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
if (n_expert <= 64 * RW_PER && !std::getenv("STRATA_ROUTER_BLOCK")) {
|
||||
router_top10_wave_kernel<<<(unsigned) n_tokens, 64, 0, (cudaStream_t) stream>>>(logits, n_tokens, n_expert, k,
|
||||
ids, weights);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));
|
||||
std::exit(1);
|
||||
}
|
||||
if (stream == nullptr && cudaDeviceSynchronize() != cudaSuccess) std::exit(1);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS;
|
||||
threads = (threads + 31) & ~31; // at least one full warp, for the reductions
|
||||
// the selection's taken-mask, then n_expert doubles for the exponentials, then n_expert floats for the
|
||||
|
||||
@@ -545,7 +545,9 @@ void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* i
|
||||
// a GPU timestamp (ns, %globaltimer) into buf[i] - the verify window's stage profiler
|
||||
namespace { __global__ void gpu_stamp_kernel(unsigned long long* buf, int i) {
|
||||
unsigned long long t;
|
||||
#if defined(__HIPCC__)
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
t = wall_clock64() * 40ull; // gfx906: the wall clock runs at 25 MHz (hipDeviceAttributeWallClockRate) -> ns
|
||||
#elif defined(__HIPCC__)
|
||||
t = wall_clock64() * 10ull; // gfx10.3 / gfx11 / gfx12: a constant 100 MHz counter, in ns
|
||||
#else
|
||||
asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
// src/kernels/fused_gr_bench.cpp - fused_gr_read_multi: the AMD fast kernels (STRATA_GR_FAST) against the old
|
||||
// ones, bit for bit on every output (lo, rs, inject, mixed, the in-place R), and each one's time.
|
||||
//
|
||||
// build/fused_gr_bench [iters] [T min] [T max]
|
||||
#include "strata/kernels/fused_gr.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace K = strata::kernels;
|
||||
|
||||
static uint16_t bf16(float x) {
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &x, 4);
|
||||
return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
const int iters = argc > 1 ? std::atoi(argv[1]) : 500;
|
||||
const int t_lo = argc > 2 ? std::atoi(argv[2]) : 1, t_hi = argc > 3 ? std::atoi(argv[3]) : 6;
|
||||
const int N = 2560, HC = 4, D = N * HC, LR = 320, TM = K::kFusedGrMaxT;
|
||||
std::mt19937 rng(7);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
auto fill = [&](std::vector<float>& v, float sc) { for (auto& x : v) x = sc * nd(rng); };
|
||||
std::vector<float> R((size_t) TM * D), bo((size_t) TM * N), inj((size_t) TM * HC), wn(D);
|
||||
fill(R, 1.0f); fill(bo, 0.5f); fill(inj, 1.0f); fill(wn, 0.3f);
|
||||
for (auto& x : wn) x += 1.0f;
|
||||
std::vector<uint16_t> wd((size_t) LR * D), wu((size_t) D * LR), wi((size_t) HC * D);
|
||||
for (auto& x : wd) x = bf16(0.02f * nd(rng));
|
||||
for (auto& x : wu) x = bf16(0.05f * nd(rng));
|
||||
for (auto& x : wi) x = bf16(0.02f * nd(rng));
|
||||
float *dR, *dbo, *dinj, *dwn, *dxn, *dlo, *drs, *dio, *dmix;
|
||||
uint16_t *dwd, *dwu, *dwi;
|
||||
cudaMalloc((void**) &dR, R.size() * 4);
|
||||
cudaMalloc((void**) &dbo, bo.size() * 4);
|
||||
cudaMalloc((void**) &dinj, inj.size() * 4);
|
||||
cudaMalloc((void**) &dwn, wn.size() * 4);
|
||||
cudaMalloc((void**) &dxn, (size_t) TM * D * 4);
|
||||
cudaMalloc((void**) &dlo, (size_t) TM * LR * 4);
|
||||
cudaMalloc((void**) &drs, (size_t) TM * HC * 4);
|
||||
cudaMalloc((void**) &dio, (size_t) TM * HC * 4);
|
||||
cudaMalloc((void**) &dmix, (size_t) TM * N * 4);
|
||||
cudaMalloc((void**) &dwd, wd.size() * 2);
|
||||
cudaMalloc((void**) &dwu, wu.size() * 2);
|
||||
cudaMalloc((void**) &dwi, wi.size() * 2);
|
||||
cudaMemcpy(dbo, bo.data(), bo.size() * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dinj, inj.data(), inj.size() * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dwn, wn.data(), wn.size() * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dwd, wd.data(), wd.size() * 2, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dwu, wu.data(), wu.size() * 2, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dwi, wi.data(), wi.size() * 2, cudaMemcpyHostToDevice);
|
||||
cudaStream_t s;
|
||||
cudaStreamCreate(&s);
|
||||
cudaEvent_t e0, e1;
|
||||
cudaEventCreate(&e0);
|
||||
cudaEventCreate(&e1);
|
||||
int failures = 0;
|
||||
for (int T = t_lo; T <= t_hi; ++T)
|
||||
for (int apply = 0; apply < 2; ++apply)
|
||||
for (int inject = 0; inject < 2; ++inject) {
|
||||
K::FusedGrArgs a[TM];
|
||||
for (int t = 0; t < T; ++t) {
|
||||
a[t].R = dR + (size_t) t * D; a[t].R_out = dR + (size_t) t * D; a[t].apply = apply;
|
||||
a[t].bo_prev = dbo + (size_t) t * N; a[t].inj_prev = dinj + (size_t) t * HC;
|
||||
a[t].w_norm = dwn; a[t].w_down = dwd; a[t].w_up = dwu; a[t].w_inject = inject ? dwi : nullptr;
|
||||
a[t].lo = dlo + (size_t) t * LR; a[t].rs = drs + (size_t) t * HC;
|
||||
a[t].inject_out = dio + (size_t) t * HC; a[t].mixed = dmix + (size_t) t * N;
|
||||
}
|
||||
std::vector<float> out[2];
|
||||
for (int f = 0; f < 2; ++f) {
|
||||
cudaMemcpy(dR, R.data(), R.size() * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemset(dlo, 0xff, (size_t) TM * LR * 4);
|
||||
cudaMemset(drs, 0xff, (size_t) TM * HC * 4);
|
||||
cudaMemset(dio, 0xff, (size_t) TM * HC * 4);
|
||||
cudaMemset(dmix, 0xff, (size_t) TM * N * 4);
|
||||
K::fused_gr_set_fast(f);
|
||||
K::fused_gr_read_multi(a, T, dxn, s);
|
||||
cudaStreamSynchronize(s);
|
||||
auto& o = out[f];
|
||||
o.resize((size_t) TM * (D + LR + HC + HC + N));
|
||||
float* p = o.data();
|
||||
cudaMemcpy(p, dR, (size_t) TM * D * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * D;
|
||||
cudaMemcpy(p, dlo, (size_t) TM * LR * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * LR;
|
||||
cudaMemcpy(p, drs, (size_t) TM * HC * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * HC;
|
||||
cudaMemcpy(p, dio, (size_t) TM * HC * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * HC;
|
||||
cudaMemcpy(p, dmix, (size_t) TM * N * 4, cudaMemcpyDeviceToHost);
|
||||
}
|
||||
const bool same = std::memcmp(out[0].data(), out[1].data(), out[0].size() * 4) == 0;
|
||||
double us[2] = {1e30, 1e30};
|
||||
for (int round = 0; round < 3; ++round)
|
||||
for (int f = 0; f < 2; ++f) {
|
||||
K::fused_gr_set_fast(f);
|
||||
for (int i = 0; i < 20; ++i) K::fused_gr_read_multi(a, T, dxn, s);
|
||||
cudaEventRecord(e0, s);
|
||||
for (int i = 0; i < iters; ++i) K::fused_gr_read_multi(a, T, dxn, s);
|
||||
cudaEventRecord(e1, s);
|
||||
cudaEventSynchronize(e1);
|
||||
float ms = 0;
|
||||
cudaEventElapsedTime(&ms, e0, e1);
|
||||
us[f] = std::fmin(us[f], 1e3 * ms / iters);
|
||||
}
|
||||
std::printf("T %d apply %d inject %d | old %6.1f us fast %6.1f us | %s\n", T, apply, inject, us[0], us[1],
|
||||
same ? "bitwise equal" : "DIFFERS");
|
||||
if (!same) ++failures;
|
||||
}
|
||||
std::printf("fused_gr_bench: %d differing\n", failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -329,7 +329,7 @@ int main() {
|
||||
float* d_at4 = dalloc<float>((size_t) QH * D);
|
||||
const bool took = k::qsa_prompt_attn_batch(d_q, pools, d_ids, d_step, cells, s, d_at4, 1, nullptr);
|
||||
if (!took) {
|
||||
#if defined(STRATA_USE_HIP)
|
||||
#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
|
||||
// AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runs
|
||||
std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n");
|
||||
#else
|
||||
|
||||
@@ -36,6 +36,8 @@
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
@@ -236,6 +238,16 @@ int main() {
|
||||
}
|
||||
// THE NEGATIVE CONTROL, asserted where it can see something: past T = 4 the generic layout is a different one,
|
||||
// so if it still finds no difference the comparison cannot tell the layouts apart and the pass proves nothing.
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// gfx906: the wave64 layout (one wavefront per row) is the same kernel for every column count, so multi_exact
|
||||
// has nothing to switch and the control cannot see a difference. The control with power is the CUDA layout:
|
||||
// ctest's mmvq_multi_parity_cuda_layout runs this with STRATA_MMVQ_WAVE=0.
|
||||
if (off.powerless_cases != 0 && !(std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0")) {
|
||||
std::printf("\nmmvq_multi_parity: ok (gfx906 wave64 layout: every column count runs the same exact kernel, "
|
||||
"so the negative control has no other layout to find; mmvq_multi_parity_cuda_layout checks it).\n");
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
if (off.powerless_cases != 0) {
|
||||
std::printf("\nmmvq_multi_parity: FAILED (no power). In %d case(s) no output differs with multi_exact off at "
|
||||
"any T > %d, where the generic layout is not the exact one: for those cases this comparison "
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
// src/kernels/native_expert_bench.cpp - the grouped native experts on real GGUF rows: one AMD layout against
|
||||
// another, bit for bit, and each one's time.
|
||||
//
|
||||
// build/native_expert_bench <shard1.gguf> <layer[,layer...]> <groups> <tokens per group> <ref mode> <mode> [iters]
|
||||
//
|
||||
// Modes are STRATA_EXP_MODE values. A group is one expert (distinct blobs, ~2 MB each, so G >= 8 does not fit
|
||||
// in L2); its entries read distinct tokens of an 8-token window. The output must be bitwise equal to the
|
||||
// reference mode's: the verify window's text depends on it.
|
||||
#include "strata/artifact/gguf_reader.hpp"
|
||||
#include "strata/kernels/cpu/native_expert.hpp"
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
|
||||
#include "ggml.h"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace cpu = strata::kernels::cpu;
|
||||
namespace K = strata::kernels;
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
setvbuf(stdout, nullptr, _IONBF, 0);
|
||||
if (argc < 7) {
|
||||
std::fprintf(stderr, "usage: native_expert_bench <shard1.gguf> <layer[,layer]> <groups> <tokens> <ref mode> <mode> [iters]\n");
|
||||
return 2;
|
||||
}
|
||||
strata::GgufFile gguf(argv[1]);
|
||||
std::vector<int> layers;
|
||||
{
|
||||
std::stringstream ss(argv[2]);
|
||||
std::string t;
|
||||
while (std::getline(ss, t, ',')) layers.push_back(std::atoi(t.c_str()));
|
||||
}
|
||||
const int G = std::atoi(argv[3]), T = std::atoi(argv[4]), mref = std::atoi(argv[5]), mode = std::atoi(argv[6]);
|
||||
const int iters = argc > 7 ? std::atoi(argv[7]) : 200;
|
||||
const int NTOK = 8;
|
||||
if (T < 1 || T > NTOK || G < 1) { std::fprintf(stderr, "tokens 1..8, groups >= 1\n"); return 2; }
|
||||
const int64_t H = 2560, FF_FULL = 640, FF = FF_FULL; // Flash-Next's expert geometry
|
||||
int failures = 0;
|
||||
cudaStream_t s;
|
||||
cudaStreamCreate(&s);
|
||||
cudaEvent_t e0, e1;
|
||||
cudaEventCreate(&e0);
|
||||
cudaEventCreate(&e1);
|
||||
for (int l : layers) {
|
||||
const strata::TensorInfo* t[3] = {};
|
||||
const char* roles[3] = {"gate", "up", "down"};
|
||||
for (const auto& ti : gguf.tensors())
|
||||
for (int r = 0; r < 3; ++r)
|
||||
if (ti.name == "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight") t[r] = &ti;
|
||||
if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; }
|
||||
cpu::NativeFmt f;
|
||||
std::string err;
|
||||
if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) {
|
||||
std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue;
|
||||
}
|
||||
cpu::NativeFmt ff; // the full expert's geometry, for strides into the GGUF
|
||||
if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF_FULL, ff, err)) {
|
||||
std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue;
|
||||
}
|
||||
const size_t dsz = f.bytes - f.down_off, dsz_full = ff.bytes - ff.down_off;
|
||||
const size_t drow = dsz / H, drow_full = dsz_full / H;
|
||||
std::vector<uint8_t> blobs((size_t) G * f.bytes);
|
||||
for (int g = 0; g < G; ++g) {
|
||||
const size_t E = (size_t) ((g * 37 + 5) % 256);
|
||||
uint8_t* b = blobs.data() + (size_t) g * f.bytes;
|
||||
std::memcpy(b, gguf.tensor_data(*t[0]) + E * ff.up_off, f.up_off);
|
||||
std::memcpy(b + f.up_off, gguf.tensor_data(*t[1]) + E * ff.up_off, f.up_off);
|
||||
for (int64_t r = 0; r < H; ++r)
|
||||
std::memcpy(b + f.down_off + r * drow, gguf.tensor_data(*t[2]) + E * dsz_full + r * drow_full, drow);
|
||||
}
|
||||
std::mt19937 rng(17 + l);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::vector<float> x((size_t) NTOK * H);
|
||||
for (auto& v : x) v = nd(rng);
|
||||
const int NE = G * T;
|
||||
std::vector<unsigned long long> ptr(G);
|
||||
std::vector<int32_t> start(G + 1), dst(NE), tok(NE);
|
||||
const auto L = K::native_expert_layout(f.gu_type, f.d_type, H, FF);
|
||||
uint8_t* dblob;
|
||||
void *dx, *dxq, *dscr;
|
||||
float* dout;
|
||||
unsigned long long* dptr;
|
||||
int32_t *dstart, *dn, *ddst, *dtok;
|
||||
cudaMalloc((void**) &dblob, blobs.size());
|
||||
cudaMalloc(&dx, x.size() * 4);
|
||||
cudaMalloc(&dxq, (size_t) NTOK * H / 32 * 36);
|
||||
cudaMalloc(&dscr, K::native_expert_scratch_bytes(NE, FF));
|
||||
cudaMalloc((void**) &dout, (size_t) NE * H * 4);
|
||||
cudaMalloc((void**) &dptr, (size_t) G * 8);
|
||||
cudaMalloc((void**) &dstart, (size_t) (G + 1) * 4);
|
||||
cudaMalloc((void**) &dn, 4);
|
||||
cudaMalloc((void**) &ddst, (size_t) NE * 4);
|
||||
cudaMalloc((void**) &dtok, (size_t) NE * 4);
|
||||
for (int g = 0; g < G; ++g) {
|
||||
ptr[g] = (unsigned long long) (dblob + (size_t) g * f.bytes);
|
||||
start[g] = g * T;
|
||||
for (int j = 0; j < T; ++j) {
|
||||
dst[g * T + j] = g * T + j;
|
||||
tok[g * T + j] = (g * 3 + j) % NTOK;
|
||||
}
|
||||
}
|
||||
start[G] = NE;
|
||||
cudaMemcpy(dblob, blobs.data(), blobs.size(), cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dptr, ptr.data(), (size_t) G * 8, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dstart, start.data(), (size_t) (G + 1) * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dn, &G, 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(ddst, dst.data(), (size_t) NE * 4, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dtok, tok.data(), (size_t) NE * 4, cudaMemcpyHostToDevice);
|
||||
K::quantize_q8_1_rows((const float*) dx, NTOK, H, dxq, s);
|
||||
auto run = [&](int m, int phase) {
|
||||
K::native_expert_set_mode(m, phase);
|
||||
K::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, G, NE, dxq, dscr, dout, s);
|
||||
};
|
||||
std::vector<float> ref((size_t) NE * H), got((size_t) NE * H);
|
||||
cudaMemsetAsync(dout, 0xff, got.size() * 4, s);
|
||||
run(mref, 0);
|
||||
cudaMemcpyAsync(ref.data(), dout, ref.size() * 4, cudaMemcpyDeviceToHost, s);
|
||||
cudaMemsetAsync(dout, 0xff, got.size() * 4, s);
|
||||
run(mode, 0);
|
||||
cudaMemcpyAsync(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost, s);
|
||||
if (cudaStreamSynchronize(s) != cudaSuccess) { std::printf("layer %d: CUDA error\n", l); return 1; }
|
||||
size_t ndiff = 0;
|
||||
double worst = 0;
|
||||
for (size_t i = 0; i < ref.size(); ++i)
|
||||
if (std::memcmp(&ref[i], &got[i], 4) != 0) {
|
||||
++ndiff;
|
||||
worst = std::fmax(worst, std::fabs((double) ref[i] - got[i]) / (std::fabs((double) ref[i]) + 1e-6));
|
||||
}
|
||||
auto time = [&](int m, int phase) {
|
||||
for (int i = 0; i < 10; ++i) run(m, phase);
|
||||
cudaEventRecord(e0, s);
|
||||
for (int i = 0; i < iters; ++i) run(m, phase);
|
||||
cudaEventRecord(e1, s);
|
||||
cudaEventSynchronize(e1);
|
||||
float ms = 0;
|
||||
cudaEventElapsedTime(&ms, e0, e1);
|
||||
return 1e3 * ms / iters;
|
||||
};
|
||||
const double gu_b = (double) G * 2 * f.up_off, d_b = (double) G * dsz;
|
||||
double us[2][3] = {{1e30, 1e30, 1e30}, {1e30, 1e30, 1e30}};
|
||||
for (int round = 0; round < 3; ++round) // interleaved, the minimum: the clocks wander between runs
|
||||
for (int k = 0; k < 2; ++k)
|
||||
for (int p = 0; p < 3; ++p) us[k][p] = std::fmin(us[k][p], time(k ? mode : mref, p));
|
||||
std::printf("layer %2d %-7s/%-6s G %d T %d | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s)"
|
||||
" | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s) | %s\n",
|
||||
l, ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), G, T,
|
||||
mref, us[0][0], us[0][1], gu_b / us[0][1] / 1e3, us[0][2], d_b / us[0][2] / 1e3,
|
||||
mode, us[1][0], us[1][1], gu_b / us[1][1] / 1e3, us[1][2], d_b / us[1][2] / 1e3,
|
||||
ndiff ? "DIFFERS" : "bitwise equal");
|
||||
if (ndiff) {
|
||||
std::printf(" %zu of %zu outputs differ, worst rel %.2e\n", ndiff, ref.size(), worst);
|
||||
++failures;
|
||||
}
|
||||
K::native_expert_set_mode(-1, 0);
|
||||
cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr);
|
||||
cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok);
|
||||
}
|
||||
std::printf("native_expert_bench: %d differing\n", failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -41,6 +41,18 @@ float h2f(uint16_t b) { __half h; *reinterpret_cast<uint16_t*>(&h) = b; return _
|
||||
uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }
|
||||
|
||||
int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 q4_0
|
||||
#if !defined(__HIPCC__) && !defined(STRATA_USE_HIP)
|
||||
if (fmt == 2) { // mode 4 (Q4_0 KV) runs on sm_80 and newer only: below that the dispatcher keeps the old kernel
|
||||
int dev = 0, major = 0;
|
||||
ck(cudaGetDevice(&dev), "device");
|
||||
ck(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev), "cc");
|
||||
if (major < 8) {
|
||||
std::printf("SKIP q4_0 ctx %lld: the tensor-core kernel takes Q4_0 KV on sm_80+ only (this device: sm_%d)\n",
|
||||
(long long) ctx, major);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
const k::QsaShapes s = k::qsa_real_shapes();
|
||||
const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
|
||||
const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// route_window_parity - the verify window's batched routing against the per-token calls, bit for bit.
|
||||
//
|
||||
// `moe_route_window` replaces n per-token (projection + top-k) pairs by one multi-column BF16 projection and one
|
||||
// n-token top-k. Speculative decoding is exact only if a token's route does not depend on how many tokens share
|
||||
// its window, so both batched kernels must equal their one-token forms exactly - this checks that on random data
|
||||
// shaped like the router (2560 -> 256, top-10) and like the shared-expert gate (2560 -> 1).
|
||||
#include "strata/kernels/bf16_gemv.hpp"
|
||||
#include "strata/kernels/router_top10.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
void ck(cudaError_t e, const char* what) {
|
||||
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(2); }
|
||||
}
|
||||
uint16_t bf16(float f) { uint32_t i; std::memcpy(&i, &f, 4); return (uint16_t) ((i + ((i >> 16) & 1u) + 0x7FFFu) >> 16); }
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
const int N = 2560, E = 256, K = 10;
|
||||
int bad = 0;
|
||||
std::mt19937 rng(7);
|
||||
std::normal_distribution<float> nd(0.0f, 1.0f);
|
||||
for (int n_out : {E, 1}) {
|
||||
for (int T : {2, 3, 4, 6}) {
|
||||
std::vector<uint16_t> w((size_t) n_out * N);
|
||||
std::vector<float> x((size_t) T * N);
|
||||
for (auto& v : w) v = bf16(nd(rng) * 0.05f);
|
||||
for (auto& v : x) v = nd(rng);
|
||||
uint16_t* dw; float *dx, *dy1, *dyn;
|
||||
ck(cudaMalloc(&dw, w.size() * 2), "w"); ck(cudaMalloc(&dx, x.size() * 4), "x");
|
||||
ck(cudaMalloc(&dy1, (size_t) T * n_out * 4), "y1"); ck(cudaMalloc(&dyn, (size_t) T * n_out * 4), "yn");
|
||||
ck(cudaMemcpy(dw, w.data(), w.size() * 2, cudaMemcpyHostToDevice), "up w");
|
||||
ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "up x");
|
||||
for (int t = 0; t < T; ++t)
|
||||
strata::kernels::bf16_gemv_fp32_mmvf(dx + (size_t) t * N, dw, dy1 + (size_t) t * n_out, N, n_out, nullptr);
|
||||
strata::kernels::bf16_gemv_fp32_mmvf_cols(dx, dw, dyn, N, n_out, T, nullptr);
|
||||
ck(cudaDeviceSynchronize(), "sync");
|
||||
std::vector<float> y1((size_t) T * n_out), yn((size_t) T * n_out);
|
||||
ck(cudaMemcpy(y1.data(), dy1, y1.size() * 4, cudaMemcpyDeviceToHost), "down 1");
|
||||
ck(cudaMemcpy(yn.data(), dyn, yn.size() * 4, cudaMemcpyDeviceToHost), "down n");
|
||||
const bool same = std::memcmp(y1.data(), yn.data(), y1.size() * 4) == 0;
|
||||
std::printf(" mmvf cols n_out %3d T %d %s\n", n_out, T, same ? "bit-identical" : "*** DIFFERS ***");
|
||||
if (!same) ++bad;
|
||||
if (n_out == E) {
|
||||
int *i1, *in_; float *w1, *wn;
|
||||
ck(cudaMalloc(&i1, (size_t) T * K * 4), "i1"); ck(cudaMalloc(&in_, (size_t) T * K * 4), "in");
|
||||
ck(cudaMalloc(&w1, (size_t) T * K * 4), "w1"); ck(cudaMalloc(&wn, (size_t) T * K * 4), "wn");
|
||||
for (int t = 0; t < T; ++t)
|
||||
strata::kernels::router_top10(dy1 + (size_t) t * E, 1, E, K, i1 + t * K, w1 + t * K, nullptr);
|
||||
strata::kernels::router_top10(dy1, T, E, K, in_, wn, nullptr);
|
||||
ck(cudaDeviceSynchronize(), "sync top");
|
||||
std::vector<int> a((size_t) T * K), b((size_t) T * K);
|
||||
std::vector<float> fa((size_t) T * K), fb((size_t) T * K);
|
||||
ck(cudaMemcpy(a.data(), i1, a.size() * 4, cudaMemcpyDeviceToHost), "ids1");
|
||||
ck(cudaMemcpy(b.data(), in_, b.size() * 4, cudaMemcpyDeviceToHost), "idsn");
|
||||
ck(cudaMemcpy(fa.data(), w1, fa.size() * 4, cudaMemcpyDeviceToHost), "w1");
|
||||
ck(cudaMemcpy(fb.data(), wn, fb.size() * 4, cudaMemcpyDeviceToHost), "wn");
|
||||
const bool s2 = a == b && std::memcmp(fa.data(), fb.data(), fa.size() * 4) == 0;
|
||||
std::printf(" top10 n T %d %s\n", T, s2 ? "bit-identical" : "*** DIFFERS ***");
|
||||
if (!s2) ++bad;
|
||||
cudaFree(i1); cudaFree(in_); cudaFree(w1); cudaFree(wn);
|
||||
}
|
||||
cudaFree(dw); cudaFree(dx); cudaFree(dy1); cudaFree(dyn);
|
||||
}
|
||||
}
|
||||
std::printf(bad ? "route_window_parity: %d FAILURES\n" : "route_window_parity OK\n", bad);
|
||||
return bad ? 1 : 0;
|
||||
}
|
||||
@@ -3,8 +3,12 @@
|
||||
#include "strata/kernels/dequant_bf16.hpp"
|
||||
|
||||
#include <cublas_v2.h>
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
|
||||
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
|
||||
// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers.
|
||||
// hipBLASLt's public headers declare native HIP shuffle functions, so keep
|
||||
@@ -298,6 +302,8 @@ Gemm::~Gemm() {
|
||||
delete static_cast<HipLtState*>(hipblaslt_state_);
|
||||
#endif
|
||||
if (handle_) cublasDestroy((cublasHandle_t) handle_);
|
||||
if (tc_w_) cudaFree(tc_w_);
|
||||
if (tc_x_) cudaFree(tc_x_);
|
||||
if (!external_) {
|
||||
if (scratch_) cudaFree(scratch_);
|
||||
if (workspace_) cudaFree(workspace_);
|
||||
@@ -372,6 +378,89 @@ bool Gemm::init(void* stream, int64_t scratch_elems, std::string& err) {
|
||||
return true;
|
||||
}
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
// ---- below sm_80: BF16 GEMMs without BF16 tensor cores (PR #655, #540, #395) ----------------------------------------
|
||||
// Turing and Volta have no BF16 tensor cores: cublasGemmEx on CUDA_R_16BF inputs falls back to a SIMT fp32 kernel
|
||||
// (magma_sgemmEx), a fifth of a 4K prompt on an RTX 2080 Ti (#655) and ~10% of a V100's prompt (#540). BF16 -> FP16
|
||||
// is exact for every value inside FP16's normal range (the 7-bit mantissa fits in 10 bits); weights and normalized
|
||||
// activations sit there. With the FP16 path, the weight is converted once per call and the activations in row
|
||||
// slices, into the instance's own buffers, and the product runs as the FP16 GEMM (fp32 accumulate) on the tensor
|
||||
// cores. Finite values beyond FP16's range are clamped to +-65504 (#540) instead of becoming Inf. A beta = 1
|
||||
// product (STRATA_PREFILL_BF16X2's remainder, ~2^-9 of the original, deep in FP16's subnormal band) keeps cuBLAS.
|
||||
// Default: on for compute capability 7.0 - 7.4 (Volta: only the experimental STRATA_EXPERIMENTAL_SM60 build runs
|
||||
// there), OFF for 7.5 (RTX 20 in the ready-made engine: the sums round differently, so it is opt-in until it has
|
||||
// been gated). STRATA_BF16_TC=1 / =0 turns it on / off on any 7.x card (=2, a test mode: on any card).
|
||||
// Pascal (6.x) has no tensor cores and cuBLAS has no BF16 GEMM for it (#395, measured NOT_SUPPORTED on a P40): both
|
||||
// operands are widened to fp32 by an exact shift and the product is cublasSgemm with the same fp32 accumulator.
|
||||
namespace {
|
||||
__global__ void bf16_to_f16_kernel(const uint16_t* __restrict__ in, __half* __restrict__ out, int64_t n) {
|
||||
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i < n) {
|
||||
float f = __uint_as_float((uint32_t) in[i] << 16);
|
||||
if (f > 65504.0f && !isinf(f)) f = 65504.0f;
|
||||
else if (f < -65504.0f && !isinf(f)) f = -65504.0f;
|
||||
out[i] = __float2half_rn(f);
|
||||
}
|
||||
}
|
||||
void bf16_to_f16(const uint16_t* in, uint16_t* out, int64_t n, cudaStream_t st) {
|
||||
if (n <= 0) return;
|
||||
bf16_to_f16_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, reinterpret_cast<__half*>(out), n);
|
||||
}
|
||||
#if defined(STRATA_EXPERIMENTAL_SM60) // Pascal runs only the experimental build
|
||||
__global__ void bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) {
|
||||
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i < n) out[i] = __uint_as_float((uint32_t) in[i] << 16);
|
||||
}
|
||||
void bf16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) {
|
||||
if (n <= 0) return;
|
||||
bf16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n);
|
||||
}
|
||||
#endif
|
||||
// The current device's compute capability as 10 * major + minor, per device (a layer split can mix cards); 0: not
|
||||
// known, read as "not an old card" so a failed query keeps the cuBLAS BF16 call.
|
||||
int current_cc() {
|
||||
static std::atomic<int> cc[64] = {};
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; }
|
||||
int v = cc[dev].load(std::memory_order_relaxed);
|
||||
if (v == 0) {
|
||||
int major = 0, minor = 0;
|
||||
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
return 0;
|
||||
}
|
||||
v = 10 * major + minor;
|
||||
cc[dev].store(v, std::memory_order_relaxed);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
// 0: cuBLAS's BF16 GEMM, 1: through FP16 (tensor cores), 2: through FP32 (Pascal)
|
||||
int bf16_path() {
|
||||
static const int forced = [] {
|
||||
const char* v = std::getenv("STRATA_BF16_TC");
|
||||
return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1;
|
||||
}();
|
||||
const int cc = current_cc();
|
||||
if (forced == 2 && cc > 0) return 1; // a test mode: the FP16 path on any card (gemm_bf16_parity on sm_80+)
|
||||
if (cc <= 0 || cc >= 80) return 0;
|
||||
if (cc < 70) return 2;
|
||||
if (forced >= 0) return forced != 0 ? 1 : 0;
|
||||
return cc < 75 ? 1 : 0;
|
||||
}
|
||||
bool grow(uint16_t*& p, int64_t& have, int64_t want) { // `have`, `want`: 2-byte elements
|
||||
if (have >= want) return true;
|
||||
if (p) cudaFree(p);
|
||||
p = nullptr;
|
||||
have = 0;
|
||||
if (cudaMalloc((void**) &p, (size_t) want * 2) != cudaSuccess) { cudaGetLastError(); p = nullptr; return false; }
|
||||
have = want;
|
||||
return true;
|
||||
}
|
||||
constexpr int64_t kXSliceElems = 16ll << 20; // 32 MiB of FP16 activations per slice (64 MiB as fp32)
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
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) {
|
||||
if (T <= 0 || N <= 0) return;
|
||||
@@ -383,6 +472,41 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64
|
||||
STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
#if !defined(__HIPCC__)
|
||||
if (const int path = K > 0 ? bf16_path() : 0; path == 1 && N > 1 && beta == 0.0f) {
|
||||
// a single output row stays cuBLAS's GEMV, faster than the conversions; beta = 1: see above
|
||||
const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
|
||||
if (grow(tc_w_, tc_w_elems_, N * K) && grow(tc_x_, tc_x_elems_, x_rows * K)) {
|
||||
bf16_to_f16(W, tc_w_, N * 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, n, N, K, ldy, beta);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
#if defined(STRATA_EXPERIMENTAL_SM60)
|
||||
else if (path == 2) {
|
||||
// Pascal: fp32 copies (2 elements of the 2-byte buffers each). Every tile is a disjoint block of Y, so each
|
||||
// gets the caller's beta.
|
||||
const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
|
||||
if (grow(tc_w_, tc_w_elems_, 2 * N * K) && grow(tc_x_, tc_x_elems_, 2 * x_rows * K)) {
|
||||
float* const wf = reinterpret_cast<float*>(tc_w_);
|
||||
float* const xf = reinterpret_cast<float*>(tc_x_);
|
||||
bf16_to_f32(W, wf, N * 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_f32(X + t0 * K, xf, n * K, (cudaStream_t) stream_);
|
||||
ck(cublasSgemm((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &alpha,
|
||||
wf, (int) K, xf, (int) K, &beta, Y + t0 * ldy, (int) ldy),
|
||||
"cublasSgemm (bf16 on Pascal)");
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#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,
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// src/prefill/gemm_bf16_parity.cu - Gemm::bf16 against cuBLAS's own BF16 product (GPU, synthetic, no model).
|
||||
//
|
||||
// Below sm_80 (no BF16 tensor cores) Gemm::bf16 converts the weight and the activations to FP16 and runs the FP16
|
||||
// tensor-core GEMM (Volta by default, Turing with STRATA_BF16_TC=1) or widens them to fp32 (Pascal); everywhere else
|
||||
// it is the cuBLAS BF16 call itself. (On Pascal the cuBLAS BF16 reference itself may be refused: the test then fails
|
||||
// at the reference, which says so.) This
|
||||
// checks the result against cublasGemmEx on the same BF16 inputs, within fp32-accumulation rounding, over the prompt
|
||||
// path's shapes: the hyper-connection down / up projections, the router and indexer rows, the PLE value matrix, a T
|
||||
// large enough to slice the activations, beta = 1 accumulation (the bf16x2 low parts) and an output row stride wider
|
||||
// than N. --bench adds the time of each against the cuBLAS BF16 product.
|
||||
#include "strata/prefill/gemm.hpp"
|
||||
|
||||
#include <cublas_v2.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
uint16_t to_bf16(float f) { // round to nearest even
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &f, 4);
|
||||
u += 0x7fffu + ((u >> 16) & 1u);
|
||||
return (uint16_t) (u >> 16);
|
||||
}
|
||||
|
||||
bool ok_or(cudaError_t e, const char* what) {
|
||||
if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e));
|
||||
return e == cudaSuccess;
|
||||
}
|
||||
|
||||
struct Shape {
|
||||
int64_t T, N, K, ldy;
|
||||
const char* what;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
|
||||
int dev = 0, maj = 0, min = 0;
|
||||
cudaGetDevice(&dev);
|
||||
cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&min, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
std::printf("gemm_bf16_parity: compute capability %d.%d\n", maj, min);
|
||||
|
||||
cudaStream_t st = nullptr;
|
||||
if (!ok_or(cudaStreamCreate(&st), "stream")) return 1;
|
||||
strata::prefill::Gemm gemm;
|
||||
std::string err;
|
||||
if (!gemm.init(st, 0, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; }
|
||||
cublasHandle_t h = nullptr;
|
||||
if (cublasCreate(&h) != CUBLAS_STATUS_SUCCESS) { std::printf("FAIL: cublasCreate\n"); return 1; }
|
||||
cublasSetStream(h, st);
|
||||
|
||||
const Shape shapes[] = {
|
||||
{4096, 320, 10240, 0, "hc down (activations sliced)"},
|
||||
{4096, 10240, 320, 0, "hc up"},
|
||||
{777, 2560, 2560, 0, "PLE value"},
|
||||
{512, 512, 2560, 0, "router / indexer q"},
|
||||
{300, 4, 10240, 0, "hc inject"},
|
||||
{2048, 1, 2560, 0, "single row"},
|
||||
{333, 128, 2560, 136, "row stride wider than N"},
|
||||
};
|
||||
std::mt19937 rng(1234);
|
||||
std::normal_distribution<float> nd(0.0f, 1.0f);
|
||||
int failures = 0;
|
||||
for (const Shape& s : shapes) {
|
||||
const int64_t ldy = s.ldy > 0 ? s.ldy : s.N;
|
||||
std::vector<uint16_t> x((size_t) (s.T * s.K)), xlo(x.size()), w((size_t) (s.N * s.K));
|
||||
for (size_t i = 0; i < x.size(); ++i) {
|
||||
const float v = 3.0f * nd(rng); // activations: normalized, a few units
|
||||
x[i] = to_bf16(v);
|
||||
xlo[i] = to_bf16(1e-3f * nd(rng)); // a bf16x2 low part
|
||||
}
|
||||
for (auto& v : w) v = to_bf16(0.02f * nd(rng));
|
||||
uint16_t *dx = nullptr, *dxlo = nullptr, *dw = nullptr;
|
||||
float *dy = nullptr, *dr = nullptr;
|
||||
const size_t ybytes = (size_t) (s.T * ldy) * 4;
|
||||
bool ok = ok_or(cudaMalloc((void**) &dx, x.size() * 2), "x") && ok_or(cudaMalloc((void**) &dxlo, x.size() * 2), "xlo") &&
|
||||
ok_or(cudaMalloc((void**) &dw, w.size() * 2), "w") && ok_or(cudaMalloc((void**) &dy, ybytes), "y") &&
|
||||
ok_or(cudaMalloc((void**) &dr, ybytes), "ref");
|
||||
if (!ok) return 1;
|
||||
cudaMemcpy(dx, x.data(), x.size() * 2, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dxlo, xlo.data(), xlo.size() * 2, cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(dw, w.data(), w.size() * 2, cudaMemcpyHostToDevice);
|
||||
cudaMemset(dy, 0, ybytes);
|
||||
cudaMemset(dr, 0, ybytes);
|
||||
|
||||
// the product under test: X . W^T, then the low part added with beta = 1
|
||||
gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy);
|
||||
gemm.bf16(dxlo, dw, dy, s.T, s.N, s.K, ldy, 1.0f);
|
||||
// the reference: cuBLAS on the BF16 inputs, the same two calls
|
||||
const float one = 1.0f, zero = 0.0f;
|
||||
auto ref = [&](const uint16_t* X, float beta) {
|
||||
return cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, (int) s.N, (int) s.T, (int) s.K, &one, dw, CUDA_R_16BF,
|
||||
(int) s.K, X, CUDA_R_16BF, (int) s.K, &beta, dr, CUDA_R_32F, (int) ldy,
|
||||
CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT);
|
||||
};
|
||||
if (ref(dx, zero) != CUBLAS_STATUS_SUCCESS || ref(dxlo, one) != CUBLAS_STATUS_SUCCESS) {
|
||||
std::printf("FAIL: reference cublasGemmEx\n");
|
||||
return 1;
|
||||
}
|
||||
if (!ok_or(cudaStreamSynchronize(st), "sync")) return 1;
|
||||
std::vector<float> y((size_t) (s.T * ldy)), r(y.size());
|
||||
cudaMemcpy(y.data(), dy, ybytes, cudaMemcpyDeviceToHost);
|
||||
cudaMemcpy(r.data(), dr, ybytes, cudaMemcpyDeviceToHost);
|
||||
double worst = 0.0, mag = 1e-30;
|
||||
int bad = 0;
|
||||
for (int64_t t = 0; t < s.T; ++t)
|
||||
for (int64_t c = 0; c < s.N; ++c) {
|
||||
const float a = y[(size_t) (t * ldy + c)], b = r[(size_t) (t * ldy + c)];
|
||||
if (!std::isfinite(a)) ++bad;
|
||||
worst = std::max(worst, (double) std::fabs(a - b));
|
||||
mag = std::max(mag, (double) std::fabs(b));
|
||||
}
|
||||
// the untouched columns of a wider row stride stay as they were
|
||||
for (int64_t t = 0; t < s.T && ldy > s.N; ++t)
|
||||
for (int64_t c = s.N; c < ldy; ++c)
|
||||
if (y[(size_t) (t * ldy + c)] != 0.0f) ++bad;
|
||||
const bool pass = bad == 0 && worst <= 1e-4 * mag;
|
||||
if (!pass) ++failures;
|
||||
std::printf(" %-32s T %5lld N %5lld K %5lld ldy %5lld: worst |diff| %.3e of max |ref| %.3e (rel %.2e) %s\n",
|
||||
s.what, (long long) s.T, (long long) s.N, (long long) s.K, (long long) ldy, worst, mag, worst / mag,
|
||||
pass ? "pass" : "FAIL");
|
||||
|
||||
if (bench) {
|
||||
auto time = [&](auto&& f) {
|
||||
for (int i = 0; i < 3; ++i) f();
|
||||
cudaStreamSynchronize(st);
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
for (int i = 0; i < 20; ++i) f();
|
||||
cudaStreamSynchronize(st);
|
||||
return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / 20;
|
||||
};
|
||||
const double us_gemm = time([&] { gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy); });
|
||||
const double us_ref = time([&] { ref(dx, zero); });
|
||||
std::printf(" bench: Gemm::bf16 %9.1f us cuBLAS BF16 %9.1f us (%.2fx)\n", us_gemm, us_ref,
|
||||
us_ref / us_gemm);
|
||||
}
|
||||
cudaFree(dx); cudaFree(dxlo); cudaFree(dw); cudaFree(dy); cudaFree(dr);
|
||||
}
|
||||
cublasDestroy(h);
|
||||
cudaStreamDestroy(st);
|
||||
std::printf("gemm_bf16_parity: %d failures\n", failures);
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -364,6 +364,11 @@ const DevInfo& dev_info() {
|
||||
DevInfo& d = g_dev[dev & 31];
|
||||
if (d.done) return d;
|
||||
d.done = true;
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and
|
||||
// empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)
|
||||
return d;
|
||||
#else
|
||||
int major = 0, minor = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
|
||||
@@ -385,6 +390,7 @@ const DevInfo& dev_info() {
|
||||
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_kernel<false>, THREADS, smem_bytes(false));
|
||||
if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0; // does not fit this card: the MMQ path
|
||||
cudaGetLastError();
|
||||
#endif
|
||||
return d;
|
||||
}
|
||||
|
||||
|
||||
@@ -516,6 +516,7 @@ struct DevInfo {
|
||||
std::mutex g_mu;
|
||||
DevInfo g_dev[32];
|
||||
|
||||
#if !defined(STRATA_HIP_GFX906)
|
||||
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;
|
||||
@@ -530,6 +531,7 @@ template <int T, bool GU, int WW> bool setup_ww(int& occ) {
|
||||
return true;
|
||||
}
|
||||
template <int T, bool GU> bool setup_one(int& occ) { return setup_ww<T, GU, 4>(occ) && setup_ww<T, GU, 2>(occ); }
|
||||
#endif
|
||||
|
||||
const DevInfo& dev_info() {
|
||||
int dev = 0;
|
||||
@@ -538,6 +540,11 @@ const DevInfo& dev_info() {
|
||||
DevInfo& d = g_dev[dev & 31];
|
||||
if (d.done) return d;
|
||||
d.done = true;
|
||||
#if defined(STRATA_HIP_GFX906)
|
||||
// gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and
|
||||
// empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)
|
||||
return d;
|
||||
#else
|
||||
int major = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
|
||||
cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
|
||||
@@ -548,6 +555,7 @@ const DevInfo& dev_info() {
|
||||
setup_one<T_Q2_0, false>(occ) && setup_one<T_IQ4_NL, false>(occ);
|
||||
d.occ = d.ok ? occ : 1;
|
||||
cudaGetLastError();
|
||||
#endif
|
||||
return d;
|
||||
}
|
||||
|
||||
|
||||
@@ -2985,6 +2985,7 @@ int main(int argc, char** argv) {
|
||||
std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, name,
|
||||
strata::cc_major_of(p.major), strata::cc_minor_of(p.minor),
|
||||
strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : "");
|
||||
#if !defined(STRATA_HIP_GFX906) // a CUDA toolkit mismatch; the gfx906 HIP build has no CUDART_VERSION
|
||||
{ // #542: a build whose libcudart is older than its headers (a CUDA 13 kit with a dangling libcudart.so that
|
||||
// CMake resolved to the system's CUDA 12 one) reads cudaDeviceProp shifted - silently, and slowly
|
||||
int rt = 0;
|
||||
@@ -2995,6 +2996,7 @@ int main(int argc, char** argv) {
|
||||
"toolkit>, with its libcudart.so present) (#542)\n",
|
||||
CUDART_VERSION / 1000, CUDART_VERSION % 1000 / 10, rt / 1000, rt % 1000 / 10);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
const std::string e = strata::core::device_code_error();
|
||||
if (!e.empty()) {
|
||||
|
||||
Reference in new issue
Block a user