Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/ggml/blob/master/src/ggml-sycl/common.hpp # ggml [Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `ggml / src / ggml-sycl / common.hpp` 1176 lines ยท 40800 bytes Raw Blame History 1 // 2 // MIT license 3 // Copyright (C) 2024 Intel Corporation 4 // SPDX-License-Identifier: MIT 5 // 6 7 // 8 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 9 // See https://llvm.org/LICENSE.txt for license information. 10 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 11 // 12 13 #ifndef GGML_SYCL_COMMON_HPP 14 #define GGML_SYCL_COMMON_HPP 15 16 #include 17 #include 18 #include 19 #include 20 #include 21 #include 22 #include 23 24 #include "base.hpp" 25 #include "dpct/helper.hpp" 26 #include "ggml.h" 27 #include "ggml-impl.h" 28 #include "ggml-sycl.h" 29 #include "presets.hpp" 30 #include "type.hpp" 31 #include "sycl_hw.hpp" 32 #include "memtrace.hpp" 33 34 namespace syclexp = sycl::ext::oneapi::experimental; 35 36 #if defined(__INTEL_LLVM_COMPILER) && __has_include() 37 #include 38 #ifndef GGML_SYCL_HAS_BF16 39 #define GGML_SYCL_HAS_BF16 40 #endif 41 #endif 42 43 #if defined(__INTEL_LLVM_COMPILER) 44 #define GGML_SYCL_DMMV_HAS_ESIMD 45 #endif 46 47 #if GGML_SYCL_DNNL 48 #include "dnnl.hpp" 49 #include "dnnl_sycl.hpp" 50 #endif 51 52 #define GGML_COMMON_DECL_SYCL 53 #define GGML_COMMON_IMPL_SYCL 54 #define SYCL_FLASH_ATTN //remove it to disable FLASH_ATTENTION in building. 55 #define SYCL_FAST_FP16 //don't change. remove it will break fattn-tile.hpp building 56 #define GGML_SYCL_FA_ALL_QUANTS //define it to enable all quantization types in flash attention. undefine it to only support F16, Q4_0 and Q8_0 in flash attention. 57 58 /* suppress warning spam */ 59 #pragma clang diagnostic push 60 #pragma clang diagnostic ignored "-Wnested-anon-types" 61 #include "ggml-common.h" 62 #pragma clang diagnostic pop 63 #include "ggml-impl.h" 64 65 void* ggml_sycl_host_malloc(size_t size); 66 void ggml_sycl_host_free(void* ptr); 67 68 69 extern int g_ggml_sycl_debug; 70 extern int g_ggml_sycl_enable_optimize; 71 extern int g_ggml_sycl_enable_fusion; 72 extern int g_ggml_sycl_enable_esimd; 73 extern int g_ggml_sycl_mmvq_wide; 74 extern int g_ggml_sycl_enable_xmx_esimd; 75 extern int g_ggml_sycl_xmx_max_cols; 76 extern int g_ggml_sycl_xmx_glu_max_cols; 77 extern int g_ggml_sycl_prioritize_dmmv; 78 79 // Which quantized weight formats may take the XMX dequant-GEMM paths. A bitmask rather than one 80 // flag per path, so a format can be enabled or measured on its own and adding a format is one bit. 81 enum ggml_sycl_xmx_gather_type { 82 GGML_SYCL_XMX_GATHER_IQ4_NL = 1 << 0, 83 GGML_SYCL_XMX_GATHER_IQ3_S = 1 << 1, 84 GGML_SYCL_XMX_GATHER_IQ4_XS = 1 << 2, 85 GGML_SYCL_XMX_GATHER_IQ3_XXS = 1 << 3, 86 GGML_SYCL_XMX_GATHER_IQ2_XXS = 1 << 4, 87 GGML_SYCL_XMX_GATHER_IQ2_XS = 1 << 5, 88 GGML_SYCL_XMX_GATHER_IQ2_S = 1 << 6, 89 GGML_SYCL_XMX_GATHER_IQ1_S = 1 << 7, 90 GGML_SYCL_XMX_GATHER_IQ1_M = 1 << 8, 91 GGML_SYCL_XMX_GATHER_Q8_0 = 1 << 9, 92 GGML_SYCL_XMX_GATHER_Q4_K = 1 << 10, 93 GGML_SYCL_XMX_GATHER_Q5_K = 1 << 11, 94 GGML_SYCL_XMX_GATHER_Q6_K = 1 << 12, 95 }; 96 static constexpr int GGML_SYCL_XMX_GATHER_TYPES_DEFAULT = ~0; 97 extern int g_ggml_sycl_xmx_gather_types; 98 // Which joint_matrix combinations the XMX dequant-GEMM paths may use, one bit each (see fused-gemm.cpp). 99 // GGML_SYCL_DYNAMIC_PRECISION picks the operand type, this mask the combinations of that type. 100 static constexpr int GGML_SYCL_XMX_GATHER_SHAPES_DEFAULT = 0xff; 101 extern int g_ggml_sycl_xmx_gather_shapes; 102 103 // GGML_SYCL_DYNAMIC_PRECISION: operand type of the XMX dequant-GEMM paths. F32 turns them off and 104 // keeps the library GEMM in f32. A src1 precision request of an op [TAG_GGML_PREC] is always met. 105 enum ggml_sycl_dynamic_precision { 106 GGML_SYCL_DYNAMIC_PRECISION_F16, 107 GGML_SYCL_DYNAMIC_PRECISION_BF16, 108 GGML_SYCL_DYNAMIC_PRECISION_TF32, 109 GGML_SYCL_DYNAMIC_PRECISION_F32, 110 }; 111 #ifdef GGML_SYCL_F16 112 static constexpr int GGML_SYCL_DYNAMIC_PRECISION_DEFAULT = GGML_SYCL_DYNAMIC_PRECISION_F16; 113 #else 114 static constexpr int GGML_SYCL_DYNAMIC_PRECISION_DEFAULT = GGML_SYCL_DYNAMIC_PRECISION_F32; 115 #endif 116 extern int g_ggml_sycl_dynamic_precision; 117 // GGML_SYCL_DYNAMIC_REQUIRED_PRECISION: the XMX type an F32 src1 request may run on instead of f32 118 // (TF32, or BF16 which also allows tf32). F32 (default): none. F16: src1 requests are ignored. 119 extern int g_ggml_sycl_dynamic_required_precision; 120 121 // [TAG_GGML_PREC] src1 precision request of the MUL_MAT/MUL_MAT_ID op dst 122 static inline int32_t ggml_sycl_src1_prec(const ggml_tensor * dst) { 123 return g_ggml_sycl_dynamic_required_precision == GGML_SYCL_DYNAMIC_PRECISION_F16 ? GGML_PREC_UNDEFINED : 124 dst->op_params[3]; 125 } 126 127 // [TAG_GGML_PREC] the library GEMM and dmmv may convert src1 of the MUL_MAT/MUL_MAT_ID op dst to f16 128 static inline bool ggml_sycl_src1_f16_ok(const ggml_tensor * dst) { 129 const int32_t src1_prec = ggml_sycl_src1_prec(dst); 130 return g_ggml_sycl_dynamic_precision != GGML_SYCL_DYNAMIC_PRECISION_F32 && 131 (src1_prec == GGML_PREC_UNDEFINED || src1_prec >= GGML_PREC_F16); 132 } 133 extern int g_ggml_sycl_enable_flash_attention; 134 extern int g_ggml_sycl_dev2dev_memcpy; 135 extern int g_ggml_sycl_fa_onednn; 136 extern int g_ggml_sycl_fa_onednn_max_kv; 137 extern int g_ggml_sycl_enable_mkl_fa; 138 extern int g_ggml_sycl_fa_dpas; 139 extern int g_ggml_sycl_memtrace; 140 extern int g_ggml_sycl_memtrace_step; 141 extern int g_ggml_sycl_graph_eviction_timeout; 142 143 144 #define CHECK_TRY_ERROR(expr) \ 145 [&]() { \ 146 try { \ 147 expr; \ 148 return dpct::success; \ 149 } catch (std::exception const& e) { \ 150 std::cerr << e.what() << "\nException caught at file:" << __FILE__ \ 151 << ", line:" << __LINE__ << ", func:" << __func__ \ 152 << std::endl; \ 153 return dpct::default_error; \ 154 } \ 155 }() 156 157 158 #define __SYCL_ARCH__ DPCT_COMPATIBILITY_TEMP 159 #define VER_4VEC 610 // todo for hardware optimize. 160 #define VER_GEN9 700 // todo for hardware optimize. 161 #define VER_GEN12 `1000000` // todo for hardware optimize. 162 #define VER_GEN13 (VER_GEN12 + 1030) // todo for hardware optimize. 163 164 #define GGML_SYCL_MAX_NODES 8192 // TODO: adapt to hardwares 165 166 // max batch size to use MMQ kernels when tensor cores are available 167 #define MMQ_MAX_BATCH_SIZE 32 168 169 // dmmv = dequantize_mul_mat_vec 170 #ifndef GGML_SYCL_DMMV_X 171 #define GGML_SYCL_DMMV_X 32 172 #endif 173 #ifndef GGML_SYCL_MMV_Y 174 #define GGML_SYCL_MMV_Y 1 175 #endif 176 177 typedef sycl::queue *queue_ptr; 178 179 enum ggml_sycl_backend_gpu_mode { 180 SYCL_UNSET_GPU_MODE = -1, 181 SYCL_SINGLE_GPU_MODE = 0, 182 SYCL_MUL_GPU_MODE 183 }; 184 185 enum ggml_sycl_dev2dev_memcpy_mode { 186 DEV2DEV_MEMCPY_SYCL = 0, 187 DEV2DEV_MEMCPY_L0 = 1, 188 DEV2DEV_MEMCPY_FORWARD = 2 189 }; 190 191 static_assert(sizeof(sycl::half) == sizeof(ggml_fp16_t), "wrong fp16 size"); 192 193 static void crash() { 194 int* ptr = NULL; 195 *ptr = 0; 196 } 197 198 [[noreturn]] static void ggml_sycl_error( 199 const char* stmt, 200 const char* func, 201 const char* file, 202 const int line, 203 const char* msg) { 204 fprintf(stderr, "SYCL error: %s: %s\n", stmt, msg); 205 fprintf(stderr, " in function %s at %s:%d\n", func, file, line); 206 GGML_ABORT("SYCL error"); 207 } 208 209 #define SYCL_CHECK(err) \ 210 do { \ 211 auto err_ = (err); \ 212 if (err_ != 0) \ 213 ggml_sycl_error(#err, __func__, __FILE__, __LINE__, "Exception caught in this line of code."); \ 214 } while (0) 215 216 #if DPCT_COMPAT_RT_VERSION >= 11100 217 #define GGML_SYCL_ASSUME(x) __builtin_assume(x) 218 #else 219 #define GGML_SYCL_ASSUME(x) 220 #endif // DPCT_COMPAT_RT_VERSION >= 11100 221 222 #ifdef GGML_SYCL_F16 223 typedef sycl::half dfloat; // dequantize float 224 typedef sycl::half2 dfloat2; 225 #else 226 typedef float dfloat; // dequantize float 227 typedef sycl::float2 dfloat2; 228 #endif // GGML_SYCL_F16 229 230 #define MMVQ_MAX_BATCH_SIZE 8 231 232 #if defined(__INTEL_LLVM_COMPILER) && __has_include() 233 # define GGML_SYCL_MMVQ_HAS_XMX 234 #endif // __INTEL_LLVM_COMPILER 235 236 // default of the most columns the XMX mul_mat_vec_q handles (GGML_SYCL_XMX_MAX_COLS), wider batches use other kernels 237 #define GGML_SYCL_XMX_MAX_COLS_DEFAULT 80 238 239 // most columns the fused gate and up XMX kernel is built for, GGML_SYCL_XMX_GLU_MAX_COLS can only lower this limit 240 #define GGML_SYCL_XMX_GLU_MAX_COLS 16 241 242 static inline bool ggml_sycl_xmx_supports_type(ggml_type type) { 243 switch (type) { 244 case GGML_TYPE_Q2_K: 245 case GGML_TYPE_Q3_K: 246 case GGML_TYPE_Q4_K: 247 case GGML_TYPE_Q5_K: 248 case GGML_TYPE_Q6_K: 249 case GGML_TYPE_Q8_0: 250 return true; 251 default: 252 return false; 253 } 254 } 255 256 // the DPAS shapes and 2D block loads used by the XMX kernel are those of Xe2 257 static inline bool ggml_sycl_xmx_supports_arch(gpu_arch arch) { 258 return arch == gpu_arch::intel_gpu_bmg_g21 || arch == gpu_arch::intel_gpu_bmg_g31 || 259 arch == gpu_arch::intel_gpu_lnl_m; 260 } 261 262 // fewest columns for which the XMX kernel is faster than the other kernels 263 static inline int ggml_sycl_xmx_min_cols(ggml_type type) { 264 return type == GGML_TYPE_Q2_K || type == GGML_TYPE_Q3_K || type == GGML_TYPE_Q4_K ? 1 : 2; 265 } 266 267 static int g_all_sycl_device_count = -1; 268 static bool g_ggml_backend_sycl_buffer_type_initialized = false; 269 270 static ggml_sycl_backend_gpu_mode g_ggml_sycl_backend_gpu_mode = 271 SYCL_UNSET_GPU_MODE; 272 273 static void* g_scratch_buffer = nullptr; 274 static size_t g_scratch_size = 0; // disabled by default 275 static size_t g_scratch_offset = 0; 276 277 [[noreturn]] static inline void bad_arch(const sycl::stream& stream_ct1) { 278 stream_ct1 << "ERROR: ggml-sycl was compiled without support for the " 279 "current GPU architecture.\n"; 280 // __trap(); 281 std::exit(1); 282 283 (void)bad_arch; // suppress unused function warning 284 } 285 286 int get_current_device_id(); 287 288 inline int ggml_sycl_get_device() { 289 return get_current_device_id(); 290 } 291 292 inline dpct::err0 ggml_sycl_set_device(const int device) try { 293 int current_device_id; 294 SYCL_CHECK(CHECK_TRY_ERROR(current_device_id = get_current_device_id())); 295 296 // GGML_SYCL_DEBUG("ggml_sycl_set_device device_id=%d, 297 // current_device_id=%d\n", device, current_device); 298 if (device == current_device_id) { 299 return 0; 300 } 301 302 return CHECK_TRY_ERROR(dpct::select_device(device)); 303 } catch (sycl::exception const& exc) { 304 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 305 << ", line:" << __LINE__ << std::endl; 306 crash(); 307 std::exit(1); 308 } 309 310 ////////////////////// 311 struct optimize_feature { 312 bool reorder=false; 313 bool onednn_optimized_gemm=false; 314 }; 315 316 struct sycl_device_info { 317 bool active; //the device is activated/used in application. 318 int cc; // compute capability 319 int nsm; // number of streaming multiprocessors (CUDA) maps to the maximum 320 // number of compute units on a SYCL device. 321 // size_t smpb; // max. shared memory per block 322 size_t smpbo; // max. shared memory per block (with opt-in) 323 int warp_size; // WARP_SIZE(16)|WARP_32_SIZE(32)|WARP_16_SIZE(16). For Intel GPU, 16 is better in most cases. Some OP support 32 only. 324 int max_wg_per_cu; // max work groups per compute unit - refer to 325 // cudaOccupancyMaxActiveBlocksPerMultiprocessor 326 bool vmm; // virtual memory support 327 bool l0_device_type_valid; 328 bool l0_discrete_gpu; // Level Zero backend and not an integrated GPU 329 size_t vmm_granularity; // granularity of virtual memory 330 size_t total_vram; 331 sycl_hw_info hw_info; 332 optimize_feature opt_feature; 333 bool usm_system_support; // support for USM system allocations 334 #ifdef GGML_SYCL_GRAPH 335 bool graph_support; // command graphs can be recorded and replayed 336 bool graph_update_support; // a finalized command graph can be updated 337 #endif 338 }; 339 340 341 struct ggml_sycl_device_info { 342 int active_device_count; //the number of active devices in the application 343 int device_count; 344 345 sycl_device_info devices[GGML_SYCL_MAX_DEVICES] = {}; 346 347 std::array default_tensor_split = {}; 348 349 int max_work_group_sizes[GGML_SYCL_MAX_DEVICES] = {0}; 350 351 bool ext_oneapi_level_zero = true; // sycl::backend::ext_oneapi_level_zero used by all enumerated GPU devices 352 }; 353 354 ggml_sycl_device_info & ggml_sycl_info(); 355 356 static inline bool ggml_sycl_xmx_enabled(int device) { 357 return g_ggml_sycl_enable_xmx_esimd && ggml_sycl_xmx_supports_arch(ggml_sycl_info().devices[device].hw_info.arch); 358 } 359 360 static constexpr size_t SYCL_BUFFER_ALIGNMENT = 128; 361 362 struct ggml_sycl_pool { 363 virtual ~ggml_sycl_pool() = default; 364 365 virtual void * alloc(size_t size, size_t * actual_size) = 0; 366 virtual void free(void * ptr, size_t size) = 0; 367 }; 368 369 template 370 struct ggml_sycl_pool_alloc { 371 ggml_sycl_pool * pool = nullptr; 372 T * ptr = nullptr; 373 size_t actual_size = 0; 374 375 explicit ggml_sycl_pool_alloc(ggml_sycl_pool & pool) : pool(&pool) { 376 } 377 378 ggml_sycl_pool_alloc(ggml_sycl_pool & pool, size_t size) : pool(&pool) { 379 alloc(size); 380 } 381 382 ~ggml_sycl_pool_alloc() { 383 if (ptr != nullptr) { 384 pool->free(ptr, actual_size); 385 } 386 } 387 388 T * realloc(size_t size) { 389 GGML_ASSERT(pool != nullptr); 390 if (ptr) 391 pool->free(ptr, actual_size); 392 ptr = (T *) pool->alloc(size * sizeof(T), &this->actual_size); 393 return ptr; 394 } 395 396 // size is in number of elements 397 T * alloc(size_t size) { 398 GGML_ASSERT(pool != nullptr); 399 GGML_ASSERT(ptr == nullptr); 400 ptr = (T *) pool->alloc(size * sizeof(T), &this->actual_size); 401 return ptr; 402 } 403 404 T * alloc(ggml_sycl_pool & pool, size_t size) { 405 this->pool = &pool; 406 return alloc(size); 407 } 408 409 T * get() { 410 return ptr; 411 } 412 413 ggml_sycl_pool_alloc() = default; 414 ggml_sycl_pool_alloc(const ggml_sycl_pool_alloc &) = delete; 415 ggml_sycl_pool_alloc(ggml_sycl_pool_alloc &&) = delete; 416 ggml_sycl_pool_alloc& operator=(const ggml_sycl_pool_alloc &) = delete; 417 ggml_sycl_pool_alloc& operator=(ggml_sycl_pool_alloc &&) = delete; 418 }; 419 420 // backend interface 421 422 struct ggml_tensor_extra_gpu { 423 void* data_device[GGML_SYCL_MAX_DEVICES]; // 1 pointer for each device for split 424 // tensors 425 dpct::event_ptr events[GGML_SYCL_MAX_DEVICES] 426 [GGML_SYCL_MAX_STREAMS]; // events for synchronizing multiple GPUs 427 optimize_feature optimized_feature; 428 }; 429 430 extern int g_ggml_sycl_use_level_zero_api; 431 void * ggml_sycl_malloc_device(size_t size, sycl::queue &q, 432 ggml_sycl_mem_type type = GGML_SYCL_MEM_DIRECT); 433 void ggml_sycl_free_device(void *ptr, sycl::queue &q); 434 435 void release_extra_gpu(ggml_tensor_extra_gpu * extra, std::vector streams={}); 436 437 struct mmid_row_mapping { 438 int32_t i1; 439 int32_t i2; 440 }; 441 442 struct ggml_sycl_gg_tile { 443 int32_t expert; 444 int32_t n0; 445 int32_t n1; 446 }; 447 448 namespace sycl_ex = sycl::ext::oneapi::experimental; 449 450 #ifdef GGML_SYCL_GRAPH 451 struct ggml_sycl_graph { 452 // src data/ne/nb are kept next to the node copy: the scheduler can hand back the same src 453 // pointer with different contents or shape, see https://github.com/ggml-org/llama.cpp/pull/21736 454 struct node_properties { 455 ggml_tensor node; 456 void * node_src_data_ptrs[GGML_MAX_SRC]; 457 int64_t node_src_ne[GGML_MAX_SRC][GGML_MAX_DIMS]; 458 size_t node_src_nb[GGML_MAX_SRC][GGML_MAX_DIMS]; 459 }; 460 461 std::unique_ptr> exec_graph = nullptr; 462 std::vector node_props; 463 bool warmup_complete = false; 464 uint64_t uid = 0; 465 int64_t last_used_time = 0; 466 467 // result of check_graph_compatibility() and the uid it was made for 468 bool compatible = false; 469 uint64_t compatible_uid = 0; 470 }; 471 472 static_assert(std::is_trivial::value, "node_properties must be trivial"); 473 #endif 474 475 struct ggml_backend_sycl_context { 476 int device; 477 std::string name; 478 optimize_feature opt_feature; 479 480 queue_ptr qptrs[GGML_SYCL_MAX_DEVICES][GGML_SYCL_MAX_STREAMS] = { { nullptr } }; 481 482 explicit ggml_backend_sycl_context(int device) : 483 device(device), 484 name(GGML_SYCL_NAME + std::to_string(device)) { 485 opt_feature = ggml_sycl_info().devices[device].opt_feature; 486 } 487 488 queue_ptr stream(int device, int stream) { 489 if (qptrs[device][stream] == nullptr) { 490 qptrs[device][stream] = &(dpct::get_device(device).default_queue()); 491 } 492 return qptrs[device][stream]; 493 } 494 495 queue_ptr stream() { 496 return stream(device, 0); 497 } 498 499 #if GGML_SYCL_DNNL 500 dnnl::engine make_engine(sycl::queue* q) { 501 // Get the device associated with the queue 502 sycl::device dev = q->get_device(); 503 // Get the context associated with the queue 504 sycl::context ctx = q->get_context(); 505 const dnnl::engine eng = dnnl::sycl_interop::make_engine(dev, ctx); 506 return eng; 507 } 508 509 std::unordered_map stream_map; 510 std::unordered_map engine_map; 511 dnnl::stream stream_dnnl(int device, int _stream) { 512 auto q = stream(device, _stream); 513 return stream_dnnl(q); 514 } 515 dnnl::engine engine_dnnl(sycl::queue* qptr) { 516 auto it = engine_map.find(qptr); 517 if (it == engine_map.end()) { 518 auto eng = make_engine(qptr); 519 engine_map[qptr] = eng; 520 return eng; 521 } 522 else 523 { 524 return it->second; 525 } 526 } 527 dnnl::stream stream_dnnl(sycl::queue* qptr) { 528 auto it = stream_map.find(qptr); 529 if (it == stream_map.end()) { 530 auto eng = engine_dnnl(qptr); 531 auto stream = dnnl::sycl_interop::make_stream(eng, *qptr); 532 stream_map[qptr] = stream; 533 return stream; 534 } 535 else 536 { 537 return it->second; 538 } 539 } 540 dnnl::stream stream_dnnl() { 541 return stream_dnnl(device, 0); 542 } 543 #endif 544 545 // pool 546 std::unique_ptr pools[GGML_SYCL_MAX_DEVICES]; 547 548 std::unique_ptr host_pools[GGML_SYCL_MAX_DEVICES]; 549 550 std::vector mmid_row_mapping_host; 551 std::vector mmid_tile_schedule_host; 552 553 static std::unique_ptr new_pool_for_device(queue_ptr qptr, int device); 554 555 static std::unique_ptr new_pool_for_host(queue_ptr qptr, int device); 556 557 ggml_sycl_pool & pool(int device) { 558 if (pools[device] == nullptr) { 559 pools[device] = new_pool_for_device(stream(device,0), device); 560 } 561 return *pools[device]; 562 } 563 564 ggml_sycl_pool & pool() { 565 return pool(device); 566 } 567 568 #ifdef GGML_SYCL_GRAPH 569 // Map from first node pointer to graph - allows multiple graphs per context when the 570 // computation is split across CPU/GPU (e.g. with --n-cpu-moe) 571 std::unordered_map> sycl_graphs; 572 573 int64_t last_graph_eviction_sweep = 0; 574 std::optional graph_compatible; 575 576 ggml_sycl_graph * sycl_graph(const void * first_node_ptr) { 577 const int64_t time_now = ggml_time_us(); 578 const int64_t eviction_timeout_us = g_ggml_sycl_graph_eviction_timeout * 1'000'000LL; 579 580 // sweep every half the eviction timeout, evicting graphs unused for >= the eviction timeout 581 if (time_now - last_graph_eviction_sweep >= eviction_timeout_us / 2) { 582 last_graph_eviction_sweep = time_now; 583 for (auto it = sycl_graphs.begin(); it != sycl_graphs.end(); ) { 584 if (time_now - it->second->last_used_time >= eviction_timeout_us) { 585 it = sycl_graphs.erase(it); 586 } else { 587 ++it; 588 } 589 } 590 } 591 592 auto it = sycl_graphs.find(first_node_ptr); 593 if (it == sycl_graphs.end()) { 594 it = sycl_graphs.emplace(first_node_ptr, std::make_unique()).first; 595 } 596 it->second->last_used_time = time_now; 597 return it->second.get(); 598 } 599 #endif 600 601 ggml_sycl_pool & host_pool(int device) { 602 if (host_pools[device] == nullptr) { 603 host_pools[device] = new_pool_for_host(stream(device, 0), device); 604 } 605 return *host_pools[device]; 606 } 607 608 ggml_sycl_pool & host_pool() { return host_pool(device); } 609 }; 610 611 // common device functions 612 613 static __dpct_inline__ float warp_reduce_sum(float x, 614 const sycl::nd_item<3>& item_ct1) { 615 #pragma unroll 616 for (int mask = WARP_SIZE / 2; mask > 0; mask >>= 1) { 617 x += dpct::permute_sub_group_by_xor(item_ct1.get_sub_group(), x, mask); 618 } 619 return x; 620 } 621 622 static __dpct_inline__ sycl::float2 623 warp_reduce_sum(sycl::float2 a, const sycl::nd_item<3>& item_ct1) { 624 #pragma unroll 625 for (int mask = WARP_SIZE / 2; mask > 0; mask >>= 1) { 626 a.x() += dpct::permute_sub_group_by_xor(item_ct1.get_sub_group(), a.x(), 627 mask); 628 a.y() += dpct::permute_sub_group_by_xor(item_ct1.get_sub_group(), a.y(), 629 mask); 630 } 631 return a; 632 } 633 634 /* use WARP_SIZE or WARP_32_SIZE*/ 635 template 636 static __dpct_inline__ int warp_reduce_sum(int x) { 637 return sycl::reduce_over_group( 638 sycl::ext::oneapi::this_work_item::get_sub_group(), x, sycl::plus<>()); 639 } 640 641 /* use WARP_SIZE or WARP_32_SIZE*/ 642 template 643 static __dpct_inline__ float warp_reduce_sum(float x) { 644 #pragma unroll 645 for (int offset = width / 2; offset > 0; offset >>= 1) { 646 x += dpct::permute_sub_group_by_xor( 647 sycl::ext::oneapi::this_work_item::get_sub_group(), x, offset, width); 648 } 649 return x; 650 } 651 652 /* use WARP_SIZE or WARP_32_SIZE*/ 653 template 654 static __dpct_inline__ float warp_reduce_sum(float x, const sycl::nd_item<3>& item_ct1) { 655 #pragma unroll 656 for (int offset = width / 2; offset > 0; offset >>= 1) { 657 x += dpct::permute_sub_group_by_xor( 658 item_ct1.get_sub_group(), x, offset); 659 } 660 return x; 661 } 662 663 /* use WARP_SIZE or WARP_32_SIZE*/ 664 template 665 static __dpct_inline__ sycl::float2 warp_reduce_sum(sycl::float2 a) { 666 #pragma unroll 667 for (int offset = width / 2; offset > 0; offset >>= 1) { 668 a.x() += dpct::permute_sub_group_by_xor( 669 sycl::ext::oneapi::this_work_item::get_sub_group(), a.x(), offset, 670 width); 671 a.y() += dpct::permute_sub_group_by_xor( 672 sycl::ext::oneapi::this_work_item::get_sub_group(), a.y(), offset, 673 width); 674 } 675 return a; 676 } 677 678 /* use WARP_SIZE or WARP_32_SIZE*/ 679 template 680 static __dpct_inline__ sycl::half2 warp_reduce_sum(sycl::half2 a) { 681 #pragma unroll 682 for (int offset = width / 2; offset > 0; offset >>= 1) { 683 a = a + dpct::permute_sub_group_by_xor( 684 sycl::ext::oneapi::this_work_item::get_sub_group(), a, offset, 685 width); 686 } 687 return a; 688 } 689 690 static constexpr int ggml_sycl_get_physical_warp_size() { 691 // todo: for old iGPU + dGPU case, need to be changed. 692 return WARP_SIZE; 693 } 694 695 /* use WARP_SIZE or WARP_32_SIZE*/ 696 template 697 static __dpct_inline__ int warp_reduce_all(int x) { 698 if (width == ggml_sycl_get_physical_warp_size()) { 699 return sycl::all_of_group( 700 sycl::ext::oneapi::this_work_item::get_sub_group(), 701 (~0xffffffff & 702 (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group() 703 .get_local_linear_id())) || 704 x); 705 } else { 706 #pragma unroll 707 for (int offset = width / 2; offset > 0; offset >>= 1) { 708 x = dpct::permute_sub_group_by_xor( 709 sycl::ext::oneapi::this_work_item::get_sub_group(), x, 710 offset, width) && 711 x; 712 } 713 return x; 714 } 715 } 716 717 /* use WARP_SIZE or WARP_32_SIZE*/ 718 template 719 static __dpct_inline__ int warp_reduce_any(int x) { 720 if (width == ggml_sycl_get_physical_warp_size()) { 721 return sycl::any_of_group( 722 sycl::ext::oneapi::this_work_item::get_sub_group(), 723 (0xffffffff & 724 (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group() 725 .get_local_linear_id())) && 726 x); 727 } else { 728 #pragma unroll 729 for (int offset = width / 2; offset > 0; offset >>= 1) { 730 x = dpct::permute_sub_group_by_xor( 731 sycl::ext::oneapi::this_work_item::get_sub_group(), x, 732 offset, width) || 733 x; 734 } 735 return x; 736 } 737 } 738 739 /* use WARP_SIZE or WARP_32_SIZE*/ 740 template 741 static __dpct_inline__ float warp_reduce_max(float x) { 742 #pragma unroll 743 for (int offset = width / 2; offset > 0; offset >>= 1) { 744 x = sycl::fmax(x, dpct::permute_sub_group_by_xor( 745 sycl::ext::oneapi::this_work_item::get_sub_group(), x, 746 offset, width)); 747 } 748 return x; 749 } 750 751 static __dpct_inline__ float warp_reduce_max(float x, 752 const sycl::nd_item<3>& item_ct1) { 753 #pragma unroll 754 for (int mask = WARP_SIZE / 2; mask > 0; mask >>= 1) { 755 x = sycl::fmax(x, dpct::permute_sub_group_by_xor( 756 item_ct1.get_sub_group(), x, mask)); 757 } 758 return x; 759 } 760 761 /* Helper for Computing the linear offset of a ggml_tensor given 762 per-dimension sizes, strides, and indices */ 763 template 764 __dpct_inline__ size_t calculate_offset(const std::array & strides, const std::array & indices) { 765 size_t offset = 0; 766 #pragma unroll 767 for (int i = 0; i < N; i++) { 768 auto index_i = indices[i]; 769 offset += strides[i] * index_i; 770 } 771 return offset; 772 } 773 774 // Helper for vec loading aligned data 775 template 776 inline sycl::vec vec_aligned_load(const Tp* aligned_ptr) { 777 return *reinterpret_cast*>(aligned_ptr); 778 } 779 780 // Helper for accessing pointers with no warnings 781 template 782 static __dpct_inline__ Tp* get_pointer(sycl::local_accessor acc) { 783 return acc.template get_multi_ptr().get(); 784 } 785 786 int64_t downsample_sycl_global_range(int64_t accumulate_block_num, int64_t block_size); 787 788 constexpr size_t ceil_div(const size_t m, const size_t n) { 789 return (m + n - 1) / n; 790 } 791 792 bool gpu_has_xmx(sycl::device &dev); 793 794 #if GGML_SYCL_DNNL 795 // oneDNN builds JIT kernels only for some GPU architectures. On the rest it falls back to 796 // reference kernels, which are much slower than the SYCL kernels here. 797 inline bool ggml_sycl_dnnl_has_optimized_gemm(int device) { 798 return ggml_sycl_info().devices[device].opt_feature.onednn_optimized_gemm; 799 } 800 #endif 801 802 int ggml_sycl_get_env(const char *env_name, int default_val); 803 804 template std::string debug_get_array_str(const std::string & prefix, const T array[N]) { 805 if (LIKELY(!g_ggml_sycl_debug)) { 806 return ""; 807 } 808 std::stringstream ss; 809 ss << prefix << "=["; 810 for (std::size_t i = 0; i < N - 1; ++i) { 811 ss << array[i] << ", "; 812 } 813 if constexpr (N > 0) { 814 ss << array[N - 1]; 815 } 816 ss << "]"; 817 return ss.str(); 818 } 819 820 inline std::string debug_get_tensor_str(const std::string &prefix, 821 const ggml_tensor *tensor, const std::string &suffix = "") { 822 std::stringstream ss; 823 if (LIKELY(!g_ggml_sycl_debug)) { return ss.str(); } 824 ss << prefix.c_str() << "="; 825 if (tensor) { 826 ss << "'" << tensor->name << "':type=" << ggml_type_name(tensor->type); 827 ss << debug_get_array_str(";ne", tensor->ne); 828 ss << debug_get_array_str(";nb", tensor->nb); 829 830 if (!ggml_is_contiguous(tensor)) { ss << ";strided"; } 831 if (ggml_is_permuted(tensor)) { ss << ";permuted"; } 832 } else { 833 ss << "nullptr"; 834 } 835 ss << suffix; 836 return ss.str(); 837 } 838 839 // Use scope_op_debug_print to log operations coming from running a model 840 struct scope_op_debug_print { 841 // Use string_views to avoid the cost of creating a string and concatenating them 842 // string_views must be alive for as long as the object is alive 843 // scope_op_debug_print are used with string literals in practice which are stored in constant space so always accessible 844 scope_op_debug_print(const std::string_view & func, const std::string_view & func_suffix, const ggml_tensor * dst, 845 std::size_t num_src, const std::string_view & suffix = "") : 846 func(func), 847 func_suffix(func_suffix) { 848 if (LIKELY(!g_ggml_sycl_debug)) { 849 return; 850 } 851 GGML_SYCL_DEBUG("[SYCL][OP] call %s%s:", func.data(), func_suffix.data()); 852 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(" dst", dst).c_str()); 853 if (dst) { 854 for (std::size_t i = 0; i < num_src; ++i) { 855 GGML_SYCL_DEBUG("%s", debug_get_tensor_str("\tsrc" + std::to_string(i), dst->src[i]).c_str()); 856 } 857 } 858 GGML_SYCL_DEBUG("%s\n", suffix.data()); 859 } 860 861 scope_op_debug_print(const std::string_view & func, const ggml_tensor * dst, std::size_t num_src, 862 const std::string_view & suffix = "") : 863 scope_op_debug_print(func, "", dst, num_src, suffix) {} 864 865 ~scope_op_debug_print() { GGML_SYCL_DEBUG("[SYCL][OP] call %s%s done\n", func.data(), func_suffix.data()); } 866 867 private: 868 std::string_view func; 869 std::string_view func_suffix; 870 }; 871 872 static __dpct_inline__ float get_alibi_slope(const float max_bias, 873 const uint32_t h, 874 const uint32_t n_head_log2, 875 const float m0, 876 const float m1) { 877 if (max_bias <= 0.0f) { 878 return 1.0f; 879 } 880 const float base = h < n_head_log2 ? m0 : m1; 881 const int exph = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1; 882 883 return dpct::pow(base, exph); 884 } 885 886 static const sycl::uint3 init_fastdiv_values(uint32_t d) { 887 GGML_ASSERT(d != 0); 888 889 uint32_t L = 0; 890 while (L < 32 && (uint32_t{ 1 } << L) < d) { 891 L++; 892 } 893 894 uint32_t mp = (uint32_t) ((uint64_t{ 1 } << 32) * ((uint64_t{ 1 } << L) - d) / d + 1); 895 return sycl::uint3(mp, L, d); 896 } 897 898 // Maximum number of bytes that can be copied in a single instruction. 899 // Set by test result. 900 static constexpr int ggml_sycl_get_max_cpy_bytes() { 901 return 16; 902 } 903 904 // Aligned memory transfers of 8/16 bytes can be faster than 2 transfers with 4 bytes. 905 template 906 static __dpct_inline__ void ggml_sycl_memcpy_1(void * dst, const void * src) { 907 if constexpr (alignment != 0) { 908 static_assert(nbytes % alignment == 0, "bad alignment"); 909 } 910 constexpr int nb_per_cpy = alignment == 0 ? nbytes : alignment; 911 912 #pragma unroll 913 for (int i = 0; i < nbytes/nb_per_cpy; ++i) { 914 if constexpr (nb_per_cpy == 1) { 915 ((char *) dst)[i] = ((const char *) src)[i]; 916 } else if constexpr (nb_per_cpy == 2) { 917 ((short *) dst)[i] = ((const short *) src)[i]; 918 } else if constexpr (nb_per_cpy == 4) { 919 ((int *) dst)[i] = ((const int *) src)[i]; 920 } else if constexpr (nb_per_cpy == 8) { 921 ((sycl::int2 *) dst)[i] = ((const sycl::int2 *) src)[i]; 922 } else if constexpr (nb_per_cpy == 16) { 923 ((sycl::int4 *) dst)[i] = ((const sycl::int4 *) src)[i]; 924 } else { 925 static_assert(nbytes == 0 && nbytes == -1, "bad nbytes"); 926 } 927 } 928 } 929 template 930 sycl::half2 __dpct_inline__ make_half2( T x, T y) { 931 sycl::half2 res(static_cast(x),static_cast(y)); 932 return res; 933 } 934 935 static __dpct_inline__ uint32_t fastdiv(uint32_t n, const sycl::uint3 fastdiv_values) { 936 const uint32_t hi = sycl::mul_hi(n, fastdiv_values.x()); 937 return (hi + n) >> fastdiv_values.y(); 938 } 939 940 941 template 942 sycl::float2 __dpct_inline__ make_float2( T x, T y) { 943 sycl::float2 res(static_cast(x),static_cast(y)); 944 return res; 945 } 946 947 sycl::float2 __dpct_inline__ __half22float2(sycl::half2 &H) { 948 sycl::float2 float2_value(static_cast(H.x()), static_cast(H.y())); 949 return float2_value; 950 } 951 952 static __dpct_inline__ sycl::uint2 fast_div_modulo(uint32_t n, const sycl::uint3 fastdiv_values) { 953 const uint32_t div_val = fastdiv(n, fastdiv_values); 954 const uint32_t mod_val = n - div_val * fastdiv_values.z(); 955 return sycl::uint2(div_val, mod_val); 956 } 957 958 static __dpct_inline__ int ggml_sycl_dp4a(const int a, const int b, int c) { 959 return dpct::dp4a(a, b, c); 960 } 961 962 static __dpct_inline__ float ggml_sycl_e8m0_to_fp32(uint8_t x) { 963 uint32_t bits; 964 if (x == 0) { 965 bits = 0x00400000; 966 } else { 967 bits = (uint32_t) x << 23; 968 } 969 970 float result; 971 memcpy(&result, &bits, sizeof(float)); 972 return result; 973 } 974 975 sycl::float2 __dpct_inline__ __half22float2(const sycl::half2 &H) { 976 sycl::float2 float2_value(static_cast(H.x()), static_cast(H.y())); 977 return float2_value; 978 } 979 980 float __dpct_inline__ __half2float(sycl::half H) { 981 return static_cast(H); 982 } 983 984 static __dpct_inline__ void ggml_sycl_mad(float & acc, const float v, const float u) { 985 acc += v*u; 986 } 987 988 static __dpct_inline__ void ggml_sycl_mad(float & acc, const sycl::float2 v, const sycl::float2 u) { 989 acc += v.x() * u.x(); 990 acc += v.y() * u.y(); 991 } 992 993 static __dpct_inline__ void ggml_sycl_mad(float & acc, const sycl::half2 v, const sycl::half2 u) { 994 #ifdef GGML_SYCL_F16 995 const sycl::float2 tmp = (v * u).template convert(); 996 acc += tmp.x() + tmp.y(); 997 #else 998 const sycl::float2 tmpv = __half22float2(v); 999 const sycl::float2 tmpu = __half22float2(u); 1000 acc += tmpv.x() * tmpu.x(); 1001 acc += tmpv.y() * tmpu.y(); 1002 #endif // GGML_SYCL_F16 1003 } 1004 1005 static __dpct_inline__ void ggml_sycl_mad(sycl::half2 & acc, const sycl::half2 v, const sycl::half2 u) { 1006 #ifdef GGML_SYCL_F16 1007 acc += v*u; 1008 #else 1009 const sycl::float2 tmpv = __half22float2(v); 1010 const sycl::float2 tmpu = __half22float2(u); 1011 sycl::float2 tmpacc = __half22float2(acc); 1012 // tmpacc.x += tmpv.x() * tmpu.x(); 1013 // tmpacc.y += tmpv.y() * tmpu.y(); 1014 sycl::float2 tmp1(tmpacc.x() + tmpv.x() * tmpu.x(), tmpacc.y() + tmpv.y() * tmpu.y()); 1015 acc = make_half2(tmp1.x(), tmp1.y()); 1016 #endif // GGML_SYCL_F16 1017 } 1018 1019 template 1020 struct ggml_sycl_unroll { 1021 template 1022 void operator()(const Func & f, Args... args) const { 1023 f(n - 1, args...); 1024 ggml_sycl_unroll{}(f, args...); 1025 } 1026 }; 1027 1028 template <> 1029 struct ggml_sycl_unroll<1> { 1030 template 1031 void operator()(const Func & f, Args... args) const { 1032 f(0, args...); 1033 } 1034 }; 1035 1036 static __dpct_inline__ sycl::half2 ggml_sycl_hmax2(const sycl::half2 a, const sycl::half2 b) { 1037 sycl::half2 ret; 1038 reinterpret_cast(ret.x()) = 1039 sycl::vec(sycl::fmax(a[0], b[0])).convert()[0]; 1040 reinterpret_cast(ret.y()) = 1041 sycl::vec(sycl::fmax(a[1], b[1])).convert()[0]; 1042 return ret; 1043 } 1044 1045 static __dpct_inline__ sycl::half ggml_sycl_hmax(const sycl::half a, const sycl::half b) { 1046 return sycl::vec( 1047 sycl::fmax(sycl::vec(a).convert()[0], 1048 sycl::vec(b).convert()[0])) 1049 .convert()[0]; 1050 } 1051 1052 static __dpct_inline__ uint32_t __hgt2_mask(const sycl::half2 a, const sycl::half2 b) { 1053 const uint32_t mask_low = 0x0000FFFF * (float(a[0]) > float(b[0])); 1054 const uint32_t mask_high = 0xFFFF0000 * (float(a[1]) > float(b[1])); 1055 return mask_low | mask_high; 1056 } 1057 1058 static __dpct_inline__ uint32_t fastmodulo(uint32_t n, const sycl::uint3 fastdiv_values) { 1059 // expects fastdiv_values to contain in (see init_fastdiv_values) 1060 return n - fastdiv(n, fastdiv_values) * fastdiv_values.z(); 1061 } 1062 1063 static bool fast_fp16_available(const int cc) { 1064 GGML_UNUSED(cc); 1065 return true; //Intel GPUs always support FP16. 1066 } 1067 1068 enum class block_reduce_method { 1069 MAX, 1070 SUM, 1071 }; 1072 1073 template 1074 struct block_reduce_policy; 1075 1076 template 1077 inline constexpr bool is_any = (std::is_same_v || ...); 1078 1079 template 1080 inline constexpr bool ggml_sycl_dependent_false_v = false; 1081 1082 #define WARP_32_SIZE 32 1083 1084 template struct block_reduce_policy { 1085 static T reduce(T val) { 1086 if constexpr (is_any) { 1087 return warp_reduce_sum(val); 1088 } else { 1089 static_assert(ggml_sycl_dependent_false_v, "Unsupported type for block reduce sum"); 1090 } 1091 } 1092 1093 static T sentinel() { 1094 if constexpr (std::is_same_v) { 1095 return 0.0f; 1096 } else if constexpr (std::is_same_v) { 1097 return sycl::float2(0.0f, 0.0f); 1098 } else if constexpr (std::is_same_v) { 1099 return sycl::half2(0.0f, 0.0f); 1100 } else if constexpr (std::is_same_v) { 1101 return 0; 1102 } else { 1103 static_assert(ggml_sycl_dependent_false_v, "Unsupported type for block reduce sum"); 1104 } 1105 } 1106 }; 1107 1108 template struct block_reduce_policy { 1109 static T reduce(T val) { 1110 if constexpr (is_any) { 1111 return warp_reduce_max(val); 1112 } else { 1113 static_assert(ggml_sycl_dependent_false_v, "Unsupported type for block reduce max"); 1114 } 1115 } 1116 1117 static T sentinel() { 1118 if constexpr (std::is_same_v) { 1119 return -INFINITY; 1120 } else if constexpr (std::is_same_v) { 1121 return sycl::half2(-INFINITY, -INFINITY); 1122 } else { 1123 static_assert(ggml_sycl_dependent_false_v, "Unsupported type for block reduce max"); 1124 } 1125 } 1126 }; 1127 1128 1129 template 1130 static T block_reduce(T val, T * shared_vals, int block_size_template) { 1131 auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>(); 1132 val = block_reduce_policy::reduce(val); 1133 const int block_size = block_size_template == 0 ? item_ct1.get_local_range(2) : block_size_template; 1134 const int nthreads = item_ct1.get_local_range(2); 1135 const int nwarps = nthreads / WARP_SIZE; 1136 1137 if (block_size > warp_size) { 1138 assert((block_size <= 1024) && (block_size % warp_size) == 0); 1139 const int warp_id = item_ct1.get_local_id(2) / warp_size; 1140 const int lane_id = item_ct1.get_local_id(2) % warp_size; 1141 if (lane_id == 0) { 1142 shared_vals[warp_id] = val; 1143 } 1144 item_ct1.barrier(sycl::access::fence_space::local_space); 1145 1146 size_t nreduce = nwarps / WARP_SIZE; 1147 float tmp = 0.f; 1148 if (lane_id < (static_cast(block_size) / warp_size)) { 1149 for (size_t i = 0; i < nreduce; i += 1) 1150 { 1151 tmp += shared_vals[lane_id + i * WARP_SIZE]; 1152 } 1153 } 1154 return block_reduce_policy::reduce(tmp); 1155 } 1156 return val; 1157 } 1158 1159 static __dpct_inline__ float ggml_sycl_ue4m3_to_fp32(uint8_t x) { 1160 // UE4M3 is unsigned: 4 exp bits (bias 7), 3 mantissa bits, no sign, no NaN. 1161 // exp == 0xF is a valid exponent (256-448 range), not NaN. 1162 if (x == 0 || x == 0x7F) { 1163 return 0.0f; 1164 } 1165 const int exp = (x >> 3) & 0xF; 1166 const int man = x & 0x7; 1167 float raw; 1168 if (exp == 0) { 1169 raw = man * (1.0f / 8.0f) * sycl::pow(2.0f, -6.0f); 1170 } else { 1171 raw = (1.0f + man / 8.0f) * sycl::pow(2.0f, (float) exp - 7.0f); 1172 } 1173 return raw * 0.5f; 1174 } 1175 1176 #endif // GGML_SYCL_COMMON_HPP