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 / common.cuh

1729 lines · 66406 bytes Raw Blame History
1#pragma once
2
3#include "ggml.h"
4#include "ggml-impl.h"
5#include "ggml-cuda.h"
6
7#include <cstdint>
8#include <cstdlib>
9#include <memory>
10#include <mutex>
11
12#if defined(GGML_USE_HIP)
13#define GGML_COMMON_DECL_HIP
14#define GGML_COMMON_IMPL_HIP
15#else
16#define GGML_COMMON_DECL_CUDA
17#define GGML_COMMON_IMPL_CUDA
18#if defined(GGML_USE_MUSA)
19#define GGML_COMMON_DECL_MUSA
20#define GGML_COMMON_IMPL_MUSA
21#endif
22#endif
23#include "ggml-common.h"
24
25#include <array>
26#include <algorithm>
27#include <cassert>
28#include <cfloat>
29#include <cstdio>
30#include <string>
31#include <unordered_map>
32#include <utility>
33#include <vector>
34
35#if defined(GGML_USE_HIP)
36#include "vendors/hip.h"
37#elif defined(GGML_USE_MUSA)
38#include "vendors/musa.h"
39#else
40#include "vendors/cuda.h"
41#endif // defined(GGML_USE_HIP)
42
43#define STRINGIZE_IMPL(...) #__VA_ARGS__
44#define STRINGIZE(...) STRINGIZE_IMPL(__VA_ARGS__)
45
46#define WARP_SIZE 32
47#define CUDART_HMAX 11070 // CUDA 11.7, min. ver. for which __hmax and __hmax2 are known to work (may be higher than needed)
48#define CUDART_HMASK 12000 // CUDA 12.0, min. ver. for half2 -> uint mask comparisons
49
50#define GGML_CUDA_CC_PASCAL 600
51#define GGML_CUDA_CC_DP4A 610 // minimum compute capability for __dp4a, an intrinsic for byte-wise dot products
52#define GGML_CUDA_CC_VOLTA 700
53#define GGML_CUDA_CC_TURING 750
54#define GGML_CUDA_CC_AMPERE 800
55#define GGML_CUDA_CC_AMPERE_GA10X 860
56#define GGML_CUDA_CC_ORIN 870
57#define GGML_CUDA_CC_ADA_LOVELACE 890
58#define GGML_CUDA_CC_HOPPER 900
59// While BW spans CC 1000, 1100 & 1200, we are integrating Tensor Core instructions available to 1200 family, see
60// https://docs.nvidia.com/cutlass/media/docs/cpp/blackwell_functionality.html#blackwell-sm120-gemms
61#define GGML_CUDA_CC_BLACKWELL 1200
62#define GGML_CUDA_CC_DGX_SPARK 1210
63#define GGML_CUDA_CC_RUBIN 1300
64#define GGML_CUDA_CC_OFFSET_AMD 0x1000000
65#define GGML_CUDA_CC_OFFSET_MTHREADS 0x0100000
66#define GGML_CUDA_CC_IS_NVIDIA(cc) (cc < GGML_CUDA_CC_OFFSET_MTHREADS)
67
68// AMD
69// GCN/CDNA, wave size is 64
70#define GGML_CUDA_CC_GCN4 (GGML_CUDA_CC_OFFSET_AMD + 0x803) // Tonga, Fiji, Polaris, minimum for fast fp16
71#define GGML_CUDA_CC_VEGA (GGML_CUDA_CC_OFFSET_AMD + 0x900) // Vega56/64, minimum for fp16 dual issue
72#define GGML_CUDA_CC_VEGA20 (GGML_CUDA_CC_OFFSET_AMD + 0x906) // MI50/Radeon VII, minimum for dp4a
73#define GGML_CUDA_CC_GFX909 (GGML_CUDA_CC_OFFSET_AMD + 0x909) // GCN APU
74#define GGML_CUDA_CC_GFX90C (GGML_CUDA_CC_OFFSET_AMD + 0x90c) // GCN APU
75#define GGML_CUDA_CC_CDNA1 (GGML_CUDA_CC_OFFSET_AMD + 0x908) // MI100, minimum for MFMA, acc registers
76#define GGML_CUDA_CC_CDNA2 (GGML_CUDA_CC_OFFSET_AMD + 0x90a) // MI210 (gfx90a), minimum acc register renaming
77#define GGML_CUDA_CC_CDNA3 (GGML_CUDA_CC_OFFSET_AMD + 0x942) // MI300
78#define GGML_CUDA_CC_CDNA4 (GGML_CUDA_CC_OFFSET_AMD + 0x950) // MI350X/MI355X
79
80// RDNA removes MFMA, dp4a, xnack, acc registers, wave size is 32
81#define GGML_CUDA_CC_RDNA1 (GGML_CUDA_CC_OFFSET_AMD + 0x1010) // RX 5000
82#define GGML_CUDA_CC_RDNA2 (GGML_CUDA_CC_OFFSET_AMD + 0x1030) // RX 6000, minimum for dp4a
83#define GGML_CUDA_CC_RDNA3 (GGML_CUDA_CC_OFFSET_AMD + 0x1100) // RX 7000, minimum for WMMA
84#define GGML_CUDA_CC_RDNA3_5 (GGML_CUDA_CC_OFFSET_AMD + 0x1150) // AI 370, AI Max 395 laptops.
85#define GGML_CUDA_CC_RDNA4_M (GGML_CUDA_CC_OFFSET_AMD + 0x1170) // gfx117X
86#define GGML_CUDA_CC_RDNA4 (GGML_CUDA_CC_OFFSET_AMD + 0x1200) // RX 9000
87
88#define GGML_CUDA_CC_IS_AMD(cc) (cc >= GGML_CUDA_CC_OFFSET_AMD)
89#define GGML_CUDA_CC_IS_RDNA(cc) (cc >= GGML_CUDA_CC_RDNA1)
90#define GGML_CUDA_CC_IS_RDNA1(cc) (cc >= GGML_CUDA_CC_RDNA1 && cc < GGML_CUDA_CC_RDNA2)
91#define GGML_CUDA_CC_IS_RDNA2(cc) (cc >= GGML_CUDA_CC_RDNA2 && cc < GGML_CUDA_CC_RDNA3)
92#define GGML_CUDA_CC_IS_RDNA3_0(cc) (cc >= GGML_CUDA_CC_RDNA3 && cc < GGML_CUDA_CC_RDNA3_5)
93#define GGML_CUDA_CC_IS_RDNA3_5(cc) (cc >= GGML_CUDA_CC_RDNA3_5 && cc < GGML_CUDA_CC_RDNA4_M)
94#define GGML_CUDA_CC_IS_RDNA3(cc) (GGML_CUDA_CC_IS_RDNA3_0(cc) || GGML_CUDA_CC_IS_RDNA3_5(cc))
95#define GGML_CUDA_CC_IS_RDNA4_M(cc) (cc >= GGML_CUDA_CC_RDNA4_M && cc < GGML_CUDA_CC_RDNA4)
96#define GGML_CUDA_CC_IS_RDNA4(cc) (cc >= GGML_CUDA_CC_RDNA4)
97#define GGML_CUDA_CC_IS_GCN_APU(cc) ((cc) == GGML_CUDA_CC_GFX909 || (cc) == GGML_CUDA_CC_GFX90C)
98#define GGML_CUDA_CC_IS_GCN(cc) ((cc > GGML_CUDA_CC_OFFSET_AMD && cc < GGML_CUDA_CC_CDNA1) || GGML_CUDA_CC_IS_GCN_APU(cc))
99#define GGML_CUDA_CC_IS_CDNA(cc) (!GGML_CUDA_CC_IS_GCN_APU(cc) && cc >= GGML_CUDA_CC_CDNA1 && cc < GGML_CUDA_CC_RDNA1)
100#define GGML_CUDA_CC_IS_CDNA1(cc) (GGML_CUDA_CC_IS_CDNA(cc) && cc >= GGML_CUDA_CC_CDNA1 && cc < GGML_CUDA_CC_CDNA2)
101#define GGML_CUDA_CC_IS_CDNA2(cc) (GGML_CUDA_CC_IS_CDNA(cc) && cc >= GGML_CUDA_CC_CDNA2 && cc < GGML_CUDA_CC_CDNA3)
102#define GGML_CUDA_CC_IS_CDNA3(cc) (GGML_CUDA_CC_IS_CDNA(cc) && cc >= GGML_CUDA_CC_CDNA3 && cc < GGML_CUDA_CC_CDNA4)
103#define GGML_CUDA_CC_IS_CDNA4(cc) (GGML_CUDA_CC_IS_CDNA(cc) && cc >= GGML_CUDA_CC_CDNA4 && cc < GGML_CUDA_CC_RDNA1)
104
105// Moore Threads
106#define MUSART_HMASK 40300 // MUSA rc4.3, min. ver. for half2 -> uint mask comparisons
107
108#define GGML_CUDA_CC_QY1 (GGML_CUDA_CC_OFFSET_MTHREADS + 0x210) // MTT S80, MTT S3000
109#define GGML_CUDA_CC_QY2 (GGML_CUDA_CC_OFFSET_MTHREADS + 0x220) // MTT S4000
110#define GGML_CUDA_CC_PH1 (GGML_CUDA_CC_OFFSET_MTHREADS + 0x310) // MTT S5000
111
112#define GGML_CUDA_CC_IS_MTHREADS(cc) (cc >= GGML_CUDA_CC_OFFSET_MTHREADS && cc < GGML_CUDA_CC_OFFSET_AMD)
113#define GGML_CUDA_CC_IS_QY1(cc) (cc >= GGML_CUDA_CC_QY1 && cc < GGML_CUDA_CC_QY2)
114#define GGML_CUDA_CC_IS_QY2(cc) (cc >= GGML_CUDA_CC_QY2 && cc < GGML_CUDA_CC_PH1)
115#define GGML_CUDA_CC_IS_PH1(cc) (cc >= GGML_CUDA_CC_PH1)
116
117#if !defined(GGML_USE_HIP) && (defined(GGML_USE_MUSA) || CUDART_VERSION >= 11070)
118# define GGML_CUDA_USE_CUB
119#endif // !defined(GGML_USE_HIP) && (defined(GGML_USE_MUSA) || CUDART_VERSION >= 11070)
120
121// PDL host-side support (cudaLaunchKernelEx) requires CUDART >= 11.8.
122// However, this has been bugged in CTK < 12.3 for MSVC builds, see
123// https://github.com/ggml-org/llama.cpp/pull/22522#discussion_r3302393293
124// __CUDA_ARCH__ is undefined in host passes; GPU arch check happens in device-side code.
125#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && \
126 (CUDART_VERSION >= 12030 || (!(defined(_MSC_VER) && !defined(__clang__)) && CUDART_VERSION >= 11080))
127# define GGML_CUDA_USE_PDL
128#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && (CUDART_VERSION >= 12030 || (!(defined(_MSC_VER) && !defined(__clang__)) && CUDART_VERSION >= 11080))
129
130static __device__ __forceinline__ void ggml_cuda_syncwarp() {
131#ifndef GGML_USE_HIP
132 __syncwarp();
133#endif // GGML_USE_HIP
134}
135
136static __device__ __forceinline__ void ggml_cuda_pdl_sync() {
137#if defined(GGML_CUDA_USE_PDL) && __CUDA_ARCH__ >= GGML_CUDA_CC_HOPPER
138 cudaGridDependencySynchronize();
139#endif // defined(GGML_CUDA_USE_PDL) && __CUDA_ARCH__ >= GGML_CUDA_CC_HOPPER
140}
141
142static __device__ __forceinline__ void ggml_cuda_pdl_lc() {
143#if defined(GGML_CUDA_USE_PDL) && __CUDA_ARCH__ >= GGML_CUDA_CC_HOPPER
144 cudaTriggerProgrammaticLaunchCompletion();
145#endif // defined(GGML_CUDA_USE_PDL) && __CUDA_ARCH__ >= GGML_CUDA_CC_HOPPER
146}
147
148#ifdef __CUDA_ARCH_LIST__
149constexpr bool ggml_cuda_has_arch_impl(int) {
150 return false;
151}
152
153template<class ... Archs>
154constexpr bool ggml_cuda_has_arch_impl(const int arch, const int first, Archs... rest) {
155 return arch == first || ggml_cuda_has_arch_impl(arch, rest...);
156}
157
158constexpr bool ggml_cuda_has_arch(const int arch) {
159 return ggml_cuda_has_arch_impl(arch, __CUDA_ARCH_LIST__);
160}
161
162constexpr int ggml_cuda_highest_compiled_arch_impl(const int /*arch*/, const int cur) {
163 if (cur == 0) {
164 return -1;
165 }
166 return cur;
167}
168
169template<class ... Archs>
170constexpr int ggml_cuda_highest_compiled_arch_impl(const int arch, const int cur, const int first, Archs... rest) {
171 if (first <= arch && first > cur) {
172 return ggml_cuda_highest_compiled_arch_impl(arch, first, rest...);
173 } else {
174 return ggml_cuda_highest_compiled_arch_impl(arch, cur, rest...);
175 }
176}
177
178constexpr int ggml_cuda_highest_compiled_arch(const int arch) {
179 return ggml_cuda_highest_compiled_arch_impl(arch, 0, __CUDA_ARCH_LIST__);
180}
181#else
182static int ggml_cuda_highest_compiled_arch(const int arch) {
183 return arch;
184}
185#endif // __CUDA_ARCH_LIST__
186
187// ---------------------------------------------------------------------------------------------------------
188
189#define MATRIX_ROW_PADDING 512 // last row of quant. matrices is a multiple of this to avoid out-of-bounds memory accesses
190
191#define GGML_CUDA_MAX_STREAMS 8
192
193[[noreturn]]
194void ggml_cuda_error(const char * stmt, const char * func, const char * file, int line, const char * msg);
195
196#define CUDA_CHECK_GEN(err, success, error_fn) \
197 do { \
198 auto err_ = (err); \
199 if (err_ != (success)) { \
200 ggml_cuda_error(#err, __func__, __FILE__, __LINE__, error_fn(err_)); \
201 } \
202 } while (0)
203
204#define CUDA_CHECK(err) CUDA_CHECK_GEN(err, cudaSuccess, cudaGetErrorString)
205
206
207#if CUDART_VERSION >= 12000 || defined(GGML_USE_MUSA)
208 static const char * cublas_get_error_str(const cublasStatus_t err) {
209 return cublasGetStatusString(err);
210 }
211#else
212 static const char * cublas_get_error_str(const cublasStatus_t err) {
213 switch (err) {
214 case CUBLAS_STATUS_SUCCESS: return "CUBLAS_STATUS_SUCCESS";
215 case CUBLAS_STATUS_NOT_INITIALIZED: return "CUBLAS_STATUS_NOT_INITIALIZED";
216 case CUBLAS_STATUS_ALLOC_FAILED: return "CUBLAS_STATUS_ALLOC_FAILED";
217 case CUBLAS_STATUS_INVALID_VALUE: return "CUBLAS_STATUS_INVALID_VALUE";
218 case CUBLAS_STATUS_ARCH_MISMATCH: return "CUBLAS_STATUS_ARCH_MISMATCH";
219 case CUBLAS_STATUS_MAPPING_ERROR: return "CUBLAS_STATUS_MAPPING_ERROR";
220 case CUBLAS_STATUS_EXECUTION_FAILED: return "CUBLAS_STATUS_EXECUTION_FAILED";
221 case CUBLAS_STATUS_INTERNAL_ERROR: return "CUBLAS_STATUS_INTERNAL_ERROR";
222 case CUBLAS_STATUS_NOT_SUPPORTED: return "CUBLAS_STATUS_NOT_SUPPORTED";
223 default: return "unknown error";
224 }
225 }
226#endif // CUDART_VERSION >= 12000
227
228#define CUBLAS_CHECK(err) CUDA_CHECK_GEN(err, CUBLAS_STATUS_SUCCESS, cublas_get_error_str)
229
230#ifdef GGML_USE_NCCL
231#define NCCL_CHECK(err) CUDA_CHECK_GEN(err, ncclSuccess, ncclGetErrorString)
232#endif // GGML_USE_NCCL
233
234#if !defined(GGML_USE_HIP) && !defined(GGML_CUDA_NO_VMM)
235static const char * cu_get_error_str(CUresult err) {
236 const char * err_str;
237 cuGetErrorString(err, &err_str);
238 return err_str;
239}
240#define CU_CHECK(err) CUDA_CHECK_GEN(err, CUDA_SUCCESS, cu_get_error_str)
241#endif
242
243#if !defined(GGML_USE_HIP)
244# define CUDA_SET_SHARED_MEMORY_LIMIT(kernel, nbytes) \
245 do { \
246 static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = { false }; \
247 const int id = ggml_cuda_get_device(); \
248 if (!shared_memory_limit_raised[id]) { \
249 CUDA_CHECK(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, nbytes)); \
250 shared_memory_limit_raised[id] = true; \
251 } \
252 } while (0)
253#else
254# define CUDA_SET_SHARED_MEMORY_LIMIT(kernel, nbytes) \
255 do { \
256 GGML_UNUSED(nbytes); \
257 } while (0)
258#endif // !defined(GGML_USE_HIP)
259
260#if CUDART_VERSION >= 11010 || defined(GGML_USE_MUSA)
261#define GGML_CUDA_ASSUME(x) __builtin_assume(x)
262#else
263#define GGML_CUDA_ASSUME(x)
264#endif // CUDART_VERSION >= 11010
265
266#if (!defined(GGML_USE_HIP) && !defined(GGML_CUDA_NO_VMM)) || (defined(GGML_USE_HIP) && !defined(GGML_HIP_NO_VMM))
267#define GGML_USE_VMM
268#endif // (!defined(GGML_USE_HIP) && !defined(GGML_CUDA_NO_VMM)) || (defined(GGML_USE_HIP) && !defined(GGML_HIP_NO_VMM))
269
270#if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) || __CUDA_ARCH__ >= GGML_CUDA_CC_PASCAL
271#define FP16_AVAILABLE
272#endif // defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) || __CUDA_ARCH__ >= GGML_CUDA_CC_PASCAL
273
274#if defined(FP16_AVAILABLE) && __CUDA_ARCH__ != 610
275#define FAST_FP16_AVAILABLE
276#endif // defined(FP16_AVAILABLE) && __CUDA_ARCH__ != 610
277
278#if defined(GGML_USE_HIP) && defined(CDNA) && !defined(GGML_HIP_NO_MMQ_MFMA)
279#define AMD_MFMA_AVAILABLE
280#endif // defined(GGML_USE_HIP) && defined(CDNA) && !defined(GGML_HIP_NO_MMQ_MFMA)
281
282#if defined(GGML_USE_HIP) && (defined(RDNA4) || defined(RDNA4_M))
283#define AMD_WMMA_128B_AVAILABLE
284#endif // defined(GGML_USE_HIP) && (defined(RDNA4) || defined(RDNA4_M))
285
286#if defined(GGML_USE_HIP) && defined(RDNA3)
287#define AMD_WMMA_256B_AVAILABLE
288#endif // defined(GGML_USE_HIP) && defined(RDNA3)
289
290#if defined(AMD_WMMA_128B_AVAILABLE) || defined(AMD_WMMA_256B_AVAILABLE)
291#define AMD_WMMA_AVAILABLE
292#endif // defined(AMD_WMMA_128B_AVAILABLE) || defined(AMD_WMMA_256B_AVAILABLE)
293
294// The Volta instructions are in principle available on Turing or newer but they are effectively unusable:
295#if !defined(GGML_USE_HIP) && __CUDA_ARCH__ == GGML_CUDA_CC_VOLTA
296#define VOLTA_MMA_AVAILABLE
297#endif // !defined(GGML_USE_HIP) && __CUDA_ARCH__ == GGML_CUDA_CC_VOLTA
298
299#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_TURING
300#define TURING_MMA_AVAILABLE
301#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_TURING
302
303#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_AMPERE
304#define AMPERE_MMA_AVAILABLE
305#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_AMPERE
306
307#if !defined(GGML_USE_HIP) && __CUDA_ARCH__ >= GGML_CUDA_CC_BLACKWELL && __CUDA_ARCH__ < GGML_CUDA_CC_RUBIN
308# define BLACKWELL_MMA_AVAILABLE
309#endif // !defined(GGML_USE_HIP) && __CUDA_ARCH__ >= GGML_CUDA_CC_BLACKWELL
310
311#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_AMPERE
312#define CP_ASYNC_AVAILABLE
313#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_AMPERE
314
315#if !defined(GGML_CUDA_NO_FA) && !(defined(GGML_USE_MUSA) && __MUSA_ARCH__ < 220)
316#define FLASH_ATTN_AVAILABLE
317#endif // !defined(GGML_CUDA_NO_FA) && !(defined(GGML_USE_MUSA) && __MUSA_ARCH__ < 220)
318
319static bool fp16_available(const int cc) {
320 return ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_PASCAL ||
321 (GGML_CUDA_CC_IS_MTHREADS(cc) && cc >= GGML_CUDA_CC_PH1);
322}
323
324static bool fast_fp16_available(const int cc) {
325 return GGML_CUDA_CC_IS_AMD(cc) ||
326 (GGML_CUDA_CC_IS_NVIDIA(cc) && fp16_available(cc) && ggml_cuda_highest_compiled_arch(cc) != 610) ||
327 (GGML_CUDA_CC_IS_MTHREADS(cc) && fp16_available(cc));
328}
329
330// To be used for feature selection of external libraries, e.g. cuBLAS.
331static bool fast_fp16_hardware_available(const int cc) {
332 return (GGML_CUDA_CC_IS_NVIDIA(cc) && cc >= GGML_CUDA_CC_PASCAL && cc != 610) || GGML_CUDA_CC_IS_AMD(cc) ||
333 (GGML_CUDA_CC_IS_MTHREADS(cc) && cc >= GGML_CUDA_CC_QY2);
334}
335
336// To be used for feature selection of external libraries, e.g. cuBLAS.
337static bool fp16_mma_hardware_available(const int cc) {
338 return (GGML_CUDA_CC_IS_NVIDIA(cc) && cc >= GGML_CUDA_CC_VOLTA) ||
339 GGML_CUDA_CC_IS_CDNA(cc) || GGML_CUDA_CC_IS_RDNA3(cc) || GGML_CUDA_CC_IS_RDNA4_M(cc) || GGML_CUDA_CC_IS_RDNA4(cc) ||
340 (GGML_CUDA_CC_IS_MTHREADS(cc) && cc >= GGML_CUDA_CC_QY2);
341}
342
343// To be used for feature selection of external libraries, e.g. cuBLAS.
344static bool fast_bf16_hardware_available(const int cc) {
345 return (GGML_CUDA_CC_IS_AMD(cc) && (cc >= GGML_CUDA_CC_RDNA3 || GGML_CUDA_CC_IS_CDNA(cc)))
346 || (GGML_CUDA_CC_IS_NVIDIA(cc) && cc >= GGML_CUDA_CC_AMPERE);
347}
348
349static bool bf16_mma_hardware_available(const int cc) {
350 return (GGML_CUDA_CC_IS_NVIDIA(cc) && cc >= GGML_CUDA_CC_AMPERE) ||
351 GGML_CUDA_CC_IS_CDNA(cc) || cc >= GGML_CUDA_CC_RDNA3 ||
352 (GGML_CUDA_CC_IS_MTHREADS(cc) && cc >= GGML_CUDA_CC_PH1);
353}
354
355static bool fp32_mma_hardware_available(const int cc) {
356 return GGML_CUDA_CC_IS_CDNA(cc);
357}
358
359static bool amd_mfma_available(const int cc) {
360#if !defined(GGML_HIP_NO_MMQ_MFMA)
361 return GGML_CUDA_CC_IS_CDNA(cc);
362#else
363 return false;
364#endif //!defined(GGML_HIP_NO_MMQ_MFMA)
365}
366
367static bool amd_wmma_available(const int cc) {
368 return GGML_CUDA_CC_IS_RDNA3(cc) || GGML_CUDA_CC_IS_RDNA4_M(cc) || GGML_CUDA_CC_IS_RDNA4(cc);
369}
370
371static bool volta_mma_available(const int cc) {
372 return GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_VOLTA;
373}
374
375static bool turing_mma_available(const int cc) {
376 return GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_TURING;
377}
378
379static bool ampere_mma_available(const int cc) {
380 return GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_AMPERE;
381}
382
383static bool cp_async_available(const int cc) {
384 return GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_AMPERE;
385}
386
387static bool blackwell_mma_available(const int cc) {
388 return GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_BLACKWELL &&
389 ggml_cuda_highest_compiled_arch(cc) < GGML_CUDA_CC_RUBIN;
390}
391
392// Checks whether the tensor's base data pointer and higher-dimensional strides are byte-aligned to `alignment` bytes.
393static bool ggml_cuda_is_aligned(const ggml_tensor * tensor, const size_t alignment) {
394 GGML_ASSERT(tensor != nullptr);
395 return (reinterpret_cast<uintptr_t>(tensor->data) % alignment) == 0 &&
396 tensor->nb[1] % alignment == 0 &&
397 tensor->nb[2] % alignment == 0 &&
398 tensor->nb[3] % alignment == 0;
399}
400
401static constexpr __device__ int ggml_cuda_get_physical_warp_size() {
402#if defined(GGML_USE_HIP) && (defined(__GFX9__) || defined(__GFX8__))
403 return 64;
404#else
405 return 32;
406#endif // defined(GGML_USE_HIP) && (defined(__GFX9__) || defined(__GFX8__))
407}
408
409// Maximum number of bytes that can be copied in a single instruction.
410static constexpr __device__ int ggml_cuda_get_max_cpy_bytes() {
411#if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA)
412 return 16;
413#else
414#if __CUDA_ARCH__ >= GGML_CUDA_CC_VOLTA
415 return 16;
416#else
417 return 8;
418#endif // __CUDA_ARCH__ >= GGML_CUDA_CC_VOLTA
419#endif // defined(GGML_USE_HIP) || defined(GGML_USE_MUSA)
420}
421
422
423[[noreturn]]
424static __device__ void no_device_code(
425 const char * file_name, const int line, const char * function_name, const int arch, const char * arch_list) {
426
427#if defined(GGML_USE_HIP)
428 printf("%s:%d: ERROR: HIP kernel %s has no device code compatible with HIP arch %d.\n",
429 file_name, line, function_name, arch);
430 GGML_UNUSED(arch_list);
431#else
432 printf("%s:%d: ERROR: CUDA kernel %s has no device code compatible with CUDA arch %d. ggml-cuda.cu was compiled for: %s\n",
433 file_name, line, function_name, arch, arch_list);
434#endif // defined(GGML_USE_HIP)
435 __trap();
436
437 GGML_UNUSED(no_device_code); // suppress unused function warning
438}
439
440#ifdef __CUDA_ARCH__
441#define NO_DEVICE_CODE no_device_code(__FILE__, __LINE__, __FUNCTION__, __CUDA_ARCH__, STRINGIZE(__CUDA_ARCH_LIST__))
442#else
443#define NO_DEVICE_CODE //GGML_ABORT("NO_DEVICE_CODE not valid in host code.")
444#endif // __CUDA_ARCH__
445
446// The compiler is always able to unroll loops if they contain continue expressions.
447// In such cases loop unrolling can still be achieved via recursion:
448template <int n>
449struct ggml_cuda_unroll {
450 template <typename Func, typename... Args>
451 __device__ void operator()(const Func & f, Args... args) const {
452 f(n - 1, args...);
453 ggml_cuda_unroll<n - 1>{}(f, args...);
454 }
455};
456
457template <>
458struct ggml_cuda_unroll<1> {
459 template <typename Func, typename... Args>
460 __device__ void operator()(const Func & f, Args... args) const {
461 f(0, args...);
462 }
463};
464
465template<int width = WARP_SIZE>
466static __device__ __forceinline__ int warp_reduce_sum(int x) {
467#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_AMPERE
468 return __reduce_add_sync(0xffffffff, x);
469#else
470#pragma unroll
471 for (int offset = width/2; offset > 0; offset >>= 1) {
472 x += __shfl_xor_sync(0xffffffff, x, offset, width);
473 }
474 return x;
475#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && __CUDA_ARCH__ >= GGML_CUDA_CC_AMPERE
476}
477
478template<int width = WARP_SIZE>
479static __device__ __forceinline__ float warp_reduce_sum(float x) {
480#pragma unroll
481 for (int offset = width/2; offset > 0; offset >>= 1) {
482 x += __shfl_xor_sync(0xffffffff, x, offset, width);
483 }
484 return x;
485}
486
487template<int width = WARP_SIZE>
488static __device__ __forceinline__ float2 warp_reduce_sum(float2 a) {
489#pragma unroll
490 for (int offset = width/2; offset > 0; offset >>= 1) {
491 a.x += __shfl_xor_sync(0xffffffff, a.x, offset, width);
492 a.y += __shfl_xor_sync(0xffffffff, a.y, offset, width);
493 }
494 return a;
495}
496
497template<int width = WARP_SIZE>
498static __device__ __forceinline__ half2 warp_reduce_sum(half2 a) {
499#ifdef FP16_AVAILABLE
500#pragma unroll
501 for (int offset = width/2; offset > 0; offset >>= 1) {
502 a = __hadd2(a, __shfl_xor_sync(0xffffffff, a, offset, width));
503 }
504 return a;
505
506#else
507 NO_DEVICE_CODE;
508 return a;
509#endif // FP16_AVAILABLE
510}
511
512template<int width = WARP_SIZE>
513static __device__ __forceinline__ int warp_reduce_all(int x) {
514 if (width == ggml_cuda_get_physical_warp_size()) {
515 return __all_sync(0xffffffff, x);
516 } else {
517#pragma unroll
518 for (int offset = width/2; offset > 0; offset >>= 1) {
519 x = __shfl_xor_sync(0xffffffff, x, offset, width) && x;
520 }
521 return x;
522 }
523}
524
525template<int width = WARP_SIZE>
526static __device__ __forceinline__ int warp_reduce_any(int x) {
527 if (width == ggml_cuda_get_physical_warp_size()) {
528 return __any_sync(0xffffffff, x);
529 } else {
530#pragma unroll
531 for (int offset = width/2; offset > 0; offset >>= 1) {
532 x = __shfl_xor_sync(0xffffffff, x, offset, width) || x;
533 }
534 return x;
535 }
536}
537
538template<int width = WARP_SIZE>
539static __device__ __forceinline__ float warp_reduce_max(float x) {
540#pragma unroll
541 for (int offset = width/2; offset > 0; offset >>= 1) {
542 x = fmaxf(x, __shfl_xor_sync(0xffffffff, x, offset, width));
543 }
544 return x;
545}
546
547template<typename T, int width = WARP_SIZE>
548static __device__ __forceinline__ T warp_prefix_inclusive_sum(T x) {
549 const int lane_id = threadIdx.x % width;
550#pragma unroll
551 for (int offset = 1; offset < width; offset <<= 1) {
552 const T t = __shfl_up_sync(0xffffffff, x, offset, width);
553 if (lane_id >= offset) {
554 x += t;
555 }
556 }
557 return x;
558}
559
560template<int width = WARP_SIZE>
561static __device__ __forceinline__ float2 warp_prefix_inclusive_sum(float2 a) {
562 const int lane_id = threadIdx.x % width;
563#pragma unroll
564 for (int offset = 1; offset < width; offset <<= 1) {
565 const float t_x = __shfl_up_sync(0xffffffff, a.x, offset, width);
566 const float t_y = __shfl_up_sync(0xffffffff, a.y, offset, width);
567 if (lane_id >= offset) {
568 a.x += t_x;
569 a.y += t_y;
570 }
571 }
572 return a;
573}
574
575template<int width = WARP_SIZE>
576static __device__ __forceinline__ half2 warp_prefix_inclusive_sum(half2 a) {
577#ifdef FP16_AVAILABLE
578 const int lane_id = threadIdx.x % width;
579#pragma unroll
580 for (int offset = 1; offset < width; offset <<= 1) {
581 const half2 t = __shfl_up_sync(0xffffffff, a, offset, width);
582 if (lane_id >= offset) {
583 a = __hadd2(a, t);
584 }
585 }
586 return a;
587
588#else
589 NO_DEVICE_CODE;
590 return a;
591#endif // FP16_AVAILABLE
592}
593
594enum class block_reduce_method {
595 MAX,
596 SUM,
597};
598
599template<block_reduce_method method_t, typename T>
600struct block_reduce_policy;
601
602template <typename T, typename... Ts>
603inline constexpr bool is_any = (std::is_same_v<T, Ts> || ...);
604
605template<typename...>
606inline constexpr bool ggml_cuda_dependent_false_v = false;
607
608template <typename T> struct block_reduce_policy<block_reduce_method::SUM, T> {
609 static __device__ T reduce(T val) {
610 if constexpr(is_any<T, float, float2, half2, int>) {
611 return warp_reduce_sum(val);
612 } else {
613 static_assert(ggml_cuda_dependent_false_v<T>, "Unsupported type for block reduce sum");
614 }
615 }
616
617 static __device__ T sentinel() {
618 if constexpr (std::is_same_v<T, float>) {
619 return 0.0f;
620 } else if constexpr (std::is_same_v<T, float2>) {
621 return make_float2(0.0f, 0.0f);
622 } else if constexpr (std::is_same_v<T, half2>) {
623 return make_half2(0.0f, 0.0f);
624 } else if constexpr (std::is_same_v<T, int>) {
625 return 0;
626 } else {
627 static_assert(ggml_cuda_dependent_false_v<T>, "Unsupported type for block reduce sum");
628 }
629 }
630};
631
632template <typename T> struct block_reduce_policy<block_reduce_method::MAX, T> {
633 static __device__ T reduce(T val) {
634 if constexpr (is_any<T, float, half2>) {
635 return warp_reduce_max(val);
636 } else {
637 static_assert(ggml_cuda_dependent_false_v<T>, "Unsupported type for block reduce max");
638 }
639 }
640
641 static __device__ T sentinel() {
642 if constexpr (std::is_same_v<T, float>) {
643 return -INFINITY;
644 } else if constexpr (std::is_same_v<T, half2>) {
645 return make_half2(-INFINITY, -INFINITY);
646 } else {
647 static_assert(ggml_cuda_dependent_false_v<T>, "Unsupported type for block reduce max");
648 }
649 }
650};
651
652template <block_reduce_method reduce_method_t, const unsigned int block_size_template = 0, typename T>
653static __device__ T block_reduce(T val, [[maybe_unused]] T * shared_vals) {
654 // for multi-warp reductions, callers must not reuse shared_vals until all reads from this invocation have completed
655 val = block_reduce_policy<reduce_method_t, T>::reduce(val);
656 const unsigned int block_size = block_size_template == 0 ? blockDim.x : block_size_template;
657 if (block_size > WARP_SIZE) {
658 assert((block_size <= 1024) && (block_size % WARP_SIZE) == 0);
659 const int warp_id = threadIdx.x / WARP_SIZE;
660 const int lane_id = threadIdx.x % WARP_SIZE;
661 if (lane_id == 0) {
662 shared_vals[warp_id] = val;
663 }
664 __syncthreads();
665 val = block_reduce_policy<reduce_method_t, T>::sentinel();
666 if (lane_id < (static_cast<int>(block_size) / WARP_SIZE)) {
667 val = shared_vals[lane_id];
668 }
669 return block_reduce_policy<reduce_method_t, T>::reduce(val);
670 }
671
672 return val;
673}
674
675static __device__ __forceinline__ half ggml_cuda_hmax(const half a, const half b) {
676#ifdef FP16_AVAILABLE
677
678#if !defined(GGML_USE_HIP) && CUDART_VERSION < CUDART_HMAX
679 return __float2half(fmaxf(__half2float(a), __half2float(b)));
680#else
681 return __hmax(a, b);
682#endif // !defined(GGML_USE_HIP) && CUDART_VERSION < CUDART_HMAX
683
684#else
685 NO_DEVICE_CODE;
686 GGML_UNUSED(b);
687 return a;
688#endif // FP16_AVAILABLE
689}
690
691static __device__ __forceinline__ half2 ggml_cuda_hmax2(const half2 a, const half2 b) {
692#if defined(GGML_USE_HIP)
693 return half2(__hmax(a.x, b.x), __hmax(a.y, b.y));
694#elif CUDART_VERSION >= CUDART_HMAX
695 return __hmax2(a, b);
696#else
697 half2 ret;
698 reinterpret_cast<half&>(ret.x) = __float2half(fmaxf( __low2float(a), __low2float(b)));
699 reinterpret_cast<half&>(ret.y) = __float2half(fmaxf(__high2float(a), __high2float(b)));
700 return ret;
701#endif
702}
703
704template<int width = WARP_SIZE>
705static __device__ __forceinline__ half2 warp_reduce_max(half2 x) {
706#pragma unroll
707 for (int offset = width/2; offset > 0; offset >>= 1) {
708 x = ggml_cuda_hmax2(x, __shfl_xor_sync(0xffffffff, x, offset, width));
709 }
710 return x;
711}
712
713#if (defined(CUDART_VERSION) && CUDART_VERSION < CUDART_HMASK) || defined(GGML_USE_HIP) || \
714 (defined(MUSART_VERSION) && MUSART_VERSION < MUSART_HMASK)
715static __device__ __forceinline__ uint32_t __hgt2_mask(const half2 a, const half2 b) {
716 const uint32_t mask_low = 0x0000FFFF * (float( __low2half(a)) > float( __low2half(b)));
717 const uint32_t mask_high = 0xFFFF0000 * (float(__high2half(a)) > float(__high2half(b)));
718 return mask_low | mask_high;
719}
720#endif // (defined(CUDART_VERSION) && CUDART_VERSION < CUDART_HMASK) || defined(GGML_USE_HIP) || (defined(MUSART_VERSION) && MUSART_VERSION < MUSART_HMASK)
721
722static __device__ __forceinline__ int ggml_cuda_dp4a(const int a, const int b, int c) {
723#if defined(GGML_USE_HIP)
724#if defined(CDNA) || defined(RDNA2) || defined(__gfx906__)
725 c = __builtin_amdgcn_sdot4(a, b, c, false);
726#elif defined(RDNA3) || defined(RDNA4_M) || defined(RDNA4)
727 c = __builtin_amdgcn_sudot4( true, a, true, b, c, false);
728#elif defined(RDNA1) || defined(__gfx900__)
729 int tmp1;
730 int tmp2;
731 asm("\n \
732 v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0 \n \
733 v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:BYTE_1 \n \
734 v_add3_u32 %0, %1, %2, %0 \n \
735 v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_2 \n \
736 v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_3 \n \
737 v_add3_u32 %0, %1, %2, %0 \n \
738 "
739 : "+v"(c), "=&v"(tmp1), "=&v"(tmp2)
740 : "v"(a), "v"(b)
741 );
742#else
743 const int8x4_t va = reinterpret_cast<const int8x4_t&>(a);
744 const int8x4_t vb = reinterpret_cast<const int8x4_t&>(b);
745 c += va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2] + va[3] * vb[3];
746#endif
747 return c;
748
749#else // defined(GGML_USE_HIP)
750
751#if __CUDA_ARCH__ >= GGML_CUDA_CC_DP4A || defined(GGML_USE_MUSA)
752 return __dp4a(a, b, c);
753#else // __CUDA_ARCH__ >= GGML_CUDA_CC_DP4A || defined(GGML_USE_MUSA)
754 const int8_t * a8 = (const int8_t *) &a;
755 const int8_t * b8 = (const int8_t *) &b;
756 return c + a8[0]*b8[0] + a8[1]*b8[1] + a8[2]*b8[2] + a8[3]*b8[3];
757#endif // __CUDA_ARCH__ >= GGML_CUDA_CC_DP4A || defined(GGML_USE_MUSA)
758
759#endif // defined(GGML_USE_HIP)
760}
761
762static __device__ __forceinline__ void ggml_cuda_mad(float & acc, const float v, const float u) {
763 acc += v*u;
764}
765
766static __device__ __forceinline__ void ggml_cuda_mad(float & acc, const float2 v, const float2 u) {
767 acc += v.x*u.x;
768 acc += v.y*u.y;
769}
770
771#if defined(GGML_USE_HIP) && (defined(RDNA2) || defined(RDNA3) || defined(RDNA4_M) || defined(RDNA4) || defined(__gfx906__) || defined(CDNA))
772#define V_DOT2_F32_F16_AVAILABLE
773#endif // defined(GGML_USE_HIP) && (defined(RDNA2) || defined(RDNA3) || defined(RDNA4_M) || defined(RDNA4) || defined(__gfx906__) || defined(CDNA))
774
775static __device__ __forceinline__ void ggml_cuda_mad(float & acc, const half2 v, const half2 u) {
776#ifdef V_DOT2_F32_F16_AVAILABLE
777 asm volatile("v_dot2_f32_f16 %0, %1, %2, %0" : "+v"(acc) : "v"(v), "v"(u));
778#else
779#ifdef FAST_FP16_AVAILABLE
780 const float2 tmp = __half22float2(v*u);
781 acc += tmp.x + tmp.y;
782#else
783 const float2 tmpv = __half22float2(v);
784 const float2 tmpu = __half22float2(u);
785 acc += tmpv.x * tmpu.x;
786 acc += tmpv.y * tmpu.y;
787#endif // FAST_FP16_AVAILABLE
788#endif // V_DOT2_F32_F16_AVAILABLE
789}
790
791static __device__ __forceinline__ void ggml_cuda_mad(half2 & acc, const half2 v, const half2 u) {
792#ifdef FAST_FP16_AVAILABLE
793 acc += v*u;
794#else
795 const float2 tmpv = __half22float2(v);
796 const float2 tmpu = __half22float2(u);
797 float2 tmpacc = __half22float2(acc);
798 tmpacc.x += tmpv.x * tmpu.x;
799 tmpacc.y += tmpv.y * tmpu.y;
800 acc = make_half2(tmpacc.x, tmpacc.y);
801#endif // FAST_FP16_AVAILABLE
802}
803
804// Aligned memory transfers of 8/16 bytes can be faster than 2 transfers with 4 bytes, especially on AMD.
805// Important: do not use this function if dst and src both point at registers.
806// Due to the strict aliasing rule the compiler can do incorrect optimizations if src and dst have different types.
807// The function is intended for copies between registers and SRAM/VRAM to make the compiler emit the right instructions.
808// If dst and src point at different address spaces then they are guaranteed to not be aliased.
809template <int nbytes, int alignment = 0>
810static __device__ __forceinline__ void ggml_cuda_memcpy_1(void * __restrict__ dst, const void * __restrict__ src) {
811 static_assert(
812 nbytes <= ggml_cuda_get_max_cpy_bytes() || alignment == 0,
813 "You are misusing the alignment parameter for ggml_cuda_memcpy_1. "
814 "The intent is for the parameter is only as a workaround if either one of the pointers is not properly aligned. "
815 "If you use it to do more bytes per copy than ggml_cuda_max_cpy_bytes() the reads and writes may not be coalesced. "
816 "Call ggml_cuda_memcpy_1 in a loop instead.");
817 if constexpr (alignment != 0) {
818 static_assert(nbytes % alignment == 0, "bad alignment");
819 }
820 constexpr int nb_per_cpy = alignment == 0 ? nbytes : alignment;
821
822#pragma unroll
823 for (int i = 0; i < nbytes/nb_per_cpy; ++i) {
824 if constexpr (nb_per_cpy == 1) {
825 ((char *) dst)[i] = ((const char *) src)[i];
826 } else if constexpr (nb_per_cpy == 2) {
827 ((short *) dst)[i] = ((const short *) src)[i];
828 } else if constexpr (nb_per_cpy == 4) {
829 ((int *) dst)[i] = ((const int *) src)[i];
830 } else if constexpr (nb_per_cpy == 8) {
831 ((int2 *) dst)[i] = ((const int2 *) src)[i];
832 } else if constexpr (nb_per_cpy == 16) {
833 ((int4 *) dst)[i] = ((const int4 *) src)[i];
834 } else {
835 static_assert(nbytes == 0 && nbytes == -1, "bad nbytes");
836 }
837 }
838}
839
840static __device__ __forceinline__ float ggml_cuda_e8m0_to_fp32(uint8_t x) {
841#if CUDART_VERSION >= 12080
842 const nv_bfloat16 e = __nv_cvt_e8m0_to_bf16raw(x);
843 return (float) e;
844#else
845 uint32_t bits;
846 if (x == 0) {
847 bits = 0x00400000;
848 } else {
849 bits = (uint32_t) x << 23;
850 }
851
852 float result;
853 memcpy(&result, &bits, sizeof(float));
854 return result;
855#endif // CUDART_VERSION >= 12050
856}
857
858static __device__ __forceinline__ float ggml_cuda_ue4m3_to_fp32(uint8_t x) {
859#if defined(GGML_USE_HIP) && defined(CDNA3) && defined(FP8_AVAILABLE) && HIP_VERSION >= 60200000
860 // ROCm does not support fp8 in software on devices with fp8 hardware,
861 // but CDNA3 supports only e4m3_fnuz (no inf).
862 const uint32_t bits = x * (x != 0x7F && x != 0xFF); // Convert NaN to 0.0f to match CPU implementation.
863 const __hip_fp8_e4m3_fnuz xf = *reinterpret_cast<const __hip_fp8_e4m3_fnuz *>(&bits);
864 return static_cast<float>(xf) / 2;
865#else
866#if defined(FP8_AVAILABLE) && !defined(GGML_USE_HIP)
867 const uint32_t bits = x * (x != 0x7F && x != 0xFF); // Convert NaN to 0.0f to match CPU implementation.
868 const __nv_fp8_e4m3 xf = *reinterpret_cast<const __nv_fp8_e4m3 *>(&bits);
869 return static_cast<float>(xf) / 2;
870#else
871 if (x == 0 || (x == 0x7F && x != 0xFF)) { // Convert NaN to 0.0f
872 return 0.0f;
873 }
874 const int exp = (x >> 3) & 0xF;
875 const int man = x & 0x7;
876 float raw;
877 if (exp == 0) {
878 raw = ldexpf((float) man, -9);
879 } else {
880 raw = ldexpf(1.0f + (float) man / 8.0f, exp - 7);
881 }
882 return static_cast<float>(raw / 2);
883#endif // defined(FP8_AVAILABLE) && !defined(GGML_USE_HIP)
884#endif // defined(GGML_USE_HIP) && defined(CDNA3) && defined(FP8_AVAILABLE) && HIP_VERSION >= 60200000
885}
886
887static __device__ __forceinline__ uint8_t ggml_cuda_fp32_to_ue4m3(float x) {
888#if defined(BLACKWELL_MMA_AVAILABLE) // This is used for NVFP4 subblock scale quantizations only
889 if (!(x > 0.0f)) {
890 return 0;
891 }
892 const __nv_fp8_e4m3 xf(x);
893 return xf.__x;
894#else
895 GGML_UNUSED(x);
896 NO_DEVICE_CODE; // Used only for NVFP4 Scales for Activations, only for Blackwell
897#endif // defined(BLACKWELL_MMA_AVAILABLE)
898}
899
900__device__ __forceinline__ uint8_t ggml_cuda_float_to_fp4_e2m1(float x, float e) {
901 const uint8_t sign_bit = (x < 0.0f) << 3;
902 float ax = fabsf(x) * e;
903
904 // Positive LUT
905 static constexpr float pos_lut[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
906
907 int best_i = 0;
908 float best_err = fabsf(ax - pos_lut[0]);
909
910#pragma unroll
911 for (int i = 1; i < 8; ++i) {
912 const float err = fabsf(ax - pos_lut[i]);
913 if (err < best_err) {
914 best_err = err;
915 best_i = i;
916 }
917 }
918
919 return static_cast<uint8_t>(best_i | sign_bit);
920}
921
922// See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
923// Precompute mp (m' in the paper) and L such that division
924// can be computed using a multiply (high 32b of 64b result)
925// and a shift:
926//
927// n/d = (mulhi(n, mp) + n) >> L;
928static const uint3 init_fastdiv_values(uint64_t d_64) {
929 GGML_ASSERT(d_64 != 0);
930 GGML_ASSERT(d_64 <= std::numeric_limits<uint32_t>::max());
931
932 uint32_t d = (uint32_t)d_64;
933
934 // compute L = ceil(log2(d));
935 uint32_t L = 0;
936 while (L < 32 && (uint32_t{ 1 } << L) < d) {
937 L++;
938 }
939
940 uint32_t mp = (uint32_t) ((uint64_t{ 1 } << 32) * ((uint64_t{ 1 } << L) - d) / d + 1);
941 // pack divisor as well to reduce error surface
942 return make_uint3(mp, L, d);
943}
944
945static __device__ __forceinline__ uint32_t fastdiv(uint32_t n, const uint3 fastdiv_values) {
946 // expects fastdiv_values to contain <mp, L, divisor> in <x, y, z>
947 // fastdiv_values.z is unused and optimized away by the compiler.
948 // Compute high 32 bits of n * mp
949 const uint32_t hi = __umulhi(n, fastdiv_values.x);
950 // add n, apply bit shift
951 return (hi + n) >> fastdiv_values.y;
952}
953
954static __device__ __forceinline__ uint32_t fastmodulo(uint32_t n, const uint3 fastdiv_values) {
955 // expects fastdiv_values to contain <mp, L, divisor> in <x, y, z> (see init_fastdiv_values)
956 return n - fastdiv(n, fastdiv_values) * fastdiv_values.z;
957}
958
959// Calculate both division and modulo at once, returns <n/divisor, n%divisor>
960static __device__ __forceinline__ uint2 fast_div_modulo(uint32_t n, const uint3 fastdiv_values) {
961 // expects fastdiv_values to contain <mp, L, divisor> in <x, y, z> (see init_fastdiv_values)
962 const uint32_t div_val = fastdiv(n, fastdiv_values);
963 const uint32_t mod_val = n - div_val * fastdiv_values.z;
964 return make_uint2(div_val, mod_val);
965}
966
967typedef void (*dequantize_kernel_t)(const void * vx, const int64_t ib, const int iqs, float2 & v);
968
969template<typename dst_t>
970using dequantize_kq_t = void (*)(const void * vx, const int64_t ib, dst_t * y, const int tid);
971
972static __device__ __forceinline__ float get_alibi_slope(
973 const float max_bias, const uint32_t h, const uint32_t n_head_log2, const float m0, const float m1
974) {
975 if (max_bias <= 0.0f) {
976 return 1.0f;
977 }
978 const float base = h < n_head_log2 ? m0 : m1;
979 const int exph = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1;
980
981 return powf(base, exph);
982}
983
984template <ggml_type type>
985struct ggml_cuda_type_traits;
986
987template<>
988struct ggml_cuda_type_traits<GGML_TYPE_F16> {
989 static constexpr int qk = 1;
990 static constexpr int qr = 1;
991 static constexpr int bs = sizeof(ggml_half);
992};
993
994template<>
995struct ggml_cuda_type_traits<GGML_TYPE_Q1_0> {
996 static constexpr int qk = QK1_0;
997 static constexpr int qr = QR1_0;
998 static constexpr int qi = QI1_0;
999 static constexpr int bs = sizeof(block_q1_0);
1000};
1001
1002template<>
1003struct ggml_cuda_type_traits<GGML_TYPE_Q2_0> {
1004 static constexpr int qk = QK2_0;
1005 static constexpr int qr = QR2_0;
1006 static constexpr int qi = QI2_0;
1007 static constexpr int bs = sizeof(block_q2_0);
1008};
1009
1010template<>
1011struct ggml_cuda_type_traits<GGML_TYPE_Q4_0> {
1012 static constexpr int qk = QK4_0;
1013 static constexpr int qr = QR4_0;
1014 static constexpr int qi = QI4_0;
1015 static constexpr int bs = sizeof(block_q4_0);
1016};
1017
1018template<>
1019struct ggml_cuda_type_traits<GGML_TYPE_Q4_1> {
1020 static constexpr int qk = QK4_1;
1021 static constexpr int qr = QR4_1;
1022 static constexpr int qi = QI4_1;
1023 static constexpr int bs = sizeof(block_q4_1);
1024};
1025
1026template<>
1027struct ggml_cuda_type_traits<GGML_TYPE_Q5_0> {
1028 static constexpr int qk = QK5_0;
1029 static constexpr int qr = QR5_0;
1030 static constexpr int qi = QI5_0;
1031 static constexpr int bs = sizeof(block_q5_0);
1032};
1033
1034template<>
1035struct ggml_cuda_type_traits<GGML_TYPE_Q5_1> {
1036 static constexpr int qk = QK5_1;
1037 static constexpr int qr = QR5_1;
1038 static constexpr int qi = QI5_1;
1039 static constexpr int bs = sizeof(block_q5_1);
1040};
1041
1042template<>
1043struct ggml_cuda_type_traits<GGML_TYPE_Q8_0> {
1044 static constexpr int qk = QK8_0;
1045 static constexpr int qr = QR8_0;
1046 static constexpr int qi = QI8_0;
1047 static constexpr int bs = sizeof(block_q8_0);
1048};
1049
1050template<>
1051struct ggml_cuda_type_traits<GGML_TYPE_MXFP4> {
1052 static constexpr int qk = QK_MXFP4;
1053 static constexpr int qr = QR_MXFP4;
1054 static constexpr int qi = QI_MXFP4;
1055 static constexpr int bs = sizeof(block_mxfp4);
1056};
1057
1058template<>
1059struct ggml_cuda_type_traits<GGML_TYPE_NVFP4> {
1060 static constexpr int qk = QK_NVFP4;
1061 static constexpr int qr = QR_NVFP4;
1062 static constexpr int qi = QI_NVFP4;
1063 static constexpr int bs = sizeof(block_nvfp4);
1064};
1065
1066template<>
1067struct ggml_cuda_type_traits<GGML_TYPE_Q2_K> {
1068 static constexpr int qk = QK_K;
1069 static constexpr int qr = QR2_K;
1070 static constexpr int qi = QI2_K;
1071 static constexpr int bs = sizeof(block_q2_K);
1072};
1073
1074template<>
1075struct ggml_cuda_type_traits<GGML_TYPE_Q3_K> {
1076 static constexpr int qk = QK_K;
1077 static constexpr int qr = QR3_K;
1078 static constexpr int qi = QI3_K;
1079 static constexpr int bs = sizeof(block_q3_K);
1080};
1081
1082template<>
1083struct ggml_cuda_type_traits<GGML_TYPE_Q4_K> {
1084 static constexpr int qk = QK_K;
1085 static constexpr int qr = QR4_K;
1086 static constexpr int qi = QI4_K;
1087 static constexpr int bs = sizeof(block_q4_K);
1088};
1089
1090template<>
1091struct ggml_cuda_type_traits<GGML_TYPE_Q5_K> {
1092 static constexpr int qk = QK_K;
1093 static constexpr int qr = QR5_K;
1094 static constexpr int qi = QI5_K;
1095 static constexpr int bs = sizeof(block_q5_K);
1096};
1097
1098template<>
1099struct ggml_cuda_type_traits<GGML_TYPE_Q6_K> {
1100 static constexpr int qk = QK_K;
1101 static constexpr int qr = QR6_K;
1102 static constexpr int qi = QI6_K;
1103 static constexpr int bs = sizeof(block_q6_K);
1104};
1105
1106template<>
1107struct ggml_cuda_type_traits<GGML_TYPE_IQ2_XXS> {
1108 static constexpr int qk = QK_K;
1109 static constexpr int qr = QR2_XXS;
1110 static constexpr int qi = QI2_XXS;
1111 static constexpr int bs = sizeof(block_iq2_xxs);
1112};
1113
1114template<>
1115struct ggml_cuda_type_traits<GGML_TYPE_IQ2_XS> {
1116 static constexpr int qk = QK_K;
1117 static constexpr int qr = QR2_XS;
1118 static constexpr int qi = QI2_XS;
1119 static constexpr int bs = sizeof(block_iq2_xs);
1120};
1121
1122template<>
1123struct ggml_cuda_type_traits<GGML_TYPE_IQ2_S> {
1124 static constexpr int qk = QK_K;
1125 static constexpr int qr = QR2_S;
1126 static constexpr int qi = QI2_S;
1127 static constexpr int bs = sizeof(block_iq2_s);
1128};
1129
1130template<>
1131struct ggml_cuda_type_traits<GGML_TYPE_IQ3_XXS> {
1132 static constexpr int qk = QK_K;
1133 static constexpr int qr = QR3_XXS;
1134 static constexpr int qi = QI3_XXS;
1135 static constexpr int bs = sizeof(block_iq3_xxs);
1136};
1137
1138template<>
1139struct ggml_cuda_type_traits<GGML_TYPE_IQ1_S> {
1140 static constexpr int qk = QK_K;
1141 static constexpr int qr = QR1_S;
1142 static constexpr int qi = QI1_S;
1143 static constexpr int bs = sizeof(block_iq1_s);
1144};
1145
1146template<>
1147struct ggml_cuda_type_traits<GGML_TYPE_IQ1_M> {
1148 static constexpr int qk = QK_K;
1149 static constexpr int qr = QR1_M;
1150 static constexpr int qi = QI1_M;
1151 static constexpr int bs = sizeof(block_iq1_m);
1152};
1153
1154template<>
1155struct ggml_cuda_type_traits<GGML_TYPE_IQ4_NL> {
1156 static constexpr int qk = QK4_NL;
1157 static constexpr int qr = QR4_NL;
1158 static constexpr int qi = QI4_NL;
1159 static constexpr int bs = sizeof(block_iq4_nl);
1160};
1161
1162template<>
1163struct ggml_cuda_type_traits<GGML_TYPE_IQ4_XS> {
1164 static constexpr int qk = QK_K;
1165 static constexpr int qr = QR4_XS;
1166 static constexpr int qi = QI4_XS;
1167 static constexpr int bs = sizeof(block_iq4_xs);
1168};
1169
1170template<>
1171struct ggml_cuda_type_traits<GGML_TYPE_IQ3_S> {
1172 static constexpr int qk = QK_K;
1173 static constexpr int qr = QR3_S;
1174 static constexpr int qi = QI3_S;
1175 static constexpr int bs = sizeof(block_iq3_s);
1176};
1177
1178//////////////////////
1179
1180struct ggml_cuda_device_info {
1181 int device_count; // number of (possibly virtual) devices exposed to the rest of ggml
1182 int physical_device_count; // number of physical CUDA devices actually present
1183
1184 struct cuda_device_info {
1185 int cc; // compute capability
1186 int nsm; // number of streaming multiprocessors
1187 size_t smpb; // max. shared memory per block
1188 size_t smpbo; // max. shared memory per block (with opt-in)
1189 bool integrated; // Device is integrated as opposed to discrete
1190 bool vmm; // virtual memory support
1191 size_t vmm_granularity; // granularity of virtual memory
1192 size_t total_vram;
1193 int warp_size; // Number of threads in a dispatch
1194 bool supports_cooperative_launch; // whether cooperative launch is supported
1195 int physical_device; // backing physical CUDA device for this (virtual) device
1196 int physical_share_count; // number of (virtual) devices sharing this device's physical GPU
1197 int virtual_index; // index of this (virtual) device among those sharing its physical GPU
1198 };
1199
1200 cuda_device_info devices[GGML_CUDA_MAX_DEVICES] = {};
1201
1202 std::array<float, GGML_CUDA_MAX_DEVICES> default_tensor_split = {};
1203};
1204
1205const ggml_cuda_device_info & ggml_cuda_info();
1206
1207void ggml_cuda_set_device(int device);
1208int ggml_cuda_get_device();
1209
1210struct ggml_cuda_pool {
1211 virtual ~ggml_cuda_pool() = default;
1212
1213 virtual void * alloc(size_t size, size_t * actual_size) = 0;
1214 virtual void free(void * ptr, size_t size) = 0;
1215};
1216
1217template<typename T>
1218struct ggml_cuda_pool_alloc {
1219 ggml_cuda_pool * pool = nullptr;
1220 T * ptr = nullptr;
1221 size_t actual_size = 0;
1222
1223 ggml_cuda_pool_alloc() = default;
1224
1225 explicit ggml_cuda_pool_alloc(ggml_cuda_pool & pool) : pool(&pool) {
1226 }
1227
1228 ggml_cuda_pool_alloc(ggml_cuda_pool & pool, size_t size) : pool(&pool) {
1229 alloc(size);
1230 }
1231
1232 ~ggml_cuda_pool_alloc() {
1233 if (ptr != nullptr) {
1234 pool->free(ptr, actual_size);
1235 }
1236 }
1237
1238 // size is in number of elements
1239 T * alloc(size_t size) {
1240 GGML_ASSERT(pool != nullptr);
1241 GGML_ASSERT(ptr == nullptr);
1242 ptr = (T *) pool->alloc(size * sizeof(T), &this->actual_size);
1243 return ptr;
1244 }
1245
1246 T * alloc(ggml_cuda_pool & pool, size_t size) {
1247 this->pool = &pool;
1248 return alloc(size);
1249 }
1250
1251 T * get() {
1252 return ptr;
1253 }
1254
1255 ggml_cuda_pool_alloc(const ggml_cuda_pool_alloc &) = delete;
1256 ggml_cuda_pool_alloc(ggml_cuda_pool_alloc &&) = delete;
1257 ggml_cuda_pool_alloc& operator=(const ggml_cuda_pool_alloc &) = delete;
1258 ggml_cuda_pool_alloc& operator=(ggml_cuda_pool_alloc &&) = delete;
1259};
1260
1261
1262// backend interface
1263
1264struct ggml_tensor_extra_gpu {
1265 void * data_device[GGML_CUDA_MAX_DEVICES]; // 1 pointer for each device for split tensors
1266 cudaEvent_t events[GGML_CUDA_MAX_DEVICES][GGML_CUDA_MAX_STREAMS]; // events for synchronizing multiple GPUs
1267};
1268
1269
1270#if (defined(GGML_CUDA_USE_GRAPHS) || defined(GGML_HIP_GRAPHS)) || defined(GGML_MUSA_GRAPHS)
1271#define USE_CUDA_GRAPH
1272#endif
1273
1274struct ggml_cuda_graph {
1275#ifdef USE_CUDA_GRAPH
1276 ~ggml_cuda_graph() {
1277 for (cudaGraphExec_t instance : instances) {
1278 CUDA_CHECK(cudaGraphExecDestroy(instance));
1279 }
1280 }
1281 // the ggml graph is captured as a series of CUDA graphs, so the GPU can run one chunk while the next is enqueued
1282 std::vector<cudaGraphExec_t> instances;
1283 size_t num_nodes = 0;
1284 std::vector<cudaGraphNode_t> nodes;
1285 bool disable_due_to_gpu_arch = false;
1286 bool warmup_complete = false;
1287 uint64_t uid = 0;
1288 int64_t last_used_time = 0;
1289 struct node_properties {
1290 ggml_tensor node;
1291 void * node_src_data_ptrs[GGML_MAX_SRC];
1292 int64_t node_src_ne[GGML_MAX_SRC][GGML_MAX_DIMS];
1293 size_t node_src_nb[GGML_MAX_SRC][GGML_MAX_DIMS];
1294 };
1295 std::vector<node_properties> node_props;
1296
1297 bool is_enabled() const {
1298 static const bool disable_cuda_graphs_due_to_env = (getenv("GGML_CUDA_DISABLE_GRAPHS") != nullptr);
1299 return !(disable_due_to_gpu_arch || disable_cuda_graphs_due_to_env);
1300 }
1301#endif
1302};
1303
1304struct ggml_cuda_concurrent_event {
1305 std::vector<cudaEvent_t> join_events;
1306 cudaEvent_t fork_event = nullptr;
1307
1308 int n_streams = 0;
1309 std::unordered_map<const ggml_tensor *, int> stream_mapping;
1310
1311 // Original order of nodes in this concurrent region (before interleaving)
1312 // Used to restore grouping for fusion within streams
1313 std::vector<const ggml_tensor *> original_order;
1314
1315 const ggml_tensor * join_node;
1316
1317 ggml_cuda_concurrent_event() = default;
1318
1319 ggml_cuda_concurrent_event(const ggml_cuda_concurrent_event &) = delete;
1320 ggml_cuda_concurrent_event & operator=(const ggml_cuda_concurrent_event &) = delete;
1321
1322 explicit ggml_cuda_concurrent_event(int n_streams) : n_streams(n_streams) {
1323 join_events.resize(n_streams);
1324
1325 for (size_t i = 0; i < join_events.size(); ++i) {
1326 CUDA_CHECK(cudaEventCreateWithFlags(&join_events[i], cudaEventDisableTiming));
1327 }
1328
1329 CUDA_CHECK(cudaEventCreateWithFlags(&fork_event, cudaEventDisableTiming));
1330 }
1331
1332 ggml_cuda_concurrent_event(ggml_cuda_concurrent_event && other) noexcept
1333 : join_events(std::move(other.join_events))
1334 , fork_event(other.fork_event)
1335 , n_streams(other.n_streams)
1336 , stream_mapping(std::move(other.stream_mapping))
1337 , original_order(std::move(other.original_order))
1338 , join_node(other.join_node) {
1339 other.fork_event = nullptr;
1340 }
1341
1342 // 1. check if any branches write to overlapping memory ranges (except the join node)
1343 // 2. check whether all srcs are either within the branch or outside the nodes covered by ggml_cuda_concurrent_event
1344 // we assume all nodes have the same buffer
1345 bool is_valid() const {
1346 std::vector<std::vector<std::pair<int64_t, int64_t>>> write_ranges;
1347 write_ranges.resize(n_streams);
1348
1349 // get join_node's memory range to exclude from overlap checking.
1350 // multiple nodes can use join_node's buffer; we synchronize on the join node.
1351 const ggml_tensor * join_t = join_node->view_src ? join_node->view_src : join_node;
1352 const int64_t join_start = (int64_t) join_t->data;
1353 const int64_t join_end = join_start + ggml_nbytes(join_t);
1354
1355 for (const auto & [tensor, stream] : stream_mapping) {
1356 const ggml_tensor * t = tensor->view_src ? tensor->view_src : tensor;
1357 const int64_t t_start = (int64_t) t->data;
1358 const int64_t t_end = t_start + ggml_nbytes(t);
1359
1360 // skip tensors that overlap with join_node's buffer.
1361 if ((t_start <= join_start && join_start < t_end) || (join_start <= t_start && t_start < join_end)) {
1362 continue;
1363 }
1364
1365 // concurrent streams begin from 1
1366 write_ranges[stream - 1].emplace_back(t_start, t_end);
1367 }
1368
1369 for (int i = 0; i < n_streams; ++i) {
1370 // sorts first by start then by end of write range
1371 std::sort(write_ranges[i].begin(), write_ranges[i].end());
1372 }
1373
1374 bool writes_overlap = false;
1375 bool dependent_srcs = false;
1376 for (const auto & [tensor, stream] : stream_mapping) {
1377 const ggml_tensor * t = tensor->view_src ? tensor->view_src : tensor;
1378 const int64_t t_start = (int64_t) t->data;
1379 const int64_t t_end = t_start + ggml_nbytes(t);
1380
1381 // skip tensors that overlap with join_node's buffer
1382 if ((t_start <= join_start && join_start < t_end) || (join_start <= t_start && t_start < join_end)) {
1383 continue;
1384 }
1385
1386 // check if this buffer's write data overlaps with another stream's
1387 std::pair<int64_t, int64_t> data_range = std::make_pair(t_start, t_end);
1388 for (int i = 0; i < n_streams; ++i) {
1389 if (i == stream - 1) {
1390 continue;
1391 }
1392 auto it = std::lower_bound(write_ranges[i].begin(), write_ranges[i].end(), data_range);
1393
1394 if (it != write_ranges[i].end()) {
1395 const std::pair<int64_t, int64_t> & other = *it;
1396
1397 // std::lower_bound returns the first element where other >= data_range (lexicographically).
1398 // This guarantees other.first >= data_range.first.
1399 // Therefore, overlap occurs iff other.first < data_range.second
1400 // (i.e., the other range starts before this range ends).
1401 if (other.first < data_range.second) {
1402 GGML_LOG_DEBUG("Writes overlap for %s", tensor->name);
1403 writes_overlap = true;
1404 break;
1405 }
1406 }
1407 }
1408
1409 //check if all srcs are either in branch or don't have a branch
1410 for (int i = 0; i < GGML_MAX_SRC; ++i) {
1411 if (!tensor->src[i]) {
1412 continue;
1413 }
1414
1415 auto it = stream_mapping.find(tensor->src[i]);
1416
1417 if (it == stream_mapping.end()) {
1418 continue;
1419 }
1420
1421 if (it->second != stream) {
1422 dependent_srcs = true;
1423 break;
1424 }
1425 }
1426
1427 if (dependent_srcs || writes_overlap) {
1428 break;
1429 }
1430 }
1431
1432 return !writes_overlap && !dependent_srcs;
1433 }
1434
1435 ~ggml_cuda_concurrent_event() {
1436 if (fork_event != nullptr) {
1437 CUDA_CHECK(cudaEventDestroy(fork_event));
1438 }
1439 for (cudaEvent_t e : join_events) {
1440 if (e != nullptr) {
1441 CUDA_CHECK(cudaEventDestroy(e));
1442 }
1443 }
1444 }
1445};
1446
1447struct ggml_cuda_stream_context {
1448 std::unordered_map<const ggml_tensor *, ggml_cuda_concurrent_event> concurrent_events;
1449
1450 void reset() {
1451 concurrent_events.clear();
1452 }
1453};
1454
1455struct ggml_backend_cuda_context {
1456 int device;
1457 std::string name;
1458 cudaEvent_t copy_event = nullptr;
1459
1460 cudaStream_t streams[GGML_CUDA_MAX_DEVICES][GGML_CUDA_MAX_STREAMS] = {};
1461 cublasHandle_t cublas_handles[GGML_CUDA_MAX_DEVICES][GGML_CUDA_MAX_STREAMS] = {};
1462 void * cublas_workspaces[GGML_CUDA_MAX_DEVICES][GGML_CUDA_MAX_STREAMS] = {};
1463 size_t cublas_workspace_sizes[GGML_CUDA_MAX_DEVICES] = {};
1464
1465 int curr_stream_no = 0;
1466
1467#ifdef USE_CUDA_GRAPH
1468 // Map from first_node_ptr to cuda_graph - allows multiple graphs per context
1469 // when the computation is split across CPU/GPU (e.g., with --n-cpu-moe)
1470 std::unordered_map<const void *, std::unique_ptr<ggml_cuda_graph>> cuda_graphs;
1471
1472 int64_t next_graph_eviction_time = 0;
1473 int64_t last_graph_use_time = 0;
1474
1475 ggml_cuda_graph * cuda_graph(const void * first_node_ptr, int64_t time_now = ggml_time_us()) {
1476 // Give all cached graphs 10s to be reused after an idle period, without updating each graph.
1477 if (!cuda_graphs.empty() && time_now - last_graph_use_time >= 10'000'000) {
1478 next_graph_eviction_time = time_now + 10'000'000;
1479 }
1480 last_graph_use_time = time_now;
1481
1482 // Sweep every 5s during active use, evicting graphs unused for at least 10s.
1483 if (time_now >= next_graph_eviction_time) {
1484 next_graph_eviction_time = time_now + 5'000'000;
1485 for (auto it = cuda_graphs.begin(); it != cuda_graphs.end(); ) {
1486 if (it->first != first_node_ptr && time_now - it->second->last_used_time >= 10'000'000) {
1487 it = cuda_graphs.erase(it);
1488 } else {
1489 ++it;
1490 }
1491 }
1492 }
1493
1494 auto it = cuda_graphs.find(first_node_ptr);
1495 if (it == cuda_graphs.end()) {
1496 it = cuda_graphs.emplace(first_node_ptr, std::make_unique<ggml_cuda_graph>()).first;
1497 }
1498 it->second->last_used_time = time_now;
1499 return it->second.get();
1500 }
1501
1502 // Check if any CUDA graph is enabled for this context (used by kernels that need to know
1503 // if graphs are in use without having access to the specific graph key)
1504 bool any_cuda_graph_enabled() const {
1505 for (const auto & [key, graph] : cuda_graphs) {
1506 if (graph && graph->is_enabled()) {
1507 return true;
1508 }
1509 }
1510 return false;
1511 }
1512
1513 // Check if any CUDA graph has an instance for this context
1514 bool any_cuda_graph_has_instance() const {
1515 for (const auto & [key, graph] : cuda_graphs) {
1516 if (graph && !graph->instances.empty()) {
1517 return true;
1518 }
1519 }
1520 return false;
1521 }
1522#endif // USE_CUDA_GRAPH
1523
1524 explicit ggml_backend_cuda_context(int device) :
1525 device(device),
1526 name(GGML_CUDA_NAME + std::to_string(device)) {
1527 }
1528
1529 ggml_cuda_stream_context concurrent_stream_context;
1530
1531 ~ggml_backend_cuda_context();
1532
1533 cudaStream_t stream(int device, int stream) {
1534 if (streams[device][stream] == nullptr) {
1535 ggml_cuda_set_device(device);
1536 CUDA_CHECK(cudaStreamCreateWithFlags(&streams[device][stream], cudaStreamNonBlocking));
1537 }
1538 return streams[device][stream];
1539 }
1540
1541 cudaStream_t stream() { return stream(device, curr_stream_no); }
1542
1543 ggml_cuda_stream_context & stream_context() { return concurrent_stream_context; }
1544
1545 cublasHandle_t cublas_handle() {
1546 if (cublas_handles[device][curr_stream_no] == nullptr) {
1547 ggml_cuda_set_device(device);
1548 CUBLAS_CHECK(cublasCreate(&cublas_handles[device][curr_stream_no]));
1549 CUBLAS_CHECK(cublasSetMathMode(cublas_handles[device][curr_stream_no], CUBLAS_TF32_TENSOR_OP_MATH));
1550 CUBLAS_CHECK(cublasSetStream(cublas_handles[device][curr_stream_no], stream()));
1551#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && (CUBLAS_VER_MAJOR > 11 || (CUBLAS_VER_MAJOR == 11 && CUBLAS_VER_MINOR >= 2))
1552 if (cublas_workspace_sizes[device] == 0) {
1553 const int cc = ggml_cuda_info().devices[device].cc;
1554 cublas_workspace_sizes[device] = (cc >= GGML_CUDA_CC_HOPPER) ? 32 * 1024 * 1024 : 4 * 1024 * 1024;
1555 }
1556 CUDA_CHECK(cudaMalloc(&cublas_workspaces[device][curr_stream_no], cublas_workspace_sizes[device]));
1557 CUBLAS_CHECK(cublasSetWorkspace(cublas_handles[device][curr_stream_no], cublas_workspaces[device][curr_stream_no], cublas_workspace_sizes[device]));
1558#endif
1559 }
1560 return cublas_handles[device][curr_stream_no];
1561 }
1562
1563 // pool
1564 std::unique_ptr<ggml_cuda_pool> pools[GGML_CUDA_MAX_DEVICES][GGML_CUDA_MAX_STREAMS];
1565
1566 static std::unique_ptr<ggml_cuda_pool> new_pool_for_device(ggml_backend_cuda_context & ctx, int device, int stream_no);
1567
1568 ggml_cuda_pool & pool(int device) {
1569 if (pools[device][curr_stream_no] == nullptr) {
1570 pools[device][curr_stream_no] = new_pool_for_device(*this, device, curr_stream_no);
1571 }
1572 return *pools[device][curr_stream_no];
1573 }
1574
1575 ggml_cuda_pool & pool() {
1576 return pool(device);
1577 }
1578};
1579
1580struct ggml_cuda_mm_fusion_args_host {
1581 const ggml_tensor * x_bias = nullptr;
1582 const ggml_tensor * gate = nullptr;
1583 const ggml_tensor * gate_bias = nullptr;
1584 const ggml_tensor * x_scale = nullptr;
1585 const ggml_tensor * gate_scale = nullptr;
1586 ggml_glu_op glu_op;
1587 float glu_limit = 0.0f;
1588 const ggml_tensor * shared_up = nullptr;
1589 const ggml_tensor * shared_gate = nullptr;
1590 ggml_tensor * shared_dst = nullptr;
1591};
1592struct ggml_cuda_mm_fusion_args_device {
1593 const void * x_bias = nullptr;
1594 const void * gate = nullptr;
1595 const void * gate_bias = nullptr;
1596 const void * x_scale = nullptr;
1597 const void * gate_scale = nullptr;
1598 ggml_glu_op glu_op;
1599 float glu_limit = 0.0f;
1600 const void * shared_up = nullptr;
1601 const void * shared_gate = nullptr;
1602 float * shared_dst = nullptr;
1603 uint32_t shared_stride_col_dst = 0;
1604};
1605
1606struct ggml_cuda_kernel_launch_params {
1607 dim3 block_nums;
1608 dim3 block_dims;
1609 size_t shmem;
1610 cudaStream_t stream;
1611
1612 // size_t shmem
1613 ggml_cuda_kernel_launch_params(const dim3& block_nums_, const dim3& block_dims_, const size_t shmem_, const cudaStream_t stream_)
1614 : block_nums(block_nums_), block_dims(block_dims_), shmem(shmem_), stream(stream_) {}
1615
1616 // Some call sites pass ints instead of the required size_t. This 2nd constructor casts int->size_t to avoid these -Wnarrowing warnings.
1617 ggml_cuda_kernel_launch_params(const dim3& block_nums_, const dim3& block_dims_, const int shmem_, const cudaStream_t stream_)
1618 : block_nums(block_nums_), block_dims(block_dims_), shmem((size_t)shmem_), stream(stream_) {}
1619};
1620
1621#if defined(GGML_CUDA_USE_PDL)
1622struct ggml_cuda_pdl_config {
1623 cudaLaunchAttribute attr;
1624 cudaLaunchConfig_t cfg;
1625
1626 ggml_cuda_pdl_config(const ggml_cuda_kernel_launch_params & params) {
1627 attr.id = cudaLaunchAttributeProgrammaticStreamSerialization;
1628 attr.val.programmaticStreamSerializationAllowed = 1;
1629
1630 cfg = {};
1631 cfg.gridDim = params.block_nums;
1632 cfg.blockDim = params.block_dims;
1633 cfg.dynamicSmemBytes = params.shmem;
1634 cfg.stream = params.stream;
1635 cfg.attrs = &attr;
1636 cfg.numAttrs = 1;
1637 }
1638
1639 // Delete due to &attr
1640 ggml_cuda_pdl_config(const ggml_cuda_pdl_config&) = delete;
1641 ggml_cuda_pdl_config& operator=(const ggml_cuda_pdl_config&) = delete;
1642 ggml_cuda_pdl_config& operator=(ggml_cuda_pdl_config&&) = delete;
1643
1644};
1645
1646static bool ggml_cuda_kernel_can_use_pdl(const void * kernel) {
1647 const int device = ggml_cuda_get_device();
1648
1649 struct cache_key {
1650 int device;
1651 const void * kernel;
1652
1653 bool operator==(const cache_key & other) const { return device == other.device && kernel == other.kernel; }
1654 };
1655
1656 struct cache_key_hash {
1657 // MurmurHash3 mixing function for better hash distribution (vs. just std::hash which in some implementations simply returns the identity)
1658 static size_t hash_mix(size_t x) {
1659 std::uint64_t y = x;
1660 const std::uint64_t m = 0xe9846af9b1a615d;
1661
1662 y ^= y >> 32;
1663 y *= m;
1664 y ^= y >> 32;
1665 y *= m;
1666 y ^= y >> 28;
1667
1668 return static_cast<size_t>(y);
1669 }
1670
1671 size_t operator()(const cache_key & key) const {
1672 // Use a nonzero seed to avoid mapping all-zero keys to zero
1673 size_t h = 42;
1674 h = hash_mix(h + key.device);
1675 h = hash_mix(h + reinterpret_cast<size_t>(key.kernel));
1676 return h;
1677 }
1678 };
1679
1680 static std::mutex cache_mutex;
1681 static std::unordered_map<cache_key, bool, cache_key_hash> cache;
1682
1683 const cache_key key = { device, kernel };
1684 std::lock_guard<std::mutex> lock(cache_mutex);
1685 const auto it = cache.find(key);
1686 if (it != cache.end()) {
1687 return it->second;
1688 }
1689
1690 cudaFuncAttributes attr = {};
1691 CUDA_CHECK(cudaFuncGetAttributes(&attr, kernel));
1692
1693 // PDL device-side primitives are emitted only for PTX versions >= 90.
1694 // We have to guard on a loaded kernel's PTX version so a kernel forward-JIT'ed
1695 // from pre-Hopper PTX to a Hopper-or-newer GPU does not opt into PDL.
1696 const bool can_use_pdl = attr.ptxVersion >= 90;
1697 cache.emplace(key, can_use_pdl);
1698 return can_use_pdl;
1699}
1700
1701#endif //defined(GGML_CUDA_USE_PDL)
1702
1703// PDL and __restrict__ need to be mutually exclusive, see https://github.com/ggml-org/llama.cpp/pull/24030
1704# if (defined(GGML_CUDA_USE_PDL) && __CUDA_ARCH__ >= GGML_CUDA_CC_HOPPER)
1705# define GGML_CUDA_RESTRICT
1706# else
1707# define GGML_CUDA_RESTRICT __restrict__
1708# endif // defined(GGML_CUDA_USE_PDL) && __CUDA_ARCH__ >= GGML_CUDA_CC_HOPPER
1709
1710template<typename Kernel, typename... Args>
1711static __inline__ void ggml_cuda_kernel_launch(Kernel kernel, const ggml_cuda_kernel_launch_params & launch_params, Args&&... args) {
1712#if defined(GGML_CUDA_USE_PDL)
1713
1714 static const bool env_pdl_enabled = []() {
1715 const char * env = getenv("GGML_CUDA_PDL");
1716 return env == nullptr || std::atoi(env) != 0;
1717 }();
1718
1719 if (env_pdl_enabled && ggml_cuda_kernel_can_use_pdl(reinterpret_cast<const void *>(kernel))) {
1720 auto pdl_cfg = ggml_cuda_pdl_config(launch_params);
1721
1722 CUDA_CHECK(cudaLaunchKernelEx(&pdl_cfg.cfg, kernel, std::forward<Args>(args)... ));
1723 return;
1724 }
1725#endif //defined(GGML_CUDA_USE_PDL)
1726
1727 kernel<<<launch_params.block_nums, launch_params.block_dims, launch_params.shmem, launch_params.stream>>>(std::forward<Args>(args)... );
1728 CUDA_CHECK(cudaGetLastError());
1729}