mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-06 16:29:04 +00:00
perf(inkling2/cuda): a GGUF's Q8_0 dense matrices stay Q8_0 and run on the int8 tensor cores, one exact GEMM for every batch size
The Unsloth UD-Q4_K_XL file stores the attention matrices (q, k, v, gate, output, rel) and the embedding as Q8_0 (int8 plus an fp16 scale per 32 weights). The loader expanded all of them to BF16: 2 bytes per weight, rounded (int8 x fp16 scale does not fit BF16), about twice the bytes read per step, and weights that were not the file's. - Loader (CUDA, one GPU with compute capability 8.0 or newer, no layer split; STRATA_INK_Q8_0_DENSE=0 goes back to BF16): the attention matrices become format 105, packed on the host (ink_q8f_pack.h) in the order the int8 mma reads: per 16-row tile and 32-wide block one 16-byte A fragment per lane, then the block scales. The embedding becomes format 104 (as stored, row by row) and its kernel decodes a row exactly. The unembedding and the sink projection stay BF16; other backends and the CPU backend never set the switch. - One GEMM (k_ink_gemm_q8f) for decode (1..64 slots) and prefill chunks: the activations are quantized per token and 32-wide block like Q8_1 (k_ink_quant_x_q8f), every output is the sum over the K/32 blocks, in block order, of the exact int32 block dot times (weight scale x activation scale) in fp32 FMA. Nothing depends on M or on the other tokens, so a token gets the same bits whether it is read in a prefill chunk, decoded alone or decoded in a batch. The q/r/gate/k/v matrices go in one launch with one activation quantization, at any M; short matrices (the output projection) split the tokens over more blocks to keep the card busy. - Diagnostics: STRATA_INK_PROF=1 prints the per-phase decode time every 100 steps (events only, no sync per phase, eager) and the MoE sub-phases (router, bin, gate/up, down); INK_DUMP_CHUNK=n makes --dump-ref feed n tokens at a time. RTX A6000, UD-Q4_K_XL, all resident, same binary, alternating arms, 3 rounds (spread under 1%), fp8 KV, --draft off, CUDA graph decode: decode 47 / 4,096 / 63,981 token prompts: 76.2 / 71.7 / 52.3 -> 83.7 / 78.2 / 55.8 tok/s (+10% / +9% / +7%). prefill: 263 / 919 / 816 -> 269 / 892 / 796 tok/s (+2% / -3% / -2%). Eager step time by number of slots (bench, tok/s): M=1 59.9 -> 64.0, M=8 216 -> 228, M=32 222 -> 225, M=64 314 -> 319. Load line trunk=: 3.29 GB -> 2.25 GB. The answers change on purpose (the BF16 rounding of the weights is gone); greedy tokens repeat bit-identically in every round, and the 5-run logits fingerprint gives one hash for prefill and one for single-token decode. Tests: engine/tests/cuda/ink_q8f_gemm_test.cu is bit-exact against a host emulation of the same arithmetic and gives identical values at M = 70, 64, 33, 9, 8, 7, 1 (compute-sanitizer memcheck 0 errors, racecheck 0 hazards); the engine under compute-sanitizer memcheck: 0 errors. Against strata-ik2 as the oracle on UnbiasedStrata's ledger / museum cases the mean KL stays about 0.01 in prefill, decode and 7-token chunks, as with BF16 (the oracle is llama.cpp-style arithmetic, not an fp32 reference).
This commit is contained in:
1 parent
617aa3f607
commit
c60259fa6a
10 files changed
+484
-23
No files matched your search
@@ -211,6 +211,8 @@ enum InkFmt : int {
|
||||
FMT_F32 = 101,
|
||||
FMT_BF16 = 102,
|
||||
FMT_F16 = 103,
|
||||
FMT_Q8_0 = 104, // GGUF Q8_0 table as stored, row by row: [N][K/32] fp16 scales, then [N][K] int8 (the embedding; CUDA backend only)
|
||||
FMT_Q8_0F = 105, // GGUF Q8_0 dense matrix in mma fragment order for k_ink_gemm_q8f (CUDA, sm_80+): see the loader
|
||||
};
|
||||
|
||||
__host__ __device__ constexpr int ink_sb_bytes(int fmt) {
|
||||
|
||||
@@ -278,6 +278,14 @@ public:
|
||||
for (;;) {
|
||||
runner_ = std::make_unique<strata::ink::InkCudaRunner>(model_);
|
||||
runner_->use_cuda_graph = vf_graph_ok && !model_.ep2_active && !model_.ls_active;
|
||||
if (const char* pe = std::getenv("STRATA_INK_PROF"); pe && pe[0] == '1') { // per-phase decode times, eager (no graph)
|
||||
runner_->prof_enabled = true;
|
||||
runner_->use_cuda_graph = false;
|
||||
strata::ink::g_ink_moe_hook_ctx = runner_.get();
|
||||
strata::ink::g_ink_moe_hook = [](int tag, void* ctx) {
|
||||
static_cast<strata::ink::InkCudaRunner*>(ctx)->prof_mark_end(8 + tag);
|
||||
};
|
||||
}
|
||||
try {
|
||||
runner_->init(max_slots_, std::max(256, opts.max_ctx), chunk_try, cuda_kvd, kv_offload_mode);
|
||||
break;
|
||||
@@ -981,4 +989,13 @@ std::unique_ptr<InkBackend> make_cuda_backend() {
|
||||
return std::make_unique<InkCudaBackend>();
|
||||
}
|
||||
|
||||
bool ink_cuda_q8f_supported(int gpu_index) {
|
||||
int major = 0;
|
||||
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, gpu_index < 0 ? 0 : gpu_index) != cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
return false;
|
||||
}
|
||||
return major >= 8;
|
||||
}
|
||||
|
||||
} // namespace ink2
|
||||
@@ -53,6 +53,16 @@ __global__ void __launch_bounds__(256) k_ink_embed_norm(
|
||||
dst[d] = v;
|
||||
ss += v * v;
|
||||
}
|
||||
} else if (emb_fmt == FMT_Q8_0) {
|
||||
// Q8_0 as the GGUF stores it (FMT_Q8_0 in ink_cuda.cuh): [rows][D/32] fp16 scales, then [rows][D] int8; the value is exact in fp32
|
||||
const int nblk = D >> 5;
|
||||
const __half* scl = reinterpret_cast<const __half*>(emb_w) + (size_t)id * nblk;
|
||||
const int8_t* qrow = reinterpret_cast<const int8_t*>(emb_w + (size_t)kInkVocabPad * nblk * 2) + (size_t)id * D;
|
||||
for (int d = tid; d < D; d += 256) {
|
||||
float v = (float)qrow[d] * __half2float(scl[d >> 5]);
|
||||
dst[d] = v;
|
||||
ss += v * v;
|
||||
}
|
||||
} else if (emb_fmt == FMT_Q8ROW) {
|
||||
// Q8_ROW layout: [rows] float32 scales followed by [rows, D] int8
|
||||
const float sc = reinterpret_cast<const float*>(emb_w)[id];
|
||||
@@ -1430,6 +1440,96 @@ __global__ void __launch_bounds__(128) k_ink_gemv_multi_bf16(
|
||||
}
|
||||
}
|
||||
|
||||
// GGUF Q8_0 dense matrices on the int8 tensor cores, one kernel for every batch size (decode 1..64 slots and prefill chunks).
|
||||
//
|
||||
// Weights (format FMT_Q8_0F), a matrix [N rows][K cols] with N % 16 == 0 and K % 32 == 0, nKB = K/32:
|
||||
// qpack [N/16][nKB][32 lanes][16 B] int8: for lane (g = lane>>2, t = lane&3) the four 32-bit A registers of mma.m16n8k32 (s8):
|
||||
// a0 = row g, k t*4..t*4+3 a1 = row g+8, k t*4..t*4+3
|
||||
// a2 = row g, k 16+t*4..+3 a3 = row g+8, k 16+t*4..+3 (rows of the 16-row tile, k within the 32 block)
|
||||
// scales [N/16][nKB][16] fp16: the Q8_0 block scale of each row of the tile.
|
||||
// Activations are quantized per token and 32-wide block the way Q8_1 does (scale = amax/127, q = round(x/scale)) into the B-fragment order:
|
||||
// xq [nMT][nKB][32 lanes][8 B] (b0 = token g, k t*4..+3; b1 = token g, k 16+t*4..+3), xs [nMT][nKB][8] fp32, nMT = ceil(M/8).
|
||||
// Each output is sum over the K/32 blocks, in block order, of (int32 dot of the block) * (weight scale * activation scale) in fp32 FMA:
|
||||
// the int32 sums are exact, the order is fixed, and nothing depends on M or on the other tokens, so a token gives the same bits
|
||||
// whether it is read in a prefill chunk or decoded alone or in a batch.
|
||||
__global__ void __launch_bounds__(256) k_ink_quant_x_q8f(const float* __restrict__ X, int8_t* __restrict__ xq, float* __restrict__ xs,
|
||||
int M, int K, int nMT) {
|
||||
const int warp = (int)((blockIdx.x * 256u + threadIdx.x) >> 5); // one warp per (padded token, 32-wide block)
|
||||
const int lane = threadIdx.x & 31;
|
||||
const int nKB = K >> 5;
|
||||
if (warp >= nMT * 8 * nKB) return;
|
||||
const int tok = warp / nKB, kb = warp % nKB;
|
||||
const float v = (tok < M) ? X[(size_t)tok * K + (size_t)kb * 32 + lane] : 0.0f;
|
||||
const float am = warp_max(fabsf(v));
|
||||
const float d = am * (1.0f / 127.0f);
|
||||
const float inv = d > 0.0f ? (127.0f / am) : 0.0f;
|
||||
const int q = max(-127, min(127, __float2int_rn(v * inv)));
|
||||
const int mt = tok >> 3, g = tok & 7;
|
||||
const int half = lane >> 4, kk = lane & 15, t = kk >> 2, j = kk & 3;
|
||||
xq[((size_t)(mt * nKB + kb) * 32 + g * 4 + t) * 8 + half * 4 + j] = (int8_t)q;
|
||||
if (lane == 0) xs[(size_t)(mt * nKB + kb) * 8 + g] = d;
|
||||
}
|
||||
|
||||
// One warp = 16 weight rows x up to MTW token tiles (8 tokens each); 2 warps per CTA; the row tiles of the (up to 5) matrices of `mp`
|
||||
// are concatenated like in the other multi-projection kernels. gridDim.y walks the token tiles in groups of MTW (prefill chunks).
|
||||
template <int MTW>
|
||||
__global__ void __launch_bounds__(64) k_ink_gemm_q8f(InkMultiProj mp, const int8_t* __restrict__ xq, const float* __restrict__ xs,
|
||||
int M, int K, int nMT) {
|
||||
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 800)
|
||||
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
|
||||
const int g = lane >> 2, t = lane & 3;
|
||||
const int grow0 = (blockIdx.x * 2 + warp) * 16;
|
||||
const uint8_t* Wp = nullptr;
|
||||
float* Yp = nullptr;
|
||||
int Np = 0, lrow = 0;
|
||||
if (!ink_resolve_multi_proj(mp, grow0, Wp, Yp, Np, lrow)) return;
|
||||
const int nKB = K >> 5;
|
||||
const int rt = lrow >> 4;
|
||||
const uint4* wq = reinterpret_cast<const uint4*>(Wp) + (size_t)rt * nKB * 32 + lane;
|
||||
const __half* ws = reinterpret_cast<const __half*>(Wp + (size_t)Np * K) + (size_t)rt * nKB * 16;
|
||||
const int mt0 = blockIdx.y * MTW;
|
||||
const int nmt = min(MTW, nMT - mt0);
|
||||
float acc[MTW][4] = {};
|
||||
constexpr int UNR = (MTW == 1) ? 8 : ((MTW == 2) ? 4 : 2); // more weight tiles in flight when there are few token tiles
|
||||
#pragma unroll UNR
|
||||
for (int kb = 0; kb < nKB; ++kb) {
|
||||
const uint4 a = wq[(size_t)kb * 32];
|
||||
const float s0 = __half2float(ws[kb * 16 + g]);
|
||||
const float s1 = __half2float(ws[kb * 16 + g + 8]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MTW; ++i) {
|
||||
if (i < nmt) {
|
||||
const size_t tb = (size_t)(mt0 + i) * nKB + kb;
|
||||
const uint2 b = *reinterpret_cast<const uint2*>(xq + (tb * 32 + lane) * 8);
|
||||
const float2 sx = *reinterpret_cast<const float2*>(xs + tb * 8 + 2 * t);
|
||||
int32_t c[4] = {0, 0, 0, 0};
|
||||
mma_m16n8k32_s8(c, a.x, a.y, a.z, a.w, b.x, b.y);
|
||||
acc[i][0] = fmaf((float)c[0], s0 * sx.x, acc[i][0]);
|
||||
acc[i][1] = fmaf((float)c[1], s0 * sx.y, acc[i][1]);
|
||||
acc[i][2] = fmaf((float)c[2], s1 * sx.x, acc[i][2]);
|
||||
acc[i][3] = fmaf((float)c[3], s1 * sx.y, acc[i][3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MTW; ++i) {
|
||||
if (i < nmt) {
|
||||
const int tok0 = (mt0 + i) * 8 + 2 * t;
|
||||
if (tok0 < M) {
|
||||
Yp[(size_t)tok0 * Np + lrow + g] = acc[i][0];
|
||||
Yp[(size_t)tok0 * Np + lrow + g + 8] = acc[i][2];
|
||||
}
|
||||
if (tok0 + 1 < M) {
|
||||
Yp[(size_t)(tok0 + 1) * Np + lrow + g] = acc[i][1];
|
||||
Yp[(size_t)(tok0 + 1) * Np + lrow + g + 8] = acc[i][3];
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
(void)mp; (void)xq; (void)xs; (void)M; (void)K; (void)nMT;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Zero-Extra-Launch 16-Lane M=1 Q8_ROW Multi-Projection GEMV (8 rows/CTA = 288 CTAs on wo_ud, inline L1 quantize -> eliminates 192 launches!)
|
||||
__global__ void __launch_bounds__(128) k_ink_gemv_multi_q8row_m1(
|
||||
InkMultiProj mp,
|
||||
|
||||
@@ -3212,6 +3212,12 @@ inline void launch_ink_moe_dn_sk_mask(
|
||||
}
|
||||
|
||||
// Standalone Top-8 / 128 exact sigmoid router (shared by single-GPU, hybrid, and Dual-GPU EP!)
|
||||
// STRATA_INK_PROF=1: the runner sets this to record an event at the end of each MoE sub-phase (router, bin, gate/up, down).
|
||||
// Tags 0..3 for SF4 / MX8 / S_K layers, 4..7 for layers with GGUF_RAW experts. Null (and free) otherwise.
|
||||
inline void (*g_ink_moe_hook)(int tag, void* ctx) = nullptr;
|
||||
inline void* g_ink_moe_hook_ctx = nullptr;
|
||||
inline void ink_moe_mark(int tag) { if (g_ink_moe_hook) g_ink_moe_hook(tag, g_ink_moe_hook_ctx); }
|
||||
|
||||
inline void launch_ink_moe_router(
|
||||
cudaStream_t st,
|
||||
cublasHandle_t cublas,
|
||||
@@ -3237,6 +3243,7 @@ inline void launch_ink_moe_router(
|
||||
CUBLAS_GEMM_DEFAULT_TENSOR_OP));
|
||||
}
|
||||
k_ink_router_select_topk8<<<M, 32, 0, st>>>(ws.r_logits, gate_b, ws.topk_idx, ws.topk_w, route_scale, M);
|
||||
ink_moe_mark(0);
|
||||
}
|
||||
|
||||
// Shared GPU expert execution helper (bins tier<=1 experts in `experts` and writes weighted outputs to ws.y_pair)
|
||||
@@ -3258,6 +3265,7 @@ inline void launch_ink_moe_dispatch_only(
|
||||
const int tile_rows = use_wmma_tc ? ((M <= 128) ? 16 : 64)
|
||||
: ((M <= 128 || use_fp16_tc) ? 16 : 64);
|
||||
k_ink_moe_bin<<<1, 128, 0, st>>>(experts, ws.topk_idx, M, tile_rows, ws.tb);
|
||||
ink_moe_mark(1);
|
||||
|
||||
const int P = M * kInkTopK;
|
||||
const int max_act = std::min(P, kInkExperts);
|
||||
@@ -3299,7 +3307,9 @@ inline void launch_ink_moe_dispatch_only(
|
||||
if (info.has_sf4) {
|
||||
if (!quant_x_done) sm120::quantize_act_fp4(x_f32, M, kInkHidden, ws.xa_fp4, st);
|
||||
sm120::moe_sf4_gu_tc(sec4_base, experts, ws.tb, ws.xa_fp4, ws.ha_fp4, mt, tile_rows, st);
|
||||
ink_moe_mark(2);
|
||||
sm120::moe_sf4_dn_tc(sec4_base, experts, ws.tb, ws.ha_fp4, ws.topk_w, ws.y_pair, mt, tile_rows, st);
|
||||
ink_moe_mark(3);
|
||||
}
|
||||
if (info.has_mx8) {
|
||||
if (!quant_x_done) sm120::quantize_act_mx8(x_f32, M, kInkHidden, ws.xq_mx8, ws.xsc_mx8, st);
|
||||
@@ -3315,10 +3325,14 @@ inline void launch_ink_moe_dispatch_only(
|
||||
dim3 g16(kInkInter / 16, max_act);
|
||||
if (M == 1) {
|
||||
k_ink_moe_gu_sf4_mx8<1><<<g16, 128, 0, st>>>(sec4_base, experts, ws.tb, x_f32, ws.h_f32);
|
||||
ink_moe_mark(2);
|
||||
k_ink_moe_dn_sf4_mx8<1><<<g16, 128, 0, st>>>(sec4_base, experts, ws.tb, ws.h_f32, ws.topk_w, ws.y_pair);
|
||||
ink_moe_mark(3);
|
||||
} else {
|
||||
k_ink_moe_gu_sf4_mx8<4><<<g16, 128, 0, st>>>(sec4_base, experts, ws.tb, x_f32, ws.h_f32);
|
||||
ink_moe_mark(2);
|
||||
k_ink_moe_dn_sf4_mx8<4><<<g16, 128, 0, st>>>(sec4_base, experts, ws.tb, ws.h_f32, ws.topk_w, ws.y_pair);
|
||||
ink_moe_mark(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3367,6 +3381,7 @@ inline void launch_ink_moe_dispatch_only(
|
||||
} else {
|
||||
k_ink_moe_gu_gguf_dp4a<16><<<g_gu, 128, 0, st>>>(sec4_base, experts, ws.tb, ws.xq_g32, x_f32, ws.h_f32);
|
||||
}
|
||||
ink_moe_mark(4);
|
||||
const int nblk_h = P * (kInkInter / 32);
|
||||
k_ink_quant_q8_1_g32<<<(nblk_h + 7) / 8, 256, 0, st>>>(ws.h_f32, ws.hq_g32, P, kInkInter);
|
||||
if (M == 1) {
|
||||
@@ -3376,6 +3391,7 @@ inline void launch_ink_moe_dispatch_only(
|
||||
} else {
|
||||
k_ink_moe_dn_gguf_dp4a<16><<<g_dn, 128, 0, st>>>(sec4_base, experts, ws.tb, ws.hq_g32, ws.h_f32, ws.topk_w, ws.y_pair);
|
||||
}
|
||||
ink_moe_mark(5);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1681,6 +1681,8 @@ struct InkCudaRunner {
|
||||
int32_t* d_acc_path = nullptr;
|
||||
__nv_bfloat16 *d_x_bf16 = nullptr;
|
||||
__nv_bfloat16 *d_w_scratch = nullptr; // [max_N, max_K] BF16 scratch for Q8_ROW / S_K cuBLAS prefill
|
||||
int8_t* d_xq8 = nullptr; // activations of a Q8_0 dense GEMM, quantized into the mma B-fragment order (k_ink_quant_x_q8f)
|
||||
float* d_xs8 = nullptr; // and their scales, one per (token, 32-wide block)
|
||||
|
||||
// Logits & screened argmax buffers
|
||||
float *d_logits = nullptr; // [logits_cap, 200058] (allocated lazily if full logits needed)
|
||||
@@ -1764,24 +1766,54 @@ struct InkCudaRunner {
|
||||
|
||||
// Optional per-stage profiler (active only when prof_enabled=true and graph disabled)
|
||||
bool prof_enabled = false;
|
||||
double prof_ms[8] = {}; // 0=res/ctrl/norm, 1=dense_qkv, 2=sconv_clip_kv, 3=attn, 4=dense_wo, 5=moe, 6=other, 7=unembed
|
||||
long prof_steps = 0;
|
||||
double prof_ms[16] = {}; // 0=res/ctrl/norm, 1=dense_qkv, 2=sconv_clip_kv, 3=attn, 4=dense_wo, 5=moe, 6=other, 7=unembed
|
||||
cudaEvent_t ev_p0 = nullptr, ev_p1 = nullptr;
|
||||
void prof_mark_start() { if (prof_enabled) INK_CK(cudaEventRecord(ev_p0, st)); }
|
||||
// The marks only record events (no sync per phase), so the GPU stays fed and the phase times are the stream's own;
|
||||
// prof_flush() adds them up once the step is done.
|
||||
struct ProfPair { cudaEvent_t a, b; int idx; };
|
||||
std::vector<cudaEvent_t> prof_pool;
|
||||
std::vector<ProfPair> prof_pairs;
|
||||
size_t prof_used = 0;
|
||||
cudaEvent_t prof_prev = nullptr;
|
||||
cudaEvent_t prof_next_ev() {
|
||||
if (prof_used == prof_pool.size()) { cudaEvent_t e; INK_CK(cudaEventCreate(&e)); prof_pool.push_back(e); }
|
||||
return prof_pool[prof_used++];
|
||||
}
|
||||
void prof_mark_start() {
|
||||
if (!prof_enabled) return;
|
||||
cudaEvent_t e = prof_next_ev();
|
||||
INK_CK(cudaEventRecord(e, st));
|
||||
prof_prev = e;
|
||||
}
|
||||
void prof_mark_end(int idx) {
|
||||
if (!prof_enabled) return;
|
||||
INK_CK(cudaEventRecord(ev_p1, st));
|
||||
INK_CK(cudaEventSynchronize(ev_p1));
|
||||
float ms = 0.0f;
|
||||
INK_CK(cudaEventElapsedTime(&ms, ev_p0, ev_p1));
|
||||
prof_ms[idx] += ms;
|
||||
cudaEvent_t e = prof_next_ev();
|
||||
INK_CK(cudaEventRecord(e, st));
|
||||
if (prof_prev) prof_pairs.push_back({prof_prev, e, idx});
|
||||
prof_prev = e;
|
||||
}
|
||||
void prof_flush() {
|
||||
if (!prof_enabled || prof_pairs.empty()) { prof_used = 0; return; }
|
||||
INK_CK(cudaStreamSynchronize(st));
|
||||
for (const auto& p : prof_pairs) {
|
||||
float ms = 0.0f;
|
||||
INK_CK(cudaEventElapsedTime(&ms, p.a, p.b));
|
||||
prof_ms[p.idx] += ms;
|
||||
}
|
||||
prof_pairs.clear();
|
||||
prof_used = 0;
|
||||
prof_prev = nullptr;
|
||||
}
|
||||
void prof_reset() { for (double& x : prof_ms) x = 0.0; }
|
||||
void prof_print(const char* tag, int iters) const {
|
||||
double tot = 0; for (double x : prof_ms) tot += x;
|
||||
std::printf("[PROF %s / %d iters] total=%.2f ms/step | res_ctrl=%.2f dense_qkv=%.2f sconv_kv=%.2f attn=%.2f dense_wo=%.2f moe=%.2f unembed=%.2f\n",
|
||||
std::fprintf(stderr, "[PROF %s / %d iters] total=%.2f ms/step | res_ctrl=%.2f dense_qkv=%.2f sconv_kv=%.2f attn=%.2f dense_wo=%.2f moe=%.2f unembed=%.2f\n",
|
||||
tag, iters, tot / iters,
|
||||
prof_ms[0] / iters, prof_ms[1] / iters, prof_ms[2] / iters, prof_ms[3] / iters,
|
||||
prof_ms[4] / iters, prof_ms[5] / iters, prof_ms[7] / iters);
|
||||
std::fprintf(stderr, "[PROF moe parts / %d iters] (the moe= above is what is left after these) router+topk=%.2f bin=%.2f gu(sf4/mx8/sk)=%.2f dn(sf4/mx8/sk)=%.2f gu(gguf)=%.2f dn(gguf)=%.2f ms/step\n",
|
||||
iters, prof_ms[8] / iters, prof_ms[9] / iters, prof_ms[10] / iters, prof_ms[11] / iters, prof_ms[12] / iters, prof_ms[13] / iters);
|
||||
}
|
||||
|
||||
static size_t kv_bytes_per_visit_pos(InkKvDtype dt) noexcept {
|
||||
@@ -2116,6 +2148,11 @@ struct InkCudaRunner {
|
||||
|
||||
d_x_bf16 = dalloc<__nv_bfloat16>(MB * std::max(kInkDsparkInter, std::max(kInkQDim, kInkHidden)));
|
||||
d_w_scratch = dalloc<__nv_bfloat16>((size_t)kInkDsparkInter * kInkHidden);
|
||||
{
|
||||
const size_t mpad = (size_t)((max_batch + 7) / 8) * 8;
|
||||
d_xq8 = dalloc<int8_t>(mpad * kInkQDim);
|
||||
d_xs8 = dalloc<float>(mpad * (kInkQDim / 32));
|
||||
}
|
||||
|
||||
// Warmup cuBLAS Tensor Cores once at init (eliminates 61 ms first-call JIT tax from prompt #1!)
|
||||
{
|
||||
@@ -2641,6 +2678,7 @@ struct InkCudaRunner {
|
||||
return is_fp16 ? XC_FP16 : gemm_fmt;
|
||||
}
|
||||
if (ti.fmt == FMT_F32) return XC_NONE;
|
||||
if (ti.fmt == FMT_Q8_0F) return XC_NONE; // quantizes its own activations (k_ink_quant_x_q8f)
|
||||
if (ti.fmt == FMT_Q8ROW) {
|
||||
if (M > 16 && cur_cc == 61 && (K % 4 == 0) && (N % 4 == 0) && N_override == 0) return XC_I8;
|
||||
const size_t cap = (size_t)kInkDsparkInter * kInkHidden;
|
||||
@@ -2658,6 +2696,28 @@ struct InkCudaRunner {
|
||||
if (need != XC_NONE) x_cached = need;
|
||||
}
|
||||
|
||||
// Q8_0 dense matrices (FMT_Q8_0F): the activations are quantized once into the fragment order, then one GEMM launch for all the
|
||||
// matrices of mp (see k_ink_gemm_q8f for the layout and why the result does not depend on M).
|
||||
bool q8f_ok(int M, int K) const { return M >= 1 && M <= max_batch && K % 32 == 0 && K <= kInkQDim && d_xq8 != nullptr; }
|
||||
void gemm_q8f(const InkMultiProj& mp, const float* X, int M, int K) {
|
||||
const int nMT = (M + 7) / 8;
|
||||
const int nKB = K >> 5;
|
||||
const int total_warps = nMT * 8 * nKB;
|
||||
k_ink_quant_x_q8f<<<(total_warps + 7) / 8, 256, 0, st>>>(X, d_xq8, d_xs8, M, K, nMT);
|
||||
const int row_tiles = mp.cumN[mp.count] / 16;
|
||||
const int gx = (row_tiles + 1) / 2;
|
||||
// token tiles per warp: as many as fit, but split the tokens over more CTAs when the matrices are short of row tiles
|
||||
// (the output projection has 144) so that about 1500 warps are in flight; the result does not depend on this choice
|
||||
const int want_gy = std::max(1, (1536 + row_tiles - 1) / row_tiles);
|
||||
int mtw = 1;
|
||||
for (int c : {8, 4, 2}) { if (nMT >= c && (nMT + c - 1) / c >= std::min(want_gy, nMT)) { mtw = c; break; } }
|
||||
const dim3 grid(gx, (nMT + mtw - 1) / mtw);
|
||||
if (mtw == 8) k_ink_gemm_q8f<8><<<grid, 64, 0, st>>>(mp, d_xq8, d_xs8, M, K, nMT);
|
||||
else if (mtw == 4) k_ink_gemm_q8f<4><<<grid, 64, 0, st>>>(mp, d_xq8, d_xs8, M, K, nMT);
|
||||
else if (mtw == 2) k_ink_gemm_q8f<2><<<grid, 64, 0, st>>>(mp, d_xq8, d_xs8, M, K, nMT);
|
||||
else k_ink_gemm_q8f<1><<<grid, 64, 0, st>>>(mp, d_xq8, d_xs8, M, K, nMT);
|
||||
}
|
||||
|
||||
// ---- Dense linear projection helper: Y[M, N] = X[M, K] @ W[N, K]^T ----
|
||||
void linear_multi(const std::string* names, float* const* Ys, int count, const float* X, int M, bool exact_fp32_x = false) {
|
||||
if (count <= 0) return;
|
||||
@@ -2667,7 +2727,8 @@ struct InkCudaRunner {
|
||||
const bool cur_attn_fp16 = m.ls_active ? m.stage_trunk_attn_fp16[cur_stage] : m.trunk_attn_fp16;
|
||||
const bool is_fp16 = cur_attn_fp16 && (names[0].find(".attn.") != std::string::npos);
|
||||
const int bf16_gemv_max = is_fp16 ? 3 : ((exact_fp32_x || cur_cc < 80) ? 16 : 7);
|
||||
bool can_fuse = (count <= 5) && ((ti0.fmt == FMT_BF16 && M <= bf16_gemv_max) || (ti0.fmt == FMT_Q8ROW && M <= 16));
|
||||
bool can_fuse = (count <= 5) && ((ti0.fmt == FMT_BF16 && M <= bf16_gemv_max) || (ti0.fmt == FMT_Q8ROW && M <= 16) ||
|
||||
(ti0.fmt == FMT_Q8_0F && q8f_ok(M, K)));
|
||||
InkMultiProj mp{};
|
||||
mp.count = count;
|
||||
mp.cumN[0] = 0;
|
||||
@@ -2682,6 +2743,10 @@ struct InkCudaRunner {
|
||||
}
|
||||
if (can_fuse) {
|
||||
const int grid = (mp.cumN[count] + 7) / 8;
|
||||
if (ti0.fmt == FMT_Q8_0F) {
|
||||
gemm_q8f(mp, X, M, K);
|
||||
return;
|
||||
}
|
||||
if (ti0.fmt == FMT_BF16) {
|
||||
if (is_fp16) {
|
||||
if (M == 1) k_ink_gemv_multi_bf16<1, true><<<grid, 128, 0, st>>>(mp, X, M, K);
|
||||
@@ -2776,6 +2841,10 @@ struct InkCudaRunner {
|
||||
cur_cc >= 80 ? CUBLAS_COMPUTE_32F_FAST_TF32 : CUBLAS_COMPUTE_32F,
|
||||
CUBLAS_GEMM_DEFAULT_TENSOR_OP));
|
||||
}
|
||||
} else if (ti.fmt == FMT_Q8_0F) {
|
||||
InkMultiProj mp{};
|
||||
mp.W[0] = W; mp.Y[0] = Y; mp.N[0] = N; mp.cumN[0] = 0; mp.cumN[1] = N; mp.count = 1;
|
||||
gemm_q8f(mp, X, M, K);
|
||||
} else if (ti.fmt == FMT_Q8ROW) {
|
||||
if (M > 16 && cur_cc == 61 && (K % 4 == 0) && (N % 4 == 0) && N_override == 0) {
|
||||
int8_t* x_i8 = reinterpret_cast<int8_t*>(d_x_bf16);
|
||||
@@ -2964,7 +3033,9 @@ struct InkCudaRunner {
|
||||
// 3. Fused Q, K, V, R, Gate_Attn, Sinks projections (1 launch on SWA-no-msg at M<=16 -> 1,500+ GB/s!)
|
||||
prof_mark_end(0); prof_mark_start();
|
||||
const bool share_qkv = (in_q == in_k && in_q == in_v);
|
||||
if (M <= 16 && share_qkv) {
|
||||
// Q8_0 dense matrices: one fused launch (one activation quantization) at any batch size, prefill chunks included
|
||||
const bool q8f_dense = (m.tinfo(p + ".attn.wq_du.weight").fmt == FMT_Q8_0F);
|
||||
if ((M <= 16 || q8f_dense) && share_qkv) {
|
||||
const std::string names[5] = {
|
||||
p + ".attn.wq_du.weight", p + ".attn.wr_du.weight", p + ".attn.gate_attn.weight",
|
||||
p + ".attn.wk_dv.weight", p + ".attn.wv_dv.weight"
|
||||
@@ -2972,7 +3043,7 @@ struct InkCudaRunner {
|
||||
float* ys[5] = { d_q, d_r, d_gate_attn, d_k_raw, d_v_raw };
|
||||
linear_multi(names, ys, 5, in_q, M, exact_x);
|
||||
linear(p + ".attn.attn_sink_proj.weight", in_q, d_sinks, M, 0, false, exact_x);
|
||||
} else if (M <= 16) {
|
||||
} else if (M <= 16 || q8f_dense) {
|
||||
const std::string names[3] = {
|
||||
p + ".attn.wq_du.weight", p + ".attn.wr_du.weight", p + ".attn.gate_attn.weight"
|
||||
};
|
||||
@@ -3446,6 +3517,11 @@ struct InkCudaRunner {
|
||||
}
|
||||
emit_48_visits(M, 0, slot0, p0, want_taps);
|
||||
if (M == 1 && m.hybrid.active && m.n_host_experts > 0) m.hybrid.step_promote(m.d_sec4, m.d_experts, st);
|
||||
if (prof_enabled) { // STRATA_INK_PROF=1: where one decode step goes (eager, events only), every 100 steps
|
||||
prof_flush();
|
||||
if (M != 1) prof_reset();
|
||||
else if (++prof_steps % 100 == 0) { prof_print("DECODE-M1", (int)prof_steps); prof_steps = 0; prof_reset(); }
|
||||
}
|
||||
}
|
||||
|
||||
// Speculative Tree-32 / Block-8 verify (100% CUDA-Graph capturable with safe eager fallback!)
|
||||
@@ -3541,6 +3617,16 @@ struct InkCudaRunner {
|
||||
return;
|
||||
}
|
||||
emit_48_visits(B, 1, 0, 0, want_taps);
|
||||
if (prof_enabled) { // STRATA_INK_PROF=1: the batched decode step, every 50 steps
|
||||
prof_flush();
|
||||
if (++prof_steps % 50 == 0) {
|
||||
char tag[32];
|
||||
std::snprintf(tag, sizeof(tag), "DECODE-B%d", B);
|
||||
prof_print(tag, (int)prof_steps);
|
||||
prof_steps = 0;
|
||||
prof_reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Unembed + Softcap(30.0) + Argmax ----
|
||||
@@ -3683,7 +3769,7 @@ struct InkCudaRunner {
|
||||
fr(d_pf_q); fr(d_pf_k); fr(d_pf_v); fr(d_pf_p); fr(d_pf_s); fr(d_pf_o); fr(d_pf_ot); fr(d_pf_m); fr(d_pf_l);
|
||||
fr(d_stage_k); fr(d_stage_v); fr(d_stage_sconv);
|
||||
fr(d_kv_desc_arr); fr(d_sconv_pool_arr); fr(d_acc_path);
|
||||
fr(d_x_bf16); fr(d_w_scratch); fr(d_logits);
|
||||
fr(d_x_bf16); fr(d_w_scratch); fr(d_logits); fr(d_xq8); fr(d_xs8);
|
||||
fr(d_dot_hat); fr(d_h_norm2); fr(d_max_lb); fr(d_cand_ids); fr(d_cand_cnt); fr(d_argmax);
|
||||
fr(d_tok_ids); fr(d_slots); fr(d_pos); fr(d_is_img); fr(d_img_emb); fr(d_sconv_lag); fr(d_tree_anc); fr(d_tree_dep);
|
||||
if (h_meta_pin) { cudaFreeHost(h_meta_pin); h_meta_pin = nullptr; }
|
||||
|
||||
@@ -135,6 +135,8 @@ std::unique_ptr<InkBackend> make_cpu_backend();
|
||||
|
||||
#ifdef INKLING_ENABLE_CUDA
|
||||
std::unique_ptr<InkBackend> make_cuda_backend();
|
||||
// true when the GPU can run the Q8_0 dense path (int8 tensor-core GEMM: compute capability 8.0 or newer)
|
||||
bool ink_cuda_q8f_supported(int gpu_index);
|
||||
#endif
|
||||
#ifdef INKLING_ENABLE_EP_CUDA
|
||||
std::unique_ptr<InkBackend> make_ep_cuda_backend();
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
#include "strata/artifact/strata_reader.hpp"
|
||||
#include "strata/core/ink_names.hpp"
|
||||
#include "strata/core/mapped_pages.hpp"
|
||||
#include "ink_q8f_pack.h"
|
||||
#include "strata/quant/dequant.hpp"
|
||||
#include "strata/quant/sk_codecs.hpp"
|
||||
|
||||
@@ -34,6 +35,14 @@ namespace ink2 {
|
||||
|
||||
namespace gguf_detail {
|
||||
|
||||
// Set by the CUDA front end (ink_main.cpp) before the model is opened: keep the dense attention matrices that the file stores as
|
||||
// Q8_0 exactly as stored (fmt 104: [rows][cols/32] fp16 scales, then [rows][cols] int8) instead of expanding them to rounded BF16.
|
||||
// Half the bytes to read per token and the file's real weights. Other backends never set it and keep BF16.
|
||||
inline bool& keep_q8_0_dense() {
|
||||
static bool v = false;
|
||||
return v;
|
||||
}
|
||||
|
||||
inline bool has_gguf_magic(const std::string& path) {
|
||||
std::FILE* fp = std::fopen(path.c_str(), "rb");
|
||||
if (!fp) return false;
|
||||
@@ -483,6 +492,47 @@ struct GgufAdapter {
|
||||
return true;
|
||||
};
|
||||
|
||||
// A dense matrix: a Q8_0 one stays Q8_0 when the CUDA front end asked for it, anything else goes through copy_mat_bf16.
|
||||
// frag == false (the embedding table): fmt 104, as stored, row by row: [rows][cols/32] fp16 scales, then [rows][cols] int8.
|
||||
// frag == true (the attention matrices): fmt 105, in the order the int8 tensor-core GEMM reads (k_ink_gemm_q8f in
|
||||
// cuda/ink_kernels.cuh): per 16-row tile and 32-wide block 512 bytes, one 16-byte A fragment per lane, then the scales
|
||||
// [rows/16][cols/32][16] fp16.
|
||||
auto copy_mat_dense = [&](const std::string& gguf_name, const std::string& canon_name, int64_t rows, int64_t cols, bool frag) -> bool {
|
||||
const strata::TensorInfo* ti = nullptr;
|
||||
const uint8_t* ptr = gguf_detail::keep_q8_0_dense() ? tensor_ptr(*model, gguf_name, ti) : nullptr;
|
||||
if (!ptr || !ti || ti->type != 8 || (cols % 32) != 0 || ((rows * cols) % 256) != 0 || (frag && (rows % 16) != 0)) {
|
||||
return copy_mat_bf16(gguf_name, canon_name, rows, cols);
|
||||
}
|
||||
const size_t nblk = static_cast<size_t>(cols / 32);
|
||||
const size_t nr = static_cast<size_t>(rows);
|
||||
const size_t nb = nr * nblk * 2 + nr * static_cast<size_t>(cols);
|
||||
size_t off = align64(sec1_arena.size());
|
||||
sec1_arena.resize(off + nb, 0);
|
||||
uint8_t* out0 = sec1_arena.data() + off;
|
||||
const size_t rb = nblk * 34; // a Q8_0 block: fp16 d, then 32 int8
|
||||
if (!frag) {
|
||||
uint8_t* sc_out = out0;
|
||||
uint8_t* q_out = out0 + nr * nblk * 2;
|
||||
for (size_t r = 0; r < nr; ++r) {
|
||||
const uint8_t* src = ptr + r * rb;
|
||||
for (size_t b = 0; b < nblk; ++b) {
|
||||
std::memcpy(sc_out + (r * nblk + b) * 2, src + b * 34, 2);
|
||||
std::memcpy(q_out + r * static_cast<size_t>(cols) + b * 32, src + b * 34 + 2, 32);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ink_q8f_pack(ptr, nr, static_cast<size_t>(cols), out0);
|
||||
}
|
||||
TInfoT out_ti;
|
||||
out_ti.name = canon_name;
|
||||
out_ti.fmt = frag ? 105 : 104; // F_Q8_0F / F_Q8_0
|
||||
out_ti.shape = {rows, cols};
|
||||
out_ti.off = off;
|
||||
out_ti.bytes = nb;
|
||||
m.trunk[canon_name] = std::move(out_ti);
|
||||
return true;
|
||||
};
|
||||
|
||||
auto copy_vec_f32 = [&](const std::string& gguf_name, const std::string& canon_name, const std::vector<int64_t>& shape) -> bool {
|
||||
std::vector<float> v;
|
||||
if (!read_tensor_f32(*model, gguf_name, v, err)) return false;
|
||||
@@ -517,7 +567,12 @@ struct GgufAdapter {
|
||||
const int q_dim = c.n_head * c.head_dim;
|
||||
const int kv_dim = c.n_kv * c.head_dim;
|
||||
|
||||
if (!copy_mat_bf16("token_embd.weight", "model.llm.embed.weight", c.vocab_padded, D)) return false;
|
||||
// the CUDA embedding kernel finds the int8 plane of a Q8_0 table at 201,024 rows (kInkVocabPad, as for Q8_ROW)
|
||||
if (c.vocab_padded == 201024) {
|
||||
if (!copy_mat_dense("token_embd.weight", "model.llm.embed.weight", c.vocab_padded, D, false)) return false;
|
||||
} else if (!copy_mat_bf16("token_embd.weight", "model.llm.embed.weight", c.vocab_padded, D)) {
|
||||
return false;
|
||||
}
|
||||
if (!copy_vec_f32("token_embd_norm.weight", "model.llm.embed_norm.weight", {D})) return false;
|
||||
if (!copy_mat_bf16("output.weight", "model.llm.unembed.weight", c.vocab_padded, D)) return false;
|
||||
if (!copy_vec_f32("output_norm.weight", "model.llm.norm.weight", {D})) return false;
|
||||
@@ -570,13 +625,13 @@ struct GgufAdapter {
|
||||
const std::string p = "model.llm.layers." + std::to_string(il) + ".";
|
||||
const bool is_swa = (c.is_swa[il] != 0);
|
||||
|
||||
if (!copy_mat_bf16(b + "attn_q.weight", p + "attn.wq_du.weight", q_dim, D)) return false;
|
||||
if (!copy_mat_bf16(b + "attn_k.weight", p + "attn.wk_dv.weight", kv_dim, D)) return false;
|
||||
if (!copy_mat_bf16(b + "attn_v.weight", p + "attn.wv_dv.weight", kv_dim, D)) return false;
|
||||
if (!copy_mat_bf16(nm(b, "attn_r.weight"), p + "attn.wr_du.weight", c.n_head * c.d_rel, D)) return false;
|
||||
if (!copy_mat_dense(b + "attn_q.weight", p + "attn.wq_du.weight", q_dim, D, true)) return false;
|
||||
if (!copy_mat_dense(b + "attn_k.weight", p + "attn.wk_dv.weight", kv_dim, D, true)) return false;
|
||||
if (!copy_mat_dense(b + "attn_v.weight", p + "attn.wv_dv.weight", kv_dim, D, true)) return false;
|
||||
if (!copy_mat_dense(nm(b, "attn_r.weight"), p + "attn.wr_du.weight", c.n_head * c.d_rel, D, true)) return false;
|
||||
if (!copy_mat_bf16(b + "attn_sink_proj.weight", p + "attn.attn_sink_proj.weight", c.n_head, D)) return false;
|
||||
if (!copy_mat_bf16(b + "attn_gate.weight", p + "attn.gate_attn.weight", q_dim, D)) return false;
|
||||
if (!copy_mat_bf16(b + "attn_output.weight", p + "attn.wo_ud.weight", D, q_dim)) return false;
|
||||
if (!copy_mat_dense(b + "attn_gate.weight", p + "attn.gate_attn.weight", q_dim, D, true)) return false;
|
||||
if (!copy_mat_dense(b + "attn_output.weight", p + "attn.wo_ud.weight", D, q_dim, true)) return false;
|
||||
if (!copy_vec_f32(b + "ffn_gate_inp.weight", p + "mlp.gate.weight", {c.n_experts, D})) return false;
|
||||
if (!copy_vec_f32(b + "exp_probs_b.bias", p + "mlp.gate.bias", {c.n_experts})) return false;
|
||||
if (!copy_vec_f32(b + "ffn_norm.weight", p + "mlp_norm.weight", {D})) return false;
|
||||
|
||||
@@ -341,10 +341,17 @@ static int cmd_dump_ref(const std::string& model_path, const std::string& out_pa
|
||||
const int32_t V = mf.m.c.vocab_unpadded;
|
||||
std::vector<float> logits(static_cast<size_t>(n_tok) * V);
|
||||
StepBatch batch;
|
||||
for (int i = 0; i < n_tok; ++i) batch.push(0, i, ids[i], true);
|
||||
if (!backend->forward_batch(batch, logits.data(), nullptr, err)) {
|
||||
fprintf(stderr, "forward: %s\n", err.c_str());
|
||||
return 1;
|
||||
// INK_DUMP_CHUNK=n feeds the tokens n at a time (1 = the single-token decode kernels), default: all in one batch
|
||||
int dump_chunk = n_tok;
|
||||
if (const char* dc = std::getenv("INK_DUMP_CHUNK"); dc && std::atoi(dc) > 0) dump_chunk = std::min<int>(std::atoi(dc), n_tok);
|
||||
for (int i0 = 0; i0 < n_tok; i0 += dump_chunk) {
|
||||
const int i1 = std::min<int>(n_tok, i0 + dump_chunk);
|
||||
batch.clear();
|
||||
for (int i = i0; i < i1; ++i) batch.push(0, i, ids[i], true);
|
||||
if (!backend->forward_batch(batch, logits.data() + static_cast<size_t>(i0) * V, nullptr, err)) {
|
||||
fprintf(stderr, "forward: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
FILE* f = std::fopen(out_path.c_str(), "wb");
|
||||
if (!f) { fprintf(stderr, "dump-ref: cannot write %s\n", out_path.c_str()); return 1; }
|
||||
@@ -541,6 +548,15 @@ int main(int argc, char** argv) {
|
||||
strata::core::set_serve_error_line(true);
|
||||
}
|
||||
|
||||
#ifdef INKLING_ENABLE_CUDA
|
||||
// One CUDA GPU (sm_80 or newer: the int8 tensor-core GEMM): a GGUF's Q8_0 dense matrices stay as stored (half the bytes of rounded BF16, the file's own weights).
|
||||
// STRATA_INK_Q8_0_DENSE=0 goes back to BF16 (for A/B runs). Several GPUs and the CPU backend keep BF16.
|
||||
if (!cfg.force_cpu && cfg.bopts.gpus == 1 && cfg.bopts.layer_split.empty() && ink2::ink_cuda_q8f_supported(cfg.bopts.gpu_index)) {
|
||||
const char* q8e = std::getenv("STRATA_INK_Q8_0_DENSE");
|
||||
ink2::gguf_detail::keep_q8_0_dense() = !(q8e && q8e[0] == '0');
|
||||
}
|
||||
#endif
|
||||
|
||||
if (mode_info) return cmd_info(info_file, cfg.vision_path, cfg.bopts.dspark_path);
|
||||
if (mode_export) return cmd_export_tokenizer(export_file, export_dir);
|
||||
if (mode_selfcheck) return cmd_selfcheck(cfg.model_path, cfg.force_cpu, verify_hash, cfg.bopts);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// ink_q8f_pack.h - GGUF Q8_0 rows -> the fragment order of the CUDA int8 tensor-core GEMM (format 105, k_ink_gemm_q8f in cuda/ink_kernels.cuh).
|
||||
// Host only, no CUDA types: the loader packs with it and the GPU test packs with it.
|
||||
//
|
||||
// Input: `rows` rows of a Q8_0 tensor, `cols` columns each (cols % 32 == 0), `rows` % 16 == 0; a row is cols/32 blocks of 34 bytes (fp16 d, 32 int8).
|
||||
// Output (rows * cols int8 bytes, then rows * cols/32 fp16 scales):
|
||||
// qpack [rows/16][cols/32][32 lanes][16 B]: lane (g = lane >> 2, t = lane & 3) holds the four A registers of mma.m16n8k32 (s8)
|
||||
// a0 = row g, k t*4..+3 a1 = row g+8, k t*4..+3 a2 = row g, k 16+t*4..+3 a3 = row g+8, k 16+t*4..+3
|
||||
// scales [rows/16][cols/32][16] fp16: the block scale of each row of the tile.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace ink2 {
|
||||
|
||||
inline size_t ink_q8f_bytes(size_t rows, size_t cols) { return rows * cols + rows * (cols / 32) * 2; }
|
||||
|
||||
inline void ink_q8f_pack(const uint8_t* src, size_t rows, size_t cols, uint8_t* out) {
|
||||
const size_t nblk = cols / 32;
|
||||
const size_t rb = nblk * 34;
|
||||
uint8_t* q_out = out;
|
||||
uint8_t* sc_out = out + rows * cols;
|
||||
for (size_t rt = 0; rt < rows / 16; ++rt) {
|
||||
for (size_t kb = 0; kb < nblk; ++kb) {
|
||||
uint8_t* tile = q_out + (rt * nblk + kb) * 512;
|
||||
for (int lane = 0; lane < 32; ++lane) {
|
||||
const int g = lane >> 2, t = lane & 3;
|
||||
const uint8_t* s0 = src + (rt * 16 + g) * rb + kb * 34 + 2;
|
||||
const uint8_t* s1 = src + (rt * 16 + g + 8) * rb + kb * 34 + 2;
|
||||
uint8_t* o = tile + lane * 16;
|
||||
std::memcpy(o + 0, s0 + t * 4, 4);
|
||||
std::memcpy(o + 4, s1 + t * 4, 4);
|
||||
std::memcpy(o + 8, s0 + 16 + t * 4, 4);
|
||||
std::memcpy(o + 12, s1 + 16 + t * 4, 4);
|
||||
}
|
||||
for (int rr = 0; rr < 16; ++rr) {
|
||||
std::memcpy(sc_out + ((rt * nblk + kb) * 16 + rr) * 2, src + (rt * 16 + rr) * rb + kb * 34, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ink2
|
||||
@@ -0,0 +1,123 @@
|
||||
// The Q8_0 dense GEMM of the CUDA Inkling engine (k_ink_gemm_q8f + k_ink_quant_x_q8f, format 105): bit-exact against a host emulation of the
|
||||
// same arithmetic, and a token's result must not depend on M (prefill chunk, batch or alone).
|
||||
// nvcc -std=c++17 -arch=sm_86 -I engine/src/inkling2 -I engine/src/inkling2/cuda -I engine/include engine/tests/cuda/ink_q8f_gemm_test.cu -o ink_q8f_gemm_test
|
||||
// Skips (exit 77) below compute capability 8.0.
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
#include "ink_cuda.cuh"
|
||||
#include "ink_kernels.cuh"
|
||||
#include "ink_q8f_pack.h"
|
||||
|
||||
using namespace strata::ink;
|
||||
|
||||
#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { std::printf("CUDA error %s at %d\n", cudaGetErrorString(e_), __LINE__); return 2; } } while (0)
|
||||
|
||||
static void run_gemm(const uint8_t* d_w, int N, int K, const float* d_x, int M, float* d_y, int8_t* d_xq, float* d_xs) {
|
||||
const int nMT = (M + 7) / 8, nKB = K >> 5;
|
||||
k_ink_quant_x_q8f<<<(nMT * 8 * nKB + 7) / 8, 256>>>(d_x, d_xq, d_xs, M, K, nMT);
|
||||
InkMultiProj mp{};
|
||||
mp.W[0] = d_w; mp.Y[0] = d_y; mp.N[0] = N; mp.cumN[0] = 0; mp.cumN[1] = N; mp.count = 1;
|
||||
const int gx = (N / 16 + 1) / 2;
|
||||
const int mtw = nMT >= 8 ? 8 : (nMT >= 4 ? 4 : (nMT >= 2 ? 2 : 1));
|
||||
const dim3 grid(gx, (nMT + mtw - 1) / mtw);
|
||||
if (mtw == 8) k_ink_gemm_q8f<8><<<grid, 64>>>(mp, d_xq, d_xs, M, K, nMT);
|
||||
else if (mtw == 4) k_ink_gemm_q8f<4><<<grid, 64>>>(mp, d_xq, d_xs, M, K, nMT);
|
||||
else if (mtw == 2) k_ink_gemm_q8f<2><<<grid, 64>>>(mp, d_xq, d_xs, M, K, nMT);
|
||||
else k_ink_gemm_q8f<1><<<grid, 64>>>(mp, d_xq, d_xs, M, K, nMT);
|
||||
}
|
||||
|
||||
int main() {
|
||||
int major = 0;
|
||||
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, 0);
|
||||
if (major < 8) { std::printf("ink_q8f_gemm_test: skipped (needs sm_80+)\n"); return 77; }
|
||||
std::mt19937 rng(12345);
|
||||
int bad = 0;
|
||||
for (int K : {2304, 3072}) {
|
||||
const int N = 160, MMAX = 70, nKB = K / 32;
|
||||
// random Q8_0 matrix: blocks of fp16 scale + 32 int8
|
||||
std::vector<uint8_t> q8(static_cast<size_t>(N) * nKB * 34);
|
||||
for (int r = 0; r < N; ++r)
|
||||
for (int b = 0; b < nKB; ++b) {
|
||||
uint8_t* blk = q8.data() + (static_cast<size_t>(r) * nKB + b) * 34;
|
||||
const __half h = __float2half(0.001f + 0.02f * (rng() % 1000) / 1000.0f);
|
||||
std::memcpy(blk, &h, 2);
|
||||
for (int i = 0; i < 32; ++i) blk[2 + i] = static_cast<uint8_t>(static_cast<int>(rng() % 255) - 127);
|
||||
}
|
||||
std::vector<uint8_t> packed(ink2::ink_q8f_bytes(N, K));
|
||||
ink2::ink_q8f_pack(q8.data(), N, K, packed.data());
|
||||
std::vector<float> x(static_cast<size_t>(MMAX) * K);
|
||||
for (int m = 0; m < MMAX; ++m)
|
||||
for (int k = 0; k < K; ++k) {
|
||||
float v = (static_cast<int>(rng() % 20001) - 10000) / 3000.0f;
|
||||
if (m % 11 == 3 && (k / 32) % 5 == 0) v = 0.0f; // some all-zero blocks
|
||||
x[static_cast<size_t>(m) * K + k] = v * (1.0f + (k % 7));
|
||||
}
|
||||
uint8_t* d_w; float *d_x, *d_y, *d_xs; int8_t* d_xq;
|
||||
CK(cudaMalloc(&d_w, packed.size())); CK(cudaMalloc(&d_x, x.size() * 4)); CK(cudaMalloc(&d_y, static_cast<size_t>(MMAX) * N * 4));
|
||||
CK(cudaMalloc(&d_xq, static_cast<size_t>(MMAX + 8) * K)); CK(cudaMalloc(&d_xs, static_cast<size_t>(MMAX + 8) * nKB * 4));
|
||||
CK(cudaMemcpy(d_w, packed.data(), packed.size(), cudaMemcpyHostToDevice));
|
||||
CK(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice));
|
||||
|
||||
// host emulation of the same arithmetic
|
||||
std::vector<float> ref(static_cast<size_t>(MMAX) * N);
|
||||
for (int m = 0; m < MMAX; ++m) {
|
||||
std::vector<int8_t> q(K);
|
||||
std::vector<float> sx(nKB);
|
||||
for (int b = 0; b < nKB; ++b) {
|
||||
float am = 0.0f;
|
||||
for (int i = 0; i < 32; ++i) am = std::fmax(am, std::fabs(x[static_cast<size_t>(m) * K + b * 32 + i]));
|
||||
const float d = am * (1.0f / 127.0f);
|
||||
const float inv = d > 0.0f ? (127.0f / am) : 0.0f;
|
||||
sx[b] = d;
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
int v = static_cast<int>(std::nearbyint(x[static_cast<size_t>(m) * K + b * 32 + i] * inv));
|
||||
q[b * 32 + i] = static_cast<int8_t>(std::max(-127, std::min(127, v)));
|
||||
}
|
||||
}
|
||||
for (int r = 0; r < N; ++r) {
|
||||
float acc = 0.0f;
|
||||
for (int b = 0; b < nKB; ++b) {
|
||||
const uint8_t* blk = q8.data() + (static_cast<size_t>(r) * nKB + b) * 34;
|
||||
__half h; std::memcpy(&h, blk, 2);
|
||||
const float sw = __half2float(h);
|
||||
int32_t c = 0;
|
||||
for (int i = 0; i < 32; ++i) c += static_cast<int32_t>(static_cast<int8_t>(blk[2 + i])) * static_cast<int32_t>(q[b * 32 + i]);
|
||||
acc = std::fmaf(static_cast<float>(c), sw * sx[b], acc);
|
||||
}
|
||||
ref[static_cast<size_t>(m) * N + r] = acc;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<float> y_full(static_cast<size_t>(MMAX) * N);
|
||||
for (int M : {70, 64, 33, 9, 8, 7, 1}) {
|
||||
CK(cudaMemset(d_y, 0xFF, static_cast<size_t>(MMAX) * N * 4));
|
||||
run_gemm(d_w, N, K, d_x, M, d_y, d_xq, d_xs);
|
||||
CK(cudaGetLastError()); CK(cudaDeviceSynchronize());
|
||||
std::vector<float> y(static_cast<size_t>(MMAX) * N);
|
||||
CK(cudaMemcpy(y.data(), d_y, y.size() * 4, cudaMemcpyDeviceToHost));
|
||||
int n_ref = 0, n_inv = 0;
|
||||
for (size_t i = 0; i < static_cast<size_t>(M) * N; ++i) {
|
||||
if (std::memcmp(&y[i], &ref[i], 4) != 0) ++n_ref;
|
||||
if (M == 70) y_full[i] = y[i];
|
||||
else if (std::memcmp(&y[i], &y_full[i], 4) != 0) ++n_inv;
|
||||
}
|
||||
// rows past M must stay untouched (0xFFFFFFFF = NaN)
|
||||
int n_over = 0;
|
||||
for (size_t i = static_cast<size_t>(M) * N; i < y.size(); ++i) {
|
||||
uint32_t u; std::memcpy(&u, &y[i], 4);
|
||||
if (u != 0xFFFFFFFFu) ++n_over;
|
||||
}
|
||||
std::printf("K=%d M=%2d: %d values differ from the host emulation, %d differ from the M=70 run, %d written past M\n", K, M, n_ref, n_inv, n_over);
|
||||
bad += n_ref + n_inv + n_over;
|
||||
}
|
||||
cudaFree(d_w); cudaFree(d_x); cudaFree(d_y); cudaFree(d_xq); cudaFree(d_xs);
|
||||
}
|
||||
if (bad) { std::printf("ink_q8f_gemm_test: FAIL (%d)\n", bad); return 1; }
|
||||
std::printf("ink_q8f_gemm_test: OK\n");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user