okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2de2641f
main
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 <algorithm> 14#include <array> 15#include <assert.h> 16#include <atomic> 17#include <cinttypes> 18#include <cstddef> 19#include <cstdint> 20#include <cstdlib> 21#include <float.h> 22#include <limits> 23#include <optional> 24#include <stdint.h> 25#include <stdio.h> 26#include <vector> 27#include <cmath> 28#include <iostream> 29#include <fstream> 30#include <stdio.h> 31#include <stdlib.h> 32#include <regex> 33 34#include <sycl/sycl.hpp> 35#include <sycl/backend.hpp> 36#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 37#include <level_zero/ze_api.h> 38#include <level_zero/zes_api.h> 39#endif 40#if defined(GGML_SYCL_GRAPH )&& SYCL_EXT_ONEAPI_ASYNC_MEMORY_ALLOC 41# include <sycl/ext/oneapi/experimental/async_alloc/async_alloc.hpp> 42#endif 43#if SYCL_EXT_ONEAPI_VIRTUAL_MEM 44# include <sycl/ext/oneapi/virtual_mem/physical_mem.hpp> 45# include <sycl/ext/oneapi/virtual_mem/virtual_mem.hpp> 46# define GGML_SYCL_SUPPORT_VMM 47#endif 48#if defined(__INTEL_LLVM_COMPILER ) 49#define GGML_SYCL_DMMV_HAS_ESIMD 50#endif 51#include <sycl/half_type.hpp> 52 53#include "ggml.h" 54#include "ggml-sycl.h" 55#include "ggml-impl.h" 56#include "ggml-backend-impl.h" 57 58#include "ggml-sycl/add-id.hpp" 59#include "ggml-sycl/backend.hpp" 60#include "ggml-sycl/common.hpp" 61#include "ggml-sycl/element_wise.hpp" 62#include "ggml-sycl/fwht.hpp" 63#include "ggml-sycl/gemm.hpp" 64#include "ggml-sycl/getrows.hpp" 65#include "ggml-sycl/mem.hpp" 66#include "ggml-sycl/norm.hpp" 67#include "ggml-sycl/presets.hpp" 68#include "ggml-sycl/quantize.hpp" 69#include "ggml-sycl/repeat_back.hpp" 70#include "ggml-sycl/set_rows.hpp" 71#include "ggml-sycl/set.hpp" 72#include "ggml-sycl/dsv4-hc.hpp" 73#include "ggml-sycl/lightning-indexer.hpp" 74#include "ggml-sycl/conv2d.hpp" 75#include "ggml-sycl/conv2d-dw.hpp" 76#include "ggml-sycl/conv2d-transpose.hpp" 77#include "ggml-sycl/ssm_conv.hpp" 78#include "ggml-sycl/sycl_hw.hpp" 79#include "ggml-sycl/ssm_scan.hpp" 80#include "ggml-sycl/fill.hpp" 81#include "ggml-sycl/cumsum.hpp" 82#include "ggml-sycl/diag.hpp" 83#include "ggml-sycl/opt-step.hpp" 84#include "ggml-sycl/solve_tri.hpp" 85#include "ggml-sycl/gated_delta_net.hpp" 86#include "ggml-sycl/pool.hpp" 87#include "ggml-sycl/cross_entropy_loss.hpp" 88 89#define MEM_SIZE_2M 0x00200000 90#define MEM_SIZE_1G 0x40000000 91 92static bool g_sycl_loaded = false; 93int g_ggml_sycl_debug = 0 ; 94int g_ggml_sycl_dev_debug = 0 ; 95int g_ggml_sycl_enable_optimize = 1 ; 96int g_ggml_sycl_enable_graph = 0 ; 97int g_ggml_sycl_enable_dnn = 1 ; 98int g_ggml_sycl_fa_onednn = 1 ; 99int g_ggml_sycl_fa_onednn_max_kv = 0 ; 100int g_ggml_sycl_enable_mkl_fa = 1 ; 101int g_ggml_sycl_memtrace = 0 ; 102int g_ggml_sycl_memtrace_step = 64 ; 103int g_ggml_sycl_enable_vmm = 1 ; 104int g_ggml_sycl_enable_fusion = 1 ; 105int g_ggml_sycl_enable_esimd = 1 ; 106int g_ggml_sycl_prioritize_dmmv = 0 ; 107int g_ggml_sycl_use_async_mem_op = 0 ; 108int g_ggml_sycl_use_async_mem_op_requested = 1 ; 109int g_ggml_sycl_use_level_zero_api = 0 ; 110int g_ggml_sycl_enable_flash_attention = 1 ; 111int g_ggml_sycl_dev2dev_memcpy = DEV2DEV_MEMCPY_SYCL ; 112int g_ggml_sycl_usm_system = 0 ; 113int g_ggml_sycl_enable_host_pinned_mem = 1 ; 114int g_ggml_sycl_host_pinned_mem_2g = 0 ; 115int g_ggml_sycl_get_mem_api = MEMORY_API_TYPE_LEVEL_ZERO ; 116 117static ggml_sycl_device_info ggml_sycl_init () { 118GGML_SYCL_DEBUG ("[SYCL] call ggml_sycl_init\n" ); 119ggml_sycl_device_info info = {}; 120 121// Do not hard crash when there exists no SYCL devices. 122// We want to allow the user to use non-SYCL tools when SYCL is compiled (such as llama-quantize) 123try { 124info .device_count = dpct::dev_mgr::instance ().device_count (); 125 }catch (sycl::exception const & exc ) { 126GGML_LOG_INFO ("%s: no SYCL device available: %s\n" ,__func__ ,exc .what ()); 127info .device_count = 0 ; 128 } 129if (info .device_count == 0 ) { 130GGML_LOG_ERROR ("%s: failed to initialize: %s\n" ,GGML_SYCL_NAME ,__func__ ); 131return info ; 132 } 133 134GGML_ASSERT (info .device_count <=GGML_SYCL_MAX_DEVICES ); 135 136int64_t total_vram = 0 ; 137/* This is a bit misleading; reserved for later */ 138// #if defined(SYCL_USE_XMX) 139// GGML_LOG_INFO("%s: SYCL_USE_XMX: yes\n", __func__); 140// #else 141// GGML_LOG_INFO("%s: SYCL_USE_XMX: no\n", __func__); 142// #endif 143for (int i = 0 ;i < info .device_count ;++ i ) { 144 dpct::device_info prop ; 145auto & device = dpct::dev_mgr::instance ().get_device (i ); 146 147SYCL_CHECK (CHECK_TRY_ERROR (dpct::get_device_info ( 148prop ,device ))); 149 150#if !defined(GGML_SYCL_SUPPORT_VMM ) 151info .devices [i ].vmm = 0 ; 152#else 153info .devices [i ].vmm = device .has (sycl::aspect::ext_oneapi_virtual_mem ); 154if (info .devices [i ].vmm ) { 155// NB: SYCL's get_mem_granularity always returns the _minimum_ granularity, 156// but the L0 API requires a larger page size for allocs above 2 MiB and 157// rejects non-multiples with UR_RESULT_ERROR_INVALID_VALUE [sic]. 158// Here we clamp it to 2 MiB for simplicity, but other devices may require 159// calling zeVirtualMemQueryPageSize or yet unexposed public API. 160const size_t physical_page = 2ull <<20 ;// 2 MiB 161info .devices [i ].vmm_granularity = std::max < size_t > ( 162 sycl::ext::oneapi::experimental::get_mem_granularity ( 163device , sycl::context (device )), 164physical_page ); 165 } 166#endif 167 168info .default_tensor_split [i ]= total_vram ; 169total_vram += prop .get_global_mem_size (); 170 171info .devices [i ].cc = 172100 * prop .get_major_version ()+ 10 * prop .get_minor_version (); 173info .devices [i ].nsm = prop .get_max_compute_units () /16 ;//16: Number of Xe Cores 174info .devices [i ].opt_feature .reorder = device .ext_oneapi_architecture_is (syclex::arch_category::intel_gpu ); 175info .devices [i ].smpbo = prop .get_local_mem_size (); 176info .devices [i ].warp_size = WARP_SIZE ; 177info .devices [i ].usm_system_support = device .has (sycl::aspect::usm_system_allocations ); 178 179info .max_work_group_sizes [i ]= prop .get_max_work_group_size (); 180info .devices [i ].max_wg_per_cu = info .max_work_group_sizes [i ] /prop .get_max_compute_units (); 181info .devices [i ].hw_info = get_device_hw_info (& device ); 182 183// Only check GPU devices; CPU devices use OpenCL and would otherwise 184// disable Level Zero for the GPUs on systems without ONEAPI_DEVICE_SELECTOR set. 185if (device .is_gpu ()&& device .default_queue ().get_backend ()!= sycl::backend::ext_oneapi_level_zero ) { 186GGML_LOG_WARN ("SYCL GPU device %d does not use Level Zero backend, disabling Level Zero memory API\n" ,i ); 187info .ext_oneapi_level_zero = false; 188 } 189 190#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 191if (info .ext_oneapi_level_zero && device .is_gpu ()&& device .default_queue ().get_backend ()== sycl::backend::ext_oneapi_level_zero ) { 192ze_device_handle_t ze_dev = sycl::get_native < sycl::backend::ext_oneapi_level_zero > (device .default_queue ().get_device ()); 193ze_device_properties_t props = {}; 194props .stype = ZE_STRUCTURE_TYPE_DEVICE_PROPERTIES ; 195ze_result_t r = zeDeviceGetProperties (ze_dev ,& props ); 196if (r == ZE_RESULT_SUCCESS ) { 197info .devices [i ].l0_device_type_valid = true; 198info .devices [i ].l0_discrete_gpu = !(props .flags & ZE_DEVICE_PROPERTY_FLAG_INTEGRATED ); 199 } 200 } 201#endif 202 } 203 204for (int id = 0 ;id < info .device_count ;++ id ) { 205info .default_tensor_split [id ] /=total_vram ; 206 } 207 208#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 209//update g_ggml_sycl_use_level_zero_api according to the device support 210g_ggml_sycl_use_level_zero_api = 211info .ext_oneapi_level_zero && g_ggml_sycl_use_level_zero_api ; 212#endif 213 214return info ; 215} 216 217const ggml_sycl_device_info & ggml_sycl_info () { 218static ggml_sycl_device_info info = ggml_sycl_init (); 219return info ; 220} 221 222static void print_device_detail (int id , sycl::device & device , std::string device_type ) { 223 224 dpct::device_info prop ; 225SYCL_CHECK (CHECK_TRY_ERROR ( 226 dpct::get_device_info (prop ,device ))); 227 228 std::string version ; 229version += std::to_string (prop .get_major_version ()); 230version += "." ; 231version += std::to_string (prop .get_minor_version ()); 232 233device_type = std::regex_replace (device_type , std::regex ("ext_oneapi_" ),"" ); 234 std::string name = std::string (prop .get_name ()); 235name = std::regex_replace (name , std::regex ("\\(R\\)" ),"" ); 236name = std::regex_replace (name , std::regex ("\\(TM\\)" ),"" ); 237 238auto global_mem_size = prop .get_global_mem_size ()/1000000 ; 239GGML_LOG_INFO ("|%2d|%19s|%39s|%7s|%7d|%8d|%5d|%6luM|%21s|\n" ,id ,device_type .c_str (), 240name .c_str (),version .c_str (),prop .get_max_compute_units (), 241prop .get_max_work_group_size (),prop .get_max_sub_group_size (), 242global_mem_size ,device .get_info < sycl::info::device::driver_version > ().c_str ()); 243} 244 245static void print_device_opt_feature (int device_count ) { 246GGML_LOG_INFO ("SYCL Optimization Feature:\n" ); 247GGML_LOG_INFO ( 248"|ID| Device Type|Reorder|\n" ); 249GGML_LOG_INFO ( 250"|--|-------------------|-------|\n" ); 251 std::map < std::string ,size_t > DeviceNums ; 252for (int id = 0 ;id < device_count ;++ id ) { 253 sycl::device device = dpct::dev_mgr::instance ().get_device (id ); 254 std::string backend_type = get_device_backend_and_type (device ); 255int type_id = DeviceNums [backend_type ]++ ; 256 std::stringstream device_type ; 257device_type <<"[" <<backend_type <<":" << std::to_string (type_id ) 258 <<"]" ; 259 std::string device_type_s = device_type .str (); 260device_type_s = std::regex_replace (device_type_s , std::regex ("ext_oneapi_" ),"" ); 261GGML_LOG_INFO ("|%2d|%19s|%7s|\n" ,id ,device_type_s .c_str (), 262ggml_sycl_info ().devices [id ].opt_feature .reorder ?"Y" :"N" ); 263 } 264 265} 266void ggml_backend_sycl_print_sycl_devices () { 267GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_print_sycl_devices\n" ); 268int device_count = dpct::dev_mgr::instance ().device_count (); 269 std::map < std::string ,size_t > DeviceNums ; 270GGML_LOG_INFO ("Found %d SYCL devices:\n" ,device_count ); 271 272GGML_LOG_INFO ( 273"| | | | " 274" |Max | |Max |Global | |\n" ); 275GGML_LOG_INFO ( 276"| | | | " 277" |compute|Max work|sub |mem | |\n" ); 278GGML_LOG_INFO ( 279"|ID| Device Type| " 280"Name|Version|units |group |group|size | Driver version|\n" ); 281GGML_LOG_INFO ( 282"|--|-------------------|---------------------------------------|------" 283"-|-------|--------|-----|-------|---------------------|\n" ); 284 285for (int id = 0 ;id < device_count ;++ id ) { 286 sycl::device device = dpct::dev_mgr::instance ().get_device (id ); 287 std::string backend_type = get_device_backend_and_type (device ); 288int type_id = DeviceNums [backend_type ]++ ; 289 std::stringstream device_type ; 290device_type <<"[" <<backend_type <<":" << std::to_string (type_id ) 291 <<"]" ; 292print_device_detail (id ,device ,device_type .str ()); 293 } 294 295print_device_opt_feature (device_count ); 296} 297 298static const char * dev2dev_int2str (int dev2dev ) { 299if (dev2dev == DEV2DEV_MEMCPY_SYCL ) { 300return "SYCL API" ; 301 }else if (dev2dev == DEV2DEV_MEMCPY_L0 ) { 302return "Level Zero API" ; 303 }else if (dev2dev == DEV2DEV_MEMCPY_FORWARD ) { 304return "Host Forward" ; 305 }else { 306return "Unknown" ; 307 } 308} 309 310/* 311* There are several entry APIs to be called as first function in SYCL backend in different cases. 312* It's the first internal function to be called by them in SYCL backend. 313* This function is used to do initialize work for the SYCL backend and set the global variables. 314*/ 315#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 316static ze_result_t init_zes () { 317ze_result_t res = zesInit (0 ); 318if (res != ZE_RESULT_SUCCESS ) { 319GGML_SYCL_DEBUG ("Warning: [%s] zesInit failed with code %d. Sysman free-memory query be unavailable.\n" , 320__func__ , (int )res ); 321 } 322return res ; 323} 324 325ze_result_t get_zes_init_res () { 326static ze_result_t zes_init_res = init_zes (); 327GGML_SYCL_DEBUG ("[SYCL] call %s: zesInit result: %d\n" ,__func__ , (int )zes_init_res ); 328return zes_init_res ; 329} 330#endif 331 332void initialize_sycl_begining () { 333#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 334//must be called in initialization stage, before any other Level Zero API calls 335GGML_SYCL_DEBUG ("[SYCL] call %s\n" ,__func__ ); 336get_zes_init_res (); 337#endif 338} 339 340static void ggml_check_sycl ()try { 341GGML_SYCL_DEBUG ("[SYCL] ggml_check_sycl()\n" ); 342static bool initialized = false; 343 344if (!initialized ) { 345initialize_sycl_begining (); 346 347g_ggml_sycl_debug = ggml_sycl_get_env ("GGML_SYCL_DEBUG" ,0 ); 348g_ggml_sycl_dev_debug = ggml_sycl_get_env ("GGML_SYCL_DEV_DEBUG" ,0 ); 349g_ggml_sycl_enable_optimize = ggml_sycl_get_env ("GGML_SYCL_ENABLE_OPT" ,1 ); 350g_ggml_sycl_enable_graph = ggml_sycl_get_env ("GGML_SYCL_ENABLE_GRAPH" ,0 ); 351g_ggml_sycl_enable_dnn = ggml_sycl_get_env ("GGML_SYCL_ENABLE_DNN" ,1 ); 352g_ggml_sycl_fa_onednn = ggml_sycl_get_env ("GGML_SYCL_FA_ONEDNN" ,1 ); 353g_ggml_sycl_fa_onednn_max_kv = ggml_sycl_get_env ("GGML_SYCL_FA_ONEDNN_MAX_KV" ,0 ); 354g_ggml_sycl_enable_mkl_fa = ggml_sycl_get_env ("GGML_SYCL_ENABLE_MKL_FA" ,1 ); 355g_ggml_sycl_memtrace = ggml_sycl_get_env ("GGML_SYCL_MEMTRACE" ,0 ); 356g_ggml_sycl_memtrace_step = ggml_sycl_get_env ("GGML_SYCL_MEMTRACE_STEP" ,64 ); 357g_ggml_sycl_enable_vmm = ggml_sycl_get_env ("GGML_SYCL_ENABLE_VMM" ,1 ); 358g_ggml_sycl_enable_fusion = ggml_sycl_get_env ("GGML_SYCL_ENABLE_FUSION" ,1 ); 359g_ggml_sycl_enable_esimd = ggml_sycl_get_env ("GGML_SYCL_ENABLE_ESIMD" ,1 ); 360g_ggml_sycl_prioritize_dmmv = ggml_sycl_get_env ("GGML_SYCL_PRIORITIZE_DMMV" ,0 ); 361 362#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 363g_ggml_sycl_use_level_zero_api = ggml_sycl_get_env ("GGML_SYCL_USE_LEVEL_ZERO_API" ,1 ); 364#else 365g_ggml_sycl_use_level_zero_api = 0 ; 366#endif 367g_ggml_sycl_dev2dev_memcpy = ggml_sycl_get_env ("GGML_SYCL_DEV2DEV_MEMCPY" ,DEV2DEV_MEMCPY_SYCL ); 368g_ggml_sycl_get_mem_api = ggml_sycl_get_env ("GGML_SYCL_GET_MEM_API" ,MEMORY_API_TYPE_LEVEL_ZERO ); 369if (g_ggml_sycl_use_level_zero_api == 0 ) { 370g_ggml_sycl_dev2dev_memcpy = DEV2DEV_MEMCPY_SYCL ; 371g_ggml_sycl_get_mem_api = MEMORY_API_TYPE_SYCL ; 372 } 373 374#ifdef SYCL_FLASH_ATTN 375g_ggml_sycl_enable_flash_attention = ggml_sycl_get_env ("GGML_SYCL_ENABLE_FLASH_ATTN" ,1 ); 376#else 377g_ggml_sycl_enable_flash_attention = 0 ; 378#endif 379 380g_ggml_sycl_usm_system = ggml_sycl_get_env ("GGML_SYCL_USM_SYSTEM" ,0 ); 381g_ggml_sycl_enable_host_pinned_mem = 382ggml_sycl_get_env ("GGML_SYCL_ENABLE_HOST_PINNED_MEM" ,1 ); 383 384g_ggml_sycl_host_pinned_mem_2g = 385ggml_sycl_get_env ("GGML_SYCL_HOST_PINNED_MEM_2G" ,0 )& g_ggml_sycl_enable_host_pinned_mem ; 386 387GGML_SYCL_DEBUG ("[SYCL] call ggml_check_sycl\n" ); 388 389GGML_LOG_INFO ("Build with Macros:\n" ); 390#if defined(GGML_SYCL_DNNL ) 391GGML_LOG_INFO (" GGML_SYCL_DNNL: yes\n" ); 392#else 393GGML_LOG_INFO (" GGML_SYCL_DNNL: no\n" ); 394#endif 395 396#if defined(GGML_SYCL_F16 ) 397GGML_LOG_INFO (" GGML_SYCL_F16: yes\n" ); 398#else 399GGML_LOG_INFO (" GGML_SYCL_F16: no\n" ); 400#endif 401 402#if defined(GGML_SYCL_FORCE_MMQ ) 403GGML_LOG_INFO (" GGML_SYCL_FORCE_MMQ: yes\n" ); 404#else 405GGML_LOG_INFO (" GGML_SYCL_FORCE_MMQ: no\n" ); 406#endif 407 408#if defined(GGML_SYCL_GRAPH ) 409GGML_LOG_INFO (" GGML_SYCL_GRAPH: yes\n" ); 410#else 411GGML_LOG_INFO (" GGML_SYCL_GRAPH: no\n" ); 412#endif 413 414#if defined(GGML_SYCL_SUPPORT_LEVEL_ZERO_API ) 415GGML_LOG_INFO (" GGML_SYCL_SUPPORT_LEVEL_ZERO_API: yes\n" ); 416#else 417GGML_LOG_INFO (" GGML_SYCL_SUPPORT_LEVEL_ZERO_API: no\n" ); 418#endif 419#if defined(GGML_SYCL_SUPPORT_VMM ) 420GGML_LOG_INFO (" GGML_SYCL_SUPPORT_VMM: yes\n" ); 421#else 422GGML_LOG_INFO (" GGML_SYCL_SUPPORT_VMM: no\n" ); 423#endif 424 425GGML_LOG_INFO ("Running with Environment Variables:\n" ); 426GGML_LOG_INFO (" GGML_SYCL_DEBUG: %d\n" ,g_ggml_sycl_debug ); 427GGML_LOG_INFO (" GGML_SYCL_DEV_DEBUG: %d\n" ,g_ggml_sycl_dev_debug ); 428 429#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 430GGML_LOG_INFO (" GGML_SYCL_DEV2DEV_MEMCPY: %d (%s)\n" ,g_ggml_sycl_dev2dev_memcpy ,dev2dev_int2str (g_ggml_sycl_dev2dev_memcpy )); 431GGML_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 )); 432#else 433GGML_LOG_INFO (" GGML_SYCL_DEV2DEV_MEMCPY: %d (%s), enable to SYCL API since missing GGML_SYCL_SUPPORT_LEVEL_ZERO_API\n" , 434g_ggml_sycl_dev2dev_memcpy ,dev2dev_int2str (g_ggml_sycl_dev2dev_memcpy )); 435GGML_LOG_INFO (" GGML_SYCL_GET_MEM_API: %d (%s), enable to SYCL API since missing GGML_SYCL_SUPPORT_LEVEL_ZERO_API\n" , 436g_ggml_sycl_get_mem_api ,mem_api_int2str (g_ggml_sycl_get_mem_api )); 437#endif 438 439#if defined(GGML_SYCL_DNNL ) 440GGML_LOG_INFO (" GGML_SYCL_ENABLE_DNN: %d\n" ,g_ggml_sycl_enable_dnn ); 441GGML_LOG_INFO (" GGML_SYCL_FA_ONEDNN: %d\n" ,g_ggml_sycl_fa_onednn ); 442#else 443GGML_LOG_INFO (" GGML_SYCL_ENABLE_DNN: DNN disabled by compile flag\n" ); 444GGML_LOG_INFO (" GGML_SYCL_FA_ONEDNN: %d\n" ,g_ggml_sycl_fa_onednn ); 445#endif 446GGML_LOG_INFO (" GGML_SYCL_FA_ONEDNN_MAX_KV: %d\n" ,g_ggml_sycl_fa_onednn_max_kv ); 447GGML_LOG_INFO (" GGML_SYCL_ENABLE_MKL_FA: %d\n" ,g_ggml_sycl_enable_mkl_fa ); 448GGML_LOG_INFO (" GGML_SYCL_MEMTRACE: %d\n" ,g_ggml_sycl_memtrace ); 449GGML_LOG_INFO (" GGML_SYCL_MEMTRACE_STEP: %d\n" ,g_ggml_sycl_memtrace_step ); 450#ifdef SYCL_FLASH_ATTN 451GGML_LOG_INFO (" GGML_SYCL_ENABLE_FLASH_ATTN: %d\n" ,g_ggml_sycl_enable_flash_attention ); 452#else 453GGML_LOG_INFO (" GGML_SYCL_ENABLE_FLASH_ATTN: %d disabled by compile flag\n" , 454g_ggml_sycl_enable_flash_attention ); 455#endif 456 457#ifdef GGML_SYCL_GRAPH 458GGML_LOG_INFO (" GGML_SYCL_ENABLE_GRAPH: %d\n" ,g_ggml_sycl_enable_graph ); 459#else 460GGML_LOG_INFO (" GGML_SYCL_ENABLE_GRAPH: graph disabled by compile flag\n" ); 461#endif 462 463GGML_LOG_INFO (" GGML_SYCL_ENABLE_OPT: %d\n" ,g_ggml_sycl_enable_optimize ); 464 465#if defined(GGML_SYCL_SUPPORT_VMM ) 466GGML_LOG_INFO (" GGML_SYCL_ENABLE_VMM: %d\n" ,g_ggml_sycl_enable_vmm ); 467#else 468GGML_LOG_INFO (" GGML_SYCL_ENABLE_VMM: virtual memory extension is not available\n" ); 469#endif 470 471GGML_LOG_INFO (" GGML_SYCL_ENABLE_FUSION: %d\n" ,g_ggml_sycl_enable_fusion ); 472 473#if defined(__INTEL_LLVM_COMPILER ) 474GGML_LOG_INFO (" GGML_SYCL_ENABLE_ESIMD: %d\n" ,g_ggml_sycl_enable_esimd ); 475#else 476GGML_LOG_INFO (" GGML_SYCL_ENABLE_ESIMD: %d disabled by compile flag\n" ,g_ggml_sycl_enable_esimd ); 477#endif 478 479GGML_LOG_INFO (" GGML_SYCL_PRIORITIZE_DMMV: %d\n" ,g_ggml_sycl_prioritize_dmmv ); 480 481g_ggml_sycl_use_async_mem_op_requested = ggml_sycl_get_env ("GGML_SYCL_USE_ASYNC_MEM_OP" ,1 ); 482GGML_LOG_INFO (" GGML_SYCL_USE_ASYNC_MEM_OP: %d\n" ,g_ggml_sycl_use_async_mem_op_requested ); 483 484#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 485GGML_LOG_INFO (" GGML_SYCL_USE_LEVEL_ZERO_API: %d\n" ,g_ggml_sycl_use_level_zero_api ); 486#else 487GGML_LOG_INFO (" GGML_SYCL_USE_LEVEL_ZERO_API: Disable Level Zero API usage by compile flag\n" ); 488#endif 489 490GGML_LOG_INFO (" GGML_SYCL_USM_SYSTEM: %d\n" ,g_ggml_sycl_usm_system ); 491GGML_LOG_INFO (" GGML_SYCL_ENABLE_HOST_PINNED_MEM: %d\n" ,g_ggml_sycl_enable_host_pinned_mem ); 492GGML_LOG_INFO (" GGML_SYCL_HOST_PINNED_MEM_2G: %d\n" ,g_ggml_sycl_host_pinned_mem_2g ); 493 494/* NOT REMOVE, keep it for next optimize for XMX. 495#if defined(SYCL_USE_XMX) 496fprintf(stderr, "%s: SYCL_USE_XMX: yes\n", __func__); 497#else 498fprintf(stderr, "%s: SYCL_USE_XMX: no\n", __func__); 499#endif 500*/ 501// Async USM allocation/free is also useful outside the graph path: it avoids the host waits in the reorder 502// staging path while preserving queue ordering semantics. Graph support still depends on the extension being 503// available, but it no longer needs to control the non-graph fast path. 504#if defined(GGML_SYCL_GRAPH )&& SYCL_EXT_ONEAPI_ASYNC_MEMORY_ALLOC 505g_ggml_sycl_use_async_mem_op = g_ggml_sycl_use_async_mem_op_requested || g_ggml_sycl_enable_graph ; 506if (g_ggml_sycl_use_async_mem_op ) { 507for (unsigned int i = 0 ;i < dpct::dev_mgr::instance ().device_count ();++ i ) { 508if (!dpct::dev_mgr::instance ().get_device (i ).has (sycl::aspect::ext_oneapi_async_memory_alloc )) { 509g_ggml_sycl_use_async_mem_op = 0 ; 510break ; 511 } 512 } 513 } 514#endif 515if (CHECK_TRY_ERROR (g_all_sycl_device_count = 516 dpct::dev_mgr::instance ().device_count ())!= 0 ) { 517initialized = true; 518g_sycl_loaded = false; 519return ; 520 } 521GGML_ASSERT (g_all_sycl_device_count <=GGML_SYCL_MAX_DEVICES ); 522 523initialized = true; 524g_sycl_loaded = true; 525ggml_backend_sycl_print_sycl_devices (); 526 } 527} 528catch (sycl::exception const & exc ) { 529 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 530 <<", line:" <<__LINE__ << std::endl ; 531 std::exit (1 ); 532} 533 534/* 535device_index: device index from 0 to n (continue numbers). 536It is used for device select/set in SYCL backend internal data structure. 537*/ 538inline void check_allow_gpu_index (const int device_index ) { 539if (device_index >=ggml_sycl_info ().device_count ) { 540char error_buf [256 ]; 541snprintf ( 542error_buf , 543sizeof (error_buf ), 544"%s error: device_index:%d is out of range: [0-%d]" , 545__func__ , 546device_index , 547ggml_sycl_info ().device_count - 1 ); 548GGML_LOG_ERROR ("%s\n" ,error_buf ); 549assert (false); 550 } 551} 552 553GGML_API void ggml_backend_sycl_get_gpu_list (int * id_list ,int max_len )try { 554GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_get_gpu_list\n" ); 555for (int i = 0 ;i < max_len ;i ++ )id_list [i ]= -1 ; 556 557for (int i = 0 ;i < ggml_sycl_info ().device_count ;i ++ ){ 558if (i >=max_len )break ; 559id_list [i ]= i ; 560 } 561return ; 562} 563catch (sycl::exception const & exc ) { 564 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 565 <<", line:" <<__LINE__ << std::endl ; 566 std::exit (1 ); 567} 568 569inline void free_aligned_mem_host (void * memblock ) { 570#ifdef _WIN32 571_aligned_free (memblock ); 572#else 573free (memblock ); 574#endif 575} 576 577// sycl buffer 578 579struct ggml_backend_sycl_buffer_context { 580int device ; 581void * dev_ptr = nullptr ; 582queue_ptr stream ; 583 std::string name ; 584optimize_feature opt_feature ; 585 std::vector < ggml_tensor_extra_gpu *> tensor_extras ; 586bool is_usm_system ; 587 588ggml_backend_sycl_buffer_context (int device ,void * dev_ptr ,queue_ptr stream ,bool is_usm_system ) : 589device (device ),dev_ptr (dev_ptr ),stream (stream ),is_usm_system (is_usm_system ) { 590check_allow_gpu_index (device ); 591name = (GGML_SYCL_NAME + std::to_string (device )); 592opt_feature = ggml_sycl_info ().devices [device ].opt_feature ; 593 } 594 595 ~ggml_backend_sycl_buffer_context () { 596if (dev_ptr != nullptr ) { 597ggml_sycl_set_device (device ); 598if (is_usm_system ) 599free_aligned_mem_host (dev_ptr ); 600else 601SYCL_CHECK (CHECK_TRY_ERROR (ggml_sycl_free_device (dev_ptr ,* stream ))); 602 } 603 604//release extra used by tensors 605for (ggml_tensor_extra_gpu * extra :tensor_extras ) { 606release_extra_gpu (extra ); 607 } 608 609 } 610}; 611 612static const char * ggml_backend_sycl_buffer_type_get_name (ggml_backend_buffer_type_t buft ); 613 614static bool ggml_backend_buffer_is_sycl (ggml_backend_buffer_t buffer ) { 615return buffer -> buft -> iface .get_name == ggml_backend_sycl_buffer_type_get_name ; 616} 617 618static void 619ggml_backend_sycl_buffer_free_buffer (ggml_backend_buffer_t buffer )try { 620ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context * )buffer -> context ; 621ggml_sycl_set_device (ctx -> device ); 622 623delete ctx ; 624} 625catch (sycl::exception const & exc ) { 626 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 627 <<", line:" <<__LINE__ << std::endl ; 628 std::exit (1 ); 629} 630 631static void * ggml_backend_sycl_buffer_get_base (ggml_backend_buffer_t buffer ) { 632ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context * )buffer -> context ; 633return ctx -> dev_ptr ; 634} 635 636static enum ggml_status 637ggml_backend_sycl_buffer_init_tensor (ggml_backend_buffer_t buffer , 638ggml_tensor * tensor )try { 639GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 640GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": tensor" ,tensor ,"\n" ).c_str ()); 641ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context * )buffer -> context ; 642 643if (tensor -> view_src != NULL ) { 644assert (tensor -> view_src -> buffer -> buft == buffer -> buft ); 645return GGML_STATUS_SUCCESS ; 646 } 647 648if (g_ggml_sycl_enable_optimize ) { 649// set reorder extra buffer based on supported type 650switch (tensor -> type ) { 651case GGML_TYPE_Q4_0 : 652case GGML_TYPE_Q8_0 : 653case GGML_TYPE_Q2_K : 654case GGML_TYPE_Q3_K : 655case GGML_TYPE_Q4_K : 656case GGML_TYPE_Q5_K : 657case GGML_TYPE_Q6_K :{ 658ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu {}; 659tensor -> extra = extra ; 660ctx -> tensor_extras .push_back (extra ); 661break ; 662 } 663default : 664break ; 665 } 666 } 667 668if (ggml_is_quantized (tensor -> type )) { 669// initialize padding to 0 to avoid possible NaN values 670size_t original_size = ggml_nbytes (tensor ); 671size_t padded_size = ggml_backend_buft_get_alloc_size (buffer -> buft ,tensor ); 672 673if (padded_size > original_size && tensor -> view_src == nullptr ) { 674SYCL_CHECK (CHECK_TRY_ERROR (ctx -> stream -> memset ( 675 (char * )tensor -> data + original_size ,0 , 676padded_size - original_size ).wait ())); 677 } 678 } 679return GGML_STATUS_SUCCESS ; 680} 681catch (sycl::exception const & exc ) { 682 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 683 <<", line:" <<__LINE__ << std::endl ; 684 std::exit (1 ); 685} 686 687static void ggml_backend_sycl_buffer_set_tensor (ggml_backend_buffer_t buffer , 688ggml_tensor * tensor , 689const void * data ,size_t offset , 690size_t size )try { 691GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 692GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": tensor" ,tensor ).c_str ()); 693GGML_SYCL_DEBUG (" size=%zu offset=%zu\n" ,size ,offset ); 694ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context * )buffer -> context ; 695ggml_sycl_set_device (ctx -> device ); 696auto stream = & (dpct::dev_mgr::instance ().get_device (ctx -> device ).default_queue ()); 697SYCL_CHECK (CHECK_TRY_ERROR (dpct::dev_mgr::instance ().get_device (ctx -> device ).queues_wait_and_throw ())); 698#ifndef _WIN32 699// Note: Use host buffer to save the data from mmap(), then copy to device. It's workaround for mmap() issue on PVC GPU. 700// 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. 701char * host_buf = (char * )malloc (size ); 702memcpy (host_buf ,data ,size ); 703SYCL_CHECK (CHECK_TRY_ERROR ((* stream ).memcpy ((char * )tensor -> data + offset ,host_buf ,size ).wait ())); 704free (host_buf ); 705#else 706SYCL_CHECK (CHECK_TRY_ERROR ((* stream ).memcpy ((char * )tensor -> data + offset ,data ,size ).wait ())); 707#endif 708} 709catch (sycl::exception const & exc ) { 710 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 711 <<", line:" <<__LINE__ << std::endl ; 712 std::exit (1 ); 713} 714 715static void ggml_backend_sycl_buffer_get_tensor (ggml_backend_buffer_t buffer , 716const ggml_tensor * tensor , 717void * data ,size_t offset , 718size_t size )try { 719GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 720GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": tensor" ,tensor ).c_str ()); 721GGML_SYCL_DEBUG (" size=%zu offset=%zu\n" ,size ,offset ); 722ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context * )buffer -> context ; 723 724ggml_sycl_set_device (ctx -> device ); 725auto stream = dpct::dev_mgr::instance ().get_device (ctx -> device ).default_queue (); 726 727SYCL_CHECK (CHECK_TRY_ERROR ( 728stream .memcpy (data , (const char * )tensor -> data + offset ,size ) 729 .wait ())); 730} 731catch (sycl::exception const & exc ) { 732 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 733 <<", line:" <<__LINE__ << std::endl ; 734 std::exit (1 ); 735} 736 737#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 738static bool ggml_sycl_is_l0_discrete_gpu (int device ) { 739return ggml_sycl_info ().devices [device ].l0_discrete_gpu ; 740} 741#endif 742 743static void dev2dev_memcpy (int device_dst , sycl::queue & q_dst ,int device_src , sycl::queue & q_src ,void * ptr_dst , 744const void * ptr_src ,size_t size ) { 745 746#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 747if (g_ggml_sycl_dev2dev_memcpy == DEV2DEV_MEMCPY_L0 ) { 748// Use Level Zero direct copy for dGPU-to-dGPU transfers. 749const bool l0_copy_supported = 750ggml_sycl_is_l0_discrete_gpu (device_dst )&& ggml_sycl_is_l0_discrete_gpu (device_src ); 751if (g_ggml_sycl_use_level_zero_api && l0_copy_supported ) { 752auto ze_ctx = sycl::get_native < sycl::backend::ext_oneapi_level_zero > (q_dst .get_context ()); 753auto ze_dev = sycl::get_native < sycl::backend::ext_oneapi_level_zero > (q_dst .get_device ()); 754ze_command_queue_desc_t cq_desc = {ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC ,nullptr ,0 ,0 , 7550 ,ZE_COMMAND_QUEUE_MODE_SYNCHRONOUS ,ZE_COMMAND_QUEUE_PRIORITY_NORMAL }; 756ze_command_list_handle_t cl ; 757ze_result_t r = zeCommandListCreateImmediate (ze_ctx ,ze_dev ,& cq_desc ,& cl ); 758if (r == ZE_RESULT_SUCCESS ) { 759GGML_SYCL_DEBUG ("[SYCL] dev2dev memcpy by L0\n" ); 760r = zeCommandListAppendMemoryCopy (cl ,ptr_dst ,ptr_src ,size ,nullptr ,0 ,nullptr ); 761zeCommandListDestroy (cl ); 762if (r == ZE_RESULT_SUCCESS ) { 763return ; 764 } 765 } 766 } 767 } 768#endif 769 770if (g_ggml_sycl_dev2dev_memcpy == DEV2DEV_MEMCPY_SYCL ) { 771if (q_dst .get_device ().ext_oneapi_can_access_peer (q_src .get_device (), 772 sycl::ext::oneapi::peer_access::access_supported )) { 773GGML_SYCL_DEBUG ("[SYCL] dev2dev memcpy by SYCL\n" ); 774q_dst .get_device ().ext_oneapi_enable_peer_access (q_src .get_device ()); 775SYCL_CHECK (CHECK_TRY_ERROR (q_dst .memcpy (ptr_dst ,ptr_src ,size ).wait ())); 776return ; 777 } 778 } 779 780// Host-staged copy 781if (g_ggml_sycl_dev2dev_memcpy == DEV2DEV_MEMCPY_FORWARD ) { 782GGML_SYCL_DEBUG ("[SYCL] dev2dev memcpy by host forward for setting GGML_SYCL_DEV2DEV_MEMCPY=2\n" ); 783 }else { 784GGML_SYCL_DEBUG ("[SYCL] dev2dev memcpy by host forward for SYCL/L0 fallback\n" ); 785 } 786char * host_buf = (char * )malloc (size ); 787q_src .memcpy (host_buf , (const char * )ptr_src ,size ).wait (); 788q_dst .memcpy ((char * )ptr_dst ,host_buf ,size ).wait (); 789free (host_buf ); 790} 791 792static bool 793ggml_backend_sycl_buffer_cpy_tensor (ggml_backend_buffer_t buffer , 794const ggml_tensor * src , 795ggml_tensor * dst )try { 796bool is_cpy_supported = ggml_backend_buffer_is_sycl (src -> buffer ); 797GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 798GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": dst" ,dst ).c_str ()); 799GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (" src" ,src ).c_str ()); 800GGML_SYCL_DEBUG (" is_cpy_supported=%d\n" ,is_cpy_supported ); 801if (is_cpy_supported ) { 802ggml_backend_sycl_buffer_context * src_ctx = (ggml_backend_sycl_buffer_context * )src -> buffer -> context ; 803ggml_backend_sycl_buffer_context * dst_ctx = (ggml_backend_sycl_buffer_context * )dst -> buffer -> context ; 804 805ggml_sycl_set_device (src_ctx -> device ); 806/* 807DPCT1009:198: SYCL uses exceptions to report errors and does not use the 808error codes. The original code was commented out and a warning string 809was inserted. You need to rewrite this code. 810*/ 811SYCL_CHECK (CHECK_TRY_ERROR ( 812 dpct::dev_mgr::instance ().get_device (src_ctx -> device ).queues_wait_and_throw ())); 813ggml_sycl_set_device (dst_ctx -> device ); 814/* 815DPCT1009:199: SYCL uses exceptions to report errors and does not use the 816error codes. The original code was commented out and a warning string 817was inserted. You need to rewrite this code. 818*/ 819SYCL_CHECK (CHECK_TRY_ERROR ( 820 dpct::dev_mgr::instance ().get_device (dst_ctx -> device ).queues_wait_and_throw ())); 821/* 822DPCT1009:200: SYCL uses exceptions to report errors and does not use the 823error codes. The original code was commented out and a warning string 824was inserted. You need to rewrite this code. 825*/ 826 827queue_ptr stream_dst = dst_ctx -> stream ; 828queue_ptr stream_src = src_ctx -> stream ; 829size_t size = ggml_nbytes (src ); 830 831//todo. it's dirty solutino to walkaroud known issue:device2device cross GPUs. 832dev2dev_memcpy (dst_ctx -> device ,* stream_dst ,src_ctx -> device ,* stream_src ,dst -> data ,src -> data ,size ); 833 834//todo, it's known issue:error in device2device cross GPUs. reused when the issue is fixed. DON"T remove 835#if 0 836SYCL_CHECK (CHECK_TRY_ERROR ((* stream ).memcpy ( 837 (char * )dst -> data , (const char * )src -> data ,size ).wait ())); 838 839/* 840DPCT1009:201: SYCL uses exceptions to report errors and does not use the 841error codes. The original code was commented out and a warning string 842was inserted. You need to rewrite this code. 843*/ 844SYCL_CHECK (CHECK_TRY_ERROR ( 845 dpct::dev_mgr::instance ().get_device (dst_ctx -> device ).queues_wait_and_throw ())); 846#endif 847return true; 848 } 849return false; 850GGML_UNUSED (buffer ); 851}catch (const sycl::exception & exc ) { 852 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ <<", line:" <<__LINE__ << std::endl ; 853 std::exit (1 ); 854} 855 856static void ggml_backend_sycl_buffer_clear (ggml_backend_buffer_t buffer , 857uint8_t value )try { 858GGML_SYCL_DEBUG ("[SYCL] call %s: size=%zu\n" ,__func__ ,buffer -> size ); 859ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context * )buffer -> context ; 860 861ggml_sycl_set_device (ctx -> device ); 862queue_ptr stream = ctx -> stream ; 863SYCL_CHECK ( 864CHECK_TRY_ERROR (dpct::get_current_device ().queues_wait_and_throw ())); 865 866constexpr size_t MAX_CHUNK = 2ULL <<30 ;// 2 GiB 867for (size_t off = 0 ;off < buffer -> size ;off += MAX_CHUNK ) { 868size_t chunk = std::min (buffer -> size - off ,MAX_CHUNK ); 869SYCL_CHECK (CHECK_TRY_ERROR ( 870 (* stream ) 871 .memset (static_cast < char *> (ctx -> dev_ptr )+ off ,value ,chunk ) 872 .wait () 873 )); 874 } 875} 876catch (sycl::exception const & exc ) { 877 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 878 <<", line:" <<__LINE__ << std::endl ; 879 std::exit (1 ); 880} 881 882static void ggml_backend_sycl_buffer_memset_tensor (ggml_backend_buffer_t buffer ,ggml_tensor * tensor ,uint8_t value , 883size_t offset ,size_t size ) { 884GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 885GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": tensor" ,tensor ).c_str ()); 886GGML_SYCL_DEBUG (" size=%zu offset=%zu value=%u\n" ,size ,offset ,value ); 887ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context * )buffer -> context ; 888SYCL_CHECK (ggml_sycl_set_device (ctx -> device )); 889auto stream = & (dpct::dev_mgr::instance ().get_device (ctx -> device ).default_queue ()); 890if (size == 0 ) { 891return ;// Nothing to do 892 } 893if (tensor -> data == nullptr ) { 894GGML_ABORT ("Error: Tensor data pointer is null.\n" ); 895 } 896void * target_ptr = static_cast < char *> (tensor -> data )+ offset ; 897SYCL_CHECK (CHECK_TRY_ERROR ((* stream ).memset (target_ptr ,value ,size ))); 898SYCL_CHECK (CHECK_TRY_ERROR ((* stream ).wait ())); 899} 900 901static void ggml_backend_sycl_buffer_reset (ggml_backend_buffer_t buffer ) { 902GGML_SYCL_DEBUG ("[SYCL] call %s\n" ,__func__ ); 903if (buffer == nullptr ) { 904return ; 905 } 906 907ggml_backend_sycl_buffer_context * ctx = (ggml_backend_sycl_buffer_context * )buffer -> context ; 908 909if (ctx != nullptr ) { 910for (ggml_tensor_extra_gpu * extra :ctx -> tensor_extras ) { 911release_extra_gpu (extra ); 912 } 913ctx -> tensor_extras .clear ();// reset the tensor_extras vector 914 } 915} 916 917static const ggml_backend_buffer_i ggml_backend_sycl_buffer_interface = { 918/* .free_buffer = */ ggml_backend_sycl_buffer_free_buffer , 919/* .get_base = */ ggml_backend_sycl_buffer_get_base , 920/* .init_tensor = */ ggml_backend_sycl_buffer_init_tensor , 921/* .memset_tensor = */ ggml_backend_sycl_buffer_memset_tensor , 922/* .set_tensor = */ ggml_backend_sycl_buffer_set_tensor , 923/* .get_tensor = */ ggml_backend_sycl_buffer_get_tensor , 924/* .set_tensor_2d = */ NULL , 925/* .get_tensor_2d = */ NULL , 926/* .cpy_tensor = */ ggml_backend_sycl_buffer_cpy_tensor , 927/* .clear = */ ggml_backend_sycl_buffer_clear , 928/* .reset = */ ggml_backend_sycl_buffer_reset , 929}; 930 931// sycl buffer type 932struct ggml_backend_sycl_buffer_type_context { 933int device ; 934 std::string name ; 935 936// each buffer type has its own stream 937queue_ptr stream = nullptr ; 938}; 939 940static const char * ggml_backend_sycl_buffer_type_get_name (ggml_backend_buffer_type_t buft ) { 941ggml_backend_sycl_buffer_type_context * ctx = (ggml_backend_sycl_buffer_type_context * )buft -> context ; 942 943return ctx -> name .c_str (); 944} 945 946static bool check_usm_system (int device ,size_t size ) { 947bool use_usm_system = g_ggml_sycl_usm_system && size >= ((size_t )4 * MEM_SIZE_1G ); 948 949if (use_usm_system && !ggml_sycl_info ().devices [device ].usm_system_support ) { 950GGML_LOG_INFO ("Device does not support USM system allocations\n" ); 951use_usm_system = false; 952 } 953 954return use_usm_system ; 955} 956 957inline void * aligned_malloc_host (size_t alignment ,size_t size ) { 958#ifdef _WIN32 959return _aligned_malloc (size ,alignment ); 960#else 961return aligned_alloc (alignment ,size ); 962#endif 963} 964 965static ggml_backend_buffer_t 966ggml_backend_sycl_buffer_type_alloc_buffer (ggml_backend_buffer_type_t buft , 967size_t size )try { 968GGML_SYCL_DEBUG ("[SYCL] call %s: size=%zu\n" ,__func__ ,size ); 969ggml_check_sycl (); 970 971ggml_backend_sycl_buffer_type_context * buft_ctx = (ggml_backend_sycl_buffer_type_context * )buft -> context ; 972ggml_sycl_set_device (buft_ctx -> device ); 973const queue_ptr stream = buft_ctx -> stream ; 974size = std::max (size , (size_t )1 );// syclMalloc returns null for size 0 975/* 976Alignment below ensures best performance. While in theory it could lead to 977wasting memory, this is acceptable because in practice only few buffers are 978allocated and even less exceed the minimum size accepted here for USM system 979allocations. 980*/ 981size_t alignment = MEM_SIZE_2M ; 982size_t aligned_size = ((size + alignment - 1 ) /alignment )* alignment ; 983bool use_usm_system = check_usm_system (buft_ctx -> device ,aligned_size ); 984 985void * dev_ptr ; 986if (use_usm_system ) { 987GGML_SYCL_DEBUG ("[SYCL] allocating %zu Bytes with USM system\n" ,size ); 988dev_ptr = (void * )aligned_malloc_host (alignment ,aligned_size ); 989if (!dev_ptr ) { 990GGML_LOG_ERROR ("%s: can't allocate %zu Bytes of memory on host\n" ,__func__ ,size ); 991return nullptr ; 992 } 993 }else { 994SYCL_CHECK (CHECK_TRY_ERROR (dev_ptr = (void * )ggml_sycl_malloc_device (size ,* stream ,GGML_SYCL_MEM_BUFFER ))); 995if (!dev_ptr ) { 996GGML_LOG_ERROR ("%s: can't allocate %zu Bytes of memory on device\n" ,__func__ ,size ); 997return nullptr ; 998 } 999 } 1000ggml_backend_sycl_buffer_context * ctx = new ggml_backend_sycl_buffer_context (buft_ctx -> device ,dev_ptr ,buft_ctx -> stream ,use_usm_system ); 1001return ggml_backend_buffer_init (buft ,ggml_backend_sycl_buffer_interface ,ctx ,size ); 1002} 1003catch (sycl::exception const & exc ) { 1004 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1005 <<", line:" <<__LINE__ << std::endl ; 1006 std::exit (1 ); 1007} 1008 1009static size_t ggml_backend_sycl_buffer_type_get_alignment (ggml_backend_buffer_type_t buft ) { 1010return SYCL_BUFFER_ALIGNMENT ; 1011GGML_UNUSED (buft ); 1012} 1013 1014bool is_bmg_g31_arch (int device ) { 1015return ggml_sycl_info ().devices [device ].hw_info .arch == gpu_arch::intel_gpu_bmg_g31 ; 1016} 1017 1018static size_t ggml_backend_sycl_buffer_type_get_max_size (ggml_backend_buffer_type_t buft ) { 1019size_t max_alloc_size = dpct::get_current_device ().get_max_mem_alloc_size (); 1020if (g_ggml_sycl_host_pinned_mem_2g ) { 1021return std::min (max_alloc_size , (size_t )2LL * 1024 * 1024 * 1024 ); 1022 }else { 1023ggml_backend_sycl_buffer_type_context * ctx = (ggml_backend_sycl_buffer_type_context * )buft -> context ; 1024int device = ctx -> device ; 1025if (is_bmg_g31_arch (device )) { 1026//Todo, it's workaround for BMG-G31, which has a known issue with large allocations. 1027//The max alloc size is reduced to 60% of the reported max alloc size. 1028//remove it after https://github.com/intel/compute-runtime/issues/998 is fixed. 1029max_alloc_size = max_alloc_size * 0.6 ; 1030 } 1031return max_alloc_size ; 1032 1033 } 1034GGML_UNUSED (buft ); 1035} 1036 1037static size_t ggml_backend_sycl_buffer_type_get_alloc_size (ggml_backend_buffer_type_t buft ,const ggml_tensor * tensor ) { 1038// Reserve the additional scratch so it's visible to the graph allocator 1039size_t size = tensor -> op == GGML_OP_FLASH_ATTN_EXT 1040 ?ggml_sycl_flash_attn_ext_get_alloc_size (tensor ) 1041 :ggml_nbytes (tensor ); 1042int64_t ne0 = tensor -> ne [0 ]; 1043 1044if (ggml_is_quantized (tensor -> type )) { 1045if (ne0 %MATRIX_ROW_PADDING != 0 ) { 1046size += ggml_row_size (tensor -> type ,MATRIX_ROW_PADDING - ne0 %MATRIX_ROW_PADDING ); 1047 } 1048 } 1049 1050return size ; 1051 1052GGML_UNUSED (buft ); 1053} 1054 1055static const ggml_backend_buffer_type_i ggml_backend_sycl_buffer_type_interface = { 1056/* .get_name = */ ggml_backend_sycl_buffer_type_get_name , 1057/* .alloc_buffer = */ ggml_backend_sycl_buffer_type_alloc_buffer , 1058/* .get_alignment = */ ggml_backend_sycl_buffer_type_get_alignment , 1059/* .get_max_size = */ ggml_backend_sycl_buffer_type_get_max_size , 1060/* .get_alloc_size = */ ggml_backend_sycl_buffer_type_get_alloc_size , 1061/* .is_host = */ NULL , 1062}; 1063 1064ggml_backend_buffer_type_t ggml_backend_sycl_buffer_type (int device ) { 1065static std::mutex mutex ; 1066 std::lock_guard < std::mutex > lock (mutex ); 1067 1068 1069auto dev_count = ggml_backend_sycl_get_device_count (); 1070 1071if (device >=dev_count ordevice < 0 ) { 1072GGML_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" , 1073device ,dev_count - 1 ); 1074GGML_ASSERT (device < dev_count ); 1075 } 1076static struct ggml_backend_buffer_type ggml_backend_sycl_buffer_types [GGML_SYCL_MAX_DEVICES ]; 1077 1078static bool ggml_backend_sycl_buffer_type_initialized = false; 1079 1080if (!ggml_backend_sycl_buffer_type_initialized ) { 1081for (int i = 0 ;i < dev_count ;i ++ ) { 1082auto & device_i = dpct::dev_mgr::instance ().get_device (i ); 1083queue_ptr stream = & (device_i .default_queue ()); 1084ggml_backend_sycl_buffer_types [i ]= { 1085/* .iface = */ ggml_backend_sycl_buffer_type_interface , 1086/* .device = */ ggml_backend_reg_dev_get (ggml_backend_sycl_reg (),i ), 1087/* .context = */ new ggml_backend_sycl_buffer_type_context {i ,GGML_SYCL_NAME + std::to_string (i ),stream }, 1088 }; 1089 } 1090ggml_backend_sycl_buffer_type_initialized = true; 1091 } 1092return & ggml_backend_sycl_buffer_types [device ]; 1093} 1094 1095static ggml_backend_buffer_type_t ggml_backend_sycl_buffer_type (ggml_backend_sycl_context * ctx ) { 1096GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_buffer_type\n" ); 1097 1098int device = ctx -> device ; 1099if (device >=ggml_sycl_info ().device_count ordevice < 0 ) { 1100GGML_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" , 1101device ,ggml_sycl_info ().device_count - 1 ); 1102GGML_ASSERT (device < ggml_sycl_info ().device_count ); 1103 } 1104static struct ggml_backend_buffer_type ggml_backend_sycl_buffer_types [GGML_SYCL_MAX_DEVICES ]; 1105 1106static bool ggml_backend_sycl_buffer_type_initialized = false; 1107 1108if (!ggml_backend_sycl_buffer_type_initialized ) { 1109for (int i = 0 ;i < ggml_sycl_info ().device_count ;i ++ ) { 1110ggml_backend_sycl_buffer_types [i ]= { 1111/* .iface = */ ggml_backend_sycl_buffer_type_interface , 1112/* .device = */ nullptr , 1113/* .context = */ new ggml_backend_sycl_buffer_type_context {i ,GGML_SYCL_NAME + std::to_string (i ),ctx -> stream (i ,0 )}, 1114 }; 1115 } 1116ggml_backend_sycl_buffer_type_initialized = true; 1117 } 1118return & ggml_backend_sycl_buffer_types [device ]; 1119} 1120 1121// sycl split buffer 1122 1123static int64_t get_row_rounding (ggml_type type ,const std::array < float ,GGML_SYCL_MAX_DEVICES > & tensor_split ) { 1124int64_t min_compute_capability = INT_MAX ; 1125int64_t max_compute_capability = INT_MIN ; 1126for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 1127if (tensor_split [i ]< (i + 1 < ggml_sycl_info ().device_count ?tensor_split [i + 1 ] :1.0f )) { 1128if (min_compute_capability > ggml_sycl_info ().devices [i ].cc ) { 1129min_compute_capability = ggml_sycl_info ().devices [i ].cc ; 1130 } 1131if (max_compute_capability < ggml_sycl_info ().devices [i ].cc ) { 1132max_compute_capability = ggml_sycl_info ().devices [i ].cc ; 1133 } 1134 } 1135 } 1136 1137switch (type ) { 1138case GGML_TYPE_Q1_0 : 1139case GGML_TYPE_Q4_0 : 1140case GGML_TYPE_Q4_1 : 1141return max_compute_capability >=VER_GEN9 ?128 :64 ; 1142case GGML_TYPE_Q5_0 : 1143case GGML_TYPE_Q5_1 : 1144case GGML_TYPE_Q8_0 : 1145return 64 ; 1146case GGML_TYPE_F16 : 1147case GGML_TYPE_F32 : 1148return 1 ; 1149case GGML_TYPE_Q2_K : 1150case GGML_TYPE_Q3_K : 1151case GGML_TYPE_Q4_K : 1152case GGML_TYPE_Q5_K : 1153case GGML_TYPE_IQ2_XXS : 1154case GGML_TYPE_IQ2_XS : 1155case GGML_TYPE_IQ2_S : 1156case GGML_TYPE_IQ1_S : 1157case GGML_TYPE_IQ1_M : 1158case GGML_TYPE_IQ3_XXS : 1159case GGML_TYPE_IQ4_XS : 1160case GGML_TYPE_IQ4_NL : 1161return max_compute_capability >=VER_GEN9 ?128 :64 ; 1162case GGML_TYPE_IQ3_S : 1163return max_compute_capability >=VER_GEN9 ?128 :64 ; 1164case GGML_TYPE_Q6_K : 1165return 64 ; 1166default : 1167GGML_ABORT ("fatal error" ); 1168 } 1169} 1170 1171static void get_row_split (int64_t * row_low ,int64_t * row_high ,const ggml_tensor * tensor ,const std::array < float ,GGML_SYCL_MAX_DEVICES > & tensor_split ,int id ) { 1172const int64_t nrows = ggml_nrows (tensor ); 1173const int64_t rounding = get_row_rounding (tensor -> type ,tensor_split ); 1174 1175* row_low = id == 0 ?0 :nrows * tensor_split [id ]; 1176* row_low -= * row_low %rounding ; 1177if (id == ggml_sycl_info ().device_count - 1 ) { 1178* row_high = nrows ; 1179 }else { 1180* row_high = nrows * tensor_split [id + 1 ]; 1181* row_high -= * row_high %rounding ; 1182 } 1183} 1184 1185static size_t ggml_nbytes_split (const struct ggml_tensor * tensor ,int nrows_split ) { 1186 static_assert(GGML_MAX_DIMS == 4 ,"GGML_MAX_DIMS is not 4 - update this function" ); 1187 1188return nrows_split * ggml_row_size (tensor -> type ,tensor -> ne [0 ]); 1189} 1190 1191struct ggml_backend_sycl_split_buffer_type_context { 1192 std::array < float ,GGML_SYCL_MAX_DEVICES > tensor_split ; 1193}; 1194 1195struct ggml_backend_sycl_split_buffer_context { 1196 ~ggml_backend_sycl_split_buffer_context ()try { 1197for (ggml_tensor_extra_gpu * extra :tensor_extras ) { 1198release_extra_gpu (extra ,streams ); 1199 } 1200 } 1201catch (sycl::exception const & exc ) { 1202 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1203 <<", line:" <<__LINE__ << std::endl ; 1204 std::exit (1 ); 1205 } 1206 1207 std::vector < ggml_tensor_extra_gpu *> tensor_extras ; 1208 std::vector < queue_ptr > streams ; 1209}; 1210 1211static void ggml_backend_sycl_split_buffer_free_buffer (ggml_backend_buffer_t buffer ) { 1212ggml_backend_sycl_split_buffer_context * ctx = (ggml_backend_sycl_split_buffer_context * )buffer -> context ; 1213delete ctx ; 1214} 1215 1216static void * ggml_backend_sycl_split_buffer_get_base (ggml_backend_buffer_t buffer ) { 1217// the pointers are stored in the tensor extras, this is just a dummy address and never dereferenced 1218return (void * )0x1000 ; 1219 1220GGML_UNUSED (buffer ); 1221} 1222 1223static enum ggml_status 1224ggml_backend_sycl_split_buffer_init_tensor (ggml_backend_buffer_t buffer , 1225ggml_tensor * tensor )try { 1226GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 1227GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": tensor" ,tensor ,"\n" ).c_str ()); 1228GGML_ASSERT (tensor -> view_src == nullptr );// views of split tensors are not supported 1229 1230ggml_backend_sycl_split_buffer_context * ctx = (ggml_backend_sycl_split_buffer_context * )buffer -> context ; 1231ggml_backend_sycl_split_buffer_type_context * buft_ctx = (ggml_backend_sycl_split_buffer_type_context * )buffer -> buft -> context ; 1232 1233const int64_t ne0 = tensor -> ne [0 ]; 1234 1235ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu {}; 1236 1237ctx -> tensor_extras .push_back (extra ); 1238ctx -> streams .push_back (& (dpct::get_current_device ().default_queue ())); 1239 1240for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 1241int64_t row_low ,row_high ; 1242get_row_split (& row_low ,& row_high ,tensor ,buft_ctx -> tensor_split ,i ); 1243 1244int64_t nrows_split = row_high - row_low ; 1245if (nrows_split == 0 ) { 1246continue ; 1247 } 1248 1249size_t size = ggml_nbytes_split (tensor ,nrows_split ); 1250const size_t original_size = size ; 1251 1252// pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses 1253if (ne0 %MATRIX_ROW_PADDING != 0 ) { 1254size += ggml_row_size (tensor -> type ,MATRIX_ROW_PADDING - ne0 %MATRIX_ROW_PADDING ); 1255 } 1256 1257ggml_sycl_set_device (i ); 1258const queue_ptr stream = ctx -> streams [i ]; 1259char * buf ; 1260SYCL_CHECK (CHECK_TRY_ERROR (buf = (char * )ggml_sycl_malloc_device (size ,* stream ,GGML_SYCL_MEM_BUFFER ))); 1261if (!buf ) { 1262char err_buf [1024 ]; 1263snprintf (err_buf ,1023 ,"%s: can't allocate %zu Bytes of memory on device\n" ,__func__ ,size ); 1264throw std::runtime_error (err_buf ); 1265 } 1266// set padding to 0 to avoid possible NaN values 1267if (size > original_size ) { 1268/* 1269DPCT1009:209: SYCL uses exceptions to report errors and does not use 1270the error codes. The original code was commented out and a warning 1271string was inserted. You need to rewrite this code. 1272*/ 1273SYCL_CHECK (CHECK_TRY_ERROR ( 1274 (* stream ) 1275 .memset (buf + original_size ,0 ,size - original_size ) 1276 .wait ())); 1277 } 1278 1279extra -> data_device [i ]= buf ; 1280 1281for (int64_t is = 0 ;is < GGML_SYCL_MAX_STREAMS ;++ is ) { 1282/* 1283DPCT1009:210: SYCL uses exceptions to report errors and does not use 1284the error codes. The original code was commented out and a warning 1285string was inserted. You need to rewrite this code. 1286*/ 1287SYCL_CHECK ( 1288CHECK_TRY_ERROR (extra -> events [i ][is ]= new sycl::event ())); 1289 } 1290 } 1291tensor -> extra = extra ; 1292return GGML_STATUS_SUCCESS ; 1293} 1294catch (sycl::exception const & exc ) { 1295 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1296 <<", line:" <<__LINE__ << std::endl ; 1297 std::exit (1 ); 1298} 1299 1300static void 1301ggml_backend_sycl_split_buffer_set_tensor (ggml_backend_buffer_t buffer , 1302ggml_tensor * tensor ,const void * data , 1303size_t offset ,size_t size )try { 1304GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 1305GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": tensor" ,tensor ).c_str ()); 1306GGML_SYCL_DEBUG (" size=%zu offset=%zu\n" ,size ,offset ); 1307// split tensors must always be set in their entirety at once 1308GGML_ASSERT (offset == 0 ); 1309GGML_ASSERT (size == ggml_nbytes (tensor )); 1310 1311ggml_backend_sycl_split_buffer_context * ctx = (ggml_backend_sycl_split_buffer_context * )buffer -> context ; 1312ggml_backend_sycl_split_buffer_type_context * buft_ctx = (ggml_backend_sycl_split_buffer_type_context * )buffer -> buft -> context ; 1313 1314const int64_t ne0 = tensor -> ne [0 ]; 1315const size_t nb1 = tensor -> nb [1 ]; 1316ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu * )tensor -> extra ; 1317 1318for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 1319int64_t row_low ,row_high ; 1320get_row_split (& row_low ,& row_high ,tensor ,buft_ctx -> tensor_split ,i ); 1321 1322int64_t nrows_split = row_high - row_low ; 1323if (nrows_split == 0 ) { 1324continue ; 1325 } 1326 1327const size_t offset_split = row_low * nb1 ; 1328size_t size = ggml_nbytes_split (tensor ,nrows_split ); 1329const size_t original_size = size ; 1330 1331// pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses 1332if (ne0 %MATRIX_ROW_PADDING != 0 ) { 1333size += ggml_row_size (tensor -> type ,MATRIX_ROW_PADDING - ne0 %MATRIX_ROW_PADDING ); 1334 } 1335 1336const char * buf_host = (const char * )data + offset_split ; 1337/* 1338DPCT1009:211: SYCL uses exceptions to report errors and does not use the 1339error codes. The original code was commented out and a warning string 1340was inserted. You need to rewrite this code. 1341*/ 1342ggml_sycl_set_device (i ); 1343const queue_ptr stream = ctx -> streams [i ]; 1344SYCL_CHECK (CHECK_TRY_ERROR ( 1345 (* stream ) 1346 .memcpy (extra -> data_device [i ],buf_host ,original_size ) 1347 .wait ())); 1348 } 1349} 1350catch (sycl::exception const & exc ) { 1351 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1352 <<", line:" <<__LINE__ << std::endl ; 1353 std::exit (1 ); 1354} 1355 1356static void 1357ggml_backend_sycl_split_buffer_get_tensor (ggml_backend_buffer_t buffer , 1358const ggml_tensor * tensor ,void * data , 1359size_t offset ,size_t size )try { 1360GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 1361GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": tensor" ,tensor ).c_str ()); 1362GGML_SYCL_DEBUG (" size=%zu offset=%zu\n" ,size ,offset ); 1363// split tensors must always be set in their entirety at once 1364GGML_ASSERT (offset == 0 ); 1365GGML_ASSERT (size == ggml_nbytes (tensor )); 1366 1367ggml_backend_sycl_split_buffer_context * ctx = (ggml_backend_sycl_split_buffer_context * )buffer -> context ; 1368ggml_backend_sycl_split_buffer_type_context * buft_ctx = (ggml_backend_sycl_split_buffer_type_context * )buffer -> buft -> context ; 1369 1370const int64_t ne0 = tensor -> ne [0 ]; 1371const size_t nb1 = tensor -> nb [1 ]; 1372ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu * )tensor -> extra ; 1373 1374for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 1375int64_t row_low ,row_high ; 1376get_row_split (& row_low ,& row_high ,tensor ,buft_ctx -> tensor_split ,i ); 1377 1378int64_t nrows_split = row_high - row_low ; 1379if (nrows_split == 0 ) { 1380continue ; 1381 } 1382 1383const size_t offset_split = row_low * nb1 ; 1384size_t size = ggml_nbytes_split (tensor ,nrows_split ); 1385const size_t original_size = size ; 1386 1387// pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses 1388if (ne0 %MATRIX_ROW_PADDING != 0 ) { 1389size += ggml_row_size (tensor -> type ,MATRIX_ROW_PADDING - ne0 %MATRIX_ROW_PADDING ); 1390 } 1391 1392char * buf_host = (char * )data + offset_split ; 1393/* 1394DPCT1009:212: SYCL uses exceptions to report errors and does not use the 1395error codes. The original code was commented out and a warning string 1396was inserted. You need to rewrite this code. 1397*/ 1398ggml_sycl_set_device (i ); 1399const queue_ptr stream = ctx -> streams [i ]; 1400SYCL_CHECK (CHECK_TRY_ERROR ( 1401 (* stream ) 1402 .memcpy (buf_host ,extra -> data_device [i ],original_size ) 1403 .wait ())); 1404 } 1405} 1406catch (sycl::exception const & exc ) { 1407 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1408 <<", line:" <<__LINE__ << std::endl ; 1409 std::exit (1 ); 1410} 1411 1412static void ggml_backend_sycl_split_buffer_clear (ggml_backend_buffer_t buffer ,uint8_t value ) { 1413GGML_UNUSED (buffer ); 1414GGML_UNUSED (value ); 1415} 1416 1417static struct ggml_backend_buffer_i ggml_backend_sycl_split_buffer_interface = { 1418/* .free_buffer = */ ggml_backend_sycl_split_buffer_free_buffer , 1419/* .get_base = */ ggml_backend_sycl_split_buffer_get_base , 1420/* .init_tensor = */ ggml_backend_sycl_split_buffer_init_tensor , 1421/* .memset_tensor = */ NULL , 1422/* .set_tensor = */ ggml_backend_sycl_split_buffer_set_tensor , 1423/* .get_tensor = */ ggml_backend_sycl_split_buffer_get_tensor , 1424/* .set_tensor_2d = */ NULL , 1425/* .get_tensor_2d = */ NULL , 1426/* .cpy_tensor = */ NULL , 1427/* .clear = */ ggml_backend_sycl_split_buffer_clear , 1428/* .reset = */ NULL , 1429}; 1430 1431// sycl split buffer type 1432 1433static const char * ggml_backend_sycl_split_buffer_type_get_name (ggml_backend_buffer_type_t buft ) { 1434return GGML_SYCL_NAME "_Split" ; 1435 1436GGML_UNUSED (buft ); 1437} 1438 1439static bool ggml_backend_buffer_is_sycl_split (ggml_backend_buffer_t buffer ) { 1440return buffer -> buft -> iface .get_name == ggml_backend_sycl_split_buffer_type_get_name ; 1441} 1442 1443static ggml_backend_buffer_t ggml_backend_sycl_split_buffer_type_alloc_buffer (ggml_backend_buffer_type_t buft ,size_t size ) { 1444// since we don't know the exact split after rounding, we cannot allocate the device buffers at this point 1445// instead, we allocate them for each tensor separately in init_tensor 1446// however, the size still represents the maximum cumulative size of all the device buffers after the tensors are allocated, 1447// as returned by get_alloc_size. this limit is enforced during tensor allocation by ggml-alloc, so it must be correct. 1448ggml_backend_sycl_split_buffer_context * ctx = new ggml_backend_sycl_split_buffer_context (); 1449 1450return ggml_backend_buffer_init (buft ,ggml_backend_sycl_split_buffer_interface ,ctx ,size ); 1451} 1452 1453static size_t ggml_backend_sycl_split_buffer_type_get_alignment (ggml_backend_buffer_type_t buft ) { 1454return SYCL_BUFFER_ALIGNMENT ; 1455GGML_UNUSED (buft ); 1456} 1457 1458static size_t ggml_backend_sycl_split_buffer_type_get_alloc_size (ggml_backend_buffer_type_t buft ,const ggml_tensor * tensor ) { 1459ggml_backend_sycl_split_buffer_type_context * ctx = (ggml_backend_sycl_split_buffer_type_context * )buft -> context ; 1460 1461size_t total_size = 0 ; 1462 1463const int64_t ne0 = tensor -> ne [0 ]; 1464 1465for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 1466int64_t row_low ,row_high ; 1467get_row_split (& row_low ,& row_high ,tensor ,ctx -> tensor_split ,i ); 1468 1469int64_t nrows_split = row_high - row_low ; 1470if (nrows_split == 0 ) { 1471continue ; 1472 } 1473 1474total_size += ggml_nbytes_split (tensor ,nrows_split ); 1475 1476// pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses 1477if (ne0 %MATRIX_ROW_PADDING != 0 ) { 1478total_size += ggml_row_size (tensor -> type ,MATRIX_ROW_PADDING - ne0 %MATRIX_ROW_PADDING ); 1479 } 1480 } 1481 1482return total_size ; 1483} 1484 1485static bool ggml_backend_sycl_split_buffer_type_is_host (ggml_backend_buffer_type_t buft ) { 1486return false; 1487 1488GGML_UNUSED (buft ); 1489} 1490 1491static ggml_backend_buffer_type_i ggml_backend_sycl_split_buffer_type_interface = { 1492/* .get_name = */ ggml_backend_sycl_split_buffer_type_get_name , 1493/* .alloc_buffer = */ ggml_backend_sycl_split_buffer_type_alloc_buffer , 1494/* .get_alignment = */ ggml_backend_sycl_split_buffer_type_get_alignment , 1495/* .get_max_size = */ NULL ,// defaults to SIZE_MAX 1496/* .get_alloc_size = */ ggml_backend_sycl_split_buffer_type_get_alloc_size , 1497/* .is_host = */ ggml_backend_sycl_split_buffer_type_is_host , 1498}; 1499 1500ggml_backend_buffer_type_t ggml_backend_sycl_split_buffer_type ([[maybe_unused ]]int main_device ,const float * tensor_split ) { 1501GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_split_buffer_type\n" ); 1502 1503static std::mutex mutex ; 1504 std::lock_guard < std::mutex > lock (mutex ); 1505 1506ggml_check_sycl (); 1507// FIXME: this is not thread safe 1508static std::map < std::array < float ,GGML_SYCL_MAX_DEVICES > ,struct ggml_backend_buffer_type > buft_map ; 1509 1510 std::array < float ,GGML_SYCL_MAX_DEVICES > tensor_split_arr = {}; 1511 1512bool all_zero = tensor_split == nullptr || std::all_of (tensor_split ,tensor_split + GGML_SYCL_MAX_DEVICES , [](float x ) {return x == 0.0f ; }); 1513if (all_zero ) { 1514tensor_split_arr = ggml_sycl_info ().default_tensor_split ; 1515 }else { 1516float split_sum = 0.0f ; 1517for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 1518tensor_split_arr [i ]= split_sum ; 1519split_sum += tensor_split [i ]; 1520 } 1521for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 1522tensor_split_arr [i ] /=split_sum ; 1523 } 1524 } 1525 1526auto it = buft_map .find (tensor_split_arr ); 1527if (it != buft_map .end ()) { 1528return & it -> second ; 1529 } 1530 1531struct ggml_backend_buffer_type buft { 1532/* .iface = */ ggml_backend_sycl_split_buffer_type_interface , 1533/* .device = */ ggml_backend_reg_dev_get (ggml_backend_sycl_reg (),0 ), 1534/* .context = */ new ggml_backend_sycl_split_buffer_type_context {tensor_split_arr }, 1535 }; 1536 1537auto result = buft_map .emplace (tensor_split_arr ,buft ); 1538return & result .first -> second ; 1539} 1540 1541// host buffer type 1542 1543struct ggml_backend_sycl_device_context { 1544int device ; 1545 std::string name ; 1546 std::string description ; 1547int op_offload_min_batch_size ; 1548}; 1549 1550static const char * ggml_backend_sycl_host_buffer_type_name (ggml_backend_buffer_type_t buft ) { 1551return GGML_SYCL_NAME "_Host" ; 1552 1553GGML_UNUSED (buft ); 1554} 1555 1556//host pinned memory 1557static void * ggml_backend_sycl_host_malloc (size_t size ) { 1558GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_host_malloc\n" ); 1559void * ptr = nullptr ; 1560try { 1561ggml_check_sycl (); 1562// USM host memory is page-locked and device-accessible by construction 1563auto & q = dpct::dev_mgr::instance ().get_device (0 ).default_queue (); 1564ptr = sycl::malloc_host (size ,q , sycl::property_list {}); 1565 }catch (...) { 1566ptr = nullptr ; 1567 } 1568if (ptr == nullptr ) { 1569GGML_LOG_WARN ("%s: failed to allocate %.2f MiB of pinned memory\n" ,__func__ , 1570size /1024.0 /1024.0 ); 1571 } 1572 1573return ptr ; 1574} 1575 1576static void ggml_backend_sycl_host_buffer_free_buffer (ggml_backend_buffer_t buffer ) { 1577if (buffer -> context == nullptr ) { 1578return ; 1579 } 1580if (g_ggml_sycl_enable_host_pinned_mem ) { 1581auto & q = dpct::dev_mgr::instance ().get_device (0 ).default_queue (); 1582SYCL_CHECK (CHECK_TRY_ERROR (sycl::free (buffer -> context ,q ))); 1583 }else { 1584free_aligned_mem_host ((void * )buffer -> context ); 1585 } 1586} 1587 1588static ggml_backend_buffer_t ggml_backend_sycl_host_buffer_type_alloc_buffer (ggml_backend_buffer_type_t buft ,size_t size ) { 1589void * ptr = g_ggml_sycl_enable_host_pinned_mem ?ggml_backend_sycl_host_malloc (size ) : 1590aligned_malloc_host (TENSOR_ALIGNMENT ,size ); 1591if (ptr == nullptr ) { 1592// fallback to cpu buffer 1593return ggml_backend_buft_alloc_buffer (ggml_backend_cpu_buffer_type (),size ); 1594 } 1595 1596// FIXME: this is a hack to avoid having to implement a new buffer type 1597ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr (ptr ,size ); 1598buffer -> buft = buft ; 1599buffer -> iface .free_buffer = ggml_backend_sycl_host_buffer_free_buffer ; 1600 1601return buffer ; 1602} 1603 1604static size_t ggml_backend_sycl_host_buffer_type_get_max_size (ggml_backend_buffer_type_t buft ) { 1605 1606if (g_ggml_sycl_enable_host_pinned_mem ) { 1607ggml_backend_sycl_device_context * dev_ctx = (ggml_backend_sycl_device_context * )buft -> device -> context ; 1608size_t max_alloc_size = dpct::dev_mgr::instance ().get_device (dev_ctx -> device ).get_max_mem_alloc_size (); 1609if (g_ggml_sycl_host_pinned_mem_2g ) { 1610return std::min (max_alloc_size , (size_t )2LL * 1024 * 1024 * 1024 ); 1611 }else { 1612return max_alloc_size ; 1613 } 1614 }else { 1615return SIZE_MAX ; 1616 } 1617} 1618 1619ggml_backend_buffer_type_t ggml_backend_sycl_host_buffer_type () { 1620GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_host_buffer_type\n" ); 1621static struct ggml_backend_buffer_type ggml_backend_sycl_buffer_type_host = { 1622/* .iface = */ { 1623/* .get_name = */ ggml_backend_sycl_host_buffer_type_name , 1624/* .alloc_buffer = */ ggml_backend_sycl_host_buffer_type_alloc_buffer , 1625/* .get_alignment = */ ggml_backend_cpu_buffer_type ()-> iface .get_alignment , 1626/* .get_max_size = */ ggml_backend_sycl_host_buffer_type_get_max_size , 1627/* .get_alloc_size = */ ggml_backend_cpu_buffer_type ()-> iface .get_alloc_size , 1628/* .is_host = */ ggml_backend_cpu_buffer_type ()-> iface .is_host , 1629 }, 1630/* .device = */ ggml_backend_reg_dev_get (ggml_backend_sycl_reg (),0 ), 1631/* .context = */ nullptr , 1632 }; 1633 1634return & ggml_backend_sycl_buffer_type_host ; 1635} 1636 1637// buffer pool for sycl (legacy) 1638struct ggml_sycl_pool_leg :public ggml_sycl_pool { 1639static const int MAX_SYCL_BUFFERS = 256 ; 1640 1641int device ; 1642queue_ptr qptr ; 1643struct ggml_sycl_buffer { 1644void * ptr = nullptr ; 1645size_t size = 0 ; 1646 }; 1647 1648ggml_sycl_buffer buffer_pool [MAX_SYCL_BUFFERS ]= {}; 1649size_t pool_size = 0 ; 1650 1651explicit ggml_sycl_pool_leg (queue_ptr qptr_ ,int device_ ) :device (device_ ),qptr (qptr_ ) {} 1652 1653 ~ggml_sycl_pool_leg () { 1654#ifdef DEBUG_SYCL_POOL 1655int n_cached = 0 ; 1656size_t bytes_cached = 0 ; 1657for (int i = 0 ;i < MAX_SYCL_BUFFERS ;++ i ) { 1658if (buffer_pool [i ].ptr != nullptr ) { 1659++ n_cached ; 1660bytes_cached += buffer_pool [i ].size ; 1661 } 1662 } 1663GGML_LOG_INFO ("%s: %d buffers, cached = %.2f MiB\n" ,__func__ , 1664n_cached ,bytes_cached /1024.0 /1024.0 ); 1665const auto slots = format_slots_in_alloc_order (); 1666if (!slots .empty ()) { 1667GGML_LOG_INFO ("%s: slots MiB: %s\n" ,__func__ ,slots .c_str ()); 1668 } 1669#endif 1670 1671for (int i = 0 ;i < MAX_SYCL_BUFFERS ;++ i ) { 1672ggml_sycl_buffer & b = buffer_pool [i ]; 1673if (b .ptr != nullptr ) { 1674SYCL_CHECK (CHECK_TRY_ERROR (ggml_sycl_free_device (b .ptr ,* qptr ))); 1675pool_size -= b .size ; 1676 } 1677 } 1678GGML_ASSERT (pool_size == 0 ); 1679 } 1680 1681#ifdef DEBUG_SYCL_POOL 1682 std::string format_slots_in_alloc_order ()const { 1683 std::string line ; 1684char buf [32 ]; 1685bool first = true; 1686for (int i = 0 ;i < MAX_SYCL_BUFFERS ;++ i ) { 1687if (buffer_pool [i ].ptr == nullptr ) { 1688continue ; 1689 } 1690if (!first ) { 1691line += '/' ; 1692 } 1693first = false; 1694snprintf (buf ,sizeof (buf ),"%.2f" ,buffer_pool [i ].size /1024.0 /1024.0 ); 1695line += buf ; 1696 } 1697return line ; 1698 } 1699#endif 1700 1701void * alloc (size_t size ,size_t * actual_size )override { 1702#ifdef DEBUG_sycl_MALLOC 1703int nnz = 0 ; 1704size_t max_size = 0 ; 1705#endif 1706size_t best_diff = 1ull <<36 ; 1707int ibest = -1 ; 1708for (int i = 0 ;i < MAX_SYCL_BUFFERS ;++ i ) { 1709ggml_sycl_buffer & b = buffer_pool [i ]; 1710if (b .ptr != nullptr ) { 1711#ifdef DEBUG_sycl_MALLOC 1712++ nnz ; 1713if (b .size > max_size )max_size = b .size ; 1714#endif 1715if (b .size >=size ) { 1716size_t diff = b .size - size ; 1717if (diff < best_diff ) { 1718best_diff = diff ; 1719ibest = i ; 1720if (!best_diff ) { 1721void * ptr = b .ptr ; 1722* actual_size = b .size ; 1723b .ptr = nullptr ; 1724b .size = 0 ; 1725return ptr ; 1726 } 1727 } 1728 } 1729 } 1730 } 1731if (ibest >=0 ) { 1732ggml_sycl_buffer & b = buffer_pool [ibest ]; 1733void * ptr = b .ptr ; 1734* actual_size = b .size ; 1735b .ptr = nullptr ; 1736b .size = 0 ; 1737return ptr ; 1738 } 1739void * ptr ; 1740size_t look_ahead_size = (size_t ) (1.05 * size ); 1741 1742SYCL_CHECK (CHECK_TRY_ERROR (ptr = (void * )ggml_sycl_malloc_device (look_ahead_size ,* qptr ,GGML_SYCL_MEM_POOL_LEG ))); 1743if (!ptr ) { 1744GGML_LOG_ERROR ("%s: can't allocate %zu Bytes of memory on device/GPU\n" ,__func__ ,look_ahead_size ); 1745return nullptr ; 1746 } 1747 1748* actual_size = look_ahead_size ; 1749pool_size += look_ahead_size ; 1750 1751#ifdef DEBUG_SYCL_MALLOC 1752GGML_LOG_DEBUG ("%s[%d]: %d buffers, max_size = %u MB, pool_size = %u MB, requested %u MB\n" ,__func__ ,id ,nnz , 1753 (uint32_t )(max_size /1024 /1024 ), (uint32_t )(g_sycl_pool_size [id ]/1024 /1024 ), (uint32_t )(size /1024 /1024 )); 1754#endif 1755 1756// GGML_SYCL_DEBUG("ggml_sycl_pool_malloc_leg look_ahead_size=%zu, return %p\n", look_ahead_size, ptr); 1757return ptr ; 1758 } 1759 1760void free (void * ptr ,size_t size )override { 1761for (int i = 0 ;i < MAX_SYCL_BUFFERS ;++ i ) { 1762ggml_sycl_buffer & b = buffer_pool [i ]; 1763if (b .ptr == nullptr ) { 1764b .ptr = ptr ; 1765b .size = size ; 1766return ; 1767 } 1768 } 1769GGML_LOG_WARN ("WARNING: sycl buffer pool full, increase MAX_sycl_BUFFERS\n" ); 1770SYCL_CHECK (CHECK_TRY_ERROR (ggml_sycl_free_device (ptr ,* qptr ))); 1771pool_size -= size ; 1772 } 1773}; 1774 1775// pool with virtual memory management 1776#if defined(GGML_SYCL_SUPPORT_VMM ) 1777struct ggml_sycl_pool_vmm :public ggml_sycl_pool { 1778static const size_t SYCL_POOL_VMM_MAX_SIZE = 1ull <<35 ;// 32 GB 1779 1780int device ; 1781 sycl::context ctx ; 1782 sycl::device dev ; 1783 1784uintptr_t pool_addr = 0 ; 1785size_t pool_used = 0 ; 1786size_t pool_size = 0 ; 1787size_t granularity ; 1788 1789// physical_mem owns the commits (unlike cuMemMap) 1790struct mapping { 1791 sycl::ext::oneapi::experimental::physical_mem phys ; 1792void * map_ptr ; 1793 }; 1794 std::vector < mapping > mappings ; 1795 1796explicit ggml_sycl_pool_vmm (queue_ptr qptr_ ,int device_ ) : 1797device (device_ ), 1798ctx (qptr_ -> get_context ()), 1799dev (qptr_ -> get_device ()), 1800granularity (ggml_sycl_info ().devices [device_ ].vmm_granularity ) { 1801 } 1802 1803 ~ggml_sycl_pool_vmm () { 1804if (pool_addr == 0 ) { 1805return ; 1806 } 1807 1808// Per spec, unmap must (a) match the exact (ptr, size) of an earlier 1809// physical_mem::map() call and (b) precede destruction of the 1810// physical_mem objects (their dtors won't unmap). 1811for (auto & m :mappings ) { 1812SYCL_CHECK (CHECK_TRY_ERROR (sycl::ext::oneapi::experimental::unmap ( 1813m .map_ptr ,m .phys .size (),ctx ))); 1814 } 1815SYCL_CHECK (CHECK_TRY_ERROR (sycl::ext::oneapi::experimental::free_virtual_mem ( 1816pool_addr ,SYCL_POOL_VMM_MAX_SIZE ,ctx ))); 1817 } 1818 1819void * alloc (size_t size ,size_t * actual_size )override { 1820// round up the allocation size to the alignment to ensure that all allocations are aligned for all data types 1821size = GGML_PAD (size ,SYCL_BUFFER_ALIGNMENT ); 1822 1823size_t avail = pool_size - pool_used ; 1824 1825if (size > avail ) { 1826// round up to the next multiple of the granularity 1827size_t reserve_size = GGML_PAD (size - avail ,granularity ); 1828 1829GGML_ASSERT (pool_size + reserve_size <=SYCL_POOL_VMM_MAX_SIZE ); 1830 1831if (ggml_sycl_memtrace_enabled ()) { 1832GGML_LOG_INFO (GGML_SYCL_MEMTRACE_TAG " pool_vmm[%d] committing %5zu MiB (pool %5zu -> %5zu MiB)\n" , 1833device ,reserve_size / (1024 * 1024 ),pool_size / (1024 * 1024 ), 1834 (pool_size + reserve_size ) / (1024 * 1024 )); 1835ggml_sycl_memtrace_report ("before pool_vmm commit" ); 1836 } 1837 1838// allocate more physical memory 1839 std::optional < sycl::ext::oneapi::experimental::physical_mem > phys ; 1840SYCL_CHECK (CHECK_TRY_ERROR (phys .emplace (dev ,ctx ,reserve_size ))); 1841 1842// reserve virtual address space (if not already reserved) 1843if (pool_addr == 0 ) { 1844SYCL_CHECK (CHECK_TRY_ERROR ( 1845pool_addr = sycl::ext::oneapi::experimental::reserve_virtual_mem ( 1846SYCL_POOL_VMM_MAX_SIZE ,ctx ))); 1847 } 1848 1849// map at the end of the pool 1850void * map_ptr = nullptr ; 1851SYCL_CHECK (CHECK_TRY_ERROR ( 1852map_ptr = phys -> map (pool_addr + pool_size ,reserve_size , 1853 sycl::ext::oneapi::experimental::address_access_mode::read_write ))); 1854 1855// stash these so we could unmap this exact range in dtor 1856mappings .push_back ({ 1857 std::move (* phys ), 1858map_ptr , 1859 }); 1860 1861// add to the pool 1862pool_size += reserve_size ; 1863ggml_sycl_memtrace_add (GGML_SYCL_MEM_POOL_VMM ,map_ptr ,reserve_size ); 1864 1865#ifdef DEBUG_SYCL_MALLOC 1866GGML_LOG_INFO ("sycl pool[%d]: size increased to %llu MB (reserved %llu MB)\n" , 1867device , (unsigned long long ) (pool_size /1024 /1024 ), 1868 (unsigned long long ) (reserve_size /1024 /1024 )); 1869#endif 1870 } 1871 1872GGML_ASSERT (pool_addr != 0 ); 1873 1874void * ptr = reinterpret_cast < void *> (pool_addr + pool_used ); 1875* actual_size = size ; 1876pool_used += size ; 1877 1878#ifdef DEBUG_SYCL_MALLOC 1879GGML_LOG_INFO ("sycl pool[%d]: allocated %llu bytes at %p\n" ,device , (unsigned long long )size ,ptr ); 1880#endif 1881 1882return ptr ; 1883 } 1884 1885void free (void * ptr ,size_t size )override { 1886#ifdef DEBUG_SYCL_MALLOC 1887GGML_LOG_INFO ("sycl pool[%d]: freed %llu bytes at %p\n" ,device , (unsigned long long )size ,ptr ); 1888#endif 1889 1890pool_used -= size ; 1891 1892// all deallocations must be in reverse order of the allocations 1893GGML_ASSERT (ptr == reinterpret_cast < void *> (pool_addr + pool_used )); 1894 } 1895}; 1896#endif // defined(GGML_SYCL_SUPPORT_VMM) 1897 1898struct ggml_sycl_pool_host :public ggml_sycl_pool { 1899queue_ptr qptr ; 1900int device ; 1901 1902inline static int counter {0 }; 1903 1904struct ggml_sycl_buffer { 1905void * ptr = nullptr ; 1906size_t size = 0 ; 1907 }; 1908 1909// Set arbitrarly to 64 1910static constexpr int MAX_POOL_SIZE {64 }; 1911 std::vector < ggml_sycl_buffer > buffer_pool = std::vector < ggml_sycl_buffer > (MAX_POOL_SIZE ); 1912size_t pool_size = 0 ; 1913 1914explicit ggml_sycl_pool_host (queue_ptr qptr_ ,int device_ ) :qptr (qptr_ ),device (device_ ) {} 1915 1916 ~ggml_sycl_pool_host () { 1917for (int i = 0 ;i < MAX_POOL_SIZE ;++ i ) { 1918ggml_sycl_buffer & b = buffer_pool [i ]; 1919if (b .ptr != nullptr ) { 1920SYCL_CHECK (CHECK_TRY_ERROR (sycl::free (b .ptr ,* qptr ))); 1921b .ptr = nullptr ; 1922pool_size -= b .size ; 1923b .size = 0 ; 1924 } 1925 } 1926counter = 0 ; 1927 } 1928 1929void * alloc (size_t size ,size_t * actual_size )override { 1930if (counter == MAX_POOL_SIZE ) { 1931ggml_sycl_buffer b = buffer_pool [0 ]; 1932void * ptr = b .ptr ; 1933* actual_size = b .size ; 1934counter = 1 ; 1935return ptr ; 1936 } 1937ggml_sycl_buffer & b = buffer_pool [counter ]; 1938 1939if (b .ptr == nullptr ) { 1940void * ptr ; 1941 1942SYCL_CHECK (CHECK_TRY_ERROR (ptr = (void * ) sycl::malloc_host (size ,* qptr ))); 1943if (!ptr ) { 1944GGML_LOG_ERROR ("%s: can't allocate %zu Bytes of memory on host\n" ,__func__ ,size ); 1945return nullptr ; 1946 } 1947pool_size += size ; 1948* actual_size = size ; 1949counter = counter + 1 ; 1950return ptr ; 1951 }else { 1952++ counter ; 1953b .size = size ; 1954return b .ptr ; 1955 } 1956 } 1957 1958void free (void * ptr ,size_t size )override { 1959// if the pool is not completed add the pointer to it in place of the first nullptr found. 1960// Otherwise do nothing, pointers will be freed once the pool is deallocated. 1961for (int i = 0 ;i < MAX_POOL_SIZE ;++ i ) { 1962ggml_sycl_buffer & b = buffer_pool [i ]; 1963if (b .ptr == nullptr ) { 1964b .ptr = ptr ; 1965b .size = size ; 1966return ; 1967 } 1968 } 1969 } 1970}; 1971 1972std::unique_ptr < ggml_sycl_pool > ggml_backend_sycl_context::new_pool_for_host (queue_ptr qptr ,int device ) { 1973// return pool for the host to speed up memory management 1974return std::unique_ptr < ggml_sycl_pool > (new ggml_sycl_pool_host (qptr ,device )); 1975} 1976 1977std::unique_ptr < ggml_sycl_pool > ggml_backend_sycl_context::new_pool_for_device (queue_ptr qptr ,int device ) { 1978#if defined(GGML_SYCL_SUPPORT_VMM ) 1979if (g_ggml_sycl_enable_vmm && ggml_sycl_info ().devices [device ].vmm ) { 1980return std::unique_ptr < ggml_sycl_pool > (new ggml_sycl_pool_vmm (qptr ,device )); 1981 } 1982#endif // defined(GGML_SYCL_SUPPORT_VMM) 1983return std::unique_ptr < ggml_sycl_pool > (new ggml_sycl_pool_leg (qptr ,device )); 1984} 1985 1986 1987std::unique_ptr < ggml_sycl_fattn_kv_buffers > ggml_backend_sycl_context::new_fattn_kv_buffers (queue_ptr qptr ,int device ) { 1988return std::unique_ptr < ggml_sycl_fattn_kv_buffers > (new ggml_sycl_fattn_kv_buffers (qptr ,device )); 1989} 1990 1991/// kernels 1992typedef void (* ggml_sycl_op_mul_mat_t )( 1993ggml_backend_sycl_context & ctx , 1994const ggml_tensor * src0 ,const ggml_tensor * src1 ,ggml_tensor * dst , 1995const char * src0_dd_i ,const float * src1_ddf_i ,const char * src1_ddq_i , 1996float * dst_dd_i ,const int64_t row_low ,const int64_t row_high , 1997const int64_t src1_ncols ,const int64_t src1_padded_row_size , 1998const queue_ptr & stream ); 1999 2000 2001 2002static void mul_mat_p021_f16_f32 ( 2003const void * __restrict__vx ,const float * __restrict__y ,float * __restrict__dst , 2004const int ncols_x ,const int nrows_x ,const int nchannels_x ,const int nchannels_y , 2005const sycl::nd_item < 3 > & item_ct1 ) { 2006 2007const sycl::half * x = (const sycl::half * )vx ; 2008 2009const int row_x = item_ct1 .get_local_range (1 )* item_ct1 .get_group (1 )+ 2010item_ct1 .get_local_id (1 ); 2011const int channel = item_ct1 .get_local_range (0 )* item_ct1 .get_group (0 )+ 2012item_ct1 .get_local_id (0 ); 2013const int channel_x = channel / (nchannels_y /nchannels_x ); 2014 2015const int nrows_y = ncols_x ; 2016const int nrows_dst = nrows_x ; 2017const int row_dst = row_x ; 2018 2019float tmp = 0.0f ; 2020 2021for (int col_x0 = 0 ;col_x0 < ncols_x ; 2022col_x0 += item_ct1 .get_local_range (2 )) { 2023const int col_x = col_x0 + item_ct1 .get_local_id (2 ); 2024 2025if (col_x >=ncols_x ) { 2026break ; 2027 } 2028 2029// x is transposed and permuted 2030const int ix = row_x * nchannels_x * ncols_x + channel_x * ncols_x + col_x ; 2031const float xi = 2032 sycl::vec < sycl::half ,1 > (x [ix ]) 2033 .convert < float , sycl::rounding_mode::automatic > ()[0 ]; 2034 2035const int row_y = col_x ; 2036 2037 2038// y is not transposed but permuted 2039const int iy = channel * nrows_y + row_y ; 2040 2041tmp += xi * y [iy ]; 2042 } 2043 2044// dst is not transposed and not permuted 2045const int idst = channel * nrows_dst + row_dst ; 2046 2047// sum up partial sums and write back result 2048#pragma unroll 2049for (int mask = WARP_SIZE /2 ;mask > 0 ;mask >>=1 ) { 2050tmp += 2051 dpct::permute_sub_group_by_xor (item_ct1 .get_sub_group (),tmp ,mask ); 2052 } 2053 2054if (item_ct1 .get_local_id (2 )== 0 ) { 2055dst [idst ]= tmp ; 2056 } 2057} 2058 2059static void mul_mat_vec_nc_f16_f32 (// nc == non-contiguous 2060const void * __restrict__vx ,const float * __restrict__y ,float * __restrict__dst ,const int ncols_x ,const int nrows_x , 2061const int row_stride_x ,const int channel_stride_x ,const int channel_stride_y ,const int channel_x_divisor , 2062const sycl::nd_item < 3 > & item_ct1 ) { 2063 2064const sycl::half * x = (const sycl::half * )vx ; 2065 2066const int row_x = item_ct1 .get_local_range (1 )* item_ct1 .get_group (1 )+ 2067item_ct1 .get_local_id (1 ); 2068const int channel = item_ct1 .get_local_range (0 )* item_ct1 .get_group (0 )+ 2069item_ct1 .get_local_id (0 ); 2070const int channel_x = channel /channel_x_divisor ; 2071 2072const int nrows_dst = nrows_x ; 2073const int row_dst = row_x ; 2074 2075const int idst = channel * nrows_dst + row_dst ; 2076 2077float tmp = 0.0f ; 2078 2079for (int col_x0 = 0 ;col_x0 < ncols_x ; 2080col_x0 += item_ct1 .get_local_range (2 )) { 2081const int col_x = col_x0 + item_ct1 .get_local_id (2 ); 2082 2083if (col_x >=ncols_x ) { 2084break ; 2085 } 2086 2087const int row_y = col_x ; 2088 2089const int ix = channel_x * channel_stride_x + row_x * row_stride_x + col_x ; 2090const int iy = channel * channel_stride_y + row_y ; 2091 2092const float xi = 2093 sycl::vec < sycl::half ,1 > (x [ix ]) 2094 .convert < float , sycl::rounding_mode::automatic > ()[0 ]; 2095 2096tmp += xi * y [iy ]; 2097 } 2098 2099// sum up partial sums and write back result 2100#pragma unroll 2101for (int mask = WARP_SIZE /2 ;mask > 0 ;mask >>=1 ) { 2102tmp += 2103 dpct::permute_sub_group_by_xor (item_ct1 .get_sub_group (),tmp ,mask ); 2104 } 2105 2106if (item_ct1 .get_local_id (2 )== 0 ) { 2107dst [idst ]= tmp ; 2108 } 2109} 2110 2111static void k_sum_rows_f32 (const float * x ,float * dst ,const int ncols , 2112const sycl::nd_item < 3 > & item_ct1 ) { 2113const int row = item_ct1 .get_group (1 ); 2114const int col = item_ct1 .get_local_id (2 ); 2115 2116float sum = 0.0f ; 2117for (int i = col ;i < ncols ;i += item_ct1 .get_local_range (2 )) { 2118sum += x [row * ncols + i ]; 2119 } 2120 2121sum = warp_reduce_sum (sum ,item_ct1 ); 2122 2123if (col == 0 ) { 2124dst [row ]= sum ; 2125 } 2126} 2127 2128 2129template < typename T > 2130static inline void ggml_sycl_swap (T & a ,T & b ) { 2131T tmp = a ; 2132a = b ; 2133b = tmp ; 2134} 2135 2136template < ggml_sort_order order > 2137__dpct_inline__ static void 2138k_argsort_f32_i32 (const float * x ,int * dst ,const int ncols ,int ncols_pad , 2139const int tasks_per_thread ,const sycl::nd_item < 3 > & item_ct1 , 2140uint8_t * dpct_local ) { 2141// bitonic sort 2142int col_index = item_ct1 .get_local_id (2 ); 2143int row = item_ct1 .get_group (1 ); 2144 2145for (int i = 0 ;i < tasks_per_thread ;i ++ ) { 2146int col = col_index * tasks_per_thread + i ; 2147if (col >=ncols_pad ) { 2148return ; 2149 } 2150 } 2151 2152const float * x_row = x + row * ncols ; 2153auto dst_row = (int * )dpct_local ; 2154 2155// initialize indices 2156for (int i = 0 ;i < tasks_per_thread ;i ++ ){ 2157int col = col_index * tasks_per_thread + i ; 2158dst_row [col ]= col ; 2159 } 2160 2161item_ct1 .barrier (sycl::access::fence_space::local_space ); 2162 2163for (int k = 2 ;k <=ncols_pad ;k *=2 ) { 2164for (int j = k /2 ;j > 0 ;j /=2 ) { 2165for (int i = 0 ;i < tasks_per_thread ;i ++ ) { 2166int col = col_index * tasks_per_thread + i ; 2167int ixj = col ^j ; 2168if (ixj > col ) { 2169if ((col & k )== 0 ) { 2170if (dst_row [col ] >=ncols || 2171 (dst_row [ixj ]< ncols && 2172 (order == GGML_SORT_ORDER_ASC 2173 ?x_row [dst_row [col ]]> x_row [dst_row [ixj ]] 2174 :x_row [dst_row [col ]]< 2175x_row [dst_row [ixj ]]))) { 2176ggml_sycl_swap (dst_row [col ],dst_row [ixj ]); 2177 } 2178 }else { 2179if (dst_row [ixj ] >=ncols || 2180 (dst_row [col ]< ncols && 2181 (order == GGML_SORT_ORDER_ASC 2182 ?x_row [dst_row [col ]]< x_row [dst_row [ixj ]] 2183 :x_row [dst_row [col ]]> 2184x_row [dst_row [ixj ]]))) { 2185ggml_sycl_swap (dst_row [col ],dst_row [ixj ]); 2186 } 2187 } 2188 } 2189item_ct1 .barrier (sycl::access::fence_space::local_space ); 2190 } 2191 } 2192 } 2193 2194// copy the result to dst without the padding 2195for (int i = 0 ;i < tasks_per_thread ;i ++ ) { 2196int col = col_index * tasks_per_thread + i ; 2197if (col < ncols ) { 2198dst [row * ncols + col ]= dst_row [col ]; 2199 } 2200 } 2201} 2202 2203static void diag_mask_inf_f32 (const float * x ,float * dst ,const int ncols ,const int rows_per_channel ,const int n_past , 2204const sycl::nd_item < 3 > & item_ct1 ) { 2205const int col = item_ct1 .get_local_range (1 )* item_ct1 .get_group (1 )+ 2206item_ct1 .get_local_id (1 ); 2207const int row = item_ct1 .get_local_range (2 )* item_ct1 .get_group (2 )+ 2208item_ct1 .get_local_id (2 ); 2209 2210if (col >=ncols ) { 2211return ; 2212 } 2213 2214const int i = row * ncols + col ; 2215//dst[i] = col > (n_past + row % rows_per_channel) ? -INFINITY : x[i]; 2216//dst[i] = x[i] - (col > n_past + row % rows_per_channel) * INT_MAX; // equivalent within rounding error but slightly faster on GPU 2217dst [i ]= x [i ]- (col > n_past + row %rows_per_channel )* FLT_MAX ; 2218} 2219 2220static void scale_f32 (const float * x ,float * dst ,const float scale ,const float bias ,const int k , 2221const sycl::nd_item < 3 > & item_ct1 ) { 2222const int i = item_ct1 .get_local_range (2 )* item_ct1 .get_group (2 )+ 2223item_ct1 .get_local_id (2 ); 2224 2225if (i >=k ) { 2226return ; 2227 } 2228 2229dst [i ]= scale * x [i ]+ bias ; 2230} 2231 2232 2233static void ggml_mul_mat_p021_f16_f32_sycl (const void * vx ,const float * y , 2234float * dst ,const int ncols_x , 2235const int nrows_x , 2236const int nchannels_x , 2237const int nchannels_y , 2238queue_ptr stream ) { 2239 2240const sycl::range < 3 > block_nums (nchannels_y ,nrows_x ,1 ); 2241const sycl::range < 3 > block_dims (1 ,1 ,WARP_SIZE ); 2242 { 2243 dpct::has_capability_or_fail (stream -> get_device (), 2244 {sycl::aspect::fp16 }); 2245 2246stream -> parallel_for ( 2247 sycl::nd_range < 3 > (block_nums * block_dims ,block_dims ), 2248 [= ](sycl::nd_item < 3 > item_ct1 ) [[sycl ::reqd_sub_group_size (WARP_SIZE )]] { 2249mul_mat_p021_f16_f32 (vx ,y ,dst ,ncols_x ,nrows_x ,nchannels_x , 2250nchannels_y ,item_ct1 ); 2251 }); 2252 } 2253} 2254 2255static void ggml_mul_mat_vec_nc_f16_f32_sycl ( 2256const void * vx ,const float * y ,float * dst ,const int ncols_x , 2257const int nrows_x ,const int row_stride_x ,const int nchannels_x , 2258const int nchannels_y ,const int channel_stride_x ,const int channel_stride_y ,queue_ptr stream ) { 2259 2260const sycl::range < 3 > block_nums (nchannels_y ,nrows_x ,1 ); 2261const sycl::range < 3 > block_dims (1 ,1 ,WARP_SIZE ); 2262 { 2263 dpct::has_capability_or_fail (stream -> get_device (), 2264 {sycl::aspect::fp16 }); 2265 2266stream -> parallel_for ( 2267 sycl::nd_range < 3 > (block_nums * block_dims ,block_dims ), 2268 [= ](sycl::nd_item < 3 > item_ct1 ) [[sycl ::reqd_sub_group_size (WARP_SIZE )]] { 2269mul_mat_vec_nc_f16_f32 (vx ,y ,dst ,ncols_x ,nrows_x , 2270row_stride_x ,channel_stride_x ,channel_stride_y , 2271nchannels_y /nchannels_x ,item_ct1 ); 2272 }); 2273 } 2274} 2275 2276 2277 2278static void scale_f32_sycl (const float * x ,float * dst ,const float scale ,const float bias , 2279const int k ,queue_ptr stream ) { 2280const int num_blocks = (k + SYCL_SCALE_BLOCK_SIZE - 1 ) /SYCL_SCALE_BLOCK_SIZE ; 2281stream -> parallel_for ( 2282 sycl::nd_range < 3 > (sycl::range < 3 > (1 ,1 ,num_blocks )* 2283 sycl::range < 3 > (1 ,1 ,SYCL_SCALE_BLOCK_SIZE ), 2284 sycl::range < 3 > (1 ,1 ,SYCL_SCALE_BLOCK_SIZE )), 2285 [= ](sycl::nd_item < 3 > item_ct1 ) { 2286scale_f32 (x ,dst ,scale ,bias ,k ,item_ct1 ); 2287 }); 2288} 2289 2290 2291static void sum_rows_f32_sycl (const float * x ,float * dst ,const int ncols , 2292const int nrows ,queue_ptr stream ) { 2293const sycl::range < 3 > block_dims (1 ,1 ,WARP_SIZE ); 2294const sycl::range < 3 > block_nums (1 ,nrows ,1 ); 2295stream -> parallel_for (sycl::nd_range < 3 > (block_nums * block_dims ,block_dims ), 2296 [= ](sycl::nd_item < 3 > item_ct1 ) 2297 [[sycl ::reqd_sub_group_size (WARP_SIZE )]] { 2298k_sum_rows_f32 (x ,dst ,ncols ,item_ct1 ); 2299 }); 2300} 2301 2302static int next_power_of_2 (int x ) { 2303int n = 1 ; 2304while (n < x ) { 2305n *=2 ; 2306 } 2307return n ; 2308} 2309 2310static void init_argsort_indices_padded ( 2311int * idx , 2312const int nrows , 2313const int ncols_pad , 2314const sycl::nd_item < 1 > & item_ct1 ) { 2315const size_t gid = item_ct1 .get_local_range (0 )* item_ct1 .get_group (0 )+ item_ct1 .get_local_id (0 ); 2316const size_t total = (size_t )nrows * (size_t )ncols_pad ; 2317 2318if (gid >=total ) { 2319return ; 2320 } 2321 2322idx [gid ]= (int ) (gid % (size_t )ncols_pad ); 2323} 2324 2325template < ggml_sort_order order > 2326static void argsort_f32_i32_global_pass (const float * x , 2327int * idx , 2328const int ncols , 2329const int nrows , 2330const int ncols_pad , 2331const int j , 2332const int k , 2333const sycl::nd_item < 1 > & item_ct1 ) { 2334const size_t gid = item_ct1 .get_local_range (0 )* item_ct1 .get_group (0 )+ item_ct1 .get_local_id (0 ); 2335const size_t total = (size_t )nrows * (size_t )ncols_pad ; 2336 2337if (gid >=total ) { 2338return ; 2339 } 2340 2341const int row = (int ) (gid / (size_t )ncols_pad ); 2342const int col = (int ) (gid % (size_t )ncols_pad ); 2343const int ixj = col ^j ; 2344 2345if (ixj <=col || ixj >=ncols_pad ) { 2346return ; 2347 } 2348 2349const size_t base = (size_t )row * (size_t )ncols_pad ; 2350const size_t pos_a = base + (size_t )col ; 2351const size_t pos_b = base + (size_t )ixj ; 2352 2353const int a = idx [pos_a ]; 2354const int b = idx [pos_b ]; 2355 2356bool do_swap = false; 2357 2358if ((col & k )== 0 ) { 2359if (a >=ncols || 2360 (b < ncols && 2361 (order == GGML_SORT_ORDER_ASC ? 2362x [(size_t )row * (size_t )ncols + (size_t )a ]> x [(size_t )row * (size_t )ncols + (size_t )b ] : 2363x [(size_t )row * (size_t )ncols + (size_t )a ]< x [(size_t )row * (size_t )ncols + (size_t )b ]))) { 2364do_swap = true; 2365 } 2366 }else { 2367if (b >=ncols || 2368 (a < ncols && 2369 (order == GGML_SORT_ORDER_ASC ? 2370x [(size_t )row * (size_t )ncols + (size_t )a ]< x [(size_t )row * (size_t )ncols + (size_t )b ] : 2371x [(size_t )row * (size_t )ncols + (size_t )a ]> x [(size_t )row * (size_t )ncols + (size_t )b ]))) { 2372do_swap = true; 2373 } 2374 } 2375 2376if (do_swap ) { 2377idx [pos_a ]= b ; 2378idx [pos_b ]= a ; 2379 } 2380} 2381 2382static void copy_argsort_indices_unpadded (const int * idx_padded , 2383int * dst , 2384const int nrows , 2385const int ncols , 2386const int ncols_pad , 2387const sycl::nd_item < 1 > & item_ct1 ) { 2388const size_t gid = item_ct1 .get_local_range (0 )* item_ct1 .get_group (0 )+ item_ct1 .get_local_id (0 ); 2389const size_t total = (size_t )nrows * (size_t )ncols ; 2390 2391if (gid >=total ) { 2392return ; 2393 } 2394 2395const int row = (int ) (gid / (size_t )ncols ); 2396const int col = (int ) (gid % (size_t )ncols ); 2397 2398dst [(size_t )row * (size_t )ncols + (size_t )col ]= idx_padded [(size_t )row * (size_t )ncols_pad + (size_t )col ]; 2399} 2400 2401static void argsort_f32_i32_sycl (const float * x ,int * dst ,const int ncols , 2402const int nrows ,ggml_sort_order order , 2403queue_ptr stream ,int device ,ggml_sycl_pool & pool ) { 2404// bitonic sort requires ncols to be power of 2 2405const int ncols_pad = next_power_of_2 (ncols ); 2406const size_t shared_mem = (size_t )ncols_pad * sizeof (int ); 2407const size_t smpbo = ggml_sycl_info ().devices [device ].smpbo ; 2408 2409if (shared_mem > smpbo ) { 2410ggml_sycl_pool_alloc < int > idx_padded_alloc (pool , (size_t )nrows * (size_t )ncols_pad ); 2411int * idx_padded = idx_padded_alloc .get (); 2412 2413constexpr size_t block_size = 256 ; 2414const size_t total_padded = (size_t )nrows * (size_t )ncols_pad ; 2415const size_t nblocks_padded = (total_padded + block_size - 1 ) /block_size ; 2416 2417stream -> parallel_for ( 2418 sycl::nd_range < 1 > (sycl::range < 1 > (nblocks_padded * block_size ), sycl::range < 1 > (block_size )), 2419 [= ](sycl::nd_item < 1 > item_ct1 ) {init_argsort_indices_padded (idx_padded ,nrows ,ncols_pad ,item_ct1 ); }); 2420 2421for (int k = 2 ;k <=ncols_pad ;k *=2 ) { 2422for (int j = k /2 ;j > 0 ;j /=2 ) { 2423if (order == GGML_SORT_ORDER_ASC ) { 2424stream -> parallel_for ( 2425 sycl::nd_range < 1 > (sycl::range < 1 > (nblocks_padded * block_size ), sycl::range < 1 > (block_size )), 2426 [= ](sycl::nd_item < 1 > item_ct1 ) { 2427argsort_f32_i32_global_pass < GGML_SORT_ORDER_ASC > (x ,idx_padded ,ncols ,nrows ,ncols_pad ,j , 2428k ,item_ct1 ); 2429 }); 2430 }else if (order == GGML_SORT_ORDER_DESC ) { 2431stream -> parallel_for ( 2432 sycl::nd_range < 1 > (sycl::range < 1 > (nblocks_padded * block_size ), sycl::range < 1 > (block_size )), 2433 [= ](sycl::nd_item < 1 > item_ct1 ) { 2434argsort_f32_i32_global_pass < GGML_SORT_ORDER_DESC > (x ,idx_padded ,ncols ,nrows ,ncols_pad ,j , 2435k ,item_ct1 ); 2436 }); 2437 }else { 2438GGML_ABORT ("invalid sort order" ); 2439 } 2440 } 2441 } 2442 2443const size_t total = (size_t )nrows * (size_t )ncols ; 2444const size_t nblocks = (total + block_size - 1 ) /block_size ; 2445stream -> parallel_for (sycl::nd_range < 1 > (sycl::range < 1 > (nblocks * block_size ), sycl::range < 1 > (block_size )), 2446 [= ](sycl::nd_item < 1 > item_ct1 ) { 2447copy_argsort_indices_unpadded (idx_padded ,dst ,nrows ,ncols ,ncols_pad ,item_ct1 ); 2448 }); 2449 2450return ; 2451 } 2452 2453int nth = 1 ; 2454int max_block_size = ggml_sycl_info ().max_work_group_sizes [device ]; 2455while (nth < ncols_pad && nth < max_block_size ) 2456nth *=2 ; 2457if (nth > max_block_size ) 2458nth = max_block_size ; 2459 2460const int tasks_per_thread = ncols_pad /nth ; 2461 2462const sycl::range < 3 > block_dims (1 ,1 ,nth ); 2463const sycl::range < 3 > block_nums (1 ,nrows ,1 ); 2464 2465if (order == GGML_SORT_ORDER_ASC ) { 2466stream -> submit ([& ](sycl::handler & cgh ) { 2467 sycl::local_accessor < uint8_t ,1 > dpct_local_acc_ct1 ( 2468 sycl::range < 1 > (shared_mem ),cgh ); 2469 2470cgh .parallel_for ( 2471 sycl::nd_range < 3 > (block_nums * block_dims ,block_dims ), 2472 [= ](sycl::nd_item < 3 > item_ct1 ) { 2473k_argsort_f32_i32 < GGML_SORT_ORDER_ASC > ( 2474x ,dst ,ncols ,ncols_pad ,tasks_per_thread ,item_ct1 , 2475dpct_local_acc_ct1 2476 .get_multi_ptr < sycl::access::decorated::no > () 2477 .get ()); 2478 }); 2479 }); 2480 }else if (order == GGML_SORT_ORDER_DESC ) { 2481stream -> submit ([& ](sycl::handler & cgh ) { 2482 sycl::local_accessor < uint8_t ,1 > dpct_local_acc_ct1 ( 2483 sycl::range < 1 > (shared_mem ),cgh ); 2484 2485cgh .parallel_for ( 2486 sycl::nd_range < 3 > (block_nums * block_dims ,block_dims ), 2487 [= ](sycl::nd_item < 3 > item_ct1 ) { 2488k_argsort_f32_i32 < GGML_SORT_ORDER_DESC > ( 2489x ,dst ,ncols ,ncols_pad ,tasks_per_thread ,item_ct1 , 2490dpct_local_acc_ct1 2491 .get_multi_ptr < sycl::access::decorated::no > () 2492 .get ()); 2493 }); 2494 }); 2495 }else { 2496GGML_ABORT ("fatal error" ); 2497 } 2498} 2499 2500// Scan and block merge, shared by every launch shape below so a partitioned row uses the 2501// same insertion order as an unpartitioned one. 2502// 2503// src_map != nullptr: report src_map[col] instead of col, so a merge pass can carry the 2504// original column index through. 2505// out_vals != nullptr: also emit the k winning values, for a later merge pass. 2506// swap01: emit in the output order the single-pass path uses. 2507static void top_k_scan_merge_f32 ( 2508const float * src_vals , 2509const int32_t * src_map , 2510const int begin , 2511const int end , 2512const int k , 2513const int block_size , 2514float * shared_vals , 2515int * shared_idx , 2516float * out_vals , 2517int32_t * out_idx , 2518const bool swap01 , 2519const sycl::nd_item < 1 > & item_ct1 2520) { 2521const int tid = item_ct1 .get_local_id (0 ); 2522 2523// The running top-k lives in SLM (shared local memory) rather than a private array: 2524// an array indexed by a runtime position cannot be register-allocated, so a private 2525// one lands in scratch, i.e. device memory, and insertion is this kernel's dominant 2526// cost. 2527// 2528// Lane-strided (lv[i * block_size]) rather than lane-blocked (lv[i]) so a given i is 2529// contiguous across lanes; a k-strided layout would put every lane of a shift step in 2530// the same SLM bank. 2531float * lv = shared_vals + tid ; 2532int * li = shared_idx + tid ; 2533 2534for (int i = 0 ;i < k ;i ++ ) { 2535lv [i * block_size ]= - FLT_MAX ; 2536li [i * block_size ]= -1 ; 2537 } 2538 2539// The k-th best, cached in a register. The reject test is taken for the large 2540// majority of elements scanned, and in that case touches no memory. 2541float kth = - FLT_MAX ; 2542 2543for (int col = begin + tid ;col < end ;col += block_size ) { 2544float val = src_vals [col ]; 2545 2546if (val > kth ) { 2547int pos = k - 1 ; 2548while (pos > 0 && val > lv [(pos - 1 )* block_size ]) { 2549pos -- ; 2550 } 2551 2552for (int i = k - 1 ;i > pos ;i -- ) { 2553lv [i * block_size ]= lv [(i - 1 )* block_size ]; 2554li [i * block_size ]= li [(i - 1 )* block_size ]; 2555 } 2556lv [pos * block_size ]= val ; 2557li [pos * block_size ]= src_map ?src_map [col ] :col ; 2558 2559kth = lv [(k - 1 )* block_size ]; 2560 } 2561 } 2562 2563item_ct1 .barrier (sycl::access::fence_space::local_space ); 2564 2565if (tid != 0 ) { 2566return ; 2567 } 2568 2569// Same treatment for the merge accumulator, past the per-lane region. 2570float * fv = shared_vals + (size_t )k * block_size ; 2571int * fi = shared_idx + (size_t )k * block_size ; 2572 2573for (int i = 0 ;i < k ;i ++ ) { 2574fv [i ]= - FLT_MAX ; 2575fi [i ]= -1 ; 2576 } 2577 2578float fkth = - FLT_MAX ; 2579 2580// Candidates are visited in the same (t, i) order as before, so tie-breaking is 2581// unchanged. 2582for (int t = 0 ;t < block_size ;t ++ ) { 2583for (int i = 0 ;i < k ;i ++ ) { 2584float val = shared_vals [i * block_size + t ]; 2585 2586if (val <=fkth ) { 2587// Lane t's list is sorted descending, so once one of its entries loses 2588// to the k-th best, every later entry loses too. fkth only rises, so 2589// that stays true for the rest of the merge. This turns the merge from 2590// block_size*k steps into roughly block_size plus the candidates 2591// accepted. 2592break ; 2593 } 2594 2595int idx = shared_idx [i * block_size + t ]; 2596 2597int pos = k - 1 ; 2598while (pos > 0 && val > fv [pos - 1 ]) { 2599pos -- ; 2600 } 2601 2602for (int j = k - 1 ;j > pos ;j -- ) { 2603fv [j ]= fv [j - 1 ]; 2604fi [j ]= fi [j - 1 ]; 2605 } 2606fv [pos ]= val ; 2607fi [pos ]= idx ; 2608 2609fkth = fv [k - 1 ]; 2610 } 2611 } 2612 2613if (out_vals ) { 2614for (int i = 0 ;i < k ;i ++ ) { 2615out_vals [i ]= fv [i ]; 2616 } 2617 } 2618 2619for (int i = 0 ;i < k ;i ++ ) { 2620out_idx [i ]= fi [i ]; 2621 } 2622 2623if (swap01 && k > 1 ) { 2624int32_t temp = out_idx [0 ]; 2625out_idx [0 ]= out_idx [1 ]; 2626out_idx [1 ]= temp ; 2627 } 2628} 2629 2630static void top_k_f32_sycl ( 2631ggml_backend_sycl_context & ctx , 2632const float * src , 2633int32_t * dst_indices , 2634const int64_t ncols , 2635const int64_t nrows , 2636const int k , 2637 dpct::queue_ptr main_stream 2638) { 2639// A row is scanned by exactly one work-group, so a vocabulary-sized row leaves the 2640// rest of the device idle. What the scan is short of is memory requests in flight, 2641// not bandwidth or per-request latency, so lanes in flight is the lever: split the 2642// row across independent work-groups, have each emit its partition's top-k, and 2643// merge those nsplit*k candidates in a second launch. 2644// 2645// split_block trades parallelism against SLM residency. Its cost is 2646// (split_block + 1) * k * 8 bytes of SLM per group, so at the k <= 32 ceiling 128 2647// lanes need about 33 KB, which leaves a single resident group per Xe-core. Revisit 2648// if the supported k ever grows. 2649constexpr int split_block = 128 ; 2650constexpr int max_splits = 128 ; 2651constexpr int min_cols = 8192 ; 2652 2653int nsplit = 1 ; 2654if (ncols >=min_cols ) { 2655// A partition is then always >= split_block = 128 columns, hence always more than 2656// the k <= 32 ceiling, so no pass is ever padded with -FLT_MAX sentinels. 2657const int64_t want = ncols /split_block ; 2658nsplit = (int ) (want > max_splits ?max_splits :want ); 2659 } 2660 2661if (nsplit > 1 ) { 2662const int nchunk = (int ) ((ncols + nsplit - 1 ) /nsplit ); 2663const size_t ncand = (size_t )nrows * nsplit * k ; 2664 2665ggml_sycl_pool_alloc < float > part_vals (ctx .pool (),ncand ); 2666ggml_sycl_pool_alloc < int32_t > part_idx (ctx .pool (),ncand ); 2667 2668float * pv = part_vals .get (); 2669int32_t * pi = part_idx .get (); 2670 2671const sycl::range < 1 > block_dims (split_block ); 2672 2673main_stream -> submit ([& ](sycl::handler & cgh ) { 2674 sycl::local_accessor < float ,1 > shared_vals (sycl::range < 1 > ((split_block + 1 )* k ),cgh ); 2675 sycl::local_accessor < int ,1 > shared_idx (sycl::range < 1 > ((split_block + 1 )* k ),cgh ); 2676 2677cgh .parallel_for ( 2678 sycl::nd_range < 1 > (sycl::range < 1 > (nrows * nsplit )* block_dims ,block_dims ), 2679 [= ](sycl::nd_item < 1 > item_ct1 ) { 2680const int grp = item_ct1 .get_group (0 ); 2681const int row = grp /nsplit ; 2682const int part = grp %nsplit ; 2683 2684const int begin = part * nchunk ; 2685int end = begin + nchunk ; 2686if (end > (int )ncols ) { 2687end = (int )ncols ; 2688 } 2689 2690top_k_scan_merge_f32 ( 2691src + (int64_t )row * ncols ,nullptr ,begin ,end ,k ,split_block , 2692shared_vals .get_multi_ptr < sycl::access::decorated::no > ().get (), 2693shared_idx .get_multi_ptr < sycl::access::decorated::no > ().get (), 2694pv + (size_t )grp * k ,pi + (size_t )grp * k , false,item_ct1 ); 2695 }); 2696 }); 2697 2698main_stream -> submit ([& ](sycl::handler & cgh ) { 2699 sycl::local_accessor < float ,1 > shared_vals (sycl::range < 1 > ((split_block + 1 )* k ),cgh ); 2700 sycl::local_accessor < int ,1 > shared_idx (sycl::range < 1 > ((split_block + 1 )* k ),cgh ); 2701 2702cgh .parallel_for ( 2703 sycl::nd_range < 1 > (sycl::range < 1 > (nrows )* block_dims ,block_dims ), 2704 [= ](sycl::nd_item < 1 > item_ct1 ) { 2705const int row = item_ct1 .get_group (0 ); 2706const size_t off = (size_t )row * nsplit * k ; 2707 2708top_k_scan_merge_f32 ( 2709pv + off ,pi + off ,0 ,nsplit * k ,k ,split_block , 2710shared_vals .get_multi_ptr < sycl::access::decorated::no > ().get (), 2711shared_idx .get_multi_ptr < sycl::access::decorated::no > ().get (), 2712nullptr ,dst_indices + (int64_t )row * k , true,item_ct1 ); 2713 }); 2714 }); 2715 2716return ; 2717 } 2718 2719const int block_size = 128 ; 2720 2721const sycl::range < 1 > block_dims (block_size ); 2722const sycl::range < 1 > grid_dims (nrows ); 2723 2724main_stream -> submit ([& ](sycl::handler & cgh ) { 2725 sycl::local_accessor < float ,1 > shared_vals (sycl::range < 1 > ((block_size + 1 )* k ),cgh ); 2726 sycl::local_accessor < int ,1 > shared_idx (sycl::range < 1 > ((block_size + 1 )* k ),cgh ); 2727 2728cgh .parallel_for ( 2729 sycl::nd_range < 1 > (grid_dims * block_dims ,block_dims ), 2730 [= ](sycl::nd_item < 1 > item_ct1 ) { 2731const int row = item_ct1 .get_group (0 ); 2732 2733if (row >=nrows )return ; 2734 2735top_k_scan_merge_f32 ( 2736src + (int64_t )row * ncols ,nullptr ,0 , (int )ncols ,k ,block_size , 2737shared_vals .get_multi_ptr < sycl::access::decorated::no > ().get (), 2738shared_idx .get_multi_ptr < sycl::access::decorated::no > ().get (), 2739nullptr ,dst_indices + (int64_t )row * k , true,item_ct1 ); 2740 }); 2741 }); 2742} 2743 2744static void argmax_f32_i32_sycl (const float * x ,int * dst ,const int ncols , 2745const int nrows ,queue_ptr stream ) { 2746const sycl::range < 3 > block_dims (1 ,1 ,SYCL_ARGMAX_BLOCK_SIZE ); 2747const sycl::range < 3 > block_nums (1 ,nrows ,1 ); 2748const size_t shared_mem = 256 * sizeof (float ); 2749 2750stream -> submit ([& ](sycl::handler & cgh ) { 2751 sycl::local_accessor < float ,1 > shared_data ( 2752 sycl::range < 1 > (shared_mem /sizeof (float )),cgh ); 2753 sycl::local_accessor < int ,1 > shared_indices ( 2754 sycl::range < 1 > (shared_mem /sizeof (float )),cgh ); 2755 2756cgh .parallel_for ( 2757 sycl::nd_range < 3 > (block_nums * block_dims ,block_dims ), 2758 [= ](sycl::nd_item < 3 > item_ct1 ) { 2759const int tid = item_ct1 .get_local_id (2 ); 2760const int row = item_ct1 .get_global_id (1 ); 2761 2762float max_val = - INFINITY ; 2763int max_idx = -1 ; 2764 2765for (int col = tid ;col < ncols ;col += 256 ) { 2766float val = x [row * ncols + col ]; 2767if (val > max_val ) { 2768max_val = val ; 2769max_idx = col ; 2770 } 2771 } 2772 2773shared_data [tid ]= max_val ; 2774shared_indices [tid ]= max_idx ; 2775item_ct1 .barrier (sycl::access::fence_space::local_space ); 2776 2777for (int stride = 256 /2 ;stride > 0 ;stride >>=1 ) { 2778if (tid < stride ) { 2779float val1 = shared_data [tid ]; 2780float val2 = shared_data [tid + stride ]; 2781if (val2 > val1 ) { 2782shared_data [tid ]= val2 ; 2783shared_indices [tid ]= shared_indices [tid + stride ]; 2784 } 2785 } 2786item_ct1 .barrier (sycl::access::fence_space::local_space ); 2787 } 2788 2789 2790if (tid == 0 ) { 2791dst [row ]= shared_indices [0 ]; 2792 } 2793 }); 2794 }); 2795} 2796static void diag_mask_inf_f32_sycl (const float * x ,float * dst , 2797const int ncols_x ,const int nrows_x , 2798const int rows_per_channel ,const int n_past , 2799queue_ptr stream ) { 2800const sycl::range < 3 > block_dims (1 ,SYCL_DIAG_MASK_INF_BLOCK_SIZE ,1 ); 2801const int block_num_x = (ncols_x + SYCL_DIAG_MASK_INF_BLOCK_SIZE - 1 ) /SYCL_DIAG_MASK_INF_BLOCK_SIZE ; 2802const sycl::range < 3 > block_nums (1 ,block_num_x ,nrows_x ); 2803stream -> parallel_for (sycl::nd_range < 3 > (block_nums * block_dims ,block_dims ), 2804 [= ](sycl::nd_item < 3 > item_ct1 ) { 2805diag_mask_inf_f32 (x ,dst ,ncols_x , 2806rows_per_channel ,n_past , 2807item_ct1 ); 2808 }); 2809} 2810 2811static dpct::err0 ggml_sycl_cpy_tensor_2d (void * dst , 2812const struct ggml_tensor * src , 2813int64_t i3 ,int64_t i2 , 2814int64_t i1_low ,int64_t i1_high , 2815queue_ptr stream )try { 2816 2817 dpct::memcpy_direction kind ; 2818char * src_ptr ; 2819if (ggml_backend_buffer_is_host (src -> buffer )) { 2820kind = dpct::host_to_device ; 2821//GGML_SYCL_DEBUG("%s: Host buffer type src tensor\n", __func__); 2822src_ptr = (char * )src -> data ; 2823// GGML_SYCL_DEBUG("ggml_sycl_cpy_tensor_2d GGML_BACKEND_TYPE_CPU src_ptr %p\n", src_ptr); 2824 }else if (ggml_backend_buffer_is_sycl (src -> buffer )) { 2825// If buffer is a SYCL buffer 2826//GGML_SYCL_DEBUG("%s: SYCL buffer type src tensor\n", __func__); 2827kind = dpct::device_to_device ; 2828src_ptr = (char * )src -> data ; 2829 }else if (ggml_backend_buffer_is_sycl_split (src -> buffer )) { 2830/* 2831If buffer is a SYCL split buffer 2832*/ 2833//GGML_SYCL_DEBUG("%s: Split buffer type src tensor\n", __func__); 2834GGML_ASSERT (i1_low == 0 && i1_high == src -> ne [1 ]); 2835kind = dpct::device_to_device ; 2836ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu * )src -> extra ; 2837int id ; 2838SYCL_CHECK (CHECK_TRY_ERROR ( 2839id = get_current_device_id ())); 2840// GGML_SYCL_DEBUG("current device index %d\n", id); 2841src_ptr = (char * )extra -> data_device [id ]; 2842 }else { 2843// GGML_SYCL_DEBUG("GGML_ABORT("fatal error")\n"); 2844GGML_ABORT ("fatal error" ); 2845 } 2846char * dst_ptr = (char * )dst ; 2847 2848GGML_TENSOR_LOCALS_1 (int64_t ,ne ,src ,ne ); 2849GGML_TENSOR_LOCALS (int64_t ,nb ,src ,nb ); 2850const enum ggml_type type = src -> type ; 2851const int64_t ts = ggml_type_size (type ); 2852const int64_t bs = ggml_blck_size (type ); 2853int64_t i1_diff = i1_high - i1_low ; 2854 2855const char * x = src_ptr + i1_low * nb1 + i2 * nb2 + i3 * nb3 ; 2856if (nb0 == ts && nb1 == ts * ne0 /bs ) { 2857// GGML_SYCL_DEBUG("stream->memcpy: dst_ptr=%p, x=%p, size=%lu\n", dst_ptr, x, i1_diff * nb1); 2858// return CHECK_TRY_ERROR(stream->memcpy(dst_ptr, x, i1_diff * nb1)); 2859return CHECK_TRY_ERROR (dpct::async_dpct_memcpy (dst_ptr ,x ,i1_diff * nb1 , 2860kind ,* stream )); 2861 2862 }else if (nb0 == ts ) { 2863return CHECK_TRY_ERROR ( 2864 dpct::async_dpct_memcpy (dst_ptr ,ts * ne0 /bs ,x ,nb1 , 2865ts * ne0 /bs ,i1_diff ,kind ,* stream )); 2866 }else { 2867for (int64_t i1 = 0 ;i1 < i1_diff ;i1 ++ ) { 2868const void * rx = (const void * ) ((const char * )x + i1 * nb1 ); 2869void * rd = (void * ) (dst_ptr + i1 * ts * ne0 /bs ); 2870// pretend the row is a matrix with cols=1 2871 dpct::err0 r = CHECK_TRY_ERROR (dpct::async_dpct_memcpy ( 2872rd ,ts /bs ,rx ,nb0 ,ts /bs ,ne0 ,kind ,* stream )); 2873/* 2874DPCT1001:85: The statement could not be removed. 2875*/ 2876/* 2877DPCT1000:86: Error handling if-stmt was detected but could not be 2878rewritten. 2879*/ 2880if (r != 0 )return r ; 2881 } 2882return 0 ; 2883 } 2884} 2885catch (sycl::exception const & exc ) { 2886 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2887 <<", line:" <<__LINE__ << std::endl ; 2888 std::exit (1 ); 2889} 2890 2891inline void ggml_sycl_op_mul_mat_sycl ( 2892ggml_backend_sycl_context & ctx , 2893const ggml_tensor * src0 ,const ggml_tensor * src1 ,ggml_tensor * dst , 2894const char * src0_dd_i ,const float * src1_ddf_i ,const char * src1_ddq_i , 2895float * dst_dd_i ,const int64_t row_low ,const int64_t row_high , 2896const int64_t src1_ncols ,const int64_t src1_padded_row_size , 2897const queue_ptr & stream )try { 2898 2899GGML_ASSERT (src0_dd_i != nullptr ); 2900GGML_ASSERT (src1_ddf_i != nullptr ); 2901GGML_ASSERT (dst_dd_i != nullptr ); 2902 2903const int64_t ne00 = src0 -> ne [0 ]; 2904const int64_t ne10 = src1 -> ne [0 ]; 2905GGML_ASSERT (ne00 == ne10 ); 2906 2907const int64_t row_diff = row_high - row_low ; 2908 2909int id ; 2910SYCL_CHECK ( 2911CHECK_TRY_ERROR (id = get_current_device_id ())); 2912 2913const int64_t ne0 = dst -> ne [0 ];// used by MKL only 2914// the main device has a larger memory buffer to hold the results from all GPUs 2915// ldc == nrows of the matrix that cuBLAS writes into 2916int ldc = id == ctx .device ?ne0 :row_diff ;// used by MKL only 2917 2918#ifdef GGML_SYCL_F16 2919bool use_fp16 = true;// TODO(Yu) SYCL capability check 2920#else 2921bool use_fp16 = false; 2922#endif 2923 2924#if GGML_SYCL_DNNL && defined(GGML_SYCL_HAS_BF16 ) 2925// Fast path for bf16 src0 2926if (src0 -> type == GGML_TYPE_BF16 && g_ggml_sycl_enable_dnn && ggml_is_contiguous (src0 )&& 2927row_diff == src0 -> ne [1 ]) { 2928using bf16_t = sycl::ext::oneapi::bfloat16 ; 2929ggml_sycl_pool_alloc < bf16_t > src1_as_bf16 (ctx .pool (),src1_ncols * ne10 ); 2930if (src1 -> type != GGML_TYPE_BF16 ) { 2931const to_bf16_sycl_t to_bf16_sycl = ggml_get_to_bf16_sycl (src1 -> type ,dst ); 2932GGML_ASSERT (to_bf16_sycl != nullptr ); 2933to_bf16_sycl (src1_ddf_i ,src1_as_bf16 .get (),src1_ncols * ne10 ,stream ); 2934 }else { 2935stream -> memcpy (src1_as_bf16 .get (),src1_ddf_i ,src1_ncols * ne10 * sizeof (bf16_t )); 2936 } 2937DnnlGemmWrapper ::row_gemm (ctx ,row_diff ,src1_ncols ,ne10 , 2938src0_dd_i ,DnnlGemmWrapper ::to_dt < bf16_t > (), 2939src1_as_bf16 .get (),DnnlGemmWrapper ::to_dt < bf16_t > (), 2940dst_dd_i ,DnnlGemmWrapper ::to_dt < float > (),stream ); 2941GGML_UNUSED (dst ); 2942GGML_UNUSED (src1_ddq_i ); 2943GGML_UNUSED (src1_padded_row_size ); 2944return ; 2945 } 2946#endif 2947 2948if ((src0 -> type == GGML_TYPE_F16 || ggml_is_quantized (src0 -> type ))&& use_fp16 && ggml_is_contiguous (src0 )&& 2949row_diff == src0 -> ne [1 ]&& dst -> op_params [0 ]== GGML_PREC_DEFAULT ) { 2950ggml_sycl_pool_alloc < sycl::half > src0_as_f16 (ctx .pool ()); 2951if (src0 -> type != GGML_TYPE_F16 ) { 2952scope_op_debug_print scope_dbg_print (__func__ ,"/to_fp16_sycl" ,dst ,/*num_src=*/ 2 , 2953" : converting src0 to fp16" ); 2954const to_fp16_sycl_t to_fp16_sycl = ggml_get_to_fp16_sycl (src0 -> type ,dst ); 2955GGML_ASSERT (to_fp16_sycl != nullptr ); 2956size_t ne = row_diff * ne00 ; 2957src0_as_f16 .alloc (ne ); 2958to_fp16_sycl (src0_dd_i ,src0_as_f16 .get (),ne ,stream ); 2959 } 2960const sycl::half * src0_ptr = src0 -> type == GGML_TYPE_F16 2961 ? (const sycl::half * )src0_dd_i 2962 :src0_as_f16 .get (); 2963 2964ggml_sycl_pool_alloc < sycl::half > src1_as_f16 (ctx .pool ()); 2965if (src1 -> type != GGML_TYPE_F16 ) { 2966scope_op_debug_print scope_dbg_print (__func__ ,"/to_fp16_sycl" ,dst ,/*num_src=*/ 2 , 2967" : converting src1 to fp16" ); 2968const to_fp16_sycl_t to_fp16_sycl = ggml_get_to_fp16_sycl (src1 -> type ,dst ); 2969GGML_ASSERT (to_fp16_sycl != nullptr ); 2970size_t ne = src1_ncols * ne10 ; 2971src1_as_f16 .alloc (ne ); 2972to_fp16_sycl (src1_ddf_i ,src1_as_f16 .get (),ne ,stream ); 2973 } 2974const sycl::half * src1_ptr = src1 -> type == GGML_TYPE_F16 2975 ? (const sycl::half * )src1 -> data + src1_padded_row_size 2976 :src1_as_f16 .get (); 2977 2978#if GGML_SYCL_DNNL 2979if (g_ggml_sycl_enable_dnn ) { 2980DnnlGemmWrapper ::row_gemm (ctx ,row_diff ,src1_ncols ,ne10 ,src0_ptr , 2981DnnlGemmWrapper ::to_dt < sycl::half > (),src1_ptr ,DnnlGemmWrapper ::to_dt < sycl::half > (), 2982dst_dd_i ,DnnlGemmWrapper ::to_dt < float > (),stream ); 2983 } 2984else 2985#endif 2986 { 2987const float alpha = 1.0f ; 2988const float beta = 0.0f ; 2989SYCL_CHECK (CHECK_TRY_ERROR (dpct::gemm ( 2990* stream , oneapi::mkl::transpose::trans , 2991 oneapi::mkl::transpose::nontrans ,row_diff ,src1_ncols ,ne10 , 2992& alpha ,src0_ptr , dpct::library_data_t::real_half ,ne00 , 2993src1_ptr , dpct::library_data_t::real_half ,ne10 ,& beta , 2994dst_dd_i , dpct::library_data_t::real_float ,ldc , 2995 dpct::library_data_t::real_float ))); 2996 } 2997 }else { 2998ggml_sycl_pool_alloc < float > src0_ddq_as_f32 (ctx .pool ()); 2999ggml_sycl_pool_alloc < float > src1_ddq_as_f32 (ctx .pool ()); 3000if (src0 -> type != GGML_TYPE_F32 ) { 3001scope_op_debug_print scope_dbg_print (__func__ ,"/to_fp32_sycl" ,dst ,/*num_src=*/ 2 , 3002" : converting src0 to fp32" ); 3003const to_fp32_sycl_t to_fp32_sycl = ggml_get_to_fp32_sycl (src0 -> type ,dst ); 3004GGML_ASSERT (to_fp32_sycl != nullptr ); 3005src0_ddq_as_f32 .alloc (row_diff * ne00 ); 3006to_fp32_sycl (src0_dd_i ,src0_ddq_as_f32 .get (),row_diff * ne00 ,stream ); 3007 } 3008if (src1 -> type != GGML_TYPE_F32 ) { 3009scope_op_debug_print scope_dbg_print (__func__ ,"/to_fp32_sycl" ,dst ,/*num_src=*/ 2 , 3010" : converting src1 to fp32" ); 3011const to_fp32_sycl_t to_fp32_sycl = ggml_get_to_fp32_sycl (src1 -> type ,dst ); 3012GGML_ASSERT (to_fp32_sycl != nullptr ); 3013src1_ddq_as_f32 .alloc (src1_ncols * ne10 ); 3014to_fp32_sycl (src1_ddf_i ,src1_ddq_as_f32 .get (),src1_ncols * ne10 ,stream ); 3015 } 3016const float * src0_ddf_i = src0 -> type == GGML_TYPE_F32 ? (const float * )src0_dd_i :src0_ddq_as_f32 .get (); 3017const float * src1_ddf1_i = src1 -> type == GGML_TYPE_F32 ? (const float * )src1_ddf_i :src1_ddq_as_f32 .get (); 3018 3019 { 3020#if GGML_SYCL_DNNL 3021const int64_t gemm_flops = (int64_t )row_diff * src1_ncols * ne10 ; 3022const bool use_mkl_direct = gemm_flops < 256 * 256 * 256 ; 3023if (g_ggml_sycl_enable_dnn && !use_mkl_direct ) { 3024DnnlGemmWrapper ::row_gemm (ctx ,row_diff ,src1_ncols ,ne10 ,src0_ddf_i , 3025DnnlGemmWrapper ::to_dt < float > (),src1_ddf1_i ,DnnlGemmWrapper ::to_dt < float > (), 3026dst_dd_i ,DnnlGemmWrapper ::to_dt < float > (),stream ); 3027 } 3028else 3029#endif 3030 { 3031const float alpha = 1.0f ; 3032const float beta = 0.0f ; 3033SYCL_CHECK (CHECK_TRY_ERROR (oneapi::mkl::blas::column_major::gemm ( 3034* stream , oneapi::mkl::transpose::trans , oneapi::mkl::transpose::nontrans ,row_diff , 3035src1_ncols ,ne10 , dpct::get_value (& alpha ,* stream ),src0_ddf_i ,ne00 ,src1_ddf1_i ,ne10 , 3036 dpct::get_value (& beta ,* stream ),dst_dd_i ,ldc ))); 3037 } 3038 } 3039 } 3040GGML_UNUSED (dst ); 3041GGML_UNUSED (src1_ddq_i ); 3042GGML_UNUSED (src1_padded_row_size ); 3043} 3044catch (sycl::exception const & exc ) { 3045 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 3046 <<", line:" <<__LINE__ << std::endl ; 3047 std::exit (1 ); 3048} 3049 3050inline void ggml_sycl_op_sum (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3051GGML_ASSERT (dst -> src [0 ]-> type == GGML_TYPE_F32 ); 3052GGML_ASSERT (dst -> type == GGML_TYPE_F32 ); 3053 dpct::queue_ptr main_stream = ctx .stream (); 3054SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3055const float * src0_dd = static_cast < const float *> (dst -> src [0 ]-> data ); 3056float * dst_dd = static_cast < float *> (dst -> data ); 3057 3058const int64_t ne = ggml_nelements (dst -> src [0 ]); 3059 3060sum_rows_f32_sycl (src0_dd ,dst_dd ,ne ,1 ,main_stream ); 3061} 3062 3063inline void ggml_sycl_op_sum_rows (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3064GGML_ASSERT (dst -> src [0 ]-> type == GGML_TYPE_F32 ); 3065GGML_ASSERT (dst -> type == GGML_TYPE_F32 ); 3066 dpct::queue_ptr main_stream = ctx .stream (); 3067SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3068const float * src0_dd = static_cast < const float *> (dst -> src [0 ]-> data ); 3069float * dst_dd = static_cast < float *> (dst -> data ); 3070 3071const int64_t ncols = dst -> src [0 ]-> ne [0 ]; 3072const int64_t nrows = ggml_nrows (dst -> src [0 ]); 3073 3074sum_rows_f32_sycl (src0_dd ,dst_dd ,ncols ,nrows ,main_stream ); 3075} 3076 3077inline void ggml_sycl_op_mean (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3078GGML_ASSERT (dst -> src [0 ]-> type == GGML_TYPE_F32 ); 3079GGML_ASSERT (dst -> type == GGML_TYPE_F32 ); 3080 3081 dpct::queue_ptr main_stream = ctx .stream (); 3082SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3083 3084const float * src0_dd = static_cast < const float *> (dst -> src [0 ]-> data ); 3085float * dst_dd = static_cast < float *> (dst -> data ); 3086 3087const int64_t ncols = dst -> src [0 ]-> ne [0 ]; 3088const int64_t nrows = ggml_nrows (dst -> src [0 ]); 3089 3090sum_rows_f32_sycl (src0_dd ,dst_dd ,ncols ,nrows ,main_stream ); 3091 3092main_stream -> parallel_for ( 3093 sycl::range < 1 > (nrows ), 3094 [= ](sycl::id < 1 > row ) { 3095dst_dd [row ] /=ncols ; 3096 } 3097 ); 3098} 3099 3100 3101inline void ggml_sycl_op_argsort (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3102GGML_ASSERT (dst -> src [0 ]-> type == GGML_TYPE_F32 ); 3103GGML_ASSERT (dst -> type == GGML_TYPE_I32 ); 3104 dpct::queue_ptr main_stream = ctx .stream (); 3105SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3106const float * src0_dd = static_cast < const float *> (dst -> src [0 ]-> data ); 3107int32_t * dst_dd = static_cast < int32_t *> (dst -> data ); 3108 3109 3110const int64_t ncols = dst -> src [0 ]-> ne [0 ]; 3111const int64_t nrows = ggml_nrows (dst -> src [0 ]); 3112 3113enum ggml_sort_order order = (enum ggml_sort_order )dst -> op_params [0 ]; 3114 3115argsort_f32_i32_sycl (src0_dd , (int * )dst_dd ,ncols ,nrows ,order , 3116main_stream ,ctx .device ,ctx .pool ()); 3117} 3118 3119static void ggml_sycl_op_top_k (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3120const ggml_tensor * src0 = dst -> src [0 ]; 3121 3122GGML_ASSERT (src0 ); 3123GGML_ASSERT (src0 -> type == GGML_TYPE_F32 ); 3124GGML_ASSERT (dst -> type == GGML_TYPE_I32 ); 3125GGML_ASSERT (ggml_is_contiguous (src0 )); 3126 3127 dpct::queue_ptr main_stream = ctx .stream (); 3128SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3129 3130const float * src0_dd = static_cast < const float *> (src0 -> data ); 3131int32_t * dst_dd = static_cast < int32_t *> (dst -> data ); 3132 3133const int k = dst -> ne [0 ]; 3134const int64_t ncols = src0 -> ne [0 ]; 3135const int64_t nrows = ggml_nrows (src0 ); 3136 3137GGML_ASSERT (k > 0 ); 3138GGML_ASSERT (k <=ncols ); 3139 3140if (k <=SYCL_TOP_K_SCAN_MERGE_MAX_K ) { 3141top_k_f32_sycl (ctx ,src0_dd ,dst_dd ,ncols ,nrows ,k ,main_stream ); 3142 }else { 3143ggml_sycl_top_k_radix (ctx ,src0_dd ,dst_dd ,ncols ,nrows ,k ,main_stream ); 3144 } 3145} 3146 3147inline void ggml_sycl_op_argmax (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3148GGML_ASSERT (dst -> src [0 ]-> type == GGML_TYPE_F32 ); 3149GGML_ASSERT (dst -> type == GGML_TYPE_I32 ); 3150 3151 dpct::queue_ptr main_stream = ctx .stream (); 3152SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3153const float * src0_dd = static_cast < const float *> (dst -> src [0 ]-> data ); 3154int32_t * dst_dd = static_cast < int32_t *> (dst -> data ); 3155 3156const int64_t ncols = dst -> src [0 ]-> ne [0 ]; 3157const int64_t nrows = ggml_nrows (dst -> src [0 ]); 3158 3159argmax_f32_i32_sycl (src0_dd ,dst_dd ,ncols ,nrows ,main_stream ); 3160} 3161 3162inline void ggml_sycl_op_diag_mask_inf (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3163GGML_ASSERT (dst -> src [0 ]-> type == GGML_TYPE_F32 ); 3164GGML_ASSERT (dst -> type == GGML_TYPE_F32 ); 3165 dpct::queue_ptr main_stream = ctx .stream (); 3166SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3167const float * src0_dd = static_cast < const float *> (dst -> src [0 ]-> data ); 3168float * dst_dd = static_cast < float *> (dst -> data ); 3169 3170const int64_t ne00 = dst -> src [0 ]-> ne [0 ]; 3171const int64_t ne01 = dst -> src [0 ]-> ne [1 ]; 3172const int nrows0 = ggml_nrows (dst -> src [0 ]); 3173 3174const int n_past = ((int32_t * )dst -> op_params )[0 ]; 3175 3176diag_mask_inf_f32_sycl (src0_dd ,dst_dd ,ne00 ,nrows0 ,ne01 ,n_past ,main_stream ); 3177} 3178 3179static void tri_f32_sycl ( 3180const float * src , 3181float * dst , 3182const int64_t ne0 , 3183const int64_t ne1 , 3184const int64_t ne2 , 3185const int64_t ne3 , 3186const ggml_tri_type ttype , 3187 dpct::queue_ptr main_stream 3188) { 3189const size_t total = (size_t )ne0 * (size_t )ne1 * (size_t )ne2 * (size_t )ne3 ; 3190 3191main_stream -> parallel_for (sycl::range < 1 > (total ), [= ](sycl::id < 1 > tid ) { 3192const int64_t idx = (int64_t )tid [0 ]; 3193 3194const int64_t i0 = idx %ne0 ; 3195const int64_t t1 = idx /ne0 ; 3196const int64_t i1 = t1 %ne1 ; 3197 3198bool keep = false; 3199switch (ttype ) { 3200case GGML_TRI_TYPE_LOWER :keep = (i0 < i1 );break ; 3201case GGML_TRI_TYPE_LOWER_DIAG :keep = (i0 <=i1 );break ; 3202case GGML_TRI_TYPE_UPPER :keep = (i0 > i1 );break ; 3203case GGML_TRI_TYPE_UPPER_DIAG :keep = (i0 >=i1 );break ; 3204default :keep = false;break ; 3205 } 3206 3207dst [idx ]= keep ?src [idx ] :0.0f ; 3208 }); 3209} 3210 3211static void ggml_sycl_op_tri (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3212const ggml_tensor * src0 = dst -> src [0 ]; 3213GGML_ASSERT (src0 ); 3214 3215GGML_ASSERT (src0 -> type == GGML_TYPE_F32 ); 3216GGML_ASSERT (dst -> type == GGML_TYPE_F32 ); 3217GGML_ASSERT (ggml_is_contiguous (src0 )); 3218GGML_ASSERT (ggml_is_contiguous (dst )); 3219GGML_ASSERT (ggml_are_same_shape (src0 ,dst )); 3220 3221 dpct::queue_ptr main_stream = ctx .stream (); 3222SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3223 3224const float * src0_dd = static_cast < const float *> (src0 -> data ); 3225float * dst_dd = static_cast < float *> (dst -> data ); 3226 3227const ggml_tri_type ttype = (ggml_tri_type )ggml_get_op_params_i32 (dst ,0 ); 3228 3229const int64_t ne0 = src0 -> ne [0 ]; 3230const int64_t ne1 = src0 -> ne [1 ]; 3231const int64_t ne2 = src0 -> ne [2 ]; 3232const int64_t ne3 = src0 -> ne [3 ]; 3233 3234tri_f32_sycl (src0_dd ,dst_dd ,ne0 ,ne1 ,ne2 ,ne3 ,ttype ,main_stream ); 3235} 3236 3237 3238inline void ggml_sycl_op_scale (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3239GGML_ASSERT (dst -> src [0 ]-> type == GGML_TYPE_F32 ); 3240GGML_ASSERT (dst -> type == GGML_TYPE_F32 ); 3241 dpct::queue_ptr main_stream = ctx .stream (); 3242SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3243const float * src0_dd = static_cast < const float *> (dst -> src [0 ]-> data ); 3244float * dst_dd = static_cast < float *> (dst -> data ); 3245 3246float scale ; 3247float bias ; 3248memcpy (& scale , (float * )dst -> op_params + 0 ,sizeof (float )); 3249memcpy (& bias , (float * )dst -> op_params + 1 ,sizeof (float )); 3250 3251scale_f32_sycl (src0_dd ,dst_dd ,scale ,bias ,ggml_nelements (dst -> src [0 ]),main_stream ); 3252/* 3253DPCT1010:87: SYCL uses exceptions to report errors and does not use the 3254error codes. The call was replaced with 0. You need to rewrite this code. 3255*/ 3256SYCL_CHECK (0 ); 3257} 3258 3259static void ggml_sycl_set_peer_access (const int n_tokens , [[maybe_unused ]]int main_device ) { 3260static bool peer_access_enabled = false; 3261 3262const bool enable_peer_access = n_tokens <=GGML_SYCL_PEER_MAX_BATCH_SIZE ; 3263 3264if (peer_access_enabled == enable_peer_access ) { 3265return ; 3266 } 3267 3268#ifdef NDEBUG 3269for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 3270SYCL_CHECK (ggml_sycl_set_device (i )); 3271 } 3272 3273for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 3274SYCL_CHECK (ggml_sycl_set_device (i )); 3275 3276for (int id_other = 0 ;id_other < ggml_sycl_info ().device_count ;++ id_other ) { 3277if (i == id_other ) { 3278continue ; 3279 } 3280if (i != main_device && id_other != main_device ) { 3281continue ; 3282 } 3283 3284// int can_access_peer; 3285// SYCL_CHECK(syclDeviceCanAccessPeer(&can_access_peer, id, id_other)); 3286// if (can_access_peer) { 3287// if (enable_peer_access) { 3288// SYCL_CHECK(syclDeviceEnablePeerAccess(id_other, 0)); 3289// } else { 3290// SYCL_CHECK(syclDeviceDisablePeerAccess(id_other)); 3291// } 3292// } 3293 } 3294 } 3295#endif // NDEBUG 3296 3297peer_access_enabled = enable_peer_access ; 3298} 3299 3300template < template < int > typename quantize_f > 3301static void ggml_sycl_op_mul_mat (ggml_backend_sycl_context & ctx ,const ggml_tensor * src0 , 3302const ggml_tensor * src1 ,ggml_tensor * dst , 3303ggml_sycl_op_mul_mat_t op )try { 3304 3305GGML_TENSOR_LOCALS (int64_t ,ne0 ,src0 ,ne ); 3306 3307GGML_TENSOR_LOCALS (int64_t ,ne1 ,src1 ,ne ); 3308const int64_t nrows1 = ggml_nrows (src1 ); 3309 3310GGML_ASSERT (ne03 == ne13 ); 3311 3312const int64_t ne0 = dst -> ne [0 ]; 3313const int64_t ne1 = dst -> ne [1 ]; 3314 3315const int nb2 = dst -> nb [2 ]; 3316const int nb3 = dst -> nb [3 ]; 3317 3318GGML_ASSERT (!ggml_backend_buffer_is_sycl_split (dst -> buffer )); 3319GGML_ASSERT (!ggml_backend_buffer_is_sycl_split (src1 -> buffer )); 3320GGML_ASSERT (src1 -> type == GGML_TYPE_F32 || (src1 -> ne [2 ]== 1 && src1 -> ne [3 ]== 1 )); 3321 3322GGML_ASSERT (ne12 >=ne02 && ne12 %ne02 == 0 ); 3323 3324const int64_t i02_divisor = ne12 /ne02 ; 3325 3326const size_t src0_ts = ggml_type_size (src0 -> type ); 3327const size_t src0_bs = ggml_blck_size (src0 -> type ); 3328const size_t q8_1_ts = sizeof (block_q8_1 ); 3329const size_t q8_1_bs = QK8_1 ; 3330 3331ggml_tensor_extra_gpu * src0_extra = (ggml_tensor_extra_gpu * )src0 -> extra ; 3332ggml_tensor_extra_gpu * src1_extra = (ggml_tensor_extra_gpu * )src1 -> extra ; 3333 3334const bool src0_is_contiguous = ggml_is_contiguous (src0 ); 3335const bool src1_is_contiguous = ggml_is_contiguous (src1 ); 3336 3337int64_t src1_padded_col_size = GGML_PAD (ne10 ,MATRIX_ROW_PADDING ); 3338 3339const bool split = ggml_backend_buffer_is_sycl_split (src0 -> buffer ); 3340GGML_ASSERT (!(split && ne02 > 1 )); 3341GGML_ASSERT (!(split && ne03 > 1 )); 3342GGML_ASSERT (!(split && ne02 < ne12 )); 3343 3344 std::array < float ,GGML_SYCL_MAX_DEVICES > tensor_split ; 3345if (split ) { 3346// TODO: check that src0->buffer->buft is a split buffer type, replace GGML_BACKEND_TYPE_GPU_SPLIT check 3347// GGML_ASSERT(src0->buffer != nullptr && src0->buffer->buft == ...); 3348ggml_backend_sycl_split_buffer_type_context * buft_ctx = (ggml_backend_sycl_split_buffer_type_context * )src0 -> buffer -> buft -> context ; 3349tensor_split = buft_ctx -> tensor_split ; 3350 } 3351 3352struct dev_data { 3353ggml_sycl_pool_alloc < char > src0_dd_alloc ; 3354ggml_sycl_pool_alloc < float > src1_ddf_alloc ; 3355ggml_sycl_pool_alloc < char > src1_ddq_alloc ; 3356ggml_sycl_pool_alloc < float > dst_dd_alloc ; 3357 3358char * src0_dd = nullptr ; 3359float * src1_ddf = nullptr ;// float 3360char * src1_ddq = nullptr ;// q8_1 3361float * dst_dd = nullptr ; 3362 3363int64_t row_low ; 3364int64_t row_high ; 3365 }; 3366 3367dev_data dev [GGML_SYCL_MAX_DEVICES ]; 3368 3369int used_devices = 0 ; 3370queue_ptr main_stream = ctx .stream (); 3371 3372for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 3373// by default, use all rows 3374dev [i ].row_low = 0 ; 3375dev [i ].row_high = ne01 ; 3376 3377// for multi GPU, get the row boundaries from tensor split 3378// and round to mul_mat_q tile sizes 3379if (split ) { 3380const int64_t rounding = get_row_rounding (src0 -> type ,tensor_split ); 3381 3382if (i != 0 ) { 3383dev [i ].row_low = ne01 * tensor_split [i ]; 3384if (dev [i ].row_low < ne01 ) { 3385dev [i ].row_low -= dev [i ].row_low %rounding ; 3386 } 3387 } 3388 3389if (i != ggml_sycl_info ().device_count - 1 ) { 3390dev [i ].row_high = ne01 * tensor_split [i + 1 ]; 3391if (dev [i ].row_high < ne01 ) { 3392dev [i ].row_high -= dev [i ].row_high %rounding ; 3393 } 3394 } 3395 } 3396 } 3397 3398constexpr bool quantize_enabled = !std::is_same_v < quantize_f < QK8_1 /WARP_SIZE > , 3399no_quantize_q8_1 < QK8_1 /WARP_SIZE >> ; 3400for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 3401if ((!split && i != ctx .device )|| dev [i ].row_low == dev [i ].row_high ) { 3402continue ; 3403 } 3404 3405used_devices ++ ; 3406 3407const bool src1_on_device = i == ctx .device ; 3408const bool dst_on_device = i == ctx .device ; 3409 3410ggml_sycl_set_device (i ); 3411queue_ptr stream = ctx .stream (i ,0 ); 3412 3413if (src0_is_contiguous ) { 3414dev [i ].src0_dd = (char * )src0 -> data ; 3415 }else { 3416dev [i ].src0_dd = dev [i ].src0_dd_alloc .alloc (ctx .pool (i ),ggml_nbytes (src0 )); 3417 } 3418 3419if (src1_on_device && src1_is_contiguous ) { 3420dev [i ].src1_ddf = (float * )src1 -> data ; 3421 }else { 3422dev [i ].src1_ddf = dev [i ].src1_ddf_alloc .alloc (ctx .pool (i ),ggml_nelements (src1 )); 3423 } 3424 3425if constexpr (quantize_enabled ) { 3426dev [i ].src1_ddq = dev [i ].src1_ddq_alloc .alloc (ctx .pool (i ),nrows1 * src1_padded_col_size * q8_1_ts /q8_1_bs ); 3427 3428if (src1_on_device && src1_is_contiguous ) { 3429scope_op_debug_print scope_dbg_print (__func__ ,"/quantize_row_q8_1_sycl" ,dst , 3430/*num_src=*/ 2 ," : converting src1 to Q8_1" ); 3431try { 3432quantize_row_q8_1_sycl < quantize_f > (dev [i ].src1_ddf ,dev [i ].src1_ddq ,ne10 ,nrows1 ,src1_padded_col_size ,stream ); 3433 }catch (sycl::exception const & exc ) { 3434 std::cerr <<"Quantize_row_q8_1_sycl error" <<exc .what () <<"Exception caught at file:" <<__FILE__ 3435 <<", line:" <<__LINE__ << std::endl ; 3436 std::exit (1 ); 3437 } 3438 } 3439 } 3440 3441if (dst_on_device ) { 3442dev [i ].dst_dd = (float * )dst -> data ; 3443 }else { 3444const size_t size_dst_ddf = split ? (dev [i ].row_high - dev [i ].row_low )* ne1 :ggml_nelements (dst ); 3445dev [i ].dst_dd = dev [i ].dst_dd_alloc .alloc (ctx .pool (i ),size_dst_ddf ); 3446 } 3447 } 3448 3449// if multiple devices are used they need to wait for the main device 3450// here an event is recorded that signals that the main device has finished calculating the input data 3451if (split && used_devices > 1 ) { 3452ggml_sycl_set_device (ctx .device ); 3453SYCL_CHECK (CHECK_TRY_ERROR ( 3454* src0_extra -> events [ctx .device ][0 ]= 3455ctx .stream ()-> ext_oneapi_submit_barrier ())); 3456 } 3457 3458const int64_t src1_col_stride = split && used_devices > 1 ?MUL_MAT_SRC1_COL_STRIDE :ne11 ; 3459for (int64_t src1_col_0 = 0 ;src1_col_0 < ne11 ;src1_col_0 += src1_col_stride ) { 3460const int64_t is = split ? (src1_col_0 /src1_col_stride ) %GGML_SYCL_MAX_STREAMS :0 ; 3461const int64_t src1_ncols = src1_col_0 + src1_col_stride > ne11 ?ne11 - src1_col_0 :src1_col_stride ; 3462for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 3463if ((!split && i != ctx .device )|| dev [i ].row_low == dev [i ].row_high ) { 3464continue ; 3465 } 3466 3467const bool src1_on_device = i == ctx .device ; 3468const bool dst_on_device = i == ctx .device ; 3469const int64_t row_diff = dev [i ].row_high - dev [i ].row_low ; 3470 3471ggml_sycl_set_device (i ); 3472queue_ptr stream = ctx .stream (i ,is ); 3473 3474// wait for main GPU data if necessary 3475if (split && (i != ctx .device || is != 0 )) { 3476SYCL_CHECK (CHECK_TRY_ERROR (stream -> ext_oneapi_submit_barrier ( 3477 {* src0_extra -> events [ctx .device ][0 ]}))); 3478 } 3479 3480for (int64_t i0 = 0 ;i0 < ne13 * ne12 ;++ i0 ) { 3481const int64_t i03 = i0 /ne12 ; 3482const int64_t i02 = i0 %ne12 ; 3483 3484const size_t src1_ddq_i_offset = (i0 * ne11 + src1_col_0 )* src1_padded_col_size * q8_1_ts /q8_1_bs ; 3485 3486// for split tensors the data begins at i0 == i0_offset_low 3487char * src0_dd_i = dev [i ].src0_dd + (i0 /i02_divisor )* (ne01 * ne00 * src0_ts )/src0_bs ; 3488float * src1_ddf_i = dev [i ].src1_ddf + (i0 * ne11 + src1_col_0 )* ne10 ; 3489char * src1_ddq_i = dev [i ].src1_ddq + src1_ddq_i_offset ; 3490float * dst_dd_i = dev [i ].dst_dd + (i0 * ne1 + src1_col_0 )* (dst_on_device ?ne0 :row_diff ); 3491 3492// the main device memory buffer can be on VRAM scratch, with space for all partial results 3493// in that case an offset on dst_ddf_i is needed 3494if (i == ctx .device ) { 3495dst_dd_i += dev [i ].row_low ;// offset is 0 if no tensor split 3496 } 3497 3498// copy src0, src1 to device if necessary 3499if (src1_is_contiguous ) { 3500if (i != ctx .device ) { 3501if constexpr (quantize_enabled ) { 3502char * src1_ddq_i_source = dev [ctx .device ].src1_ddq + src1_ddq_i_offset ; 3503SYCL_CHECK ( 3504CHECK_TRY_ERROR (stream 3505-> memcpy (src1_ddq_i ,src1_ddq_i_source , 3506src1_ncols * src1_padded_col_size * q8_1_ts /q8_1_bs ) 3507 .wait ())); 3508 }else { 3509float * src1_ddf_i_source = (float * )src1_extra -> data_device [ctx .device ]; 3510src1_ddf_i_source += (i0 * ne11 + src1_col_0 )* ne10 ; 3511 3512SYCL_CHECK ( 3513CHECK_TRY_ERROR (dev2dev_memcpy (i ,* stream ,ctx .device ,* main_stream ,src1_ddf_i ,src1_ddf_i_source , 3514src1_ncols * ne10 * sizeof (float )))); 3515 } 3516 } 3517 }else { 3518if (src1_on_device ) { 3519SYCL_CHECK (ggml_sycl_cpy_tensor_2d (src1_ddf_i ,src1 ,i03 ,i02 ,src1_col_0 , 3520src1_col_0 + src1_ncols ,stream )); 3521 }else { 3522GGML_ABORT ("src1 is non-contiguous and not on device" ); 3523 } 3524 3525if constexpr (quantize_enabled ) { 3526scope_op_debug_print scope_dbg_print (__func__ ,"/quantize_row_q8_1_sycl" ,dst , 3527/*num_src=*/ 2 ," : converting src1 to Q8_1" ); 3528try { 3529quantize_row_q8_1_sycl < quantize_q8_1 > (src1_ddf_i ,src1_ddq_i ,ne10 ,src1_ncols , 3530src1_padded_col_size ,stream ); 3531 }catch (const sycl::exception & exc ) { 3532 std::cerr <<"Quantize_row_q8_1_sycl error" <<exc .what () 3533 <<"Exception caught at file:" <<__FILE__ <<", line:" <<__LINE__ << std::endl ; 3534 std::exit (1 ); 3535 } 3536 } 3537 } 3538 3539if (src1_col_0 == 0 && !src0_is_contiguous && i02 %i02_divisor == 0 ) { 3540SYCL_CHECK (ggml_sycl_cpy_tensor_2d (src0_dd_i ,src0 ,i03 ,i02 /i02_divisor ,dev [i ].row_low ,dev [i ].row_high ,stream )); 3541 } 3542if (src1 -> type == GGML_TYPE_F16 ) { 3543src1_padded_col_size = (i0 * ne11 + src1_col_0 )* ne10 ; 3544 } 3545// do the computation 3546SYCL_CHECK (CHECK_TRY_ERROR (op (ctx ,src0 ,src1 ,dst ,src0_dd_i ,src1_ddf_i ,src1_ddq_i ,dst_dd_i , 3547dev [i ].row_low ,dev [i ].row_high ,src1_ncols ,src1_padded_col_size ,stream ))); 3548 3549// copy dst to host or other device if necessary 3550if (!dst_on_device ) { 3551void * dst_off_device = dst -> data ; 3552if (split ) { 3553// src0 = weight matrix is saved as a transposed matrix for better memory layout. 3554// dst is NOT transposed. 3555// The outputs of matrix matrix multiplications can therefore NOT simply be concatenated for >1 GPU. 3556// Instead they need to be copied to the correct slice in ne0 = dst row index. 3557// If dst is a vector with ne0 == 1 then you don't have to do this but it still produces correct results. 3558float * dhf_dst_i = (float * ) ((char * )dst_off_device + i02 * nb2 + i03 * nb3 ); 3559GGML_ASSERT (dst -> nb [1 ]== ne0 * sizeof (float )); 3560dhf_dst_i += src1_col_0 * ne0 + dev [i ].row_low ; 3561 3562SYCL_CHECK (CHECK_TRY_ERROR (dpct::async_dpct_memcpy ( 3563dhf_dst_i ,ne0 * sizeof (float ),dst_dd_i , 3564row_diff * sizeof (float ),row_diff * sizeof (float ), 3565src1_ncols , dpct::device_to_device ,* stream ))); 3566 }else { 3567float * dhf_dst_i = (float * ) ((char * )dst_off_device + i02 * nb2 + i03 * nb3 ); 3568GGML_ASSERT (dst -> nb [1 ]== ne0 * sizeof (float )); 3569dhf_dst_i += src1_col_0 * ne0 ; 3570SYCL_CHECK (CHECK_TRY_ERROR ( 3571stream -> memcpy (dhf_dst_i ,dst_dd_i , 3572src1_ncols * ne0 * sizeof (float )).wait ())); 3573 } 3574 } 3575 3576// add event for the main device to wait on until other device is done 3577if (split && (i != ctx .device || is != 0 )) { 3578SYCL_CHECK (CHECK_TRY_ERROR ( 3579* src0_extra -> events [i ][is ]= 3580stream -> ext_oneapi_submit_barrier ())); 3581 } 3582 } 3583 } 3584 } 3585 3586// main device waits for all other devices to be finished 3587if (split && ggml_sycl_info ().device_count > 1 ) { 3588int64_t is_max = (ne11 + MUL_MAT_SRC1_COL_STRIDE - 1 ) /MUL_MAT_SRC1_COL_STRIDE ; 3589is_max = is_max <=GGML_SYCL_MAX_STREAMS ?is_max :GGML_SYCL_MAX_STREAMS ; 3590 3591ggml_sycl_set_device (ctx .device ); 3592for (int i = 0 ;i < ggml_sycl_info ().device_count ;++ i ) { 3593if (dev [i ].row_low == dev [i ].row_high ) { 3594continue ; 3595 } 3596for (int64_t is = 0 ;is < is_max ;++ is ) { 3597SYCL_CHECK (CHECK_TRY_ERROR ( 3598ctx .stream ()-> ext_oneapi_submit_barrier ( 3599 {* src0_extra -> events [i ][is ]}))); 3600 } 3601 } 3602 } 3603} 3604catch (sycl::exception const & exc ) { 3605 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 3606 <<", line:" <<__LINE__ << std::endl ; 3607 std::exit (1 ); 3608} 3609 3610static void ggml_sycl_repeat_back (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3611scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 3612ggml_sycl_op_repeat_back (ctx ,dst ); 3613} 3614 3615static void ggml_sycl_get_rows (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3616scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 2 ); 3617ggml_sycl_op_get_rows (ctx ,dst ); 3618} 3619 3620static void ggml_sycl_norm (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3621scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 3622ggml_sycl_op_norm (ctx ,dst ); 3623} 3624 3625static void ggml_sycl_rms_norm (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3626scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 3627ggml_sycl_op_rms_norm (ctx ,dst ); 3628} 3629 3630static void ggml_sycl_rms_norm_back (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3631scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 2 ); 3632ggml_sycl_op_rms_norm_back (ctx ,dst ); 3633} 3634 3635static void ggml_sycl_l2_norm (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3636scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 3637ggml_sycl_op_l2_norm (ctx ,dst ); 3638} 3639 3640static void ggml_sycl_group_norm (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 3641scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 3642ggml_sycl_op_group_norm (ctx ,dst ); 3643} 3644 3645static void ggml_sycl_mul_mat_vec_p021 (ggml_backend_sycl_context & ctx ,const ggml_tensor * src0 , 3646const ggml_tensor * src1 , 3647ggml_tensor * dst )try { 3648GGML_ASSERT (ggml_is_permuted (src0 )&& ggml_is_permuted (src1 )); 3649GGML_ASSERT (!ggml_backend_buffer_is_sycl_split (src0 -> buffer )); 3650GGML_ASSERT (src0 -> nb [0 ] <=src0 -> nb [1 ]&& src0 -> nb [2 ] <=src0 -> nb [3 ]);// 0213 permutation 3651GGML_ASSERT (src1 -> nb [0 ] <=src1 -> nb [1 ]&& src1 -> nb [2 ] <=src1 -> nb [3 ]);// 0213 permutation 3652GGML_ASSERT (src0 -> type == GGML_TYPE_F16 ); 3653GGML_ASSERT (src1 -> type == GGML_TYPE_F32 ); 3654 3655const int64_t ne00 = src0 -> ne [0 ]; 3656const int64_t ne01 = src0 -> ne [1 ]; 3657const int64_t ne02 = src0 -> ne [2 ]; 3658 3659const int64_t ne12 = src1 -> ne [2 ]; 3660 3661SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3662queue_ptr main_stream = ctx .stream (); 3663 3664void * src0_ddq = src0 -> data ; 3665float * src1_ddf = (float * )src1 -> data ; 3666float * dst_ddf = (float * )dst -> data ; 3667 3668ggml_mul_mat_p021_f16_f32_sycl (src0_ddq ,src1_ddf ,dst_ddf ,ne00 ,ne01 ,ne02 ,ne12 ,main_stream ); 3669} 3670catch (sycl::exception const & exc ) { 3671 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 3672 <<", line:" <<__LINE__ << std::endl ; 3673 std::exit (1 ); 3674} 3675 3676static void ggml_sycl_mul_mat_vec_nc (ggml_backend_sycl_context & ctx ,const ggml_tensor * src0 , 3677const ggml_tensor * src1 , 3678ggml_tensor * dst )try { 3679GGML_ASSERT (!ggml_is_transposed (src0 )); 3680GGML_ASSERT (!ggml_is_transposed (src1 )); 3681GGML_ASSERT (!ggml_is_permuted (src0 )); 3682GGML_ASSERT (!ggml_backend_buffer_is_sycl_split (src0 -> buffer )); 3683GGML_ASSERT (src0 -> type == GGML_TYPE_F16 ); 3684GGML_ASSERT (src1 -> type == GGML_TYPE_F32 ); 3685GGML_ASSERT (src1 -> ne [1 ]== 1 ); 3686GGML_ASSERT (src1 -> ne [3 ]== 1 ); 3687 3688const int64_t ne00 = src0 -> ne [0 ]; 3689const int64_t ne01 = src0 -> ne [1 ]; 3690const int64_t ne02 = src0 -> ne [2 ]; 3691 3692const int64_t nb01 = src0 -> nb [1 ]; 3693const int64_t nb02 = src0 -> nb [2 ]; 3694 3695const int64_t ne12 = src1 -> ne [2 ]; 3696const int64_t nb11 = src1 -> nb [1 ]; 3697 3698SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3699queue_ptr main_stream = ctx .stream (); 3700 3701void * src0_ddq = src0 -> data ; 3702float * src1_ddf = (float * )src1 -> data ; 3703float * dst_ddf = (float * )dst -> data ; 3704 3705const int64_t row_stride_x = nb01 /sizeof (sycl::half ); 3706const int64_t channel_stride_x = nb02 /sizeof (sycl::half ); 3707const int64_t channel_stride_y = nb11 /sizeof (float ); 3708 3709ggml_mul_mat_vec_nc_f16_f32_sycl (src0_ddq ,src1_ddf ,dst_ddf ,ne00 ,ne01 ,row_stride_x ,ne02 ,ne12 ,channel_stride_x ,channel_stride_y ,main_stream ); 3710} 3711catch (sycl::exception const & exc ) { 3712 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 3713 <<", line:" <<__LINE__ << std::endl ; 3714 std::exit (1 ); 3715} 3716 3717static void k_compute_batched_ptrs (const sycl::half * src0_as_f16 ,const sycl::half * src1_as_f16 ,void * dst , 3718const void ** ptrs_src ,void ** ptrs_dst ,int64_t ne12 ,int64_t ne13 ,int64_t ne23 , 3719size_t nb02 ,size_t nb03 ,size_t nb12 ,size_t nb13 ,size_t nbd2 ,size_t nbd3 , 3720int64_t r2 ,int64_t r3 ,const sycl::nd_item < 3 > & item_ct1 ) { 3721const int64_t i13 = item_ct1 .get_group (2 )* item_ct1 .get_local_range (2 )+ item_ct1 .get_local_id (2 ); 3722const int64_t i12 = item_ct1 .get_group (1 )* item_ct1 .get_local_range (1 )+ item_ct1 .get_local_id (1 ); 3723 3724if (i13 >=ne13 || i12 >=ne12 ) { 3725return ; 3726 } 3727 3728const int64_t i03 = i13 /r3 ; 3729const int64_t i02 = i12 /r2 ; 3730 3731const uint8_t * src0_bytes = reinterpret_cast < const uint8_t *> (src0_as_f16 ); 3732const uint8_t * src1_bytes = reinterpret_cast < const uint8_t *> (src1_as_f16 ); 3733uint8_t * dst_bytes = static_cast < uint8_t *> (dst ); 3734 3735ptrs_src [0 * ne23 + i12 + i13 * ne12 ]= src0_bytes + i02 * nb02 + i03 * nb03 ; 3736ptrs_src [1 * ne23 + i12 + i13 * ne12 ]= src1_bytes + i12 * nb12 + i13 * nb13 ; 3737ptrs_dst [0 * ne23 + i12 + i13 * ne12 ]= dst_bytes + i12 * nbd2 + i13 * nbd3 ; 3738} 3739 3740static void ggml_sycl_mul_mat_batched_sycl (ggml_backend_sycl_context & ctx ,const ggml_tensor * src0 , 3741const ggml_tensor * src1 ,ggml_tensor * dst )try { 3742GGML_ASSERT (!ggml_is_transposed (src0 )); 3743GGML_ASSERT (!ggml_is_transposed (src1 )); 3744GGML_ASSERT (!ggml_backend_buffer_is_sycl_split (src0 -> buffer )); 3745GGML_ASSERT (src0 -> type == GGML_TYPE_F16 ); 3746GGML_ASSERT (dst -> type == GGML_TYPE_F32 ); 3747 3748GGML_TENSOR_BINARY_OP_LOCALS 3749 3750// TODO: see https://github.com/ggml-org/llama.cpp/pull/13155 3751// Batched mul_mat requires a rewrite to support both oneDNN and non-contiguous dst 3752GGML_ASSERT (ggml_is_contiguous (dst )); 3753 3754SYCL_CHECK (ggml_sycl_set_device (ctx .device )); 3755queue_ptr queue = ctx .stream (); 3756 3757 dpct::has_capability_or_fail (queue -> get_device (), { sycl::aspect::fp16 }); 3758 3759const sycl::half * src0_f16 = static_cast < const sycl::half *> (src0 -> data ); 3760float * dst_ddf = static_cast < float *> (dst -> data ); 3761 3762const sycl::half * src1_f16 = static_cast < const sycl::half *> (src1 -> data ); 3763#if GGML_SYCL_DNNL 3764const size_t type_size_src0 = ggml_type_size (src0 -> type ); 3765#endif 3766const size_t type_size_src1 = ggml_type_size (src1 -> type ); 3767 3768bool is_src0_cont_2 = ggml_is_contiguous_2 (src0 ); 3769bool is_src1_cont_2 = ggml_is_contiguous_2 (src1 ); 3770 3771// SRC1 strides 3772int64_t s11 = nb11 /type_size_src1 ; 3773int64_t s12 = nb12 /type_size_src1 ; 3774int64_t s13 = nb13 /type_size_src1 ; 3775ggml_sycl_pool_alloc < sycl::half > src1_f16_alloc (ctx .pool ()); 3776 3777// convert src1 to fp16 3778if (src1 -> type != GGML_TYPE_F16 ) { 3779scope_op_debug_print scope_dbg_print (__func__ ,"/to_fp16_nc_sycl" ,dst ,/*num_src=*/ 2 , 3780" : converting src1 to fp16" ); 3781 3782#if GGML_SYCL_DNNL 3783// iterate tensor dims and find the slowest moving dim and stride 3784int last_dim = 0 ; 3785int last_str = 0 ; 3786size_t largest_str = 0 ; 3787for (int i = 0 ;i < 4 ;i ++ ){ 3788// last stride is always the largest 3789if (src1 -> nb [i ]== largest_str ){ 3790if (src1 -> ne [last_dim ]== 1 ){ 3791last_str = i ; 3792last_dim = i ; 3793 } 3794 } 3795if (src1 -> nb [i ]> largest_str ){ 3796largest_str = src1 -> nb [i ]; 3797last_str = i ; 3798last_dim = i ; 3799 } 3800 3801 } 3802// oneDNN handles strided data and does not need overhead of ggml_get_to_fp16_nc_sycl 3803const int64_t ne_src1 = src1 -> nb [last_str ]* src1 -> ne [last_dim ] /type_size_src1 ; 3804src1_f16_alloc .alloc (ne_src1 ); 3805const to_fp16_sycl_t to_fp16_sycl = ggml_get_to_fp16_sycl (src1 -> type ,dst ); 3806GGML_ASSERT (to_fp16_sycl != nullptr ); 3807to_fp16_sycl (src1_f16 ,src1_f16_alloc .get (),ne_src1 ,queue ); 3808# else 3809const int64_t ne_src1 = ggml_nelements (src1 ); 3810src1_f16_alloc .alloc (ne_src1 ); 3811const to_fp16_nc_sycl_t to_fp16_nc_sycl = ggml_get_to_fp16_nc_sycl (src1 -> type ); 3812GGML_ASSERT (to_fp16_nc_sycl != nullptr ); 3813to_fp16_nc_sycl (src1_f16 ,src1_f16_alloc .get (),ne10 ,ne11 ,ne12 ,ne13 ,s11 ,s12 ,s13 ,queue ); 3814#endif 3815 3816src1_f16 = src1_f16_alloc .get (); 3817s11 = ne10 ; 3818s12 = ne11 * s11 ; 3819s13 = ne12 * s12 ; 3820 3821is_src1_cont_2 = true; 3822 } 3823 3824ggml_sycl_pool_alloc < sycl::half > dst_f16 (ctx .pool ()); 3825 3826 dpct::library_data_t mkl_compute_type = dpct::library_data_t::real_float ; 3827 dpct::library_data_t mkl_data_type = dpct::library_data_t::real_float ; 3828 3829// dst strides 3830size_t nbd2 = dst -> nb [2 ]; 3831size_t nbd3 = dst -> nb [3 ]; 3832 3833const float alpha_f32 = 1.0f ; 3834const float beta_f32 = 0.0f ; 3835 3836const void * alpha = & alpha_f32 ; 3837const void * beta = & beta_f32 ; 3838 3839GGML_ASSERT (ne12 %ne02 == 0 ); 3840GGML_ASSERT (ne13 %ne03 == 0 ); 3841GGML_ASSERT (ne01 == static_cast < int64_t > (nb1 /nb0 )); 3842GGML_ASSERT (ne10 == ne00 ); 3843 3844// broadcast factors 3845const int64_t r2 = ne12 /ne02 ; 3846const int64_t r3 = ne13 /ne03 ; 3847 3848#if GGML_SYCL_DNNL 3849if (g_ggml_sycl_enable_dnn ) { 3850int64_t str_a0 = nb00 /type_size_src0 ; 3851int64_t str_a1 = nb01 /type_size_src0 ; 3852int64_t str_a2 = nb02 /type_size_src0 ; 3853 3854int64_t str_b0 = nb10 /type_size_src1 ; 3855int64_t str_b1 = nb11 /type_size_src1 ; 3856int64_t str_b2 = nb12 /type_size_src1 ; 3857 3858auto launch_gemm_for_batches = [& ctx ,queue ](const sycl::half * src0 , 3859const sycl::half * src1 ,float * dst , 3860int64_t a0 ,int64_t a1 ,int64_t batcha , 3861int64_t /*b0*/ ,int64_t b1 ,int64_t batchb , 3862int64_t sa0 ,int64_t sa1 ,int64_t sa2 , 3863int64_t sb0 ,int64_t sb1 ,int64_t sb2 , 3864int64_t sd2 ) { 3865bool supported_broadcast = batchb == batcha ? true 3866 :batchb == 1 || batcha == 1 ? true 3867 : false; 3868if (supported_broadcast ) { 3869DnnlGemmWrapper ::gemm (ctx ,a1 ,b1 ,a0 ,src0 , 3870DnnlGemmWrapper ::to_dt < sycl::half > (),sa0 ,sa1 ,sa2 ,src1 , 3871DnnlGemmWrapper ::to_dt < sycl::half > (),sb0 ,sb1 ,sb2 ,dst , 3872DnnlGemmWrapper ::to_dt < float > (),queue ,batcha ,batchb ); 3873 }else { 3874// iterate over batches from smaller set of matrices (matrix 0) 3875int64_t batches0 = batcha ; 3876int64_t batches1 = batchb ; 3877 3878if (batches0 > batches1 ) { 3879int64_t num_mul_mats = batches1 ; 3880int64_t sub_batch = batches0 /num_mul_mats ; 3881// src0 is batched and bigger, shift and multiply with src1 3882for (int64_t i0 = 0 ;i0 < num_mul_mats ;i0 ++ ) { 3883const sycl::half * src0_shifted = src0 + (sa2 * i0 * sub_batch ); 3884const sycl::half * src1_shifted = src1 + (sb2 * i0 ); 3885float * dst_shifted = dst + (sd2 * i0 * sub_batch ); 3886DnnlGemmWrapper ::gemm (ctx ,a1 ,b1 ,a0 ,src0_shifted , 3887DnnlGemmWrapper ::to_dt < sycl::half > (),sa0 ,sa1 ,sa2 , 3888src1_shifted ,DnnlGemmWrapper ::to_dt < sycl::half > (),sb0 , 3889sb1 ,sb2 ,dst_shifted ,DnnlGemmWrapper ::to_dt < float > (), 3890queue ,sub_batch ,1 ); 3891 } 3892 }else { 3893int64_t num_mul_mats = batches0 ; 3894int64_t sub_batch = batches1 /num_mul_mats ; 3895// src1 is batched and bigger, shift and multiply with src0 3896for (int64_t i1 = 0 ;i1 < num_mul_mats ;i1 ++ ) { 3897const sycl::half * src0_shifted = src0 + (sa2 * i1 ); 3898const sycl::half * src1_shifted = src1 + (sb2 * i1 * sub_batch ); 3899float * dst_shifted = dst + (sd2 * i1 * sub_batch ); 3900DnnlGemmWrapper ::gemm (ctx ,a1 ,b1 ,a0 ,src0_shifted , 3901DnnlGemmWrapper ::to_dt < sycl::half > (),sa0 ,sa1 ,sa2 , 3902src1_shifted ,DnnlGemmWrapper ::to_dt < sycl::half > (),sb0 , 3903sb1 ,sb2 ,dst_shifted ,DnnlGemmWrapper ::to_dt < float > (), 3904queue ,1 ,sub_batch ); 3905 } 3906 } 3907 } 3908 }; 3909 3910const bool cont_batches_dim2_a = nb02 * ne02 == nb03 ; 3911const bool cont_batches_dim2_b = nb12 * ne12 == nb13 ; 3912const bool cont_batches_dim3_a = ne02 == 1 && nb02 * ne01 == nb03 ; 3913const bool cont_batches_dim3_b = ne12 == 1 && nb12 * ne11 == nb13 ; 3914if (cont_batches_dim2_a && cont_batches_dim2_b ) { 3915// A batch is considered contiguous if the dimension 2 is not strided 3916int64_t batches0 = ne02 * ne03 ; 3917int64_t batches1 = ne12 * ne13 ; 3918launch_gemm_for_batches (src0_f16 ,src1_f16 ,dst_ddf ,ne00 ,ne01 ,batches0 , 3919ne10 ,ne11 ,batches1 ,str_a0 ,str_a1 ,str_a2 ,str_b0 ,str_b1 , 3920str_b2 ,nb2 /sizeof (float )); 3921 }else if (cont_batches_dim3_a && cont_batches_dim3_b ) { 3922// This case is similar to the one above with the difference that only the batch in dimension 3 is used and the dimension 2 is of size 1. 3923int64_t batches0 = ne02 * ne03 ; 3924int64_t batches1 = ne12 * ne13 ; 3925int64_t str_a3 = nb03 /type_size_src0 ; 3926int64_t str_b3 = nb13 /type_size_src1 ; 3927launch_gemm_for_batches (src0_f16 ,src1_f16 ,dst_ddf ,ne00 ,ne01 ,batches0 , 3928ne10 ,ne11 ,batches1 ,str_a0 ,str_a1 ,str_a3 ,str_b0 ,str_b1 , 3929str_b3 ,nb2 /sizeof (float )); 3930 }else { 3931for (int64_t b_a = 0 ;b_a < ne03 ;b_a ++ ) { 3932const sycl::half * src0_f16_shifted 3933= src0_f16 + (nb03 * b_a /type_size_src0 ); 3934const sycl::half * src1_f16_shifted 3935= src1_f16 + (nb13 * b_a /type_size_src1 ); 3936float * dst_shifted = dst_ddf + (nb3 * b_a /sizeof (float )); 3937int64_t batches0 = ne02 ; 3938int64_t batches1 = ne12 ; 3939launch_gemm_for_batches (src0_f16_shifted ,src1_f16_shifted ,dst_shifted , 3940ne00 ,ne01 ,batches0 ,ne10 ,ne11 ,batches1 ,str_a0 ,str_a1 , 3941str_a2 ,str_b0 ,str_b1 ,str_b2 ,nb2 /sizeof (float )); 3942 } 3943 } 3944 3945 } 3946else 3947#endif 3948 { 3949if (r2 == 1 && r3 == 1 && is_src0_cont_2 && is_src1_cont_2 ) { 3950// with a [0, 2, 1, 3] perm. and ne02==1 the matrix strides need to be determined from dim 3: 3951const int64_t sma = ne02 == 1 ?nb03 /nb00 :nb02 /nb00 ; 3952const int64_t smb = ne12 == 1 ?s13 :s12 ; 3953 3954// there is no broadcast and src0, src1 are contiguous across dims 2, 3 3955SYCL_CHECK (CHECK_TRY_ERROR (dpct::gemm_batch (* queue , oneapi::mkl::transpose::trans , 3956 oneapi::mkl::transpose::nontrans ,ne01 ,ne11 ,ne10 ,alpha , 3957src0_f16 , dpct::library_data_t::real_half ,nb01 /nb00 ,sma , 3958src1_f16 , dpct::library_data_t::real_half ,s11 ,smb ,beta ,dst_ddf , 3959mkl_data_type ,ne0 ,ne1 * ne0 ,ne12 * ne13 ,mkl_compute_type ))); 3960 }else { 3961const int ne23 = ne12 * ne13 ; 3962 3963ggml_sycl_pool_alloc < const void *> ptrs_src (ctx .pool (),2 * ne23 ); 3964ggml_sycl_pool_alloc < void *> ptrs_dst (ctx .pool (),1 * ne23 ); 3965ggml_sycl_pool_alloc < matrix_info_t < float >> matrix_info (ctx .host_pool (),1 ); 3966 3967 sycl::range < 3 > block_dims (1 ,ne12 ,ne13 ); 3968queue -> submit ([& ](sycl::handler & cgh ) { 3969const void ** ptrs_src_get = ptrs_src .get (); 3970void ** ptrs_dst_get = ptrs_dst .get (); 3971size_t nb12_scaled = src1 -> type == GGML_TYPE_F16 ?nb12 :s12 * sizeof (sycl::half ); 3972size_t nb13_scaled = src1 -> type == GGML_TYPE_F16 ?nb13 :s13 * sizeof (sycl::half ); 3973cgh .parallel_for (sycl::nd_range < 3 > (block_dims ,block_dims ), [= ](sycl::nd_item < 3 > item_ct1 ) { 3974k_compute_batched_ptrs (src0_f16 ,src1_f16 ,dst_ddf ,ptrs_src_get ,ptrs_dst_get ,ne12 ,ne13 ,ne23 ,nb02 , 3975nb03 ,nb12_scaled ,nb13_scaled ,nbd2 ,nbd3 ,r2 ,r3 ,item_ct1 ); 3976 }); 3977 }); 3978 3979SYCL_CHECK (CHECK_TRY_ERROR (dpct::gemm_batch ( 3980* queue , oneapi::mkl::transpose::trans , oneapi::mkl::transpose::nontrans ,ne01 ,ne11 ,ne10 ,alpha , 3981 (const void ** ) (ptrs_src .get ()+ 0 * ne23 ), dpct::library_data_t::real_half ,nb01 /nb00 , 3982 (const void ** ) (ptrs_src .get ()+ 1 * ne23 ), dpct::library_data_t::real_half ,s11 ,beta , 3983 (void ** ) (ptrs_dst .get ()+ 0 * ne23 ),mkl_data_type ,ne0 ,ne23 ,mkl_compute_type ,matrix_info .get ()))); 3984 } 3985 } 3986}catch (const sycl::exception & exc ) { 3987 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ <<", line:" <<__LINE__ << std::endl ; 3988 std::exit (1 ); 3989} 3990 3991enum class mul_mat_algo { 3992DMMV = 0 , 3993MMVQ = 1 , 3994MUL_MAT_SYCL = 2 , 3995}; 3996 3997inline bool ggml_sycl_supports_mmq (enum ggml_type type ) { 3998// TODO: accuracy issues in MMQ 3999GGML_UNUSED (type ); 4000return false; 4001} 4002 4003inline bool ggml_sycl_supports_reorder_mul_mat_sycl (enum ggml_type type ) { 4004switch (type ) { 4005case GGML_TYPE_Q1_0 : 4006case GGML_TYPE_Q4_0 : 4007case GGML_TYPE_Q8_0 : 4008return true; 4009case GGML_TYPE_Q2_K : 4010case GGML_TYPE_Q3_K : 4011case GGML_TYPE_Q4_K : 4012case GGML_TYPE_Q5_K : 4013case GGML_TYPE_Q6_K : 4014return !g_ggml_sycl_prioritize_dmmv ; 4015default : 4016return false; 4017 } 4018} 4019 4020inline bool ggml_sycl_supports_reorder_dmmv (enum ggml_type type ) { 4021switch (type ) { 4022case GGML_TYPE_Q1_0 : 4023case GGML_TYPE_Q4_0 : 4024case GGML_TYPE_Q8_0 : 4025case GGML_TYPE_Q2_K : 4026case GGML_TYPE_Q3_K : 4027case GGML_TYPE_Q4_K : 4028case GGML_TYPE_Q5_K : 4029case GGML_TYPE_Q6_K : 4030return true; 4031default : 4032return false; 4033 } 4034} 4035 4036inline bool ggml_sycl_supports_reorder_mmvq (enum ggml_type type ) { 4037switch (type ) { 4038case GGML_TYPE_Q1_0 : 4039case GGML_TYPE_Q4_0 : 4040case GGML_TYPE_Q8_0 : 4041case GGML_TYPE_Q2_K : 4042case GGML_TYPE_Q3_K : 4043case GGML_TYPE_Q4_K : 4044case GGML_TYPE_Q5_K : 4045case GGML_TYPE_Q6_K : 4046return true; 4047default : 4048return false; 4049 } 4050} 4051 4052static bool ggml_sycl_supports_reorder_esimd (enum ggml_type type ) { 4053#ifdef GGML_SYCL_DMMV_HAS_ESIMD 4054switch (type ) { 4055case GGML_TYPE_Q2_K : 4056case GGML_TYPE_Q3_K : 4057case GGML_TYPE_Q4_K : 4058case GGML_TYPE_Q5_K : 4059case GGML_TYPE_Q6_K : 4060return true; 4061default : 4062return false; 4063 } 4064#else 4065GGML_UNUSED (type ); 4066return false; 4067#endif 4068} 4069 4070static bool ggml_sycl_supports_dmmv (enum ggml_type type ) { 4071switch (type ) { 4072case GGML_TYPE_Q1_0 : 4073case GGML_TYPE_Q4_0 : 4074case GGML_TYPE_Q4_1 : 4075case GGML_TYPE_Q5_0 : 4076case GGML_TYPE_Q5_1 : 4077case GGML_TYPE_Q8_0 : 4078case GGML_TYPE_Q2_K : 4079case GGML_TYPE_Q3_K : 4080case GGML_TYPE_Q4_K : 4081case GGML_TYPE_Q5_K : 4082case GGML_TYPE_Q6_K : 4083case GGML_TYPE_F16 : 4084case GGML_TYPE_BF16 : 4085return true; 4086default : 4087return false; 4088 } 4089} 4090 4091// Helper functions to unify device memory allocation for both async and sync paths 4092static inline void * sycl_ext_malloc_device (dpct::queue_ptr stream ,size_t size ) { 4093bool use_async = g_ggml_sycl_use_async_mem_op ; 4094#if defined(GGML_SYCL_GRAPH )&& SYCL_EXT_ONEAPI_ASYNC_MEMORY_ALLOC 4095if (use_async ) { 4096void * ptr = syclex::async_malloc (* stream , sycl::usm::alloc::device ,size ); 4097ggml_sycl_memtrace_add (GGML_SYCL_MEM_ASYNC ,ptr ,size ); 4098return ptr ; 4099 } 4100#else 4101// If async allocation extension is not available, use_async should always be false. 4102GGML_ASSERT (!use_async ); 4103#endif 4104return ggml_sycl_malloc_device (size ,* stream ); 4105} 4106 4107static inline void sycl_ext_free (dpct::queue_ptr stream ,void * ptr ) { 4108bool use_async = g_ggml_sycl_use_async_mem_op ; 4109#if defined(GGML_SYCL_GRAPH )&& SYCL_EXT_ONEAPI_ASYNC_MEMORY_ALLOC 4110if (use_async ) { 4111ggml_sycl_memtrace_del (ptr ); 4112 syclex::async_free (* stream ,ptr ); 4113return ; 4114 } 4115#else 4116// If async allocation extension is not available, use_async should always be false. 4117GGML_ASSERT (!use_async ); 4118#endif 4119ggml_sycl_free_device (ptr ,* stream ); 4120} 4121 4122// RAII wrapper for temporary reorder buffers with optional host memory fallback. 4123// When device allocation fails and GGML_SYCL_HOST_MEM_FALLBACK is enabled, 4124// falls back to host memory so the reorder kernel can still run (over PCIe). 4125// Device access to host memory requires Linux kernel 6.8+ (Ubuntu 26.04+). 4126struct sycl_reorder_temp_buffer { 4127void * ptr = nullptr ; 4128 dpct::queue_ptr stream ; 4129 4130sycl_reorder_temp_buffer (dpct::queue_ptr stream ,size_t size ) :stream (stream ) { 4131ptr = sycl_ext_malloc_device (stream ,size ); 4132#ifdef GGML_SYCL_HOST_MEM_FALLBACK 4133if (!ptr ) { 4134ptr = sycl::malloc_host (size ,* stream ); 4135if (ptr ) { 4136host_fallback = true; 4137GGML_LOG_WARN ("%s: device alloc of %zu bytes failed, using host memory fallback\n" ,__func__ ,size ); 4138 } 4139 } 4140#endif 4141 } 4142 4143 ~sycl_reorder_temp_buffer () { 4144if (!ptr ) { 4145return ; 4146 } 4147if (host_fallback ) { 4148 sycl::free (ptr ,* stream ); 4149 }else { 4150sycl_ext_free (stream ,ptr ); 4151 } 4152 } 4153 4154explicit operatorbool ()const {return ptr != nullptr ; } 4155 4156sycl_reorder_temp_buffer (const sycl_reorder_temp_buffer & )= delete ; 4157sycl_reorder_temp_buffer & operator= (const sycl_reorder_temp_buffer & )= delete ; 4158 4159private : 4160bool host_fallback = false; 4161}; 4162 4163static bool reorder_qw_q4_0 (uint8_t * data_device ,const int ncols ,const int nrows ,size_t size ,size_t offset , 4164 dpct::queue_ptr stream ) { 4165sycl_reorder_temp_buffer tmp (stream ,size ); 4166if (!tmp ) { 4167GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,size ); 4168return false; 4169 } 4170uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4171 4172 sycl::event copy_event ; 4173SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,size ))); 4174if (!g_ggml_sycl_use_async_mem_op ) { 4175copy_event .wait (); 4176 } 4177 4178GGML_ASSERT ((size %sizeof (block_q4_0 )== 0 )); 4179GGML_ASSERT ((offset %sizeof (block_q4_0 )== 0 )); 4180int offset_blks = offset /sizeof (block_q4_0 ); 4181auto qs_ptr = data_device + offset_blks * QK4_0 /2 ; 4182auto d_ptr = (sycl::half * )(qs_ptr + ncols * nrows /2 )+ offset_blks ; 4183 4184auto reorder_event = stream -> parallel_for ( 4185size /sizeof (block_q4_0 ), 4186 [= ](auto i ) [[sycl ::reqd_sub_group_size (WARP_SIZE )]] { 4187const block_q4_0 * x = (const block_q4_0 * )tmp_buf ; 4188const int ib = i ; 4189 4190for (int j = 0 ;j < QK4_0 /2 ;j ++ ) 4191 { 4192* (qs_ptr + ib * QK4_0 /2 + j )= x [ib ].qs [j ]; 4193 } 4194* (d_ptr + ib )= x [ib ].d ; 4195 }); 4196if (!g_ggml_sycl_use_async_mem_op ) { 4197reorder_event .wait_and_throw (); 4198 } 4199return true; 4200} 4201 4202static bool reorder_qw_q8_0 (uint8_t * data_device ,const int ncols ,const int nrows ,size_t size ,size_t offset , 4203 dpct::queue_ptr stream ) { 4204sycl_reorder_temp_buffer tmp (stream ,size ); 4205if (!tmp ) { 4206GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,size ); 4207return false; 4208 } 4209uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4210 4211 sycl::event copy_event ; 4212SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,size ))); 4213if (!g_ggml_sycl_use_async_mem_op ) { 4214copy_event .wait (); 4215 } 4216 4217GGML_ASSERT ((size %sizeof (block_q8_0 )== 0 )); 4218GGML_ASSERT ((offset %sizeof (block_q8_0 )== 0 )); 4219int offset_blks = offset /sizeof (block_q8_0 ); 4220auto qs_ptr = data_device + offset_blks * QK8_0 ; 4221auto d_ptr = (sycl::half * )(qs_ptr + ncols * nrows )+ offset_blks ; 4222 4223auto reorder_event = stream -> parallel_for ( 4224size /sizeof (block_q8_0 ), 4225 [= ](auto i ) [[sycl ::reqd_sub_group_size (WARP_SIZE )]] { 4226const block_q8_0 * x = (const block_q8_0 * )tmp_buf ; 4227const int ib = i ; 4228 4229for (int j = 0 ;j < QK8_0 ;j ++ ) 4230 { 4231* ((int8_t * )qs_ptr + ib * QK8_0 + j )= x [ib ].qs [j ]; 4232 } 4233* (d_ptr + ib )= x [ib ].d ; 4234 }); 4235if (!g_ggml_sycl_use_async_mem_op ) { 4236reorder_event .wait_and_throw (); 4237 } 4238return true; 4239} 4240 4241static bool reorder_qw_q4_k (uint8_t * data_device ,size_t size ,size_t offset , dpct::queue_ptr stream ) { 4242GGML_ASSERT (size %sizeof (block_q4_K )== 0 ); 4243GGML_ASSERT (offset %sizeof (block_q4_K )== 0 ); 4244 4245const int nblocks = size /sizeof (block_q4_K ); 4246 4247sycl_reorder_temp_buffer tmp (stream ,size ); 4248if (!tmp ) { 4249GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,size ); 4250return false; 4251 } 4252uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4253 4254 sycl::event copy_event ; 4255SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,size ))); 4256if (!g_ggml_sycl_use_async_mem_op ) { 4257copy_event .wait (); 4258 } 4259 4260auto * qs_ptr = data_device ; 4261auto * scales_ptr = qs_ptr + QK_K /2 * nblocks ; 4262auto * dm_ptr = (sycl::half2 * ) (scales_ptr + K_SCALE_SIZE * nblocks ); 4263 4264auto reorder_event = stream -> parallel_for (nblocks , [= ](auto i ) { 4265const block_q4_K * x = (const block_q4_K * )tmp_buf ; 4266const int ib = i ; 4267 4268for (int j = 0 ;j < QK_K /2 ;++ j ) { 4269qs_ptr [ib * (QK_K /2 )+ j ]= x [ib ].qs [j ]; 4270 } 4271 4272for (int j = 0 ;j < K_SCALE_SIZE ;++ j ) { 4273scales_ptr [ib * K_SCALE_SIZE + j ]= x [ib ].scales [j ]; 4274 } 4275 4276dm_ptr [ib ]= x [ib ].dm ; 4277 }); 4278if (!g_ggml_sycl_use_async_mem_op ) { 4279reorder_event .wait_and_throw (); 4280 } 4281return true; 4282} 4283 4284// Reorder each expert slice into a self-contained SoA layout. 4285static bool reorder_qw_q4_k_moe (uint8_t * data_device ,size_t expert_bytes ,int64_t n_expert , dpct::queue_ptr stream ) { 4286GGML_ASSERT (expert_bytes %sizeof (block_q4_K )== 0 ); 4287const int blocks_per_expert = (int ) (expert_bytes /sizeof (block_q4_K )); 4288const size_t total_bytes = expert_bytes * (size_t )n_expert ; 4289 4290sycl_reorder_temp_buffer tmp (stream ,total_bytes ); 4291if (!tmp ) { 4292GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,total_bytes ); 4293return false; 4294 } 4295uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4296 4297 sycl::event copy_event ; 4298SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,total_bytes ))); 4299if (!g_ggml_sycl_use_async_mem_op ) { 4300copy_event .wait (); 4301 } 4302 4303const int total_blocks = blocks_per_expert * (int )n_expert ; 4304auto reorder_event = stream -> parallel_for (total_blocks , [= ](auto gb_ ) { 4305const int gb = gb_ ; 4306const int e = gb /blocks_per_expert ; 4307const int ib = gb %blocks_per_expert ; 4308const block_q4_K * x = (const block_q4_K * ) (tmp_buf + (size_t )e * expert_bytes ); 4309uint8_t * base = data_device + (size_t )e * expert_bytes ; 4310 4311auto * qs_ptr = base ; 4312auto * scales_ptr = qs_ptr + QK_K /2 * blocks_per_expert ; 4313auto * dm_ptr = (sycl::half2 * ) (scales_ptr + K_SCALE_SIZE * blocks_per_expert ); 4314 4315for (int j = 0 ;j < QK_K /2 ;++ j ) { 4316qs_ptr [ib * (QK_K /2 )+ j ]= x [ib ].qs [j ]; 4317 } 4318for (int j = 0 ;j < K_SCALE_SIZE ;++ j ) { 4319scales_ptr [ib * K_SCALE_SIZE + j ]= x [ib ].scales [j ]; 4320 } 4321dm_ptr [ib ]= x [ib ].dm ; 4322 }); 4323if (!g_ggml_sycl_use_async_mem_op ) { 4324reorder_event .wait_and_throw (); 4325 } 4326return true; 4327} 4328 4329// Reorder each Q5_K expert slice into [qs][qh][scales][dm]. 4330static bool reorder_qw_q5_k_moe (uint8_t * data_device ,size_t expert_bytes ,int64_t n_expert , dpct::queue_ptr stream ) { 4331GGML_ASSERT (expert_bytes %sizeof (block_q5_K )== 0 ); 4332const int blocks_per_expert = (int ) (expert_bytes /sizeof (block_q5_K )); 4333const size_t total_bytes = expert_bytes * (size_t )n_expert ; 4334 4335sycl_reorder_temp_buffer tmp (stream ,total_bytes ); 4336if (!tmp ) { 4337GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,total_bytes ); 4338return false; 4339 } 4340uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4341 4342 sycl::event copy_event ; 4343SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,total_bytes ))); 4344if (!g_ggml_sycl_use_async_mem_op ) { 4345copy_event .wait (); 4346 } 4347 4348const int total_blocks = blocks_per_expert * (int )n_expert ; 4349auto reorder_event = stream -> parallel_for (total_blocks , [= ](auto gb_ ) { 4350const int gb = gb_ ; 4351const int e = gb /blocks_per_expert ; 4352const int ib = gb %blocks_per_expert ; 4353const block_q5_K * x = (const block_q5_K * ) (tmp_buf + (size_t )e * expert_bytes ); 4354uint8_t * base = data_device + (size_t )e * expert_bytes ; 4355 4356auto * qs_ptr = base ; 4357auto * qh_ptr = qs_ptr + (QK_K /2 )* blocks_per_expert ; 4358auto * scales_ptr = qh_ptr + (QK_K /8 )* blocks_per_expert ; 4359auto * dm_ptr = (sycl::half2 * ) (scales_ptr + K_SCALE_SIZE * blocks_per_expert ); 4360 4361for (int j = 0 ;j < QK_K /2 ;++ j ) { 4362qs_ptr [ib * (QK_K /2 )+ j ]= x [ib ].qs [j ]; 4363 } 4364for (int j = 0 ;j < QK_K /8 ;++ j ) { 4365qh_ptr [ib * (QK_K /8 )+ j ]= x [ib ].qh [j ]; 4366 } 4367for (int j = 0 ;j < K_SCALE_SIZE ;++ j ) { 4368scales_ptr [ib * K_SCALE_SIZE + j ]= x [ib ].scales [j ]; 4369 } 4370dm_ptr [ib ]= x [ib ].dm ; 4371 }); 4372if (!g_ggml_sycl_use_async_mem_op ) { 4373reorder_event .wait_and_throw (); 4374 } 4375return true; 4376} 4377 4378// Reorder each Q6_K expert slice into [ql][qh][scales][d]. 4379static bool reorder_qw_q6_k_moe (uint8_t * data_device ,size_t expert_bytes ,int64_t n_expert , dpct::queue_ptr stream ) { 4380GGML_ASSERT (expert_bytes %sizeof (block_q6_K )== 0 ); 4381const int blocks_per_expert = (int ) (expert_bytes /sizeof (block_q6_K )); 4382const size_t total_bytes = expert_bytes * (size_t )n_expert ; 4383 4384sycl_reorder_temp_buffer tmp (stream ,total_bytes ); 4385if (!tmp ) { 4386GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,total_bytes ); 4387return false; 4388 } 4389uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4390 4391 sycl::event copy_event ; 4392SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,total_bytes ))); 4393if (!g_ggml_sycl_use_async_mem_op ) { 4394copy_event .wait (); 4395 } 4396 4397const int total_blocks = blocks_per_expert * (int )n_expert ; 4398auto reorder_event = stream -> parallel_for (total_blocks , [= ](auto gb_ ) { 4399const int gb = gb_ ; 4400const int e = gb /blocks_per_expert ; 4401const int ib = gb %blocks_per_expert ; 4402const block_q6_K * x = (const block_q6_K * ) (tmp_buf + (size_t )e * expert_bytes ); 4403uint8_t * base = data_device + (size_t )e * expert_bytes ; 4404 4405auto * ql_ptr = base ; 4406auto * qh_ptr = ql_ptr + (QK_K /2 )* blocks_per_expert ; 4407auto * scales_ptr = qh_ptr + (QK_K /4 )* blocks_per_expert ; 4408auto * d_ptr = (sycl::half * ) (scales_ptr + (QK_K /16 )* blocks_per_expert ); 4409 4410for (int j = 0 ;j < QK_K /2 ;++ j ) { 4411ql_ptr [ib * (QK_K /2 )+ j ]= x [ib ].ql [j ]; 4412 } 4413for (int j = 0 ;j < QK_K /4 ;++ j ) { 4414qh_ptr [ib * (QK_K /4 )+ j ]= x [ib ].qh [j ]; 4415 } 4416for (int j = 0 ;j < QK_K /16 ;++ j ) { 4417scales_ptr [ib * (QK_K /16 )+ j ]= x [ib ].scales [j ]; 4418 } 4419d_ptr [ib ]= x [ib ].d ; 4420 }); 4421if (!g_ggml_sycl_use_async_mem_op ) { 4422reorder_event .wait_and_throw (); 4423 } 4424return true; 4425} 4426 4427static bool reorder_qw_q2_k (uint8_t * data_device ,size_t size ,size_t offset , dpct::queue_ptr stream ) { 4428GGML_ASSERT (size %sizeof (block_q2_K )== 0 ); 4429GGML_ASSERT (offset %sizeof (block_q2_K )== 0 ); 4430 4431const int nblocks = size /sizeof (block_q2_K ); 4432 4433sycl_reorder_temp_buffer tmp (stream ,size ); 4434if (!tmp ) { 4435GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,size ); 4436return false; 4437 } 4438uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4439 4440 sycl::event copy_event ; 4441SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,size ))); 4442if (!g_ggml_sycl_use_async_mem_op ) { 4443copy_event .wait (); 4444 } 4445 4446auto * qs_ptr = data_device ; 4447auto * scales_ptr = qs_ptr + (QK_K /4 )* nblocks ; 4448 sycl::half2 * dm_ptr = (sycl::half2 * ) (scales_ptr + (QK_K /16 )* nblocks ); 4449 4450auto reorder_event = stream -> parallel_for (nblocks , [= ](auto i ) { 4451const block_q2_K * x = (const block_q2_K * )tmp_buf ; 4452const int ib = i ; 4453 4454for (int j = 0 ;j < QK_K /4 ;++ j ) { 4455qs_ptr [ib * (QK_K /4 )+ j ]= x [ib ].qs [j ]; 4456 } 4457 4458for (int j = 0 ;j < QK_K /16 ;++ j ) { 4459scales_ptr [ib * (QK_K /16 )+ j ]= x [ib ].scales [j ]; 4460 } 4461 4462dm_ptr [ib ]= x [ib ].dm ; 4463 }); 4464if (!g_ggml_sycl_use_async_mem_op ) { 4465reorder_event .wait_and_throw (); 4466 } 4467return true; 4468} 4469 4470static bool reorder_qw_q3_k (uint8_t * data_device ,size_t size ,size_t offset , dpct::queue_ptr stream ) { 4471GGML_ASSERT (size %sizeof (block_q3_K )== 0 ); 4472GGML_ASSERT (offset %sizeof (block_q3_K )== 0 ); 4473 4474const int nblocks = size /sizeof (block_q3_K ); 4475 4476sycl_reorder_temp_buffer tmp (stream ,size ); 4477if (!tmp ) { 4478GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,size ); 4479return false; 4480 } 4481uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4482 4483 sycl::event copy_event ; 4484SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,size ))); 4485if (!g_ggml_sycl_use_async_mem_op ) { 4486copy_event .wait (); 4487 } 4488 4489auto * qs_ptr = data_device ; 4490auto * hmask_ptr = qs_ptr + (QK_K /4 )* nblocks ; 4491auto * scales_ptr = hmask_ptr + (QK_K /8 )* nblocks ; 4492 sycl::half * d_ptr = (sycl::half * ) (scales_ptr + 12 * nblocks ); 4493 4494auto reorder_event = stream -> parallel_for (nblocks , [= ](auto i ) { 4495const block_q3_K * x = (const block_q3_K * )tmp_buf ; 4496const int ib = i ; 4497 4498for (int j = 0 ;j < QK_K /4 ;++ j ) { 4499qs_ptr [ib * (QK_K /4 )+ j ]= x [ib ].qs [j ]; 4500 } 4501 4502for (int j = 0 ;j < QK_K /8 ;++ j ) { 4503hmask_ptr [ib * (QK_K /8 )+ j ]= x [ib ].hmask [j ]; 4504 } 4505 4506for (int j = 0 ;j < 12 ;++ j ) { 4507scales_ptr [ib * 12 + j ]= x [ib ].scales [j ]; 4508 } 4509 4510d_ptr [ib ]= x [ib ].d ; 4511 }); 4512if (!g_ggml_sycl_use_async_mem_op ) { 4513reorder_event .wait_and_throw (); 4514 } 4515return true; 4516} 4517 4518static bool reorder_qw_q5_k (uint8_t * data_device ,size_t size ,size_t offset , dpct::queue_ptr stream ) { 4519GGML_ASSERT (size %sizeof (block_q5_K )== 0 ); 4520GGML_ASSERT (offset %sizeof (block_q5_K )== 0 ); 4521 4522const int nblocks = size /sizeof (block_q5_K ); 4523 4524sycl_reorder_temp_buffer tmp (stream ,size ); 4525if (!tmp ) { 4526GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,size ); 4527return false; 4528 } 4529uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4530 4531 sycl::event copy_event ; 4532SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,size ))); 4533if (!g_ggml_sycl_use_async_mem_op ) { 4534copy_event .wait (); 4535 } 4536 4537auto * qs_ptr = data_device ; 4538auto * qh_ptr = qs_ptr + (QK_K /2 )* nblocks ; 4539auto * scales_ptr = qh_ptr + (QK_K /8 )* nblocks ; 4540auto * dm_ptr = (sycl::half2 * ) (scales_ptr + K_SCALE_SIZE * nblocks ); 4541 4542auto reorder_event = stream -> parallel_for (nblocks , [= ](auto i ) { 4543const block_q5_K * x = (const block_q5_K * )tmp_buf ; 4544const int ib = i ; 4545 4546for (int j = 0 ;j < QK_K /2 ;++ j ) { 4547qs_ptr [ib * (QK_K /2 )+ j ]= x [ib ].qs [j ]; 4548 } 4549 4550for (int j = 0 ;j < QK_K /8 ;++ j ) { 4551qh_ptr [ib * (QK_K /8 )+ j ]= x [ib ].qh [j ]; 4552 } 4553 4554for (int j = 0 ;j < K_SCALE_SIZE ;++ j ) { 4555scales_ptr [ib * K_SCALE_SIZE + j ]= x [ib ].scales [j ]; 4556 } 4557 4558dm_ptr [ib ]= x [ib ].dm ; 4559 }); 4560if (!g_ggml_sycl_use_async_mem_op ) { 4561reorder_event .wait_and_throw (); 4562 } 4563return true; 4564} 4565 4566static bool reorder_qw_q6_k (uint8_t * data_device ,size_t size ,size_t offset , dpct::queue_ptr stream ) { 4567GGML_ASSERT (size %sizeof (block_q6_K )== 0 ); 4568GGML_ASSERT (offset %sizeof (block_q6_K )== 0 ); 4569 4570const int nblocks = size /sizeof (block_q6_K ); 4571 4572sycl_reorder_temp_buffer tmp (stream ,size ); 4573if (!tmp ) { 4574GGML_LOG_WARN ("%s: failed to allocate %zu bytes for reorder temp buffer, skipping reorder\n" ,__func__ ,size ); 4575return false; 4576 } 4577uint8_t * tmp_buf = static_cast < uint8_t *> (tmp .ptr ); 4578 4579 sycl::event copy_event ; 4580SYCL_CHECK (CHECK_TRY_ERROR (copy_event = stream -> memcpy (tmp_buf ,data_device ,size ))); 4581if (!g_ggml_sycl_use_async_mem_op ) { 4582copy_event .wait (); 4583 } 4584 4585auto * ql_ptr = data_device ; 4586auto * qh_ptr = ql_ptr + (QK_K /2 )* nblocks ; 4587auto * scales_ptr = qh_ptr + (QK_K /4 )* nblocks ; 4588 sycl::half * dm_ptr = (sycl::half * ) (scales_ptr + (QK_K /16 )* nblocks ); 4589 4590auto reorder_event = stream -> parallel_for (nblocks , [= ](auto i ) { 4591const block_q6_K * x = (const block_q6_K * )tmp_buf ; 4592const int ib = i ; 4593 4594const uint8_t * ql = x [ib ].ql ; 4595const uint8_t * qh = x [ib ].qh ; 4596uint8_t * base_ql_ptr = ql_ptr + (QK_K /2 )* ib ; 4597uint8_t * base_qh_ptr = qh_ptr + (QK_K /4 )* ib ; 4598uint8_t * base_scales_ptr = scales_ptr + (QK_K /16 )* ib ; 4599 4600for (int j = 0 ;j < QK_K /2 ;++ j ) { 4601base_ql_ptr [j ]= ql [j ]; 4602 } 4603for (int j = 0 ;j < QK_K /4 ;++ j ) { 4604base_qh_ptr [j ]= qh [j ]; 4605 } 4606 4607for (int j = 0 ;j < QK_K /16 ;++ j ) { 4608base_scales_ptr [j ]= x [ib ].scales [j ]; 4609 } 4610 4611dm_ptr [ib ]= x [ib ].d ; 4612 }); 4613if (!g_ggml_sycl_use_async_mem_op ) { 4614reorder_event .wait_and_throw (); 4615 } 4616return true; 4617} 4618 4619static bool reorder_qw (const ggml_tensor * src0 , dpct::queue_ptr stream ) { 4620uint8_t * data_device = (uint8_t * )src0 -> data ; 4621size_t ncols = src0 -> ne [0 ]; 4622size_t nrows = src0 -> ne [1 ]; 4623size_t size = ggml_nbytes (src0 ); 4624 4625// MoE expert weights are addressed per expert via nb[2], so each slice must 4626// remain self-contained after reorder. 4627if (src0 -> ne [2 ]> 1 ) { 4628GGML_ASSERT ((size_t )size == (size_t )src0 -> ne [2 ]* src0 -> nb [2 ]); 4629switch (src0 -> type ) { 4630case GGML_TYPE_Q4_K : 4631return reorder_qw_q4_k_moe (data_device ,src0 -> nb [2 ],src0 -> ne [2 ],stream ); 4632case GGML_TYPE_Q5_K : 4633return reorder_qw_q5_k_moe (data_device ,src0 -> nb [2 ],src0 -> ne [2 ],stream ); 4634case GGML_TYPE_Q6_K : 4635return reorder_qw_q6_k_moe (data_device ,src0 -> nb [2 ],src0 -> ne [2 ],stream ); 4636default : 4637return false; 4638 } 4639 } 4640 4641switch (src0 -> type ) { 4642case GGML_TYPE_Q4_0 : 4643return reorder_qw_q4_0 (data_device ,ncols ,nrows ,size ,0 ,stream ); 4644case GGML_TYPE_Q8_0 : 4645return reorder_qw_q8_0 (data_device ,ncols ,nrows ,size ,0 ,stream ); 4646case GGML_TYPE_Q2_K : 4647return reorder_qw_q2_k (data_device ,size ,0 ,stream ); 4648case GGML_TYPE_Q3_K : 4649return reorder_qw_q3_k (data_device ,size ,0 ,stream ); 4650case GGML_TYPE_Q4_K : 4651return reorder_qw_q4_k (data_device ,size ,0 ,stream ); 4652case GGML_TYPE_Q5_K : 4653return reorder_qw_q5_k (data_device ,size ,0 ,stream ); 4654case GGML_TYPE_Q6_K : 4655return reorder_qw_q6_k (data_device ,size ,0 ,stream ); 4656default : 4657return false; 4658 } 4659} 4660 4661static bool should_reorder_tensor (ggml_backend_sycl_context & ctx ,const ggml_tensor * dst ) { 4662return g_ggml_sycl_enable_optimize && //allow optimize, controlled by $GGML_SYCL_ENABLE_OPT 4663ctx .opt_feature .reorder && //allow this device due to good perf, skip the devices with bad perf. 4664dst -> op == GGML_OP_MUL_MAT && //limit to some supported cases of Q4_0, to do for more cases. 4665// ne[1] <= 8 so multi-column decode (spec / MTP verify) also bootstraps the reorder; 4666// all reorderable types have a _switch_ncols kernel. 4667dst -> src [1 ]-> ne [1 ] <=8 && dst -> src [1 ]-> ne [2 ]== 1 && dst -> src [1 ]-> ne [3 ]== 1 ; 4668} 4669 4670static void opt_for_reorder (ggml_backend_sycl_context * ctx ,const ggml_tensor * src0 ,const ggml_tensor * /* src1 */ , 4671ggml_tensor * dst ,mul_mat_algo mm_algorithm ) { 4672if (!should_reorder_tensor (* ctx ,dst )) { 4673return ; 4674 } 4675 4676ggml_tensor_extra_gpu * extra = static_cast < ggml_tensor_extra_gpu *> (src0 -> extra ); 4677if (!extra || extra -> optimized_feature .reorder ) { 4678return ;// Skip permutations and already reordered tensors 4679 } 4680 4681switch (mm_algorithm ) { 4682case mul_mat_algo::DMMV : 4683if (!ggml_sycl_supports_reorder_dmmv (src0 -> type )) { 4684return ; 4685 } 4686break ; 4687case mul_mat_algo::MMVQ : 4688if (!ggml_sycl_supports_reorder_mmvq (src0 -> type )) { 4689return ; 4690 } 4691break ; 4692case mul_mat_algo::MUL_MAT_SYCL : 4693if (!ggml_sycl_supports_reorder_mul_mat_sycl (src0 -> type )) { 4694return ; 4695 } 4696break ; 4697 } 4698 4699if (reorder_qw (src0 ,ctx -> stream ())) { 4700extra -> optimized_feature .reorder = true;// Used to decode/dequan in next steps and avoid re-reordering 4701 } 4702} 4703 4704// Lazily reorder supported MoE expert weights once their fused path is used. 4705static void opt_for_reorder_id (ggml_backend_sycl_context * ctx ,const ggml_tensor * src0 ) { 4706if (!g_ggml_sycl_enable_optimize || !ctx -> opt_feature .reorder ) { 4707return ; 4708 } 4709if (src0 -> type != GGML_TYPE_Q4_K && src0 -> type != GGML_TYPE_Q5_K && src0 -> type != GGML_TYPE_Q6_K ) { 4710return ; 4711 } 4712ggml_tensor_extra_gpu * extra = static_cast < ggml_tensor_extra_gpu *> (src0 -> extra ); 4713if (!extra || extra -> optimized_feature .reorder ) { 4714return ; 4715 } 4716if (reorder_qw (src0 ,ctx -> stream ())) { 4717extra -> optimized_feature .reorder = true; 4718 } 4719} 4720 4721 4722static bool can_use_dequantize_mul_mat_vec (const ggml_tensor * src0 ,const ggml_tensor * src1 ,ggml_tensor * dst ) { 4723// The F16/BF16 qk=1 kernel iterates with stride 2*DMMV_X, requiring ne[0] to be 4724// a multiple of 2*DMMV_X. Quantized types use block-structured kernels that only 4725// need ne[0] % DMMV_X == 0. 4726const int64_t dmmv_x_required = (src0 -> type == GGML_TYPE_BF16 || src0 -> type == GGML_TYPE_F16 ) ? 47272 * GGML_SYCL_DMMV_X :GGML_SYCL_DMMV_X ; 4728return ggml_sycl_supports_dmmv (src0 -> type )&& src1 -> type == GGML_TYPE_F32 && dst -> type == GGML_TYPE_F32 && 4729src0 -> ne [0 ] %dmmv_x_required == 0 && src1 -> ne [1 ]== 1 ; 4730} 4731 4732static bool can_use_mul_mat_vec_q (const ggml_tensor * src0 ,const ggml_tensor * src1 ,ggml_tensor * dst ) { 4733return ggml_is_quantized (src0 -> type )&& src1 -> type == GGML_TYPE_F32 && dst -> type == GGML_TYPE_F32 && 4734src1 -> ne [1 ] <=MMVQ_MAX_BATCH_SIZE ; 4735} 4736 4737static void ggml_sycl_mul_mat (ggml_backend_sycl_context & ctx ,const ggml_tensor * src0 ,const ggml_tensor * src1 ,ggml_tensor * dst ) { 4738scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 2 ); 4739 4740// Handle HADAMARAD hint given from further up the pipeline and pass it to the correct 4741// kernel. 4742// 4743// The op check is not redundant: this backend also routes MUL_MAT_ID through here with a 4744// stack copy of dst, which carries MUL_MAT_ID's own op_params. ggml_mul_mat_set_hint() 4745// asserts GGML_OP_MUL_MAT for the same reason. 4746if (dst -> op == GGML_OP_MUL_MAT && ggml_get_op_params_i32 (dst ,1 )== GGML_HINT_SRC0_IS_HADAMARD && 4747ggml_sycl_op_fwht (ctx ,src1 ,dst )) { 4748return ; 4749 } 4750 4751const bool split = ggml_backend_buffer_is_sycl_split (src0 -> buffer ); 4752int64_t min_compute_capability = INT_MAX ; 4753 4754if (split ) { 4755ggml_backend_sycl_split_buffer_type_context * buft_ctx = 4756 (ggml_backend_sycl_split_buffer_type_context * )src0 -> buffer -> buft -> context ; 4757auto & tensor_split = buft_ctx -> tensor_split ; 4758for (int id = 0 ;id < ggml_sycl_info ().device_count ;++ id ) { 4759// skip devices that are not going to do any work: 4760if (tensor_split [id ] >= (id + 1 < ggml_sycl_info ().device_count ?tensor_split [id + 1 ] :1.0f )) { 4761continue ; 4762 } 4763 4764if (min_compute_capability > ggml_sycl_info ().devices [id ].cc ) { 4765min_compute_capability = ggml_sycl_info ().devices [id ].cc ; 4766 } 4767 } 4768 }else { 4769min_compute_capability = ggml_sycl_info ().devices [ctx .device ].cc ; 4770 } 4771 4772// check data types and tensor shapes for custom matrix multiplication kernels: 4773bool use_dequantize_mul_mat_vec = can_use_dequantize_mul_mat_vec (src0 ,src1 ,dst ); 4774 4775bool use_mul_mat_vec_q = can_use_mul_mat_vec_q (src0 ,src1 ,dst ); 4776 4777bool use_mul_mat_q = ggml_sycl_supports_mmq (src0 -> type ) 4778&& src1 -> type == GGML_TYPE_F32 && dst -> type == GGML_TYPE_F32 ; 4779 4780 4781// mmvq and mmq need the __dp4a instruction which is available for gen12+ 4782// Workaround in https://github.com/ggml-org/llama.cpp/commit/95f84d5ce8b449a9b16009434aca800df504a02e 4783use_mul_mat_q = use_mul_mat_q && (src0 -> type != GGML_TYPE_IQ2_XXS ); 4784#ifdef SYCL_USE_XMX 4785use_mul_mat_q = use_mul_mat_q && (src1 -> ne [1 ] <=MMQ_MAX_BATCH_SIZE ); 4786#endif // SYCL_USE_XMX 4787 4788// When reorder is enabled, both ESIMD, MMVQ and DMMV kernels may be used. For 4789// best performance use ESIMD when supported, followed by MMVQ, and finally DMMV. 4790// But the reordered ESIMD path cannot be used without reordered MMVQ. A later 4791// multi-token call (ne[1] in 2..8) will take the MMVQ path and it would read the 4792// reordered bytes as if they were still the unreordered layout. 4793 4794if (!g_ggml_sycl_prioritize_dmmv && ((should_reorder_tensor (ctx ,dst )&& 4795ggml_sycl_supports_reorder_mmvq (src0 -> type )))) { 4796bool use = g_ggml_sycl_enable_esimd && ggml_sycl_supports_reorder_esimd (src0 -> type ); 4797// Arc770 get benefit with Q4_0 by skipping MMVQ path 4798if (!(ggml_sycl_info ().devices [ctx .device ].hw_info .arch == 4799 gpu_arch::intel_gpu_acm_g10 && 4800src0 -> type == GGML_TYPE_Q4_0 )) { 4801use = use || !use_mul_mat_vec_q ; 4802 } 4803use_dequantize_mul_mat_vec = use_dequantize_mul_mat_vec && use ; 4804 } 4805 4806if (!split && src0 -> type == GGML_TYPE_F16 && ggml_is_permuted (src0 )&& ggml_is_permuted (src1 )&& src1 -> ne [1 ]== 1 ) { 4807// TODO: Refactor and cleanup of mul mat dispatching. 4808if (src0 -> ne [3 ]== 1 && src1 -> ne [3 ]== 1 ) { 4809// KQ single-batch 4810// mmv p021 was specific for these dimensions 4811ggml_sycl_mul_mat_vec_p021 (ctx ,src0 ,src1 ,dst ); 4812 }else { 4813// The kernel from the if path is faster for that specific case, but does not support all mul mats. 4814ggml_sycl_mul_mat_batched_sycl (ctx ,src0 ,src1 ,dst ); 4815 } 4816 }else if (!split && src0 -> type == GGML_TYPE_F16 && !ggml_is_contiguous (src0 )&& !ggml_is_transposed (src1 )&& src1 -> ne [1 ]== 1 && src1 -> ne [3 ]== 1 ) { 4817// KQV single-batch 4818ggml_sycl_mul_mat_vec_nc (ctx ,src0 ,src1 ,dst ); 4819 }else if (!split && src0 -> type == GGML_TYPE_F16 && !ggml_is_transposed (src0 )&& !ggml_is_transposed (src1 )&& src1 -> ne [2 ]* src1 -> ne [3 ]> 1 ) { 4820// KQ + KQV multi-batch 4821ggml_sycl_mul_mat_batched_sycl (ctx ,src0 ,src1 ,dst ); 4822 }else if (use_dequantize_mul_mat_vec ) { 4823opt_for_reorder (& ctx ,src0 ,src1 ,dst , mul_mat_algo::DMMV ); 4824ggml_sycl_op_mul_mat < no_quantize_q8_1 > (ctx ,src0 ,src1 ,dst ,ggml_sycl_op_dequantize_mul_mat_vec ); 4825 }else if (use_mul_mat_vec_q ) { 4826opt_for_reorder (& ctx ,src0 ,src1 ,dst , mul_mat_algo::MMVQ ); 4827ggml_tensor_extra_gpu * extra = static_cast < ggml_tensor_extra_gpu *> (src0 -> extra ); 4828if (extra && extra -> optimized_feature .reorder ) { 4829ggml_sycl_op_mul_mat < quantize_and_reorder_q8_1_soa > (ctx ,src0 ,src1 ,dst ,ggml_sycl_op_mul_mat_vec_q ); 4830 }else { 4831ggml_sycl_op_mul_mat < quantize_q8_1 > (ctx ,src0 ,src1 ,dst ,ggml_sycl_op_mul_mat_vec_q ); 4832 } 4833 }else if (use_mul_mat_q ) { 4834ggml_sycl_op_mul_mat < quantize_q8_1 > (ctx ,src0 ,src1 ,dst ,ggml_sycl_op_mul_mat_q ); 4835 }else { 4836ggml_sycl_op_mul_mat < no_quantize_q8_1 > (ctx ,src0 ,src1 ,dst ,ggml_sycl_op_mul_mat_sycl ); 4837 } 4838} 4839 4840// Fused dense-FFN mat-vec for the {mul_mat(gate), mul_mat(up), GLU} subgraph at node_idx. 4841// Returns false if it declined, in which case the caller runs the three nodes normally. 4842static bool ggml_sycl_mul_mat_glu_mmvq_fused (ggml_backend_sycl_context & ctx ,ggml_cgraph * cgraph ,int node_idx ) { 4843if (!ggml_sycl_can_fuse (cgraph ,node_idx , {GGML_OP_MUL_MAT ,GGML_OP_MUL_MAT ,GGML_OP_GLU }, {})) { 4844return false; 4845 } 4846 4847ggml_tensor * glu = cgraph -> nodes [node_idx + 2 ]; 4848ggml_tensor * gate = glu -> src [0 ]; 4849ggml_tensor * up = glu -> src [1 ]; 4850const ggml_tensor * wu = up -> src [0 ]; 4851const ggml_tensor * wg = gate -> src [0 ]; 4852const ggml_tensor * act = up -> src [1 ]; 4853 4854// this writes glu->data directly rather than the per-device row slices that 4855// ggml_sycl_op_mul_mat() stitches back together, so it cannot serve split weights 4856if (ggml_backend_buffer_is_sycl_split (wu -> buffer )|| ggml_backend_buffer_is_sycl_split (wg -> buffer )) { 4857return false; 4858 } 4859 4860// with DMMV prioritised the unfused path would not have gone through mmvq at all 4861if (g_ggml_sycl_prioritize_dmmv ) { 4862return false; 4863 } 4864 4865// install the reorder (SoA) layout the fused kernel needs, as the unfused mmvq path would; 4866// a no-op once done. after the bail checks so a declined op does not pay for it. 4867opt_for_reorder (& ctx ,wu ,act ,up , mul_mat_algo::MMVQ ); 4868opt_for_reorder (& ctx ,wg ,act ,gate , mul_mat_algo::MMVQ ); 4869 4870const auto * extra_u = static_cast < const ggml_tensor_extra_gpu *> (wu -> extra ); 4871const auto * extra_g = static_cast < const ggml_tensor_extra_gpu *> (wg -> extra ); 4872if (!extra_u || !extra_g || !extra_u -> optimized_feature .reorder || !extra_g -> optimized_feature .reorder ) { 4873return false; 4874 } 4875 4876// log the up mat-mul: glu's own srcs are the two intermediates the fusion never materialises 4877scope_op_debug_print scope_dbg_print (__func__ ,up ,/*num_src=*/ 2 ," : fused with gate + GLU" ); 4878 4879const int64_t ne00 = wu -> ne [0 ]; 4880const int64_t ne11 = act -> ne [1 ]; 4881 4882const queue_ptr stream = ctx .stream (); 4883const int src1_padded_cols = GGML_PAD ((int )ne00 ,MATRIX_ROW_PADDING ); 4884 4885// one activation, quantized once and fully consumed into src1_ddq before the GEMV on this 4886// in-order queue, so glu->data aliasing the dead activation needs no memory-range check 4887ggml_sycl_pool_alloc < char > src1_q8_alloc (ctx .pool (), 4888 (size_t )ne11 * src1_padded_cols * sizeof (block_q8_1 ) /QK8_1 ); 4889char * src1_ddq = src1_q8_alloc .get (); 4890 4891quantize_row_q8_1_sycl < quantize_and_reorder_q8_1_soa > ((const float * )act -> data ,src1_ddq , (int )ne00 , (int )ne11 , 4892src1_padded_cols ,stream ); 4893 4894return ggml_sycl_mul_mat_vec_q_glu_reorder (wu -> type ,ggml_get_glu_op (glu ),wu -> data ,wg -> data ,src1_ddq , 4895 (float * )glu -> data , (int )ne00 , (int )wu -> ne [1 ], (int )ne11 , 4896/*stride_col_y_bytes=*/ src1_padded_cols * (int )sizeof (block_q8_1 ) / 4897QK8_1 , 4898/*stride_col_dst=*/ (int )glu -> ne [0 ],stream ); 4899} 4900 4901// Batch the run of consecutive L2_NORM siblings starting at node_idx into one launch. 4902// Returns the number of extra graph nodes consumed, or 0 if the run is shorter than two 4903// (the caller then runs the norm through the per-tensor kernel). 4904static int ggml_sycl_l2_norm_batch_fused (ggml_backend_sycl_context & ctx ,ggml_cgraph * cgraph ,int node_idx ) { 4905const ggml_tensor * node = cgraph -> nodes [node_idx ]; 4906if (ggml_sycl_info ().device_count != 1 || node -> type != GGML_TYPE_F32 || 4907node -> src [0 ]-> type != GGML_TYPE_F32 || node -> src [0 ]-> ne [0 ] >=1024 ) { 4908return 0 ; 4909 } 4910 4911ggml_tensor * batch [GGML_SYCL_L2_BATCH_MAX ]; 4912int count = 0 ; 4913int last = node_idx ; 4914float eps0 ; 4915memcpy (& eps0 ,node -> op_params ,sizeof (float )); 4916 4917// Conservative aliasing test: the batched norms run concurrently in one kernel, 4918// so none may read what another writes, and none may write where another writes. 4919auto overlaps = [](const ggml_tensor * a ,const ggml_tensor * b ) { 4920const char * ab = (const char * )a -> data ; 4921const char * bb = (const char * )b -> data ; 4922return ab < bb + ggml_nbytes (b )&& bb < ab + ggml_nbytes (a ); 4923 }; 4924 4925for (int j = node_idx ;j < cgraph -> n_nodes && count < GGML_SYCL_L2_BATCH_MAX ;++ j ) { 4926ggml_tensor * nj = cgraph -> nodes [j ]; 4927if (ggml_is_empty (nj )|| nj -> op == GGML_OP_RESHAPE || nj -> op == GGML_OP_TRANSPOSE || 4928nj -> op == GGML_OP_VIEW || nj -> op == GGML_OP_PERMUTE || nj -> op == GGML_OP_NONE || 4929 (nj -> flags & GGML_TENSOR_FLAG_COMPUTE )== 0 ) { 4930continue ;// not a launch; cannot break a run of adjacent norms 4931 } 4932if (nj -> op != GGML_OP_L2_NORM || nj -> type != GGML_TYPE_F32 || 4933nj -> src [0 ]-> type != GGML_TYPE_F32 || !ggml_are_same_shape (nj ,node )|| 4934 !ggml_are_same_shape (nj -> src [0 ],node -> src [0 ])) { 4935break ;// any other launch ends the run 4936 } 4937bool same_nb = true; 4938for (int d = 0 ;d < GGML_MAX_DIMS ;++ d ) { 4939if (nj -> nb [d ]!= node -> nb [d ]|| nj -> src [0 ]-> nb [d ]!= node -> src [0 ]-> nb [d ]) { 4940same_nb = false; 4941break ; 4942 } 4943 } 4944if (!same_nb ) { 4945break ;// one nb[] stride set is shared by the whole batch 4946 } 4947float epsj ; 4948memcpy (& epsj ,nj -> op_params ,sizeof (float )); 4949if (epsj != eps0 ) { 4950break ;// eps mismatch ends the run 4951 } 4952bool indep = true; 4953for (int k = 0 ;k < count ;++ k ) { 4954if (overlaps (nj -> src [0 ],batch [k ])|| overlaps (nj ,batch [k ])) { 4955indep = false; 4956break ; 4957 } 4958 } 4959if (!indep ) { 4960break ;// an overlapping tensor would race inside one launch 4961 } 4962batch [count ++ ]= nj ; 4963last = j ; 4964 } 4965if (count < 2 ) { 4966return 0 ;// a lone norm falls through to the per-tensor kernel 4967 } 4968ggml_sycl_l2_norm_batch (ctx ,batch ,count ); 4969return last - node_idx ; 4970} 4971 4972 4973__dpct_inline__ static void k_copy_src1_to_contiguous ( 4974const char * __restrict__src1_original ,char * __restrict__src1_contiguous , 4975const mmid_row_mapping * __restrict__row_mapping , 4976int64_t ne11 ,int64_t ne10 ,size_t nb11 ,size_t nb12 , 4977const sycl::nd_item < 3 > & item_ct1 ) { 4978const int32_t src1_row = item_ct1 .get_group (2 ); 4979 4980const int32_t iid1 = row_mapping [src1_row ].i2 ; 4981const int32_t id = row_mapping [src1_row ].i1 ; 4982 4983const int64_t i11 = id %ne11 ; 4984const int64_t i12 = iid1 ; 4985 4986const float * src1_row_original = (const float * )(src1_original + i11 * nb11 + i12 * nb12 ); 4987float * src1_row_contiguous = (float * )(src1_contiguous + src1_row * nb11 ); 4988 4989#pragma unroll 4990for (int i = item_ct1 .get_local_id (2 );i < ne10 ; 4991i += item_ct1 .get_local_range (2 )) { 4992src1_row_contiguous [i ]= src1_row_original [i ]; 4993 } 4994} 4995 4996__dpct_inline__ static void k_copy_dst_from_contiguous ( 4997char * __restrict__dst_original ,const char * __restrict__dst_contiguous , 4998const mmid_row_mapping * __restrict__row_mapping ,int64_t ne0 ,size_t nb1 , 4999size_t nb2 ,const sycl::nd_item < 3 > & item_ct1 ) { 5000int32_t i = item_ct1 .get_group (2 ); 5001 5002const int32_t i1 = row_mapping [i ].i1 ; 5003const int32_t i2 = row_mapping [i ].i2 ; 5004 5005const float * dst_row_contiguous = (const float * )(dst_contiguous + i * nb1 ); 5006float * dst_row_original = (float * )(dst_original + i1 * nb1 + i2 * nb2 ); 5007 5008#pragma unroll 5009for (int j = item_ct1 .get_local_id (2 );j < ne0 ; 5010j += item_ct1 .get_local_range (2 )) { 5011dst_row_original [j ]= dst_row_contiguous [j ]; 5012 } 5013} 5014 5015// Fused MoE TG fast path. Returns false to fall back to the per-expert loop below. 5016static bool ggml_sycl_mul_mat_id_mmvq_fused ( 5017ggml_backend_sycl_context & ctx ,const ggml_tensor * src0 , 5018const ggml_tensor * src1 ,const ggml_tensor * ids ,ggml_tensor * dst ) 5019{ 5020const int64_t ne10 = src1 -> ne [0 ]; 5021const int64_t ne11 = src1 -> ne [1 ]; 5022const int64_t ne12 = src1 -> ne [2 ]; 5023if (ne12 != 1 )return false; 5024if (src1 -> type != GGML_TYPE_F32 || dst -> type != GGML_TYPE_F32 )return false; 5025if (ne10 != src0 -> ne [0 ]|| ne10 %QK8_1 != 0 )return false; 5026if (!ggml_is_contiguous (src1 ))return false; 5027 5028const int64_t n_ids_per_group = ids -> ne [0 ]; 5029if (ids -> ne [1 ]!= 1 )return false; 5030if (ne11 != 1 && ne11 != n_ids_per_group )return false; 5031 5032const queue_ptr stream = ctx .stream (); 5033const int src1_padded_cols = GGML_PAD ((int )ne10 ,MATRIX_ROW_PADDING ); 5034const int n_experts_used = (int )n_ids_per_group ; 5035const int nrows = (int )src0 -> ne [1 ]; 5036 5037// Lazily reorder the (Q4_K) expert weights into a per-expert SoA layout, then run the reorder 5038// GEMV. Placed after the bail checks so a non-dispatchable op does not pay the reorder cost. 5039opt_for_reorder_id (& ctx ,src0 ); 5040const ggml_tensor_extra_gpu * src0_extra = 5041static_cast < const ggml_tensor_extra_gpu *> (src0 -> extra ); 5042const bool use_reorder = src0_extra && src0_extra -> optimized_feature .reorder ; 5043 5044ggml_sycl_pool_alloc < char > src1_q8_alloc (ctx .pool (), 5045 (size_t )ne11 * src1_padded_cols * sizeof (block_q8_1 ) /QK8_1 ); 5046char * src1_ddq = src1_q8_alloc .get (); 5047if (use_reorder ) { 5048quantize_row_q8_1_sycl < quantize_and_reorder_q8_1_soa > ( 5049 (const float * )src1 -> data ,src1_ddq , (int )ne10 , (int )ne11 , 5050src1_padded_cols ,stream ); 5051 }else { 5052quantize_row_q8_1_sycl < quantize_q8_1 > ( 5053 (const float * )src1 -> data ,src1_ddq , (int )ne10 , (int )ne11 , 5054src1_padded_cols ,stream ); 5055 } 5056 5057const size_t bytes_per_qrow = (size_t )src1_padded_cols * sizeof (block_q8_1 ) /QK8_1 ; 5058const size_t src1_row_stride = (ne11 == 1 ) ?0 :bytes_per_qrow ; 5059 5060if (use_reorder ) { 5061return ggml_sycl_mul_mat_vec_q_id_reorder ( 5062src0 -> type ,src0 -> data ,src1_ddq , (const int32_t * )ids -> data , 5063 (float * )dst -> data , (int )ne10 ,nrows ,n_experts_used , 5064/*expert_weight_stride=*/ src0 -> nb [2 ], 5065/*dst_row_stride=*/ dst -> nb [1 ], 5066src1_row_stride ,stream ); 5067 } 5068return ggml_sycl_mul_mat_vec_q_id ( 5069src0 -> type ,src0 -> data ,src1_ddq , (const int32_t * )ids -> data , 5070 (float * )dst -> data , (int )ne10 ,nrows ,n_experts_used , 5071/*expert_weight_stride=*/ src0 -> nb [2 ], 5072/*dst_row_stride=*/ dst -> nb [1 ], 5073src1_row_stride ,stream ); 5074} 5075 5076// counting sort of the routed rows by expert id (row_id_i, as chosen by the router): 5077// builds a projection of a memory layout where each expert's slice is contiguous 5078static void mmid_counting_sort_rows ( 5079const ggml_tensor * ids ,const char * ids_host , 5080int64_t n_ids ,int64_t n_as ,int64_t n_routed_rows , 5081 std::vector < int64_t > & expert_counts , 5082 std::vector < int64_t > & expert_row_offsets , 5083 std::vector < mmid_row_mapping > & routed_row_src ) { 5084 5085// frequencies: how many routed rows each expert "owns" 5086expert_counts .assign (n_as ,0 ); 5087for (int64_t iid1 = 0 ;iid1 < ids -> ne [1 ];iid1 ++ ) { 5088for (int64_t id = 0 ;id < n_ids ;id ++ ) { 5089const int32_t row_id_i = * (const int32_t * ) (ids_host + iid1 * ids -> nb [1 ]+ id * ids -> nb [0 ]); 5090GGML_ASSERT (row_id_i >=0 && row_id_i < n_as ); 5091expert_counts [row_id_i ]++ ; 5092 } 5093 } 5094 5095// where each expert's slice starts (row indices) and the previous ends 5096expert_row_offsets .assign (n_as + 1 ,0 ); 5097for (int64_t i02 = 0 ;i02 < n_as ;i02 ++ ) { 5098expert_row_offsets [i02 + 1 ]= expert_row_offsets [i02 ]+ expert_counts [i02 ]; 5099 } 5100 5101 std::vector < int64_t > expert_row_next = expert_row_offsets ; 5102routed_row_src .resize (n_routed_rows ); 5103for (int64_t iid1 = 0 ;iid1 < ids -> ne [1 ];iid1 ++ ) { 5104for (int64_t id = 0 ;id < n_ids ;id ++ ) { 5105const int32_t row_id_i = * (const int32_t * ) (ids_host + iid1 * ids -> nb [1 ]+ id * ids -> nb [0 ]); 5106GGML_ASSERT (row_id_i >=0 && row_id_i < n_as ); 5107 5108// find and validate the next free row for a given expert (row_id_i) 5109const int64_t routed_row = expert_row_next [row_id_i ]++ ; 5110GGML_ASSERT (routed_row >=expert_row_offsets [row_id_i ]); 5111GGML_ASSERT (routed_row < expert_row_offsets [row_id_i + 1 ]); 5112routed_row_src [routed_row ]= {(int32_t )id , (int32_t )iid1 }; 5113 } 5114 } 5115} 5116 5117static void ggml_sycl_mul_mat_id (ggml_backend_sycl_context & ctx , 5118ggml_tensor * dst )try { 5119scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 3 ); 5120const ggml_tensor * src0 = dst -> src [0 ]; 5121const ggml_tensor * src1 = dst -> src [1 ]; 5122GGML_ASSERT (!ggml_backend_buffer_is_sycl_split (src0 -> buffer )&& "mul_mat_id does not support split buffers" ); 5123 5124const ggml_tensor * ids = dst -> src [2 ]; 5125GGML_TENSOR_BINARY_OP_LOCALS 5126 5127const queue_ptr stream = ctx .stream (); 5128 5129const int64_t n_as = ne02 ; 5130const int64_t n_ids = ids -> ne [0 ]; 5131 5132if (ne12 == 1 ) { 5133if (ggml_sycl_mul_mat_id_mmvq_fused (ctx ,src0 ,src1 ,ids ,dst )) { 5134return ; 5135 } 5136 } 5137 5138 std::vector < char > ids_host (ggml_nbytes (ids )); 5139const char * ids_dev = (const char * )ids -> data ; 5140 5141SYCL_CHECK (CHECK_TRY_ERROR ( 5142stream -> memcpy (ids_host .data (),ids_dev ,ggml_nbytes (ids )))); 5143 5144// also ensures ctx.mmid_row_mapping_host is drained before we use it again 5145SYCL_CHECK (CHECK_TRY_ERROR (stream -> wait ())); 5146 5147ggml_tensor src0_row = * src0 ; 5148ggml_tensor src1_row = * src1 ; 5149ggml_tensor dst_row = * dst ; 5150 5151char * src0_original = (char * )src0 -> data ; 5152char * src1_original = (char * )src1 -> data ; 5153char * dst_original = (char * )dst -> data ; 5154 5155src0_row .ne [2 ]= 1 ; 5156src0_row .ne [3 ]= 1 ; 5157src0_row .nb [3 ]= nb02 ; 5158 5159src1_row .ne [1 ]= 1 ; 5160src1_row .ne [2 ]= 1 ; 5161src1_row .ne [3 ]= 1 ; 5162src1_row .nb [2 ]= nb11 ; 5163src1_row .nb [3 ]= nb11 ; 5164 5165dst_row .ne [1 ]= 1 ; 5166dst_row .ne [2 ]= 1 ; 5167dst_row .ne [3 ]= 1 ; 5168dst_row .nb [2 ]= nb1 ; 5169dst_row .nb [3 ]= nb1 ; 5170if (ne12 == 1 ) { 5171for (int64_t iid1 = 0 ;iid1 < ids -> ne [1 ];iid1 ++ ) { 5172for (int64_t id = 0 ;id < n_ids ;id ++ ) { 5173const int32_t i02 = * (const int32_t * ) (ids_host .data ()+ iid1 * ids -> nb [1 ]+ id * ids -> nb [0 ]); 5174GGML_ASSERT (i02 >=0 && i02 < n_as ); 5175 5176const int64_t i11 = id %ne11 ; 5177const int64_t i12 = iid1 ; 5178 5179const int64_t i1 = id ; 5180const int64_t i2 = i12 ; 5181 5182src0_row .data = src0_original + i02 * nb02 ; 5183src1_row .data = src1_original + i11 * nb11 + i12 * nb12 ; 5184dst_row .data = dst_original + i1 * nb1 + i2 * nb2 ; 5185 5186ggml_sycl_mul_mat (ctx ,& src0_row ,& src1_row ,& dst_row ); 5187 } 5188 } 5189 }else { 5190const int64_t n_routed_rows = ids -> ne [1 ]* n_ids ; 5191ggml_sycl_pool_alloc < char > src1_contiguous (ctx .pool (),sizeof (float )* n_routed_rows * ne10 ); 5192ggml_sycl_pool_alloc < char > dst_contiguous (ctx .pool (),sizeof (float )* n_routed_rows * ne0 ); 5193 5194src1_row .data = src1_contiguous .get (); 5195dst_row .data = dst_contiguous .get (); 5196 5197// how many "owned" routed rows to pass to each expert 5198 std::vector < int64_t > expert_row_counts ; 5199// where each expert's slice starts and the previous ends (row indices, right-exclusive) 5200 std::vector < int64_t > expert_row_offsets ; 5201// the sources (slot/token pairs) of contiguous rows to guide k_copy_src1_to_contiguous 5202 std::vector < mmid_row_mapping > & routed_row_src = ctx .mmid_row_mapping_host ; 5203 5204mmid_counting_sort_rows (ids ,ids_host .data (),n_ids ,n_as ,n_routed_rows , 5205expert_row_counts ,expert_row_offsets ,routed_row_src ); 5206 5207ggml_sycl_pool_alloc < mmid_row_mapping > dev_row_mapping (ctx .pool (),n_routed_rows ); 5208SYCL_CHECK (CHECK_TRY_ERROR ( 5209stream -> memcpy (dev_row_mapping .get (),routed_row_src .data (),n_routed_rows * sizeof (mmid_row_mapping )))); 5210 5211const unsigned int max_work_group_size = ggml_sycl_info ().max_work_group_sizes [ctx .device ]; 5212assert (max_work_group_size % (WARP_SIZE * WARP_SIZE )== 0 ); 5213 5214 { 5215 sycl::range < 3 > block_dims (1 ,1 , std::min ((unsigned int )ne10 ,max_work_group_size )); 5216 sycl::range < 3 > grid_dims (1 ,1 ,n_routed_rows ); 5217stream -> submit ([& ](sycl::handler & cgh ) { 5218char * __restrictsrc1_contiguous_get = 5219src1_contiguous .get (); 5220mmid_row_mapping * __restrictdev_row_mapping_get = 5221dev_row_mapping .get (); 5222 5223cgh .parallel_for ( 5224 sycl::nd_range < 3 > (grid_dims * block_dims ,block_dims ), 5225 [= ](sycl::nd_item < 3 > item_ct1 ) { 5226k_copy_src1_to_contiguous ( 5227src1_original ,src1_contiguous_get , 5228dev_row_mapping_get , 5229ne11 ,ne10 ,nb11 ,nb12 , 5230item_ct1 ); 5231 }); 5232 }); 5233 } 5234 5235for (int64_t i02 = 0 ;i02 < n_as ;i02 ++ ) { 5236const int64_t num_src1_rows = expert_row_counts [i02 ]; 5237 5238if (num_src1_rows == 0 ) { 5239continue ; 5240 } 5241 5242const int64_t expert_row_offset = expert_row_offsets [i02 ]; 5243 5244src0_row .data = src0_original + i02 * nb02 ; 5245 5246GGML_ASSERT (nb11 == sizeof (float )* ne10 ); 5247GGML_ASSERT (nb1 == sizeof (float )* ne0 ); 5248src1_row .data = src1_contiguous .get ()+ expert_row_offset * nb11 ; 5249src1_row .ne [1 ]= num_src1_rows ; 5250 5251src1_row .nb [1 ]= nb11 ; 5252src1_row .nb [2 ]= num_src1_rows * nb11 ; 5253src1_row .nb [3 ]= num_src1_rows * nb11 ; 5254 5255dst_row .data = dst_contiguous .get ()+ expert_row_offset * nb1 ; 5256dst_row .ne [1 ]= num_src1_rows ; 5257dst_row .nb [1 ]= nb1 ; 5258dst_row .nb [2 ]= num_src1_rows * nb1 ; 5259dst_row .nb [3 ]= num_src1_rows * nb1 ; 5260 5261ggml_sycl_mul_mat (ctx ,& src0_row ,& src1_row ,& dst_row ); 5262 } 5263 5264 { 5265 sycl::range < 3 > block_dims (1 ,1 , std::min ((unsigned int )ne0 ,max_work_group_size )); 5266 sycl::range < 3 > grid_dims (1 ,1 ,n_routed_rows ); 5267stream -> submit ([& ](sycl::handler & cgh ) { 5268const char * __restrictdst_contiguous_get = 5269dst_contiguous .get (); 5270const mmid_row_mapping * __restrictdev_row_mapping_get = 5271dev_row_mapping .get (); 5272 5273cgh .parallel_for ( 5274 sycl::nd_range < 3 > (grid_dims * block_dims ,block_dims ), 5275 [= ](sycl::nd_item < 3 > item_ct1 ) { 5276k_copy_dst_from_contiguous (dst_original , 5277dst_contiguous_get , 5278dev_row_mapping_get , 5279ne0 ,nb1 ,nb2 ,item_ct1 ); 5280 }); 5281 }); 5282 } 5283 } 5284} 5285catch (sycl::exception const & exc ) { 5286 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5287 <<", line:" <<__LINE__ << std::endl ; 5288 std::exit (1 ); 5289} 5290 5291static void ggml_sycl_scale (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5292scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5293ggml_sycl_op_scale (ctx ,dst ); 5294} 5295 5296static void ggml_sycl_diag_mask_inf (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5297scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5298ggml_sycl_op_diag_mask_inf (ctx ,dst ); 5299} 5300 5301static void ggml_sycl_pool2d (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5302scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5303ggml_sycl_op_pool2d (ctx ,dst ); 5304} 5305 5306static void ggml_sycl_pool1d (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5307scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5308ggml_sycl_op_pool1d (ctx ,dst ); 5309} 5310 5311static void ggml_sycl_im2col (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5312scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 2 ); 5313ggml_sycl_op_im2col (ctx ,dst ); 5314} 5315 5316static void ggml_sycl_im2col_3d (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5317scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 2 ); 5318ggml_sycl_op_im2col_3d (ctx ,dst ); 5319} 5320 5321static void ggml_sycl_col2im_1d (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5322scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5323ggml_sycl_op_col2im_1d (ctx ,dst ); 5324} 5325 5326static void ggml_sycl_conv_3d (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5327scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 2 ); 5328ggml_sycl_op_conv_3d (ctx ,dst ); 5329} 5330 5331static void ggml_sycl_sum (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5332scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5333GGML_ASSERT (ggml_is_contiguous (dst -> src [0 ])); 5334ggml_sycl_op_sum (ctx ,dst ); 5335} 5336 5337static void ggml_sycl_sum_rows (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5338scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5339GGML_ASSERT (ggml_is_contiguous (dst -> src [0 ])); 5340ggml_sycl_op_sum_rows (ctx ,dst ); 5341} 5342 5343static void ggml_sycl_mean (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5344scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5345GGML_ASSERT (ggml_is_contiguous (dst -> src [0 ])); 5346ggml_sycl_op_mean (ctx ,dst ); 5347} 5348 5349static void ggml_sycl_argsort (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5350scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5351GGML_ASSERT (ggml_is_contiguous (dst -> src [0 ])); 5352ggml_sycl_op_argsort (ctx ,dst ); 5353} 5354 5355static void ggml_sycl_argmax (ggml_backend_sycl_context & ctx ,ggml_tensor * dst ) { 5356scope_op_debug_print scope_dbg_print (__func__ ,dst ,/*num_src=*/ 1 ); 5357GGML_ASSERT (ggml_is_contiguous (dst -> src [0 ])); 5358ggml_sycl_op_argmax (ctx ,dst ); 5359} 5360 5361 5362static void ggml_sycl_set_main_device (const int main_device )try { 5363if (dpct::get_current_device_id ()== static_cast < unsigned int > (main_device )) { 5364return ; 5365 } 5366check_allow_gpu_index (main_device ); 5367 dpct::select_device (main_device ); 5368 5369if (g_ggml_sycl_debug ) { 5370 dpct::device_info prop ; 5371SYCL_CHECK (CHECK_TRY_ERROR (dpct::get_device_info ( 5372prop , dpct::dev_mgr::instance ().get_device (main_device )))); 5373GGML_LOG_INFO ("Using device %d (%s) as main device\n" , 5374main_device ,prop .get_name ()); 5375 } 5376} 5377catch (sycl::exception const & exc ) { 5378 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5379 <<", line:" <<__LINE__ << std::endl ; 5380 std::exit (1 ); 5381} 5382 5383static bool ggml_sycl_compute_forward (ggml_backend_sycl_context & ctx ,struct ggml_tensor * dst )try { 5384GGML_SYCL_DEBUG ("[SYCL] ggml_sycl_compute_forward: dst=%s, op=%s\n" ,dst -> name ,ggml_op_name (dst -> op )); 5385if (!g_sycl_loaded )return false; 5386 5387if (dst -> src [0 ]!= nullptr && ggml_backend_buffer_is_sycl_split (dst -> src [0 ]-> buffer )) { 5388ggml_sycl_set_peer_access (dst -> src [1 ]-> ne [1 ],ctx .device ); 5389 } 5390 5391switch (dst -> op ) { 5392case GGML_OP_ARGMAX : 5393ggml_sycl_argmax (ctx ,dst ); 5394break ; 5395case GGML_OP_CONV_2D : 5396ggml_sycl_op_conv2d (ctx ,dst ); 5397break ; 5398case GGML_OP_CONV_2D_DW : 5399ggml_sycl_op_conv2d_dw (ctx ,dst ); 5400break ; 5401case GGML_OP_CONV_3D : 5402ggml_sycl_conv_3d (ctx ,dst ); 5403break ; 5404case GGML_OP_CONV_TRANSPOSE_1D : 5405ggml_sycl_op_conv_transpose_1d (ctx ,dst ); 5406break ; 5407case GGML_OP_CONV_TRANSPOSE_2D : 5408ggml_sycl_op_conv2d_transpose (ctx ,dst ); 5409break ; 5410case GGML_OP_REPEAT : 5411ggml_sycl_repeat (ctx ,dst ); 5412break ; 5413case GGML_OP_REPEAT_BACK : 5414ggml_sycl_repeat_back (ctx ,dst ); 5415break ; 5416case GGML_OP_GET_ROWS : 5417ggml_sycl_get_rows (ctx ,dst ); 5418break ; 5419case GGML_OP_SET : 5420ggml_sycl_op_set (ctx ,dst ); 5421break ; 5422case GGML_OP_SET_ROWS : 5423ggml_sycl_op_set_rows (ctx ,dst ); 5424break ; 5425case GGML_OP_DSV4_HC_PRE : 5426ggml_sycl_op_dsv4_hc_pre (ctx ,dst ); 5427break ; 5428case GGML_OP_DSV4_HC_COMB : 5429ggml_sycl_op_dsv4_hc_comb (ctx ,dst ); 5430break ; 5431case GGML_OP_DSV4_HC_POST : 5432ggml_sycl_op_dsv4_hc_post (ctx ,dst ); 5433break ; 5434case GGML_OP_LIGHTNING_INDEXER : 5435ggml_sycl_op_lightning_indexer (ctx ,dst ); 5436break ; 5437case GGML_OP_DUP : 5438ggml_sycl_dup (ctx ,dst ); 5439break ; 5440case GGML_OP_ADD : 5441case GGML_OP_ADD1 :// TODO: more efficient implementation 5442ggml_sycl_add (ctx ,dst ); 5443break ; 5444case GGML_OP_ADD_ID : 5445ggml_sycl_add_id (ctx ,dst ); 5446break ; 5447case GGML_OP_SUB : 5448ggml_sycl_sub (ctx ,dst ); 5449break ; 5450case GGML_OP_COUNT_EQUAL : 5451ggml_sycl_count_equal (ctx ,dst ); 5452break ; 5453case GGML_OP_ACC : 5454ggml_sycl_acc (ctx ,dst ); 5455break ; 5456case GGML_OP_MUL : 5457ggml_sycl_mul (ctx ,dst ); 5458break ; 5459case GGML_OP_LOG : 5460ggml_sycl_log (ctx ,dst ); 5461break ; 5462case GGML_OP_DIV : 5463ggml_sycl_div (ctx ,dst ); 5464break ; 5465case GGML_OP_UNARY : 5466switch (ggml_get_unary_op (dst )) { 5467case GGML_UNARY_OP_NEG : 5468ggml_sycl_neg (ctx ,dst ); 5469break ; 5470case GGML_UNARY_OP_STEP : 5471ggml_sycl_step (ctx ,dst ); 5472break ; 5473case GGML_UNARY_OP_GELU : 5474ggml_sycl_gelu (ctx ,dst ); 5475break ; 5476case GGML_UNARY_OP_SILU : 5477ggml_sycl_silu (ctx ,dst ); 5478break ; 5479case GGML_UNARY_OP_GELU_QUICK : 5480ggml_sycl_gelu_quick (ctx ,dst ); 5481break ; 5482case GGML_UNARY_OP_GELU_ERF : 5483ggml_sycl_gelu_erf (ctx ,dst ); 5484break ; 5485case GGML_UNARY_OP_TANH : 5486ggml_sycl_tanh (ctx ,dst ); 5487break ; 5488case GGML_UNARY_OP_RELU : 5489ggml_sycl_relu (ctx ,dst ); 5490break ; 5491case GGML_UNARY_OP_SIGMOID : 5492ggml_sycl_sigmoid (ctx ,dst ); 5493break ; 5494case GGML_UNARY_OP_HARDSIGMOID : 5495ggml_sycl_hardsigmoid (ctx ,dst ); 5496break ; 5497case GGML_UNARY_OP_HARDSWISH : 5498ggml_sycl_hardswish (ctx ,dst ); 5499break ; 5500case GGML_UNARY_OP_EXP : 5501ggml_sycl_exp (ctx ,dst ); 5502break ; 5503case GGML_UNARY_OP_EXPM1 : 5504ggml_sycl_expm1 (ctx ,dst ); 5505break ; 5506case GGML_UNARY_OP_SOFTPLUS : 5507ggml_sycl_softplus (ctx ,dst ); 5508break ; 5509case GGML_UNARY_OP_SGN : 5510ggml_sycl_sgn (ctx ,dst ); 5511break ; 5512case GGML_UNARY_OP_ABS : 5513ggml_sycl_abs (ctx ,dst ); 5514break ; 5515case GGML_UNARY_OP_ELU : 5516ggml_sycl_elu (ctx ,dst ); 5517break ; 5518case GGML_UNARY_OP_XIELU : 5519ggml_sycl_xielu (ctx ,dst ); 5520break ; 5521case GGML_UNARY_OP_FLOOR : 5522ggml_sycl_floor (ctx ,dst ); 5523break ; 5524case GGML_UNARY_OP_CEIL : 5525ggml_sycl_ceil (ctx ,dst ); 5526break ; 5527case GGML_UNARY_OP_ROUND : 5528ggml_sycl_round (ctx ,dst ); 5529break ; 5530case GGML_UNARY_OP_TRUNC : 5531ggml_sycl_trunc (ctx ,dst ); 5532break ; 5533default : 5534return false; 5535 } 5536break ; 5537case GGML_OP_GLU : 5538switch (ggml_get_glu_op (dst )) { 5539case GGML_GLU_OP_REGLU : 5540ggml_sycl_reglu (ctx ,dst ); 5541break ; 5542case GGML_GLU_OP_GEGLU : 5543ggml_sycl_geglu (ctx ,dst ); 5544break ; 5545case GGML_GLU_OP_SWIGLU : 5546ggml_sycl_swiglu (ctx ,dst ); 5547break ; 5548case GGML_GLU_OP_SWIGLU_OAI : 5549ggml_sycl_swiglu_oai (ctx ,dst ); 5550break ; 5551case GGML_GLU_OP_SWIGLU_CLAMP : 5552ggml_sycl_swiglu_clamp (ctx ,dst ); 5553break ; 5554case GGML_GLU_OP_GEGLU_ERF : 5555ggml_sycl_geglu_erf (ctx ,dst ); 5556break ; 5557case GGML_GLU_OP_GEGLU_QUICK : 5558ggml_sycl_geglu_quick (ctx ,dst ); 5559break ; 5560default : 5561return false; 5562 } 5563break ; 5564case GGML_OP_NORM : 5565ggml_sycl_norm (ctx ,dst ); 5566break ; 5567case GGML_OP_GROUP_NORM : 5568ggml_sycl_group_norm (ctx ,dst ); 5569break ; 5570case GGML_OP_CONCAT : 5571ggml_sycl_op_concat (ctx ,dst ); 5572break ; 5573case GGML_OP_PAD_REFLECT_1D : 5574ggml_sycl_op_pad_reflect_1d (ctx ,dst ); 5575break ; 5576case GGML_OP_UPSCALE : 5577ggml_sycl_upscale (ctx ,dst ); 5578break ; 5579case GGML_OP_PAD : 5580ggml_sycl_pad (ctx ,dst ); 5581break ; 5582case GGML_OP_LEAKY_RELU : 5583ggml_sycl_leaky_relu (ctx ,dst ); 5584break ; 5585case GGML_OP_RMS_NORM_BACK : 5586ggml_sycl_rms_norm_back (ctx ,dst ); 5587break ; 5588case GGML_OP_RMS_NORM : 5589ggml_sycl_rms_norm (ctx ,dst ); 5590break ; 5591case GGML_OP_L2_NORM : 5592ggml_sycl_l2_norm (ctx ,dst ); 5593break ; 5594case GGML_OP_MUL_MAT : 5595if (dst -> src [0 ]-> ne [3 ]!= dst -> src [1 ]-> ne [3 ]) { 5596return false; 5597 } 5598/* ggml_sycl_mul_mat_id is dependent on ggml_sycl_mul_mat */ 5599ggml_sycl_mul_mat (ctx ,dst -> src [0 ],dst -> src [1 ],dst ); 5600break ; 5601case GGML_OP_MUL_MAT_ID : 5602if (dst -> src [0 ]-> ne [3 ]!= dst -> src [1 ]-> ne [3 ]) { 5603return false; 5604 } 5605ggml_sycl_mul_mat_id (ctx ,dst ); 5606break ; 5607case GGML_OP_OUT_PROD : 5608ggml_sycl_op_out_prod (ctx ,dst ); 5609break ; 5610case GGML_OP_SCALE : 5611ggml_sycl_scale (ctx ,dst ); 5612break ; 5613case GGML_OP_SQR : 5614ggml_sycl_sqr (ctx ,dst ); 5615break ; 5616case GGML_OP_SQRT : 5617ggml_sycl_sqrt (ctx ,dst ); 5618break ; 5619case GGML_OP_SIN : 5620ggml_sycl_sin (ctx ,dst ); 5621break ; 5622case GGML_OP_COS : 5623ggml_sycl_cos (ctx ,dst ); 5624break ; 5625case GGML_OP_CLAMP : 5626ggml_sycl_clamp (ctx ,dst ); 5627break ; 5628case GGML_OP_CPY : 5629ggml_sycl_cpy (ctx ,dst -> src [0 ],dst -> src [1 ]); 5630break ; 5631case GGML_OP_CONT : 5632ggml_sycl_dup (ctx ,dst ); 5633break ; 5634case GGML_OP_NONE : 5635case GGML_OP_RESHAPE : 5636case GGML_OP_VIEW : 5637case GGML_OP_PERMUTE : 5638case GGML_OP_TRANSPOSE : 5639GGML_SYCL_DEBUG ("%s: Tensor NO-OP\n" ,__func__ ); 5640break ; 5641case GGML_OP_TRI : 5642ggml_sycl_op_tri (ctx ,dst ); 5643break ; 5644case GGML_OP_DIAG_MASK_INF : 5645ggml_sycl_diag_mask_inf (ctx ,dst ); 5646break ; 5647case GGML_OP_SOFT_MAX : 5648ggml_sycl_op_soft_max (ctx ,dst ); 5649break ; 5650case GGML_OP_SOFT_MAX_BACK : 5651ggml_sycl_op_soft_max_back (ctx ,dst ); 5652break ; 5653case GGML_OP_CROSS_ENTROPY_LOSS : 5654ggml_sycl_cross_entropy_loss (ctx ,dst ); 5655break ; 5656case GGML_OP_CROSS_ENTROPY_LOSS_BACK : 5657ggml_sycl_cross_entropy_loss_back (ctx ,dst ); 5658break ; 5659case GGML_OP_ROPE : 5660ggml_sycl_rope (ctx ,dst ); 5661break ; 5662case GGML_OP_ROPE_BACK : 5663ggml_sycl_rope_back (ctx ,dst ); 5664break ; 5665case GGML_OP_IM2COL : 5666ggml_sycl_im2col (ctx ,dst ); 5667break ; 5668case GGML_OP_IM2COL_3D : 5669ggml_sycl_im2col_3d (ctx ,dst ); 5670break ; 5671case GGML_OP_COL2IM_1D : 5672ggml_sycl_col2im_1d (ctx ,dst ); 5673break ; 5674case GGML_OP_POOL_2D : 5675ggml_sycl_pool2d (ctx ,dst ); 5676break ; 5677case GGML_OP_POOL_1D : 5678ggml_sycl_pool1d (ctx ,dst ); 5679break ; 5680case GGML_OP_SUM : 5681ggml_sycl_sum (ctx ,dst ); 5682break ; 5683case GGML_OP_SUM_ROWS : 5684ggml_sycl_sum_rows (ctx ,dst ); 5685break ; 5686case GGML_OP_MEAN : 5687ggml_sycl_mean (ctx ,dst ); 5688break ; 5689case GGML_OP_ARGSORT : 5690ggml_sycl_argsort (ctx ,dst ); 5691break ; 5692case GGML_OP_TOP_K : 5693ggml_sycl_op_top_k (ctx ,dst ); 5694break ; 5695case GGML_OP_TIMESTEP_EMBEDDING : 5696ggml_sycl_op_timestep_embedding (ctx ,dst ); 5697break ; 5698case GGML_OP_RWKV_WKV6 : 5699ggml_sycl_op_rwkv_wkv6 (ctx ,dst ); 5700break ; 5701case GGML_OP_RWKV_WKV7 : 5702ggml_sycl_op_rwkv_wkv7 (ctx ,dst ); 5703break ; 5704case GGML_OP_GATED_LINEAR_ATTN : 5705ggml_sycl_op_gated_linear_attn (ctx ,dst ); 5706break ; 5707case GGML_OP_GATED_DELTA_NET : 5708ggml_sycl_gated_delta_net (ctx ,dst ); 5709break ; 5710case GGML_OP_OPT_STEP_ADAMW : 5711ggml_sycl_opt_step_adamw (ctx ,dst ); 5712break ; 5713case GGML_OP_OPT_STEP_SGD : 5714ggml_sycl_opt_step_sgd (ctx ,dst ); 5715break ; 5716case GGML_OP_SSM_CONV : 5717ggml_sycl_ssm_conv (ctx ,dst ); 5718break ; 5719case GGML_OP_SSM_SCAN : 5720ggml_sycl_ssm_scan (ctx ,dst ); 5721break ; 5722case GGML_OP_FILL : 5723ggml_sycl_fill (ctx ,dst ); 5724break ; 5725case GGML_OP_CUMSUM : 5726ggml_sycl_cumsum (ctx ,dst ); 5727break ; 5728case GGML_OP_DIAG : 5729ggml_sycl_diag (ctx ,dst ); 5730break ; 5731case GGML_OP_SOLVE_TRI : 5732ggml_sycl_solve_tri (ctx ,dst ); 5733break ; 5734case GGML_OP_ROLL : 5735ggml_sycl_roll (ctx ,dst ); 5736break ; 5737case GGML_OP_ARANGE : 5738ggml_sycl_arange (ctx ,dst ); 5739break ; 5740case GGML_OP_FLASH_ATTN_EXT : 5741ggml_sycl_flash_attn_ext (ctx ,dst ); 5742break ; 5743default : 5744return false; 5745 } 5746 5747return true; 5748}catch (sycl::exception & e ) { 5749 std::cerr <<e .what () <<"Exception caught at file:" <<__FILE__ <<", line:" <<__LINE__ << std::endl ; 5750 std::cerr <<"Error OP " <<ggml_op_name (dst -> op )<< std::endl ; 5751 std::exit (1 ); 5752} 5753 5754GGML_API void ggml_backend_sycl_get_device_description (int device ,char * description , 5755size_t description_size )try { 5756GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_get_device_description\n" ); 5757 dpct::device_info prop ; 5758SYCL_CHECK (CHECK_TRY_ERROR (dpct::get_device_info ( 5759prop , dpct::dev_mgr::instance ().get_device (device )))); 5760snprintf (description ,description_size ,"%s" ,prop .get_name ()); 5761} 5762catch (sycl::exception const & exc ) { 5763 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5764 <<", line:" <<__LINE__ << std::endl ; 5765 std::exit (1 ); 5766} 5767 5768bool sycl_get_mem_info (int device ,size_t * free ,size_t * total ) { 5769GGML_SYCL_DEBUG ("[SYCL] [%s] g_ggml_sycl_get_mem_api=%d\n" , 5770__func__ ,g_ggml_sycl_get_mem_api ); 5771 5772MemoryAPIType mem_api_type = MemoryAPIType ::MEMORY_API_TYPE_SYCL ; 5773 5774#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API 5775mem_api_type = get_zes_init_res ()== ZE_RESULT_SUCCESS ? 5776 (MemoryAPIType )g_ggml_sycl_get_mem_api :MemoryAPIType ::MEMORY_API_TYPE_SYCL ; 5777#else 5778mem_api_type = MemoryAPIType ::MEMORY_API_TYPE_SYCL ; 5779#endif 5780bool res = get_memory_size (dpct::dev_mgr::instance ().get_device (device ), 5781* free ,* total ,mem_api_type ); 5782GGML_SYCL_DEBUG ("[SYCL] [%s] total = %zu free = %zu\n" ,__func__ ,* total ,* free ); 5783return res ; 5784} 5785 5786void ggml_backend_sycl_get_device_memory (int device ,size_t * free ,size_t * total )try { 5787GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_get_device_memory\n" ); 5788if (!sycl_get_mem_info (device ,free ,total )) { 5789GGML_ABORT ("[%s] failed to get device memory size" ,__func__ ); 5790 } 5791ggml_sycl_memtrace_report_device ("device memory query" ,device ,* free ,* total ); 5792}catch (const sycl::exception & exc ) { 5793 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ <<", line:" <<__LINE__ << std::endl ; 5794 std::exit (1 ); 5795} 5796 5797//////////////////////////////////////////////////////////////////////////////// 5798 5799// backend 5800 5801static const char * ggml_backend_sycl_get_name (ggml_backend_t backend ) { 5802 5803ggml_backend_sycl_context * sycl_ctx = (ggml_backend_sycl_context * )backend -> context ; 5804 5805return sycl_ctx -> name .c_str (); 5806} 5807 5808static void ggml_backend_sycl_free (ggml_backend_t backend ) { 5809ggml_backend_sycl_context * sycl_ctx = (ggml_backend_sycl_context * )backend -> context ; 5810 5811delete sycl_ctx ; 5812delete backend ; 5813} 5814 5815static void ggml_backend_sycl_set_tensor_async (ggml_backend_t backend , 5816ggml_tensor * tensor , 5817const void * data ,size_t offset , 5818size_t size )try { 5819GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 5820GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": tensor" ,tensor ).c_str ()); 5821GGML_SYCL_DEBUG (" size=%zu offset=%zu\n" ,size ,offset ); 5822ggml_backend_sycl_context * sycl_ctx = (ggml_backend_sycl_context * )backend -> context ; 5823ggml_backend_buffer_t buf = tensor -> view_src ?tensor -> view_src -> buffer :tensor -> buffer ; 5824 5825GGML_ASSERT (buf -> buft == ggml_backend_sycl_buffer_type (sycl_ctx -> device )&& "unsupported buffer type" ); 5826const queue_ptr stream = sycl_ctx -> stream (sycl_ctx -> device ,0 ); 5827SYCL_CHECK (CHECK_TRY_ERROR ( 5828 (stream )-> memcpy ((char * )tensor -> data + offset ,data ,size ))); 5829} 5830catch (sycl::exception const & exc ) { 5831 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5832 <<", line:" <<__LINE__ << std::endl ; 5833 std::exit (1 ); 5834} 5835 5836static void ggml_backend_sycl_get_tensor_async (ggml_backend_t backend , 5837const ggml_tensor * tensor , 5838void * data ,size_t offset , 5839size_t size )try { 5840GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 5841GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": tensor" ,tensor ).c_str ()); 5842GGML_SYCL_DEBUG (" size=%zu offset=%zu\n" ,size ,offset ); 5843ggml_backend_sycl_context * sycl_ctx = (ggml_backend_sycl_context * )backend -> context ; 5844ggml_backend_buffer_t buf = tensor -> view_src ?tensor -> view_src -> buffer :tensor -> buffer ; 5845 5846GGML_ASSERT (buf -> buft == ggml_backend_sycl_buffer_type (sycl_ctx -> device )&& "unsupported buffer type" ); 5847const queue_ptr stream = sycl_ctx -> stream (sycl_ctx -> device ,0 ); 5848SYCL_CHECK (CHECK_TRY_ERROR ((stream )-> memcpy ( 5849data , (const char * )tensor -> data + offset ,size ))); 5850} 5851catch (sycl::exception const & exc ) { 5852 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5853 <<", line:" <<__LINE__ << std::endl ; 5854 std::exit (1 ); 5855} 5856 5857static bool ggml_backend_sycl_cpy_tensor_async (ggml_backend_t backend , 5858const ggml_tensor * src , 5859ggml_tensor * dst )try { 5860ggml_backend_sycl_context * sycl_ctx = (ggml_backend_sycl_context * )backend -> context ; 5861bool is_cpy_supported = dst -> buffer -> buft == ggml_backend_sycl_buffer_type (sycl_ctx -> device )&& 5862ggml_backend_buffer_is_sycl (src -> buffer ); 5863GGML_SYCL_DEBUG ("[SYCL] call %s" ,__func__ ); 5864GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (": dst" ,dst ).c_str ()); 5865GGML_SYCL_DEBUG ("%s" ,debug_get_tensor_str (" src" ,src ).c_str ()); 5866GGML_SYCL_DEBUG (" is_cpy_supported=%d\n" ,is_cpy_supported ); 5867if (is_cpy_supported ) { 5868/* 5869DPCT1009:215: SYCL uses exceptions to report errors and does not use the 5870error codes. The original code was commented out and a warning string 5871was inserted. You need to rewrite this code. 5872*/ 5873const queue_ptr stream = sycl_ctx -> stream (sycl_ctx -> device ,0 ); 5874SYCL_CHECK (CHECK_TRY_ERROR ((stream )-> memcpy ( 5875dst -> data ,src -> data ,ggml_nbytes (dst )))); 5876return true; 5877 } 5878 5879return false; 5880} 5881catch (sycl::exception const & exc ) { 5882 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5883 <<", line:" <<__LINE__ << std::endl ; 5884 std::exit (1 ); 5885} 5886 5887static void ggml_backend_sycl_synchronize (ggml_backend_t backend )try { 5888GGML_SYCL_DEBUG ("[SYCL] call %s\n" ,__func__ ); 5889ggml_backend_sycl_context * sycl_ctx = (ggml_backend_sycl_context * )backend -> context ; 5890const queue_ptr stream = sycl_ctx -> stream (sycl_ctx -> device ,0 ); 5891SYCL_CHECK (CHECK_TRY_ERROR ((stream )-> wait ())); 5892 5893GGML_UNUSED (backend ); 5894} 5895catch (sycl::exception const & exc ) { 5896 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5897 <<", line:" <<__LINE__ << std::endl ; 5898 std::exit (1 ); 5899} 5900 5901static bool ggml_sycl_is_view_or_noop (const ggml_tensor * t ) { 5902return ggml_is_empty (t )|| t -> op == GGML_OP_RESHAPE || t -> op == GGML_OP_TRANSPOSE || 5903t -> op == GGML_OP_VIEW || t -> op == GGML_OP_PERMUTE || t -> op == GGML_OP_NONE ; 5904} 5905 5906// match gated_delta_net + the strided cpy that scatters its state snapshots into the cache 5907// (slot i -> rollback group i, slot 0 newest), so the kernel can write them and skip the cpy. 5908// returns the number of following nodes to skip (0 = no fusion) 5909// ported from ggml_cuda_try_gdn_cache_fusion - pure graph inspection, backend-agnostic 5910static int ggml_sycl_try_gdn_cache_fusion (const ggml_cgraph * cgraph ,int node_idx , 5911ggml_sycl_gated_delta_net_fused_cache & fused_state_cpy ) { 5912if (!g_ggml_sycl_enable_fusion ) { 5913return 0 ; 5914 } 5915 5916const ggml_tensor * gdn = cgraph -> nodes [node_idx ]; 5917// the kernel skips the snapshot tail, so the gdn output must not be a graph output, and the cpy 5918// found below is taken to be its only reader, as it is in every graph that builds this op 5919if (gdn -> op != GGML_OP_GATED_DELTA_NET || gdn -> type != GGML_TYPE_F32 || 5920 (gdn -> flags & GGML_TENSOR_FLAG_OUTPUT )) { 5921return 0 ; 5922 } 5923 5924const ggml_tensor * src_v = gdn -> src [2 ]; 5925const int64_t S_v = src_v -> ne [0 ]; 5926const int64_t H = src_v -> ne [1 ]; 5927const int64_t n_tokens = src_v -> ne [2 ]; 5928const int64_t n_seqs = src_v -> ne [3 ]; 5929const int64_t D = S_v * S_v * H ; 5930const int64_t K = ggml_get_op_params_i32 (gdn ,0 );// snapshot slot count 5931const int64_t n_written = std::min < int64_t > (n_tokens ,K );// newest n_written slots are written 5932 5933// snapshot tail starts right after the attention scores 5934const size_t tail_off = ggml_row_size (GGML_TYPE_F32 ,S_v * H * n_tokens * n_seqs ); 5935 5936// the cpy must be the first node the compute loop below runs, so nothing can read the cache first. 5937// skip exactly what that loop skips: views, no-ops, and nodes the graph does not compute. 5938const ggml_tensor * cpy = nullptr ; 5939int skip = 0 ; 5940for (int j = node_idx + 1 ;j < cgraph -> n_nodes && cpy == nullptr ;++ j ) { 5941const ggml_tensor * n = cgraph -> nodes [j ]; 5942if (ggml_sycl_is_view_or_noop (n )|| (n -> flags & GGML_TENSOR_FLAG_COMPUTE )== 0 ) { 5943continue ; 5944 } 5945if (n -> op != GGML_OP_CPY || (n -> flags & GGML_TENSOR_FLAG_OUTPUT )) { 5946return 0 ; 5947 } 5948cpy = n ; 5949skip = j - node_idx ; 5950 } 5951if (cpy == nullptr ) { 5952return 0 ; 5953 } 5954 5955const ggml_tensor * src = cpy -> src [0 ];// view of the gdn snapshot tail 5956const ggml_tensor * dst = cpy -> src [1 ];// cache view the kernel writes to 5957 5958// src must be this gdn's snapshot tail (contiguous, at the tail offset) 5959if (src -> op != GGML_OP_VIEW || src -> view_src != gdn || src -> view_offs != tail_off || 5960 !ggml_is_contiguous (src )) { 5961return 0 ; 5962 } 5963 5964// dst is the [D, n_seqs, n_written] cache view, with the per-seq stride D that the kernel assumes. 5965// ggml_cpy pins src to the same element count, so src needs no shape check of its own. 5966const std::array < int64_t ,GGML_MAX_DIMS > expected_ne = {D ,n_seqs ,n_written ,1 }; 5967if (dst -> op != GGML_OP_VIEW || dst -> type != GGML_TYPE_F32 || dst -> data == nullptr || 5968 !std::equal (expected_ne .begin (),expected_ne .end (),dst -> ne )|| 5969dst -> nb [0 ]!= ggml_type_size (GGML_TYPE_F32 )|| 5970dst -> nb [1 ]!= (size_t )ggml_row_size (GGML_TYPE_F32 ,D )) { 5971return 0 ; 5972 } 5973 5974fused_state_cpy .data = (float * )dst -> data ;// rollback group 0 (newest) 5975fused_state_cpy .slot_stride = K > 1 ? (int64_t ) (dst -> nb [2 ] /sizeof (float )) :0 ; 5976return skip ; 5977} 5978 5979static void ggml_backend_sycl_graph_compute_impl (ggml_backend_sycl_context * sycl_ctx ,ggml_cgraph * cgraph ) { 5980ggml_sycl_set_main_device (sycl_ctx -> device ); 5981 5982for (int i = 0 ;i < cgraph -> n_nodes ;i ++ ) { 5983ggml_tensor * node = cgraph -> nodes [i ]; 5984if (ggml_sycl_is_view_or_noop (node )) { 5985continue ; 5986 } 5987if ((node -> flags & GGML_TENSOR_FLAG_COMPUTE )== 0 ) { 5988continue ; 5989 } 5990 5991const int nodes_to_skip = ggml_sycl_fuse (* sycl_ctx ,cgraph ,i ); 5992if (nodes_to_skip != 0 ) { 5993i += nodes_to_skip ; 5994continue ; 5995 } 5996#ifndef NDEBUG 5997assert (node -> buffer -> buft == ggml_backend_sycl_buffer_type (sycl_ctx -> device )); 5998for (int j = 0 ;j < GGML_MAX_SRC ;j ++ ) { 5999if (node -> src [j ]!= nullptr ) { 6000assert (node -> src [j ]-> buffer -> buft == ggml_backend_sycl_buffer_type (sycl_ctx -> device )); 6001 } 6002 } 6003#endif 6004// gated_delta_net -> cpy: scatter recurrent-state snapshots into the cache 6005if (node -> op == GGML_OP_GATED_DELTA_NET ) { 6006ggml_sycl_gated_delta_net_fused_cache fused_state_cpy ; 6007const int gdn_nodes_to_skip = ggml_sycl_try_gdn_cache_fusion (cgraph ,i ,fused_state_cpy ); 6008if (gdn_nodes_to_skip > 0 ) { 6009ggml_sycl_op_gated_delta_net_fused_cache (* sycl_ctx ,node ,fused_state_cpy ); 6010i += gdn_nodes_to_skip ; 6011continue ; 6012 } 6013 } 6014if (node -> op == GGML_OP_RMS_NORM && 6015ggml_sycl_can_fuse (cgraph ,i , {GGML_OP_RMS_NORM ,GGML_OP_MUL ,GGML_OP_ADD }, {})) { 6016ggml_sycl_op_rms_norm_fused_add (* sycl_ctx ,node ,cgraph -> nodes [i + 1 ],cgraph -> nodes [i + 2 ]); 6017i += 2 ; 6018continue ; 6019 } 6020if (node -> op == GGML_OP_RMS_NORM && 6021ggml_sycl_can_fuse (cgraph ,i , {GGML_OP_RMS_NORM ,GGML_OP_MUL }, {})) { 6022ggml_sycl_op_rms_norm_fused (* sycl_ctx ,node ,cgraph -> nodes [i + 1 ]); 6023i ++ ; 6024continue ; 6025 } 6026if (node -> op == GGML_OP_ADD && 6027ggml_sycl_can_fuse (cgraph ,i , {GGML_OP_ADD ,GGML_OP_ADD }, {})) { 6028ggml_sycl_op_add_add_fused (* sycl_ctx ,node ,cgraph -> nodes [i + 1 ]); 6029i ++ ; 6030continue ; 6031 } 6032if (node -> op == GGML_OP_UNARY && 6033ggml_sycl_can_fuse (cgraph ,i , {GGML_OP_UNARY ,GGML_OP_MUL }, {ggml_get_unary_op (node ) })) { 6034ggml_sycl_op_unary_mul_fused (* sycl_ctx ,node ,cgraph -> nodes [i + 1 ]); 6035i ++ ; 6036continue ; 6037 } 6038 6039// Batch consecutive independent same-shape F32 L2_NORM siblings (the GDN q/k 6040// norms) into one launch; sources are strided views of the fused qkv buffer, so 6041// the scan skips the interleaved view nodes instead of breaking on them. 6042if (node -> op == GGML_OP_L2_NORM ) { 6043const int l2_batch_skip = ggml_sycl_l2_norm_batch_fused (* sycl_ctx ,cgraph ,i ); 6044if (l2_batch_skip > 0 ) { 6045i += l2_batch_skip ; 6046continue ; 6047 } 6048 } 6049 6050if (node -> op == GGML_OP_SSM_CONV && 6051ggml_sycl_can_fuse (cgraph ,i , {GGML_OP_SSM_CONV ,GGML_OP_ADD ,GGML_OP_UNARY }, {GGML_UNARY_OP_SILU })) { 6052ggml_sycl_ssm_conv_fused (* sycl_ctx ,node ,cgraph -> nodes [i + 1 ],cgraph -> nodes [i + 2 ]); 6053i += 2 ; 6054continue ; 6055 } 6056 6057if (node -> op == GGML_OP_SSM_CONV && 6058ggml_sycl_can_fuse (cgraph ,i , {GGML_OP_SSM_CONV ,GGML_OP_UNARY }, {GGML_UNARY_OP_SILU })) { 6059ggml_sycl_ssm_conv_fused (* sycl_ctx ,node ,nullptr ,cgraph -> nodes [i + 1 ]); 6060i ++ ; 6061continue ; 6062 } 6063 6064if (node -> op == GGML_OP_MUL_MAT && ggml_sycl_mul_mat_glu_mmvq_fused (* sycl_ctx ,cgraph ,i )) { 6065i += 2 ; 6066continue ; 6067 } 6068 6069bool ok = ggml_sycl_compute_forward (* sycl_ctx ,node ); 6070if (!ok ) { 6071GGML_LOG_ERROR ("%s: error: op not supported %s (%s)\n" ,__func__ ,node -> name ,ggml_op_name (node -> op )); 6072 } 6073GGML_ASSERT (ok ); 6074 } 6075} 6076 6077#ifdef GGML_SYCL_GRAPH 6078static bool check_graph_compatibility (ggml_cgraph * cgraph ) { 6079if (ggml_sycl_info ().device_count > 1 ) { 6080// A sycl_ex::command_graph object can only be created for a single device 6081GGML_LOG_INFO ("%s: disabling SYCL graphs due to multiple devices\n" ,__func__ ); 6082return false; 6083 } 6084 6085for (int i = 0 ;i < cgraph -> n_nodes ;i ++ ) { 6086const ggml_op node_op = cgraph -> nodes [i ]-> op ; 6087switch (node_op ) { 6088default : 6089break ; 6090case GGML_OP_CONCAT : 6091// ggml_sycl_op_concat() does a blocking host wait after memcpy operations, 6092// but wait() can't be called on the events returned by a queue recording 6093// to a graph. 6094 [[fallthrough ]]; 6095case GGML_OP_MUL_MAT_ID : 6096// ggml_sycl_mul_mat_id() does a blocking host wait on the sycl queue after 6097// submitting a memcpy operation, but wait() can't be called on a queue that 6098// is recording to a graph. 6099GGML_LOG_INFO ("%s: disabling SYCL graphs due to unsupported node type %s\n" ,__func__ , 6100ggml_op_name (node_op )); 6101return false; 6102case GGML_OP_MUL_MAT : 6103// We cannot use graphs with ggml_sycl_mul_mat() when SYCL async memory allocation extensions are not available, 6104// as SYCL malloc / free and host wait calls are not supported when recording to a graph which are all present 6105// in reordering. 6106if (!g_ggml_sycl_use_async_mem_op ) { 6107GGML_LOG_INFO ( 6108"%s: disabling SYCL graphs due to unsupported node type when using a compiler without the " 6109"oneAPI async memory allocation extension " 6110"%s\n" , 6111__func__ ,ggml_op_name (node_op )); 6112return false; 6113 } 6114 } 6115 } 6116return true; 6117} 6118#endif 6119 6120static ggml_status ggml_backend_sycl_graph_compute (ggml_backend_t backend ,ggml_cgraph * cgraph ) { 6121auto * sycl_ctx = static_cast < ggml_backend_sycl_context *> (backend -> context ); 6122 6123#ifdef GGML_SYCL_GRAPH 6124bool use_sycl_graph = false; 6125if (g_ggml_sycl_enable_graph ) { 6126use_sycl_graph = check_graph_compatibility (cgraph ); 6127 } 6128if (use_sycl_graph ) { 6129const bool graph_support = dpct::get_device (sycl_ctx -> device ).has (sycl::aspect::ext_oneapi_limited_graph ); 6130if (!graph_support ) { 6131GGML_SYCL_DEBUG ("[SYCL-GRAPH] can not use graphs on device:%d\n" ,sycl_ctx -> device ); 6132ggml_backend_sycl_graph_compute_impl (sycl_ctx ,cgraph ); 6133return GGML_STATUS_SUCCESS ; 6134 } 6135 6136 sycl_ex::command_graph model_sycl_graph (* (sycl_ctx -> stream ()), {sycl_ex::property::graph::assume_buffer_outlives_graph {}}); 6137 6138model_sycl_graph .begin_recording (* (sycl_ctx -> stream ())); 6139ggml_backend_sycl_graph_compute_impl (sycl_ctx ,cgraph ); 6140model_sycl_graph .end_recording (); 6141 6142const bool graph_update_support = dpct::get_device (sycl_ctx -> device ).has (sycl::aspect::ext_oneapi_graph ); 6143if (!sycl_ctx -> exec_graph || !graph_update_support ) { 6144auto exec_graph = graph_update_support ?model_sycl_graph .finalize (sycl_ex::property::graph::updatable {}) : 6145model_sycl_graph .finalize (); 6146sycl_ctx -> exec_graph = std::make_unique < 6147 sycl_ex::command_graph < sycl_ex::graph_state::executable >> (exec_graph ); 6148 }else { 6149try { 6150sycl_ctx -> exec_graph -> update (model_sycl_graph ); 6151GGML_SYCL_DEBUG ("[SYCL-GRAPH] update success\n" ); 6152 }catch (sycl::exception const & e ) { 6153GGML_SYCL_DEBUG ("[SYCL-GRAPH] Exception when updating graph, %s\n" ,e .what ()); 6154auto exec_graph = model_sycl_graph .finalize ({sycl_ex::property::graph::updatable {}}); 6155sycl_ctx -> exec_graph = std::make_unique < 6156 sycl_ex::command_graph < sycl_ex::graph_state::executable >> (exec_graph ); 6157 } 6158 } 6159 6160sycl_ctx -> stream ()-> ext_oneapi_graph (* (sycl_ctx -> exec_graph )); 6161 }else 6162#endif 6163 { 6164ggml_backend_sycl_graph_compute_impl (sycl_ctx ,cgraph ); 6165 } 6166return GGML_STATUS_SUCCESS ; 6167} 6168 6169static void ggml_backend_sycl_event_record (ggml_backend_t backend ,ggml_backend_event_t event ) 6170try 6171{ 6172ggml_backend_sycl_context * sycl_ctx = 6173 (ggml_backend_sycl_context * )backend -> context ; 6174 6175 sycl::event * sycl_event = static_cast < sycl::event *> (event -> context ); 6176 6177const queue_ptr & stream = sycl_ctx -> stream (sycl_ctx -> device ,0 ); 6178// Record the current state of the queue 6179SYCL_CHECK (CHECK_TRY_ERROR (* sycl_event = stream -> ext_oneapi_submit_barrier ())); 6180} 6181catch (sycl::exception const & exc ) 6182{ 6183 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 6184 <<", line:" <<__LINE__ << std::endl ; 6185 std::exit (1 ); 6186} 6187 6188static void ggml_backend_sycl_event_wait (ggml_backend_t backend ,ggml_backend_event_t event )try { 6189GGML_SYCL_DEBUG ("[SYCL] call %s\n" ,__func__ ); 6190 sycl::event * sycl_event = static_cast < sycl::event *> (event -> context ); 6191 6192if (ggml_backend_is_sycl (backend )) { 6193SYCL_CHECK (CHECK_TRY_ERROR (sycl_event -> wait ())); 6194 }else 6195GGML_ABORT ("fatal error" ); 6196}catch (sycl::exception const & exc ) { 6197 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 6198 <<", line:" <<__LINE__ << std::endl ; 6199 std::exit (1 ); 6200} 6201 6202static ggml_backend_i ggml_backend_sycl_interface = { 6203/* .get_name = */ ggml_backend_sycl_get_name , 6204/* .free = */ ggml_backend_sycl_free , 6205/* .set_tensor_async = */ ggml_backend_sycl_set_tensor_async , 6206/* .get_tensor_async = */ ggml_backend_sycl_get_tensor_async , 6207/* .set_tensor_2d_async = */ NULL , 6208/* .get_tensor_2d_async = */ NULL , 6209/* .cpy_tensor_async = */ NULL ,// ggml_backend_sycl_cpy_tensor_async, 6210// // TODO: update for the new 6211// interface 6212/* .synchronize = */ ggml_backend_sycl_synchronize , 6213/* .graph_plan_create = */ NULL , 6214/* .graph_plan_free = */ NULL , 6215/* .graph_plan_update = */ NULL , 6216/* .graph_plan_compute = */ NULL , 6217/* .graph_compute = */ ggml_backend_sycl_graph_compute , 6218/* .event_record = */ ggml_backend_sycl_event_record , 6219/* .event_wait = */ ggml_backend_sycl_event_wait , 6220/* .graph_optimize = */ NULL , 6221}; 6222 6223static ggml_guid_t ggml_backend_sycl_guid () { 6224static ggml_guid guid = {0x58 ,0x05 ,0x13 ,0x8f ,0xcd ,0x3a ,0x61 ,0x9d ,0xe7 ,0xcd ,0x98 ,0xa9 ,0x03 ,0xfd ,0x7c ,0x53 }; 6225return & guid ; 6226} 6227 6228bool ggml_backend_is_sycl (ggml_backend_t backend ) { 6229return backend != NULL && ggml_guid_matches (backend -> guid ,ggml_backend_sycl_guid ()); 6230} 6231 6232int ggml_backend_sycl_get_device_count () { 6233return ggml_sycl_info ().device_count ; 6234} 6235 6236 6237// backend device 6238 6239static const char * ggml_backend_sycl_device_get_name (ggml_backend_dev_t dev ) { 6240ggml_backend_sycl_device_context * ctx = (ggml_backend_sycl_device_context * )dev -> context ; 6241return ctx -> name .c_str (); 6242} 6243 6244static const char * ggml_backend_sycl_device_get_description (ggml_backend_dev_t dev ) { 6245ggml_backend_sycl_device_context * ctx = (ggml_backend_sycl_device_context * )dev -> context ; 6246return ctx -> description .c_str (); 6247} 6248 6249static void ggml_backend_sycl_device_get_memory (ggml_backend_dev_t dev ,size_t * free ,size_t * total ) { 6250GGML_SYCL_DEBUG ("[SYCL] call %s\n" ,__func__ ); 6251ggml_backend_sycl_device_context * ctx = (ggml_backend_sycl_device_context * )dev -> context ; 6252if (!sycl_get_mem_info (ctx -> device ,free ,total )) { 6253GGML_ABORT ("[%s] failed to get device memory size" ,__func__ ); 6254 } 6255GGML_SYCL_DEBUG ("[SYCL] call %s total %zu free %zu\n" ,__func__ ,* total ,* free ); 6256ggml_sycl_memtrace_report_device ("device memory query (dev)" ,ctx -> device ,* free ,* total ); 6257} 6258 6259static enum ggml_backend_dev_type ggml_backend_sycl_device_get_type (ggml_backend_dev_t dev ) { 6260ggml_backend_sycl_device_context * ctx = (ggml_backend_sycl_device_context * )dev -> context ; 6261const sycl_device_info & info = ggml_sycl_info ().devices [ctx -> device ]; 6262if (info .l0_device_type_valid && !info .l0_discrete_gpu ) { 6263return GGML_BACKEND_DEVICE_TYPE_IGPU ; 6264 } 6265return GGML_BACKEND_DEVICE_TYPE_GPU ; 6266} 6267 6268static void ggml_backend_sycl_device_get_props (ggml_backend_dev_t dev ,ggml_backend_dev_props * props ) { 6269props -> name = ggml_backend_sycl_device_get_name (dev ); 6270props -> description = ggml_backend_sycl_device_get_description (dev ); 6271props -> type = ggml_backend_sycl_device_get_type (dev ); 6272ggml_backend_sycl_device_get_memory (dev ,& props -> memory_free ,& props -> memory_total ); 6273 6274bool host_buffer = getenv ("GGML_SYCL_NO_PINNED" )== nullptr ; 6275#ifdef GGML_SYCL_NO_PEER_COPY 6276bool events = false; 6277#else 6278bool events = true; 6279#endif 6280 6281props -> caps = { 6282/* .async = */ true, 6283/* .host_buffer = */ host_buffer , 6284/* .buffer_from_host_ptr = */ false, 6285/* .events = */ events , 6286/* .mmap_support = */ true, 6287 }; 6288} 6289 6290static ggml_backend_t ggml_backend_sycl_device_init (ggml_backend_dev_t dev ,const char * params ) { 6291GGML_UNUSED (params ); 6292ggml_backend_sycl_device_context * ctx = (ggml_backend_sycl_device_context * )dev -> context ; 6293return ggml_backend_sycl_init (ctx -> device ); 6294} 6295 6296static ggml_backend_buffer_type_t ggml_backend_sycl_device_get_buffer_type (ggml_backend_dev_t dev ) { 6297ggml_backend_sycl_device_context * ctx = (ggml_backend_sycl_device_context * )dev -> context ; 6298return ggml_backend_sycl_buffer_type (ctx -> device ); 6299} 6300 6301static ggml_backend_buffer_type_t ggml_backend_sycl_device_get_host_buffer_type (ggml_backend_dev_t dev ) { 6302GGML_UNUSED (dev ); 6303return ggml_backend_sycl_host_buffer_type (); 6304} 6305 6306static ggml_backend_buffer_t ggml_backend_sycl_device_buffer_from_host_ptr (ggml_backend_dev_t dev ,void * ptr ,size_t size ,size_t max_tensor_size ) { 6307GGML_UNUSED (dev ); 6308GGML_UNUSED (ptr ); 6309GGML_UNUSED (size ); 6310GGML_UNUSED (max_tensor_size ); 6311return nullptr ; 6312} 6313 6314static bool do_ggml_backend_sycl_device_supports_op (ggml_backend_dev_t dev ,const ggml_tensor * op ) { 6315ggml_backend_sycl_device_context * sycl_ctx = 6316 (ggml_backend_sycl_device_context * )dev -> context ; 6317int device = sycl_ctx -> device ; 6318switch (op -> op ) { 6319case GGML_OP_CONV_TRANSPOSE_1D : 6320 { 6321ggml_type src0_type = op -> src [0 ]-> type ; 6322ggml_type src1_type = op -> src [1 ]-> type ; 6323if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32 ) { 6324return true; 6325 } 6326return false; 6327 } 6328case GGML_OP_CONV_2D : 6329case GGML_OP_CONV_2D_DW : 6330case GGML_OP_CONV_TRANSPOSE_2D : 6331return true; 6332case GGML_OP_UNARY : 6333switch (ggml_get_unary_op (op )) { 6334case GGML_UNARY_OP_SGN : 6335case GGML_UNARY_OP_ABS : 6336case GGML_UNARY_OP_NEG : 6337case GGML_UNARY_OP_STEP : 6338case GGML_UNARY_OP_RELU : 6339case GGML_UNARY_OP_HARDSIGMOID : 6340case GGML_UNARY_OP_TANH : 6341case GGML_UNARY_OP_GELU : 6342case GGML_UNARY_OP_SILU : 6343case GGML_UNARY_OP_SIGMOID : 6344case GGML_UNARY_OP_HARDSWISH : 6345case GGML_UNARY_OP_GELU_QUICK : 6346case GGML_UNARY_OP_GELU_ERF : 6347case GGML_UNARY_OP_EXP : 6348case GGML_UNARY_OP_EXPM1 : 6349case GGML_UNARY_OP_SOFTPLUS : 6350case GGML_UNARY_OP_ELU : 6351case GGML_UNARY_OP_XIELU : 6352case GGML_UNARY_OP_CEIL : 6353return true; 6354case GGML_UNARY_OP_FLOOR : 6355case GGML_UNARY_OP_ROUND : 6356case GGML_UNARY_OP_TRUNC : 6357return true; 6358default : 6359return false; 6360 } 6361case GGML_OP_GLU : 6362switch (ggml_get_glu_op (op )) { 6363case GGML_GLU_OP_REGLU : 6364case GGML_GLU_OP_GEGLU : 6365case GGML_GLU_OP_SWIGLU : 6366case GGML_GLU_OP_SWIGLU_OAI : 6367case GGML_GLU_OP_GEGLU_ERF : 6368case GGML_GLU_OP_GEGLU_QUICK : 6369case GGML_GLU_OP_SWIGLU_CLAMP : 6370return ggml_is_contiguous_1 (op -> src [0 ]); 6371default : 6372return false; 6373 } 6374break ; 6375case GGML_OP_MUL_MAT : 6376case GGML_OP_MUL_MAT_ID : 6377 { 6378struct ggml_tensor * a = op -> src [0 ]; 6379struct ggml_tensor * b = op -> src [1 ]; 6380 6381if (a -> ne [3 ]!= b -> ne [3 ]) { 6382return false; 6383 } 6384 6385ggml_type src0_type = op -> src [0 ]-> type ; 6386 6387// TODO: The configuration below needs more work to be supported with oneDNN 6388if (ggml_is_permuted (a )&& !ggml_is_contiguous (a )&& 6389a -> ne [2 ]> 1 && a -> ne [3 ]> 1 && src0_type == GGML_TYPE_F16 ) { 6390return false; 6391 } 6392 6393// TODO: This specific configuration can fail with oneDNN and needs more debugging 6394if (!ggml_is_permuted (a )&& ggml_is_permuted (b )&& b -> ne [2 ]> 1 && b -> ne [3 ]> 1 && 6395a -> ne [0 ]> 128 && a -> ne [2 ]== 1 && src0_type == GGML_TYPE_F16 ) { 6396return false; 6397 } 6398 6399if (src0_type == GGML_TYPE_TQ2_0 || src0_type == GGML_TYPE_TQ1_0 ) { 6400return false; 6401 } 6402 6403return true; 6404 } 6405case GGML_OP_OUT_PROD : 6406return op -> type == GGML_TYPE_F32 && 6407 (op -> src [0 ]-> type == GGML_TYPE_F32 || 6408 (op -> src [0 ]-> type == GGML_TYPE_Q1_0 && op -> src [0 ]-> ne [2 ]== op -> src [1 ]-> ne [2 ]&& 6409op -> src [0 ]-> ne [3 ]== op -> src [1 ]-> ne [3 ]))&& 6410op -> src [1 ]-> type == GGML_TYPE_F32 ; 6411case GGML_OP_GET_ROWS : 6412 { 6413switch (op -> src [0 ]-> type ) { 6414case GGML_TYPE_I32 : 6415case GGML_TYPE_F16 : 6416case GGML_TYPE_BF16 : 6417case GGML_TYPE_F32 : 6418case GGML_TYPE_Q1_0 : 6419case GGML_TYPE_MXFP4 : 6420case GGML_TYPE_NVFP4 : 6421case GGML_TYPE_IQ2_XXS : 6422case GGML_TYPE_IQ2_XS : 6423case GGML_TYPE_IQ2_S : 6424case GGML_TYPE_IQ3_XXS : 6425case GGML_TYPE_IQ1_S : 6426case GGML_TYPE_IQ1_M : 6427case GGML_TYPE_IQ3_S : 6428case GGML_TYPE_IQ4_NL : 6429case GGML_TYPE_IQ4_XS : 6430case GGML_TYPE_Q2_K : 6431case GGML_TYPE_Q3_K : 6432case GGML_TYPE_Q4_0 : 6433case GGML_TYPE_Q4_1 : 6434case GGML_TYPE_Q4_K : 6435case GGML_TYPE_Q5_0 : 6436case GGML_TYPE_Q5_1 : 6437case GGML_TYPE_Q5_K : 6438case GGML_TYPE_Q6_K : 6439case GGML_TYPE_Q8_0 : 6440return true; 6441default : 6442return false; 6443 } 6444 } 6445case GGML_OP_SET : 6446return (op -> type == GGML_TYPE_F32 )&& 6447 (op -> src [0 ]&& op -> src [1 ])&& 6448 (op -> src [0 ]-> type == GGML_TYPE_F32 )&& 6449 (op -> src [1 ]-> type == GGML_TYPE_F32 ); 6450 6451case GGML_OP_SET_ROWS : 6452 { 6453if (op -> type == GGML_TYPE_TQ2_0 || op -> type == GGML_TYPE_TQ1_0 ) { 6454return false; 6455 } 6456auto res = (op -> src [0 ]-> type == GGML_TYPE_F32 || op -> src [0 ]-> type == GGML_TYPE_F16 || 6457op -> src [0 ]-> type == GGML_TYPE_BF16 )&& 6458 (op -> src [1 ]-> type == GGML_TYPE_I64 || op -> src [1 ]-> type == GGML_TYPE_I32 ); 6459return res ; 6460 } 6461break ; 6462case GGML_OP_DSV4_HC_PRE : 6463return op -> src [0 ]-> type == GGML_TYPE_F32 && op -> src [1 ]-> type == GGML_TYPE_F32 && 6464op -> type == GGML_TYPE_F32 && ggml_get_op_params_i32 (op ,1 )== 0 ; 6465case GGML_OP_DSV4_HC_COMB : 6466return op -> src [0 ]-> type == GGML_TYPE_F32 && op -> src [1 ]-> type == GGML_TYPE_F32 && 6467op -> src [2 ]-> type == GGML_TYPE_F32 && op -> type == GGML_TYPE_F32 ; 6468case GGML_OP_DSV4_HC_POST : 6469return op -> src [0 ]-> type == GGML_TYPE_F32 && op -> src [1 ]-> type == GGML_TYPE_F32 && 6470op -> src [2 ]-> type == GGML_TYPE_F32 && op -> src [3 ]!= nullptr && op -> src [3 ]-> type == GGML_TYPE_F32 && 6471op -> type == GGML_TYPE_F32 ; 6472case GGML_OP_LIGHTNING_INDEXER : 6473return op -> src [0 ]-> type == GGML_TYPE_F32 && 6474 (op -> src [1 ]-> type == GGML_TYPE_F16 || op -> src [1 ]-> type == GGML_TYPE_F32 || 6475op -> src [1 ]-> type == GGML_TYPE_BF16 || op -> src [1 ]-> type == GGML_TYPE_Q8_0 || 6476op -> src [1 ]-> type == GGML_TYPE_Q5_1 || op -> src [1 ]-> type == GGML_TYPE_Q5_0 || 6477op -> src [1 ]-> type == GGML_TYPE_Q4_1 || op -> src [1 ]-> type == GGML_TYPE_Q4_0 || 6478op -> src [1 ]-> type == GGML_TYPE_IQ4_NL )&& 6479op -> src [2 ]-> type == GGML_TYPE_F32 && 6480op -> src [3 ]-> type == GGML_TYPE_F16 && 6481op -> type == GGML_TYPE_F32 && 6482op -> src [0 ]-> ne [0 ]== WARP_SIZE * 8 ; 6483case GGML_OP_CPY : 6484 { 6485ggml_type src0_type = op -> src [0 ]-> type ; 6486ggml_type src1_type = op -> src [1 ]-> type ; 6487 6488if (src0_type == GGML_TYPE_F16 ) { 6489if (src1_type == GGML_TYPE_Q2_K || 6490src1_type == GGML_TYPE_Q3_K || 6491src1_type == GGML_TYPE_Q4_K || 6492src1_type == GGML_TYPE_Q5_K || 6493src1_type == GGML_TYPE_Q6_K || 6494src1_type == GGML_TYPE_IQ2_XXS || 6495src1_type == GGML_TYPE_IQ2_XS || 6496src1_type == GGML_TYPE_IQ2_S || 6497src1_type == GGML_TYPE_IQ3_XXS || 6498src1_type == GGML_TYPE_IQ1_S || 6499src1_type == GGML_TYPE_IQ1_M || 6500src1_type == GGML_TYPE_IQ3_S || 6501src1_type == GGML_TYPE_IQ4_XS ) { 6502return false; 6503 } 6504 } 6505 6506if (src0_type == GGML_TYPE_BF16 ) { 6507if (src1_type == GGML_TYPE_Q4_0 || //big error in ut 6508src1_type == GGML_TYPE_Q4_1 || //big error in ut 6509src1_type == GGML_TYPE_Q8_0 || //big error in ut 6510src1_type == GGML_TYPE_Q2_K || 6511src1_type == GGML_TYPE_Q3_K || 6512src1_type == GGML_TYPE_Q4_K || 6513src1_type == GGML_TYPE_Q5_K || 6514src1_type == GGML_TYPE_Q6_K || 6515src1_type == GGML_TYPE_IQ2_XXS || 6516src1_type == GGML_TYPE_IQ2_XS || 6517src1_type == GGML_TYPE_IQ2_S || 6518src1_type == GGML_TYPE_IQ3_XXS || 6519src1_type == GGML_TYPE_IQ1_S || 6520src1_type == GGML_TYPE_IQ1_M || 6521src1_type == GGML_TYPE_IQ3_S || 6522src1_type == GGML_TYPE_IQ4_XS ) { 6523return false; 6524 } 6525 } 6526 6527if (src0_type == GGML_TYPE_F32 ) { 6528if (src1_type == GGML_TYPE_Q2_K || 6529src1_type == GGML_TYPE_Q3_K || 6530src1_type == GGML_TYPE_Q4_K || 6531src1_type == GGML_TYPE_Q5_K || 6532src1_type == GGML_TYPE_Q6_K || 6533src1_type == GGML_TYPE_IQ2_XXS || 6534src1_type == GGML_TYPE_IQ2_XS || 6535src1_type == GGML_TYPE_IQ2_S || 6536src1_type == GGML_TYPE_IQ3_XXS || 6537src1_type == GGML_TYPE_IQ1_S || 6538src1_type == GGML_TYPE_IQ1_M || 6539src1_type == GGML_TYPE_IQ3_S || 6540src1_type == GGML_TYPE_IQ4_XS ) { 6541return false; 6542 } 6543 } 6544 6545if (src1_type == GGML_TYPE_F32 ) { 6546if (src0_type == GGML_TYPE_Q1_0 || 6547src0_type == GGML_TYPE_NVFP4 || 6548src0_type == GGML_TYPE_Q2_K || 6549src0_type == GGML_TYPE_Q3_K || 6550src0_type == GGML_TYPE_Q4_K || 6551src0_type == GGML_TYPE_Q5_K || 6552src0_type == GGML_TYPE_Q6_K || 6553src0_type == GGML_TYPE_IQ2_XXS || 6554src0_type == GGML_TYPE_IQ2_XS || 6555src0_type == GGML_TYPE_IQ2_S || 6556src0_type == GGML_TYPE_IQ3_XXS || 6557src0_type == GGML_TYPE_IQ1_S || 6558src0_type == GGML_TYPE_IQ1_M || 6559src0_type == GGML_TYPE_IQ3_S || 6560src0_type == GGML_TYPE_IQ4_NL || 6561src0_type == GGML_TYPE_IQ4_XS 6562 ) { 6563return false; 6564 } 6565 } 6566 6567if (src0_type == src1_type ) { 6568if (src1_type == GGML_TYPE_IQ2_XXS || 6569src1_type == GGML_TYPE_IQ2_XS || 6570src1_type == GGML_TYPE_IQ2_S || 6571src1_type == GGML_TYPE_IQ3_XXS || 6572src1_type == GGML_TYPE_IQ3_S || 6573src1_type == GGML_TYPE_IQ1_S || 6574src1_type == GGML_TYPE_IQ1_M || 6575src1_type == GGML_TYPE_TQ2_0 || 6576src1_type == GGML_TYPE_TQ1_0 ) { 6577return false; 6578 } 6579 } 6580 6581if (src0_type == GGML_TYPE_TQ2_0 || src1_type == GGML_TYPE_TQ2_0 || 6582src0_type == GGML_TYPE_TQ1_0 || src1_type == GGML_TYPE_TQ1_0 ) { 6583return false; 6584 } 6585 6586return true; 6587 } 6588case GGML_OP_REPEAT_BACK : 6589 { 6590ggml_type src0_type = op -> src [0 ]-> type ; 6591return src0_type == GGML_TYPE_F32 ; 6592 } 6593case GGML_OP_CONCAT : 6594case GGML_OP_DUP : 6595case GGML_OP_ARGMAX : 6596case GGML_OP_NONE : 6597case GGML_OP_RESHAPE : 6598case GGML_OP_VIEW : 6599case GGML_OP_PERMUTE : 6600case GGML_OP_TRANSPOSE : 6601case GGML_OP_ADD : 6602case GGML_OP_ADD1 : 6603case GGML_OP_ADD_ID : 6604case GGML_OP_SUB : 6605case GGML_OP_COUNT_EQUAL : 6606case GGML_OP_MUL : 6607case GGML_OP_DIV : 6608case GGML_OP_REPEAT : 6609return true; 6610case GGML_OP_PAD_REFLECT_1D : 6611return ggml_is_contiguous (op -> src [0 ])&& op -> type == GGML_TYPE_F32 && op -> src [0 ]-> type == GGML_TYPE_F32 ; 6612case GGML_OP_SQR : 6613case GGML_OP_SQRT : 6614case GGML_OP_SIN : 6615case GGML_OP_COS : 6616case GGML_OP_CLAMP : 6617case GGML_OP_LOG : 6618case GGML_OP_NORM : 6619case GGML_OP_L2_NORM : 6620case GGML_OP_GROUP_NORM : 6621case GGML_OP_RMS_NORM : 6622return true; 6623case GGML_OP_RMS_NORM_BACK : 6624return ggml_is_contiguous (op -> src [0 ]); 6625case GGML_OP_SCALE : 6626return true; 6627case GGML_OP_CONT : 6628return true; 6629case GGML_OP_TRI : 6630 { 6631const ggml_tensor * src0 = op -> src [0 ]; 6632return src0 && 6633op -> type == GGML_TYPE_F32 && 6634ggml_is_contiguous (src0 ); 6635 } 6636case GGML_OP_DIAG_MASK_INF : 6637return true; 6638case GGML_OP_SOFT_MAX : 6639return true; 6640case GGML_OP_SOFT_MAX_BACK : { 6641float max_bias = 0.0f ; 6642memcpy (& max_bias , (const float * )op -> op_params + 1 ,sizeof (float )); 6643return max_bias == 0.0f ; 6644 } 6645case GGML_OP_ROPE : 6646case GGML_OP_ROPE_BACK : 6647case GGML_OP_IM2COL : 6648case GGML_OP_IM2COL_3D : 6649case GGML_OP_UPSCALE : 6650return true; 6651case GGML_OP_COL2IM_1D : 6652return ggml_is_contiguous (op -> src [0 ])&& 6653 (op -> type == GGML_TYPE_F32 || op -> type == GGML_TYPE_F16 6654#ifdef GGML_SYCL_HAS_BF16 6655|| op -> type == GGML_TYPE_BF16 6656#endif 6657 )&& 6658op -> src [0 ]-> type == op -> type ; 6659case GGML_OP_CONV_3D : 6660return op -> type == GGML_TYPE_F32 && 6661 (op -> src [0 ]-> type == GGML_TYPE_F32 || op -> src [0 ]-> type == GGML_TYPE_F16 )&& 6662op -> src [1 ]-> type == GGML_TYPE_F32 && 6663ggml_is_contiguous (op -> src [0 ])&& 6664ggml_is_contiguous (op -> src [1 ]); 6665case GGML_OP_SUM : 6666case GGML_OP_SUM_ROWS : 6667case GGML_OP_MEAN : 6668return ggml_is_contiguous (op -> src [0 ]); 6669case GGML_OP_ARGSORT : 6670return true; 6671case GGML_OP_TOP_K : { 6672const ggml_tensor * src0 = op -> src [0 ]; 6673const int k = op -> ne [0 ]; 6674return src0 && 6675op -> type == GGML_TYPE_I32 && 6676src0 -> type == GGML_TYPE_F32 && 6677ggml_is_contiguous (src0 )&& 6678k > 0 && k <=src0 -> ne [0 ]; 6679 } 6680case GGML_OP_POOL_2D : 6681case GGML_OP_POOL_1D : 6682case GGML_OP_ACC : 6683return true; 6684case GGML_OP_PAD : 6685if (ggml_get_op_params_i32 (op ,8 )!= 0 ) { 6686return false; 6687 } 6688return true; 6689case GGML_OP_LEAKY_RELU : 6690case GGML_OP_TIMESTEP_EMBEDDING : 6691case GGML_OP_RWKV_WKV6 : 6692case GGML_OP_RWKV_WKV7 : 6693case GGML_OP_GATED_LINEAR_ATTN : 6694case GGML_OP_GATED_DELTA_NET : 6695case GGML_OP_OPT_STEP_ADAMW : 6696case GGML_OP_OPT_STEP_SGD : 6697return true; 6698case GGML_OP_SSM_CONV : 6699return op -> type == GGML_TYPE_F32 && 6700op -> src [0 ]-> type == GGML_TYPE_F32 && 6701op -> src [1 ]-> type == GGML_TYPE_F32 ; 6702case GGML_OP_ROLL : 6703return op -> type == GGML_TYPE_F32 ; 6704case GGML_OP_ARANGE : 6705return op -> type == GGML_TYPE_F32 ; 6706case GGML_OP_SSM_SCAN : 6707if (op -> src [3 ]-> ne [0 ]== 1 ) { 6708// Mamba2 6709// (kernel only supports (d_state == 128 || d_state == 256) && d_head % WARP_SIZE == 0) 6710return (op -> src [0 ]-> ne [0 ]== 128 || op -> src [0 ]-> ne [0 ]== 256 )&& op -> src [0 ]-> ne [1 ] %WARP_SIZE == 0 ; 6711 }else { 6712// TODO Mamba-1 not yet ported to SYCL 6713return false; 6714 } 6715case GGML_OP_FILL : 6716case GGML_OP_CUMSUM : 6717case GGML_OP_DIAG : 6718case GGML_OP_CROSS_ENTROPY_LOSS : 6719case GGML_OP_CROSS_ENTROPY_LOSS_BACK : 6720return true; 6721case GGML_OP_SOLVE_TRI : 6722return op -> src [0 ]-> ne [0 ] <=SYCL_SOLVE_TRI_MAX_N && op -> src [1 ]-> ne [0 ] <=SYCL_SOLVE_TRI_MAX_K ; 6723case GGML_OP_FLASH_ATTN_EXT : 6724return ggml_sycl_flash_attn_ext_supported (device ,op ); 6725default : 6726return false; 6727 } 6728 6729GGML_UNUSED (dev ); 6730} 6731 6732static bool ggml_backend_sycl_device_supports_op (ggml_backend_dev_t dev ,const ggml_tensor * op ) { 6733bool res = do_ggml_backend_sycl_device_supports_op (dev ,op ); 6734GGML_SYCL_DEBUG ("[SYCL] call %s op->op=%s op->type=%s -> %s\n" ,__func__ ,ggml_op_name (op -> op ), 6735ggml_type_name (op -> type ),res ?"true" :"false" ); 6736return res ; 6737} 6738 6739static bool ggml_backend_sycl_device_supports_buft (ggml_backend_dev_t dev ,ggml_backend_buffer_type_t buft ) { 6740if (buft -> iface .get_name != ggml_backend_sycl_buffer_type_get_name ) { 6741return false; 6742 } 6743ggml_backend_sycl_buffer_type_context * buft_ctx = (ggml_backend_sycl_buffer_type_context * )buft -> context ; 6744ggml_backend_sycl_device_context * sycl_ctx = (ggml_backend_sycl_device_context * )dev -> context ; 6745return buft_ctx -> device == sycl_ctx -> device ; 6746} 6747 6748static int64_t get_op_batch_size (const ggml_tensor * op ) { 6749switch (op -> op ) { 6750case GGML_OP_GET_ROWS : 6751return 0 ; 6752case GGML_OP_MUL_MAT : 6753return op -> ne [1 ]; 6754case GGML_OP_MUL_MAT_ID : 6755case GGML_OP_ROPE : 6756return op -> ne [2 ]; 6757default : 6758return ggml_nrows (op ); 6759 } 6760} 6761 6762static bool ggml_backend_sycl_device_offload_op (ggml_backend_dev_t dev ,const ggml_tensor * op ) { 6763ggml_backend_sycl_device_context * sycl_ctx = (ggml_backend_sycl_device_context * )dev -> context ; 6764return get_op_batch_size (op ) >=sycl_ctx -> op_offload_min_batch_size ; 6765} 6766 6767static ggml_backend_event_t 6768ggml_backend_sycl_device_event_new (ggml_backend_dev_t dev ) { 6769 6770#ifdef GGML_SYCL_NO_PEER_COPY 6771return nullptr ; 6772#else 6773 sycl::event * event_ptr = new sycl::event (); 6774 6775return new ggml_backend_event { 6776/* .device = */ dev , 6777/* .context = */ event_ptr , 6778 }; 6779#endif 6780} 6781 6782static void ggml_backend_sycl_device_event_free (ggml_backend_dev_t dev ,ggml_backend_event_t event )try { 6783GGML_UNUSED (dev ); 6784if (event == nullptr ) { 6785return ; 6786 } 6787 6788if (event -> context != nullptr ) { 6789 sycl::event * sycl_event = static_cast < sycl::event *> (event -> context ); 6790delete sycl_event ; 6791event -> context = nullptr ; 6792 } 6793 6794delete event ; 6795}catch (sycl::exception const & exc ) { 6796 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 6797 <<", line:" <<__LINE__ << std::endl ; 6798 std::exit (1 ); 6799} 6800 6801 6802static void ggml_backend_sycl_device_event_synchronize (ggml_backend_dev_t dev ,ggml_backend_event_t event )try { 6803GGML_UNUSED (dev ); 6804GGML_SYCL_DEBUG ("[SYCL] call %s\n" ,__func__ ); 6805 6806 sycl::event * sycl_event = static_cast < sycl::event *> (event -> context ); 6807SYCL_CHECK (CHECK_TRY_ERROR (sycl_event -> wait ())); 6808}catch (sycl::exception const & exc ) { 6809 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 6810 <<", line:" <<__LINE__ << std::endl ; 6811 std::exit (1 ); 6812} 6813 6814static const ggml_backend_device_i ggml_backend_sycl_device_interface = { 6815/* .get_name = */ ggml_backend_sycl_device_get_name , 6816/* .get_description = */ ggml_backend_sycl_device_get_description , 6817/* .get_memory = */ ggml_backend_sycl_device_get_memory , 6818/* .get_type = */ ggml_backend_sycl_device_get_type , 6819/* .get_props = */ ggml_backend_sycl_device_get_props , 6820/* .init_backend = */ ggml_backend_sycl_device_init , 6821/* .get_buffer_type = */ ggml_backend_sycl_device_get_buffer_type , 6822/* .get_host_buffer_type = */ ggml_backend_sycl_device_get_host_buffer_type , 6823/* .buffer_from_host_ptr = */ ggml_backend_sycl_device_buffer_from_host_ptr , 6824/* .supports_op = */ ggml_backend_sycl_device_supports_op , 6825/* .supports_buft = */ ggml_backend_sycl_device_supports_buft , 6826/* .offload_op = */ ggml_backend_sycl_device_offload_op , 6827/* .event_new = */ ggml_backend_sycl_device_event_new , 6828/* .event_free = */ ggml_backend_sycl_device_event_free , 6829/* .event_synchronize = */ ggml_backend_sycl_device_event_synchronize , 6830}; 6831 6832// backend reg 6833 6834struct ggml_backend_sycl_reg_context { 6835 std::vector < ggml_backend_dev_t > devices ; 6836}; 6837 6838static const char * ggml_backend_sycl_reg_get_name (ggml_backend_reg_t reg ) { 6839GGML_UNUSED (reg ); 6840return GGML_SYCL_NAME ; 6841} 6842 6843static size_t ggml_backend_sycl_reg_get_device_count (ggml_backend_reg_t reg ) { 6844ggml_backend_sycl_reg_context * ctx = (ggml_backend_sycl_reg_context * )reg -> context ; 6845return ctx -> devices .size (); 6846} 6847 6848static ggml_backend_dev_t ggml_backend_sycl_reg_get_device (ggml_backend_reg_t reg ,size_t index ) { 6849ggml_backend_sycl_reg_context * ctx = (ggml_backend_sycl_reg_context * )reg -> context ; 6850GGML_ASSERT (index < ctx -> devices .size ()); 6851return ctx -> devices [index ]; 6852} 6853 6854// ========================================================================== 6855// Tensor parallelism (--split-mode tensor) for the SYCL backend. 6856// 6857// The meta-backend invokes these three entry points via get_proc_address: 6858// * ggml_backend_sycl_comm_init - one-time per-graph setup 6859// * ggml_backend_sycl_comm_allreduce_tensor - per-allreduce step 6860// * ggml_backend_sycl_comm_free - tear-down 6861// 6862// For N=2 (dual-GPU), this is a degenerate ring allreduce with dual paths 6863// chosen by tensor size: 6864// 6865// * Small (nelem < 32K): FP32 direct memcpy + per-device ADD 6866// kernel. The kernel depends_on() its corresponding memcpy event 6867// so it doesn't read partial data. Both devices run in parallel. 6868// 6869// * Large (nelem >= 32K): BF16-compressed. Each device compresses 6870// its FP32 partial to BF16 locally, cross-device memcpys 6871// to the peer (half the PCI bandwidth), where it is decompressed 6872// and added into the local FP32 partial. 6 SYCL submissions per 6873// allreduce (2 compress + 2 memcpy + 2 decompress-add) vs the 6874// 4 for the small path, but the bandwidth saving > 6 GB/s PCIe x 2 6875// dominates for larger tensors. 6876// 6877// Storage: A persistent uint8_t buffer per device, sized to 6878// 4 * nelem bytes. Both paths reinterpret the same bytes (small path 6879// as nelem floats; large path as outbox + inbox = 2*nelem uint16_t 6880// each, using the full 4*nelem byte budget either way). Single 6881// alloc+free per device keeps the SYCL pool's strict-LIFO invariant 6882// trivial. 6883// 6884// For non-(N=2 FP32 contiguous) cases, comm_init or comm_allreduce_tensor 6885// returns null/false, causing the meta-backend to use its generic 6886// butterfly all-reduce fallback. 6887// ========================================================================== 6888 6889struct ggml_backend_sycl_comm_context { 6890 std::vector < ggml_backend_t > backends ; 6891// ONE persistent per-device byte buffer, 4*nelem bytes. Both the 6892// FP32 small-tensor path and the BF16 large-tensor path share it 6893// by reinterpreting. 6894 std::unique_ptr < ggml_sycl_pool_alloc < uint8_t >> buf0 ; 6895 std::unique_ptr < ggml_sycl_pool_alloc < uint8_t >> buf1 ; 6896int64_t buf_nelem = 0 ; 6897}; 6898 6899void * ggml_backend_sycl_comm_init (ggml_backend_t * backends ,size_t n_backends )try { 6900for (size_t i = 0 ;i < n_backends ;++ i ) { 6901if (!ggml_backend_is_sycl (backends [i ])) { 6902return nullptr ; 6903 } 6904 } 6905 6906// Initial version: N=2 only. For N!=2, returning null makes the 6907// meta-backend skip this backend-specific allreduce entirely. 6908if (n_backends != 2 ) { 6909return nullptr ; 6910 } 6911 6912auto * ctx = new ggml_backend_sycl_comm_context ; 6913ctx -> backends .assign (backends ,backends + n_backends ); 6914auto * sctx0 = (ggml_backend_sycl_context * )backends [0 ]-> context ; 6915auto * sctx1 = (ggml_backend_sycl_context * )backends [1 ]-> context ; 6916ctx -> buf0 = std::make_unique < ggml_sycl_pool_alloc < uint8_t >> (sctx0 -> pool ()); 6917ctx -> buf1 = std::make_unique < ggml_sycl_pool_alloc < uint8_t >> (sctx1 -> pool ()); 6918return ctx ; 6919} 6920catch (const sycl::exception & ) {return nullptr ; } 6921catch (...) {return nullptr ; } 6922 6923void ggml_backend_sycl_comm_free (void * comm_ctx_v ) { 6924auto * comm_ctx = static_cast < ggml_backend_sycl_comm_context *> (comm_ctx_v ); 6925if (comm_ctx == nullptr ) { 6926return ; 6927 } 6928 6929// Sync both per-device queues so the pool_alloc destructors don't 6930// return memory still in use by the last kernel. 6931if (comm_ctx -> backends .size ()== 2 ) { 6932auto * sctx0 = (ggml_backend_sycl_context * )comm_ctx -> backends [0 ]-> context ; 6933auto * sctx1 = (ggml_backend_sycl_context * )comm_ctx -> backends [1 ]-> context ; 6934try { 6935sctx0 -> stream ()-> wait (); 6936sctx1 -> stream ()-> wait (); 6937 }catch (...) {/* best effort during shutdown */ } 6938 } 6939 6940delete comm_ctx ; 6941} 6942 6943bool ggml_backend_sycl_comm_allreduce_tensor (void * comm_ctx_v ,struct ggml_tensor ** tensors )try { 6944if (comm_ctx_v == nullptr ) { 6945return false; 6946 } 6947 6948auto * comm_ctx = static_cast < ggml_backend_sycl_comm_context *> (comm_ctx_v ); 6949const size_t n_backends = comm_ctx -> backends .size (); 6950 6951// Fast path: N=2, F32/F16, contiguous, matching shapes. 6952if (n_backends != 2 ) { 6953return false; 6954 } 6955// Accept F32 or F16 inputs natively (types must match). F16 takes the 6956// direct 2-byte memcpy + add path below; other types return false so the 6957// meta-backend uses its generic all-reduce. 6958if (tensors [0 ]-> type != tensors [1 ]-> type ) { 6959return false; 6960 } 6961if (tensors [0 ]-> type != GGML_TYPE_F32 && tensors [0 ]-> type != GGML_TYPE_F16 ) { 6962return false; 6963 } 6964if (!ggml_is_contiguous (tensors [0 ])|| !ggml_is_contiguous (tensors [1 ])) { 6965return false; 6966 } 6967if (ggml_nelements (tensors [0 ])!= ggml_nelements (tensors [1 ])) { 6968return false; 6969 } 6970 6971const int64_t nelem = ggml_nelements (tensors [0 ]); 6972const size_t nbytes = ggml_nbytes (tensors [0 ]); 6973if (nelem == 0 ) { 6974return true; 6975 } 6976 6977auto * ctx0 = (ggml_backend_sycl_context * )comm_ctx -> backends [0 ]-> context ; 6978auto * ctx1 = (ggml_backend_sycl_context * )comm_ctx -> backends [1 ]-> context ; 6979queue_ptr q0 = ctx0 -> stream (); 6980queue_ptr q1 = ctx1 -> stream (); 6981 6982// Grow per-device byte buffers if needed (4 * nelem bytes each). 6983if (comm_ctx -> buf_nelem < nelem ) { 6984comm_ctx -> buf0 -> realloc (nelem * 4 ); 6985comm_ctx -> buf1 -> realloc (nelem * 4 ); 6986comm_ctx -> buf_nelem = nelem ; 6987 } 6988uint8_t * buf0 = comm_ctx -> buf0 -> get (); 6989uint8_t * buf1 = comm_ctx -> buf1 -> get (); 6990 6991// F16 native path: direct 2-byte cross-device copy + add, skipping the 6992// F32 round-trip the meta-backend fallback would force. Cross-device copies 6993// go through dev2dev_memcpy because the two devices are in separate SYCL 6994// contexts (a raw peer-USM q->memcpy would be a silent no-op). 6995if (tensors [0 ]-> type == GGML_TYPE_F16 ) { 6996 sycl::half * f16_out0 = (sycl::half * )tensors [0 ]-> data ; 6997 sycl::half * f16_out1 = (sycl::half * )tensors [1 ]-> data ; 6998 sycl::half * f16_tmp0 = (sycl::half * )buf0 ; 6999 sycl::half * f16_tmp1 = (sycl::half * )buf1 ; 7000 7001q0 -> wait (); 7002q1 -> wait (); 7003dev2dev_memcpy (ctx0 -> device ,* q0 ,ctx1 -> device ,* q1 ,f16_tmp0 ,tensors [1 ]-> data ,nbytes ); 7004dev2dev_memcpy (ctx1 -> device ,* q1 ,ctx0 -> device ,* q0 ,f16_tmp1 ,tensors [0 ]-> data ,nbytes ); 7005 7006q0 -> submit ([& ](sycl::handler & h ) { 7007h .parallel_for (sycl::range < 1 > (nelem ), [= ](sycl::id < 1 > i ) { 7008f16_out0 [i ]= (sycl::half ) ((float )f16_out0 [i ]+ (float )f16_tmp0 [i ]); 7009 }); 7010 }); 7011q1 -> submit ([& ](sycl::handler & h ) { 7012h .parallel_for (sycl::range < 1 > (nelem ), [= ](sycl::id < 1 > i ) { 7013f16_out1 [i ]= (sycl::half ) ((float )f16_out1 [i ]+ (float )f16_tmp1 [i ]); 7014 }); 7015 }); 7016return true; 7017 } 7018 7019float * out0 = (float * )tensors [0 ]-> data ; 7020float * out1 = (float * )tensors [1 ]-> data ; 7021 7022// BF16 threshold: above this, the PCIe savings from halving the 7023// cross-device bytes outweigh the 2 extra compress kernels. 7024// Below: stay on the FP32 fast path. Threshold mirrors the CUDA 7025// NCCL allreduce pattern for n_backends=2. 7026static constexpr int64_t BF16_THRESHOLD = 32768 ; 7027 7028if (nelem < BF16_THRESHOLD ) { 7029// FP32 small path: 4 SYCL submissions per allreduce. 7030float * tmp0 = (float * )buf0 ; 7031float * tmp1 = (float * )buf1 ; 7032 7033// COMM-D2D-FIX: the two devices are in SEPARATE SYCL contexts, so a raw 7034// q->memcpy of a peer USM pointer is a silent no-op. Route cross-device 7035// copies through dev2dev_memcpy (L0 direct copy / host staging). It is 7036// synchronous, so wait for the local partials to be produced first. 7037q0 -> wait (); 7038q1 -> wait (); 7039dev2dev_memcpy (ctx0 -> device ,* q0 ,ctx1 -> device ,* q1 ,tmp0 ,tensors [1 ]-> data ,nbytes ); 7040dev2dev_memcpy (ctx1 -> device ,* q1 ,ctx0 -> device ,* q0 ,tmp1 ,tensors [0 ]-> data ,nbytes ); 7041 7042q0 -> submit ([& ](sycl::handler & h ) { 7043h .parallel_for (sycl::range < 1 > (nelem ), [= ](sycl::id < 1 > i ) { 7044out0 [i ]+= tmp0 [i ]; 7045 }); 7046 }); 7047q1 -> submit ([& ](sycl::handler & h ) { 7048h .parallel_for (sycl::range < 1 > (nelem ), [= ](sycl::id < 1 > i ) { 7049out1 [i ]+= tmp1 [i ]; 7050 }); 7051 }); 7052return true; 7053 } 7054 7055// BF16 large path: 6 SYCL submissions per allreduce, but the 7056// cross-device memcpy is HALF the bytes. Pure bit-shift 7057// conversion (no rounding) — matches ggml's truncating fp32->bf16. 7058uint16_t * outbox0 = (uint16_t * )buf0 ; 7059uint16_t * inbox0 = outbox0 + nelem ; 7060uint16_t * outbox1 = (uint16_t * )buf1 ; 7061uint16_t * inbox1 = outbox1 + nelem ; 7062 7063// Phase A: compress each device's local partial in parallel. 7064 sycl::event c0 = q0 -> parallel_for (sycl::range < 1 > (nelem ), [= ](sycl::id < 1 > i ) { 7065outbox0 [i ]= (uint16_t ) (sycl::bit_cast < uint32_t > (out0 [i ]) >>16 ); 7066 }); 7067 7068 sycl::event c1 = q1 -> parallel_for (sycl::range < 1 > (nelem ), [= ](sycl::id < 1 > i ) { 7069outbox1 [i ]= (uint16_t ) (sycl::bit_cast < uint32_t > (out1 [i ]) >>16 ); 7070 }); 7071 7072// Phase B: COMM-D2D-FIX-BF16 cross-device copy of compressed bytes via 7073// dev2dev_memcpy (separate SYCL contexts; sync copy after compress). 7074const size_t bf16_bytes = nelem * sizeof (uint16_t ); 7075c0 .wait (); 7076c1 .wait (); 7077dev2dev_memcpy (ctx0 -> device ,* q0 ,ctx1 -> device ,* q1 ,inbox0 ,outbox1 ,bf16_bytes ); 7078dev2dev_memcpy (ctx1 -> device ,* q1 ,ctx0 -> device ,* q0 ,inbox1 ,outbox0 ,bf16_bytes ); 7079 7080// Phase C: decompress + add into local FP32 partial. 7081q0 -> submit ([& ](sycl::handler & h ) { 7082h .parallel_for (sycl::range < 1 > (nelem ), [= ](sycl::id < 1 > i ) { 7083out0 [i ]+= sycl::bit_cast < float > (((uint32_t )inbox0 [i ]) <<16 ); 7084 }); 7085 }); 7086 7087q1 -> submit ([& ](sycl::handler & h ) { 7088h .parallel_for (sycl::range < 1 > (nelem ), [= ](sycl::id < 1 > i ) { 7089out1 [i ]+= sycl::bit_cast < float > (((uint32_t )inbox1 [i ]) <<16 ); 7090 }); 7091 }); 7092 7093return true; 7094} 7095catch (const sycl::exception & ) {return false; } 7096catch (...) {return false; } 7097 7098static void * ggml_backend_sycl_reg_get_proc_address (ggml_backend_reg_t reg ,const char * name ) { 7099GGML_UNUSED (reg ); 7100 7101if (strcmp (name ,"ggml_backend_split_buffer_type" )== 0 ) { 7102return (void * )ggml_backend_sycl_split_buffer_type ; 7103 } 7104 7105// Tensor parallelism (--split-mode tensor) entry points. 7106if (strcmp (name ,"ggml_backend_comm_init" )== 0 ) { 7107return (void * )ggml_backend_sycl_comm_init ; 7108 } 7109if (strcmp (name ,"ggml_backend_comm_free" )== 0 ) { 7110return (void * )ggml_backend_sycl_comm_free ; 7111 } 7112if (strcmp (name ,"ggml_backend_comm_allreduce_tensor" )== 0 ) { 7113return (void * )ggml_backend_sycl_comm_allreduce_tensor ; 7114 } 7115 7116// SYCL doesn't support registering host memory, left here for reference 7117// "ggml_backend_register_host_buffer" 7118// "ggml_backend_unregister_host_buffer" 7119GGML_UNUSED (name ); 7120return nullptr ; 7121} 7122 7123static const ggml_backend_reg_i ggml_backend_sycl_reg_interface = { 7124/* .get_name = */ ggml_backend_sycl_reg_get_name , 7125/* .get_device_count = */ ggml_backend_sycl_reg_get_device_count , 7126/* .get_device = */ ggml_backend_sycl_reg_get_device , 7127/* .get_proc_address = */ ggml_backend_sycl_reg_get_proc_address , 7128}; 7129 7130 7131// backend registry 7132 7133ggml_backend_reg_t ggml_backend_sycl_reg () { 7134GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_reg\n" ); 7135static ggml_backend_reg reg ; 7136static bool initialized = false; 7137 7138 { 7139static std::mutex mutex ; 7140 std::lock_guard < std::mutex > lock (mutex ); 7141if (!initialized ) { 7142ggml_check_sycl (); 7143ggml_backend_sycl_reg_context * ctx = new ggml_backend_sycl_reg_context ; 7144const int min_batch_size = getenv ("GGML_OP_OFFLOAD_MIN_BATCH" ) ?atoi (getenv ("GGML_OP_OFFLOAD_MIN_BATCH" )) :32 ; 7145 7146for (int i = 0 ;i < ggml_sycl_info ().device_count ;i ++ ) { 7147ggml_backend_sycl_device_context * dev_ctx = new ggml_backend_sycl_device_context ; 7148dev_ctx -> device = i ; 7149dev_ctx -> name = GGML_SYCL_NAME + std::to_string (i ); 7150 7151ggml_sycl_set_device (i ); 7152 7153 dpct::device_info prop ; 7154SYCL_CHECK (CHECK_TRY_ERROR (dpct::get_device_info ( 7155prop , dpct::dev_mgr::instance ().get_device (i )))); 7156 7157dev_ctx -> description = prop .get_name (); 7158dev_ctx -> op_offload_min_batch_size = min_batch_size ; 7159 7160ggml_backend_dev_t dev = new ggml_backend_device { 7161/* .iface = */ ggml_backend_sycl_device_interface , 7162/* .reg = */ & reg , 7163/* .context = */ dev_ctx 7164 }; 7165ctx -> devices .push_back (dev ); 7166 } 7167 7168reg = ggml_backend_reg { 7169/* .api_version = */ GGML_BACKEND_API_VERSION , 7170/* .iface = */ ggml_backend_sycl_reg_interface , 7171/* .context = */ ctx 7172 }; 7173 } 7174 7175initialized = true; 7176 } 7177 7178return & reg ; 7179} 7180 7181ggml_backend_t ggml_backend_sycl_init (int device ) { 7182GGML_SYCL_DEBUG ("[SYCL] call ggml_backend_sycl_init\n" ); 7183ggml_check_sycl (); 7184 7185check_allow_gpu_index (device ); 7186 7187ggml_backend_sycl_context * ctx = new ggml_backend_sycl_context (device ); 7188if (ctx == nullptr ) { 7189GGML_LOG_ERROR ("%s: error: failed to allocate context\n" ,__func__ ); 7190return nullptr ; 7191 }; 7192 7193ggml_backend_t sycl_backend = new ggml_backend { 7194/* .guid = */ ggml_backend_sycl_guid (), 7195/* .iface = */ ggml_backend_sycl_interface , 7196/* .device = */ ggml_backend_reg_dev_get (ggml_backend_sycl_reg (),device ), 7197/* .context = */ ctx 7198 }; 7199 7200return sycl_backend ; 7201} 7202 7203GGML_BACKEND_DL_IMPL (ggml_backend_sycl_reg )