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 / softmax.cu

480 lines · 17724 bytes Raw Blame History
1#include "common.cuh"
2#include "ggml.h"
3#include "softmax.cuh"
4
5#ifdef GGML_USE_HIP
6#include <hip/hip_cooperative_groups.h>
7#else
8#include <cooperative_groups.h>
9#include <cooperative_groups/reduce.h>
10#endif // GGML_USE_HIP
11
12#include <cstdint>
13#include <utility>
14
15template <typename T>
16static __device__ __forceinline__ float t2f32(T val) {
17 return (float) val;
18}
19
20template <>
21__device__ float __forceinline__ t2f32<half>(half val) {
22 return __half2float(val);
23}
24
25struct soft_max_params {
26
27 int64_t nheads;
28 uint32_t n_head_log2;
29 int64_t ncols;
30 int64_t nrows_x;
31 int64_t nrows_y;
32 int64_t ne00;
33 int64_t ne01;
34 int64_t ne02;
35 int64_t ne03;
36 int64_t nb11;
37 int64_t nb12;
38 int64_t nb13;
39
40 int64_t ne12;
41 int64_t ne13;
42 float scale;
43 float max_bias;
44 float m0;
45 float m1;
46};
47
48// When ncols_template == 0 the bounds for the loops in this function are not known and can't be unrolled.
49// As we want to keep pragma unroll for all other cases we suppress the clang transformation warning here.
50#ifdef __clang__
51#pragma clang diagnostic push
52#pragma clang diagnostic ignored "-Wpass-failed"
53#endif // __clang__
54template <bool use_shared, int ncols_template, int block_size_template, typename T>
55static __global__ void soft_max_f32(
56 const float * x, const T * mask, const float * sinks, float * dst, const soft_max_params p) {
57 const int ncols = ncols_template == 0 ? p.ncols : ncols_template;
58
59 const int tid = threadIdx.x;
60
61 const int64_t i03 = blockIdx.z;
62 const int64_t i02 = blockIdx.y;
63 const int64_t i01 = blockIdx.x;
64
65 //TODO: noncontigous inputs/outputs
66 const int rowx = blockIdx.x + blockIdx.y * gridDim.x + blockIdx.z * gridDim.x * gridDim.y;
67
68 const int64_t i11 = i01;
69 const int64_t i12 = i02 % p.ne12;
70 const int64_t i13 = i03 % p.ne13;
71
72 x += int64_t(rowx)*ncols;
73 mask += (i11*p.nb11 + i12*p.nb12 + i13*p.nb13) / sizeof(T) * (mask != nullptr);
74 dst += int64_t(rowx)*ncols;
75
76 const int block_size = block_size_template == 0 ? blockDim.x : block_size_template;
77
78 const float slope = get_alibi_slope(p.max_bias, i02, p.n_head_log2, p.m0, p.m1);
79
80 extern __shared__ float data_soft_max_f32[];
81 float * buf_iw = data_soft_max_f32; // shared memory buffer for inter-warp communication
82 // shared memory buffer to cache values between iterations:
83 float * vals = use_shared ? buf_iw + WARP_SIZE : dst;
84
85 float max_val = sinks ? sinks[i02] : -INFINITY;
86
87#pragma unroll
88 for (int col0 = 0; col0 < ncols; col0 += block_size) {
89 const int col = col0 + tid;
90
91 if (ncols_template == 0 && col >= ncols) {
92 break;
93 }
94
95 const float val = x[col]*p.scale + (mask ? slope*t2f32(mask[col]) : 0.0f);
96
97 vals[col] = val;
98 max_val = max(max_val, val);
99 }
100
101 // find the max value in the block
102 max_val = block_reduce<block_reduce_method::MAX, block_size_template>(max_val, buf_iw);
103
104 float tmp = 0.0f; // partial sum
105
106#pragma unroll
107 for (int col0 = 0; col0 < ncols; col0 += block_size) {
108 const int col = col0 + tid;
109
110 if (ncols_template == 0 && col >= ncols) {
111 break;
112 }
113
114 const float val = expf(vals[col] - max_val);
115 tmp += val;
116 vals[col] = val;
117 }
118
119 if (block_size > WARP_SIZE) {
120 // sync is needed as we reuse buf_iw across block_reduce invocations, see #26385
121 // for block_size <= WARP_SIZE, block_reduce does not access buf_iw
122 __syncthreads();
123 }
124 // find the sum of exps in the block
125 tmp = block_reduce<block_reduce_method::SUM, block_size_template>(tmp, buf_iw);
126
127 if (sinks) {
128 tmp += expf(sinks[i02] - max_val);
129 }
130
131 const float inv_sum = 1.0f / tmp;
132
133#pragma unroll
134 for (int col0 = 0; col0 < ncols; col0 += block_size) {
135 const int col = col0 + tid;
136
137 if (ncols_template == 0 && col >= ncols) {
138 return;
139 }
140
141 dst[col] = vals[col] * inv_sum;
142 }
143}
144
145// TODO: Template to allow keeping ncols in registers if they fit
146static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __restrict__ x,
147 float * __restrict__ dst,
148 float * __restrict__ tmp_maxs,
149 float * __restrict__ tmp_sums,
150 float * shared_vals_max,
151 float * shared_vals_sum,
152 const soft_max_params p) {
153 namespace cg = cooperative_groups;
154
155 const cg::grid_group g = cg::this_grid();
156
157 const int tid = threadIdx.x;
158 const int col_start = blockIdx.x * blockDim.x + tid;
159 const int n_elem_per_thread = 4;
160
161 float local_vals[n_elem_per_thread] = { -INFINITY, -INFINITY, -INFINITY, -INFINITY };
162 float local_max = -INFINITY;
163 const int step_size = gridDim.x * blockDim.x;
164
165 // Compute thread-local max
166 for (int col = col_start; col < p.ncols;) {
167#pragma unroll
168 for (int i = 0; i < n_elem_per_thread; i++) {
169 const int idx = col + i * step_size;
170 local_vals[i] = idx < p.ncols ? x[idx] : -INFINITY;
171 }
172#pragma unroll
173 for (int i = 0; i < n_elem_per_thread; i++) {
174 local_max = fmaxf(local_max, local_vals[i]);
175 }
176 col += step_size * n_elem_per_thread;
177 }
178
179 // Compute CTA-level max
180 local_max = block_reduce<block_reduce_method::MAX>(local_max, shared_vals_max);
181
182 // Store CTA-level max to GMEM
183 if (tid == 0) {
184 tmp_maxs[blockIdx.x] = local_max;
185 }
186 g.sync();
187
188 // Compute compute global max from CTA-level maxs
189 assert(gridDim.x < blockDim.x); // currently we only support this case
190 if (tid < gridDim.x) {
191 local_max = tmp_maxs[tid];
192 } else {
193 local_max = -INFINITY;
194 }
195 local_max = block_reduce<block_reduce_method::MAX>(local_max, shared_vals_max);
196
197 // Compute softmax dividends, accumulate divisor
198 float tmp_expf = 0.0f;
199 for (int col = col_start; col < p.ncols;) {
200#pragma unroll
201 for (int i = 0; i < n_elem_per_thread; i++) {
202 const int idx = col + i * step_size;
203 local_vals[i] = idx < p.ncols ? x[idx] : -INFINITY;
204 }
205#pragma unroll
206 for (int i = 0; i < n_elem_per_thread; i++) {
207 const int idx = col + i * step_size;
208 if (idx < p.ncols) {
209 const float tmp = expf(local_vals[i] - local_max);
210 tmp_expf += tmp;
211 dst[idx] = tmp;
212 }
213 }
214 col += step_size * n_elem_per_thread;
215 }
216
217 // Reduce divisor within CTA
218 tmp_expf = block_reduce<block_reduce_method::SUM>(tmp_expf, shared_vals_sum);
219
220 // Store CTA-level sum to GMEM
221 if (tid == 0) {
222 tmp_sums[blockIdx.x] = tmp_expf;
223 }
224 g.sync();
225
226 // Compute global sum from CTA-level sums
227 if (tid < gridDim.x) {
228 tmp_expf = tmp_sums[tid];
229 } else {
230 tmp_expf = 0.0f;
231 }
232 tmp_expf = block_reduce<block_reduce_method::SUM>(tmp_expf, shared_vals_sum);
233
234 // Divide dividend by global sum + store data
235 for (int col = col_start; col < p.ncols;) {
236#pragma unroll
237 for (int i = 0; i < n_elem_per_thread; i++) {
238 const int idx = col + i * step_size;
239 local_vals[i] = idx < p.ncols ? dst[idx] : -INFINITY;
240 }
241#pragma unroll
242 for (int i = 0; i < n_elem_per_thread; i++) {
243 const int idx = col + i * step_size;
244 if (idx < p.ncols) {
245 dst[idx] = local_vals[i] / tmp_expf;
246 }
247 }
248 col += step_size * n_elem_per_thread;
249 }
250}
251
252#ifdef __clang__
253#pragma clang diagnostic pop
254#endif // __clang__
255
256static __global__ void soft_max_back_f32(
257 const float * grad, const float * dstf, float * dst, const int ncols, const float scale) {
258 const int tid = threadIdx.x;
259 const int rowx = blockIdx.x;
260
261 grad += int64_t(rowx)*ncols;
262 dstf += int64_t(rowx)*ncols;
263 dst += int64_t(rowx)*ncols;
264
265 float dgf_dot = 0.0f; // dot product of dst from forward pass and gradients
266
267 for (int col = tid; col < ncols; col += WARP_SIZE) {
268 dgf_dot += dstf[col]*grad[col];
269 }
270
271 dgf_dot = warp_reduce_sum(dgf_dot);
272
273 for (int col = tid; col < ncols; col += WARP_SIZE) {
274 dst[col] = scale * (grad[col] - dgf_dot) * dstf[col];
275 }
276}
277
278template<int... Ns, typename T>
279static void launch_soft_max_kernels(const float * x, const T * mask, const float * sinks, float * dst,
280 const soft_max_params & p, cudaStream_t stream, dim3 block_dims, dim3 block_nums, size_t nbytes_shared)
281{
282 const int id = ggml_cuda_get_device();
283 const size_t smpbo = ggml_cuda_info().devices[id].smpbo;
284
285 auto launch_kernel = [=](auto I) -> bool {
286 constexpr int ncols = decltype(I)::value;
287 constexpr int block = (ncols > 1024 ? 1024 : ncols);
288
289 if (p.ncols == ncols) {
290 CUDA_SET_SHARED_MEMORY_LIMIT((soft_max_f32<true, ncols, block, T>), smpbo);
291 soft_max_f32<true, ncols, block><<<block_nums, block_dims, nbytes_shared, stream>>>
292 (x, mask, sinks, dst, p);
293 return true;
294 }
295 return false;
296 };
297
298 // unary fold over launch_kernel
299 if ((launch_kernel(std::integral_constant<int, Ns>{}) || ...)) {
300 return;
301 }
302
303 //default case
304 CUDA_SET_SHARED_MEMORY_LIMIT((soft_max_f32<true, 0, 0, T>), smpbo);
305 soft_max_f32<true, 0, 0><<<block_nums, block_dims, nbytes_shared, stream>>>(x, mask, sinks, dst, p);
306}
307
308__launch_bounds__(8*WARP_SIZE, 1) static __global__ void soft_max_f32_parallelize_cols(const float * __restrict__ x,
309 float * __restrict__ dst,
310 float * __restrict__ tmp_maxs,
311 float * __restrict__ tmp_sums,
312 const soft_max_params p)
313// We loop over all instead of parallelizing across gridDim.y as cooperative groups
314// currently only support synchronizing the complete grid if not launched as a cluster group
315// (which requires CC > 9.0)
316// https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/device-callable-apis.html#grid-synchronization
317// https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/device-callable-apis.html#class-cluster-group
318{
319 __shared__ float shared_vals[2][32];
320
321 for (int rowx = 0; rowx < p.ne01 * p.ne02 * p.ne03; rowx++) {
322 soft_max_f32_parallelize_cols_single_row(x + int64_t(rowx) * p.ncols, dst + int64_t(rowx) * p.ncols, tmp_maxs,
323 tmp_sums, shared_vals[0], shared_vals[1], p);
324 }
325}
326
327template <typename T>
328static void soft_max_f32_cuda(const float * x,
329 const T * mask,
330 const float * sinks,
331 float * dst,
332 const soft_max_params & params,
333 cudaStream_t stream,
334 [[maybe_unused]] ggml_backend_cuda_context & ctx) {
335 int nth = WARP_SIZE;
336 const int64_t ncols_x = params.ncols;
337
338 while (nth < ncols_x && nth < CUDA_SOFT_MAX_BLOCK_SIZE) nth *= 2;
339 const dim3 block_dims(nth, 1, 1);
340 const dim3 block_nums(params.ne01, params.ne02, params.ne03);
341 const size_t nbytes_shared = (GGML_PAD(ncols_x, WARP_SIZE) + WARP_SIZE)*sizeof(float);
342 static_assert(CUDA_SOFT_MAX_BLOCK_SIZE == 1024, "These values need to be adjusted.");
343
344
345 const int id = ggml_cuda_get_device();
346 const size_t smpbo = ggml_cuda_info().devices[id].smpbo;
347
348
349 if (nbytes_shared <= smpbo) {
350 launch_soft_max_kernels<32, 64, 128, 256, 512, 1024, 2048, 4096>(x, mask, sinks, dst, params, stream, block_dims, block_nums, nbytes_shared);
351 } else {
352 // Parallelize across SMs for top-p/dist-sampling
353 // The heuristic for parallelizing rows across SMs vs parallelizing single row & looping over all rows was done on the basis of a B6000 GPU and
354 // Can be adapted further for lower-SM-count GPUs, though keeping data in registers should be implemented first as that is the optimal solution.
355 if (ggml_cuda_info().devices[id].supports_cooperative_launch &&
356 ncols_x / (params.ne01 * params.ne02 * params.ne03) > 8192 && mask == nullptr && sinks == nullptr &&
357 params.scale == 1.0f && params.max_bias == 0.0f) {
358 ggml_cuda_pool_alloc<float> tmp_maxs_alloc(ctx.pool(), ggml_cuda_info().devices[id].nsm * sizeof(float));
359 ggml_cuda_pool_alloc<float> tmp_sums_alloc(ctx.pool(), ggml_cuda_info().devices[id].nsm * sizeof(float));
360
361 void * kernel_args[] = { (void *) &x, (void *) &dst, (void *) &tmp_maxs_alloc.ptr,
362 (void *) &tmp_sums_alloc.ptr, (void *) const_cast<soft_max_params *>(&params) };
363 CUDA_CHECK(cudaLaunchCooperativeKernel((void *) soft_max_f32_parallelize_cols,
364 dim3(ggml_cuda_info().devices[id].nsm, 1, 1),
365 dim3(WARP_SIZE * 8, 1, 1), kernel_args, 0, stream));
366 } else {
367 const size_t nbytes_shared_low = WARP_SIZE * sizeof(float);
368 soft_max_f32<false, 0, 0>
369 <<<block_nums, block_dims, nbytes_shared_low, stream>>>(x, mask, sinks, dst, params);
370 }
371 }
372}
373
374static void soft_max_back_f32_cuda(
375 const float * grad, const float * dstf, float * dst,
376 const int ncols, const int nrows, const float scale, cudaStream_t stream) {
377 const dim3 block_dims(WARP_SIZE, 1, 1);
378 const dim3 block_nums(nrows, 1, 1);
379
380 soft_max_back_f32<<<block_nums, block_dims, 0, stream>>>(grad, dstf, dst, ncols, scale);
381}
382
383void ggml_cuda_op_soft_max(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
384 const ggml_tensor * src0 = dst->src[0];
385 const ggml_tensor * src1 = dst->src[1];
386 const ggml_tensor * src2 = dst->src[2];
387
388 const float * src0_d = (const float *) src0->data;
389 const void * src1_d = src1 ? (const void *) src1->data : nullptr;
390 const void * src2_d = src2 ? (const void *) src2->data : nullptr;
391 float * dst_d = (float *) dst->data;
392
393 cudaStream_t stream = ctx.stream();
394
395 GGML_ASSERT(src0->type == GGML_TYPE_F32);
396 GGML_ASSERT( dst->type == GGML_TYPE_F32);
397
398 GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_F32); // src1 contains mask and it is optional
399
400 const int64_t nrows_x = ggml_nrows(src0);
401 const int64_t nrows_y = src0->ne[1];
402
403 const int64_t ne00 = src0->ne[0];
404
405 float scale = 1.0f;
406 float max_bias = 0.0f;
407
408 memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
409 memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
410
411 const bool use_f16 = (src1 && src1->type == GGML_TYPE_F16);
412
413 const int64_t nb11 = src1 ? src1->nb[1] : 1;
414 const int64_t nb12 = src1 ? src1->nb[2] : 1;
415 const int64_t nb13 = src1 ? src1->nb[3] : 1;
416
417 const int64_t ne12 = src1 ? src1->ne[2] : 1;
418 const int64_t ne13 = src1 ? src1->ne[3] : 1;
419
420 const uint32_t n_head = src0->ne[2];
421 const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head));
422
423 const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
424 const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
425
426
427 soft_max_params params = {};
428 params.nheads = src0->ne[2];
429 params.n_head_log2 = n_head_log2;
430 params.ncols = ne00;
431 params.nrows_x = nrows_x;
432 params.nrows_y = nrows_y;
433 params.ne00 = src0->ne[0];
434 params.ne01 = src0->ne[1];
435 params.ne02 = src0->ne[2];
436 params.ne03 = src0->ne[3];
437 params.nb11 = nb11;
438 params.nb12 = nb12;
439 params.nb13 = nb13;
440 params.ne12 = ne12;
441 params.ne13 = ne13;
442 params.scale = scale;
443 params.max_bias = max_bias;
444 params.m0 = m0;
445 params.m1 = m1;
446
447 if (use_f16) {
448 soft_max_f32_cuda(src0_d, (const half *) src1_d, (const float *) src2_d, dst_d, params, stream, ctx);
449 } else {
450 soft_max_f32_cuda(src0_d, (const float *) src1_d, (const float *) src2_d, dst_d, params, stream, ctx);
451 }
452}
453
454void ggml_cuda_op_soft_max_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
455 const ggml_tensor * src0 = dst->src[0]; // grad
456 const ggml_tensor * src1 = dst->src[1]; // forward pass output
457
458 const float * src0_d = (const float *) src0->data;
459 const float * src1_d = (const float *) src1->data;
460 float * dst_d = (float *) dst->data;
461
462 cudaStream_t stream = ctx.stream();
463
464 GGML_ASSERT(src0->type == GGML_TYPE_F32);
465 GGML_ASSERT(src1->type == GGML_TYPE_F32);
466 GGML_ASSERT( dst->type == GGML_TYPE_F32);
467
468 const int64_t ncols = src0->ne[0];
469 const int64_t nrows = ggml_nrows(src0);
470
471 float scale = 1.0f;
472 float max_bias = 0.0f;
473
474 memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
475 memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
476
477 GGML_ASSERT(max_bias == 0.0f);
478
479 soft_max_back_f32_cuda(src0_d, src1_d, dst_d, ncols, nrows, scale, stream);
480}