common.cuh 22 KB

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