common.cuh 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. #pragma once
  2. #include "ggml.h"
  3. #include "ggml-cuda.h"
  4. #include <memory>
  5. #if defined(GGML_USE_HIPBLAS)
  6. #define GGML_COMMON_DECL_HIP
  7. #define GGML_COMMON_IMPL_HIP
  8. #else
  9. #define GGML_COMMON_DECL_CUDA
  10. #define GGML_COMMON_IMPL_CUDA
  11. #endif
  12. #include "ggml-common.h"
  13. #include <cstdio>
  14. #include <array>
  15. #include <cassert>
  16. #include <cfloat>
  17. #include <string>
  18. #include <vector>
  19. #if defined(GGML_USE_HIPBLAS)
  20. #include <hip/hip_runtime.h>
  21. #include <hipblas/hipblas.h>
  22. #include <hip/hip_fp16.h>
  23. #ifdef __HIP_PLATFORM_AMD__
  24. // for rocblas_initialize()
  25. #include "rocblas/rocblas.h"
  26. #endif // __HIP_PLATFORM_AMD__
  27. #define CUBLAS_COMPUTE_16F HIPBLAS_R_16F
  28. #define CUBLAS_COMPUTE_32F HIPBLAS_R_32F
  29. #define CUBLAS_COMPUTE_32F_FAST_16F HIPBLAS_R_32F
  30. #define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT
  31. #define CUBLAS_GEMM_DEFAULT_TENSOR_OP HIPBLAS_GEMM_DEFAULT
  32. #define CUBLAS_OP_N HIPBLAS_OP_N
  33. #define CUBLAS_OP_T HIPBLAS_OP_T
  34. #define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS
  35. #define CUBLAS_TF32_TENSOR_OP_MATH 0
  36. #define CUDA_R_16F HIPBLAS_R_16F
  37. #define CUDA_R_32F HIPBLAS_R_32F
  38. #define __shfl_xor_sync(mask, var, laneMask, width) __shfl_xor(var, laneMask, width)
  39. #define cublasComputeType_t hipblasDatatype_t //deprecated, new hipblasComputeType_t not in 5.6
  40. #define cublasCreate hipblasCreate
  41. #define cublasDestroy hipblasDestroy
  42. #define cublasGemmEx hipblasGemmEx
  43. #define cublasGemmBatchedEx hipblasGemmBatchedEx
  44. #define cublasGemmStridedBatchedEx hipblasGemmStridedBatchedEx
  45. #define cublasHandle_t hipblasHandle_t
  46. #define cublasSetMathMode(handle, mode) CUBLAS_STATUS_SUCCESS
  47. #define cublasSetStream hipblasSetStream
  48. #define cublasSgemm hipblasSgemm
  49. #define cublasStatus_t hipblasStatus_t
  50. #define cudaDataType_t hipblasDatatype_t //deprecated, new hipblasDatatype not in 5.6
  51. #define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer
  52. #define cudaDeviceDisablePeerAccess hipDeviceDisablePeerAccess
  53. #define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess
  54. #define cudaDeviceProp hipDeviceProp_t
  55. #define cudaDeviceSynchronize hipDeviceSynchronize
  56. #define cudaError_t hipError_t
  57. #define cudaErrorPeerAccessAlreadyEnabled hipErrorPeerAccessAlreadyEnabled
  58. #define cudaErrorPeerAccessNotEnabled hipErrorPeerAccessNotEnabled
  59. #define cudaEventCreateWithFlags hipEventCreateWithFlags
  60. #define cudaEventDisableTiming hipEventDisableTiming
  61. #define cudaEventRecord hipEventRecord
  62. #define cudaEventSynchronize hipEventSynchronize
  63. #define cudaEvent_t hipEvent_t
  64. #define cudaEventDestroy hipEventDestroy
  65. #define cudaFree hipFree
  66. #define cudaFreeHost hipHostFree
  67. #define cudaGetDevice hipGetDevice
  68. #define cudaGetDeviceCount hipGetDeviceCount
  69. #define cudaGetDeviceProperties hipGetDeviceProperties
  70. #define cudaGetErrorString hipGetErrorString
  71. #define cudaGetLastError hipGetLastError
  72. #define cudaHostRegister hipHostRegister
  73. #define cudaHostRegisterPortable hipHostRegisterPortable
  74. #define cudaHostRegisterReadOnly hipHostRegisterReadOnly
  75. #define cudaHostUnregister hipHostUnregister
  76. #define cudaLaunchHostFunc hipLaunchHostFunc
  77. #ifdef GGML_HIP_UMA
  78. #define cudaMalloc hipMallocManaged
  79. #define cudaMallocHost(ptr, size) hipHostMalloc(ptr, size)
  80. #else
  81. #define cudaMalloc hipMalloc
  82. #define cudaMallocHost(ptr, size) hipHostMalloc(ptr, size, hipHostMallocDefault)
  83. #endif
  84. #define cudaMemcpy hipMemcpy
  85. #define cudaMemcpyAsync hipMemcpyAsync
  86. #define cudaMemcpyPeerAsync hipMemcpyPeerAsync
  87. #define cudaMemcpy2DAsync hipMemcpy2DAsync
  88. #define cudaMemcpyDeviceToDevice hipMemcpyDeviceToDevice
  89. #define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost
  90. #define cudaMemcpyHostToDevice hipMemcpyHostToDevice
  91. #define cudaMemcpyKind hipMemcpyKind
  92. #define cudaMemset hipMemset
  93. #define cudaMemsetAsync hipMemsetAsync
  94. #define cudaMemGetInfo hipMemGetInfo
  95. #define cudaOccupancyMaxPotentialBlockSize hipOccupancyMaxPotentialBlockSize
  96. #define cudaSetDevice hipSetDevice
  97. #define cudaStreamCreateWithFlags hipStreamCreateWithFlags
  98. #define cudaStreamDestroy hipStreamDestroy
  99. #define cudaStreamFireAndForget hipStreamFireAndForget
  100. #define cudaStreamNonBlocking hipStreamNonBlocking
  101. #define cudaStreamPerThread hipStreamPerThread
  102. #define cudaStreamSynchronize hipStreamSynchronize
  103. #define cudaStreamWaitEvent(stream, event, flags) hipStreamWaitEvent(stream, event, flags)
  104. #define cudaStream_t hipStream_t
  105. #define cudaSuccess hipSuccess
  106. #define __trap abort
  107. #define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS
  108. #define CUBLAS_STATUS_NOT_INITIALIZED HIPBLAS_STATUS_NOT_INITIALIZED
  109. #define CUBLAS_STATUS_ALLOC_FAILED HIPBLAS_STATUS_ALLOC_FAILED
  110. #define CUBLAS_STATUS_INVALID_VALUE HIPBLAS_STATUS_INVALID_VALUE
  111. #define CUBLAS_STATUS_ARCH_MISMATCH HIPBLAS_STATUS_ARCH_MISMATCH
  112. #define CUBLAS_STATUS_MAPPING_ERROR HIPBLAS_STATUS_MAPPING_ERROR
  113. #define CUBLAS_STATUS_EXECUTION_FAILED HIPBLAS_STATUS_EXECUTION_FAILED
  114. #define CUBLAS_STATUS_INTERNAL_ERROR HIPBLAS_STATUS_INTERNAL_ERROR
  115. #define CUBLAS_STATUS_NOT_SUPPORTED HIPBLAS_STATUS_NOT_SUPPORTED
  116. #else
  117. #include <cuda_runtime.h>
  118. #include <cuda.h>
  119. #include <cublas_v2.h>
  120. #include <cuda_fp16.h>
  121. #if CUDART_VERSION < 11020
  122. #define CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED
  123. #define CUBLAS_TF32_TENSOR_OP_MATH CUBLAS_TENSOR_OP_MATH
  124. #define CUBLAS_COMPUTE_16F CUDA_R_16F
  125. #define CUBLAS_COMPUTE_32F CUDA_R_32F
  126. #define cublasComputeType_t cudaDataType_t
  127. #endif // CUDART_VERSION < 11020
  128. #endif // defined(GGML_USE_HIPBLAS)
  129. #define STRINGIZE_IMPL(...) #__VA_ARGS__
  130. #define STRINGIZE(...) STRINGIZE_IMPL(__VA_ARGS__)
  131. #define WARP_SIZE 32
  132. #define CUDART_HMAX 11070 // CUDA 11.7, min. ver. for which __hmax and __hmax2 are known to work (may be higher than needed)
  133. #define CUDART_HMASK 12000 // CUDA 12.0, min. ver. for half2 -> uint mask comparisons
  134. #define CC_PASCAL 600
  135. #define MIN_CC_DP4A 610 // minimum compute capability for __dp4a, an intrinsic for byte-wise dot products
  136. #define CC_VOLTA 700
  137. #define CC_AMPERE 800
  138. #define CC_OFFSET_AMD 1000000
  139. #define CC_RDNA1 (CC_OFFSET_AMD + 1010)
  140. #define CC_RDNA2 (CC_OFFSET_AMD + 1030)
  141. #define CC_RDNA3 (CC_OFFSET_AMD + 1100)
  142. // define this if you want to always fallback to MMQ kernels and not use cuBLAS for matrix multiplication
  143. // on modern hardware, using cuBLAS is recommended as it utilizes F16 tensor cores which are very performant
  144. // for large computational tasks. the drawback is that this requires some extra amount of VRAM:
  145. // - 7B quantum model: +100-200 MB
  146. // - 13B quantum model: +200-400 MB
  147. //
  148. //#define GGML_CUDA_FORCE_MMQ
  149. // TODO: improve this to be correct for more hardware
  150. // for example, currently fails for GeForce GTX 1660 which is TURING arch (> VOLTA) but does not have tensor cores
  151. #if !defined(GGML_CUDA_FORCE_MMQ)
  152. #define CUDA_USE_TENSOR_CORES
  153. #endif
  154. #define MMVQ_MAX_BATCH_SIZE 8 // max batch size to use MMVQ kernels
  155. #define MMQ_MAX_BATCH_SIZE 32 // max batch size to use MMQ kernels when tensor cores are available
  156. #define MATRIX_ROW_PADDING 512 // last row of quant. matrices is a multiple of this to avoid out-of-bounds memory accesses
  157. #if defined(_MSC_VER)
  158. #pragma warning(disable: 4244 4267) // possible loss of data
  159. #endif
  160. #define GGML_CUDA_MAX_STREAMS 8
  161. [[noreturn]]
  162. void ggml_cuda_error(const char * stmt, const char * func, const char * file, int line, const char * msg);
  163. #define CUDA_CHECK_GEN(err, success, error_fn) \
  164. do { \
  165. auto err_ = (err); \
  166. if (err_ != (success)) { \
  167. ggml_cuda_error(#err, __func__, __FILE__, __LINE__, error_fn(err_)); \
  168. } \
  169. } while (0)
  170. #define CUDA_CHECK(err) CUDA_CHECK_GEN(err, cudaSuccess, cudaGetErrorString)
  171. #if CUDART_VERSION >= 12000
  172. static const char * cublas_get_error_str(const cublasStatus_t err) {
  173. return cublasGetStatusString(err);
  174. }
  175. #else
  176. static const char * cublas_get_error_str(const cublasStatus_t err) {
  177. switch (err) {
  178. case CUBLAS_STATUS_SUCCESS: return "CUBLAS_STATUS_SUCCESS";
  179. case CUBLAS_STATUS_NOT_INITIALIZED: return "CUBLAS_STATUS_NOT_INITIALIZED";
  180. case CUBLAS_STATUS_ALLOC_FAILED: return "CUBLAS_STATUS_ALLOC_FAILED";
  181. case CUBLAS_STATUS_INVALID_VALUE: return "CUBLAS_STATUS_INVALID_VALUE";
  182. case CUBLAS_STATUS_ARCH_MISMATCH: return "CUBLAS_STATUS_ARCH_MISMATCH";
  183. case CUBLAS_STATUS_MAPPING_ERROR: return "CUBLAS_STATUS_MAPPING_ERROR";
  184. case CUBLAS_STATUS_EXECUTION_FAILED: return "CUBLAS_STATUS_EXECUTION_FAILED";
  185. case CUBLAS_STATUS_INTERNAL_ERROR: return "CUBLAS_STATUS_INTERNAL_ERROR";
  186. case CUBLAS_STATUS_NOT_SUPPORTED: return "CUBLAS_STATUS_NOT_SUPPORTED";
  187. default: return "unknown error";
  188. }
  189. }
  190. #endif // CUDART_VERSION >= 12000
  191. #define CUBLAS_CHECK(err) CUDA_CHECK_GEN(err, CUBLAS_STATUS_SUCCESS, cublas_get_error_str)
  192. #if !defined(GGML_USE_HIPBLAS)
  193. static const char * cu_get_error_str(CUresult err) {
  194. const char * err_str;
  195. cuGetErrorString(err, &err_str);
  196. return err_str;
  197. }
  198. #define CU_CHECK(err) CUDA_CHECK_GEN(err, CUDA_SUCCESS, cu_get_error_str)
  199. #endif
  200. #if CUDART_VERSION >= 11100
  201. #define GGML_CUDA_ASSUME(x) __builtin_assume(x)
  202. #else
  203. #define GGML_CUDA_ASSUME(x)
  204. #endif // CUDART_VERSION >= 11100
  205. #ifdef GGML_CUDA_F16
  206. typedef half dfloat; // dequantize float
  207. typedef half2 dfloat2;
  208. #else
  209. typedef float dfloat; // dequantize float
  210. typedef float2 dfloat2;
  211. #endif //GGML_CUDA_F16
  212. [[noreturn]]
  213. static __device__ void no_device_code(
  214. const char * file_name, const int line, const char * function_name, const int arch, const char * arch_list) {
  215. #if defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__)
  216. printf("%s:%d: ERROR: HIP kernel %s has no device code compatible with HIP arch %d.\n",
  217. file_name, line, function_name, arch);
  218. GGML_UNUSED(arch_list);
  219. #else
  220. printf("%s:%d: ERROR: CUDA kernel %s has no device code compatible with CUDA arch %d. ggml-cuda.cu was compiled for: %s\n",
  221. file_name, line, function_name, arch, arch_list);
  222. #endif // defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__)
  223. __trap();
  224. GGML_UNUSED(no_device_code); // suppress unused function warning
  225. }
  226. #ifdef __CUDA_ARCH__
  227. #define NO_DEVICE_CODE no_device_code(__FILE__, __LINE__, __FUNCTION__, __CUDA_ARCH__, STRINGIZE(__CUDA_ARCH_LIST__))
  228. #else
  229. #define NO_DEVICE_CODE //GGML_ASSERT(false && "NO_DEVICE_CODE not valid in host code.")
  230. #endif // __CUDA_ARCH__
  231. static __device__ __forceinline__ float warp_reduce_sum(float x) {
  232. #pragma unroll
  233. for (int mask = 16; mask > 0; mask >>= 1) {
  234. x += __shfl_xor_sync(0xffffffff, x, mask, 32);
  235. }
  236. return x;
  237. }
  238. static __device__ __forceinline__ float2 warp_reduce_sum(float2 a) {
  239. #pragma unroll
  240. for (int mask = 16; mask > 0; mask >>= 1) {
  241. a.x += __shfl_xor_sync(0xffffffff, a.x, mask, 32);
  242. a.y += __shfl_xor_sync(0xffffffff, a.y, mask, 32);
  243. }
  244. return a;
  245. }
  246. static __device__ __forceinline__ half2 warp_reduce_sum(half2 a) {
  247. #if !(defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__)) && __CUDA_ARCH__ >= CC_PASCAL
  248. #pragma unroll
  249. for (int mask = 16; mask > 0; mask >>= 1) {
  250. a = __hadd2(a, __shfl_xor_sync(0xffffffff, a, mask, 32));
  251. }
  252. return a;
  253. #else
  254. GGML_UNUSED(a);
  255. NO_DEVICE_CODE;
  256. #endif // !(defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__)) && __CUDA_ARCH__ >= CC_PASCAL
  257. }
  258. static __device__ __forceinline__ float warp_reduce_max(float x) {
  259. #pragma unroll
  260. for (int mask = 16; mask > 0; mask >>= 1) {
  261. x = fmaxf(x, __shfl_xor_sync(0xffffffff, x, mask, 32));
  262. }
  263. return x;
  264. }
  265. static __device__ __forceinline__ half ggml_cuda_hmax(const half a, const half b) {
  266. #if !(defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__))
  267. #if CUDART_VERSION >= CUDART_HMAX
  268. return __hmax(a, b);
  269. #else
  270. return __half2float(a) > __half2float(b) ? a : b;
  271. #endif // CUDART_VERSION >= CUDART_HMAX
  272. #else
  273. GGML_UNUSED(a);
  274. GGML_UNUSED(b);
  275. NO_DEVICE_CODE;
  276. #endif // !(defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__)) && CUDART_VERSION < CUDART_HMAX
  277. }
  278. static __device__ __forceinline__ half2 ggml_cuda_hmax2(const half2 a, const half2 b) {
  279. #if !(defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__))
  280. #if CUDART_VERSION >= CUDART_HMAX
  281. return __hmax2(a, b);
  282. #else
  283. half2 ret;
  284. reinterpret_cast<half&>(ret.x) = __low2float(a) > __low2float(b) ? __low2half(a) : __low2half(b);
  285. reinterpret_cast<half&>(ret.y) = __high2float(a) > __high2float(b) ? __high2half(a) : __high2half(b);
  286. return ret;
  287. #endif // CUDART_VERSION >= CUDART_HMAX
  288. #else
  289. GGML_UNUSED(a);
  290. GGML_UNUSED(b);
  291. NO_DEVICE_CODE;
  292. #endif // !(defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__)) && CUDART_VERSION < CUDART_HMAX
  293. }
  294. static __device__ __forceinline__ half2 warp_reduce_max(half2 x) {
  295. #if !(defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__)) && __CUDA_ARCH__ >= CC_PASCAL
  296. #pragma unroll
  297. for (int mask = 16; mask > 0; mask >>= 1) {
  298. x = ggml_cuda_hmax2(x, __shfl_xor_sync(0xffffffff, x, mask, 32));
  299. }
  300. return x;
  301. #else
  302. GGML_UNUSED(x);
  303. NO_DEVICE_CODE;
  304. #endif // !(defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__)) && __CUDA_ARCH__ >= CC_PASCAL
  305. }
  306. #if CUDART_VERSION < CUDART_HMASK
  307. static __device__ __forceinline__ uint32_t __hgt2_mask(const half2 a, const half2 b) {
  308. const uint32_t mask_low = 0x0000FFFF * (float( __low2half(a)) > float( __low2half(b)));
  309. const uint32_t mask_high = 0xFFFF0000 * (float(__high2half(a)) > float(__high2half(b)));
  310. return mask_low | mask_high;
  311. }
  312. #endif // CUDART_VERSION < 12000
  313. #if defined(GGML_USE_HIPBLAS)
  314. #define __CUDA_ARCH__ 1300
  315. #if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \
  316. defined(__gfx1150__) || defined(__gfx1151__)
  317. #define RDNA3
  318. #endif
  319. #if defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__) || defined(__gfx1033__) || \
  320. defined(__gfx1034__) || defined(__gfx1035__) || defined(__gfx1036__) || defined(__gfx1037__)
  321. #define RDNA2
  322. #endif
  323. #ifndef __has_builtin
  324. #define __has_builtin(x) 0
  325. #endif
  326. typedef int8_t int8x4_t __attribute__((ext_vector_type(4)));
  327. typedef uint8_t uint8x4_t __attribute__((ext_vector_type(4)));
  328. static __device__ __forceinline__ int __vsubss4(const int a, const int b) {
  329. const int8x4_t va = reinterpret_cast<const int8x4_t&>(a);
  330. const int8x4_t vb = reinterpret_cast<const int8x4_t&>(b);
  331. #if __has_builtin(__builtin_elementwise_sub_sat)
  332. const int8x4_t c = __builtin_elementwise_sub_sat(va, vb);
  333. return reinterpret_cast<const int &>(c);
  334. #else
  335. int8x4_t c;
  336. int16_t tmp;
  337. #pragma unroll
  338. for (int i = 0; i < 4; i++) {
  339. tmp = va[i] - vb[i];
  340. if(tmp > std::numeric_limits<int8_t>::max()) tmp = std::numeric_limits<int8_t>::max();
  341. if(tmp < std::numeric_limits<int8_t>::min()) tmp = std::numeric_limits<int8_t>::min();
  342. c[i] = tmp;
  343. }
  344. return reinterpret_cast<int &>(c);
  345. #endif // __has_builtin(__builtin_elementwise_sub_sat)
  346. }
  347. static __device__ __forceinline__ int __vsub4(const int a, const int b) {
  348. return __vsubss4(a, b);
  349. }
  350. static __device__ __forceinline__ unsigned int __vcmpeq4(unsigned int a, unsigned int b) {
  351. const uint8x4_t& va = reinterpret_cast<const uint8x4_t&>(a);
  352. const uint8x4_t& vb = reinterpret_cast<const uint8x4_t&>(b);
  353. unsigned int c;
  354. uint8x4_t& vc = reinterpret_cast<uint8x4_t&>(c);
  355. #pragma unroll
  356. for (int i = 0; i < 4; ++i) {
  357. vc[i] = va[i] == vb[i] ? 0xff : 0x00;
  358. }
  359. return c;
  360. }
  361. static __device__ __forceinline__ int __dp4a(const int a, const int b, int c) {
  362. #if defined(__gfx906__) || defined(__gfx908__) || defined(__gfx90a__) || defined(__gfx1030__)
  363. c = __builtin_amdgcn_sdot4(a, b, c, false);
  364. #elif defined(RDNA3)
  365. c = __builtin_amdgcn_sudot4( true, a, true, b, c, false);
  366. #elif defined(__gfx1010__) || defined(__gfx900__)
  367. int tmp1;
  368. int tmp2;
  369. asm("\n \
  370. 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 \
  371. 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 \
  372. v_add3_u32 %0, %1, %2, %0 \n \
  373. 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 \
  374. 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 \
  375. v_add3_u32 %0, %1, %2, %0 \n \
  376. "
  377. : "+v"(c), "=&v"(tmp1), "=&v"(tmp2)
  378. : "v"(a), "v"(b)
  379. );
  380. #else
  381. const int8x4_t va = reinterpret_cast<const int8x4_t&>(a);
  382. const int8x4_t vb = reinterpret_cast<const int8x4_t&>(b);
  383. c += va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2] + va[3] * vb[3];
  384. #endif
  385. return c;
  386. }
  387. #endif // defined(GGML_USE_HIPBLAS)
  388. #define FP16_AVAILABLE defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__) ? \
  389. defined(RDNA1) || defined(RDNA2) || defined(RDNA3) : __CUDA_ARCH__ >= CC_PASCAL
  390. #define FP16_MMA_AVAILABLE !(defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__)) && __CUDA_ARCH__ >= CC_VOLTA
  391. // TODO: move to ggml-common.h
  392. static const __device__ int8_t kvalues_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
  393. typedef void (*dequantize_kernel_t)(const void * vx, const int64_t ib, const int iqs, dfloat2 & v);
  394. //////////////////////
  395. struct ggml_cuda_device_info {
  396. int device_count;
  397. struct cuda_device_info {
  398. int cc; // compute capability
  399. int nsm; // number of streaming multiprocessors
  400. size_t smpb; // max. shared memory per block
  401. bool vmm; // virtual memory support
  402. size_t vmm_granularity; // granularity of virtual memory
  403. size_t total_vram;
  404. };
  405. cuda_device_info devices[GGML_CUDA_MAX_DEVICES] = {};
  406. std::array<float, GGML_CUDA_MAX_DEVICES> default_tensor_split = {};
  407. };
  408. const ggml_cuda_device_info & ggml_cuda_info();
  409. void ggml_cuda_set_device(int device);
  410. int ggml_cuda_get_device();
  411. struct ggml_cuda_pool {
  412. virtual ~ggml_cuda_pool() = default;
  413. virtual void * alloc(size_t size, size_t * actual_size) = 0;
  414. virtual void free(void * ptr, size_t size) = 0;
  415. };
  416. template<typename T>
  417. struct ggml_cuda_pool_alloc {
  418. ggml_cuda_pool * pool = nullptr;
  419. T * ptr = nullptr;
  420. size_t actual_size = 0;
  421. ggml_cuda_pool_alloc() = default;
  422. explicit ggml_cuda_pool_alloc(ggml_cuda_pool & pool) : pool(&pool) {
  423. }
  424. ggml_cuda_pool_alloc(ggml_cuda_pool & pool, size_t size) : pool(&pool) {
  425. alloc(size);
  426. }
  427. ~ggml_cuda_pool_alloc() {
  428. if (ptr != nullptr) {
  429. pool->free(ptr, actual_size);
  430. }
  431. }
  432. // size is in number of elements
  433. T * alloc(size_t size) {
  434. GGML_ASSERT(pool != nullptr);
  435. GGML_ASSERT(ptr == nullptr);
  436. ptr = (T *) pool->alloc(size * sizeof(T), &this->actual_size);
  437. return ptr;
  438. }
  439. T * alloc(ggml_cuda_pool & pool, size_t size) {
  440. this->pool = &pool;
  441. return alloc(size);
  442. }
  443. T * get() {
  444. return ptr;
  445. }
  446. ggml_cuda_pool_alloc(const ggml_cuda_pool_alloc &) = delete;
  447. ggml_cuda_pool_alloc(ggml_cuda_pool_alloc &&) = delete;
  448. ggml_cuda_pool_alloc& operator=(const ggml_cuda_pool_alloc &) = delete;
  449. ggml_cuda_pool_alloc& operator=(ggml_cuda_pool_alloc &&) = delete;
  450. };
  451. // backend interface
  452. struct ggml_tensor_extra_gpu {
  453. void * data_device[GGML_CUDA_MAX_DEVICES]; // 1 pointer for each device for split tensors
  454. cudaEvent_t events[GGML_CUDA_MAX_DEVICES][GGML_CUDA_MAX_STREAMS]; // events for synchronizing multiple GPUs
  455. };
  456. #if (CUDART_VERSION >= 12000) && defined(GGML_CUDA_USE_GRAPHS)
  457. #define USE_CUDA_GRAPH
  458. #endif
  459. struct ggml_graph_node_properties {
  460. void * node_address;
  461. ggml_op node_op;
  462. int64_t ne[GGML_MAX_DIMS];
  463. size_t nb[GGML_MAX_DIMS];
  464. void * src_address[GGML_MAX_SRC];
  465. };
  466. struct ggml_cuda_graph {
  467. #ifdef USE_CUDA_GRAPH
  468. ~ggml_cuda_graph() {
  469. if (instance != nullptr) {
  470. CUDA_CHECK(cudaGraphExecDestroy(instance));
  471. }
  472. if (graph != nullptr) {
  473. CUDA_CHECK(cudaGraphDestroy(graph));
  474. }
  475. }
  476. cudaGraph_t graph = nullptr;
  477. cudaGraphExec_t instance = nullptr;
  478. size_t num_nodes = 0;
  479. std::vector<cudaGraphNode_t> nodes;
  480. std::vector<cudaKernelNodeParams> params;
  481. bool disable_due_to_gpu_arch = false;
  482. bool disable_due_to_too_many_updates = false;
  483. bool disable_due_to_failed_graph_capture = false;
  484. int number_consecutive_updates = 0;
  485. std::vector<ggml_graph_node_properties> ggml_graph_properties;
  486. std::vector<char **> updated_kernel_arg;
  487. #endif
  488. };
  489. struct ggml_backend_cuda_context {
  490. int device;
  491. std::string name;
  492. cudaEvent_t copy_event = nullptr;
  493. cudaStream_t streams[GGML_CUDA_MAX_DEVICES][GGML_CUDA_MAX_STREAMS] = { { nullptr } };
  494. cublasHandle_t cublas_handles[GGML_CUDA_MAX_DEVICES] = {nullptr};
  495. std::unique_ptr<ggml_cuda_graph> cuda_graph;
  496. explicit ggml_backend_cuda_context(int device) :
  497. device(device),
  498. name(GGML_CUDA_NAME + std::to_string(device)) {
  499. }
  500. ~ggml_backend_cuda_context() {
  501. if (copy_event != nullptr) {
  502. CUDA_CHECK(cudaEventDestroy(copy_event));
  503. }
  504. for (int i = 0; i < GGML_CUDA_MAX_DEVICES; ++i) {
  505. for (int j = 0; j < GGML_CUDA_MAX_STREAMS; ++j) {
  506. if (streams[i][j] != nullptr) {
  507. CUDA_CHECK(cudaStreamDestroy(streams[i][j]));
  508. }
  509. }
  510. if (cublas_handles[i] != nullptr) {
  511. CUBLAS_CHECK(cublasDestroy(cublas_handles[i]));
  512. }
  513. }
  514. }
  515. cudaStream_t stream(int device, int stream) {
  516. if (streams[device][stream] == nullptr) {
  517. ggml_cuda_set_device(device);
  518. CUDA_CHECK(cudaStreamCreateWithFlags(&streams[device][stream], cudaStreamNonBlocking));
  519. }
  520. return streams[device][stream];
  521. }
  522. cudaStream_t stream() {
  523. return stream(device, 0);
  524. }
  525. cublasHandle_t cublas_handle(int device) {
  526. if (cublas_handles[device] == nullptr) {
  527. ggml_cuda_set_device(device);
  528. CUBLAS_CHECK(cublasCreate(&cublas_handles[device]));
  529. CUBLAS_CHECK(cublasSetMathMode(cublas_handles[device], CUBLAS_TF32_TENSOR_OP_MATH));
  530. }
  531. return cublas_handles[device];
  532. }
  533. cublasHandle_t cublas_handle() {
  534. return cublas_handle(device);
  535. }
  536. // pool
  537. std::unique_ptr<ggml_cuda_pool> pools[GGML_CUDA_MAX_DEVICES];
  538. static std::unique_ptr<ggml_cuda_pool> new_pool_for_device(int device);
  539. ggml_cuda_pool & pool(int device) {
  540. if (pools[device] == nullptr) {
  541. pools[device] = new_pool_for_device(device);
  542. }
  543. return *pools[device];
  544. }
  545. ggml_cuda_pool & pool() {
  546. return pool(device);
  547. }
  548. };