interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-sycl / ggml-sycl.cpp

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