okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4ef5079f5
main
1// tools/vision/own/vit_sycl.cpp - the VitGpu class (vit_gpu.h) on an Intel GPU: SYCL kernels and oneMKL products (own-stack phase 3, OWN-3V part B). 2// 3// A line-for-line counterpart of vit_gpu.cu (CUDA / HIP): the same host flow, weights as stored (BF16 / F16; F32 matrices become BF16, Q8_0 becomes F16), the same 4// row chunking, the same 16-bit types (F16 q, k, v with 1/sqrt(head size) in q, F16 scores turned into F16 probabilities in place, float32 residual stream, 5// 16-bit product inputs with float32 results) and the same diagnostics (STRATA_VIT_REF_ROUND, STRATA_VIT_ROWS, STRATA_VIT_SCORES, STRATA_VIT_PROF). 6// Two differences, both forced by oneMKL on the Arc (RESULTS-OWN-3V.md 11): 7// - the P*V product writes the attention context head by head, ctx[h][token][j] (oneMKL refuses batched outputs that interleave), and the o-projection's 8// cast reads it back into the token-major 16-bit input (the same numbers); 9// - the score chunk is larger than on CUDA (oneMKL's batched products with an inner size of 72 are slow on small chunks), sized so the reader's device memory 10// stays at or below mtmd-SYCL's. 11// No atomics: every reduction is a work-group reduction of a fixed work-group size, and oneMKL gave one result in eight launches on every shape used here. 12#include "vit_gpu.h" 13 14#include <sycl/sycl.hpp> 15#include <oneapi/mkl.hpp> 16 17#include <algorithm> 18#include <cfloat> 19#include <chrono> 20#include <cmath> 21#include <cstdint> 22#include <cstdio> 23#include <cstdlib> 24#include <cstring> 25 26namespace strata_vit { 27 28namespace { 29 30namespace blas= oneapi::mkl::blas::column_major; 31using oneapi::mkl::transpose ; 32using half = sycl::half ; 33using bf16 = sycl::ext::oneapi::bfloat16 ; 34 35enum Kind {K_F32 = 0 ,K_F16 = 1 ,K_BF16 = 2 };// the 16-bit kind a product's input takes (its weight's) 36 37struct DevW {// a weight matrix [rows = out][cols = in] on the device 38void * p = nullptr ; 39Kind kind = K_BF16 ; 40int rows = 0 ,cols = 0 ; 41}; 42 43struct DevLayer { 44float * ln1_w = nullptr ,* ln1_b = nullptr ,* ln2_w = nullptr ,* ln2_b = nullptr ,* qkv_b = nullptr ,* o_b = nullptr ,* up_b = nullptr ,* down_b = nullptr ; 45DevW qkv ,o ,up ,down ; 46}; 47 48inline uint16_t f_to_bf16 (float f ) {// round to nearest even 49uint32_t u = sycl::bit_cast < uint32_t > (f ); 50if ((u & 0x7fffffffu )> 0x7f800000u )return (uint16_t ) ((u >>16 ) |0x40 );// NaN stays NaN 51u += 0x7fffu + ((u >>16 )& 1u ); 52return (uint16_t ) (u >>16 ); 53} 54inline uint16_t f_to_f16bits (float f ) {return sycl::bit_cast < uint16_t > (half (f )); } 55inline float f16bits_to_f (uint16_t u ) {return (float ) sycl::bit_cast < half > (u ); } 56 57inline void store_kind (void * out ,size_t i ,float v ,int kind ) { 58if (kind == K_F32 ) ((float * )out )[i ]= v ; 59else if (kind == K_F16 ) ((uint16_t * )out )[i ]= f_to_f16bits (v ); 60else ((uint16_t * )out )[i ]= f_to_bf16 (v ); 61} 62 63constexpr int kSoftmaxThreads = 256 ,kSoftmaxPer = 64 ; 64 65uint16_t host_f32_to_bf16 (float f ) { 66uint32_t u ; 67 std::memcpy (& u ,& f ,4 ); 68if ((u & 0x7fffffffu )> 0x7f800000u )return (uint16_t ) ((u >>16 ) |0x40 ); 69u += 0x7fffu + ((u >>16 )& 1u ); 70return (uint16_t ) (u >>16 ); 71} 72uint16_t host_f32_to_f16 (float f ) { 73const half h (f ); 74uint16_t u ; 75 std::memcpy (& u ,& h ,2 ); 76return u ; 77} 78 79// ---- kernels (the CUDA kernels of vit_gpu.cu; one work-group of `T` items per row unless said otherwise) ---- 80 81// x[t] += patch bias + the position table resized (bilinear, align corners) to the token's grid position 82void k_patch_post (sycl::queue & q ,float * x ,const float * bias ,const float * pos ,int G ,int pw ,int ph ,int nbx ,int D ,int N ) { 83q .parallel_for (sycl::nd_range < 1 > ((size_t )N * 256 ,256 ), [= ](sycl::nd_item < 1 > it ) { 84const int t = (int )it .get_group (0 ),b = t /4 ,r = t %4 ; 85const int ty = 2 * (b /nbx )+ r /2 ,tx = 2 * (b %nbx )+ r %2 ; 86float sfx = (float )pw /G ,sfy = (float )ph /G ; 87if (pw > 1 && G > 1 )sfx = (float ) (pw - 1 ) / (G - 1 ); 88if (ph > 1 && G > 1 )sfy = (float ) (ph - 1 ) / (G - 1 ); 89const float fy = (float )ty /sfy ,fx = (float )tx /sfx ; 90int y0 = (int ) sycl::floor (fy ),x0 = (int ) sycl::floor (fx ),y1 = y0 + 1 ,x1 = x0 + 1 ; 91y0 = sycl::max (0 , sycl::min (y0 ,G - 1 ));y1 = sycl::max (0 , sycl::min (y1 ,G - 1 )); 92x0 = sycl::max (0 , sycl::min (x0 ,G - 1 ));x1 = sycl::max (0 , sycl::min (x1 ,G - 1 )); 93const float dy = sycl::fmax (0.0f , sycl::fmin (fy - (float )y0 ,1.0f )),dx = sycl::fmax (0.0f , sycl::fmin (fx - (float )x0 ,1.0f )); 94const float * a = pos + ((size_t )y0 * G + x0 )* D ; 95const float * bb = pos + ((size_t )y0 * G + x1 )* D ; 96const float * c = pos + ((size_t )y1 * G + x0 )* D ; 97const float * d = pos + ((size_t )y1 * G + x1 )* D ; 98float * xr = x + (size_t )t * D ; 99for (int i = (int )it .get_local_id (0 );i < D ;i += 256 ) 100xr [i ]+= bias [i ]+ (a [i ]* (1 - dx )* (1 - dy )+ bb [i ]* dx * (1 - dy )+ c [i ]* (1 - dx )* dy + d [i ]* dx * dy ); 101 }); 102} 103 104// out = LayerNorm(x) * w + b, into `kind`; rows rows of D 105void k_layernorm (sycl::queue & q ,const float * x ,const float * w ,const float * b ,float eps ,int D ,void * out ,int kind ,int rows ) { 106q .parallel_for (sycl::nd_range < 1 > ((size_t )rows * 256 ,256 ), [= ](sycl::nd_item < 1 > it ) { 107const size_t row = it .get_group (0 ); 108const int lid = (int )it .get_local_id (0 ); 109const float * xr = x + row * D ; 110float s = 0.0f ; 111for (int i = lid ;i < D ;i += 256 )s += xr [i ]; 112const float mean = sycl::reduce_over_group (it .get_group (),s , sycl::plus < float > ()) / (float )D ; 113float v = 0.0f ; 114for (int i = lid ;i < D ;i += 256 ) {const float d = xr [i ]- mean ;v += d * d ; } 115const float scale = sycl::rsqrt (sycl::reduce_over_group (it .get_group (),v , sycl::plus < float > ()) / (float )D + eps ); 116for (int i = lid ;i < D ;i += 256 )store_kind (out ,row * D + i , (xr [i ]- mean )* scale * w [i ]+ b [i ],kind ); 117 }); 118} 119 120// y [rows][3D] (the fused qkv product of the tokens row0 ..) + bias -> q, k (rotary applied), v, each [N][D] in F16 121void k_qkv_rope (sycl::queue & q ,const float * y ,const float * bias ,int row0 ,int nbx ,int heads ,int hd ,float theta_scale ,float qscale ,uint16_t * qo ,uint16_t * ko , 122uint16_t * vo ,int rows ) { 123q .parallel_for (sycl::nd_range < 1 > ((size_t )rows * 256 ,256 ), [= ](sycl::nd_item < 1 > it ) { 124const int t = row0 + (int )it .get_group (0 ),D = heads * hd ,half_ = hd /2 ,quarter = hd /4 ; 125const int b = t /4 ,r = t %4 ; 126const int ty = 2 * (b /nbx )+ r /2 ,tx = 2 * (b %nbx )+ r %2 ; 127const float * yr = y + it .get_group (0 )* 3 * (size_t )D ; 128const int lid = (int )it .get_local_id (0 ); 129for (int i = lid ;i < 2 * heads * half_ ;i += 256 ) { 130const int part = i / (heads * half_ ),rem = i % (heads * half_ ),h = rem /half_ ,j = rem %half_ ; 131const int base = part * D + h * hd ; 132const float a = yr [base + j ]+ bias [base + j ],c = yr [base + j + half_ ]+ bias [base + j + half_ ]; 133const float freq = sycl::pow (theta_scale , (float ) (j %quarter )); 134const float ang = (float ) (j < quarter ?ty :tx )* freq ; 135const float sn = sycl::sin (ang ),cs = sycl::cos (ang ); 136uint16_t * dst = (part == 0 ?qo :ko )+ (size_t )t * D + h * hd ; 137const float sc = part == 0 ?qscale :1.0f ; 138dst [j ]= f_to_f16bits ((a * cs - c * sn )* sc ); 139dst [j + half_ ]= f_to_f16bits ((a * sn + c * cs )* sc ); 140 } 141for (int e = lid ;e < D ;e += 256 )vo [(size_t )t * D + e ]= f_to_f16bits (yr [2 * D + e ]+ bias [2 * D + e ]); 142 }); 143} 144 145// In place: rows of n F16 scores become F16 probabilities. T items and PER scores per item (T * PER >= n), the row held in registers. 146template < int T ,int PER > 147void k_softmax_rows (sycl::queue & q ,uint16_t * S ,int n ,int ld ,int rows ) { 148q .parallel_for (sycl::nd_range < 1 > ((size_t )rows * T ,T ), [= ](sycl::nd_item < 1 > it ) { 149uint16_t * s = S + it .get_group (0 )* (size_t )ld ; 150const int lid = (int )it .get_local_id (0 ); 151float v [PER ]; 152float m = - FLT_MAX ; 153#pragma unroll 154for (int k = 0 ;k < PER ;++ k ) { 155const int j = lid + k * T ; 156v [k ]= j < n ?f16bits_to_f (s [j ]) :- FLT_MAX ; 157m = sycl::fmax (m ,v [k ]); 158 } 159m = sycl::reduce_over_group (it .get_group (),m , sycl::maximum < float > ()); 160float sum = 0.0f ; 161#pragma unroll 162for (int k = 0 ;k < PER ;++ k ) { 163const int j = lid + k * T ; 164v [k ]= j < n ? sycl::exp (v [k ]- m ) :0.0f ; 165sum += v [k ]; 166 } 167sum = sycl::reduce_over_group (it .get_group (),sum , sycl::plus < float > ()); 168const float inv = 1.0f /sum ; 169#pragma unroll 170for (int k = 0 ;k < PER ;++ k ) { 171const int j = lid + k * T ; 172if (j < n )s [j ]= f_to_f16bits (v [k ]* inv ); 173 } 174 }); 175} 176 177void softmax_rows (sycl::queue & q ,uint16_t * S ,int n ,int ld ,int rows ) { 178if (n <=128 )k_softmax_rows < 64 ,2 > (q ,S ,n ,ld ,rows ); 179else if (n <=512 )k_softmax_rows < 64 ,8 > (q ,S ,n ,ld ,rows ); 180else if (n <=1024 )k_softmax_rows < 128 ,8 > (q ,S ,n ,ld ,rows ); 181else if (n <=4096 )k_softmax_rows < 256 ,16 > (q ,S ,n ,ld ,rows ); 182else k_softmax_rows < 256 ,64 > (q ,S ,n ,ld ,rows ); 183} 184 185// a row too long for registers (more than 16,384 patches): three passes over the row in memory 186void k_softmax_rows_long (sycl::queue & q ,uint16_t * S ,int n ,int ld ,int rows ) { 187q .parallel_for (sycl::nd_range < 1 > ((size_t )rows * kSoftmaxThreads ,kSoftmaxThreads ), [= ](sycl::nd_item < 1 > it ) { 188uint16_t * s = S + it .get_group (0 )* (size_t )ld ; 189const int lid = (int )it .get_local_id (0 ); 190float m = - FLT_MAX ; 191for (int j = lid ;j < n ;j += kSoftmaxThreads )m = sycl::fmax (m ,f16bits_to_f (s [j ])); 192m = sycl::reduce_over_group (it .get_group (),m , sycl::maximum < float > ()); 193float sum = 0.0f ; 194for (int j = lid ;j < n ;j += kSoftmaxThreads )sum += sycl::exp (f16bits_to_f (s [j ])- m ); 195sum = sycl::reduce_over_group (it .get_group (),sum , sycl::plus < float > ()); 196const float inv = 1.0f /sum ; 197for (int j = lid ;j < n ;j += kSoftmaxThreads )s [j ]= f_to_f16bits (sycl::exp (f16bits_to_f (s [j ])- m )* inv ); 198 }); 199} 200 201size_t grid_for (size_t n ) {return std::min < size_t > ((n + 255 ) /256 ,65535 )* 256 ; } 202 203// y[i] rounded to the 16-bit kind and back (STRATA_VIT_REF_ROUND) 204void k_round (sycl::queue & q ,float * y ,size_t n ,int kind ) { 205const size_t g = grid_for (n ); 206q .parallel_for (sycl::nd_range < 1 > (g ,256 ), [= ](sycl::nd_item < 1 > it ) { 207for (size_t i = it .get_global_id (0 );i < n ;i += g ) { 208const float v = y [i ]; 209y [i ]= kind == K_F16 ? (float )half (v ) : sycl::bit_cast < float > ((uint32_t )f_to_bf16 (v ) <<16 ); 210 } 211 }); 212} 213 214// the head-major attention context ctx[h][token][j] (N tokens) of rows r0 .. r0 + rows to the token-major 16-bit input out[r][h * hd + j] 215void k_cast_ctx (sycl::queue & q ,const float * ctx ,int N ,int heads ,int hd ,int r0 ,int rows ,void * out ,int kind ) { 216const int D = heads * hd ; 217q .parallel_for (sycl::nd_range < 1 > ((size_t )rows * 256 ,256 ), [= ](sycl::nd_item < 1 > it ) { 218const int r = (int )it .get_group (0 ); 219for (int e = (int )it .get_local_id (0 );e < D ;e += 256 ) { 220const int h = e /hd ,j = e %hd ; 221store_kind (out , (size_t )r * D + e ,ctx [((size_t )h * N + (size_t ) (r0 + r ))* hd + j ],kind ); 222 } 223 }); 224} 225 226// x[r] += y[r] + bias 227void k_add_bias_res (sycl::queue & q ,float * x ,const float * y ,const float * bias ,int D ,int rows ) { 228q .parallel_for (sycl::nd_range < 1 > ((size_t )rows * 256 ,256 ), [= ](sycl::nd_item < 1 > it ) { 229const size_t base = it .get_group (0 )* (size_t )D ; 230for (int i = (int )it .get_local_id (0 );i < D ;i += 256 )x [base + i ]+= y [base + i ]+ bias [i ]; 231 }); 232} 233 234// out = gelu_tanh(y + bias) into `kind` 235void k_bias_gelu_cast (sycl::queue & q ,const float * y ,const float * bias ,int n ,void * out ,int kind ,int rows ) { 236q .parallel_for (sycl::nd_range < 1 > ((size_t )rows * 256 ,256 ), [= ](sycl::nd_item < 1 > it ) { 237const size_t base = it .get_group (0 )* (size_t )n ; 238for (int i = (int )it .get_local_id (0 );i < n ;i += 256 ) { 239const float x = y [base + i ]+ bias [i ]; 240const float g = 0.5f * x * (1.0f + sycl::tanh (0.79788456080286535587989211986876f * x * (1.0f + 0.044715f * x * x ))); 241store_kind (out ,base + i ,g ,kind ); 242 } 243 }); 244} 245 246// y[r] += bias 247void k_add_bias (sycl::queue & q ,float * y ,const float * bias ,int n ,int rows ) { 248q .parallel_for (sycl::nd_range < 1 > ((size_t )rows * 256 ,256 ), [= ](sycl::nd_item < 1 > it ) { 249const size_t base = it .get_group (0 )* (size_t )n ; 250for (int i = (int )it .get_local_id (0 );i < n ;i += 256 )y [base + i ]+= bias [i ]; 251 }); 252} 253 254// the GPU this reader uses: the Level Zero (else any) GPU with the most memory; ONEAPI_DEVICE_SELECTOR filters the list 255bool pick_gpu (sycl::device & out , std::string & why ) { 256try { 257 std::vector < sycl::device > gpus = sycl::device::get_devices (sycl::info::device_type::gpu ); 258if (gpus .empty ()) {why = "no GPU found" ;return false; } 259auto score = [](const sycl::device & d ) { 260const bool l0 = d .get_backend ()== sycl::backend::ext_oneapi_level_zero ; 261return std::make_pair (l0 ?1 :0 , (unsigned long long )d .get_info < sycl::info::device::global_mem_size > ()); 262 }; 263out = * std::max_element (gpus .begin (),gpus .end (), [& ](const sycl::device & a ,const sycl::device & b ) {return score (a )< score (b ); }); 264if (!out .has (sycl::aspect::fp16 )) {why = "the GPU has no 16-bit float support" ;return false; } 265return true; 266 }catch (const sycl::exception & e ) { 267why = std::string ("no GPU runtime: " )+ e .what (); 268return false; 269 } 270} 271 272}// namespace 273 274struct VitGpuImpl { 275VitGeometry g ; 276 sycl::queue q ; 277 std::string async_err ;// the first asynchronous error the queue reported 278 std::vector < void *> allocs ;// every device allocation (weights and work buffers), freed in the destructor 279size_t bytes = 0 ,work_bytes = 0 ; 280size_t n_weight_allocs = 0 ; 281 282float * patch_w = nullptr ,* patch_b = nullptr ,* pos = nullptr ,* post_w = nullptr ,* post_b = nullptr ,* mm0_b = nullptr ,* mm2_b = nullptr ; 283DevW mm0 ,mm2 ; 284 std::vector < DevLayer > layers ; 285 286int cap_patches = 0 ; 287float * d_x = nullptr ,* d_ctx = nullptr ,* d_y = nullptr ,* d_out = nullptr ;// as vit_gpu.cu; d_ctx holds the context HEAD-MAJOR [H][N][HD] 288uint16_t * d_a = nullptr ,* d_f16 = nullptr ; 289uint16_t * d_q16 = nullptr ,* d_k16 = nullptr ,* d_v16 = nullptr ; 290uint16_t * d_S = nullptr ; 291size_t sp_elems = 0 ; 292int kRows = 512 ; 293// scores per attention chunk: 32M elements = 64 MB of F16 (CUDA: 8M). oneMKL's batched products with an inner size of 72 need wide chunks to be fast 294// on the Arc (RESULTS-OWN-3V.md 11.1); 64 MB keeps the reader at or below mtmd-SYCL's memory at 1,024 tokens. STRATA_VIT_SCORES (M elements) overrides. 295size_t kScoreElems = (size_t )32 <<20 ; 296size_t kScoreElemsLarge = (size_t )256 <<20 ;// above 16,384 patches: 256M scores (512 MB); A750, 16,384 tokens: 147.9 s at the 64-query floor, 118.3 s with 256M, 117.0 s with 512M 297bool scores_env = false;// STRATA_VIT_SCORES given: one size for every picture 298bool round_out = false; 299 300 ~VitGpuImpl () { 301try { 302q .wait (); 303 }catch (...) { 304 } 305for (void * p :allocs ) sycl::free (p ,q ); 306 } 307template < class T > bool alloc (T *& p ,size_t n , std::string & err ,bool weight ) { 308void * m = nullptr ; 309try { 310m = sycl::malloc_device (n * sizeof (T ),q ); 311 }catch (const sycl::exception & e ) { 312err = std::string ("GPU memory: " )+ e .what (); 313return false; 314 } 315if (!m ) {err = "GPU memory: out of device memory" ;return false; } 316p = (T * )m ; 317allocs .push_back (m ); 318bytes += n * sizeof (T ); 319if (!weight )work_bytes += n * sizeof (T ); 320return true; 321 } 322bool upload_f32 (float *& dst ,const Gguf & gg ,const std::string & name , std::string & err ) { 323const GgufTensorInfo * t = gg .tensor (name ); 324if (!t ) {err = "the mmproj file lacks the tensor " + name ;return false; } 325 std::vector < float > h ((size_t )t -> nelem ()); 326if (!gg .read_f32 (* t ,h .data (),err ))return false; 327if (!alloc (dst ,h .size (),err , true))return false; 328q .memcpy (dst ,h .data (),h .size ()* 4 ).wait (); 329return true; 330 } 331bool upload_matrix (DevW & w ,const Gguf & gg ,const std::string & name , std::string & err ) { 332const GgufTensorInfo * t = gg .tensor (name ); 333if (!t || t -> ne .size ()!= 2 ) {err = "the mmproj file lacks the matrix " + name ;return false; } 334w .cols = (int )t -> ne [0 ]; 335w .rows = (int )t -> ne [1 ]; 336const size_t n = (size_t )t -> nelem (); 337 std::vector < unsigned char > raw ; 338if (t -> type == GT_F16 || t -> type == GT_BF16 ) {// as stored 339raw .resize (n * 2 ); 340if (!gg .read_raw (* t ,raw .data (),err ))return false; 341w .kind = t -> type == GT_F16 ?K_F16 :K_BF16 ; 342 }else {// F32 -> BF16, Q8_0 -> F16 343 std::vector < float > f (n ); 344if (!gg .read_f32 (* t ,f .data (),err ))return false; 345raw .resize (n * 2 ); 346const bool bf = t -> type == GT_F32 ; 347w .kind = bf ?K_BF16 :K_F16 ; 348for (size_t i = 0 ;i < n ;++ i ) { 349const uint16_t u = bf ?host_f32_to_bf16 (f [i ]) :host_f32_to_f16 (f [i ]); 350 std::memcpy (& raw [i * 2 ],& u ,2 ); 351 } 352 } 353uint16_t * dev = nullptr ; 354if (!alloc (dev ,n ,err , true))return false; 355w .p = dev ; 356q .memcpy (w .p ,raw .data (),n * 2 ).wait (); 357return true; 358 } 359 360// y[M][w.rows] (float32) = A[M][w.cols] (kind of w) * w^T 361void gemm (const DevW & w ,const void * A ,int M ,float * y ) { 362const int m = w .rows ,k = w .cols ; 363if (w .kind == K_F32 ) 364 blas::gemm (q , transpose::trans , transpose::nontrans ,m ,M ,k ,1.0f , (const float * )w .p ,k , (const float * )A ,k ,0.0f ,y ,m ); 365else if (w .kind == K_F16 ) 366 blas::gemm (q , transpose::trans , transpose::nontrans ,m ,M ,k ,1.0f , (const half * )w .p ,k , (const half * )A ,k ,0.0f ,y ,m ); 367else 368 blas::gemm (q , transpose::trans , transpose::nontrans ,m ,M ,k ,1.0f , (const bf16 * )w .p ,k , (const bf16 * )A ,k ,0.0f ,y ,m ); 369if (round_out && w .kind != K_F32 )k_round (q ,y , (size_t )M * w .rows , (int )w .kind ); 370 } 371 372bool size_buffers (int patches , std::string & err ) { 373if (patches <=cap_patches )return true; 374q .wait (); 375for (size_t i = allocs .size ();i > n_weight_allocs ;-- i ) sycl::free (allocs [i - 1 ],q ); 376bytes -= work_bytes ; 377work_bytes = 0 ; 378allocs .resize (n_weight_allocs ); 379const size_t N = (size_t )patches ,D = (size_t )g .width ,F = (size_t ) std::max (g .ffn ,g .merger_hidden ); 380const size_t K0 = (size_t )3 * g .patch * g .patch ; 381d_x = d_y = d_ctx = d_out = nullptr ; 382d_a = d_f16 = d_q16 = d_k16 = d_v16 = nullptr ; 383d_S = nullptr ; 384const size_t Np = (N + 7 ) /8 * 8 ; 385const size_t budget = (N > 16384 && !scores_env ) ?kScoreElemsLarge :kScoreElems ; 386sp_elems = std::min < size_t > ((size_t )g .heads * N * Np , std::max < size_t > (budget , (size_t )g .heads * Np * 64 )); 387const size_t R = std::min < size_t > (N , (size_t )kRows ); 388const size_t ctx_elems = std::max ({N * D ,N * K0 , (N /4 )* (size_t )g .out_dim }); 389bool 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)&& 390alloc (d_a ,R * D ,err , false)&& alloc (d_f16 ,R * F ,err , false)&& 391alloc (d_q16 ,N * D ,err , false)&& alloc (d_k16 ,N * D ,err , false)&& alloc (d_v16 ,N * D ,err , false); 392if (ok && !alloc (d_S ,sp_elems ,err , false)) { 393// no room for the large chunk: the default chunk instead, slower, never an error 394ok = false; 395if (budget != kScoreElems ) { 396err .clear (); 397sp_elems = std::min < size_t > ((size_t )g .heads * N * Np , std::max < size_t > (kScoreElems , (size_t )g .heads * Np * 64 )); 398ok = alloc (d_S ,sp_elems ,err , false); 399 } 400 } 401d_out = d_ctx ; 402if (!ok ) {cap_patches = 0 ;return false; } 403cap_patches = patches ; 404return true; 405 } 406}; 407 408VitGpu ::VitGpu () :impl_ (new VitGpuImpl ()) {} 409VitGpu ::~VitGpu ()= default ; 410size_t VitGpu ::device_bytes ()const {return impl_ -> bytes ; } 411 412bool VitGpu ::available (std::string & why ) { 413 sycl::device d ; 414return pick_gpu (d ,why ); 415} 416 417bool VitGpu ::prefer_mtmd (bool bf16_matrices ,int max_tokens , std::string & why ) { 418 (void )bf16_matrices ; 419 (void )max_tokens ; 420 (void )why ; 421return false; 422} 423 424bool VitGpu ::load (const Gguf & gg ,const VitGeometry & g ,int device ,int max_patches , std::string & err ) { 425VitGpuImpl & m = * impl_ ; 426 (void )device ;// one GPU: the one pick_gpu chooses 427 std::string why ; 428if (!vit_geometry_supported (g ,why )) {err = "this tower is not supported: " + why ;return false; } 429m .g = g ; 430 sycl::device dev ; 431if (!pick_gpu (dev ,why )) {err = "cannot use the GPU: " + why ;return false; } 432try { 433 std::string * sink = & m .async_err ; 434m .q = sycl::queue (dev , [sink ](sycl::exception_list l ) { 435for (auto & e :l ) { 436try { 437 std::rethrow_exception (e ); 438 }catch (const std::exception & x ) { 439if (sink -> empty ())* sink = x .what (); 440 } 441 } 442 }, sycl::property::queue::in_order ()); 443 {// the patch embedding: the two temporal taps summed, kept in float32 (a small matrix) 444const GgufTensorInfo * t0 = gg .tensor ("v.patch_embd.weight" ); 445if (!t0 ) {err = "the mmproj file lacks v.patch_embd.weight" ;return false; } 446 std::vector < float > w0 ((size_t )t0 -> nelem ()),w1 ; 447if (!gg .read_f32 (* t0 ,w0 .data (),err ))return false; 448if (g .patch_taps == 2 ) { 449const GgufTensorInfo * t1 = gg .tensor ("v.patch_embd.weight.1" ); 450w1 .resize (w0 .size ()); 451if (!t1 || !gg .read_f32 (* t1 ,w1 .data (),err )) {if (err .empty ())err = "the mmproj file lacks v.patch_embd.weight.1" ;return false; } 452for (size_t i = 0 ;i < w0 .size ();++ i )w0 [i ]+= w1 [i ]; 453 } 454if (!m .alloc (m .patch_w ,w0 .size (),err , true))return false; 455m .q .memcpy (m .patch_w ,w0 .data (),w0 .size ()* 4 ).wait (); 456 } 457if (!m .upload_f32 (m .patch_b ,gg ,"v.patch_embd.bias" ,err )|| !m .upload_f32 (m .pos ,gg ,"v.position_embd.weight" ,err )|| 458 !m .upload_f32 (m .post_w ,gg ,"v.post_ln.weight" ,err )|| !m .upload_f32 (m .post_b ,gg ,"v.post_ln.bias" ,err )|| 459 !m .upload_matrix (m .mm0 ,gg ,"mm.0.weight" ,err )|| !m .upload_f32 (m .mm0_b ,gg ,"mm.0.bias" ,err )|| 460 !m .upload_matrix (m .mm2 ,gg ,"mm.2.weight" ,err )|| !m .upload_f32 (m .mm2_b ,gg ,"mm.2.bias" ,err )) 461return false; 462m .layers .assign ((size_t )g .layers ,DevLayer {}); 463for (int il = 0 ;il < g .layers ;++ il ) { 464DevLayer & L = m .layers [(size_t )il ]; 465const std::string p = "v.blk." + std::to_string (il )+ "." ; 466if (!m .upload_f32 (L .ln1_w ,gg ,p + "ln1.weight" ,err )|| !m .upload_f32 (L .ln1_b ,gg ,p + "ln1.bias" ,err )|| 467 !m .upload_f32 (L .ln2_w ,gg ,p + "ln2.weight" ,err )|| !m .upload_f32 (L .ln2_b ,gg ,p + "ln2.bias" ,err )|| 468 !m .upload_matrix (L .qkv ,gg ,p + "attn_qkv.weight" ,err )|| !m .upload_f32 (L .qkv_b ,gg ,p + "attn_qkv.bias" ,err )|| 469 !m .upload_matrix (L .o ,gg ,p + "attn_out.weight" ,err )|| !m .upload_f32 (L .o_b ,gg ,p + "attn_out.bias" ,err )|| 470 !m .upload_matrix (L .up ,gg ,p + "ffn_up.weight" ,err )|| !m .upload_f32 (L .up_b ,gg ,p + "ffn_up.bias" ,err )|| 471 !m .upload_matrix (L .down ,gg ,p + "ffn_down.weight" ,err )|| !m .upload_f32 (L .down_b ,gg ,p + "ffn_down.bias" ,err )) 472return false; 473 } 474m .n_weight_allocs = m .allocs .size (); 475if (const char * e = std::getenv ("STRATA_VIT_REF_ROUND" ))m .round_out = std::atoi (e )!= 0 ; 476if (const char * e = std::getenv ("STRATA_VIT_ROWS" )) {const int v = std::atoi (e );if (v >=16 )m .kRows = v ; } 477if (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; } } 478if (const char * e = std::getenv ("STRATA_VIT_SCORES_LARGE" )) {const long v = std::atol (e );if (v >=1 )m .kScoreElemsLarge = (size_t )v <<20 ; }// a diagnostic, as in vit_gpu.cu 479return m .size_buffers (std::max (max_patches ,16 ),err ); 480 }catch (const std::exception & e ) { 481err = std::string ("the GPU failed while loading the vision encoder: " )+ e .what (); 482return false; 483 } 484} 485 486bool VitGpu ::encode (const PreparedImage & img , std::vector < float >& rows ,int & nx ,int & ny , std::string & err ) { 487VitGpuImpl & m = * impl_ ; 488const VitGeometry & g = m .g ; 489if (m .layers .empty ()) {err = "the tower is not loaded" ;return false; } 490if (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; } 491if (g .head_dim > 96 || g .head_dim %4 != 0 ) {err = "this head size is not handled by the GPU attention kernel" ;return false; } 492const int P = g .patch ,D = g .width ,H = g .heads ,HD = g .head_dim ,F = g .ffn ; 493const int pw = img .w /P ,ph = img .h /P ,N = pw * ph ,nbx = pw /2 ; 494nx = pw /2 ; 495ny = ph /2 ; 496 sycl::queue & q = m .q ; 497try { 498if (!m .size_buffers (N ,err ))return false; 499static const bool prof = std::getenv ("STRATA_VIT_PROF" )!= nullptr ; 500double pt [11 ]= {0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 }; 501auto pclock = [] {return std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ().time_since_epoch ()).count (); }; 502double pmark = prof ?pclock () :0.0 ; 503auto stage = [& ](int i ) { 504if (!prof )return ; 505q .wait (); 506const double now = pclock (); 507pt [i ]+= now - pmark ; 508pmark = now ; 509 }; 510auto sync_err = [& ](const char * what ) { 511q .wait_and_throw (); 512if (!m .async_err .empty ()) {err = std::string (what )+ ": " + m .async_err ;m .async_err .clear ();return false; } 513return true; 514 }; 515const int K0 = 3 * P * P ; 516 {// the patch matrix [N][K0], channel-major per patch, tokens in 2x2-merge order, built on the host; it lives in the context buffer 517 std::vector < float > pm ((size_t )N * K0 ); 518const size_t plane = (size_t )img .w * img .h ; 519for (int t = 0 ;t < N ;++ t ) { 520const int b = t /4 ,r = t %4 ,py = 2 * (b /nbx )+ r /2 ,px = 2 * (b %nbx )+ r %2 ; 521float * a = & pm [(size_t )t * K0 ]; 522for (int c = 0 ;c < 3 ;++ c ) 523for (int ky = 0 ;ky < P ;++ ky ) 524 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 )); 525 } 526q .memcpy (m .d_ctx ,pm .data (),pm .size ()* 4 ).wait (); 527 } 528stage (0 ); 529DevW pw_w ; 530pw_w .p = m .patch_w ;pw_w .kind = K_F32 ;pw_w .rows = D ;pw_w .cols = K0 ; 531m .gemm (pw_w ,m .d_ctx ,N ,m .d_x ); 532k_patch_post (q ,m .d_x ,m .patch_b ,m .pos ,g .pos_grid ,pw ,ph ,nbx ,D ,N ); 533if (!sync_err ("patch embedding" ))return false; 534stage (1 ); 535 536const float theta_scale = std::pow (g .rope_theta ,-2.0f / (float ) (HD /2 )); 537const float kq_scale = 1.0f / std::sqrt ((float )HD ); 538const int R = m .kRows ; 539uint16_t * const a16 = m .d_a ; 540for (const DevLayer & L :m .layers ) { 541for (int r0 = 0 ;r0 < N ;r0 += R ) { 542const int rows_ = std::min (R ,N - r0 ); 543k_layernorm (q ,m .d_x + (size_t )r0 * D ,L .ln1_w ,L .ln1_b ,g .eps ,D ,a16 , (int )L .qkv .kind ,rows_ ); 544m .gemm (L .qkv ,a16 ,rows_ ,m .d_y ); 545k_qkv_rope (q ,m .d_y ,L .qkv_b ,r0 ,nbx ,H ,HD ,theta_scale ,kq_scale ,m .d_q16 ,m .d_k16 ,m .d_v16 ,rows_ ); 546 } 547stage (2 ); 548// per chunk of queries: S = K Q^T (one batched product over the heads), softmax, O = V P written head-major (ctx[h][token][j]) 549const int Np = (N + 7 ) /8 * 8 ; 550const int QC = (int ) std::max < size_t > (1 , std::min < size_t > ((size_t )N ,m .sp_elems / ((size_t )H * Np ))); 551for (int q0 = 0 ;q0 < N ;q0 += QC ) { 552const int qc = std::min (QC ,N - q0 ); 553 blas::gemm_batch (q , transpose::trans , transpose::nontrans ,N ,qc ,HD ,half (1.0f ), (const half * )m .d_k16 ,D ,HD , (const half * ) (m .d_q16 + (size_t )q0 * D ),D , 554HD ,half (0.0f ), (half * )m .d_S ,Np , (int64_t )qc * Np ,H ); 555stage (8 ); 556if (N <=kSoftmaxThreads * kSoftmaxPer )softmax_rows (q ,m .d_S ,N ,Np ,H * qc ); 557else k_softmax_rows_long (q ,m .d_S ,N ,Np ,H * qc ); 558stage (9 ); 559 blas::gemm_batch (q , transpose::nontrans , transpose::nontrans ,HD ,qc ,N ,1.0f , (const half * )m .d_v16 ,D ,HD , (const half * )m .d_S ,Np , (int64_t )qc * Np ,0.0f , 560m .d_ctx + (size_t )q0 * HD ,HD , (int64_t )N * HD ,H ); 561stage (10 ); 562 } 563stage (3 ); 564for (int r0 = 0 ;r0 < N ;r0 += R ) {// the output projection in chunks: the head-major context rows to the 16-bit input, the product, the residual 565const int rows_ = std::min (R ,N - r0 ); 566k_cast_ctx (q ,m .d_ctx ,N ,H ,HD ,r0 ,rows_ ,a16 , (int )L .o .kind ); 567m .gemm (L .o ,a16 ,rows_ ,m .d_y ); 568k_add_bias_res (q ,m .d_x + (size_t )r0 * D ,m .d_y ,L .o_b ,D ,rows_ ); 569 } 570stage (4 ); 571for (int r0 = 0 ;r0 < N ;r0 += R ) {// the feed-forward block in chunks 572const int rows_ = std::min (R ,N - r0 ); 573k_layernorm (q ,m .d_x + (size_t )r0 * D ,L .ln2_w ,L .ln2_b ,g .eps ,D ,a16 , (int )L .up .kind ,rows_ ); 574m .gemm (L .up ,a16 ,rows_ ,m .d_y ); 575k_bias_gelu_cast (q ,m .d_y ,L .up_b ,F ,m .d_f16 , (int )L .down .kind ,rows_ ); 576m .gemm (L .down ,m .d_f16 ,rows_ ,m .d_y ); 577k_add_bias_res (q ,m .d_x + (size_t )r0 * D ,m .d_y ,L .down_b ,D ,rows_ ); 578 } 579stage (5 ); 580 } 581if (!sync_err ("the layers" ))return false; 582const int M = N /4 ,RM = std::max (1 ,R /4 ); 583for (int r0 = 0 ;r0 < M ;r0 += RM ) { 584const int rows_ = std::min (RM ,M - r0 ); 585k_layernorm (q ,m .d_x + (size_t )r0 * 4 * D ,m .post_w ,m .post_b ,g .eps ,D ,a16 , (int )m .mm0 .kind ,rows_ * 4 ); 586m .gemm (m .mm0 ,a16 ,rows_ ,m .d_y ); 587k_bias_gelu_cast (q ,m .d_y ,m .mm0_b ,g .merger_hidden ,m .d_f16 , (int )m .mm2 .kind ,rows_ ); 588m .gemm (m .mm2 ,m .d_f16 ,rows_ ,m .d_out + (size_t )r0 * g .out_dim ); 589k_add_bias (q ,m .d_out + (size_t )r0 * g .out_dim ,m .mm2_b ,g .out_dim ,rows_ ); 590 } 591if (!sync_err ("the projector" ))return false; 592stage (6 ); 593rows .resize ((size_t )M * g .out_dim ); 594q .memcpy (rows .data (),m .d_out ,rows .size ()* 4 ).wait (); 595stage (7 ); 596if (prof ) 597 std::fprintf (stderr ,"vit-prof N=%d: patch-matrix %.2f, patch-embed %.2f, ln+qkv %.2f, attention %.2f (S product %.2f, softmax %.2f, PV product %.2f), o-proj %.2f, ffn %.2f, merger %.2f, copy-out %.2f ms\n" , 598N ,pt [0 ],pt [1 ],pt [2 ],pt [3 ]+ pt [8 ]+ pt [9 ]+ pt [10 ],pt [8 ],pt [9 ],pt [10 ],pt [4 ],pt [5 ],pt [6 ],pt [7 ]); 599return true; 600 }catch (const std::exception & e ) { 601err = std::string ("the GPU failed: " )+ e .what (); 602return false; 603 } 604} 605 606}// namespace strata_vit