interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-cuda / conv2d.cu

447 lines · 20635 bytes Raw Blame History
1#include "conv2d.cuh"
2#include "convert.cuh"
3#include "mma.cuh"
4
5struct conv_params {
6 const int64_t IW, IH;
7 const int64_t OW, OH;
8 const int64_t KW, KH;
9 const int64_t ST_X, ST_Y;
10 const int64_t PD_X, PD_Y;
11 const int64_t DL_X, DL_Y;
12 const int64_t IC, OC;
13 const int64_t B;
14 const int64_t TOTAL;
15};
16
17struct kernel_bounds {
18 int64_t y_min, y_max;
19 int64_t x_min, x_max;
20};
21
22__device__ __forceinline__ int64_t max64(int64_t a, int64_t b) {
23 return (a > b) ? a : b;
24}
25
26__device__ __forceinline__ int64_t min64(int64_t a, int64_t b) {
27 return (a < b) ? a : b;
28}
29
30__device__ __forceinline__ kernel_bounds calculate_kernel_bounds(int64_t out_x, int64_t out_y, const conv_params & P) {
31 kernel_bounds bounds;
32 bounds.y_min = max64(0, (P.PD_Y - out_y * P.ST_Y + P.DL_Y - 1) / P.DL_Y);
33 bounds.y_max = min64(P.KH, (P.IH + P.PD_Y - out_y * P.ST_Y + P.DL_Y - 1) / P.DL_Y);
34 bounds.x_min = max64(0, (P.PD_X - out_x * P.ST_X + P.DL_X - 1) / P.DL_X);
35 bounds.x_max = min64(P.KW, (P.IW + P.PD_X - out_x * P.ST_X + P.DL_X - 1) / P.DL_X);
36 return bounds;
37}
38
39__device__ __forceinline__ int calculate_input_coord(int64_t out_coord,
40 int64_t kern_coord,
41 int64_t stride,
42 int64_t dilation,
43 int64_t padding) {
44 return out_coord * stride + kern_coord * dilation - padding;
45}
46
47struct whcn_layout {
48 __device__ static int64_t input_index(int64_t n, int64_t c, int64_t y, int64_t x, const conv_params & P) {
49 return n * (P.IC * P.IW * P.IH) + c * P.IW * P.IH + y * P.IW + x;
50 }
51
52 __device__ static int64_t kernel_index(int64_t c_out, int64_t c_in, int64_t ky, int64_t kx, const conv_params & P) {
53 return c_out * (P.IC * P.KH * P.KW) + c_in * (P.KH * P.KW) + ky * P.KW + kx;
54 }
55
56 __device__ static int64_t output_index(int64_t n, int64_t c, int64_t y, int64_t x, const conv_params & P) {
57 return n * (P.OC * P.OW * P.OH) + c * P.OW * P.OH + y * P.OW + x;
58 }
59
60 __device__ static void unpack_indices(int64_t global_idx,
61 const conv_params & P,
62 int64_t & n,
63 int64_t & c,
64 int64_t & out_y,
65 int64_t & out_x) {
66 out_x = global_idx % P.OW;
67 out_y = (global_idx / P.OW) % P.OH;
68 c = (global_idx / (P.OW * P.OH)) % P.OC;
69 n = global_idx / (P.OW * P.OH * P.OC);
70 }
71};
72
73template <typename T, typename Layout>
74static __global__ void conv2d_kernel(const float * __restrict__ input,
75 const T * __restrict__ kernel,
76 float * __restrict__ output,
77 const conv_params P) {
78 const int64_t global_idx = blockIdx.x * blockDim.x + threadIdx.x;
79
80 if (global_idx >= P.TOTAL) {
81 return;
82 }
83
84 int64_t n, c_out, out_y, out_x;
85 Layout::unpack_indices(global_idx, P, n, c_out, out_y, out_x);
86
87 float acc = 0.0f;
88
89 for (int64_t c_in = 0; c_in < P.IC; ++c_in) {
90 kernel_bounds bounds = calculate_kernel_bounds(out_x, out_y, P);
91
92 for (int64_t ky = bounds.y_min; ky < bounds.y_max; ++ky) {
93 const int64_t in_y = calculate_input_coord(out_y, ky, P.ST_Y, P.DL_Y, P.PD_Y);
94
95 for (int64_t kx = bounds.x_min; kx < bounds.x_max; ++kx) {
96 const int64_t in_x = calculate_input_coord(out_x, kx, P.ST_X, P.DL_X, P.PD_X);
97
98 const float input_val = input[Layout::input_index(n, c_in, in_y, in_x, P)];
99 const T kernel_val = kernel[Layout::kernel_index(c_out, c_in, ky, kx, P)];
100 acc += (input_val * ggml_cuda_cast<float>(kernel_val));
101 }
102 }
103 }
104
105 // [N, OC, OH, OW]
106 output[Layout::output_index(n, c_out, out_y, out_x, P)] = acc;
107}
108
109template <typename T>
110static void conv2d_cuda(const float * X_D, const T * K_D, float * Y_D, const conv_params P, cudaStream_t st) {
111 const int blocks = (P.TOTAL + CUDA_CONV2D_BLOCK_SIZE - 1) / CUDA_CONV2D_BLOCK_SIZE;
112 conv2d_kernel<T, whcn_layout><<<blocks, CUDA_CONV2D_BLOCK_SIZE, 0, st>>>(X_D, K_D, Y_D, P);
113}
114
115static __global__ void
116conv2d_pad_f16(const float * input, half * output, int iw, int ih, int pw, int ph, int px, int py, int total) {
117 const int i = blockIdx.x * blockDim.x + threadIdx.x;
118 if (i >= total) {
119 return;
120 }
121 const int x = i % pw - px, y = i / pw % ph - py, nc = i / (pw * ph);
122 output[i] = __float2half(
123 (unsigned) x < (unsigned) iw && (unsigned) y < (unsigned) ih ? input[(nc * ih + y) * iw + x] : 0.0f);
124}
125
126template <int KW, int KH, bool use_mma>
127static __global__ void conv2d_implicit_gemm_f16(const half * __restrict__ input,
128 const half * __restrict__ weight,
129 float * __restrict__ output,
130 const conv_params P,
131 const int split_k) {
132 using namespace ggml_cuda_mma;
133 constexpr int warp_size = ggml_cuda_get_physical_warp_size();
134 constexpr int nthreads = 4 * warp_size;
135 constexpr int BM = 64, BN = 64, BK = 64;
136 constexpr int AS = BK / 2 + 4;
137 constexpr int BS = BN / 2 + 4;
138 __shared__ __align__(16) half2 a_s[BM][AS];
139 __shared__ __align__(16) half2 b_s[BK][BS];
140
141 const int tid = threadIdx.y * warp_size + threadIdx.x;
142 const int iw = int(P.IW), ih = int(P.IH), ow = int(P.OW), oh = int(P.OH);
143 const int kw = KW ? KW : int(P.KW), kh = KH ? KH : int(P.KH);
144 const int ic = int(P.IC), oc = int(P.OC);
145 const int sx = int(P.ST_X), sy = int(P.ST_Y);
146 const int dx = int(P.DL_X), dy = int(P.DL_Y);
147 const int n = blockIdx.z / split_k, split = blockIdx.z % split_k;
148 const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN;
149
150 const int k_total = ic * kw * kh;
151 const int load_lane = warp_size == 32 ? threadIdx.x : threadIdx.x % (BN / 2);
152 const int load_row = threadIdx.y * (warp_size / (BN / 2)) + (warp_size == 32 ? 0 : threadIdx.x / (BN / 2));
153 const int spatial = n0 + 2 * load_lane;
154 const int spatial0 = min(spatial, ow * oh - 1), spatial1 = min(spatial + 1, ow * oh - 1);
155 const int y0 = spatial0 / ow, x0 = spatial0 % ow;
156 const int y1 = spatial1 / ow, x1 = spatial1 % ow;
157 const int pos0 = y0 * sy * iw + x0 * sx, pos1 = y1 * sy * iw + x1 * sx;
158
159 [[maybe_unused]] const int wm = threadIdx.y / 2 * 32, wn = threadIdx.y % 2 * 32;
160#if defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)
161 using tile_ab = tile<16, 8, half2, get_input_data_layout()>;
162# if defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)
163 // AMD accumulator fragments transpose the input fragment's row/column mapping.
164 using tile_c = tile<16, 16, float, DATA_LAYOUT_J_MAJOR>;
165# else
166 using tile_c = tile<16, 16, float>;
167# endif
168 [[maybe_unused]] tile_c c[2][2];
169#else
170 if constexpr (use_mma) {
171 NO_DEVICE_CODE;
172 return;
173 }
174#endif
175 constexpr int RM = 4, RN = BM * BN / (nthreads * RM);
176 [[maybe_unused]] const int simt_m = tid / (BN / RN) * RM, simt_n = tid % (BN / RN) * RN;
177 [[maybe_unused]] float c_simt[RM][RN] = {};
178 const int tiles = (k_total + BK - 1) / BK;
179 const int begin = int(int64_t(tiles) * split / split_k) * BK;
180 const int end = int(int64_t(tiles) * (split + 1) / split_k) * BK;
181 for (int k0 = begin; k0 < end; k0 += BK) {
182 if (k_total % 8 == 0 && uintptr_t(weight) % 16 == 0) {
183 for (int i = tid; i < BM * BK / 8; i += nthreads) {
184 const int row = i / (BK / 8), col = 8 * (i % (BK / 8));
185 const int4 v = m0 + row < oc && k0 + col < k_total ?
186 ((const int4 *) weight)[((m0 + row) * k_total + k0 + col) / 8] :
187 make_int4(0, 0, 0, 0);
188 *(int4 *) &a_s[row][col / 2] = v;
189 }
190 } else {
191 for (int i = tid; i < BM * BK / 2; i += nthreads) {
192 const int row = i / (BK / 2), col = 2 * (i % (BK / 2));
193 half lo = __float2half(0.0f), hi = lo;
194 if (m0 + row < oc && k0 + col < k_total) {
195 lo = weight[(m0 + row) * k_total + k0 + col];
196 if (k0 + col + 1 < k_total) {
197 hi = weight[(m0 + row) * k_total + k0 + col + 1];
198 }
199 }
200 a_s[row][col / 2] = __halves2half2(lo, hi);
201 }
202 }
203 for (int k = load_row; k < BK; k += nthreads / (BN / 2)) {
204 const int ki = k0 + k;
205 const int ci = ki / (kw * kh), ky = ki / kw % kh, kx = ki % kw;
206 const int offset = ki < k_total ? (n * ic + ci) * ih * iw + ky * dy * iw + kx * dx : 0;
207 half lo = __float2half(0.0f), hi = lo;
208 if (ki < k_total && spatial < ow * oh) {
209 lo = input[offset + pos0];
210 }
211 if (ki < k_total && spatial + 1 < ow * oh) {
212 hi = input[offset + pos1];
213 }
214 b_s[k][load_lane] = __halves2half2(lo, hi);
215 }
216 __syncthreads();
217 if constexpr (use_mma) {
218#if defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)
219# pragma unroll
220 for (int k = 0; k < BK; k += 16) {
221 tile_ab a[2], b[2];
222# pragma unroll
223 for (int i = 0; i < 2; ++i) {
224 load_ldmatrix(a[i], &a_s[wm + 16 * i][k / 2], AS);
225 load_ldmatrix_trans(b[i], &b_s[k][(wn + 16 * i) / 2], BS);
226 }
227# pragma unroll
228 for (int i = 0; i < 2; ++i) {
229# pragma unroll
230 for (int j = 0; j < 2; ++j) {
231 mma(c[i][j], a[i], b[j]);
232 }
233 }
234 }
235#endif
236 } else {
237#pragma unroll 4
238 for (int k = 0; k < BK; ++k) {
239 float a[RM], b[RN];
240#pragma unroll
241 for (int i = 0; i < RM; ++i) {
242 a[i] = __half2float(((const half *) a_s[simt_m + i])[k]);
243 }
244#pragma unroll
245 for (int j = 0; j < RN; ++j) {
246 b[j] = __half2float(((const half *) b_s[k])[simt_n + j]);
247 }
248#pragma unroll
249 for (int i = 0; i < RM; ++i) {
250#pragma unroll
251 for (int j = 0; j < RN; ++j) {
252 c_simt[i][j] += a[i] * b[j];
253 }
254 }
255 }
256 }
257 __syncthreads();
258 }
259 if constexpr (use_mma) {
260#if defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)
261# pragma unroll
262 for (int i = 0; i < 2; ++i) {
263# pragma unroll
264 for (int j = 0; j < 2; ++j) {
265# pragma unroll
266 for (int l = 0; l < c[i][j].ne; ++l) {
267 const int co = m0 + wm + 16 * i + c[i][j].get_i(l);
268 const int pos = n0 + wn + 16 * j + c[i][j].get_j(l);
269 if (co < oc && pos < ow * oh) {
270 output[(int64_t(blockIdx.z) * oc + co) * ow * oh + pos] = c[i][j].x[l];
271 }
272 }
273 }
274 }
275#endif
276 } else {
277#pragma unroll
278 for (int i = 0; i < RM; ++i) {
279#pragma unroll
280 for (int j = 0; j < RN; ++j) {
281 const int co = m0 + simt_m + i, pos = n0 + simt_n + j;
282 if (co < oc && pos < ow * oh) {
283 output[(int64_t(blockIdx.z) * oc + co) * ow * oh + pos] = c_simt[i][j];
284 }
285 }
286 }
287 }
288}
289
290static __global__ void conv2d_reduce_split_k(const float * __restrict__ partial,
291 float * __restrict__ output,
292 const int total,
293 const int per_batch,
294 const int split_k) {
295 const int i = blockIdx.x * blockDim.x + threadIdx.x;
296 if (i >= total) {
297 return;
298 }
299 const int n = i / per_batch;
300 const float * src = partial + int64_t(n) * (split_k - 1) * per_batch + i;
301 float sum = 0.0f;
302 for (int k = 0; k < split_k; ++k) {
303 sum += src[int64_t(k) * per_batch];
304 }
305 output[i] = sum;
306}
307
308template <bool use_mma>
309static void conv2d_launch_implicit_gemm(const half * input,
310 const half * weight,
311 float * output,
312 const conv_params & params,
313 int split_k,
314 dim3 grid,
315 dim3 block,
316 cudaStream_t stream) {
317 if (params.KW == 3 && params.KH == 3) {
318 conv2d_implicit_gemm_f16<3, 3, use_mma><<<grid, block, 0, stream>>>(input, weight, output, params, split_k);
319 } else if (params.KW == 1 && params.KH == 1) {
320 conv2d_implicit_gemm_f16<1, 1, use_mma><<<grid, block, 0, stream>>>(input, weight, output, params, split_k);
321 } else {
322 conv2d_implicit_gemm_f16<0, 0, use_mma><<<grid, block, 0, stream>>>(input, weight, output, params, split_k);
323 }
324}
325
326static void conv2d_cuda_f16(const float * X_D, const half * K_D, float * Y_D, const conv_params P, cudaStream_t st) {
327 conv2d_cuda<half>(X_D, K_D, Y_D, P, st);
328}
329
330static void conv2d_cuda_f32(const float * X_D, const float * K_D, float * Y_D, const conv_params P, cudaStream_t st) {
331 conv2d_cuda<float>(X_D, K_D, Y_D, P, st);
332}
333
334void ggml_cuda_op_conv2d(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
335 const ggml_tensor * kernel = dst->src[0];
336 const ggml_tensor * input = dst->src[1];
337 float * K_D = (float *) kernel->data;
338 const float * X_D = (const float *) input->data;
339 float * Y_D = (float *) dst->data;
340
341 GGML_ASSERT(input->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
342 GGML_ASSERT(ggml_is_contiguous(input));
343 GGML_ASSERT(ggml_is_contiguous(kernel));
344 GGML_ASSERT(kernel->type == GGML_TYPE_F16 || kernel->type == GGML_TYPE_F32);
345
346 // same number of input channels
347 GGML_ASSERT(input->ne[2] == kernel->ne[2]);
348
349 cudaStream_t st = ctx.stream();
350
351 const int32_t * p = (const int32_t *) dst->op_params;
352 const int ST_X = p[0]; // stride_x
353 const int ST_Y = p[1]; // stride_y
354 const int PD_X = p[2]; // padding_x
355 const int PD_Y = p[3]; // padding_y
356 const int DL_X = p[4]; // dilation_x
357 const int DL_Y = p[5]; // dilation_y
358
359 // No cwhn
360 GGML_ASSERT(p[6] == false);
361
362 const int64_t IW = input->ne[0]; // input_w
363 const int64_t IH = input->ne[1]; // input_h
364 const int64_t OW = dst->ne[0]; // output_w
365 const int64_t OH = dst->ne[1]; // output_h
366 const int64_t KW = kernel->ne[0]; // kernel_w
367 const int64_t KH = kernel->ne[1]; // kernel_h
368 const int64_t IC = input->ne[2]; // input_channels
369 const int64_t OC = kernel->ne[3]; // ouptut_chanles
370 const int64_t B = input->ne[3]; // n_batches
371
372 const int64_t total = B * OC * OH * OW;
373 conv_params params = { IW, IH, OW, OH, KW, KH, ST_X, ST_Y, PD_X, PD_Y, DL_X, DL_Y, IC, OC, B, total };
374
375 const auto & device = ggml_cuda_info().devices[ctx.device];
376 const bool use_mma =
377 turing_mma_available(device.cc) || amd_wmma_available(device.cc) || amd_mfma_available(device.cc);
378 // Devices without a native fragment implementation in mma.cuh can share the tiling.
379 const bool use_simt = GGML_CUDA_CC_IS_MTHREADS(device.cc) || (GGML_CUDA_CC_IS_AMD(device.cc) && !use_mma && IC * KW * KH >= 64);
380 const bool pointwise = KW == 1 && KH == 1 && ST_X == 1 && ST_Y == 1 && PD_X == 0 && PD_Y == 0;
381 const bool use_blas = pointwise && fast_fp16_hardware_available(device.cc);
382 // Short reductions on small maps do not amortize conversion and launch costs.
383 const bool small_conv = IC * KW * KH < 64 && OW * OH < 512;
384
385 const int64_t limit = INT_MAX - 256;
386 const int64_t padded_w = IW + 2 * int64_t(PD_X), padded_h = IH + 2 * int64_t(PD_Y);
387 const bool padded_fits = padded_w > 0 && padded_w <= limit && padded_h > 0 && padded_h <= limit &&
388 padded_w * padded_h <= limit && IC * B <= limit / (padded_w * padded_h);
389 if (kernel->type == GGML_TYPE_F16 && (use_mma || use_blas || use_simt) && (use_blas || !small_conv) &&
390 ggml_nelements(input) <= limit && ggml_nelements(kernel) <= limit && total <= limit && padded_fits &&
391 PD_X >= 0 && PD_Y >= 0 && ST_X > 0 && ST_Y > 0 && DL_X > 0 && DL_Y > 0 &&
392 (OW - 1) * ST_X + (KW - 1) * DL_X < padded_w && (OH - 1) * ST_Y + (KH - 1) * DL_Y < padded_h &&
393 (OC + 63) / 64 <= 65535 && B <= 65535) {
394 const int pw = int(padded_w), ph = int(padded_h);
395 const int padded_total = int(padded_w * padded_h * IC * B);
396
397 ggml_cuda_pool_alloc<half> x_half(ctx.pool(), padded_total);
398 // Match im2col's F16 input precision, but expand patches only in shared memory and accumulate in F32.
399 if (PD_X == 0 && PD_Y == 0) {
400 ggml_get_to_fp16_cuda(input->type)(X_D, x_half.get(), padded_total, st);
401 } else {
402 conv2d_pad_f16<<<(padded_total + 255) / 256, 256, 0, st>>>(X_D, x_half.get(), int(IW), int(IH), pw, ph,
403 PD_X, PD_Y, padded_total);
404 }
405 const conv_params padded_params = { pw, ph, OW, OH, KW, KH, ST_X, ST_Y, 0, 0, DL_X, DL_Y, IC, OC, B, total };
406 if (use_blas) {
407 const float alpha = 1.0f, beta = 0.0f;
408 const int positions = int(OW * OH);
409 cublasHandle_t cublas_h = ctx.cublas_handle();
410 for (int n = 0; n < B; ++n) {
411 CUBLAS_CHECK(cublasGemmEx(cublas_h, CUBLAS_OP_N, CUBLAS_OP_N, positions, int(OC), int(IC), &alpha,
412 x_half.get() + int64_t(n) * IC * positions, CUDA_R_16F, positions, K_D,
413 CUDA_R_16F, int(IC), &beta, Y_D + int64_t(n) * OC * positions, CUDA_R_32F,
414 positions, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP));
415 }
416 return;
417 }
418 const int64_t blocks = ((OW * OH + 63) / 64) * ((OC + 63) / 64) * B;
419 const int target = 8 * ggml_cuda_info().devices[ctx.device].nsm;
420 // Split long reductions so small spatial maps still occupy the GPU.
421 const int split_k = int(std::min({ int64_t(32), int64_t(65535) / B, (IC * KW * KH + 63) / 64,
422 std::max(int64_t(1), (target + blocks - 1) / blocks) }));
423
424 ggml_cuda_pool_alloc<float> partial(ctx.pool());
425 float * result = split_k == 1 ? Y_D : partial.alloc(total * split_k);
426 const dim3 block(device.warp_size, 4);
427 const dim3 grid(unsigned((OW * OH + 63) / 64), unsigned((OC + 63) / 64), unsigned(B * split_k));
428 if (use_mma) {
429 conv2d_launch_implicit_gemm<true>(x_half.get(), (const half *) K_D, result, padded_params, split_k, grid,
430 block, st);
431 } else {
432 conv2d_launch_implicit_gemm<false>(x_half.get(), (const half *) K_D, result, padded_params, split_k, grid,
433 block, st);
434 }
435 if (split_k > 1) {
436 conv2d_reduce_split_k<<<(total + 255) / 256, 256, 0, st>>>(result, Y_D, int(total), int(OC * OW * OH),
437 split_k);
438 }
439 return;
440 }
441
442 if (kernel->type == GGML_TYPE_F16) {
443 conv2d_cuda_f16(X_D, (half *) K_D, Y_D, params, st);
444 } else {
445 conv2d_cuda_f32(X_D, K_D, Y_D, params, st);
446 }
447}