| 1 | #include "clamp.cuh" |
| 2 | |
| 3 | static __device__ __forceinline__ float op_clamp(float x, float min, float max) { |
| 4 | return fminf(a: fmaxf(a: x, b: min), b: max); |
| 5 | } |
| 6 | |
| 7 | template <class T> |
| 8 | static __global__ void op_clamp_kernel(const T * x, T * dst, const T min, const T max, const int k) { |
| 9 | const int i = blockDim.x*blockIdx.x + threadIdx.x; |
| 10 | |
| 11 | if (i >= k) { |
| 12 | return; |
| 13 | } |
| 14 | |
| 15 | dst[i] = (T)op_clamp(x: (float)x[i], min: (float)min, max: (float)max); |
| 16 | } |
| 17 | |
| 18 | template <class T> |
| 19 | static void clamp_cuda(const T * x, T * dst, const T min, const T max, const int k, cudaStream_t stream) { |
| 20 | const int num_blocks = (k + CUDA_CLAMP_BLOCK_SIZE - 1) / CUDA_CLAMP_BLOCK_SIZE; |
| 21 | op_clamp_kernel<<<gridDim: num_blocks, CUDA_CLAMP_BLOCK_SIZE, sharedMem: 0, stream>>>(x, dst, min, max, k); |
| 22 | } |
| 23 | |
| 24 | |
| 25 | void ggml_cuda_op_clamp(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { |
| 26 | const ggml_tensor * src0 = dst->src[0]; |
| 27 | const void * src0_d = src0->data; |
| 28 | void * dst_d = dst->data; |
| 29 | cudaStream_t stream = ctx.stream(); |
| 30 | |
| 31 | GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); |
| 32 | GGML_ASSERT( dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16); |
| 33 | GGML_ASSERT(src0->type == dst->type); |
| 34 | |
| 35 | float min; |
| 36 | float max; |
| 37 | memcpy(&min, dst->op_params, sizeof(float)); |
| 38 | memcpy(dest: &max, src: (float *) dst->op_params + 1, n: sizeof(float)); |
| 39 | |
| 40 | if (src0->type == GGML_TYPE_F16) { |
| 41 | clamp_cuda((const half *)src0_d, (half *)dst_d, (half)min, (half)max, ggml_nelements(src0), stream); |
| 42 | } else { |
| 43 | clamp_cuda((const float *)src0_d, (float *)dst_d, (float)min, (float)max, ggml_nelements(src0), stream); |
| 44 | } |
| 45 | } |
| 46 | |