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/ggml-sycl.cpp # 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 / ggml-sycl.cpp` 8225 lines · 347534 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 #include 14 #include 15 #include 16 #include 17 #include 18 #include 19 #include 20 #include 21 #include 22 #include 23 #include 24 #include 25 #include 26 #include 27 #include 28 #include 29 #include 30 #include 31 #include 32 #include 33 #include 34 #include 35 36 #include 37 #include 38 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 39 #include 40 #include 41 #endif 42 #if defined(GGML_SYCL_GRAPH) && SYCL_EXT_ONEAPI_ASYNC_MEMORY_ALLOC 43 # include 44 #endif 45 #if SYCL_EXT_ONEAPI_VIRTUAL_MEM 46 # include 47 # include 48 # define GGML_SYCL_SUPPORT_VMM 49 #endif 50 // beginning in oneDNN 3.12.3, "Enabled matmul and inner product primitives compatibility with SYCL Graph native recording mode on Intel GPUs." 51 #if GGML_SYCL_DNNL 52 # include "dnnl_version.h" 53 # if (DNNL_VERSION_MAJOR > 3 || (DNNL_VERSION_MAJOR == 3 && (DNNL_VERSION_MINOR > 12 || (DNNL_VERSION_MINOR == 12 && DNNL_VERSION_PATCH >= 3)))) 54 # define GGML_SYCL_GRAPH_DNNL_SUPPORTED 55 # endif 56 #endif 57 #include 58 59 #include "ggml.h" 60 #include "ggml-sycl.h" 61 #include "ggml-impl.h" 62 #include "ggml-backend-impl.h" 63 64 #include "ggml-sycl/add-id.hpp" 65 #include "ggml-sycl/backend.hpp" 66 #include "ggml-sycl/common.hpp" 67 #include "ggml-sycl/element_wise.hpp" 68 #include "ggml-sycl/fwht.hpp" 69 #include "ggml-sycl/fused-gemm.hpp" 70 #include "ggml-sycl/gemm.hpp" 71 #include "ggml-sycl/getrows.hpp" 72 #include "ggml-sycl/mem.hpp" 73 #include "ggml-sycl/norm.hpp" 74 #include "ggml-sycl/presets.hpp" 75 #include "ggml-sycl/quantize.hpp" 76 #include "ggml-sycl/repeat_back.hpp" 77 #include "ggml-sycl/set_rows.hpp" 78 #include "ggml-sycl/set.hpp" 79 #include "ggml-sycl/dsv4-hc.hpp" 80 #include "ggml-sycl/lightning-indexer.hpp" 81 #include "ggml-sycl/conv2d.hpp" 82 #include "ggml-sycl/conv2d-dw.hpp" 83 #include "ggml-sycl/conv2d-transpose.hpp" 84 #include "ggml-sycl/ssm_conv.hpp" 85 #include "ggml-sycl/sycl_hw.hpp" 86 #include "ggml-sycl/ssm_scan.hpp" 87 #include "ggml-sycl/fill.hpp" 88 #include "ggml-sycl/cumsum.hpp" 89 #include "ggml-sycl/diag.hpp" 90 #include "ggml-sycl/opt-step.hpp" 91 #include "ggml-sycl/solve_tri.hpp" 92 #include "ggml-sycl/gated_delta_net.hpp" 93 #include "ggml-sycl/pool.hpp" 94 #include "ggml-sycl/cross_entropy_loss.hpp" 95 96 #define MEM_SIZE_2M 0x00200000 97 #define MEM_SIZE_1G 0x40000000 98 99 static bool g_sycl_loaded = false; 100 int g_ggml_sycl_debug = 0; 101 int g_ggml_sycl_dev_debug = 0; 102 int g_ggml_sycl_enable_optimize = 1; 103 int g_ggml_sycl_enable_graph = 0; 104 int g_ggml_sycl_enable_dnn = 1; 105 int g_ggml_sycl_fa_onednn = 1; 106 int g_ggml_sycl_fa_onednn_max_kv = 0; 107 int g_ggml_sycl_enable_mkl_fa = 1; 108 int g_ggml_sycl_fa_dpas = 1; 109 int g_ggml_sycl_memtrace = 0; 110 int g_ggml_sycl_memtrace_step = 64; 111 int g_ggml_sycl_enable_vmm = 1; 112 int g_ggml_sycl_enable_fusion = 1; 113 int g_ggml_sycl_enable_esimd = 1; 114 int g_ggml_sycl_mmvq_wide = 1; 115 int g_ggml_sycl_enable_xmx_esimd = 1; 116 int g_ggml_sycl_xmx_max_cols = GGML_SYCL_XMX_MAX_COLS_DEFAULT; 117 int g_ggml_sycl_xmx_glu_max_cols = GGML_SYCL_XMX_GLU_MAX_COLS; 118 int g_ggml_sycl_prioritize_dmmv = 0; 119 int g_ggml_sycl_xmx_gather_types = GGML_SYCL_XMX_GATHER_TYPES_DEFAULT; 120 int g_ggml_sycl_xmx_gather_shapes = GGML_SYCL_XMX_GATHER_SHAPES_DEFAULT; 121 int g_ggml_sycl_dynamic_precision = GGML_SYCL_DYNAMIC_PRECISION_DEFAULT; 122 int g_ggml_sycl_dynamic_required_precision = GGML_SYCL_DYNAMIC_PRECISION_F32; 123 static const char * ggml_sycl_dynamic_precision_names[] = { "F16", "BF16", "TF32", "F32" }; 124 125 // value of a GGML_SYCL_DYNAMIC_PRECISION-style variable; def if unset or invalid 126 static int ggml_sycl_get_env_precision(const char * name, int def) { 127 const char * env = getenv(name); 128 if (!env) { 129 return def; 130 } 131 std::string mode(env); 132 for (char & c : mode) { 133 c = (char) std::toupper((unsigned char) c); 134 } 135 for (int i = GGML_SYCL_DYNAMIC_PRECISION_F16; i <= GGML_SYCL_DYNAMIC_PRECISION_F32; i++) { 136 if (mode == ggml_sycl_dynamic_precision_names[i]) { 137 return i; 138 } 139 } 140 GGML_LOG_WARN("%s: unknown %s=%s, using %s\n", __func__, name, env, ggml_sycl_dynamic_precision_names[def]); 141 return def; 142 } 143 int g_ggml_sycl_use_async_mem_op = 0; 144 int g_ggml_sycl_use_async_mem_op_requested = 1; 145 int g_ggml_sycl_use_level_zero_api = 0; 146 int g_ggml_sycl_enable_flash_attention = 1; 147 int g_ggml_sycl_dev2dev_memcpy = DEV2DEV_MEMCPY_SYCL; 148 int g_ggml_sycl_usm_system = 0; 149 int g_ggml_sycl_enable_host_pinned_mem = 1; 150 int g_ggml_sycl_host_pinned_mem_2g = 0; 151 int g_ggml_sycl_upload_staging_slots = 4; 152 int g_ggml_sycl_get_mem_api = MEMORY_API_TYPE_LEVEL_ZERO; 153 int g_ggml_sycl_enable_sparse_fa = 0; 154 int g_ggml_sycl_debug_sparse_fa = 0; 155 int g_ggml_sycl_sparse_fa_margin = 256; 156 int g_ggml_sycl_graph_eviction_timeout = 10; 157 158 #if GGML_SYCL_DNNL 159 // ask oneDNN which matmul it picks for a small f16 problem 160 static bool ggml_sycl_dnnl_detect_optimized_gemm(int device) { 161 using dt = dnnl::memory::data_type; 162 163 try { 164 const dnnl::memory::dims dims = { 1, 64, 64 }; 165 const dnnl::memory::dims strides = { 64 * 64, 64, 1 }; 166 167 dnnl::primitive_attr attr; 168 attr.set_scratchpad_mode(dnnl::scratchpad_mode::user); 169 170 const auto & q = dpct::dev_mgr::instance().get_device(device).default_queue(); 171 const auto eng = dnnl::sycl_interop::make_engine(q.get_device(), q.get_context()); 172 const auto pd = dnnl::matmul::primitive_desc(eng, 173 dnnl::memory::desc(dims, dt::f16, strides), 174 dnnl::memory::desc(dims, dt::f16, strides), 175 dnnl::memory::desc(dims, dt::f32, strides), attr); 176 177 const std::string impl = pd.impl_info_str(); 178 if (impl.find("ref") == std::string::npos) { 179 return true; 180 } 181 182 GGML_LOG_WARN("%s: oneDNN has no optimized matmul for device %d (picks %s), using SYCL kernels\n", 183 __func__, device, impl.c_str()); 184 } catch (const std::exception & e) { 185 GGML_LOG_WARN("%s: oneDNN matmul probe failed on device %d (%s), using SYCL kernels\n", 186 __func__, device, e.what()); 187 } 188 189 return false; 190 } 191 #endif 192 193 static ggml_sycl_device_info ggml_sycl_init() { 194 GGML_SYCL_DEBUG("[SYCL] call ggml_sycl_init\n"); 195 ggml_sycl_device_info info = {}; 196 197 // Do not hard crash when there exists no SYCL devices. 198 // We want to allow the user to use non-SYCL tools when SYCL is compiled (such as llama-quantize) 199 try { 200 info.device_count = dpct::dev_mgr::instance().device_count(); 201 } catch (sycl::exception const &exc) { 202 GGML_LOG_INFO("%s: no SYCL device available: %s\n", __func__, exc.what()); 203 info.device_count = 0; 204 } 205 if (info.device_count == 0) { 206 GGML_LOG_ERROR("%s: failed to initialize: %s\n", GGML_SYCL_NAME, __func__); 207 return info; 208 } 209 210 GGML_ASSERT(info.device_count <= GGML_SYCL_MAX_DEVICES); 211 212 int64_t total_vram = 0; 213 /* This is a bit misleading; reserved for later */ 214 // #if defined(GGML_SYCL_SUPPORT_XMX) && !defined(GGML_SYCL_FORCE_MMQ) 215 // GGML_LOG_INFO("%s: GGML_SYCL_SUPPORT_XMX: yes\n", __func__); 216 // #else 217 // GGML_LOG_INFO("%s: GGML_SYCL_SUPPORT_XMX: no\n", __func__); 218 // #endif 219 for (int i = 0; i < info.device_count; ++i) { 220 dpct::device_info prop; 221 auto & device = dpct::dev_mgr::instance().get_device(i); 222 223 SYCL_CHECK(CHECK_TRY_ERROR(dpct::get_device_info( 224 prop, device))); 225 226 #if !defined(GGML_SYCL_SUPPORT_VMM) 227 info.devices[i].vmm = 0; 228 #else 229 info.devices[i].vmm = device.has(sycl::aspect::ext_oneapi_virtual_mem); 230 if (info.devices[i].vmm) { 231 // NB: SYCL's get_mem_granularity always returns the _minimum_ granularity, 232 // but the L0 API requires a larger page size for allocs above 2 MiB and 233 // rejects non-multiples with UR_RESULT_ERROR_INVALID_VALUE [sic]. 234 // Here we clamp it to 2 MiB for simplicity, but other devices may require 235 // calling zeVirtualMemQueryPageSize or yet unexposed public API. 236 const size_t physical_page = 2ull << 20; // 2 MiB 237 info.devices[i].vmm_granularity = std::max( 238 sycl::ext::oneapi::experimental::get_mem_granularity( 239 device, sycl::context(device)), 240 physical_page); 241 } 242 #endif 243 244 info.default_tensor_split[i] = total_vram; 245 total_vram += prop.get_global_mem_size(); 246 247 info.devices[i].cc = 248 100 * prop.get_major_version() + 10 * prop.get_minor_version(); 249 info.devices[i].nsm = prop.get_max_compute_units() / 16; //16: Number of Xe Cores 250 info.devices[i].opt_feature.reorder = device.ext_oneapi_architecture_is(syclex::arch_category::intel_gpu); 251 #if GGML_SYCL_DNNL 252 info.devices[i].opt_feature.onednn_optimized_gemm = ggml_sycl_dnnl_detect_optimized_gemm(i); 253 #endif 254 info.devices[i].smpbo = prop.get_local_mem_size(); 255 info.devices[i].warp_size = WARP_SIZE; 256 info.devices[i].usm_system_support = device.has(sycl::aspect::usm_system_allocations); 257 258 #ifdef GGML_SYCL_GRAPH 259 info.devices[i].graph_support = device.has(sycl::aspect::ext_oneapi_limited_graph); 260 info.devices[i].graph_update_support = device.has(sycl::aspect::ext_oneapi_graph); 261 #endif 262 263 info.max_work_group_sizes[i] = prop.get_max_work_group_size(); 264 info.devices[i].max_wg_per_cu = info.max_work_group_sizes[i] / prop.get_max_compute_units(); 265 info.devices[i].hw_info = get_device_hw_info(&device); 266 267 // Only check GPU devices; CPU devices use OpenCL and would otherwise 268 // disable Level Zero for the GPUs on systems without ONEAPI_DEVICE_SELECTOR set. 269 if (device.is_gpu() && device.default_queue().get_backend() != sycl::backend::ext_oneapi_level_zero) { 270 GGML_LOG_WARN("SYCL GPU device %d does not use Level Zero backend, disabling Level Zero memory API\n", i); 271 info.ext_oneapi_level_zero = false; 272 } 273 274 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 275 if (info.ext_oneapi_level_zero && device.is_gpu() && device.default_queue().get_backend() == sycl::backend::ext_oneapi_level_zero) { 276 ze_device_handle_t ze_dev = sycl::get_native(device.default_queue().get_device()); 277 ze_device_properties_t props = {}; 278 props.stype = ZE_STRUCTURE_TYPE_DEVICE_PROPERTIES; 279 ze_result_t r = zeDeviceGetProperties(ze_dev, &props); 280 if (r == ZE_RESULT_SUCCESS) { 281 info.devices[i].l0_device_type_valid = true; 282 info.devices[i].l0_discrete_gpu = !(props.flags & ZE_DEVICE_PROPERTY_FLAG_INTEGRATED); 283 } 284 } 285 #endif 286 } 287 288 for (int id = 0; id < info.device_count; ++id) { 289 info.default_tensor_split[id] /= total_vram; 290 } 291 292 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 293 //update g_ggml_sycl_use_level_zero_api according to the device support 294 g_ggml_sycl_use_level_zero_api = 295 info.ext_oneapi_level_zero && g_ggml_sycl_use_level_zero_api; 296 #endif 297 298 return info; 299 } 300 301 ggml_sycl_device_info & ggml_sycl_info() { 302 static ggml_sycl_device_info info = ggml_sycl_init(); 303 return info; 304 } 305 306 static void print_device_detail(int id, sycl::device &device, std::string device_type) { 307 308 dpct::device_info prop; 309 SYCL_CHECK(CHECK_TRY_ERROR( 310 dpct::get_device_info(prop, device))); 311 312 std::string version; 313 version += std::to_string(prop.get_major_version()); 314 version += "."; 315 version += std::to_string(prop.get_minor_version()); 316 317 device_type = std::regex_replace(device_type, std::regex("ext_oneapi_"), ""); 318 std::string name = std::string(prop.get_name()); 319 name = std::regex_replace(name, std::regex("\\(R\\)"), ""); 320 name = std::regex_replace(name, std::regex("\\(TM\\)"), ""); 321 322 auto global_mem_size = prop.get_global_mem_size()/`1000000`; 323 GGML_LOG_INFO("|%2d|%19s|%39s|%7s|%7d|%8d|%5d|%6luM|%21s|\n", id, device_type.c_str(), 324 name.c_str(), version.c_str(), prop.get_max_compute_units(), 325 prop.get_max_work_group_size(), prop.get_max_sub_group_size(), 326 global_mem_size, device.get_info().c_str()); 327 } 328 329 static void print_device_opt_feature(int device_count) { 330 GGML_LOG_INFO("SYCL Optimization Feature:\n"); 331 GGML_LOG_INFO( 332 "|ID| Device Type|Reorder|\n"); 333 GGML_LOG_INFO( 334 "|--|-------------------|-------|\n"); 335 std::map DeviceNums; 336 for (int id = 0; id < device_count; ++id) { 337 sycl::device device = dpct::dev_mgr::instance().get_device(id); 338 std::string backend_type = get_device_backend_and_type(device); 339 int type_id = DeviceNums[backend_type]++; 340 std::stringstream device_type; 341 device_type << "[" << backend_type << ":" << std::to_string(type_id) 342 << "]"; 343 std::string device_type_s = device_type.str(); 344 device_type_s = std::regex_replace(device_type_s, std::regex("ext_oneapi_"), ""); 345 GGML_LOG_INFO("|%2d|%19s|%7s|\n", id, device_type_s.c_str(), 346 ggml_sycl_info().devices[id].opt_feature.reorder ? "Y": "N"); 347 } 348 349 } 350 void ggml_backend_sycl_print_sycl_devices() { 351 GGML_SYCL_DEBUG("[SYCL] call ggml_backend_sycl_print_sycl_devices\n"); 352 int device_count = dpct::dev_mgr::instance().device_count(); 353 std::map DeviceNums; 354 GGML_LOG_INFO("Found %d SYCL devices:\n", device_count); 355 356 GGML_LOG_INFO( 357 "| | | | " 358 " |Max | |Max |Global | |\n"); 359 GGML_LOG_INFO( 360 "| | | | " 361 " |compute|Max work|sub |mem | |\n"); 362 GGML_LOG_INFO( 363 "|ID| Device Type| " 364 "Name|Version|units |group |group|size | Driver version|\n"); 365 GGML_LOG_INFO( 366 "|--|-------------------|---------------------------------------|------" 367 "-|-------|--------|-----|-------|---------------------|\n"); 368 369 for (int id = 0; id < device_count; ++id) { 370 sycl::device device = dpct::dev_mgr::instance().get_device(id); 371 std::string backend_type = get_device_backend_and_type(device); 372 int type_id = DeviceNums[backend_type]++; 373 std::stringstream device_type; 374 device_type << "[" << backend_type << ":" << std::to_string(type_id) 375 << "]"; 376 print_device_detail(id, device, device_type.str()); 377 } 378 379 print_device_opt_feature(device_count); 380 } 381 382 static const char* dev2dev_int2str(int dev2dev) { 383 if (dev2dev == DEV2DEV_MEMCPY_SYCL) { 384 return "SYCL API"; 385 } else if (dev2dev == DEV2DEV_MEMCPY_L0) { 386 return "Level Zero API"; 387 } else if (dev2dev == DEV2DEV_MEMCPY_FORWARD) { 388 return "Host Forward"; 389 } else { 390 return "Unknown"; 391 } 392 } 393 394 /* 395 * There are several entry APIs to be called as first function in SYCL backend in different cases. 396 * It's the first internal function to be called by them in SYCL backend. 397 * This function is used to do initialize work for the SYCL backend and set the global variables. 398 */ 399 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 400 static ze_result_t init_zes() { 401 ze_result_t res = zesInit(0); 402 if (res != ZE_RESULT_SUCCESS) { 403 GGML_SYCL_DEBUG("Warning: [%s] zesInit failed with code %d. Sysman free-memory query be unavailable.\n", 404 __func__, (int) res); 405 } 406 return res; 407 } 408 409 static ze_result_t get_zes_init_res() { 410 static ze_result_t zes_init_res = init_zes(); 411 GGML_SYCL_DEBUG("[SYCL] call %s: zesInit result: %d\n", __func__, (int) zes_init_res); 412 return zes_init_res; 413 } 414 #endif 415 416 static void initialize_sycl_begining() { 417 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 418 //must be called in initialization stage, before any other Level Zero API calls 419 GGML_SYCL_DEBUG("[SYCL] call %s\n", __func__); 420 get_zes_init_res(); 421 #endif 422 } 423 424 static void ggml_check_sycl() try { 425 GGML_SYCL_DEBUG("[SYCL] ggml_check_sycl()\n"); 426 static bool initialized = false; 427 428 if (!initialized) { 429 initialize_sycl_begining(); 430 431 g_ggml_sycl_debug = ggml_sycl_get_env("GGML_SYCL_DEBUG", 0); 432 g_ggml_sycl_dev_debug = ggml_sycl_get_env("GGML_SYCL_DEV_DEBUG", 0); 433 g_ggml_sycl_enable_optimize = ggml_sycl_get_env("GGML_SYCL_ENABLE_OPT", 1); 434 g_ggml_sycl_enable_graph = ggml_sycl_get_env("GGML_SYCL_ENABLE_GRAPH", 0); 435 g_ggml_sycl_enable_dnn = ggml_sycl_get_env("GGML_SYCL_ENABLE_DNN", 1); 436 g_ggml_sycl_fa_onednn = ggml_sycl_get_env("GGML_SYCL_FA_ONEDNN", 1); 437 g_ggml_sycl_fa_onednn_max_kv = ggml_sycl_get_env("GGML_SYCL_FA_ONEDNN_MAX_KV", 0); 438 g_ggml_sycl_enable_mkl_fa = ggml_sycl_get_env("GGML_SYCL_ENABLE_MKL_FA", 1); 439 g_ggml_sycl_fa_dpas = ggml_sycl_get_env("GGML_SYCL_FA_DPAS", 1); 440 g_ggml_sycl_memtrace = ggml_sycl_get_env("GGML_SYCL_MEMTRACE", 0); 441 g_ggml_sycl_memtrace_step = ggml_sycl_get_env("GGML_SYCL_MEMTRACE_STEP", 64); 442 g_ggml_sycl_enable_vmm = ggml_sycl_get_env("GGML_SYCL_ENABLE_VMM", 1); 443 g_ggml_sycl_enable_fusion = ggml_sycl_get_env("GGML_SYCL_ENABLE_FUSION", 1); 444 g_ggml_sycl_enable_esimd = ggml_sycl_get_env("GGML_SYCL_ENABLE_ESIMD", 1); 445 g_ggml_sycl_mmvq_wide = ggml_sycl_get_env("GGML_SYCL_MMVQ_WIDE", 1); 446 g_ggml_sycl_enable_xmx_esimd = ggml_sycl_get_env("GGML_SYCL_ENABLE_XMX_ESIMD", 1); 447 g_ggml_sycl_xmx_max_cols = std::max(0, ggml_sycl_get_env("GGML_SYCL_XMX_MAX_COLS", GGML_SYCL_XMX_MAX_COLS_DEFAULT)); 448 g_ggml_sycl_xmx_glu_max_cols = 449 std::clamp(ggml_sycl_get_env("GGML_SYCL_XMX_GLU_MAX_COLS", GGML_SYCL_XMX_GLU_MAX_COLS), 0, GGML_SYCL_XMX_GLU_MAX_COLS); 450 g_ggml_sycl_prioritize_dmmv = ggml_sycl_get_env("GGML_SYCL_PRIORITIZE_DMMV", 0); 451 g_ggml_sycl_graph_eviction_timeout = ggml_sycl_get_env("GGML_SYCL_GRAPH_EVICTION_TIMEOUT", 10); 452 g_ggml_sycl_xmx_gather_types = ggml_sycl_get_env("GGML_SYCL_XMX_GATHER_TYPES", GGML_SYCL_XMX_GATHER_TYPES_DEFAULT); 453 g_ggml_sycl_xmx_gather_shapes = ggml_sycl_get_env("GGML_SYCL_XMX_GATHER_SHAPES", GGML_SYCL_XMX_GATHER_SHAPES_DEFAULT); 454 g_ggml_sycl_dynamic_precision = 455 ggml_sycl_get_env_precision("GGML_SYCL_DYNAMIC_PRECISION", GGML_SYCL_DYNAMIC_PRECISION_DEFAULT); 456 g_ggml_sycl_dynamic_required_precision = 457 ggml_sycl_get_env_precision("GGML_SYCL_DYNAMIC_REQUIRED_PRECISION", GGML_SYCL_DYNAMIC_PRECISION_F32); 458 459 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 460 g_ggml_sycl_use_level_zero_api = ggml_sycl_get_env("GGML_SYCL_USE_LEVEL_ZERO_API", 1); 461 #else 462 g_ggml_sycl_use_level_zero_api = 0; 463 #endif 464 g_ggml_sycl_dev2dev_memcpy = ggml_sycl_get_env("GGML_SYCL_DEV2DEV_MEMCPY", DEV2DEV_MEMCPY_SYCL); 465 g_ggml_sycl_get_mem_api = ggml_sycl_get_env("GGML_SYCL_GET_MEM_API", MEMORY_API_TYPE_LEVEL_ZERO); 466 if (g_ggml_sycl_use_level_zero_api == 0) { 467 g_ggml_sycl_dev2dev_memcpy = DEV2DEV_MEMCPY_SYCL; 468 g_ggml_sycl_get_mem_api = MEMORY_API_TYPE_SYCL; 469 } 470 471 #ifdef SYCL_FLASH_ATTN 472 g_ggml_sycl_enable_flash_attention = ggml_sycl_get_env("GGML_SYCL_ENABLE_FLASH_ATTN", 1); 473 #else 474 g_ggml_sycl_enable_flash_attention = 0; 475 #endif 476 477 g_ggml_sycl_usm_system = ggml_sycl_get_env("GGML_SYCL_USM_SYSTEM", 0); 478 g_ggml_sycl_enable_host_pinned_mem = 479 ggml_sycl_get_env("GGML_SYCL_ENABLE_HOST_PINNED_MEM", 1); 480 481 g_ggml_sycl_host_pinned_mem_2g = 482 ggml_sycl_get_env("GGML_SYCL_HOST_PINNED_MEM_2G", 0) & g_ggml_sycl_enable_host_pinned_mem; 483 g_ggml_sycl_upload_staging_slots = std::max(0, ggml_sycl_get_env("GGML_SYCL_UPLOAD_STAGING_SLOTS", 4)); 484 485 g_ggml_sycl_enable_sparse_fa = ggml_sycl_get_env("GGML_SYCL_SPARSE_FA", 0); 486 g_ggml_sycl_debug_sparse_fa = ggml_sycl_get_env("GGML_SYCL_SPARSE_FA_DEBUG", 0); 487 g_ggml_sycl_sparse_fa_margin = ggml_sycl_get_env("GGML_SYCL_SPARSE_FA_MARGIN", 256); 488 489 GGML_SYCL_DEBUG("[SYCL] call ggml_check_sycl\n"); 490 491 GGML_LOG_INFO("Build with Macros:\n"); 492 #if defined(GGML_SYCL_DNNL) 493 GGML_LOG_INFO(" GGML_SYCL_DNNL: yes\n"); 494 #else 495 GGML_LOG_INFO(" GGML_SYCL_DNNL: no\n"); 496 #endif 497 498 #if defined(GGML_SYCL_F16) 499 GGML_LOG_INFO(" GGML_SYCL_F16: yes\n"); 500 #else 501 GGML_LOG_INFO(" GGML_SYCL_F16: no\n"); 502 #endif 503 504 #if defined(GGML_SYCL_FORCE_MMQ) 505 GGML_LOG_INFO(" GGML_SYCL_FORCE_MMQ: yes\n"); 506 #else 507 GGML_LOG_INFO(" GGML_SYCL_FORCE_MMQ: no\n"); 508 #endif 509 510 #if defined(GGML_SYCL_SUPPORT_XMX) 511 GGML_LOG_INFO(" GGML_SYCL_SUPPORT_XMX: yes\n"); 512 #else 513 GGML_LOG_INFO(" GGML_SYCL_SUPPORT_XMX: no\n"); 514 #endif 515 516 #if defined(GGML_SYCL_GRAPH) 517 GGML_LOG_INFO(" GGML_SYCL_GRAPH: yes\n"); 518 #else 519 GGML_LOG_INFO(" GGML_SYCL_GRAPH: no\n"); 520 #endif 521 522 #if defined(GGML_SYCL_SUPPORT_LEVEL_ZERO_API) 523 GGML_LOG_INFO(" GGML_SYCL_SUPPORT_LEVEL_ZERO_API: yes\n"); 524 #else 525 GGML_LOG_INFO(" GGML_SYCL_SUPPORT_LEVEL_ZERO_API: no\n"); 526 #endif 527 #if defined(GGML_SYCL_SUPPORT_VMM) 528 GGML_LOG_INFO(" GGML_SYCL_SUPPORT_VMM: yes\n"); 529 #else 530 GGML_LOG_INFO(" GGML_SYCL_SUPPORT_VMM: no\n"); 531 #endif 532 533 //Print the running environment variables for SYCL backend 534 GGML_LOG_INFO("Running with Environment Variables:\n"); 535 GGML_LOG_INFO(" GGML_SYCL_DEBUG: %d\n", g_ggml_sycl_debug); 536 GGML_LOG_INFO(" GGML_SYCL_DEV_DEBUG: %d\n", g_ggml_sycl_dev_debug); 537 538 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 539 GGML_LOG_INFO(" GGML_SYCL_DEV2DEV_MEMCPY: %d (%s)\n", g_ggml_sycl_dev2dev_memcpy, dev2dev_int2str(g_ggml_sycl_dev2dev_memcpy)); 540 GGML_LOG_INFO(" GGML_SYCL_GET_MEM_API: %d (%s)\n", g_ggml_sycl_get_mem_api, mem_api_int2str(g_ggml_sycl_get_mem_api)); 541 #else 542 GGML_LOG_INFO(" GGML_SYCL_DEV2DEV_MEMCPY: %d (%s), enable to SYCL API since missing GGML_SYCL_SUPPORT_LEVEL_ZERO_API\n", 543 g_ggml_sycl_dev2dev_memcpy, dev2dev_int2str(g_ggml_sycl_dev2dev_memcpy)); 544 GGML_LOG_INFO(" GGML_SYCL_GET_MEM_API: %d (%s), enable to SYCL API since missing GGML_SYCL_SUPPORT_LEVEL_ZERO_API\n", 545 g_ggml_sycl_get_mem_api, mem_api_int2str(g_ggml_sycl_get_mem_api)); 546 #endif 547 548 #if defined(GGML_SYCL_DNNL) 549 GGML_LOG_INFO(" GGML_SYCL_ENABLE_DNN: %d\n", g_ggml_sycl_enable_dnn); 550 GGML_LOG_INFO(" GGML_SYCL_FA_ONEDNN: %d\n", g_ggml_sycl_fa_onednn); 551 #else 552 GGML_LOG_INFO(" GGML_SYCL_ENABLE_DNN: DNN disabled by compile flag\n"); 553 GGML_LOG_INFO(" GGML_SYCL_FA_ONEDNN: %d\n", g_ggml_sycl_fa_onednn); 554 #endif 555 GGML_LOG_INFO(" GGML_SYCL_FA_ONEDNN_MAX_KV: %d\n", g_ggml_sycl_fa_onednn_max_kv); 556 GGML_LOG_INFO(" GGML_SYCL_ENABLE_MKL_FA: %d\n", g_ggml_sycl_enable_mkl_fa); 557 GGML_LOG_INFO(" GGML_SYCL_FA_DPAS: %d\n", g_ggml_sycl_fa_dpas); 558 GGML_LOG_INFO(" GGML_SYCL_MEMTRACE: %d\n", g_ggml_sycl_memtrace); 559 GGML_LOG_INFO(" GGML_SYCL_MEMTRACE_STEP: %d\n", g_ggml_sycl_memtrace_step); 560 #ifdef SYCL_FLASH_ATTN 561 GGML_LOG_INFO(" GGML_SYCL_ENABLE_FLASH_ATTN: %d\n", g_ggml_sycl_enable_flash_attention); 562 #else 563 GGML_LOG_INFO(" GGML_SYCL_ENABLE_FLASH_ATTN: %d disabled by compile flag\n", 564 g_ggml_sycl_enable_flash_attention); 565 #endif 566 567 #ifdef GGML_SYCL_GRAPH 568 GGML_LOG_INFO(" GGML_SYCL_ENABLE_GRAPH: %d\n", g_ggml_sycl_enable_graph); 569 GGML_LOG_INFO(" GGML_SYCL_GRAPH_EVICTION_TIMEOUT: %d\n", g_ggml_sycl_graph_eviction_timeout); 570 #else 571 GGML_LOG_INFO(" GGML_SYCL_ENABLE_GRAPH: graph disabled by compile flag\n"); 572 #endif 573 574 GGML_LOG_INFO(" GGML_SYCL_ENABLE_OPT: %d\n", g_ggml_sycl_enable_optimize); 575 GGML_LOG_INFO(" GGML_SYCL_XMX_GATHER_TYPES: %d\n", g_ggml_sycl_xmx_gather_types); 576 GGML_LOG_INFO(" GGML_SYCL_XMX_GATHER_SHAPES: %d\n", g_ggml_sycl_xmx_gather_shapes); 577 GGML_LOG_INFO(" GGML_SYCL_DYNAMIC_PRECISION: %s\n", 578 ggml_sycl_dynamic_precision_names[g_ggml_sycl_dynamic_precision]); 579 GGML_LOG_INFO(" GGML_SYCL_DYNAMIC_REQUIRED_PRECISION: %s\n", 580 ggml_sycl_dynamic_precision_names[g_ggml_sycl_dynamic_required_precision]); 581 582 #if defined(GGML_SYCL_SUPPORT_VMM) 583 GGML_LOG_INFO(" GGML_SYCL_ENABLE_VMM: %d\n", g_ggml_sycl_enable_vmm); 584 #else 585 GGML_LOG_INFO(" GGML_SYCL_ENABLE_VMM: virtual memory extension is not available\n"); 586 #endif 587 588 GGML_LOG_INFO(" GGML_SYCL_ENABLE_FUSION: %d\n", g_ggml_sycl_enable_fusion); 589 GGML_LOG_INFO(" GGML_SYCL_UPLOAD_STAGING_SLOTS: %d\n", g_ggml_sycl_upload_staging_slots); 590 591 #if defined(__INTEL_LLVM_COMPILER) 592 GGML_LOG_INFO(" GGML_SYCL_ENABLE_ESIMD: %d\n", g_ggml_sycl_enable_esimd); 593 #else 594 GGML_LOG_INFO(" GGML_SYCL_ENABLE_ESIMD: %d disabled by compile flag\n", g_ggml_sycl_enable_esimd); 595 #endif 596 597 GGML_LOG_INFO(" GGML_SYCL_MMVQ_WIDE: %d\n", g_ggml_sycl_mmvq_wide); 598 599 GGML_LOG_INFO(" GGML_SYCL_ENABLE_XMX_ESIMD: %d\n", g_ggml_sycl_enable_xmx_esimd); 600 GGML_LOG_INFO(" GGML_SYCL_XMX_MAX_COLS: %d\n", g_ggml_sycl_xmx_max_cols); 601 GGML_LOG_INFO(" GGML_SYCL_XMX_GLU_MAX_COLS: %d\n", g_ggml_sycl_xmx_glu_max_cols); 602 603 GGML_LOG_INFO(" GGML_SYCL_PRIORITIZE_DMMV: %d\n", g_ggml_sycl_prioritize_dmmv); 604 605 g_ggml_sycl_use_async_mem_op_requested = ggml_sycl_get_env("GGML_SYCL_USE_ASYNC_MEM_OP", 1); 606 GGML_LOG_INFO(" GGML_SYCL_USE_ASYNC_MEM_OP: %d\n", g_ggml_sycl_use_async_mem_op_requested); 607 608 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 609 GGML_LOG_INFO(" GGML_SYCL_USE_LEVEL_ZERO_API: %d\n", g_ggml_sycl_use_level_zero_api); 610 #else 611 GGML_LOG_INFO(" GGML_SYCL_USE_LEVEL_ZERO_API: Disable Level Zero API usage by compile flag\n"); 612 #endif 613 614 GGML_LOG_INFO(" GGML_SYCL_USM_SYSTEM: %d\n", g_ggml_sycl_usm_system); 615 GGML_LOG_INFO(" GGML_SYCL_ENABLE_HOST_PINNED_MEM: %d\n", g_ggml_sycl_enable_host_pinned_mem); 616 GGML_LOG_INFO(" GGML_SYCL_HOST_PINNED_MEM_2G: %d\n", g_ggml_sycl_host_pinned_mem_2g); 617 618 GGML_LOG_INFO(" GGML_SYCL_SPARSE_FA: %d\n", g_ggml_sycl_enable_sparse_fa); 619 GGML_LOG_INFO(" GGML_SYCL_SPARSE_FA_DEBUG: %d\n", g_ggml_sycl_debug_sparse_fa); 620 GGML_LOG_INFO(" GGML_SYCL_SPARSE_FA_MARGIN: %d\n", g_ggml_sycl_sparse_fa_margin); 621 622 /* NOT REMOVE, keep it for next optimize for XMX. 623 #if defined(GGML_SYCL_SUPPORT_XMX) && !defined(GGML_SYCL_FORCE_MMQ) 624 fprintf(stderr, "%s: GGML_SYCL_SUPPORT_XMX: yes\n", __func__); 625 #else 626 fprintf(stderr, "%s: GGML_SYCL_SUPPORT_XMX: no\n", __func__); 627 #endif 628 */ 629 #ifdef GGML_SYCL_GRAPH 630 if (g_ggml_sycl_enable_graph) { 631 for (unsigned int i = 0; i < dpct::dev_mgr::instance().device_count(); ++i) { 632 if (!dpct::dev_mgr::instance().get_device(i).has(sycl::aspect::ext_oneapi_limited_graph)) { 633 GGML_LOG_WARN("SYCL device %u does not support SYCL graphs\n", i); 634 } 635 } 636 } 637 638 // Async USM allocation/free is also useful outside the graph path: it avoids the host waits in the reorder 639 // staging path while preserving queue ordering semantics. Graph support still depends on the extension being 640 // available, but it no longer needs to control the non-graph fast path. 641 #if SYCL_EXT_ONEAPI_ASYNC_MEMORY_ALLOC 642 g_ggml_sycl_use_async_mem_op = g_ggml_sycl_use_async_mem_op_requested || g_ggml_sycl_enable_graph; 643 if (g_ggml_sycl_use_async_mem_op) { 644 for (unsigned int i = 0; i < dpct::dev_mgr::instance().device_count(); ++i) { 645 if (!dpct::dev_mgr::instance().get_device(i).has(sycl::aspect::ext_oneapi_async_memory_alloc)) { 646 g_ggml_sycl_use_async_mem_op = 0; 647 break; 648 } 649 } 650 } 651 #endif 652 #endif 653 if (CHECK_TRY_ERROR(g_all_sycl_device_count = 654 dpct::dev_mgr::instance().device_count()) != 0) { 655 initialized = true; 656 g_sycl_loaded = false; 657 return; 658 } 659 GGML_ASSERT(g_all_sycl_device_count <= GGML_SYCL_MAX_DEVICES); 660 661 initialized = true; 662 g_sycl_loaded = true; 663 ggml_backend_sycl_print_sycl_devices(); 664 } 665 } 666 catch (sycl::exception const &exc) { 667 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 668 << ", line:" << __LINE__ << std::endl; 669 std::exit(1); 670 } 671 672 /* 673 device_index: device index from 0 to n (continue numbers). 674 It is used for device select/set in SYCL backend internal data structure. 675 */ 676 inline void check_allow_gpu_index(const int device_index) { 677 if (device_index >= ggml_sycl_info().device_count) { 678 char error_buf[256]; 679 snprintf( 680 error_buf, 681 sizeof(error_buf), 682 "%s error: device_index:%d is out of range: [0-%d]", 683 __func__, 684 device_index, 685 ggml_sycl_info().device_count - 1); 686 GGML_LOG_ERROR("%s\n", error_buf); 687 assert(false); 688 } 689 } 690 691 GGML_API void ggml_backend_sycl_get_gpu_list(int *id_list, int max_len) try { 692 GGML_SYCL_DEBUG("[SYCL] call ggml_backend_sycl_get_gpu_list\n"); 693 for(int i=0;i=max_len) break; 697 id_list[i] = i; 698 } 699 return; 700 } 701 catch (sycl::exception const &exc) { 702 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 703 << ", line:" << __LINE__ << std::endl; 704 std::exit(1); 705 } 706 707 inline void free_aligned_mem_host(void * memblock) { 708 #ifdef _WIN32 709 _aligned_free(memblock); 710 #else 711 free(memblock); 712 #endif 713 } 714 715 // sycl buffer 716 717 struct ggml_backend_sycl_buffer_context { 718 // pinned staging for uploads; the host fills one slot while the previous one transfers 719 static constexpr size_t staging_slot_size = 8*1024*1024; 720 721 struct host_staging { 722 void * data = nullptr; 723 std::vector events; 724 std::vector submitted; 725 int next = 0; 726 }; 727 728 int device; 729 void * dev_ptr = nullptr; 730 queue_ptr stream; 731 std::string name; 732 optimize_feature opt_feature; 733 std::vector tensor_extras; 734 host_staging staging; 735 bool is_usm_system; 736 737 ggml_backend_sycl_buffer_context(int device, void * dev_ptr, queue_ptr stream, bool is_usm_system) : 738 device(device), dev_ptr(dev_ptr), stream(stream), is_usm_system(is_usm_system) { 739 check_allow_gpu_index(device); 740 name = (GGML_SYCL_NAME + std::to_string(device)); 741 opt_feature = ggml_sycl_info().devices[device].opt_feature; 742 } 743 744 // waits for every queued upload, then releases the pinned block 745 void drop_host_staging() { 746 for (size_t i = 0; i < staging.submitted.size(); ++i) { 747 if (staging.submitted[i]) { 748 staging.events[i].wait_and_throw(); 749 staging.submitted[i] = false; 750 } 751 } 752 if (staging.data != nullptr) { 753 sycl::free(staging.data, *stream); 754 staging.data = nullptr; 755 } 756 } 757 758 ~ggml_backend_sycl_buffer_context() { 759 drop_host_staging(); 760 if (dev_ptr != nullptr) { 761 ggml_sycl_set_device(device); 762 if (is_usm_system) 763 free_aligned_mem_host(dev_ptr); 764 else 765 SYCL_CHECK(CHECK_TRY_ERROR(ggml_sycl_free_device(dev_ptr, *stream))); 766 } 767 768 //release extra used by tensors 769 for (ggml_tensor_extra_gpu * extra : tensor_extras) { 770 release_extra_gpu(extra); 771 } 772 773 } 774 }; 775 776 static const char * ggml_backend_sycl_buffer_type_get_name(ggml_backend_buffer_type_t buft); 777 778 static bool ggml_backend_buffer_is_sycl(ggml_backend_buffer_t buffer) { 779 return buffer->buft->iface.get_name == ggml_backend_sycl_buffer_type_get_name; 780 } 781 782 static void 783 ggml_backend_sycl_buffer_free_buffer(ggml_backend_buffer_t buffer) try { 784 ggml_backend_sycl_buffer_context * ctx = ( ggml_backend_sycl_buffer_context *)buffer->context; 785 ggml_sycl_set_device(ctx->device); 786 787 delete ctx; 788 } 789 catch (sycl::exception const &exc) { 790 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 791 << ", line:" << __LINE__ << std::endl; 792 std::exit(1); 793 } 794 795 static void * ggml_backend_sycl_buffer_get_base(ggml_backend_buffer_t buffer) { 796 ggml_backend_sycl_buffer_context * ctx = ( ggml_backend_sycl_buffer_context *)buffer->context; 797 return ctx->dev_ptr; 798 } 799 800 static enum ggml_status 801 ggml_backend_sycl_buffer_init_tensor(ggml_backend_buffer_t buffer, 802 ggml_tensor *tensor) try { 803 GGML_SYCL_DEBUG("[SYCL] call %s", __func__); 804 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(": tensor", tensor, "\n").c_str()); 805 ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context *)buffer->context; 806 807 if (tensor->view_src != NULL) { 808 assert(tensor->view_src->buffer->buft == buffer->buft); 809 return GGML_STATUS_SUCCESS; 810 } 811 812 if (g_ggml_sycl_enable_optimize) { 813 // set reorder extra buffer based on supported type 814 switch (tensor->type) { 815 case GGML_TYPE_Q4_0: 816 case GGML_TYPE_Q8_0: 817 case GGML_TYPE_Q2_K: 818 case GGML_TYPE_Q3_K: 819 case GGML_TYPE_Q4_K: 820 case GGML_TYPE_Q5_K: 821 case GGML_TYPE_Q6_K: 822 case GGML_TYPE_IQ3_XXS: 823 case GGML_TYPE_IQ3_S: 824 case GGML_TYPE_MXFP4:{ 825 ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu{}; 826 tensor->extra = extra; 827 ctx->tensor_extras.push_back(extra); 828 break; 829 } 830 default: 831 break; 832 } 833 } 834 835 if (ggml_is_quantized(tensor->type)) { 836 // initialize padding to 0 to avoid possible NaN values 837 size_t original_size = ggml_nbytes(tensor); 838 size_t padded_size = ggml_backend_buft_get_alloc_size(buffer->buft, tensor); 839 840 if (padded_size > original_size && tensor->view_src == nullptr) { 841 SYCL_CHECK(CHECK_TRY_ERROR(ctx->stream->memset( 842 (char *)tensor->data + original_size, 0, 843 padded_size - original_size).wait())); 844 } 845 } 846 return GGML_STATUS_SUCCESS; 847 } 848 catch (sycl::exception const &exc) { 849 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 850 << ", line:" << __LINE__ << std::endl; 851 std::exit(1); 852 } 853 854 // allocates the pinned upload staging on first use; returns false if staging is disabled or the allocation failed 855 static bool ggml_sycl_buffer_init_staging(ggml_backend_sycl_buffer_context * ctx) { 856 const int n_slots = g_ggml_sycl_upload_staging_slots; 857 if (n_slots > 0 && ctx->staging.data == nullptr) { 858 ctx->staging.data = sycl::malloc_host(n_slots * ctx->staging_slot_size, *ctx->stream); 859 if (ctx->staging.data != nullptr) { 860 ctx->staging.events.resize(n_slots); 861 ctx->staging.submitted.assign(n_slots, false); 862 } 863 } 864 return ctx->staging.data != nullptr; 865 } 866 867 static void ggml_backend_sycl_buffer_set_tensor(ggml_backend_buffer_t buffer, 868 ggml_tensor *tensor, 869 const void *data, size_t offset, 870 size_t size) try { 871 GGML_SYCL_DEBUG("[SYCL] call %s", __func__); 872 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(": tensor", tensor).c_str()); 873 GGML_SYCL_DEBUG(" size=%zu offset=%zu\n", size, offset); 874 ggml_backend_sycl_buffer_context * ctx = ( ggml_backend_sycl_buffer_context *)buffer->context; 875 ggml_sycl_set_device(ctx->device); 876 877 // copy through pinned memory so the device never reads mmap()ed pages directly 878 // chunks pipeline on the in-order compute queue, so no drain per tensor is needed 879 if (ggml_sycl_buffer_init_staging(ctx)) { 880 queue_ptr stream = ctx->stream; 881 char * dst = (char *) tensor->data + offset; 882 const char * src = (const char *) data; 883 size_t remaining = size; 884 while (remaining > 0) { 885 const size_t chunk = std::min(remaining, ctx->staging_slot_size); 886 const int slot = ctx->staging.next; 887 ctx->staging.next = (ctx->staging.next + 1) % (int) ctx->staging.submitted.size(); 888 if (ctx->staging.submitted[slot]) { 889 ctx->staging.events[slot].wait_and_throw(); 890 } 891 void * stage = (char *) ctx->staging.data + slot * ctx->staging_slot_size; 892 memcpy(stage, src, chunk); 893 ctx->staging.events[slot] = stream->memcpy(dst, stage, chunk); 894 ctx->staging.submitted[slot] = true; 895 src += chunk; 896 dst += chunk; 897 remaining -= chunk; 898 } 899 return; 900 } 901 902 auto stream = &(dpct::dev_mgr::instance().get_device(ctx->device).default_queue()); 903 SYCL_CHECK(CHECK_TRY_ERROR(dpct::dev_mgr::instance().get_device(ctx->device).queues_wait_and_throw())); 904 #ifndef _WIN32 905 // Note: Use host buffer to save the data from mmap(), then copy to device. It's workaround for mmap() issue on PVC GPU. 906 // This function will be called during load model from disk. Use memory buffer replace dynamic won't save more time and brings potential memory leak risk here. 907 char * host_buf = (char *) malloc(size); 908 memcpy(host_buf, data, size); 909 SYCL_CHECK(CHECK_TRY_ERROR((*stream).memcpy((char *) tensor->data + offset, host_buf, size).wait())); 910 free(host_buf); 911 #else 912 SYCL_CHECK(CHECK_TRY_ERROR((*stream).memcpy((char *) tensor->data + offset, data, size).wait())); 913 #endif 914 } 915 catch (sycl::exception const &exc) { 916 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 917 << ", line:" << __LINE__ << std::endl; 918 std::exit(1); 919 } 920 921 // Copy n_copies rows in one call. -sm tensor uploads split weights this way; the generic fallback does one set_tensor per row. 922 static void ggml_backend_sycl_buffer_set_tensor_2d(ggml_backend_buffer_t buffer, ggml_tensor * tensor, 923 const void * data, size_t offset, size_t size, 924 size_t n_copies, size_t stride_tensor, 925 size_t stride_data) try { 926 ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context *) buffer->context; 927 const char * src = (const char *) data; 928 ggml_sycl_set_device(ctx->device); 929 930 if (stride_tensor != size || size > ctx->staging_slot_size || !ggml_sycl_buffer_init_staging(ctx)) { 931 // dst rows not contiguous, row larger than a staging slot, or no staging: same as the generic fallback 932 for (size_t i = 0; i < n_copies; ++i) { 933 ggml_backend_sycl_buffer_set_tensor(buffer, tensor, src + i * stride_data, offset + i * stride_tensor, size); 934 } 935 return; 936 } 937 938 // dst rows are contiguous: pack as many rows as fit into a staging slot and copy each slot with one memcpy 939 // a slot is only waited on when it is reused, so packing the next slot overlaps with the previous copies 940 queue_ptr stream = ctx->stream; 941 char * dst = (char *) tensor->data + offset; 942 const size_t rows_per_slot = ctx->staging_slot_size / size; 943 for (size_t i0 = 0; i0 < n_copies; i0 += rows_per_slot) { 944 const size_t n = std::min(rows_per_slot, n_copies - i0); 945 const int slot = ctx->staging.next; 946 ctx->staging.next = (ctx->staging.next + 1) % (int) ctx->staging.submitted.size(); 947 if (ctx->staging.submitted[slot]) { 948 ctx->staging.events[slot].wait_and_throw(); 949 } 950 char * stage = (char *) ctx->staging.data + slot * ctx->staging_slot_size; 951 for (size_t i = 0; i < n; ++i) { 952 memcpy(stage + i * size, src + (i0 + i) * stride_data, size); 953 } 954 ctx->staging.events[slot] = stream->memcpy(dst + i0 * size, stage, n * size); 955 ctx->staging.submitted[slot] = true; 956 } 957 } 958 catch (sycl::exception const &exc) { 959 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 960 << ", line:" << __LINE__ << std::endl; 961 std::exit(1); 962 } 963 964 static void ggml_backend_sycl_buffer_get_tensor(ggml_backend_buffer_t buffer, 965 const ggml_tensor *tensor, 966 void *data, size_t offset, 967 size_t size) try { 968 GGML_SYCL_DEBUG("[SYCL] call %s", __func__); 969 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(": tensor", tensor).c_str()); 970 GGML_SYCL_DEBUG(" size=%zu offset=%zu\n", size, offset); 971 ggml_backend_sycl_buffer_context * ctx = ( ggml_backend_sycl_buffer_context *)buffer->context; 972 973 ggml_sycl_set_device(ctx->device); 974 auto stream = dpct::dev_mgr::instance().get_device(ctx->device).default_queue(); 975 976 SYCL_CHECK(CHECK_TRY_ERROR( 977 stream.memcpy(data, (const char *)tensor->data + offset, size) 978 .wait())); 979 } 980 catch (sycl::exception const &exc) { 981 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 982 << ", line:" << __LINE__ << std::endl; 983 std::exit(1); 984 } 985 986 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 987 static bool ggml_sycl_is_l0_discrete_gpu(int device) { 988 return ggml_sycl_info().devices[device].l0_discrete_gpu; 989 } 990 #endif 991 992 static void memcpy_host_forward(sycl::queue &q_dst, sycl::queue &q_src, void *ptr_dst, 993 const void *ptr_src, size_t size) { 994 char *host_buf = (char *)malloc(size); 995 if (host_buf == nullptr) { 996 GGML_LOG_ERROR("%s: can't allocate %zu Bytes of memory for host staging\n", __func__, size); 997 GGML_ABORT("fatal error"); 998 } 999 q_src.memcpy(host_buf, (const char *)ptr_src, size).wait(); 1000 q_dst.memcpy((char *)ptr_dst, host_buf, size).wait(); 1001 free(host_buf); 1002 } 1003 1004 static void dev2dev_memcpy(int device_dst, sycl::queue &q_dst, int device_src, sycl::queue &q_src, void *ptr_dst, 1005 const void *ptr_src, size_t size) { 1006 1007 #ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 1008 if (g_ggml_sycl_dev2dev_memcpy == DEV2DEV_MEMCPY_L0) { 1009 // Use Level Zero direct copy for dGPU-to-dGPU transfers. 1010 const bool l0_copy_supported = 1011 ggml_sycl_is_l0_discrete_gpu(device_dst) && ggml_sycl_is_l0_discrete_gpu(device_src); 1012 if (g_ggml_sycl_use_level_zero_api && l0_copy_supported) { 1013 auto ze_ctx = sycl::get_native(q_dst.get_context()); 1014 auto ze_dev = sycl::get_native(q_dst.get_device()); 1015 ze_command_queue_desc_t cq_desc = {ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC, nullptr, 0, 0, 1016 0, ZE_COMMAND_QUEUE_MODE_SYNCHRONOUS, ZE_COMMAND_QUEUE_PRIORITY_NORMAL}; 1017 ze_command_list_handle_t cl; 1018 ze_result_t r = zeCommandListCreateImmediate(ze_ctx, ze_dev, &cq_desc, &cl); 1019 if (r == ZE_RESULT_SUCCESS) { 1020 GGML_SYCL_DEBUG("[SYCL] dev2dev memcpy by L0\n"); 1021 r = zeCommandListAppendMemoryCopy(cl, ptr_dst, ptr_src, size, nullptr, 0, nullptr); 1022 zeCommandListDestroy(cl); 1023 if (r == ZE_RESULT_SUCCESS) { 1024 return; 1025 } 1026 } 1027 } 1028 } 1029 #endif 1030 1031 if (g_ggml_sycl_dev2dev_memcpy == DEV2DEV_MEMCPY_SYCL) { 1032 if (q_dst.get_device().ext_oneapi_can_access_peer(q_src.get_device(), 1033 sycl::ext::oneapi::peer_access::access_supported)) { 1034 GGML_SYCL_DEBUG("[SYCL] dev2dev memcpy by SYCL\n"); 1035 q_dst.get_device().ext_oneapi_enable_peer_access(q_src.get_device()); 1036 SYCL_CHECK(CHECK_TRY_ERROR(q_dst.memcpy(ptr_dst, ptr_src, size).wait())); 1037 return; 1038 } 1039 } 1040 1041 // Host-staged copy 1042 if(g_ggml_sycl_dev2dev_memcpy == DEV2DEV_MEMCPY_FORWARD) { 1043 GGML_SYCL_DEBUG("[SYCL] dev2dev memcpy by host forward for setting GGML_SYCL_DEV2DEV_MEMCPY=2\n"); 1044 } else { 1045 GGML_SYCL_DEBUG("[SYCL] dev2dev memcpy by host forward for SYCL/L0 fallback\n"); 1046 } 1047 memcpy_host_forward(q_dst, q_src, ptr_dst, ptr_src, size); 1048 } 1049 1050 static bool 1051 ggml_backend_sycl_buffer_cpy_tensor(ggml_backend_buffer_t buffer, 1052 const ggml_tensor *src, 1053 ggml_tensor *dst) try { 1054 bool is_cpy_supported = ggml_backend_buffer_is_sycl(src->buffer); 1055 GGML_SYCL_DEBUG("[SYCL] call %s", __func__); 1056 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(": dst", dst).c_str()); 1057 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(" src", src).c_str()); 1058 GGML_SYCL_DEBUG(" is_cpy_supported=%d\n", is_cpy_supported); 1059 if (is_cpy_supported) { 1060 ggml_backend_sycl_buffer_context * src_ctx = (ggml_backend_sycl_buffer_context *)src->buffer->context; 1061 ggml_backend_sycl_buffer_context * dst_ctx = (ggml_backend_sycl_buffer_context *)dst->buffer->context; 1062 1063 ggml_sycl_set_device(src_ctx->device); 1064 /* 1065 DPCT1009:198: SYCL uses exceptions to report errors and does not use the 1066 error codes. The original code was commented out and a warning string 1067 was inserted. You need to rewrite this code. 1068 */ 1069 SYCL_CHECK(CHECK_TRY_ERROR( 1070 dpct::dev_mgr::instance().get_device(src_ctx->device).queues_wait_and_throw())); 1071 ggml_sycl_set_device(dst_ctx->device); 1072 /* 1073 DPCT1009:199: SYCL uses exceptions to report errors and does not use the 1074 error codes. The original code was commented out and a warning string 1075 was inserted. You need to rewrite this code. 1076 */ 1077 SYCL_CHECK(CHECK_TRY_ERROR( 1078 dpct::dev_mgr::instance().get_device(dst_ctx->device).queues_wait_and_throw())); 1079 /* 1080 DPCT1009:200: SYCL uses exceptions to report errors and does not use the 1081 error codes. The original code was commented out and a warning string 1082 was inserted. You need to rewrite this code. 1083 */ 1084 1085 queue_ptr stream_dst = dst_ctx->stream; 1086 queue_ptr stream_src = src_ctx->stream; 1087 size_t size = ggml_nbytes(src); 1088 1089 //todo. it's dirty solutino to walkaroud known issue:device2device cross GPUs. 1090 dev2dev_memcpy(dst_ctx->device, *stream_dst, src_ctx->device, *stream_src, dst->data, src->data, size); 1091 1092 //todo, it's known issue:error in device2device cross GPUs. reused when the issue is fixed. DON"T remove 1093 #if 0 1094 SYCL_CHECK(CHECK_TRY_ERROR((*stream).memcpy( 1095 (char *)dst->data, (const char *)src->data, size).wait())); 1096 1097 /* 1098 DPCT1009:201: SYCL uses exceptions to report errors and does not use the 1099 error codes. The original code was commented out and a warning string 1100 was inserted. You need to rewrite this code. 1101 */ 1102 SYCL_CHECK(CHECK_TRY_ERROR( 1103 dpct::dev_mgr::instance().get_device(dst_ctx->device).queues_wait_and_throw())); 1104 #endif 1105 return true; 1106 } 1107 return false; 1108 GGML_UNUSED(buffer); 1109 } catch (const sycl::exception & exc) { 1110 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ << ", line:" << __LINE__ << std::endl; 1111 std::exit(1); 1112 } 1113 1114 static void ggml_backend_sycl_buffer_clear(ggml_backend_buffer_t buffer, 1115 uint8_t value) try { 1116 GGML_SYCL_DEBUG("[SYCL] call %s: size=%zu\n", __func__, buffer->size); 1117 ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context *) buffer->context; 1118 1119 ggml_sycl_set_device(ctx->device); 1120 queue_ptr stream = ctx->stream; 1121 SYCL_CHECK( 1122 CHECK_TRY_ERROR(dpct::get_current_device().queues_wait_and_throw())); 1123 1124 constexpr size_t MAX_CHUNK = 2ULL << 30; // 2 GiB 1125 for (size_t off = 0; off < buffer->size; off += MAX_CHUNK) { 1126 size_t chunk = std::min(buffer->size - off, MAX_CHUNK); 1127 SYCL_CHECK(CHECK_TRY_ERROR( 1128 (*stream) 1129 .memset(static_cast(ctx->dev_ptr) + off, value, chunk) 1130 .wait() 1131 )); 1132 } 1133 } 1134 catch (sycl::exception const &exc) { 1135 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 1136 << ", line:" << __LINE__ << std::endl; 1137 std::exit(1); 1138 } 1139 1140 static void ggml_backend_sycl_buffer_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, 1141 size_t offset, size_t size) { 1142 GGML_SYCL_DEBUG("[SYCL] call %s", __func__); 1143 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(": tensor", tensor).c_str()); 1144 GGML_SYCL_DEBUG(" size=%zu offset=%zu value=%u\n", size, offset, value); 1145 ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context *) buffer->context; 1146 SYCL_CHECK(ggml_sycl_set_device(ctx->device)); 1147 auto stream = &(dpct::dev_mgr::instance().get_device(ctx->device).default_queue()); 1148 if (size == 0) { 1149 return; // Nothing to do 1150 } 1151 if (tensor->data == nullptr) { 1152 GGML_ABORT("Error: Tensor data pointer is null.\n"); 1153 } 1154 void * target_ptr = static_cast(tensor->data) + offset; 1155 SYCL_CHECK(CHECK_TRY_ERROR((*stream).memset(target_ptr, value, size))); 1156 SYCL_CHECK(CHECK_TRY_ERROR((*stream).wait())); 1157 } 1158 1159 static void ggml_backend_sycl_buffer_reset(ggml_backend_buffer_t buffer) { 1160 GGML_SYCL_DEBUG("[SYCL] call %s\n", __func__); 1161 if (buffer == nullptr) { 1162 return; 1163 } 1164 1165 ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context *) buffer->context; 1166 1167 if (ctx != nullptr) { 1168 for (ggml_tensor_extra_gpu * extra : ctx->tensor_extras) { 1169 release_extra_gpu(extra); 1170 } 1171 ctx->tensor_extras.clear(); // reset the tensor_extras vector 1172 } 1173 } 1174 1175 static const ggml_backend_buffer_i ggml_backend_sycl_buffer_interface = { 1176 /* .free_buffer = */ ggml_backend_sycl_buffer_free_buffer, 1177 /* .get_base = */ ggml_backend_sycl_buffer_get_base, 1178 /* .init_tensor = */ ggml_backend_sycl_buffer_init_tensor, 1179 /* .memset_tensor = */ ggml_backend_sycl_buffer_memset_tensor, 1180 /* .set_tensor = */ ggml_backend_sycl_buffer_set_tensor, 1181 /* .get_tensor = */ ggml_backend_sycl_buffer_get_tensor, 1182 /* .set_tensor_2d = */ ggml_backend_sycl_buffer_set_tensor_2d, 1183 /* .get_tensor_2d = */ NULL, 1184 /* .cpy_tensor = */ ggml_backend_sycl_buffer_cpy_tensor, 1185 /* .clear = */ ggml_backend_sycl_buffer_clear, 1186 /* .reset = */ ggml_backend_sycl_buffer_reset, 1187 /* .set_tensor_n = */ NULL, 1188 /* .get_tensor_n = */ NULL, 1189 /* .cpy_tensor_n = */ NULL, 1190 }; 1191 1192 // sycl buffer type 1193 struct ggml_backend_sycl_buffer_type_context { 1194 int device; 1195 std::string name; 1196 1197 // each buffer type has its own stream 1198 queue_ptr stream = nullptr; 1199 }; 1200 1201 static const char * ggml_backend_sycl_buffer_type_get_name(ggml_backend_buffer_type_t buft) { 1202 ggml_backend_sycl_buffer_type_context * ctx = (ggml_backend_sycl_buffer_type_context *)buft->context; 1203 1204 return ctx->name.c_str(); 1205 } 1206 1207 static bool check_usm_system(int device, size_t size) { 1208 bool use_usm_system = g_ggml_sycl_usm_system && size >= ((size_t)4 * MEM_SIZE_1G); 1209 1210 if (use_usm_system && !ggml_sycl_info().devices[device].usm_system_support) { 1211 GGML_LOG_INFO("Device does not support USM system allocations\n"); 1212 use_usm_system = false; 1213 } 1214 1215 return use_usm_system; 1216 } 1217 1218 inline void * aligned_malloc_host(size_t alignment, size_t size) { 1219 #ifdef _WIN32 1220 return _aligned_malloc(size, alignment); 1221 #else 1222 return aligned_alloc(alignment, size); 1223 #endif 1224 } 1225 1226 static ggml_backend_buffer_t 1227 ggml_backend_sycl_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, 1228 size_t size) try { 1229 GGML_SYCL_DEBUG("[SYCL] call %s: size=%zu\n", __func__, size); 1230 ggml_check_sycl(); 1231 1232 ggml_backend_sycl_buffer_type_context * buft_ctx = (ggml_backend_sycl_buffer_type_context *)buft->context; 1233 ggml_sycl_set_device(buft_ctx->device); 1234 const queue_ptr stream = buft_ctx->stream; 1235 size = std::max(size, (size_t)1); // syclMalloc returns null for size 0 1236 /* 1237 Alignment below ensures best performance. While in theory it could lead to 1238 wasting memory, this is acceptable because in practice only few buffers are 1239 allocated and even less exceed the minimum size accepted here for USM system 1240 allocations. 1241 */ 1242 size_t alignment = MEM_SIZE_2M; 1243 size_t aligned_size = ((size + alignment - 1) / alignment) * alignment; 1244 bool use_usm_system = check_usm_system(buft_ctx->device, aligned_size); 1245 1246 void * dev_ptr; 1247 if (use_usm_system) { 1248 GGML_SYCL_DEBUG("[SYCL] allocating %zu Bytes with USM system\n", size); 1249 dev_ptr = (void *)aligned_malloc_host(alignment, aligned_size); 1250 if (!dev_ptr) { 1251 GGML_LOG_ERROR("%s: can't allocate %zu Bytes of memory on host\n", __func__, size); 1252 return nullptr; 1253 } 1254 } else { 1255 SYCL_CHECK(CHECK_TRY_ERROR(dev_ptr = (void *)ggml_sycl_malloc_device(size, *stream, GGML_SYCL_MEM_BUFFER))); 1256 if (!dev_ptr) { 1257 GGML_LOG_ERROR("%s: can't allocate %zu Bytes of memory on device\n", __func__, size); 1258 return nullptr; 1259 } 1260 } 1261 ggml_backend_sycl_buffer_context * ctx = new ggml_backend_sycl_buffer_context(buft_ctx->device, dev_ptr, buft_ctx->stream, use_usm_system); 1262 return ggml_backend_buffer_init(buft, ggml_backend_sycl_buffer_interface, ctx, size); 1263 } 1264 catch (sycl::exception const &exc) { 1265 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 1266 << ", line:" << __LINE__ << std::endl; 1267 std::exit(1); 1268 } 1269 1270 static size_t ggml_backend_sycl_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) { 1271 return SYCL_BUFFER_ALIGNMENT; 1272 GGML_UNUSED(buft); 1273 } 1274 1275 static bool is_bmg_g31_arch(int device) { 1276 return ggml_sycl_info().devices[device].hw_info.arch == gpu_arch::intel_gpu_bmg_g31; 1277 } 1278 1279 static size_t ggml_backend_sycl_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) { 1280 ggml_backend_sycl_buffer_type_context * ctx = (ggml_backend_sycl_buffer_type_context *)buft->context; 1281 int device = ctx->device; 1282 // use the buft device, the current device may differ on multi-GPU systems 1283 size_t max_alloc_size = dpct::get_device(device).get_max_mem_alloc_size(); 1284 if (g_ggml_sycl_host_pinned_mem_2g) { 1285 return std::min(max_alloc_size, (size_t) 2LL*1024*1024*1024); 1286 } else { 1287 if(is_bmg_g31_arch(device)) { 1288 //Todo, it's workaround for BMG-G31, which has a known issue with large allocations. 1289 //The max alloc size is reduced to 60% of the reported max alloc size. 1290 //remove it after https://github.com/intel/compute-runtime/issues/998 is fixed. 1291 max_alloc_size = max_alloc_size*0.6; 1292 } 1293 return max_alloc_size; 1294 1295 } 1296 GGML_UNUSED(buft); 1297 } 1298 1299 static size_t ggml_backend_sycl_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) { 1300 // Reserve the additional scratch so it's visible to the graph allocator 1301 size_t size = tensor->op == GGML_OP_FLASH_ATTN_EXT 1302 ? ggml_sycl_flash_attn_ext_get_alloc_size(tensor) 1303 : ggml_nbytes(tensor); 1304 int64_t ne0 = tensor->ne[0]; 1305 1306 if (ggml_is_quantized(tensor->type)) { 1307 if (ne0 % MATRIX_ROW_PADDING != 0) { 1308 size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING); 1309 } 1310 } 1311 1312 return size; 1313 1314 GGML_UNUSED(buft); 1315 } 1316 1317 static const ggml_backend_buffer_type_i ggml_backend_sycl_buffer_type_interface = { 1318 /* .get_name = */ ggml_backend_sycl_buffer_type_get_name, 1319 /* .alloc_buffer = */ ggml_backend_sycl_buffer_type_alloc_buffer, 1320 /* .alloc_buffer_n = */ NULL, 1321 /* .get_alignment = */ ggml_backend_sycl_buffer_type_get_alignment, 1322 /* .get_max_size = */ ggml_backend_sycl_buffer_type_get_max_size, 1323 /* .get_alloc_size = */ ggml_backend_sycl_buffer_type_get_alloc_size, 1324 /* .get_alloc_size_n = */ NULL, 1325 /* .is_host = */ NULL, 1326 }; 1327 1328 ggml_backend_buffer_type_t ggml_backend_sycl_buffer_type(int device) { 1329 static std::mutex mutex; 1330 std::lock_guard lock(mutex); 1331 1332 1333 auto dev_count = ggml_backend_sycl_get_device_count(); 1334 1335 if (device>=dev_count or device<0) { 1336 GGML_LOG_ERROR("ggml_backend_sycl_buffer_type error: device_index:%d is out of range [0, %d], miss to call ggml_backend_sycl_set_single_device()\n", 1337 device, dev_count-1); 1338 GGML_ASSERT(devicedevice; 1363 if (device>=ggml_sycl_info().device_count or device<0) { 1364 GGML_LOG_ERROR("ggml_backend_sycl_buffer_type error: device_index:%d is out of range [0, %d], miss to call ggml_backend_sycl_set_single_device()\n", 1365 device, ggml_sycl_info().device_count-1); 1366 GGML_ASSERT(devicestream(i, 0)}, 1378 }; 1379 } 1380 ggml_backend_sycl_buffer_type_initialized = true; 1381 } 1382 return &ggml_backend_sycl_buffer_types[device]; 1383 } 1384 1385 // sycl split buffer 1386 1387 static int64_t get_row_rounding(ggml_type type, const std::array & tensor_split) { 1388 int64_t min_compute_capability = INT_MAX; 1389 int64_t max_compute_capability = INT_MIN; 1390 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 1391 if (tensor_split[i] < (i + 1 < ggml_sycl_info().device_count ? tensor_split[i + 1] : 1.0f)) { 1392 if (min_compute_capability > ggml_sycl_info().devices[i].cc) { 1393 min_compute_capability = ggml_sycl_info().devices[i].cc; 1394 } 1395 if (max_compute_capability < ggml_sycl_info().devices[i].cc) { 1396 max_compute_capability = ggml_sycl_info().devices[i].cc; 1397 } 1398 } 1399 } 1400 1401 switch(type) { 1402 case GGML_TYPE_Q1_0: 1403 case GGML_TYPE_Q4_0: 1404 case GGML_TYPE_Q4_1: 1405 return max_compute_capability >= VER_GEN9 ? 128 : 64; 1406 case GGML_TYPE_Q5_0: 1407 case GGML_TYPE_Q5_1: 1408 case GGML_TYPE_Q8_0: 1409 return 64; 1410 case GGML_TYPE_F16: 1411 case GGML_TYPE_F32: 1412 return 1; 1413 case GGML_TYPE_Q2_K: 1414 case GGML_TYPE_Q3_K: 1415 case GGML_TYPE_Q4_K: 1416 case GGML_TYPE_Q5_K: 1417 case GGML_TYPE_IQ2_XXS: 1418 case GGML_TYPE_IQ2_XS: 1419 case GGML_TYPE_IQ2_S: 1420 case GGML_TYPE_IQ1_S: 1421 case GGML_TYPE_IQ1_M: 1422 case GGML_TYPE_IQ3_XXS: 1423 case GGML_TYPE_IQ4_XS: 1424 case GGML_TYPE_IQ4_NL: 1425 return max_compute_capability >= VER_GEN9 ? 128 : 64; 1426 case GGML_TYPE_IQ3_S: 1427 return max_compute_capability >= VER_GEN9 ? 128 : 64; 1428 case GGML_TYPE_Q6_K: 1429 return 64; 1430 default: 1431 GGML_ABORT("fatal error"); 1432 } 1433 } 1434 1435 static void get_row_split(int64_t * row_low, int64_t * row_high, const ggml_tensor * tensor, const std::array & tensor_split, int id) { 1436 const int64_t nrows = ggml_nrows(tensor); 1437 const int64_t rounding = get_row_rounding(tensor->type, tensor_split); 1438 1439 *row_low = id == 0 ? 0 : nrows*tensor_split[id]; 1440 *row_low -= *row_low % rounding; 1441 if (id == ggml_sycl_info().device_count - 1) { 1442 *row_high = nrows; 1443 } else { 1444 *row_high = nrows*tensor_split[id + 1]; 1445 *row_high -= *row_high % rounding; 1446 } 1447 } 1448 1449 static size_t ggml_nbytes_split(const struct ggml_tensor * tensor, int nrows_split) { 1450 static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function"); 1451 1452 return nrows_split*ggml_row_size(tensor->type, tensor->ne[0]); 1453 } 1454 1455 struct ggml_backend_sycl_split_buffer_type_context { 1456 std::array tensor_split; 1457 }; 1458 1459 struct ggml_backend_sycl_split_buffer_context { 1460 ~ggml_backend_sycl_split_buffer_context() try { 1461 for (ggml_tensor_extra_gpu * extra : tensor_extras) { 1462 release_extra_gpu(extra, streams); 1463 } 1464 } 1465 catch (sycl::exception const &exc) { 1466 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 1467 << ", line:" << __LINE__ << std::endl; 1468 std::exit(1); 1469 } 1470 1471 std::vector tensor_extras; 1472 std::vector streams; 1473 }; 1474 1475 static void ggml_backend_sycl_split_buffer_free_buffer(ggml_backend_buffer_t buffer) { 1476 ggml_backend_sycl_split_buffer_context * ctx = (ggml_backend_sycl_split_buffer_context *)buffer->context; 1477 delete ctx; 1478 } 1479 1480 static void * ggml_backend_sycl_split_buffer_get_base(ggml_backend_buffer_t buffer) { 1481 // the pointers are stored in the tensor extras, this is just a dummy address and never dereferenced 1482 return (void *)0x1000; 1483 1484 GGML_UNUSED(buffer); 1485 } 1486 1487 static enum ggml_status 1488 ggml_backend_sycl_split_buffer_init_tensor(ggml_backend_buffer_t buffer, 1489 ggml_tensor *tensor) try { 1490 GGML_SYCL_DEBUG("[SYCL] call %s", __func__); 1491 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(": tensor", tensor, "\n").c_str()); 1492 GGML_ASSERT(tensor->view_src == nullptr); // views of split tensors are not supported 1493 1494 ggml_backend_sycl_split_buffer_context * ctx = (ggml_backend_sycl_split_buffer_context *)buffer->context; 1495 ggml_backend_sycl_split_buffer_type_context * buft_ctx = (ggml_backend_sycl_split_buffer_type_context *)buffer->buft->context; 1496 1497 const int64_t ne0 = tensor->ne[0]; 1498 1499 ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu{}; 1500 1501 ctx->tensor_extras.push_back(extra); 1502 // consumers index the queues by device id, so size the vector once with one queue per device 1503 if (ctx->streams.empty()) { 1504 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 1505 ctx->streams.push_back(&(dpct::get_device(i).default_queue())); 1506 } 1507 } 1508 1509 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 1510 int64_t row_low, row_high; 1511 get_row_split(&row_low, &row_high, tensor, buft_ctx->tensor_split, i); 1512 1513 int64_t nrows_split = row_high - row_low; 1514 if (nrows_split == 0) { 1515 continue; 1516 } 1517 1518 size_t size = ggml_nbytes_split(tensor, nrows_split); 1519 const size_t original_size = size; 1520 1521 // pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses 1522 if (ne0 % MATRIX_ROW_PADDING != 0) { 1523 size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING); 1524 } 1525 1526 ggml_sycl_set_device(i); 1527 const queue_ptr stream = ctx->streams[i]; 1528 char * buf; 1529 SYCL_CHECK(CHECK_TRY_ERROR(buf = (char *)ggml_sycl_malloc_device(size, *stream, GGML_SYCL_MEM_BUFFER))); 1530 if (!buf) { 1531 char err_buf[1024]; 1532 snprintf(err_buf, 1023, "%s: can't allocate %zu Bytes of memory on device\n", __func__, size); 1533 throw std::runtime_error(err_buf); 1534 } 1535 // set padding to 0 to avoid possible NaN values 1536 if (size > original_size) { 1537 /* 1538 DPCT1009:209: SYCL uses exceptions to report errors and does not use 1539 the error codes. The original code was commented out and a warning 1540 string was inserted. You need to rewrite this code. 1541 */ 1542 SYCL_CHECK(CHECK_TRY_ERROR( 1543 (*stream) 1544 .memset(buf + original_size, 0, size - original_size) 1545 .wait())); 1546 } 1547 1548 extra->data_device[i] = buf; 1549 1550 for (int64_t is = 0; is < GGML_SYCL_MAX_STREAMS; ++is) { 1551 /* 1552 DPCT1009:210: SYCL uses exceptions to report errors and does not use 1553 the error codes. The original code was commented out and a warning 1554 string was inserted. You need to rewrite this code. 1555 */ 1556 SYCL_CHECK( 1557 CHECK_TRY_ERROR(extra->events[i][is] = new sycl::event())); 1558 } 1559 } 1560 tensor->extra = extra; 1561 return GGML_STATUS_SUCCESS; 1562 } 1563 catch (sycl::exception const &exc) { 1564 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 1565 << ", line:" << __LINE__ << std::endl; 1566 std::exit(1); 1567 } 1568 1569 static void 1570 ggml_backend_sycl_split_buffer_set_tensor(ggml_backend_buffer_t buffer, 1571 ggml_tensor *tensor, const void *data, 1572 size_t offset, size_t size) try { 1573 GGML_SYCL_DEBUG("[SYCL] call %s", __func__); 1574 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(": tensor", tensor).c_str()); 1575 GGML_SYCL_DEBUG(" size=%zu offset=%zu\n", size, offset); 1576 // split tensors must always be set in their entirety at once 1577 GGML_ASSERT(offset == 0); 1578 GGML_ASSERT(size == ggml_nbytes(tensor)); 1579 1580 ggml_backend_sycl_split_buffer_context * ctx = (ggml_backend_sycl_split_buffer_context *)buffer->context; 1581 ggml_backend_sycl_split_buffer_type_context * buft_ctx = (ggml_backend_sycl_split_buffer_type_context *)buffer->buft->context; 1582 1583 const int64_t ne0 = tensor->ne[0]; 1584 const size_t nb1 = tensor->nb[1]; 1585 ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *)tensor->extra; 1586 1587 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 1588 int64_t row_low, row_high; 1589 get_row_split(&row_low, &row_high, tensor, buft_ctx->tensor_split, i); 1590 1591 int64_t nrows_split = row_high - row_low; 1592 if (nrows_split == 0) { 1593 continue; 1594 } 1595 1596 const size_t offset_split = row_low*nb1; 1597 size_t size = ggml_nbytes_split(tensor, nrows_split); 1598 const size_t original_size = size; 1599 1600 // pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses 1601 if (ne0 % MATRIX_ROW_PADDING != 0) { 1602 size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING); 1603 } 1604 1605 const char * buf_host = (const char *)data + offset_split; 1606 /* 1607 DPCT1009:211: SYCL uses exceptions to report errors and does not use the 1608 error codes. The original code was commented out and a warning string 1609 was inserted. You need to rewrite this code. 1610 */ 1611 ggml_sycl_set_device(i); 1612 const queue_ptr stream = ctx->streams[i]; 1613 SYCL_CHECK(CHECK_TRY_ERROR( 1614 (*stream) 1615 .memcpy(extra->data_device[i], buf_host, original_size) 1616 .wait())); 1617 } 1618 } 1619 catch (sycl::exception const &exc) { 1620 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 1621 << ", line:" << __LINE__ << std::endl; 1622 std::exit(1); 1623 } 1624 1625 static void 1626 ggml_backend_sycl_split_buffer_get_tensor(ggml_backend_buffer_t buffer, 1627 const ggml_tensor *tensor, void *data, 1628 size_t offset, size_t size) try { 1629 GGML_SYCL_DEBUG("[SYCL] call %s", __func__); 1630 GGML_SYCL_DEBUG("%s", debug_get_tensor_str(": tensor", tensor).c_str()); 1631 GGML_SYCL_DEBUG(" size=%zu offset=%zu\n", size, offset); 1632 // split tensors must always be set in their entirety at once 1633 GGML_ASSERT(offset == 0); 1634 GGML_ASSERT(size == ggml_nbytes(tensor)); 1635 1636 ggml_backend_sycl_split_buffer_context * ctx = (ggml_backend_sycl_split_buffer_context *)buffer->context; 1637 ggml_backend_sycl_split_buffer_type_context * buft_ctx = (ggml_backend_sycl_split_buffer_type_context *)buffer->buft->context; 1638 1639 const int64_t ne0 = tensor->ne[0]; 1640 const size_t nb1 = tensor->nb[1]; 1641 ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *)tensor->extra; 1642 1643 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 1644 int64_t row_low, row_high; 1645 get_row_split(&row_low, &row_high, tensor, buft_ctx->tensor_split, i); 1646 1647 int64_t nrows_split = row_high - row_low; 1648 if (nrows_split == 0) { 1649 continue; 1650 } 1651 1652 const size_t offset_split = row_low*nb1; 1653 size_t size = ggml_nbytes_split(tensor, nrows_split); 1654 const size_t original_size = size; 1655 1656 // pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses 1657 if (ne0 % MATRIX_ROW_PADDING != 0) { 1658 size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING); 1659 } 1660 1661 char * buf_host = (char *)data + offset_split; 1662 /* 1663 DPCT1009:212: SYCL uses exceptions to report errors and does not use the 1664 error codes. The original code was commented out and a warning string 1665 was inserted. You need to rewrite this code. 1666 */ 1667 ggml_sycl_set_device(i); 1668 const queue_ptr stream = ctx->streams[i]; 1669 SYCL_CHECK(CHECK_TRY_ERROR( 1670 (*stream) 1671 .memcpy(buf_host, extra->data_device[i], original_size) 1672 .wait())); 1673 } 1674 } 1675 catch (sycl::exception const &exc) { 1676 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 1677 << ", line:" << __LINE__ << std::endl; 1678 std::exit(1); 1679 } 1680 1681 static void ggml_backend_sycl_split_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { 1682 GGML_UNUSED(buffer); 1683 GGML_UNUSED(value); 1684 } 1685 1686 static struct ggml_backend_buffer_i ggml_backend_sycl_split_buffer_interface = { 1687 /* .free_buffer = */ ggml_backend_sycl_split_buffer_free_buffer, 1688 /* .get_base = */ ggml_backend_sycl_split_buffer_get_base, 1689 /* .init_tensor = */ ggml_backend_sycl_split_buffer_init_tensor, 1690 /* .memset_tensor = */ NULL, 1691 /* .set_tensor = */ ggml_backend_sycl_split_buffer_set_tensor, 1692 /* .get_tensor = */ ggml_backend_sycl_split_buffer_get_tensor, 1693 /* .set_tensor_2d = */ NULL, 1694 /* .get_tensor_2d = */ NULL, 1695 /* .cpy_tensor = */ NULL, 1696 /* .clear = */ ggml_backend_sycl_split_buffer_clear, 1697 /* .reset = */ NULL, 1698 /* .set_tensor_n = */ NULL, 1699 /* .get_tensor_n = */ NULL, 1700 /* .cpy_tensor_n = */ NULL, 1701 }; 1702 1703 // sycl split buffer type 1704 1705 static const char * ggml_backend_sycl_split_buffer_type_get_name(ggml_backend_buffer_type_t buft) { 1706 return GGML_SYCL_NAME "_Split"; 1707 1708 GGML_UNUSED(buft); 1709 } 1710 1711 static bool ggml_backend_buffer_is_sycl_split(ggml_backend_buffer_t buffer) { 1712 return buffer->buft->iface.get_name == ggml_backend_sycl_split_buffer_type_get_name; 1713 } 1714 1715 static ggml_backend_buffer_t ggml_backend_sycl_split_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) { 1716 // since we don't know the exact split after rounding, we cannot allocate the device buffers at this point 1717 // instead, we allocate them for each tensor separately in init_tensor 1718 // however, the size still represents the maximum cumulative size of all the device buffers after the tensors are allocated, 1719 // as returned by get_alloc_size. this limit is enforced during tensor allocation by ggml-alloc, so it must be correct. 1720 ggml_backend_sycl_split_buffer_context * ctx = new ggml_backend_sycl_split_buffer_context(); 1721 1722 return ggml_backend_buffer_init(buft, ggml_backend_sycl_split_buffer_interface, ctx, size); 1723 } 1724 1725 static size_t ggml_backend_sycl_split_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) { 1726 return SYCL_BUFFER_ALIGNMENT; 1727 GGML_UNUSED(buft); 1728 } 1729 1730 static size_t ggml_backend_sycl_split_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) { 1731 ggml_backend_sycl_split_buffer_type_context * ctx = (ggml_backend_sycl_split_buffer_type_context *)buft->context; 1732 1733 size_t total_size = 0; 1734 1735 const int64_t ne0 = tensor->ne[0]; 1736 1737 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 1738 int64_t row_low, row_high; 1739 get_row_split(&row_low, &row_high, tensor, ctx->tensor_split, i); 1740 1741 int64_t nrows_split = row_high - row_low; 1742 if (nrows_split == 0) { 1743 continue; 1744 } 1745 1746 total_size += ggml_nbytes_split(tensor, nrows_split); 1747 1748 // pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses 1749 if (ne0 % MATRIX_ROW_PADDING != 0) { 1750 total_size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING); 1751 } 1752 } 1753 1754 return total_size; 1755 } 1756 1757 static bool ggml_backend_sycl_split_buffer_type_is_host(ggml_backend_buffer_type_t buft) { 1758 return false; 1759 1760 GGML_UNUSED(buft); 1761 } 1762 1763 static ggml_backend_buffer_type_i ggml_backend_sycl_split_buffer_type_interface = { 1764 /* .get_name = */ ggml_backend_sycl_split_buffer_type_get_name, 1765 /* .alloc_buffer = */ ggml_backend_sycl_split_buffer_type_alloc_buffer, 1766 /* .alloc_buffer_n = */ NULL, 1767 /* .get_alignment = */ ggml_backend_sycl_split_buffer_type_get_alignment, 1768 /* .get_max_size = */ NULL, // defaults to SIZE_MAX 1769 /* .get_alloc_size = */ ggml_backend_sycl_split_buffer_type_get_alloc_size, 1770 /* .get_alloc_size_n = */ NULL, 1771 /* .is_host = */ ggml_backend_sycl_split_buffer_type_is_host, 1772 }; 1773 1774 ggml_backend_buffer_type_t ggml_backend_sycl_split_buffer_type(int main_device, const float * tensor_split) { 1775 GGML_SYCL_DEBUG("[SYCL] call ggml_backend_sycl_split_buffer_type\n"); 1776 1777 GGML_UNUSED(main_device); 1778 1779 static std::mutex mutex; 1780 std::lock_guard lock(mutex); 1781 1782 ggml_check_sycl(); 1783 // FIXME: this is not thread safe 1784 static std::map, struct ggml_backend_buffer_type> buft_map; 1785 1786 std::array tensor_split_arr = {}; 1787 1788 bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + GGML_SYCL_MAX_DEVICES, [](float x) { return x == 0.0f; }); 1789 if (all_zero) { 1790 tensor_split_arr = ggml_sycl_info().default_tensor_split; 1791 } else { 1792 float split_sum = 0.0f; 1793 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 1794 tensor_split_arr[i] = split_sum; 1795 split_sum += tensor_split[i]; 1796 } 1797 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 1798 tensor_split_arr[i] /= split_sum; 1799 } 1800 } 1801 1802 auto it = buft_map.find(tensor_split_arr); 1803 if (it != buft_map.end()) { 1804 return &it->second; 1805 } 1806 1807 struct ggml_backend_buffer_type buft { 1808 /* .iface = */ ggml_backend_sycl_split_buffer_type_interface, 1809 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_sycl_reg(), 0), 1810 /* .context = */ new ggml_backend_sycl_split_buffer_type_context{tensor_split_arr}, 1811 }; 1812 1813 auto result = buft_map.emplace(tensor_split_arr, buft); 1814 return &result.first->second; 1815 } 1816 1817 // host buffer type 1818 1819 struct ggml_backend_sycl_device_context { 1820 int device; 1821 std::string name; 1822 std::string description; 1823 int op_offload_min_batch_size; 1824 }; 1825 1826 static const char * ggml_backend_sycl_host_buffer_type_name(ggml_backend_buffer_type_t buft) { 1827 return GGML_SYCL_NAME "_Host"; 1828 1829 GGML_UNUSED(buft); 1830 } 1831 1832 static int ggml_backend_sycl_host_buffer_type_device(ggml_backend_buffer_type_t buft) { 1833 return static_cast(buft->device->context)->device; 1834 } 1835 1836 //host pinned memory 1837 static void * ggml_backend_sycl_host_malloc(int device, size_t size) { 1838 GGML_SYCL_DEBUG("[SYCL] call ggml_backend_sycl_host_malloc of size %.2f MiB on device %d\n", size / 1024.0 / 1024.0, device); 1839 void * ptr = nullptr; 1840 try { 1841 ggml_check_sycl(); 1842 // USM host memory is page-locked and device-accessible by construction 1843 auto & q = dpct::dev_mgr::instance().get_device(device).default_queue(); 1844 ptr = sycl::malloc_host(size, q, sycl::property_list{}); 1845 } catch (...) { 1846 ptr = nullptr; 1847 } 1848 if (ptr == nullptr) { 1849 GGML_LOG_WARN("%s: failed to allocate %.2f MiB of pinned memory\n", __func__, 1850 size / 1024.0 / 1024.0); 1851 } 1852 1853 return ptr; 1854 } 1855 1856 static void ggml_backend_sycl_host_buffer_free_buffer(ggml_backend_buffer_t buffer) { 1857 if (buffer->context == nullptr) { 1858 return; 1859 } 1860 if (g_ggml_sycl_enable_host_pinned_mem) { 1861 const int device = ggml_backend_sycl_host_buffer_type_device(buffer->buft); 1862 auto & q = dpct::dev_mgr::instance().get_device(device).default_queue(); 1863 SYCL_CHECK(CHECK_TRY_ERROR(sycl::free(buffer->context, q))); 1864 } else { 1865 free_aligned_mem_host((void *) buffer->context); 1866 } 1867 } 1868 1869 static ggml_backend_buffer_t ggml_backend_sycl_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) { 1870 void * ptr = g_ggml_sycl_enable_host_pinned_mem ? 1871 ggml_backend_sycl_host_malloc(ggml_backend_sycl_host_buffer_type_device(buft), size) : 1872 aligned_malloc_host(TENSOR_ALIGNMENT, size); 1873 if (ptr == nullptr) { 1874 // fallback to cpu buffer 1875 return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size); 1876 } 1877 1878 // FIXME: this is a hack to avoid having to implement a new buffer type 1879 ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size); 1880 buffer->buft = buft; 1881 buffer->iface.free_buffer = ggml_backend_sycl_host_buffer_free_buffer; 1882 1883 return buffer; 1884 } 1885 1886 static size_t ggml_backend_sycl_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) { 1887 1888 if (g_ggml_sycl_enable_host_pinned_mem) { 1889 const int device = ggml_backend_sycl_host_buffer_type_device(buft); 1890 size_t max_alloc_size = dpct::dev_mgr::instance().get_device(device).get_max_mem_alloc_size(); 1891 if (g_ggml_sycl_host_pinned_mem_2g) { 1892 return std::min(max_alloc_size, (size_t) 2LL*1024*1024*1024); 1893 } else { 1894 return max_alloc_size; 1895 } 1896 } else { 1897 return SIZE_MAX; 1898 } 1899 } 1900 1901 static ggml_backend_buffer_type_t ggml_backend_sycl_host_buffer_type_for_device(int device) { 1902 GGML_SYCL_DEBUG("[SYCL] call ggml_backend_sycl_host_buffer_type_for_device on device %d\n", device); 1903 1904 // the vector is never resized after this, so the returned pointers stay valid 1905 static std::vector buffer_types_host = [] { 1906 std::vector bufts(ggml_backend_sycl_get_device_count()); 1907 for (size_t i = 0; i < bufts.size(); i++) { 1908 bufts[i] = { 1909 /* .iface = */ { 1910 /* .get_name = */ ggml_backend_sycl_host_buffer_type_name, 1911 /* .alloc_buffer = */ ggml_backend_sycl_host_buffer_type_alloc_buffer, 1912 /* .alloc_buffer_n = */ NULL, 1913 /* .get_alignment = */ ggml_backend_cpu_buffer_type()->iface.get_alignment, 1914 /* .get_max_size = */ ggml_backend_sycl_host_buffer_type_get_max_size, 1915 /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size, 1916 /* .get_alloc_size_n = */ NULL, 1917 /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host, 1918 }, 1919 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_sycl_reg(), i), 1920 /* .context = */ nullptr, 1921 }; 1922 } 1923 return bufts; 1924 }(); 1925 1926 GGML_ASSERT(device >= 0 && device < (int) buffer_types_host.size()); 1927 1928 return &buffer_types_host[device]; 1929 } 1930 1931 // TODO: this function is unused and is a temporary hack to avoid breaking changes 1932 ggml_backend_buffer_type_t ggml_backend_sycl_host_buffer_type() { 1933 return ggml_backend_sycl_host_buffer_type_for_device(0); 1934 } 1935 1936 // buffer pool for sycl (legacy) 1937 struct ggml_sycl_pool_leg : public ggml_sycl_pool { 1938 static const int MAX_SYCL_BUFFERS = 256; 1939 1940 int device; 1941 queue_ptr qptr; 1942 struct ggml_sycl_buffer { 1943 void * ptr = nullptr; 1944 size_t size = 0; 1945 }; 1946 1947 ggml_sycl_buffer buffer_pool[MAX_SYCL_BUFFERS] = {}; 1948 size_t pool_size = 0; 1949 1950 explicit ggml_sycl_pool_leg(queue_ptr qptr_, int device_) : device(device_), qptr(qptr_) {} 1951 1952 ~ggml_sycl_pool_leg() { 1953 #ifdef DEBUG_SYCL_POOL 1954 int n_cached = 0; 1955 size_t bytes_cached = 0; 1956 for (int i = 0; i < MAX_SYCL_BUFFERS; ++i) { 1957 if (buffer_pool[i].ptr != nullptr) { 1958 ++n_cached; 1959 bytes_cached += buffer_pool[i].size; 1960 } 1961 } 1962 GGML_LOG_INFO("%s: %d buffers, cached = %.2f MiB\n", __func__, 1963 n_cached, bytes_cached / 1024.0 / 1024.0); 1964 const auto slots = format_slots_in_alloc_order(); 1965 if (!slots.empty()) { 1966 GGML_LOG_INFO("%s: slots MiB: %s\n", __func__, slots.c_str()); 1967 } 1968 #endif 1969 1970 for (int i = 0; i < MAX_SYCL_BUFFERS; ++i) { 1971 ggml_sycl_buffer & b = buffer_pool[i]; 1972 if (b.ptr != nullptr) { 1973 SYCL_CHECK(CHECK_TRY_ERROR(ggml_sycl_free_device(b.ptr, *qptr))); 1974 pool_size -= b.size; 1975 } 1976 } 1977 GGML_ASSERT(pool_size == 0); 1978 } 1979 1980 #ifdef DEBUG_SYCL_POOL 1981 std::string format_slots_in_alloc_order() const { 1982 std::string line; 1983 char buf[32]; 1984 bool first = true; 1985 for (int i = 0; i < MAX_SYCL_BUFFERS; ++i) { 1986 if (buffer_pool[i].ptr == nullptr) { 1987 continue; 1988 } 1989 if (!first) { 1990 line += '/'; 1991 } 1992 first = false; 1993 snprintf(buf, sizeof(buf), "%.2f", buffer_pool[i].size / 1024.0 / 1024.0); 1994 line += buf; 1995 } 1996 return line; 1997 } 1998 #endif 1999 2000 void * alloc(size_t size, size_t * actual_size) override { 2001 #ifdef DEBUG_sycl_MALLOC 2002 int nnz = 0; 2003 size_t max_size = 0; 2004 #endif 2005 size_t best_diff = 1ull << 36; 2006 int ibest = -1; 2007 for (int i = 0; i < MAX_SYCL_BUFFERS; ++i) { 2008 ggml_sycl_buffer& b = buffer_pool[i]; 2009 if (b.ptr != nullptr) { 2010 #ifdef DEBUG_sycl_MALLOC 2011 ++nnz; 2012 if (b.size > max_size) max_size = b.size; 2013 #endif 2014 if (b.size >= size) { 2015 size_t diff = b.size - size; 2016 if (diff < best_diff) { 2017 best_diff = diff; 2018 ibest = i; 2019 if (!best_diff) { 2020 void * ptr = b.ptr; 2021 *actual_size = b.size; 2022 b.ptr = nullptr; 2023 b.size = 0; 2024 return ptr; 2025 } 2026 } 2027 } 2028 } 2029 } 2030 if (ibest >= 0) { 2031 ggml_sycl_buffer& b = buffer_pool[ibest]; 2032 void * ptr = b.ptr; 2033 *actual_size = b.size; 2034 b.ptr = nullptr; 2035 b.size = 0; 2036 return ptr; 2037 } 2038 void * ptr; 2039 size_t look_ahead_size = (size_t) (1.05 * size); 2040 2041 SYCL_CHECK(CHECK_TRY_ERROR(ptr = (void *)ggml_sycl_malloc_device(look_ahead_size, *qptr, GGML_SYCL_MEM_POOL_LEG))); 2042 if (!ptr) { 2043 GGML_LOG_ERROR("%s: can't allocate %zu Bytes of memory on device/GPU\n", __func__, look_ahead_size); 2044 return nullptr; 2045 } 2046 2047 *actual_size = look_ahead_size; 2048 pool_size += look_ahead_size; 2049 2050 #ifdef DEBUG_SYCL_MALLOC 2051 GGML_LOG_DEBUG("%s[%d]: %d buffers, max_size = %u MB, pool_size = %u MB, requested %u MB\n", __func__, id, nnz, 2052 (uint32_t)(max_size/1024/1024), (uint32_t)(g_sycl_pool_size[id]/1024/1024), (uint32_t)(size/1024/1024)); 2053 #endif 2054 2055 // GGML_SYCL_DEBUG("ggml_sycl_pool_malloc_leg look_ahead_size=%zu, return %p\n", look_ahead_size, ptr); 2056 return ptr; 2057 } 2058 2059 void free(void * ptr, size_t size) override { 2060 for (int i = 0; i < MAX_SYCL_BUFFERS; ++i) { 2061 ggml_sycl_buffer& b = buffer_pool[i]; 2062 if (b.ptr == nullptr) { 2063 b.ptr = ptr; 2064 b.size = size; 2065 return; 2066 } 2067 } 2068 GGML_LOG_WARN("WARNING: sycl buffer pool full, increase MAX_sycl_BUFFERS\n"); 2069 SYCL_CHECK(CHECK_TRY_ERROR(ggml_sycl_free_device(ptr, *qptr))); 2070 pool_size -= size; 2071 } 2072 }; 2073 2074 // pool with virtual memory management 2075 #if defined(GGML_SYCL_SUPPORT_VMM) 2076 struct ggml_sycl_pool_vmm : public ggml_sycl_pool { 2077 static const size_t SYCL_POOL_VMM_MAX_SIZE = 1ull << 35; // 32 GB 2078 2079 int device; 2080 sycl::context ctx; 2081 sycl::device dev; 2082 2083 uintptr_t pool_addr = 0; 2084 size_t pool_used = 0; 2085 size_t pool_size = 0; 2086 size_t granularity; 2087 2088 // physical_mem owns the commits (unlike cuMemMap) 2089 struct mapping { 2090 sycl::ext::oneapi::experimental::physical_mem phys; 2091 void * map_ptr; 2092 }; 2093 std::vector mappings; 2094 2095 explicit ggml_sycl_pool_vmm(queue_ptr qptr_, int device_) : 2096 device(device_), 2097 ctx(qptr_->get_context()), 2098 dev(qptr_->get_device()), 2099 granularity(ggml_sycl_info().devices[device_].vmm_granularity) { 2100 } 2101 2102 ~ggml_sycl_pool_vmm() { 2103 if (pool_addr == 0) { 2104 return; 2105 } 2106 2107 // Per spec, unmap must (a) match the exact (ptr, size) of an earlier 2108 // physical_mem::map() call and (b) precede destruction of the 2109 // physical_mem objects (their dtors won't unmap). 2110 for (auto & m : mappings) { 2111 SYCL_CHECK(CHECK_TRY_ERROR(sycl::ext::oneapi::experimental::unmap( 2112 m.map_ptr, m.phys.size(), ctx))); 2113 } 2114 SYCL_CHECK(CHECK_TRY_ERROR(sycl::ext::oneapi::experimental::free_virtual_mem( 2115 pool_addr, SYCL_POOL_VMM_MAX_SIZE, ctx))); 2116 } 2117 2118 void * alloc(size_t size, size_t * actual_size) override { 2119 // round up the allocation size to the alignment to ensure that all allocations are aligned for all data types 2120 size = GGML_PAD(size, SYCL_BUFFER_ALIGNMENT); 2121 2122 size_t avail = pool_size - pool_used; 2123 2124 if (size > avail) { 2125 // round up to the next multiple of the granularity 2126 size_t reserve_size = GGML_PAD(size - avail, granularity); 2127 2128 GGML_ASSERT(pool_size + reserve_size <= SYCL_POOL_VMM_MAX_SIZE); 2129 2130 if (ggml_sycl_memtrace_enabled()) { 2131 GGML_LOG_INFO(GGML_SYCL_MEMTRACE_TAG " pool_vmm[%d] committing %5zu MiB (pool %5zu -> %5zu MiB)\n", 2132 device, reserve_size / (1024 * 1024), pool_size / (1024 * 1024), 2133 (pool_size + reserve_size) / (1024 * 1024)); 2134 ggml_sycl_memtrace_report("before pool_vmm commit"); 2135 } 2136 2137 // allocate more physical memory 2138 std::optional phys; 2139 SYCL_CHECK(CHECK_TRY_ERROR(phys.emplace(dev, ctx, reserve_size))); 2140 2141 // reserve virtual address space (if not already reserved) 2142 if (pool_addr == 0) { 2143 SYCL_CHECK(CHECK_TRY_ERROR( 2144 pool_addr = sycl::ext::oneapi::experimental::reserve_virtual_mem( 2145 SYCL_POOL_VMM_MAX_SIZE, ctx))); 2146 } 2147 2148 // map at the end of the pool 2149 void * map_ptr = nullptr; 2150 SYCL_CHECK(CHECK_TRY_ERROR( 2151 map_ptr = phys->map(pool_addr + pool_size, reserve_size, 2152 sycl::ext::oneapi::experimental::address_access_mode::read_write))); 2153 2154 // stash these so we could unmap this exact range in dtor 2155 mappings.push_back({ 2156 std::move(*phys), 2157 map_ptr, 2158 }); 2159 2160 // add to the pool 2161 pool_size += reserve_size; 2162 ggml_sycl_memtrace_add(GGML_SYCL_MEM_POOL_VMM, map_ptr, reserve_size); 2163 2164 #ifdef DEBUG_SYCL_MALLOC 2165 GGML_LOG_INFO("sycl pool[%d]: size increased to %llu MB (reserved %llu MB)\n", 2166 device, (unsigned long long) (pool_size/1024/1024), 2167 (unsigned long long) (reserve_size/1024/1024)); 2168 #endif 2169 } 2170 2171 GGML_ASSERT(pool_addr != 0); 2172 2173 void * ptr = reinterpret_cast(pool_addr + pool_used); 2174 *actual_size = size; 2175 pool_used += size; 2176 2177 #ifdef DEBUG_SYCL_MALLOC 2178 GGML_LOG_INFO("sycl pool[%d]: allocated %llu bytes at %p\n", device, (unsigned long long) size, ptr); 2179 #endif 2180 2181 return ptr; 2182 } 2183 2184 void free(void * ptr, size_t size) override { 2185 #ifdef DEBUG_SYCL_MALLOC 2186 GGML_LOG_INFO("sycl pool[%d]: freed %llu bytes at %p\n", device, (unsigned long long) size, ptr); 2187 #endif 2188 2189 pool_used -= size; 2190 2191 // all deallocations must be in reverse order of the allocations 2192 GGML_ASSERT(ptr == reinterpret_cast(pool_addr + pool_used)); 2193 } 2194 }; 2195 #endif // defined(GGML_SYCL_SUPPORT_VMM) 2196 2197 struct ggml_sycl_pool_host : public ggml_sycl_pool { 2198 queue_ptr qptr; 2199 int device; 2200 2201 struct ggml_sycl_buffer { 2202 void * ptr = nullptr; 2203 size_t size = 0; 2204 }; 2205 2206 // Set arbitrarly to 64 2207 static constexpr int MAX_POOL_SIZE{ 64 }; 2208 std::vector buffer_pool = std::vector(MAX_POOL_SIZE); 2209 size_t pool_size = 0; 2210 int counter = 0; 2211 2212 explicit ggml_sycl_pool_host(queue_ptr qptr_, int device_) : qptr(qptr_), device(device_) {} 2213 2214 ~ggml_sycl_pool_host() { 2215 for (int i = 0; i < MAX_POOL_SIZE; ++i) { 2216 ggml_sycl_buffer & b = buffer_pool[i]; 2217 if (b.ptr != nullptr) { 2218 SYCL_CHECK(CHECK_TRY_ERROR(sycl::free(b.ptr, *qptr))); 2219 b.ptr = nullptr; 2220 pool_size -= b.size; 2221 b.size = 0; 2222 } 2223 } 2224 } 2225 2226 void * alloc(size_t size, size_t * actual_size) override { 2227 if (counter == MAX_POOL_SIZE) { 2228 // the pool wrapped around, no slot is reserved for this allocation 2229 void * ptr = nullptr; 2230 SYCL_CHECK(CHECK_TRY_ERROR(ptr = (void *) sycl::malloc_host(size, *qptr))); 2231 if (!ptr) { 2232 GGML_LOG_ERROR("%s: can't allocate %zu Bytes of memory on host\n", __func__, size); 2233 return nullptr; 2234 } 2235 pool_size += size; 2236 *actual_size = size; 2237 counter = 0; 2238 return ptr; 2239 } 2240 ggml_sycl_buffer & b = buffer_pool[counter]; 2241 ++counter; 2242 2243 if (b.ptr != nullptr) { 2244 if (b.size >= size) { 2245 // hand out the cached buffer, free() puts it back into the pool 2246 void * ptr = b.ptr; 2247 *actual_size = b.size; 2248 b.ptr = nullptr; 2249 b.size = 0; 2250 return ptr; 2251 } 2252 // the cached buffer is too small, replace it 2253 SYCL_CHECK(CHECK_TRY_ERROR(sycl::free(b.ptr, *qptr))); 2254 pool_size -= b.size; 2255 b.ptr = nullptr; 2256 b.size = 0; 2257 } 2258 2259 void * ptr; 2260 SYCL_CHECK(CHECK_TRY_ERROR(ptr = (void *) sycl::malloc_host(size, *qptr))); 2261 if (!ptr) { 2262 GGML_LOG_ERROR("%s: can't allocate %zu Bytes of memory on host\n", __func__, size); 2263 return nullptr; 2264 } 2265 pool_size += size; 2266 *actual_size = size; 2267 return ptr; 2268 } 2269 2270 void free(void * ptr, size_t size) override { 2271 // if the pool is not completed add the pointer to it in place of the first nullptr found. 2272 // Otherwise free the buffer, all slots are cached. 2273 for (int i = 0; i < MAX_POOL_SIZE; ++i) { 2274 ggml_sycl_buffer & b = buffer_pool[i]; 2275 if (b.ptr == nullptr) { 2276 b.ptr = ptr; 2277 b.size = size; 2278 return; 2279 } 2280 } 2281 SYCL_CHECK(CHECK_TRY_ERROR(sycl::free(ptr, *qptr))); 2282 pool_size -= size; 2283 } 2284 }; 2285 2286 std::unique_ptr ggml_backend_sycl_context::new_pool_for_host(queue_ptr qptr, int device) { 2287 // return pool for the host to speed up memory management 2288 return std::unique_ptr(new ggml_sycl_pool_host(qptr, device)); 2289 } 2290 2291 std::unique_ptr ggml_backend_sycl_context::new_pool_for_device(queue_ptr qptr, int device) { 2292 #if defined(GGML_SYCL_SUPPORT_VMM) 2293 if (g_ggml_sycl_enable_vmm && ggml_sycl_info().devices[device].vmm) { 2294 return std::unique_ptr(new ggml_sycl_pool_vmm(qptr, device)); 2295 } 2296 #endif // defined(GGML_SYCL_SUPPORT_VMM) 2297 return std::unique_ptr(new ggml_sycl_pool_leg(qptr, device)); 2298 } 2299 2300 /// kernels 2301 typedef void (*ggml_sycl_op_mul_mat_t)( 2302 ggml_backend_sycl_context & ctx, 2303 const ggml_tensor *src0, const ggml_tensor *src1, ggml_tensor *dst, 2304 const char *src0_dd_i, const float *src1_ddf_i, const char *src1_ddq_i, 2305 float *dst_dd_i, const int64_t row_low, const int64_t row_high, 2306 const int64_t src1_ncols, const int64_t src1_padded_row_size, 2307 const queue_ptr &stream); 2308 2309 2310 2311 static void mul_mat_p021_f16_f32( 2312 const void * __restrict__ vx, const float * __restrict__ y, float * __restrict__ dst, 2313 const int ncols_x, const int nrows_x, const int nchannels_x, const int nchannels_y, 2314 const sycl::nd_item<3> &item_ct1) { 2315 2316 const sycl::half *x = (const sycl::half *)vx; 2317 2318 const int row_x = item_ct1.get_local_range(1) * item_ct1.get_group(1) + 2319 item_ct1.get_local_id(1); 2320 const int channel = item_ct1.get_local_range(0) * item_ct1.get_group(0) + 2321 item_ct1.get_local_id(0); 2322 const int channel_x = channel / (nchannels_y / nchannels_x); 2323 2324 const int nrows_y = ncols_x; 2325 const int nrows_dst = nrows_x; 2326 const int row_dst = row_x; 2327 2328 float tmp = 0.0f; 2329 2330 for (int col_x0 = 0; col_x0 < ncols_x; 2331 col_x0 += item_ct1.get_local_range(2)) { 2332 const int col_x = col_x0 + item_ct1.get_local_id(2); 2333 2334 if (col_x >= ncols_x) { 2335 break; 2336 } 2337 2338 // x is transposed and permuted 2339 const int ix = row_x*nchannels_x*ncols_x + channel_x*ncols_x + col_x; 2340 const float xi = 2341 sycl::vec(x[ix]) 2342 .convert()[0]; 2343 2344 const int row_y = col_x; 2345 2346 2347 // y is not transposed but permuted 2348 const int iy = channel*nrows_y + row_y; 2349 2350 tmp += xi * y[iy]; 2351 } 2352 2353 // dst is not transposed and not permuted 2354 const int idst = channel*nrows_dst + row_dst; 2355 2356 // sum up partial sums and write back result 2357 #pragma unroll 2358 for (int mask = WARP_SIZE / 2; mask > 0; mask >>= 1) { 2359 tmp += 2360 dpct::permute_sub_group_by_xor(item_ct1.get_sub_group(), tmp, mask); 2361 } 2362 2363 if (item_ct1.get_local_id(2) == 0) { 2364 dst[idst] = tmp; 2365 } 2366 } 2367 2368 static void mul_mat_vec_nc_f16_f32( // nc == non-contiguous 2369 const void * __restrict__ vx, const float * __restrict__ y, float * __restrict__ dst, const int ncols_x, const int nrows_x, 2370 const int row_stride_x, const int channel_stride_x,const int channel_stride_y, const int channel_x_divisor, 2371 const sycl::nd_item<3> &item_ct1) { 2372 2373 const sycl::half *x = (const sycl::half *)vx; 2374 2375 const int row_x = item_ct1.get_local_range(1) * item_ct1.get_group(1) + 2376 item_ct1.get_local_id(1); 2377 const int channel = item_ct1.get_local_range(0) * item_ct1.get_group(0) + 2378 item_ct1.get_local_id(0); 2379 const int channel_x = channel / channel_x_divisor; 2380 2381 const int nrows_dst = nrows_x; 2382 const int row_dst = row_x; 2383 2384 const int idst = channel*nrows_dst + row_dst; 2385 2386 float tmp = 0.0f; 2387 2388 for (int col_x0 = 0; col_x0 < ncols_x; 2389 col_x0 += item_ct1.get_local_range(2)) { 2390 const int col_x = col_x0 + item_ct1.get_local_id(2); 2391 2392 if (col_x >= ncols_x) { 2393 break; 2394 } 2395 2396 const int row_y = col_x; 2397 2398 const int ix = channel_x*channel_stride_x + row_x*row_stride_x + col_x; 2399 const int iy = channel * channel_stride_y + row_y; 2400 2401 const float xi = 2402 sycl::vec(x[ix]) 2403 .convert()[0]; 2404 2405 tmp += xi * y[iy]; 2406 } 2407 2408 // sum up partial sums and write back result 2409 #pragma unroll 2410 for (int mask = WARP_SIZE / 2; mask > 0; mask >>= 1) { 2411 tmp += 2412 dpct::permute_sub_group_by_xor(item_ct1.get_sub_group(), tmp, mask); 2413 } 2414 2415 if (item_ct1.get_local_id(2) == 0) { 2416 dst[idst] = tmp; 2417 } 2418 } 2419 2420 static void k_sum_rows_f32(const float * x, float * dst, const int ncols, 2421 const sycl::nd_item<3> &item_ct1) { 2422 const int row = item_ct1.get_group(1); 2423 const int col = item_ct1.get_local_id(2); 2424 2425 float sum = 0.0f; 2426 for (int i = col; i < ncols; i += item_ct1.get_local_range(2)) { 2427 sum += x[row * ncols + i]; 2428 } 2429 2430 sum = warp_reduce_sum(sum, item_ct1); 2431 2432 if (col == 0) { 2433 dst[row] = sum; 2434 } 2435 } 2436 2437 2438 template 2439 static inline void ggml_sycl_swap(T & a, T & b) { 2440 T tmp = a; 2441 a = b; 2442 b = tmp; 2443 } 2444 2445 template 2446 __dpct_inline__ static void 2447 k_argsort_f32_i32(const float *x, int *dst, const int ncols, int ncols_pad, 2448 const int tasks_per_thread, const sycl::nd_item<3> &item_ct1, 2449 uint8_t *dpct_local) { 2450 // bitonic sort 2451 int col_index = item_ct1.get_local_id(2); 2452 int row = item_ct1.get_group(1); 2453 2454 for (int i = 0; i < tasks_per_thread; i++) { 2455 int col = col_index * tasks_per_thread + i; 2456 if (col >= ncols_pad) { 2457 return; 2458 } 2459 } 2460 2461 const float * x_row = x + row * ncols; 2462 auto dst_row = (int *)dpct_local; 2463 2464 // initialize indices 2465 for (int i=0;i 0; j /= 2) { 2474 for (int i = 0; i < tasks_per_thread; i++) { 2475 int col = col_index * tasks_per_thread + i; 2476 int ixj = col ^ j; 2477 if (ixj > col) { 2478 if ((col & k) == 0) { 2479 if (dst_row[col] >= ncols || 2480 (dst_row[ixj] < ncols && 2481 (order == GGML_SORT_ORDER_ASC 2482 ? x_row[dst_row[col]] > x_row[dst_row[ixj]] 2483 : x_row[dst_row[col]] < 2484 x_row[dst_row[ixj]]))) { 2485 ggml_sycl_swap(dst_row[col], dst_row[ixj]); 2486 } 2487 } else { 2488 if (dst_row[ixj] >= ncols || 2489 (dst_row[col] < ncols && 2490 (order == GGML_SORT_ORDER_ASC 2491 ? x_row[dst_row[col]] < x_row[dst_row[ixj]] 2492 : x_row[dst_row[col]] > 2493 x_row[dst_row[ixj]]))) { 2494 ggml_sycl_swap(dst_row[col], dst_row[ixj]); 2495 } 2496 } 2497 } 2498 item_ct1.barrier(sycl::access::fence_space::local_space); 2499 } 2500 } 2501 } 2502 2503 // copy the result to dst without the padding 2504 for (int i = 0; i < tasks_per_thread; i++) { 2505 int col = col_index * tasks_per_thread + i; 2506 if (col < ncols) { 2507 dst[row * ncols + col] = dst_row[col]; 2508 } 2509 } 2510 } 2511 2512 static void diag_mask_inf_f32(const float * x, float * dst, const int ncols, const int rows_per_channel, const int n_past, 2513 const sycl::nd_item<3> &item_ct1) { 2514 const int col = item_ct1.get_local_range(1) * item_ct1.get_group(1) + 2515 item_ct1.get_local_id(1); 2516 const int row = item_ct1.get_local_range(2) * item_ct1.get_group(2) + 2517 item_ct1.get_local_id(2); 2518 2519 if (col >= ncols) { 2520 return; 2521 } 2522 2523 const int i = row*ncols + col; 2524 //dst[i] = col > (n_past + row % rows_per_channel) ? -INFINITY : x[i]; 2525 //dst[i] = x[i] - (col > n_past + row % rows_per_channel) * INT_MAX; // equivalent within rounding error but slightly faster on GPU 2526 dst[i] = x[i] - (col > n_past + row % rows_per_channel) * FLT_MAX; 2527 } 2528 2529 static void scale_f32(const float * x, float * dst, const float scale, const float bias, const int k, 2530 const sycl::nd_item<3> &item_ct1) { 2531 const int i = item_ct1.get_local_range(2) * item_ct1.get_group(2) + 2532 item_ct1.get_local_id(2); 2533 2534 if (i >= k) { 2535 return; 2536 } 2537 2538 dst[i] = scale * x[i] + bias; 2539 } 2540 2541 2542 static void ggml_mul_mat_p021_f16_f32_sycl(const void *vx, const float *y, 2543 float *dst, const int ncols_x, 2544 const int nrows_x, 2545 const int nchannels_x, 2546 const int nchannels_y, 2547 queue_ptr stream) { 2548 2549 const sycl::range<3> block_nums(nchannels_y, nrows_x, 1); 2550 const sycl::range<3> block_dims(1, 1, WARP_SIZE); 2551 { 2552 dpct::has_capability_or_fail(stream->get_device(), 2553 {sycl::aspect::fp16}); 2554 2555 stream->parallel_for( 2556 sycl::nd_range<3>(block_nums * block_dims, block_dims), 2557 [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { 2558 mul_mat_p021_f16_f32(vx, y, dst, ncols_x, nrows_x, nchannels_x, 2559 nchannels_y, item_ct1); 2560 }); 2561 } 2562 } 2563 2564 static void ggml_mul_mat_vec_nc_f16_f32_sycl( 2565 const void *vx, const float *y, float *dst, const int ncols_x, 2566 const int nrows_x, const int row_stride_x, const int nchannels_x, 2567 const int nchannels_y, const int channel_stride_x, const int channel_stride_y, queue_ptr stream) { 2568 2569 const sycl::range<3> block_nums(nchannels_y, nrows_x, 1); 2570 const sycl::range<3> block_dims(1, 1, WARP_SIZE); 2571 { 2572 dpct::has_capability_or_fail(stream->get_device(), 2573 {sycl::aspect::fp16}); 2574 2575 stream->parallel_for( 2576 sycl::nd_range<3>(block_nums * block_dims, block_dims), 2577 [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { 2578 mul_mat_vec_nc_f16_f32(vx, y, dst, ncols_x, nrows_x, 2579 row_stride_x, channel_stride_x, channel_stride_y, 2580 nchannels_y / nchannels_x, item_ct1); 2581 }); 2582 } 2583 } 2584 2585 2586 2587 static void scale_f32_sycl(const float *x, float *dst, const float scale, const float bias, 2588 const int k, queue_ptr stream) { 2589 const int num_blocks = (k + SYCL_SCALE_BLOCK_SIZE - 1) / SYCL_SCALE_BLOCK_SIZE; 2590 stream->parallel_for( 2591 sycl::nd_range<3>(sycl::range<3>(1, 1, num_blocks) * 2592 sycl::range<3>(1, 1, SYCL_SCALE_BLOCK_SIZE), 2593 sycl::range<3>(1, 1, SYCL_SCALE_BLOCK_SIZE)), 2594 [=](sycl::nd_item<3> item_ct1) { 2595 scale_f32(x, dst, scale, bias, k, item_ct1); 2596 }); 2597 } 2598 2599 2600 static void sum_rows_f32_sycl(const float *x, float *dst, const int ncols, 2601 const int nrows, queue_ptr stream) { 2602 const sycl::range<3> block_dims(1, 1, WARP_SIZE); 2603 const sycl::range<3> block_nums(1, nrows, 1); 2604 stream->parallel_for(sycl::nd_range<3>(block_nums * block_dims, block_dims), 2605 [=](sycl::nd_item<3> item_ct1) 2606 [[sycl::reqd_sub_group_size(WARP_SIZE)]] { 2607 k_sum_rows_f32(x, dst, ncols, item_ct1); 2608 }); 2609 } 2610 2611 static int next_power_of_2(int x) { 2612 int n = 1; 2613 while (n < x) { 2614 n *= 2; 2615 } 2616 return n; 2617 } 2618 2619 static void init_argsort_indices_padded( 2620 int * idx, 2621 const int nrows, 2622 const int ncols_pad, 2623 const sycl::nd_item<1> & item_ct1) { 2624 const size_t gid = item_ct1.get_local_range(0) * item_ct1.get_group(0) + item_ct1.get_local_id(0); 2625 const size_t total = (size_t) nrows * (size_t) ncols_pad; 2626 2627 if (gid >= total) { 2628 return; 2629 } 2630 2631 idx[gid] = (int) (gid % (size_t) ncols_pad); 2632 } 2633 2634 template 2635 static void argsort_f32_i32_global_pass(const float * x, 2636 int * idx, 2637 const int ncols, 2638 const int nrows, 2639 const int ncols_pad, 2640 const int j, 2641 const int k, 2642 const sycl::nd_item<1> & item_ct1) { 2643 const size_t gid = item_ct1.get_local_range(0) * item_ct1.get_group(0) + item_ct1.get_local_id(0); 2644 const size_t total = (size_t) nrows * (size_t) ncols_pad; 2645 2646 if (gid >= total) { 2647 return; 2648 } 2649 2650 const int row = (int) (gid / (size_t) ncols_pad); 2651 const int col = (int) (gid % (size_t) ncols_pad); 2652 const int ixj = col ^ j; 2653 2654 if (ixj <= col || ixj >= ncols_pad) { 2655 return; 2656 } 2657 2658 const size_t base = (size_t) row * (size_t) ncols_pad; 2659 const size_t pos_a = base + (size_t) col; 2660 const size_t pos_b = base + (size_t) ixj; 2661 2662 const int a = idx[pos_a]; 2663 const int b = idx[pos_b]; 2664 2665 bool do_swap = false; 2666 2667 if ((col & k) == 0) { 2668 if (a >= ncols || 2669 (b < ncols && 2670 (order == GGML_SORT_ORDER_ASC ? 2671 x[(size_t) row * (size_t) ncols + (size_t) a] > x[(size_t) row * (size_t) ncols + (size_t) b] : 2672 x[(size_t) row * (size_t) ncols + (size_t) a] < x[(size_t) row * (size_t) ncols + (size_t) b]))) { 2673 do_swap = true; 2674 } 2675 } else { 2676 if (b >= ncols || 2677 (a < ncols && 2678 (order == GGML_SORT_ORDER_ASC ? 2679 x[(size_t) row * (size_t) ncols + (size_t) a] < x[(size_t) row * (size_t) ncols + (size_t) b] : 2680 x[(size_t) row * (size_t) ncols + (size_t) a] > x[(size_t) row * (size_t) ncols + (size_t) b]))) { 2681 do_swap = true; 2682 } 2683 } 2684 2685 if (do_swap) { 2686 idx[pos_a] = b; 2687 idx[pos_b] = a; 2688 } 2689 } 2690 2691 static void copy_argsort_indices_unpadded(const int * idx_padded, 2692 int * dst, 2693 const int nrows, 2694 const int ncols, 2695 const int ncols_pad, 2696 const sycl::nd_item<1> & item_ct1) { 2697 const size_t gid = item_ct1.get_local_range(0) * item_ct1.get_group(0) + item_ct1.get_local_id(0); 2698 const size_t total = (size_t) nrows * (size_t) ncols; 2699 2700 if (gid >= total) { 2701 return; 2702 } 2703 2704 const int row = (int) (gid / (size_t) ncols); 2705 const int col = (int) (gid % (size_t) ncols); 2706 2707 dst[(size_t) row * (size_t) ncols + (size_t) col] = idx_padded[(size_t) row * (size_t) ncols_pad + (size_t) col]; 2708 } 2709 2710 static void argsort_f32_i32_sycl(const float *x, int *dst, const int ncols, 2711 const int nrows, ggml_sort_order order, 2712 queue_ptr stream, int device, ggml_sycl_pool & pool) { 2713 // bitonic sort requires ncols to be power of 2 2714 const int ncols_pad = next_power_of_2(ncols); 2715 const size_t shared_mem = (size_t) ncols_pad * sizeof(int); 2716 const size_t smpbo = ggml_sycl_info().devices[device].smpbo; 2717 2718 if (shared_mem > smpbo) { 2719 ggml_sycl_pool_alloc idx_padded_alloc(pool, (size_t) nrows * (size_t) ncols_pad); 2720 int * idx_padded = idx_padded_alloc.get(); 2721 2722 constexpr size_t block_size = 256; 2723 const size_t total_padded = (size_t) nrows * (size_t) ncols_pad; 2724 const size_t nblocks_padded = (total_padded + block_size - 1) / block_size; 2725 2726 stream->parallel_for( 2727 sycl::nd_range<1>(sycl::range<1>(nblocks_padded * block_size), sycl::range<1>(block_size)), 2728 [=](sycl::nd_item<1> item_ct1) { init_argsort_indices_padded(idx_padded, nrows, ncols_pad, item_ct1); }); 2729 2730 for (int k = 2; k <= ncols_pad; k *= 2) { 2731 for (int j = k / 2; j > 0; j /= 2) { 2732 if (order == GGML_SORT_ORDER_ASC) { 2733 stream->parallel_for( 2734 sycl::nd_range<1>(sycl::range<1>(nblocks_padded * block_size), sycl::range<1>(block_size)), 2735 [=](sycl::nd_item<1> item_ct1) { 2736 argsort_f32_i32_global_pass(x, idx_padded, ncols, nrows, ncols_pad, j, 2737 k, item_ct1); 2738 }); 2739 } else if (order == GGML_SORT_ORDER_DESC) { 2740 stream->parallel_for( 2741 sycl::nd_range<1>(sycl::range<1>(nblocks_padded * block_size), sycl::range<1>(block_size)), 2742 [=](sycl::nd_item<1> item_ct1) { 2743 argsort_f32_i32_global_pass(x, idx_padded, ncols, nrows, ncols_pad, j, 2744 k, item_ct1); 2745 }); 2746 } else { 2747 GGML_ABORT("invalid sort order"); 2748 } 2749 } 2750 } 2751 2752 const size_t total = (size_t) nrows * (size_t) ncols; 2753 const size_t nblocks = (total + block_size - 1) / block_size; 2754 stream->parallel_for(sycl::nd_range<1>(sycl::range<1>(nblocks * block_size), sycl::range<1>(block_size)), 2755 [=](sycl::nd_item<1> item_ct1) { 2756 copy_argsort_indices_unpadded(idx_padded, dst, nrows, ncols, ncols_pad, item_ct1); 2757 }); 2758 2759 return; 2760 } 2761 2762 int nth = 1; 2763 int max_block_size = ggml_sycl_info().max_work_group_sizes[device]; 2764 while (nth < ncols_pad && nth < max_block_size) 2765 nth *= 2; 2766 if (nth > max_block_size) 2767 nth = max_block_size; 2768 2769 const int tasks_per_thread = ncols_pad / nth; 2770 2771 const sycl::range<3> block_dims(1, 1, nth); 2772 const sycl::range<3> block_nums(1, nrows, 1); 2773 2774 if (order == GGML_SORT_ORDER_ASC) { 2775 stream->submit([&](sycl::handler &cgh) { 2776 sycl::local_accessor dpct_local_acc_ct1( 2777 sycl::range<1>(shared_mem), cgh); 2778 2779 cgh.parallel_for( 2780 sycl::nd_range<3>(block_nums * block_dims, block_dims), 2781 [=](sycl::nd_item<3> item_ct1) { 2782 k_argsort_f32_i32( 2783 x, dst, ncols, ncols_pad, tasks_per_thread, item_ct1, 2784 dpct_local_acc_ct1 2785 .get_multi_ptr() 2786 .get()); 2787 }); 2788 }); 2789 } else if (order == GGML_SORT_ORDER_DESC) { 2790 stream->submit([&](sycl::handler &cgh) { 2791 sycl::local_accessor dpct_local_acc_ct1( 2792 sycl::range<1>(shared_mem), cgh); 2793 2794 cgh.parallel_for( 2795 sycl::nd_range<3>(block_nums * block_dims, block_dims), 2796 [=](sycl::nd_item<3> item_ct1) { 2797 k_argsort_f32_i32( 2798 x, dst, ncols, ncols_pad, tasks_per_thread, item_ct1, 2799 dpct_local_acc_ct1 2800 .get_multi_ptr() 2801 .get()); 2802 }); 2803 }); 2804 } else { 2805 GGML_ABORT("fatal error"); 2806 } 2807 } 2808 2809 // Scan and block merge, shared by every launch shape below so a partitioned row uses the 2810 // same insertion order as an unpartitioned one. 2811 // 2812 // src_map != nullptr: report src_map[col] instead of col, so a merge pass can carry the 2813 // original column index through. 2814 // out_vals != nullptr: also emit the k winning values, for a later merge pass. 2815 // swap01: emit in the output order the single-pass path uses. 2816 static void top_k_scan_merge_f32( 2817 const float * src_vals, 2818 const int32_t * src_map, 2819 const int begin, 2820 const int end, 2821 const int k, 2822 const int block_size, 2823 float * shared_vals, 2824 int * shared_idx, 2825 float * out_vals, 2826 int32_t * out_idx, 2827 const bool swap01, 2828 const sycl::nd_item<1> & item_ct1 2829 ) { 2830 const int tid = item_ct1.get_local_id(0); 2831 2832 // The running top-k lives in SLM (shared local memory) rather than a private array: 2833 // an array indexed by a runtime position cannot be register-allocated, so a private 2834 // one lands in scratch, i.e. device memory, and insertion is this kernel's dominant 2835 // cost. 2836 // 2837 // Lane-strided (lv[i * block_size]) rather than lane-blocked (lv[i]) so a given i is 2838 // contiguous across lanes; a k-strided layout would put every lane of a shift step in 2839 // the same SLM bank. 2840 float * lv = shared_vals + tid; 2841 int * li = shared_idx + tid; 2842 2843 for (int i = 0; i < k; i++) { 2844 lv[i * block_size] = -FLT_MAX; 2845 li[i * block_size] = -1; 2846 } 2847 2848 // The k-th best, cached in a register. The reject test is taken for the large 2849 // majority of elements scanned, and in that case touches no memory. 2850 float kth = -FLT_MAX; 2851 2852 for (int col = begin + tid; col < end; col += block_size) { 2853 float val = src_vals[col]; 2854 2855 if (val > kth) { 2856 int pos = k - 1; 2857 while (pos > 0 && val > lv[(pos - 1) * block_size]) { 2858 pos--; 2859 } 2860 2861 for (int i = k - 1; i > pos; i--) { 2862 lv[i * block_size] = lv[(i - 1) * block_size]; 2863 li[i * block_size] = li[(i - 1) * block_size]; 2864 } 2865 lv[pos * block_size] = val; 2866 li[pos * block_size] = src_map ? src_map[col] : col; 2867 2868 kth = lv[(k - 1) * block_size]; 2869 } 2870 } 2871 2872 item_ct1.barrier(sycl::access::fence_space::local_space); 2873 2874 if (tid != 0) { 2875 return; 2876 } 2877 2878 // Same treatment for the merge accumulator, past the per-lane region. 2879 float * fv = shared_vals + (size_t) k * block_size; 2880 int * fi = shared_idx + (size_t) k * block_size; 2881 2882 for (int i = 0; i < k; i++) { 2883 fv[i] = -FLT_MAX; 2884 fi[i] = -1; 2885 } 2886 2887 float fkth = -FLT_MAX; 2888 2889 // Candidates are visited in the same (t, i) order as before, so tie-breaking is 2890 // unchanged. 2891 for (int t = 0; t < block_size; t++) { 2892 for (int i = 0; i < k; i++) { 2893 float val = shared_vals[i * block_size + t]; 2894 2895 if (val <= fkth) { 2896 // Lane t's list is sorted descending, so once one of its entries loses 2897 // to the k-th best, every later entry loses too. fkth only rises, so 2898 // that stays true for the rest of the merge. This turns the merge from 2899 // block_size*k steps into roughly block_size plus the candidates 2900 // accepted. 2901 break; 2902 } 2903 2904 int idx = shared_idx[i * block_size + t]; 2905 2906 int pos = k - 1; 2907 while (pos > 0 && val > fv[pos - 1]) { 2908 pos--; 2909 } 2910 2911 for (int j = k - 1; j > pos; j--) { 2912 fv[j] = fv[j - 1]; 2913 fi[j] = fi[j - 1]; 2914 } 2915 fv[pos] = val; 2916 fi[pos] = idx; 2917 2918 fkth = fv[k - 1]; 2919 } 2920 } 2921 2922 if (out_vals) { 2923 for (int i = 0; i < k; i++) { 2924 out_vals[i] = fv[i]; 2925 } 2926 } 2927 2928 for (int i = 0; i < k; i++) { 2929 out_idx[i] = fi[i]; 2930 } 2931 2932 if (swap01 && k > 1) { 2933 int32_t temp = out_idx[0]; 2934 out_idx[0] = out_idx[1]; 2935 out_idx[1] = temp; 2936 } 2937 } 2938 2939 static void top_k_f32_sycl( 2940 ggml_backend_sycl_context & ctx, 2941 const float * src, 2942 int32_t * dst_indices, 2943 const int64_t ncols, 2944 const int64_t nrows, 2945 const int k, 2946 dpct::queue_ptr main_stream 2947 ) { 2948 // A row is scanned by exactly one work-group, so a vocabulary-sized row leaves the 2949 // rest of the device idle. What the scan is short of is memory requests in flight, 2950 // not bandwidth or per-request latency, so lanes in flight is the lever: split the 2951 // row across independent work-groups, have each emit its partition's top-k, and 2952 // merge those nsplit*k candidates in a second launch. 2953 // 2954 // split_block trades parallelism against SLM residency. Its cost is 2955 // (split_block + 1) * k * 8 bytes of SLM per group, so at the k <= 32 ceiling 128 2956 // lanes need about 33 KB, which leaves a single resident group per Xe-core. Revisit 2957 // if the supported k ever grows. 2958 constexpr int split_block = 128; 2959 constexpr int max_splits = 128; 2960 constexpr int min_cols = 8192; 2961 2962 int nsplit = 1; 2963 if (ncols >= min_cols) { 2964 // A partition is then always >= split_block = 128 columns, hence always more than 2965 // the k <= 32 ceiling, so no pass is ever padded with -FLT_MAX sentinels. 2966 const int64_t want = ncols / split_block; 2967 nsplit = (int) (want > max_splits ? max_splits : want); 2968 } 2969 2970 if (nsplit > 1) { 2971 const int nchunk = (int) ((ncols + nsplit - 1) / nsplit); 2972 const size_t ncand = (size_t) nrows * nsplit * k; 2973 2974 ggml_sycl_pool_alloc part_vals(ctx.pool(), ncand); 2975 ggml_sycl_pool_alloc part_idx(ctx.pool(), ncand); 2976 2977 float * pv = part_vals.get(); 2978 int32_t * pi = part_idx.get(); 2979 2980 const sycl::range<1> block_dims(split_block); 2981 2982 main_stream->submit([&](sycl::handler &cgh) { 2983 sycl::local_accessor shared_vals(sycl::range<1>((split_block + 1) * k), cgh); 2984 sycl::local_accessor shared_idx(sycl::range<1>((split_block + 1) * k), cgh); 2985 2986 cgh.parallel_for( 2987 sycl::nd_range<1>(sycl::range<1>(nrows * nsplit) * block_dims, block_dims), 2988 [=](sycl::nd_item<1> item_ct1) { 2989 const int grp = item_ct1.get_group(0); 2990 const int row = grp / nsplit; 2991 const int part = grp % nsplit; 2992 2993 const int begin = part * nchunk; 2994 int end = begin + nchunk; 2995 if (end > (int) ncols) { 2996 end = (int) ncols; 2997 } 2998 2999 top_k_scan_merge_f32( 3000 src + (int64_t) row * ncols, nullptr, begin, end, k, split_block, 3001 shared_vals.get_multi_ptr().get(), 3002 shared_idx.get_multi_ptr().get(), 3003 pv + (size_t) grp * k, pi + (size_t) grp * k, false, item_ct1); 3004 }); 3005 }); 3006 3007 main_stream->submit([&](sycl::handler &cgh) { 3008 sycl::local_accessor shared_vals(sycl::range<1>((split_block + 1) * k), cgh); 3009 sycl::local_accessor shared_idx(sycl::range<1>((split_block + 1) * k), cgh); 3010 3011 cgh.parallel_for( 3012 sycl::nd_range<1>(sycl::range<1>(nrows) * block_dims, block_dims), 3013 [=](sycl::nd_item<1> item_ct1) { 3014 const int row = item_ct1.get_group(0); 3015 const size_t off = (size_t) row * nsplit * k; 3016 3017 top_k_scan_merge_f32( 3018 pv + off, pi + off, 0, nsplit * k, k, split_block, 3019 shared_vals.get_multi_ptr().get(), 3020 shared_idx.get_multi_ptr().get(), 3021 nullptr, dst_indices + (int64_t) row * k, true, item_ct1); 3022 }); 3023 }); 3024 3025 return; 3026 } 3027 3028 // Short rows: one work-item per column and k work-group argmax rounds. 3029 // Ties take the lower column. 3030 const int wg = std::max(WARP_SIZE, next_power_of_2((int) ncols)); 3031 if (wg <= ggml_sycl_info().max_work_group_sizes[ctx.device]) { 3032 main_stream->parallel_for( 3033 sycl::nd_range<1>(sycl::range<1>(nrows * wg), sycl::range<1>(wg)), 3034 [=](sycl::nd_item<1> item_ct1) { 3035 const int64_t row = item_ct1.get_group(0); 3036 const int tid = item_ct1.get_local_id(0); 3037 const auto grp = item_ct1.get_group(); 3038 3039 // NaN is never preferred, and every round still has a winner since k <= ncols 3040 const float x = tid < ncols ? src[row * ncols + tid] : -INFINITY; 3041 const float val = sycl::isnan(x) ? -INFINITY : x; 3042 bool taken = tid >= ncols; 3043 for (int i = 0; i < k; i++) { 3044 const float cand = taken ? -INFINITY : val; 3045 const float best = sycl::reduce_over_group(grp, cand, sycl::maximum()); 3046 const int winner = sycl::reduce_over_group(grp, !taken && cand == best ? tid : INT_MAX, 3047 sycl::minimum()); 3048 if (tid == winner) { 3049 dst_indices[row * k + i] = tid; 3050 taken = true; 3051 } 3052 } 3053 }); 3054 return; 3055 } 3056 3057 const int block_size = 128; 3058 3059 const sycl::range<1> block_dims(block_size); 3060 const sycl::range<1> grid_dims(nrows); 3061 3062 main_stream->submit([&](sycl::handler &cgh) { 3063 sycl::local_accessor shared_vals(sycl::range<1>((block_size + 1) * k), cgh); 3064 sycl::local_accessor shared_idx(sycl::range<1>((block_size + 1) * k), cgh); 3065 3066 cgh.parallel_for( 3067 sycl::nd_range<1>(grid_dims * block_dims, block_dims), 3068 [=](sycl::nd_item<1> item_ct1) { 3069 const int row = item_ct1.get_group(0); 3070 3071 if (row >= nrows) return; 3072 3073 top_k_scan_merge_f32( 3074 src + (int64_t) row * ncols, nullptr, 0, (int) ncols, k, block_size, 3075 shared_vals.get_multi_ptr().get(), 3076 shared_idx.get_multi_ptr().get(), 3077 nullptr, dst_indices + (int64_t) row * k, true, item_ct1); 3078 }); 3079 }); 3080 } 3081 3082 static void argmax_f32_i32_sycl(const float *x, int *dst, const int ncols, 3083 const int nrows, queue_ptr stream) { 3084 const sycl::range<3> block_dims(1, 1, SYCL_ARGMAX_BLOCK_SIZE); 3085 const sycl::range<3> block_nums(1, nrows, 1); 3086 const size_t shared_mem = 256 * sizeof(float); 3087 3088 stream->submit([&](sycl::handler &cgh) { 3089 sycl::local_accessor shared_data( 3090 sycl::range<1>(shared_mem/sizeof(float)), cgh); 3091 sycl::local_accessor shared_indices( 3092 sycl::range<1>(shared_mem/sizeof(float)), cgh); 3093 3094 cgh.parallel_for( 3095 sycl::nd_range<3>(block_nums * block_dims, block_dims), 3096 [=](sycl::nd_item<3> item_ct1) { 3097 const int tid = item_ct1.get_local_id(2); 3098 const int row = item_ct1.get_global_id(1); 3099 3100 float max_val = -INFINITY; 3101 int max_idx = -1; 3102 3103 for (int col = tid; col < ncols; col += 256) { 3104 float val = x[row * ncols + col]; 3105 if (val > max_val) { 3106 max_val = val; 3107 max_idx = col; 3108 } 3109 } 3110 3111 shared_data[tid] = max_val; 3112 shared_indices[tid] = max_idx; 3113 item_ct1.barrier(sycl::access::fence_space::local_space); 3114 3115 for (int stride = 256/2; stride > 0; stride >>= 1) { 3116 if (tid < stride) { 3117 float val1 = shared_data[tid]; 3118 float val2 = shared_data[tid + stride]; 3119 if (val2 > val1) { 3120 shared_data[tid] = val2; 3121 shared_indices[tid] = shared_indices[tid + stride]; 3122 } 3123 } 3124 item_ct1.barrier(sycl::access::fence_space::local_space); 3125 } 3126 3127 3128 if (tid == 0) { 3129 dst[row] = shared_indices[0]; 3130 } 3131 }); 3132 }); 3133 } 3134 static void diag_mask_inf_f32_sycl(const float *x, float *dst, 3135 const int ncols_x, const int nrows_x, 3136 const int rows_per_channel, const int n_past, 3137 queue_ptr stream) { 3138 const sycl::range<3> block_dims(1, SYCL_DIAG_MASK_INF_BLOCK_SIZE, 1); 3139 const int block_num_x = (ncols_x + SYCL_DIAG_MASK_INF_BLOCK_SIZE - 1) / SYCL_DIAG_MASK_INF_BLOCK_SIZE; 3140 const sycl::range<3> block_nums(1, block_num_x, nrows_x); 3141 stream->parallel_for(sycl::nd_range<3>(block_nums * block_dims, block_dims), 3142 [=](sycl::nd_item<3> item_ct1) { 3143 diag_mask_inf_f32(x, dst, ncols_x, 3144 rows_per_channel, n_past, 3145 item_ct1); 3146 }); 3147 } 3148 3149 static dpct::err0 ggml_sycl_cpy_tensor_2d(void *dst, 3150 const struct ggml_tensor *src, 3151 int64_t i3, int64_t i2, 3152 int64_t i1_low, int64_t i1_high, 3153 queue_ptr stream) try { 3154 3155 dpct::memcpy_direction kind; 3156 char * src_ptr; 3157 if (ggml_backend_buffer_is_host(src->buffer)) { 3158 kind = dpct::host_to_device; 3159 //GGML_SYCL_DEBUG("%s: Host buffer type src tensor\n", __func__); 3160 src_ptr = (char *) src->data; 3161 // GGML_SYCL_DEBUG("ggml_sycl_cpy_tensor_2d GGML_BACKEND_TYPE_CPU src_ptr %p\n", src_ptr); 3162 } else if (ggml_backend_buffer_is_sycl(src->buffer)) { 3163 // If buffer is a SYCL buffer 3164 //GGML_SYCL_DEBUG("%s: SYCL buffer type src tensor\n", __func__); 3165 kind = dpct::device_to_device; 3166 src_ptr = (char *) src->data; 3167 } else if (ggml_backend_buffer_is_sycl_split(src->buffer)) { 3168 /* 3169 If buffer is a SYCL split buffer 3170 */ 3171 //GGML_SYCL_DEBUG("%s: Split buffer type src tensor\n", __func__); 3172 GGML_ASSERT(i1_low == 0 && i1_high == src->ne[1]); 3173 kind = dpct::device_to_device; 3174 ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) src->extra; 3175 int id; 3176 SYCL_CHECK(CHECK_TRY_ERROR( 3177 id = get_current_device_id())); 3178 // GGML_SYCL_DEBUG("current device index %d\n", id); 3179 src_ptr = (char *) extra->data_device[id]; 3180 } else { 3181 // GGML_SYCL_DEBUG("GGML_ABORT("fatal error")\n"); 3182 GGML_ABORT("fatal error"); 3183 } 3184 char * dst_ptr = (char *) dst; 3185 3186 GGML_TENSOR_LOCALS_1(int64_t, ne, src, ne); 3187 GGML_TENSOR_LOCALS(int64_t, nb, src, nb); 3188 const enum ggml_type type = src->type; 3189 const int64_t ts = ggml_type_size(type); 3190 const int64_t bs = ggml_blck_size(type); 3191 int64_t i1_diff = i1_high - i1_low; 3192 3193 const char * x = src_ptr + i1_low*nb1 + i2*nb2 + i3*nb3; 3194 if (nb0 == ts && nb1 == ts*ne0/bs) { 3195 // GGML_SYCL_DEBUG("stream->memcpy: dst_ptr=%p, x=%p, size=%lu\n", dst_ptr, x, i1_diff * nb1); 3196 // return CHECK_TRY_ERROR(stream->memcpy(dst_ptr, x, i1_diff * nb1)); 3197 return CHECK_TRY_ERROR(dpct::async_dpct_memcpy(dst_ptr, x, i1_diff * nb1, 3198 kind, *stream)); 3199 3200 } else if (nb0 == ts) { 3201 return CHECK_TRY_ERROR( 3202 dpct::async_dpct_memcpy(dst_ptr, ts * ne0 / bs, x, nb1, 3203 ts * ne0 / bs, i1_diff, kind, *stream)); 3204 } else { 3205 for (int64_t i1 = 0; i1 < i1_diff; i1++) { 3206 const void * rx = (const void *) ((const char *) x + i1*nb1); 3207 void * rd = (void *) (dst_ptr + i1*ts*ne0/bs); 3208 // pretend the row is a matrix with cols=1 3209 dpct::err0 r = CHECK_TRY_ERROR(dpct::async_dpct_memcpy( 3210 rd, ts / bs, rx, nb0, ts / bs, ne0, kind, *stream)); 3211 /* 3212 DPCT1001:85: The statement could not be removed. 3213 */ 3214 /* 3215 DPCT1000:86: Error handling if-stmt was detected but could not be 3216 rewritten. 3217 */ 3218 if (r != 0) return r; 3219 } 3220 return 0; 3221 } 3222 } 3223 catch (sycl::exception const &exc) { 3224 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 3225 << ", line:" << __LINE__ << std::endl; 3226 std::exit(1); 3227 } 3228 3229 #if GGML_SYCL_DNNL 3230 // F32 GEMMs below this size (row_diff * src1_ncols * ne10) call oneMKL directly instead of oneDNN 3231 static constexpr int64_t SYCL_F32_DNNL_MIN_GEMM_FLOPS = 256 * 256 * 256; 3232 #endif 3233 3234 inline void ggml_sycl_op_mul_mat_sycl( 3235 ggml_backend_sycl_context & ctx, 3236 const ggml_tensor *src0, const ggml_tensor *src1, ggml_tensor *dst, 3237 const char *src0_dd_i, const float *src1_ddf_i, const char *src1_ddq_i, 3238 float *dst_dd_i, const int64_t row_low, const int64_t row_high, 3239 const int64_t src1_ncols, const int64_t src1_padded_row_size, 3240 const queue_ptr &stream) try { 3241 3242 GGML_ASSERT(src0_dd_i != nullptr); 3243 GGML_ASSERT(src1_ddf_i != nullptr); 3244 GGML_ASSERT(dst_dd_i != nullptr); 3245 3246 const int64_t ne00 = src0->ne[0]; 3247 const int64_t ne10 = src1->ne[0]; 3248 GGML_ASSERT(ne00 == ne10); 3249 3250 const int64_t row_diff = row_high - row_low; 3251 3252 int id; 3253 SYCL_CHECK( 3254 CHECK_TRY_ERROR(id = get_current_device_id())); 3255 3256 const int64_t ne0 = dst->ne[0]; // used by MKL only 3257 // the main device has a larger memory buffer to hold the results from all GPUs 3258 // ldc == nrows of the matrix that cuBLAS writes into 3259 int ldc = id == ctx.device ? ne0 : row_diff; // used by MKL only 3260 3261 #ifdef GGML_SYCL_F16 3262 bool use_fp16 = true; // TODO(Yu) SYCL capability check 3263 #else 3264 bool use_fp16 = false; 3265 #endif 3266 3267 #if GGML_SYCL_DNNL && defined(GGML_SYCL_HAS_BF16) 3268 // Fast path for bf16 src0 3269 if (src0->type == GGML_TYPE_BF16 && g_ggml_sycl_enable_dnn && 3270 ggml_sycl_dnnl_has_optimized_gemm(ggml_sycl_get_device()) && ggml_is_contiguous(src0) && 3271 row_diff == src0->ne[1]) { 3272 using bf16_t = sycl::ext::oneapi::bfloat16; 3273 ggml_sycl_pool_alloc src1_as_bf16(ctx.pool(), src1_ncols*ne10); 3274 if (src1->type != GGML_TYPE_BF16) { 3275 const to_bf16_sycl_t to_bf16_sycl = ggml_get_to_bf16_sycl(src1->type, dst); 3276 GGML_ASSERT(to_bf16_sycl != nullptr); 3277 to_bf16_sycl(src1_ddf_i, src1_as_bf16.get(), src1_ncols*ne10, stream); 3278 } else { 3279 stream->memcpy(src1_as_bf16.get(), src1_ddf_i, src1_ncols*ne10*sizeof(bf16_t)); 3280 } 3281 DnnlGemmWrapper::row_gemm(ctx, row_diff, src1_ncols, ne10, 3282 src0_dd_i, DnnlGemmWrapper::to_dt(), 3283 src1_as_bf16.get(), DnnlGemmWrapper::to_dt(), 3284 dst_dd_i, DnnlGemmWrapper::to_dt(), stream); 3285 GGML_UNUSED(dst); 3286 GGML_UNUSED(src1_ddq_i); 3287 GGML_UNUSED(src1_padded_row_size); 3288 return; 3289 } 3290 #endif 3291 3292 // dequantize inside the GEMM instead of writing the f16 weights out and reading them back; src1 3293 // goes in its own type, so there is no separate conversion pass. The A stage 3294 // decodes the weight bytes in place, so an installed persistent reorder must be 3295 // visible to it: pass the flag through; types without an SoA A-stage decline 3296 // inside and this falls through to the reorder-aware conversion route below. 3297 bool src0_reordered = false; 3298 if (const auto * src0_extra = static_cast(src0->extra)) { 3299 src0_reordered = src0_extra->optimized_feature.reorder; 3300 } 3301 if (ggml_is_quantized(src0->type) && ggml_is_contiguous(src0) && row_diff == src0->ne[1] && 3302 ggml_sycl_fused_dequant_gemm(src0->type, src0_reordered, src0_dd_i, src1_ddf_i, src1->type, ggml_sycl_src1_prec(dst), dst_dd_i, 3303 row_diff, src1_ncols, ne10, ldc, ctx.pool(), stream)) { 3304 return; 3305 } 3306 3307 // the f16 route converts src1 to f16 [TAG_GGML_PREC] 3308 use_fp16 = use_fp16 && ggml_sycl_src1_f16_ok(dst); 3309 if ((src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)) && use_fp16 && ggml_is_contiguous(src0) && 3310 row_diff == src0->ne[1] && dst->op_params[0] == GGML_PREC_DEFAULT) { 3311 ggml_sycl_pool_alloc src1_as_f16(ctx.pool()); 3312 if (src1->type != GGML_TYPE_F16) { 3313 scope_op_debug_print scope_dbg_print(__func__, "/to_fp16_sycl", dst, /*num_src=*/2, 3314 " : converting src1 to fp16"); 3315 const to_fp16_sycl_t to_fp16_sycl = ggml_get_to_fp16_sycl(src1->type, dst); 3316 GGML_ASSERT(to_fp16_sycl != nullptr); 3317 size_t ne = src1_ncols*ne10; 3318 src1_as_f16.alloc(ne); 3319 to_fp16_sycl(src1_ddf_i, src1_as_f16.get(), ne, stream); 3320 } 3321 const sycl::half *src1_ptr = src1->type == GGML_TYPE_F16 3322 ? (const sycl::half *)src1_ddf_i 3323 : src1_as_f16.get(); 3324 3325 ggml_sycl_pool_alloc src0_as_f16(ctx.pool()); 3326 if (src0->type != GGML_TYPE_F16) { 3327 scope_op_debug_print scope_dbg_print(__func__, "/to_fp16_sycl", dst, /*num_src=*/2, 3328 " : converting src0 to fp16"); 3329 const to_fp16_sycl_t to_fp16_sycl = ggml_get_to_fp16_sycl(src0->type, dst); 3330 GGML_ASSERT(to_fp16_sycl != nullptr); 3331 size_t ne = row_diff*ne00; 3332 src0_as_f16.alloc(ne); 3333 to_fp16_sycl(src0_dd_i, src0_as_f16.get(), ne, stream); 3334 } 3335 const sycl::half *src0_ptr = src0->type == GGML_TYPE_F16 3336 ? (const sycl::half *)src0_dd_i 3337 : src0_as_f16.get(); 3338 3339 #if GGML_SYCL_DNNL 3340 if (g_ggml_sycl_enable_dnn && ggml_sycl_dnnl_has_optimized_gemm(ggml_sycl_get_device())) { 3341 DnnlGemmWrapper::row_gemm(ctx,row_diff, src1_ncols , ne10, src0_ptr, 3342 DnnlGemmWrapper::to_dt(), src1_ptr, DnnlGemmWrapper::to_dt(), 3343 dst_dd_i, DnnlGemmWrapper::to_dt(), stream); 3344 } 3345 else 3346 #endif 3347 { 3348 const float alpha = 1.0f; 3349 const float beta = 0.0f; 3350 SYCL_CHECK(CHECK_TRY_ERROR(dpct::gemm( 3351 *stream, oneapi::mkl::transpose::trans, 3352 oneapi::mkl::transpose::nontrans, row_diff, src1_ncols, ne10, 3353 &alpha, src0_ptr, dpct::library_data_t::real_half, ne00, 3354 src1_ptr, dpct::library_data_t::real_half, ne10, &beta, 3355 dst_dd_i, dpct::library_data_t::real_float, ldc, 3356 dpct::library_data_t::real_float))); 3357 } 3358 } else { 3359 ggml_sycl_pool_alloc src0_ddq_as_f32(ctx.pool()); 3360 ggml_sycl_pool_alloc src1_ddq_as_f32(ctx.pool()); 3361 if (src0->type != GGML_TYPE_F32) { 3362 scope_op_debug_print scope_dbg_print(__func__, "/to_fp32_sycl", dst, /*num_src=*/2, 3363 " : converting src0 to fp32"); 3364 const to_fp32_sycl_t to_fp32_sycl = ggml_get_to_fp32_sycl(src0->type, dst); 3365 GGML_ASSERT(to_fp32_sycl != nullptr); 3366 src0_ddq_as_f32.alloc(row_diff*ne00); 3367 to_fp32_sycl(src0_dd_i, src0_ddq_as_f32.get(), row_diff*ne00, stream); 3368 } 3369 if (src1->type != GGML_TYPE_F32) { 3370 scope_op_debug_print scope_dbg_print(__func__, "/to_fp32_sycl", dst, /*num_src=*/2, 3371 " : converting src1 to fp32"); 3372 const to_fp32_sycl_t to_fp32_sycl = ggml_get_to_fp32_sycl(src1->type, dst); 3373 GGML_ASSERT(to_fp32_sycl != nullptr); 3374 src1_ddq_as_f32.alloc(src1_ncols*ne10); 3375 to_fp32_sycl(src1_ddf_i, src1_ddq_as_f32.get(), src1_ncols*ne10, stream); 3376 } 3377 const float * src0_ddf_i = src0->type == GGML_TYPE_F32 ? (const float *) src0_dd_i : src0_ddq_as_f32.get(); 3378 const float * src1_ddf1_i = src1->type == GGML_TYPE_F32 ? (const float *) src1_ddf_i : src1_ddq_as_f32.get(); 3379 3380 { 3381 #if GGML_SYCL_DNNL 3382 const int64_t gemm_flops = (int64_t)row_diff * src1_ncols * ne10; 3383 const bool use_mkl_direct = gemm_flops < SYCL_F32_DNNL_MIN_GEMM_FLOPS; 3384 if (g_ggml_sycl_enable_dnn && !use_mkl_direct && ggml_sycl_dnnl_has_optimized_gemm(ggml_sycl_get_device())) { 3385 DnnlGemmWrapper::row_gemm(ctx, row_diff, src1_ncols, ne10, src0_ddf_i, 3386 DnnlGemmWrapper::to_dt(), src1_ddf1_i, DnnlGemmWrapper::to_dt(), 3387 dst_dd_i, DnnlGemmWrapper::to_dt(), stream); 3388 } 3389 else 3390 #endif 3391 { 3392 const float alpha = 1.0f; 3393 const float beta = 0.0f; 3394 SYCL_CHECK(CHECK_TRY_ERROR(oneapi::mkl::blas::column_major::gemm( 3395 *stream, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, row_diff, 3396 src1_ncols, ne10, dpct::get_value(&alpha, *stream), src0_ddf_i, ne00, src1_ddf1_i, ne10, 3397 dpct::get_value(&beta, *stream), dst_dd_i, ldc))); 3398 } 3399 } 3400 } 3401 GGML_UNUSED(dst); 3402 GGML_UNUSED(src1_ddq_i); 3403 GGML_UNUSED(src1_padded_row_size); 3404 } 3405 catch (sycl::exception const &exc) { 3406 std::cerr << exc.what() << "Exception caught at file:" << __FILE__ 3407 << ", line:" << __LINE__ << std::endl; 3408 std::exit(1); 3409 } 3410 3411 inline void ggml_sycl_op_sum(ggml_backend_sycl_context & ctx, ggml_tensor *dst) { 3412 GGML_ASSERT(dst->src[0]->type == GGML_TYPE_F32); 3413 GGML_ASSERT( dst->type == GGML_TYPE_F32); 3414 dpct::queue_ptr main_stream = ctx.stream(); 3415 SYCL_CHECK(ggml_sycl_set_device(ctx.device)); 3416 const float * src0_dd = static_cast(dst->src[0]->data); 3417 float * dst_dd = static_cast(dst->data); 3418 3419 const int64_t ne = ggml_nelements(dst->src[0]); 3420 // the kernel indexes in 32-bit 3421 GGML_ASSERT(ne <= INT32_MAX); 3422 3423 sum_rows_f32_sycl(src0_dd, dst_dd, ne, 1, main_stream); 3424 } 3425 3426 inline void ggml_sycl_op_sum_rows(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { 3427 GGML_ASSERT(dst->src[0]->type == GGML_TYPE_F32); 3428 GGML_ASSERT( dst->type == GGML_TYPE_F32); 3429 dpct::queue_ptr main_stream = ctx.stream(); 3430 SYCL_CHECK(ggml_sycl_set_device(ctx.device)); 3431 const float * src0_dd = static_cast(dst->src[0]->data); 3432 float * dst_dd = static_cast(dst->data); 3433 3434 const int64_t ncols = dst->src[0]->ne[0]; 3435 const int64_t nrows = ggml_nrows(dst->src[0]); 3436 // the kernel indexes in 32-bit 3437 GGML_ASSERT(ncols * nrows <= INT32_MAX); 3438 3439 sum_rows_f32_sycl(src0_dd, dst_dd, ncols, nrows, main_stream); 3440 } 3441 3442 inline void ggml_sycl_op_mean(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { 3443 GGML_ASSERT(dst->src[0]->type == GGML_TYPE_F32); 3444 GGML_ASSERT(dst->type == GGML_TYPE_F32); 3445 3446 dpct::queue_ptr main_stream = ctx.stream(); 3447 SYCL_CHECK(ggml_sycl_set_device(ctx.device)); 3448 3449 const float * src0_dd = static_cast(dst->src[0]->data); 3450 float * dst_dd = static_cast(dst->data); 3451 3452 const int64_t ncols = dst->src[0]->ne[0]; 3453 const int64_t nrows = ggml_nrows(dst->src[0]); 3454 // the kernel indexes in 32-bit 3455 GGML_ASSERT(ncols * nrows <= INT32_MAX); 3456 3457 sum_rows_f32_sycl(src0_dd, dst_dd, ncols, nrows, main_stream); 3458 3459 main_stream->parallel_for( 3460 sycl::range<1>(nrows), 3461 [=](sycl::id<1> row) { 3462 dst_dd[row] /= ncols; 3463 } 3464 ); 3465 } 3466 3467 3468 inline void ggml_sycl_op_argsort(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { 3469 GGML_ASSERT(dst->src[0]->type == GGML_TYPE_F32); 3470 GGML_ASSERT(dst->type == GGML_TYPE_I32); 3471 dpct::queue_ptr main_stream = ctx.stream(); 3472 SYCL_CHECK(ggml_sycl_set_device(ctx.device)); 3473 const float * src0_dd = static_cast(dst->src[0]->data); 3474 int32_t * dst_dd = static_cast(dst->data); 3475 3476 3477 const int64_t ncols = dst->src[0]->ne[0]; 3478 const int64_t nrows = ggml_nrows(dst->src[0]); 3479 3480 enum ggml_sort_order order = (enum ggml_sort_order) dst->op_params[0]; 3481 3482 argsort_f32_i32_sycl(src0_dd, (int *)dst_dd, ncols, nrows, order, 3483 main_stream, ctx.device, ctx.pool()); 3484 } 3485 3486 static void ggml_sycl_op_top_k(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { 3487 const ggml_tensor * src0 = dst->src[0]; 3488 3489 GGML_ASSERT(src0); 3490 GGML_ASSERT(src0->type == GGML_TYPE_F32); 3491 GGML_ASSERT(dst->type == GGML_TYPE_I32); 3492 GGML_ASSERT(ggml_is_contiguous(src0)); 3493 3494 dpct::queue_ptr main_stream = ctx.stream(); 3495 SYCL_CHECK(ggml_sycl_set_device(ctx.device)); 3496 3497 const float * src0_dd = static_cast(src0->data); 3498 int32_t * dst_dd = static_cast(dst->data); 3499 3500 const int k = dst->ne[0]; 3501 const int64_t ncols = src0->ne[0]; 3502 const int64_t nrows = ggml_nrows(src0); 3503 3504 GGML_ASSERT(k > 0); 3505 GGML_ASSERT(k <= ncols); 3506 3507 if (k <= SYCL_TOP_K_SCAN_MERGE_MAX_K) { 3508 top_k_f32_sycl(ctx, src0_dd, dst_dd, ncols, nrows, k, main_stream); 3509 } else { 3510 ggml_sycl_top_k_radix(ctx, src0_dd, dst_dd, ncols, nrows, k, main_stream); 3511 } 3512 } 3513 3514 inline void ggml_sycl_op_argmax(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { 3515 GGML_ASSERT(dst->src[0]->type == GGML_TYPE_F32); 3516 GGML_ASSERT( dst->type == GGML_TYPE_I32); 3517 3518 dpct::queue_ptr main_stream = ctx.stream(); 3519 SYCL_CHECK(ggml_sycl_set_device(ctx.device)); 3520 const float * src0_dd = static_cast(dst->src[0]->data); 3521 int32_t * dst_dd = static_cast(dst->data); 3522 3523 const int64_t ncols = dst->src[0]->ne[0]; 3524 const int64_t nrows = ggml_nrows(dst->src[0]); 3525 // the kernel indexes in 32-bit 3526 GGML_ASSERT(ncols * nrows <= INT32_MAX); 3527 3528 argmax_f32_i32_sycl(src0_dd, dst_dd, ncols, nrows, main_stream); 3529 } 3530 3531 inline void ggml_sycl_op_diag_mask_inf(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { 3532 GGML_ASSERT(dst->src[0]->type == GGML_TYPE_F32); 3533 GGML_ASSERT( dst->type == GGML_TYPE_F32); 3534 dpct::queue_ptr main_stream = ctx.stream(); 3535 SYCL_CHECK(ggml_sycl_set_device(ctx.device)); 3536 const float * src0_dd = static_cast(dst->src[0]->data); 3537 float * dst_dd = static_cast(dst->data); 3538 3539 const int64_t ne00 = dst->src[0]->ne[0]; 3540 const int64_t ne01 = dst->src[0]->ne[1]; 3541 const int nrows0 = ggml_nrows(dst->src[0]); 3542 // the kernel indexes in 32-bit 3543 GGML_ASSERT(ne00 * nrows0 <= INT32_MAX); 3544 3545 const int n_past = ((int32_t *) dst->op_params)[0]; 3546 3547 diag_mask_inf_f32_sycl(src0_dd, dst_dd, ne00, nrows0, ne01, n_past, main_stream); 3548 } 3549 3550 static void tri_f32_sycl( 3551 const float * src, 3552 float * dst, 3553 const int64_t ne0, 3554 const int64_t ne1, 3555 const int64_t ne2, 3556 const int64_t ne3, 3557 const ggml_tri_type ttype, 3558 dpct::queue_ptr main_stream 3559 ) { 3560 const size_t total = (size_t) ne0 * (size_t) ne1 * (size_t) ne2 * (size_t) ne3; 3561 3562 main_stream->parallel_for(sycl::range<1>(total), [=](sycl::id<1> tid) { 3563 const int64_t idx = (int64_t) tid[0]; 3564 3565 const int64_t i0 = idx % ne0; 3566 const int64_t t1 = idx / ne0; 3567 const int64_t i1 = t1 % ne1; 3568 3569 bool keep = false; 3570 switch (ttype) { 3571 case GGML_TRI_TYPE_LOWER: keep = (i0 < i1); break; 3572 case GGML_TRI_TYPE_LOWER_DIAG: keep = (i0 <= i1); break; 3573 case GGML_TRI_TYPE_UPPER: keep = (i0 > i1); break; 3574 case GGML_TRI_TYPE_UPPER_DIAG: keep = (i0 >= i1); break; 3575 default: keep = false; break; 3576 } 3577 3578 dst[idx] = keep ? src[idx] : 0.0f; 3579 }); 3580 } 3581 3582 static void ggml_sycl_op_tri(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { 3583 const ggml_tensor * src0 = dst->src[0]; 3584 GGML_ASSERT(src0); 3585 3586 GGML_ASSERT(src0->type == GGML_TYPE_F32); 3587 GGML_ASSERT(dst->type == GGML_TYPE_F32); 3588 GGML_ASSERT(ggml_is_contiguous(src0)); 3589 GGML_ASSERT(ggml_is_contiguous(dst)); 3590 GGML_ASSERT(ggml_are_same_shape(src0, dst)); 3591 3592 dpct::queue_ptr main_stream = ctx.stream(); 3593 SYCL_CHECK(ggml_sycl_set_device(ctx.device)); 3594 3595 const float * src0_dd = static_cast(src0->data); 3596 float * dst_dd = static_cast(dst->data); 3597 3598 const ggml_tri_type ttype = (ggml_tri_type) ggml_get_op_params_i32(dst, 0); 3599 3600 const int64_t ne0 = src0->ne[0]; 3601 const int64_t ne1 = src0->ne[1]; 3602 const int64_t ne2 = src0->ne[2]; 3603 const int64_t ne3 = src0->ne[3]; 3604 3605 tri_f32_sycl(src0_dd, dst_dd, ne0, ne1, ne2, ne3, ttype, main_stream); 3606 } 3607 3608 3609 inline void ggml_sycl_op_scale(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { 3610 GGML_ASSERT(dst->src[0]->type == GGML_TYPE_F32); 3611 GGML_ASSERT( dst->type == GGML_TYPE_F32); 3612 dpct::queue_ptr main_stream = ctx.stream(); 3613 SYCL_CHECK(ggml_sycl_set_device(ctx.device)); 3614 const float * src0_dd = static_cast(dst->src[0]->data); 3615 float * dst_dd = static_cast(dst->data); 3616 3617 float scale; 3618 float bias; 3619 memcpy(&scale, (float *) dst->op_params + 0, sizeof(float)); 3620 memcpy(&bias, (float *) dst->op_params + 1, sizeof(float)); 3621 3622 // the kernel indexes in 32-bit 3623 GGML_ASSERT(ggml_nelements(dst->src[0]) <= INT32_MAX); 3624 3625 scale_f32_sycl(src0_dd, dst_dd, scale, bias, ggml_nelements(dst->src[0]), main_stream); 3626 /* 3627 DPCT1010:87: SYCL uses exceptions to report errors and does not use the 3628 error codes. The call was replaced with 0. You need to rewrite this code. 3629 */ 3630 SYCL_CHECK(0); 3631 } 3632 3633 static void ggml_sycl_set_peer_access(const int n_tokens, [[maybe_unused]] int main_device) { 3634 static bool peer_access_enabled = false; 3635 3636 const bool enable_peer_access = n_tokens <= GGML_SYCL_PEER_MAX_BATCH_SIZE; 3637 3638 if (peer_access_enabled == enable_peer_access) { 3639 return; 3640 } 3641 3642 #ifdef NDEBUG 3643 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 3644 SYCL_CHECK(ggml_sycl_set_device(i)); 3645 } 3646 3647 for (int i = 0; i < ggml_sycl_info().device_count; ++i) { 3648 SYCL_CHECK(ggml_sycl_set_device(i)); 3649 3650 for (int id_other = 0; id_other < ggml_sycl_info().device_count; ++id_other) { 3651 if (i == id_other) { 3652 continue; 3653 } 3654 if (i != main_device && id_other != main_device) { 3655 continue; 3656 } 3657 3658 // int can_access_peer; 3659 // SYCL_CHECK(syclDeviceCanAccessPeer(&can_access_peer, id, id_other)); 3660 // if (can_access_peer) { 3661 // if (enable_peer_access) { 3662 // SYCL_CHECK(syclDeviceEnablePeerAccess(id_other, 0)); 3663 // } else { 3664 // SYCL_CHECK(syclDeviceDisablePeerAccess(id_other)); 3665 // } 3666 // } 3667 } 3668 } 3669 #endif // NDEBUG 3670 3671 peer_access_enabled = enable_peer_access; 3672 } 3673 3674 template