1
0

marlin_cuda_kernel.cu 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. /*
  2. * Modified by Neural Magic
  3. * Copyright (C) Marlin.2024 Elias Frantar
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. #include <torch/extension.h>
  18. #include <ATen/cuda/CUDAContext.h>
  19. #include <c10/cuda/CUDAGuard.h>
  20. #include <cuda.h>
  21. #include <cuda_fp16.h>
  22. #include <cuda_runtime.h>
  23. #include <iostream>
  24. template <typename T> inline std::string str(T x) { return std::to_string(x); }
  25. namespace marlin {
  26. constexpr int ceildiv(int a, int b) { return (a + b - 1) / b; }
  27. #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
  28. // Instances of `Vec` are used to organize groups of >>registers<<, as needed
  29. // for instance as inputs to tensor core operations. Consequently, all
  30. // corresponding index accesses must be compile-time constants, which is why we
  31. // extensively use `#pragma unroll` throughout the kernel code to guarantee
  32. // this.
  33. template <typename T, int n> struct Vec {
  34. T elems[n];
  35. __device__ T &operator[](int i) { return elems[i]; }
  36. };
  37. using I4 = Vec<int, 4>;
  38. // Matrix fragments for tensor core instructions; their precise layout is
  39. // documented here:
  40. // https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#matrix-fragments-for-mma-m16n8k16-with-floating-point-type
  41. using FragA = Vec<half2, 4>;
  42. using FragB = Vec<half2, 2>;
  43. using FragC = Vec<float, 4>;
  44. using FragS = Vec<half2, 1>; // quantization scales
  45. // Predicated asynchronous global->shared copy; used for inputs A where we apply
  46. // predication to handle batchsizes that are not multiples of 16.
  47. __device__ inline void cp_async4_pred(void *smem_ptr, const void *glob_ptr,
  48. bool pred = true) {
  49. const int BYTES = 16;
  50. uint32_t smem = static_cast<uint32_t>(__cvta_generic_to_shared(smem_ptr));
  51. asm volatile("{\n"
  52. " .reg .pred p;\n"
  53. " setp.ne.b32 p, %0, 0;\n"
  54. " @p cp.async.cg.shared.global [%1], [%2], %3;\n"
  55. "}\n" ::"r"((int)pred),
  56. "r"(smem), "l"(glob_ptr), "n"(BYTES));
  57. }
  58. // Asynchronous global->shared copy with a cache hint indicating that the values
  59. // may be evicted immediately; used for quantized weights B, which are only
  60. // accessed precisely once and should thus not pollute the L2 cache which we
  61. // need for inputs A and outputs C.
  62. __device__ inline void cp_async4_stream(void *smem_ptr, const void *glob_ptr) {
  63. const int BYTES = 16;
  64. uint32_t smem = static_cast<uint32_t>(__cvta_generic_to_shared(smem_ptr));
  65. asm volatile(
  66. "{\n"
  67. " .reg .b64 p;\n"
  68. " createpolicy.fractional.L2::evict_first.b64 p, 1.0;"
  69. " cp.async.cg.shared.global.L2::cache_hint [%0], [%1], %2, p;\n"
  70. "}\n" ::"r"(smem),
  71. "l"(glob_ptr), "n"(BYTES));
  72. }
  73. // Async copy fence.
  74. __device__ inline void cp_async_fence() {
  75. asm volatile("cp.async.commit_group;\n" ::);
  76. }
  77. // Wait until at most `n` async copy stages are still pending.
  78. template <int n> __device__ inline void cp_async_wait() {
  79. asm volatile("cp.async.wait_group %0;\n" ::"n"(n));
  80. }
  81. // m16n8k16 tensor core mma instruction with fp16 inputs and fp32
  82. // output/accumulation.
  83. __device__ inline void mma(const FragA &a_frag, const FragB &frag_b,
  84. FragC &frag_c) {
  85. const uint32_t *a = reinterpret_cast<const uint32_t *>(&a_frag);
  86. const uint32_t *b = reinterpret_cast<const uint32_t *>(&frag_b);
  87. float *c = reinterpret_cast<float *>(&frag_c);
  88. asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 "
  89. "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%10,%11,%12,%13};\n"
  90. : "=f"(c[0]), "=f"(c[1]), "=f"(c[2]), "=f"(c[3])
  91. : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]),
  92. "r"(b[1]), "f"(c[0]), "f"(c[1]), "f"(c[2]), "f"(c[3]));
  93. }
  94. // Instruction for loading a full 16x16 matrix fragment of operand A from shared
  95. // memory, directly in tensor core layout.
  96. __device__ inline void ldsm4(FragA &frag_a, const void *smem_ptr) {
  97. uint32_t *a = reinterpret_cast<uint32_t *>(&frag_a);
  98. uint32_t smem = static_cast<uint32_t>(__cvta_generic_to_shared(smem_ptr));
  99. asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
  100. : "=r"(a[0]), "=r"(a[1]), "=r"(a[2]), "=r"(a[3])
  101. : "r"(smem));
  102. }
  103. // Lookup-table based 3-input logical operation; explicitly used for
  104. // dequantization as the compiler does not seem to automatically recognize it in
  105. // all cases.
  106. template <int lut> __device__ inline int lop3(int a, int b, int c) {
  107. int res;
  108. asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
  109. : "=r"(res)
  110. : "r"(a), "r"(b), "r"(c), "n"(lut));
  111. return res;
  112. }
  113. // Efficiently dequantize an int32 value into a full B-fragment of 4 fp16
  114. // values. We mostly follow the strategy in the link below, with some small
  115. // changes:
  116. // https://github.com/NVIDIA/FasterTransformer/blob/main/src/fastertransformer/cutlass_extensions/include/cutlass_extensions/interleaved_numeric_conversion.h
  117. __device__ inline FragB dequant(int q) {
  118. const int LO = 0x000f000f;
  119. const int HI = 0x00f000f0;
  120. const int EX = 0x64006400;
  121. // Guarantee that the `(a & b) | c` operations are LOP3s.
  122. int lo = lop3<(0xf0 & 0xcc) | 0xaa>(q, LO, EX);
  123. int hi = lop3<(0xf0 & 0xcc) | 0xaa>(q, HI, EX);
  124. // We want signed int4 outputs, hence we fuse the `-8` symmetric zero point
  125. // directly into `SUB` and `ADD`.
  126. const int SUB = 0x64086408;
  127. const int MUL = 0x2c002c00;
  128. const int ADD = 0xd480d480;
  129. FragB frag_b;
  130. frag_b[0] = __hsub2(*reinterpret_cast<half2 *>(&lo),
  131. *reinterpret_cast<const half2 *>(&SUB));
  132. frag_b[1] = __hfma2(*reinterpret_cast<half2 *>(&hi),
  133. *reinterpret_cast<const half2 *>(&MUL),
  134. *reinterpret_cast<const half2 *>(&ADD));
  135. return frag_b;
  136. }
  137. // Multiply dequantized values by the corresponding quantization scale; used
  138. // only for grouped quantization.
  139. __device__ inline void scale(FragB &frag_b, FragS &frag_s, int i) {
  140. half2 s = __half2half2(reinterpret_cast<__half *>(&frag_s)[i]);
  141. frag_b[0] = __hmul2(frag_b[0], s);
  142. frag_b[1] = __hmul2(frag_b[1], s);
  143. }
  144. // Wait until barrier reaches `count`, then lock for current threadblock.
  145. __device__ inline void barrier_acquire(int *lock, int count) {
  146. if (threadIdx.x == 0) {
  147. int state = -1;
  148. do
  149. // Guarantee that subsequent writes by this threadblock will be visible
  150. // globally.
  151. asm volatile("ld.global.acquire.gpu.b32 %0, [%1];\n"
  152. : "=r"(state)
  153. : "l"(lock));
  154. while (state != count);
  155. }
  156. __syncthreads();
  157. }
  158. // Release barrier and increment visitation count.
  159. __device__ inline void barrier_release(int *lock, bool reset = false) {
  160. __syncthreads();
  161. if (threadIdx.x == 0) {
  162. if (reset) {
  163. lock[0] = 0;
  164. return;
  165. }
  166. int val = 1;
  167. // Make sure that all writes since acquiring this barrier are visible
  168. // globally, while releasing the barrier.
  169. asm volatile("fence.acq_rel.gpu;\n");
  170. asm volatile("red.relaxed.gpu.global.add.s32 [%0], %1;\n"
  171. :
  172. : "l"(lock), "r"(val));
  173. }
  174. }
  175. template <const int threads, // number of threads in a threadblock
  176. const int thread_m_blocks, // number of 16x16 blocks in the m
  177. // dimension (batchsize) of the threadblock
  178. const int thread_n_blocks, // same for n dimension (output)
  179. const int thread_k_blocks, // same for k dimension (reduction)
  180. const int stages, // number of stages for the async global->shared
  181. // fetch pipeline
  182. const int group_blocks = -1 // number of consecutive 16x16 blocks with
  183. // a separate quantization scale
  184. >
  185. __global__ void
  186. Marlin(const int4 *__restrict__ A, // fp16 input matrix of shape mxk
  187. const int4 *__restrict__ B, // 4bit quantized weight matrix of shape kxn
  188. int4 *__restrict__ C, // fp16 output buffer of shape mxn
  189. const int4
  190. *__restrict__ s, // fp16 quantization scales of shape (k/groupsize)xn
  191. int prob_m, // batch dimension m
  192. int prob_n, // output dimension n
  193. int prob_k, // reduction dimension k
  194. int *locks // extra global storage for barrier synchronization
  195. ) {
  196. // Each threadblock processes one "stripe" of the B matrix with (roughly) the
  197. // same size, which might involve multiple column "slices" (of width 16 *
  198. // `thread_n_blocks`). Stripes are defined as shown in the 3x3 matrix 5 SM
  199. // example:
  200. // 0 1 3
  201. // 0 2 3
  202. // 1 2 4
  203. // While this kind of partitioning makes things somewhat more complicated, it
  204. // ensures good utilization of all SMs for many kinds of shape and GPU
  205. // configurations, while requiring as few slow global cross-threadblock
  206. // reductions as possible.
  207. // For larger GEMMs we run multiple batchsize 64 versions in parallel for a
  208. // better partitioning with less reductions
  209. int parallel = 1;
  210. if (prob_m > 16 * thread_m_blocks) {
  211. parallel = prob_m / (16 * thread_m_blocks);
  212. prob_m = 16 * thread_m_blocks;
  213. }
  214. int k_tiles = prob_k / 16 / thread_k_blocks;
  215. int n_tiles = prob_n / 16 / thread_n_blocks;
  216. int iters = ceildiv(k_tiles * n_tiles * parallel, gridDim.x);
  217. // Ensure that the number of tiles in each stripe is a multiple of the
  218. // groupsize; this avoids an annoying special case where a stripe starts in
  219. // the middle of group.
  220. if (group_blocks != -1)
  221. iters = (group_blocks / thread_k_blocks) *
  222. ceildiv(iters, (group_blocks / thread_k_blocks));
  223. int slice_row = (iters * blockIdx.x) % k_tiles;
  224. int slice_col_par = (iters * blockIdx.x) / k_tiles;
  225. int slice_col = slice_col_par;
  226. int slice_iters; // number of threadblock tiles in the current slice
  227. int slice_count =
  228. 0; // total number of active threadblocks in the current slice
  229. int slice_idx; // index of threadblock in current slice; numbered bottom to
  230. // top
  231. // We can easily implement parallel problem execution by just remapping
  232. // indices and advancing global pointers
  233. if (slice_col_par >= n_tiles) {
  234. A += (slice_col_par / n_tiles) * 16 * thread_m_blocks * prob_k / 8;
  235. C += (slice_col_par / n_tiles) * 16 * thread_m_blocks * prob_n / 8;
  236. locks += (slice_col_par / n_tiles) * n_tiles;
  237. slice_col = slice_col_par % n_tiles;
  238. }
  239. // Compute all information about the current slice which is required for
  240. // synchronization.
  241. auto init_slice = [&]() {
  242. slice_iters =
  243. iters * (blockIdx.x + 1) - (k_tiles * slice_col_par + slice_row);
  244. if (slice_iters < 0 || slice_col_par >= n_tiles * parallel)
  245. slice_iters = 0;
  246. if (slice_iters == 0)
  247. return;
  248. if (slice_row + slice_iters > k_tiles)
  249. slice_iters = k_tiles - slice_row;
  250. slice_count = 1;
  251. slice_idx = 0;
  252. int col_first = iters * ceildiv(k_tiles * slice_col_par, iters);
  253. if (col_first <= k_tiles * (slice_col_par + 1)) {
  254. int col_off = col_first - k_tiles * slice_col_par;
  255. slice_count = ceildiv(k_tiles - col_off, iters);
  256. if (col_off > 0)
  257. slice_count++;
  258. int delta_first = iters * blockIdx.x - col_first;
  259. if (delta_first < 0 || (col_off == 0 && delta_first == 0))
  260. slice_idx = slice_count - 1;
  261. else {
  262. slice_idx = slice_count - 1 - delta_first / iters;
  263. if (col_off > 0)
  264. slice_idx--;
  265. }
  266. }
  267. if (slice_col == n_tiles) {
  268. A += 16 * thread_m_blocks * prob_k / 8;
  269. C += 16 * thread_m_blocks * prob_n / 8;
  270. locks += n_tiles;
  271. slice_col = 0;
  272. }
  273. };
  274. init_slice();
  275. int a_gl_stride = prob_k / 8; // stride of the A matrix in global memory
  276. // We typically use `constexpr` to indicate that this value is a compile-time
  277. // constant
  278. constexpr int a_sh_stride =
  279. 16 * thread_k_blocks / 8; // stride of an A matrix tile in shared memory
  280. constexpr int a_gl_rd_delta_o =
  281. 16 * thread_k_blocks /
  282. 8; // delta between subsequent A tiles in global memory
  283. int a_gl_rd_delta_i =
  284. a_gl_stride *
  285. (threads / a_gl_rd_delta_o); // between subsequent accesses within a tile
  286. constexpr int a_sh_wr_delta =
  287. a_sh_stride * (threads / a_gl_rd_delta_o); // between shared memory writes
  288. constexpr int a_sh_rd_delta_o =
  289. 2 * ((threads / 32) /
  290. (thread_n_blocks / 4)); // between shared memory tile reads
  291. constexpr int a_sh_rd_delta_i =
  292. a_sh_stride * 16; // within a shared memory tile
  293. constexpr int a_sh_stage =
  294. a_sh_stride * (16 * thread_m_blocks); // overall size of a tile
  295. constexpr int a_sh_wr_iters =
  296. ceildiv(a_sh_stage,
  297. a_sh_wr_delta); // number of shared write iterations for a tile
  298. int b_gl_stride = 16 * prob_n / 32;
  299. constexpr int b_sh_stride = 32 * thread_n_blocks / 4;
  300. int b_gl_rd_delta_o = b_gl_stride * thread_k_blocks;
  301. int b_gl_rd_delta_i = b_gl_stride * (threads / b_sh_stride);
  302. constexpr int b_sh_wr_delta = threads;
  303. constexpr int b_sh_rd_delta = threads;
  304. constexpr int b_sh_stage = b_sh_stride * thread_k_blocks;
  305. constexpr int b_sh_wr_iters = b_sh_stage / b_sh_wr_delta;
  306. int s_gl_stride = prob_n / 8;
  307. constexpr int s_sh_stride = 16 * thread_n_blocks / 8;
  308. constexpr int s_sh_stage = s_sh_stride;
  309. int s_gl_rd_delta = s_gl_stride;
  310. // Global A read index of current thread.
  311. int a_gl_rd = a_gl_stride * (threadIdx.x / a_gl_rd_delta_o) +
  312. (threadIdx.x % a_gl_rd_delta_o);
  313. a_gl_rd += a_gl_rd_delta_o * slice_row;
  314. // Shared write index of current thread.
  315. int a_sh_wr = a_sh_stride * (threadIdx.x / a_gl_rd_delta_o) +
  316. (threadIdx.x % a_gl_rd_delta_o);
  317. // Shared read index.
  318. int a_sh_rd =
  319. a_sh_stride * ((threadIdx.x % 32) % 16) + (threadIdx.x % 32) / 16;
  320. a_sh_rd += 2 * ((threadIdx.x / 32) / (thread_n_blocks / 4));
  321. int b_gl_rd =
  322. b_gl_stride * (threadIdx.x / b_sh_stride) + (threadIdx.x % b_sh_stride);
  323. b_gl_rd += b_sh_stride * slice_col;
  324. b_gl_rd += b_gl_rd_delta_o * slice_row;
  325. int b_sh_wr = threadIdx.x;
  326. int b_sh_rd = threadIdx.x;
  327. int s_gl_rd = s_gl_stride * ((thread_k_blocks * slice_row) / group_blocks) +
  328. s_sh_stride * slice_col + threadIdx.x;
  329. int s_sh_wr = threadIdx.x;
  330. int s_sh_rd;
  331. // We use a different scale layout for grouped and column-wise quantization as
  332. // we scale a `half2` tile in column-major layout in the former and in
  333. // row-major in the latter case.
  334. if (group_blocks != -1)
  335. s_sh_rd = 8 * ((threadIdx.x / 32) % (thread_n_blocks / 4)) +
  336. (threadIdx.x % 32) / 4;
  337. else
  338. s_sh_rd = 8 * ((threadIdx.x / 32) % (thread_n_blocks / 4)) +
  339. (threadIdx.x % 32) % 4;
  340. // Precompute which thread should not read memory in which iterations; this is
  341. // needed if there are more threads than required for a certain tilesize or
  342. // when the batchsize is not a multiple of 16.
  343. bool a_sh_wr_pred[a_sh_wr_iters];
  344. #pragma unroll
  345. for (int i = 0; i < a_sh_wr_iters; i++)
  346. a_sh_wr_pred[i] = a_sh_wr_delta * i + a_sh_wr < a_sh_stride * prob_m;
  347. bool s_sh_wr_pred = threadIdx.x < s_sh_stride;
  348. // To ensure that writing and reading A tiles to/from shared memory, the
  349. // latter in fragment format, is fully bank conflict free, we need to use a
  350. // rather fancy XOR-based layout. The key here is that neither reads nor
  351. // writes of the 16-byte `int4` blocks of 8 consecutive threads involve the
  352. // same shared memory banks. Further, it seems (based on NSight-Compute) that
  353. // each warp must also write a consecutive memory segment?
  354. auto transform_a = [&](int i) {
  355. int row = i / a_gl_rd_delta_o;
  356. return a_gl_rd_delta_o * row + (i % a_gl_rd_delta_o) ^ row;
  357. };
  358. // Since the computation of this remapping is non-trivial and, due to our main
  359. // loop unrolls, all shared memory accesses are static, we simply precompute
  360. // both transformed reads and writes.
  361. int a_sh_wr_trans[a_sh_wr_iters];
  362. #pragma unroll
  363. for (int i = 0; i < a_sh_wr_iters; i++)
  364. a_sh_wr_trans[i] = transform_a(a_sh_wr_delta * i + a_sh_wr);
  365. int a_sh_rd_trans[b_sh_wr_iters][thread_m_blocks];
  366. #pragma unroll
  367. for (int i = 0; i < b_sh_wr_iters; i++) {
  368. #pragma unroll
  369. for (int j = 0; j < thread_m_blocks; j++)
  370. a_sh_rd_trans[i][j] =
  371. transform_a(a_sh_rd_delta_o * i + a_sh_rd_delta_i * j + a_sh_rd);
  372. }
  373. // Since B-accesses have non-constant stride they have to be computed at
  374. // runtime; we break dependencies between subsequent accesses with a tile by
  375. // maintining multiple pointers (we have enough registers), a tiny
  376. // optimization.
  377. const int4 *B_ptr[b_sh_wr_iters];
  378. #pragma unroll
  379. for (int i = 0; i < b_sh_wr_iters; i++)
  380. B_ptr[i] = B + b_gl_rd_delta_i * i + b_gl_rd;
  381. extern __shared__ int4 sh[];
  382. // Shared memory storage for global fetch pipelines.
  383. int4 *sh_a = sh;
  384. int4 *sh_b = sh_a + (stages * a_sh_stage);
  385. int4 *sh_s = sh_b + (stages * b_sh_stage);
  386. // Register storage for double buffer of shared memory reads.
  387. FragA frag_a[2][thread_m_blocks];
  388. I4 frag_b_quant[2];
  389. FragC frag_c[thread_m_blocks][4][2];
  390. FragS frag_s[2][4];
  391. // Zero accumulators.
  392. auto zero_accums = [&]() {
  393. #pragma unroll
  394. for (int i = 0; i < thread_m_blocks * 4 * 2 * 4; i++)
  395. reinterpret_cast<float *>(frag_c)[i] = 0;
  396. };
  397. // Asynchronously fetch the next A, B and s tile from global to the next
  398. // shared memory pipeline location.
  399. auto fetch_to_shared = [&](int pipe, int a_off, bool pred = true) {
  400. if (pred) {
  401. int4 *sh_a_stage = sh_a + a_sh_stage * pipe;
  402. #pragma unroll
  403. for (int i = 0; i < a_sh_wr_iters; i++) {
  404. cp_async4_pred(
  405. &sh_a_stage[a_sh_wr_trans[i]],
  406. &A[a_gl_rd_delta_i * i + a_gl_rd + a_gl_rd_delta_o * a_off],
  407. a_sh_wr_pred[i]);
  408. }
  409. int4 *sh_b_stage = sh_b + b_sh_stage * pipe;
  410. #pragma unroll
  411. for (int i = 0; i < b_sh_wr_iters; i++) {
  412. cp_async4_stream(&sh_b_stage[b_sh_wr_delta * i + b_sh_wr], B_ptr[i]);
  413. B_ptr[i] += b_gl_rd_delta_o;
  414. }
  415. // Only fetch scales if this tile starts a new group
  416. if (group_blocks != -1 && pipe % (group_blocks / thread_k_blocks) == 0) {
  417. int4 *sh_s_stage = sh_s + s_sh_stage * pipe;
  418. if (s_sh_wr_pred)
  419. cp_async4_stream(&sh_s_stage[s_sh_wr], &s[s_gl_rd]);
  420. s_gl_rd += s_gl_rd_delta;
  421. }
  422. }
  423. // Insert a fence even when we are winding down the pipeline to ensure that
  424. // waiting is also correct at this point.
  425. cp_async_fence();
  426. };
  427. // Wait until the next thread tile has been loaded to shared memory.
  428. auto wait_for_stage = [&]() {
  429. // We only have `stages - 2` active fetches since we are double buffering
  430. // and can only issue the next fetch when it is guaranteed that the previous
  431. // shared memory load is fully complete (as it may otherwise be
  432. // overwritten).
  433. cp_async_wait<stages - 2>();
  434. __syncthreads();
  435. };
  436. // Load the next sub-tile from the current location in the shared memory pipe
  437. // into the current register buffer.
  438. auto fetch_to_registers = [&](int k, int pipe) {
  439. // It may seem inefficient that we reload the groups for every sub-tile;
  440. // however, this does not seem to be a significant bottleneck, while some
  441. // theoretically better attempts have lead to bad instruction ordering by
  442. // the compiler and correspondingly a noticeable drop in performance.
  443. if (group_blocks != -1) {
  444. int4 *sh_s_stage =
  445. sh_s + s_sh_stage * ((group_blocks / thread_k_blocks) *
  446. (pipe / (group_blocks / thread_k_blocks)));
  447. reinterpret_cast<int4 *>(&frag_s[k % 2])[0] = sh_s_stage[s_sh_rd];
  448. }
  449. int4 *sh_a_stage = sh_a + a_sh_stage * pipe;
  450. #pragma unroll
  451. for (int i = 0; i < thread_m_blocks; i++)
  452. ldsm4(frag_a[k % 2][i], &sh_a_stage[a_sh_rd_trans[k % b_sh_wr_iters][i]]);
  453. int4 *sh_b_stage = sh_b + b_sh_stage * pipe;
  454. frag_b_quant[k % 2] = *reinterpret_cast<I4 *>(
  455. &sh_b_stage[b_sh_rd_delta * (k % b_sh_wr_iters) + b_sh_rd]);
  456. };
  457. // Execute the actual tensor core matmul of a sub-tile.
  458. auto matmul = [&](int k) {
  459. // We have the m dimension as the inner loop in order to encourage overlapping
  460. // dequantization and matmul operations.
  461. #pragma unroll
  462. for (int j = 0; j < 4; j++) {
  463. int b_quant = frag_b_quant[k % 2][j];
  464. int b_quant_shift = b_quant >> 8;
  465. FragB frag_b0 = dequant(b_quant);
  466. // If there are no groups, we can just scale the final output once and can
  467. // avoid doing so for each weight.
  468. if (group_blocks != -1)
  469. scale(frag_b0, frag_s[k % 2][j], 0);
  470. FragB frag_b1 = dequant(b_quant_shift);
  471. if (group_blocks != -1)
  472. scale(frag_b1, frag_s[k % 2][j], 1);
  473. #pragma unroll
  474. for (int i = 0; i < thread_m_blocks; i++) {
  475. mma(frag_a[k % 2][i], frag_b0, frag_c[i][j][0]);
  476. mma(frag_a[k % 2][i], frag_b1, frag_c[i][j][1]);
  477. }
  478. }
  479. };
  480. // Since we slice across the k dimension of a tile in order to increase the
  481. // number of warps while keeping the n dimension of a tile reasonable, we have
  482. // multiple warps that accumulate their partial sums of the same output
  483. // location; which we have to reduce over in the end. We do in shared memory.
  484. auto thread_block_reduce = [&]() {
  485. constexpr int red_off = threads / b_sh_stride / 2;
  486. if (red_off >= 1) {
  487. int red_idx = threadIdx.x / b_sh_stride;
  488. constexpr int red_sh_stride = b_sh_stride * 4 * 2;
  489. constexpr int red_sh_delta = b_sh_stride;
  490. int red_sh_rd = red_sh_stride * (threadIdx.x / b_sh_stride) +
  491. (threadIdx.x % b_sh_stride);
  492. // Parallel logarithmic shared memory reduction. We make sure to avoid any
  493. // unnecessary read or write iterations, e.g., for two warps we write only
  494. // once by warp 1 and read only once by warp 0.
  495. #pragma unroll
  496. for (int m_block = 0; m_block < thread_m_blocks; m_block++) {
  497. #pragma unroll
  498. for (int i = red_off; i > 0; i /= 2) {
  499. if (i <= red_idx && red_idx < 2 * i) {
  500. #pragma unroll
  501. for (int j = 0; j < 4 * 2; j++) {
  502. int red_sh_wr =
  503. red_sh_delta * j + (red_sh_rd - red_sh_stride * i);
  504. if (i < red_off) {
  505. float *c_rd = reinterpret_cast<float *>(
  506. &sh[red_sh_delta * j + red_sh_rd]);
  507. float *c_wr = reinterpret_cast<float *>(&sh[red_sh_wr]);
  508. #pragma unroll
  509. for (int k = 0; k < 4; k++)
  510. reinterpret_cast<FragC *>(frag_c)[4 * 2 * m_block + j][k] +=
  511. c_rd[k] + c_wr[k];
  512. }
  513. sh[red_sh_wr] =
  514. reinterpret_cast<int4 *>(&frag_c)[4 * 2 * m_block + j];
  515. }
  516. }
  517. __syncthreads();
  518. }
  519. if (red_idx == 0) {
  520. #pragma unroll
  521. for (int i = 0; i < 4 * 2; i++) {
  522. float *c_rd =
  523. reinterpret_cast<float *>(&sh[red_sh_delta * i + red_sh_rd]);
  524. #pragma unroll
  525. for (int j = 0; j < 4; j++)
  526. reinterpret_cast<FragC *>(frag_c)[4 * 2 * m_block + i][j] +=
  527. c_rd[j];
  528. }
  529. }
  530. __syncthreads();
  531. }
  532. }
  533. };
  534. // Since multiple threadblocks may process parts of the same column slice, we
  535. // finally have to globally reduce over the results. As the striped partitioning
  536. // minimizes the number of such reductions and our outputs are usually rather
  537. // small, we perform this reduction serially in L2 cache.
  538. auto global_reduce = [&](bool first = false, bool last = false) {
  539. // We are very careful here to reduce directly in the output buffer to
  540. // maximize L2 cache utilization in this step. To do this, we write out
  541. // results in FP16 (but still reduce with FP32 compute).
  542. constexpr int active_threads = 32 * thread_n_blocks / 4;
  543. if (threadIdx.x < active_threads) {
  544. int c_gl_stride = prob_n / 8;
  545. int c_gl_wr_delta_o = 8 * c_gl_stride;
  546. int c_gl_wr_delta_i = 4 * (active_threads / 32);
  547. int c_gl_wr = c_gl_stride * ((threadIdx.x % 32) / 4) +
  548. 4 * (threadIdx.x / 32) + threadIdx.x % 4;
  549. c_gl_wr += (2 * thread_n_blocks) * slice_col;
  550. constexpr int c_sh_wr_delta = active_threads;
  551. int c_sh_wr = threadIdx.x;
  552. int row = (threadIdx.x % 32) / 4;
  553. if (!first) {
  554. // Interestingly, doing direct global accesses here really seems to mess up the
  555. // compiler and lead to slowdowns, hence we also use async-copies even though
  556. // these fetches are not actually asynchronous.
  557. #pragma unroll
  558. for (int i = 0; i < thread_m_blocks * 4; i++) {
  559. cp_async4_pred(&sh[c_sh_wr + c_sh_wr_delta * i],
  560. &C[c_gl_wr + c_gl_wr_delta_o * (i / 2) +
  561. c_gl_wr_delta_i * (i % 2)],
  562. i < (thread_m_blocks - 1) * 4 ||
  563. 8 * (i / 2) + row < prob_m);
  564. }
  565. cp_async_fence();
  566. cp_async_wait<0>();
  567. }
  568. #pragma unroll
  569. for (int i = 0; i < thread_m_blocks * 4; i++) {
  570. if (i < (thread_m_blocks - 1) * 4 || 8 * (i / 2) + row < prob_m) {
  571. if (!first) {
  572. int4 c_red = sh[c_sh_wr + i * c_sh_wr_delta];
  573. #pragma unroll
  574. for (int j = 0; j < 2 * 4; j++) {
  575. reinterpret_cast<float *>(
  576. &frag_c)[4 * 2 * 4 * (i / 4) + 4 * j + (i % 4)] +=
  577. __half2float(reinterpret_cast<__half *>(&c_red)[j]);
  578. }
  579. }
  580. if (!last) {
  581. int4 c;
  582. #pragma unroll
  583. for (int j = 0; j < 2 * 4; j++) {
  584. reinterpret_cast<__half *>(&c)[j] =
  585. __float2half(reinterpret_cast<float *>(
  586. &frag_c)[4 * 2 * 4 * (i / 4) + 4 * j + (i % 4)]);
  587. }
  588. C[c_gl_wr + c_gl_wr_delta_o * (i / 2) + c_gl_wr_delta_i * (i % 2)] =
  589. c;
  590. }
  591. }
  592. }
  593. }
  594. };
  595. // Write out the reduce final result in the correct layout. We only actually
  596. // reshuffle matrix fragments in this step, the reduction above is performed
  597. // in fragment layout.
  598. auto write_result = [&]() {
  599. int c_gl_stride = prob_n / 8;
  600. constexpr int c_sh_stride = 2 * thread_n_blocks + 1;
  601. int c_gl_wr_delta = c_gl_stride * (threads / (2 * thread_n_blocks));
  602. constexpr int c_sh_rd_delta =
  603. c_sh_stride * (threads / (2 * thread_n_blocks));
  604. int c_gl_wr = c_gl_stride * (threadIdx.x / (2 * thread_n_blocks)) +
  605. (threadIdx.x % (2 * thread_n_blocks));
  606. c_gl_wr += (2 * thread_n_blocks) * slice_col;
  607. int c_sh_wr =
  608. (4 * c_sh_stride) * ((threadIdx.x % 32) / 4) + (threadIdx.x % 32) % 4;
  609. c_sh_wr += 32 * (threadIdx.x / 32);
  610. int c_sh_rd = c_sh_stride * (threadIdx.x / (2 * thread_n_blocks)) +
  611. (threadIdx.x % (2 * thread_n_blocks));
  612. int c_gl_wr_end = c_gl_stride * prob_m;
  613. // We first reorder in shared memory to guarantee the most efficient final
  614. // global write patterns
  615. auto write = [&](int idx, float c0, float c1, FragS &s) {
  616. half2 res = __halves2half2(__float2half(c0), __float2half(c1));
  617. if (group_blocks ==
  618. -1) // for per-column quantization we finally apply the scale here
  619. res = __hmul2(res, s[0]);
  620. ((half2 *)sh)[idx] = res;
  621. };
  622. if (threadIdx.x / 32 < thread_n_blocks / 4) {
  623. #pragma unroll
  624. for (int i = 0; i < thread_m_blocks; i++) {
  625. #pragma unroll
  626. for (int j = 0; j < 4; j++) {
  627. int wr = c_sh_wr + 8 * j;
  628. write(wr + (4 * c_sh_stride) * 0 + 0, frag_c[i][j][0][0],
  629. frag_c[i][j][0][1], frag_s[j / 2][2 * (j % 2) + 0]);
  630. write(wr + (4 * c_sh_stride) * 8 + 0, frag_c[i][j][0][2],
  631. frag_c[i][j][0][3], frag_s[j / 2][2 * (j % 2) + 0]);
  632. write(wr + (4 * c_sh_stride) * 0 + 4, frag_c[i][j][1][0],
  633. frag_c[i][j][1][1], frag_s[j / 2][2 * (j % 2) + 1]);
  634. write(wr + (4 * c_sh_stride) * 8 + 4, frag_c[i][j][1][2],
  635. frag_c[i][j][1][3], frag_s[j / 2][2 * (j % 2) + 1]);
  636. }
  637. c_sh_wr += 16 * (4 * c_sh_stride);
  638. }
  639. }
  640. __syncthreads();
  641. #pragma unroll
  642. for (int i = 0;
  643. i < ceildiv(16 * thread_m_blocks, threads / (2 * thread_n_blocks));
  644. i++) {
  645. if (c_gl_wr < c_gl_wr_end) {
  646. C[c_gl_wr] = sh[c_sh_rd];
  647. c_gl_wr += c_gl_wr_delta;
  648. c_sh_rd += c_sh_rd_delta;
  649. }
  650. }
  651. };
  652. // Start global fetch and register load pipelines.
  653. auto start_pipes = [&]() {
  654. #pragma unroll
  655. for (int i = 0; i < stages - 1; i++)
  656. fetch_to_shared(i, i, i < slice_iters);
  657. zero_accums();
  658. wait_for_stage();
  659. fetch_to_registers(0, 0);
  660. a_gl_rd += a_gl_rd_delta_o * (stages - 1);
  661. };
  662. start_pipes();
  663. // Main loop.
  664. while (slice_iters) {
  665. // We unroll over both the global fetch and the register load pipeline to ensure
  666. // all shared memory accesses are static. Note that both pipelines have even
  667. // length meaning that the next iteration will always start at index 0.
  668. #pragma unroll
  669. for (int pipe = 0; pipe < stages;) {
  670. #pragma unroll
  671. for (int k = 0; k < b_sh_wr_iters; k++) {
  672. fetch_to_registers(k + 1, pipe % stages);
  673. if (k == b_sh_wr_iters - 2) {
  674. fetch_to_shared((pipe + stages - 1) % stages, pipe,
  675. slice_iters >= stages);
  676. pipe++;
  677. wait_for_stage();
  678. }
  679. matmul(k);
  680. }
  681. slice_iters--;
  682. if (slice_iters == 0)
  683. break;
  684. }
  685. a_gl_rd += a_gl_rd_delta_o * stages;
  686. // Process results and, if necessary, proceed to the next column slice.
  687. // While this pattern may not be the most readable, other ways of writing
  688. // the loop seemed to noticeably worse performance after compilation.
  689. if (slice_iters == 0) {
  690. cp_async_wait<0>();
  691. bool last = slice_idx == slice_count - 1;
  692. // For per-column scales, we only fetch them here in the final step before
  693. // write-out
  694. if (group_blocks == -1 && last) {
  695. if (s_sh_wr_pred)
  696. cp_async4_stream(&sh_s[s_sh_wr], &s[s_gl_rd]);
  697. cp_async_fence();
  698. }
  699. thread_block_reduce();
  700. if (group_blocks == -1 && last) {
  701. cp_async_wait<0>();
  702. __syncthreads();
  703. if (threadIdx.x / 32 < thread_n_blocks / 4) {
  704. reinterpret_cast<int4 *>(&frag_s)[0] = sh_s[s_sh_rd + 0];
  705. reinterpret_cast<int4 *>(&frag_s)[1] = sh_s[s_sh_rd + 4];
  706. }
  707. }
  708. if (slice_count > 1) { // only globally reduce if there is more than one
  709. // block in a slice
  710. barrier_acquire(&locks[slice_col], slice_idx);
  711. global_reduce(slice_idx == 0, last);
  712. barrier_release(&locks[slice_col], last);
  713. }
  714. if (last) // only the last block in a slice actually writes the result
  715. write_result();
  716. slice_row = 0;
  717. slice_col_par++;
  718. slice_col++;
  719. init_slice();
  720. if (slice_iters) {
  721. a_gl_rd = a_gl_stride * (threadIdx.x / a_gl_rd_delta_o) +
  722. (threadIdx.x % a_gl_rd_delta_o);
  723. #pragma unroll
  724. for (int i = 0; i < b_sh_wr_iters; i++)
  725. B_ptr[i] += b_sh_stride - b_gl_rd_delta_o * k_tiles;
  726. if (slice_col == 0) {
  727. #pragma unroll
  728. for (int i = 0; i < b_sh_wr_iters; i++)
  729. B_ptr[i] -= b_gl_stride;
  730. }
  731. s_gl_rd = s_sh_stride * slice_col + threadIdx.x;
  732. start_pipes();
  733. }
  734. }
  735. }
  736. }
  737. #else
  738. template <const int threads, // number of threads in a threadblock
  739. const int thread_m_blocks, // number of 16x16 blocks in the m
  740. // dimension (batchsize) of the threadblock
  741. const int thread_n_blocks, // same for n dimension (output)
  742. const int thread_k_blocks, // same for k dimension (reduction)
  743. const int stages, // number of stages for the async global->shared
  744. // fetch pipeline
  745. const int group_blocks = -1 // number of consecutive 16x16 blocks with
  746. // a separate quantization scale
  747. >
  748. __global__ void
  749. Marlin(const int4 *__restrict__ A, // fp16 input matrix of shape mxk
  750. const int4 *__restrict__ B, // 4bit quantized weight matrix of shape kxn
  751. int4 *__restrict__ C, // fp16 output buffer of shape mxn
  752. const int4
  753. *__restrict__ s, // fp16 quantization scales of shape (k/groupsize)xn
  754. int prob_m, // batch dimension m
  755. int prob_n, // output dimension n
  756. int prob_k, // reduction dimension k
  757. int *locks // extra global storage for barrier synchronization
  758. ) {
  759. // Marlin is not implemented yet for SM < 8.0
  760. assert(false);
  761. return;
  762. }
  763. #endif
  764. // 8 warps are a good choice since every SM has 4 schedulers and having more
  765. // than 1 warp per schedule allows some more latency hiding. At the same time,
  766. // we want relatively few warps to have many registers per warp and small tiles.
  767. const int USER_THREADS =
  768. 256; // Note: This is only used with user-provided thread_k/n
  769. const int STAGES = 4; // 4 pipeline stages fit into shared memory
  770. const int SHARED_MEM =
  771. 96 * 1024; // max shared memory on compute capability 8.6 (< 8.0)
  772. static constexpr int min_thread_n = 64;
  773. static constexpr int min_thread_k = 64;
  774. static constexpr int tile_size = 16;
  775. static constexpr int max_par = 16;
  776. static constexpr int pack_factor_4bit =
  777. 8; // We have 8 4-bit vals inside a 32 bit
  778. #define __CALL_IF(THREAD_M_BLOCKS, THREAD_N_BLOCKS, THREAD_K_BLOCKS, \
  779. GROUP_BLOCKS, NUM_THREADS) \
  780. else if (thread_m_blocks == THREAD_M_BLOCKS && \
  781. thread_n_blocks == THREAD_N_BLOCKS && \
  782. thread_k_blocks == THREAD_K_BLOCKS && \
  783. group_blocks == GROUP_BLOCKS && num_threads == NUM_THREADS) { \
  784. cudaFuncSetAttribute(Marlin<NUM_THREADS, THREAD_M_BLOCKS, THREAD_N_BLOCKS, \
  785. THREAD_K_BLOCKS, STAGES, GROUP_BLOCKS>, \
  786. cudaFuncAttributeMaxDynamicSharedMemorySize, \
  787. SHARED_MEM); \
  788. Marlin<NUM_THREADS, THREAD_M_BLOCKS, THREAD_N_BLOCKS, THREAD_K_BLOCKS, \
  789. STAGES, GROUP_BLOCKS><<<blocks, NUM_THREADS, SHARED_MEM, stream>>>( \
  790. A_ptr, B_ptr, C_ptr, s_ptr, prob_m, prob_n, prob_k, locks); \
  791. }
  792. typedef struct {
  793. int thread_k;
  794. int thread_n;
  795. int num_threads;
  796. } thread_config_t;
  797. thread_config_t small_batch_thread_configs[] = {
  798. // Ordered by priority
  799. // thread_k, thread_n, num_threads
  800. {128, 128, 256}, // Default
  801. {128, 64, 128}, // Reduce N 2X, same K
  802. {64, 256, 256}, // Reduce K 2X, increase N 2X
  803. {64, 128, 128}, // Reduce K 2X, same N
  804. };
  805. thread_config_t large_batch_thread_configs[] = {
  806. // Ordered by priority
  807. // thread_k, thread_n, num_threads
  808. {64, 256, 256}, // Default
  809. {128, 128, 256}, // Reduce N 2X, increase K 2X
  810. {64, 128, 128}, // Reduce N 2X, same K
  811. {128, 64, 128}, // Reduce N 4X, increase K 2X
  812. };
  813. bool is_valid_config(thread_config_t const &th_config, int prob_m, int prob_n,
  814. int prob_k) {
  815. // Sanity
  816. if (th_config.thread_k == -1 || th_config.thread_n == -1 ||
  817. th_config.num_threads == -1) {
  818. return false;
  819. }
  820. // Verify K/N are divisible by thread K/N
  821. if (prob_k % th_config.thread_k != 0 || prob_n % th_config.thread_n != 0) {
  822. return false;
  823. }
  824. // thread_k can be only 128 or 64 (because it must be less than groupsize
  825. // which is 128)
  826. if (th_config.thread_k != 128 && th_config.thread_k != 64) {
  827. return false;
  828. }
  829. // Verify min for thread K/N
  830. if (th_config.thread_n < min_thread_n || th_config.thread_k < min_thread_k) {
  831. return false;
  832. }
  833. // num_threads must be at least 128 (= 4 warps)
  834. if (th_config.num_threads < 128) {
  835. return false;
  836. }
  837. return true;
  838. }
  839. thread_config_t determine_thread_config(int prob_m, int prob_n, int prob_k) {
  840. if (prob_m <= 16) {
  841. for (auto th_config : small_batch_thread_configs) {
  842. if (is_valid_config(th_config, prob_m, prob_n, prob_k)) {
  843. return th_config;
  844. }
  845. }
  846. } else {
  847. for (auto th_config : large_batch_thread_configs) {
  848. if (is_valid_config(th_config, prob_m, prob_n, prob_k)) {
  849. return th_config;
  850. }
  851. }
  852. }
  853. return thread_config_t{-1, -1, -1};
  854. }
  855. #define CALL_IF(N_BLOCKS, K_BLOCKS, NUM_THREADS) \
  856. __CALL_IF(1, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
  857. __CALL_IF(1, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS) \
  858. __CALL_IF(1, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
  859. __CALL_IF(1, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS) \
  860. __CALL_IF(2, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
  861. __CALL_IF(2, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS) \
  862. __CALL_IF(3, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
  863. __CALL_IF(3, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS) \
  864. __CALL_IF(4, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
  865. __CALL_IF(4, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS)
  866. void marlin_cuda(const void *A, const void *B, void *C, void *s, int prob_m,
  867. int prob_n, int prob_k, void *workspace, int groupsize = -1,
  868. int dev = 0, cudaStream_t stream = 0, int thread_k = -1,
  869. int thread_n = -1, int sms = -1, int max_par = 16) {
  870. int tot_m = prob_m;
  871. int tot_m_blocks = ceildiv(tot_m, 16);
  872. int pad = 16 * tot_m_blocks - tot_m;
  873. if (sms == -1)
  874. cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev);
  875. // Set thread config
  876. thread_config_t th_config;
  877. if (thread_k != -1 && thread_n != -1) {
  878. // User-defined config
  879. th_config = thread_config_t{thread_k, thread_n, USER_THREADS};
  880. } else {
  881. // Auto config
  882. th_config = determine_thread_config(prob_m, prob_n, prob_k);
  883. }
  884. if (!is_valid_config(th_config, prob_m, prob_n, prob_k)) {
  885. throw std::runtime_error(
  886. "Invalid thread config: thread_k = " + str(th_config.thread_k) +
  887. ", thread_n = " + str(th_config.thread_n) +
  888. ", num_threads = " + str(th_config.num_threads) + " for MKN = [" +
  889. str(prob_m) + ", " + str(prob_k) + ", " + str(prob_n) + "]");
  890. }
  891. // Uncomment for debug
  892. // std::cout << "Using thread_config: thread_k = " + str(th_config.thread_k) +
  893. // ", thread_n = " + str(th_config.thread_n) +
  894. // ", num_threads = " + str(th_config.num_threads) + " for
  895. // MKN = [" + str(prob_m) +
  896. // ", " + str(prob_k) + ", " + str(prob_n) + "]\n";
  897. int num_threads = th_config.num_threads;
  898. thread_k = th_config.thread_k;
  899. thread_n = th_config.thread_n;
  900. int thread_k_blocks = thread_k / 16;
  901. int thread_n_blocks = thread_n / 16;
  902. int group_blocks = (groupsize == -1) ? -1 : groupsize / 16;
  903. int blocks = sms;
  904. if (prob_m == 0 || prob_n == 0 || prob_k == 0) {
  905. return;
  906. }
  907. TORCH_CHECK(prob_n % thread_n == 0, "prob_n = ", prob_n,
  908. " is not divisible by thread_n = ", thread_n);
  909. TORCH_CHECK(prob_k % thread_k == 0, "prob_k = ", prob_k,
  910. " is not divisible by thread_k = ", thread_k);
  911. if (group_blocks != -1) {
  912. TORCH_CHECK(prob_k % group_blocks == 0, "prob_k = ", prob_k,
  913. " is not divisible by group_blocks = ", group_blocks);
  914. }
  915. const int4 *A_ptr = (const int4 *)A;
  916. const int4 *B_ptr = (const int4 *)B;
  917. int4 *C_ptr = (int4 *)C;
  918. const int4 *s_ptr = (const int4 *)s;
  919. int *locks = (int *)workspace;
  920. for (int i = 0; i < tot_m_blocks; i += 4) {
  921. int thread_m_blocks = tot_m_blocks - i;
  922. prob_m = tot_m - 16 * i;
  923. int par = 1;
  924. if (thread_m_blocks > 4) {
  925. // Note that parallel > 1 currently only works for inputs without any
  926. // padding
  927. par = (16 * thread_m_blocks - pad) / 64;
  928. if (par > max_par)
  929. par = max_par;
  930. prob_m = 64 * par;
  931. i += 4 * (par - 1);
  932. thread_m_blocks = 4;
  933. }
  934. // For compilation speed, we only define the kernel configurations that have
  935. // seemed useful (in terms of performance) in our testing, however many more
  936. // are, in principle, possible.
  937. if (false) {
  938. }
  939. CALL_IF(8, 8, 256)
  940. CALL_IF(16, 4, 256)
  941. CALL_IF(8, 4, 128)
  942. CALL_IF(4, 8, 128)
  943. else {
  944. throw std::runtime_error("Unsupported shapes: MKN = [" + str(prob_m) +
  945. ", " + str(prob_k) + ", " + str(prob_n) + "]" +
  946. ", groupsize = " + str(groupsize) +
  947. ", thread_m_blocks = " + str(thread_m_blocks) +
  948. ", thread_n_blocks = " + str(thread_n_blocks) +
  949. ", thread_k_blocks = " + str(thread_k_blocks));
  950. }
  951. A_ptr += 16 * thread_m_blocks * (prob_k / 8) * par;
  952. C_ptr += 16 * thread_m_blocks * (prob_n / 8) * par;
  953. }
  954. }
  955. } // namespace marlin
  956. torch::Tensor marlin_gemm(torch::Tensor &a, torch::Tensor &b_q_weight,
  957. torch::Tensor &b_scales, torch::Tensor &workspace,
  958. int64_t size_m, int64_t size_n, int64_t size_k) {
  959. // Verify M
  960. TORCH_CHECK(size_m == a.size(0),
  961. "Shape mismatch: a.size(0) = " + str(a.size(0)) +
  962. ", size_m = " + str(size_m));
  963. // Verify K
  964. TORCH_CHECK(size_k == a.size(1),
  965. "Shape mismatch: a.size(1) = " + str(a.size(1)) +
  966. ", size_k = " + str(size_k));
  967. TORCH_CHECK(size_k % marlin::tile_size == 0,
  968. "size_k = " + str(size_k) +
  969. " is not divisible by tile_size = " + str(marlin::tile_size));
  970. TORCH_CHECK((size_k / marlin::tile_size) == b_q_weight.size(0),
  971. "Shape mismatch: b_q_weight.size(0) = " +
  972. str(b_q_weight.size(0)) + ", size_k = " + str(size_k) +
  973. ", tile_size = " + str(marlin::tile_size));
  974. // Verify N
  975. TORCH_CHECK(b_scales.size(1) == size_n,
  976. "b_scales.size(1) = " + str(b_scales.size(1)) +
  977. ", size_n = " + str(size_n));
  978. TORCH_CHECK(b_q_weight.size(1) % marlin::tile_size == 0,
  979. "b_q_weight.size(1) = " + str(b_q_weight.size(1)) +
  980. " is not divisible by tile_size = " + str(marlin::tile_size));
  981. int actual_size_n =
  982. (b_q_weight.size(1) / marlin::tile_size) * marlin::pack_factor_4bit;
  983. TORCH_CHECK(size_n == actual_size_n,
  984. "size_n = " + str(size_n) +
  985. ", actual_size_n = " + str(actual_size_n));
  986. // Verify A device and strides
  987. TORCH_CHECK(a.device().is_cuda(), "A is not on GPU");
  988. TORCH_CHECK(a.is_contiguous(), "A is not contiguous");
  989. // Verify B device and strides
  990. TORCH_CHECK(b_q_weight.device().is_cuda(), "b_q_weight is not on GPU");
  991. TORCH_CHECK(b_q_weight.is_contiguous(), "b_q_weight is not contiguous");
  992. // Verify scales device and strides
  993. TORCH_CHECK(b_scales.device().is_cuda(), "b_scales is not on GPU");
  994. TORCH_CHECK(b_scales.is_contiguous(), "b_scales is not contiguous");
  995. // Alloc C matrix
  996. const at::cuda::OptionalCUDAGuard device_guard(device_of(a));
  997. auto options = torch::TensorOptions().dtype(a.dtype()).device(a.device());
  998. torch::Tensor c = torch::empty({size_m, size_n}, options);
  999. // thread_k: `k` size of a thread_tile in `weights` (can usually be left as
  1000. // auto -1)
  1001. int thread_k = -1;
  1002. // thread_n: `n` size of a thread_tile in `weights` (can usually be left as
  1003. // auto -1)
  1004. int thread_n = -1;
  1005. // sms: number of SMs to use for the kernel (can usually be left as auto -1)
  1006. int sms = -1;
  1007. // Detect groupsize
  1008. if (b_scales.size(0) != 1) {
  1009. TORCH_CHECK(size_k % b_scales.size(0) == 0,
  1010. "size_k = " + str(size_k) +
  1011. ", is not divisible by b_scales.size(0) = " +
  1012. str(b_scales.size(0)));
  1013. }
  1014. int groupsize = b_scales.size(0) == 1 ? -1 : size_k / b_scales.size(0);
  1015. // Verify groupsize
  1016. TORCH_CHECK(groupsize == -1 || groupsize == 128,
  1017. "Unexpected groupsize = " + str(groupsize));
  1018. // Verify workspace size
  1019. TORCH_CHECK(
  1020. size_n % marlin::min_thread_n == 0,
  1021. "size_n = " + str(size_n) +
  1022. ", is not divisible by min_thread_n = " + str(marlin::min_thread_n));
  1023. int min_workspace_size = (size_n / marlin::min_thread_n) * marlin::max_par;
  1024. TORCH_CHECK(workspace.numel() >= min_workspace_size,
  1025. "workspace.numel = " + str(workspace.numel()) +
  1026. " is below min_workspace_size = " + str(min_workspace_size));
  1027. int dev = a.get_device();
  1028. marlin::marlin_cuda(a.data_ptr(), b_q_weight.data_ptr(), c.data_ptr(),
  1029. b_scales.data_ptr(), size_m, size_n, size_k,
  1030. workspace.data_ptr(), groupsize, dev,
  1031. at::cuda::getCurrentCUDAStream(dev), thread_k, thread_n,
  1032. sms, marlin::max_par);
  1033. return c;
  1034. }