interplane.Get Omega
Read in your language

ggml

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

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-cuda / ggml-cuda.cu

6592 lines · 275325 bytes Raw Blame History
1#include "ggml-cuda.h"
2#include "ggml-impl.h"
3#include "ggml-backend-impl.h"
4
5#include "ggml-cuda/allreduce.cuh"
6#include "ggml-cuda/common.cuh"
7#include "ggml-cuda/acc.cuh"
8#include "ggml-cuda/add-id.cuh"
9#include "ggml-cuda/arange.cuh"
10#include "ggml-cuda/argmax.cuh"
11#include "ggml-cuda/argsort.cuh"
12#include "ggml-cuda/batch-get.cuh"
13#include "ggml-cuda/binbcast.cuh"
14#include "ggml-cuda/clamp.cuh"
15#include "ggml-cuda/col2im-1d.cuh"
16#include "ggml-cuda/concat.cuh"
17#include "ggml-cuda/conv-transpose-1d.cuh"
18#include "ggml-cuda/conv2d.cuh"
19#include "ggml-cuda/conv2d-dw.cuh"
20#include "ggml-cuda/conv2d-transpose.cuh"
21#include "ggml-cuda/conv3d.cuh"
22#include "ggml-cuda/convert.cuh"
23#include "ggml-cuda/count-equal.cuh"
24#include "ggml-cuda/cpy.cuh"
25#include "ggml-cuda/cross-entropy-loss.cuh"
26#include "ggml-cuda/cumsum.cuh"
27#include "ggml-cuda/diagmask.cuh"
28#include "ggml-cuda/diag.cuh"
29#include "ggml-cuda/fattn.cuh"
30#include "ggml-cuda/fwht.cuh"
31#include "ggml-cuda/getrows.cuh"
32#include "ggml-cuda/im2col.cuh"
33#include "ggml-cuda/mmf.cuh"
34#include "ggml-cuda/mmq.cuh"
35#include "ggml-cuda/mmvf.cuh"
36#include "ggml-cuda/mmvq.cuh"
37#include "ggml-cuda/moe-weighted-reduction.cuh"
38#include "ggml-cuda/norm.cuh"
39#include "ggml-cuda/opt-step-adamw.cuh"
40#include "ggml-cuda/opt-step-sgd.cuh"
41#include "ggml-cuda/out-prod.cuh"
42#include "ggml-cuda/pad.cuh"
43#include "ggml-cuda/pool2d.cuh"
44#include "ggml-cuda/pool1d.cuh"
45#include "ggml-cuda/quantize.cuh"
46#include "ggml-cuda/rope.cuh"
47#include "ggml-cuda/roll.cuh"
48#include "ggml-cuda/scale.cuh"
49#include "ggml-cuda/snake.cuh"
50#include "ggml-cuda/softcap.cuh"
51#include "ggml-cuda/softmax.cuh"
52#include "ggml-cuda/ssm-conv.cuh"
53#include "ggml-cuda/ssm-scan.cuh"
54#include "ggml-cuda/sum.cuh"
55#include "ggml-cuda/sumrows.cuh"
56#include "ggml-cuda/top-k.cuh"
57#include "ggml-cuda/mean.cuh"
58#include "ggml-cuda/tsembd.cuh"
59#include "ggml-cuda/topk-moe.cuh"
60#include "ggml-cuda/unary.cuh"
61#include "ggml-cuda/upscale.cuh"
62#include "ggml-cuda/wkv.cuh"
63#include "ggml-cuda/gla.cuh"
64#include "ggml-cuda/gated_delta_net.cuh"
65#include "ggml-cuda/dsv4-hc.cuh"
66#include "ggml-cuda/set.cuh"
67#include "ggml-cuda/set-rows.cuh"
68#include "ggml-cuda/pad_reflect_1d.cuh"
69#include "ggml-cuda/solve_tri.cuh"
70#include "ggml-cuda/tri.cuh"
71#include "ggml-cuda/cumsum.cuh"
72#include "ggml-cuda/fill.cuh"
73#include "ggml-cuda/lightning-indexer.cuh"
74#include "ggml-cuda/top-k-mask.cuh"
75#include "ggml.h"
76
77#include <algorithm>
78#include <array>
79#include <atomic>
80#include <charconv>
81#include <cinttypes>
82#include <condition_variable>
83#include <cstddef>
84#include <cstdint>
85#include <cfloat>
86#include <initializer_list>
87#include <limits>
88#include <map>
89#include <memory>
90#include <mutex>
91#include <cstdarg>
92#include <cstdio>
93#include <cstdlib>
94#include <string>
95#include <vector>
96
97static_assert(sizeof(half) == sizeof(ggml_fp16_t), "wrong fp16 size");
98
99#define GGML_LOG_WARN_ONCE(str) \
100 { static std::once_flag warn_flag; std::call_once(warn_flag, []() { GGML_LOG_WARN(str); }); }
101
102[[noreturn]]
103void ggml_cuda_error(const char * stmt, const char * func, const char * file, int line, const char * msg) {
104 int id = -1; // in case cudaGetDevice fails
105 (void)cudaGetDevice(&id);
106
107 GGML_LOG_ERROR(GGML_CUDA_NAME " error: %s\n", msg);
108 GGML_LOG_ERROR(" current device: %d, in function %s at %s:%d\n", id, func, file, line);
109 GGML_LOG_ERROR(" %s\n", stmt);
110 // abort with GGML_ABORT to get a stack trace
111 GGML_ABORT(GGML_CUDA_NAME " error");
112}
113
114// map a (possibly virtual) device id to the physical CUDA device that backs it
115static int ggml_cuda_get_physical_device(int device) {
116 const ggml_cuda_device_info & info = ggml_cuda_info();
117 GGML_ASSERT(device >= 0 && device < info.device_count);
118 return info.devices[device].physical_device;
119}
120
121// this is faster on Windows
122// probably because the Windows CUDA libraries forget to make this check before invoking the drivers
123void ggml_cuda_set_device(int device) {
124 // translate the (possibly virtual) device id to the physical CUDA device that backs it
125 const int physical_device = ggml_cuda_get_physical_device(device);
126
127 int current_device;
128 CUDA_CHECK(cudaGetDevice(&current_device));
129
130 if (physical_device == current_device) {
131 return;
132 }
133
134 CUDA_CHECK(cudaSetDevice(physical_device));
135}
136
137int ggml_cuda_get_device() {
138 int id;
139 CUDA_CHECK(cudaGetDevice(&id));
140 return id;
141}
142
143static bool ggml_cuda_env_flag(const char * name) {
144 const char * env = getenv(name);
145 return env != nullptr && std::atoi(env) != 0;
146}
147
148static int ggml_cuda_env_int(const char * name, int default_value) {
149 const char * env = getenv(name);
150 return env != nullptr ? std::atoi(env) : default_value;
151}
152
153static bool ggml_cuda_env_set(const char * name) {
154 return getenv(name) != nullptr;
155}
156
157static bool ggml_cuda_unified_memory_enabled() {
158 static const bool enabled = ggml_cuda_env_flag("GGML_CUDA_ENABLE_UNIFIED_MEMORY");
159 return enabled;
160}
161
162static bool ggml_cuda_pinned_memory_disabled() {
163 static const bool disabled = ggml_cuda_env_flag("GGML_CUDA_NO_PINNED");
164 return disabled;
165}
166
167static bool ggml_cuda_register_host_enabled() {
168 static const bool enabled = ggml_cuda_env_flag("GGML_CUDA_REGISTER_HOST");
169 return enabled;
170}
171
172static bool ggml_cuda_fusion_disabled() {
173 static const bool disabled = ggml_cuda_env_flag("GGML_CUDA_DISABLE_FUSION");
174 return disabled;
175}
176
177static bool ggml_cuda_p2p_enabled() {
178 static const bool enabled = ggml_cuda_env_set("GGML_CUDA_P2P");
179 return enabled;
180}
181
182static int ggml_cuda_op_offload_min_batch() {
183 static const int min_batch = ggml_cuda_env_int("GGML_OP_OFFLOAD_MIN_BATCH", 32);
184 return min_batch;
185}
186
187static cudaError_t ggml_cuda_device_malloc(void ** ptr, size_t size, int device) {
188 ggml_cuda_set_device(device);
189 cudaError_t err;
190 if (ggml_cuda_unified_memory_enabled()) {
191 err = cudaMallocManaged(ptr, size);
192#if defined(GGML_USE_HIP)
193 if (err == hipSuccess) {
194 // hipMemAdviseSetCoarseGrain is an optional performance hint;
195 // ignore errors (e.g. hipErrorInvalidValue on some APU/iGPU configs).
196 (void)cudaMemAdvise(*ptr, size, hipMemAdviseSetCoarseGrain, device);
197 (void)hipGetLastError(); // clear any error
198 }
199
200 // fall back to cudaMalloc if not supported (e.g. on Windows)
201 if (err == hipErrorNotSupported) {
202 static bool warned_unsupported = false;
203 if (!warned_unsupported) {
204 GGML_LOG_WARN("hipMallocManaged unsupported, falling back to hipMalloc.\n");
205 warned_unsupported = true;
206 }
207
208 err = cudaMalloc(ptr, size);
209 }
210#endif // defined(GGML_USE_HIP)
211 } else {
212 err = cudaMalloc(ptr, size);
213 }
214 return err;
215}
216
217#if defined(GGML_USE_HIP)
218static int ggml_cuda_parse_id(const char * devName) {
219 // A list of possible Target IDs can be found under the rocclr/clr repo in device.cpp
220 // these values are not stable so this is susceptible to breakage
221 // https://github.com/ROCm/clr/blob/amd-staging/rocclr/device/device.cpp
222 // Extract the base architecture model ("gfx908:sramecc+:xnack-" -> "908")
223 std::string archName = devName;
224 archName.erase(0, 3);
225 archName = archName.substr(0, archName.find(':'));
226
227 const auto hex = [](const std::string & s) { return (int) strtoul(s.c_str(), nullptr, 16); };
228
229 int cc = 0;
230
231 // tease out the version information
232 if (archName.size() > 8) {
233 // versions labeled generic use '-' as delimiter
234 if (archName.compare(archName.size() - 8, 8, "-generic") == 0) {
235 archName.resize(archName.size() - 8);
236 const size_t sep = archName.find('-');
237 cc = 0x100 * hex(archName.substr(0, sep));
238 if (sep != std::string::npos) {
239 cc += 0x10 * hex(archName.substr(sep + 1));
240 }
241 }
242 } else if (archName.size() >= 3) {
243 // ordinary IDs are the version in hex
244 cc = hex(archName);
245 }
246
247 return GGML_CUDA_CC_OFFSET_AMD + cc;
248}
249#endif // defined(GGML_USE_HIP)
250
251static ggml_cuda_device_info ggml_cuda_init() {
252 ggml_cuda_device_info info = {};
253
254 cudaError_t err = cudaGetDeviceCount(&info.physical_device_count);
255 if (err != cudaSuccess) {
256 GGML_LOG_ERROR("%s: failed to initialize " GGML_CUDA_NAME ": %s\n", __func__, cudaGetErrorString(err));
257 return info;
258 }
259
260 GGML_ASSERT(info.physical_device_count <= GGML_CUDA_MAX_DEVICES);
261
262 // by default expose exactly the physical devices; GGML_CUDA_DEVICES can request a different
263 // number of (virtual) devices to emulate multi-GPU systems on a machine with fewer GPUs
264 info.device_count = info.physical_device_count;
265
266 const char * devices_env = getenv("GGML_CUDA_DEVICES");
267 if (devices_env != nullptr && info.physical_device_count > 0) {
268 const int requested = atoi(devices_env);
269 if (requested > 0) {
270 info.device_count = requested;
271 } else {
272 GGML_LOG_WARN("%s: ignoring invalid GGML_CUDA_DEVICES=\"%s\"\n", __func__, devices_env);
273 }
274 }
275
276 if (info.device_count > GGML_CUDA_MAX_DEVICES) {
277 GGML_LOG_WARN("%s: requested %d devices, clamping to GGML_CUDA_MAX_DEVICES=%d\n",
278 __func__, info.device_count, GGML_CUDA_MAX_DEVICES);
279 info.device_count = GGML_CUDA_MAX_DEVICES;
280 }
281
282 // map each (virtual) device to a backing physical device (round-robin), assign each its index
283 // among the (virtual) devices sharing that physical GPU, and store the per-physical share count
284 int physical_share_count[GGML_CUDA_MAX_DEVICES] = {};
285 GGML_ASSERT(info.device_count == 0 || info.physical_device_count > 0);
286 for (int id = 0; id < info.device_count; ++id) {
287 info.devices[id].physical_device = id % info.physical_device_count;
288 info.devices[id].virtual_index = physical_share_count[info.devices[id].physical_device]++;
289 }
290
291 int64_t total_vram = 0;
292 for (int id = 0; id < info.physical_device_count; ++id) {
293 cudaDeviceProp prop;
294 CUDA_CHECK(cudaGetDeviceProperties(&prop, id));
295 total_vram += prop.totalGlobalMem;
296 }
297 GGML_LOG_INFO("%s: found %d " GGML_CUDA_NAME " devices (Total VRAM: %zu MiB):\n",
298 __func__, info.physical_device_count, (size_t)(total_vram / (1024 * 1024)));
299 if (info.device_count != info.physical_device_count) {
300 GGML_LOG_INFO("%s: emulating %d virtual device(s) on %d physical device(s) (GGML_CUDA_DEVICES)\n",
301 __func__, info.device_count, info.physical_device_count);
302 }
303 total_vram = 0;
304
305 std::vector<std::pair<int, std::string>> turing_devices_without_mma;
306 for (int id = 0; id < info.device_count; ++id) {
307 const int physical_id = info.devices[id].physical_device;
308
309 int device_vmm = 0;
310
311#if defined(GGML_USE_VMM)
312 CUdevice device;
313 CU_CHECK(cuDeviceGet(&device, physical_id));
314 CU_CHECK(cuDeviceGetAttribute(&device_vmm, CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, device));
315
316 if (device_vmm) {
317 CUmemAllocationProp alloc_prop = {};
318 alloc_prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
319 alloc_prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
320 alloc_prop.location.id = physical_id;
321 CU_CHECK(cuMemGetAllocationGranularity(&info.devices[id].vmm_granularity, &alloc_prop, CU_MEM_ALLOC_GRANULARITY_RECOMMENDED));
322 }
323#endif // defined(GGML_USE_VMM)
324 info.devices[id].vmm = !!device_vmm;
325
326 cudaDeviceProp prop;
327 CUDA_CHECK(cudaGetDeviceProperties(&prop, physical_id));
328
329 // a virtual device owns only a share of its physical GPU's memory; report that share so the
330 // logged per-device VRAM sums to the physical total above.
331 GGML_ASSERT(physical_share_count[physical_id] > 0);
332 info.devices[id].physical_share_count = physical_share_count[physical_id];
333 const size_t device_vram = prop.totalGlobalMem / info.devices[id].physical_share_count;
334 const size_t device_vram_mib = device_vram / (1024 * 1024);
335
336 info.default_tensor_split[id] = total_vram;
337 total_vram += device_vram;
338 info.devices[id].integrated = false; // Temporarily disabled due to issues with corrupted output (e.g. #15034)
339 info.devices[id].nsm = prop.multiProcessorCount;
340 info.devices[id].smpb = prop.sharedMemPerBlock;
341 info.devices[id].warp_size = prop.warpSize;
342
343 int supports_coop_launch = 0;
344 CUDA_CHECK(cudaDeviceGetAttribute(&supports_coop_launch, cudaDevAttrCooperativeLaunch, physical_id));
345 info.devices[id].supports_cooperative_launch = !!supports_coop_launch;
346
347#if defined(GGML_USE_HIP)
348 info.devices[id].smpbo = prop.sharedMemPerBlock;
349
350 info.devices[id].cc = ggml_cuda_parse_id(prop.gcnArchName);
351 if ((info.devices[id].cc & 0xff00) == 0x0) {
352 GGML_LOG_WARN("invalid architecture ID received for device %d %s: %s cc %d.%d\n",
353 id, prop.name, prop.gcnArchName, prop.major, prop.minor);
354
355 // Fallback to prop.major and prop.minor
356 if (prop.major > 0) {
357 info.devices[id].cc = GGML_CUDA_CC_OFFSET_AMD + prop.major * 0x100;
358 info.devices[id].cc += prop.minor * 0x10;
359 }
360 }
361 GGML_LOG_INFO(" Device %d: %s, %s (0x%x), VMM: %s, Wave Size: %d, VRAM: %zu MiB\n",
362 id, prop.name, prop.gcnArchName, info.devices[id].cc & 0xffff,
363 device_vmm ? "yes" : "no", prop.warpSize,
364 device_vram_mib);
365#elif defined(GGML_USE_MUSA)
366 info.devices[id].smpbo = prop.sharedMemPerBlockOptin;
367 info.devices[id].cc = GGML_CUDA_CC_OFFSET_MTHREADS + prop.major * 0x100;
368 info.devices[id].cc += prop.minor * 0x10;
369 GGML_LOG_INFO(" Device %d: %s, compute capability %d.%d, VMM: %s, VRAM: %zu MiB\n",
370 id, prop.name, prop.major, prop.minor, device_vmm ? "yes" : "no",
371 device_vram_mib);
372#else
373 info.devices[id].smpbo = prop.sharedMemPerBlockOptin;
374 info.devices[id].cc = 100*prop.major + 10*prop.minor;
375 GGML_LOG_INFO(" Device %d: %s, compute capability %d.%d, VMM: %s, VRAM: %zu MiB\n",
376 id, prop.name, prop.major, prop.minor, device_vmm ? "yes" : "no",
377 device_vram_mib);
378 std::string device_name(prop.name);
379 if (device_name == "NVIDIA GeForce MX450") {
380 turing_devices_without_mma.push_back({ id, device_name });
381 } else if (device_name == "NVIDIA GeForce MX550") {
382 turing_devices_without_mma.push_back({ id, device_name });
383 } else if (device_name.substr(0, 21) == "NVIDIA GeForce GTX 16") {
384 turing_devices_without_mma.push_back({ id, device_name });
385 }
386
387 // Temporary performance fix:
388 // Setting device scheduling strategy for iGPUs with cc121 to "spinning" to avoid delays in cuda synchronize calls.
389 // TODO: Check for future drivers the default scheduling strategy and
390 // remove this call again when cudaDeviceScheduleSpin is default.
391 if (prop.major == 12 && prop.minor == 1) {
392 CUDA_CHECK(cudaSetDevice(physical_id));
393 CUDA_CHECK(cudaSetDeviceFlags(cudaDeviceScheduleSpin));
394 }
395
396#endif // defined(GGML_USE_HIP)
397 }
398
399 if (ggml_cuda_highest_compiled_arch(GGML_CUDA_CC_TURING) >= GGML_CUDA_CC_TURING && !turing_devices_without_mma.empty()) {
400 GGML_LOG_INFO("The following devices will have suboptimal performance due to a lack of tensor cores:\n");
401 for (size_t device_pos = 0; device_pos < turing_devices_without_mma.size(); device_pos++) {
402 GGML_LOG_INFO(
403 " Device %d: %s\n", turing_devices_without_mma[device_pos].first, turing_devices_without_mma[device_pos].second.c_str());
404 }
405 GGML_LOG_INFO(
406 "Consider compiling with CMAKE_CUDA_ARCHITECTURES=61-virtual;80-virtual and DGGML_CUDA_FORCE_MMQ to force the use of the Pascal code for Turing.\n");
407 }
408
409 for (int id = 0; id < info.device_count; ++id) {
410 info.default_tensor_split[id] /= total_vram;
411 }
412
413 // configure logging to stdout
414 // CUBLAS_CHECK(cublasLoggerConfigure(1, 1, 0, nullptr));
415
416 if (ggml_cuda_p2p_enabled()) {
417 for (int id = 0; id < info.physical_device_count; ++id) {
418 CUDA_CHECK(cudaSetDevice(id));
419 for (int id_other = 0; id_other < info.physical_device_count; ++id_other) {
420 if (id == id_other) {
421 continue;
422 }
423 int can_access_peer;
424 CUDA_CHECK(cudaDeviceCanAccessPeer(&can_access_peer, id, id_other));
425 if (can_access_peer) {
426 CUDA_CHECK(cudaDeviceEnablePeerAccess(id_other, 0));
427 }
428 }
429 }
430 }
431
432 return info;
433}
434
435const ggml_cuda_device_info & ggml_cuda_info() {
436 static ggml_cuda_device_info info = ggml_cuda_init();
437 return info;
438}
439
440// #define DEBUG_CUDA_MALLOC
441
442// buffer pool for cuda (legacy)
443struct ggml_cuda_pool_leg : public ggml_cuda_pool {
444 static const int MAX_BUFFERS = 256;
445
446 ggml_backend_cuda_context & ctx;
447 int device;
448 struct ggml_cuda_buffer {
449 void * ptr = nullptr;
450 size_t size = 0;
451 };
452
453 ggml_cuda_buffer buffer_pool[MAX_BUFFERS] = {};
454 size_t pool_size = 0;
455
456 ggml_cuda_pool_leg(ggml_backend_cuda_context & ctx, int device) :
457 ctx(ctx),
458 device(device) {
459 }
460
461 ~ggml_cuda_pool_leg() {
462 clear_pool();
463 GGML_ASSERT(pool_size == 0);
464 }
465
466 void clear_pool() {
467 ggml_cuda_set_device(device);
468 for (int i = 0; i < MAX_BUFFERS; ++i) {
469 ggml_cuda_buffer & b = buffer_pool[i];
470 if (b.ptr != nullptr) {
471 CUDA_CHECK(cudaFree(b.ptr));
472 pool_size -= b.size;
473 b.ptr = nullptr;
474 b.size = 0;
475 }
476 }
477 }
478
479 // captured CUDA graphs can still use freed buffers, so they must be captured again
480 void invalidate_cuda_graphs() {
481#ifdef USE_CUDA_GRAPH
482 int n_captured = 0;
483 for (const auto & [key, graph] : ctx.cuda_graphs) {
484 n_captured += graph->instances.size();
485 }
486 if (n_captured > 0) {
487 GGML_LOG_DEBUG(GGML_CUDA_NAME " pool[%d]: memory freed, %d captured CUDA graphs must be captured again\n", device, n_captured);
488 }
489 ctx.cuda_graphs.clear();
490#endif // USE_CUDA_GRAPH
491 }
492
493 void * alloc(size_t size, size_t * actual_size) override {
494#ifdef DEBUG_CUDA_MALLOC
495 int nnz = 0;
496 size_t max_size = 0;
497#endif
498 size_t best_diff = 1ull << 36;
499 int ibest = -1;
500 for (int i = 0; i < MAX_BUFFERS; ++i) {
501 ggml_cuda_buffer& b = buffer_pool[i];
502 if (b.ptr != nullptr) {
503#ifdef DEBUG_CUDA_MALLOC
504 ++nnz;
505 if (b.size > max_size) max_size = b.size;
506#endif
507 if (b.size >= size) {
508 size_t diff = b.size - size;
509 if (diff < best_diff) {
510 best_diff = diff;
511 ibest = i;
512 if (!best_diff) {
513 void * ptr = b.ptr;
514 *actual_size = b.size;
515 b.ptr = nullptr;
516 b.size = 0;
517 return ptr;
518 }
519 }
520 }
521 }
522 }
523 if (ibest >= 0) {
524 ggml_cuda_buffer& b = buffer_pool[ibest];
525 void * ptr = b.ptr;
526 *actual_size = b.size;
527 b.ptr = nullptr;
528 b.size = 0;
529 return ptr;
530 }
531 void * ptr;
532 size_t look_ahead_size = (size_t) (1.05 * size);
533 look_ahead_size = 256 * ((look_ahead_size + 255)/256);
534 ggml_cuda_set_device(device);
535 cudaError_t err = ggml_cuda_device_malloc(&ptr, look_ahead_size, device);
536 if (err == cudaErrorMemoryAllocation) {
537 (void)cudaGetLastError();
538 const size_t cached_bytes = pool_size;
539 GGML_LOG_DEBUG(GGML_CUDA_NAME " pool[%d]: alloc of %.2f MiB failed, flushing %.2f MiB of cached buffers and retrying\n",
540 device, look_ahead_size/1024.0/1024.0, cached_bytes/1024.0/1024.0);
541 CUDA_CHECK(cudaDeviceSynchronize());
542 clear_pool();
543 invalidate_cuda_graphs();
544 err = ggml_cuda_device_malloc(&ptr, look_ahead_size, device);
545 if (err == cudaSuccess) {
546 GGML_LOG_DEBUG(GGML_CUDA_NAME " pool[%d]: retry succeeded\n", device);
547 }
548 }
549 CUDA_CHECK(err);
550 *actual_size = look_ahead_size;
551 pool_size += look_ahead_size;
552#ifdef DEBUG_CUDA_MALLOC
553 GGML_LOG_INFO("%s[%d]: %d buffers, max_size = %u MB, pool_size = %u MB, requested %u MB\n", __func__, device, nnz,
554 (uint32_t)(max_size / 1024 / 1024), (uint32_t)(pool_size / 1024 / 1024), (uint32_t)(size / 1024 / 1024));
555#endif
556 return ptr;
557 }
558
559 void free(void * ptr, size_t size) override {
560 for (int i = 0; i < MAX_BUFFERS; ++i) {
561 ggml_cuda_buffer& b = buffer_pool[i];
562 if (b.ptr == nullptr) {
563 b.ptr = ptr;
564 b.size = size;
565 return;
566 }
567 }
568 GGML_LOG_DEBUG(GGML_CUDA_NAME " buffer pool full, increase MAX_CUDA_BUFFERS\n");
569 ggml_cuda_set_device(device);
570 CUDA_CHECK(cudaFree(ptr));
571 pool_size -= size;
572 invalidate_cuda_graphs();
573 }
574};
575
576// pool with virtual memory
577#if defined(GGML_USE_VMM)
578struct ggml_cuda_pool_vmm : public ggml_cuda_pool {
579 static const size_t CUDA_POOL_VMM_MAX_SIZE = 1ull << 35; // 32 GB
580
581 int device;
582 int physical_device;
583 CUdeviceptr pool_addr = 0;
584 size_t pool_used = 0;
585 size_t pool_size = 0;
586 size_t granularity;
587#if defined(GGML_USE_HIP)
588 std::vector<std::pair<CUdeviceptr, size_t>> mappings;
589#endif
590
591 explicit ggml_cuda_pool_vmm(int device) :
592 device(device),
593 physical_device(ggml_cuda_get_physical_device(device)),
594 granularity(ggml_cuda_info().devices[device].vmm_granularity) {
595 }
596
597 ~ggml_cuda_pool_vmm() {
598 if (pool_addr != 0) {
599#if defined(GGML_USE_HIP)
600 // Workaround for https://github.com/ROCm/ROCR-Runtime/issues/285
601 for (std::pair<CUdeviceptr, size_t> & mapping : mappings) {
602 CU_CHECK(cuMemUnmap(mapping.first, mapping.second));
603 }
604#else
605 CU_CHECK(cuMemUnmap(pool_addr, pool_size));
606#endif
607 CU_CHECK(cuMemAddressFree(pool_addr, CUDA_POOL_VMM_MAX_SIZE));
608 }
609 }
610
611 void * alloc(size_t size, size_t * actual_size) override {
612 // round up the allocation size to the alignment to ensure that all allocations are aligned for all data types
613 const size_t alignment = 128;
614 size = alignment * ((size + alignment - 1) / alignment);
615
616 size_t avail = pool_size - pool_used;
617
618 if (size > avail) {
619 // round up to the next multiple of the granularity
620 size_t reserve_size = size - avail;
621 reserve_size = granularity * ((reserve_size + granularity - 1) / granularity);
622
623 GGML_ASSERT(pool_size + reserve_size <= CUDA_POOL_VMM_MAX_SIZE);
624
625 // allocate more physical memory
626 CUmemAllocationProp prop = {};
627 prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
628 prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
629 prop.location.id = physical_device;
630 CUmemGenericAllocationHandle handle;
631 CU_CHECK(cuMemCreate(&handle, reserve_size, &prop, 0));
632
633 // reserve virtual address space (if not already reserved)
634 if (pool_addr == 0) {
635 CU_CHECK(cuMemAddressReserve(&pool_addr, CUDA_POOL_VMM_MAX_SIZE, 0, 0, 0));
636 }
637
638 // map at the end of the pool
639 CUdeviceptr start_ptr = (CUdeviceptr)((char *)(pool_addr) + pool_size);
640 CU_CHECK(cuMemMap(start_ptr, reserve_size, 0, handle, 0));
641#if defined(GGML_USE_HIP)
642 mappings.push_back({start_ptr, reserve_size});
643#endif
644
645 // the memory allocation handle is no longer needed after mapping
646 CU_CHECK(cuMemRelease(handle));
647
648 // VMM Bug fix for P2P access if GGML_CUDA_P2P is set, or if NCCL build
649 bool use_peer_access = ggml_cuda_p2p_enabled();
650#if defined(GGML_USE_NCCL)
651 use_peer_access = true;
652#endif // defined(GGML_USE_NCCL)
653
654 if (use_peer_access) {
655 // NCCL implicitly enables peer access (cudaDeviceEnablePeerAccess), and
656 // GGML_CUDA_P2P enables it explicitly. Unlike cudaMalloc buffers, VMM
657 // allocations do not become peer-accessible from that alone, so access
658 // must be granted explicitly here. With virtual devices, grant access
659 // on the backing *physical* devices (deduplicated, since several
660 // virtual devices can map to the same physical GPU).
661 std::vector<CUmemAccessDesc> access_descs;
662 bool physical_seen[GGML_CUDA_MAX_DEVICES] = {};
663 const int device_count = ggml_cuda_info().device_count;
664 for (int id = 0; id < device_count; ++id) {
665 const int id_physical = ggml_cuda_get_physical_device(id);
666 if (id_physical != physical_device) {
667 int can_access_peer = 0;
668 CUDA_CHECK(cudaDeviceCanAccessPeer(&can_access_peer, id_physical, physical_device));
669 if (!can_access_peer) {
670 continue;
671 }
672 }
673 if (physical_seen[id_physical]) {
674 continue;
675 }
676 physical_seen[id_physical] = true;
677 CUmemAccessDesc access = {};
678 access.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
679 access.location.id = id_physical;
680 access.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE;
681 access_descs.push_back(access);
682 }
683 CU_CHECK(cuMemSetAccess(start_ptr, reserve_size, access_descs.data(), access_descs.size()));
684 } else {
685 // set access for non P2P
686 CUmemAccessDesc access = {};
687 access.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
688 access.location.id = physical_device;
689 access.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE;
690 CU_CHECK(cuMemSetAccess(start_ptr, reserve_size, &access, 1));
691 }
692
693 // add to the pool
694 pool_size += reserve_size;
695
696 //printf("cuda pool[%d]: size increased to %llu MB (reserved %llu MB)\n",
697 // device, (unsigned long long) (pool_size/1024/1024),
698 // (unsigned long long) (reserve_size/1024/1024));
699 }
700
701 GGML_ASSERT(pool_addr != 0);
702
703 void * ptr = (void *) ((CUdeviceptr)((char *)(pool_addr) + pool_used));
704 *actual_size = size;
705 pool_used += size;
706
707#ifdef DEBUG_CUDA_MALLOC
708 printf("cuda pool[%d]: allocated %llu bytes at %llx\n", device, (unsigned long long) size, ptr);
709#endif
710
711 return ptr;
712 }
713
714 void free(void * ptr, size_t size) override {
715#ifdef DEBUG_CUDA_MALLOC
716 printf("cuda pool[%d]: freed %llu bytes at %llx\n", device, (unsigned long long) size, ptr);
717#endif
718
719 pool_used -= size;
720
721 // all deallocations must be in reverse order of the allocations
722 GGML_ASSERT(ptr == (void *) ((char *)(pool_addr) + pool_used));
723 }
724};
725#endif // defined(GGML_USE_VMM)
726
727std::unique_ptr<ggml_cuda_pool> ggml_backend_cuda_context::new_pool_for_device(ggml_backend_cuda_context & ctx,
728 int device,
729 [[maybe_unused]] int stream_no) {
730#if defined(GGML_USE_VMM)
731 if (ggml_cuda_info().devices[device].vmm) {
732 return std::unique_ptr<ggml_cuda_pool>(new ggml_cuda_pool_vmm(device));
733 }
734#endif // defined(GGML_USE_VMM)
735 return std::unique_ptr<ggml_cuda_pool>(new ggml_cuda_pool_leg(ctx, device));
736}
737
738// destroying a cuBLAS handle while a graph is being captured in a different thread can result in a CUDA error
739// this lock is used to ensure that no cuBLAS handle is destroyed while a graph is being captured
740
741static std::mutex ggml_cuda_lock;
742static std::condition_variable ggml_cuda_lock_cv;
743static std::atomic<int> ggml_cuda_lock_counter;
744
745ggml_backend_cuda_context::~ggml_backend_cuda_context() {
746 std::unique_lock<std::mutex> lock(ggml_cuda_lock);
747 ggml_cuda_lock_cv.wait(lock, []{ return ggml_cuda_lock_counter.load(std::memory_order_relaxed) == 0; });
748
749 if (copy_event != nullptr) {
750 CUDA_CHECK(cudaEventDestroy(copy_event));
751 }
752 for (int i = 0; i < GGML_CUDA_MAX_DEVICES; ++i) {
753 for (int j = 0; j < GGML_CUDA_MAX_STREAMS; ++j) {
754 if (streams[i][j] != nullptr) {
755 CUDA_CHECK(cudaStreamDestroy(streams[i][j]));
756 }
757 if (cublas_handles[i][j] != nullptr) {
758 CUBLAS_CHECK(cublasDestroy(cublas_handles[i][j]));
759 }
760 if (cublas_workspaces[i][j] != nullptr) {
761 CUDA_CHECK(cudaFree(cublas_workspaces[i][j]));
762 }
763 }
764 }
765}
766
767
768// cuda buffer
769
770struct ggml_backend_cuda_buffer_context {
771 int device;
772 void * dev_ptr = nullptr;
773 std::string name;
774
775 ggml_backend_cuda_buffer_context(int device, void * dev_ptr) :
776 device(device), dev_ptr(dev_ptr),
777 name(GGML_CUDA_NAME + std::to_string(device)) {
778 }
779
780 ~ggml_backend_cuda_buffer_context() {
781 CUDA_CHECK(cudaFree(dev_ptr));
782 }
783};
784
785static void ggml_backend_cuda_buffer_free_buffer(ggml_backend_buffer_t buffer) {
786 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
787 delete ctx;
788}
789
790static bool ggml_backend_buffer_is_cuda(ggml_backend_buffer_t buffer) {
791 return buffer->iface.free_buffer == ggml_backend_cuda_buffer_free_buffer;
792}
793
794static void * ggml_backend_cuda_buffer_get_base(ggml_backend_buffer_t buffer) {
795 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
796 return ctx->dev_ptr;
797}
798
799static enum ggml_status ggml_backend_cuda_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
800 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
801
802 if (tensor->view_src != NULL) {
803 assert(tensor->view_src->buffer->buft == buffer->buft);
804 return GGML_STATUS_SUCCESS;
805 }
806
807 if (ggml_is_quantized(tensor->type) && tensor->view_src == nullptr && ggml_backend_buffer_get_usage(buffer) != GGML_BACKEND_BUFFER_USAGE_COMPUTE) {
808 // initialize padding to 0 to avoid possible NaN values
809 const size_t original_size = ggml_nbytes(tensor);
810 const size_t padded_size = ggml_backend_buft_get_alloc_size(buffer->buft, tensor);
811
812 if (padded_size > original_size) {
813 ggml_cuda_set_device(ctx->device);
814 CUDA_CHECK(cudaMemsetAsync((char *)tensor->data + original_size, 0, padded_size - original_size, cudaStreamPerThread));
815 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
816 }
817 }
818 return GGML_STATUS_SUCCESS;
819}
820
821static void ggml_backend_cuda_buffer_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
822 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *) buffer->context;
823
824 ggml_cuda_set_device(ctx->device);
825 CUDA_CHECK(cudaMemsetAsync((char *) tensor->data + offset, value, size, cudaStreamPerThread));
826 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
827}
828
829static void ggml_backend_cuda_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
830 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *) buffer->context;
831
832 ggml_cuda_set_device(ctx->device);
833 CUDA_CHECK(cudaMemcpyAsync((char *) tensor->data + offset, data, size, cudaMemcpyHostToDevice, cudaStreamPerThread));
834 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
835}
836
837static void ggml_backend_cuda_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
838 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *) buffer->context;
839
840 ggml_cuda_set_device(ctx->device);
841 CUDA_CHECK(cudaMemcpyAsync(data, (const char *) tensor->data + offset, size, cudaMemcpyDeviceToHost, cudaStreamPerThread));
842 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
843}
844
845static void ggml_backend_cuda_buffer_set_tensor_2d(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data,
846 size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) {
847 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *) buffer->context;
848
849 ggml_cuda_set_device(ctx->device);
850 CUDA_CHECK(cudaMemcpy2DAsync(
851 (char *) tensor->data + offset, stride_tensor, data, stride_data, size, n_copies, cudaMemcpyHostToDevice, cudaStreamPerThread));
852 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
853}
854
855static void ggml_backend_cuda_buffer_get_tensor_2d(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor, void * data,
856 size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) {
857 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
858
859 ggml_cuda_set_device(ctx->device);
860 CUDA_CHECK(cudaMemcpy2DAsync(
861 data, stride_data, (const char *) tensor->data + offset, stride_tensor, size, n_copies, cudaMemcpyDeviceToHost, cudaStreamPerThread));
862 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
863}
864
865static void ggml_backend_cuda_buffer_set_tensor_n(ggml_backend_buffer_t buffer, struct ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors) {
866 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
867
868 ggml_cuda_set_device(ctx->device);
869
870 for (size_t i = 0; i < n_tensors; i++) {
871 if (sizes[i] == 0) {
872 continue;
873 }
874 CUDA_CHECK(cudaMemcpyAsync(
875 (char *) tensors[i]->data + offsets[i],
876 data[i],
877 sizes[i],
878 cudaMemcpyHostToDevice,
879 cudaStreamPerThread));
880 }
881
882 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
883}
884
885static void ggml_backend_cuda_buffer_get_tensor_n(ggml_backend_buffer_t buffer, const struct ggml_tensor * const * tensors, void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors) {
886 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
887
888 ggml_cuda_set_device(ctx->device);
889
890 if (!ggml_cuda_pinned_memory_disabled() &&
891 ggml_cuda_get_tensor_n(ctx->device, tensors, data, offsets, sizes, n_tensors)) {
892 return;
893 }
894
895 for (size_t i = 0; i < n_tensors; i++) {
896 if (sizes[i] == 0) {
897 continue;
898 }
899 CUDA_CHECK(cudaMemcpyAsync(
900 data[i],
901 (const char *) tensors[i]->data + offsets[i],
902 sizes[i],
903 cudaMemcpyDeviceToHost,
904 cudaStreamPerThread));
905 }
906
907 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
908}
909
910static bool ggml_backend_cuda_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
911 if (ggml_backend_buffer_is_cuda(src->buffer)) {
912 ggml_backend_cuda_buffer_context * src_ctx = (ggml_backend_cuda_buffer_context *)src->buffer->context;
913 ggml_backend_cuda_buffer_context * dst_ctx = (ggml_backend_cuda_buffer_context *)dst->buffer->context;
914 // compare the backing physical devices: distinct virtual devices may share one physical GPU,
915 // in which case a same-device copy (not a peer copy) is required
916 const int src_physical = ggml_cuda_get_physical_device(src_ctx->device);
917 const int dst_physical = ggml_cuda_get_physical_device(dst_ctx->device);
918 if (src_physical == dst_physical) {
919 CUDA_CHECK(cudaMemcpyAsync(dst->data, src->data, ggml_nbytes(src), cudaMemcpyDeviceToDevice, cudaStreamPerThread));
920 } else {
921#ifdef GGML_CUDA_NO_PEER_COPY
922 return false;
923#else
924 CUDA_CHECK(cudaMemcpyPeerAsync(dst->data, dst_physical, src->data, src_physical, ggml_nbytes(src), cudaStreamPerThread));
925#endif
926 }
927 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
928 return true;
929 }
930 return false;
931
932 GGML_UNUSED(buffer);
933}
934
935static bool ggml_backend_cuda_buffer_cpy_tensor_n(ggml_backend_buffer_t buffer, const struct ggml_tensor * const * srcs, struct ggml_tensor * const * dsts, size_t n_tensors) {
936 ggml_backend_cuda_buffer_context * dst_ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
937
938 for (size_t i = 0; i < n_tensors; i++) {
939 ggml_backend_buffer_t src_buf = srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer;
940 if (!ggml_backend_buffer_is_cuda(src_buf)) {
941 return false;
942 }
943 }
944
945#ifdef GGML_CUDA_NO_PEER_COPY
946 for (size_t i = 0; i < n_tensors; i++) {
947 ggml_backend_buffer_t src_buf = srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer;
948 ggml_backend_buffer_t dst_buf = dsts[i]->view_src ? dsts[i]->view_src->buffer : dsts[i]->buffer;
949 ggml_backend_cuda_buffer_context * src_ctx = (ggml_backend_cuda_buffer_context *)src_buf->context;
950 ggml_backend_cuda_buffer_context * dst_ctx_i = (ggml_backend_cuda_buffer_context *)dst_buf->context;
951 const int src_physical = ggml_cuda_get_physical_device(src_ctx->device);
952 const int dst_physical = ggml_cuda_get_physical_device(dst_ctx_i->device);
953 if (src_physical != dst_physical) {
954 return false;
955 }
956 }
957#endif
958
959 ggml_cuda_set_device(dst_ctx->device);
960
961 for (size_t i = 0; i < n_tensors; i++) {
962 ggml_backend_buffer_t src_buf = srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer;
963 ggml_backend_buffer_t dst_buf = dsts[i]->view_src ? dsts[i]->view_src->buffer : dsts[i]->buffer;
964 ggml_backend_cuda_buffer_context * src_ctx = (ggml_backend_cuda_buffer_context *)src_buf->context;
965 ggml_backend_cuda_buffer_context * dst_ctx_i = (ggml_backend_cuda_buffer_context *)dst_buf->context;
966 const int src_physical = ggml_cuda_get_physical_device(src_ctx->device);
967 const int dst_physical = ggml_cuda_get_physical_device(dst_ctx_i->device);
968 if (src_physical == dst_physical) {
969 CUDA_CHECK(cudaMemcpyAsync(dsts[i]->data, srcs[i]->data, ggml_nbytes(srcs[i]), cudaMemcpyDeviceToDevice, cudaStreamPerThread));
970 } else {
971#ifdef GGML_CUDA_NO_PEER_COPY
972 GGML_ABORT("peer copy not supported");
973#else
974 CUDA_CHECK(cudaMemcpyPeerAsync(dsts[i]->data, dst_physical, srcs[i]->data, src_physical, ggml_nbytes(srcs[i]), cudaStreamPerThread));
975#endif
976 }
977 }
978
979 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
980 return true;
981}
982
983static void ggml_backend_cuda_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
984 ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
985
986 ggml_cuda_set_device(ctx->device);
987 CUDA_CHECK(cudaMemsetAsync(ctx->dev_ptr, value, buffer->size, cudaStreamPerThread));
988 CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
989}
990
991static const ggml_backend_buffer_i ggml_backend_cuda_buffer_interface = {
992 /* .free_buffer = */ ggml_backend_cuda_buffer_free_buffer,
993 /* .get_base = */ ggml_backend_cuda_buffer_get_base,
994 /* .init_tensor = */ ggml_backend_cuda_buffer_init_tensor,
995 /* .memset_tensor = */ ggml_backend_cuda_buffer_memset_tensor,
996 /* .set_tensor = */ ggml_backend_cuda_buffer_set_tensor,
997 /* .get_tensor = */ ggml_backend_cuda_buffer_get_tensor,
998 /* .set_tensor_2d = */ ggml_backend_cuda_buffer_set_tensor_2d,
999 /* .get_tensor_2d = */ ggml_backend_cuda_buffer_get_tensor_2d,
1000 /* .cpy_tensor = */ ggml_backend_cuda_buffer_cpy_tensor,
1001 /* .clear = */ ggml_backend_cuda_buffer_clear,
1002 /* .reset = */ NULL,
1003 /* .set_tensor_n = */ ggml_backend_cuda_buffer_set_tensor_n,
1004 /* .get_tensor_n = */ ggml_backend_cuda_buffer_get_tensor_n,
1005 /* .cpy_tensor_n = */ ggml_backend_cuda_buffer_cpy_tensor_n,
1006};
1007
1008// cuda buffer type
1009struct ggml_backend_cuda_buffer_type_context {
1010 int device;
1011 std::string name;
1012};
1013
1014static const char * ggml_backend_cuda_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
1015 ggml_backend_cuda_buffer_type_context * ctx = (ggml_backend_cuda_buffer_type_context *)buft->context;
1016
1017 return ctx->name.c_str();
1018}
1019
1020static bool ggml_backend_buft_is_cuda(ggml_backend_buffer_type_t buft) {
1021 return buft->iface.get_name == ggml_backend_cuda_buffer_type_get_name;
1022}
1023
1024static ggml_backend_buffer_t ggml_backend_cuda_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
1025 ggml_backend_cuda_buffer_type_context * buft_ctx = (ggml_backend_cuda_buffer_type_context *)buft->context;
1026
1027 ggml_cuda_set_device(buft_ctx->device);
1028
1029 void * dev_ptr;
1030 cudaError_t err = ggml_cuda_device_malloc(&dev_ptr, size, buft_ctx->device);
1031 if (err != cudaSuccess) {
1032 // clear the error
1033 (void)cudaGetLastError();
1034 GGML_LOG_ERROR("%s: allocating %.2f MiB on device %d: cudaMalloc failed: %s\n", __func__, size / 1024.0 / 1024.0, buft_ctx->device, cudaGetErrorString(err));
1035 return nullptr;
1036 }
1037
1038 ggml_backend_cuda_buffer_context * ctx = new ggml_backend_cuda_buffer_context(buft_ctx->device, dev_ptr);
1039
1040 return ggml_backend_buffer_init(buft, ggml_backend_cuda_buffer_interface, ctx, size);
1041}
1042
1043static size_t ggml_backend_cuda_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
1044 return 128;
1045
1046 GGML_UNUSED(buft);
1047}
1048
1049static size_t ggml_backend_cuda_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
1050 ggml_backend_cuda_buffer_type_context * buft_ctx = (ggml_backend_cuda_buffer_type_context *) buft->context;
1051
1052 size_t size = tensor->op == GGML_OP_FLASH_ATTN_EXT
1053 ? ggml_cuda_flash_attn_ext_get_alloc_size(buft_ctx->device, tensor)
1054 : ggml_nbytes(tensor);
1055 int64_t ne0 = tensor->ne[0];
1056
1057 // [TAG_ALLOC_SIZE_EXPAND]
1058 if (ggml_is_quantized(tensor->type)) {
1059 if (ne0 % MATRIX_ROW_PADDING != 0) {
1060 GGML_ASSERT(tensor->nb[0] == ggml_element_size(tensor));
1061 size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING);
1062 }
1063 }
1064
1065 return size;
1066}
1067
1068static const ggml_backend_buffer_type_i ggml_backend_cuda_buffer_type_interface = {
1069 /* .get_name = */ ggml_backend_cuda_buffer_type_get_name,
1070 /* .alloc_buffer = */ ggml_backend_cuda_buffer_type_alloc_buffer,
1071 /* .alloc_buffer_n = */ NULL,
1072 /* .get_alignment = */ ggml_backend_cuda_buffer_type_get_alignment,
1073 /* .get_max_size = */ NULL, // defaults to SIZE_MAX
1074 /* .get_alloc_size = */ ggml_backend_cuda_buffer_type_get_alloc_size,
1075 /* .get_alloc_size_n = */ NULL,
1076 /* .is_host = */ NULL,
1077};
1078
1079ggml_backend_buffer_type_t ggml_backend_cuda_buffer_type(int device) {
1080 static std::mutex mutex;
1081 std::lock_guard<std::mutex> lock(mutex);
1082
1083 if (device >= ggml_backend_cuda_get_device_count()) {
1084 return nullptr;
1085 }
1086
1087 static ggml_backend_buffer_type ggml_backend_cuda_buffer_types[GGML_CUDA_MAX_DEVICES];
1088
1089 static bool ggml_backend_cuda_buffer_type_initialized = false;
1090
1091 if (!ggml_backend_cuda_buffer_type_initialized) {
1092 for (int i = 0; i < ggml_backend_cuda_get_device_count(); i++) {
1093 ggml_backend_cuda_buffer_types[i] = {
1094 /* .iface = */ ggml_backend_cuda_buffer_type_interface,
1095 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_cuda_reg(), i),
1096 /* .context = */ new ggml_backend_cuda_buffer_type_context{i, GGML_CUDA_NAME + std::to_string(i)},
1097 };
1098 }
1099 ggml_backend_cuda_buffer_type_initialized = true;
1100 }
1101
1102 return &ggml_backend_cuda_buffer_types[device];
1103}
1104
1105// Communication context for multi-GPU AllReduce during tensor parallelism.
1106//
1107// Created once per meta backend instance. Resources for the selected mode
1108// (NCCL communicators or the internal AllReduce pipeline) are initialised
1109// eagerly during comm_init so any init failure surfaces at startup rather
1110// than mid-run.
1111struct ggml_backend_cuda_comm_context {
1112 using try_allreduce_fn = bool(*)(ggml_backend_cuda_comm_context *, struct ggml_tensor **);
1113
1114 std::vector<ggml_backend_t> backends;
1115 std::vector<int> dev_ids;
1116
1117 // Set by the init chain (comm_init_{nccl, internal, none}) to one of
1118 // try_allreduce_{nccl, internal, butterfly}. nccl needs `comms`,
1119 // internal needs `ar_pipeline`, butterfly needs nothing. Per-call
1120 // failures return false; the meta backend's generic implementation then
1121 // handles that call.
1122 try_allreduce_fn try_allreduce = nullptr;
1123
1124 ggml_cuda_ar_pipeline * ar_pipeline = nullptr;
1125
1126 // Number of ranks in the communicator when each rank is a separate process. Zero unless
1127 // comm_init_rank created this context.
1128 int world_size = 0;
1129
1130 // Number of ranks taking part in the reduction. For a communicator from comm_init_rank this is
1131 // world_size. Otherwise it is the number of backends this process holds. The NCCL reduction
1132 // uses it to choose the tensor size below which it reduces in F32 rather than converting to
1133 // BF16 first.
1134 size_t n_ranks() const {
1135 return world_size > 0 ? (size_t) world_size : backends.size();
1136 }
1137
1138#ifdef GGML_USE_NCCL
1139 std::vector<ncclComm_t> comms;
1140#endif // GGML_USE_NCCL
1141
1142 ~ggml_backend_cuda_comm_context() {
1143#ifdef GGML_USE_NCCL
1144 for (ncclComm_t comm : comms) {
1145 NCCL_CHECK(ncclCommDestroy(comm));
1146 }
1147#endif // GGML_USE_NCCL
1148 ggml_cuda_ar_pipeline_free(ar_pipeline);
1149 }
1150};
1151
1152#ifdef GGML_USE_NCCL
1153// AllReduce via NCCL. Reduces as FP32 for small tensors and BF16 for large
1154// tensors (bandwidth-bound), then converts back to FP32.
1155static bool ggml_backend_cuda_comm_allreduce_nccl(
1156 ggml_backend_cuda_comm_context * comm_ctx, struct ggml_tensor ** tensors) {
1157 const int64_t ne = ggml_nelements(tensors[0]);
1158 // FIXME the input of llm_graph_context::build_in_out_ids can produce a tensor with 0 elements if n_outputs == 0
1159 // This then causes a crash in this function
1160 if (ne == 0) {
1161 return true;
1162 }
1163
1164 const size_t n_backends = comm_ctx->backends.size();
1165 const size_t n_ranks = comm_ctx->n_ranks();
1166
1167 for (size_t i = 0; i < n_backends; ++i) {
1168 GGML_ASSERT(tensors[i] != nullptr);
1169 GGML_ASSERT(ggml_nelements(tensors[i]) == ne);
1170 GGML_ASSERT(ggml_is_contiguously_allocated(tensors[i]));
1171 }
1172
1173 // For small tensors, simply reduce them as FP32.
1174 // The following heuristic for how "small" a tensor should be is based on RTX 4090s connected via 16x PCIe 4.0.
1175 if ((n_ranks <= 2 && ne < 32768) || (n_ranks == 3 && ne < 131072) || (n_ranks >= 4 && ne < 262144)) {
1176 for (size_t i = 0; i < n_backends; ++i) {
1177 if ((tensors[i]->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
1178 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) comm_ctx->backends[i]->context;
1179 ggml_cuda_set_device(cuda_ctx->device);
1180 CUDA_CHECK(cudaMemsetAsync(tensors[i]->data, 0, ggml_nbytes(tensors[i]), cuda_ctx->stream()));
1181 }
1182 }
1183 NCCL_CHECK(ncclGroupStart());
1184 for (size_t i = 0; i < n_backends; ++i) {
1185 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) comm_ctx->backends[i]->context;
1186 NCCL_CHECK(ncclAllReduce(tensors[i]->data, tensors[i]->data, ne, ncclFloat, ncclSum, comm_ctx->comms[i], cuda_ctx->stream()));
1187 }
1188 NCCL_CHECK(ncclGroupEnd());
1189 return true;
1190 }
1191
1192 // For large tensors it's faster to compress them to BF16 for the reduction:
1193 to_bf16_cuda_t to_bf16 = ggml_get_to_bf16_cuda(GGML_TYPE_F32);
1194 to_fp32_cuda_t to_fp32 = ggml_get_to_fp32_cuda(GGML_TYPE_BF16);
1195
1196 ggml_cuda_pool_alloc<nv_bfloat16> tmp[GGML_CUDA_MAX_DEVICES];
1197 for (size_t i = 0; i < n_backends; ++i) {
1198 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) comm_ctx->backends[i]->context;
1199 tmp[i].pool = &cuda_ctx->pool();
1200 tmp[i].alloc(ne);
1201
1202 ggml_cuda_set_device(cuda_ctx->device);
1203 if (tensors[i]->flags & GGML_TENSOR_FLAG_COMPUTE) {
1204 to_bf16(tensors[i]->data, tmp[i].get(), ne, cuda_ctx->stream());
1205 } else {
1206 CUDA_CHECK(cudaMemsetAsync(tmp[i].get(), 0, ne * sizeof(nv_bfloat16), cuda_ctx->stream()));
1207 }
1208 CUDA_CHECK(cudaGetLastError());
1209 }
1210
1211 NCCL_CHECK(ncclGroupStart());
1212 for (size_t i = 0; i < n_backends; ++i) {
1213 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) comm_ctx->backends[i]->context;
1214 NCCL_CHECK(ncclAllReduce(tmp[i].get(), tmp[i].get(), ne, ncclBfloat16, ncclSum, comm_ctx->comms[i], cuda_ctx->stream()));
1215 }
1216 NCCL_CHECK(ncclGroupEnd());
1217
1218 for (size_t i = 0; i < n_backends; ++i) {
1219 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) comm_ctx->backends[i]->context;
1220
1221 ggml_cuda_set_device(cuda_ctx->device);
1222 to_fp32(tmp[i].get(), (float *) tensors[i]->data, ne, cuda_ctx->stream());
1223 CUDA_CHECK(cudaGetLastError());
1224 }
1225
1226 return true;
1227}
1228#endif // GGML_USE_NCCL
1229
1230// Run the internal AR pipeline. Returns false on unsupported / failed input
1231// -- the caller decides whether to abort (env-forced) or fall back silently.
1232static bool ggml_backend_cuda_comm_allreduce_internal(
1233 ggml_backend_cuda_comm_context * comm_ctx, struct ggml_tensor ** tensors) {
1234 GGML_ASSERT(comm_ctx->ar_pipeline != nullptr);
1235
1236 const size_t n_backends = comm_ctx->backends.size();
1237 GGML_ASSERT(n_backends == 2);
1238 GGML_ASSERT(tensors[0] != nullptr);
1239
1240 const int64_t ne = ggml_nelements(tensors[0]);
1241 const ggml_type type = tensors[0]->type;
1242
1243 if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16 && type != GGML_TYPE_BF16) {
1244 GGML_LOG_DEBUG("%s: internal unsupported: type=%d\n", __func__, (int) type);
1245 return false;
1246 }
1247
1248 if (ne == 0) {
1249 return true;
1250 }
1251
1252 for (size_t i = 0; i < n_backends; ++i) {
1253 if (tensors[i] == nullptr) {
1254 GGML_LOG_ERROR("%s: internal failed: tensor[%zu] is null\n", __func__, i);
1255 return false;
1256 }
1257 if (ggml_nelements(tensors[i]) != ne || tensors[i]->type != type) {
1258 GGML_LOG_ERROR("%s: internal failed: tensor[%zu] ne=%" PRId64 " type=%d expected ne=%" PRId64 " type=%d\n",
1259 __func__, i, ggml_nelements(tensors[i]), (int) tensors[i]->type, ne, (int) type);
1260 return false;
1261 }
1262 if (!ggml_is_contiguously_allocated(tensors[i])) {
1263 GGML_LOG_DEBUG("%s: internal unsupported: tensor[%zu] is not contiguously allocated: ne=%" PRId64 " nbytes=%zu packed=%zu type=%d\n",
1264 __func__, i, ne, ggml_nbytes(tensors[i]),
1265 (size_t) ne * ggml_type_size(type) / ggml_blck_size(type), (int) type);
1266 return false;
1267 }
1268 if (((uintptr_t) tensors[i]->data & 0xF) != 0) {
1269 GGML_LOG_DEBUG("%s: internal unsupported: tensor[%zu] data pointer is not 16-byte aligned: %p type=%d ne=%" PRId64 "\n",
1270 __func__, i, tensors[i]->data, (int) type, ne);
1271 return false;
1272 }
1273 GGML_ASSERT((ggml_nbytes(tensors[i]) & 0xF) == 0);
1274 }
1275
1276 return ggml_cuda_ar_allreduce(comm_ctx->ar_pipeline, comm_ctx->backends.data(), tensors);
1277}
1278
1279// ---------------------------------------------------------------------------
1280// Per-call dispatch -- three variants, one per backend. Each is set as
1281// comm_ctx->try_allreduce by the matching init step. Per-call failure
1282// returns false; the meta backend's generic implementation handles that call.
1283// ---------------------------------------------------------------------------
1284
1285#ifdef GGML_USE_NCCL
1286static bool ggml_backend_cuda_comm_try_allreduce_nccl(
1287 ggml_backend_cuda_comm_context * comm_ctx, struct ggml_tensor ** tensors) {
1288 return ggml_backend_cuda_comm_allreduce_nccl(comm_ctx, tensors);
1289}
1290#endif // GGML_USE_NCCL
1291
1292static bool ggml_backend_cuda_comm_try_allreduce_internal(
1293 ggml_backend_cuda_comm_context * comm_ctx, struct ggml_tensor ** tensors) {
1294 return ggml_backend_cuda_comm_allreduce_internal(comm_ctx, tensors);
1295}
1296
1297static bool ggml_backend_cuda_comm_try_allreduce_butterfly(
1298 ggml_backend_cuda_comm_context *, struct ggml_tensor **) {
1299 return false;
1300}
1301
1302static void ggml_backend_cuda_comm_free(void * comm_ctx_v) {
1303 if (comm_ctx_v == nullptr) {
1304 return;
1305 }
1306 delete static_cast<ggml_backend_cuda_comm_context *>(comm_ctx_v);
1307}
1308
1309// ---------------------------------------------------------------------------
1310// Init -- chained nccl -> internal -> none. Each step tries to bring up its
1311// resource; on failure it warns and recurses into the next step.
1312// ---------------------------------------------------------------------------
1313static void ggml_backend_cuda_comm_init_none(ggml_backend_cuda_comm_context * ret) {
1314 ret->try_allreduce = ggml_backend_cuda_comm_try_allreduce_butterfly;
1315}
1316
1317static void ggml_backend_cuda_comm_init_internal(ggml_backend_cuda_comm_context * ret) {
1318 ret->ar_pipeline = ggml_cuda_ar_pipeline_init(ret->dev_ids.data(), ret->dev_ids.size());
1319 if (ret->ar_pipeline) {
1320 ret->try_allreduce = ggml_backend_cuda_comm_try_allreduce_internal;
1321 return;
1322 }
1323
1324 // Clear sticky CUDA error from the failed init.
1325 (void) cudaGetLastError();
1326 GGML_LOG_WARN("internal AllReduce init failed (n_devices != 2?); "
1327 "falling back to meta-backend butterfly\n");
1328 ggml_backend_cuda_comm_init_none(ret);
1329}
1330
1331static void ggml_backend_cuda_comm_init_nccl(ggml_backend_cuda_comm_context * ret) {
1332#ifdef GGML_USE_NCCL
1333 // Disabling NCCL path when CUDA virtual devices are in use since NCCL requires one distinct physical GPU per rank.
1334 const ggml_cuda_device_info & info = ggml_cuda_info();
1335 if (info.device_count > info.physical_device_count) {
1336 GGML_LOG_WARN("NCCL disabled: virtual devices in use; "
1337 "falling back to internal AllReduce\n");
1338 ggml_backend_cuda_comm_init_internal(ret);
1339 return;
1340 }
1341
1342 const size_t n = ret->dev_ids.size();
1343 ret->comms.resize(n);
1344 ncclResult_t rc = ncclCommInitAll(ret->comms.data(), (int) n, ret->dev_ids.data());
1345 if (rc == ncclSuccess) {
1346 ret->try_allreduce = ggml_backend_cuda_comm_try_allreduce_nccl;
1347 return;
1348 }
1349
1350 ret->comms.clear();
1351 GGML_LOG_WARN("NCCL init failed (%s); falling back to internal AllReduce\n",
1352 ncclGetErrorString(rc));
1353#else // GGML_USE_NCCL
1354#ifndef GGML_USE_HIP
1355 GGML_LOG_WARN("NCCL not compiled in; falling back to internal AllReduce. "
1356 "Recompile with -DGGML_CUDA_NCCL=ON for best multi-GPU performance.\n");
1357#endif // !GGML_USE_HIP
1358#endif // GGML_USE_NCCL
1359
1360 ggml_backend_cuda_comm_init_internal(ret);
1361}
1362
1363// Top-level init. Picks one of the three init paths based on
1364// GGML_CUDA_ALLREDUCE (or the platform default) and lets the chain handle
1365// any fallback. Unrecognised env values warn and fall through to the
1366// platform default.
1367static void * ggml_backend_cuda_comm_init(ggml_backend_t * backends, size_t n_backends) {
1368 for (size_t i = 0; i < n_backends; i++) {
1369 if (!ggml_backend_is_cuda(backends[i])) {
1370 return nullptr;
1371 }
1372 }
1373
1374 auto * ret = new ggml_backend_cuda_comm_context;
1375 ret->backends.assign(backends, backends + n_backends);
1376 ret->dev_ids.reserve(n_backends);
1377 for (size_t i = 0; i < n_backends; i++) {
1378 ret->dev_ids.push_back(static_cast<ggml_backend_cuda_context *>(backends[i]->context)->device);
1379 }
1380
1381 const char * env = getenv("GGML_CUDA_ALLREDUCE");
1382 if (!env) {
1383 // Platform default: Linux uses NCCL, otherwise (generally Windows) internal
1384#if defined(__linux__)
1385 ggml_backend_cuda_comm_init_nccl(ret);
1386#else
1387 ggml_backend_cuda_comm_init_internal(ret);
1388#endif // defined(__linux__)
1389 } else {
1390 std::string env_str(env);
1391 if (env_str == "nccl") {
1392 ggml_backend_cuda_comm_init_nccl(ret);
1393 } else if (env_str == "internal") {
1394 ggml_backend_cuda_comm_init_internal(ret);
1395 } else if (env_str == "none") {
1396 ggml_backend_cuda_comm_init_none(ret);
1397 } else {
1398 GGML_LOG_WARN("unknown GGML_CUDA_ALLREDUCE value: %s\n", env);
1399 ggml_backend_cuda_comm_init_none(ret);
1400 }
1401 }
1402
1403 return ret;
1404}
1405
1406#ifdef GGML_USE_NCCL
1407// Builds the communicator with ncclCommInitRank, for the case where each rank is its own
1408// process. Blocks until all world_size ranks have joined.
1409static void * ggml_backend_cuda_comm_init_rank(ggml_backend_t backend, int rank, int world_size,
1410 ggml_backend_comm_bootstrap_callback bootstrap_callback, void * bootstrap_callback_data) {
1411 if (world_size < 1 || rank < 0 || rank >= world_size) {
1412 GGML_LOG_ERROR("%s: invalid rank %d for world size %d\n", __func__, rank, world_size);
1413 return nullptr;
1414 }
1415
1416 // Every rank sends whether its local checks passed, and rank 0 also sends the NCCL unique id.
1417 // So all ranks either join together or fail together, and no rank waits in ncclCommInitRank alone.
1418 struct bootstrap_msg {
1419 uint8_t ok;
1420 ncclUniqueId id;
1421 };
1422 bootstrap_msg local;
1423 memset(&local, 0, sizeof(local));
1424 local.ok = 1;
1425
1426 if (!ggml_backend_is_cuda(backend)) {
1427 GGML_LOG_ERROR("%s: backend is not a CUDA backend\n", __func__);
1428 local.ok = 0;
1429 } else {
1430 // NCCL requires one distinct physical GPU per rank, see ggml_backend_cuda_comm_init_nccl.
1431 const ggml_cuda_device_info & info = ggml_cuda_info();
1432 if (info.device_count > info.physical_device_count) {
1433 GGML_LOG_ERROR("%s: CUDA virtual devices are in use, which NCCL does not support\n", __func__);
1434 local.ok = 0;
1435 }
1436 }
1437 if (local.ok && rank == 0) {
1438 const ncclResult_t rc = ncclGetUniqueId(&local.id);
1439 if (rc != ncclSuccess) {
1440 GGML_LOG_ERROR("%s: ncclGetUniqueId failed (%s)\n", __func__, ncclGetErrorString(rc));
1441 local.ok = 0;
1442 }
1443 }
1444
1445 std::vector<bootstrap_msg> all(world_size);
1446 if (!bootstrap_callback(bootstrap_callback_data, &local, all.data(), sizeof(local))) {
1447 GGML_LOG_ERROR("%s: bootstrap exchange failed on rank %d\n", __func__, rank);
1448 return nullptr;
1449 }
1450 for (int i = 0; i < world_size; i++) {
1451 if (!all[i].ok) {
1452 GGML_LOG_ERROR("%s: rank %d failed its setup checks\n", __func__, i);
1453 return nullptr;
1454 }
1455 }
1456
1457 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context;
1458
1459 auto * ret = new ggml_backend_cuda_comm_context;
1460 ret->backends.push_back(backend);
1461 ret->dev_ids.push_back(cuda_ctx->device);
1462 ret->world_size = world_size;
1463 ret->comms.resize(1);
1464 ret->try_allreduce = ggml_backend_cuda_comm_try_allreduce_nccl;
1465
1466 // On DGX Spark, NCCL picks 64 channels by default, which is slower and uses more memory than 8.
1467 // NCCL_MAX_CTAS still overrides this.
1468 ncclConfig_t config = NCCL_CONFIG_INITIALIZER;
1469 const int cc = ggml_cuda_info().devices[cuda_ctx->device].cc;
1470 if (GGML_CUDA_CC_IS_NVIDIA(cc) && cc == GGML_CUDA_CC_DGX_SPARK) {
1471 config.maxCTAs = 8;
1472 }
1473
1474 ggml_cuda_set_device(cuda_ctx->device);
1475 const ncclResult_t rc = ncclCommInitRankConfig(&ret->comms[0], world_size, all[0].id, rank, &config);
1476 if (rc != ncclSuccess) {
1477 GGML_LOG_ERROR("%s: ncclCommInitRankConfig failed for rank %d/%d (%s)\n",
1478 __func__, rank, world_size, ncclGetErrorString(rc));
1479 ret->comms.clear();
1480 delete ret;
1481 return nullptr;
1482 }
1483
1484 GGML_LOG_INFO("%s: joined NCCL communicator as rank %d/%d on device %d\n",
1485 __func__, rank, world_size, cuda_ctx->device);
1486 return ret;
1487}
1488#endif // GGML_USE_NCCL
1489
1490// Top-level dispatch -- calls the function pointer chosen by comm_init.
1491// Returns false to let the meta-backend's butterfly run.
1492static bool ggml_backend_cuda_comm_allreduce_tensor(void * comm_ctx_v, struct ggml_tensor ** tensors) {
1493 if (comm_ctx_v == nullptr) {
1494 return false;
1495 }
1496 auto * comm_ctx = static_cast<ggml_backend_cuda_comm_context *>(comm_ctx_v);
1497 return comm_ctx->try_allreduce(comm_ctx, tensors);
1498}
1499
1500// host buffer type
1501
1502static const char * ggml_backend_cuda_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
1503 return GGML_CUDA_NAME "_Host";
1504
1505 GGML_UNUSED(buft);
1506}
1507
1508static bool ggml_backend_buft_is_cuda_host(ggml_backend_buffer_type_t buft) {
1509 return buft->iface.get_name == ggml_backend_cuda_host_buffer_type_name;
1510}
1511
1512static void ggml_backend_cuda_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
1513 CUDA_CHECK(cudaFreeHost(buffer->context));
1514}
1515
1516static void * ggml_cuda_host_malloc(size_t size) {
1517 if (ggml_cuda_pinned_memory_disabled()) {
1518 return nullptr;
1519 }
1520
1521 void * ptr = nullptr;
1522 cudaError_t err = cudaMallocHost((void **) &ptr, size);
1523 if (err != cudaSuccess) {
1524 // clear the error
1525 (void)cudaGetLastError();
1526 GGML_LOG_DEBUG("%s: failed to allocate %.2f MiB of pinned memory: %s\n", __func__,
1527 size / 1024.0 / 1024.0, cudaGetErrorString(err));
1528 return nullptr;
1529 }
1530
1531 return ptr;
1532}
1533
1534static ggml_backend_buffer_t ggml_backend_cuda_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
1535 void * ptr = ggml_cuda_host_malloc(size);
1536
1537 if (ptr == nullptr) {
1538 // fallback to cpu buffer
1539 return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
1540 }
1541
1542 ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
1543 buffer->buft = buft;
1544 buffer->iface.free_buffer = ggml_backend_cuda_host_buffer_free_buffer;
1545
1546 return buffer;
1547}
1548
1549static size_t ggml_backend_cuda_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
1550 GGML_UNUSED(buft);
1551 // very large pinned allocations can fail (e.g. on Windows) and fall back to pageable memory, smaller ones succeed
1552 return 4ull*1024*1024*1024;
1553}
1554
1555ggml_backend_buffer_type_t ggml_backend_cuda_host_buffer_type() {
1556 static struct ggml_backend_buffer_type ggml_backend_cuda_buffer_type_host = {
1557 /* .iface = */ {
1558 /* .get_name = */ ggml_backend_cuda_host_buffer_type_name,
1559 /* .alloc_buffer = */ ggml_backend_cuda_host_buffer_type_alloc_buffer,
1560 /* .alloc_buffer_n = */ NULL,
1561 /* .get_alignment = */ ggml_backend_cpu_buffer_type()->iface.get_alignment,
1562 /* .get_max_size = */ ggml_backend_cuda_host_buffer_type_get_max_size,
1563 /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
1564 /* .get_alloc_size_n = */ NULL,
1565 /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
1566 },
1567 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_cuda_reg(), 0),
1568 /* .context = */ nullptr,
1569 };
1570
1571 return &ggml_backend_cuda_buffer_type_host;
1572}
1573
1574//static bool ggml_backend_buffer_is_cuda_host(ggml_backend_buffer_t buffer) {
1575// return buffer->buft->iface.get_name == ggml_backend_cuda_host_buffer_type_name;
1576//}
1577
1578/// kernels
1579
1580typedef void (*ggml_cuda_op_mul_mat_t)(
1581 ggml_backend_cuda_context & ctx,
1582 const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const char * src0_dd_i, const float * src1_ddf_i,
1583 const char * src1_ddq_i, float * dst_dd_i, const int64_t row_low, const int64_t row_high, const int64_t src1_ncols,
1584 const int64_t src1_padded_row_size, cudaStream_t stream);
1585
1586static __global__ void k_compute_batched_ptrs(
1587 const void * src0_as_f16, const void * src1_as_f16, char * dst,
1588 const void ** ptrs_src, void ** ptrs_dst,
1589 int64_t ne12, int64_t ne13,
1590 int64_t ne23,
1591 size_t nb02, size_t nb03,
1592 size_t nb12, size_t nb13,
1593 size_t nbd2, size_t nbd3,
1594 int64_t r2, int64_t r3) {
1595 const int64_t i13 = blockIdx.x * blockDim.x + threadIdx.x;
1596 const int64_t i12 = blockIdx.y * blockDim.y + threadIdx.y;
1597
1598 if (i13 >= ne13 || i12 >= ne12) {
1599 return;
1600 }
1601
1602 const int64_t i03 = i13 / r3;
1603 const int64_t i02 = i12 / r2;
1604
1605 ptrs_src[0*ne23 + i12 + i13*ne12] = (const char *) src0_as_f16 + i02*nb02 + i03*nb03;
1606 ptrs_src[1*ne23 + i12 + i13*ne12] = (const char *) src1_as_f16 + i12*nb12 + i13*nb13;
1607 ptrs_dst[0*ne23 + i12 + i13*ne12] = ( char *) dst + i12*nbd2 + i13*nbd3;
1608}
1609
1610// Type traits for mapping ggml types to CUDA/cuBLAS types
1611template<ggml_type T>
1612struct batched_mul_mat_traits;
1613
1614template<>
1615struct batched_mul_mat_traits<GGML_TYPE_F32> {
1616 using cuda_type = float;
1617 static inline const cublasComputeType_t compute_type = CUBLAS_COMPUTE_32F;
1618 static inline const cudaDataType_t data_type = CUDA_R_32F;
1619 static inline const ggml_type ggml_type_val = GGML_TYPE_F32;
1620 static inline const float alpha = 1.0f;
1621 static inline const float beta = 0.0f;
1622 static inline const void* get_alpha() { static const float val = alpha; return &val; }
1623 static inline const void* get_beta() { static const float val = beta; return &val; }
1624 static inline auto convert(ggml_type src_type) { return ggml_get_to_fp32_cuda(src_type); }
1625 static inline auto convert_nc(ggml_type src_type) { return ggml_get_to_fp32_nc_cuda(src_type); }
1626};
1627
1628template<>
1629struct batched_mul_mat_traits<GGML_TYPE_BF16> {
1630 using cuda_type = nv_bfloat16;
1631 static inline const cublasComputeType_t compute_type = CUBLAS_COMPUTE_32F;
1632 static inline const cudaDataType_t data_type = CUDA_R_16BF;
1633 static inline const ggml_type ggml_type_val = GGML_TYPE_BF16;
1634 static inline const float alpha = 1.0f;
1635 static inline const float beta = 0.0f;
1636 static inline const void* get_alpha() { static const float val = alpha; return &val; }
1637 static inline const void* get_beta() { static const float val = beta; return &val; }
1638 static inline auto convert(ggml_type src_type) { return ggml_get_to_bf16_cuda(src_type); }
1639 static inline auto convert_nc(ggml_type src_type) { return ggml_get_to_bf16_nc_cuda(src_type); }
1640};
1641
1642template<>
1643struct batched_mul_mat_traits<GGML_TYPE_F16> {
1644 using cuda_type = half;
1645 static inline const cublasComputeType_t compute_type = CUBLAS_COMPUTE_16F;
1646 static inline const cudaDataType_t data_type = CUDA_R_16F;
1647 static inline const ggml_type ggml_type_val = GGML_TYPE_F16;
1648 static inline const half alpha = 1.0;
1649 static inline const half beta = 0.0;
1650 static inline const void* get_alpha() { static const half val = alpha; return &val; }
1651 static inline const void* get_beta() { static const half val = beta; return &val; }
1652 static inline auto convert(ggml_type src_type) { return ggml_get_to_fp16_cuda(src_type); }
1653 static inline auto convert_nc(ggml_type src_type) { return ggml_get_to_fp16_nc_cuda(src_type); }
1654};
1655
1656template<ggml_type compute_type>
1657static void ggml_cuda_mul_mat_cublas_impl(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
1658 using traits = batched_mul_mat_traits<compute_type>;
1659 using cuda_t = typename traits::cuda_type;
1660
1661 // F32 chunks can have padding between rows to preserve the original destination stride.
1662 GGML_ASSERT(ggml_is_contiguous(dst) ||
1663 (compute_type == GGML_TYPE_F32 && ggml_is_contiguous_1(dst)));
1664
1665 GGML_TENSOR_BINARY_OP_LOCALS
1666
1667 const int64_t ldc = nb1 / sizeof(float);
1668 const int64_t ne_dst = ggml_nelements(dst);
1669 cudaStream_t main_stream = ctx.stream();
1670 cublasHandle_t cublas_h = ctx.cublas_handle();
1671
1672 const size_t src0_ts = ggml_type_size(src0->type);
1673 GGML_ASSERT(nb00 == src0_ts);
1674 int64_t s01 = nb01 / src0_ts;
1675 int64_t s02 = nb02 / src0_ts;
1676 int64_t s03 = nb03 / src0_ts;
1677
1678 const size_t src1_ts = ggml_type_size(src1->type);
1679 GGML_ASSERT(nb10 == src1_ts);
1680 int64_t s11 = nb11 / src1_ts;
1681 int64_t s12 = nb12 / src1_ts;
1682 int64_t s13 = nb13 / src1_ts;
1683
1684 float * dst_ddf = (float *) dst->data;
1685
1686 const cuda_t * src0_ptr = nullptr;
1687 const cuda_t * src1_ptr = nullptr;
1688
1689 ggml_cuda_pool_alloc<cuda_t> src0_alloc(ctx.pool());
1690 ggml_cuda_pool_alloc<cuda_t> src1_alloc(ctx.pool());
1691
1692 bool is_src0_cont_2 = ggml_is_contiguous_2(src0);
1693 bool is_src1_cont_2 = ggml_is_contiguous_2(src1);
1694
1695 if (src0->type == compute_type) {
1696 src0_ptr = (const cuda_t *) src0->data;
1697 } else {
1698 src0_alloc.alloc(ggml_nelements(src0));
1699
1700 if (ggml_is_contiguously_allocated(src0)) {
1701 const auto convert_func = traits::convert(src0->type);
1702 GGML_ASSERT(convert_func != nullptr);
1703 convert_func(src0->data, src0_alloc.get(), ggml_nelements(src0), main_stream);
1704 const size_t src0_bs = ggml_blck_size(src0->type);
1705 s01 *= src0_bs;
1706 s02 *= src0_bs;
1707 s03 *= src0_bs;
1708 } else {
1709 const auto convert_func = traits::convert_nc(src0->type);
1710 GGML_ASSERT(convert_func != nullptr);
1711 convert_func(src0->data, src0_alloc.get(), ne00, ne01, ne02, ne03, s01, s02, s03, main_stream);
1712 s01 = ne00;
1713 s02 = ne01*s01;
1714 s03 = ne02*s02;
1715 is_src0_cont_2 = true;
1716 }
1717 src0_ptr = src0_alloc.get();
1718 }
1719
1720 if (src1->type == compute_type) {
1721 src1_ptr = (const cuda_t *) src1->data;
1722 } else {
1723 src1_alloc.alloc(ggml_nelements(src1));
1724
1725 if (ggml_is_contiguously_allocated(src1)) {
1726 const auto convert_func = traits::convert(src1->type);
1727 GGML_ASSERT(convert_func != nullptr);
1728 convert_func(src1->data, src1_alloc.get(), ggml_nelements(src1), main_stream);
1729 const size_t src1_bs = ggml_blck_size(src1->type);
1730 s11 *= src1_bs;
1731 s12 *= src1_bs;
1732 s13 *= src1_bs;
1733 } else {
1734 const auto convert_func = traits::convert_nc(src1->type);
1735 GGML_ASSERT(convert_func != nullptr);
1736 convert_func(src1->data, src1_alloc.get(), ne10, ne11, ne12, ne13, s11, s12, s13, main_stream);
1737 s11 = ne10;
1738 s12 = ne11*s11;
1739 s13 = ne12*s12;
1740 is_src1_cont_2 = true;
1741 }
1742 src1_ptr = src1_alloc.get();
1743 }
1744
1745 ggml_cuda_pool_alloc<cuda_t> dst_temp(ctx.pool());
1746 char * dst_ptr;
1747 size_t nbd2 = dst->nb[2];
1748 size_t nbd3 = dst->nb[3];
1749
1750 cublasComputeType_t cu_compute_type = traits::compute_type;
1751 cudaDataType_t cu_data_type = traits::data_type;
1752 cudaDataType_t cu_data_type_a = traits::data_type;
1753 cudaDataType_t cu_data_type_b = traits::data_type;
1754 const void * alpha = traits::get_alpha();
1755 const void * beta = traits::get_beta();
1756
1757 const int cc = ggml_cuda_info().devices[ctx.device].cc;
1758 bool prefer_f32_output = false;
1759 if (compute_type == GGML_TYPE_F16) {
1760 prefer_f32_output = cc == GGML_CUDA_CC_VOLTA || GGML_CUDA_CC_IS_RDNA4(cc) || GGML_CUDA_CC_IS_CDNA(cc);
1761 } else if (compute_type == GGML_TYPE_BF16) {
1762 prefer_f32_output = !GGML_CUDA_CC_IS_RDNA3(cc) && !GGML_CUDA_CC_IS_RDNA4_M(cc) && !GGML_CUDA_CC_IS_CDNA(cc);
1763 }
1764
1765 if (prefer_f32_output) {
1766 dst_ptr = (char *) dst_ddf;
1767 cu_compute_type = batched_mul_mat_traits<GGML_TYPE_F32>::compute_type;
1768 cu_data_type = batched_mul_mat_traits<GGML_TYPE_F32>::data_type;
1769 alpha = batched_mul_mat_traits<GGML_TYPE_F32>::get_alpha();
1770 beta = batched_mul_mat_traits<GGML_TYPE_F32>::get_beta();
1771 } else {
1772 if constexpr (compute_type == GGML_TYPE_F32) {
1773 dst_ptr = (char *) dst_ddf; // Direct F32 output
1774 } else {
1775 dst_ptr = (char *) dst_temp.alloc(ne_dst);
1776 nbd2 /= sizeof(float) / sizeof(cuda_t);
1777 nbd3 /= sizeof(float) / sizeof(cuda_t);
1778 }
1779 }
1780
1781 GGML_ASSERT(ne12 % ne02 == 0);
1782 GGML_ASSERT(ne13 % ne03 == 0);
1783
1784 // broadcast factors
1785 const int64_t r2 = ne12/ne02;
1786 const int64_t r3 = ne13/ne03;
1787
1788 // Theoretically cublasGemmStridedBatchedEx would always work, even for a single matrix.
1789 // However, for some old NVIDIA and AMD GPUs the strided/Ex GEMM is much slower,
1790 // probably because the internal kernel selection logic is suboptimal.
1791 if (compute_type == GGML_TYPE_F32 && ne12 == 1 && ne13 == 1) {
1792 CUBLAS_CHECK(
1793 cublasSgemm(cublas_h, CUBLAS_OP_T, CUBLAS_OP_N,
1794 ne01, ne11, ne10,
1795 (const float *) alpha, (const float *) src0_ptr, s01,
1796 (const float *) src1_ptr, s11,
1797 (const float *) beta, (float *) dst_ptr, ldc));
1798 } else if (ne12 == 1 && ne13 == 1) {
1799 CUBLAS_CHECK(
1800 cublasGemmEx(cublas_h, CUBLAS_OP_T, CUBLAS_OP_N,
1801 ne01, ne11, ne10,
1802 alpha, src0_ptr, cu_data_type_a, s01,
1803 src1_ptr, cu_data_type_b, s11,
1804 beta, dst_ptr, cu_data_type, ldc,
1805 cu_compute_type,
1806 CUBLAS_GEMM_DEFAULT_TENSOR_OP));
1807 } else if (r2 == 1 && r3 == 1 && is_src0_cont_2 && is_src1_cont_2) {
1808 // with a [0, 2, 1, 3] perm. and ne02==1 the matrix strides need to be determined from dim 3:
1809 const int64_t sma = ne02 == 1 ? s03 : s02;
1810 const int64_t smb = ne12 == 1 ? s13 : s12;
1811
1812 // there is no broadcast and src0, src1 are contiguous across dims 2, 3
1813 // use cublasGemmStridedBatchedEx
1814 CUBLAS_CHECK(
1815 cublasGemmStridedBatchedEx(cublas_h, CUBLAS_OP_T, CUBLAS_OP_N,
1816 ne01, ne11, ne10,
1817 alpha, src0_ptr, cu_data_type_a, s01, sma, // strideA
1818 src1_ptr, cu_data_type_b, s11, smb, // strideB
1819 beta, dst_ptr, cu_data_type, ldc, ne1*ldc, // strideC
1820 ne12*ne13,
1821 cu_compute_type,
1822 CUBLAS_GEMM_DEFAULT_TENSOR_OP));
1823 } else {
1824 // use cublasGemmBatchedEx
1825 const int64_t ne23 = ne12*ne13;
1826
1827 ggml_cuda_pool_alloc<const void *> ptrs_src(ctx.pool(), 2*ne23);
1828 ggml_cuda_pool_alloc< void *> ptrs_dst(ctx.pool(), 1*ne23);
1829
1830 const size_t src_type_size = sizeof(cuda_t);
1831
1832 const int threads_x = 16;
1833 const int threads_y = 16;
1834 const dim3 block_dims(threads_x, threads_y);
1835
1836 const dim3 grid_dims(
1837 (ne13 + threads_x - 1) / threads_x,
1838 (ne12 + threads_y - 1) / threads_y
1839 );
1840 k_compute_batched_ptrs<<<grid_dims, block_dims, 0, main_stream>>>(
1841 src0_ptr, src1_ptr, dst_ptr,
1842 ptrs_src.get(), ptrs_dst.get(),
1843 ne12, ne13,
1844 ne23,
1845 s02*src_type_size, s03*src_type_size,
1846 s12*src_type_size, s13*src_type_size,
1847 nbd2, nbd3,
1848 r2, r3);
1849
1850 CUDA_CHECK(cudaGetLastError());
1851
1852 CUBLAS_CHECK(
1853 cublasGemmBatchedEx(cublas_h, CUBLAS_OP_T, CUBLAS_OP_N,
1854 ne01, ne11, ne10,
1855 alpha, (const void **) (ptrs_src.get() + 0*ne23), cu_data_type_a, s01,
1856 (const void **) (ptrs_src.get() + 1*ne23), cu_data_type_b, s11,
1857 beta, ( void **) (ptrs_dst.get() + 0*ne23), cu_data_type, ldc,
1858 ne23,
1859 cu_compute_type,
1860 CUBLAS_GEMM_DEFAULT_TENSOR_OP));
1861 }
1862
1863 // Convert output back to F32 if needed
1864 if (cu_data_type != CUDA_R_32F) {
1865 const to_fp32_cuda_t to_fp32_cuda = ggml_get_to_fp32_cuda(traits::ggml_type_val);
1866 to_fp32_cuda(dst_temp.get(), dst_ddf, ne_dst, main_stream);
1867 }
1868}
1869
1870static void ggml_cuda_mul_mat_cublas(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
1871 const int cc = ggml_cuda_info().devices[ctx.device].cc;
1872 const ggml_prec prec = (ggml_prec) ggml_get_op_params_i32(dst, 0);
1873 ggml_type compute_type = src0->type;
1874 if (ggml_is_quantized(compute_type)) {
1875 compute_type = fast_fp16_hardware_available(cc) ? GGML_TYPE_F16 : GGML_TYPE_F32;
1876 } else if (compute_type == GGML_TYPE_F16 && !fast_fp16_hardware_available(cc)) {
1877 compute_type = GGML_TYPE_F32;
1878 } else if (compute_type == GGML_TYPE_BF16 && !fast_bf16_hardware_available(cc)) {
1879 if (GGML_CUDA_CC_IS_AMD(cc) && src1->ne[1] > 32) {
1880 compute_type = GGML_TYPE_F32;
1881 }
1882 if (GGML_CUDA_CC_IS_NVIDIA(cc) && src1->ne[1] > (cc >= GGML_CUDA_CC_VOLTA ? 8 : 128)) {
1883 compute_type = GGML_TYPE_F32;
1884 }
1885 }
1886 // F16 is the only compute type that can not satisfy a request for BF16
1887 if (prec == GGML_PREC_BF16 && compute_type == GGML_TYPE_F16) {
1888 compute_type = fast_bf16_hardware_available(cc) ? GGML_TYPE_BF16 : GGML_TYPE_F32;
1889 } else if (prec == GGML_PREC_F32) {
1890 compute_type = GGML_TYPE_F32;
1891 }
1892
1893 const char * env_c = getenv("GGML_CUDA_CUBLAS_COMPUTE_TYPE");
1894 if (env_c != nullptr) {
1895 std::string env_cpp = env_c;
1896 for (char & c : env_cpp) {
1897 c = std::tolower(c);
1898 }
1899 if (env_cpp == "f32" || env_cpp == "fp32") {
1900 compute_type = GGML_TYPE_F32;
1901 } else if (env_cpp == "f16" || env_cpp == "fp16") {
1902 compute_type = GGML_TYPE_F16;
1903 } else if (env_cpp == "bf16") {
1904 compute_type = GGML_TYPE_BF16;
1905 } else if (env_cpp != "auto") {
1906 GGML_LOG_WARN("%s: unknown value for GGML_CUDA_CUBLAS_COMPUTE_TYPE: %s", __func__, env_cpp.c_str());
1907 }
1908 }
1909
1910 constexpr size_t max_src0_convert_size = 512ull * 1024 * 1024;
1911 const size_t src0_f32_size = ggml_nelements(src0) * sizeof(float);
1912
1913 if (compute_type == GGML_TYPE_F32 &&
1914 (src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16) &&
1915 src0_f32_size > max_src0_convert_size) {
1916 const size_t f32_row_size = src0_f32_size / src0->ne[1];
1917 const int64_t rows_per_chunk = std::max<int64_t>(1, (int64_t) (max_src0_convert_size / f32_row_size));
1918
1919 if (rows_per_chunk < src0->ne[1]) {
1920 ggml_tensor src0_chunk = *src0;
1921 ggml_tensor dst_chunk = *dst;
1922
1923 for (int64_t i01 = 0; i01 < src0->ne[1]; i01 += rows_per_chunk) {
1924 src0_chunk.ne[1] = std::min(rows_per_chunk, src0->ne[1] - i01);
1925 src0_chunk.data = (char *) src0->data + i01*src0->nb[1];
1926
1927 dst_chunk.ne[0] = src0_chunk.ne[1];
1928 dst_chunk.data = (char *) dst->data + i01*dst->nb[0];
1929
1930 ggml_cuda_mul_mat_cublas_impl<GGML_TYPE_F32>(ctx, &src0_chunk, src1, &dst_chunk);
1931 }
1932 return;
1933 }
1934 }
1935
1936 switch (compute_type) {
1937 case GGML_TYPE_F32:
1938 ggml_cuda_mul_mat_cublas_impl<GGML_TYPE_F32>(ctx, src0, src1, dst);
1939 break;
1940 case GGML_TYPE_BF16:
1941 ggml_cuda_mul_mat_cublas_impl<GGML_TYPE_BF16>(ctx, src0, src1, dst);
1942 break;
1943 case GGML_TYPE_F16:
1944 ggml_cuda_mul_mat_cublas_impl<GGML_TYPE_F16>(ctx, src0, src1, dst);
1945 break;
1946 default:
1947 GGML_ABORT("fatal error");
1948 }
1949}
1950
1951static bool ggml_cuda_should_fuse_mul_mat(const ggml_tensor * ffn_up,
1952 const ggml_tensor * ffn_gate,
1953 const ggml_tensor * glu,
1954 const ggml_tensor * ffn_up_bias = nullptr,
1955 const ggml_tensor * ffn_gate_bias = nullptr,
1956 const ggml_tensor * ffn_up_scale = nullptr,
1957 const ggml_tensor * ffn_gate_scale = nullptr) {
1958 const bool has_bias = ffn_up_bias != nullptr || ffn_gate_bias != nullptr;
1959 const bool has_scale = ffn_up_scale != nullptr || ffn_gate_scale != nullptr;
1960
1961 if (has_bias && (!ffn_up_bias || !ffn_gate_bias)) {
1962 return false;
1963 }
1964 if (has_scale && (!ffn_up_scale || !ffn_gate_scale)) {
1965 return false;
1966 }
1967
1968 const bool is_mul_mat = ffn_up->op == GGML_OP_MUL_MAT && ffn_gate->op == GGML_OP_MUL_MAT && glu->op == GGML_OP_GLU;
1969 const bool is_mul_mat_id = ffn_up->op == GGML_OP_MUL_MAT_ID && ffn_gate->op == GGML_OP_MUL_MAT_ID && glu->op == GGML_OP_GLU;
1970
1971 GGML_ASSERT(ffn_up && ffn_gate && glu);
1972
1973 if (!is_mul_mat && !is_mul_mat_id) {
1974 return false;
1975 }
1976
1977 const ggml_op expected_bias_op = is_mul_mat ? GGML_OP_ADD : GGML_OP_ADD_ID;
1978 const ggml_tensor * ffn_up_bias_src = has_scale ? ffn_up_scale : ffn_up;
1979 const ggml_tensor * ffn_gate_bias_src = has_scale ? ffn_gate_scale : ffn_gate;
1980 const ggml_tensor * ffn_up_out = has_bias ? ffn_up_bias : ffn_up_bias_src;
1981 const ggml_tensor * ffn_gate_out = has_bias ? ffn_gate_bias : ffn_gate_bias_src;
1982
1983 if (glu->src[0] != ffn_gate_out || glu->src[1] != ffn_up_out) {
1984 return false;
1985 }
1986
1987 if (has_scale) {
1988 if (ffn_up_scale->op != GGML_OP_MUL || ffn_gate_scale->op != GGML_OP_MUL) {
1989 return false;
1990 }
1991 const bool up_has_mm = ffn_up_scale->src[0] == ffn_up || ffn_up_scale->src[1] == ffn_up;
1992 const bool gate_has_mm = ffn_gate_scale->src[0] == ffn_gate || ffn_gate_scale->src[1] == ffn_gate;
1993 if (!up_has_mm || !gate_has_mm) {
1994 return false;
1995 }
1996 }
1997
1998 if (has_bias) {
1999 if (ffn_up_bias->op != expected_bias_op || ffn_gate_bias->op != expected_bias_op) {
2000 return false;
2001 }
2002
2003 if (expected_bias_op == GGML_OP_ADD) {
2004 const bool up_has_mul = ffn_up_bias->src[0] == ffn_up_bias_src || ffn_up_bias->src[1] == ffn_up_bias_src;
2005 const bool gate_has_mul = ffn_gate_bias->src[0] == ffn_gate_bias_src || ffn_gate_bias->src[1] == ffn_gate_bias_src;
2006 if (!up_has_mul || !gate_has_mul) {
2007 return false;
2008 }
2009 } else { // GGML_OP_ADD_ID
2010 if (ffn_up_bias->src[0] != ffn_up_bias_src || ffn_gate_bias->src[0] != ffn_gate_bias_src) {
2011 return false;
2012 }
2013 if (ffn_up_bias->src[2] != ffn_up->src[2] || ffn_gate_bias->src[2] != ffn_gate->src[2]) {
2014 return false;
2015 }
2016 }
2017 }
2018
2019 if (ffn_up->src[0]->type != ffn_gate->src[0]->type || !ggml_are_same_shape(ffn_up->src[0], ffn_gate->src[0]) ||
2020 !ggml_are_same_stride(ffn_up->src[0], ffn_gate->src[0])) {
2021 return false;
2022 }
2023
2024 if (ffn_up->src[1] != ffn_gate->src[1]) {
2025 return false;
2026 }
2027
2028 if (is_mul_mat_id && ffn_up->src[2] != ffn_gate->src[2]) {
2029 return false;
2030 }
2031
2032 static constexpr std::array<ggml_glu_op, 4> valid_glu_ops = { GGML_GLU_OP_SWIGLU, GGML_GLU_OP_GEGLU, GGML_GLU_OP_SWIGLU_OAI, GGML_GLU_OP_SWIGLU_CLAMP };
2033
2034 if (std::find(valid_glu_ops.begin(), valid_glu_ops.end(), ggml_get_glu_op(glu)) == valid_glu_ops.end()) {
2035 return false;
2036 }
2037
2038 if (const bool swapped = ggml_get_op_params_i32(glu, 1); swapped) {
2039 return false;
2040 }
2041
2042 return true;
2043}
2044
2045static bool ggml_cuda_should_fuse_mul_mat_vec_f(const ggml_tensor * tensor) {
2046 ggml_tensor * src0 = tensor->src[0];
2047 ggml_tensor * src1 = tensor->src[1];
2048 const ggml_tensor * dst = tensor;
2049
2050 const bool is_mul_mat_id = tensor->op == GGML_OP_MUL_MAT_ID;
2051
2052 bool use_mul_mat_vec_f =
2053 (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16) &&
2054 src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32;
2055
2056 const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
2057 const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size;
2058 use_mul_mat_vec_f = use_mul_mat_vec_f && ggml_cuda_should_use_mmvf(src0->type, cc, warp_size, src0->ne, src0->nb, is_mul_mat_id ? src1->ne[2] : src1->ne[1]);
2059
2060 //we only support fusion for ncols_dst = 1
2061 if (tensor->op == GGML_OP_MUL_MAT && dst->ne[1] != 1) {
2062 return false;
2063 }
2064
2065 if (tensor->op == GGML_OP_MUL_MAT_ID && dst->ne[2] != 1) {
2066 return false;
2067 }
2068
2069
2070 return use_mul_mat_vec_f;
2071}
2072
2073static bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor) {
2074 ggml_tensor * src0 = tensor->src[0];
2075 ggml_tensor * src1 = tensor->src[1];
2076 const ggml_tensor * dst = tensor;
2077
2078 const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE &&
2079 ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) &&
2080 src0->view_src;
2081
2082 bool use_mul_mat_vec_q = ggml_is_quantized(src0->type) && !bad_padding_clear && src1->type == GGML_TYPE_F32 &&
2083 dst->type == GGML_TYPE_F32 && src1->ne[1] <= MMVQ_MAX_BATCH_SIZE;
2084
2085 // fusion is not universally faster on Pascal
2086 const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
2087 if (cc <= GGML_CUDA_CC_PASCAL) {
2088 return false;
2089 }
2090 //we only support fusion for ncols_dst = 1
2091 if (tensor->op == GGML_OP_MUL_MAT && dst->ne[1] != 1) {
2092 return false;
2093 }
2094
2095 if (tensor->op == GGML_OP_MUL_MAT_ID && dst->ne[2] > get_mmvq_mmid_max_batch(src0->type, cc)) {
2096 return false;
2097 }
2098
2099 return use_mul_mat_vec_q;
2100}
2101
2102static bool ggml_cuda_match_shared_expert(const ggml_cgraph * graph, int routed_idx, int shared_idx) {
2103 if (routed_idx + 2 >= graph->n_nodes || shared_idx + 2 >= graph->n_nodes || shared_idx < routed_idx + 3) {
2104 return false;
2105 }
2106 const int nodes[] = { routed_idx, routed_idx + 1, routed_idx + 2, shared_idx, shared_idx + 1, shared_idx + 2 };
2107 const ggml_op ops[] = { GGML_OP_MUL_MAT_ID, GGML_OP_MUL_MAT_ID, GGML_OP_GLU,
2108 GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU };
2109 const int outputs[] = { routed_idx + 2, shared_idx + 2 };
2110 if (!ggml_can_fuse_subgraph_ext(graph, nodes, 6, ops, outputs, 2)) {
2111 return false;
2112 }
2113
2114 const ggml_tensor * routed = graph->nodes[routed_idx + 2];
2115 const ggml_tensor * shared = graph->nodes[shared_idx + 2];
2116 const ggml_tensor * gate = routed->src[0];
2117 const ggml_tensor * up = routed->src[1];
2118 const ggml_tensor * shared_gate = shared->src[0];
2119 const ggml_tensor * shared_up = shared->src[1];
2120 const auto is_pair = [&](const ggml_tensor * a, const ggml_tensor * b, int idx) {
2121 return (a == graph->nodes[idx] && b == graph->nodes[idx + 1]) ||
2122 (b == graph->nodes[idx] && a == graph->nodes[idx + 1]);
2123 };
2124 // only batch-size independent checks here: graph_optimize must produce the same graph topology for every ubatch
2125 // size, otherwise ggml-alloc has to re-reserve (and the scheduler to synchronize) at runtime.
2126 // the MMVQ batch size check is done in ggml_cuda_try_fuse
2127 if (!is_pair(gate, up, routed_idx) || !is_pair(shared_gate, shared_up, shared_idx) ||
2128 !ggml_cuda_should_fuse_mul_mat(up, gate, routed) ||
2129 !ggml_cuda_should_fuse_mul_mat(shared_up, shared_gate, shared) ||
2130 !up->src[0]->buffer ||
2131 !ggml_is_quantized(up->src[0]->type)) {
2132 return false;
2133 }
2134 const ggml_tensor * input = up->src[1];
2135 const ggml_tensor * weight = up->src[0];
2136 const ggml_tensor * shared_weight = shared_up->src[0];
2137 if (input->op != GGML_OP_RESHAPE || input->src[0] != shared_up->src[1] ||
2138 input->ne[1] != 1 || input->ne[3] != 1 || !ggml_is_contiguous(input) ||
2139 !ggml_is_contiguous(shared_up->src[1]) || !ggml_is_matrix(shared_up->src[1]) ||
2140 weight->type != shared_weight->type || weight->ne[0] != shared_weight->ne[0] ||
2141 weight->ne[1] != shared_weight->ne[1] || weight->nb[1] != shared_weight->nb[1] || weight->ne[3] != 1 ||
2142 !ggml_is_matrix(shared_weight) || !ggml_is_contiguous(shared_weight) ||
2143 !ggml_is_contiguous(shared_gate->src[0]) || !ggml_is_contiguous(routed) || !ggml_is_contiguous(shared)) {
2144 return false;
2145 }
2146 if (shared_weight->op != GGML_OP_NONE || shared_gate->src[0]->op != GGML_OP_NONE ||
2147 ggml_get_glu_op(routed) != ggml_get_glu_op(shared) ||
2148 ggml_get_op_params_f32(routed, 3) != ggml_get_op_params_f32(shared, 3)) {
2149 return false;
2150 }
2151 return true;
2152}
2153
2154// Buffer- and batch-size independent, so graph_optimize produces the same graph topology for every ubatch size (see #29986).
2155static bool ggml_cuda_mul_mat_q_fusion_matches(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu, const int device) {
2156 const ggml_tensor * x_up = up->src[0];
2157 const ggml_tensor * y = up->src[1];
2158
2159 if ((up->op != GGML_OP_MUL_MAT && up->op != GGML_OP_MUL_MAT_ID) || !ggml_cuda_mmq_fusion_supported(x_up->type) || y->type != GGML_TYPE_F32) {
2160 return false;
2161 }
2162
2163 // The fused kernel is only compiled for weights whose rows fill whole tiles (no fallback).
2164 if (ggml_cuda_mmq_needs_fallback(x_up->ne[1])) {
2165 return false;
2166 }
2167
2168 if (!ggml_cuda_should_fuse_mul_mat(up, gate, glu)) {
2169 return false;
2170 }
2171
2172 // The fused write-back applies SWIGLU_OAI with the default alpha and limit of ggml_cuda_op_swiglu_oai_single.
2173 if (ggml_get_glu_op(glu) == GGML_GLU_OP_SWIGLU_OAI && (ggml_get_op_params_f32(glu, 2) != 1.702f || ggml_get_op_params_f32(glu, 3) != 7.0f)) {
2174 return false;
2175 }
2176
2177 // NVIDIA only: the fused write-back relies on the MMA accumulator layout.
2178 return turing_mma_available(ggml_cuda_info().devices[device].cc);
2179}
2180
2181static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu) {
2182 // A hinted matmul can be fused, but its unfused path may be faster (e.g. FWHT for GGML_HINT_SRC0_IS_HADAMARD).
2183 if (ggml_get_op_params_i32(up, 1) != GGML_HINT_NONE || ggml_get_op_params_i32(gate, 1) != GGML_HINT_NONE) {
2184 return false;
2185 }
2186
2187 // The padding of a compute-buffer weight that is a view cannot be cleared, see ggml_cuda_mul_mat.
2188 const auto bad_padding_clear = [](const ggml_tensor * x) {
2189 return ggml_backend_buffer_get_usage(x->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE &&
2190 ggml_nbytes(x) != ggml_backend_buffer_get_alloc_size(x->buffer, x) && x->view_src;
2191 };
2192 const int device = ggml_cuda_get_device();
2193 if (!ggml_cuda_mul_mat_q_fusion_matches(up, gate, glu, device) || bad_padding_clear(up->src[0]) || bad_padding_clear(gate->src[0])) {
2194 return false;
2195 }
2196
2197 // The batch size checks are done here, not in ggml_cuda_mul_mat_q_fusion_matches.
2198 const ggml_tensor * x_up = up->src[0];
2199 const ggml_tensor * y = up->src[1];
2200 const int cc = ggml_cuda_info().devices[device].cc;
2201
2202 // For MUL_MAT_ID: same kernel choice as ggml_cuda_mul_mat_id, with the nominal tiles of all experts (the per-expert token counts are only known on the GPU).
2203 const bool is_id = up->op == GGML_OP_MUL_MAT_ID;
2204 const int64_t ncols = is_id ? y->ne[2] : y->ne[1];
2205 const int64_t nchannels = is_id ? x_up->ne[2] : y->ne[2]*y->ne[3];
2206 const bool use_mmvq = is_id ? ncols <= get_mmvq_mmid_max_batch(x_up->type, cc) : ggml_cuda_should_use_mmvq(x_up->type, cc, ncols);
2207 if (use_mmvq || !ggml_cuda_should_use_mmq(x_up->type, cc, ncols, /*n_experts =*/ is_id ? x_up->ne[2] : 0)) {
2208 return false;
2209 }
2210
2211 // The fused kernel needs one block per tile (no stream-k split), so only fuse if the tiling is efficient.
2212 return ggml_cuda_mmq_fusion_is_efficient(x_up->type, x_up->ne[1], ncols, nchannels, device);
2213}
2214
2215static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
2216 GGML_TENSOR_BINARY_OP_LOCALS
2217
2218 if (ggml_cuda_op_mul_mat_use_fwht(dst) && ggml_cuda_op_fwht(ctx, src1, dst)) {
2219 return;
2220 }
2221
2222 // If src0 is a temporary compute buffer it may have some padding that needs to be cleared for mul_mat_vec_q or mul_mat_q.
2223 // But if src0 is also a view of another tensor then this cannot be done safely because it may overwrite valid tensor data.
2224 // Therefore, in such cases use cuBLAS.
2225 const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE
2226 && ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) && src0->view_src;
2227 if (bad_padding_clear || src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
2228 ggml_cuda_mul_mat_cublas(ctx, src0, src1, dst);
2229 return;
2230 }
2231
2232 const int cc = ggml_cuda_info().devices[ctx.device].cc;
2233 const int warp_size = ggml_cuda_info().devices[ctx.device].warp_size;
2234
2235 if (ggml_cuda_should_use_mmvf(src0->type, cc, warp_size, src0->ne, src0->nb, ne11)) {
2236 // The custom F16 vector kernel can be used over batched cuBLAS GEMM.
2237 // But this is only faster for GPUs without tensor cores or with a thin src0 matrix (particularly KQV in attention)
2238 ggml_cuda_mul_mat_vec_f(ctx, src0, src1, nullptr, dst);
2239 return;
2240 }
2241 // A transposed vector can still use MMVQ (i.e. ne01 == 1)
2242 if (ne01 == 1 && ne11 > MMVF_MAX_BATCH_SIZE && ne2 == 1 && ne3 == 1
2243 && src0->type == GGML_TYPE_F32
2244 && ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)
2245 && ggml_cuda_should_use_mmvf(src1->type, cc, warp_size, src1->ne, src1->nb, /*ne11 =*/ 1)) {
2246 ggml_tensor dst_vec = *dst;
2247 dst_vec.ne[0] = ne11;
2248 dst_vec.ne[1] = 1;
2249 dst_vec.nb[1] = dst_vec.nb[0]*ne11;
2250 dst_vec.nb[2] = dst_vec.nb[1];
2251 dst_vec.nb[3] = dst_vec.nb[1];
2252 ggml_cuda_mul_mat_vec_f(ctx, src1, src0, nullptr, &dst_vec);
2253 return;
2254 }
2255 if (ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, ne11, /*mul_mat_id =*/ false)) {
2256 ggml_cuda_mul_mat_f(ctx, src0, src1, nullptr, dst);
2257 return;
2258 }
2259 if (ggml_cuda_should_use_mmvq(src0->type, cc, ne11)) {
2260 ggml_cuda_mul_mat_vec_q(ctx, src0, src1, nullptr, dst);
2261 return;
2262 }
2263 if (ggml_cuda_should_use_mmq(src0->type, cc, ne11, /*n_experts =*/ 0)) {
2264 ggml_cuda_mul_mat_q(ctx, src0, src1, nullptr, dst);
2265 return;
2266 }
2267 ggml_cuda_mul_mat_cublas(ctx, src0, src1, dst);
2268}
2269
2270// returns true when ggml_cuda_mul_mat_id takes the fallback path that requires stream synchronization
2271// [TAG_MUL_MAT_ID_CUDA_GRAPHS]
2272static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int cc) {
2273 const ggml_tensor * src0 = dst->src[0];
2274 const ggml_tensor * src1 = dst->src[1];
2275
2276 const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size;
2277
2278 if (src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
2279 return true;
2280 }
2281
2282 if (dst->ne[2] <= MMVQ_MAX_BATCH_SIZE) {
2283 if (ggml_is_quantized(src0->type)) {
2284 if (dst->ne[2] <= get_mmvq_mmid_max_batch(src0->type, cc)) {
2285 return false;
2286 }
2287 } else if (GGML_CUDA_CC_IS_AMD(cc)) {
2288 return false;
2289 }
2290 }
2291
2292 if (ggml_cuda_should_use_mmq(src0->type, cc, src1->ne[2], /*n_experts=*/src0->ne[2])) {
2293 return false;
2294 }
2295
2296 if (ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) {
2297 return false;
2298 }
2299
2300 return true;
2301}
2302
2303static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
2304 const ggml_tensor * src0 = dst->src[0];
2305 const ggml_tensor * src1 = dst->src[1];
2306 const ggml_tensor * ids = dst->src[2];
2307
2308 GGML_ASSERT(src1->type == GGML_TYPE_F32);
2309 GGML_ASSERT(dst->type == GGML_TYPE_F32);
2310
2311 GGML_TENSOR_BINARY_OP_LOCALS
2312
2313 const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
2314 const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size;
2315
2316 // [TAG_MUL_MAT_ID_CUDA_GRAPHS]
2317 if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
2318 static_assert(MMVQ_MAX_BATCH_SIZE == MMVF_MAX_BATCH_SIZE);
2319 if (ne2 <= MMVQ_MAX_BATCH_SIZE) {
2320 if (ggml_is_quantized(src0->type)) {
2321 const int mmvq_mmid_max = get_mmvq_mmid_max_batch(src0->type, cc);
2322 if (ne2 <= mmvq_mmid_max) {
2323 ggml_cuda_mul_mat_vec_q(ctx, src0, src1, ids, dst);
2324 return;
2325 }
2326 } else {
2327 if (GGML_CUDA_CC_IS_AMD(cc)) {
2328 ggml_cuda_mul_mat_vec_f(ctx, src0, src1, ids, dst);
2329 return;
2330 }
2331 }
2332 }
2333
2334 if (ggml_cuda_should_use_mmq(src0->type, cc, ne12, /*n_experts=*/ne02)) {
2335 ggml_cuda_mul_mat_q(ctx, src0, src1, ids, dst);
2336 return;
2337 }
2338
2339 if (ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) {
2340 ggml_cuda_mul_mat_f(ctx, src0, src1, ids, dst);
2341 return;
2342 }
2343 }
2344
2345 // note: this path should not be reached when recording CUDA graphs, because it requires stream synchronization
2346 GGML_ASSERT(ggml_cuda_mul_mat_id_needs_sync(dst, cc));
2347 cudaStream_t stream = ctx.stream();
2348
2349 GGML_ASSERT(nb12 % nb11 == 0);
2350 GGML_ASSERT(nb2 % nb1 == 0);
2351
2352 const ggml_type type_src1_sorted = (src0->type == GGML_TYPE_F16 && !fast_fp16_hardware_available(cc))
2353 || ggml_is_quantized(src0->type) ? GGML_TYPE_F32 : src0->type;
2354 const ggml_type type_dst_sorted = GGML_TYPE_F32;
2355 const size_t ts_src1_sorted = ggml_type_size(type_src1_sorted);
2356 const size_t ts_dst_sorted = ggml_type_size(type_dst_sorted);
2357
2358 const int64_t n_expert_used = ids->ne[0];
2359 const int64_t ne_get_rows = ne12 * n_expert_used;
2360
2361 std::vector<int32_t> ids_to_sorted_host;
2362 ids_to_sorted_host.reserve(2*ne_get_rows);
2363 std::vector<int32_t> ids_from_sorted_host(ne_get_rows);
2364
2365 ggml_cuda_pool_alloc<int32_t> ids_buf_dev(ctx.pool(), 2*ne_get_rows);
2366
2367 std::vector<int32_t> tokens_per_expert(ne02);
2368
2369 ggml_cuda_pool_alloc<char> src1_sorted(ctx.pool(), ne12*n_expert_used*ne10*ts_src1_sorted);
2370 ggml_cuda_pool_alloc<char> dst_sorted(ctx.pool(), ne2 *n_expert_used* ne0*ts_dst_sorted);
2371
2372 std::vector<char> ids_host(ggml_nbytes(ids));
2373 CUDA_CHECK(cudaMemcpyAsync(ids_host.data(), ids->data, ggml_nbytes(ids), cudaMemcpyDeviceToHost, stream));
2374 CUDA_CHECK(cudaStreamSynchronize(stream));
2375
2376 for (int64_t i02 = 0; i02 < ne02; ++i02) { // expert matrices
2377 for (int64_t i12 = 0; i12 < ne12; ++i12) { // tokens
2378 for (int64_t iex = 0; iex < n_expert_used; ++iex) {
2379 const int32_t expert_to_use = *(const int32_t *)(ids_host.data() + i12*ids->nb[1] + iex*ids->nb[0]);
2380 assert(expert_to_use >= 0 && expert_to_use < ne02);
2381 if (expert_to_use == i02) {
2382 ids_from_sorted_host[i12*n_expert_used + iex] = ids_to_sorted_host.size();
2383 ids_to_sorted_host.push_back(i12*ne11 + iex % ne11);
2384 tokens_per_expert[i02]++;
2385 break;
2386 }
2387 }
2388 }
2389 }
2390 GGML_ASSERT(ids_to_sorted_host.size() == size_t(ne_get_rows));
2391
2392 ids_to_sorted_host.insert(ids_to_sorted_host.end(), ids_from_sorted_host.begin(), ids_from_sorted_host.end());
2393
2394 CUDA_CHECK(cudaMemcpyAsync(ids_buf_dev.ptr, ids_to_sorted_host.data(), 2*ne_get_rows*sizeof(int32_t), cudaMemcpyHostToDevice, stream));
2395 CUDA_CHECK(cudaStreamSynchronize(stream));
2396
2397 const int32_t * ids_to_sorted = ids_buf_dev.ptr + 0*ne_get_rows;
2398 const int32_t * ids_from_sorted = ids_buf_dev.ptr + 1*ne_get_rows;
2399
2400 get_rows_cuda(src1->data, src1->type, ids_to_sorted, src1_sorted.ptr, type_src1_sorted,
2401 ne10, nb11, nb12, nb13,
2402 ne_get_rows, 1, 1, sizeof(int32_t), ne_get_rows*sizeof(int32_t), ne_get_rows*sizeof(int32_t),
2403 ne10*ts_src1_sorted, ne_get_rows*ne10*ts_src1_sorted, ne_get_rows*ne10*ts_src1_sorted, stream);
2404 CUDA_CHECK(cudaGetLastError());
2405
2406 char * src1_data_cur = (char *) src1_sorted.ptr;
2407 char * dst_data_cur = (char *) dst_sorted.ptr;
2408 for (int64_t i02 = 0; i02 < ne02; ++i02) {
2409 if (tokens_per_expert[i02] == 0) {
2410 continue;
2411 }
2412
2413 ggml_tensor src0_slice = *src0;
2414 src0_slice.ne[2] = 1;
2415 src0_slice.nb[3] = src0_slice.nb[2];
2416 src0_slice.op = GGML_OP_VIEW;
2417 src0_slice.view_src = dst->src[0]; // non-const pointer to src0
2418 src0_slice.data = (char *) src0->data + i02*nb02;
2419
2420 ggml_tensor src1_slice;
2421 memset(&src1_slice, 0, sizeof(src1_slice));
2422 src1_slice.buffer = src1->buffer;
2423 src1_slice.type = type_src1_sorted;
2424 src1_slice.ne[0] = ne10;
2425 src1_slice.ne[1] = tokens_per_expert[i02];
2426 src1_slice.ne[2] = 1;
2427 src1_slice.ne[3] = 1;
2428 src1_slice.nb[0] = ts_src1_sorted;
2429 src1_slice.nb[1] = src1_slice.ne[0] * src1_slice.nb[0];
2430 src1_slice.nb[2] = src1_slice.ne[1] * src1_slice.nb[1];
2431 src1_slice.nb[3] = src1_slice.ne[2] * src1_slice.nb[2];
2432 src1_slice.data = src1_data_cur;
2433
2434 ggml_tensor dst_slice;
2435 memset(&dst_slice, 0, sizeof(dst_slice));
2436 memcpy(dst_slice.op_params, dst->op_params, sizeof(dst_slice.op_params));
2437 dst_slice.buffer = dst->buffer;
2438 dst_slice.type = type_dst_sorted;
2439 dst_slice.ne[0] = ne0;
2440 dst_slice.ne[1] = tokens_per_expert[i02];
2441 dst_slice.ne[2] = 1;
2442 dst_slice.ne[3] = 1;
2443 dst_slice.nb[0] = ts_dst_sorted;
2444 dst_slice.nb[1] = dst_slice.ne[0] * dst_slice.nb[0];
2445 dst_slice.nb[2] = dst_slice.ne[1] * dst_slice.nb[1];
2446 dst_slice.nb[3] = dst_slice.ne[2] * dst_slice.nb[2];
2447 dst_slice.data = dst_data_cur;
2448
2449 ggml_cuda_mul_mat(ctx, &src0_slice, &src1_slice, &dst_slice);
2450 CUDA_CHECK(cudaGetLastError());
2451
2452 src1_data_cur += src1_slice.nb[2];
2453 dst_data_cur += dst_slice.nb[2];
2454 }
2455
2456 get_rows_cuda(dst_sorted.ptr, type_dst_sorted, ids_from_sorted, dst->data, dst->type,
2457 ne0, ne0*ts_dst_sorted, ne_get_rows*ne0*ts_dst_sorted, ne_get_rows*ne0*ts_dst_sorted,
2458 ne_get_rows, 1, 1, sizeof(int32_t), ne_get_rows*sizeof(int32_t), ne_get_rows*sizeof(int32_t),
2459 nb1, nb2, nb3, stream);
2460}
2461
2462static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct ggml_tensor * dst) {
2463 switch (dst->op) {
2464 case GGML_OP_ARGMAX:
2465 ggml_cuda_argmax(ctx, dst);
2466 break;
2467 case GGML_OP_COUNT_EQUAL:
2468 ggml_cuda_count_equal(ctx, dst);
2469 break;
2470 case GGML_OP_REPEAT:
2471 ggml_cuda_op_repeat(ctx, dst);
2472 break;
2473 case GGML_OP_REPEAT_BACK:
2474 ggml_cuda_op_repeat_back(ctx, dst);
2475 break;
2476 case GGML_OP_GET_ROWS:
2477 ggml_cuda_op_get_rows(ctx, dst);
2478 break;
2479 case GGML_OP_GET_ROWS_BACK:
2480 ggml_cuda_op_get_rows_back(ctx, dst);
2481 break;
2482 case GGML_OP_SET_ROWS:
2483 ggml_cuda_op_set_rows(ctx, dst);
2484 break;
2485 case GGML_OP_SET:
2486 ggml_cuda_op_set(ctx, dst);
2487 break;
2488 case GGML_OP_DUP:
2489 ggml_cuda_dup(ctx, dst);
2490 break;
2491 case GGML_OP_CPY:
2492 ggml_cuda_cpy(ctx, dst->src[0], dst->src[1]);
2493 break;
2494 case GGML_OP_CONT:
2495 ggml_cuda_dup(ctx, dst);
2496 break;
2497 case GGML_OP_ADD:
2498 case GGML_OP_ADD1: // TODO: more efficient implementation
2499 ggml_cuda_op_add(ctx, dst);
2500 break;
2501 case GGML_OP_ADD_ID:
2502 ggml_cuda_op_add_id(ctx, dst);
2503 break;
2504 case GGML_OP_SUB:
2505 ggml_cuda_op_sub(ctx, dst);
2506 break;
2507 case GGML_OP_ACC:
2508 ggml_cuda_op_acc(ctx, dst);
2509 break;
2510 case GGML_OP_MUL:
2511 ggml_cuda_op_mul(ctx, dst);
2512 break;
2513 case GGML_OP_DIV:
2514 ggml_cuda_op_div(ctx, dst);
2515 break;
2516 case GGML_OP_UNARY:
2517 switch (ggml_get_unary_op(dst)) {
2518 case GGML_UNARY_OP_ABS:
2519 ggml_cuda_op_abs(ctx, dst);
2520 break;
2521 case GGML_UNARY_OP_SGN:
2522 ggml_cuda_op_sgn(ctx, dst);
2523 break;
2524 case GGML_UNARY_OP_NEG:
2525 ggml_cuda_op_neg(ctx, dst);
2526 break;
2527 case GGML_UNARY_OP_STEP:
2528 ggml_cuda_op_step(ctx, dst);
2529 break;
2530 case GGML_UNARY_OP_GELU:
2531 ggml_cuda_op_gelu(ctx, dst);
2532 break;
2533 case GGML_UNARY_OP_SILU:
2534 ggml_cuda_op_silu(ctx, dst);
2535 break;
2536 case GGML_UNARY_OP_GELU_ERF:
2537 ggml_cuda_op_gelu_erf(ctx, dst);
2538 break;
2539 case GGML_UNARY_OP_GELU_QUICK:
2540 ggml_cuda_op_gelu_quick(ctx, dst);
2541 break;
2542 case GGML_UNARY_OP_TANH:
2543 ggml_cuda_op_tanh(ctx, dst);
2544 break;
2545 case GGML_UNARY_OP_RELU:
2546 ggml_cuda_op_relu(ctx, dst);
2547 break;
2548 case GGML_UNARY_OP_SIGMOID:
2549 ggml_cuda_op_sigmoid(ctx, dst);
2550 break;
2551 case GGML_UNARY_OP_HARDSIGMOID:
2552 ggml_cuda_op_hardsigmoid(ctx, dst);
2553 break;
2554 case GGML_UNARY_OP_HARDSWISH:
2555 ggml_cuda_op_hardswish(ctx, dst);
2556 break;
2557 case GGML_UNARY_OP_EXP:
2558 ggml_cuda_op_exp(ctx, dst);
2559 break;
2560 case GGML_UNARY_OP_ELU:
2561 ggml_cuda_op_elu(ctx, dst);
2562 break;
2563 case GGML_UNARY_OP_XIELU:
2564 ggml_cuda_op_xielu(ctx, dst);
2565 break;
2566 case GGML_UNARY_OP_FLOOR:
2567 ggml_cuda_op_floor(ctx, dst);
2568 break;
2569 case GGML_UNARY_OP_CEIL:
2570 ggml_cuda_op_ceil(ctx, dst);
2571 break;
2572 case GGML_UNARY_OP_ROUND:
2573 ggml_cuda_op_round(ctx, dst);
2574 break;
2575 case GGML_UNARY_OP_TRUNC:
2576 ggml_cuda_op_trunc(ctx, dst);
2577 break;
2578 case GGML_UNARY_OP_EXPM1:
2579 ggml_cuda_op_expm1(ctx, dst);
2580 break;
2581 case GGML_UNARY_OP_SOFTPLUS:
2582 ggml_cuda_op_softplus(ctx, dst);
2583 break;
2584 default:
2585 return false;
2586 }
2587 break;
2588 case GGML_OP_GLU:
2589 switch (ggml_get_glu_op(dst)) {
2590 case GGML_GLU_OP_REGLU:
2591 ggml_cuda_op_reglu(ctx, dst);
2592 break;
2593 case GGML_GLU_OP_GEGLU:
2594 ggml_cuda_op_geglu(ctx, dst);
2595 break;
2596 case GGML_GLU_OP_SWIGLU:
2597 ggml_cuda_op_swiglu(ctx, dst);
2598 break;
2599 case GGML_GLU_OP_SWIGLU_OAI:
2600 ggml_cuda_op_swiglu_oai(ctx, dst);
2601 break;
2602 case GGML_GLU_OP_GEGLU_ERF:
2603 ggml_cuda_op_geglu_erf(ctx, dst);
2604 break;
2605 case GGML_GLU_OP_GEGLU_QUICK:
2606 ggml_cuda_op_geglu_quick(ctx, dst);
2607 break;
2608 case GGML_GLU_OP_SWIGLU_CLAMP:
2609 ggml_cuda_op_swiglu_clamp(ctx, dst);
2610 break;
2611 default:
2612 return false;
2613 }
2614 break;
2615 case GGML_OP_NORM:
2616 ggml_cuda_op_norm(ctx, dst);
2617 break;
2618 case GGML_OP_GROUP_NORM:
2619 ggml_cuda_op_group_norm(ctx, dst);
2620 break;
2621 case GGML_OP_L2_NORM:
2622 ggml_cuda_op_l2_norm(ctx, dst);
2623 break;
2624 case GGML_OP_CONCAT:
2625 ggml_cuda_op_concat(ctx, dst);
2626 break;
2627 case GGML_OP_UPSCALE:
2628 ggml_cuda_op_upscale(ctx, dst);
2629 break;
2630 case GGML_OP_PAD:
2631 ggml_cuda_op_pad(ctx, dst);
2632 break;
2633 case GGML_OP_PAD_REFLECT_1D:
2634 ggml_cuda_op_pad_reflect_1d(ctx, dst);
2635 break;
2636 case GGML_OP_ARANGE:
2637 ggml_cuda_op_arange(ctx, dst);
2638 break;
2639 case GGML_OP_TIMESTEP_EMBEDDING:
2640 ggml_cuda_op_timestep_embedding(ctx, dst);
2641 break;
2642 case GGML_OP_LEAKY_RELU:
2643 ggml_cuda_op_leaky_relu(ctx, dst);
2644 break;
2645 case GGML_OP_SILU_BACK:
2646 ggml_cuda_op_silu_back(ctx, dst);
2647 break;
2648 case GGML_OP_RMS_NORM:
2649 ggml_cuda_op_rms_norm(ctx, dst);
2650 break;
2651 case GGML_OP_RMS_NORM_BACK:
2652 ggml_cuda_op_rms_norm_back(ctx, dst);
2653 break;
2654 case GGML_OP_MUL_MAT:
2655 ggml_cuda_mul_mat(ctx, dst->src[0], dst->src[1], dst);
2656 break;
2657 case GGML_OP_MUL_MAT_ID:
2658 ggml_cuda_mul_mat_id(ctx, dst);
2659 break;
2660 case GGML_OP_OUT_PROD:
2661 ggml_cuda_out_prod(ctx, dst);
2662 break;
2663 case GGML_OP_SCALE:
2664 ggml_cuda_op_scale(ctx, dst);
2665 break;
2666 case GGML_OP_SQR:
2667 ggml_cuda_op_sqr(ctx, dst);
2668 break;
2669 case GGML_OP_SQRT:
2670 ggml_cuda_op_sqrt(ctx, dst);
2671 break;
2672 case GGML_OP_SIN:
2673 ggml_cuda_op_sin(ctx, dst);
2674 break;
2675 case GGML_OP_COS:
2676 ggml_cuda_op_cos(ctx, dst);
2677 break;
2678 case GGML_OP_CLAMP:
2679 ggml_cuda_op_clamp(ctx, dst);
2680 break;
2681 case GGML_OP_LOG:
2682 ggml_cuda_op_log(ctx, dst);
2683 break;
2684 case GGML_OP_NONE:
2685 case GGML_OP_RESHAPE:
2686 case GGML_OP_VIEW:
2687 case GGML_OP_PERMUTE:
2688 case GGML_OP_TRANSPOSE:
2689 break;
2690 case GGML_OP_DIAG:
2691 ggml_cuda_op_diag(ctx, dst);
2692 break;
2693 case GGML_OP_DIAG_MASK_INF:
2694 ggml_cuda_op_diag_mask_inf(ctx, dst);
2695 break;
2696 case GGML_OP_SOFT_MAX:
2697 ggml_cuda_op_soft_max(ctx, dst);
2698 break;
2699 case GGML_OP_SOFT_MAX_BACK:
2700 ggml_cuda_op_soft_max_back(ctx, dst);
2701 break;
2702 case GGML_OP_ROPE:
2703 ggml_cuda_op_rope(ctx, dst);
2704 break;
2705 case GGML_OP_ROPE_BACK:
2706 ggml_cuda_op_rope_back(ctx, dst);
2707 break;
2708 case GGML_OP_ROLL:
2709 ggml_cuda_op_roll(ctx, dst);
2710 break;
2711 case GGML_OP_IM2COL:
2712 ggml_cuda_op_im2col(ctx, dst);
2713 break;
2714 case GGML_OP_IM2COL_3D:
2715 ggml_cuda_op_im2col_3d(ctx, dst);
2716 break;
2717 case GGML_OP_CONV_2D:
2718 ggml_cuda_op_conv2d(ctx, dst);
2719 break;
2720 case GGML_OP_CONV_3D:
2721 ggml_cuda_op_conv3d(ctx, dst);
2722 break;
2723 case GGML_OP_CONV_2D_DW:
2724 ggml_cuda_op_conv2d_dw(ctx, dst);
2725 break;
2726 case GGML_OP_CONV_TRANSPOSE_2D:
2727 ggml_cuda_conv_2d_transpose_p0(ctx, dst);
2728 break;
2729 case GGML_OP_CONV_TRANSPOSE_1D:
2730 ggml_cuda_op_conv_transpose_1d(ctx,dst);
2731 break;
2732 case GGML_OP_COL2IM_1D:
2733 ggml_cuda_op_col2im_1d(ctx, dst);
2734 break;
2735 case GGML_OP_POOL_2D:
2736 ggml_cuda_op_pool2d(ctx, dst);
2737 break;
2738 case GGML_OP_POOL_1D:
2739 ggml_cuda_op_pool1d(ctx, dst);
2740 break;
2741 case GGML_OP_SUM:
2742 ggml_cuda_op_sum(ctx, dst);
2743 break;
2744 case GGML_OP_CUMSUM:
2745 ggml_cuda_op_cumsum(ctx, dst);
2746 break;
2747 case GGML_OP_SUM_ROWS:
2748 ggml_cuda_op_sum_rows(ctx, dst);
2749 break;
2750 case GGML_OP_MEAN:
2751 ggml_cuda_op_mean(ctx, dst);
2752 break;
2753 case GGML_OP_SSM_CONV:
2754 ggml_cuda_op_ssm_conv(ctx, dst);
2755 break;
2756 case GGML_OP_SSM_SCAN:
2757 ggml_cuda_op_ssm_scan(ctx, dst);
2758 break;
2759 case GGML_OP_TOP_K:
2760 ggml_cuda_op_top_k(ctx, dst);
2761 break;
2762 case GGML_OP_ARGSORT:
2763 ggml_cuda_op_argsort(ctx, dst);
2764 break;
2765 case GGML_OP_FLASH_ATTN_EXT:
2766 ggml_cuda_flash_attn_ext(ctx, dst);
2767 break;
2768 case GGML_OP_CROSS_ENTROPY_LOSS:
2769 ggml_cuda_cross_entropy_loss(ctx, dst);
2770 break;
2771 case GGML_OP_TRI:
2772 ggml_cuda_op_tri(ctx, dst);
2773 break;
2774 case GGML_OP_RWKV_WKV6:
2775 ggml_cuda_op_rwkv_wkv6(ctx, dst);
2776 break;
2777 case GGML_OP_GATED_LINEAR_ATTN:
2778 ggml_cuda_op_gated_linear_attn(ctx, dst);
2779 break;
2780 case GGML_OP_GATED_DELTA_NET:
2781 ggml_cuda_op_gated_delta_net(ctx, dst);
2782 break;
2783 case GGML_OP_DSV4_HC_COMB:
2784 ggml_cuda_op_dsv4_hc_comb(ctx, dst);
2785 break;
2786 case GGML_OP_DSV4_HC_PRE:
2787 ggml_cuda_op_dsv4_hc_pre(ctx, dst);
2788 break;
2789 case GGML_OP_DSV4_HC_POST:
2790 ggml_cuda_op_dsv4_hc_post(ctx, dst);
2791 break;
2792 case GGML_OP_RWKV_WKV7:
2793 ggml_cuda_op_rwkv_wkv7(ctx, dst);
2794 break;
2795 case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
2796 ggml_cuda_cross_entropy_loss_back(ctx, dst);
2797 break;
2798 case GGML_OP_OPT_STEP_ADAMW:
2799 ggml_cuda_opt_step_adamw(ctx, dst);
2800 break;
2801 case GGML_OP_OPT_STEP_SGD:
2802 ggml_cuda_opt_step_sgd(ctx, dst);
2803 break;
2804 case GGML_OP_SOLVE_TRI:
2805 ggml_cuda_op_solve_tri(ctx, dst);
2806 break;
2807 case GGML_OP_FILL:
2808 ggml_cuda_op_fill(ctx, dst);
2809 break;
2810 case GGML_OP_LIGHTNING_INDEXER:
2811 ggml_cuda_lightning_indexer(ctx, dst);
2812 break;
2813 case GGML_OP_TOP_K_MASK:
2814 ggml_cuda_op_top_k_mask(ctx, dst);
2815 break;
2816 default:
2817 return false;
2818 }
2819
2820 cudaError_t err = cudaGetLastError();
2821 if (err != cudaSuccess) {
2822 GGML_LOG_ERROR("%s: %s failed\n", __func__, ggml_op_desc(dst));
2823 CUDA_CHECK(err);
2824 }
2825
2826 return true;
2827}
2828
2829////////////////////////////////////////////////////////////////////////////////
2830
2831// backend
2832
2833static const char * ggml_backend_cuda_get_name(ggml_backend_t backend) {
2834 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
2835
2836 return cuda_ctx->name.c_str();
2837}
2838
2839static void ggml_backend_cuda_free(ggml_backend_t backend) {
2840 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
2841
2842 delete cuda_ctx;
2843 delete backend;
2844}
2845
2846static void ggml_backend_cuda_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
2847 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context;
2848 ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
2849
2850 GGML_ASSERT(buf->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device) && "unsupported buffer type");
2851
2852 CUDA_CHECK(cudaMemcpyAsync((char *) tensor->data + offset, data, size, cudaMemcpyHostToDevice, cuda_ctx->stream()));
2853}
2854
2855static void ggml_backend_cuda_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
2856 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context;
2857 ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
2858
2859 GGML_ASSERT(buf->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device) && "unsupported buffer type");
2860
2861 CUDA_CHECK(cudaMemcpyAsync(data, (const char *) tensor->data + offset, size, cudaMemcpyDeviceToHost, cuda_ctx->stream()));
2862}
2863
2864static void ggml_backend_cuda_set_tensor_2d_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data,
2865 size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) {
2866 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context;
2867 ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
2868
2869 GGML_ASSERT(buf->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device) && "unsupported buffer type");
2870
2871 CUDA_CHECK(cudaMemcpy2DAsync(
2872 (char *) tensor->data + offset, stride_tensor, data, stride_data, size, n_copies, cudaMemcpyHostToDevice, cuda_ctx->stream()));
2873}
2874
2875static void ggml_backend_cuda_get_tensor_2d_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data,
2876 size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) {
2877 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context;
2878 ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
2879
2880 GGML_ASSERT(buf->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device) && "unsupported buffer type");
2881
2882 CUDA_CHECK(cudaMemcpy2DAsync(
2883 data, stride_data, (const char *) tensor->data + offset, stride_tensor, size, n_copies, cudaMemcpyDeviceToHost, cuda_ctx->stream()));
2884}
2885
2886static bool ggml_backend_cuda_cpy_tensor_async(ggml_backend_t backend_src, ggml_backend_t backend_dst, const ggml_tensor * src, ggml_tensor * dst) {
2887 ggml_backend_buffer_t buf_src = src->view_src ? src->view_src->buffer : src->buffer;
2888 ggml_backend_buffer_t buf_dst = dst->view_src ? dst->view_src->buffer : dst->buffer;
2889
2890 if (!ggml_backend_is_cuda(backend_src) || !ggml_backend_is_cuda(backend_dst)) {
2891 return false;
2892 }
2893
2894 if (!ggml_backend_buffer_is_cuda(buf_src) || !ggml_backend_buffer_is_cuda(buf_dst)) {
2895 return false;
2896 }
2897
2898 // device -> device copy
2899 ggml_backend_cuda_context * cuda_ctx_src = (ggml_backend_cuda_context *) backend_src->context;
2900 ggml_backend_cuda_context * cuda_ctx_dst = (ggml_backend_cuda_context *) backend_dst->context;
2901
2902 ggml_backend_cuda_buffer_context * buf_ctx_src = (ggml_backend_cuda_buffer_context *) buf_src->context;
2903 ggml_backend_cuda_buffer_context * buf_ctx_dst = (ggml_backend_cuda_buffer_context *) buf_dst->context;
2904
2905 if (cuda_ctx_src->device != buf_ctx_src->device || cuda_ctx_dst->device != buf_ctx_dst->device) {
2906#ifndef NDEBUG
2907 GGML_LOG_DEBUG("%s: backend and buffer devices do not match\n", __func__);
2908#endif // NDEBUG
2909 return false;
2910 }
2911
2912 if (backend_src != backend_dst) {
2913 // copy on src stream
2914 // compare the backing physical devices: distinct virtual devices may share one physical GPU,
2915 // in which case a same-device copy (not a peer copy) is required
2916 const int src_physical = ggml_cuda_get_physical_device(cuda_ctx_src->device);
2917 const int dst_physical = ggml_cuda_get_physical_device(cuda_ctx_dst->device);
2918 if (src_physical == dst_physical) {
2919 CUDA_CHECK(cudaMemcpyAsync(dst->data, src->data, ggml_nbytes(dst), cudaMemcpyDeviceToDevice, cuda_ctx_src->stream()));
2920 } else {
2921#ifdef GGML_CUDA_NO_PEER_COPY
2922 return false;
2923#else
2924 CUDA_CHECK(cudaMemcpyPeerAsync(dst->data, dst_physical, src->data, src_physical, ggml_nbytes(dst), cuda_ctx_src->stream()));
2925#endif // GGML_CUDA_NO_PEER_COPY
2926 }
2927
2928 // record event on src stream after the copy
2929 if (!cuda_ctx_src->copy_event) {
2930 ggml_cuda_set_device(cuda_ctx_src->device);
2931 CUDA_CHECK(cudaEventCreateWithFlags(&cuda_ctx_src->copy_event, cudaEventDisableTiming));
2932 }
2933
2934 CUDA_CHECK(cudaEventRecord(cuda_ctx_src->copy_event, cuda_ctx_src->stream()));
2935
2936 // wait on dst stream for the copy to complete
2937 CUDA_CHECK(cudaStreamWaitEvent(cuda_ctx_dst->stream(), cuda_ctx_src->copy_event, 0));
2938 } else {
2939 // src and dst are on the same backend
2940 CUDA_CHECK(cudaMemcpyAsync(dst->data, src->data, ggml_nbytes(dst), cudaMemcpyDeviceToDevice, cuda_ctx_src->stream()));
2941 }
2942 return true;
2943}
2944
2945static void ggml_backend_cuda_synchronize(ggml_backend_t backend) {
2946 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
2947
2948 CUDA_CHECK(cudaStreamSynchronize(cuda_ctx->stream()));
2949
2950 GGML_UNUSED(backend);
2951}
2952
2953static bool ggml_cuda_is_view_or_noop(const ggml_tensor * t) {
2954 return ggml_is_empty(t) || t->op == GGML_OP_RESHAPE || t->op == GGML_OP_TRANSPOSE ||
2955 t->op == GGML_OP_VIEW || t->op == GGML_OP_PERMUTE || t->op == GGML_OP_NONE;
2956}
2957
2958#ifdef USE_CUDA_GRAPH
2959static bool ggml_cuda_graph_debug_enabled() {
2960 static const bool enabled = ggml_cuda_env_flag("GGML_CUDA_GRAPH_DEBUG");
2961 return enabled;
2962}
2963
2964static bool ggml_cuda_graph_check_compability(ggml_cgraph * cgraph) {
2965
2966 bool use_cuda_graph = true;
2967 // Loop over nodes in GGML graph to obtain info needed for CUDA graph
2968
2969 for (int i = 0; i < cgraph->n_nodes; i++) {
2970 ggml_tensor * node = cgraph->nodes[i];
2971
2972 if (ggml_cuda_is_view_or_noop(node)) {
2973 continue;
2974 }
2975
2976 // [TAG_MUL_MAT_ID_CUDA_GRAPHS]
2977 if (node->op == GGML_OP_MUL_MAT_ID) {
2978 const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
2979 if (ggml_cuda_mul_mat_id_needs_sync(node, cc)) {
2980 // the mul_mat_id fallback path synchronizes the stream, so we cannot use CUDA graphs
2981 // ref: https://github.com/ggml-org/llama.cpp/pull/18958
2982 use_cuda_graph = false;
2983 if (ggml_cuda_graph_debug_enabled()) {
2984 GGML_LOG_DEBUG("%s: disabling CUDA graphs due to unsupported node type\n", __func__);
2985 }
2986 }
2987 }
2988
2989 if (!use_cuda_graph) {
2990 break;
2991 }
2992 }
2993
2994 return use_cuda_graph;
2995}
2996
2997static const void * ggml_cuda_graph_get_key(ggml_cgraph * cgraph) {
2998 return cgraph->nodes[0];
2999}
3000
3001static bool ggml_cuda_graph_update_required(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph) {
3002 bool res = false;
3003
3004 const void * graph_key = ggml_cuda_graph_get_key(cgraph);
3005 ggml_cuda_graph * graph = cuda_ctx->cuda_graph(graph_key);
3006
3007 if (cgraph->uid != 0 &&
3008 cgraph->uid == graph->uid) {
3009 if (ggml_cuda_graph_debug_enabled()) {
3010 GGML_LOG_DEBUG("CUDA Graph id %zu reused\n", cgraph->uid);
3011 }
3012 GGML_ASSERT((int)graph->node_props.size() == cgraph->n_nodes);
3013 return false;
3014 }
3015
3016 graph->uid = cgraph->uid;
3017
3018 // Check if the graph size has changed
3019 if ((int)graph->node_props.size() != cgraph->n_nodes) {
3020 res = true;
3021 graph->node_props.resize(cgraph->n_nodes);
3022 }
3023
3024 for (int i = 0; i < cgraph->n_nodes; i++) {
3025 ggml_cuda_graph::node_properties prop = {};
3026 memcpy(&prop.node, cgraph->nodes[i], sizeof(ggml_tensor));
3027
3028 for (int j = 0; j < GGML_MAX_SRC; ++j) {
3029 if (cgraph->nodes[i]->src[j]) {
3030 prop.node_src_data_ptrs[j] = cgraph->nodes[i]->src[j]->data;
3031 memcpy(prop.node_src_ne[j], cgraph->nodes[i]->src[j]->ne, sizeof(prop.node_src_ne[j]));
3032 memcpy(prop.node_src_nb[j], cgraph->nodes[i]->src[j]->nb, sizeof(prop.node_src_nb[j]));
3033 }
3034 }
3035
3036 if (res || memcmp(&graph->node_props[i], &prop, sizeof(prop)) != 0) {
3037 graph->node_props[i] = prop;
3038 res = true;
3039 }
3040 }
3041
3042 return res;
3043}
3044
3045static void ggml_cuda_graph_update_executable(cudaGraphExec_t & instance, cudaGraph_t cuda_graph) {
3046#if CUDART_VERSION >= 12000
3047 cudaGraphExecUpdateResultInfo result_info;
3048 cudaError_t stat = cudaGraphExecUpdate(instance, cuda_graph, &result_info);
3049#else
3050 cudaGraphNode_t errorNode;
3051 cudaGraphExecUpdateResult result_info;
3052 cudaError_t stat = cudaGraphExecUpdate(instance, cuda_graph, &errorNode, &result_info);
3053#endif // CUDART_VERSION >= 12000
3054
3055 if (stat == cudaErrorGraphExecUpdateFailure) {
3056 if (ggml_cuda_graph_debug_enabled()) {
3057 GGML_LOG_DEBUG("%s: CUDA graph update failed\n", __func__);
3058 }
3059
3060 // The pre-existing graph exec cannot be updated due to violated constraints
3061 // so instead clear error and re-instantiate
3062 (void)cudaGetLastError();
3063 CUDA_CHECK(cudaGraphExecDestroy(instance));
3064 instance = nullptr;
3065 CUDA_CHECK(cudaGraphInstantiate(&instance, cuda_graph, nullptr, nullptr, 0));
3066 } else {
3067 GGML_ASSERT(stat == cudaSuccess);
3068 }
3069}
3070
3071// number of ggml nodes per CUDA graph chunk, 0 captures the whole ggml graph as one CUDA graph
3072static int ggml_cuda_graph_chunk_size() {
3073 static const int chunk_size = [] {
3074 const char * env = getenv("GGML_CUDA_GRAPH_CHUNK_SIZE");
3075 return env != nullptr ? atoi(env) : 512;
3076 }();
3077 return chunk_size;
3078}
3079
3080// end the capture of chunk `idx`, update or create its executable and launch it
3081static void ggml_cuda_graph_launch_chunk(ggml_backend_cuda_context * cuda_ctx, ggml_cuda_graph * graph, size_t idx) {
3082 cudaGraph_t cuda_graph = nullptr;
3083 CUDA_CHECK(cudaStreamEndCapture(cuda_ctx->stream(), &cuda_graph));
3084
3085 if (idx < graph->instances.size()) {
3086 ggml_cuda_graph_update_executable(graph->instances[idx], cuda_graph);
3087 } else {
3088 GGML_ASSERT(idx == graph->instances.size());
3089 graph->instances.emplace_back(nullptr);
3090 CUDA_CHECK(cudaGraphInstantiate(&graph->instances[idx], cuda_graph, nullptr, nullptr, 0));
3091 }
3092 CUDA_CHECK(cudaGraphDestroy(cuda_graph));
3093
3094 CUDA_CHECK(cudaGraphLaunch(graph->instances[idx], cuda_ctx->stream()));
3095}
3096#endif // USE_CUDA_GRAPH
3097
3098static bool ggml_cuda_should_fuse_rope_set_rows(const ggml_tensor * rope,
3099 const ggml_tensor * view,
3100 const ggml_tensor * set_rows) {
3101
3102 if (rope->op != GGML_OP_ROPE || view->op != GGML_OP_VIEW || set_rows->op != GGML_OP_SET_ROWS) {
3103 return false;
3104 }
3105 // ne3 not tested
3106 if (rope->src[0]->ne[3] != 1) {
3107 return false;
3108 }
3109
3110 if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
3111 return false;
3112 }
3113
3114 if (set_rows->src[1]->type != GGML_TYPE_I64) {
3115 return false;
3116 }
3117
3118 // The view should flatten two dims of rope into one dim
3119 if (!ggml_is_contiguous(view) || view->ne[0] != rope->ne[0] * rope->ne[1]) {
3120 return false;
3121 }
3122
3123 // Only norm/neox/multi shaders have the fusion code
3124 const int mode = ((const int32_t *) rope->op_params)[2];
3125 if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX &&
3126 mode != GGML_ROPE_TYPE_MROPE && mode != GGML_ROPE_TYPE_IMROPE) {
3127 return false;
3128 }
3129
3130 return true;
3131}
3132
3133static bool ggml_cuda_should_fuse_rms_norm_mul_rope(const ggml_tensor * rms_norm,
3134 const ggml_tensor * mul,
3135 const ggml_tensor * rope) {
3136 if (rms_norm->op != GGML_OP_RMS_NORM || mul->op != GGML_OP_MUL || rope->op != GGML_OP_ROPE) {
3137 return false;
3138 }
3139
3140 if (rms_norm->src[0]->type != GGML_TYPE_F32 || rms_norm->type != GGML_TYPE_F32 ||
3141 mul->src[0]->type != GGML_TYPE_F32 || mul->src[1]->type != GGML_TYPE_F32 ||
3142 mul->type != GGML_TYPE_F32 || rope->type != GGML_TYPE_F32) {
3143 return false;
3144 }
3145
3146 if (rope->src[0] != mul) {
3147 return false;
3148 }
3149
3150 //if rms norm is the B operand, then we don't handle broadcast
3151 if (rms_norm == mul->src[1] && !ggml_are_same_shape(mul->src[0], rms_norm)) {
3152 return false;
3153 }
3154
3155 if (!ggml_are_same_shape(rms_norm, mul)) {
3156 return false;
3157 }
3158
3159 //rms_norm kernel assumes contiguous rows
3160 if (!ggml_is_contiguous_rows(rms_norm->src[0]) ||
3161 !ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
3162 return false;
3163 }
3164
3165 // the fused kernel handles the norm/neox rope modes only
3166 const int mode = ((const int32_t *) rope->op_params)[2];
3167 if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX) {
3168 return false;
3169 }
3170
3171 const int n_dims = ((const int32_t *) rope->op_params)[1];
3172 if (n_dims % 2 != 0 || rope->src[0]->ne[0] % 2 != 0) {
3173 return false;
3174 }
3175
3176 // ggml_rope_set_offset is not yet supported in the fused kernel
3177 const int n_offs = ((const int32_t *) rope->op_params)[15];
3178 if (n_offs != 0) {
3179 return false;
3180 }
3181
3182 return true;
3183}
3184
3185// match gated_delta_net + the strided cpy that scatters its state snapshots into the cache
3186// (slot i -> rollback group i, slot 0 newest), so the kernel can write them and skip the cpy.
3187static int ggml_cuda_try_gdn_cache_fusion(
3188 const ggml_cgraph * cgraph, int node_idx, ggml_cuda_gated_delta_net_fused_cache & fused_state_cpy) {
3189 const ggml_tensor * gdn = cgraph->nodes[node_idx];
3190 // the kernel skips the snapshot tail, so the gdn output must not be a graph output
3191 if (gdn->op != GGML_OP_GATED_DELTA_NET || gdn->type != GGML_TYPE_F32 ||
3192 (gdn->flags & GGML_TENSOR_FLAG_OUTPUT)) {
3193 return 0;
3194 }
3195
3196 const ggml_tensor * src_v = gdn->src[2];
3197 const int64_t S_v = src_v->ne[0];
3198 const int64_t H = src_v->ne[1];
3199 const int64_t n_tokens = src_v->ne[2];
3200 const int64_t n_seqs = src_v->ne[3];
3201 const int64_t D = S_v * S_v * H;
3202 const int64_t K = ggml_get_op_params_i32(gdn, 0); // snapshot slot count
3203 const int64_t n_written = std::min<int64_t>(n_tokens, K); // newest n_written slots are written
3204
3205 // snapshot tail starts right after the attention scores
3206 const size_t tail_off = ggml_row_size(GGML_TYPE_F32, S_v * H * n_tokens * n_seqs);
3207
3208 // snapshot cpy is the first real node after the gdn (skip views/no-ops)
3209 const ggml_tensor * cpy = nullptr;
3210 int skip = 0;
3211 for (int j = node_idx + 1; j < cgraph->n_nodes && cpy == nullptr; ++j) {
3212 const ggml_tensor * n = cgraph->nodes[j];
3213 if (ggml_cuda_is_view_or_noop(n)) {
3214 continue;
3215 }
3216 if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT)) {
3217 return 0;
3218 }
3219 cpy = n;
3220 skip = j - node_idx;
3221 }
3222 if (cpy == nullptr) {
3223 return 0;
3224 }
3225
3226 const ggml_tensor * src = cpy->src[0]; // view of the gdn snapshot tail
3227 const ggml_tensor * dst = cpy->src[1]; // cache view the kernel writes to
3228
3229 // src must be this gdn's snapshot tail (contiguous, at the tail offset)
3230 if (src->op != GGML_OP_VIEW || src->view_src != gdn || src->view_offs != tail_off ||
3231 !ggml_is_contiguous(src)) {
3232 return 0;
3233 }
3234
3235 // dst is the [D, n_seqs, n_written] cache view; require nb[1] == D (the per-seq stride the kernel
3236 // assumes). ggml_cpy pins src to the same element count.
3237 const std::array<int64_t, GGML_MAX_DIMS> expected_ne = { D, n_seqs, n_written, 1 };
3238 if (dst->op != GGML_OP_VIEW || dst->type != GGML_TYPE_F32 || dst->data == nullptr ||
3239 !std::equal(expected_ne.begin(), expected_ne.end(), dst->ne) ||
3240 dst->nb[0] != ggml_type_size(GGML_TYPE_F32) || dst->nb[1] != (size_t) ggml_row_size(GGML_TYPE_F32, D)) {
3241 return 0;
3242 }
3243
3244 fused_state_cpy.data = (float *) dst->data; // rollback group 0 (newest)
3245 fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0;
3246 return skip;
3247}
3248
3249// match ssm_scan + the strided cpy that scatters its state snapshots into the cache, so the kernel writes them and skips the cpy
3250static int ggml_cuda_try_ssm_scan_cache_fusion(
3251 const ggml_cgraph * cgraph, int node_idx, ggml_cuda_ssm_scan_fused_cache & fused_state_cpy) {
3252 const ggml_tensor * ssm = cgraph->nodes[node_idx];
3253 // the kernel skips the snapshot tail, so the scan output must not be a graph output
3254 if (ssm->op != GGML_OP_SSM_SCAN || ssm->type != GGML_TYPE_F32 || (ssm->flags & GGML_TENSOR_FLAG_OUTPUT)) {
3255 return 0;
3256 }
3257
3258 const int64_t K = ggml_get_op_params_i32(ssm, 0); // snapshot slot count
3259
3260 const ggml_tensor * s = ssm->src[0];
3261 const ggml_tensor * x = ssm->src[1];
3262 const ggml_tensor * A = ssm->src[3];
3263
3264 const int64_t d_state = s->ne[0];
3265 const int64_t D = d_state * s->ne[1] * x->ne[1]; // d_state * head_dim * n_head
3266 const int64_t n_tok = x->ne[2];
3267 const int64_t n_seqs = x->ne[3];
3268
3269 // only the mamba-2 kernels (group scan and SSD) write to the cache; mamba-1 still uses the cpy
3270 if (A->nb[1] != sizeof(float) || (d_state != 96 && d_state != 128 && d_state != 256)) {
3271 return 0;
3272 }
3273
3274 // the scan reads its input rows from the cache (picked by ids), so with more than one seq a seq can read a row that another seq writes in the same launch
3275 if (n_seqs != 1) {
3276 return 0;
3277 }
3278
3279 const int64_t n_written = std::min<int64_t>(n_tok, K);
3280 const size_t tail_off = ggml_row_size(GGML_TYPE_F32, ggml_nelements(x));
3281
3282 // snapshot cpy is the first real node after the scan (skip views/no-ops)
3283 const ggml_tensor * cpy = nullptr;
3284 int skip = 0;
3285 for (int j = node_idx + 1; j < cgraph->n_nodes && cpy == nullptr; ++j) {
3286 const ggml_tensor * n = cgraph->nodes[j];
3287 if (ggml_cuda_is_view_or_noop(n)) {
3288 continue;
3289 }
3290 if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT)) {
3291 return 0;
3292 }
3293 cpy = n;
3294 skip = j - node_idx;
3295 }
3296 if (cpy == nullptr) {
3297 return 0;
3298 }
3299
3300 const ggml_tensor * src = cpy->src[0]; // view of the scan snapshot tail
3301 const ggml_tensor * dst = cpy->src[1]; // cache view the kernel writes to
3302
3303 // src must be this scan's snapshot tail (contiguous, at the tail offset)
3304 if (src->op != GGML_OP_VIEW || src->view_src != ssm || src->view_offs != tail_off ||
3305 !ggml_is_contiguous(src)) {
3306 return 0;
3307 }
3308
3309 // dst is the [D, n_seqs, n_written] cache view; require nb[1] == D, the per-seq stride the kernel takes from src0->nb[3]
3310 const std::array<int64_t, GGML_MAX_DIMS> expected_ne = { D, n_seqs, n_written, 1 };
3311 if (dst->op != GGML_OP_VIEW || dst->type != GGML_TYPE_F32 || dst->data == nullptr ||
3312 !std::equal(expected_ne.begin(), expected_ne.end(), dst->ne) ||
3313 dst->nb[0] != ggml_type_size(GGML_TYPE_F32) || dst->nb[1] != (size_t) ggml_row_size(GGML_TYPE_F32, D)) {
3314 return 0;
3315 }
3316
3317 fused_state_cpy.data = (float *) dst->data; // rollback slot 0 (newest)
3318 fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0;
3319 return skip;
3320}
3321
3322// expert group selection from build_moe_ffn (n_expert_groups > 1)
3323// src0/src1 index into this table, -1 is the (biased) probs, -2 is not checked
3324static const struct {
3325 ggml_op op;
3326 int src0;
3327 int src1;
3328} topk_moe_group_pattern[] = {
3329 { GGML_OP_RESHAPE, -1, -2 }, // 0: [n_exp_per_group, n_expert_groups, n_tokens]
3330 { GGML_OP_RESHAPE, 0, -2 }, // 1: [1, n_exp_per_group, n_expert_groups, n_tokens]
3331 { GGML_OP_ARGSORT, 0, -2 }, // 2
3332 { GGML_OP_VIEW, 2, -2 }, // 3: top-2 per group
3333 { GGML_OP_GET_ROWS, 1, 3 }, // 4
3334 { GGML_OP_RESHAPE, 4, -2 }, // 5
3335 { GGML_OP_SUM_ROWS, 5, -2 }, // 6: group scores
3336 { GGML_OP_RESHAPE, 6, -2 }, // 7
3337 { GGML_OP_ARGSORT, 7, -2 }, // 8
3338 { GGML_OP_VIEW, 8, -2 }, // 9: top n_group_used groups
3339 { GGML_OP_GET_ROWS, 0, 9 }, // 10
3340 { GGML_OP_FILL, 0, -2 }, // 11
3341 { GGML_OP_SET_ROWS, 10, 9 }, // 12: unused groups -> -inf
3342 { GGML_OP_RESHAPE, 12, -2 }, // 13: [n_expert, n_tokens]
3343};
3344
3345static bool ggml_cuda_topk_moe_group_fusion(const struct ggml_cgraph * cgraph, int node_idx, const ggml_tensor * selection, ggml_cuda_topk_moe_args & args) {
3346#if defined(GGML_USE_HIP) && HIP_VERSION < 60300000
3347 GGML_UNUSED_VARS(cgraph, node_idx, selection, args);
3348 return false;
3349#else
3350 const int n_ops = (int) std::size(topk_moe_group_pattern);
3351 if (node_idx + n_ops > cgraph->n_nodes) {
3352 return false;
3353 }
3354
3355 ggml_tensor ** nodes = cgraph->nodes + node_idx;
3356 auto src_ok = [&](const ggml_tensor * src, int idx) {
3357 return idx == -2 || src == (idx == -1 ? selection : nodes[idx]);
3358 };
3359
3360 for (int i = 0; i < n_ops; i++) {
3361 const auto & p = topk_moe_group_pattern[i];
3362 if (nodes[i]->op != p.op || !src_ok(nodes[i]->src[0], p.src0) || !src_ok(nodes[i]->src[1], p.src1)) {
3363 return false;
3364 }
3365 }
3366
3367 const int n_groups = nodes[0]->ne[1];
3368 const int n_group_used = nodes[9]->ne[0];
3369
3370 if (nodes[3]->ne[0] != 2 || nodes[12]->src[2] != nodes[11] || ggml_get_op_params_f32(nodes[11], 0) != -INFINITY ||
3371 n_groups > WARP_SIZE) {
3372 return false;
3373 }
3374
3375 args.n_groups = n_groups;
3376 args.n_group_used = n_group_used;
3377 return true;
3378#endif // defined(GGML_USE_HIP) && HIP_VERSION < 60300000
3379}
3380
3381static bool ggml_cuda_topk_moe_fusion(const struct ggml_cgraph * cgraph, int node_idx, ggml_cuda_topk_moe_args & args) {
3382 args.sigmoid = false;
3383 args.sqrt_softplus = false;
3384 args.softmax = false;
3385 args.delayed_softmax = false;
3386 args.prob_bias = false;
3387 args.norm = false;
3388 args.n_groups = 0;
3389 args.n_group_used = 0;
3390
3391 const int n_nodes = cgraph->n_nodes;
3392 ggml_tensor ** nodes = cgraph->nodes;
3393
3394 if (nodes[node_idx]->op == GGML_OP_SOFT_MAX) {
3395 args.softmax = true;
3396 }
3397
3398 if (nodes[node_idx]->op == GGML_OP_UNARY) {
3399 const ggml_unary_op unary_op = ggml_get_unary_op(nodes[node_idx]);
3400 if (unary_op == GGML_UNARY_OP_SIGMOID) {
3401 args.sigmoid = true;
3402 } else if (unary_op == GGML_UNARY_OP_SOFTPLUS && node_idx + 1 < n_nodes &&
3403 nodes[node_idx + 1]->op == GGML_OP_SQRT && nodes[node_idx + 1]->src[0] == nodes[node_idx]) {
3404 // sqrt(softplus(x)) scoring (DeepSeek-V4)
3405 args.sqrt_softplus = true;
3406 node_idx++;
3407 } else {
3408 return false;
3409 }
3410 }
3411
3412 if (nodes[node_idx]->op == GGML_OP_ARGSORT) {
3413 args.delayed_softmax = true;
3414 }
3415
3416 node_idx++;
3417
3418 if (args.sigmoid || args.sqrt_softplus || args.softmax) {
3419 // SOFTMAX -> RESHAPE
3420 if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_RESHAPE ||
3421 nodes[node_idx]->src[0] != nodes[node_idx - 1]) {
3422 return false;
3423 }
3424 ggml_tensor * probs_reshaped = nodes[node_idx];
3425 node_idx++;
3426
3427 if (node_idx >= n_nodes) {
3428 return false;
3429 }
3430
3431 // src of bias add is the unreshaped probs (-2 instead of -1)
3432 const ggml_tensor * selection = nodes[node_idx - 2];
3433 if (nodes[node_idx]->op == GGML_OP_ADD && nodes[node_idx]->src[0] == selection) {
3434 args.prob_bias = true;
3435 selection = nodes[node_idx];
3436 node_idx++;
3437 }
3438
3439 if (ggml_cuda_topk_moe_group_fusion(cgraph, node_idx, selection, args)) {
3440 node_idx += (int) std::size(topk_moe_group_pattern);
3441 selection = nodes[node_idx - 1];
3442 }
3443
3444 // RESHAPE/ADD/group mask -> ARGSORT
3445 if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_ARGSORT || nodes[node_idx]->src[0] != selection) {
3446 return false;
3447 }
3448
3449 node_idx++;
3450
3451 // ARGSORT-> VIEW
3452 if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_VIEW ||
3453 nodes[node_idx]->src[0] != nodes[node_idx - 1]) {
3454 return false;
3455 }
3456
3457 // kept groups must hold all used experts
3458 if (args.n_groups > 0 && nodes[node_idx]->ne[0] > args.n_group_used * (probs_reshaped->ne[1] / args.n_groups)) {
3459 return false;
3460 }
3461 node_idx++;
3462
3463 if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_GET_ROWS) {
3464 return false;
3465 }
3466
3467 // GET_ROWS
3468 if (nodes[node_idx]->src[0] != probs_reshaped || nodes[node_idx]->src[1] != nodes[node_idx - 1]) {
3469 return false;
3470 }
3471 node_idx++;
3472 } else if (args.delayed_softmax) {
3473 if (node_idx - 2 < 0) {
3474 return false;
3475 }
3476 ggml_tensor * probs_reshaped = nodes[node_idx - 2];
3477
3478 // VIEW->ARGSORT
3479 if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_VIEW ||
3480 nodes[node_idx]->src[0] != nodes[node_idx - 1]) {
3481 return false;
3482 }
3483 node_idx++;
3484
3485 // GET_ROWS
3486 if (node_idx >= n_nodes || nodes[node_idx]->src[1] != nodes[node_idx - 1] ||
3487 nodes[node_idx]->src[0] != probs_reshaped) {
3488 return false;
3489 }
3490 node_idx++;
3491
3492 static const std::vector<ggml_op> remaining_ops = { GGML_OP_RESHAPE, GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
3493
3494 for (const ggml_op op : remaining_ops) {
3495 if (node_idx >= n_nodes || nodes[node_idx]->op != op || nodes[node_idx]->src[0] != nodes[node_idx - 1]) {
3496 return false;
3497 }
3498 node_idx++;
3499 }
3500 }
3501
3502 // At this point we can check for norm + scale. Everything is now at least valid till the norm
3503 if (node_idx >= n_nodes) {
3504 return true;
3505 }
3506
3507 if (nodes[node_idx]->op == GGML_OP_RESHAPE) {
3508 //check RESHAPE->SUM_ROWS->CLAMP->DIV->RESHAPE
3509 static const std::vector<ggml_op> norm_ops = { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP };
3510
3511 args.norm = true;
3512 for (const ggml_op op : norm_ops) {
3513 if (nodes[node_idx]->op == op && nodes[node_idx]->src[0] == nodes[node_idx - 1]) {
3514 node_idx++;
3515 } else {
3516 args.norm = false;
3517 return true;
3518 }
3519 }
3520
3521 // DIV <- CLAMP, RESHAPE
3522 if (nodes[node_idx]->op != GGML_OP_DIV || nodes[node_idx]->src[1] != nodes[node_idx - 1] ||
3523 nodes[node_idx]->src[0] != nodes[node_idx - 3]) {
3524 args.norm = false;
3525 return true;
3526 }
3527 node_idx++;
3528
3529 if (nodes[node_idx]->op != GGML_OP_RESHAPE || nodes[node_idx]->src[0] != nodes[node_idx - 1]) {
3530 args.norm = false;
3531 return true;
3532 }
3533
3534 node_idx++;
3535 }
3536
3537 if (nodes[node_idx]->op == GGML_OP_SCALE && nodes[node_idx]->src[0] == nodes[node_idx - 1]) {
3538 args.scale = true;
3539 }
3540
3541 return true;
3542}
3543
3544// returns whether the write (out) nodes overwrite the read nodes in operation
3545static bool ggml_cuda_check_fusion_memory_ranges(const ggml_cgraph * cgraph,
3546 const int node_idx,
3547 const int node_count,
3548 const int * out_nodes,
3549 const int out_count,
3550 const bool is_topk_moe = false) {
3551 auto nodes_overlap = [&](const ggml_tensor * a, const ggml_tensor * b) {
3552 const int64_t a_start = (int64_t) a->data;
3553 const int64_t a_end = a_start + ggml_backend_buft_get_alloc_size(a->buffer->buft, a);
3554
3555 const int64_t b_start = (int64_t) b->data;
3556 const int64_t b_end = b_start + ggml_backend_buft_get_alloc_size(b->buffer->buft, b);
3557
3558 if ((b_start <= a_start && a_start < b_end) || (a_start <= b_start && b_start < a_end)) {
3559 return true;
3560 }
3561
3562 return false;
3563 };
3564
3565 bool is_ok = true;
3566 // one block reads all logits before it writes, so logits may alias the out nodes
3567 const ggml_tensor * logits_may_alias = nullptr;
3568 if (is_topk_moe && ggml_nrows(cgraph->nodes[node_idx]) <= TOPK_MOE_ROWS_PER_BLOCK) {
3569 logits_may_alias = cgraph->nodes[node_idx]->src[0];
3570 }
3571
3572 for (int i = 0; i < out_count; ++i) {
3573 const ggml_tensor * dst = cgraph->nodes[out_nodes[i]];
3574
3575 for (int j = node_idx; j < node_idx + node_count; ++j) {
3576 // Loop over all srcs of all nodes in the fusion. If the src overlaps
3577 // the destination and the src is not an intermediate node that's being
3578 // elided, then disable fusion.
3579
3580 for (int src_idx = 0; src_idx < GGML_MAX_SRC; ++src_idx) {
3581 const ggml_tensor * src = cgraph->nodes[j]->src[src_idx];
3582
3583 if (!src || src->op == GGML_OP_NONE || src == logits_may_alias) {
3584 continue;
3585 }
3586
3587 if (nodes_overlap(dst, src)) {
3588 bool found = false;
3589
3590 for (int k = node_idx; k < j; ++k) {
3591 if (cgraph->nodes[k] == src) {
3592 found = true;
3593 break;
3594 }
3595 }
3596
3597 if (!found) {
3598 is_ok = false;
3599 break;
3600 }
3601 }
3602 }
3603 }
3604 }
3605
3606 return is_ok;
3607}
3608
3609// The long form spans 2*k + 1 nodes. ggml_can_fuse_subgraph() accepts at most
3610// 31 nodes, so k <= 15; larger values use the per-operation path.
3611static constexpr int MOE_WEIGHTED_REDUCTION_MAX_EXPERTS = 15;
3612
3613struct ggml_cuda_moe_weighted_reduction_match {
3614 const ggml_tensor * experts = nullptr;
3615 const ggml_tensor * expert_scale = nullptr;
3616 const ggml_tensor * weights = nullptr;
3617 ggml_tensor * dst = nullptr;
3618 int node_count = 0;
3619};
3620
3621static bool ggml_cuda_match_moe_weighted_reduction(
3622 const ggml_cgraph * cgraph,
3623 int node_idx,
3624 ggml_cuda_moe_weighted_reduction_match & match) {
3625 const ggml_tensor * first = cgraph->nodes[node_idx];
3626 if (first->op != GGML_OP_MUL || first->type != GGML_TYPE_F32 || !ggml_is_contiguous(first)) {
3627 return false;
3628 }
3629
3630 auto split_mul = [](const ggml_tensor * mul, const ggml_tensor *& full, const ggml_tensor *& broadcast) {
3631 auto is_weights = [mul](const ggml_tensor * tensor) {
3632 return tensor && tensor->type == GGML_TYPE_F32 && ggml_is_contiguous(tensor) && tensor->ne[0] == 1 &&
3633 tensor->ne[1] == mul->ne[1] && tensor->ne[2] == mul->ne[2] && tensor->ne[3] == mul->ne[3];
3634 };
3635 auto is_experts = [mul](const ggml_tensor * tensor) {
3636 return tensor && tensor->type == GGML_TYPE_F32 && ggml_is_contiguous(tensor) &&
3637 ggml_are_same_shape(tensor, mul);
3638 };
3639
3640 if (is_experts(mul->src[0]) && is_weights(mul->src[1])) {
3641 full = mul->src[0];
3642 broadcast = mul->src[1];
3643 return true;
3644 }
3645 if (is_experts(mul->src[1]) && is_weights(mul->src[0])) {
3646 full = mul->src[1];
3647 broadcast = mul->src[0];
3648 return true;
3649 }
3650 return false;
3651 };
3652
3653 const ggml_tensor * weighted = first;
3654 const ggml_tensor * experts = nullptr;
3655 const ggml_tensor * expert_scale = nullptr;
3656 const ggml_tensor * weights = nullptr;
3657 int mul_count = 1;
3658
3659 // Match both structural forms:
3660 // (experts * expert_scale) * router_weight
3661 // experts * router_weight
3662 // The matcher does not depend on the model or quantization type.
3663 if (node_idx + 1 < cgraph->n_nodes) {
3664 const ggml_tensor * second = cgraph->nodes[node_idx + 1];
3665 const ggml_tensor * scaled = nullptr;
3666 const ggml_tensor * route = nullptr;
3667 const ggml_tensor * raw = nullptr;
3668 const ggml_tensor * scale = nullptr;
3669 if (second->op == GGML_OP_MUL && second->type == GGML_TYPE_F32 && ggml_is_contiguous(second) &&
3670 split_mul(second, scaled, route) && scaled == first && split_mul(first, raw, scale)) {
3671 weighted = second;
3672 experts = raw;
3673 expert_scale = scale;
3674 weights = route;
3675 mul_count = 2;
3676 }
3677 }
3678
3679 if (experts == nullptr && !split_mul(first, experts, weights)) {
3680 return false;
3681 }
3682
3683 const int n_expert_used = (int) weighted->ne[1];
3684 const int64_t n_tokens = weighted->ne[2] * weighted->ne[3];
3685 if (n_expert_used < 2 || n_expert_used > MOE_WEIGHTED_REDUCTION_MAX_EXPERTS) {
3686 return false;
3687 }
3688
3689 const int node_count = 2 * n_expert_used + mul_count - 1;
3690 if (node_idx + node_count > cgraph->n_nodes) {
3691 return false;
3692 }
3693
3694 std::vector<ggml_op> ops(node_count, GGML_OP_VIEW);
3695 ops[0] = GGML_OP_MUL;
3696 if (mul_count == 2) {
3697 ops[1] = GGML_OP_MUL;
3698 }
3699 std::vector<const ggml_tensor *> views;
3700 views.reserve(n_expert_used);
3701 const ggml_tensor * previous = nullptr;
3702 int n_adds = 0;
3703 for (int offset = mul_count; offset < node_count; ++offset) {
3704 const ggml_tensor * candidate = cgraph->nodes[node_idx + offset];
3705 ops[offset] = candidate->op;
3706
3707 if (candidate->op == GGML_OP_VIEW) {
3708 const int expert = (int) views.size();
3709 if (expert >= n_expert_used || candidate->src[0] != weighted || candidate->view_src != weighted ||
3710 candidate->type != GGML_TYPE_F32 || candidate->ne[0] != weighted->ne[0] ||
3711 candidate->ne[1] != n_tokens || candidate->ne[2] != 1 || candidate->ne[3] != 1 ||
3712 candidate->nb[0] != weighted->nb[0] || candidate->nb[1] != weighted->nb[2] ||
3713 candidate->view_offs != (size_t) expert * weighted->nb[1]) {
3714 return false;
3715 }
3716 views.push_back(candidate);
3717 continue;
3718 }
3719
3720 if (candidate->op != GGML_OP_ADD || views.size() < 2 || n_adds + 1 >= (int) views.size()) {
3721 return false;
3722 }
3723 const ggml_tensor * lhs = n_adds == 0 ? views[0] : previous;
3724 const ggml_tensor * rhs = views[n_adds + 1];
3725 if (candidate->src[0] != lhs || candidate->src[1] != rhs || candidate->type != GGML_TYPE_F32) {
3726 return false;
3727 }
3728 previous = candidate;
3729 ++n_adds;
3730 }
3731
3732 if ((int) views.size() != n_expert_used || n_adds != n_expert_used - 1 || previous == nullptr) {
3733 return false;
3734 }
3735 if (!ggml_is_contiguous(previous) || previous->ne[0] != weighted->ne[0] ||
3736 previous->ne[1] != n_tokens || previous->ne[2] != 1 || previous->ne[3] != 1) {
3737 return false;
3738 }
3739
3740 const int output_idx = node_idx + node_count - 1;
3741 if (!ggml_can_fuse_subgraph(cgraph, node_idx, node_count, ops.data(), &output_idx, 1)) {
3742 return false;
3743 }
3744
3745 match.experts = experts;
3746 match.expert_scale = expert_scale;
3747 match.weights = weights;
3748 match.dst = cgraph->nodes[output_idx];
3749 match.node_count = node_count;
3750 return true;
3751}
3752
3753
3754static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph,
3755 int node_idx,
3756 std::initializer_list<enum ggml_op> ops,
3757 std::initializer_list<enum ggml_unary_op> unary_ops) {
3758#ifndef NDEBUG
3759 const size_t num_unary = std::count(ops.begin(), ops.end(), GGML_OP_UNARY);
3760 GGML_ASSERT(unary_ops.size() == num_unary);
3761#endif
3762
3763 const auto is_equal = [](const std::initializer_list<enum ggml_op> & list1,
3764 const std::initializer_list<enum ggml_op> & list2) {
3765 return std::equal(list1.begin(), list1.end(), list2.begin(), list2.end());
3766 };
3767
3768 std::initializer_list<enum ggml_op> mul_mat_bias_glu_ops = { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_GLU };
3769 std::initializer_list<enum ggml_op> mul_mat_id_bias_glu_ops = { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_GLU };
3770
3771 std::initializer_list<enum ggml_op> mul_mat_id_glu_ops = { GGML_OP_MUL_MAT_ID, GGML_OP_MUL_MAT_ID, GGML_OP_GLU };
3772 std::initializer_list<enum ggml_op> mul_mat_glu_ops = { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU };
3773
3774 if ((is_equal(mul_mat_bias_glu_ops, ops) || is_equal(mul_mat_id_bias_glu_ops, ops)) &&
3775 ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 4 })) {
3776 const ggml_tensor * ffn_gate = cgraph->nodes[node_idx];
3777 const ggml_tensor * ffn_gate_bias = cgraph->nodes[node_idx + 1];
3778 const ggml_tensor * ffn_up = cgraph->nodes[node_idx + 2];
3779 const ggml_tensor * ffn_up_bias = cgraph->nodes[node_idx + 3];
3780 const ggml_tensor * glu = cgraph->nodes[node_idx + 4];
3781
3782 if (ggml_cuda_should_fuse_mul_mat(ffn_up, ffn_gate, glu, ffn_up_bias, ffn_gate_bias)) {
3783 int out_nodes[] = { node_idx + 4 };
3784 return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1);
3785 }
3786 }
3787
3788 if ((is_equal(mul_mat_id_glu_ops, ops) || is_equal(mul_mat_glu_ops, ops)) &&
3789 ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 2 })) {
3790 const ggml_tensor * ffn_gate = cgraph->nodes[node_idx];
3791 const ggml_tensor * ffn_up = cgraph->nodes[node_idx + 1];
3792 const ggml_tensor * glu = cgraph->nodes[node_idx + 2];
3793
3794 if (ggml_cuda_should_fuse_mul_mat(ffn_up, ffn_gate, glu)) {
3795 int out_nodes[] = { node_idx + 2 };
3796 return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1);
3797 }
3798 }
3799
3800 std::initializer_list<enum ggml_op> rms_norm_mul_rope_ops = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE };
3801 std::initializer_list<enum ggml_op> rms_norm_mul_rope_set_rows_ops = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS };
3802
3803 if (is_equal(rms_norm_mul_rope_set_rows_ops, ops) && ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 4 })) {
3804 const ggml_tensor * rms_norm = cgraph->nodes[node_idx];
3805 const ggml_tensor * mul = cgraph->nodes[node_idx + 1];
3806 const ggml_tensor * rope = cgraph->nodes[node_idx + 2];
3807 const ggml_tensor * view = cgraph->nodes[node_idx + 3];
3808 const ggml_tensor * set_rows = cgraph->nodes[node_idx + 4];
3809
3810 if (ggml_check_edges(cgraph, node_idx, {{1, 0, 0}, {2, 0, 1}, {3, 0, 2}, {4, 0, 3}}) &&
3811 ggml_cuda_should_fuse_rms_norm_mul_rope(rms_norm, mul, rope) &&
3812 ggml_cuda_should_fuse_rope_set_rows(rope, view, set_rows)) {
3813 int out_nodes[] = { node_idx + 4 };
3814 return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1);
3815 }
3816 }
3817
3818 if (is_equal(rms_norm_mul_rope_ops, ops) && ggml_can_fuse(cgraph, node_idx, ops)) {
3819 const ggml_tensor * rms_norm = cgraph->nodes[node_idx];
3820 const ggml_tensor * mul = cgraph->nodes[node_idx + 1];
3821 const ggml_tensor * rope = cgraph->nodes[node_idx + 2];
3822
3823 if (ggml_cuda_should_fuse_rms_norm_mul_rope(rms_norm, mul, rope)) {
3824 int out_nodes[] = { node_idx + 2 };
3825 return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1);
3826 }
3827 return false;
3828 }
3829
3830 std::initializer_list<enum ggml_op> rope_set_rows_ops = { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS };
3831
3832 if (is_equal(rope_set_rows_ops, ops) && ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 2 })) {
3833 const ggml_tensor * rope = cgraph->nodes[node_idx];
3834 const ggml_tensor * view = cgraph->nodes[node_idx + 1];
3835 const ggml_tensor * set_rows = cgraph->nodes[node_idx + 2];
3836
3837 if (ggml_cuda_should_fuse_rope_set_rows(rope, view, set_rows)) {
3838 int out_nodes[] = { node_idx + 2 };
3839 return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1);
3840 }
3841 }
3842
3843 // scale_out*sigmoid(scale_in*post) as the hc_post weights (qwen4exp hc_combine)
3844 std::initializer_list<enum ggml_op> hc_post_gate_ops = { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_DSV4_HC_POST };
3845
3846 if (is_equal(hc_post_gate_ops, ops) && ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 3 })) {
3847 const ggml_tensor * scale_in = cgraph->nodes[node_idx];
3848 const ggml_tensor * sigmoid = cgraph->nodes[node_idx + 1];
3849 const ggml_tensor * scale_out = cgraph->nodes[node_idx + 2];
3850
3851 // the chain must feed hc_post->src[2]; a bias on either scale is not handled
3852 if (ggml_check_edges(cgraph, node_idx, {{1, 0, 0}, {2, 0, 1}, {3, 2, 2}}) &&
3853 ggml_get_unary_op(sigmoid) == GGML_UNARY_OP_SIGMOID &&
3854 ggml_get_op_params_f32(scale_in, 1) == 0.0f && ggml_get_op_params_f32(scale_out, 1) == 0.0f &&
3855 scale_in->src[0]->type == GGML_TYPE_F32 && scale_out->type == GGML_TYPE_F32 &&
3856 ggml_are_same_shape(scale_in->src[0], scale_out)) {
3857 int out_nodes[] = { node_idx + 3 };
3858 return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1);
3859 }
3860 return false;
3861 }
3862
3863 if (!ggml_can_fuse(cgraph, node_idx, ops)) {
3864 return false;
3865 }
3866
3867 if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
3868 const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
3869 const ggml_tensor *mul = cgraph->nodes[node_idx+1];
3870 const ggml_tensor *add = nullptr;
3871
3872 if (ops.size() == 3 && ops.begin()[2] == GGML_OP_ADD) {
3873 add = cgraph->nodes[node_idx+2];
3874 }
3875
3876 GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
3877 GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
3878
3879 //rms norm only supports F32
3880 if (mul->src[0]->type != GGML_TYPE_F32 ||
3881 mul->src[1]->type != GGML_TYPE_F32 ||
3882 mul->type != GGML_TYPE_F32) {
3883 return false;
3884 }
3885
3886 if (add && (add->src[0]->type != GGML_TYPE_F32 ||
3887 add->src[1]->type != GGML_TYPE_F32 ||
3888 add->type != GGML_TYPE_F32) ) {
3889 return false;
3890 }
3891
3892 //if rms norm is the B operand, then we don't handle broadcast
3893 if (rms_norm == mul->src[1] && !ggml_are_same_shape(mul->src[0], rms_norm)) {
3894 return false;
3895 }
3896
3897 //rms_norm kernel assumes contiguous rows
3898 if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
3899 return false;
3900 }
3901
3902 if (add && (!ggml_is_contiguous(add->src[0]) || !ggml_is_contiguous_rows(add->src[1]))) {
3903 return false;
3904 }
3905
3906 return true;
3907 }
3908
3909 if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_SCALE) {
3910 const ggml_tensor * rms_norm = cgraph->nodes[node_idx];
3911 const ggml_tensor * scale = cgraph->nodes[node_idx+1];
3912
3913 GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
3914 GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
3915
3916 float bias;
3917 memcpy(&bias, (const float *) scale->op_params + 1, sizeof(float));
3918
3919 return bias == 0.0f && scale->type == GGML_TYPE_F32;
3920 }
3921
3922 if (ops.size() == 2 && ops.begin()[0] == GGML_OP_SSM_CONV && ops.begin()[1] == GGML_OP_UNARY
3923 && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_SILU) {
3924 const ggml_tensor * ssm_conv = cgraph->nodes[node_idx];
3925 const ggml_tensor * silu = cgraph->nodes[node_idx+1];
3926 if (ggml_get_unary_op(silu) != unary_ops.begin()[0]) {
3927 return false;
3928 }
3929
3930 if (ssm_conv->type != GGML_TYPE_F32 || silu->type != GGML_TYPE_F32) {
3931 return false;
3932 }
3933
3934 return true;
3935 }
3936
3937 if (ops.size() == 3 && ops.begin()[0] == GGML_OP_SSM_CONV && ops.begin()[1] == GGML_OP_ADD
3938 && ops.begin()[2] == GGML_OP_UNARY && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_SILU) {
3939 const ggml_tensor * ssm_conv = cgraph->nodes[node_idx];
3940 const ggml_tensor * add = cgraph->nodes[node_idx+1];
3941 const ggml_tensor * silu = cgraph->nodes[node_idx+2];
3942 if (ggml_get_unary_op(silu) != unary_ops.begin()[0]) {
3943 return false;
3944 }
3945
3946 if (ssm_conv->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32 || silu->type != GGML_TYPE_F32) {
3947 return false;
3948 }
3949
3950 // ADD must consume ssm_conv's output and broadcast a 1-D channel-wise bias.
3951 const ggml_tensor * bias = (add->src[0] == ssm_conv) ? add->src[1] : add->src[0];
3952 if (bias->type != GGML_TYPE_F32 || !ggml_is_contiguous(bias)) {
3953 return false;
3954 }
3955 if (ggml_nelements(bias) != ssm_conv->ne[0] || bias->ne[0] != ssm_conv->ne[0]) {
3956 return false;
3957 }
3958
3959 return true;
3960 }
3961
3962 if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_MUL
3963 && unary_ops.size() == 1 && (unary_ops.begin()[0] == GGML_UNARY_OP_SILU || unary_ops.begin()[0] == GGML_UNARY_OP_SIGMOID || unary_ops.begin()[0] == GGML_UNARY_OP_SOFTPLUS)) {
3964 const ggml_tensor * unary = cgraph->nodes[node_idx];
3965 const ggml_tensor * mul = cgraph->nodes[node_idx+1];
3966
3967 if (ggml_get_unary_op(unary) != unary_ops.begin()[0]) {
3968 return false;
3969 }
3970
3971 if (unary->type != GGML_TYPE_F32 && unary->type != GGML_TYPE_F16 && unary->type != GGML_TYPE_BF16) {
3972 return false;
3973 }
3974
3975 if (unary->type != mul->type) {
3976 return false;
3977 }
3978
3979 const ggml_tensor * other = (mul->src[0] == unary) ? mul->src[1] : mul->src[0];
3980 if (other->type != unary->type) {
3981 return false;
3982 }
3983 if (!ggml_is_contiguous_1(other) || !ggml_is_contiguous_1(unary->src[0]) || !ggml_are_same_shape(other, unary)) {
3984 return false;
3985 }
3986
3987 return true;
3988 }
3989
3990 if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_SQR
3991 && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_RELU) {
3992 const ggml_tensor * unary = cgraph->nodes[node_idx];
3993 const ggml_tensor * sqr = cgraph->nodes[node_idx+1];
3994
3995 if (ggml_get_unary_op(unary) != GGML_UNARY_OP_RELU) {
3996 return false;
3997 }
3998
3999 if (unary->type != GGML_TYPE_F32 && unary->type != GGML_TYPE_F16) {
4000 return false;
4001 }
4002
4003 if (unary->type != sqr->type) {
4004 return false;
4005 }
4006
4007 if (!ggml_is_contiguous(unary->src[0])) {
4008 return false;
4009 }
4010
4011 return true;
4012 }
4013
4014 if (ops.size() == 3 && ops.begin()[0] == GGML_OP_SCALE && ops.begin()[1] == GGML_OP_UNARY && ops.begin()[2] == GGML_OP_SCALE
4015 && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_TANH) {
4016 const ggml_tensor *scale = cgraph->nodes[node_idx];
4017 const ggml_tensor *tanh = cgraph->nodes[node_idx+1];
4018 const ggml_tensor *scale2 = cgraph->nodes[node_idx+2];
4019
4020 // the fused softcap kernel is F32 only
4021 if (scale->src[0]->type != GGML_TYPE_F32 || scale->type != GGML_TYPE_F32) {
4022 return false;
4023 }
4024
4025 // TODO: make the fused softcap kernel stride aware, it reads src and writes dst as dense
4026 if (!ggml_is_contiguous(scale->src[0]) || !ggml_is_contiguous(scale2)) {
4027 return false;
4028 }
4029
4030 if (ggml_get_unary_op(tanh) != GGML_UNARY_OP_TANH) {
4031 return false;
4032 }
4033
4034 // Check for bias
4035 if (ggml_get_op_params_f32(scale, 1) != 0.0f || ggml_get_op_params_f32(scale2, 1) != 0.0f) {
4036 return false;
4037 }
4038
4039 return true;
4040 }
4041
4042 return false;
4043}
4044
4045// try and fuse nodes and return the number of nodes to skip
4046static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
4047
4048 if (ggml_cuda_fusion_disabled()) {
4049 return 0;
4050 }
4051
4052 ggml_tensor * node = cgraph->nodes[i];
4053
4054 if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() &&
4055 ggml_cuda_match_shared_expert(cgraph, i, i + 3) &&
4056 ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1])) {
4057 const int outputs[] = { i + 2, i + 5 };
4058 if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, 6, outputs, 2)) {
4059 ggml_tensor * routed = cgraph->nodes[i + 2];
4060 ggml_tensor * shared = cgraph->nodes[i + 5];
4061 const ggml_tensor * up = routed->src[1];
4062 ggml_cuda_mm_fusion_args_host fusion{};
4063 fusion.gate = routed->src[0]->src[0];
4064 fusion.glu_op = ggml_get_glu_op(routed);
4065 fusion.glu_limit = ggml_get_op_params_f32(routed, 3);
4066 fusion.shared_up = shared->src[1]->src[0];
4067 fusion.shared_gate = shared->src[0]->src[0];
4068 fusion.shared_dst = shared;
4069 ggml_cuda_mul_mat_vec_q(*cuda_ctx, up->src[0], up->src[1], up->src[2], routed, &fusion);
4070 return 5;
4071 }
4072 }
4073
4074 if (node->op == GGML_OP_MUL) {
4075 ggml_cuda_moe_weighted_reduction_match match;
4076 if (ggml_cuda_match_moe_weighted_reduction(cgraph, i, match)) {
4077 const int output_idx = i + match.node_count - 1;
4078 if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, match.node_count, &output_idx, 1)) {
4079 ggml_cuda_op_moe_weighted_reduction(
4080 *cuda_ctx, match.experts, match.expert_scale, match.weights, match.dst);
4081 return match.node_count - 1;
4082 }
4083 }
4084 }
4085
4086 // gated_delta_net -> cpy: scatter recurrent-state snapshots into the cache
4087 if (node->op == GGML_OP_GATED_DELTA_NET) {
4088 ggml_cuda_gated_delta_net_fused_cache fused_state_cpy;
4089 const int nodes_to_skip = ggml_cuda_try_gdn_cache_fusion(cgraph, i, fused_state_cpy);
4090 if (nodes_to_skip > 0) {
4091#ifdef GGML_CUDA_DEBUG
4092 GGML_LOG_INFO("%s: fused gated_delta_net snapshot copies for %s (skipped %d nodes)\n",
4093 __func__, node->name, nodes_to_skip);
4094#endif
4095 ggml_cuda_op_gated_delta_net_fused_cache(*cuda_ctx, node, fused_state_cpy);
4096 return nodes_to_skip;
4097 }
4098 }
4099
4100 // ssm_scan -> cpy: scatter recurrent-state snapshots into the cache
4101 if (node->op == GGML_OP_SSM_SCAN) {
4102 ggml_cuda_ssm_scan_fused_cache fused_state_cpy;
4103 const int nodes_to_skip = ggml_cuda_try_ssm_scan_cache_fusion(cgraph, i, fused_state_cpy);
4104 if (nodes_to_skip > 0) {
4105#ifdef GGML_CUDA_DEBUG
4106 GGML_LOG_INFO("%s: fused ssm_scan snapshot copies for %s (skipped %d nodes)\n",
4107 __func__, node->name, nodes_to_skip);
4108#endif
4109 ggml_cuda_op_ssm_scan_fused_cache(*cuda_ctx, node, fused_state_cpy);
4110 return nodes_to_skip;
4111 }
4112 }
4113
4114 //topk-moe
4115 if (cgraph->nodes[i]->op == GGML_OP_UNARY || cgraph->nodes[i]->op == GGML_OP_SOFT_MAX ||
4116 cgraph->nodes[i]->op == GGML_OP_ARGSORT) {
4117 ggml_cuda_topk_moe_args args;
4118 const bool can_fuse = ggml_cuda_topk_moe_fusion(cgraph, i, args);
4119 std::vector<ggml_op> ops;
4120 ops.reserve(13); // max ops; avoids gcc -Wstringop-overflow false positive
4121
4122 if (can_fuse) {
4123 const ggml_tensor * logits = node->src[0];
4124 ggml_tensor * weights = nullptr;
4125 ggml_tensor * ids = nullptr;
4126 const ggml_tensor * bias = nullptr;
4127 const ggml_tensor * clamp = nullptr;
4128 const ggml_tensor * scale = nullptr;
4129
4130 if (!args.delayed_softmax) {
4131 int out_nodes[2]; // nodes which can't be elided
4132
4133 if (args.sigmoid) {
4134 ops.insert(ops.end(), { GGML_OP_UNARY });
4135 } else if (args.sqrt_softplus) {
4136 ops.insert(ops.end(), { GGML_OP_UNARY, GGML_OP_SQRT });
4137 } else {
4138 ops.insert(ops.end(), { GGML_OP_SOFT_MAX });
4139 }
4140 ops.push_back(GGML_OP_RESHAPE);
4141 if (args.prob_bias) {
4142 ops.push_back(GGML_OP_ADD);
4143 bias = cgraph->nodes[i + ops.size() - 1]->src[1];
4144 }
4145 if (args.n_groups > 0) {
4146 for (const auto & p : topk_moe_group_pattern) {
4147 ops.push_back(p.op);
4148 }
4149 }
4150 ops.insert(ops.end(), { GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS });
4151 out_nodes[0] = i + ops.size() - 2;
4152 ids = cgraph->nodes[out_nodes[0]];
4153
4154 if (args.norm) {
4155 ops.insert(ops.end(),
4156 { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV, GGML_OP_RESHAPE });
4157 clamp = cgraph->nodes[i + ops.size() - 3];
4158 }
4159 if (args.scale) {
4160 ops.insert(ops.end(), { GGML_OP_SCALE });
4161 scale = cgraph->nodes[i + ops.size() - 1];
4162 }
4163
4164 weights = cgraph->nodes[i + ops.size() - 1];
4165 out_nodes[1] = i + ops.size() - 1;
4166
4167 if (ggml_can_fuse_subgraph(cgraph, i, ops.size(), ops.data(), out_nodes, 2) &&
4168 ggml_cuda_should_use_topk_moe(node, logits, weights, ids) &&
4169 ggml_cuda_check_fusion_memory_ranges(cgraph, i, ops.size(), out_nodes, 2, /*is_topk_moe=*/true)) {
4170 ggml_cuda_op_topk_moe(*cuda_ctx, logits, weights, ids, clamp, scale, bias, args);
4171 return ops.size() - 1;
4172 }
4173 } else if (!args.norm && !args.prob_bias) {
4174 //special case gpt-oss, no norm, no bias.
4175 ops.insert(ops.end(), { GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
4176 GGML_OP_SOFT_MAX, GGML_OP_RESHAPE });
4177 weights = cgraph->nodes[i + 5];
4178 ids = cgraph->nodes[i + 1];
4179 const ggml_tensor * softmax = cgraph->nodes[i + 4];
4180
4181 int out_nodes[2] = { i + 1, i + 5 };
4182 if (ggml_can_fuse_subgraph(cgraph, i, ops.size(), ops.data(), out_nodes, 2) &&
4183 ggml_cuda_should_use_topk_moe(softmax, logits, weights, ids) &&
4184 ggml_cuda_check_fusion_memory_ranges(cgraph, i, ops.size(), out_nodes, 2, /*is_topk_moe=*/true)) {
4185 ggml_cuda_op_topk_moe(*cuda_ctx, logits, weights, ids, clamp, scale, bias, args);
4186 return ops.size() - 1;
4187 }
4188 }
4189 }
4190 }
4191
4192 //RoPE + view + set-rows
4193 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, {})) {
4194 ggml_tensor * rope = cgraph->nodes[i];
4195 ggml_tensor * set_rows = cgraph->nodes[i + 2];
4196
4197 ggml_cuda_op_rope_fused(*cuda_ctx, rope, set_rows);
4198 return 2;
4199 }
4200
4201 // Snake activation: y = x + sin(a*x)^2 * inv_b
4202 // Naive 5-op decomposition emitted by frontends: mul -> sin -> sqr -> mul -> add
4203 if (ggml_can_fuse_subgraph(cgraph, i,
4204 { GGML_OP_MUL, GGML_OP_SIN, GGML_OP_SQR, GGML_OP_MUL, GGML_OP_ADD },
4205 { i + 4 })) {
4206 const ggml_tensor * mul0 = cgraph->nodes[i];
4207 const ggml_tensor * sqr = cgraph->nodes[i + 2];
4208 const ggml_tensor * mul1 = cgraph->nodes[i + 3];
4209 ggml_tensor * add = cgraph->nodes[i + 4];
4210
4211 // x carries the full activation shape, a is the broadcast operand
4212 const ggml_tensor * x = ggml_are_same_shape(mul0, mul0->src[0]) ? mul0->src[0] : mul0->src[1];
4213 const ggml_tensor * a = (x == mul0->src[0]) ? mul0->src[1] : mul0->src[0];
4214
4215 // mul1 reads sqr and inv_b in either operand order
4216 const ggml_tensor * inv_b = (mul1->src[0] == sqr) ? mul1->src[1] : mul1->src[0];
4217
4218 // closure check: the trailing add must read the same x as the leading mul
4219 const ggml_tensor * x_in_add = (add->src[0] == mul1) ? add->src[1] : add->src[0];
4220
4221 // Kernel iterates over total = T * C, so x and add must be 2D and
4222 // a / inv_b must collapse to [1, C, 1, 1]. Higher dims are not handled.
4223 const bool dim_ok = (x->ne[2] == 1 && x->ne[3] == 1) &&
4224 (add->ne[2] == 1 && add->ne[3] == 1) &&
4225 (a->ne[2] == 1 && a->ne[3] == 1);
4226 const bool shape_ok = ggml_are_same_shape(a, inv_b) && a->ne[0] == 1 && a->ne[1] == x->ne[1];
4227
4228 // x is in the supported whitelist and every chain intermediate shares
4229 // x's type. launch_snake reads a and inv_b as const float *, so they
4230 // stay F32.
4231 const ggml_tensor * sin1 = cgraph->nodes[i + 1];
4232 const bool types_ok = (x->type == GGML_TYPE_F32 || x->type == GGML_TYPE_F16 || x->type == GGML_TYPE_BF16) &&
4233 (a->type == GGML_TYPE_F32) && (inv_b->type == GGML_TYPE_F32) &&
4234 (mul0->type == x->type) && (sin1->type == x->type) &&
4235 (sqr->type == x->type) && (mul1->type == x->type) &&
4236 (add->type == x->type);
4237
4238 // kernel reads x[idx] and a[c] / inv_b[c] linearly, so every operand is contiguous
4239 const bool contig_ok = ggml_is_contiguous(x) && ggml_is_contiguous(add) &&
4240 ggml_is_contiguous(a) && ggml_is_contiguous(inv_b);
4241
4242 if (types_ok && shape_ok && dim_ok && contig_ok && x_in_add == x) {
4243 ggml_cuda_op_snake_fused(*cuda_ctx, x, a, inv_b, add);
4244 return 4;
4245 }
4246 }
4247
4248 // multi-(add or mul)
4249 if (node->op == GGML_OP_ADD || node->op == GGML_OP_MUL) {
4250 int n_fuse = 0;
4251 ggml_op ops[8];
4252 std::fill(ops, ops + 8, node->op);
4253
4254 for (; n_fuse <= 6; ++n_fuse) {
4255 if (!ggml_can_fuse(cgraph, i + n_fuse, ops + n_fuse, 2)) {
4256 break;
4257 }
4258 if (cgraph->nodes[i + n_fuse] != cgraph->nodes[i + n_fuse + 1]->src[0]) {
4259 break;
4260 }
4261 if (!ggml_are_same_layout(cgraph->nodes[i + n_fuse]->src[1], cgraph->nodes[i + n_fuse + 1]->src[1])) {
4262 break;
4263 }
4264 }
4265
4266 n_fuse++;
4267
4268 if (n_fuse > 1) {
4269 ggml_tensor fused_node;
4270 memcpy(&fused_node, node, sizeof(ggml_tensor));
4271 for (int j = 0; j < n_fuse - 1; ++j) {
4272 fused_node.src[j + 2] = cgraph->nodes[i + j + 1]->src[1];
4273 }
4274 fused_node.data = cgraph->nodes[i + n_fuse - 1]->data;
4275 if (node->op == GGML_OP_ADD) {
4276 ggml_cuda_op_fused_add(*cuda_ctx, &fused_node, n_fuse);
4277 } else {
4278 ggml_cuda_op_fused_mul(*cuda_ctx, &fused_node, n_fuse);
4279 }
4280 return n_fuse - 1;
4281 }
4282 }
4283
4284 bool fused_mul_mat_vec = false;
4285 int fused_node_count = 0;
4286
4287 auto get_mul_mat_scale = [](const ggml_tensor * scale_node, const ggml_tensor * mm_node) -> const ggml_tensor * {
4288 const bool scale_lhs_mm = scale_node->src[0] == mm_node;
4289 const bool scale_rhs_mm = scale_node->src[1] == mm_node;
4290 if (!scale_lhs_mm && !scale_rhs_mm) {
4291 return nullptr;
4292 }
4293
4294 const ggml_tensor * scale = scale_lhs_mm ? scale_node->src[1] : scale_node->src[0];
4295 if (mm_node->src[0]->type != GGML_TYPE_NVFP4 || scale_node->type != GGML_TYPE_F32 ||
4296 scale->type != GGML_TYPE_F32 || !ggml_is_contiguous(scale) || ggml_nelements(scale) != 1 ||
4297 !ggml_are_same_shape(scale_node, mm_node)) {
4298 return nullptr;
4299 }
4300
4301 return scale;
4302 };
4303
4304 auto get_mul_mat_id_scale = [](const ggml_tensor * reshape, const ggml_tensor * repeat, const ggml_tensor * getrows,
4305 const ggml_tensor * scale_node, const ggml_tensor * mm_node) -> const ggml_tensor * {
4306 if (repeat->src[0] != reshape || getrows->src[0] != repeat || getrows->src[1] != mm_node->src[2]) {
4307 return nullptr;
4308 }
4309 if (!((scale_node->src[0] == mm_node && scale_node->src[1] == getrows) ||
4310 (scale_node->src[0] == getrows && scale_node->src[1] == mm_node))) {
4311 return nullptr;
4312 }
4313
4314 const ggml_tensor * scale = reshape->src[0];
4315 if (mm_node->src[0]->type != GGML_TYPE_NVFP4 || scale_node->type != GGML_TYPE_F32 ||
4316 scale->type != GGML_TYPE_F32 || !ggml_is_contiguous(scale) || ggml_nelements(scale) != mm_node->src[0]->ne[2] ||
4317 !ggml_are_same_shape(scale_node, mm_node)) {
4318 return nullptr;
4319 }
4320
4321 return scale;
4322 };
4323
4324 auto get_bias_tensor = [](const ggml_tensor * bias_node, const ggml_tensor * mul_node, ggml_op op_bias) -> const ggml_tensor * {
4325 if (op_bias == GGML_OP_ADD) {
4326 if (bias_node->src[0] == mul_node) {
4327 return bias_node->src[1];
4328 }
4329 if (bias_node->src[1] == mul_node) {
4330 return bias_node->src[0];
4331 }
4332 return nullptr;
4333 }
4334 GGML_ASSERT(op_bias == GGML_OP_ADD_ID);
4335 GGML_ASSERT(bias_node->src[0] == mul_node);
4336 return bias_node->src[1];
4337 };
4338
4339 // gate + glu + up, with optional scale/bias on both lanes.
4340 for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) {
4341 const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID;
4342
4343 if (op == GGML_OP_MUL_MAT) {
4344 for (const bool with_bias : { false, true }) {
4345 const int gate_idx = i;
4346 const int gate_scale_idx = i + 1;
4347 const int gate_bias_idx = with_bias ? i + 2 : -1;
4348 const int up_idx = with_bias ? i + 3 : i + 2;
4349 const int up_scale_idx = up_idx + 1;
4350 const int up_bias_idx = with_bias ? up_idx + 2 : -1;
4351 const int glu_idx = with_bias ? up_idx + 3 : up_idx + 2;
4352
4353 const int out_nodes[] = { glu_idx };
4354 ggml_op ops[7];
4355 if (with_bias) {
4356 ops[0] = op;
4357 ops[1] = GGML_OP_MUL;
4358 ops[2] = bias_op;
4359 ops[3] = op;
4360 ops[4] = GGML_OP_MUL;
4361 ops[5] = bias_op;
4362 ops[6] = GGML_OP_GLU;
4363 } else {
4364 ops[0] = op;
4365 ops[1] = GGML_OP_MUL;
4366 ops[2] = op;
4367 ops[3] = GGML_OP_MUL;
4368 ops[4] = GGML_OP_GLU;
4369 }
4370 const int n_ops = with_bias ? 7 : 5;
4371
4372 if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) ||
4373 !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) {
4374 continue;
4375 }
4376
4377 ggml_tensor * gate_n = cgraph->nodes[gate_idx];
4378 ggml_tensor * gate_scale_n = cgraph->nodes[gate_scale_idx];
4379 ggml_tensor * gate_out_n = with_bias ? cgraph->nodes[gate_bias_idx] : gate_scale_n;
4380 ggml_tensor * up_n = cgraph->nodes[up_idx];
4381 ggml_tensor * up_scale_n = cgraph->nodes[up_scale_idx];
4382 ggml_tensor * up_out_n = with_bias ? cgraph->nodes[up_bias_idx] : up_scale_n;
4383 const ggml_tensor * glu = cgraph->nodes[glu_idx];
4384
4385 if (!ggml_cuda_should_fuse_mul_mat(up_n, gate_n, glu,
4386 with_bias ? up_out_n : nullptr, with_bias ? gate_out_n : nullptr, up_scale_n, gate_scale_n)) {
4387 continue;
4388 }
4389
4390 const ggml_tensor * gate_scale = get_mul_mat_scale(gate_scale_n, gate_n);
4391 const ggml_tensor * up_scale = get_mul_mat_scale(up_scale_n, up_n);
4392 if (!gate_scale || !up_scale) {
4393 continue;
4394 }
4395
4396 const ggml_tensor * up_bias = with_bias ? get_bias_tensor(up_out_n, up_scale_n, bias_op) : nullptr;
4397 const ggml_tensor * gate_bias = with_bias ? get_bias_tensor(gate_out_n, gate_scale_n, bias_op) : nullptr;
4398 if (with_bias && (!ggml_are_same_shape(gate_out_n->src[0], gate_out_n->src[1]) ||
4399 !ggml_are_same_shape(up_out_n->src[0], up_out_n->src[1]))) {
4400 continue;
4401 }
4402
4403 const ggml_tensor * src0 = up_n->src[0];
4404 const ggml_tensor * src1 = up_n->src[1];
4405 const ggml_tensor * ids = up_n->src[2];
4406
4407 ggml_cuda_mm_fusion_args_host fusion_data{};
4408 fusion_data.gate = gate_n->src[0];
4409 fusion_data.x_bias = up_bias;
4410 fusion_data.gate_bias = gate_bias;
4411 fusion_data.x_scale = up_scale;
4412 fusion_data.gate_scale = gate_scale;
4413 fusion_data.glu_op = ggml_get_glu_op(glu);
4414 fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
4415
4416 if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) {
4417 ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data);
4418 fused_mul_mat_vec = true;
4419 fused_node_count = n_ops;
4420 break;
4421 }
4422 }
4423
4424 if (fused_mul_mat_vec) {
4425 break;
4426 }
4427 } else {
4428 for (const bool with_bias : { false, true }) {
4429 const int gate_idx = i;
4430 const int gate_scale_idx = i + 4;
4431 const int gate_bias_idx = with_bias ? i + 5 : -1;
4432 const int up_idx = with_bias ? i + 6 : i + 5;
4433 const int up_scale_idx = up_idx + 4;
4434 const int up_bias_idx = with_bias ? up_idx + 5 : -1;
4435 const int glu_idx = with_bias ? up_idx + 6 : up_idx + 5;
4436
4437 const int out_nodes[] = { glu_idx };
4438 ggml_op ops[13];
4439 if (with_bias) {
4440 ops[0] = op;
4441 ops[1] = GGML_OP_RESHAPE;
4442 ops[2] = GGML_OP_REPEAT;
4443 ops[3] = GGML_OP_GET_ROWS;
4444 ops[4] = GGML_OP_MUL;
4445 ops[5] = bias_op;
4446 ops[6] = op;
4447 ops[7] = GGML_OP_RESHAPE;
4448 ops[8] = GGML_OP_REPEAT;
4449 ops[9] = GGML_OP_GET_ROWS;
4450 ops[10] = GGML_OP_MUL;
4451 ops[11] = bias_op;
4452 ops[12] = GGML_OP_GLU;
4453 } else {
4454 ops[0] = op;
4455 ops[1] = GGML_OP_RESHAPE;
4456 ops[2] = GGML_OP_REPEAT;
4457 ops[3] = GGML_OP_GET_ROWS;
4458 ops[4] = GGML_OP_MUL;
4459 ops[5] = op;
4460 ops[6] = GGML_OP_RESHAPE;
4461 ops[7] = GGML_OP_REPEAT;
4462 ops[8] = GGML_OP_GET_ROWS;
4463 ops[9] = GGML_OP_MUL;
4464 ops[10] = GGML_OP_GLU;
4465 }
4466 const int n_ops = with_bias ? 13 : 11;
4467
4468 if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) ||
4469 !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) {
4470 continue;
4471 }
4472
4473 ggml_tensor * gate_n = cgraph->nodes[gate_idx];
4474 ggml_tensor * gate_scale_n = cgraph->nodes[gate_scale_idx];
4475 ggml_tensor * gate_out_n = with_bias ? cgraph->nodes[gate_bias_idx] : gate_scale_n;
4476 ggml_tensor * up_n = cgraph->nodes[up_idx];
4477 ggml_tensor * up_scale_n = cgraph->nodes[up_scale_idx];
4478 ggml_tensor * up_out_n = with_bias ? cgraph->nodes[up_bias_idx] : up_scale_n;
4479 const ggml_tensor * glu = cgraph->nodes[glu_idx];
4480
4481 if (!ggml_cuda_should_fuse_mul_mat(up_n, gate_n, glu,
4482 with_bias ? up_out_n : nullptr, with_bias ? gate_out_n : nullptr, up_scale_n, gate_scale_n)) {
4483 continue;
4484 }
4485
4486 const ggml_tensor * gate_scale = get_mul_mat_id_scale(cgraph->nodes[gate_idx + 1], cgraph->nodes[gate_idx + 2],
4487 cgraph->nodes[gate_idx + 3], gate_scale_n, gate_n);
4488 const ggml_tensor * up_scale = get_mul_mat_id_scale(cgraph->nodes[up_idx + 1], cgraph->nodes[up_idx + 2],
4489 cgraph->nodes[up_idx + 3], up_scale_n, up_n);
4490 if (!gate_scale || !up_scale) {
4491 continue;
4492 }
4493
4494 const ggml_tensor * up_bias = with_bias ? get_bias_tensor(up_out_n, up_scale_n, bias_op) : nullptr;
4495 const ggml_tensor * gate_bias = with_bias ? get_bias_tensor(gate_out_n, gate_scale_n, bias_op) : nullptr;
4496
4497 const ggml_tensor * src0 = up_n->src[0];
4498 const ggml_tensor * src1 = up_n->src[1];
4499 const ggml_tensor * ids = up_n->src[2];
4500
4501 ggml_cuda_mm_fusion_args_host fusion_data{};
4502 fusion_data.gate = gate_n->src[0];
4503 fusion_data.x_bias = up_bias;
4504 fusion_data.gate_bias = gate_bias;
4505 fusion_data.x_scale = up_scale;
4506 fusion_data.gate_scale = gate_scale;
4507 fusion_data.glu_op = ggml_get_glu_op(glu);
4508 fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
4509
4510 if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) {
4511 ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data);
4512 fused_mul_mat_vec = true;
4513 fused_node_count = n_ops;
4514 break;
4515 }
4516 }
4517
4518 if (fused_mul_mat_vec) {
4519 break;
4520 }
4521 }
4522
4523 if (ggml_cuda_can_fuse(cgraph, i, { op, bias_op, op, bias_op, GGML_OP_GLU }, {})) {
4524 ggml_tensor * glu = cgraph->nodes[i + 4];
4525 ggml_tensor * gate_bias_n = glu->src[0];
4526 ggml_tensor * up_bias_n = glu->src[1];
4527
4528 //we don't assume the order for {gate, up}. Instead infer it from the bias tensor
4529 ggml_tensor * gate_n = nullptr;
4530 ggml_tensor * up_n = nullptr;
4531
4532 if (gate_bias_n->src[0] == cgraph->nodes[i] || gate_bias_n->src[1] == cgraph->nodes[i]) {
4533 gate_n = cgraph->nodes[i];
4534 up_n = cgraph->nodes[i + 2];
4535 } else if (gate_bias_n->src[0] == cgraph->nodes[i + 2] || gate_bias_n->src[1] == cgraph->nodes[i + 2]) {
4536 gate_n = cgraph->nodes[i + 2];
4537 up_n = cgraph->nodes[i];
4538 } else {
4539 continue;
4540 }
4541
4542 const ggml_tensor * up_bias_tensor = get_bias_tensor(up_bias_n, up_n, bias_op);
4543 const ggml_tensor * gate_bias_tensor = get_bias_tensor(gate_bias_n, gate_n, bias_op);
4544
4545 if (!up_bias_tensor || !gate_bias_tensor) {
4546 continue;
4547 }
4548
4549 // we don't support repeating adds
4550 if (bias_op == GGML_OP_ADD && (!ggml_are_same_shape(gate_bias_n->src[0], gate_bias_n->src[1]) ||
4551 !ggml_are_same_shape(up_bias_n->src[0], up_bias_n->src[1]))) {
4552 continue;
4553 }
4554
4555 const ggml_tensor * src0 = up_n->src[0];
4556 const ggml_tensor * src1 = up_n->src[1];
4557 const ggml_tensor * ids = up_n->src[2];
4558
4559 if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n)) {
4560 ggml_cuda_mm_fusion_args_host fusion_data{};
4561 fusion_data.gate = gate_n->src[0];
4562 fusion_data.x_bias = up_bias_tensor;
4563 fusion_data.gate_bias = gate_bias_tensor;
4564 fusion_data.glu_op = ggml_get_glu_op(glu);
4565 fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
4566
4567 ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
4568 fused_mul_mat_vec = true;
4569 fused_node_count = 5;
4570 break;
4571 }
4572
4573 if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) {
4574 ggml_cuda_mm_fusion_args_host fusion_data{};
4575 fusion_data.gate = gate_n->src[0];
4576 fusion_data.x_bias = up_bias_tensor;
4577 fusion_data.gate_bias = gate_bias_tensor;
4578 fusion_data.glu_op = ggml_get_glu_op(glu);
4579 fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
4580
4581 ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
4582 fused_mul_mat_vec = true;
4583 fused_node_count = 5;
4584 break;
4585 }
4586 } else if (ggml_cuda_can_fuse(cgraph, i, { op, op, GGML_OP_GLU }, {})) {
4587 ggml_tensor * glu = cgraph->nodes[i + 2];
4588 ggml_tensor * gate = glu->src[0];
4589 ggml_tensor * up = glu->src[1];
4590
4591 bool ok = (gate == cgraph->nodes[i] && up == cgraph->nodes[i + 1]) ||
4592 (gate == cgraph->nodes[i + 1] && up == cgraph->nodes[i]);
4593
4594 if (!ok) {
4595 continue;
4596 }
4597
4598 const ggml_tensor * src0 = up->src[0];
4599 const ggml_tensor * src1 = up->src[1];
4600 const ggml_tensor * ids = up->src[2];
4601
4602 if (ggml_cuda_should_fuse_mul_mat_vec_f(up)) {
4603 ggml_cuda_mm_fusion_args_host fusion_data{};
4604 fusion_data.gate = gate->src[0];
4605 fusion_data.glu_op = ggml_get_glu_op(glu);
4606 fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
4607
4608 ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
4609 fused_mul_mat_vec = true;
4610 fused_node_count = 3;
4611 break;
4612 }
4613
4614 if (ggml_cuda_should_fuse_mul_mat_vec_q(up)) {
4615 ggml_cuda_mm_fusion_args_host fusion_data{};
4616 fusion_data.gate = gate->src[0];
4617 fusion_data.glu_op = ggml_get_glu_op(glu);
4618 fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
4619
4620 ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
4621 fused_mul_mat_vec = true;
4622 fused_node_count = 3;
4623 break;
4624 }
4625
4626 if (ggml_cuda_should_fuse_mul_mat_q(up, gate, glu)) {
4627 ggml_cuda_mm_fusion_args_host fusion_data{};
4628 fusion_data.gate = gate->src[0];
4629 fusion_data.glu_op = ggml_get_glu_op(glu);
4630 fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
4631
4632 ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
4633 fused_mul_mat_vec = true;
4634 fused_node_count = 3;
4635 break;
4636 }
4637 }
4638 }
4639
4640 if (fused_mul_mat_vec) {
4641 return fused_node_count - 1;
4642 }
4643
4644 fused_mul_mat_vec = false;
4645 fused_node_count = 0;
4646
4647 // mul_mat + scale + optional bias
4648 for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) {
4649 const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID;
4650
4651 for (const bool with_bias : { false, true }) {
4652 const int n_ops = op == GGML_OP_MUL_MAT ? (with_bias ? 3 : 2) : (with_bias ? 6 : 5);
4653 const int out_nodes[] = { i + n_ops - 1 };
4654 ggml_op ops[6];
4655 if (op == GGML_OP_MUL_MAT) {
4656 if (with_bias) {
4657 ops[0] = op;
4658 ops[1] = GGML_OP_MUL;
4659 ops[2] = bias_op;
4660 } else {
4661 ops[0] = op;
4662 ops[1] = GGML_OP_MUL;
4663 }
4664 } else {
4665 if (with_bias) {
4666 ops[0] = op;
4667 ops[1] = GGML_OP_RESHAPE;
4668 ops[2] = GGML_OP_REPEAT;
4669 ops[3] = GGML_OP_GET_ROWS;
4670 ops[4] = GGML_OP_MUL;
4671 ops[5] = bias_op;
4672 } else {
4673 ops[0] = op;
4674 ops[1] = GGML_OP_RESHAPE;
4675 ops[2] = GGML_OP_REPEAT;
4676 ops[3] = GGML_OP_GET_ROWS;
4677 ops[4] = GGML_OP_MUL;
4678 }
4679 }
4680
4681 if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) ||
4682 !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) {
4683 continue;
4684 }
4685
4686 ggml_tensor * mm_node = cgraph->nodes[i];
4687 ggml_tensor * scale_node = op == GGML_OP_MUL_MAT ? cgraph->nodes[i + 1] : cgraph->nodes[i + 4];
4688 ggml_tensor * out_node = with_bias ? cgraph->nodes[i + n_ops - 1] : scale_node;
4689
4690 const ggml_tensor * scale = nullptr;
4691 if (op == GGML_OP_MUL_MAT) {
4692 scale = get_mul_mat_scale(scale_node, mm_node);
4693 } else {
4694 scale = get_mul_mat_id_scale(cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 3], scale_node, mm_node);
4695 }
4696 if (!scale) {
4697 continue;
4698 }
4699
4700 const ggml_tensor * bias = with_bias ? get_bias_tensor(out_node, scale_node, bias_op) : nullptr;
4701 if (with_bias && !bias) {
4702 continue;
4703 }
4704 if (with_bias && bias_op == GGML_OP_ADD && !ggml_are_same_shape(out_node->src[0], out_node->src[1])) {
4705 continue;
4706 }
4707 if (with_bias && bias_op == GGML_OP_ADD_ID && out_node->src[2] != mm_node->src[2]) {
4708 continue;
4709 }
4710
4711 const ggml_tensor * src0 = mm_node->src[0];
4712 const ggml_tensor * src1 = mm_node->src[1];
4713 const ggml_tensor * ids = mm_node->src[2];
4714
4715 ggml_cuda_mm_fusion_args_host fusion_data{};
4716 fusion_data.x_bias = bias;
4717 fusion_data.x_scale = scale;
4718
4719 if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node)) {
4720 ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data);
4721 fused_mul_mat_vec = true;
4722 fused_node_count = n_ops;
4723 break;
4724 }
4725 }
4726 if (fused_mul_mat_vec) {
4727 break;
4728 }
4729 }
4730
4731 if (fused_mul_mat_vec) {
4732 return fused_node_count - 1;
4733 }
4734
4735 // mul_mat + add
4736 for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) {
4737 const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID;
4738
4739 if (!ggml_can_fuse(cgraph, i, { op, bias_op })) {
4740 continue;
4741 }
4742
4743 ggml_tensor * mm_node = cgraph->nodes[i];
4744 ggml_tensor * bias_node = cgraph->nodes[i + 1];
4745
4746 ggml_tensor * bias_tensor = nullptr;
4747 if (bias_op == GGML_OP_ADD) {
4748 if (bias_node->src[0] == mm_node) {
4749 bias_tensor = bias_node->src[1];
4750 } else if (bias_node->src[1] == mm_node) {
4751 bias_tensor = bias_node->src[0];
4752 } else {
4753 continue;
4754 }
4755 } else {
4756 if (bias_node->src[0] != mm_node) {
4757 continue;
4758 }
4759 bias_tensor = bias_node->src[1];
4760 }
4761
4762 const ggml_tensor * src0 = mm_node->src[0];
4763 const ggml_tensor * src1 = mm_node->src[1];
4764 const ggml_tensor * ids = mm_node->src[2];
4765
4766 if (bias_op == GGML_OP_ADD_ID && bias_node->src[2] != ids) {
4767 continue;
4768 }
4769
4770 if (bias_op == GGML_OP_ADD && !ggml_are_same_shape(bias_node->src[0], bias_node->src[1])) {
4771 continue;
4772 }
4773
4774 ggml_cuda_mm_fusion_args_host fusion_data{};
4775 fusion_data.x_bias = bias_tensor;
4776
4777 if (ggml_cuda_should_fuse_mul_mat_vec_f(mm_node)) {
4778 ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, bias_node, &fusion_data);
4779 fused_mul_mat_vec = true;
4780 fused_node_count = 2;
4781 break;
4782 }
4783
4784 if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node)) {
4785 ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, bias_node, &fusion_data);
4786 fused_mul_mat_vec = true;
4787 fused_node_count = 2;
4788 break;
4789 }
4790 }
4791
4792 if (fused_mul_mat_vec) {
4793 return fused_node_count - 1;
4794 }
4795
4796 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, {})) {
4797 ggml_cuda_op_rms_norm_mul_rope_fused(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 4]);
4798 return 4;
4799 }
4800
4801 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE }, {})) {
4802 ggml_cuda_op_rms_norm_mul_rope_fused(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2], nullptr);
4803 return 2;
4804 }
4805
4806 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD }, {})) {
4807 ggml_cuda_op_rms_norm_fused_add(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]);
4808 return 2;
4809 }
4810
4811 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL }, {})) {
4812 ggml_cuda_op_rms_norm_fused(*cuda_ctx, node, cgraph->nodes[i + 1]);
4813 return 1;
4814 }
4815
4816 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_SCALE }, {})) {
4817 ggml_cuda_op_rms_norm_scale_fused(*cuda_ctx, node, cgraph->nodes[i + 1]);
4818 return 1;
4819 }
4820
4821 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SSM_CONV, GGML_OP_ADD, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) {
4822 ggml_cuda_op_ssm_conv(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]);
4823 return 2;
4824 }
4825
4826 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SSM_CONV, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) {
4827 ggml_cuda_op_ssm_conv(*cuda_ctx, node, /*bias_add_node=*/ nullptr, cgraph->nodes[i + 1]);
4828 return 1;
4829 }
4830
4831 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SILU }) ||
4832 ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SIGMOID }) ||
4833 ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SOFTPLUS })) {
4834 ggml_cuda_op_unary_mul(*cuda_ctx, node, cgraph->nodes[i + 1]);
4835 return 1;
4836 }
4837
4838 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_SQR }, { GGML_UNARY_OP_RELU })) {
4839 ggml_cuda_op_relu_sqr(*cuda_ctx, node, cgraph->nodes[i + 1]);
4840 return 1;
4841 }
4842
4843 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_DSV4_HC_POST }, { GGML_UNARY_OP_SIGMOID })) {
4844 ggml_cuda_op_dsv4_hc_post(*cuda_ctx, cgraph->nodes[i + 3], node, cgraph->nodes[i + 2]);
4845 return 3;
4846 }
4847
4848 if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE }, { GGML_UNARY_OP_TANH })) {
4849 ggml_cuda_op_softcap(*cuda_ctx, cgraph->nodes[i + 2], node);
4850 return 2;
4851 }
4852
4853 return 0;
4854}
4855
4856static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, const bool use_cuda_graph, const bool cuda_graph_update_required, const void * graph_key) {
4857 bool graph_evaluated_or_captured = false;
4858
4859 // flag used to determine whether it is an integrated_gpu
4860 const bool integrated = ggml_cuda_info().devices[cuda_ctx->device].integrated;
4861
4862 ggml_cuda_stream_context & stream_ctx = cuda_ctx->stream_context();
4863 bool is_concurrent_event_active = false;
4864 ggml_cuda_concurrent_event * concurrent_event = nullptr;
4865 bool should_launch_concurrent_events = false;
4866
4867#ifdef USE_CUDA_GRAPH
4868 ggml_cuda_graph * graph = use_cuda_graph ? cuda_ctx->cuda_graph(graph_key) : nullptr;
4869 const int chunk_size = ggml_cuda_graph_chunk_size();
4870 int chunk_end = chunk_size;
4871 size_t n_chunks = 0;
4872#endif // USE_CUDA_GRAPH
4873
4874 const auto try_launch_concurrent_event = [&](const ggml_tensor * node) {
4875 if (stream_ctx.concurrent_events.find(node) != stream_ctx.concurrent_events.end()) {
4876 concurrent_event = &stream_ctx.concurrent_events[node];
4877
4878 is_concurrent_event_active = true;
4879
4880 GGML_LOG_DEBUG("Launching %d streams at %s\n", concurrent_event->n_streams, node->name);
4881
4882 cudaStream_t main_stream = cuda_ctx->stream(); // this should be stream 0
4883 GGML_ASSERT(cuda_ctx->curr_stream_no == 0);
4884 CUDA_CHECK(cudaEventRecord(concurrent_event->fork_event, main_stream));
4885
4886 for (int i = 1; i <= concurrent_event->n_streams; ++i) {
4887 cudaStream_t stream = cuda_ctx->stream(cuda_ctx->device, i);
4888 CUDA_CHECK(cudaStreamWaitEvent(stream, concurrent_event->fork_event));
4889 }
4890 }
4891 };
4892
4893 while (!graph_evaluated_or_captured) {
4894 // Only perform the graph execution if CUDA graphs are not enabled, or we are capturing the graph.
4895 // With the use of CUDA graphs, the execution will be performed by the graph launch.
4896 if (!use_cuda_graph || cuda_graph_update_required) {
4897 [[maybe_unused]] int prev_i = 0;
4898
4899 if (stream_ctx.concurrent_events.size() > 0) {
4900 should_launch_concurrent_events = true;
4901 for (const auto & [tensor, event] : stream_ctx.concurrent_events) {
4902 should_launch_concurrent_events = should_launch_concurrent_events && event.is_valid();
4903 }
4904 }
4905
4906 if (should_launch_concurrent_events) {
4907 // Restore original node order within each concurrent region to enable fusion within streams
4908
4909 std::unordered_map<const ggml_tensor *, int> node_to_idx;
4910 node_to_idx.reserve(cgraph->n_nodes);
4911 for (int i = 0; i < cgraph->n_nodes; ++i) {
4912 node_to_idx[cgraph->nodes[i]] = i;
4913 }
4914
4915 for (auto & [fork_node, event] : stream_ctx.concurrent_events) {
4916 // Find positions of all nodes from this event in the current graph
4917 std::vector<int> positions;
4918 positions.reserve(event.original_order.size());
4919
4920 bool all_found = true;
4921 for (const ggml_tensor * orig_node : event.original_order) {
4922 auto it = node_to_idx.find(orig_node);
4923 if (it != node_to_idx.end()) {
4924 positions.push_back(it->second);
4925 } else {
4926 all_found = false;
4927 break;
4928 }
4929 }
4930
4931 if (!all_found || positions.size() != event.original_order.size()) {
4932 continue;
4933 }
4934
4935 // Sort positions to get contiguous range
4936 std::vector<int> sorted_positions = positions;
4937 std::sort(sorted_positions.begin(), sorted_positions.end());
4938
4939 bool is_contiguous = true;
4940 for (size_t i = 1; i < sorted_positions.size(); ++i) {
4941 if (sorted_positions[i] != sorted_positions[i-1] + 1) {
4942 is_contiguous = false;
4943 break;
4944 }
4945 }
4946
4947 if (!is_contiguous) {
4948 continue;
4949 }
4950
4951 // Restore original order at the sorted positions
4952 int start_pos = sorted_positions[0];
4953 for (size_t i = 0; i < event.original_order.size(); ++i) {
4954 cgraph->nodes[start_pos + i] = const_cast<ggml_tensor *>(event.original_order[i]);
4955 }
4956 }
4957 } else {
4958 stream_ctx.concurrent_events.clear();
4959 }
4960
4961 for (int i = 0; i < cgraph->n_nodes; i++) {
4962 ggml_tensor * node = cgraph->nodes[i];
4963#ifdef USE_CUDA_GRAPH
4964 // fused nodes are skipped together, so a cut never splits a fusion
4965 // a concurrent region must join before its capture can end
4966 if (use_cuda_graph && chunk_size > 0 && i >= chunk_end && !is_concurrent_event_active) {
4967 ggml_cuda_graph_launch_chunk(cuda_ctx, graph, n_chunks++);
4968 CUDA_CHECK(cudaStreamBeginCapture(cuda_ctx->stream(), cudaStreamCaptureModeRelaxed));
4969 chunk_end = i + chunk_size;
4970 }
4971#endif // USE_CUDA_GRAPH
4972 if (is_concurrent_event_active) {
4973 GGML_ASSERT(concurrent_event);
4974
4975 if (node == concurrent_event->join_node) {
4976 cuda_ctx->curr_stream_no = 0;
4977 for (int i = 1; i <= concurrent_event->n_streams; ++i) {
4978 // Wait on join events of forked streams in the main stream
4979 CUDA_CHECK(cudaEventRecord(concurrent_event->join_events[i - 1],
4980 cuda_ctx->stream(cuda_ctx->device, i)));
4981 CUDA_CHECK(cudaStreamWaitEvent(cuda_ctx->stream(), concurrent_event->join_events[i - 1]));
4982 }
4983
4984 is_concurrent_event_active = false;
4985 concurrent_event = nullptr;
4986 } else {
4987 GGML_ASSERT (concurrent_event->stream_mapping.find(node) != concurrent_event->stream_mapping.end());
4988 cuda_ctx->curr_stream_no = concurrent_event->stream_mapping[node];
4989 GGML_LOG_DEBUG("Setting stream no to %d for node %s\n", cuda_ctx->curr_stream_no, node->name);
4990 }
4991 } else if (i - prev_i > 1) {
4992 //the previous node was fused
4993 const ggml_tensor * prev_node = cgraph->nodes[i - 1];
4994 try_launch_concurrent_event(prev_node);
4995
4996 if (is_concurrent_event_active) {
4997 cuda_ctx->curr_stream_no = concurrent_event->stream_mapping[node];
4998 GGML_LOG_DEBUG("Setting stream no to %d for node %s\n", cuda_ctx->curr_stream_no, node->name);
4999 }
5000 }
5001
5002 prev_i = i;
5003
5004 if (ggml_cuda_is_view_or_noop(node)) {
5005 continue;
5006 }
5007
5008 if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
5009 continue;
5010 }
5011
5012 int nodes_to_skip = ggml_cuda_try_fuse(cuda_ctx, cgraph, i);
5013
5014 if (nodes_to_skip != 0) {
5015#ifdef GGML_CUDA_DEBUG
5016 const int last_fused = i + nodes_to_skip;
5017 GGML_LOG_INFO("nodes_fused: %d, first: %s (%s), last: %s (%s)\n",
5018 nodes_to_skip + 1, ggml_op_name(node->op), node->name,
5019 ggml_op_name(cgraph->nodes[last_fused]->op), cgraph->nodes[last_fused]->name);
5020#endif
5021 i += nodes_to_skip;
5022 continue;
5023 }
5024#ifndef NDEBUG
5025 // On integrated GPUs (APUs, e.g. RDNA3.5) the scheduler may place a
5026 // node's output on the host-visible buffer, which the compute path
5027 // handles. Allow that here, mirroring the src-tensor check below.
5028 assert(node->buffer->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device) ||
5029 (integrated && ggml_backend_buft_is_cuda_host(node->buffer->buft)));
5030 for (int j = 0; j < GGML_MAX_SRC; j++) {
5031 if (node->src[j] != nullptr) {
5032 assert(node->src[j]->buffer);
5033 assert(node->src[j]->buffer->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device) ||
5034 (integrated && ggml_backend_buft_is_cuda_host(node->src[j]->buffer->buft)));
5035 }
5036 }
5037#else
5038 GGML_UNUSED(integrated);
5039#endif // NDEBUG
5040
5041 bool ok = ggml_cuda_compute_forward(*cuda_ctx, node);
5042 if (!ok) {
5043 GGML_LOG_ERROR("%s: op not supported %s (%s)\n", __func__, node->name, ggml_op_name(node->op));
5044 }
5045 GGML_ASSERT(ok);
5046
5047 if (!is_concurrent_event_active) {
5048 try_launch_concurrent_event(node);
5049 }
5050 }
5051 }
5052
5053#ifdef USE_CUDA_GRAPH
5054 if (use_cuda_graph && cuda_graph_update_required) { // End CUDA graph capture
5055 ggml_cuda_graph_launch_chunk(cuda_ctx, graph, n_chunks++);
5056
5057 // drop the chunks left over from a longer graph
5058 for (size_t i = n_chunks; i < graph->instances.size(); ++i) {
5059 CUDA_CHECK(cudaGraphExecDestroy(graph->instances[i]));
5060 }
5061 graph->instances.resize(n_chunks);
5062 graph_evaluated_or_captured = true; // CUDA graph has been captured
5063
5064 std::lock_guard<std::mutex> lock(ggml_cuda_lock);
5065 if (ggml_cuda_lock_counter.fetch_sub(1, std::memory_order_relaxed) == 1) {
5066 ggml_cuda_lock_cv.notify_all();
5067 }
5068 } else {
5069 graph_evaluated_or_captured = true; // ggml graph has been directly evaluated
5070 }
5071 }
5072
5073 if (use_cuda_graph && !cuda_graph_update_required) {
5074 // the chunks were launched during capture, otherwise launch them here
5075 for (cudaGraphExec_t instance : graph->instances) {
5076 CUDA_CHECK(cudaGraphLaunch(instance, cuda_ctx->stream()));
5077 }
5078#else
5079 GGML_UNUSED(graph_key);
5080 graph_evaluated_or_captured = true;
5081#endif // USE_CUDA_GRAPH
5082 }
5083}
5084
5085#ifdef USE_CUDA_GRAPH
5086static bool ggml_cuda_graph_set_enabled(ggml_backend_cuda_context * cuda_ctx, const void * graph_key) {
5087 ggml_cuda_graph * graph = cuda_ctx->cuda_graph(graph_key);
5088
5089 if (graph->instances.empty()) {
5090 if (ggml_cuda_info().devices[cuda_ctx->device].cc < GGML_CUDA_CC_VOLTA) {
5091 if (!graph->disable_due_to_gpu_arch && ggml_cuda_graph_debug_enabled()) {
5092 GGML_LOG_DEBUG("%s: disabling CUDA graphs due to GPU architecture\n", __func__);
5093 }
5094 graph->disable_due_to_gpu_arch = true;
5095 }
5096 }
5097
5098 return graph->is_enabled();
5099}
5100#endif // USE_CUDA_GRAPH
5101
5102static enum ggml_status ggml_backend_cuda_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
5103 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context;
5104
5105 ggml_cuda_set_device(cuda_ctx->device);
5106
5107 bool use_cuda_graph = false;
5108 bool cuda_graph_update_required = false;
5109 const void * graph_key = nullptr;
5110
5111#ifdef USE_CUDA_GRAPH
5112 graph_key = ggml_cuda_graph_get_key(cgraph);
5113
5114 ggml_cuda_graph_set_enabled(cuda_ctx, graph_key);
5115
5116 ggml_cuda_graph * graph = cuda_ctx->cuda_graph(graph_key);
5117 if (graph->is_enabled()) {
5118 const bool graph_compatible = ggml_cuda_graph_check_compability(cgraph);
5119 if (graph_compatible) {
5120 const bool properties_changed = ggml_cuda_graph_update_required(cuda_ctx, cgraph);
5121
5122 if (!graph->warmup_complete) {
5123 // Warmup: need at least 2 calls with no property change on the 2nd call
5124 if (!properties_changed) {
5125 graph->warmup_complete = true;
5126 if (ggml_cuda_graph_debug_enabled()) {
5127 GGML_LOG_DEBUG("%s: CUDA graph warmup complete\n", __func__);
5128 }
5129 use_cuda_graph = true;
5130 cuda_graph_update_required = true;
5131 }
5132 // else: properties changed or first call - execute directly (use_cuda_graph stays false)
5133 } else {
5134 // Post-warmup: normal CUDA graph operation
5135 if (properties_changed) {
5136 // Properties changed - reset warmup, execute directly until stable again
5137 graph->warmup_complete = false;
5138 if (ggml_cuda_graph_debug_enabled()) {
5139 GGML_LOG_DEBUG("%s: CUDA graph warmup reset\n", __func__);
5140 }
5141 } else {
5142 use_cuda_graph = true;
5143 cuda_graph_update_required = graph->instances.empty();
5144 }
5145 }
5146 }
5147 }
5148#endif // USE_CUDA_GRAPH
5149
5150 if (use_cuda_graph && cuda_graph_update_required) {
5151 // Start CUDA graph capture
5152 {
5153 std::lock_guard<std::mutex> lock(ggml_cuda_lock);
5154 ggml_cuda_lock_counter.fetch_add(1, std::memory_order_relaxed);
5155 }
5156
5157 CUDA_CHECK(cudaStreamBeginCapture(cuda_ctx->stream(), cudaStreamCaptureModeRelaxed));
5158 }
5159
5160 ggml_cuda_graph_evaluate_and_capture(cuda_ctx, cgraph, use_cuda_graph, cuda_graph_update_required, graph_key);
5161
5162 return GGML_STATUS_SUCCESS;
5163}
5164
5165static void ggml_backend_cuda_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
5166 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
5167
5168 CUDA_CHECK(cudaEventRecord((cudaEvent_t)event->context, cuda_ctx->stream()));
5169}
5170
5171static void ggml_backend_cuda_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
5172 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
5173
5174 if (ggml_backend_is_cuda(backend)) {
5175 CUDA_CHECK(cudaStreamWaitEvent(cuda_ctx->stream(), (cudaEvent_t)event->context, 0));
5176 } else {
5177#if 0
5178 // untested
5179 auto wait_fn = [](void * user_data) {
5180 ggml_backend_event_t event = (ggml_backend_event_t)user_data;
5181 ggml_backend_event_synchronize(event);
5182 };
5183
5184 CUDA_CHECK(cudaLaunchHostFunc(cuda_ctx->stream(), wait_fn, event));
5185#endif
5186 GGML_ABORT("fatal error");
5187 }
5188}
5189
5190static void ggml_backend_cuda_graph_optimize(ggml_backend_t backend, ggml_cgraph * cgraph, ggml_backend_graph_optimize_params * params) {
5191 ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context;
5192
5193 const bool disable_fusion = ggml_cuda_fusion_disabled();
5194
5195 auto add_alloc_deps = [&](size_t start, size_t last_node) {
5196
5197 for (size_t i = start; i < last_node; ++i) {
5198 params->add_alloc_dep(params->user_data, cgraph->nodes[i], cgraph->nodes[last_node]);
5199
5200 for (int j = 0; j < GGML_MAX_SRC; ++j) {
5201 if (cgraph->nodes[i]->src[j]) {
5202 params->add_alloc_dep(params->user_data, cgraph->nodes[i]->src[j], cgraph->nodes[last_node]);
5203 }
5204 }
5205 }
5206 };
5207
5208 if (!disable_fusion) {
5209 // add alloc deps for performance positive fusions. This may increase the overall compute buffer size.
5210 // TODO: consolidate fusion paths in graph_optimize and graph_compute
5211 ggml_cuda_set_device(cuda_ctx->device);
5212 for (int i = 0; i + 5 < cgraph->n_nodes; ++i) {
5213 if (cgraph->nodes[i]->op != GGML_OP_MUL_MAT_ID) {
5214 continue;
5215 }
5216 for (int j = i + 3; j + 2 < cgraph->n_nodes; ++j) {
5217 if (cgraph->nodes[j]->op == GGML_OP_MUL_MAT_ID && cgraph->nodes[j + 1]->op == GGML_OP_MUL_MAT_ID) {
5218 break;
5219 }
5220 if (cgraph->nodes[j]->op != GGML_OP_MUL_MAT || !ggml_cuda_match_shared_expert(cgraph, i, j)) {
5221 continue;
5222 }
5223 // Group both outputs before allocation so the shared result cannot alias intervening nodes.
5224 std::rotate(cgraph->nodes + i + 3, cgraph->nodes + j, cgraph->nodes + j + 3);
5225 ggml_tensor * up = cgraph->nodes[i + 2]->src[1];
5226 params->add_alloc_dep(params->user_data, up->src[1], cgraph->nodes[i + 5]);
5227 params->add_alloc_dep(params->user_data, up->src[2], cgraph->nodes[i + 5]);
5228 i += 5;
5229 break;
5230 }
5231 }
5232 for (int i = 0; i < cgraph->n_nodes; ++i) {
5233 // Keep the inputs of the fused gate/up/GLU MMQ kernel alive until the GLU so that they cannot alias its output (under op offload the weights are buffer copies).
5234 if (i + 2 < cgraph->n_nodes && cgraph->nodes[i + 2]->op == GGML_OP_GLU) {
5235 ggml_tensor * glu = cgraph->nodes[i + 2];
5236 ggml_tensor * gate = glu->src[0];
5237 ggml_tensor * up = glu->src[1];
5238 const bool ok = (gate == cgraph->nodes[i] && up == cgraph->nodes[i + 1]) || (gate == cgraph->nodes[i + 1] && up == cgraph->nodes[i]);
5239 if (ok && ggml_cuda_mul_mat_q_fusion_matches(up, gate, glu, cuda_ctx->device)) {
5240 add_alloc_deps(i, i + 2);
5241 i += 2;
5242 continue;
5243 }
5244 }
5245
5246 ggml_cuda_moe_weighted_reduction_match match;
5247 if (ggml_cuda_match_moe_weighted_reduction(cgraph, i, match)) {
5248 params->add_alloc_dep(params->user_data, const_cast<ggml_tensor *>(match.experts), match.dst);
5249 params->add_alloc_dep(params->user_data, const_cast<ggml_tensor *>(match.weights), match.dst);
5250 if (match.expert_scale != nullptr) {
5251 params->add_alloc_dep(
5252 params->user_data, const_cast<ggml_tensor *>(match.expert_scale), match.dst);
5253 }
5254 i += match.node_count - 1;
5255 }
5256
5257 if (cgraph->nodes[i]->op == GGML_OP_UNARY || cgraph->nodes[i]->op == GGML_OP_SOFT_MAX ||
5258 cgraph->nodes[i]->op == GGML_OP_ARGSORT) {
5259 ggml_cuda_topk_moe_args args;
5260 const bool can_fuse = ggml_cuda_topk_moe_fusion(cgraph, i, args);
5261 std::vector<ggml_op> ops;
5262 ops.reserve(13); // max ops; avoids gcc -Wstringop-overflow false positive
5263
5264 const ggml_tensor * node = cgraph->nodes[i];
5265
5266 if (can_fuse) {
5267 const ggml_tensor * logits = node->src[0];
5268 ggml_tensor * weights = nullptr;
5269 ggml_tensor * ids = nullptr;
5270
5271 if (!args.delayed_softmax) {
5272 int out_nodes[2]; // nodes which can't be elided
5273
5274 if (args.sigmoid) {
5275 ops.insert(ops.end(), { GGML_OP_UNARY });
5276 } else if (args.sqrt_softplus) {
5277 ops.insert(ops.end(), { GGML_OP_UNARY, GGML_OP_SQRT });
5278 } else {
5279 ops.insert(ops.end(), { GGML_OP_SOFT_MAX });
5280 }
5281 const int i_probs = i + (int) ops.size() - 1; // last node of the gating activation
5282
5283 if (args.prob_bias) {
5284 ops.insert(ops.end(), { GGML_OP_RESHAPE, GGML_OP_ADD, GGML_OP_ARGSORT, GGML_OP_VIEW,
5285 GGML_OP_GET_ROWS });
5286 out_nodes[0] = i_probs + 4;
5287 } else {
5288 ops.insert(ops.end(), { GGML_OP_RESHAPE, GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS });
5289 out_nodes[0] = i_probs + 3;
5290 }
5291 ids = cgraph->nodes[out_nodes[0]];
5292
5293 if (args.norm) {
5294 ops.insert(ops.end(),
5295 { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV, GGML_OP_RESHAPE });
5296 }
5297 if (args.scale) {
5298 ops.insert(ops.end(), { GGML_OP_SCALE });
5299 }
5300
5301 weights = cgraph->nodes[i + ops.size() - 1];
5302 out_nodes[1] = i + ops.size() - 1;
5303
5304 if (ggml_can_fuse_subgraph(cgraph, i, ops.size(), ops.data(), out_nodes, 2) &&
5305 ggml_cuda_should_use_topk_moe(node, logits, weights, ids)) {
5306
5307 add_alloc_deps(i, i + ops.size());
5308 i += ops.size() - 1;
5309 }
5310 }
5311 }
5312 }
5313 }
5314 }
5315
5316#ifdef USE_CUDA_GRAPH
5317 const void * graph_key = ggml_cuda_graph_get_key(cgraph);
5318 const bool use_cuda_graph = ggml_cuda_graph_set_enabled(cuda_ctx, graph_key);
5319#else
5320 const bool use_cuda_graph = false;
5321 GGML_UNUSED(cuda_ctx);
5322 GGML_UNUSED(cgraph);
5323#endif
5324
5325 static bool enable_graph_optimization = [] {
5326 const char * env = getenv("GGML_CUDA_GRAPH_OPT");
5327 return env != nullptr && atoi(env) == 1;
5328 }();
5329
5330 if (!enable_graph_optimization) {
5331 return;
5332 }
5333
5334 ggml_cuda_stream_context & stream_context = cuda_ctx->stream_context();
5335 stream_context.reset();
5336
5337 if (!use_cuda_graph) {
5338 return;
5339 }
5340
5341 ggml_cuda_set_device(cuda_ctx->device);
5342
5343 // number of out-degrees for a particular node
5344 std::unordered_map<const ggml_tensor *, int> fan_out;
5345 // reverse mapping of node to index in the cgraph
5346 std::unordered_map<const ggml_tensor *, int> node_indices;
5347
5348 const auto & is_noop = [](const ggml_tensor * node) -> bool {
5349 return ggml_is_empty(node) || node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE ||
5350 node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE;
5351 };
5352
5353 const auto & depends_on = [](const ggml_tensor * dst, const ggml_tensor * src) -> bool {
5354 for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
5355 if (dst->src[s] == src) {
5356 return true;
5357 }
5358 }
5359 // implicit dependency if they view the same tensor
5360 const ggml_tensor * dst2 = dst->view_src ? dst->view_src : dst;
5361 const ggml_tensor * src2 = src->view_src ? src->view_src : src;
5362 if (dst2 == src2) {
5363 return true;
5364 }
5365 return false;
5366 };
5367
5368 for (int node_idx = 0; node_idx < cgraph->n_nodes; node_idx++) {
5369 const ggml_tensor * node = cgraph->nodes[node_idx];
5370 node_indices[node] = node_idx;
5371
5372 if (is_noop(node)) {
5373 continue;
5374 }
5375 for (int src_idx = 0; src_idx < GGML_MAX_SRC; ++src_idx) {
5376 const ggml_tensor * src = cgraph->nodes[node_idx]->src[src_idx];
5377 //TODO: check why nrows > 1 fails
5378 if (node && !is_noop(node) && ggml_nrows(node) <= 1) {
5379 fan_out[src] += 1;
5380 }
5381 }
5382 }
5383
5384 // Target Q, K, V for concurrency
5385 // this is a more general way to find nodes which can be candidates for concurrency (although it has not been tested for anything else):
5386 // 1. find fan-out (fork) nodes where the same input is used at least N times (in QKV, it would be "attn-norm")
5387 // 2. find the join node, where 2 or more of the outputs are required (in QKV, this would "KQ" or "flash-attn")
5388 // 3. account for all branches from the fork to the join
5389 // 4. To extend lifetimes of the tensors, we interleave the branches (see below for more details)
5390 // 5. save the original cgraph and restore it in graph_compute, to enable fusion within streams
5391 // See discussion: https://github.com/ggml-org/llama.cpp/pull/16991#issuecomment-3522620030
5392
5393 const int min_fan_out = 3;
5394 const int max_fan_out = 3;
5395
5396 // store {fork_idx, join_idx}
5397 std::vector<std::pair<int, int>> concurrent_node_ranges;
5398
5399 for (const auto & [root_node, count] : fan_out) {
5400 if (count >= min_fan_out && count <= max_fan_out) {
5401 const int root_node_idx = node_indices[root_node];
5402
5403 // only optimize for attn_norm
5404 // TODO: make this more generic
5405 if (!strstr(root_node->name, "attn_norm")) {
5406 continue;
5407 }
5408
5409 bool is_part_of_event = false;
5410 for (const auto & [start, end] : concurrent_node_ranges) {
5411 if (root_node_idx >= start && root_node_idx <= end) {
5412 is_part_of_event = true;
5413 }
5414 }
5415
5416 if (is_part_of_event) {
5417 continue;
5418 }
5419
5420 std::vector<std::vector<const ggml_tensor *>> nodes_per_branch;
5421 for (int i = root_node_idx + 1; i < cgraph->n_nodes; ++i) {
5422 const ggml_tensor * node = cgraph->nodes[i];
5423 if (!is_noop(node) && depends_on(node, root_node)) {
5424 nodes_per_branch.push_back({ node });
5425 }
5426 }
5427
5428 GGML_ASSERT(nodes_per_branch.size() == (size_t) count);
5429
5430 //find the join point
5431 const ggml_tensor * join_node = nullptr;
5432
5433 const auto & belongs_to_branch = [&](const ggml_tensor * node,
5434 const std::vector<const ggml_tensor *> & branch) -> bool {
5435 for (const ggml_tensor * n : branch) {
5436 if (depends_on(node, n)) {
5437 return true;
5438 }
5439 }
5440 return false;
5441 };
5442
5443 for (int i = root_node_idx + 1; i < cgraph->n_nodes; ++i) {
5444 const ggml_tensor * curr_node = cgraph->nodes[i];
5445
5446 int num_joins = 0;
5447 for (size_t branch_idx = 0; branch_idx < nodes_per_branch.size(); branch_idx++) {
5448 if (belongs_to_branch(curr_node, nodes_per_branch[branch_idx])) {
5449 num_joins++;
5450 }
5451 }
5452
5453 if (num_joins >= 2) {
5454 join_node = curr_node;
5455 break;
5456 }
5457
5458 bool found_branch = false;
5459 for (size_t branch_idx = 0; branch_idx < nodes_per_branch.size(); branch_idx++) {
5460 std::vector<const ggml_tensor *> & branch_vec = nodes_per_branch[branch_idx];
5461 if (belongs_to_branch(curr_node, branch_vec)) {
5462 //continue accumulating
5463 if (std::find(branch_vec.begin(), branch_vec.end(), curr_node) == branch_vec.end()) {
5464 branch_vec.push_back(curr_node);
5465 }
5466 found_branch = true;
5467 }
5468 }
5469
5470 if (!found_branch && is_noop(curr_node)) {
5471 // we can put it in any branch because it will be ignored
5472 nodes_per_branch[0].push_back({ curr_node });
5473 }
5474 }
5475
5476 if (join_node) {
5477 //Create ggml_cuda_concurrent_event
5478 ggml_cuda_concurrent_event concurrent_event(nodes_per_branch.size());
5479 concurrent_event.join_node = join_node;
5480
5481 for (size_t branch_idx = 0; branch_idx < nodes_per_branch.size(); branch_idx++) {
5482 for (const ggml_tensor * n : nodes_per_branch[branch_idx]) {
5483 concurrent_event.stream_mapping[n] = branch_idx + 1;
5484 }
5485 }
5486
5487 int fork_node_idx = node_indices[root_node];
5488 int join_node_idx = node_indices[join_node];
5489
5490 int current_branch_idx = 0;
5491 int current_node_idx = fork_node_idx + 1;
5492 const int n_branches = nodes_per_branch.size();
5493
5494 int total_branch_nodes = 0;
5495 for (std::vector<const ggml_tensor *> branch_nodes : nodes_per_branch) {
5496 total_branch_nodes += branch_nodes.size();
5497 }
5498
5499 // there are other nodes in the middle which are unaccounted for
5500 // usually (cpy) nodes, then ignore this fork
5501 if (join_node_idx - fork_node_idx - 1 != total_branch_nodes) {
5502 GGML_LOG_DEBUG(
5503 "Skipping %s because the number of nodes in the middle is not equal to the total number of "
5504 "branch nodes %d != %d\n",
5505 root_node->name, join_node_idx - fork_node_idx - 1, total_branch_nodes);
5506 continue;
5507 }
5508
5509 // Save the original order of nodes in this region before interleaving
5510 // This is used later to restore grouping for fusion within streams
5511 concurrent_event.original_order.reserve(total_branch_nodes);
5512 for (int i = fork_node_idx + 1; i < join_node_idx; ++i) {
5513 concurrent_event.original_order.push_back(cgraph->nodes[i]);
5514 }
5515
5516 std::unordered_map<const ggml_tensor *, ggml_cuda_concurrent_event> & concurrent_events = cuda_ctx->stream_context().concurrent_events;
5517 GGML_ASSERT(concurrent_events.find(root_node) == concurrent_events.end());
5518 concurrent_events.emplace(root_node, std::move(concurrent_event));
5519 GGML_LOG_DEBUG("Adding stream at node %s %p\n", root_node->name, root_node);
5520 concurrent_node_ranges.emplace_back(fork_node_idx, join_node_idx);
5521
5522 // interleave tensors to extend lifetimes so that ggml graph doesn't recycle them
5523 // example transformation:
5524 // [attn-norm, QMul, QNorm, QRope, KMul, KNorm, KRope, VMul, attn] ->
5525 // [attn-norm, QMul, KMul, VMul, QNorm, VNorm, QRope, KRope, attn]
5526 while (current_node_idx < join_node_idx) {
5527 std::vector<const ggml_tensor *> & branch_nodes = nodes_per_branch[current_branch_idx];
5528
5529 bool has_node = false;
5530 for (std::vector<const ggml_tensor *> branch_node : nodes_per_branch) {
5531 has_node |= branch_node.size() > 0;
5532 }
5533
5534 GGML_ASSERT(has_node);
5535
5536 if (branch_nodes.empty()) {
5537 current_branch_idx = (current_branch_idx + 1) % n_branches;
5538 continue;
5539 }
5540
5541 cgraph->nodes[current_node_idx] = const_cast<ggml_tensor *>(branch_nodes.front());
5542 current_node_idx++;
5543 branch_nodes.erase(branch_nodes.begin());
5544
5545 // append all empty nodes
5546 while (!branch_nodes.empty() && is_noop(branch_nodes.front())) {
5547 cgraph->nodes[current_node_idx] = const_cast<ggml_tensor *>(branch_nodes.front());
5548 current_node_idx++;
5549 branch_nodes.erase(branch_nodes.begin());
5550 }
5551
5552 current_branch_idx = (current_branch_idx + 1) % n_branches;
5553 }
5554 }
5555 }
5556 }
5557}
5558
5559static const ggml_backend_i ggml_backend_cuda_interface = {
5560 /* .get_name = */ ggml_backend_cuda_get_name,
5561 /* .free = */ ggml_backend_cuda_free,
5562 /* .set_tensor_async = */ ggml_backend_cuda_set_tensor_async,
5563 /* .get_tensor_async = */ ggml_backend_cuda_get_tensor_async,
5564 /* .set_tensor_2d_async = */ ggml_backend_cuda_set_tensor_2d_async,
5565 /* .get_tensor_2d_async = */ ggml_backend_cuda_get_tensor_2d_async,
5566 /* .cpy_tensor_async = */ ggml_backend_cuda_cpy_tensor_async,
5567 /* .synchronize = */ ggml_backend_cuda_synchronize,
5568 /* .graph_plan_create = */ NULL,
5569 /* .graph_plan_free = */ NULL,
5570 /* .graph_plan_update = */ NULL,
5571 /* .graph_plan_compute = */ NULL,
5572 /* .graph_compute = */ ggml_backend_cuda_graph_compute,
5573 /* .event_record = */ ggml_backend_cuda_event_record,
5574 /* .event_wait = */ ggml_backend_cuda_event_wait,
5575 /* .graph_optimize = */ ggml_backend_cuda_graph_optimize,
5576};
5577
5578static ggml_guid_t ggml_backend_cuda_guid() {
5579 static ggml_guid guid = { 0x2c, 0xdd, 0xe8, 0x1c, 0x65, 0xb3, 0x65, 0x73, 0x6a, 0x12, 0x88, 0x61, 0x1c, 0xc9, 0xdc, 0x25 };
5580 return &guid;
5581}
5582
5583bool ggml_backend_is_cuda(ggml_backend_t backend) {
5584 return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_cuda_guid());
5585}
5586
5587int ggml_backend_cuda_get_device_count() {
5588 return ggml_cuda_info().device_count;
5589}
5590
5591static std::string ggml_cuda_device_description(int device) {
5592 cudaDeviceProp prop;
5593 CUDA_CHECK(cudaGetDeviceProperties(&prop, ggml_cuda_get_physical_device(device)));
5594
5595 const ggml_cuda_device_info & info = ggml_cuda_info();
5596 std::string description = prop.name;
5597 if (info.device_count > info.physical_device_count) {
5598 description += " (dev p" + std::to_string(info.devices[device].physical_device) +
5599 "/v" + std::to_string(info.devices[device].virtual_index) + ")";
5600 }
5601 return description;
5602}
5603
5604void ggml_backend_cuda_get_device_description(int device, char * description, size_t description_size) {
5605 snprintf(description, description_size, "%s", ggml_cuda_device_description(device).c_str());
5606}
5607
5608static int ggml_cuda_physical_device_share_count(int device) {
5609 const ggml_cuda_device_info & info = ggml_cuda_info();
5610 GGML_ASSERT(device >= 0 && device < info.device_count);
5611 return info.devices[device].physical_share_count;
5612}
5613
5614void ggml_backend_cuda_get_device_memory(int device, size_t * free, size_t * total) {
5615 ggml_cuda_set_device(device);
5616
5617 CUDA_CHECK(cudaMemGetInfo(free, total));
5618
5619 // virtual devices sharing one physical GPU share its memory pool; split it between them
5620 const int share_count = ggml_cuda_physical_device_share_count(device);
5621 *free /= share_count;
5622 *total /= share_count;
5623}
5624
5625bool ggml_backend_cuda_register_host_buffer(void * buffer, size_t size) {
5626 if (!ggml_cuda_register_host_enabled()) {
5627 return false;
5628 }
5629
5630#if CUDART_VERSION >= 11010 || defined(GGML_USE_MUSA) || defined(GGML_USE_HIP)
5631 cudaError_t err = cudaHostRegister(buffer, size, cudaHostRegisterPortable | cudaHostRegisterReadOnly);
5632 if (err != cudaSuccess) {
5633 // clear the error
5634 (void)cudaGetLastError();
5635
5636 GGML_LOG_DEBUG("%s: failed to register %.2f MiB of pinned memory: %s\n", __func__,
5637 size / 1024.0 / 1024.0, cudaGetErrorString(err));
5638 return false;
5639 }
5640 return true;
5641#else
5642 GGML_UNUSED(buffer);
5643 GGML_UNUSED(size);
5644 return false;
5645#endif // CUDART_VERSION >= 11010 || defined(GGML_USE_MUSA)
5646}
5647
5648void ggml_backend_cuda_unregister_host_buffer(void * buffer) {
5649 if (!ggml_cuda_register_host_enabled()) {
5650 return;
5651 }
5652
5653 cudaError_t err = cudaHostUnregister(buffer);
5654 if (err != cudaSuccess) {
5655 // clear the error
5656 (void)cudaGetLastError();
5657 }
5658}
5659
5660
5661// backend device
5662
5663struct ggml_backend_cuda_device_context {
5664 int device;
5665 std::string name;
5666 std::string description;
5667 std::string pci_bus_id;
5668 int op_offload_min_batch_size;
5669};
5670
5671static const char * ggml_backend_cuda_device_get_name(ggml_backend_dev_t dev) {
5672 ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
5673 return ctx->name.c_str();
5674}
5675
5676static const char * ggml_backend_cuda_device_get_description(ggml_backend_dev_t dev) {
5677 ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
5678 return ctx->description.c_str();
5679}
5680
5681#if defined(__linux__)
5682// Helper function to get available memory from /proc/meminfo for UMA systems
5683static bool ggml_backend_cuda_get_available_uma_memory(long * available_memory_kb, long * free_swap_kb) {
5684 FILE * meminfo_file = nullptr;
5685 // 2KB buffer for reading /proc/meminfo since it does not report size info, should be enough
5686 const size_t BUFFER_SIZE = 2048;
5687 auto file_buffer = std::make_unique<char[]>(BUFFER_SIZE);
5688 size_t bytes_read = 0;
5689 long huge_tlb_total_pages = -1;
5690 long huge_tlb_free_pages = -1;
5691 long huge_tlb_page_size = -1;
5692
5693 if (available_memory_kb == nullptr || free_swap_kb == nullptr) {
5694 return false;
5695 }
5696
5697 meminfo_file = fopen("/proc/meminfo", "r");
5698 if (meminfo_file == nullptr) {
5699 GGML_LOG_ERROR("%s: failed to open /proc/meminfo\n", __func__);
5700 return false;
5701 }
5702
5703 // Read file into buffer
5704 bytes_read = fread(file_buffer.get(), 1, BUFFER_SIZE - 1, meminfo_file);
5705 fclose(meminfo_file);
5706
5707 if (bytes_read == 0) {
5708 GGML_LOG_ERROR("%s: failed to read from /proc/meminfo\n", __func__);
5709 return false;
5710 }
5711 file_buffer[bytes_read] = '\0';
5712
5713 *available_memory_kb = -1;
5714 *free_swap_kb = -1;
5715
5716 // Parse the file buffer line by line
5717 char * line = file_buffer.get();
5718 char * line_next;
5719 while (line < file_buffer.get() + bytes_read) {
5720 // Find the end of the current line
5721 line_next = strchr(line, '\n');
5722 if (line_next != nullptr) {
5723 *line_next = '\0';
5724 line_next++;
5725 } else {
5726 line_next = file_buffer.get() + bytes_read;
5727 }
5728
5729 long value;
5730 if (sscanf(line, "MemAvailable: %ld kB", &value) == 1) {
5731 *available_memory_kb = value;
5732 } else if (sscanf(line, "SwapFree: %ld kB", &value) == 1) {
5733 *free_swap_kb = value;
5734 } else if (sscanf(line, "HugePages_Total: %ld", &value) == 1) {
5735 huge_tlb_total_pages = value;
5736 } else if (sscanf(line, "HugePages_Free: %ld", &value) == 1) {
5737 huge_tlb_free_pages = value;
5738 } else if (sscanf(line, "Hugepagesize: %ld kB", &value) == 1) {
5739 huge_tlb_page_size = value;
5740 }
5741
5742 line = line_next;
5743 }
5744
5745 if (huge_tlb_total_pages != 0 && huge_tlb_total_pages != -1) {
5746 *available_memory_kb = huge_tlb_free_pages * huge_tlb_page_size;
5747
5748 // Hugetlbfs pages are not swappable.
5749 *free_swap_kb = 0;
5750 }
5751
5752 GGML_LOG_DEBUG("%s: final available_memory_kb: %ld\n", __func__, *available_memory_kb);
5753 return true;
5754}
5755#endif // defined(__linux__)
5756
5757static void ggml_backend_cuda_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) {
5758 ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
5759 ggml_cuda_set_device(ctx->device);
5760 cudaError_t err = cudaMemGetInfo(free, total);
5761 if (err != cudaSuccess) {
5762 (void)cudaGetLastError();
5763 GGML_LOG_WARN("%s: cudaMemGetInfo failed (%s), returning 0/0\n", __func__, cudaGetErrorString(err));
5764 *free = 0;
5765 *total = 0;
5766 return;
5767 }
5768
5769// ref: https://github.com/ggml-org/llama.cpp/pull/17368
5770#if defined(__linux__) && !defined(GGML_USE_HIP)
5771 // Check if this is a UMA (Unified Memory Architecture) system
5772 cudaDeviceProp prop;
5773 CUDA_CHECK(cudaGetDeviceProperties(&prop, ggml_cuda_get_physical_device(ctx->device)));
5774
5775 // Check if UMA is explicitly enabled via environment variable
5776 bool is_uma = prop.integrated > 0 || ggml_cuda_unified_memory_enabled();
5777
5778 if (is_uma) {
5779 // For UMA systems (like DGX Spark), use system memory info
5780 long available_memory_kb = 0;
5781 long free_swap_kb = 0;
5782
5783 if (ggml_backend_cuda_get_available_uma_memory(&available_memory_kb, &free_swap_kb) && available_memory_kb > 0) {
5784 *free = (size_t)available_memory_kb * 1024;
5785 } else {
5786 GGML_LOG_ERROR("%s: /proc/meminfo reading failed, using cudaMemGetInfo\n", __func__);
5787 }
5788 }
5789#endif // defined(__linux__) && !defined(GGML_USE_HIP)
5790
5791 // virtual devices sharing one physical GPU share its memory pool; split it between them
5792 const int share_count = ggml_cuda_physical_device_share_count(ctx->device);
5793 *free /= share_count;
5794 *total /= share_count;
5795}
5796
5797static enum ggml_backend_dev_type ggml_backend_cuda_device_get_type(ggml_backend_dev_t dev) {
5798 ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *) dev->context;
5799
5800 cudaDeviceProp prop;
5801 CUDA_CHECK(cudaGetDeviceProperties(&prop, ggml_cuda_get_physical_device(ctx->device)));
5802
5803 return prop.integrated
5804 ? GGML_BACKEND_DEVICE_TYPE_IGPU
5805 : GGML_BACKEND_DEVICE_TYPE_GPU;
5806}
5807
5808static void ggml_backend_cuda_device_get_props(ggml_backend_dev_t dev, ggml_backend_dev_props * props) {
5809 ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
5810
5811 props->name = ggml_backend_cuda_device_get_name(dev);
5812 props->description = ggml_backend_cuda_device_get_description(dev);
5813 props->type = ggml_backend_cuda_device_get_type(dev);
5814 props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
5815 ggml_backend_cuda_device_get_memory(dev, &props->memory_free, &props->memory_total);
5816
5817 const bool host_buffer = !ggml_cuda_pinned_memory_disabled();
5818#ifdef GGML_CUDA_NO_PEER_COPY
5819 bool events = false;
5820#else
5821 bool events = true;
5822#endif
5823
5824 props->caps = {
5825 /* .async = */ true,
5826 /* .host_buffer = */ host_buffer,
5827 /* .buffer_from_host_ptr = */ false,
5828 /* .events = */ events,
5829 /* .mmap_support = */ props->type != GGML_BACKEND_DEVICE_TYPE_IGPU,
5830 };
5831}
5832
5833static ggml_backend_t ggml_backend_cuda_device_init_backend(ggml_backend_dev_t dev, const char * params) {
5834 GGML_UNUSED(params);
5835 ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
5836 return ggml_backend_cuda_init(ctx->device);
5837}
5838
5839static ggml_backend_buffer_type_t ggml_backend_cuda_device_get_buffer_type(ggml_backend_dev_t dev) {
5840 ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
5841 return ggml_backend_cuda_buffer_type(ctx->device);
5842}
5843
5844static ggml_backend_buffer_type_t ggml_backend_cuda_device_get_host_buffer_type(ggml_backend_dev_t dev) {
5845 GGML_UNUSED(dev);
5846 return ggml_backend_cuda_host_buffer_type();
5847}
5848
5849// TODO: move these functions here
5850static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
5851 ggml_backend_cuda_device_context * dev_ctx = (ggml_backend_cuda_device_context *) dev->context;
5852
5853 // check if all the sources are allocated on this device
5854 for (int i = 0; i < GGML_MAX_SRC; i++) {
5855 if (op->src[i] && op->src[i]->buffer && ggml_backend_buft_is_cuda(op->src[i]->buffer->buft)) {
5856 ggml_backend_cuda_buffer_type_context * buft_ctx = (ggml_backend_cuda_buffer_type_context *)op->src[i]->buffer->buft->context;
5857 if (buft_ctx->device != dev_ctx->device) {
5858 return false;
5859 }
5860 }
5861 }
5862
5863 switch (op->op) {
5864 case GGML_OP_UNARY:
5865 switch (ggml_get_unary_op(op)) {
5866 case GGML_UNARY_OP_ABS:
5867 case GGML_UNARY_OP_SGN:
5868 case GGML_UNARY_OP_NEG:
5869 case GGML_UNARY_OP_STEP:
5870 case GGML_UNARY_OP_GELU:
5871 case GGML_UNARY_OP_SILU:
5872 case GGML_UNARY_OP_RELU:
5873 case GGML_UNARY_OP_SIGMOID:
5874 case GGML_UNARY_OP_HARDSIGMOID:
5875 case GGML_UNARY_OP_HARDSWISH:
5876 case GGML_UNARY_OP_GELU_ERF:
5877 case GGML_UNARY_OP_GELU_QUICK:
5878 case GGML_UNARY_OP_TANH:
5879 case GGML_UNARY_OP_EXP:
5880 case GGML_UNARY_OP_EXPM1:
5881 case GGML_UNARY_OP_SOFTPLUS:
5882 case GGML_UNARY_OP_ELU:
5883 case GGML_UNARY_OP_XIELU:
5884 case GGML_UNARY_OP_FLOOR:
5885 case GGML_UNARY_OP_CEIL:
5886 case GGML_UNARY_OP_ROUND:
5887 case GGML_UNARY_OP_TRUNC:
5888 if (op->src[0]->type == GGML_TYPE_BF16 && ggml_get_unary_op(op) == GGML_UNARY_OP_XIELU) {
5889 return false;
5890 }
5891 return op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_BF16;
5892 default:
5893 return false;
5894 }
5895 case GGML_OP_GLU:
5896 switch (ggml_get_glu_op(op)) {
5897 case GGML_GLU_OP_REGLU:
5898 case GGML_GLU_OP_GEGLU:
5899 case GGML_GLU_OP_SWIGLU:
5900 case GGML_GLU_OP_SWIGLU_OAI:
5901 case GGML_GLU_OP_GEGLU_ERF:
5902 case GGML_GLU_OP_GEGLU_QUICK:
5903 case GGML_GLU_OP_SWIGLU_CLAMP:
5904 if (op->src[0]->type == GGML_TYPE_BF16 &&
5905 (ggml_get_glu_op(op) == GGML_GLU_OP_SWIGLU_OAI || ggml_get_glu_op(op) == GGML_GLU_OP_SWIGLU_CLAMP)) {
5906 return false;
5907 }
5908 if (op->src[0]->type == GGML_TYPE_F16 && ggml_get_glu_op(op) == GGML_GLU_OP_SWIGLU_OAI) {
5909 return false;
5910 }
5911 return ggml_is_contiguous_1(op->src[0]);
5912 default:
5913 return false;
5914 }
5915 case GGML_OP_MUL_MAT:
5916 case GGML_OP_MUL_MAT_ID:
5917 {
5918 struct ggml_tensor * a = op->src[0];
5919 struct ggml_tensor * b = op->src[1];
5920 if (a->nb[0] != ggml_element_size(a) || b->nb[0] != ggml_element_size(b)) {
5921 return false; // TODO this could in principle be implemented though currently there is no use case.
5922 }
5923 if (b->type == GGML_TYPE_F16 && a->type != GGML_TYPE_F16 && !ggml_cuda_op_mul_mat_use_fwht(op)) {
5924 return false;
5925 }
5926 if (op->op == GGML_OP_MUL_MAT_ID && ggml_get_op_params_i32(op, 3) == GGML_PREC_F32) {
5927 return false;
5928 }
5929#ifdef GGML_USE_MUSA
5930 const int cc = ggml_cuda_info().devices[dev_ctx->device].cc;
5931 if (b->ne[2]*b->ne[3] > 1 && !ggml_is_transposed(a) && !ggml_is_transposed(b)) {
5932 if (GGML_CUDA_CC_IS_QY1(cc) && op->op == GGML_OP_MUL_MAT &&
5933 a->type == GGML_TYPE_F16 && b->type == GGML_TYPE_F16) {
5934 return false;
5935 }
5936 if (GGML_CUDA_CC_IS_QY2(cc) && op->op == GGML_OP_MUL_MAT_ID &&
5937 a->type == GGML_TYPE_Q2_K && b->type == GGML_TYPE_F32) {
5938 return false;
5939 }
5940 }
5941#endif // GGML_USE_MUSA
5942 switch (a->type) {
5943 case GGML_TYPE_F32:
5944 case GGML_TYPE_F16:
5945 case GGML_TYPE_Q1_0:
5946 case GGML_TYPE_Q2_0:
5947 case GGML_TYPE_Q4_0:
5948 case GGML_TYPE_Q4_1:
5949 case GGML_TYPE_Q5_0:
5950 case GGML_TYPE_Q5_1:
5951 case GGML_TYPE_Q8_0:
5952 case GGML_TYPE_MXFP4:
5953 case GGML_TYPE_NVFP4:
5954 case GGML_TYPE_Q2_K:
5955 case GGML_TYPE_Q3_K:
5956 case GGML_TYPE_Q4_K:
5957 case GGML_TYPE_Q5_K:
5958 case GGML_TYPE_Q6_K:
5959 case GGML_TYPE_Q8_K:
5960 case GGML_TYPE_IQ1_M:
5961 case GGML_TYPE_IQ1_S:
5962 case GGML_TYPE_IQ2_S:
5963 case GGML_TYPE_IQ2_XS:
5964 case GGML_TYPE_IQ2_XXS:
5965 case GGML_TYPE_IQ3_S:
5966 case GGML_TYPE_IQ3_XXS:
5967 case GGML_TYPE_IQ4_NL:
5968 case GGML_TYPE_IQ4_XS:
5969 case GGML_TYPE_BF16:
5970 return true;
5971 default:
5972 return false;
5973 }
5974 }
5975 case GGML_OP_OUT_PROD:
5976 return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
5977 case GGML_OP_GET_ROWS:
5978 {
5979 switch (op->src[0]->type) {
5980 case GGML_TYPE_F16:
5981 case GGML_TYPE_F32:
5982 case GGML_TYPE_BF16:
5983 case GGML_TYPE_I32:
5984 case GGML_TYPE_Q1_0:
5985 case GGML_TYPE_Q2_0:
5986 case GGML_TYPE_Q4_0:
5987 case GGML_TYPE_Q4_1:
5988 case GGML_TYPE_Q5_0:
5989 case GGML_TYPE_Q5_1:
5990 case GGML_TYPE_Q8_0:
5991 case GGML_TYPE_Q2_K:
5992 case GGML_TYPE_Q3_K:
5993 case GGML_TYPE_Q4_K:
5994 case GGML_TYPE_Q5_K:
5995 case GGML_TYPE_Q6_K:
5996 case GGML_TYPE_IQ2_XXS:
5997 case GGML_TYPE_IQ2_XS:
5998 case GGML_TYPE_IQ2_S:
5999 case GGML_TYPE_IQ3_XXS:
6000 case GGML_TYPE_IQ3_S:
6001 case GGML_TYPE_IQ1_S:
6002 case GGML_TYPE_IQ1_M:
6003 case GGML_TYPE_IQ4_XS:
6004 return true;
6005 case GGML_TYPE_IQ4_NL:
6006 case GGML_TYPE_MXFP4:
6007 // 32-value sub-blocks, the row size does not guarantee
6008 // the QK_K super-blocks the get_rows kernel iterates on
6009 return op->src[0]->ne[0] % QK_K == 0;
6010 default:
6011 return false;
6012 }
6013 }
6014 case GGML_OP_GET_ROWS_BACK:
6015 return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32 && op->ne[2] == 1 && op->ne[3] == 1;
6016 case GGML_OP_SET_ROWS:
6017 {
6018 return (
6019 (
6020 (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_BF16 ||
6021 op->type == GGML_TYPE_Q4_0 || op->type == GGML_TYPE_Q4_1 || op->type == GGML_TYPE_Q5_0 ||
6022 op->type == GGML_TYPE_Q5_1 || op->type == GGML_TYPE_Q8_0 || op->type == GGML_TYPE_IQ4_NL) &&
6023 op->src[0]->type == GGML_TYPE_F32
6024 ) || (
6025 op->type == GGML_TYPE_F16 && op->src[0]->type == GGML_TYPE_F16
6026 )
6027 ) &&
6028 (op->src[1]->type == GGML_TYPE_I64 || op->src[1]->type == GGML_TYPE_I32);
6029 }
6030 case GGML_OP_SET:
6031 {
6032 const ggml_type t = op->type;
6033 return (t == GGML_TYPE_F32 || t == GGML_TYPE_I32) &&
6034 t == op->src[0]->type &&
6035 t == op->src[1]->type;
6036 }
6037 case GGML_OP_CPY:
6038 {
6039 ggml_type src0_type = op->src[0]->type;
6040 ggml_type src1_type = op->src[1]->type;
6041 if ((src0_type == GGML_TYPE_F32 || src0_type == GGML_TYPE_BF16 || src0_type == GGML_TYPE_F16) &&
6042 (src1_type == GGML_TYPE_F32 || src1_type == GGML_TYPE_BF16 || src1_type == GGML_TYPE_F16)
6043 ) {
6044 return true;
6045 }
6046 if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q8_0) {
6047 return true;
6048 }
6049 if (src0_type == GGML_TYPE_Q8_0 && src1_type == GGML_TYPE_F32) {
6050 return true;
6051 }
6052 if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q4_0) {
6053 return true;
6054 }
6055 if (src0_type == GGML_TYPE_Q4_0 && src1_type == GGML_TYPE_F32) {
6056 return true;
6057 }
6058 if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q4_1) {
6059 return true;
6060 }
6061 if (src0_type == GGML_TYPE_Q4_1 && src1_type == GGML_TYPE_F32) {
6062 return true;
6063 }
6064 if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q5_0) {
6065 return true;
6066 }
6067 if (src0_type == GGML_TYPE_Q5_0 && src1_type == GGML_TYPE_F32) {
6068 return true;
6069 }
6070 if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q5_1) {
6071 return true;
6072 }
6073 if (src0_type == GGML_TYPE_Q5_1 && src1_type == GGML_TYPE_F32) {
6074 return true;
6075 }
6076 if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_IQ4_NL) {
6077 return true;
6078 }
6079 if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) {
6080 return true;
6081 }
6082 if (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32) {
6083 return true;
6084 }
6085 if (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_I32) {
6086 return true;
6087 }
6088 if (src0_type == src1_type && ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1])) {
6089 return true;
6090 }
6091 return false;
6092 }
6093 case GGML_OP_DUP:
6094 return true;
6095 case GGML_OP_ARGMAX:
6096 case GGML_OP_COUNT_EQUAL:
6097 return true;
6098 case GGML_OP_REPEAT:
6099 {
6100 // the CUDA REPEAT path only implements F32/F16; other types assert at runtime
6101 ggml_type src0_type = op->src[0]->type;
6102 return src0_type == GGML_TYPE_F32 || src0_type == GGML_TYPE_F16;
6103 }
6104 case GGML_OP_REPEAT_BACK:
6105 return op->type == GGML_TYPE_F32 && (op->src[0]->ne[2]*op->src[0]->ne[3]) <= (1 << 15);
6106 case GGML_OP_CONCAT:
6107 {
6108 ggml_type src0_type = op->src[0]->type;
6109 ggml_type src1_type = op->src[1]->type;
6110 const int32_t dim = op->op_params[0];
6111 return src0_type == src1_type &&
6112 src0_type == op->type &&
6113 (
6114 (
6115 ggml_is_quantized(src0_type) &&
6116 (
6117 (
6118 dim == 3 &&
6119 ggml_is_contiguous(op->src[0]) &&
6120 ggml_is_contiguous(op->src[1])
6121 ) || (
6122 dim != 3 &&
6123 ggml_is_contiguous_to_3(op->src[0]) &&
6124 ggml_is_contiguous_to_3(op->src[1])
6125 )
6126 ) &&
6127 op->src[0]->ne[0] % ggml_blck_size(src0_type) == 0 &&
6128 op->src[1]->ne[0] % ggml_blck_size(src0_type) == 0
6129 ) || (
6130 !ggml_is_quantized(src0_type) &&
6131 ggml_blck_size(src0_type) == 1 &&
6132 (
6133 ggml_type_size(src0_type) == 1 ||
6134 ggml_type_size(src0_type) == 2 ||
6135 ggml_type_size(src0_type) == 4 ||
6136 ggml_type_size(src0_type) == 8
6137 )
6138 )
6139 );
6140 }
6141 case GGML_OP_CONV_TRANSPOSE_1D:
6142 {
6143 ggml_type src0_type = op->src[0]->type;
6144 ggml_type src1_type = op->src[1]->type;
6145 if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
6146 return true;
6147 }
6148 return false;
6149 }
6150 case GGML_OP_COL2IM_1D:
6151 {
6152 ggml_type src0_type = op->src[0]->type;
6153 return (src0_type == GGML_TYPE_F32 || src0_type == GGML_TYPE_F16 || src0_type == GGML_TYPE_BF16) &&
6154 op->type == src0_type &&
6155 ggml_is_contiguous(op->src[0]) &&
6156 ggml_is_contiguous(op);
6157 }
6158 case GGML_OP_SILU_BACK:
6159 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
6160 case GGML_OP_NORM:
6161 case GGML_OP_RMS_NORM:
6162 case GGML_OP_L2_NORM:
6163 return ggml_is_contiguous_rows(op->src[0]);
6164 case GGML_OP_RMS_NORM_BACK:
6165 return ggml_is_contiguous(op->src[0]);
6166 case GGML_OP_NONE:
6167 case GGML_OP_RESHAPE:
6168 case GGML_OP_VIEW:
6169 case GGML_OP_PERMUTE:
6170 case GGML_OP_TRANSPOSE:
6171 case GGML_OP_ADD_ID:
6172 case GGML_OP_ADD1:
6173 case GGML_OP_SQR:
6174 case GGML_OP_SQRT:
6175 case GGML_OP_SIN:
6176 case GGML_OP_COS:
6177 case GGML_OP_LOG:
6178 return true;
6179 case GGML_OP_SCALE:
6180 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_BF16) && op->type == op->src[0]->type &&
6181 ggml_is_contiguous_rows(op->src[0]);
6182 case GGML_OP_CLAMP:
6183 return ggml_is_contiguous_rows(op->src[0]);
6184 case GGML_OP_ADD:
6185 case GGML_OP_SUB:
6186 case GGML_OP_MUL:
6187 case GGML_OP_DIV:
6188 if (op->src[0]->type == GGML_TYPE_BF16 || op->src[1]->type == GGML_TYPE_BF16 || op->type == GGML_TYPE_BF16) {
6189 return op->src[0]->type == GGML_TYPE_BF16 && op->type == GGML_TYPE_BF16 &&
6190 (op->src[1]->type == GGML_TYPE_BF16 || op->src[1]->type == GGML_TYPE_F32);
6191 }
6192 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
6193 (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
6194 (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
6195 case GGML_OP_SSM_SCAN: {
6196 const int32_t K = ggml_get_op_params_i32(op, 0);
6197
6198 if (op->src[3]->ne[0] == 1) {
6199 // Mamba2
6200 // (kernel only supports (d_state == 96 || d_state == 128 || d_state == 256) && d_head % 16 == 0)
6201 const int64_t d_state = op->src[0]->ne[0];
6202 return (d_state == 96 || d_state == 128 || d_state == 256) && op->src[0]->ne[1] % 16 == 0;
6203 } else {
6204 if (K > 1) {
6205 return false;
6206 }
6207
6208 // Mamba
6209 // (kernel only supports d_state == 16, d_head == 1, n_head % 128 == 0, n_group == 1)
6210 return op->src[0]->ne[0] == 16 && op->src[0]->ne[1] == 1 && op->src[0]->ne[2] % 128 == 0 && op->src[4]->ne[1] == 1;
6211 }
6212 }
6213 case GGML_OP_SSM_CONV: {
6214 // assumes d_inner % threads == 0
6215 return op->src[0]->ne[1] % 128 == 0;
6216 }
6217 case GGML_OP_CONT:
6218 return true;
6219 case GGML_OP_DIAG_MASK_INF:
6220 return true;
6221 case GGML_OP_SOFT_MAX:
6222 return true;
6223 case GGML_OP_SOFT_MAX_BACK: {
6224 float max_bias = 0.0f;
6225 memcpy(&max_bias, (const float *) op->op_params + 1, sizeof(float));
6226 return max_bias == 0.0f;
6227 }
6228 case GGML_OP_ROLL:
6229 if(op->src[0]->type == GGML_TYPE_F32) {
6230 return true;
6231 }
6232 return false;
6233 case GGML_OP_ROPE:
6234 case GGML_OP_ROPE_BACK: {
6235 return op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && ggml_is_contiguous_2(op->src[0]);
6236 }
6237 case GGML_OP_IM2COL:
6238 case GGML_OP_IM2COL_3D:
6239 case GGML_OP_CONV_2D:
6240 return (ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]));
6241 case GGML_OP_CONV_3D:
6242 return (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32) &&
6243 op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 &&
6244 ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]) && ggml_is_contiguous(op);
6245 case GGML_OP_CONV_2D_DW:
6246 return (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32) &&
6247 op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32;
6248 case GGML_OP_CONV_TRANSPOSE_2D:
6249 case GGML_OP_POOL_1D:
6250 case GGML_OP_POOL_2D:
6251 return true;
6252 case GGML_OP_ACC:
6253 // TODO: extend support like so:
6254 //return ggml_is_contiguous_rows(op->src[0]) && ggml_is_contiguous_rows(op->src[1]);
6255 return ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]);
6256 case GGML_OP_SUM:
6257 return ggml_is_contiguously_allocated(op->src[0]);
6258 case GGML_OP_TOP_K:
6259 return op->src[0]->ne[0] <= INT_MAX;
6260 case GGML_OP_ARGSORT:
6261#ifndef GGML_CUDA_USE_CUB
6262 {
6263 // bitonic path: the padded row must fit in shared memory
6264 int64_t ncols_pad = 1;
6265 while (ncols_pad < op->src[0]->ne[0]) {
6266 ncols_pad *= 2;
6267 }
6268 return ncols_pad * sizeof(int) <= ggml_cuda_info().devices[dev_ctx->device].smpb;
6269 }
6270#else
6271 return op->src[0]->ne[0] <= INT_MAX;
6272#endif
6273 case GGML_OP_SUM_ROWS:
6274 return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
6275 case GGML_OP_MEAN:
6276 return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
6277 case GGML_OP_GROUP_NORM:
6278 return ggml_is_contiguous(op->src[0]);
6279 case GGML_OP_PAD:
6280 return true;
6281 case GGML_OP_UPSCALE:
6282 case GGML_OP_PAD_REFLECT_1D:
6283 case GGML_OP_ARANGE:
6284 case GGML_OP_TIMESTEP_EMBEDDING:
6285 case GGML_OP_LEAKY_RELU:
6286 case GGML_OP_RWKV_WKV6:
6287 case GGML_OP_GATED_LINEAR_ATTN:
6288 case GGML_OP_RWKV_WKV7:
6289 return true;
6290 case GGML_OP_GATED_DELTA_NET:
6291 return true;
6292 case GGML_OP_DSV4_HC_COMB:
6293 return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 &&
6294 op->src[2]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32;
6295 case GGML_OP_DSV4_HC_PRE:
6296 return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 &&
6297 op->type == GGML_TYPE_F32;
6298 case GGML_OP_DSV4_HC_POST:
6299 return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 &&
6300 op->src[2]->type == GGML_TYPE_F32 && (op->src[3] == nullptr || op->src[3]->type == GGML_TYPE_F32) &&
6301 op->type == GGML_TYPE_F32;
6302 case GGML_OP_FLASH_ATTN_EXT:
6303 return ggml_cuda_flash_attn_ext_supported(dev_ctx->device, op);
6304 case GGML_OP_CROSS_ENTROPY_LOSS:
6305 case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
6306 case GGML_OP_OPT_STEP_ADAMW:
6307 case GGML_OP_OPT_STEP_SGD:
6308 case GGML_OP_FILL:
6309 case GGML_OP_CUMSUM:
6310 case GGML_OP_TRI:
6311 case GGML_OP_DIAG:
6312 case GGML_OP_SOLVE_TRI:
6313 return true;
6314 case GGML_OP_LIGHTNING_INDEXER:
6315 return ggml_cuda_lightning_indexer_supported(dev_ctx->device, op);
6316 case GGML_OP_TOP_K_MASK:
6317 return op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32;
6318
6319 default:
6320 return false;
6321 }
6322}
6323
6324static bool ggml_backend_cuda_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
6325 ggml_backend_cuda_device_context * dev_ctx = (ggml_backend_cuda_device_context *) dev->context;
6326 const bool integrated = ggml_cuda_info().devices[dev_ctx->device].integrated;
6327 return (ggml_backend_buft_is_cuda(buft) && buft->device == dev) || (integrated && ggml_backend_buft_is_cuda_host(buft));
6328}
6329
6330static int64_t get_op_batch_size(const ggml_tensor * op) {
6331 switch (op->op) {
6332 case GGML_OP_GET_ROWS:
6333 return 0;
6334 case GGML_OP_MUL_MAT:
6335 return op->ne[1];
6336 case GGML_OP_MUL_MAT_ID:
6337 case GGML_OP_ROPE:
6338 case GGML_OP_ROPE_BACK:
6339 return op->ne[2];
6340 default:
6341 return ggml_nrows(op);
6342 }
6343}
6344
6345static bool ggml_backend_cuda_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
6346 ggml_backend_cuda_device_context * dev_ctx = (ggml_backend_cuda_device_context *) dev->context;
6347
6348 return get_op_batch_size(op) >= dev_ctx->op_offload_min_batch_size;
6349}
6350
6351static ggml_backend_event_t ggml_backend_cuda_device_event_new(ggml_backend_dev_t dev) {
6352#ifdef GGML_CUDA_NO_PEER_COPY
6353 GGML_UNUSED(dev);
6354 return nullptr;
6355#else
6356 ggml_backend_cuda_device_context * dev_ctx = (ggml_backend_cuda_device_context *)dev->context;
6357
6358 ggml_cuda_set_device(dev_ctx->device);
6359
6360 cudaEvent_t event;
6361 CUDA_CHECK(cudaEventCreateWithFlags(&event, cudaEventDisableTiming));
6362
6363 return new ggml_backend_event {
6364 /* .device = */ dev,
6365 /* .context = */ event,
6366 };
6367#endif
6368}
6369
6370static void ggml_backend_cuda_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
6371 GGML_UNUSED(dev);
6372
6373 CUDA_CHECK(cudaEventDestroy((cudaEvent_t)event->context));
6374 delete event;
6375}
6376
6377static void ggml_backend_cuda_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
6378 GGML_UNUSED(dev);
6379 CUDA_CHECK(cudaEventSynchronize((cudaEvent_t)event->context));
6380}
6381
6382static const ggml_backend_device_i ggml_backend_cuda_device_interface = {
6383 /* .get_name = */ ggml_backend_cuda_device_get_name,
6384 /* .get_description = */ ggml_backend_cuda_device_get_description,
6385 /* .get_memory = */ ggml_backend_cuda_device_get_memory,
6386 /* .get_type = */ ggml_backend_cuda_device_get_type,
6387 /* .get_props = */ ggml_backend_cuda_device_get_props,
6388 /* .init_backend = */ ggml_backend_cuda_device_init_backend,
6389 /* .get_buffer_type = */ ggml_backend_cuda_device_get_buffer_type,
6390 /* .get_host_buffer_type = */ ggml_backend_cuda_device_get_host_buffer_type,
6391 /* .buffer_from_host_ptr = */ NULL,
6392 /* .supports_op = */ ggml_backend_cuda_device_supports_op,
6393 /* .supports_buft = */ ggml_backend_cuda_device_supports_buft,
6394 /* .offload_op = */ ggml_backend_cuda_device_offload_op,
6395 /* .event_new = */ ggml_backend_cuda_device_event_new,
6396 /* .event_free = */ ggml_backend_cuda_device_event_free,
6397 /* .event_synchronize = */ ggml_backend_cuda_device_event_synchronize,
6398};
6399
6400// backend reg
6401
6402struct ggml_backend_cuda_reg_context {
6403 std::vector<ggml_backend_dev_t> devices;
6404};
6405
6406static const char * ggml_backend_cuda_reg_get_name(ggml_backend_reg_t reg) {
6407 GGML_UNUSED(reg);
6408 return GGML_CUDA_NAME;
6409}
6410
6411static size_t ggml_backend_cuda_reg_get_device_count(ggml_backend_reg_t reg) {
6412 ggml_backend_cuda_reg_context * ctx = (ggml_backend_cuda_reg_context *)reg->context;
6413 return ctx->devices.size();
6414}
6415
6416static ggml_backend_dev_t ggml_backend_cuda_reg_get_device(ggml_backend_reg_t reg, size_t index) {
6417 ggml_backend_cuda_reg_context * ctx = (ggml_backend_cuda_reg_context *)reg->context;
6418 GGML_ASSERT(index < ctx->devices.size());
6419 return ctx->devices[index];
6420}
6421
6422static ggml_backend_feature * ggml_backend_cuda_get_features(ggml_backend_reg_t reg) {
6423 static std::vector<ggml_backend_feature> features = []() {
6424 std::vector<ggml_backend_feature> features;
6425 #define _STRINGIFY(...) #__VA_ARGS__
6426 #define STRINGIFY(...) _STRINGIFY(__VA_ARGS__)
6427
6428 #ifdef __CUDA_ARCH_LIST__
6429 features.push_back({ "ARCHS", STRINGIFY(__CUDA_ARCH_LIST__) });
6430 #endif
6431
6432 #ifdef GGML_CUDA_FORCE_MMQ
6433 features.push_back({ "FORCE_MMQ", "1" });
6434 #endif
6435
6436 #ifdef GGML_CUDA_FORCE_CUBLAS
6437 features.push_back({ "FORCE_CUBLAS", "1" });
6438 #endif
6439
6440 #ifndef GGML_USE_VMM
6441 features.push_back({ "NO_VMM", "1" });
6442 #endif
6443
6444 #ifdef GGML_CUDA_NO_PEER_COPY
6445 features.push_back({ "NO_PEER_COPY", "1" });
6446 #endif
6447
6448 #ifdef GGML_CUDA_USE_GRAPHS
6449 features.push_back({ "USE_GRAPHS", "1" });
6450 #endif
6451
6452 #ifdef GGML_CUDA_FA_QUANTS
6453 features.push_back({ "FA_QUANTS", GGML_CUDA_FA_QUANTS });
6454 #endif
6455
6456 {
6457 const auto & info = ggml_cuda_info();
6458 for (int id = 0; id < info.device_count; ++id) {
6459 if (blackwell_mma_available(info.devices[id].cc)) {
6460 features.push_back({ "BLACKWELL_NATIVE_FP4", "1"});
6461 break;
6462 }
6463 }
6464 }
6465
6466 #undef _STRINGIFY
6467 #undef STRINGIFY
6468
6469 features.push_back({ nullptr, nullptr });
6470
6471 return features;
6472 }();
6473
6474 return features.data();
6475
6476 GGML_UNUSED(reg);
6477}
6478
6479static void * ggml_backend_cuda_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) {
6480 GGML_UNUSED(reg);
6481 if (strcmp(name, "ggml_backend_comm_init") == 0) {
6482 return (void *)ggml_backend_cuda_comm_init;
6483 }
6484 if (strcmp(name, "ggml_backend_comm_free") == 0) {
6485 return (void *)ggml_backend_cuda_comm_free;
6486 }
6487 if (strcmp(name, "ggml_backend_comm_allreduce_tensor") == 0) {
6488 return (void *)ggml_backend_cuda_comm_allreduce_tensor;
6489 }
6490#ifdef GGML_USE_NCCL
6491 if (strcmp(name, "ggml_backend_comm_init_rank") == 0) {
6492 return (void *)ggml_backend_cuda_comm_init_rank;
6493 }
6494#endif // GGML_USE_NCCL
6495 if (strcmp(name, "ggml_backend_register_host_buffer") == 0) {
6496 return (void *)ggml_backend_cuda_register_host_buffer;
6497 }
6498 if (strcmp(name, "ggml_backend_unregister_host_buffer") == 0) {
6499 return (void *)ggml_backend_cuda_unregister_host_buffer;
6500 }
6501 if (strcmp(name, "ggml_backend_get_features") == 0) {
6502 return (void *)ggml_backend_cuda_get_features;
6503 }
6504 return nullptr;
6505}
6506
6507static const ggml_backend_reg_i ggml_backend_cuda_reg_interface = {
6508 /* .get_name = */ ggml_backend_cuda_reg_get_name,
6509 /* .get_device_count = */ ggml_backend_cuda_reg_get_device_count,
6510 /* .get_device = */ ggml_backend_cuda_reg_get_device,
6511 /* .get_proc_address = */ ggml_backend_cuda_reg_get_proc_address,
6512};
6513
6514// backend registry
6515ggml_backend_reg_t ggml_backend_cuda_reg() {
6516 static ggml_backend_reg reg;
6517 static bool initialized = false;
6518
6519 {
6520 static std::mutex mutex;
6521 std::lock_guard<std::mutex> lock(mutex);
6522 if (!initialized) {
6523 ggml_backend_cuda_reg_context * ctx = new ggml_backend_cuda_reg_context;
6524 const int min_batch_size = ggml_cuda_op_offload_min_batch();
6525
6526 const ggml_cuda_device_info & info = ggml_cuda_info();
6527 const bool virtual_devices = info.device_count > info.physical_device_count;
6528
6529 for (int i = 0; i < info.device_count; i++) {
6530 const int physical_id = info.devices[i].physical_device;
6531
6532 ggml_backend_cuda_device_context * dev_ctx = new ggml_backend_cuda_device_context;
6533 dev_ctx->device = i;
6534 dev_ctx->name = GGML_CUDA_NAME + std::to_string(i);
6535 dev_ctx->description = ggml_cuda_device_description(i);
6536
6537 char pci_bus_id[32] = {};
6538 CUDA_CHECK(cudaDeviceGetPCIBusId(pci_bus_id, sizeof(pci_bus_id), physical_id));
6539 dev_ctx->pci_bus_id = pci_bus_id;
6540 if (virtual_devices) {
6541 // make the pci bus id unique for virtual devices
6542 dev_ctx->pci_bus_id += "-v" + std::to_string(i);
6543 }
6544 for (char & c : dev_ctx->pci_bus_id) {
6545 c = std::tolower(c);
6546 }
6547 dev_ctx->op_offload_min_batch_size = min_batch_size;
6548
6549 ggml_backend_dev_t dev = new ggml_backend_device {
6550 /* .iface = */ ggml_backend_cuda_device_interface,
6551 /* .reg = */ &reg,
6552 /* .context = */ dev_ctx
6553 };
6554 ctx->devices.push_back(dev);
6555 }
6556
6557 reg = ggml_backend_reg {
6558 /* .api_version = */ GGML_BACKEND_API_VERSION,
6559 /* .iface = */ ggml_backend_cuda_reg_interface,
6560 /* .context = */ ctx
6561 };
6562 }
6563
6564 initialized = true;
6565 }
6566
6567 return &reg;
6568}
6569
6570ggml_backend_t ggml_backend_cuda_init(int device) {
6571 if (device < 0 || device >= ggml_backend_cuda_get_device_count()) {
6572 GGML_LOG_ERROR("%s: invalid device %d\n", __func__, device);
6573 return nullptr;
6574 }
6575
6576 ggml_backend_cuda_context * ctx = new ggml_backend_cuda_context(device);
6577 if (ctx == nullptr) {
6578 GGML_LOG_ERROR("%s: failed to allocate context\n", __func__);
6579 return nullptr;
6580 }
6581
6582 ggml_backend_t cuda_backend = new ggml_backend {
6583 /* .guid = */ ggml_backend_cuda_guid(),
6584 /* .iface = */ ggml_backend_cuda_interface,
6585 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_cuda_reg(), device),
6586 /* .context = */ ctx,
6587 };
6588
6589 return cuda_backend;
6590}
6591
6592GGML_BACKEND_DL_IMPL(ggml_backend_cuda_reg)