okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

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