@tduncan / Nvidia-Optimization-Stack-VLLM Mirror · read-only / commits / c0c2335ce0
Fork 0

A high-throughput and memory-efficient inference and serving engine for LLMs

Mirrored from https://github.com/tduncan-lum/Nvidia-Optimization-Stack---VLLM.git

Synced Nov 17, 04:15 UTC

Integrate Marlin Kernels for Int4 GPTQ inference (#2497)

Co-authored-by: Robert Shaw <114415538+rib-2@users.noreply.github.com> Co-authored-by: alexm <alexm@neuralmagic.com>

Robert Shaw committed Mar 1, 2024 at 14:47 UTC c0c2335ce027486d254c31f665ce00d7db427d22
12 files changed +1752 -6
csrc/ops.h
+9
@@ -84,6 +84,15 @@ torch::Tensor awq_dequantize(
84 int split_k_iters,
85 int thx,
86 int thy);
87 +
88 +torch::Tensor marlin_gemm(
89 + torch::Tensor& a,
90 + torch::Tensor& b_q_weight,
91 + torch::Tensor& b_scales,
92 + torch::Tensor& workspace,
93 + int64_t size_m,
94 + int64_t size_n,
95 + int64_t size_k);
96 #endif
97
98 void squeezellm_gemm(
csrc/pybind.cpp
+3 -1
@@ -52,11 +52,13 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
52 &rotary_embedding,
53 "Apply GPT-NeoX or GPT-J style rotary embedding to query and key");
54
55 - // Quantization ops
55 +// Quantization ops
56 #ifndef USE_ROCM
57 ops.def("awq_gemm", &awq_gemm, "Quantized GEMM for AWQ");
58 + ops.def("marlin_gemm", &marlin_gemm, "Marlin Optimized Quantized GEMM for GPTQ");
59 ops.def("awq_dequantize", &awq_dequantize, "Dequantization for AWQ");
60 #endif
61 +
62 ops.def("gptq_gemm", &gptq_gemm, "Quantized GEMM for GPTQ");
63 ops.def("gptq_shuffle", &gptq_shuffle, "Post processing for GPTQ");
64 ops.def("squeezellm_gemm", &squeezellm_gemm, "Quantized GEMM for SqueezeLLM");
csrc/quantization/marlin/LICENSE new
+209
@@ -0,0 +1,209 @@
1 +Contains code from https://github.com/IST-DASLab/marlin
2 +
3 + Apache License
4 + Version 2.0, January 2004
5 + http://www.apache.org/licenses/
6 +
7 + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8 +
9 + 1. Definitions.
10 +
11 + "License" shall mean the terms and conditions for use, reproduction,
12 + and distribution as defined by Sections 1 through 9 of this document.
13 +
14 + "Licensor" shall mean the copyright owner or entity authorized by
15 + the copyright owner that is granting the License.
16 +
17 + "Legal Entity" shall mean the union of the acting entity and all
18 + other entities that control, are controlled by, or are under common
19 + control with that entity. For the purposes of this definition,
20 + "control" means (i) the power, direct or indirect, to cause the
21 + direction or management of such entity, whether by contract or
22 + otherwise, or (ii) ownership of fifty percent (50%) or more of the
23 + outstanding shares, or (iii) beneficial ownership of such entity.
24 +
25 + "You" (or "Your") shall mean an individual or Legal Entity
26 + exercising permissions granted by this License.
27 +
28 + "Source" form shall mean the preferred form for making modifications,
29 + including but not limited to software source code, documentation
30 + source, and configuration files.
31 +
32 + "Object" form shall mean any form resulting from mechanical
33 + transformation or translation of a Source form, including but
34 + not limited to compiled object code, generated documentation,
35 + and conversions to other media types.
36 +
37 + "Work" shall mean the work of authorship, whether in Source or
38 + Object form, made available under the License, as indicated by a
39 + copyright notice that is included in or attached to the work
40 + (an example is provided in the Appendix below).
41 +
42 + "Derivative Works" shall mean any work, whether in Source or Object
43 + form, that is based on (or derived from) the Work and for which the
44 + editorial revisions, annotations, elaborations, or other modifications
45 + represent, as a whole, an original work of authorship. For the purposes
46 + of this License, Derivative Works shall not include works that remain
47 + separable from, or merely link (or bind by name) to the interfaces of,
48 + the Work and Derivative Works thereof.
49 +
50 + "Contribution" shall mean any work of authorship, including
51 + the original version of the Work and any modifications or additions
52 + to that Work or Derivative Works thereof, that is intentionally
53 + submitted to Licensor for inclusion in the Work by the copyright owner
54 + or by an individual or Legal Entity authorized to submit on behalf of
55 + the copyright owner. For the purposes of this definition, "submitted"
56 + means any form of electronic, verbal, or written communication sent
57 + to the Licensor or its representatives, including but not limited to
58 + communication on electronic mailing lists, source code control systems,
59 + and issue tracking systems that are managed by, or on behalf of, the
60 + Licensor for the purpose of discussing and improving the Work, but
61 + excluding communication that is conspicuously marked or otherwise
62 + designated in writing by the copyright owner as "Not a Contribution."
63 +
64 + "Contributor" shall mean Licensor and any individual or Legal Entity
65 + on behalf of whom a Contribution has been received by Licensor and
66 + subsequently incorporated within the Work.
67 +
68 + 2. Grant of Copyright License. Subject to the terms and conditions of
69 + this License, each Contributor hereby grants to You a perpetual,
70 + worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71 + copyright license to reproduce, prepare Derivative Works of,
72 + publicly display, publicly perform, sublicense, and distribute the
73 + Work and such Derivative Works in Source or Object form.
74 +
75 + 3. Grant of Patent License. Subject to the terms and conditions of
76 + this License, each Contributor hereby grants to You a perpetual,
77 + worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78 + (except as stated in this section) patent license to make, have made,
79 + use, offer to sell, sell, import, and otherwise transfer the Work,
80 + where such license applies only to those patent claims licensable
81 + by such Contributor that are necessarily infringed by their
82 + Contribution(s) alone or by combination of their Contribution(s)
83 + with the Work to which such Contribution(s) was submitted. If You
84 + institute patent litigation against any entity (including a
85 + cross-claim or counterclaim in a lawsuit) alleging that the Work
86 + or a Contribution incorporated within the Work constitutes direct
87 + or contributory patent infringement, then any patent licenses
88 + granted to You under this License for that Work shall terminate
89 + as of the date such litigation is filed.
90 +
91 + 4. Redistribution. You may reproduce and distribute copies of the
92 + Work or Derivative Works thereof in any medium, with or without
93 + modifications, and in Source or Object form, provided that You
94 + meet the following conditions:
95 +
96 + (a) You must give any other recipients of the Work or
97 + Derivative Works a copy of this License; and
98 +
99 + (b) You must cause any modified files to carry prominent notices
100 + stating that You changed the files; and
101 +
102 + (c) You must retain, in the Source form of any Derivative Works
103 + that You distribute, all copyright, patent, trademark, and
104 + attribution notices from the Source form of the Work,
105 + excluding those notices that do not pertain to any part of
106 + the Derivative Works; and
107 +
108 + (d) If the Work includes a "NOTICE" text file as part of its
109 + distribution, then any Derivative Works that You distribute must
110 + include a readable copy of the attribution notices contained
111 + within such NOTICE file, excluding those notices that do not
112 + pertain to any part of the Derivative Works, in at least one
113 + of the following places: within a NOTICE text file distributed
114 + as part of the Derivative Works; within the Source form or
115 + documentation, if provided along with the Derivative Works; or,
116 + within a display generated by the Derivative Works, if and
117 + wherever such third-party notices normally appear. The contents
118 + of the NOTICE file are for informational purposes only and
119 + do not modify the License. You may add Your own attribution
120 + notices within Derivative Works that You distribute, alongside
121 + or as an addendum to the NOTICE text from the Work, provided
122 + that such additional attribution notices cannot be construed
123 + as modifying the License.
124 +
125 + You may add Your own copyright statement to Your modifications and
126 + may provide additional or different license terms and conditions
127 + for use, reproduction, or distribution of Your modifications, or
128 + for any such Derivative Works as a whole, provided Your use,
129 + reproduction, and distribution of the Work otherwise complies with
130 + the conditions stated in this License.
131 +
132 + 5. Submission of Contributions. Unless You explicitly state otherwise,
133 + any Contribution intentionally submitted for inclusion in the Work
134 + by You to the Licensor shall be under the terms and conditions of
135 + this License, without any additional terms or conditions.
136 + Notwithstanding the above, nothing herein shall supersede or modify
137 + the terms of any separate license agreement you may have executed
138 + with Licensor regarding such Contributions.
139 +
140 + 6. Trademarks. This License does not grant permission to use the trade
141 + names, trademarks, service marks, or product names of the Licensor,
142 + except as required for reasonable and customary use in describing the
143 + origin of the Work and reproducing the content of the NOTICE file.
144 +
145 + 7. Disclaimer of Warranty. Unless required by applicable law or
146 + agreed to in writing, Licensor provides the Work (and each
147 + Contributor provides its Contributions) on an "AS IS" BASIS,
148 + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149 + implied, including, without limitation, any warranties or conditions
150 + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151 + PARTICULAR PURPOSE. You are solely responsible for determining the
152 + appropriateness of using or redistributing the Work and assume any
153 + risks associated with Your exercise of permissions under this License.
154 +
155 + 8. Limitation of Liability. In no event and under no legal theory,
156 + whether in tort (including negligence), contract, or otherwise,
157 + unless required by applicable law (such as deliberate and grossly
158 + negligent acts) or agreed to in writing, shall any Contributor be
159 + liable to You for damages, including any direct, indirect, special,
160 + incidental, or consequential damages of any character arising as a
161 + result of this License or out of the use or inability to use the
162 + Work (including but not limited to damages for loss of goodwill,
163 + work stoppage, computer failure or malfunction, or any and all
164 + other commercial damages or losses), even if such Contributor
165 + has been advised of the possibility of such damages.
166 +
167 + 9. Accepting Warranty or Additional Liability. While redistributing
168 + the Work or Derivative Works thereof, You may choose to offer,
169 + and charge a fee for, acceptance of support, warranty, indemnity,
170 + or other liability obligations and/or rights consistent with this
171 + License. However, in accepting such obligations, You may act only
172 + on Your own behalf and on Your sole responsibility, not on behalf
173 + of any other Contributor, and only if You agree to indemnify,
174 + defend, and hold each Contributor harmless for any liability
175 + incurred by, or claims asserted against, such Contributor by reason
176 + of your accepting any such warranty or additional liability.
177 +
178 + END OF TERMS AND CONDITIONS
179 +
180 + APPENDIX: How to apply the Apache License to your work.
181 +
182 + To apply the Apache License to your work, attach the following
183 + boilerplate notice, with the fields enclosed by brackets "{}"
184 + replaced with your own identifying information. (Don't include
185 + the brackets!) The text should be enclosed in the appropriate
186 + comment syntax for the file format. We also recommend that a
187 + file or class name and description of purpose be included on the
188 + same "printed page" as the copyright notice for easier
189 + identification within third-party archives.
190 +
191 + Copyright {yyyy} {name of copyright owner}
192 +
193 + Licensed under the Apache License, Version 2.0 (the "License");
194 + you may not use this file except in compliance with the License.
195 + You may obtain a copy of the License at
196 +
197 + http://www.apache.org/licenses/LICENSE-2.0
198 +
199 + Unless required by applicable law or agreed to in writing, software
200 + distributed under the License is distributed on an "AS IS" BASIS,
201 + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202 + See the License for the specific language governing permissions and
203 + limitations under the License.
204 +
205 +------------------------------------------------------------------------------------
206 +
207 +This product bundles various third-party components under other open source licenses.
208 +This section summarizes those components and their licenses. See licenses/
209 +for text of these licenses.
csrc/quantization/marlin/marlin_cuda_kernel.cu new
+1145
@@ -0,0 +1,1145 @@
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 +
18 +#include <torch/extension.h>
19 +
20 +#include <ATen/cuda/CUDAContext.h>
21 +#include <c10/cuda/CUDAGuard.h>
22 +#include <cuda.h>
23 +#include <cuda_fp16.h>
24 +#include <cuda_runtime.h>
25 +
26 +#include <iostream>
27 +
28 +template <typename T> inline std::string str(T x) { return std::to_string(x); }
29 +
30 +namespace marlin {
31 +
32 +constexpr int ceildiv(int a, int b) { return (a + b - 1) / b; }
33 +
34 +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
35 +
36 +// Instances of `Vec` are used to organize groups of >>registers<<, as needed
37 +// for instance as inputs to tensor core operations. Consequently, all
38 +// corresponding index accesses must be compile-time constants, which is why we
39 +// extensively use `#pragma unroll` throughout the kernel code to guarantee
40 +// this.
41 +template <typename T, int n> struct Vec {
42 + T elems[n];
43 + __device__ T &operator[](int i) { return elems[i]; }
44 +};
45 +
46 +using I4 = Vec<int, 4>;
47 +
48 +// Matrix fragments for tensor core instructions; their precise layout is
49 +// documented here:
50 +// https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#matrix-fragments-for-mma-m16n8k16-with-floating-point-type
51 +using FragA = Vec<half2, 4>;
52 +using FragB = Vec<half2, 2>;
53 +using FragC = Vec<float, 4>;
54 +using FragS = Vec<half2, 1>; // quantization scales
55 +
56 +// Predicated asynchronous global->shared copy; used for inputs A where we apply
57 +// predication to handle batchsizes that are not multiples of 16.
58 +__device__ inline void cp_async4_pred(void *smem_ptr, const void *glob_ptr,
59 + bool pred = true) {
60 + const int BYTES = 16;
61 + uint32_t smem = static_cast<uint32_t>(__cvta_generic_to_shared(smem_ptr));
62 + asm volatile("{\n"
63 + " .reg .pred p;\n"
64 + " setp.ne.b32 p, %0, 0;\n"
65 + " @p cp.async.cg.shared.global [%1], [%2], %3;\n"
66 + "}\n" ::"r"((int)pred),
67 + "r"(smem), "l"(glob_ptr), "n"(BYTES));
68 +}
69 +
70 +// Asynchronous global->shared copy with a cache hint indicating that the values
71 +// may be evicted immediately; used for quantized weights B, which are only
72 +// accessed precisely once and should thus not pollute the L2 cache which we
73 +// need for inputs A and outputs C.
74 +__device__ inline void cp_async4_stream(void *smem_ptr, const void *glob_ptr) {
75 + const int BYTES = 16;
76 + uint32_t smem = static_cast<uint32_t>(__cvta_generic_to_shared(smem_ptr));
77 + asm volatile(
78 + "{\n"
79 + " .reg .b64 p;\n"
80 + " createpolicy.fractional.L2::evict_first.b64 p, 1.0;"
81 + " cp.async.cg.shared.global.L2::cache_hint [%0], [%1], %2, p;\n"
82 + "}\n" ::"r"(smem),
83 + "l"(glob_ptr), "n"(BYTES));
84 +}
85 +
86 +// Async copy fence.
87 +__device__ inline void cp_async_fence() {
88 + asm volatile("cp.async.commit_group;\n" ::);
89 +}
90 +
91 +// Wait until at most `n` async copy stages are still pending.
92 +template <int n> __device__ inline void cp_async_wait() {
93 + asm volatile("cp.async.wait_group %0;\n" ::"n"(n));
94 +}
95 +
96 +// m16n8k16 tensor core mma instruction with fp16 inputs and fp32
97 +// output/accumulation.
98 +__device__ inline void mma(const FragA &a_frag, const FragB &frag_b,
99 + FragC &frag_c) {
100 + const uint32_t *a = reinterpret_cast<const uint32_t *>(&a_frag);
101 + const uint32_t *b = reinterpret_cast<const uint32_t *>(&frag_b);
102 + float *c = reinterpret_cast<float *>(&frag_c);
103 + asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 "
104 + "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%10,%11,%12,%13};\n"
105 + : "=f"(c[0]), "=f"(c[1]), "=f"(c[2]), "=f"(c[3])
106 + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]),
107 + "r"(b[1]), "f"(c[0]), "f"(c[1]), "f"(c[2]), "f"(c[3]));
108 +}
109 +
110 +// Instruction for loading a full 16x16 matrix fragment of operand A from shared
111 +// memory, directly in tensor core layout.
112 +__device__ inline void ldsm4(FragA &frag_a, const void *smem_ptr) {
113 + uint32_t *a = reinterpret_cast<uint32_t *>(&frag_a);
114 + uint32_t smem = static_cast<uint32_t>(__cvta_generic_to_shared(smem_ptr));
115 + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
116 + : "=r"(a[0]), "=r"(a[1]), "=r"(a[2]), "=r"(a[3])
117 + : "r"(smem));
118 +}
119 +
120 +// Lookup-table based 3-input logical operation; explicitly used for
121 +// dequantization as the compiler does not seem to automatically recognize it in
122 +// all cases.
123 +template <int lut> __device__ inline int lop3(int a, int b, int c) {
124 + int res;
125 + asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
126 + : "=r"(res)
127 + : "r"(a), "r"(b), "r"(c), "n"(lut));
128 + return res;
129 +}
130 +
131 +// Efficiently dequantize an int32 value into a full B-fragment of 4 fp16
132 +// values. We mostly follow the strategy in the link below, with some small
133 +// changes:
134 +// https://github.com/NVIDIA/FasterTransformer/blob/main/src/fastertransformer/cutlass_extensions/include/cutlass_extensions/interleaved_numeric_conversion.h
135 +__device__ inline FragB dequant(int q) {
136 + const int LO = 0x000f000f;
137 + const int HI = 0x00f000f0;
138 + const int EX = 0x64006400;
139 + // Guarantee that the `(a & b) | c` operations are LOP3s.
140 + int lo = lop3<(0xf0 & 0xcc) | 0xaa>(q, LO, EX);
141 + int hi = lop3<(0xf0 & 0xcc) | 0xaa>(q, HI, EX);
142 + // We want signed int4 outputs, hence we fuse the `-8` symmetric zero point
143 + // directly into `SUB` and `ADD`.
144 + const int SUB = 0x64086408;
145 + const int MUL = 0x2c002c00;
146 + const int ADD = 0xd480d480;
147 + FragB frag_b;
148 + frag_b[0] = __hsub2(*reinterpret_cast<half2 *>(&lo),
149 + *reinterpret_cast<const half2 *>(&SUB));
150 + frag_b[1] = __hfma2(*reinterpret_cast<half2 *>(&hi),
151 + *reinterpret_cast<const half2 *>(&MUL),
152 + *reinterpret_cast<const half2 *>(&ADD));
153 + return frag_b;
154 +}
155 +
156 +// Multiply dequantized values by the corresponding quantization scale; used
157 +// only for grouped quantization.
158 +__device__ inline void scale(FragB &frag_b, FragS &frag_s, int i) {
159 + half2 s = __half2half2(reinterpret_cast<__half *>(&frag_s)[i]);
160 + frag_b[0] = __hmul2(frag_b[0], s);
161 + frag_b[1] = __hmul2(frag_b[1], s);
162 +}
163 +
164 +// Wait until barrier reaches `count`, then lock for current threadblock.
165 +__device__ inline void barrier_acquire(int *lock, int count) {
166 + if (threadIdx.x == 0) {
167 + int state = -1;
168 + do
169 + // Guarantee that subsequent writes by this threadblock will be visible
170 + // globally.
171 + asm volatile("ld.global.acquire.gpu.b32 %0, [%1];\n"
172 + : "=r"(state)
173 + : "l"(lock));
174 + while (state != count);
175 + }
176 + __syncthreads();
177 +}
178 +
179 +// Release barrier and increment visitation count.
180 +__device__ inline void barrier_release(int *lock, bool reset = false) {
181 + __syncthreads();
182 + if (threadIdx.x == 0) {
183 + if (reset) {
184 + lock[0] = 0;
185 + return;
186 + }
187 + int val = 1;
188 + // Make sure that all writes since acquiring this barrier are visible
189 + // globally, while releasing the barrier.
190 + asm volatile("fence.acq_rel.gpu;\n");
191 + asm volatile("red.relaxed.gpu.global.add.s32 [%0], %1;\n"
192 + :
193 + : "l"(lock), "r"(val));
194 + }
195 +}
196 +
197 +template <const int threads, // number of threads in a threadblock
198 + const int thread_m_blocks, // number of 16x16 blocks in the m
199 + // dimension (batchsize) of the threadblock
200 + const int thread_n_blocks, // same for n dimension (output)
201 + const int thread_k_blocks, // same for k dimension (reduction)
202 + const int stages, // number of stages for the async global->shared
203 + // fetch pipeline
204 + const int group_blocks = -1 // number of consecutive 16x16 blocks with
205 + // a separate quantization scale
206 + >
207 +__global__ void
208 +Marlin(const int4 *__restrict__ A, // fp16 input matrix of shape mxk
209 + const int4 *__restrict__ B, // 4bit quantized weight matrix of shape kxn
210 + int4 *__restrict__ C, // fp16 output buffer of shape mxn
211 + const int4
212 + *__restrict__ s, // fp16 quantization scales of shape (k/groupsize)xn
213 + int prob_m, // batch dimension m
214 + int prob_n, // output dimension n
215 + int prob_k, // reduction dimension k
216 + int *locks // extra global storage for barrier synchronization
217 +) {
218 + // Each threadblock processes one "stripe" of the B matrix with (roughly) the
219 + // same size, which might involve multiple column "slices" (of width 16 *
220 + // `thread_n_blocks`). Stripes are defined as shown in the 3x3 matrix 5 SM
221 + // example:
222 + // 0 1 3
223 + // 0 2 3
224 + // 1 2 4
225 + // While this kind of partitioning makes things somewhat more complicated, it
226 + // ensures good utilization of all SMs for many kinds of shape and GPU
227 + // configurations, while requiring as few slow global cross-threadblock
228 + // reductions as possible.
229 +
230 + // For larger GEMMs we run multiple batchsize 64 versions in parallel for a
231 + // better partitioning with less reductions
232 + int parallel = 1;
233 + if (prob_m > 16 * thread_m_blocks) {
234 + parallel = prob_m / (16 * thread_m_blocks);
235 + prob_m = 16 * thread_m_blocks;
236 + }
237 +
238 + int k_tiles = prob_k / 16 / thread_k_blocks;
239 + int n_tiles = prob_n / 16 / thread_n_blocks;
240 + int iters = ceildiv(k_tiles * n_tiles * parallel, gridDim.x);
241 + // Ensure that the number of tiles in each stripe is a multiple of the
242 + // groupsize; this avoids an annoying special case where a stripe starts in
243 + // the middle of group.
244 + if (group_blocks != -1)
245 + iters = (group_blocks / thread_k_blocks) *
246 + ceildiv(iters, (group_blocks / thread_k_blocks));
247 +
248 + int slice_row = (iters * blockIdx.x) % k_tiles;
249 + int slice_col_par = (iters * blockIdx.x) / k_tiles;
250 + int slice_col = slice_col_par;
251 + int slice_iters; // number of threadblock tiles in the current slice
252 + int slice_count =
253 + 0; // total number of active threadblocks in the current slice
254 + int slice_idx; // index of threadblock in current slice; numbered bottom to
255 + // top
256 +
257 + // We can easily implement parallel problem execution by just remapping
258 + // indices and advancing global pointers
259 + if (slice_col_par >= n_tiles) {
260 + A += (slice_col_par / n_tiles) * 16 * thread_m_blocks * prob_k / 8;
261 + C += (slice_col_par / n_tiles) * 16 * thread_m_blocks * prob_n / 8;
262 + locks += (slice_col_par / n_tiles) * n_tiles;
263 + slice_col = slice_col_par % n_tiles;
264 + }
265 +
266 + // Compute all information about the current slice which is required for
267 + // synchronization.
268 + auto init_slice = [&]() {
269 + slice_iters =
270 + iters * (blockIdx.x + 1) - (k_tiles * slice_col_par + slice_row);
271 + if (slice_iters < 0 || slice_col_par >= n_tiles * parallel)
272 + slice_iters = 0;
273 + if (slice_iters == 0)
274 + return;
275 + if (slice_row + slice_iters > k_tiles)
276 + slice_iters = k_tiles - slice_row;
277 + slice_count = 1;
278 + slice_idx = 0;
279 + int col_first = iters * ceildiv(k_tiles * slice_col_par, iters);
280 + if (col_first <= k_tiles * (slice_col_par + 1)) {
281 + int col_off = col_first - k_tiles * slice_col_par;
282 + slice_count = ceildiv(k_tiles - col_off, iters);
283 + if (col_off > 0)
284 + slice_count++;
285 + int delta_first = iters * blockIdx.x - col_first;
286 + if (delta_first < 0 || (col_off == 0 && delta_first == 0))
287 + slice_idx = slice_count - 1;
288 + else {
289 + slice_idx = slice_count - 1 - delta_first / iters;
290 + if (col_off > 0)
291 + slice_idx--;
292 + }
293 + }
294 + if (slice_col == n_tiles) {
295 + A += 16 * thread_m_blocks * prob_k / 8;
296 + C += 16 * thread_m_blocks * prob_n / 8;
297 + locks += n_tiles;
298 + slice_col = 0;
299 + }
300 + };
301 + init_slice();
302 +
303 + int a_gl_stride = prob_k / 8; // stride of the A matrix in global memory
304 + // We typically use `constexpr` to indicate that this value is a compile-time
305 + // constant
306 + constexpr int a_sh_stride =
307 + 16 * thread_k_blocks / 8; // stride of an A matrix tile in shared memory
308 + constexpr int a_gl_rd_delta_o =
309 + 16 * thread_k_blocks /
310 + 8; // delta between subsequent A tiles in global memory
311 + int a_gl_rd_delta_i =
312 + a_gl_stride *
313 + (threads / a_gl_rd_delta_o); // between subsequent accesses within a tile
314 + constexpr int a_sh_wr_delta =
315 + a_sh_stride * (threads / a_gl_rd_delta_o); // between shared memory writes
316 + constexpr int a_sh_rd_delta_o =
317 + 2 * ((threads / 32) /
318 + (thread_n_blocks / 4)); // between shared memory tile reads
319 + constexpr int a_sh_rd_delta_i =
320 + a_sh_stride * 16; // within a shared memory tile
321 + constexpr int a_sh_stage =
322 + a_sh_stride * (16 * thread_m_blocks); // overall size of a tile
323 + constexpr int a_sh_wr_iters =
324 + ceildiv(a_sh_stage,
325 + a_sh_wr_delta); // number of shared write iterations for a tile
326 +
327 + int b_gl_stride = 16 * prob_n / 32;
328 + constexpr int b_sh_stride = 32 * thread_n_blocks / 4;
329 + int b_gl_rd_delta_o = b_gl_stride * thread_k_blocks;
330 + int b_gl_rd_delta_i = b_gl_stride * (threads / b_sh_stride);
331 + constexpr int b_sh_wr_delta = threads;
332 + constexpr int b_sh_rd_delta = threads;
333 + constexpr int b_sh_stage = b_sh_stride * thread_k_blocks;
334 + constexpr int b_sh_wr_iters = b_sh_stage / b_sh_wr_delta;
335 +
336 + int s_gl_stride = prob_n / 8;
337 + constexpr int s_sh_stride = 16 * thread_n_blocks / 8;
338 + constexpr int s_sh_stage = s_sh_stride;
339 + int s_gl_rd_delta = s_gl_stride;
340 +
341 + // Global A read index of current thread.
342 + int a_gl_rd = a_gl_stride * (threadIdx.x / a_gl_rd_delta_o) +
343 + (threadIdx.x % a_gl_rd_delta_o);
344 + a_gl_rd += a_gl_rd_delta_o * slice_row;
345 + // Shared write index of current thread.
346 + int a_sh_wr = a_sh_stride * (threadIdx.x / a_gl_rd_delta_o) +
347 + (threadIdx.x % a_gl_rd_delta_o);
348 + // Shared read index.
349 + int a_sh_rd =
350 + a_sh_stride * ((threadIdx.x % 32) % 16) + (threadIdx.x % 32) / 16;
351 + a_sh_rd += 2 * ((threadIdx.x / 32) / (thread_n_blocks / 4));
352 +
353 + int b_gl_rd =
354 + b_gl_stride * (threadIdx.x / b_sh_stride) + (threadIdx.x % b_sh_stride);
355 + b_gl_rd += b_sh_stride * slice_col;
356 + b_gl_rd += b_gl_rd_delta_o * slice_row;
357 + int b_sh_wr = threadIdx.x;
358 + int b_sh_rd = threadIdx.x;
359 +
360 + int s_gl_rd = s_gl_stride * ((thread_k_blocks * slice_row) / group_blocks) +
361 + s_sh_stride * slice_col + threadIdx.x;
362 + int s_sh_wr = threadIdx.x;
363 + int s_sh_rd;
364 + // We use a different scale layout for grouped and column-wise quantization as
365 + // we scale a `half2` tile in column-major layout in the former and in
366 + // row-major in the latter case.
367 + if (group_blocks != -1)
368 + s_sh_rd = 8 * ((threadIdx.x / 32) % (thread_n_blocks / 4)) +
369 + (threadIdx.x % 32) / 4;
370 + else
371 + s_sh_rd = 8 * ((threadIdx.x / 32) % (thread_n_blocks / 4)) +
372 + (threadIdx.x % 32) % 4;
373 +
374 + // Precompute which thread should not read memory in which iterations; this is
375 + // needed if there are more threads than required for a certain tilesize or
376 + // when the batchsize is not a multiple of 16.
377 + bool a_sh_wr_pred[a_sh_wr_iters];
378 +#pragma unroll
379 + for (int i = 0; i < a_sh_wr_iters; i++)
380 + a_sh_wr_pred[i] = a_sh_wr_delta * i + a_sh_wr < a_sh_stride * prob_m;
381 + bool s_sh_wr_pred = threadIdx.x < s_sh_stride;
382 +
383 + // To ensure that writing and reading A tiles to/from shared memory, the
384 + // latter in fragment format, is fully bank conflict free, we need to use a
385 + // rather fancy XOR-based layout. The key here is that neither reads nor
386 + // writes of the 16-byte `int4` blocks of 8 consecutive threads involve the
387 + // same shared memory banks. Further, it seems (based on NSight-Compute) that
388 + // each warp must also write a consecutive memory segment?
389 + auto transform_a = [&](int i) {
390 + int row = i / a_gl_rd_delta_o;
391 + return a_gl_rd_delta_o * row + (i % a_gl_rd_delta_o) ^ row;
392 + };
393 + // Since the computation of this remapping is non-trivial and, due to our main
394 + // loop unrolls, all shared memory accesses are static, we simply precompute
395 + // both transformed reads and writes.
396 + int a_sh_wr_trans[a_sh_wr_iters];
397 +#pragma unroll
398 + for (int i = 0; i < a_sh_wr_iters; i++)
399 + a_sh_wr_trans[i] = transform_a(a_sh_wr_delta * i + a_sh_wr);
400 + int a_sh_rd_trans[b_sh_wr_iters][thread_m_blocks];
401 +#pragma unroll
402 + for (int i = 0; i < b_sh_wr_iters; i++) {
403 +#pragma unroll
404 + for (int j = 0; j < thread_m_blocks; j++)
405 + a_sh_rd_trans[i][j] =
406 + transform_a(a_sh_rd_delta_o * i + a_sh_rd_delta_i * j + a_sh_rd);
407 + }
408 +
409 + // Since B-accesses have non-constant stride they have to be computed at
410 + // runtime; we break dependencies between subsequent accesses with a tile by
411 + // maintining multiple pointers (we have enough registers), a tiny
412 + // optimization.
413 + const int4 *B_ptr[b_sh_wr_iters];
414 +#pragma unroll
415 + for (int i = 0; i < b_sh_wr_iters; i++)
416 + B_ptr[i] = B + b_gl_rd_delta_i * i + b_gl_rd;
417 +
418 + extern __shared__ int4 sh[];
419 + // Shared memory storage for global fetch pipelines.
420 + int4 *sh_a = sh;
421 + int4 *sh_b = sh_a + (stages * a_sh_stage);
422 + int4 *sh_s = sh_b + (stages * b_sh_stage);
423 + // Register storage for double buffer of shared memory reads.
424 + FragA frag_a[2][thread_m_blocks];
425 + I4 frag_b_quant[2];
426 + FragC frag_c[thread_m_blocks][4][2];
427 + FragS frag_s[2][4];
428 +
429 + // Zero accumulators.
430 + auto zero_accums = [&]() {
431 +#pragma unroll
432 + for (int i = 0; i < thread_m_blocks * 4 * 2 * 4; i++)
433 + reinterpret_cast<float *>(frag_c)[i] = 0;
434 + };
435 +
436 + // Asynchronously fetch the next A, B and s tile from global to the next
437 + // shared memory pipeline location.
438 + auto fetch_to_shared = [&](int pipe, int a_off, bool pred = true) {
439 + if (pred) {
440 + int4 *sh_a_stage = sh_a + a_sh_stage * pipe;
441 +#pragma unroll
442 + for (int i = 0; i < a_sh_wr_iters; i++) {
443 + cp_async4_pred(
444 + &sh_a_stage[a_sh_wr_trans[i]],
445 + &A[a_gl_rd_delta_i * i + a_gl_rd + a_gl_rd_delta_o * a_off],
446 + a_sh_wr_pred[i]);
447 + }
448 + int4 *sh_b_stage = sh_b + b_sh_stage * pipe;
449 +#pragma unroll
450 + for (int i = 0; i < b_sh_wr_iters; i++) {
451 + cp_async4_stream(&sh_b_stage[b_sh_wr_delta * i + b_sh_wr], B_ptr[i]);
452 + B_ptr[i] += b_gl_rd_delta_o;
453 + }
454 + // Only fetch scales if this tile starts a new group
455 + if (group_blocks != -1 && pipe % (group_blocks / thread_k_blocks) == 0) {
456 + int4 *sh_s_stage = sh_s + s_sh_stage * pipe;
457 + if (s_sh_wr_pred)
458 + cp_async4_stream(&sh_s_stage[s_sh_wr], &s[s_gl_rd]);
459 + s_gl_rd += s_gl_rd_delta;
460 + }
461 + }
462 + // Insert a fence even when we are winding down the pipeline to ensure that
463 + // waiting is also correct at this point.
464 + cp_async_fence();
465 + };
466 +
467 + // Wait until the next thread tile has been loaded to shared memory.
468 + auto wait_for_stage = [&]() {
469 + // We only have `stages - 2` active fetches since we are double buffering
470 + // and can only issue the next fetch when it is guaranteed that the previous
471 + // shared memory load is fully complete (as it may otherwise be
472 + // overwritten).
473 + cp_async_wait<stages - 2>();
474 + __syncthreads();
475 + };
476 +
477 + // Load the next sub-tile from the current location in the shared memory pipe
478 + // into the current register buffer.
479 + auto fetch_to_registers = [&](int k, int pipe) {
480 + // It may seem inefficient that we reload the groups for every sub-tile;
481 + // however, this does not seem to be a significant bottleneck, while some
482 + // theoretically better attempts have lead to bad instruction ordering by
483 + // the compiler and correspondingly a noticeable drop in performance.
484 + if (group_blocks != -1) {
485 + int4 *sh_s_stage =
486 + sh_s + s_sh_stage * ((group_blocks / thread_k_blocks) *
487 + (pipe / (group_blocks / thread_k_blocks)));
488 + reinterpret_cast<int4 *>(&frag_s[k % 2])[0] = sh_s_stage[s_sh_rd];
489 + }
490 + int4 *sh_a_stage = sh_a + a_sh_stage * pipe;
491 +#pragma unroll
492 + for (int i = 0; i < thread_m_blocks; i++)
493 + ldsm4(frag_a[k % 2][i], &sh_a_stage[a_sh_rd_trans[k % b_sh_wr_iters][i]]);
494 + int4 *sh_b_stage = sh_b + b_sh_stage * pipe;
495 + frag_b_quant[k % 2] = *reinterpret_cast<I4 *>(
496 + &sh_b_stage[b_sh_rd_delta * (k % b_sh_wr_iters) + b_sh_rd]);
497 + };
498 +
499 + // Execute the actual tensor core matmul of a sub-tile.
500 + auto matmul = [&](int k) {
501 +// We have the m dimension as the inner loop in order to encourage overlapping
502 +// dequantization and matmul operations.
503 +#pragma unroll
504 + for (int j = 0; j < 4; j++) {
505 + int b_quant = frag_b_quant[k % 2][j];
506 + int b_quant_shift = b_quant >> 8;
507 + FragB frag_b0 = dequant(b_quant);
508 + // If there are no groups, we can just scale the final output once and can
509 + // avoid doing so for each weight.
510 + if (group_blocks != -1)
511 + scale(frag_b0, frag_s[k % 2][j], 0);
512 + FragB frag_b1 = dequant(b_quant_shift);
513 + if (group_blocks != -1)
514 + scale(frag_b1, frag_s[k % 2][j], 1);
515 +#pragma unroll
516 + for (int i = 0; i < thread_m_blocks; i++) {
517 + mma(frag_a[k % 2][i], frag_b0, frag_c[i][j][0]);
518 + mma(frag_a[k % 2][i], frag_b1, frag_c[i][j][1]);
519 + }
520 + }
521 + };
522 +
523 + // Since we slice across the k dimension of a tile in order to increase the
524 + // number of warps while keeping the n dimension of a tile reasonable, we have
525 + // multiple warps that accumulate their partial sums of the same output
526 + // location; which we have to reduce over in the end. We do in shared memory.
527 + auto thread_block_reduce = [&]() {
528 + constexpr int red_off = threads / b_sh_stride / 2;
529 + if (red_off >= 1) {
530 + int red_idx = threadIdx.x / b_sh_stride;
531 + constexpr int red_sh_stride = b_sh_stride * 4 * 2;
532 + constexpr int red_sh_delta = b_sh_stride;
533 + int red_sh_rd = red_sh_stride * (threadIdx.x / b_sh_stride) +
534 + (threadIdx.x % b_sh_stride);
535 +
536 + // Parallel logarithmic shared memory reduction. We make sure to avoid any
537 + // unnecessary read or write iterations, e.g., for two warps we write only
538 + // once by warp 1 and read only once by warp 0.
539 +
540 +#pragma unroll
541 + for (int m_block = 0; m_block < thread_m_blocks; m_block++) {
542 +#pragma unroll
543 + for (int i = red_off; i > 0; i /= 2) {
544 + if (i <= red_idx && red_idx < 2 * i) {
545 +#pragma unroll
546 + for (int j = 0; j < 4 * 2; j++) {
547 + int red_sh_wr =
548 + red_sh_delta * j + (red_sh_rd - red_sh_stride * i);
549 + if (i < red_off) {
550 + float *c_rd = reinterpret_cast<float *>(
551 + &sh[red_sh_delta * j + red_sh_rd]);
552 + float *c_wr = reinterpret_cast<float *>(&sh[red_sh_wr]);
553 +#pragma unroll
554 + for (int k = 0; k < 4; k++)
555 + reinterpret_cast<FragC *>(frag_c)[4 * 2 * m_block + j][k] +=
556 + c_rd[k] + c_wr[k];
557 + }
558 + sh[red_sh_wr] =
559 + reinterpret_cast<int4 *>(&frag_c)[4 * 2 * m_block + j];
560 + }
561 + }
562 + __syncthreads();
563 + }
564 + if (red_idx == 0) {
565 +#pragma unroll
566 + for (int i = 0; i < 4 * 2; i++) {
567 + float *c_rd =
568 + reinterpret_cast<float *>(&sh[red_sh_delta * i + red_sh_rd]);
569 +#pragma unroll
570 + for (int j = 0; j < 4; j++)
571 + reinterpret_cast<FragC *>(frag_c)[4 * 2 * m_block + i][j] +=
572 + c_rd[j];
573 + }
574 + }
575 + __syncthreads();
576 + }
577 + }
578 + };
579 +
580 + // Since multiple threadblocks may process parts of the same column slice, we
581 + // finally have to globally reduce over the results. As the striped partitioning
582 + // minimizes the number of such reductions and our outputs are usually rather
583 + // small, we perform this reduction serially in L2 cache.
584 + auto global_reduce = [&](bool first = false, bool last = false) {
585 + // We are very careful here to reduce directly in the output buffer to
586 + // maximize L2 cache utilization in this step. To do this, we write out
587 + // results in FP16 (but still reduce with FP32 compute).
588 + constexpr int active_threads = 32 * thread_n_blocks / 4;
589 + if (threadIdx.x < active_threads) {
590 + int c_gl_stride = prob_n / 8;
591 + int c_gl_wr_delta_o = 8 * c_gl_stride;
592 + int c_gl_wr_delta_i = 4 * (active_threads / 32);
593 + int c_gl_wr = c_gl_stride * ((threadIdx.x % 32) / 4) +
594 + 4 * (threadIdx.x / 32) + threadIdx.x % 4;
595 + c_gl_wr += (2 * thread_n_blocks) * slice_col;
596 + constexpr int c_sh_wr_delta = active_threads;
597 + int c_sh_wr = threadIdx.x;
598 +
599 + int row = (threadIdx.x % 32) / 4;
600 +
601 + if (!first) {
602 +// Interestingly, doing direct global accesses here really seems to mess up the
603 +// compiler and lead to slowdowns, hence we also use async-copies even though
604 +// these fetches are not actually asynchronous.
605 +#pragma unroll
606 + for (int i = 0; i < thread_m_blocks * 4; i++) {
607 + cp_async4_pred(&sh[c_sh_wr + c_sh_wr_delta * i],
608 + &C[c_gl_wr + c_gl_wr_delta_o * (i / 2) +
609 + c_gl_wr_delta_i * (i % 2)],
610 + i < (thread_m_blocks - 1) * 4 ||
611 + 8 * (i / 2) + row < prob_m);
612 + }
613 + cp_async_fence();
614 + cp_async_wait<0>();
615 + }
616 +
617 +#pragma unroll
618 + for (int i = 0; i < thread_m_blocks * 4; i++) {
619 + if (i < (thread_m_blocks - 1) * 4 || 8 * (i / 2) + row < prob_m) {
620 + if (!first) {
621 + int4 c_red = sh[c_sh_wr + i * c_sh_wr_delta];
622 +#pragma unroll
623 + for (int j = 0; j < 2 * 4; j++) {
624 + reinterpret_cast<float *>(
625 + &frag_c)[4 * 2 * 4 * (i / 4) + 4 * j + (i % 4)] +=
626 + __half2float(reinterpret_cast<__half *>(&c_red)[j]);
627 + }
628 + }
629 + if (!last) {
630 + int4 c;
631 +#pragma unroll
632 + for (int j = 0; j < 2 * 4; j++) {
633 + reinterpret_cast<__half *>(&c)[j] =
634 + __float2half(reinterpret_cast<float *>(
635 + &frag_c)[4 * 2 * 4 * (i / 4) + 4 * j + (i % 4)]);
636 + }
637 + C[c_gl_wr + c_gl_wr_delta_o * (i / 2) + c_gl_wr_delta_i * (i % 2)] =
638 + c;
639 + }
640 + }
641 + }
642 + }
643 + };
644 +
645 + // Write out the reduce final result in the correct layout. We only actually
646 + // reshuffle matrix fragments in this step, the reduction above is performed
647 + // in fragment layout.
648 + auto write_result = [&]() {
649 + int c_gl_stride = prob_n / 8;
650 + constexpr int c_sh_stride = 2 * thread_n_blocks + 1;
651 + int c_gl_wr_delta = c_gl_stride * (threads / (2 * thread_n_blocks));
652 + constexpr int c_sh_rd_delta =
653 + c_sh_stride * (threads / (2 * thread_n_blocks));
654 +
655 + int c_gl_wr = c_gl_stride * (threadIdx.x / (2 * thread_n_blocks)) +
656 + (threadIdx.x % (2 * thread_n_blocks));
657 + c_gl_wr += (2 * thread_n_blocks) * slice_col;
658 + int c_sh_wr =
659 + (4 * c_sh_stride) * ((threadIdx.x % 32) / 4) + (threadIdx.x % 32) % 4;
660 + c_sh_wr += 32 * (threadIdx.x / 32);
661 + int c_sh_rd = c_sh_stride * (threadIdx.x / (2 * thread_n_blocks)) +
662 + (threadIdx.x % (2 * thread_n_blocks));
663 +
664 + int c_gl_wr_end = c_gl_stride * prob_m;
665 +
666 + // We first reorder in shared memory to guarantee the most efficient final
667 + // global write patterns
668 + auto write = [&](int idx, float c0, float c1, FragS &s) {
669 + half2 res = __halves2half2(__float2half(c0), __float2half(c1));
670 + if (group_blocks ==
671 + -1) // for per-column quantization we finally apply the scale here
672 + res = __hmul2(res, s[0]);
673 + ((half2 *)sh)[idx] = res;
674 + };
675 + if (threadIdx.x / 32 < thread_n_blocks / 4) {
676 +#pragma unroll
677 + for (int i = 0; i < thread_m_blocks; i++) {
678 +#pragma unroll
679 + for (int j = 0; j < 4; j++) {
680 + int wr = c_sh_wr + 8 * j;
681 + write(wr + (4 * c_sh_stride) * 0 + 0, frag_c[i][j][0][0],
682 + frag_c[i][j][0][1], frag_s[j / 2][2 * (j % 2) + 0]);
683 + write(wr + (4 * c_sh_stride) * 8 + 0, frag_c[i][j][0][2],
684 + frag_c[i][j][0][3], frag_s[j / 2][2 * (j % 2) + 0]);
685 + write(wr + (4 * c_sh_stride) * 0 + 4, frag_c[i][j][1][0],
686 + frag_c[i][j][1][1], frag_s[j / 2][2 * (j % 2) + 1]);
687 + write(wr + (4 * c_sh_stride) * 8 + 4, frag_c[i][j][1][2],
688 + frag_c[i][j][1][3], frag_s[j / 2][2 * (j % 2) + 1]);
689 + }
690 + c_sh_wr += 16 * (4 * c_sh_stride);
691 + }
692 + }
693 + __syncthreads();
694 +
695 +#pragma unroll
696 + for (int i = 0;
697 + i < ceildiv(16 * thread_m_blocks, threads / (2 * thread_n_blocks));
698 + i++) {
699 + if (c_gl_wr < c_gl_wr_end) {
700 + C[c_gl_wr] = sh[c_sh_rd];
701 + c_gl_wr += c_gl_wr_delta;
702 + c_sh_rd += c_sh_rd_delta;
703 + }
704 + }
705 + };
706 +
707 + // Start global fetch and register load pipelines.
708 + auto start_pipes = [&]() {
709 +#pragma unroll
710 + for (int i = 0; i < stages - 1; i++)
711 + fetch_to_shared(i, i, i < slice_iters);
712 + zero_accums();
713 + wait_for_stage();
714 + fetch_to_registers(0, 0);
715 + a_gl_rd += a_gl_rd_delta_o * (stages - 1);
716 + };
717 + start_pipes();
718 +
719 + // Main loop.
720 + while (slice_iters) {
721 +// We unroll over both the global fetch and the register load pipeline to ensure
722 +// all shared memory accesses are static. Note that both pipelines have even
723 +// length meaning that the next iteration will always start at index 0.
724 +#pragma unroll
725 + for (int pipe = 0; pipe < stages;) {
726 +#pragma unroll
727 + for (int k = 0; k < b_sh_wr_iters; k++) {
728 + fetch_to_registers(k + 1, pipe % stages);
729 + if (k == b_sh_wr_iters - 2) {
730 + fetch_to_shared((pipe + stages - 1) % stages, pipe,
731 + slice_iters >= stages);
732 + pipe++;
733 + wait_for_stage();
734 + }
735 + matmul(k);
736 + }
737 + slice_iters--;
738 + if (slice_iters == 0)
739 + break;
740 + }
741 + a_gl_rd += a_gl_rd_delta_o * stages;
742 +
743 + // Process results and, if necessary, proceed to the next column slice.
744 + // While this pattern may not be the most readable, other ways of writing
745 + // the loop seemed to noticeably worse performance after compilation.
746 + if (slice_iters == 0) {
747 + cp_async_wait<0>();
748 + bool last = slice_idx == slice_count - 1;
749 + // For per-column scales, we only fetch them here in the final step before
750 + // write-out
751 + if (group_blocks == -1 && last) {
752 + if (s_sh_wr_pred)
753 + cp_async4_stream(&sh_s[s_sh_wr], &s[s_gl_rd]);
754 + cp_async_fence();
755 + }
756 + thread_block_reduce();
757 + if (group_blocks == -1 && last) {
758 + cp_async_wait<0>();
759 + __syncthreads();
760 + if (threadIdx.x / 32 < thread_n_blocks / 4) {
761 + reinterpret_cast<int4 *>(&frag_s)[0] = sh_s[s_sh_rd + 0];
762 + reinterpret_cast<int4 *>(&frag_s)[1] = sh_s[s_sh_rd + 4];
763 + }
764 + }
765 + if (slice_count > 1) { // only globally reduce if there is more than one
766 + // block in a slice
767 + barrier_acquire(&locks[slice_col], slice_idx);
768 + global_reduce(slice_idx == 0, last);
769 + barrier_release(&locks[slice_col], last);
770 + }
771 + if (last) // only the last block in a slice actually writes the result
772 + write_result();
773 + slice_row = 0;
774 + slice_col_par++;
775 + slice_col++;
776 + init_slice();
777 + if (slice_iters) {
778 + a_gl_rd = a_gl_stride * (threadIdx.x / a_gl_rd_delta_o) +
779 + (threadIdx.x % a_gl_rd_delta_o);
780 +#pragma unroll
781 + for (int i = 0; i < b_sh_wr_iters; i++)
782 + B_ptr[i] += b_sh_stride - b_gl_rd_delta_o * k_tiles;
783 + if (slice_col == 0) {
784 +#pragma unroll
785 + for (int i = 0; i < b_sh_wr_iters; i++)
786 + B_ptr[i] -= b_gl_stride;
787 + }
788 + s_gl_rd = s_sh_stride * slice_col + threadIdx.x;
789 + start_pipes();
790 + }
791 + }
792 + }
793 +}
794 +
795 +#else
796 +
797 +template <const int threads, // number of threads in a threadblock
798 + const int thread_m_blocks, // number of 16x16 blocks in the m
799 + // dimension (batchsize) of the threadblock
800 + const int thread_n_blocks, // same for n dimension (output)
801 + const int thread_k_blocks, // same for k dimension (reduction)
802 + const int stages, // number of stages for the async global->shared
803 + // fetch pipeline
804 + const int group_blocks = -1 // number of consecutive 16x16 blocks with
805 + // a separate quantization scale
806 + >
807 +__global__ void
808 +Marlin(const int4 *__restrict__ A, // fp16 input matrix of shape mxk
809 + const int4 *__restrict__ B, // 4bit quantized weight matrix of shape kxn
810 + int4 *__restrict__ C, // fp16 output buffer of shape mxn
811 + const int4
812 + *__restrict__ s, // fp16 quantization scales of shape (k/groupsize)xn
813 + int prob_m, // batch dimension m
814 + int prob_n, // output dimension n
815 + int prob_k, // reduction dimension k
816 + int *locks // extra global storage for barrier synchronization
817 +) {
818 + // Marlin is not implemented yet for SM < 8.0
819 + assert(false);
820 + return;
821 +}
822 +
823 +#endif
824 +
825 +// 8 warps are a good choice since every SM has 4 schedulers and having more
826 +// than 1 warp per schedule allows some more latency hiding. At the same time,
827 +// we want relatively few warps to have many registers per warp and small tiles.
828 +const int USER_THREADS =
829 + 256; // Note: This is only used with user-provided thread_k/n
830 +const int STAGES = 4; // 4 pipeline stages fit into shared memory
831 +const int SHARED_MEM =
832 + 96 * 1024; // max shared memory on compute capability 8.6 (< 8.0)
833 +
834 +static constexpr int min_thread_n = 64;
835 +static constexpr int min_thread_k = 64;
836 +
837 +static constexpr int tile_size = 16;
838 +static constexpr int max_par = 16;
839 +
840 +static constexpr int pack_factor_4bit =
841 + 8; // We have 8 4-bit vals inside a 32 bit
842 +
843 +#define __CALL_IF(THREAD_M_BLOCKS, THREAD_N_BLOCKS, THREAD_K_BLOCKS, \
844 + GROUP_BLOCKS, NUM_THREADS) \
845 + else if (thread_m_blocks == THREAD_M_BLOCKS && \
846 + thread_n_blocks == THREAD_N_BLOCKS && \
847 + thread_k_blocks == THREAD_K_BLOCKS && \
848 + group_blocks == GROUP_BLOCKS && num_threads == NUM_THREADS) { \
849 + cudaFuncSetAttribute(Marlin<NUM_THREADS, THREAD_M_BLOCKS, THREAD_N_BLOCKS, \
850 + THREAD_K_BLOCKS, STAGES, GROUP_BLOCKS>, \
851 + cudaFuncAttributeMaxDynamicSharedMemorySize, \
852 + SHARED_MEM); \
853 + Marlin<NUM_THREADS, THREAD_M_BLOCKS, THREAD_N_BLOCKS, THREAD_K_BLOCKS, \
854 + STAGES, GROUP_BLOCKS><<<blocks, NUM_THREADS, SHARED_MEM, stream>>>( \
855 + A_ptr, B_ptr, C_ptr, s_ptr, prob_m, prob_n, prob_k, locks); \
856 + }
857 +
858 +typedef struct {
859 + int thread_k;
860 + int thread_n;
861 + int num_threads;
862 +} thread_config_t;
863 +
864 +thread_config_t small_batch_thread_configs[] = {
865 + // Ordered by priority
866 +
867 + // thread_k, thread_n, num_threads
868 + {128, 128, 256}, // Default
869 + {128, 64, 128}, // Reduce N 2X, same K
870 + {64, 256, 256}, // Reduce K 2X, increase N 2X
871 + {64, 128, 128}, // Reduce K 2X, same N
872 +};
873 +
874 +thread_config_t large_batch_thread_configs[] = {
875 + // Ordered by priority
876 +
877 + // thread_k, thread_n, num_threads
878 + {64, 256, 256}, // Default
879 + {128, 128, 256}, // Reduce N 2X, increase K 2X
880 + {64, 128, 128}, // Reduce N 2X, same K
881 + {128, 64, 128}, // Reduce N 4X, increase K 2X
882 +};
883 +
884 +bool is_valid_config(thread_config_t const &th_config, int prob_m, int prob_n,
885 + int prob_k) {
886 + // Sanity
887 + if (th_config.thread_k == -1 || th_config.thread_n == -1 ||
888 + th_config.num_threads == -1) {
889 + return false;
890 + }
891 +
892 + // Verify K/N are divisible by thread K/N
893 + if (prob_k % th_config.thread_k != 0 || prob_n % th_config.thread_n != 0) {
894 + return false;
895 + }
896 +
897 + // thread_k can be only 128 or 64 (because it must be less than groupsize
898 + // which is 128)
899 + if (th_config.thread_k != 128 && th_config.thread_k != 64) {
900 + return false;
901 + }
902 +
903 + // Verify min for thread K/N
904 + if (th_config.thread_n < min_thread_n || th_config.thread_k < min_thread_k) {
905 + return false;
906 + }
907 +
908 + // num_threads must be at least 128 (= 4 warps)
909 + if (th_config.num_threads < 128) {
910 + return false;
911 + }
912 +
913 + return true;
914 +}
915 +
916 +thread_config_t determine_thread_config(int prob_m, int prob_n, int prob_k) {
917 +
918 + if (prob_m <= 16) {
919 + for (auto th_config : small_batch_thread_configs) {
920 + if (is_valid_config(th_config, prob_m, prob_n, prob_k)) {
921 + return th_config;
922 + }
923 + }
924 +
925 + } else {
926 + for (auto th_config : large_batch_thread_configs) {
927 + if (is_valid_config(th_config, prob_m, prob_n, prob_k)) {
928 + return th_config;
929 + }
930 + }
931 + }
932 +
933 + return thread_config_t{-1, -1, -1};
934 +}
935 +
936 +#define CALL_IF(N_BLOCKS, K_BLOCKS, NUM_THREADS) \
937 + __CALL_IF(1, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
938 + __CALL_IF(1, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS) \
939 + __CALL_IF(1, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
940 + __CALL_IF(1, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS) \
941 + __CALL_IF(2, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
942 + __CALL_IF(2, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS) \
943 + __CALL_IF(3, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
944 + __CALL_IF(3, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS) \
945 + __CALL_IF(4, N_BLOCKS, K_BLOCKS, -1, NUM_THREADS) \
946 + __CALL_IF(4, N_BLOCKS, K_BLOCKS, 8, NUM_THREADS)
947 +
948 +void marlin_cuda(const void *A, const void *B, void *C, void *s, int prob_m,
949 + int prob_n, int prob_k, void *workspace, int groupsize = -1,
950 + int dev = 0, cudaStream_t stream = 0, int thread_k = -1,
951 + int thread_n = -1, int sms = -1, int max_par = 16) {
952 + int tot_m = prob_m;
953 + int tot_m_blocks = ceildiv(tot_m, 16);
954 + int pad = 16 * tot_m_blocks - tot_m;
955 +
956 + if (sms == -1)
957 + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev);
958 +
959 + // Set thread config
960 + thread_config_t th_config;
961 + if (thread_k != -1 && thread_n != -1) {
962 + // User-defined config
963 + th_config = thread_config_t{thread_k, thread_n, USER_THREADS};
964 + } else {
965 + // Auto config
966 + th_config = determine_thread_config(prob_m, prob_n, prob_k);
967 + }
968 +
969 + if (!is_valid_config(th_config, prob_m, prob_n, prob_k)) {
970 + throw std::runtime_error(
971 + "Invalid thread config: thread_k = " + str(th_config.thread_k) +
972 + ", thread_n = " + str(th_config.thread_n) +
973 + ", num_threads = " + str(th_config.num_threads) + " for MKN = [" +
974 + str(prob_m) + ", " + str(prob_k) + ", " + str(prob_n) + "]");
975 + }
976 +
977 + // Uncomment for debug
978 + // std::cout << "Using thread_config: thread_k = " + str(th_config.thread_k) +
979 + // ", thread_n = " + str(th_config.thread_n) +
980 + // ", num_threads = " + str(th_config.num_threads) + " for
981 + // MKN = [" + str(prob_m) +
982 + // ", " + str(prob_k) + ", " + str(prob_n) + "]\n";
983 +
984 + int num_threads = th_config.num_threads;
985 + thread_k = th_config.thread_k;
986 + thread_n = th_config.thread_n;
987 +
988 + int thread_k_blocks = thread_k / 16;
989 + int thread_n_blocks = thread_n / 16;
990 + int group_blocks = (groupsize == -1) ? -1 : groupsize / 16;
991 + int blocks = sms;
992 +
993 + if (prob_m == 0 || prob_n == 0 || prob_k == 0) {
994 + return;
995 + }
996 +
997 + TORCH_CHECK(prob_n % thread_n == 0, "prob_n = ", prob_n,
998 + " is not divisible by thread_n = ", thread_n);
999 + TORCH_CHECK(prob_k % thread_k == 0, "prob_k = ", prob_k,
1000 + " is not divisible by thread_k = ", thread_k);
1001 + if (group_blocks != -1) {
1002 + TORCH_CHECK(prob_k % group_blocks == 0, "prob_k = ", prob_k,
1003 + " is not divisible by group_blocks = ", group_blocks);
1004 + }
1005 +
1006 + const int4 *A_ptr = (const int4 *)A;
1007 + const int4 *B_ptr = (const int4 *)B;
1008 + int4 *C_ptr = (int4 *)C;
1009 + const int4 *s_ptr = (const int4 *)s;
1010 +
1011 + int *locks = (int *)workspace;
1012 +
1013 + for (int i = 0; i < tot_m_blocks; i += 4) {
1014 + int thread_m_blocks = tot_m_blocks - i;
1015 + prob_m = tot_m - 16 * i;
1016 + int par = 1;
1017 + if (thread_m_blocks > 4) {
1018 + // Note that parallel > 1 currently only works for inputs without any
1019 + // padding
1020 + par = (16 * thread_m_blocks - pad) / 64;
1021 + if (par > max_par)
1022 + par = max_par;
1023 + prob_m = 64 * par;
1024 + i += 4 * (par - 1);
1025 + thread_m_blocks = 4;
1026 + }
1027 +
1028 + // For compilation speed, we only define the kernel configurations that have
1029 + // seemed useful (in terms of performance) in our testing, however many more
1030 + // are, in principle, possible.
1031 + if (false) {
1032 + }
1033 + CALL_IF(8, 8, 256)
1034 + CALL_IF(16, 4, 256)
1035 + CALL_IF(8, 4, 128)
1036 + CALL_IF(4, 8, 128)
1037 + else {
1038 + throw std::runtime_error("Unsupported shapes: MKN = [" + str(prob_m) +
1039 + ", " + str(prob_k) + ", " + str(prob_n) + "]" +
1040 + ", groupsize = " + str(groupsize) +
1041 + ", thread_m_blocks = " + str(thread_m_blocks) +
1042 + ", thread_n_blocks = " + str(thread_n_blocks) +
1043 + ", thread_k_blocks = " + str(thread_k_blocks));
1044 + }
1045 +
1046 + A_ptr += 16 * thread_m_blocks * (prob_k / 8) * par;
1047 + C_ptr += 16 * thread_m_blocks * (prob_n / 8) * par;
1048 + }
1049 +}
1050 +
1051 +} // namespace marlin
1052 +
1053 +torch::Tensor marlin_gemm(torch::Tensor &a, torch::Tensor &b_q_weight,
1054 + torch::Tensor &b_scales, torch::Tensor &workspace,
1055 + int64_t size_m, int64_t size_n, int64_t size_k) {
1056 +
1057 + // Verify M
1058 + TORCH_CHECK(size_m == a.size(0),
1059 + "Shape mismatch: a.size(0) = " + str(a.size(0)) +
1060 + ", size_m = " + str(size_m));
1061 +
1062 + // Verify K
1063 + TORCH_CHECK(size_k == a.size(1),
1064 + "Shape mismatch: a.size(1) = " + str(a.size(1)) +
1065 + ", size_k = " + str(size_k));
1066 + TORCH_CHECK(size_k % marlin::tile_size == 0,
1067 + "size_k = " + str(size_k) +
1068 + " is not divisible by tile_size = " + str(marlin::tile_size));
1069 + TORCH_CHECK((size_k / marlin::tile_size) == b_q_weight.size(0),
1070 + "Shape mismatch: b_q_weight.size(0) = " +
1071 + str(b_q_weight.size(0)) + ", size_k = " + str(size_k) +
1072 + ", tile_size = " + str(marlin::tile_size));
1073 +
1074 + // Verify N
1075 + TORCH_CHECK(b_scales.size(1) == size_n,
1076 + "b_scales.size(1) = " + str(b_scales.size(1)) +
1077 + ", size_n = " + str(size_n));
1078 + TORCH_CHECK(b_q_weight.size(1) % marlin::tile_size == 0,
1079 + "b_q_weight.size(1) = " + str(b_q_weight.size(1)) +
1080 + " is not divisible by tile_size = " + str(marlin::tile_size));
1081 +
1082 + int actual_size_n =
1083 + (b_q_weight.size(1) / marlin::tile_size) * marlin::pack_factor_4bit;
1084 + TORCH_CHECK(size_n == actual_size_n,
1085 + "size_n = " + str(size_n) +
1086 + ", actual_size_n = " + str(actual_size_n));
1087 +
1088 + // Verify A device and strides
1089 + TORCH_CHECK(a.device().is_cuda(), "A is not on GPU");
1090 + TORCH_CHECK(a.is_contiguous(), "A is not contiguous");
1091 +
1092 + // Verify B device and strides
1093 + TORCH_CHECK(b_q_weight.device().is_cuda(), "b_q_weight is not on GPU");
1094 + TORCH_CHECK(b_q_weight.is_contiguous(), "b_q_weight is not contiguous");
1095 +
1096 + // Verify scales device and strides
1097 + TORCH_CHECK(b_scales.device().is_cuda(), "b_scales is not on GPU");
1098 + TORCH_CHECK(b_scales.is_contiguous(), "b_scales is not contiguous");
1099 +
1100 + // Alloc C matrix
1101 + const at::cuda::OptionalCUDAGuard device_guard(device_of(a));
1102 + auto options = torch::TensorOptions().dtype(a.dtype()).device(a.device());
1103 + torch::Tensor c = torch::empty({size_m, size_n}, options);
1104 +
1105 + // thread_k: `k` size of a thread_tile in `weights` (can usually be left as
1106 + // auto -1)
1107 + int thread_k = -1;
1108 + // thread_n: `n` size of a thread_tile in `weights` (can usually be left as
1109 + // auto -1)
1110 + int thread_n = -1;
1111 + // sms: number of SMs to use for the kernel (can usually be left as auto -1)
1112 + int sms = -1;
1113 +
1114 + // Detect groupsize
1115 + if (b_scales.size(0) != 1) {
1116 + TORCH_CHECK(size_k % b_scales.size(0) == 0,
1117 + "size_k = " + str(size_k) +
1118 + ", is not divisible by b_scales.size(0) = " +
1119 + str(b_scales.size(0)));
1120 + }
1121 + int groupsize = b_scales.size(0) == 1 ? -1 : size_k / b_scales.size(0);
1122 +
1123 + // Verify groupsize
1124 + TORCH_CHECK(groupsize == -1 || groupsize == 128,
1125 + "Unexpected groupsize = " + str(groupsize));
1126 +
1127 + // Verify workspace size
1128 + TORCH_CHECK(
1129 + size_n % marlin::min_thread_n == 0,
1130 + "size_n = " + str(size_n) +
1131 + ", is not divisible by min_thread_n = " + str(marlin::min_thread_n));
1132 + int min_workspace_size = (size_n / marlin::min_thread_n) * marlin::max_par;
1133 + TORCH_CHECK(workspace.numel() >= min_workspace_size,
1134 + "workspace.numel = " + str(workspace.numel()) +
1135 + " is below min_workspace_size = " + str(min_workspace_size));
1136 +
1137 + int dev = a.get_device();
1138 + marlin::marlin_cuda(a.data_ptr(), b_q_weight.data_ptr(), c.data_ptr(),
1139 + b_scales.data_ptr(), size_m, size_n, size_k,
1140 + workspace.data_ptr(), groupsize, dev,
1141 + at::cuda::getCurrentCUDAStream(dev), thread_k, thread_n,
1142 + sms, marlin::max_par);
1143 +
1144 + return c;
1145 +}
requirements-dev.txt
+1
@@ -15,6 +15,7 @@ types-setuptools
15 pytest
16 pytest-forked
17 pytest-asyncio
18 +pytest-rerunfailures
19 httpx
20 einops # required for MPT
21 openai
setup.py
+2
@@ -342,6 +342,8 @@ vllm_extension_sources = [
342
343 if _is_cuda():
344 vllm_extension_sources.append("csrc/quantization/awq/gemm_kernels.cu")
345 + vllm_extension_sources.append(
346 + "csrc/quantization/marlin/marlin_cuda_kernel.cu")
347 vllm_extension_sources.append("csrc/custom_all_reduce.cu")
348
349 # Add MoE kernels.
tests/conftest.py
+32
@@ -199,6 +199,24 @@ class VllmRunner:
199 outputs.append((req_sample_output_ids, req_sample_output_strs))
200 return outputs
201
202 + def generate_w_logprobs(
203 + self,
204 + prompts: List[str],
205 + sampling_params: SamplingParams,
206 + ) -> List[Tuple[List[int], str]]:
207 + assert sampling_params.logprobs is not None
208 +
209 + req_outputs = self.model.generate(prompts,
210 + sampling_params=sampling_params)
211 + outputs = []
212 + for req_output in req_outputs:
213 + for sample in req_output.outputs:
214 + output_str = sample.text
215 + output_ids = sample.token_ids
216 + output_logprobs = sample.logprobs
217 + outputs.append((output_ids, output_str, output_logprobs))
218 + return outputs
219 +
220 def generate_greedy(
221 self,
222 prompts: List[str],
@@ -209,6 +227,20 @@ class VllmRunner:
227 return [(output_ids[0], output_str[0])
228 for output_ids, output_str in outputs]
229
230 + def generate_greedy_logprobs(
231 + self,
232 + prompts: List[str],
233 + max_tokens: int,
234 + num_logprobs: int,
235 + ) -> List[Tuple[List[int], str]]:
236 + greedy_logprobs_params = SamplingParams(temperature=0.0,
237 + max_tokens=max_tokens,
238 + logprobs=num_logprobs)
239 + outputs = self.generate_w_logprobs(prompts, greedy_logprobs_params)
240 +
241 + return [(output_ids, output_str, output_logprobs)
242 + for output_ids, output_str, output_logprobs in outputs]
243 +
244 def generate_beam_search(
245 self,
246 prompts: List[str],
tests/models/test_marlin.py new
+97
@@ -0,0 +1,97 @@
1 +"""Compare the outputs of a GPTQ model to a Marlin model.
2 +
3 +Note: GPTQ and Marlin do not have bitwise correctness.
4 +As a result, in this test, we just confirm that the top selected tokens of the
5 +Marlin/GPTQ models are in the top 3 selections of each other.
6 +
7 +Note: Marlin internally uses locks to synchronize the threads. This can
8 +result in very slight nondeterminism for Marlin. As a result, we re-run the test
9 +up to 3 times to see if we pass.
10 +
11 +Run `pytest tests/models/test_marlin.py --forked`.
12 +"""
13 +
14 +import pytest
15 +import torch
16 +from dataclasses import dataclass
17 +from vllm.model_executor.layers.quantization import _QUANTIZATION_CONFIG_REGISTRY
18 +
19 +capability = torch.cuda.get_device_capability()
20 +capability = capability[0] * 10 + capability[1]
21 +marlin_not_supported = (
22 + capability < _QUANTIZATION_CONFIG_REGISTRY["marlin"].get_min_capability())
23 +
24 +
25 +@dataclass
26 +class ModelPair:
27 + model_marlin: str
28 + model_gptq: str
29 +
30 +
31 +model_pairs = [
32 + ModelPair(model_marlin="nm-testing/zephyr-beta-7b-marlin-g128",
33 + model_gptq="nm-testing/zephyr-beta-7b-gptq-g128"),
34 + ModelPair(model_marlin="robertgshaw2/zephyr-7b-beta-channelwise-marlin",
35 + model_gptq="robertgshaw2/zephyr-7b-beta-channelwise-gptq"),
36 + ModelPair(model_marlin="robertgshaw2/TinyLlama-1.1B-Chat-v1.0-g128-marlin",
37 + model_gptq="robertgshaw2/TinyLlama-1.1B-Chat-v1.0-g128-gptq")
38 +]
39 +
40 +
41 +@pytest.mark.flaky(reruns=2)
42 +@pytest.mark.skipif(marlin_not_supported,
43 + reason="Marlin is not supported on this GPU type.")
44 +@pytest.mark.parametrize("model_pair", model_pairs)
45 +@pytest.mark.parametrize("dtype", ["half"])
46 +@pytest.mark.parametrize("max_tokens", [32])
47 +@pytest.mark.parametrize("num_logprobs", [3])
48 +def test_models(
49 + vllm_runner,
50 + example_prompts,
51 + model_pair: ModelPair,
52 + dtype: str,
53 + max_tokens: int,
54 + num_logprobs: int,
55 +) -> None:
56 + marlin_model = vllm_runner(model_pair.model_marlin, dtype=dtype)
57 + marlin_outputs = marlin_model.generate_greedy_logprobs(
58 + example_prompts, max_tokens, num_logprobs)
59 +
60 + # Note: not sure why, but deleting just the model on Ada Lovelace
61 + # does not free the GPU memory. On Ampere, deleting the just model
62 + # frees the memory.
63 + del marlin_model.model.llm_engine.driver_worker
64 + del marlin_model
65 +
66 + gptq_model = vllm_runner(model_pair.model_gptq, dtype=dtype)
67 + gptq_outputs = gptq_model.generate_greedy_logprobs(example_prompts,
68 + max_tokens,
69 + num_logprobs)
70 +
71 + # Note: not sure why, but deleting just the model on Ada Lovelace
72 + # does not free the GPU memory. On Ampere, deleting the just model
73 + # frees the memory.
74 + del gptq_model.model.llm_engine.driver_worker
75 + del gptq_model
76 +
77 + # loop through the prompts
78 + for prompt_idx in range(len(example_prompts)):
79 + gptq_output_ids, gptq_output_str, gptq_logprobs = gptq_outputs[
80 + prompt_idx]
81 + marlin_output_ids, marlin_output_str, marlin_logprobs = marlin_outputs[
82 + prompt_idx]
83 +
84 + for idx, (gptq_output_id, marlin_output_id) in enumerate(
85 + zip(gptq_output_ids, marlin_output_ids)):
86 + # If sequence is not an exact match,
87 + if marlin_output_id != gptq_output_id:
88 + # Each predicted token must be in top 5 of the other's
89 + assert gptq_output_id in marlin_logprobs[idx], (
90 + f"Test{prompt_idx}:\nGPTQ:\t{gptq_output_str!r}\nMarlin:\t{marlin_output_str!r}"
91 + )
92 + assert marlin_output_id in gptq_logprobs[idx], (
93 + f"Test{prompt_idx}:\nGPTQ:\t{gptq_output_str!r}\nMarlin:\t{marlin_output_str!r}"
94 + )
95 +
96 + # Break out since sequences will now diverge.
97 + break
vllm/config.py
+13 -5
@@ -155,15 +155,21 @@ class ModelConfig:
155 self.tokenizer_mode = tokenizer_mode
156
157 def _verify_quantization(self) -> None:
158 - supported_quantization = ["awq", "gptq", "squeezellm"]
159 - rocm_not_supported_quantization = ["awq"]
158 + supported_quantization = ["awq", "gptq", "squeezellm", "marlin"]
159 + rocm_not_supported_quantization = ["awq", "marlin"]
160 if self.quantization is not None:
161 self.quantization = self.quantization.lower()
162
163 # Parse quantization method from the HF model config, if available.
164 hf_quant_config = getattr(self.hf_config, "quantization_config", None)
165 if hf_quant_config is not None:
166 +
167 hf_quant_method = str(hf_quant_config["quant_method"]).lower()
168 + # If the GPTQ model is serialized in marlin format, use marlin.
169 + if (hf_quant_method == "gptq"
170 + and "is_marlin_format" in hf_quant_config
171 + and hf_quant_config["is_marlin_format"]):
172 + hf_quant_method = "marlin"
173 if self.quantization is None:
174 self.quantization = hf_quant_method
175 elif self.quantization != hf_quant_method:
@@ -183,9 +189,11 @@ class ModelConfig:
189 raise ValueError(
190 f"{self.quantization} quantization is currently not supported "
191 f"in ROCm.")
186 - logger.warning(f"{self.quantization} quantization is not fully "
187 - "optimized yet. The speed can be slower than "
188 - "non-quantized models.")
192 + if self.quantization != "marlin":
193 + logger.warning(
194 + f"{self.quantization} quantization is not fully "
195 + "optimized yet. The speed can be slower than "
196 + "non-quantized models.")
197
198 def _verify_cuda_graph(self) -> None:
199 if self.max_context_len_to_capture is None:
vllm/model_executor/layers/linear.py
+29
@@ -17,6 +17,14 @@ from vllm.logger import init_logger
17 logger = init_logger(__name__)
18
19
20 +def adjust_marlin_shard(param, shard_size, shard_offset):
21 + marlin_tile_size = getattr(param, "marlin_tile_size", None)
22 + if marlin_tile_size is None:
23 + return shard_size, shard_offset
24 +
25 + return shard_size * marlin_tile_size, shard_offset * marlin_tile_size
26 +
27 +
28 class LinearMethodBase(ABC):
29 """Base class for different (maybe quantized) linear methods."""
30
@@ -276,6 +284,11 @@ class MergedColumnParallelLinear(ColumnParallelLinear):
284 if packed_dim == output_dim:
285 shard_size = shard_size // param.pack_factor
286 shard_offset = shard_offset // param.pack_factor
287 +
288 + # If marlin, we need to adjust the offset and size to account for the tiling.
289 + shard_size, shard_offset = adjust_marlin_shard(
290 + param, shard_size, shard_offset)
291 +
292 loaded_weight_shard = loaded_weight.narrow(
293 output_dim, shard_offset, shard_size)
294 self.weight_loader(param, loaded_weight_shard, shard_id)
@@ -293,6 +306,11 @@ class MergedColumnParallelLinear(ColumnParallelLinear):
306 if packed_dim == output_dim:
307 shard_size = shard_size // param.pack_factor
308 shard_offset = shard_offset // param.pack_factor
309 +
310 + # If marlin, we need to adjust the offset and size to account for the tiling.
311 + shard_size, shard_offset = adjust_marlin_shard(
312 + param, shard_size, shard_offset)
313 +
314 param_data = param_data.narrow(output_dim, shard_offset,
315 shard_size)
316 start_idx = tp_rank * shard_size
@@ -372,6 +390,7 @@ class QKVParallelLinear(ColumnParallelLinear):
390 loaded_shard_id: Optional[str] = None):
391 param_data = param.data
392 output_dim = getattr(param, "output_dim", None)
393 +
394 if loaded_shard_id is None:
395 # Loaded weight is already packed.
396 if output_dim is None:
@@ -393,6 +412,11 @@ class QKVParallelLinear(ColumnParallelLinear):
412 if packed_dim == output_dim:
413 shard_size = shard_size // param.pack_factor
414 shard_offset = shard_offset // param.pack_factor
415 +
416 + # If marlin, we need to adjust the offset and size to account for the tiling.
417 + shard_size, shard_offset = adjust_marlin_shard(
418 + param, shard_size, shard_offset)
419 +
420 loaded_weight_shard = loaded_weight.narrow(
421 output_dim, shard_offset, shard_size)
422 self.weight_loader(param, loaded_weight_shard, shard_id)
@@ -417,6 +441,11 @@ class QKVParallelLinear(ColumnParallelLinear):
441 if packed_dim == output_dim:
442 shard_size = shard_size // param.pack_factor
443 shard_offset = shard_offset // param.pack_factor
444 +
445 + # If marlin, we need to adjust the offset and size to account for the tiling.
446 + shard_size, shard_offset = adjust_marlin_shard(
447 + param, shard_size, shard_offset)
448 +
449 param_data = param_data.narrow(output_dim, shard_offset,
450 shard_size)
451 if loaded_shard_id == "q":
vllm/model_executor/layers/quantization/__init__.py
+2
@@ -4,11 +4,13 @@ from vllm.model_executor.layers.quantization.base_config import QuantizationConf
4 from vllm.model_executor.layers.quantization.awq import AWQConfig
5 from vllm.model_executor.layers.quantization.gptq import GPTQConfig
6 from vllm.model_executor.layers.quantization.squeezellm import SqueezeLLMConfig
7 +from vllm.model_executor.layers.quantization.marlin import MarlinConfig
8
9 _QUANTIZATION_CONFIG_REGISTRY = {
10 "awq": AWQConfig,
11 "gptq": GPTQConfig,
12 "squeezellm": SqueezeLLMConfig,
13 + "marlin": MarlinConfig,
14 }
15
16
vllm/model_executor/layers/quantization/marlin.py new
+210
@@ -0,0 +1,210 @@
1 +from typing import Any, Dict, List, Optional
2 +
3 +import torch
4 +from torch.nn.parameter import Parameter
5 +
6 +from vllm._C import ops
7 +from vllm.model_executor.layers.linear import LinearMethodBase, set_weight_attrs
8 +from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
9 +
10 +
11 +class MarlinConfig(QuantizationConfig):
12 + """Config class for Marlin.
13 +
14 + Reference: https://github.com/IST-DASLab/marlin/tree/master
15 + """
16 +
17 + def __init__(
18 + self,
19 + group_size: int,
20 + ) -> None:
21 + # Group size for the quantization.
22 + self.group_size = group_size
23 + if self.group_size != 128 and self.group_size != -1:
24 + raise ValueError(
25 + "Currently, only group size 128 and -1 (channelwise) is supported for "
26 + f"Marlin, but got group_size of {self.group_size}")
27 +
28 + # 4 Bits packed into 32 bit datatype.
29 + self.pack_factor = 32 // 4
30 +
31 + # Tile size used by marlin kernels.
32 + self.tile_size = 16
33 +
34 + # Min out_features dim
35 + self.min_n_threads = 64
36 +
37 + # Min in_features dim
38 + self.min_k_threads = 128
39 +
40 + # Max parallel problems to solve at once (improves large batch performance)
41 + self.max_parallel = 16
42 +
43 + # Permutation length used by the marlin kernels.
44 + self.perm_len = 1024
45 +
46 + def __repr__(self) -> str:
47 + return f"MarlinConfig(group_size={self.group_size}"
48 +
49 + @classmethod
50 + def get_name(cls) -> str:
51 + return "marlin"
52 +
53 + @classmethod
54 + def get_supported_act_dtypes(cls) -> List[torch.dtype]:
55 + return [torch.half]
56 +
57 + @classmethod
58 + # Need to figure it out
59 + def get_min_capability(cls) -> int:
60 + return 80
61 +
62 + @classmethod
63 + def get_config_filenames(cls) -> List[str]:
64 + return ["quantize_config.json"]
65 +
66 + @classmethod
67 + def from_config(cls, config: Dict[str, Any]) -> "MarlinConfig":
68 + group_size = cls.get_from_keys(config, ["group_size"])
69 + return cls(group_size)
70 +
71 + def get_linear_method(self) -> "MarlinLinearMethod":
72 + return MarlinLinearMethod(self)
73 +
74 + def get_scaled_act_names(self) -> List[str]:
75 + return []
76 +
77 +
78 +class MarlinLinearMethod(LinearMethodBase):
79 + """Linear method for Marlin.
80 +
81 + Args:
82 + quant_config: The Marlin quantization config.
83 + """
84 +
85 + def __init__(self, quant_config: MarlinConfig):
86 + self.quant_config = quant_config
87 +
88 + def create_weights(
89 + self,
90 + input_size_per_partition: int,
91 + output_size_per_partition: int,
92 + input_size: int,
93 + output_size: int,
94 + params_dtype: torch.dtype,
95 + ) -> Dict[str, Any]:
96 + del output_size # Unused.
97 +
98 + if params_dtype != torch.float16:
99 + raise ValueError(
100 + f"The params dtype must be float16, but got {params_dtype}")
101 +
102 + # Validate output_size_per_partition
103 + if output_size_per_partition % self.quant_config.min_n_threads != 0:
104 + raise ValueError(
105 + f"Weight output_size_per_partition = {output_size_per_partition} is not divisible by min_n_threads = {self.quant_config.min_n_threads}."
106 + )
107 + if output_size_per_partition % self.quant_config.pack_factor != 0:
108 + raise ValueError(
109 + f"Weight output_size_per_partition = {output_size_per_partition} is not divisible by pack_factor = {self.quant_config.pack_factor}."
110 + )
111 +
112 + # Validate input_size_per_partition
113 + if input_size_per_partition % self.quant_config.min_k_threads != 0:
114 + raise ValueError(
115 + f"Weight input_size_per_partition = {input_size_per_partition} is not divisible by min_k_threads = {self.quant_config.min_k_threads}."
116 + )
117 + if self.quant_config.group_size != -1 and input_size_per_partition % self.quant_config.group_size != 0:
118 + raise ValueError(
119 + f"Weight input_size_per_partition = f{input_size_per_partition} is not divisible by group_size = {self.quant_config.group_size}."
120 + )
121 +
122 + # Check that we have at least 4 tiles horizontally in the shard
123 + num_tiles_per_perm = self.quant_config.perm_len // (
124 + self.quant_config.tile_size**2)
125 + if output_size_per_partition % num_tiles_per_perm != 0:
126 + raise ValueError(
127 + "Each permutation group must reside on the same gpu")
128 +
129 + # Quantized 4Bit weights packed into Int32.
130 + qweight = Parameter(
131 + torch.empty(
132 + input_size_per_partition // self.quant_config.tile_size,
133 + output_size_per_partition * self.quant_config.tile_size //
134 + self.quant_config.pack_factor,
135 + device="cuda",
136 + dtype=torch.int32,
137 + ),
138 + requires_grad=False,
139 + )
140 + set_weight_attrs(
141 + qweight,
142 + {
143 + "input_dim": 0,
144 + "output_dim": 1,
145 + "packed_dim": 1,
146 + "pack_factor": self.quant_config.pack_factor,
147 + "marlin_tile_size": self.quant_config.tile_size,
148 + },
149 + )
150 +
151 + # Determine if channelwise or not
152 + input_groups = 1 if self.quant_config.group_size == -1 else input_size_per_partition // self.quant_config.group_size
153 +
154 + scales = Parameter(
155 + torch.empty(
156 + input_groups,
157 + output_size_per_partition,
158 + device="cuda",
159 + dtype=params_dtype,
160 + ),
161 + requires_grad=False,
162 + )
163 + set_weight_attrs(
164 + scales,
165 + {
166 + "input_dim": None if input_groups == 1 else 0,
167 + "output_dim": 1,
168 + },
169 + )
170 +
171 + # Allocate workspace (Used for internal locking mechanism)
172 + max_workspace_size = (
173 + output_size_per_partition //
174 + self.quant_config.min_n_threads) * self.quant_config.max_parallel
175 + workspace = Parameter(torch.zeros(max_workspace_size,
176 + device="cuda",
177 + dtype=torch.int),
178 + requires_grad=False)
179 +
180 + return {
181 + "B": qweight,
182 + "s": scales,
183 + "workspace": workspace,
184 + }
185 +
186 + def apply_weights(
187 + self,
188 + weights: Dict[str, Any],
189 + x: torch.Tensor,
190 + bias: Optional[torch.Tensor] = None,
191 + ) -> torch.Tensor:
192 + qweight = weights["B"]
193 + scales = weights["s"]
194 + workspace = weights["workspace"]
195 +
196 + x_2d = x.view(-1, x.shape[-1])
197 +
198 + size_m = x_2d.shape[0]
199 + size_k = x_2d.shape[1]
200 + size_n = scales.shape[1]
201 +
202 + output_2d = ops.marlin_gemm(x_2d, qweight, scales, workspace, size_m,
203 + size_n, size_k)
204 +
205 + output = output_2d.view(x.shape[:-1] + (output_2d.shape[1], ))
206 +
207 + if bias is not None:
208 + output.add_(bias) # In-place add
209 +
210 + return output