okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
60d431e2a
main
1// tools/vision/own/vit_gpu.cu - see vit_gpu.h. One source for CUDA and HIP (STRATA_VIT_HIP maps the few runtime / BLAS names). 2#include "vit_gpu.h" 3#include "vit_f16.h" 4 5#include <algorithm> 6#include <cfloat> 7#include <chrono> 8#include <cmath> 9#include <cstdio> 10#include <cstdint> 11#include <cstdlib> 12#include <cstring> 13#include <thread> 14 15#if defined(STRATA_VIT_HIP) 16#include <hip/hip_fp16.h> 17#include <hip/hip_runtime.h> 18#include <hipblas/hipblas.h> 19#if defined(STRATA_VIT_HIPBLASLT) 20// hipBLASLt for the matrix products (STRATA_VIT_LT / STRATA_VIT_LT_ATT, off by default): on gfx1151 the package's rocBLAS carries only its generic 21// fallback kernels, and the products took 1.7 to 3.0 times mtmd-HIP's whole picture (RESULTS-OWN-3V.md 12.14, section 14) 22#include <hipblaslt/hipblaslt.h> 23#include <hipblaslt/hipblaslt-ext.hpp> 24#include <map> 25#include <tuple> 26#endif 27#define cudaError_t hipError_t 28#define cudaSuccess hipSuccess 29#define cudaGetErrorString hipGetErrorString 30#define cudaGetDeviceCount hipGetDeviceCount 31#define cudaSetDevice hipSetDevice 32#define cudaMalloc hipMalloc 33#define cudaFree hipFree 34#define cudaMemcpy hipMemcpy 35#define cudaMemcpyHostToDevice hipMemcpyHostToDevice 36#define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost 37#define cudaMemset hipMemset 38#define cudaGetLastError hipGetLastError 39#define cudaDeviceSynchronize hipDeviceSynchronize 40#define cudaMemGetInfo hipMemGetInfo 41#define cudaDataType_t hipDataType 42#define cublasHandle_t hipblasHandle_t 43#define cublasCreate hipblasCreate 44#define cublasDestroy hipblasDestroy 45#define cublasStatus_t hipblasStatus_t 46#define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS 47#define CUBLAS_OP_T HIPBLAS_OP_T 48#define CUBLAS_OP_N HIPBLAS_OP_N 49#define CUDA_R_32F HIP_R_32F 50#define CUDA_R_16F HIP_R_16F 51#define CUDA_R_16BF HIP_R_16BF 52#define VIT_COMPUTE_32F HIPBLAS_COMPUTE_32F 53#define VIT_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT 54#define cublasGemmEx hipblasGemmEx 55#define cublasGemmStridedBatchedEx hipblasGemmStridedBatchedEx 56#define VIT_SHFL_XOR(v, m) __shfl_xor((v), (m)) 57#else 58#include <cublas_v2.h> 59#include <cuda_fp16.h> 60#include <cuda_runtime.h> 61#define VIT_COMPUTE_32F CUBLAS_COMPUTE_32F 62#define VIT_GEMM_DEFAULT CUBLAS_GEMM_DEFAULT 63#define VIT_SHFL_XOR(v, m) __shfl_xor_sync(0xffffffffu, (v), (m)) 64#endif 65 66namespace strata_vit { 67 68namespace { 69 70// the 16-bit kind a GEMM's input takes (its weight's). K_BH: a BF16 matrix held as F16 (every BF16 value of the weights' and activations' range is an F16 value; 71// the activations are rounded to BF16 first, so the products see the BF16 values): gfx1151's default, elsewhere STRATA_VIT_BF16_AS_F16=1. 72// K_HF: a BF16 matrix held as F16 with the activations written as F16 directly (clamped to +-65,504), the default for BF16 matrices elsewhere: BF16's 7-bit 73// mantissa on the inputs of the 27 blocks' products left 50 picture tokens of 12,308 under cosine 0.99 against the float32 reference on the CUDA reader, 74// 10 bits (F16) none in a CPU emulation (RESULTS-OWN-B18.md BLOCKS 16-18). A matrix with a weight beyond F16's range stays K_BF16. 75enum Kind { K_F32 = 0, K_F16 = 1, K_BF16 = 2, K_BH = 3, K_HF = 4 }; 76 77struct DevW { // a weight matrix [rows = out][cols = in] on the device 78 void* p = nullptr; 79 Kind kind = K_BF16; 80 int rows = 0, cols = 0; 81}; 82 83struct DevLayer { 84 float *ln1_w = nullptr, *ln1_b = nullptr, *ln2_w = nullptr, *ln2_b = nullptr, *qkv_b = nullptr, *o_b = nullptr, *up_b = nullptr, *down_b = nullptr; 85 DevW qkv, o, up, down; 86}; 87 88__device__ __forceinline__ uint16_t f_to_bf16(float f) { // round to nearest even 89 uint32_t u = __float_as_uint(f); 90 if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 0x40); // NaN stays NaN 91 u += 0x7fffu + ((u >> 16) & 1u); 92 return (uint16_t) (u >> 16); 93} 94__device__ __forceinline__ uint16_t f_to_f16bits(float f) { return __half_as_ushort(__float2half_rn(f)); } 95 96__device__ __forceinline__ void store_kind(void* out, size_t i, float v, int kind) { 97 if (kind == K_F32) ((float*) out)[i] = v; 98 else if (kind == K_F16) ((uint16_t*) out)[i] = f_to_f16bits(v); 99 else if (kind == K_BH) ((uint16_t*) out)[i] = f_to_f16bits(__uint_as_float((uint32_t) f_to_bf16(v) << 16)); 100 else if (kind == K_HF) ((uint16_t*) out)[i] = f_to_f16bits(f16_clamp(v)); 101 else ((uint16_t*) out)[i] = f_to_bf16(v); 102} 103 104 105// block-wide sum of one float per thread (blockDim.x a multiple of the warp size, at most 1024) 106__device__ float block_sum(float v) { 107 __shared__ float red[32]; 108 const int lane = threadIdx.x % warpSize, wid = threadIdx.x / warpSize; 109 for (int o = warpSize / 2; o > 0; o >>= 1) v += VIT_SHFL_XOR(v, o); 110 __syncthreads(); 111 if (lane == 0) red[wid] = v; 112 __syncthreads(); 113 const int nw = (blockDim.x + warpSize - 1) / warpSize; 114 v = lane < nw ? red[lane] : 0.0f; 115 for (int o = warpSize / 2; o > 0; o >>= 1) v += VIT_SHFL_XOR(v, o); 116 return v; 117} 118 119 120// x[t] += patch bias + the position table resized (bilinear, align corners: ggml's maths, in float) to the token's grid position 121__global__ void k_patch_post(float* __restrict__ x, const float* __restrict__ bias, const float* __restrict__ pos, int G, int pw, int ph, int nbx, int D) { 122 const int t = blockIdx.x, b = t / 4, r = t % 4; 123 const int ty = 2 * (b / nbx) + r / 2, tx = 2 * (b % nbx) + r % 2; 124 float sfx = (float) pw / G, sfy = (float) ph / G; 125 if (pw > 1 && G > 1) sfx = (float) (pw - 1) / (G - 1); 126 if (ph > 1 && G > 1) sfy = (float) (ph - 1) / (G - 1); 127 const float fy = (float) ty / sfy, fx = (float) tx / sfx; 128 int y0 = (int) floorf(fy), x0 = (int) floorf(fx), y1 = y0 + 1, x1 = x0 + 1; 129 y0 = max(0, min(y0, G - 1)); y1 = max(0, min(y1, G - 1)); 130 x0 = max(0, min(x0, G - 1)); x1 = max(0, min(x1, G - 1)); 131 const float dy = fmaxf(0.0f, fminf(fy - (float) y0, 1.0f)), dx = fmaxf(0.0f, fminf(fx - (float) x0, 1.0f)); 132 const float* a = pos + ((size_t) y0 * G + x0) * D; 133 const float* bb = pos + ((size_t) y0 * G + x1) * D; 134 const float* c = pos + ((size_t) y1 * G + x0) * D; 135 const float* d = pos + ((size_t) y1 * G + x1) * D; 136 float* xr = x + (size_t) t * D; 137 for (int i = threadIdx.x; i < D; i += blockDim.x) 138 xr[i] += bias[i] + (a[i] * (1 - dx) * (1 - dy) + bb[i] * dx * (1 - dy) + c[i] * (1 - dx) * dy + d[i] * dx * dy); 139} 140 141// out = LayerNorm(x) * w + b, into `kind` 142__global__ void k_layernorm(const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ b, float eps, int D, void* out, int kind) { 143 const float* xr = x + (size_t) blockIdx.x * D; 144 float s = 0.0f; 145 for (int i = threadIdx.x; i < D; i += blockDim.x) s += xr[i]; 146 const float mean = block_sum(s) / (float) D; 147 float v = 0.0f; 148 for (int i = threadIdx.x; i < D; i += blockDim.x) { const float d = xr[i] - mean; v += d * d; } 149 const float scale = rsqrtf(block_sum(v) / (float) D + eps); 150 for (int i = threadIdx.x; i < D; i += blockDim.x) store_kind(out, (size_t) blockIdx.x * D + i, (xr[i] - mean) * scale * w[i] + b[i], kind); 151} 152 153// y [rows][3D] (the fused qkv product of the tokens row0 ..) + bias -> q, k (rotary applied), v, each [N][D] in F16 (as ggml's flash attention holds 154// them). Pair j of a head is (j, j + hd/2); j < hd/4 turns with the token's row, the others with its column. 155__global__ void k_qkv_rope(const float* __restrict__ y, const float* __restrict__ bias, int row0, int nbx, int heads, int hd, float theta_scale, float qscale, 156 uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v) { 157 const int t = row0 + blockIdx.x, D = heads * hd, half = hd / 2, quarter = hd / 4; 158 const int b = t / 4, r = t % 4; 159 const int ty = 2 * (b / nbx) + r / 2, tx = 2 * (b % nbx) + r % 2; 160 const float* yr = y + (size_t) blockIdx.x * 3 * D; 161 for (int i = threadIdx.x; i < 2 * heads * half; i += blockDim.x) { 162 const int part = i / (heads * half), rem = i % (heads * half), h = rem / half, j = rem % half; 163 const int base = part * D + h * hd; 164 const float a = yr[base + j] + bias[base + j], c = yr[base + j + half] + bias[base + j + half]; 165 const float freq = powf(theta_scale, (float) (j % quarter)); 166 float sn, cs; 167 sincosf((float) (j < quarter ? ty : tx) * freq, &sn, &cs); 168 uint16_t* dst = (part == 0 ? q : k) + (size_t) t * D + h * hd; 169 const float sc = part == 0 ? qscale : 1.0f; // the attention's 1/sqrt(head size) goes into q: the scores are then smaller, and an F16 score keeps more digits 170 dst[j] = f_to_f16bits((a * cs - c * sn) * sc); 171 dst[j + half] = f_to_f16bits((a * sn + c * cs) * sc); 172 } 173 for (int e = threadIdx.x; e < D; e += blockDim.x) v[(size_t) t * D + e] = f_to_f16bits(yr[2 * D + e] + bias[2 * D + e]); 174} 175 176// In place: a row of n F16 scores (the scale is already in q) becomes the row of probabilities, F16. One block (256 threads) per row; the row is held in 177// registers (at most 256 * kSoftmaxPer = 16,384 scores), read once and written once. 178constexpr int kSoftmaxThreads = 256, kSoftmaxPer = 64; 179// T threads and PER scores per thread (T * PER >= n): a short row (a small picture) gets a small block and a short loop, as the long loop with its 180// predicated steps cost a 93-token picture 9 of its 26 ms 181template <int T, int PER> 182__global__ void __launch_bounds__(T) k_softmax_rows(uint16_t* __restrict__ S, int n, int ld) { 183 uint16_t* s = S + (size_t) blockIdx.x * ld; 184 __shared__ float red[32]; 185 const int lane = threadIdx.x % warpSize, wid = threadIdx.x / warpSize, nw = (blockDim.x + warpSize - 1) / warpSize; 186 float v[PER]; 187 float m = -FLT_MAX; 188#pragma unroll 189 for (int k = 0; k < PER; ++k) { 190 const int j = threadIdx.x + k * T; 191 v[k] = j < n ? __half2float(__ushort_as_half(s[j])) : -FLT_MAX; 192 m = fmaxf(m, v[k]); 193 } 194 for (int o = warpSize / 2; o > 0; o >>= 1) m = fmaxf(m, VIT_SHFL_XOR(m, o)); 195 if (lane == 0) red[wid] = m; 196 __syncthreads(); 197 m = lane < nw ? red[lane] : -FLT_MAX; 198 for (int o = warpSize / 2; o > 0; o >>= 1) m = fmaxf(m, VIT_SHFL_XOR(m, o)); 199 __syncthreads(); 200 float sum = 0.0f; 201#pragma unroll 202 for (int k = 0; k < PER; ++k) { 203 const int j = threadIdx.x + k * T; 204 v[k] = j < n ? expf(v[k] - m) : 0.0f; 205 sum += v[k]; 206 } 207 for (int o = warpSize / 2; o > 0; o >>= 1) sum += VIT_SHFL_XOR(sum, o); 208 if (lane == 0) red[wid] = sum; 209 __syncthreads(); 210 sum = lane < nw ? red[lane] : 0.0f; 211 for (int o = warpSize / 2; o > 0; o >>= 1) sum += VIT_SHFL_XOR(sum, o); 212 const float inv = 1.0f / sum; 213#pragma unroll 214 for (int k = 0; k < PER; ++k) { 215 const int j = threadIdx.x + k * T; 216 if (j < n) s[j] = f_to_f16bits(v[k] * inv); 217 } 218} 219 220// launches the short-row kernel with the smallest block and loop that hold n scores (n <= 256 * 64) 221static void softmax_rows(uint16_t* S, int n, int ld, int rows) { 222 if (n <= 128) k_softmax_rows<64, 2><<<rows, 64>>>(S, n, ld); 223 else if (n <= 512) k_softmax_rows<64, 8><<<rows, 64>>>(S, n, ld); 224 else if (n <= 1024) k_softmax_rows<128, 8><<<rows, 128>>>(S, n, ld); 225 else if (n <= 4096) k_softmax_rows<256, 16><<<rows, 256>>>(S, n, ld); 226 else k_softmax_rows<256, 64><<<rows, 256>>>(S, n, ld); 227} 228 229// The same for a row too long to hold in registers (more than 16,384 patches: a picture of 4,096 image tokens or more): three passes over the row in memory. 230__global__ void __launch_bounds__(kSoftmaxThreads) k_softmax_rows_long(uint16_t* __restrict__ S, int n, int ld) { 231 uint16_t* s = S + (size_t) blockIdx.x * ld; 232 __shared__ float red[32]; 233 const int lane = threadIdx.x % warpSize, wid = threadIdx.x / warpSize, nw = (blockDim.x + warpSize - 1) / warpSize; 234 float m = -FLT_MAX; 235 for (int j = threadIdx.x; j < n; j += blockDim.x) m = fmaxf(m, __half2float(__ushort_as_half(s[j]))); 236 for (int o = warpSize / 2; o > 0; o >>= 1) m = fmaxf(m, VIT_SHFL_XOR(m, o)); 237 if (lane == 0) red[wid] = m; 238 __syncthreads(); 239 m = lane < nw ? red[lane] : -FLT_MAX; 240 for (int o = warpSize / 2; o > 0; o >>= 1) m = fmaxf(m, VIT_SHFL_XOR(m, o)); 241 __syncthreads(); 242 float sum = 0.0f; 243 for (int j = threadIdx.x; j < n; j += blockDim.x) sum += expf(__half2float(__ushort_as_half(s[j])) - m); 244 for (int o = warpSize / 2; o > 0; o >>= 1) sum += VIT_SHFL_XOR(sum, o); 245 if (lane == 0) red[wid] = sum; 246 __syncthreads(); 247 sum = lane < nw ? red[lane] : 0.0f; 248 for (int o = warpSize / 2; o > 0; o >>= 1) sum += VIT_SHFL_XOR(sum, o); 249 const float inv = 1.0f / sum; 250 for (int j = threadIdx.x; j < n; j += blockDim.x) s[j] = f_to_f16bits(expf(__half2float(__ushort_as_half(s[j])) - m) * inv); 251} 252 253// y[i] rounded to the 16-bit kind and back (STRATA_VIT_REF_ROUND: ggml's GPU matrix product hands back its result in the weight's 16-bit type) 254__global__ void k_round(float* __restrict__ y, size_t n, int kind) { 255 for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) { 256 const float v = y[i]; 257 y[i] = kind == K_F16 ? __half2float(__float2half_rn(v)) : __uint_as_float((uint32_t) f_to_bf16(v) << 16); // K_BF16, K_BH and K_HF: BF16 258 } 259} 260 261// BF16 weights to F16 in place (K_HF): exact inside F16's range, F16's round to nearest even under 2^-14 (matrices with a weight beyond the range stay BF16) 262__global__ void k_bf16_to_f16(uint16_t* __restrict__ p, size_t n) { 263 for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) 264 p[i] = f_to_f16bits(__uint_as_float((uint32_t) p[i] << 16)); 265} 266 267// n floats to the 16-bit kind 268__global__ void k_cast(const float* __restrict__ in, size_t n, void* out, int kind) { 269 for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) store_kind(out, i, in[i], kind); 270} 271 272#if defined(STRATA_VIT_HIP) 273// n 16-bit values (K_F16: F16, else BF16) to float32 (STRATA_VIT_HPA16: a product computed with float32 accumulation and a 16-bit result, widened back) 274__global__ void k_widen16(const uint16_t* __restrict__ in, size_t n, float* __restrict__ out, int kind) { 275 for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) 276 out[i] = kind == K_F16 ? __half2float(__ushort_as_half(in[i])) : __uint_as_float((uint32_t) in[i] << 16); 277} 278 279// The fused attention for gfx11 (RDNA3 / RDNA3.5: gfx1100-1103, gfx1150, gfx1151; STRATA_VIT_FA=1): S = Q K^T, the softmax and O = P V of a chunk of queries for 280// every head in one launch, flash-attention style, with the gfx11 WMMA instruction (16x16x16, F16 in, float32 accumulate, wave32). One block = 4 waves = 281// 64 queries of one head; each wave owns 16 queries and walks the keys in tiles of kFaKeys. Per tile: the scores of the wave's 16 queries (float32, never 282// rounded to 16 bits), an online softmax in float32 (running row maximum and sum, expf), P rounded to F16 for the second product, O += P V in float32 283// registers. The head size is padded with zeros to NT * 16 (72 -> 80). O / row sum goes to ctx in float32. No atomics, a fixed key order: the result is 284// the same on every run. q is already scaled by 1 / sqrt(head size) (k_qkv_rope). The WMMA fragment layouts (wave32): A: lane l holds row l % 16, 16 285// consecutive K values; B: lane l holds column l % 16, 16 consecutive K values; C / D (float32): lane l holds column l % 16, rows 2 * e + l / 16, e = 0..7. 286constexpr int kFaQ = 64, kFaKeys = 64; 287#if defined(__GFX11__) 288typedef _Float16 vit_half16 __attribute__((ext_vector_type(16))); 289typedef float vit_float8 __attribute__((ext_vector_type(8))); 290// 16 consecutive F16 values from a 16-byte aligned address, as two 128-bit loads 291__device__ __forceinline__ vit_half16 fa_ld16(const _Float16* p) { 292 const uint4 x0 = *(const uint4*) p, x1 = *(const uint4*) (p + 8); 293 vit_half16 r; 294 __builtin_memcpy(&r, &x0, 16); 295 __builtin_memcpy((char*) &r + 16, &x1, 16); 296 return r; 297} 298#endif 299// Tuning round 1 (11-11): K and V reach LDS by 128-bit global loads (8 F16 values; the head size must be a multiple of 8), the fragments leave LDS by 300// 128-bit loads (LDS rows padded by 8 values to stay 16-byte aligned and to shift the banks), 64-key tiles, exp2f with log2(e) folded into the scores, 301// and the P exchange inside a wave (a wave barrier with LDS fences, not a block barrier). 302template <int NT> 303__global__ void __launch_bounds__(128) k_attn_fa_gfx11(const uint16_t* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, 304 float* __restrict__ ctx, int N, int q0, int qc, int D, int hd) { 305#if defined(__GFX11__) 306 constexpr int DP = NT * 16, SKP = DP + 8, KP = kFaKeys + 8, CH = DP / 8; 307 constexpr float kLog2e = 1.4426950408889634f; 308 __shared__ __attribute__((aligned(16))) _Float16 sK[kFaKeys][SKP]; // the key tile, row = key 309 __shared__ __attribute__((aligned(16))) _Float16 sVt[DP][KP]; // the value tile transposed, row = head dimension 310 __shared__ __attribute__((aligned(16))) _Float16 sP[4][16][KP]; // each wave's probabilities, row = query 311 const int h = blockIdx.y, wave = threadIdx.x / 32, lane = threadIdx.x % 32, l16 = lane % 16, hi = lane / 16; 312 const int qw = q0 + blockIdx.x * kFaQ + wave * 16; // this wave's first query 313 const size_t hoff = (size_t) h * hd; 314 // the wave's Q as NT A fragments: row l16 = query qw + l16, columns 16 * s .. 16 * s + 15 of the head 315 vit_half16 qa[NT]; 316 { 317 const int qi = qw + l16; 318 const bool ok = qi < q0 + qc; 319 const _Float16* qr = (const _Float16*) q + (size_t) qi * D + hoff; 320 for (int s = 0; s < NT; ++s) 321 for (int e = 0; e < 16; ++e) { 322 const int d = s * 16 + e; 323 qa[s][e] = (ok && d < hd) ? qr[d] : (_Float16) 0.0f; 324 } 325 } 326 vit_float8 o[NT]; 327 for (int t = 0; t < NT; ++t) o[t] = vit_float8{0, 0, 0, 0, 0, 0, 0, 0}; 328 float mrow[8], lrow[8]; // rows 2 * e + hi of the wave's 16 queries; the maximum in log2 units 329 for (int e = 0; e < 8; ++e) { mrow[e] = -INFINITY; lrow[e] = 0.0f; } 330 for (int k0 = 0; k0 < N; k0 += kFaKeys) { 331 __syncthreads(); // the previous tile is used up 332 for (int i = threadIdx.x; i < kFaKeys * CH; i += blockDim.x) { 333 const int key = i / CH, d = (i % CH) * 8, kk = k0 + key; 334 uint4 kx = make_uint4(0, 0, 0, 0), vx = make_uint4(0, 0, 0, 0); 335 if (kk < N && d < hd) { 336 const size_t g = (size_t) kk * D + hoff + d; 337 kx = *(const uint4*) (k + g); 338 vx = *(const uint4*) (v + g); 339 } 340 *(uint4*) &sK[key][d] = kx; 341 _Float16 vv[8]; 342 __builtin_memcpy(vv, &vx, 16); 343 for (int e = 0; e < 8; ++e) sVt[d + e][key] = vv[e]; 344 } 345 __syncthreads(); 346 // the scores of the wave's 16 queries against the tile's keys, in 16-key quarters, times log2(e) 347 vit_float8 sc[kFaKeys / 16]; 348 for (int j = 0; j < kFaKeys / 16; ++j) { 349 vit_float8 acc = vit_float8{0, 0, 0, 0, 0, 0, 0, 0}; 350 for (int s = 0; s < NT; ++s) acc = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(qa[s], fa_ld16(&sK[j * 16 + l16][s * 16]), acc); 351 const bool valid = k0 + j * 16 + l16 < N; 352 for (int e = 0; e < 8; ++e) sc[j][e] = valid ? acc[e] * kLog2e : -INFINITY; 353 } 354 // online softmax per query row: this lane holds rows 2 * e + hi of one key column per quarter; the row's other keys are in the 16 lanes of its half 355 for (int e = 0; e < 8; ++e) { 356 float mx = sc[0][e]; 357 for (int j = 1; j < kFaKeys / 16; ++j) mx = fmaxf(mx, sc[j][e]); 358 for (int off = 8; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 16)); 359 const float mnew = fmaxf(mrow[e], mx); 360 const float corr = exp2f(mrow[e] - mnew); 361 float sum = 0.0f; 362 for (int j = 0; j < kFaKeys / 16; ++j) { 363 const float pr = exp2f(sc[j][e] - mnew); 364 sum += pr; 365 sP[wave][2 * e + hi][j * 16 + l16] = (_Float16) pr; 366 } 367 for (int off = 8; off > 0; off >>= 1) sum += __shfl_xor(sum, off, 16); 368 lrow[e] = lrow[e] * corr + sum; 369 mrow[e] = mnew; 370 for (int t = 0; t < NT; ++t) o[t][e] *= corr; 371 } 372 // sP is this wave's own: every lane's writes before any lane's reads, inside the wave 373 __builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront"); 374 __builtin_amdgcn_wave_barrier(); 375 __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); 376 // O += P V: A = P (row = query l16, 16 keys), B = V (16 keys, column = head dimension t * 16 + l16) 377 for (int j = 0; j < kFaKeys / 16; ++j) { 378 const vit_half16 pa = fa_ld16(&sP[wave][l16][j * 16]); 379 for (int t = 0; t < NT; ++t) o[t] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(pa, fa_ld16(&sVt[t * 16 + l16][j * 16]), o[t]); 380 } 381 } 382 // O / row sum to the context rows: lane column = head dimension t * 16 + l16, rows 2 * e + hi 383 for (int e = 0; e < 8; ++e) { 384 const int qi = qw + 2 * e + hi; 385 if (qi >= q0 + qc) continue; 386 const float inv = 1.0f / lrow[e]; 387 float* out = ctx + (size_t) qi * D + hoff; 388 for (int t = 0; t < NT; ++t) { 389 const int d = t * 16 + l16; 390 if (d < hd) out[d] = o[t][e] * inv; 391 } 392 } 393#else 394 (void) q; (void) k; (void) v; (void) ctx; (void) N; (void) q0; (void) qc; (void) D; (void) hd; 395#endif 396} 397#endif 398 399// x[r] += y[r] + bias 400__global__ void k_add_bias_res(float* __restrict__ x, const float* __restrict__ y, const float* __restrict__ bias, int D) { 401 const size_t base = (size_t) blockIdx.x * D; 402 for (int i = threadIdx.x; i < D; i += blockDim.x) x[base + i] += y[base + i] + bias[i]; 403} 404 405// out = gelu_tanh(y + bias) into `kind` 406__global__ void k_bias_gelu_cast(const float* __restrict__ y, const float* __restrict__ bias, int n, void* out, int kind) { 407 const size_t base = (size_t) blockIdx.x * n; 408 for (int i = threadIdx.x; i < n; i += blockDim.x) { 409 const float x = y[base + i] + bias[i]; 410 const float g = 0.5f * x * (1.0f + tanhf(0.79788456080286535587989211986876f * x * (1.0f + 0.044715f * x * x))); 411 store_kind(out, base + i, g, kind); 412 } 413} 414 415// y[r] += bias 416__global__ void k_add_bias(float* __restrict__ y, const float* __restrict__ bias, int n) { 417 const size_t base = (size_t) blockIdx.x * n; 418 for (int i = threadIdx.x; i < n; i += blockDim.x) y[base + i] += bias[i]; 419} 420 421// ---- host side ---- 422uint16_t host_f32_to_bf16(float f) { 423 uint32_t u; 424 std::memcpy(&u, &f, 4); 425 if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 0x40); 426 u += 0x7fffu + ((u >> 16) & 1u); 427 return (uint16_t) (u >> 16); 428} 429 430uint16_t host_f32_to_f16(float f) { 431 const __half h = __float2half_rn(f); 432 uint16_t u; 433 std::memcpy(&u, &h, 2); 434 return u; 435} 436 437} // namespace 438 439struct VitGpuImpl { 440 VitGeometry g; 441 int device = 0; 442 cublasHandle_t blas = nullptr; 443 std::vector<void*> allocs; // every device allocation (weights and work buffers), freed in the destructor 444 size_t bytes = 0, work_bytes = 0; 445 std::vector<void*> work; // the work buffers (a prefix of allocs is weights, the rest are these) 446 size_t n_weight_allocs = 0; 447 448 float *patch_w = nullptr, *patch_b = nullptr, *pos = nullptr, *post_w = nullptr, *post_b = nullptr, *mm0_b = nullptr, *mm2_b = nullptr; 449 DevW mm0, mm2; 450 std::vector<DevLayer> layers; 451 452 int cap_patches = 0; 453 // Work buffers, sized for cap_patches patches N (D = width). The GPU memory is what a reader costs next to the engine, so the matrix products run in 454 // chunks of kRows tokens: only the residual stream, the attention context and the 16-bit q, k, v and GEMM input are N rows long. 455 float *d_x = nullptr, *d_ctx = nullptr, *d_y = nullptr, *d_out = nullptr; // d_x: residual [N][D]; d_ctx: attention context [N][D] (also the patch matrix, and d_out the 456 // projector's output at the end); d_y: one chunk's product [kRows][max(3D, ffn, merger)] 457 uint16_t *d_a = nullptr, *d_f16 = nullptr; // a chunk's GEMM input in its 16-bit kind [kRows][D]; the activated FFN / merger hidden of a chunk [kRows][max(ffn, merger)] 458 uint16_t *d_q16 = nullptr, *d_k16 = nullptr, *d_v16 = nullptr; // q (scaled by 1/sqrt(head size)), k, v [N][D], F16 459 uint16_t* d_S = nullptr; // the scores of a chunk of queries for every head, F16; the softmax turns them into the probabilities in place 460 size_t sp_elems = 0; 461 int kRows = 512; // rows per chunk of the matrix products (STRATA_VIT_ROWS overrides: a diagnostic) 462 size_t kScoreElems = (size_t) 8 << 20; // scores per attention chunk, 8M: 16 MB of F16 (STRATA_VIT_SCORES, in M elements, overrides) 463 size_t kScoreElemsLarge = (size_t) 512 << 20; // the chunk above 16,384 patches: 512M scores, 1 GB of F16 (see size_buffers) 464 bool scores_env = false; // STRATA_VIT_SCORES was given: one size for every picture 465 // Above 16,384 patches a score row is padded to a multiple of 64 elements and the queries of an attention chunk are a multiple of 64: with the 466 // picture's own row length (limit_7000x5000.png, 65,232 patches: 514 queries per chunk, rows not 128-byte aligned) the A4000 took 108.1 s against 467 // 80.3 s aligned, while 65,536 patches took 80.9 s (RESULTS-OWN-3V.md 16.2). Up to 16,384 patches: 8 and no rounding, as before. 468 // STRATA_VIT_NPAD / STRATA_VIT_QALIGN (diagnostics) set both for every picture. 469 int n_pad = 0, q_align = 0; // 0: the rule above 470 int pad_for(size_t n) const { return n_pad ? n_pad : n > 16384 ? 64 : 8; } 471 int align_for(size_t n) const { return q_align ? q_align : n > 16384 ? 64 : 1; } 472 size_t padded(size_t n) const { const size_t p = (size_t) pad_for(n); return (n + p - 1) / p * p; } 473 // BF16 matrices as F16 with F16 inputs (K_HF) on every CUDA card, Pascal included, and on every HIP card but gfx1151 (Strix Halo: K_BH, the BF16-rounded 474 // kind, not measured with K_HF). Pascal needs one of the F16 kinds: cuBLAS has no fast BF16 kernel there (a P100 spent 645 ms of a 1,024-token picture in 475 // magma_sgemmEx for BF16 against 497 ms with F16 inputs; the 12-token picture 44 ms against 15; RESULTS-OWN-3V.md 16.1). P100, 16 pictures against the 476 // float32 reference: K_HF no token under cosine 0.99 (smallest 0.9970), K_BH 44 under 0.99 (smallest 0.866), the same encode time (13.23 against 13.24 s), 477 // loaded in 0.6 against 1.5 s (K_BH converts on the host). STRATA_VIT_BF16_AS_F16 (a diagnostic) overrides: 0 = BF16 as stored (K_BF16), 1 = K_BH, 478 // 2 = K_HF (vit_gpu_bf16_mode in vit_f16.h). 479 int bf16_mode = BF16_TO_F16; 480 struct F16Note { std::string name; Kind kind; Bf16F16Count c; long long n; }; 481 std::vector<F16Note> f16_notes; // per BF16 matrix in K_HF mode: the kind it got and its counts (printed under STRATA_TRACE) 482 483#if defined(STRATA_VIT_HIPBLASLT) 484 // hipBLASLt (HIP builds that found it). STRATA_VIT_LT=1: the 16-bit weight products; STRATA_VIT_LT_ATT=1: the two batched attention products; 485 // STRATA_VIT_LT_SOL=<id>: that solution for the weight products instead of hipBLASLt's first heuristic answer; STRATA_VIT_LT_VERBOSE=1: the solution 486 // of every new shape and a summary on stderr. The solution of a shape is chosen once per process, by id or as the heuristic's first answer that fits 487 // the workspace, never by timing, so two processes take the same kernels. A shape hipBLASLt cannot run goes to hipBLAS as before. 488 struct LtPlan { 489 bool ok = false; 490 int sol = -1; 491 hipblasLtMatmulAlgo_t algo{}; 492 hipblasLtMatmulDesc_t op = nullptr; 493 hipblasLtMatrixLayout_t a = nullptr, b = nullptr, c = nullptr; 494 }; 495 using LtKey = std::tuple<int, int, int, int, int, int, int, int, int, int, int, int, long long, long long, long long>; 496 hipblasLtHandle_t lt = nullptr; 497 void* lt_ws = nullptr; 498 size_t lt_ws_bytes = (size_t) 32 << 20; 499 bool lt_weights = false, lt_att = false, lt_verbose = false; 500 int lt_sol = -1; 501 std::map<LtKey, LtPlan> lt_plans; 502 unsigned long long lt_launches = 0, lt_fallbacks = 0; 503 504 static hipblasLtMatrixLayout_t lt_layout(hipDataType t, int rows, int cols, int ld, int batch, long long stride) { 505 hipblasLtMatrixLayout_t l = nullptr; 506 if (hipblasLtMatrixLayoutCreate(&l, t, rows, cols, ld) != HIPBLAS_STATUS_SUCCESS) return nullptr; 507 if (batch > 1) { 508 const int32_t bc = batch; 509 const int64_t st = stride; 510 if (hipblasLtMatrixLayoutSetAttribute(l, HIPBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &bc, sizeof(bc)) != HIPBLAS_STATUS_SUCCESS || 511 hipblasLtMatrixLayoutSetAttribute(l, HIPBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &st, sizeof(st)) != HIPBLAS_STATUS_SUCCESS) { 512 hipblasLtMatrixLayoutDestroy(l); 513 return nullptr; 514 } 515 } 516 return l; 517 } 518 static void lt_free(LtPlan& p) { 519 if (p.op) hipblasLtMatmulDescDestroy(p.op); 520 if (p.a) hipblasLtMatrixLayoutDestroy(p.a); 521 if (p.b) hipblasLtMatrixLayoutDestroy(p.b); 522 if (p.c) hipblasLtMatrixLayoutDestroy(p.c); 523 p = LtPlan{}; 524 } 525 // the descriptors and the solution of one call shape (made once, kept for the reader's life) 526 LtPlan& lt_plan(bool ta, bool tb, int m, int n, int k, hipDataType at, int lda, long long sa, hipDataType bt, int ldb, long long sb, hipDataType ct, int ldc, 527 long long sc, int batch, int sol) { 528 const LtKey key{(int) ta, (int) tb, m, n, k, (int) at, (int) bt, (int) ct, lda, ldb, ldc, batch, sa, sb, sc}; 529 auto it = lt_plans.find(key); 530 if (it != lt_plans.end()) return it->second; 531 LtPlan& p = lt_plans[key]; 532 const hipblasOperation_t oa = ta ? HIPBLAS_OP_T : HIPBLAS_OP_N, ob = tb ? HIPBLAS_OP_T : HIPBLAS_OP_N; 533 if (hipblasLtMatmulDescCreate(&p.op, HIPBLAS_COMPUTE_32F, HIP_R_32F) != HIPBLAS_STATUS_SUCCESS || 534 hipblasLtMatmulDescSetAttribute(p.op, HIPBLASLT_MATMUL_DESC_TRANSA, &oa, sizeof(oa)) != HIPBLAS_STATUS_SUCCESS || 535 hipblasLtMatmulDescSetAttribute(p.op, HIPBLASLT_MATMUL_DESC_TRANSB, &ob, sizeof(ob)) != HIPBLAS_STATUS_SUCCESS || 536 !(p.a = lt_layout(at, ta ? k : m, ta ? m : k, lda, batch, sa)) || !(p.b = lt_layout(bt, tb ? n : k, tb ? k : n, ldb, batch, sb)) || 537 !(p.c = lt_layout(ct, m, n, ldc, batch, sc))) { 538 lt_free(p); 539 return p; 540 } 541 const float alpha = 1.0f, beta = 0.0f; 542 size_t need = 0; 543 if (sol >= 0) { // a given solution id 544 std::vector<int> ids{sol}; 545 std::vector<hipblasLtMatmulHeuristicResult_t> r; 546 if (hipblaslt_ext::getAlgosFromIndex(lt, ids, r) == HIPBLAS_STATUS_SUCCESS && !r.empty() && r.front().state == HIPBLAS_STATUS_SUCCESS) { 547 hipblasLtMatmulAlgo_t algo = r.front().algo; 548 if (hipblaslt_ext::matmulIsAlgoSupported(lt, p.op, &alpha, p.a, p.b, &beta, p.c, p.c, algo, need) == HIPBLAS_STATUS_SUCCESS && 549 need <= lt_ws_bytes) { 550 p.algo = algo; 551 p.ok = true; 552 } 553 } 554 } else { // hipBLASLt's first heuristic answer that fits the workspace 555 hipblasLtMatmulPreference_t pref = nullptr; 556 const uint64_t ws = lt_ws_bytes; 557 if (hipblasLtMatmulPreferenceCreate(&pref) == HIPBLAS_STATUS_SUCCESS && 558 hipblasLtMatmulPreferenceSetAttribute(pref, HIPBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, &ws, sizeof(ws)) == HIPBLAS_STATUS_SUCCESS) { 559 hipblasLtMatmulHeuristicResult_t r[8]; 560 int got = 0; 561 if (hipblasLtMatmulAlgoGetHeuristic(lt, p.op, p.a, p.b, p.c, p.c, pref, 8, r, &got) == HIPBLAS_STATUS_SUCCESS) 562 for (int i = 0; i < got && !p.ok; ++i) 563 if (r[i].state == HIPBLAS_STATUS_SUCCESS && r[i].workspaceSize <= lt_ws_bytes) { 564 p.algo = r[i].algo; 565 need = r[i].workspaceSize; 566 p.ok = true; 567 } 568 } 569 if (pref) hipblasLtMatmulPreferenceDestroy(pref); 570 } 571 if (p.ok) p.sol = hipblaslt_ext::getIndexFromAlgo(p.algo); 572 if (lt_verbose) 573 std::fprintf(stderr, "vit-lt: %s%s m=%d n=%d k=%d types=%d/%d/%d batch=%d -> %s %d (workspace %zu)\n", ta ? "T" : "N", tb ? "T" : "N", m, n, k, (int) at, 574 (int) bt, (int) ct, batch, p.ok ? "solution" : "hipBLAS, no solution", p.sol, need); 575 if (!p.ok) { lt_free(p); p.ok = false; } 576 return p; 577 } 578 // the product through hipBLASLt; false: not run (the caller uses hipBLAS) 579 bool lt_mm(bool ta, bool tb, int m, int n, int k, const void* A, cudaDataType_t at, int lda, long long sa, const void* B, cudaDataType_t bt, int ldb, 580 long long sb, void* C, cudaDataType_t ct, int ldc, long long sc, int batch, int sol) { 581 LtPlan& p = lt_plan(ta, tb, m, n, k, at, lda, sa, bt, ldb, sb, ct, ldc, sc, batch, sol); 582 if (!p.ok) { ++lt_fallbacks; return false; } 583 const float alpha = 1.0f, beta = 0.0f; 584 if (hipblasLtMatmul(lt, p.op, &alpha, A, p.a, B, p.b, &beta, C, p.c, C, p.c, &p.algo, lt_ws, lt_ws_bytes, nullptr) != HIPBLAS_STATUS_SUCCESS) { 585 std::fprintf(stderr, "vit-lt: the hipBLASLt product failed (m=%d n=%d k=%d batch=%d); hipBLAS from now on for this shape\n", m, n, k, batch); 586 lt_free(p); 587 p.ok = false; 588 ++lt_fallbacks; 589 return false; 590 } 591 ++lt_launches; 592 return true; 593 } 594 void lt_setup() { 595 auto on = [](const char* name) { const char* e = std::getenv(name); return e && std::atoi(e) != 0; }; 596 lt_weights = on("STRATA_VIT_LT"); 597 lt_att = on("STRATA_VIT_LT_ATT"); 598 lt_verbose = on("STRATA_VIT_LT_VERBOSE"); 599 if (const char* e = std::getenv("STRATA_VIT_LT_SOL")) lt_sol = std::atoi(e); 600 if (!lt_weights && !lt_att) return; 601 if (hipblasLtCreate(<) != HIPBLAS_STATUS_SUCCESS || cudaMalloc(<_ws, lt_ws_bytes) != cudaSuccess) { 602 (void) cudaGetLastError(); 603 std::fprintf(stderr, "vit-lt: hipBLASLt is not usable here; hipBLAS for every product\n"); 604 if (lt) { hipblasLtDestroy(lt); lt = nullptr; } 605 lt_ws = nullptr; 606 lt_weights = lt_att = false; 607 return; 608 } 609 std::fprintf(stderr, "vit-lt: hipBLASLt for %s%s%s (solution %s)\n", lt_weights ? "the weight products" : "", lt_weights && lt_att ? " and " : "", 610 lt_att ? "the attention products" : "", lt_sol >= 0 ? std::to_string(lt_sol).c_str() : "heuristic"); 611 } 612 void lt_close() { 613 for (auto& kv : lt_plans) lt_free(kv.second); 614 lt_plans.clear(); 615 if (lt_ws) (void) cudaFree(lt_ws); 616 if (lt) hipblasLtDestroy(lt); 617 if (lt_verbose && (lt_launches || lt_fallbacks)) 618 std::fprintf(stderr, "vit-lt: %llu hipBLASLt products, %llu by hipBLAS\n", lt_launches, lt_fallbacks); 619 lt = nullptr; 620 lt_ws = nullptr; 621 } 622#endif 623 624#if defined(STRATA_VIT_HIP) 625 // STRATA_VIT_HPA16=1 (on by default on gfx1151 only, see VitGpu::load): the 16-bit weight products ask rocBLAS for a 16-bit RESULT with float32 accumulation (BF16 -> BF16 and F16 -> F16, 626 // compute 32F: rocBLAS's BB_HPA / HH_HPA kernels), then widen it to float32. On gfx110x and gfx1151 the Windows ROCm package's rocBLAS has tuned kernels 627 // for those types and only its generic fallback kernels for BF16 / F16 -> F32 (BS_HPA / HS_HPA), which our products asked for (lane COVER 11-11, 628 // phaseA-tests\par\RESULTS-COVER.md); mtmd's reader asks for the 16-bit result there. STRATA_VIT_HPA16_ATT=1: the same for the attention's P*V product 629 // (F16 -> F16, float32 accumulation; the score product S is F16 -> F16 already). The result is the float32 sum rounded once to 16 bits. 630 bool hpa16 = false, hpa16_att = false; 631 // [DRAFT, status: research] STRATA_VIT_FA (on by default on gfx1151 only, see VitGpu::load; =1 asks for it on another gfx11 card, =0 turns it off): the fused attention 632 // k_attn_fa_gfx11 on gfx11 cards (wave32). A launch takes at most fa_units query x key x head 633 // triples (STRATA_VIT_FA_UNITS overrides): 2^29, measured on the 780M with the first version at about 1.4 TFLOP/s as about 110 ms, so far 634 // from the Windows GPU timeout of 2 s on any gfx11 card, also at the 16,384-token limit (65,232 patches: about 130 launches a layer). With STRATA_VIT_PROF the longest launch of an encode is printed. 635 bool fa = false; 636 long long fa_units = 1LL << 29; 637 double fa_longest_ms = 0.0; 638 uint16_t *d_y16 = nullptr, *d_pv16 = nullptr; // the 16-bit results (sized with the work buffers when the switch is on) 639 size_t y16_elems = 0, pv16_elems = 0; 640#endif 641 642 // C = alpha * op(A) * op(B), batched, column-major as the BLAS wants it 643 bool bgemm(bool ta, bool tb, int m, int n, int k, const void* A, cudaDataType_t at, int lda, long long sa, const void* B, cudaDataType_t bt, int ldb, 644 long long sb, void* C, cudaDataType_t ct, int ldc, long long sc, int batch, std::string& err) { 645#if defined(STRATA_VIT_HIPBLASLT) 646 if (lt_att && lt_mm(ta, tb, m, n, k, A, at, lda, sa, B, bt, ldb, sb, C, ct, ldc, sc, batch, -1)) return true; 647#endif 648#if defined(STRATA_VIT_HIP) 649 // a float32 result whose batches tile its rows (P*V: the heads side by side in a row of the context): 16-bit result, then widened 650 if (hpa16_att && ct == CUDA_R_32F && at == CUDA_R_16F && bt == CUDA_R_16F && (long long) batch * sc == ldc && m <= ldc && 651 (size_t) n * ldc <= pv16_elems) { 652 const float alpha = 1.0f, beta = 0.0f; 653 const cublasStatus_t s = cublasGemmStridedBatchedEx(blas, ta ? CUBLAS_OP_T : CUBLAS_OP_N, tb ? CUBLAS_OP_T : CUBLAS_OP_N, m, n, k, &alpha, A, at, lda, 654 sa, B, bt, ldb, sb, &beta, d_pv16, CUDA_R_16F, ldc, sc, batch, VIT_COMPUTE_32F, VIT_GEMM_DEFAULT); 655 if (s != CUBLAS_STATUS_SUCCESS) { err = "the batched BLAS product failed (status " + std::to_string((int) s) + ")"; return false; } 656 const size_t cnt = (size_t) n * ldc; 657 k_widen16<<<blocks_for(cnt), 256>>>(d_pv16, cnt, (float*) C, (int) K_F16); 658 return true; 659 } 660#endif 661 const float alpha = 1.0f, beta = 0.0f; 662 const cublasStatus_t s = cublasGemmStridedBatchedEx(blas, ta ? CUBLAS_OP_T : CUBLAS_OP_N, tb ? CUBLAS_OP_T : CUBLAS_OP_N, m, n, k, &alpha, A, at, lda, sa, 663 B, bt, ldb, sb, &beta, C, ct, ldc, sc, batch, VIT_COMPUTE_32F, VIT_GEMM_DEFAULT); 664 if (s != CUBLAS_STATUS_SUCCESS) { err = "the batched BLAS product failed (status " + std::to_string((int) s) + ")"; return false; } 665 return true; 666 } 667 668 ~VitGpuImpl() { 669 (void) cudaSetDevice(device); 670#if defined(STRATA_VIT_HIPBLASLT) 671 lt_close(); 672#endif 673 for (void* p : allocs) (void) cudaFree(p); 674 if (blas) cublasDestroy(blas); 675 } 676 template <class T> bool alloc(T*& p, size_t n, std::string& err, bool weight) { 677 void* q = nullptr; 678 const cudaError_t e = cudaMalloc(&q, n * sizeof(T)); 679 if (e != cudaSuccess) { err = std::string("GPU memory: ") + cudaGetErrorString(e); (void) cudaGetLastError(); return false; } 680 p = (T*) q; 681 allocs.push_back(q); 682 bytes += n * sizeof(T); 683 if (!weight) work_bytes += n * sizeof(T); 684 return true; 685 } 686 bool upload_f32(float*& dst, const Gguf& gg, const std::string& name, std::string& err) { 687 const GgufTensorInfo* t = gg.tensor(name); 688 if (!t) { err = "the mmproj file lacks the tensor " + name; return false; } 689 std::vector<float> h((size_t) t->nelem()); 690 if (!gg.read_f32(*t, h.data(), err)) return false; 691 if (!alloc(dst, h.size(), err, true)) return false; 692 return cudaMemcpy(dst, h.data(), h.size() * 4, cudaMemcpyHostToDevice) == cudaSuccess || (err = "GPU copy failed", false); 693 } 694 bool upload_matrix(DevW& w, const Gguf& gg, const std::string& name, std::string& err) { 695 const GgufTensorInfo* t = gg.tensor(name); 696 if (!t || t->ne.size() != 2) { err = "the mmproj file lacks the matrix " + name; return false; } 697 w.cols = (int) t->ne[0]; 698 w.rows = (int) t->ne[1]; 699 const size_t n = (size_t) t->nelem(); 700 std::vector<unsigned char> raw; 701 if (t->type == GT_BF16 && bf16_mode == BF16_TO_F16) { // BF16 -> F16 (K_HF) unless a weight is beyond F16's range 702 raw.resize(n * 2); 703 if (!gg.read_raw(*t, raw.data(), err)) return false; 704 // the full count (weights not exact in F16, their largest error) only for the trace; the rule needs the overflow count alone 705 Bf16F16Count c; 706 if (trace) c = bf16_count_f16((const uint16_t*) raw.data(), (long long) n); 707 else c.overflow = bf16_count_beyond_f16((const uint16_t*) raw.data(), (long long) n); 708 w.kind = bf16_matrix_fits_f16(c.overflow) ? K_HF : K_BF16; 709 f16_notes.push_back({name, w.kind, c, (long long) n}); 710 // uploaded as stored and turned into F16 on the GPU (k_bf16_to_f16): a host loop over the 444 M weights of the Qwen3.8 reader took 0.8 s 711 } else if (t->type == GT_BF16 && bf16_mode == BF16_ROUNDED) { // BF16 -> F16 (K_BH) 712 std::vector<float> f(n); 713 if (!gg.read_f32(*t, f.data(), err)) return false; 714 raw.resize(n * 2); 715 w.kind = K_BH; 716 for (size_t i = 0; i < n; ++i) { 717 const uint16_t u = host_f32_to_f16(f[i]); 718 std::memcpy(&raw[i * 2], &u, 2); 719 } 720 } else if (t->type == GT_F16 || t->type == GT_BF16) { // as stored 721 raw.resize(n * 2); 722 if (!gg.read_raw(*t, raw.data(), err)) return false; 723 w.kind = t->type == GT_F16 ? K_F16 : K_BF16; 724 } else { // F32 -> BF16, Q8_0 -> F16 725 std::vector<float> f(n); 726 if (!gg.read_f32(*t, f.data(), err)) return false; 727 raw.resize(n * 2); 728 const bool bf = t->type == GT_F32; 729 w.kind = bf ? K_BF16 : K_F16; 730 for (size_t i = 0; i < n; ++i) { 731 const uint16_t u = bf ? host_f32_to_bf16(f[i]) : host_f32_to_f16(f[i]); 732 std::memcpy(&raw[i * 2], &u, 2); 733 } 734 } 735 uint16_t* dev = nullptr; 736 if (!alloc(dev, n, err, true)) return false; 737 w.p = dev; 738 if (cudaMemcpy(w.p, raw.data(), n * 2, cudaMemcpyHostToDevice) != cudaSuccess) { err = "GPU copy failed"; return false; } 739 if (w.kind == K_HF) { 740 k_bf16_to_f16<<<blocks_for(n), 256>>>(dev, n); 741 if (cudaGetLastError() != cudaSuccess) { err = "the BF16 to F16 conversion failed on the GPU"; return false; } 742 } 743 return true; 744 } 745 bool trace = false; // STRATA_TRACE: the per-matrix F16 counts 746 static cudaDataType_t dtype(Kind k) { return k == K_F32 ? CUDA_R_32F : (k == K_F16 || k == K_BH || k == K_HF) ? CUDA_R_16F : CUDA_R_16BF; } 747 748 // y[M][N] (float32) = A[M][K] (kind of w) * w^T 749 bool gemm(const DevW& w, const void* A, int M, void* y, cudaDataType_t kind_a, std::string& err) { 750 const float alpha = 1.0f, beta = 0.0f; 751 bool done = false; 752#if defined(STRATA_VIT_HIPBLASLT) 753 if (lt_weights && kind_a != CUDA_R_32F) 754 done = lt_mm(true, false, w.rows, M, w.cols, w.p, kind_a, w.cols, 0, A, kind_a, w.cols, 0, y, CUDA_R_32F, w.rows, 0, 1, lt_sol); 755#endif 756#if defined(STRATA_VIT_HIP) 757 if (!done && hpa16 && kind_a != CUDA_R_32F && (size_t) M * w.rows <= y16_elems) { 758 const cublasStatus_t s = cublasGemmEx(blas, CUBLAS_OP_T, CUBLAS_OP_N, w.rows, M, w.cols, &alpha, w.p, kind_a, w.cols, A, kind_a, w.cols, &beta, d_y16, 759 kind_a, w.rows, VIT_COMPUTE_32F, VIT_GEMM_DEFAULT); 760 if (s != CUBLAS_STATUS_SUCCESS) { err = "the BLAS matrix product failed (status " + std::to_string((int) s) + ")"; return false; } 761 const size_t cnt = (size_t) M * w.rows; 762 k_widen16<<<blocks_for(cnt), 256>>>(d_y16, cnt, (float*) y, kind_a == CUDA_R_16F ? (int) K_F16 : (int) K_BF16); 763 done = true; 764 } 765#endif 766 if (!done) { 767 const cublasStatus_t s = cublasGemmEx(blas, CUBLAS_OP_T, CUBLAS_OP_N, w.rows, M, w.cols, &alpha, w.p, kind_a, w.cols, A, kind_a, w.cols, &beta, y, 768 CUDA_R_32F, w.rows, VIT_COMPUTE_32F, VIT_GEMM_DEFAULT); 769 if (s != CUBLAS_STATUS_SUCCESS) { err = "the BLAS matrix product failed (status " + std::to_string((int) s) + ")"; return false; } 770 } 771 if (round_out && w.kind != K_F32) { // the result as ggml's GPU path keeps it: 16 bits (its inputs are 16 bits here already) 772 const size_t n = (size_t) M * w.rows; 773 k_round<<<blocks_for(n), 256>>>((float*) y, n, (int) w.kind); 774 } 775 return true; 776 } 777 bool round_out = false; // STRATA_VIT_REF_ROUND=1 (a diagnostic, off by default): round every matrix product's result to its weight's 16-bit type 778 static int blocks_for(size_t n, int per = 256) { return (int) std::min<size_t>((n + per - 1) / per, 65535); } 779 780 bool size_buffers(int patches, std::string& err) { 781 if (patches <= cap_patches) return true; 782 (void) cudaSetDevice(device); 783 // free the old work buffers and take new ones sized for this many patches 784 for (size_t i = allocs.size(); i > n_weight_allocs; --i) { (void) cudaFree(allocs[i - 1]); } 785 bytes -= work_bytes; 786 work_bytes = 0; 787 allocs.resize(n_weight_allocs); 788 const size_t N = (size_t) patches, D = (size_t) g.width, F = (size_t) std::max(g.ffn, g.merger_hidden); 789 const size_t K0 = (size_t) 3 * g.patch * g.patch; 790 d_x = d_y = d_ctx = d_out = nullptr; 791 d_a = d_f16 = d_q16 = d_k16 = d_v16 = nullptr; 792 d_S = nullptr; 793 // attention by batched GEMMs: scores S (float32) and probabilities P (F16) of a chunk of queries for every head, at most kScoreElems each 794 // (a very large picture gets at least 64 queries per chunk, so its many chunks stay few) 795 // a score row is padded to a multiple of 8 elements (the product's leading dimension): with an odd row length the BLAS cannot use its tensor-core 796 // kernels (a 93-token picture spent half its time there) 797 const size_t Np = padded(N); 798 // above 16,384 patches (pictures of more than 4,096 tokens) the chunk is 512M scores (1 GB): with the 16 MB chunk such a picture runs 64 queries per 799 // product and the attention is launch-bound (l620, 16,384 tokens: 33.4 s, 1.17 of mtmd-GPU; with 512M 24.8 s, 0.87, at 3,398 MiB against mtmd-GPU's 800 // 3,858; RESULTS-OWN-3V.md 12.11). STRATA_VIT_SCORES sets both sizes. 801 const size_t budget = (N > 16384 && !scores_env) ? kScoreElemsLarge : kScoreElems; 802 sp_elems = std::min<size_t>((size_t) g.heads * N * Np, std::max<size_t>(budget, (size_t) g.heads * Np * 64)); 803 const size_t R = std::min<size_t>(N, (size_t) kRows); 804 // d_ctx holds, one after the other: the patch matrix, the attention context, and at the end the projector's output rows (d_out) 805 const size_t ctx_elems = std::max({N * D, N * K0, (N / 4) * (size_t) g.out_dim}); 806 bool ok = alloc(d_x, N * D, err, false) && alloc(d_ctx, ctx_elems, err, false) && alloc(d_y, R * std::max<size_t>(3 * D, F), err, false) && 807 alloc(d_a, R * D, err, false) && alloc(d_f16, R * F, err, false) && 808 alloc(d_q16, N * D, err, false) && alloc(d_k16, N * D, err, false) && alloc(d_v16, N * D, err, false); 809#if defined(STRATA_VIT_HIP) 810 d_y16 = d_pv16 = nullptr; 811 y16_elems = pv16_elems = 0; 812 if (ok && hpa16) { y16_elems = R * std::max<size_t>(3 * D, F); ok = alloc(d_y16, y16_elems, err, false); } 813 if (ok && hpa16_att) { pv16_elems = N * D; ok = alloc(d_pv16, pv16_elems, err, false); } 814#endif 815 if (ok && !alloc(d_S, sp_elems, err, false)) { 816 // no room for the large chunk (a small card, or the engine beside the reader): the 16 MB chunk instead, slower, never an error 817 ok = false; 818 if (budget != kScoreElems) { 819 err.clear(); 820 sp_elems = std::min<size_t>((size_t) g.heads * N * Np, std::max<size_t>(kScoreElems, (size_t) g.heads * Np * 64)); 821 ok = alloc(d_S, sp_elems, err, false); 822 } 823 } 824 d_out = d_ctx; 825 if (!ok) { cap_patches = 0; return false; } 826 cap_patches = patches; 827 return true; 828 } 829}; 830 831// cudaSetDevice, which makes the context. On an integrated GPU in a Linux CUDA build a "out of memory" is tried again (vit_gpu.h, vit_gpu_retry_context); anywhere 832// else this is the one call it was. Returns the error of the last call; the runtime's own error state is cleared after each failure. 833static cudaError_t set_device_retrying(int device) { 834 int retries = 0; 835 const auto t0 = std::chrono::steady_clock::now(); 836 for (;;) { 837 const cudaError_t e = cudaSetDevice(device); 838 if (e == cudaSuccess) { 839 if (retries > 0 && std::getenv("STRATA_VIT_PROF")) 840 std::fprintf(stderr, "vit-prof: GPU context made after %d retries, %.2f s\n", retries, std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count()); 841 return e; 842 } 843 (void) cudaGetLastError(); 844#if defined(__linux__) && !defined(STRATA_VIT_HIP) // SPARK-CTX-RETRY 845 int integrated = 0; 846 if (cudaDeviceGetAttribute(&integrated, cudaDevAttrIntegrated, device) != cudaSuccess) { integrated = 0; (void) cudaGetLastError(); } 847 if (vit_gpu_retry_context(true, integrated != 0, e == cudaErrorMemoryAllocation, retries)) { 848 ++retries; 849 std::this_thread::sleep_for(std::chrono::milliseconds(kVitCtxWaitMs)); 850 continue; 851 } 852#endif 853 return e; 854 } 855} 856 857VitGpu::VitGpu() : impl_(new VitGpuImpl()) {} 858VitGpu::~VitGpu() = default; 859size_t VitGpu::device_bytes() const { return impl_->bytes; } 860 861bool VitGpu::available(std::string& why) { 862 int n = 0; 863 const cudaError_t e = cudaGetDeviceCount(&n); 864 if (e != cudaSuccess || n <= 0) { why = e != cudaSuccess ? std::string("no GPU runtime: ") + cudaGetErrorString(e) : "no GPU found"; (void) cudaGetLastError(); return false; } 865 return true; 866} 867 868bool VitGpu::prefer_mtmd(bool bf16_matrices, int max_tokens, std::string& why) { 869#if defined(STRATA_VIT_HIP) 870 hipDeviceProp_t p; 871 (void) bf16_matrices; 872 (void) max_tokens; 873 if (hipGetDeviceProperties(&p, 0) != hipSuccess) { (void) hipGetLastError(); return false; } 874#ifdef _WIN32 875 const bool windows = true; 876#else 877 const bool windows = false; 878#endif 879 if (vit_gpu_hip_windows_not_measured(windows, p.gcnArchName)) { 880 why = std::string(p.gcnArchName) + " on Windows: the own HIP tower is not measured with the Windows ROCm package yet, mtmd stays"; 881 return true; 882 } 883 return false; 884#else 885 cudaDeviceProp p; 886 if (cudaGetDeviceProperties(&p, 0) != cudaSuccess) { (void) cudaGetLastError(); return false; } 887 if (vit_gpu_slower_nvidia(p.major, p.minor, bf16_matrices, max_tokens)) { 888 why = "compute capability " + std::to_string(p.major) + "." + std::to_string(p.minor) + " (Pascal): the own GPU tower is not measured there, mtmd stays"; 889 return true; 890 } 891 return false; 892#endif 893} 894 895bool VitGpu::load(const Gguf& gg, const VitGeometry& g, int device, int max_patches, std::string& err) { 896 VitGpuImpl& m = *impl_; 897 std::string why; 898 if (!vit_geometry_supported(g, why)) { err = "this tower is not supported: " + why; return false; } 899 m.g = g; 900 m.device = device; 901#if defined(STRATA_VIT_HIP) 902 bool fa_default = false; // the fused attention is the default on gfx1151 (below); STRATA_VIT_FA overrides it either way 903#endif 904#if !defined(STRATA_VIT_HIP) 905 bool pascal = false; 906 { // Pascal (compute capability 6.x): the larger score chunk below; BF16 matrices take K_HF as on every other CUDA card (see bf16_mode) 907 cudaDeviceProp p; 908 if (cudaGetDeviceProperties(&p, device) == cudaSuccess && p.major == 6) pascal = true; 909 (void) cudaGetLastError(); 910 } 911#else 912 { // gfx1151 (Strix Halo): every product with a 16-bit result and float32 accumulation, BF16 matrices held as F16, so all of them run rocBLAS's tuned 913 // HH_HPA kernels (F16 results, 10-bit mantissa). Strix, 18 pictures at 1,024 tokens: Qwen3.8 0.54-0.83 of mtmd-HIP's time (median 0.66), Qwen3.6 914 // 0.57-0.91 (median 0.67), rule 1 and 2 pass on both, byte-identical in and across processes; the BF16 results of BB_HPA missed rule 1 on 3 of the 915 // Qwen3.8 pictures and rule 2 on 3 (RESULTS-OWN-3V.md PART F2/F3). STRATA_VIT_HPA16, STRATA_VIT_HPA16_ATT and STRATA_VIT_BF16_AS_F16 = 0 turn each off. 916 // The fused attention k_attn_fa_gfx11 is on by default there too (Strix, RESULTS-OWN-3V.md PART F8): attention 0.50 of the default's time on the 1,024-token 917 // picture, the whole picture 0.84-0.90, rule 1 and 2 on 18 of 18 pictures on both models, byte-identical in and across processes, longest launch 6 ms 918 // (17 ms at 65,536 patches, which read 0.999693 against mtmd-CPU). STRATA_VIT_FA=0 turns it off. gfx1151 only: gfx1103 and the other gfx11 cards keep it off 919 // until they have their own gate. 920 hipDeviceProp_t p; 921 if (hipGetDeviceProperties(&p, device) == hipSuccess && vit_gpu_is_gfx1151(p.gcnArchName)) { 922 m.bf16_mode = BF16_ROUNDED; 923 m.hpa16 = m.hpa16_att = true; 924 fa_default = p.warpSize == 32 && g.head_dim <= 96 && g.head_dim % 8 == 0; 925 } 926 (void) hipGetLastError(); 927 } 928#endif 929 m.bf16_mode = vit_gpu_bf16_mode(std::getenv("STRATA_VIT_BF16_AS_F16"), m.bf16_mode); 930 m.trace = std::getenv("STRATA_TRACE") != nullptr; 931 { 932 const cudaError_t se = set_device_retrying(device); 933 if (se != cudaSuccess) { err = std::string("cannot use GPU ") + std::to_string(device) + ": " + cudaGetErrorString(se); return false; } 934 } 935 if (cublasCreate(&m.blas) != CUBLAS_STATUS_SUCCESS) { err = "cannot create the BLAS handle"; return false; } 936#if defined(STRATA_VIT_HIPBLASLT) 937 m.lt_setup(); 938#endif 939#if defined(STRATA_VIT_HIP) 940 if (const char* e = std::getenv("STRATA_VIT_HPA16")) m.hpa16 = std::atoi(e) != 0; 941 if (const char* e = std::getenv("STRATA_VIT_HPA16_ATT")) m.hpa16_att = std::atoi(e) != 0; 942 if (m.hpa16 || m.hpa16_att) 943 std::fprintf(stderr, "vit-hpa16: 16-bit results with float32 accumulation for %s%s%s\n", m.hpa16 ? "the weight products" : "", 944 m.hpa16 && m.hpa16_att ? " and " : "", m.hpa16_att ? "the attention's P*V product" : ""); 945 bool want_fa = fa_default; 946 if (const char* e = std::getenv("STRATA_VIT_FA")) want_fa = std::atoi(e) != 0; 947 if (want_fa) { 948 hipDeviceProp_t p; 949 if (hipGetDeviceProperties(&p, device) == hipSuccess && std::string(p.gcnArchName).rfind("gfx11", 0) == 0 && p.warpSize == 32 && g.head_dim <= 96 && g.head_dim % 8 == 0) 950 m.fa = true; 951 (void) hipGetLastError(); 952 std::fprintf(stderr, "vit-fa: fused attention %s\n", m.fa ? "on (gfx11 WMMA)" : "asked for but not available on this card (gfx11, wave32, head size <= 96 and a multiple of 8 only)"); 953 } 954 if (const char* e = std::getenv("STRATA_VIT_FA_UNITS")) { const long long u = std::atoll(e); if (u >= (1LL << 20)) m.fa_units = u; } 955#endif 956 // the patch embedding: the two temporal taps summed, kept in float32 (a small matrix) 957 { 958 const GgufTensorInfo* t0 = gg.tensor("v.patch_embd.weight"); 959 if (!t0) { err = "the mmproj file lacks v.patch_embd.weight"; return false; } 960 std::vector<float> w0((size_t) t0->nelem()), w1; 961 if (!gg.read_f32(*t0, w0.data(), err)) return false; 962 if (g.patch_taps == 2) { 963 const GgufTensorInfo* t1 = gg.tensor("v.patch_embd.weight.1"); 964 w1.resize(w0.size()); 965 if (!t1 || !gg.read_f32(*t1, w1.data(), err)) { if (err.empty()) err = "the mmproj file lacks v.patch_embd.weight.1"; return false; } 966 for (size_t i = 0; i < w0.size(); ++i) w0[i] += w1[i]; 967 } 968 if (!m.alloc(m.patch_w, w0.size(), err, true)) return false; 969 if (cudaMemcpy(m.patch_w, w0.data(), w0.size() * 4, cudaMemcpyHostToDevice) != cudaSuccess) { err = "GPU copy failed"; return false; } 970 } 971 if (!m.upload_f32(m.patch_b, gg, "v.patch_embd.bias", err) || !m.upload_f32(m.pos, gg, "v.position_embd.weight", err) || 972 !m.upload_f32(m.post_w, gg, "v.post_ln.weight", err) || !m.upload_f32(m.post_b, gg, "v.post_ln.bias", err) || 973 !m.upload_matrix(m.mm0, gg, "mm.0.weight", err) || !m.upload_f32(m.mm0_b, gg, "mm.0.bias", err) || 974 !m.upload_matrix(m.mm2, gg, "mm.2.weight", err) || !m.upload_f32(m.mm2_b, gg, "mm.2.bias", err)) 975 return false; 976 m.layers.assign((size_t) g.layers, DevLayer{}); 977 for (int il = 0; il < g.layers; ++il) { 978 DevLayer& L = m.layers[(size_t) il]; 979 const std::string p = "v.blk." + std::to_string(il) + "."; 980 if (!m.upload_f32(L.ln1_w, gg, p + "ln1.weight", err) || !m.upload_f32(L.ln1_b, gg, p + "ln1.bias", err) || 981 !m.upload_f32(L.ln2_w, gg, p + "ln2.weight", err) || !m.upload_f32(L.ln2_b, gg, p + "ln2.bias", err) || 982 !m.upload_matrix(L.qkv, gg, p + "attn_qkv.weight", err) || !m.upload_f32(L.qkv_b, gg, p + "attn_qkv.bias", err) || 983 !m.upload_matrix(L.o, gg, p + "attn_out.weight", err) || !m.upload_f32(L.o_b, gg, p + "attn_out.bias", err) || 984 !m.upload_matrix(L.up, gg, p + "ffn_up.weight", err) || !m.upload_f32(L.up_b, gg, p + "ffn_up.bias", err) || 985 !m.upload_matrix(L.down, gg, p + "ffn_down.weight", err) || !m.upload_f32(L.down_b, gg, p + "ffn_down.bias", err)) 986 return false; 987 } 988 m.n_weight_allocs = m.allocs.size(); 989 if (m.trace && !m.f16_notes.empty()) { 990 for (const VitGpuImpl::F16Note& f : m.f16_notes) 991 std::fprintf(stderr, "vit-f16 trace: %s %s, %lld of %lld weights not exact in F16 (%lld beyond its range), largest error %.3g\n", f.name.c_str(), 992 f.kind == K_HF ? "F16" : "BF16", f.c.not_exact, f.n, f.c.overflow, f.c.max_abs_error); 993 } 994#if !defined(STRATA_VIT_HIP) 995 // Pascal with 16-bit matrices (F16, or BF16 held as F16): a 32M-score attention chunk (64 MB): the P*V product's tile is only partly used with a head 996 // size of 72, and more queries per product made a 1,024-token picture 1,242 -> 1,064 ms on a P100 (BF16 file: at 1,362 MiB against mtmd-GPU's 1,364; 997 // RESULTS-OWN-3V.md 16.1). F16 file (Qwen3.6) on a P100: 1,243 -> 1,064 ms, 270 -> 263 ms at 350 tokens, rule 1 unchanged (min / mean 0.999865 / 0.999969 on 18 pictures) 998 // (RESULTS-OWN-3V.md PART G), 48 MB more than the 16 MB chunk. 999 if (pascal && !m.layers.empty() && (m.layers[0].qkv.kind == K_BH || m.layers[0].qkv.kind == K_HF || m.layers[0].qkv.kind == K_F16)) m.kScoreElems = (size_t) 32 << 20; 1000#endif 1001 if (const char* e = std::getenv("STRATA_VIT_REF_ROUND")) m.round_out = std::atoi(e) != 0; 1002 if (const char* e = std::getenv("STRATA_VIT_ROWS")) { const int v = std::atoi(e); if (v >= 16) m.kRows = v; } 1003 if (const char* e = std::getenv("STRATA_VIT_SCORES")) { const int v = std::atoi(e); if (v >= 1) { m.kScoreElems = (size_t) v << 20; m.scores_env = true; } } 1004 // STRATA_VIT_SCORES_LARGE (M elements, a diagnostic): the chunk above 16,384 patches; a size the GPU cannot hold tests the fallback to the default chunk 1005 if (const char* e = std::getenv("STRATA_VIT_SCORES_LARGE")) { const long v = std::atol(e); if (v >= 1) m.kScoreElemsLarge = (size_t) v << 20; } 1006 if (const char* e = std::getenv("STRATA_VIT_NPAD")) { const int v = std::atoi(e); if (v >= 8 && v % 8 == 0) m.n_pad = v; } 1007 if (const char* e = std::getenv("STRATA_VIT_QALIGN")) { const int v = std::atoi(e); if (v >= 1) m.q_align = v; } 1008 return m.size_buffers(std::max(max_patches, 16), err); 1009} 1010 1011bool VitGpu::encode(const PreparedImage& img, std::vector<float>& rows, int& nx, int& ny, std::string& err) { 1012 VitGpuImpl& m = *impl_; 1013 const VitGeometry& g = m.g; 1014 if (m.layers.empty()) { err = "the tower is not loaded"; return false; } 1015 if (img.w <= 0 || img.h <= 0 || img.w % g.align() != 0 || img.h % g.align() != 0) { err = "the picture size is not a multiple of patch * merge"; return false; } 1016 if (g.head_dim > 96 || g.head_dim % 4 != 0) { err = "this head size is not handled by the GPU attention kernel"; return false; } 1017 const int P = g.patch, D = g.width, H = g.heads, HD = g.head_dim, F = g.ffn; 1018 const int pw = img.w / P, ph = img.h / P, N = pw * ph, nbx = pw / 2; 1019 nx = pw / 2; 1020 ny = ph / 2; 1021 if (cudaSetDevice(m.device) != cudaSuccess) { err = "cannot use the GPU"; return false; } 1022 if (!m.size_buffers(N, err)) return false; 1023 auto sync_err = [&](const char* what) { 1024 const cudaError_t e = cudaGetLastError(); 1025 if (e != cudaSuccess) { err = std::string(what) + ": " + cudaGetErrorString(e); return false; } 1026 return true; 1027 }; 1028 // STRATA_VIT_PROF=1 (a diagnostic, stderr only, off by default): the time of each stage, the GPU synchronised after every stage 1029 static const bool prof = std::getenv("STRATA_VIT_PROF") != nullptr; 1030 double pt[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 1031 auto pclock = [] { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); }; 1032 double pmark = prof ? pclock() : 0.0; 1033 auto stage = [&](int i) { 1034 if (!prof) return; 1035 (void) cudaDeviceSynchronize(); 1036 const double now = pclock(); 1037 pt[i] += now - pmark; 1038 pmark = now; 1039 }; 1040 const int K0 = 3 * P * P; 1041 { // the patch matrix [N][K0], channel-major per patch, tokens in 2x2-merge order, built on the host; it lives in the context buffer (free until the first attention) 1042 std::vector<float> pm((size_t) N * K0); 1043 const size_t plane = (size_t) img.w * img.h; 1044 for (int t = 0; t < N; ++t) { 1045 const int b = t / 4, r = t % 4, py = 2 * (b / nbx) + r / 2, px = 2 * (b % nbx) + r % 2; 1046 float* a = &pm[(size_t) t * K0]; 1047 for (int c = 0; c < 3; ++c) 1048 for (int ky = 0; ky < P; ++ky) 1049 std::memcpy(a + (size_t) c * P * P + (size_t) ky * P, &img.chw[c * plane + (size_t) (py * P + ky) * img.w + (size_t) px * P], (size_t) P * sizeof(float)); 1050 } 1051 if (cudaMemcpy(m.d_ctx, pm.data(), pm.size() * 4, cudaMemcpyHostToDevice) != cudaSuccess) { err = "GPU copy failed"; return false; } 1052 } 1053 stage(0); 1054 // patch embedding (float32 GEMM), then bias + position 1055 DevW pw_w; 1056 pw_w.p = m.patch_w; pw_w.kind = K_F32; pw_w.rows = D; pw_w.cols = K0; 1057 if (!m.gemm(pw_w, m.d_ctx, N, m.d_x, CUDA_R_32F, err)) return false; 1058 k_patch_post<<<N, 256>>>(m.d_x, m.patch_b, m.pos, g.pos_grid, pw, ph, nbx, D); 1059 if (!sync_err("patch embedding")) return false; 1060 stage(1); 1061 1062 const float theta_scale = powf(g.rope_theta, -2.0f / (float) (HD / 2)); 1063 const float kq_scale = 1.0f / sqrtf((float) HD); 1064 const int R = m.kRows; 1065 uint16_t* const a16 = m.d_a; 1066 for (const DevLayer& L : m.layers) { 1067 for (int r0 = 0; r0 < N; r0 += R) { // the fused projection in chunks of rows (norm, product); q and k get their rotary, all three go to F16 1068 const int rows = std::min(R, N - r0); 1069 k_layernorm<<<rows, 256>>>(m.d_x + (size_t) r0 * D, L.ln1_w, L.ln1_b, g.eps, D, a16, (int) L.qkv.kind); 1070 if (!m.gemm(L.qkv, a16, rows, m.d_y, VitGpuImpl::dtype(L.qkv.kind), err)) return false; 1071 k_qkv_rope<<<rows, 256>>>(m.d_y, L.qkv_b, r0, nbx, H, HD, theta_scale, kq_scale, m.d_q16, m.d_k16, m.d_v16); 1072 } 1073 stage(2); 1074 // per chunk of queries: S = K Q^T (one batched product over the heads), softmax, O = V P (a head's matrix is a column slice of the [N][D] arrays: 1075 // leading dimension D, batch stride HD) 1076 const int Np = (int) m.padded((size_t) N); // the score rows' leading dimension (see size_buffers) 1077 int QC = (int) std::max<size_t>(1, std::min<size_t>((size_t) N, m.sp_elems / ((size_t) H * Np))); 1078 const int qa = m.align_for((size_t) N); 1079 if (qa > 1 && QC < N && QC >= qa) QC -= QC % qa; 1080#if defined(STRATA_VIT_HIP) 1081 if (m.fa) { // the fused attention, in launches of at most fa_units query x key x head triples (multiples of 64 queries) 1082 long long qf = std::max<long long>(kFaQ, m.fa_units / ((long long) N * H)); 1083 qf = std::min<long long>((qf / kFaQ) * kFaQ, ((long long) N + kFaQ - 1) / kFaQ * kFaQ); 1084 const int NT = (HD + 15) / 16; 1085 for (int q0 = 0; q0 < N; q0 += (int) qf) { 1086 const int qc = (int) std::min<long long>(qf, N - q0); 1087 const dim3 grid((unsigned) ((qc + kFaQ - 1) / kFaQ), (unsigned) H); 1088 const double t0 = prof ? pclock() : 0.0; 1089 switch (NT) { 1090 case 1: k_attn_fa_gfx11<1><<<grid, 128>>>(m.d_q16, m.d_k16, m.d_v16, m.d_ctx, N, q0, qc, D, HD); break; 1091 case 2: k_attn_fa_gfx11<2><<<grid, 128>>>(m.d_q16, m.d_k16, m.d_v16, m.d_ctx, N, q0, qc, D, HD); break; 1092 case 3: k_attn_fa_gfx11<3><<<grid, 128>>>(m.d_q16, m.d_k16, m.d_v16, m.d_ctx, N, q0, qc, D, HD); break; 1093 case 4: k_attn_fa_gfx11<4><<<grid, 128>>>(m.d_q16, m.d_k16, m.d_v16, m.d_ctx, N, q0, qc, D, HD); break; 1094 case 5: k_attn_fa_gfx11<5><<<grid, 128>>>(m.d_q16, m.d_k16, m.d_v16, m.d_ctx, N, q0, qc, D, HD); break; 1095 default: k_attn_fa_gfx11<6><<<grid, 128>>>(m.d_q16, m.d_k16, m.d_v16, m.d_ctx, N, q0, qc, D, HD); break; 1096 } 1097 if (prof) { 1098 (void) cudaDeviceSynchronize(); 1099 m.fa_longest_ms = std::max(m.fa_longest_ms, pclock() - t0); 1100 } 1101 } 1102 if (!sync_err("the fused attention")) return false; 1103 } else 1104#endif 1105 for (int q0 = 0; q0 < N; q0 += QC) { 1106 const int qc = std::min(QC, N - q0); 1107 if (!m.bgemm(true, false, N, qc, HD, m.d_k16, CUDA_R_16F, D, HD, m.d_q16 + (size_t) q0 * D, CUDA_R_16F, D, HD, m.d_S, CUDA_R_16F, Np, 1108 (long long) qc * Np, H, err)) 1109 return false; 1110 stage(8); 1111 if (N <= kSoftmaxThreads * kSoftmaxPer) softmax_rows(m.d_S, N, Np, H * qc); 1112 else k_softmax_rows_long<<<H * qc, kSoftmaxThreads>>>(m.d_S, N, Np); 1113 stage(9); 1114 if (!m.bgemm(false, false, HD, qc, N, m.d_v16, CUDA_R_16F, D, HD, m.d_S, CUDA_R_16F, Np, (long long) qc * Np, m.d_ctx + (size_t) q0 * D, 1115 CUDA_R_32F, D, HD, H, err)) 1116 return false; 1117 } 1118 stage(3); 1119 for (int r0 = 0; r0 < N; r0 += R) { // the output projection in chunks: the context rows to the 16-bit input, the product, added to the residual 1120 const int rows = std::min(R, N - r0); 1121 k_cast<<<VitGpuImpl::blocks_for((size_t) rows * D), 256>>>(m.d_ctx + (size_t) r0 * D, (size_t) rows * D, a16, (int) L.o.kind); 1122 if (!m.gemm(L.o, a16, rows, m.d_y, VitGpuImpl::dtype(L.o.kind), err)) return false; 1123 k_add_bias_res<<<rows, 256>>>(m.d_x + (size_t) r0 * D, m.d_y, L.o_b, D); 1124 } 1125 stage(4); 1126 for (int r0 = 0; r0 < N; r0 += R) { // the feed-forward block in chunks: norm, up, GELU, down, added to the residual 1127 const int rows = std::min(R, N - r0); 1128 k_layernorm<<<rows, 256>>>(m.d_x + (size_t) r0 * D, L.ln2_w, L.ln2_b, g.eps, D, a16, (int) L.up.kind); 1129 if (!m.gemm(L.up, a16, rows, m.d_y, VitGpuImpl::dtype(L.up.kind), err)) return false; 1130 k_bias_gelu_cast<<<rows, 256>>>(m.d_y, L.up_b, F, m.d_f16, (int) L.down.kind); 1131 if (!m.gemm(L.down, m.d_f16, rows, m.d_y, VitGpuImpl::dtype(L.down.kind), err)) return false; 1132 k_add_bias_res<<<rows, 256>>>(m.d_x + (size_t) r0 * D, m.d_y, L.down_b, D); 1133 } 1134 stage(5); 1135 } 1136 if (!sync_err("the layers")) return false; 1137 // post norm (into the merger's input kind), then the merger on 4-patch rows, in chunks 1138 const int M = N / 4, RM = std::max(1, R / 4); // a chunk of RM merged rows is 4 * RM tokens: R rows of the 16-bit input 1139 for (int r0 = 0; r0 < M; r0 += RM) { 1140 const int rows = std::min(RM, M - r0); 1141 k_layernorm<<<rows * 4, 256>>>(m.d_x + (size_t) r0 * 4 * D, m.post_w, m.post_b, g.eps, D, a16, (int) m.mm0.kind); 1142 if (!m.gemm(m.mm0, a16, rows, m.d_y, VitGpuImpl::dtype(m.mm0.kind), err)) return false; 1143 k_bias_gelu_cast<<<rows, 256>>>(m.d_y, m.mm0_b, g.merger_hidden, m.d_f16, (int) m.mm2.kind); 1144 if (!m.gemm(m.mm2, m.d_f16, rows, m.d_out + (size_t) r0 * g.out_dim, VitGpuImpl::dtype(m.mm2.kind), err)) return false; 1145 k_add_bias<<<rows, 256>>>(m.d_out + (size_t) r0 * g.out_dim, m.mm2_b, g.out_dim); 1146 } 1147 if (!sync_err("the projector")) return false; 1148 stage(6); 1149 rows.resize((size_t) M * g.out_dim); 1150 if (cudaMemcpy(rows.data(), m.d_out, rows.size() * 4, cudaMemcpyDeviceToHost) != cudaSuccess) { err = std::string("GPU copy failed: ") + cudaGetErrorString(cudaGetLastError()); return false; } 1151 stage(7); 1152 if (prof) 1153 std::fprintf(stderr, "vit-prof N=%d: patch-matrix %.2f, patch-embed %.2f, ln+qkv %.2f, attention %.2f (S product %.2f, softmax %.2f), o-proj %.2f, ffn %.2f, merger %.2f, copy-out %.2f ms\n", N, pt[0], pt[1], pt[2], 1154 pt[3] + pt[8] + pt[9], pt[8], pt[9], pt[4], pt[5], pt[6], pt[7]); 1155#if defined(STRATA_VIT_HIP) 1156 if (prof && m.fa) { 1157 std::fprintf(stderr, "vit-prof fa: longest fused-attention launch %.2f ms (STRATA_VIT_FA_UNITS %lld)\n", m.fa_longest_ms, m.fa_units); 1158 m.fa_longest_ms = 0.0; 1159 } 1160#endif 1161 return true; 1162} 1163 1164} // namespace strata_vit