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 "common.hpp"
14
15#include "ggml-backend-impl.h"
16#include "ggml-impl.h"
17
18int get_current_device_id() {
19 return dpct::dev_mgr::instance().current_device_id();
20}
21
22void* ggml_sycl_host_malloc(size_t size) try {
23 if (getenv("GGML_SYCL_NO_PINNED") != nullptr) {
24 return nullptr;
25 }
26
27 void* ptr = nullptr;
28 // allow to use dpct::get_in_order_queue() for host malloc
29 dpct::err0 err = CHECK_TRY_ERROR(
30 ptr = (void*)sycl::malloc_host(size, dpct::get_in_order_queue()));
31
32 if (err != 0) {
33 // clear the error
34 GGML_LOG_ERROR("WARNING: failed to allocate %.2f MB of pinned memory: %s\n", size / 1024.0 / 1024.0, "syclGetErrorString is not supported");
35 return nullptr;
36 }
37
38 return ptr;
39} catch (sycl::exception const& exc) {
40 std::cerr << exc.what() << "Exception caught at file:" << __FILE__
41 << ", line:" << __LINE__ << std::endl;
42 std::exit(1);
43}
44
45void ggml_sycl_host_free(void* ptr) try {
46 // allow to use dpct::get_in_order_queue() for host malloc
47 SYCL_CHECK(CHECK_TRY_ERROR(sycl::free(ptr, dpct::get_in_order_queue())));
48} catch (sycl::exception const& exc) {
49 std::cerr << exc.what() << "Exception caught at file:" << __FILE__
50 << ", line:" << __LINE__ << std::endl;
51 std::exit(1);
52}
53
54bool gpu_has_xmx(sycl::device &dev) {
55 return dev.has(sycl::aspect::ext_intel_matrix);
56}
57
58int64_t downsample_sycl_global_range(int64_t accumulate_block_num, int64_t block_size) {
59 const int64_t max_range = std::numeric_limits<int>::max();
60 int64_t sycl_down_blk_size = block_size;
61 int64_t global_range = accumulate_block_num * sycl_down_blk_size;
62 while(global_range > max_range) {
63 sycl_down_blk_size /= 2;
64 global_range = accumulate_block_num * sycl_down_blk_size;
65 }
66 return sycl_down_blk_size;
67}
68
69void release_extra_gpu(ggml_tensor_extra_gpu * extra, std::vector<queue_ptr> streams) {
70 for (int i = 0; i < ggml_sycl_info().device_count; ++i) {
71 for (int64_t is = 0; is < GGML_SYCL_MAX_STREAMS; ++is) {
72 if (extra->events[i][is] != nullptr) {
73 SYCL_CHECK(CHECK_TRY_ERROR(dpct::destroy_event(extra->events[i][is])));
74 }
75 }
76 if (extra->data_device[i] != nullptr && streams.size()>0) {
77 ggml_sycl_set_device(i);
78 SYCL_CHECK(
79 CHECK_TRY_ERROR(sycl::free(extra->data_device[i], *(streams[i]))));
80 }
81 }
82 delete extra;
83}