@@ -196,6 +196,62 @@ void ggml_cuda_op_log(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
196
196
ggml_cuda_op_unary<op_log>(ctx, dst);
197
197
}
198
198
199
+ /* gated ops */
200
+
201
+ template <float (*op)(float ), typename T>
202
+ static __global__ void unary_gated_op_kernel (const T * x, T * dst, const int k, const int n, const int o) {
203
+ const int i = blockDim .x *blockIdx .x + threadIdx .x ;
204
+
205
+ if (i >= k) {
206
+ return ;
207
+ }
208
+
209
+ // perform base op on first half of row and multiply with gate in second half
210
+ const int j = (i / n) * o + (i % n);
211
+ dst[i] = (T)(op ((float )x[j]) * (float )x[j + n]);
212
+ }
213
+
214
+ template <float (*op)(float ), typename T>
215
+ static void unary_gated_cuda (const T * x, T * dst, const int k, const int n, const int o, cudaStream_t stream) {
216
+ const int num_blocks = (k + CUDA_NEG_BLOCK_SIZE - 1 ) / CUDA_NEG_BLOCK_SIZE;
217
+ unary_gated_op_kernel<op><<<num_blocks, CUDA_NEG_BLOCK_SIZE, 0 , stream>>> (x, dst, k, n, o);
218
+ }
219
+
220
+ template <float (*op)(float )>
221
+ void ggml_cuda_op_unary_gated (ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
222
+ const ggml_tensor * src0 = dst->src [0 ];
223
+ const void * src0_d = src0->data ;
224
+ void * dst_d = dst->data ;
225
+ const int nc = src0->ne [0 ] / 2 ;
226
+ cudaStream_t stream = ctx.stream ();
227
+
228
+ GGML_ASSERT (ggml_is_contiguous_1 (src0));
229
+
230
+ GGML_ASSERT (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
231
+ GGML_ASSERT ( dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16);
232
+ GGML_ASSERT (src0->type == dst->type );
233
+ GGML_ASSERT (dst->ne [0 ] >= nc);
234
+ GGML_ASSERT (ggml_nrows (dst) >= ggml_nrows (src0));
235
+
236
+ if (src0->type == GGML_TYPE_F16) {
237
+ unary_gated_cuda<op>((const half *)src0_d, (half *)dst_d, ggml_nelements (dst), nc, src0->nb [1 ] / sizeof (half), stream);
238
+ } else {
239
+ unary_gated_cuda<op>((const float *)src0_d, (float *)dst_d, ggml_nelements (dst), nc, src0->nb [1 ] / sizeof (float ), stream);
240
+ }
241
+ }
242
+
243
+ void ggml_cuda_op_reglu (ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
244
+ ggml_cuda_op_unary_gated<op_relu>(ctx, dst);
245
+ }
246
+
247
+ void ggml_cuda_op_geglu (ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
248
+ ggml_cuda_op_unary_gated<op_gelu>(ctx, dst);
249
+ }
250
+
251
+ void ggml_cuda_op_swiglu (ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
252
+ ggml_cuda_op_unary_gated<op_silu>(ctx, dst);
253
+ }
254
+
199
255
/* silu_back */
200
256
201
257
static __device__ __forceinline__ float op_silu_back (float grad, float x) {
0 commit comments