whispercpp 1.3.0 → 1.3.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (132) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +5 -0
  3. data/LICENSE +1 -1
  4. data/README.md +165 -434
  5. data/Rakefile +60 -11
  6. data/ext/.gitignore +13 -0
  7. data/ext/cpu.mk +9 -0
  8. data/ext/{dr_wav.h → examples/dr_wav.h} +3560 -1179
  9. data/ext/extconf.rb +185 -16
  10. data/ext/ggml/include/ggml-alloc.h +76 -0
  11. data/ext/ggml/include/ggml-backend.h +352 -0
  12. data/ext/ggml/include/ggml-blas.h +25 -0
  13. data/ext/ggml/include/ggml-cann.h +123 -0
  14. data/ext/ggml/include/ggml-cpp.h +38 -0
  15. data/ext/ggml/include/ggml-cpu.h +135 -0
  16. data/ext/ggml/include/ggml-cuda.h +47 -0
  17. data/ext/ggml/include/ggml-kompute.h +50 -0
  18. data/ext/ggml/include/ggml-metal.h +66 -0
  19. data/ext/ggml/include/ggml-opencl.h +26 -0
  20. data/ext/ggml/include/ggml-opt.h +216 -0
  21. data/ext/ggml/include/ggml-rpc.h +28 -0
  22. data/ext/ggml/include/ggml-sycl.h +49 -0
  23. data/ext/ggml/include/ggml-vulkan.h +31 -0
  24. data/ext/{ggml.h → ggml/include/ggml.h} +479 -596
  25. data/ext/ggml/src/ggml-alloc.c +1037 -0
  26. data/ext/ggml/src/ggml-amx/common.h +94 -0
  27. data/ext/ggml/src/ggml-amx/ggml-amx.cpp +446 -0
  28. data/ext/ggml/src/ggml-amx/mmq.cpp +2510 -0
  29. data/ext/ggml/src/ggml-amx/mmq.h +17 -0
  30. data/ext/ggml/src/ggml-backend-impl.h +256 -0
  31. data/ext/ggml/src/ggml-backend-reg.cpp +552 -0
  32. data/ext/ggml/src/ggml-backend.cpp +1999 -0
  33. data/ext/ggml/src/ggml-blas/ggml-blas.cpp +517 -0
  34. data/ext/ggml/src/ggml-cann/acl_tensor.cpp +175 -0
  35. data/ext/ggml/src/ggml-cann/acl_tensor.h +258 -0
  36. data/ext/ggml/src/ggml-cann/aclnn_ops.cpp +3427 -0
  37. data/ext/ggml/src/ggml-cann/aclnn_ops.h +592 -0
  38. data/ext/ggml/src/ggml-cann/common.h +286 -0
  39. data/ext/ggml/src/ggml-cann/ggml-cann.cpp +2188 -0
  40. data/ext/ggml/src/ggml-cann/kernels/ascendc_kernels.h +19 -0
  41. data/ext/ggml/src/ggml-cann/kernels/dup.cpp +236 -0
  42. data/ext/ggml/src/ggml-cann/kernels/get_row_f16.cpp +197 -0
  43. data/ext/ggml/src/ggml-cann/kernels/get_row_f32.cpp +190 -0
  44. data/ext/ggml/src/ggml-cann/kernels/get_row_q4_0.cpp +204 -0
  45. data/ext/ggml/src/ggml-cann/kernels/get_row_q8_0.cpp +191 -0
  46. data/ext/ggml/src/ggml-cann/kernels/quantize_f16_q8_0.cpp +218 -0
  47. data/ext/ggml/src/ggml-cann/kernels/quantize_f32_q8_0.cpp +216 -0
  48. data/ext/ggml/src/ggml-cann/kernels/quantize_float_to_q4_0.cpp +295 -0
  49. data/ext/ggml/src/ggml-common.h +1853 -0
  50. data/ext/ggml/src/ggml-cpu/amx/amx.cpp +220 -0
  51. data/ext/ggml/src/ggml-cpu/amx/amx.h +8 -0
  52. data/ext/ggml/src/ggml-cpu/amx/common.h +91 -0
  53. data/ext/ggml/src/ggml-cpu/amx/mmq.cpp +2511 -0
  54. data/ext/ggml/src/ggml-cpu/amx/mmq.h +10 -0
  55. data/ext/ggml/src/ggml-cpu/cpu-feats-x86.cpp +323 -0
  56. data/ext/ggml/src/ggml-cpu/ggml-cpu-aarch64.cpp +4262 -0
  57. data/ext/ggml/src/ggml-cpu/ggml-cpu-aarch64.h +8 -0
  58. data/ext/ggml/src/ggml-cpu/ggml-cpu-hbm.cpp +55 -0
  59. data/ext/ggml/src/ggml-cpu/ggml-cpu-hbm.h +8 -0
  60. data/ext/ggml/src/ggml-cpu/ggml-cpu-impl.h +386 -0
  61. data/ext/ggml/src/ggml-cpu/ggml-cpu-quants.c +10835 -0
  62. data/ext/ggml/src/ggml-cpu/ggml-cpu-quants.h +63 -0
  63. data/ext/ggml/src/ggml-cpu/ggml-cpu-traits.cpp +36 -0
  64. data/ext/ggml/src/ggml-cpu/ggml-cpu-traits.h +38 -0
  65. data/ext/ggml/src/ggml-cpu/ggml-cpu.c +14123 -0
  66. data/ext/ggml/src/ggml-cpu/ggml-cpu.cpp +622 -0
  67. data/ext/ggml/src/ggml-cpu/llamafile/sgemm.cpp +1884 -0
  68. data/ext/ggml/src/ggml-cpu/llamafile/sgemm.h +14 -0
  69. data/ext/ggml/src/ggml-cuda/vendors/cuda.h +14 -0
  70. data/ext/ggml/src/ggml-cuda/vendors/hip.h +186 -0
  71. data/ext/ggml/src/ggml-cuda/vendors/musa.h +134 -0
  72. data/ext/ggml/src/ggml-impl.h +556 -0
  73. data/ext/ggml/src/ggml-kompute/ggml-kompute.cpp +2251 -0
  74. data/ext/ggml/src/ggml-metal/ggml-metal-impl.h +288 -0
  75. data/ext/ggml/src/ggml-metal/ggml-metal.m +4884 -0
  76. data/ext/ggml/src/ggml-metal/ggml-metal.metal +6732 -0
  77. data/ext/ggml/src/ggml-opt.cpp +854 -0
  78. data/ext/ggml/src/ggml-quants.c +5238 -0
  79. data/ext/ggml/src/ggml-quants.h +100 -0
  80. data/ext/ggml/src/ggml-rpc/ggml-rpc.cpp +1406 -0
  81. data/ext/ggml/src/ggml-sycl/common.cpp +95 -0
  82. data/ext/ggml/src/ggml-sycl/concat.cpp +196 -0
  83. data/ext/ggml/src/ggml-sycl/conv.cpp +99 -0
  84. data/ext/ggml/src/ggml-sycl/convert.cpp +547 -0
  85. data/ext/ggml/src/ggml-sycl/dmmv.cpp +1023 -0
  86. data/ext/ggml/src/ggml-sycl/element_wise.cpp +1030 -0
  87. data/ext/ggml/src/ggml-sycl/ggml-sycl.cpp +4729 -0
  88. data/ext/ggml/src/ggml-sycl/im2col.cpp +126 -0
  89. data/ext/ggml/src/ggml-sycl/mmq.cpp +3031 -0
  90. data/ext/ggml/src/ggml-sycl/mmvq.cpp +1015 -0
  91. data/ext/ggml/src/ggml-sycl/norm.cpp +378 -0
  92. data/ext/ggml/src/ggml-sycl/outprod.cpp +56 -0
  93. data/ext/ggml/src/ggml-sycl/rope.cpp +276 -0
  94. data/ext/ggml/src/ggml-sycl/softmax.cpp +251 -0
  95. data/ext/ggml/src/ggml-sycl/tsembd.cpp +72 -0
  96. data/ext/ggml/src/ggml-sycl/wkv6.cpp +141 -0
  97. data/ext/ggml/src/ggml-threading.cpp +12 -0
  98. data/ext/ggml/src/ggml-threading.h +14 -0
  99. data/ext/ggml/src/ggml-vulkan/ggml-vulkan.cpp +8657 -0
  100. data/ext/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +593 -0
  101. data/ext/ggml/src/ggml.c +7694 -0
  102. data/ext/{whisper.h → include/whisper.h} +23 -22
  103. data/ext/metal-embed.mk +17 -0
  104. data/ext/metal.mk +6 -0
  105. data/ext/ruby_whisper.cpp +1492 -9
  106. data/ext/ruby_whisper.h +10 -0
  107. data/ext/scripts/get-flags.mk +38 -0
  108. data/ext/src/coreml/whisper-decoder-impl.h +146 -0
  109. data/ext/src/coreml/whisper-decoder-impl.m +201 -0
  110. data/ext/src/coreml/whisper-encoder-impl.h +142 -0
  111. data/ext/src/coreml/whisper-encoder-impl.m +197 -0
  112. data/ext/src/coreml/whisper-encoder.h +26 -0
  113. data/ext/src/openvino/whisper-openvino-encoder.cpp +108 -0
  114. data/ext/src/openvino/whisper-openvino-encoder.h +31 -0
  115. data/ext/{whisper.cpp → src/whisper.cpp} +661 -492
  116. data/extsources.rb +6 -0
  117. data/lib/whisper/model/uri.rb +157 -0
  118. data/lib/whisper.rb +2 -0
  119. data/tests/helper.rb +7 -0
  120. data/tests/jfk_reader/.gitignore +5 -0
  121. data/tests/jfk_reader/extconf.rb +3 -0
  122. data/tests/jfk_reader/jfk_reader.c +68 -0
  123. data/tests/test_callback.rb +160 -0
  124. data/tests/test_error.rb +20 -0
  125. data/tests/test_model.rb +71 -0
  126. data/tests/test_package.rb +31 -0
  127. data/tests/test_params.rb +160 -0
  128. data/tests/test_segment.rb +83 -0
  129. data/tests/test_whisper.rb +211 -123
  130. data/whispercpp.gemspec +36 -0
  131. metadata +137 -11
  132. data/ext/ggml.c +0 -21755
@@ -0,0 +1,2251 @@
1
+ #include "ggml-impl.h"
2
+ #include "ggml-backend.h"
3
+ #include "ggml-backend-impl.h"
4
+ #include "ggml-kompute.h"
5
+
6
+ // These are generated at build time by cmake custom command
7
+ #include "shaderop_scale.h"
8
+ #include "shaderop_scale_8.h"
9
+ #include "shaderop_add.h"
10
+ #include "shaderop_addrow.h"
11
+ #include "shaderop_mul.h"
12
+ #include "shaderop_silu.h"
13
+ #include "shaderop_relu.h"
14
+ #include "shaderop_gelu.h"
15
+ #include "shaderop_softmax.h"
16
+ #include "shaderop_norm.h"
17
+ #include "shaderop_rmsnorm.h"
18
+ #include "shaderop_diagmask.h"
19
+ #include "shaderop_mul_mat_f16.h"
20
+ #include "shaderop_mul_mat_q8_0.h"
21
+ #include "shaderop_mul_mat_q4_0.h"
22
+ #include "shaderop_mul_mat_q4_1.h"
23
+ #include "shaderop_mul_mat_q4_k.h"
24
+ #include "shaderop_mul_mat_q6_k.h"
25
+ #include "shaderop_mul_mat_mat_f32.h"
26
+ #include "shaderop_getrows_f32.h"
27
+ #include "shaderop_getrows_f16.h"
28
+ #include "shaderop_getrows_q4_0.h"
29
+ #include "shaderop_getrows_q4_1.h"
30
+ #include "shaderop_getrows_q6_k.h"
31
+ #include "shaderop_rope_norm_f16.h"
32
+ #include "shaderop_rope_norm_f32.h"
33
+ #include "shaderop_rope_neox_f16.h"
34
+ #include "shaderop_rope_neox_f32.h"
35
+ #include "shaderop_cpy_f16_f16.h"
36
+ #include "shaderop_cpy_f16_f32.h"
37
+ #include "shaderop_cpy_f32_f16.h"
38
+ #include "shaderop_cpy_f32_f32.h"
39
+
40
+ #include <algorithm>
41
+ #include <array>
42
+ #include <cassert>
43
+ #include <cstdint>
44
+ #include <cstdio>
45
+ #include <cstring>
46
+ #include <iostream>
47
+ #include <memory>
48
+ #include <mutex>
49
+ #include <stdexcept>
50
+ #include <string>
51
+ #include <unordered_map>
52
+ #include <utility>
53
+ #include <vector>
54
+
55
+ #include <kompute/Kompute.hpp>
56
+ #include <vulkan/vulkan.hpp>
57
+
58
+ #ifdef __linux__
59
+ #include <cstdlib> // for setenv
60
+ #endif
61
+
62
+ #define QK4_0 32
63
+ #define QR4_0 2
64
+ #define QK4_1 32
65
+ #define QK_NL 16
66
+
67
+ typedef ggml_fp16_t half;
68
+
69
+ static std::string ggml_kompute_format_name(int device) {
70
+ return "Kompute" + std::to_string(device);
71
+ }
72
+
73
+ struct ggml_kompute_context {
74
+ int device;
75
+ std::string name;
76
+ std::shared_ptr<vk::DescriptorPool> pool;
77
+
78
+ ggml_kompute_context(int device)
79
+ : device(device), name(ggml_kompute_format_name(device)) {}
80
+ };
81
+
82
+ // FIXME: It would be good to consolidate the kompute manager and the kompute context into one object
83
+ // and consolidate the init functions and simplify object lifetime management. As it currently stands,
84
+ // we *have* to have the kompute manager no matter what for device discovery, but the kompute context
85
+ // is only created when a device is set and vulkan is explicitly turned on.
86
+ static ggml_kompute_context *s_kompute_context = nullptr;
87
+
88
+ class kompute_manager {
89
+ kp::Manager *s_mgr = nullptr;
90
+
91
+ public:
92
+ kp::Manager *operator()() {
93
+ if (s_mgr && !s_mgr->hasInstance()) {
94
+ destroy();
95
+ }
96
+ if (!s_mgr) {
97
+ s_mgr = new kp::Manager;
98
+ }
99
+ return s_mgr;
100
+ }
101
+
102
+ void destroy() {
103
+ delete s_mgr;
104
+ s_mgr = nullptr;
105
+ }
106
+ };
107
+
108
+ static kompute_manager komputeManager;
109
+
110
+ struct ggml_vk_memory {
111
+ void *data = nullptr;
112
+ size_t size = 0;
113
+ vk::DeviceMemory *primaryMemory = nullptr;
114
+ vk::Buffer *primaryBuffer = nullptr;
115
+ vk::DeviceMemory *stagingMemory = nullptr;
116
+ vk::Buffer *stagingBuffer = nullptr;
117
+ };
118
+
119
+ #ifdef __linux__
120
+ __attribute__((constructor))
121
+ static void enable_sam() {
122
+ setenv("RADV_PERFTEST", "sam", false);
123
+ }
124
+ #endif
125
+
126
+ static bool ggml_vk_checkPhysicalDeviceFeatures(vk::PhysicalDevice physical_device) {
127
+ vk::PhysicalDeviceFeatures availableFeatures;
128
+ physical_device.getFeatures(&availableFeatures);
129
+
130
+ if (!availableFeatures.shaderInt16)
131
+ return false;
132
+
133
+ vk::PhysicalDeviceVulkan11Features availableFeatures11;
134
+ vk::PhysicalDeviceVulkan12Features availableFeatures12;
135
+
136
+ availableFeatures11.pNext = &availableFeatures12;
137
+ availableFeatures12.pNext = nullptr;
138
+
139
+ vk::PhysicalDeviceFeatures2 features2;
140
+ features2.pNext = &availableFeatures11;
141
+
142
+ physical_device.getFeatures2(&features2);
143
+
144
+ if (!availableFeatures11.uniformAndStorageBuffer16BitAccess ||
145
+ !availableFeatures11.storageBuffer16BitAccess) {
146
+ return false;
147
+ }
148
+
149
+ if (!availableFeatures12.storageBuffer8BitAccess ||
150
+ !availableFeatures12.uniformAndStorageBuffer8BitAccess ||
151
+ !availableFeatures12.shaderFloat16 ||
152
+ !availableFeatures12.shaderInt8) {
153
+ return false;
154
+ }
155
+
156
+ return true;
157
+ }
158
+
159
+ static const char * ggml_vk_getVendorName(uint32_t vendorID) {
160
+ switch (vendorID) {
161
+ case 0x10DE:
162
+ return "nvidia";
163
+ case 0x1002:
164
+ return "amd";
165
+ case 0x8086:
166
+ return "intel";
167
+ default:
168
+ return "unknown";
169
+ }
170
+ }
171
+
172
+ static std::vector<ggml_vk_device> ggml_vk_available_devices_internal(size_t memoryRequired) {
173
+ std::vector<ggml_vk_device> results;
174
+ if (!komputeManager()->hasVulkan() || !komputeManager()->hasInstance())
175
+ return results;
176
+
177
+ std::vector<vk::PhysicalDevice> physical_devices;
178
+ try {
179
+ physical_devices = komputeManager()->listDevices();
180
+ } catch (vk::SystemError & err) {
181
+ std::cerr << __func__ << ": ignoring Vulkan exception: " << err.what() << "\n";
182
+ return results;
183
+ }
184
+
185
+ uint32_t deviceCount = physical_devices.size();
186
+ if (deviceCount == 0)
187
+ return results;
188
+
189
+ std::unordered_map<std::string, size_t> count_by_name;
190
+
191
+ for (uint32_t i = 0; i < deviceCount; i++) {
192
+ const auto & physical_device = physical_devices[i];
193
+
194
+ VkPhysicalDeviceProperties dev_props = physical_device.getProperties();
195
+ VkPhysicalDeviceMemoryProperties memoryProperties = physical_device.getMemoryProperties();
196
+ const uint32_t major = VK_VERSION_MAJOR(dev_props.apiVersion);
197
+ const uint32_t minor = VK_VERSION_MINOR(dev_props.apiVersion);
198
+ if (major < 1 || minor < 2)
199
+ continue;
200
+
201
+ if (!ggml_vk_checkPhysicalDeviceFeatures(physical_device))
202
+ continue;
203
+
204
+ size_t heapSize = 0;
205
+ for (uint32_t j = 0; j < memoryProperties.memoryHeapCount; ++j) {
206
+ VkMemoryHeap heap = memoryProperties.memoryHeaps[j];
207
+ if (heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
208
+ heapSize = heap.size;
209
+ break;
210
+ }
211
+ }
212
+
213
+ if (heapSize < memoryRequired)
214
+ continue;
215
+
216
+ auto ext_props = physical_device.enumerateDeviceExtensionProperties();
217
+ bool has_maintenance4 = false;
218
+
219
+ // Check if maintenance4 is supported
220
+ for (const auto & properties : ext_props) {
221
+ if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
222
+ has_maintenance4 = true;
223
+ }
224
+ }
225
+
226
+ vk::PhysicalDeviceSubgroupProperties subgroup_props;
227
+ vk::PhysicalDeviceProperties2 dev_props2;
228
+ vk::PhysicalDeviceMaintenance3Properties dev_props3;
229
+ vk::PhysicalDeviceMaintenance4Properties dev_props4;
230
+ dev_props2.pNext = &dev_props3;
231
+ dev_props3.pNext = &subgroup_props;
232
+ if (has_maintenance4) {
233
+ subgroup_props.pNext = &dev_props4;
234
+ }
235
+ physical_device.getProperties2(&dev_props2);
236
+
237
+ if (subgroup_props.subgroupSize < 32)
238
+ continue;
239
+
240
+ ggml_vk_device d;
241
+ d.index = i;
242
+ d.type = dev_props.deviceType;
243
+ d.heapSize = heapSize;
244
+ d.vendor = strdup(ggml_vk_getVendorName(dev_props.vendorID));
245
+ d.subgroupSize = subgroup_props.subgroupSize;
246
+ d.bufferAlignment = dev_props.limits.minStorageBufferOffsetAlignment;
247
+
248
+ if (has_maintenance4) {
249
+ d.maxAlloc = std::min(dev_props3.maxMemoryAllocationSize, dev_props4.maxBufferSize);
250
+ } else {
251
+ d.maxAlloc = dev_props3.maxMemoryAllocationSize;
252
+ }
253
+
254
+ std::string name(dev_props.deviceName);
255
+ size_t n_idx = ++count_by_name[name];
256
+ if (n_idx > 1) {
257
+ name += " (" + std::to_string(n_idx) + ")";
258
+ }
259
+ d.name = strdup(name.c_str());
260
+
261
+ results.push_back(d);
262
+ }
263
+
264
+ std::stable_sort(results.begin(), results.end(),
265
+ [](const ggml_vk_device& lhs, const ggml_vk_device& rhs) -> bool {
266
+ if (lhs.type != rhs.type) {
267
+ if (lhs.type == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) return true;
268
+ if (rhs.type == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) return false;
269
+
270
+ if (lhs.type == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) return true;
271
+ if (rhs.type == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) return false;
272
+ }
273
+ return lhs.heapSize < rhs.heapSize;
274
+ }
275
+ );
276
+
277
+ return results;
278
+ }
279
+
280
+ static std::vector<ggml_vk_device>& ggml_vk_available_devices() {
281
+ static std::vector<ggml_vk_device> devices = ggml_vk_available_devices_internal(0);
282
+ return devices;
283
+ }
284
+
285
+ static void ggml_vk_filterByVendor(std::vector<ggml_vk_device>& devices, const std::string& targetVendor) {
286
+ devices.erase(
287
+ std::remove_if(devices.begin(), devices.end(),
288
+ [&targetVendor](const ggml_vk_device& device) {
289
+ return device.vendor != targetVendor;
290
+ }),
291
+ devices.end()
292
+ );
293
+ }
294
+
295
+ static void ggml_vk_filterByName(std::vector<ggml_vk_device>& devices, const std::string& targetName) {
296
+ devices.erase(
297
+ std::remove_if(devices.begin(), devices.end(),
298
+ [&targetName](const ggml_vk_device& device) {
299
+ return device.name != targetName;
300
+ }),
301
+ devices.end()
302
+ );
303
+ }
304
+
305
+ static bool ggml_vk_get_device(ggml_vk_device * device, size_t memoryRequired, const std::string & name) {
306
+ if (name.empty())
307
+ return false;
308
+
309
+ auto devices = ggml_vk_available_devices_internal(memoryRequired);
310
+ if (name == "amd" || name == "nvidia" || name == "intel") {
311
+ ggml_vk_filterByVendor(devices, name);
312
+ } else if (name != "gpu") {
313
+ ggml_vk_filterByName(devices, name);
314
+ }
315
+
316
+ if (devices.empty())
317
+ return false;
318
+
319
+ *device = devices.front();
320
+ return true;
321
+ }
322
+
323
+ bool ggml_vk_get_device(ggml_vk_device * device, size_t memoryRequired, const char * name) {
324
+ return ggml_vk_get_device(device, memoryRequired, std::string(name));
325
+ }
326
+
327
+ bool ggml_vk_has_vulkan() {
328
+ return komputeManager()->hasVulkan();
329
+ }
330
+
331
+ bool ggml_vk_has_device() {
332
+ return komputeManager()->hasDevice();
333
+ }
334
+
335
+ ggml_vk_device ggml_vk_current_device() {
336
+ if (!komputeManager()->hasDevice())
337
+ return ggml_vk_device();
338
+
339
+ auto devices = ggml_vk_available_devices();
340
+ ggml_vk_filterByName(devices, komputeManager()->physicalDevice()->getProperties().deviceName.data());
341
+ GGML_ASSERT(!devices.empty());
342
+ return devices.front();
343
+ }
344
+
345
+ static
346
+ void ggml_vk_allocate_descriptor_pool(struct ggml_kompute_context * ctx, size_t size) {
347
+ std::vector<vk::DescriptorPoolSize> descriptorPoolSizes = {
348
+ vk::DescriptorPoolSize(
349
+ vk::DescriptorType::eStorageBuffer,
350
+ 4 * size // Descriptor count is number of possible tensors to pass into an algorithm
351
+ )
352
+ };
353
+
354
+ vk::DescriptorPoolCreateInfo descriptorPoolInfo(
355
+ vk::DescriptorPoolCreateFlags(),
356
+ size, // Max sets
357
+ static_cast<uint32_t>(descriptorPoolSizes.size()),
358
+ descriptorPoolSizes.data());
359
+
360
+ ctx->pool = std::make_shared<vk::DescriptorPool>();
361
+ vk::Result r = komputeManager()->device()->createDescriptorPool(
362
+ &descriptorPoolInfo, nullptr, ctx->pool.get());
363
+ if (r != vk::Result::eSuccess)
364
+ std::cerr << "Error allocating descriptor pool" << vk::to_string(r);
365
+ }
366
+
367
+ static
368
+ void ggml_vk_free_descriptor_pool(struct ggml_kompute_context * ctx) {
369
+ if (ctx->pool) {
370
+ komputeManager()->device()->destroy(
371
+ *ctx->pool,
372
+ (vk::Optional<const vk::AllocationCallbacks>)nullptr);
373
+ ctx->pool = nullptr;
374
+ }
375
+ }
376
+
377
+ static
378
+ vk::Buffer *ggml_vk_allocate_buffer(size_t size) {
379
+ vk::BufferCreateInfo bufferCreateInfo;
380
+ bufferCreateInfo.size = size;
381
+ bufferCreateInfo.usage = vk::BufferUsageFlagBits::eStorageBuffer |
382
+ vk::BufferUsageFlagBits::eTransferSrc |
383
+ vk::BufferUsageFlagBits::eTransferDst;
384
+ bufferCreateInfo.sharingMode = vk::SharingMode::eExclusive;
385
+
386
+ vk::Buffer *vkBuffer = new vk::Buffer;
387
+ vk::Result r = komputeManager()->device()->createBuffer(&bufferCreateInfo, nullptr, vkBuffer);
388
+ if (r != vk::Result::eSuccess)
389
+ std::cerr << "Error allocating buffer " << vk::to_string(r) << std::endl;
390
+ return vkBuffer;
391
+ }
392
+
393
+ static
394
+ vk::DeviceMemory *ggml_vk_allocate(size_t size, vk::MemoryPropertyFlags flags, vk::MemoryRequirements requirements, bool *isHostVisible) {
395
+
396
+ uint32_t memoryTypeIndex = -1;
397
+ bool memoryTypeIndexFound = false;
398
+ vk::PhysicalDeviceMemoryProperties memoryProperties = komputeManager()->physicalDevice()->getMemoryProperties();
399
+ for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++) {
400
+ const vk::MemoryType &memoryType = memoryProperties.memoryTypes[i];
401
+ const vk::MemoryHeap &memoryHeap = memoryProperties.memoryHeaps[memoryType.heapIndex];
402
+ if (memoryHeap.size < size) {
403
+ continue;
404
+ }
405
+
406
+ if (requirements.memoryTypeBits & (1 << i)) {
407
+ if (((memoryProperties.memoryTypes[i]).propertyFlags &
408
+ flags) == flags) {
409
+ memoryTypeIndex = i;
410
+ memoryTypeIndexFound = true;
411
+ if (isHostVisible && (memoryProperties.memoryTypes[i].propertyFlags & vk::MemoryPropertyFlagBits::eHostVisible)) {
412
+ *isHostVisible = true;
413
+ }
414
+ break;
415
+ }
416
+ }
417
+ }
418
+ if (!memoryTypeIndexFound) {
419
+ throw std::runtime_error(
420
+ "Memory type index for buffer creation not found");
421
+ }
422
+
423
+ vk::MemoryAllocateInfo allocInfo;
424
+ allocInfo.allocationSize = size;
425
+ allocInfo.memoryTypeIndex = memoryTypeIndex;
426
+ vk::DeviceMemory *vkDeviceMemory = new vk::DeviceMemory;
427
+ vk::Result r = komputeManager()->device()->allocateMemory(&allocInfo, nullptr, vkDeviceMemory);
428
+ if (r != vk::Result::eSuccess) {
429
+ std::cerr << "Error allocating memory " << vk::to_string(r) << std::endl;
430
+ throw std::runtime_error("Error allocating vulkan memory.");
431
+ }
432
+ return vkDeviceMemory;
433
+ }
434
+
435
+ static size_t ggml_vk_aligned_offset(ggml_backend_buffer_t buffer, size_t offset) {
436
+ size_t minStorageBufferOffsetAlignment = ggml_backend_buffer_get_alignment(buffer);
437
+
438
+ // If offset is already aligned, return it directly
439
+ if (offset % minStorageBufferOffsetAlignment == 0) {
440
+ return offset;
441
+ }
442
+
443
+ // Otherwise, return the largest multiple of minStorageBufferOffsetAlignment less than offset
444
+ return (offset / minStorageBufferOffsetAlignment) * minStorageBufferOffsetAlignment;
445
+ }
446
+
447
+ static ggml_vk_memory ggml_vk_allocate(size_t size) {
448
+ ggml_vk_memory memory;
449
+ bool isHostVisible = false;
450
+ {
451
+ memory.primaryBuffer = ggml_vk_allocate_buffer(size);
452
+ vk::MemoryRequirements memoryRequirements = komputeManager()->device()->getBufferMemoryRequirements(*memory.primaryBuffer);
453
+ vk::MemoryPropertyFlags memoryPropertyFlags = vk::MemoryPropertyFlagBits::eDeviceLocal;
454
+ memory.primaryMemory = ggml_vk_allocate(size, memoryPropertyFlags, memoryRequirements, &isHostVisible);
455
+ komputeManager()->device()->bindBufferMemory(*memory.primaryBuffer, *memory.primaryMemory, 0);
456
+ if (isHostVisible) {
457
+ vk::Result r = komputeManager()->device()->mapMemory(*memory.primaryMemory, 0, size, vk::MemoryMapFlags(), &memory.data);
458
+ if (r != vk::Result::eSuccess)
459
+ std::cerr << "Error mapping memory" << vk::to_string(r);
460
+ }
461
+ }
462
+
463
+ if (!isHostVisible) {
464
+ memory.stagingBuffer = ggml_vk_allocate_buffer(size);
465
+ vk::MemoryRequirements memoryRequirements = komputeManager()->device()->getBufferMemoryRequirements(*memory.stagingBuffer);
466
+ vk::MemoryPropertyFlags memoryPropertyFlags = vk::MemoryPropertyFlagBits::eHostVisible |
467
+ vk::MemoryPropertyFlagBits::eHostCoherent |
468
+ vk::MemoryPropertyFlagBits::eHostCached;
469
+ memory.stagingMemory = ggml_vk_allocate(size, memoryPropertyFlags, memoryRequirements, &isHostVisible);
470
+ komputeManager()->device()->bindBufferMemory(*memory.stagingBuffer, *memory.stagingMemory, 0);
471
+ vk::Result r = komputeManager()->device()->mapMemory(*memory.stagingMemory, 0, size, vk::MemoryMapFlags(), &memory.data);
472
+ if (r != vk::Result::eSuccess)
473
+ std::cerr << "Error mapping memory" << vk::to_string(r);
474
+ }
475
+
476
+ memory.size = size;
477
+ return memory;
478
+ }
479
+
480
+ static void ggml_vk_free_memory(ggml_vk_memory &memory)
481
+ {
482
+ komputeManager()->device()->destroy(
483
+ *memory.primaryBuffer,
484
+ (vk::Optional<const vk::AllocationCallbacks>)nullptr);
485
+ if (memory.stagingBuffer) {
486
+ komputeManager()->device()->destroy(
487
+ *memory.stagingBuffer,
488
+ (vk::Optional<const vk::AllocationCallbacks>)nullptr);
489
+ }
490
+ komputeManager()->device()->freeMemory(
491
+ *memory.primaryMemory,
492
+ (vk::Optional<const vk::AllocationCallbacks>)nullptr);
493
+ if (memory.stagingMemory) {
494
+ komputeManager()->device()->freeMemory(
495
+ *memory.stagingMemory,
496
+ (vk::Optional<const vk::AllocationCallbacks>)nullptr);
497
+ }
498
+ }
499
+
500
+ static const char * ggml_backend_kompute_buffer_type_get_name(ggml_backend_buffer_type_t buft);
501
+
502
+ static
503
+ ggml_vk_memory * ggml_vk_find_tensor(const struct ggml_tensor * t, uint64_t & offset) {
504
+ ggml_backend_buffer_t buffer = t->view_src ? t->view_src->buffer : t->buffer;
505
+
506
+ // compatibility with ggml-backend
507
+ GGML_ASSERT(buffer && buffer->buft->iface.get_name == ggml_backend_kompute_buffer_type_get_name);
508
+
509
+ ggml_vk_memory * buf_ctx = static_cast<ggml_vk_memory *>(buffer->context);
510
+
511
+ const intptr_t ioffs = intptr_t(t->data) - intptr_t(buf_ctx->data);
512
+
513
+ GGML_ASSERT(ioffs >= 0 && ioffs + int64_t(ggml_nbytes(t)) <= int64_t(buffer->size));
514
+
515
+ offset = uint64_t(ioffs);
516
+ return buf_ctx;
517
+ }
518
+
519
+ static
520
+ const std::shared_ptr<kp::Tensor> ggml_vk_get_tensor(const struct ggml_tensor * t, uint32_t * alignedOffset = nullptr) {
521
+ uint64_t originalOffset = 0;
522
+ auto * res = ggml_vk_find_tensor(t, originalOffset);
523
+ if (!res) {
524
+ static std::shared_ptr<kp::Tensor> nullTensor = nullptr;
525
+ return nullTensor;
526
+ }
527
+
528
+ // Create a tensor whose memory will be composed of our buffers at the correct offset
529
+ const size_t nelements = ggml_nelements(t);
530
+ size_t nbytes = ggml_nbytes(t);
531
+
532
+ size_t vulkanOffset = ggml_vk_aligned_offset(t->buffer, originalOffset);
533
+ if (alignedOffset) {
534
+ *alignedOffset = originalOffset - vulkanOffset;
535
+ nbytes += *alignedOffset;
536
+ }
537
+
538
+ return komputeManager()->tensor(
539
+ t->data,
540
+ nelements,
541
+ nbytes, kp::Tensor::TensorDataTypes::eFloat,
542
+ res->primaryMemory, res->primaryBuffer,
543
+ res->stagingMemory, res->stagingBuffer,
544
+ vulkanOffset);
545
+ }
546
+
547
+ static std::vector<uint32_t> getSpirvShader(const unsigned char* rawData, size_t size) {
548
+ if (size % sizeof(uint32_t) != 0) {
549
+ throw std::runtime_error("Invalid size: must be divisible by sizeof(uint32_t)");
550
+ }
551
+
552
+ const uint32_t* data_ptr = reinterpret_cast<const uint32_t*>(rawData);
553
+ size_t count = size / sizeof(uint32_t);
554
+ return std::vector<uint32_t>(data_ptr, data_ptr + count);
555
+ }
556
+
557
+ inline static
558
+ uint32_t safe_divide(uint32_t a, uint32_t b) {
559
+ if (b <= 1) {
560
+ return a;
561
+ }
562
+ if ((a % b) != 0) {
563
+ fprintf(stderr, "((%u %% %u) == %u) != 0\n", a, b, a % b);
564
+ GGML_ABORT("safe_divide result would've had remainder");
565
+ }
566
+ return a / b;
567
+ }
568
+
569
+ static void ggml_vk_add(
570
+ kp::Sequence& seq,
571
+ const std::shared_ptr<kp::Tensor>& inA,
572
+ const std::shared_ptr<kp::Tensor>& inB,
573
+ const std::shared_ptr<kp::Tensor>& out,
574
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
575
+ int32_t ne00, int32_t ne01, int32_t ne02, int32_t ne03,
576
+ int32_t nb00, int32_t nb01, int32_t nb02, int32_t nb03,
577
+ int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
578
+ int32_t nb10, int32_t nb11, int32_t nb12, int32_t nb13,
579
+ int32_t ne0,
580
+ int32_t nb0, int32_t nb1, int32_t nb2, int32_t nb3
581
+ ) {
582
+ const static auto spirv = getSpirvShader(kp::shader_data::op_add_comp_spv,
583
+ kp::shader_data::op_add_comp_spv_len);
584
+
585
+ struct PushConstants {
586
+ uint32_t inAOff, inBOff, outOff;
587
+ int32_t ne00;
588
+ int32_t nb00, nb01, nb02, nb03;
589
+ int32_t ne10, ne11, ne12, ne13;
590
+ int32_t nb10, nb11, nb12, nb13;
591
+ int32_t ne0;
592
+ int32_t nb0, nb1, nb2, nb3;
593
+ } const pushConsts {
594
+ safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
595
+ ne00,
596
+ nb00, nb01, nb02, nb03,
597
+ ne10, ne11, ne12, ne13,
598
+ nb10, nb11, nb12, nb13,
599
+ ne0,
600
+ nb0, nb1, nb2, nb3
601
+ };
602
+
603
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
604
+ if (!komputeManager()->hasAlgorithm(__func__)) {
605
+ s_algo = komputeManager()->algorithm<float, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {}, {pushConsts});
606
+ } else {
607
+ s_algo = komputeManager()->getAlgorithm(__func__);
608
+ s_algo->setTensors({inA, inB, out});
609
+ s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
610
+ s_algo->setPushConstants<PushConstants>({pushConsts});
611
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
612
+ }
613
+ seq.record<kp::OpAlgoDispatch>(s_algo);
614
+ }
615
+
616
+ static void ggml_vk_addrow(kp::Sequence& seq,
617
+ const std::shared_ptr<kp::Tensor>& inA,
618
+ const std::shared_ptr<kp::Tensor>& inB,
619
+ const std::shared_ptr<kp::Tensor>& out,
620
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
621
+ uint32_t size, uint32_t row = 0) {
622
+
623
+ const static auto spirv = getSpirvShader(kp::shader_data::op_addrow_comp_spv,
624
+ kp::shader_data::op_addrow_comp_spv_len);
625
+
626
+ struct PushConstants {
627
+ uint32_t inAOff, inBOff, outOff;
628
+ uint32_t row;
629
+ } const pushConsts {
630
+ safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
631
+ row
632
+ };
633
+
634
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
635
+ if (!komputeManager()->hasAlgorithm(__func__))
636
+ s_algo = komputeManager()->algorithm<float, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {size}, {}, {pushConsts});
637
+ else {
638
+ s_algo = komputeManager()->getAlgorithm(__func__);
639
+ s_algo->setTensors({inA, inB, out});
640
+ s_algo->setWorkgroup({size});
641
+ s_algo->setPushConstants<PushConstants>({pushConsts});
642
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
643
+ }
644
+ seq.record<kp::OpAlgoDispatch>(s_algo);
645
+ }
646
+
647
+ static void ggml_vk_mul(
648
+ kp::Sequence& seq,
649
+ const std::shared_ptr<kp::Tensor>& inA,
650
+ const std::shared_ptr<kp::Tensor>& inB,
651
+ const std::shared_ptr<kp::Tensor>& out,
652
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
653
+ int32_t ne00, int32_t ne01, int32_t ne02, int32_t ne03,
654
+ int32_t nb00, int32_t nb01, int32_t nb02, int32_t nb03,
655
+ int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
656
+ int32_t nb10, int32_t nb11, int32_t nb12, int32_t nb13,
657
+ int32_t ne0,
658
+ int32_t nb0, int32_t nb1, int32_t nb2, int32_t nb3
659
+ ) {
660
+ const static auto spirv = getSpirvShader(kp::shader_data::op_mul_comp_spv,
661
+ kp::shader_data::op_mul_comp_spv_len);
662
+
663
+ struct PushConstants {
664
+ uint32_t inAOff, inBOff, outOff;
665
+ int32_t ne00;
666
+ int32_t nb00, nb01, nb02, nb03;
667
+ int32_t ne10, ne11, ne12, ne13;
668
+ int32_t nb10, nb11, nb12, nb13;
669
+ int32_t ne0;
670
+ int32_t nb0, nb1, nb2, nb3;
671
+ } const pushConsts {
672
+ safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
673
+ ne00,
674
+ nb00, nb01, nb02, nb03,
675
+ ne10, ne11, ne12, ne13,
676
+ nb10, nb11, nb12, nb13,
677
+ ne0,
678
+ nb0, nb1, nb2, nb3
679
+ };
680
+
681
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
682
+ if (!komputeManager()->hasAlgorithm(__func__)) {
683
+ s_algo = komputeManager()->algorithm<float, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {}, {pushConsts});
684
+ } else {
685
+ s_algo = komputeManager()->getAlgorithm(__func__);
686
+ s_algo->setTensors({inA, inB, out});
687
+ s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
688
+ s_algo->setPushConstants<PushConstants>({pushConsts});
689
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
690
+ }
691
+ seq.record<kp::OpAlgoDispatch>(s_algo);
692
+ }
693
+
694
+ static void ggml_vk_scale(kp::Sequence& seq,
695
+ const std::shared_ptr<kp::Tensor>& in,
696
+ const std::shared_ptr<kp::Tensor>& out,
697
+ uint32_t inOff, uint32_t outOff,
698
+ uint32_t size, float scale) {
699
+ const static auto spirv_1 = getSpirvShader(
700
+ kp::shader_data::op_scale_comp_spv, kp::shader_data::op_scale_comp_spv_len
701
+ );
702
+ const static auto spirv_8 = getSpirvShader(
703
+ kp::shader_data::op_scale_8_comp_spv, kp::shader_data::op_scale_8_comp_spv_len
704
+ );
705
+
706
+ struct PushConstants {
707
+ uint32_t inOff, outOff;
708
+ float scale;
709
+ } const pushConsts {
710
+ safe_divide(inOff, 4), safe_divide(outOff, 4),
711
+ scale
712
+ };
713
+
714
+ const auto * spirv = &spirv_1;
715
+ std::string name(__func__);
716
+ if (size % 8 == 0) {
717
+ size /= 8;
718
+ name += "_8";
719
+ spirv = &spirv_8;
720
+ }
721
+
722
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
723
+ if (!komputeManager()->hasAlgorithm(name)) {
724
+ s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {in, out}, *spirv, {size}, {}, {pushConsts});
725
+ } else {
726
+ s_algo = komputeManager()->getAlgorithm(name);
727
+ s_algo->setTensors({in, out});
728
+ s_algo->setWorkgroup({size});
729
+ s_algo->setPushConstants<PushConstants>({pushConsts});
730
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
731
+ }
732
+ seq.record<kp::OpAlgoDispatch>(s_algo);
733
+ }
734
+
735
+ static void ggml_vk_xxlu(
736
+ const std::vector<uint32_t>& spirv, const char * suffix, kp::Sequence& seq,
737
+ const std::shared_ptr<kp::Tensor>& in,
738
+ const std::shared_ptr<kp::Tensor>& out,
739
+ uint32_t inOff, uint32_t outOff,
740
+ uint32_t size
741
+ ) {
742
+ struct PushConstants {
743
+ uint32_t inOff, outOff;
744
+ } const pushConsts {
745
+ safe_divide(inOff, 4), safe_divide(outOff, 4),
746
+ };
747
+
748
+ auto name = std::string(__func__) + "_" + suffix;
749
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
750
+ if (!komputeManager()->hasAlgorithm(name)) {
751
+ s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {in, out}, spirv, {size}, {}, {pushConsts});
752
+ } else {
753
+ s_algo = komputeManager()->getAlgorithm(name);
754
+ s_algo->setTensors({in, out});
755
+ s_algo->setWorkgroup({size});
756
+ s_algo->setPushConstants<PushConstants>({pushConsts});
757
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
758
+ }
759
+ seq.record<kp::OpAlgoDispatch>(s_algo);
760
+ }
761
+
762
+ template <typename... Args>
763
+ static void ggml_vk_silu(Args&&... args) {
764
+ const static auto spirv = getSpirvShader(kp::shader_data::op_silu_comp_spv,
765
+ kp::shader_data::op_silu_comp_spv_len);
766
+
767
+ ggml_vk_xxlu(spirv, "silu", std::forward<Args>(args)...);
768
+ }
769
+
770
+ template <typename... Args>
771
+ static void ggml_vk_relu(Args&&... args) {
772
+ const static auto spirv = getSpirvShader(kp::shader_data::op_relu_comp_spv,
773
+ kp::shader_data::op_relu_comp_spv_len);
774
+
775
+ ggml_vk_xxlu(spirv, "relu", std::forward<Args>(args)...);
776
+ }
777
+
778
+ template <typename... Args>
779
+ static void ggml_vk_gelu(Args&&... args) {
780
+ const static auto spirv = getSpirvShader(kp::shader_data::op_gelu_comp_spv,
781
+ kp::shader_data::op_gelu_comp_spv_len);
782
+
783
+ ggml_vk_xxlu(spirv, "gelu", std::forward<Args>(args)...);
784
+ }
785
+
786
+ static void ggml_vk_soft_max(
787
+ kp::Sequence& seq,
788
+ const std::shared_ptr<kp::Tensor>& inA,
789
+ const std::shared_ptr<kp::Tensor>& inB,
790
+ const std::shared_ptr<kp::Tensor>& out,
791
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
792
+ int32_t ne00, int32_t ne01, int32_t ne02, uint32_t ne03,
793
+ float scale, float max_bias, float m0, float m1,
794
+ uint32_t n_head_log2
795
+ ) {
796
+ const static auto spirv = getSpirvShader(kp::shader_data::op_softmax_comp_spv,
797
+ kp::shader_data::op_softmax_comp_spv_len);
798
+
799
+ struct PushConstants {
800
+ uint32_t inAOff, inBOff, outOff;
801
+ int32_t ne00, ne01, ne02;
802
+ float scale, max_bias, m0, m1;
803
+ uint32_t n_head_log2;
804
+ int32_t mask;
805
+ } pushConsts {
806
+ safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
807
+ ne00, ne01, ne02,
808
+ scale, max_bias, m0, m1,
809
+ n_head_log2,
810
+ bool(inB)
811
+ };
812
+
813
+ auto & inB_ = inB ? inB : inA;
814
+
815
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
816
+ if (!komputeManager()->hasAlgorithm(__func__)) {
817
+ // FIXME: The softmax kernel needs to be fixed to use the subgroupsize which can vary by device
818
+ const uint32_t local_x = 32;
819
+ s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB_, out}, spirv, {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {local_x}, {pushConsts});
820
+ } else {
821
+ s_algo = komputeManager()->getAlgorithm(__func__);
822
+ s_algo->setTensors({inA, inB_, out});
823
+ s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
824
+ s_algo->setPushConstants<PushConstants>({pushConsts});
825
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
826
+ }
827
+ seq.record<kp::OpAlgoDispatch>(s_algo);
828
+ }
829
+
830
+ static void ggml_vk_norm_(
831
+ const std::vector<uint32_t>& spirv, const char * suffix, kp::Sequence& seq,
832
+ const std::shared_ptr<kp::Tensor>& in,
833
+ const std::shared_ptr<kp::Tensor>& out,
834
+ uint32_t inOff, uint32_t outOff,
835
+ int32_t ne00, int32_t nb01,
836
+ int32_t nrows, float epsilon
837
+ ) {
838
+ GGML_ASSERT(nb01%sizeof(float) == 0);
839
+ GGML_ASSERT(ne00%sizeof(float) == 0);
840
+
841
+ struct PushConstants {
842
+ uint32_t inOff, outOff;
843
+ uint32_t ne00, nb01;
844
+ float eps;
845
+ } pushConsts {
846
+ safe_divide(inOff, 4), safe_divide(outOff, 4),
847
+ (uint32_t)ne00, (uint32_t)nb01, epsilon
848
+ };
849
+
850
+ auto name = std::string(__func__) + "_" + suffix;
851
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
852
+ if (!komputeManager()->hasAlgorithm(name)) {
853
+ s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {in, out}, spirv, {(uint32_t)nrows}, {}, {pushConsts});
854
+ } else {
855
+ s_algo = komputeManager()->getAlgorithm(name);
856
+ s_algo->setTensors({in, out});
857
+ s_algo->setWorkgroup({(uint32_t)nrows});
858
+ s_algo->setPushConstants<PushConstants>({pushConsts});
859
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
860
+ }
861
+ seq.record<kp::OpAlgoDispatch>(s_algo);
862
+ }
863
+
864
+ template <typename... Args>
865
+ static void ggml_vk_norm(Args&&... args) {
866
+ const static auto spirv = getSpirvShader(kp::shader_data::op_norm_comp_spv,
867
+ kp::shader_data::op_norm_comp_spv_len);
868
+
869
+ ggml_vk_norm_(spirv, "norm", std::forward<Args>(args)...);
870
+ }
871
+
872
+ template <typename... Args>
873
+ static void ggml_vk_rms_norm(Args&&... args) {
874
+ const static auto spirv = getSpirvShader(kp::shader_data::op_rmsnorm_comp_spv,
875
+ kp::shader_data::op_rmsnorm_comp_spv_len);
876
+
877
+ ggml_vk_norm_(spirv, "rms", std::forward<Args>(args)...);
878
+ }
879
+
880
+ static void ggml_vk_diag_mask_inf(kp::Sequence& seq,
881
+ const std::shared_ptr<kp::Tensor>& in,
882
+ const std::shared_ptr<kp::Tensor>& out,
883
+ uint32_t inOff, uint32_t outOff,
884
+ uint32_t n_past,
885
+ int32_t ne00, int32_t ne01, int32_t ne02) {
886
+ const static auto spirv = getSpirvShader(kp::shader_data::op_diagmask_comp_spv,
887
+ kp::shader_data::op_diagmask_comp_spv_len);
888
+
889
+ struct PushConstants {
890
+ uint32_t inOff, outOff;
891
+ uint32_t n_past;
892
+ int32_t ne00, ne01;
893
+ } pushConsts {
894
+ safe_divide(inOff, 4), safe_divide(outOff, 4),
895
+ n_past,
896
+ ne00, ne01
897
+ };
898
+
899
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
900
+ if (!komputeManager()->hasAlgorithm(__func__))
901
+ s_algo = komputeManager()->algorithm<float, PushConstants>(__func__, s_kompute_context->pool.get(), {in, out}, spirv, {unsigned(ne00), unsigned(ne01), unsigned(ne02)}, {}, {pushConsts});
902
+ else {
903
+ s_algo = komputeManager()->getAlgorithm(__func__);
904
+ s_algo->setTensors({in, out});
905
+ s_algo->setWorkgroup({unsigned(ne00), unsigned(ne01), unsigned(ne02)});
906
+ s_algo->setPushConstants<PushConstants>({pushConsts});
907
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
908
+ }
909
+ seq.record<kp::OpAlgoDispatch>(s_algo);
910
+ }
911
+
912
+ static void ggml_vk_mul_mat_f16(
913
+ kp::Sequence& seq,
914
+ const std::shared_ptr<kp::Tensor>& inA,
915
+ const std::shared_ptr<kp::Tensor>& inB,
916
+ const std::shared_ptr<kp::Tensor>& out,
917
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
918
+ int32_t ne00, int32_t ne01, int32_t ne02,
919
+ uint32_t nb00, uint32_t nb01, uint32_t nb02, uint32_t nb03,
920
+ int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
921
+ uint32_t nb10, uint32_t nb11, uint32_t nb12, uint32_t nb13,
922
+ int32_t ne0, int32_t ne1,
923
+ uint32_t r2, uint32_t r3
924
+ ) {
925
+ const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_f16_comp_spv,
926
+ kp::shader_data::op_mul_mat_f16_comp_spv_len);
927
+
928
+ struct PushConstants {
929
+ uint32_t inAOff, inBOff, outOff;
930
+ int32_t ne00, ne01, ne02;
931
+ uint32_t nb00, nb01, nb02, nb03;
932
+ int32_t ne10, ne11, ne12;
933
+ uint32_t nb10, nb11, nb12, nb13;
934
+ int32_t ne0, ne1;
935
+ uint32_t r2, r3;
936
+ } pushConsts {
937
+ safe_divide(inAOff, 2), safe_divide(inBOff, 4), safe_divide(outOff, 4),
938
+ ne00, ne01, ne02,
939
+ nb00, nb01, nb02, nb03,
940
+ ne10, ne11, ne12,
941
+ nb10, nb11, nb12, nb13,
942
+ ne0, ne1,
943
+ r2, r3
944
+ };
945
+
946
+ const unsigned ny = unsigned((ne11 + 4 - 1)/4);
947
+
948
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
949
+ if (!komputeManager()->hasAlgorithm(__func__)) {
950
+ const uint32_t local_x = ggml_vk_current_device().subgroupSize * 2;
951
+ s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned(ne01), ny, unsigned(ne12*ne13)}, {local_x}, {pushConsts});
952
+ } else {
953
+ s_algo = komputeManager()->getAlgorithm(__func__);
954
+ s_algo->setTensors({inA, inB, out});
955
+ s_algo->setWorkgroup({unsigned(ne01), ny, unsigned(ne12*ne13)});
956
+ s_algo->setPushConstants<PushConstants>({pushConsts});
957
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
958
+ }
959
+ seq.record<kp::OpAlgoDispatch>(s_algo);
960
+ }
961
+
962
+ static void ggml_vk_mul_mat_mat_f32(kp::Sequence& seq,
963
+ const std::shared_ptr<kp::Tensor>& inA,
964
+ const std::shared_ptr<kp::Tensor>& inB,
965
+ const std::shared_ptr<kp::Tensor>& out,
966
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
967
+ int32_t ne00, int32_t ne01, int32_t ne02,
968
+ uint32_t nb01, uint32_t nb02,
969
+ int32_t ne11, int32_t ne12,
970
+ uint32_t nb11, uint32_t nb12,
971
+ uint32_t nb1, uint32_t nb2) {
972
+ const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_mat_f32_comp_spv,
973
+ kp::shader_data::op_mul_mat_mat_f32_comp_spv_len);
974
+
975
+ struct PushConstants {
976
+ uint32_t inAOff, inBOff, outOff;
977
+ int32_t ne00, ne01, ne02, ne11, ne12;
978
+ uint32_t nb01, nb02;
979
+ uint32_t nb11, nb12;
980
+ uint32_t nb1, nb2;
981
+ } pushConsts {
982
+ safe_divide(inAOff, 4), safe_divide(inBOff, 4), safe_divide(outOff, 4),
983
+ ne00, ne01, ne02, ne11, ne12,
984
+ nb01, nb02, nb11, nb12,
985
+ nb1, nb2
986
+ };
987
+
988
+ const uint32_t local_x = ggml_vk_current_device().subgroupSize;
989
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
990
+ if (!komputeManager()->hasAlgorithm(__func__)) {
991
+ s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(__func__, s_kompute_context->pool.get(),
992
+ {inA, inB, out}, spirv,
993
+ {unsigned(ne01),
994
+ unsigned(ne11),
995
+ unsigned(std::max(ne12, ne02))
996
+ },
997
+ {local_x},
998
+ {pushConsts});
999
+ } else {
1000
+ s_algo = komputeManager()->getAlgorithm(__func__);
1001
+ s_algo->setTensors({inA, inB, out});
1002
+ s_algo->setWorkgroup({unsigned(ne01),
1003
+ unsigned(ne11),
1004
+ unsigned(std::max(ne12, ne02)),
1005
+ });
1006
+ s_algo->setPushConstants<PushConstants>({pushConsts});
1007
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
1008
+ }
1009
+ seq.record<kp::OpAlgoDispatch>(s_algo);
1010
+ }
1011
+
1012
+ static void ggml_vk_mul_mat_impl(
1013
+ const std::vector<uint32_t>& spirv, const char * suffix, uint32_t block_size, kp::Sequence& seq,
1014
+ const std::shared_ptr<kp::Tensor>& inA,
1015
+ const std::shared_ptr<kp::Tensor>& inB,
1016
+ const std::shared_ptr<kp::Tensor>& out,
1017
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
1018
+ int32_t ne00, int32_t ne01, int32_t ne02,
1019
+ int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
1020
+ int32_t ne0, int32_t ne1,
1021
+ uint32_t nb01, uint32_t nb02, uint32_t nb03,
1022
+ uint32_t nb11, uint32_t nb12, uint32_t nb13,
1023
+ uint32_t r2, uint32_t r3
1024
+ ) {
1025
+ struct PushConstants {
1026
+ uint32_t inAOff, inBOff, outOff;
1027
+ int32_t ne00, ne01, ne02;
1028
+ int32_t ne10, ne12;
1029
+ int32_t ne0, ne1;
1030
+ uint32_t nb01, nb02, nb03;
1031
+ uint32_t nb11, nb12, nb13;
1032
+ uint32_t r2, r3;
1033
+ } pushConsts {
1034
+ safe_divide(inAOff, block_size), safe_divide(inBOff, 4), safe_divide(outOff, 4),
1035
+ ne00, ne01, ne02,
1036
+ ne10, ne12,
1037
+ ne0, ne1,
1038
+ nb01, nb02, nb03,
1039
+ nb11, nb12, nb13,
1040
+ r2, r3
1041
+ };
1042
+
1043
+ auto name = std::string(__func__) + "_" + suffix;
1044
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
1045
+ if (!komputeManager()->hasAlgorithm(name)) {
1046
+ const uint32_t local_x = (ggml_vk_current_device().subgroupSize * 2) / 8;
1047
+ s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(name, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned((ne01 + 7)/8), unsigned(ne11), unsigned(ne12*ne13)}, {local_x}, {pushConsts});
1048
+ } else {
1049
+ s_algo = komputeManager()->getAlgorithm(name);
1050
+ s_algo->setTensors({inA, inB, out});
1051
+ s_algo->setWorkgroup({unsigned((ne01 + 7)/8), unsigned(ne11), unsigned(ne12*ne13)});
1052
+ s_algo->setPushConstants<PushConstants>({pushConsts});
1053
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
1054
+ }
1055
+ seq.record<kp::OpAlgoDispatch>(s_algo);
1056
+ }
1057
+
1058
+ template <typename... Args>
1059
+ static void ggml_vk_mul_mat_q4_0(Args&&... args) {
1060
+ const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_q4_0_comp_spv,
1061
+ kp::shader_data::op_mul_mat_q4_0_comp_spv_len);
1062
+
1063
+ ggml_vk_mul_mat_impl(spirv, "q4_0", 1/*We access blocks unaligned*/, std::forward<Args>(args)...);
1064
+ }
1065
+
1066
+ template <typename... Args>
1067
+ static void ggml_vk_mul_mat_q4_1(Args&&... args) {
1068
+ const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_q4_1_comp_spv,
1069
+ kp::shader_data::op_mul_mat_q4_1_comp_spv_len);
1070
+
1071
+ ggml_vk_mul_mat_impl(spirv, "q4_1", 1/*We access blocks unaligned*/, std::forward<Args>(args)...);
1072
+ }
1073
+
1074
+ template <typename... Args>
1075
+ static void ggml_vk_mul_mat_q8_0(Args&&... args) {
1076
+ const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_q8_0_comp_spv,
1077
+ kp::shader_data::op_mul_mat_q8_0_comp_spv_len);
1078
+
1079
+ ggml_vk_mul_mat_impl(spirv, "q8_0", 1/*We access blocks unaligned*/, std::forward<Args>(args)...);
1080
+ }
1081
+
1082
+ static void ggml_vk_mul_mat_q4_k(
1083
+ kp::Sequence& seq,
1084
+ const std::shared_ptr<kp::Tensor>& inA,
1085
+ const std::shared_ptr<kp::Tensor>& inB,
1086
+ const std::shared_ptr<kp::Tensor>& out,
1087
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
1088
+ int32_t ne00, int32_t ne01, int32_t ne02,
1089
+ int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
1090
+ int32_t ne0, int32_t ne1,
1091
+ uint32_t nb01, uint32_t nb02, uint32_t nb03,
1092
+ uint32_t nb11, uint32_t nb12, uint32_t nb13,
1093
+ uint32_t r2, uint32_t r3
1094
+ ) {
1095
+ const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_q4_k_comp_spv,
1096
+ kp::shader_data::op_mul_mat_q4_k_comp_spv_len);
1097
+
1098
+ struct PushConstants {
1099
+ uint32_t inAOff, inBOff, outOff;
1100
+ int32_t ne00, ne10, ne0, ne1, ne01, ne02, ne12;
1101
+ uint32_t nb01, nb02, nb03, nb11, nb12, nb13;
1102
+ uint32_t r2, r3;
1103
+ } pushConsts {
1104
+ inAOff, safe_divide(inBOff, 4), safe_divide(outOff, 4),
1105
+ ne00, ne10, ne0, ne1, ne01, ne02, ne12,
1106
+ nb01, nb02, nb03, nb11, nb12, nb13,
1107
+ r2, r3
1108
+ };
1109
+
1110
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
1111
+ if (!komputeManager()->hasAlgorithm(__func__)) {
1112
+ s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned((ne01 + 3)/4), unsigned(ne11), unsigned(ne12) * unsigned(ne13)}, {}, {pushConsts});
1113
+ } else {
1114
+ s_algo = komputeManager()->getAlgorithm(__func__);
1115
+ s_algo->setTensors({inA, inB, out});
1116
+ s_algo->setWorkgroup({unsigned((ne01 + 3)/4), unsigned(ne11), unsigned(ne12) * unsigned(ne13)});
1117
+ s_algo->setPushConstants<PushConstants>({pushConsts});
1118
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
1119
+ }
1120
+ seq.record<kp::OpAlgoDispatch>(s_algo);
1121
+ }
1122
+
1123
+ static void ggml_vk_mul_mat_q6_k(
1124
+ kp::Sequence& seq,
1125
+ const std::shared_ptr<kp::Tensor>& inA,
1126
+ const std::shared_ptr<kp::Tensor>& inB,
1127
+ const std::shared_ptr<kp::Tensor>& out,
1128
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
1129
+ int32_t ne00, int32_t ne01, int32_t ne02,
1130
+ int32_t ne10, int32_t ne11, int32_t ne12, int32_t ne13,
1131
+ int32_t ne0, int32_t ne1,
1132
+ uint32_t nb01, uint32_t nb02, uint32_t nb03,
1133
+ uint32_t nb11, uint32_t nb12, uint32_t nb13,
1134
+ uint32_t r2, uint32_t r3
1135
+ ) {
1136
+ const static auto spirv = getSpirvShader(kp::shader_data::op_mul_mat_q6_k_comp_spv,
1137
+ kp::shader_data::op_mul_mat_q6_k_comp_spv_len);
1138
+
1139
+ struct PushConstants {
1140
+ uint32_t inAOff, inBOff, outOff;
1141
+ int32_t ne00, ne10, ne0, ne1, ne01, ne02, ne12;
1142
+ uint32_t nb01, nb02, nb03, nb11, nb12, nb13;
1143
+ uint32_t r2, r3;
1144
+ } pushConsts {
1145
+ inAOff, safe_divide(inBOff, 4), safe_divide(outOff, 4),
1146
+ ne00, ne10, ne0, ne1, ne01, ne02, ne12,
1147
+ nb01, nb02, nb03, nb11, nb12, nb13,
1148
+ r2, r3
1149
+ };
1150
+
1151
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
1152
+ if (!komputeManager()->hasAlgorithm(__func__)) {
1153
+ const uint32_t local_x = 2;
1154
+ const uint32_t local_y = ggml_vk_current_device().subgroupSize;
1155
+ s_algo = komputeManager()->algorithm<uint32_t, PushConstants>(__func__, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {unsigned((ne01 + 1)/2), unsigned(ne11), unsigned(ne12)*unsigned(ne13)}, {local_x, local_y}, {pushConsts});
1156
+ } else {
1157
+ s_algo = komputeManager()->getAlgorithm(__func__);
1158
+ s_algo->setTensors({inA, inB, out});
1159
+ s_algo->setWorkgroup({unsigned((ne01 + 1)/2), unsigned(ne11), unsigned(ne12)*unsigned(ne13)});
1160
+ s_algo->setPushConstants<PushConstants>({pushConsts});
1161
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
1162
+ }
1163
+ seq.record<kp::OpAlgoDispatch>(s_algo);
1164
+ }
1165
+
1166
+ static void ggml_vk_get_rows(
1167
+ const std::vector<uint32_t>& spirv,
1168
+ const char * suffix,
1169
+ unsigned element_size, unsigned qk,
1170
+ kp::Sequence& seq,
1171
+ const std::shared_ptr<kp::Tensor>& inA,
1172
+ const std::shared_ptr<kp::Tensor>& inB,
1173
+ const std::shared_ptr<kp::Tensor>& out,
1174
+ uint32_t inAOff, uint32_t inBOff, uint32_t outOff,
1175
+ int32_t ne00, int32_t nb01, int32_t nb1,
1176
+ uint32_t size
1177
+ ) {
1178
+ GGML_ASSERT(nb01%element_size == 0);
1179
+ GGML_ASSERT(nb1%sizeof(float) == 0);
1180
+ if (qk) GGML_ASSERT(ne00%qk == 0);
1181
+
1182
+ struct PushConstants {
1183
+ uint32_t inAOff, inBOff, outOff;
1184
+ int32_t ne00, nb01, nb1;
1185
+ } pushConsts {
1186
+ safe_divide(inAOff, element_size), safe_divide(inBOff, 4), safe_divide(outOff, 4),
1187
+ ne00, nb01, nb1
1188
+ };
1189
+
1190
+ auto name = std::string(__func__) + "_" + suffix;
1191
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
1192
+ if (!komputeManager()->hasAlgorithm(name)) {
1193
+ s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {inA, inB, out}, spirv, {size}, {}, {pushConsts});
1194
+ } else {
1195
+ s_algo = komputeManager()->getAlgorithm(name);
1196
+ s_algo->setTensors({inA, inB, out});
1197
+ s_algo->setWorkgroup({size});
1198
+ s_algo->setPushConstants<PushConstants>({pushConsts});
1199
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
1200
+ }
1201
+ seq.record<kp::OpAlgoDispatch>(s_algo);
1202
+ }
1203
+
1204
+ template <typename... Args>
1205
+ static void ggml_vk_get_rows_f32(Args&&... args) {
1206
+ const static auto spirv = getSpirvShader(kp::shader_data::op_getrows_f32_comp_spv,
1207
+ kp::shader_data::op_getrows_f32_comp_spv_len);
1208
+
1209
+ ggml_vk_get_rows(spirv, "f32", sizeof(float), 0, std::forward<Args>(args)...);
1210
+ }
1211
+
1212
+ template <typename... Args>
1213
+ static void ggml_vk_get_rows_f16(Args&&... args) {
1214
+ const static auto spirv = getSpirvShader(kp::shader_data::op_getrows_f16_comp_spv,
1215
+ kp::shader_data::op_getrows_f16_comp_spv_len);
1216
+
1217
+ ggml_vk_get_rows(spirv, "f16", sizeof(half), 0, std::forward<Args>(args)...);
1218
+ }
1219
+
1220
+ template <typename... Args>
1221
+ static void ggml_vk_get_rows_q4_0(Args&&... args) {
1222
+ const static auto spirv = getSpirvShader(kp::shader_data::op_getrows_q4_0_comp_spv,
1223
+ kp::shader_data::op_getrows_q4_0_comp_spv_len);
1224
+
1225
+ ggml_vk_get_rows(spirv, "q4_0", 1/*We access blocks unaligned*/, QK4_0, std::forward<Args>(args)...);
1226
+ }
1227
+
1228
+ template <typename... Args>
1229
+ static void ggml_vk_get_rows_q4_1(Args&&... args) {
1230
+ const static auto spirv = getSpirvShader(kp::shader_data::op_getrows_q4_1_comp_spv,
1231
+ kp::shader_data::op_getrows_q4_1_comp_spv_len);
1232
+
1233
+ ggml_vk_get_rows(spirv, "q4_1", 1/*We access blocks unaligned*/, QK4_1, std::forward<Args>(args)...);
1234
+ }
1235
+
1236
+ template <typename... Args>
1237
+ static void ggml_vk_get_rows_q6_k(Args&&... args) {
1238
+ const static auto spirv = getSpirvShader(kp::shader_data::op_getrows_q6_k_comp_spv,
1239
+ kp::shader_data::op_getrows_q6_k_comp_spv_len);
1240
+ ggml_vk_get_rows(spirv, "q6_k", 1/*We access blocks unaligned*/, QK_NL, std::forward<Args>(args)...);
1241
+ }
1242
+
1243
+ static void ggml_vk_rope(
1244
+ kp::Sequence& seq,
1245
+ const std::shared_ptr<kp::Tensor>& inA,
1246
+ const std::shared_ptr<kp::Tensor>& inB,
1247
+ const std::shared_ptr<kp::Tensor>& inC,
1248
+ const std::shared_ptr<kp::Tensor>& out,
1249
+ uint32_t inAOff, uint32_t inBOff, uint32_t inCOff, uint32_t outOff,
1250
+ ggml_type src0t, int32_t n_dims, int32_t mode, int32_t n_ctx_orig,
1251
+ float freq_base, float freq_scale, bool has_freq_factors, float ext_factor, float attn_factor, float beta_fast, float beta_slow,
1252
+ int32_t ne01, int32_t ne02, int32_t ne03,
1253
+ uint32_t nb00, uint32_t nb01, uint32_t nb02, uint32_t nb03,
1254
+ int32_t ne0,
1255
+ uint32_t nb0, uint32_t nb1, uint32_t nb2, uint32_t nb3
1256
+ ) {
1257
+ GGML_ASSERT(src0t == GGML_TYPE_F16 || src0t == GGML_TYPE_F32);
1258
+
1259
+ static const auto spirv_norm_f16 = getSpirvShader(
1260
+ kp::shader_data::op_rope_norm_f16_comp_spv, kp::shader_data::op_rope_norm_f16_comp_spv_len
1261
+ );
1262
+ static const auto spirv_norm_f32 = getSpirvShader(
1263
+ kp::shader_data::op_rope_norm_f32_comp_spv, kp::shader_data::op_rope_norm_f32_comp_spv_len
1264
+ );
1265
+ static const auto spirv_neox_f16 = getSpirvShader(
1266
+ kp::shader_data::op_rope_neox_f16_comp_spv, kp::shader_data::op_rope_neox_f16_comp_spv_len
1267
+ );
1268
+ static const auto spirv_neox_f32 = getSpirvShader(
1269
+ kp::shader_data::op_rope_neox_f32_comp_spv, kp::shader_data::op_rope_neox_f32_comp_spv_len
1270
+ );
1271
+
1272
+ int type_size = src0t == GGML_TYPE_F16 ? 2 : 4;
1273
+
1274
+ GGML_ASSERT(nb03 % type_size == 0);
1275
+ GGML_ASSERT(nb02 % type_size == 0);
1276
+ GGML_ASSERT(nb01 % type_size == 0);
1277
+ GGML_ASSERT(nb00 % type_size == 0);
1278
+ GGML_ASSERT(nb3 % type_size == 0);
1279
+ GGML_ASSERT(nb2 % type_size == 0);
1280
+ GGML_ASSERT(nb1 % type_size == 0);
1281
+ GGML_ASSERT(nb0 % type_size == 0);
1282
+
1283
+ struct PushConstants {
1284
+ uint32_t inAOff, inBOff, inCOff, outOff;
1285
+ int32_t n_dims, mode, n_ctx_orig;
1286
+ float freq_base, freq_scale;
1287
+ bool has_freq_factors;
1288
+ float ext_factor, attn_factor, beta_fast, beta_slow;
1289
+ uint32_t nb00, nb01, nb02, nb03;
1290
+ int32_t ne0;
1291
+ uint32_t nb0, nb1, nb2, nb3;
1292
+ } pushConsts {
1293
+ safe_divide(inAOff, type_size), safe_divide(inBOff, 4), safe_divide(inCOff, type_size), safe_divide(outOff, type_size),
1294
+ n_dims, mode, n_ctx_orig,
1295
+ freq_base, freq_scale,
1296
+ has_freq_factors,
1297
+ ext_factor, attn_factor, beta_fast, beta_slow,
1298
+ nb00, nb01, nb02, nb03,
1299
+ ne0,
1300
+ nb0, nb1, nb2, nb3
1301
+ };
1302
+
1303
+ auto & inC_ = inC ? inC : inA;
1304
+ const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
1305
+ const bool is_f16 = src0t == GGML_TYPE_F16;
1306
+
1307
+ auto name = std::string(__func__) + (is_neox ? "_neox" : "_norm") + (src0t == GGML_TYPE_F16 ? "_f16" : "_f32");
1308
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
1309
+ if (!komputeManager()->hasAlgorithm(name)) {
1310
+ auto & spirv = is_neox ? is_f16 ? spirv_neox_f16 : spirv_neox_f32 : is_f16 ? spirv_norm_f16 : spirv_norm_f32;
1311
+ s_algo = komputeManager()->algorithm<float, PushConstants>(
1312
+ name, s_kompute_context->pool.get(), {inA, inB, inC_, out}, spirv,
1313
+ {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {}, {pushConsts}
1314
+ );
1315
+ } else {
1316
+ s_algo = komputeManager()->getAlgorithm(name);
1317
+ s_algo->setTensors({inA, inB, inC_, out});
1318
+ s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
1319
+ s_algo->setPushConstants<PushConstants>({pushConsts});
1320
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
1321
+ }
1322
+ seq.record<kp::OpAlgoDispatch>(s_algo);
1323
+ }
1324
+
1325
+ static void ggml_vk_cpy(
1326
+ const std::vector<uint32_t>& spirv,
1327
+ uint32_t in_element_size, uint32_t out_element_size,
1328
+ kp::Sequence& seq,
1329
+ const std::shared_ptr<kp::Tensor>& in,
1330
+ const std::shared_ptr<kp::Tensor>& out,
1331
+ uint32_t inOff, uint32_t outOff,
1332
+ int32_t ne00, int32_t ne01, int32_t ne02, int32_t ne03,
1333
+ uint32_t nb00, uint32_t nb01, uint32_t nb02, uint32_t nb03,
1334
+ int32_t ne0, int32_t ne1, int32_t ne2,
1335
+ uint32_t nb0, uint32_t nb1, uint32_t nb2, uint32_t nb3
1336
+ ) {
1337
+ struct PushConstants {
1338
+ uint32_t inOff, outOff;
1339
+ int32_t ne00, ne01, ne02;
1340
+ uint32_t nb00, nb01, nb02, nb03;
1341
+ int32_t ne0, ne1, ne2;
1342
+ uint32_t nb0, nb1, nb2, nb3;
1343
+ } pushConsts {
1344
+ safe_divide(inOff, in_element_size), safe_divide(outOff, out_element_size),
1345
+ ne00, ne01, ne02,
1346
+ nb00, nb01, nb02, nb03,
1347
+ ne0, ne1, ne2,
1348
+ nb0, nb1, nb2, nb3
1349
+ };
1350
+
1351
+ std::string name = std::string(__func__)
1352
+ + "_i_" + std::to_string(in_element_size)
1353
+ + "_o_" + std::to_string(out_element_size);
1354
+ std::shared_ptr<kp::Algorithm> s_algo = nullptr;
1355
+ if (!komputeManager()->hasAlgorithm(name))
1356
+ s_algo = komputeManager()->algorithm<float, PushConstants>(name, s_kompute_context->pool.get(), {in, out}, spirv, {unsigned(ne01), unsigned(ne02), unsigned(ne03)}, {}, {pushConsts});
1357
+ else {
1358
+ s_algo = komputeManager()->getAlgorithm(name);
1359
+ s_algo->setTensors({in, out});
1360
+ s_algo->setWorkgroup({unsigned(ne01), unsigned(ne02), unsigned(ne03)});
1361
+ s_algo->setPushConstants<PushConstants>({pushConsts});
1362
+ s_algo->updateDescriptors(s_kompute_context->pool.get());
1363
+ }
1364
+ seq.record<kp::OpAlgoDispatch>(s_algo);
1365
+ }
1366
+
1367
+ template <typename... Args>
1368
+ static void ggml_vk_cpy_f32_f16(Args&&... args) {
1369
+ const static auto spirv = getSpirvShader(kp::shader_data::op_cpy_f32_f16_comp_spv,
1370
+ kp::shader_data::op_cpy_f32_f16_comp_spv_len);
1371
+ ggml_vk_cpy(spirv, 4, 2, std::forward<Args>(args)...);
1372
+ }
1373
+
1374
+ template <typename... Args>
1375
+ static void ggml_vk_cpy_f32_f32(Args&&... args) {
1376
+ const static auto spirv = getSpirvShader(kp::shader_data::op_cpy_f32_f32_comp_spv,
1377
+ kp::shader_data::op_cpy_f32_f32_comp_spv_len);
1378
+ ggml_vk_cpy(spirv, 4, 4, std::forward<Args>(args)...);
1379
+ }
1380
+
1381
+ template <typename... Args>
1382
+ static void ggml_vk_cpy_f16_f16(Args&&... args) {
1383
+ const static auto spirv = getSpirvShader(kp::shader_data::op_cpy_f16_f16_comp_spv,
1384
+ kp::shader_data::op_cpy_f16_f16_comp_spv_len);
1385
+ ggml_vk_cpy(spirv, 2, 2, std::forward<Args>(args)...);
1386
+ }
1387
+
1388
+ template <typename... Args>
1389
+ static void ggml_vk_cpy_f16_f32(Args&&... args) {
1390
+ const static auto spirv = getSpirvShader(kp::shader_data::op_cpy_f16_f32_comp_spv,
1391
+ kp::shader_data::op_cpy_f16_f32_comp_spv_len);
1392
+ ggml_vk_cpy(spirv, 2, 4, std::forward<Args>(args)...);
1393
+ }
1394
+
1395
+ static bool ggml_backend_kompute_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) {
1396
+ int64_t n = ggml_nelements(op);
1397
+ switch (op->op) {
1398
+ case GGML_OP_UNARY:
1399
+ if (n % 4 != 0) return false;
1400
+ switch (ggml_get_unary_op(op)) {
1401
+ case GGML_UNARY_OP_GELU:
1402
+ if (n % 8 != 0) return false;
1403
+ // fall through
1404
+ case GGML_UNARY_OP_RELU:
1405
+ case GGML_UNARY_OP_SILU:
1406
+ return ggml_is_contiguous(op->src[0]);
1407
+ default:
1408
+ ;
1409
+ }
1410
+ break;
1411
+ case GGML_OP_NONE:
1412
+ case GGML_OP_RESHAPE:
1413
+ case GGML_OP_VIEW:
1414
+ case GGML_OP_TRANSPOSE:
1415
+ case GGML_OP_PERMUTE:
1416
+ case GGML_OP_ADD:
1417
+ case GGML_OP_MUL:
1418
+ case GGML_OP_SCALE:
1419
+ case GGML_OP_SOFT_MAX:
1420
+ case GGML_OP_RMS_NORM:
1421
+ case GGML_OP_NORM:
1422
+ return true;
1423
+ case GGML_OP_ROPE:
1424
+ {
1425
+ const int mode = ((const int32_t *) op->op_params)[2];
1426
+ if (mode & GGML_ROPE_TYPE_MROPE) {
1427
+ return false;
1428
+ }
1429
+ if (mode & GGML_ROPE_TYPE_VISION) {
1430
+ return false;
1431
+ }
1432
+ return true;
1433
+ }
1434
+ case GGML_OP_DUP:
1435
+ case GGML_OP_CPY:
1436
+ case GGML_OP_CONT:
1437
+ switch (op->src[0]->type) {
1438
+ case GGML_TYPE_F32:
1439
+ case GGML_TYPE_F16:
1440
+ break;
1441
+ default:
1442
+ return false;
1443
+ }
1444
+ switch (op->type) {
1445
+ case GGML_TYPE_F32:
1446
+ case GGML_TYPE_F16:
1447
+ break;
1448
+ default:
1449
+ return false;
1450
+ }
1451
+ return true;
1452
+ case GGML_OP_DIAG_MASK_INF:
1453
+ return op->ne[3] == 1;
1454
+ case GGML_OP_GET_ROWS:
1455
+ switch (op->src[0]->type) {
1456
+ case GGML_TYPE_F32:
1457
+ case GGML_TYPE_F16:
1458
+ case GGML_TYPE_Q4_0:
1459
+ case GGML_TYPE_Q4_1:
1460
+ case GGML_TYPE_Q6_K:
1461
+ return op->ne[2] == 1 && op->ne[3] == 1;
1462
+ default:
1463
+ ;
1464
+ }
1465
+ return false;
1466
+ case GGML_OP_MUL_MAT:
1467
+ if (op->src[1]->type != GGML_TYPE_F32 || ggml_is_transposed(op->src[0]) || ggml_is_transposed(op->src[1]))
1468
+ return false;
1469
+
1470
+ switch (op->src[0]->type) {
1471
+ case GGML_TYPE_F32:
1472
+ return op->ne[3] == 1;
1473
+ case GGML_TYPE_Q6_K:
1474
+ case GGML_TYPE_F16:
1475
+ case GGML_TYPE_Q8_0:
1476
+ case GGML_TYPE_Q4_0:
1477
+ case GGML_TYPE_Q4_1:
1478
+ case GGML_TYPE_Q4_K:
1479
+ return true;
1480
+ default:
1481
+ ;
1482
+ }
1483
+ default:
1484
+ ;
1485
+ }
1486
+ return false;
1487
+
1488
+ GGML_UNUSED(dev);
1489
+ }
1490
+
1491
+ static void ggml_vk_graph_compute(struct ggml_kompute_context * ctx, struct ggml_cgraph * gf) {
1492
+ const int n_seq = 8;
1493
+
1494
+ // FIXME: Figure out if we can somehow optimize the size of the pool... right now we're setting
1495
+ // it to the size of the graph, but I think it can be made smaller?
1496
+ ggml_vk_allocate_descriptor_pool(ctx, gf->n_nodes);
1497
+
1498
+ std::vector<std::shared_ptr<kp::Sequence>> sequences(n_seq);
1499
+
1500
+ for (auto& sequence : sequences) {
1501
+ sequence = komputeManager()->sequence();
1502
+ }
1503
+ for (int seq_idx = 0; seq_idx < n_seq; ++seq_idx) {
1504
+ const int n_nodes_per_seq = (gf->n_nodes + n_seq - 1) / n_seq;
1505
+
1506
+ auto& seq = *sequences[seq_idx];
1507
+
1508
+ const int node_start = (seq_idx + 0) * n_nodes_per_seq;
1509
+ const int node_end = std::min((seq_idx == n_seq - 1) ? gf->n_nodes : (seq_idx + 1) * n_nodes_per_seq, gf->n_nodes);
1510
+
1511
+ bool any_commands_recorded = false;
1512
+
1513
+ for (int i = node_start; i < node_end; ++i) {
1514
+ struct ggml_tensor * src0 = gf->nodes[i]->src[0];
1515
+ struct ggml_tensor * src1 = gf->nodes[i]->src[1];
1516
+ struct ggml_tensor * src2 = gf->nodes[i]->src[2]; GGML_UNUSED(src2);
1517
+ struct ggml_tensor * dst = gf->nodes[i];
1518
+ GGML_ASSERT(dst->data != nullptr);
1519
+
1520
+ if (ggml_is_empty(dst)) {
1521
+ continue;
1522
+ }
1523
+
1524
+ switch (dst->op) {
1525
+ case GGML_OP_NONE:
1526
+ case GGML_OP_RESHAPE:
1527
+ case GGML_OP_VIEW:
1528
+ case GGML_OP_TRANSPOSE:
1529
+ case GGML_OP_PERMUTE:
1530
+ continue; // noop -> next node
1531
+ default:
1532
+ break;
1533
+ }
1534
+
1535
+ any_commands_recorded = true;
1536
+
1537
+ const int32_t ne00 = src0 ? src0->ne[0] : 0;
1538
+ const int32_t ne01 = src0 ? src0->ne[1] : 0;
1539
+ const int32_t ne02 = src0 ? src0->ne[2] : 0;
1540
+ const int32_t ne03 = src0 ? src0->ne[3] : 0;
1541
+
1542
+ const uint32_t nb00 = src0 ? src0->nb[0] : 0;
1543
+ const uint32_t nb01 = src0 ? src0->nb[1] : 0;
1544
+ const uint32_t nb02 = src0 ? src0->nb[2] : 0;
1545
+ const uint32_t nb03 = src0 ? src0->nb[3] : 0;
1546
+
1547
+ const int32_t ne10 = src1 ? src1->ne[0] : 0;
1548
+ const int32_t ne11 = src1 ? src1->ne[1] : 0;
1549
+ const int32_t ne12 = src1 ? src1->ne[2] : 0;
1550
+ const int32_t ne13 = src1 ? src1->ne[3] : 0;
1551
+
1552
+ const uint32_t nb10 = src1 ? src1->nb[0] : 0;
1553
+ const uint32_t nb11 = src1 ? src1->nb[1] : 0;
1554
+ const uint32_t nb12 = src1 ? src1->nb[2] : 0;
1555
+ const uint32_t nb13 = src1 ? src1->nb[3] : 0;
1556
+
1557
+ const int32_t ne0 = dst ? dst->ne[0] : 0;
1558
+ const int32_t ne1 = dst ? dst->ne[1] : 0;
1559
+ const int32_t ne2 = dst ? dst->ne[2] : 0;
1560
+ // const int32_t ne3 = dst ? dst->ne[3] : 0;
1561
+
1562
+ const uint32_t nb0 = dst ? dst->nb[0] : 0;
1563
+ const uint32_t nb1 = dst ? dst->nb[1] : 0;
1564
+ const uint32_t nb2 = dst ? dst->nb[2] : 0;
1565
+ const uint32_t nb3 = dst ? dst->nb[3] : 0;
1566
+
1567
+ const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
1568
+ const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
1569
+ const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
1570
+
1571
+ const static std::shared_ptr<kp::Tensor> nullTensor = nullptr;
1572
+ uint32_t off_src0 = 0;
1573
+ uint32_t off_src1 = 0;
1574
+ uint32_t off_src2 = 0;
1575
+ uint32_t off_dst = 0;
1576
+ const std::shared_ptr<kp::Tensor>& id_src0 = src0 ? ggml_vk_get_tensor(src0, &off_src0) : nullTensor;
1577
+ const std::shared_ptr<kp::Tensor>& id_src1 = src1 ? ggml_vk_get_tensor(src1, &off_src1) : nullTensor;
1578
+ const std::shared_ptr<kp::Tensor>& id_src2 = src2 ? ggml_vk_get_tensor(src2, &off_src2) : nullTensor;
1579
+ const std::shared_ptr<kp::Tensor>& id_dst = dst ? ggml_vk_get_tensor(dst, &off_dst) : nullTensor;
1580
+
1581
+ switch (dst->op) {
1582
+ case GGML_OP_ADD:
1583
+ {
1584
+ if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) {
1585
+ // src1 is a row
1586
+ ggml_vk_addrow(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ggml_nelements(dst)/4, ne00);
1587
+ } else {
1588
+ ggml_vk_add(
1589
+ seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
1590
+ ne00, ne01, ne02, ne03,
1591
+ nb00, nb01, nb02, nb03,
1592
+ ne10, ne11, ne12, ne13,
1593
+ nb10, nb11, nb12, nb13,
1594
+ ne0,
1595
+ nb0, nb1, nb2, nb3
1596
+ );
1597
+ }
1598
+ } break;
1599
+ case GGML_OP_MUL:
1600
+ {
1601
+ ggml_vk_mul(
1602
+ seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
1603
+ ne00, ne01, ne02, ne03,
1604
+ nb00, nb01, nb02, nb03,
1605
+ ne10, ne11, ne12, ne13,
1606
+ nb10, nb11, nb12, nb13,
1607
+ ne0,
1608
+ nb0, nb1, nb2, nb3
1609
+ );
1610
+ } break;
1611
+ case GGML_OP_SCALE:
1612
+ {
1613
+ float scale; memcpy(&scale, dst->op_params, sizeof(float));
1614
+
1615
+ ggml_vk_scale(seq, id_src0, id_dst, off_src0, off_dst, ggml_nelements(dst), scale);
1616
+ } break;
1617
+ case GGML_OP_UNARY:
1618
+ {
1619
+ int64_t n = ggml_nelements(dst);
1620
+ GGML_ASSERT(n % 4 == 0);
1621
+ switch (ggml_get_unary_op(gf->nodes[i])) {
1622
+ case GGML_UNARY_OP_SILU:
1623
+ {
1624
+ ggml_vk_silu(seq, id_src0, id_dst, off_src0, off_dst, n/4);
1625
+ } break;
1626
+ case GGML_UNARY_OP_RELU:
1627
+ {
1628
+ ggml_vk_relu(seq, id_src0, id_dst, off_src0, off_dst, n/4);
1629
+ } break;
1630
+ case GGML_UNARY_OP_GELU:
1631
+ {
1632
+ GGML_ASSERT(n % 8 == 0);
1633
+ ggml_vk_gelu(seq, id_src0, id_dst, off_src0, off_dst, n/8);
1634
+ } break;
1635
+ default:
1636
+ {
1637
+ fprintf(stderr, "%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
1638
+ GGML_ABORT("fatal error");
1639
+ }
1640
+ }
1641
+ } break;
1642
+ case GGML_OP_SOFT_MAX:
1643
+ {
1644
+ float scale;
1645
+ float max_bias;
1646
+
1647
+ memcpy(&scale, (float *)dst->op_params + 0, sizeof(float));
1648
+ memcpy(&max_bias, (float *)dst->op_params + 1, sizeof(float));
1649
+
1650
+ #pragma message("TODO: add ggml_vk_soft_max() F16 src1 support")
1651
+ #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5021")
1652
+ GGML_ASSERT(!src1 || src1t == GGML_TYPE_F32);
1653
+
1654
+ const int64_t nrows_x = ggml_nrows(src0);
1655
+ const int64_t nrows_y = src0->ne[1];
1656
+
1657
+ const uint32_t n_head = nrows_x/nrows_y;
1658
+ const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head));
1659
+
1660
+ const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
1661
+ const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
1662
+
1663
+ ggml_vk_soft_max(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, ne01, ne02, ne03, scale, max_bias, m0, m1, n_head_log2);
1664
+ } break;
1665
+ case GGML_OP_DIAG_MASK_INF:
1666
+ {
1667
+ const int n_past = ((int32_t *)(dst->op_params))[0];
1668
+ ggml_vk_diag_mask_inf(seq, id_src0, id_dst, off_src0, off_dst, n_past, ne00, ne01, ne02);
1669
+ } break;
1670
+ case GGML_OP_NORM:
1671
+ {
1672
+ float eps;
1673
+ memcpy(&eps, dst->op_params, sizeof(float));
1674
+ ggml_vk_norm(seq, id_src0, id_dst, off_src0, off_dst, ne00, nb01, ggml_nrows(src0), eps);
1675
+ } break;
1676
+ case GGML_OP_RMS_NORM:
1677
+ {
1678
+ GGML_ASSERT(ne00 % 4 == 0);
1679
+
1680
+ float eps;
1681
+ memcpy(&eps, dst->op_params, sizeof(float));
1682
+ ggml_vk_rms_norm(seq, id_src0, id_dst, off_src0, off_dst, ne00, nb01, ggml_nrows(src0), eps);
1683
+ } break;
1684
+ case GGML_OP_MUL_MAT:
1685
+ {
1686
+ GGML_ASSERT(ne00 == ne10);
1687
+
1688
+ GGML_ASSERT(ne12 % ne02 == 0);
1689
+ GGML_ASSERT(ne13 % ne03 == 0);
1690
+
1691
+ const uint32_t r2 = ne12/ne02;
1692
+ const uint32_t r3 = ne13/ne03;
1693
+
1694
+ if (src1t != GGML_TYPE_F32) {
1695
+ fprintf(stderr, "%s: %s: Unsupported src1 type: %u/%u\n", __func__, ggml_op_name(dst->op), src0t, src1t);
1696
+ goto not_implemented;
1697
+ }
1698
+
1699
+ if (ggml_is_transposed(src0) ||
1700
+ ggml_is_transposed(src1)) {
1701
+ fprintf(stderr, "%s: %s: matmul on tranposed tensor not supported: %u/%u\n", __func__, ggml_op_name(dst->op), src0t, src1t);
1702
+ goto not_implemented;
1703
+ }
1704
+
1705
+ switch (src0t) {
1706
+ case GGML_TYPE_F32:
1707
+ ggml_vk_mul_mat_mat_f32(
1708
+ seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
1709
+ ne00, ne01, ne02, nb01, nb02, ne11, ne12, nb11, nb12, nb1, nb2
1710
+ );
1711
+ break;
1712
+ case GGML_TYPE_F16:
1713
+ ggml_vk_mul_mat_f16(
1714
+ seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
1715
+ ne00, ne01, ne02, nb00, nb01, nb02, nb03,
1716
+ ne10, ne11, ne12, ne13, nb10, nb11, nb12, nb13,
1717
+ ne0, ne1, r2, r3
1718
+ );
1719
+ break;
1720
+ case GGML_TYPE_Q8_0:
1721
+ ggml_vk_mul_mat_q8_0(
1722
+ seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
1723
+ ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1,
1724
+ nb01, nb02, nb03, nb11, nb12, nb13, r2, r3
1725
+ );
1726
+ break;
1727
+ case GGML_TYPE_Q4_0:
1728
+ ggml_vk_mul_mat_q4_0(
1729
+ seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
1730
+ ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1,
1731
+ nb01, nb02, nb03, nb11, nb12, nb13, r2, r3
1732
+ );
1733
+ break;
1734
+ case GGML_TYPE_Q4_1:
1735
+ ggml_vk_mul_mat_q4_1(
1736
+ seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
1737
+ ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1,
1738
+ nb01, nb02, nb03, nb11, nb12, nb13, r2, r3
1739
+ );
1740
+ break;
1741
+ case GGML_TYPE_Q4_K:
1742
+ ggml_vk_mul_mat_q4_k(
1743
+ seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
1744
+ ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1,
1745
+ nb01, nb02, nb03, nb11, nb12, nb13, r2, r3
1746
+ );
1747
+ break;
1748
+ case GGML_TYPE_Q6_K:
1749
+ ggml_vk_mul_mat_q6_k(
1750
+ seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst,
1751
+ ne00, ne01, ne02, ne10, ne11, ne12, ne13, ne0, ne1,
1752
+ nb01, nb02, nb03, nb11, nb12, nb13, r2, r3
1753
+ );
1754
+ break;
1755
+ default: {
1756
+ fprintf(stderr, "%s: %s: Unsupported quantization: %u/%u\n", __func__, ggml_op_name(dst->op), src0t, src1t);
1757
+ goto not_implemented;
1758
+ }
1759
+ }
1760
+
1761
+ } break;
1762
+ case GGML_OP_GET_ROWS:
1763
+ {
1764
+ if (src0t == GGML_TYPE_F32) {
1765
+ ggml_vk_get_rows_f32(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
1766
+ } else if (src0t == GGML_TYPE_F16) {
1767
+ ggml_vk_get_rows_f16(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
1768
+ } else if (src0t == GGML_TYPE_Q4_0) {
1769
+ ggml_vk_get_rows_q4_0(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
1770
+ } else if (src0t == GGML_TYPE_Q4_1) {
1771
+ ggml_vk_get_rows_q4_1(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
1772
+ } else if (src0t == GGML_TYPE_Q6_K) {
1773
+ ggml_vk_get_rows_q6_k(seq, id_src0, id_src1, id_dst, off_src0, off_src1, off_dst, ne00, nb01, nb1, ggml_nelements(src1));
1774
+ } else {
1775
+ fprintf(stderr, "%s: %s: Unsupported quantization: %u\n", __func__, ggml_op_name(dst->op), src0t);
1776
+ goto not_implemented;
1777
+ }
1778
+ } break;
1779
+ case GGML_OP_ROPE:
1780
+ {
1781
+ GGML_ASSERT(ne10 == ne02);
1782
+ GGML_ASSERT(src0t == dstt);
1783
+ // const int n_past = ((int32_t *) dst->op_params)[0];
1784
+ const int n_dims = ((int32_t *) dst->op_params)[1];
1785
+ const int mode = ((int32_t *) dst->op_params)[2];
1786
+ // skip 3, n_ctx used in GLM RoPE, unimplemented in Vulkan
1787
+ const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
1788
+
1789
+ const bool has_freq_factors = dst->src[2] != nullptr;
1790
+
1791
+ float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
1792
+ memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
1793
+ memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
1794
+ memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
1795
+ memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
1796
+ memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
1797
+ memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
1798
+ ggml_vk_rope(
1799
+ seq, id_src0, id_src1, id_src2, id_dst, off_src0, off_src1, off_src2, off_dst, src0t, n_dims, mode, n_ctx_orig,
1800
+ freq_base, freq_scale, has_freq_factors, ext_factor, attn_factor, beta_fast, beta_slow,
1801
+ ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, nb0, nb1, nb2, nb3
1802
+ );
1803
+ } break;
1804
+ case GGML_OP_DUP:
1805
+ case GGML_OP_CPY:
1806
+ case GGML_OP_CONT:
1807
+ {
1808
+ switch (src0t) {
1809
+ case GGML_TYPE_F32:
1810
+ {
1811
+ switch (dstt) {
1812
+ case GGML_TYPE_F16: ggml_vk_cpy_f32_f16(seq, id_src0, id_dst, off_src0, off_dst, ne00, ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, ne1, ne2, nb0, nb1, nb2, nb3); break;
1813
+ case GGML_TYPE_F32: ggml_vk_cpy_f32_f32(seq, id_src0, id_dst, off_src0, off_dst, ne00, ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, ne1, ne2, nb0, nb1, nb2, nb3); break;
1814
+ default: goto not_implemented;
1815
+ }
1816
+ } break;
1817
+ case GGML_TYPE_F16:
1818
+ {
1819
+ switch (dstt) {
1820
+ case GGML_TYPE_F16: ggml_vk_cpy_f16_f16(seq, id_src0, id_dst, off_src0, off_dst, ne00, ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, ne1, ne2, nb0, nb1, nb2, nb3); break;
1821
+ case GGML_TYPE_F32: ggml_vk_cpy_f16_f32(seq, id_src0, id_dst, off_src0, off_dst, ne00, ne01, ne02, ne03, nb00, nb01, nb02, nb03, ne0, ne1, ne2, nb0, nb1, nb2, nb3); break;
1822
+ default: goto not_implemented;
1823
+ } break;
1824
+ default: goto not_implemented;
1825
+ }
1826
+ }
1827
+ } break;
1828
+ default: goto not_implemented;
1829
+ }
1830
+ continue;
1831
+ not_implemented: {}
1832
+ fprintf(stderr, "%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
1833
+ //GGML_ABORT("fatal error");
1834
+ }
1835
+
1836
+ // Evaluate sequence
1837
+ if (any_commands_recorded) {
1838
+ seq.evalAsync();
1839
+ }
1840
+ }
1841
+
1842
+ // Wait for all sequences to finish
1843
+ for (auto& sequence : sequences) {
1844
+ if (sequence->isRunning())
1845
+ sequence->evalAwait();
1846
+ }
1847
+
1848
+ ggml_vk_free_descriptor_pool(ctx);
1849
+ }
1850
+
1851
+ template<>
1852
+ kp::Tensor::TensorDataTypes
1853
+ kp::TensorT<half>::dataType()
1854
+ {
1855
+ return TensorDataTypes::eFloat;
1856
+ }
1857
+
1858
+ template<>
1859
+ kp::Tensor::TensorDataTypes
1860
+ kp::TensorT<uint8_t>::dataType()
1861
+ {
1862
+ return TensorDataTypes::eUnsignedInt;
1863
+ }
1864
+
1865
+ ////////////////////////////////////////////////////////////////////////////////
1866
+
1867
+ // backend interface
1868
+
1869
+ struct ggml_backend_kompute_buffer_type_context {
1870
+ int device;
1871
+ int device_ref = 0;
1872
+ uint64_t buffer_alignment;
1873
+ uint64_t max_alloc;
1874
+ std::string name;
1875
+
1876
+ ggml_backend_kompute_buffer_type_context(int device, uint64_t buffer_alignment, uint64_t max_alloc)
1877
+ : device(device), buffer_alignment(buffer_alignment), max_alloc(max_alloc), name(ggml_kompute_format_name(device)) {}
1878
+ };
1879
+
1880
+ static void ggml_backend_kompute_device_ref(ggml_backend_buffer_type_t buft) {
1881
+ auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
1882
+
1883
+ if (!ctx->device_ref) {
1884
+ komputeManager()->initializeDevice(
1885
+ ctx->device, {}, {
1886
+ "VK_KHR_shader_float16_int8", "VK_KHR_8bit_storage",
1887
+ "VK_KHR_16bit_storage", "VK_KHR_shader_non_semantic_info"
1888
+ }
1889
+ );
1890
+ }
1891
+
1892
+ assert(ggml_vk_has_device());
1893
+ ctx->device_ref++;
1894
+ }
1895
+
1896
+ static void ggml_backend_kompute_device_unref(ggml_backend_buffer_type_t buft) {
1897
+ auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
1898
+
1899
+ assert(ctx->device_ref > 0);
1900
+
1901
+ ctx->device_ref--;
1902
+
1903
+ if (!ctx->device_ref) {
1904
+ komputeManager.destroy();
1905
+ }
1906
+ }
1907
+
1908
+ static void ggml_backend_kompute_buffer_free_buffer(ggml_backend_buffer_t buffer) {
1909
+ auto * memory = (ggml_vk_memory *)buffer->context;
1910
+ if (ggml_vk_has_device()) {
1911
+ ggml_vk_free_memory(*memory);
1912
+ }
1913
+ delete memory;
1914
+ }
1915
+
1916
+ static void * ggml_backend_kompute_buffer_get_base(ggml_backend_buffer_t buffer) {
1917
+ return ((ggml_vk_memory *)buffer->context)->data;
1918
+ }
1919
+
1920
+ static void ggml_backend_kompute_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
1921
+ GGML_UNUSED(buffer);
1922
+
1923
+ const auto res = ggml_vk_get_tensor(tensor);
1924
+ GGML_ASSERT(res);
1925
+
1926
+ memcpy((char *)tensor->data + offset, data, size);
1927
+
1928
+ komputeManager()->sequence()->eval<kp::OpTensorSyncDevice>({res});
1929
+ }
1930
+
1931
+ static void ggml_backend_kompute_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
1932
+ GGML_UNUSED(buffer);
1933
+
1934
+ const auto res = ggml_vk_get_tensor(tensor);
1935
+ GGML_ASSERT(res);
1936
+
1937
+ komputeManager()->sequence()->eval<kp::OpTensorSyncLocal>({res});
1938
+
1939
+ memcpy(data, (const char *)tensor->data + offset, size);
1940
+ }
1941
+
1942
+ static void ggml_backend_kompute_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
1943
+ auto * memory = (ggml_vk_memory *)buffer->context;
1944
+ memset(memory->data, value, buffer->size);
1945
+
1946
+ if (memory->stagingBuffer)
1947
+ komputeManager()->sequence()->eval<kp::OpBufferSyncDevice>(memory->primaryBuffer, memory->stagingBuffer, memory->size);
1948
+ }
1949
+
1950
+ static ggml_backend_buffer_i ggml_backend_kompute_buffer_i = {
1951
+ /* .free_buffer = */ ggml_backend_kompute_buffer_free_buffer,
1952
+ /* .get_base = */ ggml_backend_kompute_buffer_get_base,
1953
+ /* .init_tensor = */ NULL,
1954
+ /* .memset_tensor = */ NULL,
1955
+ /* .set_tensor = */ ggml_backend_kompute_buffer_set_tensor,
1956
+ /* .get_tensor = */ ggml_backend_kompute_buffer_get_tensor,
1957
+ /* .cpy_tensor = */ NULL,
1958
+ /* .clear = */ ggml_backend_kompute_buffer_clear,
1959
+ /* .reset = */ NULL,
1960
+ };
1961
+
1962
+ // default buffer type
1963
+
1964
+ static const char * ggml_backend_kompute_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
1965
+ auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
1966
+ return ctx->name.c_str();
1967
+ }
1968
+
1969
+ static ggml_backend_buffer_t ggml_backend_kompute_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
1970
+ ggml_backend_kompute_device_ref(buft);
1971
+ auto * ctx = new ggml_vk_memory(ggml_vk_allocate(size));
1972
+ return ggml_backend_buffer_init(buft, ggml_backend_kompute_buffer_i, ctx, size);
1973
+ }
1974
+
1975
+ static size_t ggml_backend_kompute_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
1976
+ auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
1977
+ return ctx->buffer_alignment;
1978
+ }
1979
+
1980
+ static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
1981
+ auto * ctx = static_cast<ggml_backend_kompute_buffer_type_context *>(buft->context);
1982
+ return ctx->max_alloc;
1983
+ }
1984
+
1985
+ static ggml_backend_buffer_type_i ggml_backend_kompute_buffer_type_interface = {
1986
+ /* .get_name = */ ggml_backend_kompute_buffer_type_get_name,
1987
+ /* .alloc_buffer = */ ggml_backend_kompute_buffer_type_alloc_buffer,
1988
+ /* .get_alignment = */ ggml_backend_kompute_buffer_type_get_alignment,
1989
+ /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
1990
+ /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
1991
+ /* .is_host = */ NULL,
1992
+ };
1993
+
1994
+ ggml_backend_buffer_type_t ggml_backend_kompute_buffer_type(int device) {
1995
+ static std::mutex mutex;
1996
+ std::lock_guard<std::mutex> lock(mutex);
1997
+
1998
+ auto devices = ggml_vk_available_devices();
1999
+ int32_t device_count = (int32_t) devices.size();
2000
+ GGML_ASSERT(device < device_count);
2001
+ GGML_ASSERT(devices.size() <= GGML_KOMPUTE_MAX_DEVICES);
2002
+
2003
+ static ggml_backend_buffer_type
2004
+ ggml_backend_kompute_buffer_types[GGML_KOMPUTE_MAX_DEVICES];
2005
+
2006
+ static bool ggml_backend_kompute_buffer_type_initialized = false;
2007
+
2008
+ if (!ggml_backend_kompute_buffer_type_initialized) {
2009
+ for (int32_t i = 0; i < device_count; i++) {
2010
+ ggml_backend_kompute_buffer_types[i] = {
2011
+ /* .iface = */ ggml_backend_kompute_buffer_type_interface,
2012
+ /* .device = */ ggml_backend_reg_dev_get(ggml_backend_kompute_reg(), i),
2013
+ /* .context = */ new ggml_backend_kompute_buffer_type_context{ i, devices[i].bufferAlignment, devices[i].maxAlloc },
2014
+ };
2015
+ }
2016
+ ggml_backend_kompute_buffer_type_initialized = true;
2017
+ }
2018
+
2019
+ return &ggml_backend_kompute_buffer_types[device];
2020
+ }
2021
+
2022
+ // backend
2023
+
2024
+ static const char * ggml_backend_kompute_name(ggml_backend_t backend) {
2025
+ auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
2026
+ return ctx->name.c_str();
2027
+ }
2028
+
2029
+ static void ggml_backend_kompute_free(ggml_backend_t backend) {
2030
+ auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
2031
+
2032
+ assert(ctx == s_kompute_context);
2033
+ s_kompute_context = nullptr;
2034
+ if (ctx != nullptr) {
2035
+ delete ctx;
2036
+ }
2037
+
2038
+ delete backend;
2039
+ }
2040
+
2041
+ static ggml_status ggml_backend_kompute_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
2042
+ auto * ctx = static_cast<ggml_kompute_context *>(backend->context);
2043
+ ggml_vk_graph_compute(ctx, cgraph);
2044
+ return GGML_STATUS_SUCCESS;
2045
+ }
2046
+
2047
+ static struct ggml_backend_i kompute_backend_i = {
2048
+ /* .get_name = */ ggml_backend_kompute_name,
2049
+ /* .free = */ ggml_backend_kompute_free,
2050
+ /* .set_tensor_async = */ NULL,
2051
+ /* .get_tensor_async = */ NULL,
2052
+ /* .cpy_tensor_async = */ NULL,
2053
+ /* .synchronize = */ NULL,
2054
+ /* .graph_plan_create = */ NULL,
2055
+ /* .graph_plan_free = */ NULL,
2056
+ /* .graph_plan_update = */ NULL,
2057
+ /* .graph_plan_compute = */ NULL,
2058
+ /* .graph_compute = */ ggml_backend_kompute_graph_compute,
2059
+ /* .event_record = */ NULL,
2060
+ /* .event_wait = */ NULL,
2061
+ };
2062
+
2063
+ static ggml_guid_t ggml_backend_kompute_guid() {
2064
+ static ggml_guid guid = { 0x7b, 0x57, 0xdc, 0xaf, 0xde, 0x12, 0x1d, 0x49, 0xfb, 0x35, 0xfa, 0x9b, 0x18, 0x31, 0x1d, 0xca };
2065
+ return &guid;
2066
+ }
2067
+
2068
+ ggml_backend_t ggml_backend_kompute_init(int device) {
2069
+ GGML_ASSERT(s_kompute_context == nullptr);
2070
+ s_kompute_context = new ggml_kompute_context(device);
2071
+
2072
+ ggml_backend_t kompute_backend = new ggml_backend {
2073
+ /* .guid = */ ggml_backend_kompute_guid(),
2074
+ /* .interface = */ kompute_backend_i,
2075
+ /* .device = */ ggml_backend_reg_dev_get(ggml_backend_kompute_reg(), device),
2076
+ /* .context = */ s_kompute_context,
2077
+ };
2078
+
2079
+ return kompute_backend;
2080
+ }
2081
+
2082
+ bool ggml_backend_is_kompute(ggml_backend_t backend) {
2083
+ return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_kompute_guid());
2084
+ }
2085
+
2086
+ static size_t ggml_backend_kompute_get_device_count() {
2087
+ auto devices = ggml_vk_available_devices();
2088
+ return devices.size();
2089
+ }
2090
+
2091
+ static void ggml_backend_kompute_get_device_description(int device, char * description, size_t description_size) {
2092
+ auto devices = ggml_vk_available_devices();
2093
+ GGML_ASSERT((size_t) device < devices.size());
2094
+ snprintf(description, description_size, "%s", devices[device].name);
2095
+ }
2096
+
2097
+ static void ggml_backend_kompute_get_device_memory(int device, size_t * free, size_t * total) {
2098
+ auto devices = ggml_vk_available_devices();
2099
+ GGML_ASSERT((size_t) device < devices.size());
2100
+ *total = devices[device].heapSize;
2101
+ *free = devices[device].heapSize;
2102
+ }
2103
+
2104
+ //////////////////////////
2105
+
2106
+ struct ggml_backend_kompute_device_context {
2107
+ int device;
2108
+ std::string name;
2109
+ std::string description;
2110
+ };
2111
+
2112
+ static const char * ggml_backend_kompute_device_get_name(ggml_backend_dev_t dev) {
2113
+ ggml_backend_kompute_device_context * ctx = (ggml_backend_kompute_device_context *)dev->context;
2114
+ return ctx->name.c_str();
2115
+ }
2116
+
2117
+ static const char * ggml_backend_kompute_device_get_description(ggml_backend_dev_t dev) {
2118
+ ggml_backend_kompute_device_context * ctx = (ggml_backend_kompute_device_context *)dev->context;
2119
+ return ctx->description.c_str();
2120
+ }
2121
+
2122
+ static void ggml_backend_kompute_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) {
2123
+ ggml_backend_kompute_device_context * ctx = (ggml_backend_kompute_device_context *)dev->context;
2124
+ ggml_backend_kompute_get_device_memory(ctx->device, free, total);
2125
+ }
2126
+
2127
+ static ggml_backend_buffer_type_t ggml_backend_kompute_device_get_buffer_type(ggml_backend_dev_t dev) {
2128
+ ggml_backend_kompute_device_context * ctx = (ggml_backend_kompute_device_context *)dev->context;
2129
+ return ggml_backend_kompute_buffer_type(ctx->device);
2130
+ }
2131
+
2132
+ static bool ggml_backend_kompute_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
2133
+ if (buft->iface.get_name != ggml_backend_kompute_buffer_type_get_name) {
2134
+ return false;
2135
+ }
2136
+
2137
+ ggml_backend_kompute_device_context * ctx = (ggml_backend_kompute_device_context *)dev->context;
2138
+ ggml_backend_kompute_buffer_type_context * buft_ctx = (ggml_backend_kompute_buffer_type_context *)buft->context;
2139
+
2140
+ return buft_ctx->device == ctx->device;
2141
+ }
2142
+
2143
+ static enum ggml_backend_dev_type ggml_backend_kompute_device_get_type(ggml_backend_dev_t dev) {
2144
+ GGML_UNUSED(dev);
2145
+ return GGML_BACKEND_DEVICE_TYPE_GPU;
2146
+ }
2147
+
2148
+ static void ggml_backend_kompute_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
2149
+ props->name = ggml_backend_kompute_device_get_name(dev);
2150
+ props->description = ggml_backend_kompute_device_get_description(dev);
2151
+ props->type = ggml_backend_kompute_device_get_type(dev);
2152
+ ggml_backend_kompute_device_get_memory(dev, &props->memory_free, &props->memory_total);
2153
+ props->caps = {
2154
+ /* async = */ false,
2155
+ /* host_buffer = */ false,
2156
+ /* .buffer_from_host_ptr = */ false,
2157
+ /* events = */ false,
2158
+ };
2159
+ }
2160
+
2161
+ static ggml_backend_t ggml_backend_kompute_device_init(ggml_backend_dev_t dev, const char * params) {
2162
+ GGML_UNUSED(params);
2163
+ ggml_backend_kompute_device_context * ctx = (ggml_backend_kompute_device_context *)dev->context;
2164
+ return ggml_backend_kompute_init(ctx->device);
2165
+ }
2166
+
2167
+ static bool ggml_backend_kompute_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
2168
+ const int min_batch_size = 32;
2169
+
2170
+ return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
2171
+ (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
2172
+
2173
+ GGML_UNUSED(dev);
2174
+ }
2175
+
2176
+ static const struct ggml_backend_device_i ggml_backend_kompute_device_i = {
2177
+ /* .get_name = */ ggml_backend_kompute_device_get_name,
2178
+ /* .get_description = */ ggml_backend_kompute_device_get_description,
2179
+ /* .get_memory = */ ggml_backend_kompute_device_get_memory,
2180
+ /* .get_type = */ ggml_backend_kompute_device_get_type,
2181
+ /* .get_props = */ ggml_backend_kompute_device_get_props,
2182
+ /* .init_backend = */ ggml_backend_kompute_device_init,
2183
+ /* .get_buffer_type = */ ggml_backend_kompute_device_get_buffer_type,
2184
+ /* .get_host_buffer_type = */ NULL,
2185
+ /* .buffer_from_host_ptr = */ NULL,
2186
+ /* .supports_op = */ ggml_backend_kompute_device_supports_op,
2187
+ /* .supports_buft = */ ggml_backend_kompute_device_supports_buft,
2188
+ /* .offload_op = */ ggml_backend_kompute_device_offload_op,
2189
+ /* .event_new = */ NULL,
2190
+ /* .event_free = */ NULL,
2191
+ /* .event_synchronize = */ NULL,
2192
+ };
2193
+
2194
+ static const char * ggml_backend_kompute_reg_get_name(ggml_backend_reg_t reg) {
2195
+ GGML_UNUSED(reg);
2196
+ return "Kompute";
2197
+ }
2198
+
2199
+ static size_t ggml_backend_kompute_reg_get_device_count(ggml_backend_reg_t reg) {
2200
+ GGML_UNUSED(reg);
2201
+ return ggml_backend_kompute_get_device_count();
2202
+ }
2203
+
2204
+ static ggml_backend_dev_t ggml_backend_kompute_reg_get_device(ggml_backend_reg_t reg, size_t device) {
2205
+ static std::vector<ggml_backend_dev_t> devices;
2206
+
2207
+ static bool initialized = false;
2208
+
2209
+ {
2210
+ static std::mutex mutex;
2211
+ std::lock_guard<std::mutex> lock(mutex);
2212
+ if (!initialized) {
2213
+ for (size_t i = 0; i < ggml_backend_kompute_get_device_count(); i++) {
2214
+ ggml_backend_kompute_device_context * ctx = new ggml_backend_kompute_device_context;
2215
+ char desc[256];
2216
+ ggml_backend_kompute_get_device_description(i, desc, sizeof(desc));
2217
+ ctx->device = i;
2218
+ ctx->name = "Kompute" + std::to_string(i);
2219
+ ctx->description = desc;
2220
+ devices.push_back(new ggml_backend_device {
2221
+ /* .iface = */ ggml_backend_kompute_device_i,
2222
+ /* .reg = */ reg,
2223
+ /* .context = */ ctx,
2224
+ });
2225
+ }
2226
+ initialized = true;
2227
+ }
2228
+ }
2229
+
2230
+ GGML_ASSERT(device < devices.size());
2231
+ return devices[device];
2232
+ }
2233
+
2234
+ static const struct ggml_backend_reg_i ggml_backend_kompute_reg_i = {
2235
+ /* .get_name = */ ggml_backend_kompute_reg_get_name,
2236
+ /* .get_device_count = */ ggml_backend_kompute_reg_get_device_count,
2237
+ /* .get_device = */ ggml_backend_kompute_reg_get_device,
2238
+ /* .get_proc_address = */ NULL,
2239
+ };
2240
+
2241
+ ggml_backend_reg_t ggml_backend_kompute_reg() {
2242
+ static ggml_backend_reg reg = {
2243
+ /* .api_version = */ GGML_BACKEND_API_VERSION,
2244
+ /* .iface = */ ggml_backend_kompute_reg_i,
2245
+ /* .context = */ nullptr,
2246
+ };
2247
+
2248
+ return &reg;
2249
+ }
2250
+
2251
+ GGML_BACKEND_DL_IMPL(ggml_backend_kompute_reg)