okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

main
198.9 KiB5756 linesraw
1#include "ggml-metal-ops.h"
2
3#include "ggml.h"
4#include "ggml-impl.h"
5#include "ggml-backend-impl.h"
6
7#include "ggml-metal-impl.h"
8#include "ggml-metal-common.h"
9#include "ggml-metal-device.h"
10#include "ggml-metal-fusion.h"
11#include "ggml-metal-tuning.h"
12
13#include <cassert>
14#include <algorithm>
15#include <limits>
16#include <cmath>
17
18static ggml_metal_buffer_id ggml_metal_get_buffer_id(const ggml_tensor * t) {
19    if (!t) {
20        return { nullptr, 0 };
21    }
22
23    ggml_backend_buffer_t buffer = t->view_src ? t->view_src->buffer : t->buffer;
24
25    ggml_metal_buffer_t ctx = (ggml_metal_buffer_t) buffer->context;
26
27    return ggml_metal_buffer_get_id(ctx, t);
28}
29
30struct ggml_metal_op {
31    ggml_metal_op(
32        ggml_metal_device_t dev,
33        ggml_metal_cmd_buf_t cmd_buf,
34        ggml_cgraph * gf,
35        ggml_metal_fusion_info * finfo,
36        int  idx_start,
37        int  idx_end,
38        bool use_concurrency,
39        bool use_capture,
40        int  debug_graph) {
41        this->dev             = dev;
42        this->lib             = ggml_metal_device_get_library(dev);
43        this->enc             = ggml_metal_encoder_init(cmd_buf, use_concurrency);
44        this->mem_ranges      = ggml_mem_ranges_init(debug_graph);
45        this->finfo           = finfo;
46        this->idx_start       = idx_start;
47        this->idx_end         = idx_end;
48        this->use_concurrency = use_concurrency;
49        this->use_capture     = use_capture;
50        this->debug_graph     = debug_graph;
51        this->gf              = gf;
52
53        idxs.reserve(gf->n_nodes);
54
55        // filter empty nodes
56        // TODO: this can be removed when the allocator starts filtering them earlier
57        //       https://github.com/ggml-org/llama.cpp/pull/16130#issuecomment-3327905830
58        for (int i = idx_start; i < idx_end; i++) {
59            if (!ggml_op_is_empty(gf->nodes[i]->op) && !ggml_is_empty(gf->nodes[i])) {
60                idxs.push_back(i);
61            }
62        }
63    }
64
65    ~ggml_metal_op() {
66        ggml_metal_encoder_end_encoding(this->enc);
67        ggml_metal_encoder_free(this->enc);
68        ggml_mem_ranges_free(this->mem_ranges);
69    }
70
71    int n_nodes() const {
72        return idxs.size();
73    }
74
75    ggml_tensor * node(int i) const {
76        assert(i >= 0 && i < (int) idxs.size());
77        return ggml_graph_node(gf, idxs[i]);
78    }
79
80    // consult the fusion table for the longest pattern starting at i0
81    // returns the matching pattern (nullptr if no fusion) and sets *n_out to the number of nodes
82    const ggml_metal_fusion * can_fuse(int i0, enum ggml_metal_fusion_mode mode, int * n_out) const {
83        assert(use_fusion());
84        assert(i0 >= 0 && i0 < n_nodes());
85
86        return ggml_metal_fusion_next(gf, idxs.data(), (int) idxs.size(), i0, mode, n_out);
87    }
88
89    // whether to attempt fusion; the toggle lives in the shared fusion debugging context owned
90    // by the device (initialized from GGML_METAL_FUSION_DISABLE, overridable by the test)
91    bool use_fusion() const {
92        return ggml_metal_fusion_info_enabled(finfo);
93    }
94
95    // record that a fusion fired, indexed by the matching table entry
96    void count_fusions(const ggml_metal_fusion * fusion) const {
97        ggml_metal_fusion_info_count_fusion(finfo, fusion);
98    }
99
100    ggml_metal_device_t  dev;
101    ggml_metal_library_t lib;
102    ggml_metal_encoder_t enc;
103    ggml_mem_ranges_t    mem_ranges;
104
105    // shared fusion debugging context
106    ggml_metal_fusion_info * finfo;
107
108    bool use_concurrency;
109    bool use_capture;
110
111    int debug_graph;
112
113private:
114    ggml_cgraph * gf;
115
116    int idx_start;
117    int idx_end;
118
119    // non-empty node indices
120    std::vector<int> idxs;
121};
122
123ggml_metal_op_t ggml_metal_op_init(
124        ggml_metal_device_t dev,
125        ggml_metal_cmd_buf_t cmd_buf,
126        ggml_cgraph * gf,
127        ggml_metal_fusion_info * finfo,
128        int idx_start,
129        int idx_end,
130        bool use_concurrency,
131        bool use_capture,
132        int debug_graph) {
133    ggml_metal_op_t res = new ggml_metal_op(
134        dev,
135        cmd_buf,
136        gf,
137        finfo,
138        idx_start,
139        idx_end,
140        use_concurrency,
141        use_capture,
142        debug_graph);
143
144    return res;
145}
146
147void ggml_metal_op_free(ggml_metal_op_t ctx) {
148    delete ctx;
149}
150
151int ggml_metal_op_n_nodes(ggml_metal_op_t ctx) {
152    return ctx->n_nodes();
153}
154
155static bool ggml_metal_op_concurrency_reset(ggml_metal_op_t ctx) {
156    if (!ctx->mem_ranges) {
157        return true;
158    }
159
160    ggml_metal_encoder_memory_barrier(ctx->enc);
161
162    ggml_mem_ranges_reset(ctx->mem_ranges);
163
164    return true;
165}
166
167static bool ggml_metal_op_concurrency_check(ggml_metal_op_t ctx, const ggml_tensor * node) {
168    if (!ctx->mem_ranges) {
169        return false;
170    }
171
172    return ggml_mem_ranges_check(ctx->mem_ranges, node);
173}
174
175static bool ggml_metal_op_concurrency_add(ggml_metal_op_t ctx, const ggml_tensor * node) {
176    if (!ctx->mem_ranges) {
177        return true;
178    }
179
180    return ggml_mem_ranges_add(ctx->mem_ranges, node);
181}
182
183static int ggml_metal_op_encode_impl(ggml_metal_op_t ctx, int idx) {
184    struct ggml_tensor * node = ctx->node(idx);
185
186    //GGML_LOG_INFO("%s: encoding node %3d, op = %8s\n", __func__, idx, ggml_op_name(node->op));
187
188    if (ggml_is_empty(node)) {
189        return 1;
190    }
191
192    switch (node->op) {
193        case GGML_OP_NONE:
194        case GGML_OP_RESHAPE:
195        case GGML_OP_VIEW:
196        case GGML_OP_TRANSPOSE:
197        case GGML_OP_PERMUTE:
198            {
199                // noop -> next node
200                if (ctx->debug_graph > 0) {
201                    GGML_LOG_DEBUG("%s: node[%5d] - %-12s %s\n", __func__, idx, ggml_op_name(node->op), "(noop)");
202                }
203            } return 1;
204        default:
205            {
206            } break;
207    }
208
209    if (!ggml_metal_device_supports_op(ctx->dev, node)) {
210        GGML_LOG_ERROR("%s: error: unsupported op '%s'\n", __func__, ggml_op_desc(node));
211        GGML_ABORT("unsupported op");
212    }
213
214    if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
215        return 1;
216    }
217
218    int n_fuse = 1;
219
220    // check if the current node can run concurrently with other nodes before it
221    // the condition is that:
222    //  - the current node cannot write to any previous src or dst ranges
223    //  - the current node cannot read from any previous dst ranges
224    //
225    // if the condition is not satisfied, we put a memory barrier and clear all ranges
226    // otherwise, we add the new ranges to the encoding context and process the node concurrently
227    //
228    {
229        bool is_concurrent = ggml_metal_op_concurrency_check(ctx, node);
230
231        if (is_concurrent && ctx->use_fusion()) {
232            int n_fuse = 1;
233            const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n_fuse);
234            if (fusion) {
235                // fused kernels write to the last node of the group, not necessarily to the first node's dst
236                is_concurrent = ggml_mem_ranges_check(ctx->mem_ranges, ctx->node(idx + n_fuse - 1));
237            }
238        }
239
240        if (!is_concurrent) {
241            ggml_metal_op_concurrency_reset(ctx);
242        }
243
244        if (ctx->debug_graph > 0) {
245            GGML_LOG_DEBUG("%s: node[%5d] - %-12s %-12s %s\n", __func__, idx, ggml_op_name(node->op), ggml_get_name(node), is_concurrent ? "(concurrent)" : "");
246        }
247        if (ctx->debug_graph > 1) {
248            GGML_TENSOR_LOCALS( int64_t, ne0, node->src[0], ne);
249            GGML_TENSOR_LOCALS(uint64_t, nb0, node->src[0], nb);
250            GGML_TENSOR_LOCALS( int64_t, ne1, node->src[1], ne);
251            GGML_TENSOR_LOCALS(uint64_t, nb1, node->src[1], nb);
252            GGML_TENSOR_LOCALS( int64_t, ne2, node->src[2], ne);
253            GGML_TENSOR_LOCALS(uint64_t, nb2, node->src[2], nb);
254            GGML_TENSOR_LOCALS( int64_t, ne3, node->src[3], ne);
255            GGML_TENSOR_LOCALS(uint64_t, nb3, node->src[3], nb);
256            GGML_TENSOR_LOCALS( int64_t, ne,  node,         ne);
257            GGML_TENSOR_LOCALS(uint64_t, nb,  node,         nb);
258
259            if (node->src[0]) {
260                GGML_LOG_DEBUG("%s: src0 - %4s [%5lld, %5lld, %5lld, %5lld] [%5lld, %5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(node->src[0]->type), ne00, ne01, ne02, ne03, nb00, nb01, nb02, nb03,
261                        ggml_is_contiguous(node->src[0]), node->src[0]->name);
262            }
263            if (node->src[1]) {
264                GGML_LOG_DEBUG("%s: src1 - %4s [%5lld, %5lld, %5lld, %5lld] [%5lld, %5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(node->src[1]->type), ne10, ne11, ne12, ne13, nb10, nb11, nb12, nb13,
265                        ggml_is_contiguous(node->src[1]), node->src[1]->name);
266            }
267            if (node->src[2]) {
268                GGML_LOG_DEBUG("%s: src2 - %4s [%5lld, %5lld, %5lld, %5lld] [%5lld, %5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(node->src[2]->type), ne20, ne21, ne22, ne23, nb20, nb21, nb22, nb23,
269                        ggml_is_contiguous(node->src[2]), node->src[2]->name);
270            }
271            if (node->src[3]) {
272                GGML_LOG_DEBUG("%s: src3 - %4s [%5lld, %5lld, %5lld, %5lld] [%5lld, %5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(node->src[3]->type), ne30, ne31, ne32, ne33, nb30, nb31, nb32, nb33,
273                        ggml_is_contiguous(node->src[3]), node->src[3]->name);
274            }
275            if (node) {
276                GGML_LOG_DEBUG("%s: node  - %4s [%5lld, %5lld, %5lld, %5lld] [%5lld, %5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(node->type), ne0, ne1, ne2, ne3, nb0, nb1, nb2, nb3,
277                        node->name);
278            }
279        }
280    }
281
282    switch (node->op) {
283        case GGML_OP_CONCAT:
284            {
285                n_fuse = ggml_metal_op_concat(ctx, idx);
286            } break;
287        case GGML_OP_ADD:
288        case GGML_OP_SUB:
289        case GGML_OP_MUL:
290        case GGML_OP_DIV:
291            {
292                n_fuse = ggml_metal_op_bin(ctx, idx);
293            } break;
294        case GGML_OP_ADD_ID:
295            {
296                n_fuse = ggml_metal_op_add_id(ctx, idx);
297            } break;
298        case GGML_OP_REPEAT:
299            {
300                n_fuse = ggml_metal_op_repeat(ctx, idx);
301            } break;
302        case GGML_OP_ACC:
303            {
304                n_fuse = ggml_metal_op_acc(ctx, idx);
305            } break;
306        case GGML_OP_SCALE:
307        case GGML_OP_FILL:
308        case GGML_OP_CLAMP:
309        case GGML_OP_LEAKY_RELU:
310        case GGML_OP_SQR:
311        case GGML_OP_SQRT:
312        case GGML_OP_SIN:
313        case GGML_OP_COS:
314        case GGML_OP_LOG:
315        case GGML_OP_UNARY:
316            {
317                n_fuse = ggml_metal_op_unary(ctx, idx);
318            } break;
319        case GGML_OP_SILU_BACK:
320            {
321                n_fuse = ggml_metal_op_silu_back(ctx, idx);
322            } break;
323        case GGML_OP_GLU:
324            {
325                n_fuse = ggml_metal_op_glu(ctx, idx);
326            } break;
327        case GGML_OP_SUM:
328            {
329                n_fuse = ggml_metal_op_sum(ctx, idx);
330            } break;
331        case GGML_OP_SUM_ROWS:
332        case GGML_OP_MEAN:
333            {
334                n_fuse = ggml_metal_op_sum_rows(ctx, idx);
335            } break;
336        case GGML_OP_CUMSUM:
337            {
338                n_fuse = ggml_metal_op_cumsum(ctx, idx);
339            } break;
340        case GGML_OP_LIGHTNING_INDEXER:
341            {
342                n_fuse = ggml_metal_op_lightning_indexer(ctx, idx);
343            } break;
344        case GGML_OP_DSV4_HC_COMB:
345        case GGML_OP_DSV4_HC_PRE:
346        case GGML_OP_DSV4_HC_POST:
347            {
348                n_fuse = ggml_metal_op_dsv4_hc(ctx, idx);
349            } break;
350        case GGML_OP_SOFT_MAX:
351            {
352                n_fuse = ggml_metal_op_soft_max(ctx, idx);
353            } break;
354        case GGML_OP_SSM_CONV:
355            {
356                n_fuse = ggml_metal_op_ssm_conv(ctx, idx);
357            } break;
358        case GGML_OP_SSM_SCAN:
359            {
360                n_fuse = ggml_metal_op_ssm_scan(ctx, idx);
361            } break;
362        case GGML_OP_RWKV_WKV6:
363        case GGML_OP_RWKV_WKV7:
364            {
365                n_fuse = ggml_metal_op_rwkv(ctx, idx);
366            } break;
367        case GGML_OP_GATED_DELTA_NET:
368            {
369                n_fuse = ggml_metal_op_gated_delta_net(ctx, idx);
370            } break;
371        case GGML_OP_SOLVE_TRI:
372            {
373                n_fuse = ggml_metal_op_solve_tri(ctx, idx);
374            } break;
375        case GGML_OP_MUL_MAT:
376            {
377                n_fuse = ggml_metal_op_mul_mat(ctx, idx);
378            } break;
379        case GGML_OP_MUL_MAT_ID:
380            {
381                n_fuse = ggml_metal_op_mul_mat_id(ctx, idx);
382            } break;
383        case GGML_OP_GET_ROWS:
384            {
385                n_fuse = ggml_metal_op_get_rows(ctx, idx);
386            } break;
387        case GGML_OP_SET_ROWS:
388            {
389                n_fuse = ggml_metal_op_set_rows(ctx, idx);
390            } break;
391        case GGML_OP_DIAG:
392            {
393                n_fuse = ggml_metal_op_diag(ctx, idx);
394            } break;
395        case GGML_OP_L2_NORM:
396            {
397                n_fuse = ggml_metal_op_l2_norm(ctx, idx);
398            } break;
399        case GGML_OP_GROUP_NORM:
400            {
401                n_fuse = ggml_metal_op_group_norm(ctx, idx);
402            } break;
403        case GGML_OP_NORM:
404        case GGML_OP_RMS_NORM:
405            {
406                n_fuse = ggml_metal_op_norm(ctx, idx);
407            } break;
408        case GGML_OP_ROPE:
409        case GGML_OP_ROPE_BACK:
410            {
411                n_fuse = ggml_metal_op_rope(ctx, idx);
412            } break;
413        case GGML_OP_IM2COL:
414            {
415                n_fuse = ggml_metal_op_im2col(ctx, idx);
416            } break;
417        case GGML_OP_CONV_2D:
418            {
419                n_fuse = ggml_metal_op_conv_2d(ctx, idx);
420            } break;
421        case GGML_OP_CONV_2D_DW:
422            {
423                n_fuse = ggml_metal_op_conv_2d_dw(ctx, idx);
424            } break;
425        case GGML_OP_CONV_TRANSPOSE_1D:
426            {
427                n_fuse = ggml_metal_op_conv_transpose_1d(ctx, idx);
428            } break;
429        case GGML_OP_CONV_TRANSPOSE_2D:
430            {
431                n_fuse = ggml_metal_op_conv_transpose_2d(ctx, idx);
432            } break;
433        case GGML_OP_COL2IM_1D:
434            {
435                n_fuse = ggml_metal_op_col2im_1d(ctx, idx);
436            } break;
437        case GGML_OP_CONV_3D:
438            {
439                n_fuse = ggml_metal_op_conv_3d(ctx, idx);
440            } break;
441        case GGML_OP_UPSCALE:
442            {
443                n_fuse = ggml_metal_op_upscale(ctx, idx);
444            } break;
445        case GGML_OP_PAD:
446            {
447                n_fuse = ggml_metal_op_pad(ctx, idx);
448            } break;
449        case GGML_OP_PAD_REFLECT_1D:
450            {
451                n_fuse = ggml_metal_op_pad_reflect_1d(ctx, idx);
452            } break;
453        case GGML_OP_ROLL:
454            {
455                n_fuse = ggml_metal_op_roll(ctx, idx);
456            } break;
457        case GGML_OP_ARANGE:
458            {
459                n_fuse = ggml_metal_op_arange(ctx, idx);
460            } break;
461        case GGML_OP_TIMESTEP_EMBEDDING:
462            {
463                n_fuse = ggml_metal_op_timestep_embedding(ctx, idx);
464            } break;
465        case GGML_OP_ARGSORT:
466            {
467                n_fuse = ggml_metal_op_argsort(ctx, idx);
468            } break;
469        case GGML_OP_TOP_K:
470            {
471                n_fuse = ggml_metal_op_top_k(ctx, idx);
472            } break;
473        case GGML_OP_TRI:
474            {
475                n_fuse = ggml_metal_op_tri(ctx, idx);
476            } break;
477        case GGML_OP_FLASH_ATTN_EXT:
478            {
479                n_fuse = ggml_metal_op_flash_attn_ext(ctx, idx);
480            } break;
481        case GGML_OP_SET:
482            {
483                n_fuse = ggml_metal_op_set(ctx, idx);
484            } break;
485        case GGML_OP_DUP:
486        case GGML_OP_CPY:
487        case GGML_OP_CONT:
488            {
489                n_fuse = ggml_metal_op_cpy(ctx, idx);
490            } break;
491        case GGML_OP_POOL_1D:
492            {
493                n_fuse = ggml_metal_op_pool_1d(ctx, idx);
494            } break;
495        case GGML_OP_POOL_2D:
496            {
497                n_fuse = ggml_metal_op_pool_2d(ctx, idx);
498            } break;
499        case GGML_OP_ARGMAX:
500            {
501                n_fuse = ggml_metal_op_argmax(ctx, idx);
502            } break;
503        case GGML_OP_OPT_STEP_ADAMW:
504            {
505                n_fuse = ggml_metal_op_opt_step_adamw(ctx, idx);
506            } break;
507        case GGML_OP_OPT_STEP_SGD:
508            {
509                n_fuse = ggml_metal_op_opt_step_sgd(ctx, idx);
510            } break;
511        case GGML_OP_COUNT_EQUAL:
512            {
513                n_fuse = ggml_metal_op_count_equal(ctx, idx);
514            } break;
515        default:
516            {
517                GGML_LOG_ERROR("%s: error: node %3d, op = %8s not implemented\n", __func__, idx, ggml_op_name(node->op));
518                GGML_ABORT("fatal error");
519            }
520    }
521
522    if (ctx->debug_graph > 0) {
523        if (n_fuse > 1) {
524            GGML_LOG_DEBUG("%s:               fuse %d ops\n", __func__, n_fuse);
525        }
526    }
527
528    // update the mem ranges in the encoding context
529    for (int i = 0; i < n_fuse; ++i) {
530        if (!ggml_metal_op_concurrency_add(ctx, ctx->node(idx + i))) {
531            ggml_metal_op_concurrency_reset(ctx);
532        }
533    }
534
535    return n_fuse;
536}
537
538int ggml_metal_op_encode(ggml_metal_op_t ctx, int idx) {
539    if (ctx->use_capture) {
540        ggml_metal_encoder_debug_group_push(ctx->enc, ggml_op_desc(ctx->node(idx)));
541    }
542
543    int res = ggml_metal_op_encode_impl(ctx, idx);
544    if (idx + res > ctx->n_nodes()) {
545        GGML_ABORT("fusion error: nodes spanning multiple encoders have been fused. this indicates a bug in the fusion logic %s",
546                "https://github.com/ggml-org/llama.cpp/pull/14849");
547    }
548
549    if (ctx->use_capture) {
550        ggml_metal_encoder_debug_group_pop(ctx->enc);
551    }
552
553    return res;
554}
555
556int ggml_metal_op_concat(ggml_metal_op_t ctx, int idx) {
557    ggml_tensor * op = ctx->node(idx);
558
559    ggml_metal_library_t lib = ctx->lib;
560    ggml_metal_encoder_t enc = ctx->enc;
561
562    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
563    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
564    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
565    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
566    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
567    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
568
569    const int32_t dim = ((const int32_t *) op->op_params)[0];
570
571    const bool is_q = ggml_is_quantized(op->type);
572
573    // for quantized types, concat is done at the block level (nb0 == type_size == block size)
574    int32_t ne00_arg = ne00;
575    int32_t ne10_arg = ne10;
576    int32_t ne0_arg  = ne0;
577    if (is_q) {
578        const int32_t blck = ggml_blck_size(op->type);
579        GGML_ASSERT(ne00 % blck == 0);
580        GGML_ASSERT(ne10 % blck == 0);
581        GGML_ASSERT(ne0  % blck == 0);
582        ne00_arg = ne00/blck;
583        ne10_arg = ne10/blck;
584        ne0_arg  = ne0/blck;
585    }
586
587    ggml_metal_kargs_concat args = {
588        /*.ne00 =*/ ne00_arg,
589        /*.ne01 =*/ ne01,
590        /*.ne02 =*/ ne02,
591        /*.ne03 =*/ ne03,
592        /*.nb00 =*/ nb00,
593        /*.nb01 =*/ nb01,
594        /*.nb02 =*/ nb02,
595        /*.nb03 =*/ nb03,
596        /*.ne10 =*/ ne10_arg,
597        /*.ne11 =*/ ne11,
598        /*.ne12 =*/ ne12,
599        /*.ne13 =*/ ne13,
600        /*.nb10 =*/ nb10,
601        /*.nb11 =*/ nb11,
602        /*.nb12 =*/ nb12,
603        /*.nb13 =*/ nb13,
604        /*.ne0  =*/ ne0_arg,
605        /*.ne1  =*/ ne1,
606        /*.ne2  =*/ ne2,
607        /*.ne3  =*/ ne3,
608        /*.nb0  =*/ nb0,
609        /*.nb1  =*/ nb1,
610        /*.nb2  =*/ nb2,
611        /*.nb3  =*/ nb3,
612        /*.dim  =*/ dim,
613    };
614
615    auto pipeline = ggml_metal_library_get_pipeline_concat(lib, op->type);
616
617    ggml_metal_encoder_set_pipeline(enc, pipeline);
618    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
619    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
620    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
621    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
622
623    int nth = std::min(256, ne0_arg);
624
625    // when rows are small, we can batch them together in a single threadgroup
626    int nrptg = 1;
627    if (nth < 256) {
628        nrptg = std::min((256 + nth - 1) / nth, ne1);
629        if (nrptg * nth > 256) {
630            nrptg = 256 / nth;
631        }
632    }
633
634    const int nw0 = (ne1 + nrptg - 1) / nrptg;
635
636    ggml_metal_encoder_dispatch_threadgroups(enc, nw0, ne2, ne3, nth, nrptg, 1);
637
638    return 1;
639}
640
641int ggml_metal_op_repeat(ggml_metal_op_t ctx, int idx) {
642    ggml_tensor * op = ctx->node(idx);
643
644    ggml_metal_library_t lib = ctx->lib;
645    ggml_metal_encoder_t enc = ctx->enc;
646
647    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
648    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
649    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
650    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
651
652    auto pipeline = ggml_metal_library_get_pipeline_repeat(lib, op->type);
653
654    ggml_metal_kargs_repeat args = {
655        /*.ne00 =*/ ne00,
656        /*.ne01 =*/ ne01,
657        /*.ne02 =*/ ne02,
658        /*.ne03 =*/ ne03,
659        /*.nb00 =*/ nb00,
660        /*.nb01 =*/ nb01,
661        /*.nb02 =*/ nb02,
662        /*.nb03 =*/ nb03,
663        /*.ne0  =*/ ne0,
664        /*.ne1  =*/ ne1,
665        /*.ne2  =*/ ne2,
666        /*.ne3  =*/ ne3,
667        /*.nb0  =*/ nb0,
668        /*.nb1  =*/ nb1,
669        /*.nb2  =*/ nb2,
670        /*.nb3  =*/ nb3,
671    };
672
673    ggml_metal_encoder_set_pipeline(enc, pipeline);
674    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
675    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
676    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
677
678    const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), ne0);
679
680    ggml_metal_encoder_dispatch_threadgroups(enc, ne1, ne2, ne3, nth, 1, 1);
681
682    return 1;
683}
684
685int ggml_metal_op_acc(ggml_metal_op_t ctx, int idx) {
686    ggml_tensor * op = ctx->node(idx);
687
688    ggml_metal_library_t lib = ctx->lib;
689    ggml_metal_encoder_t enc = ctx->enc;
690
691    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
692    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
693    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
694    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
695    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
696    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
697
698    GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32);
699    GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
700    GGML_ASSERT(op->type         == GGML_TYPE_F32);
701
702    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
703    GGML_ASSERT(ggml_is_contiguous_rows(op->src[1]));
704
705    const size_t pnb1 = ((const int32_t *) op->op_params)[0];
706    const size_t pnb2 = ((const int32_t *) op->op_params)[1];
707    const size_t pnb3 = ((const int32_t *) op->op_params)[2];
708    const size_t offs = ((const int32_t *) op->op_params)[3];
709
710    const bool inplace = (bool) ((const int32_t *) op->op_params)[4];
711
712    if (!inplace) {
713        // run a separate kernel to cpy src->dst
714        // not sure how to avoid this
715        // TODO: make a simpler cpy_bytes kernel
716
717        //const id<MTLComputePipelineState> pipeline = ctx->pipelines[GGML_METAL_PIPELINE_TYPE_CPY_F32_F32].obj;
718        auto pipeline = ggml_metal_library_get_pipeline_cpy(lib, op->src[0]->type, op->type);
719
720        ggml_metal_kargs_cpy args = {
721            /*.nk0  =*/ ne00,
722            /*.ne00 =*/ ne00,
723            /*.ne01 =*/ ne01,
724            /*.ne02 =*/ ne02,
725            /*.ne03 =*/ ne03,
726            /*.nb00 =*/ nb00,
727            /*.nb01 =*/ nb01,
728            /*.nb02 =*/ nb02,
729            /*.nb03 =*/ nb03,
730            /*.ne0  =*/ ne0,
731            /*.ne1  =*/ ne1,
732            /*.ne2  =*/ ne2,
733            /*.ne3  =*/ ne3,
734            /*.nb0  =*/ nb0,
735            /*.nb1  =*/ nb1,
736            /*.nb2  =*/ nb2,
737            /*.nb3  =*/ nb3,
738        };
739
740        ggml_metal_encoder_set_pipeline(enc, pipeline);
741        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
742        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
743        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
744
745        const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), ne00);
746
747        ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
748
749        ggml_metal_op_concurrency_reset(ctx);
750    }
751
752    ggml_metal_kargs_bin args = {
753        /*.ne00 =*/ ne10,
754        /*.ne01 =*/ ne11,
755        /*.ne02 =*/ ne12,
756        /*.ne03 =*/ ne13,
757        /*.nb00 =*/ nb00,
758        /*.nb01 =*/ pnb1,
759        /*.nb02 =*/ pnb2,
760        /*.nb03 =*/ pnb3,
761        /*.ne10 =*/ ne10,
762        /*.ne11 =*/ ne11,
763        /*.ne12 =*/ ne12,
764        /*.ne13 =*/ ne13,
765        /*.nb10 =*/ nb10,
766        /*.nb11 =*/ nb11,
767        /*.nb12 =*/ nb12,
768        /*.nb13 =*/ nb13,
769        /*.ne0  =*/ ne10,
770        /*.ne1  =*/ ne11,
771        /*.ne2  =*/ ne12,
772        /*.ne3  =*/ ne13,
773        /*.nb0  =*/ nb0,
774        /*.nb1  =*/ pnb1,
775        /*.nb2  =*/ pnb2,
776        /*.nb3  =*/ pnb3,
777        /*.offs =*/ offs,
778        /*.o1   =*/ { 0 },
779    };
780
781    auto pipeline = ggml_metal_library_get_pipeline_bin_one(lib, GGML_OP_ADD);
782
783    ggml_metal_encoder_set_pipeline(enc, pipeline);
784    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
785    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
786    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
787    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
788
789    const int nth_max = MIN(256, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
790
791    int nth = 1;
792
793    while (2*nth < args.ne0 && nth < nth_max) {
794        nth *= 2;
795    }
796
797    ggml_metal_encoder_dispatch_threadgroups(enc, ne11, ne12, ne13, nth, 1, 1);
798
799    return 1;
800}
801
802int ggml_metal_op_unary(ggml_metal_op_t ctx, int idx) {
803    ggml_tensor * op = ctx->node(idx);
804
805    ggml_metal_library_t lib = ctx->lib;
806    ggml_metal_encoder_t enc = ctx->enc;
807
808    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
809    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
810    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
811    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
812
813    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
814
815    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
816    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
817
818    ggml_metal_kargs_unary args = {
819        /*.ne00  =*/ ne00,
820        /*.ne01  =*/ ne01,
821        /*.ne02  =*/ ne02,
822        /*.ne03  =*/ ne03,
823        /*.nb00  =*/ nb00,
824        /*.nb01  =*/ nb01,
825        /*.nb02  =*/ nb02,
826        /*.nb03  =*/ nb03,
827        /*.ne0   =*/ ne0,
828        /*.ne1   =*/ ne1,
829        /*.ne2   =*/ ne2,
830        /*.ne3   =*/ ne3,
831        /*.nb0   =*/ nb0,
832        /*.nb1   =*/ nb1,
833        /*.nb2   =*/ nb2,
834        /*.nb3   =*/ nb3,
835        /*.slope =*/ 0.0,
836        /*.scale =*/ 0.0,
837        /*.bias  =*/ 0.0,
838        /*.val   =*/ 0.0,
839        /*.min   =*/ 0.0,
840        /*.max   =*/ 0.0,
841    };
842
843    if (op->op == GGML_OP_LEAKY_RELU) {
844        args.slope = ggml_get_op_params_f32(op, 0);
845    }
846
847    if (op->op == GGML_OP_SCALE) {
848        args.scale = ggml_get_op_params_f32(op, 0);
849        args.bias  = ggml_get_op_params_f32(op, 1);
850    }
851
852    if (op->op == GGML_OP_FILL) {
853        args.val = ggml_get_op_params_f32(op, 0);
854    }
855
856    if (op->op == GGML_OP_CLAMP) {
857        args.min = ggml_get_op_params_f32(op, 0);
858        args.max = ggml_get_op_params_f32(op, 1);
859    }
860
861    if (op->op == GGML_OP_UNARY && ggml_get_unary_op(op) == GGML_UNARY_OP_XIELU) {
862        args.slope = ggml_get_op_params_f32(op, 1); // alpha_n
863        args.scale = ggml_get_op_params_f32(op, 2); // alpha_p
864        args.bias  = ggml_get_op_params_f32(op, 3); // beta
865        args.val   = ggml_get_op_params_f32(op, 4); // eps
866    }
867
868    auto pipeline = ggml_metal_library_get_pipeline_unary(lib, op);
869
870    if (pipeline.c4) {
871        args.ne00 = ne00/4;
872        args.ne0  = ne0/4;
873    }
874
875    ggml_metal_encoder_set_pipeline(enc, pipeline);
876    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
877    ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
878    ggml_metal_encoder_set_buffer  (enc, bid_dst,  2);
879
880    if (pipeline.cnt) {
881        const int n = pipeline.c4 ? ggml_nelements(op)/4 : ggml_nelements(op);
882
883        ggml_metal_encoder_dispatch_threadgroups(enc, n, 1, 1, 1, 1, 1);
884    } else {
885        const int nth_max = MIN(256, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
886        const int nth = MIN(args.ne00, nth_max);
887        const int nk0 = (args.ne00 + nth - 1)/nth;
888
889        ggml_metal_encoder_dispatch_threadgroups(enc, nk0*ne01, ne02, ne03, nth, 1, 1);
890    }
891
892    return 1;
893}
894
895int ggml_metal_op_glu(ggml_metal_op_t ctx, int idx) {
896    ggml_tensor * op = ctx->node(idx);
897
898    ggml_metal_library_t lib = ctx->lib;
899    ggml_metal_encoder_t enc = ctx->enc;
900
901    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
902    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
903    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
904    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
905    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
906    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
907
908    if (op->src[1]) {
909        GGML_ASSERT(ggml_are_same_shape(op->src[0], op->src[1]));
910    }
911
912    auto pipeline = ggml_metal_library_get_pipeline_glu(lib, op);
913
914    const int32_t swp = ggml_get_op_params_i32(op, 1);
915    const float alpha = ggml_get_op_params_f32(op, 2);
916    const float limit = ggml_get_op_params_f32(op, 3);
917
918    const int32_t i00 = swp ? ne0 : 0;
919    const int32_t i10 = swp ? 0 : ne0;
920
921    ggml_metal_kargs_glu args = {
922        /*.ne00 =*/ ne00,
923        /*.nb01 =*/ nb01,
924        /*.ne10 =*/ op->src[1] ? ne10 : ne00,
925        /*.nb11 =*/ op->src[1] ? nb11 : nb01,
926        /*.ne0  =*/ ne0,
927        /*.nb1  =*/ nb1,
928        /*.i00  =*/ op->src[1] ? 0 : i00,
929        /*.i10  =*/ op->src[1] ? 0 : i10,
930        /*.alpha=*/ alpha,
931        /*.limit=*/ limit
932    };
933
934    const int64_t nrows = ggml_nrows(op->src[0]);
935
936    const int32_t nth = std::max(1, std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), ne00/2));
937
938    ggml_metal_encoder_set_pipeline(enc, pipeline);
939    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
940    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
941    if (op->src[1]) {
942        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
943    } else {
944        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 2);
945    }
946    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
947
948    ggml_metal_encoder_dispatch_threadgroups(enc, nrows, 1, 1, nth, 1, 1);
949
950    return 1;
951}
952
953int ggml_metal_op_sum(ggml_metal_op_t ctx, int idx) {
954    ggml_tensor * op  = ctx->node(idx);
955
956    ggml_metal_library_t lib = ctx->lib;
957    ggml_metal_encoder_t enc = ctx->enc;
958
959    const uint64_t n = (uint64_t) ggml_nelements(op->src[0]);
960
961    ggml_metal_kargs_sum args = {
962        /*.np =*/ n,
963    };
964
965    auto pipeline = ggml_metal_library_get_pipeline_sum(lib, op);
966
967    int nth = 32; // SIMD width
968
969    while (nth < (int) n && nth < ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
970        nth *= 2;
971    }
972
973    nth = std::min(nth, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
974    nth = std::min(nth, (int) n);
975
976    const int nsg = (nth + 31) / 32;
977
978    ggml_metal_encoder_set_pipeline(enc, pipeline);
979    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
980    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
981    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
982
983    ggml_metal_encoder_set_threadgroup_memory_size(enc, GGML_PAD(nsg * sizeof(float), 16), 0);
984
985    ggml_metal_encoder_dispatch_threadgroups(enc, 1, 1, 1, nth, 1, 1);
986
987    return 1;
988}
989
990int ggml_metal_op_sum_rows(ggml_metal_op_t ctx, int idx) {
991    ggml_tensor * op = ctx->node(idx);
992
993    ggml_metal_library_t lib = ctx->lib;
994    ggml_metal_encoder_t enc = ctx->enc;
995
996    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
997    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
998    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
999    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
1000
1001    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
1002
1003    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
1004    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
1005
1006    ggml_metal_kargs_sum_rows args = {
1007        /*.ne00 =*/ ne00,
1008        /*.ne01 =*/ ne01,
1009        /*.ne02 =*/ ne02,
1010        /*.ne03 =*/ ne03,
1011        /*.nb00 =*/ nb00,
1012        /*.nb01 =*/ nb01,
1013        /*.nb02 =*/ nb02,
1014        /*.nb03 =*/ nb03,
1015        /*.ne0  =*/ ne0,
1016        /*.ne1  =*/ ne1,
1017        /*.ne2  =*/ ne2,
1018        /*.ne3  =*/ ne3,
1019        /*.nb0  =*/ nb0,
1020        /*.nb1  =*/ nb1,
1021        /*.nb2  =*/ nb2,
1022        /*.nb3  =*/ nb3,
1023    };
1024
1025    auto pipeline = ggml_metal_library_get_pipeline_sum_rows(lib, op);
1026
1027    if (pipeline.c4) {
1028        args.ne00 = ne00/4;
1029        args.ne0  = ne0/4;
1030    }
1031
1032    int nth = 32; // SIMD width
1033
1034    while (nth < args.ne00 && nth < ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
1035        nth *= 2;
1036    }
1037
1038    nth = std::min(nth, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
1039    nth = std::min(nth, (int) args.ne00);
1040
1041    const size_t smem = pipeline.smem;
1042
1043    ggml_metal_encoder_set_pipeline(enc, pipeline);
1044    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
1045    ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
1046    ggml_metal_encoder_set_buffer  (enc, bid_dst,  2);
1047
1048    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
1049
1050    ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
1051
1052    return 1;
1053}
1054
1055int ggml_metal_op_cumsum(ggml_metal_op_t ctx, int idx) {
1056    ggml_tensor * op = ctx->node(idx);
1057
1058    ggml_metal_library_t lib = ctx->lib;
1059    ggml_metal_encoder_t enc = ctx->enc;
1060
1061    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
1062
1063    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
1064    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
1065    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
1066    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
1067
1068    auto pipeline_blk = ggml_metal_library_get_pipeline_cumsum_blk(lib, op);
1069
1070    int nth = 1;
1071    while (nth < ne00 && 2*nth <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline_blk)) {
1072        nth *= 2;
1073    }
1074
1075    GGML_ASSERT(ne00 <= nth*nth);
1076
1077    const int64_t net0 = (ne00 + nth - 1) / nth;
1078    const int64_t net1 = ne01;
1079    const int64_t net2 = ne02;
1080    const int64_t net3 = ne03;
1081
1082    const uint64_t nbt0 = sizeof(float);
1083    const uint64_t nbt1 = net0*nbt0;
1084    const uint64_t nbt2 = net1*nbt1;
1085    const uint64_t nbt3 = net2*nbt2;
1086
1087    const size_t smem = GGML_PAD(32*sizeof(float), 16);
1088
1089    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
1090    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
1091
1092    ggml_metal_buffer_id bid_tmp = bid_dst;
1093    bid_tmp.offs += ggml_nbytes(op);
1094
1095    {
1096        ggml_metal_kargs_cumsum_blk args = {
1097            /*.ne00 =*/ ne00,
1098            /*.ne01 =*/ ne01,
1099            /*.ne02 =*/ ne02,
1100            /*.ne03 =*/ ne03,
1101            /*.nb00 =*/ nb00,
1102            /*.nb01 =*/ nb01,
1103            /*.nb02 =*/ nb02,
1104            /*.nb03 =*/ nb03,
1105            /*.net0 =*/ net0,
1106            /*.net1 =*/ net1,
1107            /*.net2 =*/ net2,
1108            /*.net3 =*/ net3,
1109            /*.nbt0 =*/ nbt0,
1110            /*.nbt1 =*/ nbt1,
1111            /*.nbt2 =*/ nbt2,
1112            /*.nbt3 =*/ nbt3,
1113            /*.outb =*/ ne00 > nth,
1114        };
1115
1116        ggml_metal_encoder_set_pipeline(enc, pipeline_blk);
1117        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
1118        ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
1119        ggml_metal_encoder_set_buffer  (enc, bid_tmp,  2);
1120        ggml_metal_encoder_set_buffer  (enc, bid_dst,  3);
1121
1122        ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
1123
1124        ggml_metal_encoder_dispatch_threadgroups(enc, net0*ne01, ne02, ne03, nth, 1, 1);
1125    }
1126
1127    if (ne00 > nth) {
1128        ggml_metal_op_concurrency_reset(ctx);
1129
1130        {
1131            ggml_metal_kargs_cumsum_blk args = {
1132                /*.ne00 =*/ net0,
1133                /*.ne01 =*/ net1,
1134                /*.ne02 =*/ net2,
1135                /*.ne03 =*/ net3,
1136                /*.nb00 =*/ nbt0,
1137                /*.nb01 =*/ nbt1,
1138                /*.nb02 =*/ nbt2,
1139                /*.nb03 =*/ nbt3,
1140                /*.net0 =*/ net0,
1141                /*.net1 =*/ net1,
1142                /*.net2 =*/ net2,
1143                /*.net3 =*/ net3,
1144                /*.nbt0 =*/ nbt0,
1145                /*.nbt1 =*/ nbt1,
1146                /*.nbt2 =*/ nbt2,
1147                /*.nbt3 =*/ nbt3,
1148                /*.outb =*/ false,
1149            };
1150
1151            ggml_metal_encoder_set_pipeline(enc, pipeline_blk);
1152            ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
1153            ggml_metal_encoder_set_buffer  (enc, bid_tmp, 1);
1154            ggml_metal_encoder_set_buffer  (enc, bid_tmp, 2);
1155            ggml_metal_encoder_set_buffer  (enc, bid_tmp, 3);
1156
1157            ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
1158
1159            ggml_metal_encoder_dispatch_threadgroups(enc, net1, net2, net3, nth, 1, 1);
1160        }
1161
1162        ggml_metal_op_concurrency_reset(ctx);
1163
1164        {
1165            auto pipeline_add = ggml_metal_library_get_pipeline_cumsum_add(lib, op);
1166
1167            ggml_metal_kargs_cumsum_add args = {
1168                /*.ne00 =*/ ne00,
1169                /*.ne01 =*/ ne01,
1170                /*.ne02 =*/ ne02,
1171                /*.ne03 =*/ ne03,
1172                /*.nb00 =*/ nb00,
1173                /*.nb01 =*/ nb01,
1174                /*.nb02 =*/ nb02,
1175                /*.nb03 =*/ nb03,
1176                /*.net0 =*/ net0,
1177                /*.net1 =*/ net1,
1178                /*.net2 =*/ net2,
1179                /*.net3 =*/ net3,
1180                /*.nbt0 =*/ nbt0,
1181                /*.nbt1 =*/ nbt1,
1182                /*.nbt2 =*/ nbt2,
1183                /*.nbt3 =*/ nbt3,
1184            };
1185
1186            ggml_metal_encoder_set_pipeline(enc, pipeline_add);
1187            ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
1188            ggml_metal_encoder_set_buffer  (enc, bid_tmp, 1);
1189            ggml_metal_encoder_set_buffer  (enc, bid_dst, 2);
1190
1191            ggml_metal_encoder_dispatch_threadgroups(enc, net0*ne01, ne02, ne03, nth, 1, 1);
1192        }
1193    }
1194
1195    return 1;
1196}
1197
1198int ggml_metal_op_get_rows(ggml_metal_op_t ctx, int idx) {
1199    ggml_tensor * op = ctx->node(idx);
1200
1201    ggml_metal_library_t lib = ctx->lib;
1202    ggml_metal_encoder_t enc = ctx->enc;
1203
1204    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
1205    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
1206    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
1207    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
1208    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
1209    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
1210
1211    auto pipeline = ggml_metal_library_get_pipeline_get_rows(lib, op->src[0]->type);
1212
1213    ggml_metal_kargs_get_rows args = {
1214        /*.ne00t =*/ ggml_is_quantized(op->src[0]->type) ? ne00/16 : ne00,
1215        /*.ne00  =*/ ne00,
1216        /*.nb01  =*/ nb01,
1217        /*.nb02  =*/ nb02,
1218        /*.nb03  =*/ nb03,
1219        /*.ne10  =*/ ne10,
1220        /*.nb10  =*/ nb10,
1221        /*.nb11  =*/ nb11,
1222        /*.nb12  =*/ nb12,
1223        /*.nb1   =*/ nb1,
1224        /*.nb2   =*/ nb2,
1225        /*.nb3   =*/ nb3,
1226    };
1227
1228    const int nth = std::min(args.ne00t, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
1229
1230    const int nw0 = (args.ne00t + nth - 1)/nth;
1231
1232    ggml_metal_encoder_set_pipeline(enc, pipeline);
1233    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
1234    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
1235    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
1236    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
1237
1238    ggml_metal_encoder_dispatch_threadgroups(enc, nw0*ne10, ne11, ne12, nth, 1, 1);
1239
1240    return 1;
1241}
1242
1243int ggml_metal_op_set_rows(ggml_metal_op_t ctx, int idx) {
1244    ggml_tensor * op = ctx->node(idx);
1245
1246    ggml_metal_library_t lib = ctx->lib;
1247    ggml_metal_encoder_t enc = ctx->enc;
1248
1249    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
1250    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
1251    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
1252    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
1253    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
1254    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
1255
1256    auto pipeline = ggml_metal_library_get_pipeline_set_rows(lib, op);
1257
1258    const int32_t nk0 = ne0/ggml_blck_size(op->type);
1259
1260    int nth = 32; // SIMD width
1261
1262    while (nth < nk0 && nth < ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
1263        nth *= 2;
1264    }
1265
1266    int nrptg = 1;
1267    if (nth > nk0) {
1268        nrptg = (nth + nk0 - 1)/nk0;
1269        nth   = nk0;
1270
1271        if (nrptg*nth > ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
1272            nrptg--;
1273        }
1274    }
1275
1276    nth = std::min(nth, nk0);
1277
1278    ggml_metal_kargs_set_rows args = {
1279        /*.nk0  =*/ nk0,
1280        /*.ne01 =*/ ne01,
1281        /*.nb01 =*/ nb01,
1282        /*.nb02 =*/ nb02,
1283        /*.nb03 =*/ nb03,
1284        /*.ne11 =*/ ne11,
1285        /*.ne12 =*/ ne12,
1286        /*.nb10 =*/ nb10,
1287        /*.nb11 =*/ nb11,
1288        /*.nb12 =*/ nb12,
1289        /*.nb1  =*/ nb1,
1290        /*.nb2  =*/ nb2,
1291        /*.nb3  =*/ nb3,
1292    };
1293
1294    ggml_metal_encoder_set_pipeline(enc, pipeline);
1295    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
1296    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
1297    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
1298    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
1299
1300    ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nrptg - 1)/nrptg, ne02, ne03, nth, nrptg, 1);
1301
1302    return 1;
1303}
1304
1305int ggml_metal_op_diag(ggml_metal_op_t ctx, int idx) {
1306    ggml_tensor * op = ctx->node(idx);
1307
1308    ggml_metal_library_t lib = ctx->lib;
1309    ggml_metal_encoder_t enc = ctx->enc;
1310
1311    GGML_TENSOR_LOCALS(int32_t,  ne0, op->src[0], ne);
1312    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
1313    GGML_TENSOR_LOCALS(int32_t,  ne, op, ne);
1314    GGML_TENSOR_LOCALS(uint64_t, nb, op, nb);
1315
1316    ggml_metal_kargs_diag args = {
1317        /*.ne00 =*/ne00,
1318        /*.ne01 =*/ne01,
1319        /*.ne02 =*/ne02,
1320        /*.ne03 =*/ne03,
1321        /*.nb00 =*/nb00,
1322        /*.nb01 =*/nb01,
1323        /*.nb02 =*/nb02,
1324        /*.nb03 =*/nb03,
1325        /*.ne0  =*/ne0,
1326        /*.ne1  =*/ne1,
1327        /*.ne2  =*/ne2,
1328        /*.ne3  =*/ne3,
1329        /*.nb0  =*/nb0,
1330        /*.nb1  =*/nb1,
1331        /*.nb2  =*/nb2,
1332        /*.nb3  =*/nb3,
1333    };
1334
1335    auto pipeline = ggml_metal_library_get_pipeline_diag(lib, op);
1336
1337    ggml_metal_encoder_set_pipeline(enc, pipeline);
1338    ggml_metal_encoder_set_bytes(enc, &args, sizeof(args), 0);
1339    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[0]), 1);
1340    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op),         2);
1341
1342    ggml_metal_encoder_dispatch_threadgroups(enc, ne1, ne2, ne3, 32, 1, 1);
1343
1344    return 1;
1345}
1346
1347int ggml_metal_op_lightning_indexer(ggml_metal_op_t ctx, int idx) {
1348    ggml_tensor * op = ctx->node(idx);
1349
1350    ggml_metal_encoder_t enc = ctx->enc;
1351
1352    GGML_ASSERT(op->op == GGML_OP_LIGHTNING_INDEXER);
1353
1354    const ggml_tensor * q = op->src[0];
1355    const ggml_tensor * k = op->src[1];
1356    const ggml_tensor * w = op->src[2];
1357    const ggml_tensor * m = op->src[3];
1358
1359    GGML_ASSERT(q->type == GGML_TYPE_F32);
1360    GGML_ASSERT(k->type == GGML_TYPE_F32  ||
1361                k->type == GGML_TYPE_F16  ||
1362                k->type == GGML_TYPE_BF16 ||
1363                k->type == GGML_TYPE_Q4_0 ||
1364                k->type == GGML_TYPE_Q4_1 ||
1365                k->type == GGML_TYPE_Q5_0 ||
1366                k->type == GGML_TYPE_Q5_1 ||
1367                k->type == GGML_TYPE_Q8_0);
1368    GGML_ASSERT(w->type == GGML_TYPE_F32);
1369    GGML_ASSERT(m->type == GGML_TYPE_F16);
1370    GGML_ASSERT(op->type == GGML_TYPE_F32);
1371
1372    GGML_ASSERT(q->ne[0] == OP_LIGHTNING_INDEXER_DK);
1373    GGML_ASSERT(q->ne[1] == OP_LIGHTNING_INDEXER_NH);
1374
1375    ggml_metal_kargs_lightning_indexer args = {
1376        /*.n_kv      =*/ (int32_t) k->ne[2],
1377        /*.n_batch   =*/ (int32_t) q->ne[2],
1378        /*.mask_ne3  =*/ (int32_t) m->ne[3],
1379        /*.nb1       =*/ op->nb[1],
1380        /*.nb3       =*/ op->nb[3],
1381        /*.nbq1      =*/ q->nb[1],
1382        /*.nbq2      =*/ q->nb[2],
1383        /*.nbq3      =*/ q->nb[3],
1384        /*.nbk2      =*/ k->nb[2],
1385        /*.nbk3      =*/ k->nb[3],
1386        /*.nbw1      =*/ w->nb[1],
1387        /*.nbw3      =*/ w->nb[3],
1388        /*.nbm1      =*/ m->nb[1],
1389        /*.nbm3      =*/ m->nb[3],
1390    };
1391
1392    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(q),  1);
1393    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(k),  2);
1394    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(w),  3);
1395    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(m),  4);
1396    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op), 5);
1397
1398    const int nsg   = OP_LIGHTNING_INDEXER_NSG;
1399    const int nkptg = OP_LIGHTNING_INDEXER_NKPSG*nsg;
1400    const int nbptg = OP_LIGHTNING_INDEXER_NBPTG;
1401
1402    auto pipeline = ggml_metal_library_get_pipeline_lightning_indexer(ctx->lib, op);
1403    ggml_metal_encoder_set_pipeline(enc, pipeline);
1404    ggml_metal_encoder_set_bytes(enc, &args, sizeof(args), 0);
1405    ggml_metal_encoder_dispatch_threadgroups(enc,
1406            (k->ne[2] + nkptg - 1)/nkptg,
1407            (q->ne[2] + nbptg - 1)/nbptg,
1408            q->ne[3], 32, nsg, 1);
1409
1410    return 1;
1411}
1412
1413int ggml_metal_op_dsv4_hc(ggml_metal_op_t ctx, int idx) {
1414    ggml_tensor * op = ctx->node(idx);
1415
1416    ggml_metal_encoder_t enc = ctx->enc;
1417    auto pipeline = ggml_metal_library_get_pipeline_dsv4_hc(ctx->lib, op);
1418
1419    ggml_metal_encoder_set_pipeline(enc, pipeline);
1420
1421    switch (op->op) {
1422        case GGML_OP_DSV4_HC_COMB:
1423            {
1424                const ggml_tensor * mixes = op->src[0];
1425                const ggml_tensor * scale = op->src[1];
1426                const ggml_tensor * base  = op->src[2];
1427
1428                GGML_ASSERT(mixes->type == GGML_TYPE_F32);
1429                GGML_ASSERT(scale->type == GGML_TYPE_F32);
1430                GGML_ASSERT(base->type  == GGML_TYPE_F32);
1431                GGML_ASSERT(op->type    == GGML_TYPE_F32);
1432                GGML_ASSERT(mixes->ne[0] == 24);
1433                GGML_ASSERT(op->ne[0] == 4 && op->ne[1] == 4);
1434
1435                ggml_metal_kargs_dsv4_hc_comb args = {
1436                    /*.n_tokens =*/ (int32_t) mixes->ne[1],
1437                    /*.n_iter   =*/ ggml_get_op_params_i32(op, 1),
1438                    /*.nb_m0    =*/ mixes->nb[0],
1439                    /*.nb_m1    =*/ mixes->nb[1],
1440                    /*.nb_s0    =*/ scale->nb[0],
1441                    /*.nb_b0    =*/ base->nb[0],
1442                    /*.nb_d0    =*/ op->nb[0],
1443                    /*.nb_d1    =*/ op->nb[1],
1444                    /*.nb_d2    =*/ op->nb[2],
1445                    /*.eps      =*/ ggml_get_op_params_f32(op, 0),
1446                };
1447
1448                ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0);
1449                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(mixes), 1);
1450                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(scale), 2);
1451                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(base),  3);
1452                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op),    4);
1453
1454                // One SIMDgroup owns one 4x4 Sinkhorn matrix. Packing up to four
1455                // independent tokens per threadgroup keeps both decode and prompt
1456                // dispatches compact without any threadgroup-memory synchronization.
1457                const int nsg = std::min(4, args.n_tokens);
1458                ggml_metal_encoder_dispatch_threadgroups(
1459                        enc, (args.n_tokens + nsg - 1)/nsg, 1, 1, 32, nsg, 1);
1460            } break;
1461        case GGML_OP_DSV4_HC_PRE:
1462            {
1463                const ggml_tensor * x       = op->src[0];
1464                const ggml_tensor * weights = op->src[1];
1465
1466                GGML_ASSERT(x->type       == GGML_TYPE_F32);
1467                GGML_ASSERT(weights->type == GGML_TYPE_F32);
1468                GGML_ASSERT(op->type      == GGML_TYPE_F32);
1469                GGML_ASSERT(x->ne[1] == 4);
1470
1471                ggml_metal_kargs_dsv4_hc_pre args = {
1472                    /*.n_embd   =*/ (int32_t) x->ne[0],
1473                    /*.n_tokens =*/ (int32_t) x->ne[2],
1474                    /*.nb_x0    =*/ x->nb[0],
1475                    /*.nb_x1    =*/ x->nb[1],
1476                    /*.nb_x2    =*/ x->nb[2],
1477                    /*.nb_w0    =*/ weights->nb[0],
1478                    /*.nb_w1    =*/ weights->nb[1],
1479                    /*.nb_w2    =*/ weights->nb[2],
1480                    /*.nb_d0    =*/ op->nb[0],
1481                    /*.nb_d1    =*/ op->nb[1],
1482                    /*.scale    =*/ ggml_get_op_params_f32(op, 0),
1483                };
1484
1485                ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0);
1486                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(x),       1);
1487                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(weights), 2);
1488                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op),      3);
1489
1490                const int n_tiles = (args.n_embd + 31)/32;
1491                const int nsg = std::min(4, n_tiles);
1492                ggml_metal_encoder_dispatch_threadgroups(
1493                        enc, (n_tiles + nsg - 1)/nsg, args.n_tokens, 1, 32, nsg, 1);
1494            } break;
1495        case GGML_OP_DSV4_HC_POST:
1496            {
1497                const ggml_tensor * x        = op->src[0];
1498                const ggml_tensor * residual = op->src[1];
1499                const ggml_tensor * post     = op->src[2];
1500                const ggml_tensor * comb     = op->src[3];
1501
1502                GGML_ASSERT(x->type        == GGML_TYPE_F32);
1503                GGML_ASSERT(residual->type == GGML_TYPE_F32);
1504                GGML_ASSERT(post->type     == GGML_TYPE_F32);
1505                GGML_ASSERT(op->type       == GGML_TYPE_F32);
1506                GGML_ASSERT(residual->ne[1] == 4);
1507
1508                ggml_metal_kargs_dsv4_hc_post args = {
1509                    /*.n_embd   =*/ (int32_t) x->ne[0],
1510                    /*.n_tokens =*/ (int32_t) x->ne[1],
1511                    /*.nb_x0    =*/ x->nb[0],
1512                    /*.nb_x1    =*/ x->nb[1],
1513                    /*.nb_r0    =*/ residual->nb[0],
1514                    /*.nb_r1    =*/ residual->nb[1],
1515                    /*.nb_r2    =*/ residual->nb[2],
1516                    /*.nb_p0    =*/ post->nb[0],
1517                    /*.nb_p1    =*/ post->nb[1],
1518                    /*.nb_c0    =*/ comb ? comb->nb[0] : 0,
1519                    /*.nb_c1    =*/ comb ? comb->nb[1] : 0,
1520                    /*.nb_c2    =*/ comb ? comb->nb[2] : 0,
1521                    /*.nb_d0    =*/ op->nb[0],
1522                    /*.nb_d1    =*/ op->nb[1],
1523                    /*.nb_d2    =*/ op->nb[2],
1524                };
1525
1526                ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0);
1527                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(x),        1);
1528                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(residual), 2);
1529                ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(post),     3);
1530                if (comb) {
1531                    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(comb), 4);
1532                    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op),   5);
1533                } else {
1534                    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op),   4);
1535                }
1536
1537                const int n_tiles = (args.n_embd + 31)/32;
1538                const int nsg = std::min(4, n_tiles);
1539                ggml_metal_encoder_dispatch_threadgroups(
1540                        enc, (n_tiles + nsg - 1)/nsg, args.n_tokens, 1, 32, nsg, 1);
1541            } break;
1542        default:
1543            GGML_ABORT("fatal error");
1544    }
1545
1546    return 1;
1547}
1548
1549int ggml_metal_op_soft_max(ggml_metal_op_t ctx, int idx) {
1550    ggml_tensor * op = ctx->node(idx);
1551
1552    if (ctx->use_fusion()) {
1553        int n = 1;
1554        const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n);
1555        if (fusion && ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_TOPK_MOE) {
1556            return ggml_metal_op_topk_moe(ctx, idx);
1557        }
1558    }
1559
1560    ggml_metal_library_t lib = ctx->lib;
1561    ggml_metal_encoder_t enc = ctx->enc;
1562
1563    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
1564    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
1565    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
1566    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
1567    GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
1568    GGML_TENSOR_LOCALS(uint64_t, nb2, op->src[2], nb);
1569    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
1570    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
1571
1572    float scale;
1573    float max_bias;
1574
1575    memcpy(&scale,    ((const int32_t *) op->op_params) + 0, sizeof(scale));
1576    memcpy(&max_bias, ((const int32_t *) op->op_params) + 1, sizeof(max_bias));
1577
1578    const uint32_t n_head      = op->src[0]->ne[2];
1579    const  int32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head));
1580
1581    const float m0 = powf(2.0f, -(max_bias       ) / n_head_log2);
1582    const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
1583
1584    // softmax
1585
1586    ggml_metal_kargs_soft_max args = {
1587        /*.ne00        =*/ ne00,
1588        /*.ne01        =*/ ne01,
1589        /*.ne02        =*/ ne02,
1590        /*.nb01        =*/ nb01,
1591        /*.nb02        =*/ nb02,
1592        /*.nb03        =*/ nb03,
1593        /*.ne11        =*/ ne11,
1594        /*.ne12        =*/ ne12,
1595        /*.ne13        =*/ ne13,
1596        /*.nb11        =*/ nb11,
1597        /*.nb12        =*/ nb12,
1598        /*.nb13        =*/ nb13,
1599        /*.nb1         =*/ nb1,
1600        /*.nb2         =*/ nb2,
1601        /*.nb3         =*/ nb3,
1602        /*.scale       =*/ scale,
1603        /*.max_bias    =*/ max_bias,
1604        /*.m0          =*/ m0,
1605        /*.m1          =*/ m1,
1606        /*.n_head_log2 =*/ n_head_log2,
1607    };
1608
1609    auto pipeline = ggml_metal_library_get_pipeline_soft_max(lib, op);
1610
1611    int nth = 32; // SIMD width
1612
1613    if (ne00%4 == 0) {
1614        while (nth < ne00/4 && nth*ne01*ne02*ne03 < 256) {
1615            nth *= 2;
1616        }
1617    } else {
1618        while (nth < ne00 && nth*ne01*ne02*ne03 < 256) {
1619            nth *= 2;
1620        }
1621    }
1622
1623    const size_t smem = pipeline.smem;
1624
1625    ggml_metal_encoder_set_pipeline(enc, pipeline);
1626    ggml_metal_encoder_set_bytes(enc, &args, sizeof(args), 0);
1627    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[0]), 1);
1628    if (op->src[1]) {
1629        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[1]), 2);
1630    } else {
1631        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[0]), 2);
1632    }
1633    if (op->src[2]) {
1634        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[2]), 3);
1635    } else {
1636        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[0]), 3);
1637    }
1638    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op), 4);
1639
1640    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
1641
1642    ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
1643
1644    return 1;
1645}
1646
1647int ggml_metal_op_ssm_conv(ggml_metal_op_t ctx, int idx) {
1648    ggml_tensor * op = ctx->node(idx);
1649
1650    ggml_metal_library_t lib = ctx->lib;
1651    ggml_metal_encoder_t enc = ctx->enc;
1652
1653    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
1654    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
1655    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
1656    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
1657    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
1658    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
1659
1660    int n_fuse = 1;
1661    bool use_silu = false;
1662
1663    if (ctx->use_fusion()) {
1664        int n = 1;
1665        const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n);
1666        if (fusion && ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_SSM_CONV_SILU) {
1667            n_fuse = n;
1668            use_silu = true;
1669
1670            ctx->count_fusions(fusion);
1671        }
1672    }
1673
1674    ggml_metal_kargs_ssm_conv args = {
1675        /*.ne00 =*/ ne00,
1676        /*.ne01 =*/ ne01,
1677        /*.ne02 =*/ ne02,
1678        /*.nb00 =*/ nb00,
1679        /*.nb01 =*/ nb01,
1680        /*.nb02 =*/ nb02,
1681        /*.ne11 =*/ ne11,
1682        /*.nb10 =*/ nb10,
1683        /*.nb11 =*/ nb11,
1684        /*.ne0  =*/ ne0,
1685        /*.ne1  =*/ ne1,
1686        /*.ne2  =*/ ne2,
1687        /*.nb0  =*/ nb0,
1688        /*.nb1  =*/ nb1,
1689        /*.nb2  =*/ nb2,
1690    };
1691
1692    const ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id(n_fuse > 1 ? ctx->node(idx + n_fuse - 1) : op);
1693
1694    // Use batched kernel for prefill (ne1 > 1) to reduce threadgroup dispatch overhead
1695    const bool use_batched = (ne1 > 1);
1696
1697    if (use_batched) {
1698        // Determine the smallest power of 2 that's >= ne1, but <= 256
1699        int BATCH_SIZE;
1700        if      (ne1 > 128) BATCH_SIZE = 256;
1701        else if (ne1 > 64 ) BATCH_SIZE = 128;
1702        else if (ne1 > 32 ) BATCH_SIZE = 64;
1703        else if (ne1 > 16 ) BATCH_SIZE = 32;
1704        else if (ne1 > 8  ) BATCH_SIZE = 16;
1705        else if (ne1 > 4  ) BATCH_SIZE = 8;
1706        else                BATCH_SIZE = 2;
1707
1708        auto pipeline = ggml_metal_library_get_pipeline_ssm_conv_batched(lib, op, BATCH_SIZE, (int32_t) ne10, use_silu);
1709
1710        ggml_metal_encoder_set_pipeline(enc, pipeline);
1711        ggml_metal_encoder_set_bytes(enc, &args, sizeof(args), 0);
1712        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[0]), 1);
1713        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[1]), 2);
1714        ggml_metal_encoder_set_buffer(enc, bid_dst, 3);
1715
1716        // Dispatch: ne01 rows, ceil(ne1/BATCH_SIZE) token batches, ne02 sequences
1717        // Each threadgroup has BATCH_SIZE threads, each handling one token
1718        const int n_token_batches = (ne1 + BATCH_SIZE - 1) / BATCH_SIZE;
1719        ggml_metal_encoder_dispatch_threadgroups(enc, ne01, n_token_batches, ne02, BATCH_SIZE, 1, 1);
1720    } else {
1721        auto pipeline = ggml_metal_library_get_pipeline_ssm_conv(lib, op, (int32_t) ne10, use_silu);
1722
1723        ggml_metal_encoder_set_pipeline(enc, pipeline);
1724        ggml_metal_encoder_set_bytes(enc, &args, sizeof(args), 0);
1725        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[0]), 1);
1726        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[1]), 2);
1727        ggml_metal_encoder_set_buffer(enc, bid_dst, 3);
1728
1729        ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne1, ne02, 1, 1, 1);
1730    }
1731
1732    if (n_fuse > 1 && ggml_metal_fusion_info_debug(ctx->finfo) > 1) {
1733        GGML_LOG_DEBUG("%s: fuse: SSM_CONV + UNARY\n", __func__);
1734    }
1735
1736    return n_fuse;
1737}
1738
1739int ggml_metal_op_ssm_scan(ggml_metal_op_t ctx, int idx) {
1740    ggml_tensor * op = ctx->node(idx);
1741
1742    ggml_metal_library_t lib = ctx->lib;
1743    ggml_metal_encoder_t enc = ctx->enc;
1744    const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ctx->dev);
1745
1746    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
1747    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
1748    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
1749    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
1750    GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
1751    GGML_TENSOR_LOCALS(uint64_t, nb2, op->src[2], nb);
1752    GGML_TENSOR_LOCALS( int32_t, ne3, op->src[3], ne);
1753    GGML_TENSOR_LOCALS(uint64_t, nb3, op->src[3], nb);
1754    GGML_TENSOR_LOCALS( int32_t, ne4, op->src[4], ne);
1755    GGML_TENSOR_LOCALS(uint64_t, nb4, op->src[4], nb);
1756    GGML_TENSOR_LOCALS( int32_t, ne5, op->src[5], ne);
1757    GGML_TENSOR_LOCALS(uint64_t, nb5, op->src[5], nb);
1758    GGML_TENSOR_LOCALS( int32_t, ne6, op->src[6], ne);
1759    GGML_TENSOR_LOCALS(uint64_t, nb6, op->src[6], nb);
1760    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
1761    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
1762
1763    const ggml_tensor * src3 = op->src[3];
1764    const ggml_tensor * src4 = op->src[4];
1765    const ggml_tensor * src5 = op->src[5];
1766    const ggml_tensor * src6 = op->src[6];
1767
1768    GGML_ASSERT(src3);
1769    GGML_ASSERT(src4);
1770    GGML_ASSERT(src5);
1771    GGML_ASSERT(src6);
1772
1773    const int64_t d_state      = ne00;
1774    const int64_t d_inner      = ne01;
1775    const int64_t n_head       = ne02;
1776    const int64_t n_group      = ne41;
1777    const int64_t n_seq_tokens = ne12;
1778    const int64_t n_seqs       = ne13;
1779    const int64_t K            = ggml_get_op_params_i32(op, 0);
1780
1781    GGML_ASSERT(K >= 1);
1782    GGML_ASSERT(ggml_nelements(op->src[1]) + K*d_state*d_inner*n_head*n_seqs == ggml_nelements(op));
1783
1784    ggml_metal_kargs_ssm_scan args = {
1785        /*.d_state      =*/ d_state,
1786        /*.d_inner      =*/ d_inner,
1787        /*.n_head       =*/ n_head,
1788        /*.n_group      =*/ n_group,
1789        /*.n_seq_tokens =*/ n_seq_tokens,
1790        /*.n_seq_tokens_total =*/ n_seq_tokens,
1791        /*.token_offset =*/ 0,
1792        /*.n_seqs       =*/ n_seqs,
1793        /*.K            =*/ K,
1794        /*.s_off        =*/ ggml_nelements(op->src[1]) * sizeof(float),
1795        /*.nb00         =*/ nb00,
1796        /*.nb01         =*/ nb01,
1797        /*.nb02         =*/ nb02,
1798        /*.nb03         =*/ nb03,
1799        /*.nb10         =*/ nb10,
1800        /*.nb11         =*/ nb11,
1801        /*.nb12         =*/ nb12,
1802        /*.ns12         =*/ nb12/nb10,
1803        /*.nb13         =*/ nb13,
1804        /*.nb20         =*/ nb20,
1805        /*.nb21         =*/ nb21,
1806        /*.ns21         =*/ nb21/nb20,
1807        /*.nb22         =*/ nb22,
1808        /*.ne30         =*/ ne30,
1809        /*.nb31         =*/ nb31,
1810        /*.nb41         =*/ nb41,
1811        /*.nb42         =*/ nb42,
1812        /*.ns42         =*/ nb42/nb40,
1813        /*.nb43         =*/ nb43,
1814        /*.nb51         =*/ nb51,
1815        /*.nb52         =*/ nb52,
1816        /*.ns52         =*/ nb52/nb50,
1817        /*.nb53         =*/ nb53,
1818        /*.nb0          =*/ nb0,
1819    };
1820
1821    constexpr int64_t CHUNK = OP_SSM_SCAN_SSD_CS;
1822
1823    const int64_t snap_reserve = K > 1 ? K : 0; // tokens reserved for sequential kernel rollback snapshots
1824    const int64_t mma_tokens = ((n_seq_tokens - snap_reserve) / CHUNK) * CHUNK; // largest multiple of CHUNK that leaves snap_reserve for the tail
1825    const bool use_mma =
1826        mma_tokens > 0 &&
1827        ne30 == 1 && // checks that A tensor is set to scalar decay per head (A shape {1, n_head})
1828        props_dev->has_simdgroup_mm && // hardware check for M1 or newer
1829        d_state % 8 == 0 && // d_state must be multiple of 8 to align with simdgroup_float 8x8 tiles
1830        d_inner == OP_SSM_SCAN_SSD_HD; // mma kernel is specialized for the Mamba-2 head dim; this checks it
1831
1832    const auto dispatch = [&](ggml_metal_pipeline_with_params pipeline, int64_t nth, int64_t n_tg_x) {
1833        GGML_ASSERT(nth <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
1834        GGML_ASSERT(pipeline.smem <= props_dev->max_theadgroup_memory_size);
1835
1836        ggml_metal_encoder_set_pipeline(enc, pipeline);
1837        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
1838        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
1839        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
1840        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[2]), 3);
1841        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[3]), 4);
1842        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[4]), 5);
1843        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[5]), 6);
1844        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[6]), 7);
1845        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         8);
1846        ggml_metal_encoder_set_threadgroup_memory_size(enc, pipeline.smem, 0);
1847        ggml_metal_encoder_dispatch_threadgroups(enc, n_tg_x, n_head, n_seqs, nth, 1, 1);
1848    };
1849
1850    if (!use_mma) {
1851        dispatch(ggml_metal_library_get_pipeline_ssm_scan(lib, op, false), d_state, d_inner);
1852        return 1;
1853    }
1854
1855    args.n_seq_tokens = mma_tokens;
1856    dispatch(
1857        ggml_metal_library_get_pipeline_ssm_scan_ssd_mma(lib, op),
1858        OP_SSM_SCAN_SSD_NSG*32,
1859        1);
1860
1861    if (mma_tokens < n_seq_tokens) {
1862        ggml_metal_op_concurrency_reset(ctx);
1863
1864        args.n_seq_tokens = n_seq_tokens - mma_tokens;
1865        args.token_offset = mma_tokens;
1866        dispatch(ggml_metal_library_get_pipeline_ssm_scan(lib, op, true), d_state, d_inner);
1867    }
1868
1869    return 1;
1870}
1871
1872int ggml_metal_op_rwkv(ggml_metal_op_t ctx, int idx) {
1873    ggml_tensor * op = ctx->node(idx);
1874
1875    ggml_metal_library_t lib = ctx->lib;
1876    ggml_metal_encoder_t enc = ctx->enc;
1877
1878    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
1879    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
1880    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
1881    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
1882
1883    const int64_t B = op->op == GGML_OP_RWKV_WKV6 ? op->src[5]->ne[1] : op->src[6]->ne[1];
1884    const int64_t T = op->src[0]->ne[2];
1885    const int64_t C = op->ne[0];
1886    const int64_t H = op->src[0]->ne[1];
1887
1888    auto pipeline = ggml_metal_library_get_pipeline_rwkv(lib, op);
1889
1890    int ida = 0;
1891
1892    ggml_metal_encoder_set_pipeline(enc, pipeline);
1893    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), ida++);
1894    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), ida++);
1895    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[2]), ida++);
1896    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[3]), ida++);
1897    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[4]), ida++);
1898    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[5]), ida++);
1899    if (op->op == GGML_OP_RWKV_WKV7) {
1900        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[6]), ida++);
1901    }
1902    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         ida++);
1903    ggml_metal_encoder_set_bytes   (enc, (void *) &B, sizeof(B), ida++);
1904    ggml_metal_encoder_set_bytes   (enc, (void *) &T, sizeof(T), ida++);
1905    ggml_metal_encoder_set_bytes   (enc, (void *) &C, sizeof(C), ida++);
1906    ggml_metal_encoder_set_bytes   (enc, (void *) &H, sizeof(H), ida++);
1907
1908    ggml_metal_encoder_dispatch_threadgroups(enc, B * H, 1, 1, C/H, 1, 1);
1909
1910    return 1;
1911}
1912
1913int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) {
1914    ggml_tensor * op = ctx->node(idx);
1915
1916    ggml_metal_library_t lib = ctx->lib;
1917    ggml_metal_encoder_t enc = ctx->enc;
1918
1919    const bool use_fusion = ctx->use_fusion();
1920    const int  debug_fusion = ggml_metal_fusion_info_debug(ctx->finfo);
1921
1922    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
1923    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
1924    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
1925    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
1926    GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
1927    GGML_TENSOR_LOCALS(uint64_t, nb2, op->src[2], nb);
1928    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
1929    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
1930
1931    auto pipeline = ggml_metal_library_get_pipeline_gated_delta_net(lib, op);
1932
1933    // when fused with the trailing cache cpy, the snapshots are written straight into the
1934    // recurrent cache and the cpy is skipped (see GGML_METAL_FUSION_GDN_CACHE)
1935    ggml_metal_buffer_id bid_out = ggml_metal_get_buffer_id(op);
1936    uint64_t nb_out = 0;
1937    int n_fuse = 1;
1938
1939    if (use_fusion) {
1940        int n = 1;
1941        const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n);
1942
1943        if (fusion && ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_GDN_CACHE) {
1944            const ggml_tensor * dst_cache = ctx->node(idx + 1)->src[1]; // cache view
1945
1946            bid_out = ggml_metal_get_buffer_id(dst_cache);
1947            nb_out  = dst_cache->nb[2]/sizeof(float);
1948            n_fuse = 2;
1949
1950            ctx->count_fusions(fusion);
1951
1952            if (debug_fusion > 1) {
1953                GGML_LOG_DEBUG("%s: fuse: GATED_DELTA_NET + CPY\n", __func__);
1954            }
1955        }
1956    }
1957
1958    int ida = 0;
1959
1960    ggml_metal_kargs_gated_delta_net args = {
1961        /*.ne00 =*/ ne00,
1962        /*.ne01 =*/ ne01,
1963        /*.ne02 =*/ ne02,
1964        /*.ne03 =*/ ne03,
1965        /*.nb00 =*/ nb00,
1966        /*.nb01 =*/ nb01,
1967        /*.nb02 =*/ nb02,
1968        /*.nb03 =*/ nb03,
1969        /*.ne10 =*/ ne10,
1970        /*.ne11 =*/ ne11,
1971        /*.ne12 =*/ ne12,
1972        /*.ne13 =*/ ne13,
1973        /*.nb10 =*/ nb10,
1974        /*.nb11 =*/ nb11,
1975        /*.nb12 =*/ nb12,
1976        /*.nb13 =*/ nb13,
1977        /*.ne20 =*/ ne20,
1978        /*.ne21 =*/ ne21,
1979        /*.ne22 =*/ ne22,
1980        /*.ne23 =*/ ne23,
1981        /*.nb20 =*/ nb20,
1982        /*.nb21 =*/ nb21,
1983        /*.nb22 =*/ nb22,
1984        /*.nb23 =*/ nb23,
1985        /*.ns02 =*/ (int32_t) (nb02/sizeof(float)),
1986        /*.ns12 =*/ (int32_t) (nb12/sizeof(float)),
1987        /*.ns22 =*/ (int32_t) (nb22/sizeof(float)),
1988        /*.ne0  =*/ ne0,
1989        /*.ne1  =*/ ne1,
1990        /*.ne2  =*/ ne2,
1991        /*.ne3  =*/ ne3,
1992        /*.nb0  =*/ nb0,
1993        /*.nb1  =*/ nb1,
1994        /*.nb2  =*/ nb2,
1995        /*.nb3  =*/ nb3,
1996        /*.nb_out =*/ nb_out,
1997    };
1998
1999    ggml_metal_encoder_set_pipeline(enc, pipeline);
2000    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args),                  ida++); // args
2001    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), ida++); // q
2002    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), ida++); // k
2003    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[2]), ida++); // v
2004    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[3]), ida++); // gate
2005    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[4]), ida++); // beta
2006    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[5]), ida++); // state
2007    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         ida++); // dst (attn)
2008    ggml_metal_encoder_set_buffer  (enc, bid_out,                              ida++); // state_out
2009
2010    const int nsg = pipeline.nsg;
2011
2012    ggml_metal_encoder_dispatch_threadgroups(enc, op->src[2]->ne[0]/nsg, op->src[2]->ne[1], op->src[2]->ne[3], 32, nsg, 1);
2013
2014    return n_fuse;
2015}
2016
2017int ggml_metal_op_solve_tri(ggml_metal_op_t ctx, int idx) {
2018    ggml_tensor * op = ctx->node(idx);
2019
2020    ggml_metal_library_t lib = ctx->lib;
2021    ggml_metal_encoder_t enc = ctx->enc;
2022
2023    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
2024    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
2025    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
2026    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
2027    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
2028    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
2029
2030    ggml_metal_kargs_solve_tri args = {
2031        /*.ne00 =*/ ne00,
2032        /*.ne01 =*/ ne01,
2033        /*.ne02 =*/ ne02,
2034        /*.ne03 =*/ ne03,
2035        /*.nb00 =*/ nb00,
2036        /*.nb01 =*/ nb01,
2037        /*.nb02 =*/ nb02,
2038        /*.nb03 =*/ nb03,
2039        /*.ne10 =*/ ne10,
2040        /*.ne11 =*/ ne11,
2041        /*.ne12 =*/ ne12,
2042        /*.ne13 =*/ ne13,
2043        /*.nb10 =*/ nb10,
2044        /*.nb11 =*/ nb11,
2045        /*.nb12 =*/ nb12,
2046        /*.nb13 =*/ nb13,
2047        /*.ne0  =*/ ne0,
2048        /*.ne1  =*/ ne1,
2049        /*.ne2  =*/ ne2,
2050        /*.ne3  =*/ ne3,
2051        /*.nb0  =*/ nb0,
2052        /*.nb1  =*/ nb1,
2053        /*.nb2  =*/ nb2,
2054        /*.nb3  =*/ nb3,
2055    };
2056
2057    auto pipeline = ggml_metal_library_get_pipeline_solve_tri(lib, op);
2058
2059    ggml_metal_encoder_set_pipeline(enc, pipeline);
2060    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2061    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
2062    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
2063    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
2064
2065    const int nsg = pipeline.nsg;
2066
2067    ggml_metal_encoder_set_threadgroup_memory_size(enc, pipeline.smem, 0);
2068
2069    ggml_metal_encoder_dispatch_threadgroups(enc, (ne10 + nsg - 1)/nsg, ne02, ne03, 32, nsg, 1);
2070
2071    return 1;
2072}
2073
2074int ggml_metal_op_set(ggml_metal_op_t ctx, int idx) {
2075    ggml_tensor * op = ctx->node(idx);
2076
2077    ggml_metal_library_t lib = ctx->lib;
2078    ggml_metal_encoder_t enc = ctx->enc;
2079
2080    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
2081    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
2082    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
2083    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
2084    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
2085    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
2086
2087    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
2088    ggml_metal_buffer_id bid_src1 = ggml_metal_get_buffer_id(op->src[1]);
2089    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
2090
2091    const size_t pnb1 = ((const int32_t *) op->op_params)[0];
2092    const size_t pnb2 = ((const int32_t *) op->op_params)[1];
2093    const size_t pnb3 = ((const int32_t *) op->op_params)[2];
2094    const size_t offs = ((const int32_t *) op->op_params)[3];
2095
2096    const bool inplace = (bool) ((const int32_t *) op->op_params)[4];
2097
2098    if (!inplace) {
2099        // run a separate kernel to cpy src->dst
2100        // not sure how to avoid this
2101        // TODO: make a simpler cpy_bytes kernel
2102
2103        //const id<MTLComputePipelineState> pipeline = ctx->pipelines[GGML_METAL_PIPELINE_TYPE_CPY_F32_F32].obj;
2104        auto pipeline = ggml_metal_library_get_pipeline_cpy(lib, op->src[0]->type, op->type);
2105
2106        ggml_metal_kargs_cpy args = {
2107            /*.nk0  =*/ ne00,
2108            /*.ne00 =*/ ne00,
2109            /*.ne01 =*/ ne01,
2110            /*.ne02 =*/ ne02,
2111            /*.ne03 =*/ ne03,
2112            /*.nb00 =*/ nb00,
2113            /*.nb01 =*/ nb01,
2114            /*.nb02 =*/ nb02,
2115            /*.nb03 =*/ nb03,
2116            /*.ne0  =*/ ne0,
2117            /*.ne1  =*/ ne1,
2118            /*.ne2  =*/ ne2,
2119            /*.ne3  =*/ ne3,
2120            /*.nb0  =*/ nb0,
2121            /*.nb1  =*/ nb1,
2122            /*.nb2  =*/ nb2,
2123            /*.nb3  =*/ nb3,
2124        };
2125
2126        ggml_metal_encoder_set_pipeline(enc, pipeline);
2127        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2128        ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
2129        ggml_metal_encoder_set_buffer  (enc, bid_dst,  2);
2130
2131        const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), ne00);
2132
2133        ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
2134
2135        ggml_metal_op_concurrency_reset(ctx);
2136    }
2137
2138    auto pipeline = ggml_metal_library_get_pipeline_cpy(lib, op->src[1]->type, op->type);
2139
2140    GGML_ASSERT(ne10 % ggml_blck_size(op->src[1]->type) == 0);
2141
2142    int64_t nk0 = ne10;
2143    if (ggml_is_quantized(op->src[1]->type)) {
2144        nk0 = ne10/16;
2145    } else if (ggml_is_quantized(op->type)) {
2146        nk0 = ne10/ggml_blck_size(op->type);
2147    }
2148
2149    int nth = std::min<int>(nk0*ne11, 256);
2150
2151    // when rows are small, we can batch them together in a single threadgroup
2152    int nrptg = 1;
2153
2154    // TODO: relax this constraint in the future
2155    if (ggml_blck_size(op->src[1]->type) == 1 && ggml_blck_size(op->type) == 1) {
2156        if (nth > nk0) {
2157            nrptg = (nth + nk0 - 1)/nk0;
2158            nth   = nk0;
2159
2160            if (nrptg*nth > 256) {
2161                nrptg--;
2162            }
2163        }
2164    }
2165
2166    nth = std::min<int>(nth, nk0);
2167
2168    ggml_metal_kargs_cpy args = {
2169        /*.nk0  =*/ nk0,
2170        /*.ne00 =*/ ne10,
2171        /*.ne01 =*/ ne11,
2172        /*.ne02 =*/ ne12,
2173        /*.ne03 =*/ ne13,
2174        /*.nb00 =*/ nb10,
2175        /*.nb01 =*/ nb11,
2176        /*.nb02 =*/ nb12,
2177        /*.nb03 =*/ nb13,
2178        /*.ne0  =*/ ne10,
2179        /*.ne1  =*/ ne11,
2180        /*.ne2  =*/ ne12,
2181        /*.ne3  =*/ ne13,
2182        /*.nb0  =*/ ggml_element_size(op),
2183        /*.nb1  =*/ pnb1,
2184        /*.nb2  =*/ pnb2,
2185        /*.nb3  =*/ pnb3,
2186    };
2187
2188    const int nw0 = nrptg == 1 ? (nk0 + nth - 1)/nth : 1;
2189
2190    bid_dst.offs += offs;
2191
2192    ggml_metal_encoder_set_pipeline(enc, pipeline);
2193    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2194    ggml_metal_encoder_set_buffer  (enc, bid_src1, 1);
2195    ggml_metal_encoder_set_buffer  (enc, bid_dst,  2);
2196
2197    ggml_metal_encoder_dispatch_threadgroups(enc, nw0*(ne11 + nrptg - 1)/nrptg, ne12, ne13, nth, nrptg, 1);
2198
2199    return 1;
2200}
2201
2202int ggml_metal_op_cpy(ggml_metal_op_t ctx, int idx) {
2203    ggml_tensor * op = ctx->node(idx);
2204
2205    ggml_metal_library_t lib = ctx->lib;
2206    ggml_metal_encoder_t enc = ctx->enc;
2207
2208    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
2209    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
2210    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
2211    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
2212
2213    auto pipeline = ggml_metal_library_get_pipeline_cpy(lib, op->src[0]->type, op->type);
2214
2215    GGML_ASSERT(ne00 % ggml_blck_size(op->src[0]->type) == 0);
2216
2217    int64_t nk0 = ne00;
2218    if (ggml_is_quantized(op->src[0]->type)) {
2219        nk0 = ne00/16;
2220    } else if (ggml_is_quantized(op->type)) {
2221        nk0 = ne00/ggml_blck_size(op->type);
2222    }
2223
2224    int nth = std::min<int>(nk0*ne01, 256);
2225
2226    // when rows are small, we can batch them together in a single threadgroup
2227    int nrptg = 1;
2228
2229    // TODO: relax this constraint in the future
2230    if (ggml_blck_size(op->src[0]->type) == 1 && ggml_blck_size(op->type) == 1) {
2231        if (nth > nk0) {
2232            nrptg = (nth + nk0 - 1)/nk0;
2233            nth   = nk0;
2234
2235            if (nrptg*nth > 256) {
2236                nrptg--;
2237            }
2238        }
2239    }
2240
2241    nth = std::min<int>(nth, nk0);
2242
2243    ggml_metal_kargs_cpy args = {
2244        /*.nk0  =*/ nk0,
2245        /*.ne00 =*/ ne00,
2246        /*.ne01 =*/ ne01,
2247        /*.ne02 =*/ ne02,
2248        /*.ne03 =*/ ne03,
2249        /*.nb00 =*/ nb00,
2250        /*.nb01 =*/ nb01,
2251        /*.nb02 =*/ nb02,
2252        /*.nb03 =*/ nb03,
2253        /*.ne0  =*/ ne0,
2254        /*.ne1  =*/ ne1,
2255        /*.ne2  =*/ ne2,
2256        /*.ne3  =*/ ne3,
2257        /*.nb0  =*/ nb0,
2258        /*.nb1  =*/ nb1,
2259        /*.nb2  =*/ nb2,
2260        /*.nb3  =*/ nb3,
2261    };
2262
2263    const int nw0 = nrptg == 1 ? (nk0 + nth - 1)/nth : 1;
2264
2265    ggml_metal_encoder_set_pipeline(enc, pipeline);
2266    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2267    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
2268    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
2269
2270    ggml_metal_encoder_dispatch_threadgroups(enc, nw0*(ne01 + nrptg - 1)/nrptg, ne02, ne03, nth, nrptg, 1);
2271
2272    return 1;
2273}
2274
2275int ggml_metal_op_pool_1d(ggml_metal_op_t ctx, int idx) {
2276    ggml_tensor * op = ctx->node(idx);
2277
2278    ggml_metal_library_t lib = ctx->lib;
2279    ggml_metal_encoder_t enc = ctx->enc;
2280
2281    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
2282    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
2283    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
2284    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
2285
2286    const int32_t * opts = op->op_params;
2287    ggml_op_pool op_pool = (ggml_op_pool) opts[0];
2288
2289    const int32_t k0 = opts[1];
2290    const int32_t s0 = opts[2];
2291    const int32_t p0 = opts[3];
2292
2293    const int64_t IW = op->src[0]->ne[0];
2294    const int64_t OW = op->ne[0];
2295
2296    const int64_t np = ggml_nelements(op);
2297
2298    ggml_metal_kargs_pool_1d args_pool_1d = {
2299        /* .k0 = */  k0,
2300        /* .s0 = */  s0,
2301        /* .p0 = */  p0,
2302        /* .IW = */  IW,
2303        /* .OW = */  OW,
2304        /* .np = */  np
2305    };
2306
2307    auto pipeline = ggml_metal_library_get_pipeline_pool_1d(lib, op, op_pool);
2308
2309    const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), (int) np);
2310    const int ntg = (np + nth - 1) / nth;
2311
2312    ggml_metal_encoder_set_pipeline(enc, pipeline);
2313    ggml_metal_encoder_set_bytes   (enc, &args_pool_1d, sizeof(args_pool_1d),  0);
2314    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
2315    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
2316
2317    ggml_metal_encoder_dispatch_threadgroups(enc, ntg, 1, 1, nth, 1, 1);
2318
2319    return 1;
2320}
2321
2322int ggml_metal_op_fwht(ggml_metal_op_t ctx, int idx) {
2323    ggml_tensor * op = ctx->node(idx);
2324
2325    ggml_metal_library_t lib = ctx->lib;
2326    ggml_metal_encoder_t enc = ctx->enc;
2327
2328    ggml_tensor * src1 = op->src[1];
2329
2330    const int64_t n = src1->ne[0];
2331    const int64_t nrows = ggml_nrows(src1);
2332
2333    ggml_metal_kargs_fwht args = {
2334        /*.nrows = */ (int32_t) nrows,
2335    };
2336
2337    auto pipeline = ggml_metal_library_get_pipeline_fwht(lib, n, src1->type);
2338
2339    ggml_metal_encoder_set_pipeline(enc, pipeline);
2340    ggml_metal_encoder_set_bytes(enc, &args, sizeof(args), 0);
2341    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(src1), 1);
2342    ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op), 2);
2343
2344    const int th_max = ggml_metal_pipeline_max_theads_per_threadgroup(pipeline);
2345    const int simd_size = 32;
2346
2347    int sg_per_tg = 2;
2348    sg_per_tg = std::min(sg_per_tg, th_max/simd_size);
2349    sg_per_tg = std::max(sg_per_tg, 1);
2350
2351    const int64_t n_tg = (nrows + sg_per_tg - 1) / sg_per_tg;
2352    ggml_metal_encoder_dispatch_threadgroups(enc, n_tg, 1, 1, 32*sg_per_tg, 1, 1);
2353
2354    return 1;
2355}
2356
2357int ggml_metal_op_pool_2d(ggml_metal_op_t ctx, int idx) {
2358    ggml_tensor * op = ctx->node(idx);
2359
2360    ggml_metal_library_t lib = ctx->lib;
2361    ggml_metal_encoder_t enc = ctx->enc;
2362
2363    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
2364    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
2365    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
2366    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
2367
2368    const int32_t * opts = op->op_params;
2369    ggml_op_pool op_pool = (ggml_op_pool) opts[0];
2370
2371    const int32_t k0 = opts[1];
2372    const int32_t k1 = opts[2];
2373    const int32_t s0 = opts[3];
2374    const int32_t s1 = opts[4];
2375    const int32_t p0 = opts[5];
2376    const int32_t p1 = opts[6];
2377
2378    const int64_t IH = op->src[0]->ne[1];
2379    const int64_t IW = op->src[0]->ne[0];
2380
2381    const int64_t N  = op->ne[3];
2382    const int64_t OC = op->ne[2];
2383    const int64_t OH = op->ne[1];
2384    const int64_t OW = op->ne[0];
2385
2386    const int64_t np = N * OC * OH * OW;
2387
2388    ggml_metal_kargs_pool_2d args_pool_2d = {
2389        /* .k0 = */ k0,
2390        /* .k1 = */ k1,
2391        /* .s0 = */ s0,
2392        /* .s1 = */ s1,
2393        /* .p0 = */ p0,
2394        /* .p1 = */ p1,
2395        /* .IH = */ IH,
2396        /* .IW = */ IW,
2397        /* .OH = */ OH,
2398        /* .OW = */ OW,
2399        /* .np = */ np
2400    };
2401
2402    auto pipeline = ggml_metal_library_get_pipeline_pool_2d(lib, op, op_pool);
2403
2404    const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), (int) np);
2405    const int ntg = (np + nth - 1) / nth;
2406
2407    ggml_metal_encoder_set_pipeline(enc, pipeline);
2408    ggml_metal_encoder_set_bytes   (enc, &args_pool_2d, sizeof(args_pool_2d), 0);
2409    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
2410    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
2411
2412    ggml_metal_encoder_dispatch_threadgroups(enc, ntg, 1, 1, nth, 1, 1);
2413
2414    return 1;
2415}
2416
2417int ggml_metal_op_mul_mat(ggml_metal_op_t ctx, int idx) {
2418    ggml_tensor * op = ctx->node(idx);
2419
2420    ggml_metal_library_t lib = ctx->lib;
2421    ggml_metal_encoder_t enc = ctx->enc;
2422
2423    if (ggml_metal_op_mul_mat_use_fwht(op)) {
2424        return ggml_metal_op_fwht(ctx, idx);
2425    }
2426    const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ctx->dev);
2427
2428    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
2429    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
2430    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
2431    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
2432    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
2433    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
2434
2435    GGML_ASSERT(ne00 == ne10);
2436
2437    GGML_ASSERT(ne12 % ne02 == 0);
2438    GGML_ASSERT(ne13 % ne03 == 0);
2439
2440    const int16_t r2 = ne12/ne02;
2441    const int16_t r3 = ne13/ne03;
2442
2443    // first try to use small-batch mat-mv kernels
2444    // these should be efficient for BS [2, ~8]
2445    if (op->src[1]->type == GGML_TYPE_F32 && (ne00%128 == 0) &&
2446        (
2447         (
2448          (
2449           op->src[0]->type == GGML_TYPE_F32  || // TODO: helper function
2450           op->src[0]->type == GGML_TYPE_F16  ||
2451           op->src[0]->type == GGML_TYPE_BF16 ||
2452           op->src[0]->type == GGML_TYPE_Q1_0 ||
2453           op->src[0]->type == GGML_TYPE_Q2_0 ||
2454           op->src[0]->type == GGML_TYPE_Q4_0 ||
2455           op->src[0]->type == GGML_TYPE_Q4_1 ||
2456           op->src[0]->type == GGML_TYPE_Q5_0 ||
2457           op->src[0]->type == GGML_TYPE_Q5_1 ||
2458           op->src[0]->type == GGML_TYPE_Q8_0 ||
2459           op->src[0]->type == GGML_TYPE_MXFP4 ||
2460           op->src[0]->type == GGML_TYPE_IQ4_NL ||
2461           false) && (ne11 >= 2 && ne11 <= 8)
2462         ) ||
2463         (
2464          (
2465           op->src[0]->type == GGML_TYPE_Q4_K ||
2466           op->src[0]->type == GGML_TYPE_Q5_K ||
2467           op->src[0]->type == GGML_TYPE_Q6_K ||
2468           op->src[0]->type == GGML_TYPE_Q2_K ||
2469           op->src[0]->type == GGML_TYPE_Q3_K ||
2470           false) && (ne11 >= 4 && ne11 <= 8)
2471         )
2472        )
2473       ) {
2474        // TODO: determine the optimal parameters based on grid utilization
2475        //       I still don't know why we should not always use the maximum available threads:
2476        //
2477        //       nsg = pipeline.maxTotalThreadsPerThreadgroup / 32
2478        //
2479        //       my current hypothesis is that the work grid is not evenly divisible for different nsg
2480        //       values and there can be some tail effects when nsg is high. need to confirm this
2481        //
2482        const int nsg    = 2;                 // num simdgroups per threadgroup
2483
2484        // num threads along row per simdgroup
2485        int16_t nxpsg = 0;
2486        if (ne00 % 256 == 0 && ne11 < 3) {
2487            nxpsg = 16;
2488        } else if (ne00 % 128 == 0) {
2489            nxpsg = 8;
2490        } else {
2491            nxpsg = 4;
2492        }
2493
2494        const int16_t nypsg  = 32/nxpsg;          // num threads along col per simdgroup (i.e. a simdgroup processes that many src0 rows at a time)
2495        const int16_t r0ptg  = nypsg*nsg;         // num src0 rows per threadgroup
2496              int16_t r1ptg  = 4;                 // num src1 rows per threadgroup
2497
2498        // note: not sure how optimal are those across all different hardware. there might be something cleverer
2499        switch (ne11) {
2500            case 2:
2501                r1ptg = 2; break;
2502            case 3:
2503            case 6:
2504                r1ptg = 3; break;
2505            case 4:
2506            case 7:
2507            case 8:
2508                r1ptg = 4; break;
2509            case 5:
2510                r1ptg = 5; break;
2511            default:
2512                GGML_ABORT("unsupported ne11");
2513        };
2514
2515        auto pipeline = ggml_metal_library_get_pipeline_mul_mv_ext(lib, op, nsg, nxpsg, r1ptg);
2516
2517        ggml_metal_kargs_mul_mv_ext args = {
2518            /*.ne00  =*/ ne00,
2519            /*.ne01  =*/ ne01,
2520            /*.ne02  =*/ ne02,
2521            /*.nb00  =*/ nb00,
2522            /*.nb01  =*/ nb01,
2523            /*.nb02  =*/ nb02,
2524            /*.nb03  =*/ nb03,
2525            /*.ne10  =*/ ne10,
2526            /*.ne11  =*/ ne11,
2527            /*.ne12  =*/ ne12,
2528            /*.nb10  =*/ nb10,
2529            /*.nb11  =*/ nb11,
2530            /*.nb12  =*/ nb12,
2531            /*.nb13  =*/ nb13,
2532            /*.ne0   =*/ ne0,
2533            /*.ne1   =*/ ne1,
2534            /*.r2    =*/ r2,
2535            /*.r3    =*/ r3,
2536        };
2537
2538        ggml_metal_encoder_set_pipeline(enc, pipeline);
2539        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2540        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
2541        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
2542        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
2543
2544        ggml_metal_encoder_dispatch_threadgroups(enc, ((ne01 + r0ptg - 1)/r0ptg), ((ne11 + r1ptg - 1)/r1ptg), ne12*ne13, 32, nsg, 1);
2545    } else if (ggml_metal_op_mul_mat_use_mm(op, props_dev->has_simdgroup_mm)) {
2546        //GGML_LOG_INFO("matrix: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
2547
2548        // some Metal matrix data types require aligned pointers
2549        // ref: https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf (Table 2.5)
2550        //switch (op->src[0]->type) {
2551        //    case GGML_TYPE_F32:  GGML_ASSERT(nb01 % 16 == 0); break;
2552        //    case GGML_TYPE_F16:  GGML_ASSERT(nb01 % 8  == 0); break;
2553        //    case GGML_TYPE_BF16: GGML_ASSERT(nb01 % 8  == 0); break;
2554        //    default: break;
2555        //}
2556
2557        auto pipeline = ggml_metal_library_get_pipeline_mul_mm(lib, op);
2558
2559        ggml_metal_kargs_mul_mm args = {
2560            /*.ne00 =*/ ne00,
2561            /*.ne02 =*/ ne02,
2562            /*.nb01 =*/ nb01,
2563            /*.nb02 =*/ nb02,
2564            /*.nb03 =*/ nb03,
2565            /*.ne12 =*/ ne12,
2566            /*.nb10 =*/ nb10,
2567            /*.nb11 =*/ nb11,
2568            /*.nb12 =*/ nb12,
2569            /*.nb13 =*/ nb13,
2570            /*.ne0  =*/ ne0,
2571            /*.ne1  =*/ ne1,
2572            /*.r2   =*/ r2,
2573            /*.r3   =*/ r3,
2574        };
2575
2576        ggml_metal_encoder_set_pipeline(enc, pipeline);
2577        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2578        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
2579        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
2580        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
2581
2582        const size_t smem = pipeline.smem;
2583
2584        ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
2585
2586        const int nr0 = pipeline.nr0;
2587        const int nr1 = pipeline.nr1;
2588        const int nsg = pipeline.nsg;
2589
2590        ggml_metal_encoder_dispatch_threadgroups(enc, ((ne11 + nr1 - 1) / nr1), ((ne01 + nr0 - 1) / nr0), ne12 * ne13, 32, nsg, 1);
2591    } else {
2592        auto pipeline = ggml_metal_library_get_pipeline_mul_mv(lib, op);
2593
2594        const int nr0 = pipeline.nr0;
2595        const int nr1 = pipeline.nr1;
2596        const int nsg = pipeline.nsg;
2597
2598        const size_t smem = pipeline.smem;
2599
2600        ggml_metal_kargs_mul_mv args = {
2601            /*.ne00 =*/ ne00,
2602            /*.ne01 =*/ ne01,
2603            /*.ne02 =*/ ne02,
2604            /*.nb00 =*/ nb00,
2605            /*.nb01 =*/ nb01,
2606            /*.nb02 =*/ nb02,
2607            /*.nb03 =*/ nb03,
2608            /*.ne10 =*/ ne10,
2609            /*.ne11 =*/ ne11,
2610            /*.ne12 =*/ ne12,
2611            /*.nb10 =*/ nb10,
2612            /*.nb11 =*/ nb11,
2613            /*.nb12 =*/ nb12,
2614            /*.nb13 =*/ nb13,
2615            /*.ne0  =*/ ne0,
2616            /*.ne1  =*/ ne1,
2617            /*.nr0  =*/ nr0,
2618            /*.r2   =*/ r2,
2619            /*.r3   =*/ r3,
2620        };
2621
2622        ggml_metal_encoder_set_pipeline(enc, pipeline);
2623        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2624        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
2625        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
2626        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
2627
2628        ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
2629
2630        if (op->src[0]->type == GGML_TYPE_F32 ||
2631            op->src[0]->type == GGML_TYPE_F16 ||
2632            op->src[0]->type == GGML_TYPE_BF16 ||
2633            op->src[0]->type == GGML_TYPE_Q8_0) {
2634            ggml_metal_encoder_dispatch_threadgroups(enc, ((ne01 + nr0 - 1)/(nr0)), ((ne11 + nr1 - 1)/nr1), ne12*ne13, 32, nsg, 1);
2635        } else {
2636            ggml_metal_encoder_dispatch_threadgroups(enc, ((ne01 + nr0*nsg - 1)/(nr0*nsg)), ((ne11 + nr1 - 1)/nr1), ne12*ne13, 32, nsg, 1);
2637        }
2638    }
2639
2640    return 1;
2641}
2642
2643size_t ggml_metal_op_mul_mat_id_extra_tpe(const ggml_tensor * op) {
2644    assert(op->op == GGML_OP_MUL_MAT_ID);
2645
2646    const int64_t ne02 = op->src[0]->ne[2]; // n_expert
2647
2648    return ggml_type_size(GGML_TYPE_I32)*ne02;
2649}
2650
2651size_t ggml_metal_op_mul_mat_id_extra_ids(const ggml_tensor * op) {
2652    assert(op->op == GGML_OP_MUL_MAT_ID);
2653
2654    const int64_t ne02 = op->src[0]->ne[2]; // n_expert
2655    const int64_t ne21 = op->src[2]->ne[1]; // n_token
2656
2657    return ggml_type_size(GGML_TYPE_I32)*ne02*ne21;
2658}
2659
2660size_t ggml_metal_op_mul_mat_id_extra_amax(const ggml_tensor * op) {
2661    assert(op->op == GGML_OP_MUL_MAT_ID);
2662
2663    GGML_UNUSED(op);
2664
2665    // 2 scaling factors (8 bytes) + N_MM_NPART_AMAX per-threadgroup scales for stage-1
2666    return 8 + N_MM_NPART_AMAX*sizeof(float);
2667}
2668
2669int ggml_metal_op_mul_mat_id(ggml_metal_op_t ctx, int idx) {
2670    ggml_tensor * op = ctx->node(idx);
2671
2672    ggml_metal_library_t lib = ctx->lib;
2673    ggml_metal_encoder_t enc = ctx->enc;
2674
2675    const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ctx->dev);
2676
2677    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
2678    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
2679    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
2680    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
2681    GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
2682    GGML_TENSOR_LOCALS(uint64_t, nb2, op->src[2], nb);
2683    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
2684    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
2685
2686    // src2 = ids
2687    GGML_ASSERT(op->src[2]->type == GGML_TYPE_I32);
2688
2689    GGML_ASSERT(!ggml_is_transposed(op->src[0]));
2690    GGML_ASSERT(!ggml_is_transposed(op->src[1]));
2691
2692    GGML_ASSERT(ne03 == 1);
2693    GGML_ASSERT(ne13 == 1);
2694
2695    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
2696    ggml_metal_buffer_id bid_src1 = ggml_metal_get_buffer_id(op->src[1]);
2697    ggml_metal_buffer_id bid_src2 = ggml_metal_get_buffer_id(op->src[2]);
2698    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
2699
2700    const uint32_t r2 = 1;
2701    const uint32_t r3 = 1;
2702
2703    if (ggml_metal_op_mul_mat_id_use_mm(op, props_dev->has_simdgroup_mm)) {
2704        // some Metal matrix data types require aligned pointers
2705        // ref: https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf (Table 2.5)
2706        //switch (op->src[0]->type) {
2707        //    case GGML_TYPE_F32:  GGML_ASSERT(nb01 % 16 == 0); break;
2708        //    case GGML_TYPE_F16:  GGML_ASSERT(nb01 % 8  == 0); break;
2709        //    case GGML_TYPE_BF16: GGML_ASSERT(nb01 % 8  == 0); break;
2710        //    default: break;
2711        //}
2712
2713        // extra buffers for intermediate id mapping
2714        ggml_metal_buffer_id bid_tpe = bid_dst;
2715        bid_tpe.offs += ggml_nbytes(op);
2716
2717        ggml_metal_buffer_id bid_ids = bid_tpe;
2718        bid_ids.offs += ggml_metal_op_mul_mat_id_extra_tpe(op);
2719
2720        ggml_metal_buffer_id bid_amax = bid_ids;
2721        bid_amax.offs += ggml_metal_op_mul_mat_id_extra_ids(op);
2722
2723        // src1 rescale factors, computed before the matmul
2724        // ref: https://github.com/ggml-org/llama.cpp/pull/26223
2725        {
2726            ggml_metal_kargs_mul_mm_id_amax args = {
2727                /*.ne00 =*/ ne10,
2728                /*.ne01 =*/ ne11,
2729                /*.ne02 =*/ ne12,
2730                /*.nb01 =*/ nb11,
2731                /*.nb02 =*/ nb12,
2732            };
2733
2734            auto pipeline = ggml_metal_library_get_pipeline_mul_mm_id_amax_part(lib);
2735
2736            const size_t smem = pipeline.smem;
2737
2738            GGML_ASSERT(smem <= props_dev->max_theadgroup_memory_size);
2739
2740            ggml_metal_encoder_set_pipeline(enc, pipeline);
2741            ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2742            ggml_metal_encoder_set_buffer  (enc, bid_src1, 1);
2743            ggml_metal_encoder_set_buffer  (enc, bid_amax, 2);
2744
2745            ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
2746
2747            ggml_metal_encoder_dispatch_threadgroups(enc, N_MM_NPART_AMAX, 1, 1, 256, 1, 1);
2748        }
2749
2750        {
2751            ggml_metal_kargs_mul_mm_id_map0 args = {
2752                ne02,
2753                ne10,
2754                ne11, // n_expert_used (bcast)
2755                nb11,
2756                nb12,
2757                ne21, // n_tokens
2758                ne20, // n_expert_used
2759                nb21,
2760            };
2761
2762            auto pipeline = ggml_metal_library_get_pipeline_mul_mm_id_map0(lib, ne02, ne20);
2763
2764            const size_t smem = pipeline.smem;
2765
2766            GGML_ASSERT(ne02 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
2767
2768            GGML_ASSERT(smem <= props_dev->max_theadgroup_memory_size);
2769
2770            ggml_metal_encoder_set_pipeline(enc, pipeline);
2771            ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2772            ggml_metal_encoder_set_buffer  (enc, bid_src2, 1);
2773            ggml_metal_encoder_set_buffer  (enc, bid_tpe,  2);
2774            ggml_metal_encoder_set_buffer  (enc, bid_ids,  3);
2775
2776            ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
2777
2778            ggml_metal_encoder_dispatch_threadgroups(enc, 1, 1, 1, ne02, 1, 1);
2779        }
2780
2781        ggml_metal_op_concurrency_reset(ctx);
2782
2783        {
2784            auto pipeline = ggml_metal_library_get_pipeline_mul_mm_id_amax(lib);
2785
2786            ggml_metal_encoder_set_pipeline(enc, pipeline);
2787            ggml_metal_encoder_set_buffer  (enc, bid_amax, 0);
2788
2789            ggml_metal_encoder_dispatch_threadgroups(enc, 1, 1, 1, 32, 1, 1);
2790        }
2791
2792        // the next kernel has to wait for the amax data
2793        ggml_metal_op_concurrency_reset(ctx);
2794
2795        {
2796            auto pipeline = ggml_metal_library_get_pipeline_mul_mm_id(lib, op);
2797
2798            ggml_metal_kargs_mul_mm_id args = {
2799                /*.ne00  =*/ ne00,
2800                /*.ne02  =*/ ne02,
2801                /*.nb01  =*/ nb01,
2802                /*.nb02  =*/ nb02,
2803                /*.nb03  =*/ nb03,
2804                /*.ne11  =*/ ne11, // n_expert_used (bcast)
2805                /*.nb10  =*/ nb10,
2806                /*.nb11  =*/ nb11,
2807                /*.nb12  =*/ nb12,
2808                /*.nb13  =*/ nb13,
2809                /*.ne20  =*/ ne20, // n_expert_used
2810                /*.ne21  =*/ ne21, // n_tokens
2811                /*.ne0   =*/ ne0,
2812                /*.ne1   =*/ ne1,
2813                /*.r2    =*/ r2,
2814                /*.r3    =*/ r3,
2815            };
2816
2817            ggml_metal_encoder_set_pipeline(enc, pipeline);
2818            ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2819            ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
2820            ggml_metal_encoder_set_buffer  (enc, bid_src1, 2);
2821            ggml_metal_encoder_set_buffer  (enc, bid_tpe,  3);
2822            ggml_metal_encoder_set_buffer  (enc, bid_ids,  4);
2823            ggml_metal_encoder_set_buffer  (enc, bid_dst,  5);
2824            ggml_metal_encoder_set_buffer  (enc, bid_amax, 6);
2825
2826            const size_t smem = pipeline.smem;
2827
2828            ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
2829
2830            ggml_metal_encoder_dispatch_threadgroups(enc, (ne21 + 31)/32, (ne01 + 63)/64, ne02, 128, 1, 1);
2831        }
2832    } else {
2833        auto pipeline = ggml_metal_library_get_pipeline_mul_mv_id(lib, op);
2834
2835        const int nr0 = pipeline.nr0;
2836        const int nr1 = pipeline.nr1;
2837        const int nsg = pipeline.nsg;
2838
2839        const size_t smem = pipeline.smem;
2840
2841        ggml_metal_kargs_mul_mv_id args = {
2842            /*.nei0 =*/ ne20,
2843            /*.nei1 =*/ ne21,
2844            /*.nbi1 =*/ nb21,
2845            /*.ne00 =*/ ne00,
2846            /*.ne01 =*/ ne01,
2847            /*.ne02 =*/ ne02,
2848            /*.nb00 =*/ nb00,
2849            /*.nb01 =*/ nb01,
2850            /*.nb02 =*/ nb02,
2851            /*.ne10 =*/ ne10,
2852            /*.ne11 =*/ ne11,
2853            /*.ne12 =*/ ne12,
2854            /*.ne13 =*/ ne13,
2855            /*.nb10 =*/ nb10,
2856            /*.nb11 =*/ nb11,
2857            /*.nb12 =*/ nb12,
2858            /*.ne0  =*/ ne0,
2859            /*.ne1  =*/ ne1,
2860            /*.nb1  =*/ nb1,
2861            /*.nr0  =*/ nr0,
2862        };
2863
2864        if (ggml_is_quantized(op->src[0]->type)) {
2865            GGML_ASSERT(ne00 >= nsg*nr0);
2866        }
2867
2868        ggml_metal_encoder_set_pipeline(enc, pipeline);
2869        ggml_metal_encoder_set_bytes(enc, &args, sizeof(args), 0);
2870        ggml_metal_encoder_set_buffer(enc, bid_src0, 1);
2871        ggml_metal_encoder_set_buffer(enc, bid_src1, 2);
2872        ggml_metal_encoder_set_buffer(enc, bid_dst,  3);
2873        ggml_metal_encoder_set_buffer(enc, bid_src2, 4);
2874
2875        const int64_t _ne1 = 1;
2876        const int64_t ne123 = ne20*ne21;
2877
2878        ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
2879
2880        if (op->src[0]->type == GGML_TYPE_F32 ||
2881            op->src[0]->type == GGML_TYPE_F16 ||
2882            op->src[0]->type == GGML_TYPE_BF16 ||
2883            op->src[0]->type == GGML_TYPE_Q8_0) {
2884            ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nr0 - 1)/(nr0), (_ne1 + nr1 - 1)/nr1, ne123, 32, nsg, 1);
2885        } else {
2886            ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nr0*nsg - 1)/(nr0*nsg), (_ne1 + nr1 - 1)/nr1, ne123, 32, nsg, 1);
2887        }
2888    }
2889
2890    return 1;
2891}
2892
2893int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) {
2894    ggml_tensor * op = ctx->node(idx);
2895
2896    ggml_metal_library_t lib = ctx->lib;
2897    ggml_metal_encoder_t enc = ctx->enc;
2898
2899    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
2900    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
2901    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
2902    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
2903    GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
2904    GGML_TENSOR_LOCALS(uint64_t, nb2, op->src[2], nb);
2905    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
2906
2907    GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32);
2908    GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
2909    GGML_ASSERT(op->src[2]->type == GGML_TYPE_I32);
2910    GGML_ASSERT(op->type         == GGML_TYPE_F32);
2911
2912    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
2913
2914    ggml_metal_kargs_add_id args = {
2915        /*.ne0  =*/ ne0,
2916        /*.ne1  =*/ ne1,
2917        /*.nb01 =*/ nb01,
2918        /*.nb02 =*/ nb02,
2919        /*.nb11 =*/ nb11,
2920        /*.nb21 =*/ nb21,
2921    };
2922
2923    auto pipeline = ggml_metal_library_get_pipeline_base(lib, GGML_OP_ADD_ID);
2924
2925    ggml_metal_encoder_set_pipeline(enc, pipeline);
2926    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
2927    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
2928    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
2929    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[2]), 3);
2930    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         4);
2931
2932    const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), ne00);
2933
2934    ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, 1, nth, 1, 1);
2935
2936    return 1;
2937}
2938
2939bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) {
2940    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
2941
2942    const int64_t ne00 = op->src[0]->ne[0]; // head size
2943    const int64_t ne01 = op->src[0]->ne[1]; // batch size
2944
2945    // use vec kernel if the batch size is small and if the head size is supported
2946    return (ne01 < 20) && (ne00 % 32 == 0);
2947}
2948
2949// ref: https://github.com/ggml-org/llama.cpp/pull/27390
2950// dequantize the quantized KV cache to F16 before running the F16 flash attention kernels
2951static bool ggml_metal_op_flash_attn_ext_use_kv_f16(const ggml_tensor * op) {
2952    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
2953
2954    // depending on compute/bandwidth ratio, dequant to f16 kv is not always beneficial
2955    // ref: https://github.com/ggml-org/llama.cpp/pull/27390#issuecomment-5355152767
2956    // TODO: tune per device
2957    if (op->src[0]->ne[1] < 32) {
2958        return false;
2959    }
2960
2961    switch (op->src[1]->type) {
2962        case GGML_TYPE_Q4_0:
2963        case GGML_TYPE_Q4_1:
2964        case GGML_TYPE_Q5_0:
2965        case GGML_TYPE_Q5_1:
2966        case GGML_TYPE_Q8_0:
2967            return true;
2968        default:
2969            return false;
2970    }
2971}
2972
2973// returns the n_kv_max hint if the sparse path is available for this op, or 0 otherwise
2974// the mask (src[3]) remains the single source of truth: finite entries are the valid KV positions,
2975// n_kv_max is only an upper bound on their number per mask row, used to size the index lists
2976static int ggml_metal_op_flash_attn_ext_n_kv_max_sparse(const ggml_tensor * op) {
2977    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
2978
2979    int32_t n_kv_max = 0;
2980    memcpy(&n_kv_max, ((const int32_t *) op->op_params) + 4, sizeof(n_kv_max));
2981
2982    if (n_kv_max <= 0) {
2983        return 0;
2984    }
2985
2986    // the sparse indices are gathered from the mask
2987    if (!op->src[3]) {
2988        return 0;
2989    }
2990
2991    // bound the size of the index lists
2992    if (n_kv_max > 4096) {
2993        return 0;
2994    }
2995
2996    // vec kernel instantiations exist for these (type, dk, dv) combinations only
2997    const int64_t dk = op->src[1]->ne[0];
2998    const int64_t dv = op->src[2]->ne[0];
2999
3000    const bool dk_dv_ok = (dk == 32  && dv == 32)  ||
3001                          (dk == 64  && dv == 64)  ||
3002                          (dk == 96  && dv == 96)  ||
3003                          (dk == 96  && dv == 64)  ||
3004                          (dk == 128 && dv == 128) ||
3005                          (dk == 192 && dv == 128) ||
3006                          (dk == 192 && dv == 192) ||
3007                          (dk == 256 && dv == 256) ||
3008                          (dk == 320 && dv == 256) ||
3009                          (dk == 512 && dv == 512) ||
3010                          (dk == 576 && dv == 512);
3011
3012    if (!dk_dv_ok) {
3013        return 0;
3014    }
3015
3016    switch (op->src[1]->type) {
3017        case GGML_TYPE_F16:
3018        case GGML_TYPE_BF16:
3019        case GGML_TYPE_F32:
3020        case GGML_TYPE_Q4_0:
3021        case GGML_TYPE_Q4_1:
3022        case GGML_TYPE_Q5_0:
3023        case GGML_TYPE_Q5_1:
3024        case GGML_TYPE_Q8_0:
3025            break;
3026        default:
3027            return 0;
3028    }
3029
3030    return n_kv_max;
3031}
3032
3033// in some models (e.g. MLA-based), V is a view of K (the first ne20 elements of each K row);
3034// the dequantized V is then a view of the dequantized K and does not need its own dequant or scratch
3035// - ref: https://github.com/ggml-org/llama.cpp/pull/13435
3036static bool ggml_metal_op_flash_attn_ext_v_is_view_of_k(const ggml_tensor * op) {
3037    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
3038
3039    const ggml_tensor * K = op->src[1];
3040    const ggml_tensor * V = op->src[2];
3041
3042    return V->view_src && (V->view_src == K || (V->view_src == K->view_src && V->view_offs == K->view_offs));
3043}
3044
3045// size of the F16 dequantized K tensor; the dequantized V tensor follows it in the same scratch buffer
3046static size_t ggml_metal_op_flash_attn_ext_kv_f16_k_size(const ggml_tensor * op) {
3047    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
3048
3049    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
3050
3051    return GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne10*ne11*ne12*ne13, 16);
3052}
3053
3054size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) {
3055    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
3056
3057    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
3058    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
3059    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
3060    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
3061    GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
3062    GGML_TENSOR_LOCALS(uint64_t, nb2, op->src[2], nb);
3063    GGML_TENSOR_LOCALS( int32_t, ne3, op->src[3], ne);
3064    GGML_TENSOR_LOCALS(uint64_t, nb3, op->src[3], nb);
3065
3066    size_t res = 0;
3067
3068    const bool has_mask = op->src[3] != nullptr;
3069    const bool use_kv_f16 = ggml_metal_op_flash_attn_ext_use_kv_f16(op);
3070
3071    // when the KV is dequantized to F16, the pad kernel copies the tail chunk from the F16 scratch buffer
3072    // note: when V is a view of K, the dequantized V is read from the dequantized K with K's row stride
3073    const bool v_is_view_of_k = use_kv_f16 && ggml_metal_op_flash_attn_ext_v_is_view_of_k(op);
3074    uint64_t nb11_pad = nb11;
3075    uint64_t nb21_pad = nb21;
3076
3077    if (use_kv_f16) {
3078        nb11_pad = sizeof(ggml_fp16_t)*ne10;
3079        nb21_pad = sizeof(ggml_fp16_t)*(v_is_view_of_k ? ne10 : ne20);
3080    }
3081
3082    // note: the non-vec kernel requires more extra memory, so always reserve for it
3083    GGML_ASSERT(OP_FLASH_ATTN_EXT_NCPSG >= OP_FLASH_ATTN_EXT_VEC_NCPSG);
3084
3085    //if (ggml_metal_op_flash_attn_ext_use_vec(op)) {
3086    if (false) {
3087        // note: always reserve the padding space to avoid graph reallocations
3088        //const bool has_kvpad = ne11 % OP_FLASH_ATTN_EXT_VEC_NCPSG != 0;
3089        const bool has_kvpad = true;
3090
3091        if (has_kvpad) {
3092            res += OP_FLASH_ATTN_EXT_VEC_NCPSG*(
3093                nb11_pad*ne12*ne13 +
3094                nb21_pad*ne22*ne23 +
3095                (has_mask ? ggml_type_size(GGML_TYPE_F16)*ne31*ne32*ne33 : 0));
3096        }
3097    } else {
3098        //const bool has_kvpad = ne11 % OP_FLASH_ATTN_EXT_NCPSG != 0;
3099        const bool has_kvpad = true;
3100
3101        if (has_kvpad) {
3102            res += OP_FLASH_ATTN_EXT_NCPSG*(
3103                nb11_pad*ne12*ne13 +
3104                nb21_pad*ne22*ne23 +
3105                (has_mask ? ggml_type_size(GGML_TYPE_F16)*ne31*ne32*ne33 : 0));
3106        }
3107    }
3108
3109    return res;
3110}
3111
3112size_t ggml_metal_op_flash_attn_ext_extra_blk(const ggml_tensor * op) {
3113    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
3114
3115    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
3116  //GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
3117  //GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
3118  //GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
3119  //GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
3120  //GGML_TENSOR_LOCALS(uint64_t, nb2, op->src[2], nb);
3121    GGML_TENSOR_LOCALS( int32_t, ne3, op->src[3], ne);
3122    GGML_TENSOR_LOCALS(uint64_t, nb3, op->src[3], nb);
3123
3124    size_t res = 0;
3125
3126    const bool has_mask = op->src[3] != nullptr;
3127
3128    if (!has_mask) {
3129        return res;
3130    }
3131
3132    const bool is_vec = ggml_metal_op_flash_attn_ext_use_vec(op);
3133
3134    // this optimization is not useful for the vector kernels
3135    // note: always reserve the blk buffer to avoid graph reallocations
3136    //if (is_vec) {
3137    //    return res;
3138    //}
3139
3140    const int nqptg = is_vec ? OP_FLASH_ATTN_EXT_VEC_NQPSG : OP_FLASH_ATTN_EXT_NQPSG;
3141    const int ncpsg = is_vec ? OP_FLASH_ATTN_EXT_VEC_NCPSG : OP_FLASH_ATTN_EXT_NCPSG;
3142
3143    const int64_t ne1 = (ne01 + nqptg - 1)/nqptg;
3144    const int64_t ne0 = (ne30 + ncpsg - 1)/ncpsg;
3145
3146    res += GGML_PAD(ggml_type_size(GGML_TYPE_I8)*ne0*ne1*ne32*ne33, 32);
3147
3148    return res;
3149}
3150
3151size_t ggml_metal_op_flash_attn_ext_extra_tmp(const ggml_tensor * op) {
3152    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
3153
3154    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
3155    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
3156  //GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
3157  //GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
3158    GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
3159    GGML_TENSOR_LOCALS(uint64_t, nb2, op->src[2], nb);
3160  //GGML_TENSOR_LOCALS( int32_t, ne3, op->src[3], ne);
3161  //GGML_TENSOR_LOCALS(uint64_t, nb3, op->src[3], nb);
3162
3163    size_t res = 0;
3164
3165    // note: always reserve the temp buffer to avoid graph reallocations
3166    //if (ggml_metal_op_flash_attn_ext_use_vec(op)) {
3167    if (true) {
3168        const int64_t nwg = 32;
3169        const int64_t ne01_max = std::min(ne01, 32);
3170
3171        // temp buffer for writing the results from each workgroup
3172        // - ne20: the size of the Value head
3173        // -  + 2: the S and M values for each intermediate result
3174        res += ggml_type_size(GGML_TYPE_F32)*(ne01_max*ne02*ne03*nwg*(ne20 + 2));
3175    }
3176
3177    return res;
3178}
3179
3180size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) {
3181    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
3182
3183    // note: always reserve the temp buffer to avoid graph reallocations
3184    //if (!ggml_metal_op_flash_attn_ext_use_kv_f16(op)) {
3185    //    return 0;
3186    //}
3187
3188    GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
3189
3190    const size_t k_size = ggml_metal_op_flash_attn_ext_kv_f16_k_size(op);
3191
3192    // when V is a view of K, the dequantized V is a view of the dequantized K
3193    const bool v_is_view_of_k = ggml_metal_op_flash_attn_ext_v_is_view_of_k(op);
3194    if (v_is_view_of_k) {
3195        return k_size;
3196    }
3197
3198    const size_t v_size = GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne20*ne21*ne22*ne23, 16);
3199
3200    return k_size + v_size;
3201}
3202
3203// size of the sparse index lists: one list of KV indices per mask row,
3204// padded with -1 up to a multiple of OP_FLASH_ATTN_EXT_VEC_NCPSG
3205size_t ggml_metal_op_flash_attn_ext_extra_idx(const ggml_tensor * op) {
3206    assert(op->op == GGML_OP_FLASH_ATTN_EXT);
3207
3208    GGML_TENSOR_LOCALS( int32_t, ne3, op->src[3], ne);
3209
3210    const int n_kv_max = ggml_metal_op_flash_attn_ext_n_kv_max_sparse(op);
3211
3212    if (n_kv_max <= 0) {
3213        return 0;
3214    }
3215
3216    const int n_kv_max_padded = GGML_PAD(n_kv_max, OP_FLASH_ATTN_EXT_VEC_NCPSG);
3217
3218    return GGML_PAD(sizeof(int32_t)*(size_t) n_kv_max_padded*ne31*ne32*ne33, 16);
3219}
3220
3221int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) {
3222    ggml_tensor * op = ctx->node(idx);
3223
3224    ggml_metal_library_t lib = ctx->lib;
3225    ggml_metal_encoder_t enc = ctx->enc;
3226
3227    const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ctx->dev);
3228
3229    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
3230    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
3231    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
3232    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
3233    GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne);
3234    GGML_TENSOR_LOCALS(uint64_t, nb2, op->src[2], nb);
3235    GGML_TENSOR_LOCALS( int32_t, ne3, op->src[3], ne);
3236    GGML_TENSOR_LOCALS(uint64_t, nb3, op->src[3], nb);
3237    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
3238    GGML_TENSOR_LOCALS( int32_t, nb,  op,         nb);
3239
3240    GGML_ASSERT(ne00 % 4 == 0);
3241
3242    GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32);
3243    GGML_ASSERT(op->src[1]->type == op->src[2]->type);
3244
3245    //GGML_ASSERT(ggml_are_same_shape (src1, src2));
3246    GGML_ASSERT(ne11 == ne21);
3247    GGML_ASSERT(ne12 == ne22);
3248
3249    GGML_ASSERT(!op->src[3] || op->src[3]->type == GGML_TYPE_F16);
3250    GGML_ASSERT(!op->src[3] || op->src[3]->ne[1] >= op->src[0]->ne[1] &&
3251            "the Flash-Attention Metal kernel requires the mask to be at least n_queries big");
3252
3253    float scale;
3254    float max_bias;
3255    float logit_softcap;
3256
3257    memcpy(&scale,         ((const int32_t *) op->op_params) + 0, sizeof(scale));
3258    memcpy(&max_bias,      ((const int32_t *) op->op_params) + 1, sizeof(max_bias));
3259    memcpy(&logit_softcap, ((const int32_t *) op->op_params) + 2, sizeof(logit_softcap));
3260
3261    if (logit_softcap != 0.0f) {
3262        scale /= logit_softcap;
3263    }
3264
3265    const bool has_mask  = op->src[3] != NULL;
3266    const bool has_sinks = op->src[4] != NULL;
3267    const bool has_bias  = max_bias != 0.0f;
3268    const bool has_scap  = logit_softcap != 0.0f;
3269
3270    const uint32_t n_head      = op->src[0]->ne[2];
3271    const  int32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head));
3272
3273    const float m0 = powf(2.0f, -(max_bias       ) / n_head_log2);
3274    const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
3275
3276    GGML_ASSERT(ne01 < 65536);
3277
3278    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
3279    ggml_metal_buffer_id bid_src1 = ggml_metal_get_buffer_id(op->src[1]);
3280    ggml_metal_buffer_id bid_src2 = ggml_metal_get_buffer_id(op->src[2]);
3281    ggml_metal_buffer_id bid_src3 = has_mask  ? ggml_metal_get_buffer_id(op->src[3]) : bid_src0;
3282    ggml_metal_buffer_id bid_src4 = has_sinks ? ggml_metal_get_buffer_id(op->src[4]) : bid_src0;
3283
3284    ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id(op);
3285
3286    ggml_metal_buffer_id bid_pad = bid_dst;
3287    bid_pad.offs += ggml_nbytes(op);
3288
3289    ggml_metal_buffer_id bid_blk = bid_pad;
3290    bid_blk.offs += ggml_metal_op_flash_attn_ext_extra_pad(op);
3291
3292    ggml_metal_buffer_id bid_tmp = bid_blk;
3293    bid_tmp.offs += ggml_metal_op_flash_attn_ext_extra_blk(op);
3294
3295    ggml_metal_buffer_id bid_kv_f16 = bid_tmp;
3296    bid_kv_f16.offs += ggml_metal_op_flash_attn_ext_extra_tmp(op);
3297
3298    // sparse path: gather the finite mask entries into index lists and run the vec kernels over them
3299    const int n_kv_max_sparse = ggml_metal_op_flash_attn_ext_n_kv_max_sparse(op);
3300    const bool use_sparse = n_kv_max_sparse > 0;
3301    const int n_kv_max_padded = use_sparse ? GGML_PAD(n_kv_max_sparse, OP_FLASH_ATTN_EXT_VEC_NCPSG) : 0;
3302
3303    // the vec kernels dequantize the KV inline; no need for the F16 dequant pass in the sparse path
3304    const bool use_kv_f16 = !use_sparse && ggml_metal_op_flash_attn_ext_use_kv_f16(op);
3305
3306    ggml_metal_buffer_id bid_idx = bid_kv_f16;
3307    bid_idx.offs += ggml_metal_op_flash_attn_ext_extra_kv_f16(op);
3308
3309    ggml_metal_buffer_id bid_k = bid_src1;
3310    ggml_metal_buffer_id bid_v = bid_src2;
3311
3312    uint64_t nb10_attn = nb10;
3313    uint64_t nb11_attn = nb11;
3314    uint64_t nb12_attn = nb12;
3315    uint64_t nb13_attn = nb13;
3316    uint64_t nb20_attn = nb20;
3317    uint64_t nb21_attn = nb21;
3318    uint64_t nb22_attn = nb22;
3319    uint64_t nb23_attn = nb23;
3320
3321    if (use_kv_f16) {
3322        assert(ggml_metal_op_flash_attn_ext_extra_kv_f16(op) != 0);
3323
3324        const bool v_is_view_of_k = ggml_metal_op_flash_attn_ext_v_is_view_of_k(op);
3325
3326        const int64_t nblocks1_64 = (ne10/ggml_blck_size(op->src[1]->type))*(int64_t) ne11*ne12*ne13;
3327        GGML_ASSERT(nblocks1_64 <= INT32_MAX);
3328        const int32_t nblocks1 = nblocks1_64;
3329
3330        ggml_metal_buffer_id bid_v_f16 = bid_kv_f16;
3331        bid_v_f16.offs += ggml_metal_op_flash_attn_ext_kv_f16_k_size(op);
3332
3333        auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_kv_f16(lib, op);
3334        const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline0), 256);
3335
3336        // K
3337        ggml_metal_kargs_flash_attn_ext_kv_f16 args_k = {
3338            /*.ne0    =*/ ne10,
3339            /*.ne1    =*/ ne11,
3340            /*.ne2    =*/ ne12,
3341            /*.ne3    =*/ ne13,
3342            /*.nb0    =*/ nb10,
3343            /*.nb1    =*/ nb11,
3344            /*.nb2    =*/ nb12,
3345            /*.nb3    =*/ nb13,
3346            /*.nblocks =*/ nblocks1,
3347        };
3348
3349        ggml_metal_encoder_set_pipeline(enc, pipeline0);
3350        ggml_metal_encoder_set_bytes   (enc, &args_k, sizeof(args_k), 0);
3351        ggml_metal_encoder_set_buffer  (enc, bid_src1,        1);
3352        ggml_metal_encoder_set_buffer  (enc, bid_kv_f16, 2);
3353
3354        ggml_metal_encoder_dispatch_threadgroups(enc, (nblocks1 + nth - 1)/nth, 1, 1, nth, 1, 1);
3355
3356        // V (skip when V is a view of K: the dequantized V is a view of the dequantized K)
3357        if (!v_is_view_of_k) {
3358            const int64_t nblocks2_64 = (ne20/ggml_blck_size(op->src[2]->type))*(int64_t) ne21*ne22*ne23;
3359            GGML_ASSERT(nblocks2_64 <= INT32_MAX);
3360            const int32_t nblocks2 = nblocks2_64;
3361
3362            ggml_metal_kargs_flash_attn_ext_kv_f16 args_v = {
3363                /*.ne0    =*/ ne20,
3364                /*.ne1    =*/ ne21,
3365                /*.ne2    =*/ ne22,
3366                /*.ne3    =*/ ne23,
3367                /*.nb0    =*/ nb20,
3368                /*.nb1    =*/ nb21,
3369                /*.nb2    =*/ nb22,
3370                /*.nb3    =*/ nb23,
3371                /*.nblocks =*/ nblocks2,
3372            };
3373
3374            ggml_metal_encoder_set_pipeline(enc, pipeline0);
3375            ggml_metal_encoder_set_bytes   (enc, &args_v, sizeof(args_v), 0);
3376            ggml_metal_encoder_set_buffer  (enc, bid_src2,        1);
3377            ggml_metal_encoder_set_buffer  (enc, bid_v_f16,       2);
3378
3379            ggml_metal_encoder_dispatch_threadgroups(enc, (nblocks2 + nth - 1)/nth, 1, 1, nth, 1, 1);
3380        }
3381
3382        // the pad and attention kernels read the dequantized KV
3383        ggml_metal_op_concurrency_reset(ctx);
3384
3385        bid_k = bid_kv_f16;
3386        bid_v = v_is_view_of_k ? bid_k : bid_v_f16;
3387
3388        // contiguous F16 layout of the dequantized K
3389        nb10_attn = sizeof(ggml_fp16_t);
3390        nb11_attn = nb10_attn*ne10;
3391        nb12_attn = nb11_attn*ne11;
3392        nb13_attn = nb12_attn*ne12;
3393
3394        // if V is a view of K, the dequantized V is read from the dequantized K with K's strides
3395        if (v_is_view_of_k) {
3396            nb20_attn = nb10_attn;
3397            nb21_attn = nb11_attn;
3398            nb22_attn = nb12_attn;
3399            nb23_attn = nb13_attn;
3400        } else {
3401            // contiguous F16 layout of the dequantized V
3402            nb20_attn = sizeof(ggml_fp16_t);
3403            nb21_attn = nb20_attn*ne20;
3404            nb22_attn = nb21_attn*ne21;
3405            nb23_attn = nb22_attn*ne22;
3406        }
3407    }
3408
3409    if (!use_sparse && !ggml_metal_op_flash_attn_ext_use_vec(op)) {
3410        // half8x8 kernel
3411        const int nqptg = OP_FLASH_ATTN_EXT_NQPSG; // queries per threadgroup
3412        const int ncpsg = OP_FLASH_ATTN_EXT_NCPSG; // cache values per simdgroup
3413
3414        GGML_ASSERT(nqptg <= 32);
3415        GGML_ASSERT(nqptg  % 8  == 0);
3416        GGML_ASSERT(ncpsg  % 32 == 0);
3417
3418        bool need_sync = false;
3419
3420        const bool has_kvpad = ne11 % ncpsg != 0;
3421
3422        if (has_kvpad) {
3423            assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0);
3424
3425            ggml_metal_kargs_flash_attn_ext_pad args0 = {
3426                /*.ne11    =*/ne11,
3427                /*.ne_12_2 =*/ne12,
3428                /*.ne_12_3 =*/ne13,
3429                /*.nb11    =*/nb11_attn,
3430                /*.nb12    =*/nb12_attn,
3431                /*.nb13    =*/nb13_attn,
3432                /*.nb21    =*/nb21_attn,
3433                /*.nb22    =*/nb22_attn,
3434                /*.nb23    =*/nb23_attn,
3435                /*.ne31    =*/ne31,
3436                /*.ne32    =*/ne32,
3437                /*.ne33    =*/ne33,
3438                /*.nb31    =*/nb31,
3439                /*.nb32    =*/nb32,
3440                /*.nb33    =*/nb33,
3441            };
3442
3443            auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, ncpsg);
3444
3445            ggml_metal_encoder_set_pipeline(enc, pipeline0);
3446            ggml_metal_encoder_set_bytes   (enc, &args0, sizeof(args0), 0);
3447            ggml_metal_encoder_set_buffer  (enc, bid_k,    1);
3448            ggml_metal_encoder_set_buffer  (enc, bid_v,    2);
3449            ggml_metal_encoder_set_buffer  (enc, bid_src3, 3);
3450            ggml_metal_encoder_set_buffer  (enc, bid_pad,  4);
3451
3452            assert(ne12 == ne22);
3453            assert(ne13 == ne23);
3454
3455            ggml_metal_encoder_dispatch_threadgroups(enc, ncpsg, std::max(ne12, ne32), std::max(ne13, ne33), 32, 1, 1);
3456
3457            need_sync = true;
3458        }
3459
3460        if (has_mask) {
3461            assert(ggml_metal_op_flash_attn_ext_extra_blk(op) != 0);
3462
3463            ggml_metal_kargs_flash_attn_ext_blk args0 = {
3464                /*.ne01 =*/ ne01,
3465                /*.ne30 =*/ ne30,
3466                /*.ne31 =*/ ne31,
3467                /*.ne32 =*/ ne32,
3468                /*.ne33 =*/ ne33,
3469                /*.nb31 =*/ nb31,
3470                /*.nb32 =*/ nb32,
3471                /*.nb33 =*/ nb33,
3472            };
3473
3474            auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_blk(lib, op, nqptg, ncpsg);
3475
3476            ggml_metal_encoder_set_pipeline(enc, pipeline0);
3477            ggml_metal_encoder_set_bytes   (enc, &args0, sizeof(args0), 0);
3478            ggml_metal_encoder_set_buffer  (enc, bid_src3, 1);
3479            ggml_metal_encoder_set_buffer  (enc, bid_blk,  2);
3480
3481            const int32_t nblk1 = ((ne01 + nqptg - 1)/nqptg);
3482            const int32_t nblk0 = ((ne30 + ncpsg - 1)/ncpsg);
3483
3484            ggml_metal_encoder_dispatch_threadgroups(enc, nblk0, nblk1, ne32*ne33, 32, 1, 1);
3485
3486            need_sync = true;
3487        }
3488
3489        if (need_sync) {
3490            ggml_metal_op_concurrency_reset(ctx);
3491        }
3492
3493        const int is_q = !use_kv_f16 && ggml_is_quantized(op->src[1]->type) ? 1 : 0;
3494
3495        // 2*(2*ncpsg)
3496        // ncpsg soft_max values + ncpsg mask values
3497        //
3498        // 16*32*(nsg)
3499        // the shared memory needed for the simdgroups to load the KV cache
3500        // each thread loads (dequantizes) 16 head elements, there are 32 threads in th SG
3501        //
3502#define FATTN_SMEM(nsg) (GGML_PAD((nqptg*(ne00 + 2*GGML_PAD(ne20, 64) + 2*(2*ncpsg)) + is_q*(16*32*(nsg)))*(sizeof(float)/2), 16))
3503
3504        //int64_t nsgmax = 4;
3505        //
3506        //if (is_q) {
3507        //    nsgmax = 2;
3508        //    while (true) {
3509        //        const size_t smem = FATTN_SMEM(nsgmax);
3510        //        if (smem > props_dev->max_theadgroup_memory_size) {
3511        //            break;
3512        //        }
3513        //        nsgmax *= 2;
3514        //    }
3515        //    nsgmax /= 2;
3516        //}
3517
3518        // simdgroups per threadgroup (a.k.a. warps)
3519        //nsg = ne01 <= nqptg ? MAX(4, MIN(nsgmax, MIN(ne11/ncpsg, (int64_t) pipeline.maxTotalThreadsPerThreadgroup/32))) : 4;
3520        int32_t nsg = ne00 >= 512 ? 8 : 4;
3521
3522        const size_t smem = FATTN_SMEM(nsg);
3523
3524        const int32_t ns10 = nb11_attn/nb10_attn;
3525        const int32_t ns20 = nb21_attn/nb20_attn;
3526
3527        ggml_metal_kargs_flash_attn_ext args = {
3528            /*.ne01          =*/ ne01,
3529            /*.ne02          =*/ ne02,
3530            /*.ne03          =*/ ne03,
3531            /*.nb01          =*/ nb01,
3532            /*.nb02          =*/ nb02,
3533            /*.nb03          =*/ nb03,
3534            /*.ne11          =*/ ne11,
3535            /*.ne_12_2       =*/ ne12,
3536            /*.ne_12_3       =*/ ne13,
3537            /*.ns10          =*/ ns10,
3538            /*.nb11          =*/ nb11_attn,
3539            /*.nb12          =*/ nb12_attn,
3540            /*.nb13          =*/ nb13_attn,
3541            /*.ns20          =*/ ns20,
3542            /*.nb21          =*/ nb21_attn,
3543            /*.nb22          =*/ nb22_attn,
3544            /*.nb23          =*/ nb23_attn,
3545            /*.ne31          =*/ ne31,
3546            /*.ne32          =*/ ne32,
3547            /*.ne33          =*/ ne33,
3548            /*.nb31          =*/ nb31,
3549            /*.nb32          =*/ nb32,
3550            /*.nb33          =*/ nb33,
3551            /*.ne1           =*/ ne1,
3552            /*.ne2           =*/ ne2,
3553            /*.ne3           =*/ ne3,
3554            /*.scale         =*/ scale,
3555            /*.max_bias      =*/ max_bias,
3556            /*.m0            =*/ m0,
3557            /*.m1            =*/ m1,
3558            /*.n_head_log2   =*/ n_head_log2,
3559            /*.logit_softcap =*/ logit_softcap,
3560        };
3561
3562        auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, nsg, use_kv_f16, ns10, ns20);
3563
3564        ggml_metal_encoder_set_pipeline(enc, pipeline);
3565        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
3566        ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
3567        ggml_metal_encoder_set_buffer  (enc, bid_k,    2);
3568        ggml_metal_encoder_set_buffer  (enc, bid_v,    3);
3569        ggml_metal_encoder_set_buffer  (enc, bid_src3, 4);
3570        ggml_metal_encoder_set_buffer  (enc, bid_src4, 5);
3571        ggml_metal_encoder_set_buffer  (enc, bid_pad,  6);
3572        ggml_metal_encoder_set_buffer  (enc, bid_blk,  7);
3573        ggml_metal_encoder_set_buffer  (enc, bid_dst,  8);
3574
3575        ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
3576
3577        ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nqptg - 1)/nqptg, ne02, ne03, 32, nsg, 1);
3578#undef FATTN_SMEM
3579    } else {
3580        // half4x4 kernel
3581        // sparse: the index lists are per query row, so a threadgroup can share KV with Q == 1 only
3582        auto cfg = use_sparse
3583                ? ggml_metal_tuning::fa_vec_baseline_cfg((int) ne00, (int) ne20)
3584                : ggml_metal_tuning::fa_vec_pick(
3585                          props_dev->device_id,
3586                          props_dev->gpu_family,
3587                          (int) op->src[1]->type,
3588                          (int) ne00, (int) ne20,   // dk, dv (ne00 == dk for FA)
3589                          ne11, ne01);
3590
3591        int nqptg = cfg.Q; // queries per threadgroup
3592
3593        const int ncpsg = OP_FLASH_ATTN_EXT_VEC_NCPSG; // cache values per simdgroup !! sync with kernel template arguments !!
3594        const int nhptg = 1;                           // heads per threadgroup
3595
3596        GGML_ASSERT(nqptg <= 32);
3597        GGML_ASSERT(nqptg == 1 || nqptg == 2 || nqptg == 4);  // only instantiated Q values
3598        GGML_ASSERT(ncpsg  % 32 == 0);
3599
3600        bool need_sync = false;
3601
3602        const bool has_kvpad = !use_sparse && ne11 % ncpsg != 0;
3603
3604        if (use_sparse) {
3605            assert(ggml_metal_op_flash_attn_ext_extra_idx(op) != 0);
3606
3607            GGML_ASSERT(ne30 == ne11);
3608
3609            ggml_metal_kargs_flash_attn_ext_vec_idx args0 = {
3610                /*.ne30              =*/ ne30,
3611                /*.ne31              =*/ ne31,
3612                /*.ne32              =*/ ne32,
3613                /*.ne33              =*/ ne33,
3614                /*.nb31              =*/ nb31,
3615                /*.nb32              =*/ nb32,
3616                /*.nb33              =*/ nb33,
3617                /*.n_kv_max          =*/ n_kv_max_sparse,
3618                /*.n_kv_max_padded   =*/ n_kv_max_padded,
3619            };
3620
3621            auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_vec_idx(lib, op);
3622
3623            ggml_metal_encoder_set_pipeline(enc, pipeline0);
3624            ggml_metal_encoder_set_bytes   (enc, &args0, sizeof(args0), 0);
3625            ggml_metal_encoder_set_buffer  (enc, bid_src3, 1);
3626            ggml_metal_encoder_set_buffer  (enc, bid_idx,  2);
3627
3628            int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline0), 256);
3629            nth = std::max(32, (nth/32)*32);
3630
3631            ggml_metal_encoder_dispatch_threadgroups(enc, ne31, ne32, ne33, nth, 1, 1);
3632
3633            need_sync = true;
3634        }
3635
3636        if (has_kvpad) {
3637            assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0);
3638
3639            ggml_metal_kargs_flash_attn_ext_pad args0 = {
3640                /*.ne11    =*/ne11,
3641                /*.ne_12_2 =*/ne12,
3642                /*.ne_12_3 =*/ne13,
3643                /*.nb11    =*/nb11_attn,
3644                /*.nb12    =*/nb12_attn,
3645                /*.nb13    =*/nb13_attn,
3646                /*.nb21    =*/nb21_attn,
3647                /*.nb22    =*/nb22_attn,
3648                /*.nb23    =*/nb23_attn,
3649                /*.ne31    =*/ne31,
3650                /*.ne32    =*/ne32,
3651                /*.ne33    =*/ne33,
3652                /*.nb31    =*/nb31,
3653                /*.nb32    =*/nb32,
3654                /*.nb33    =*/nb33,
3655            };
3656
3657            auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, ncpsg);
3658
3659            ggml_metal_encoder_set_pipeline(enc, pipeline0);
3660            ggml_metal_encoder_set_bytes   (enc, &args0, sizeof(args0), 0);
3661            ggml_metal_encoder_set_buffer  (enc, bid_k,    1);
3662            ggml_metal_encoder_set_buffer  (enc, bid_v,    2);
3663            ggml_metal_encoder_set_buffer  (enc, bid_src3, 3);
3664            ggml_metal_encoder_set_buffer  (enc, bid_pad,  4);
3665
3666            assert(ne12 == ne22);
3667            assert(ne13 == ne23);
3668
3669            ggml_metal_encoder_dispatch_threadgroups(enc, ncpsg, std::max(ne12, ne32), std::max(ne13, ne33), 32, 1, 1);
3670
3671            need_sync = true;
3672        }
3673
3674        if (need_sync) {
3675            ggml_metal_op_concurrency_reset(ctx);
3676        }
3677
3678        // note: for simplicity assume the K is larger or equal than V
3679        GGML_ASSERT(ne10 >= ne20);
3680
3681        // ne00 + 2*ncpsg*(nsg)
3682        // for each query, we load it as f16 in shared memory (ne00)
3683        // and store the soft_max values and the mask
3684        //
3685        // ne20*(nsg)
3686        // each simdgroup has a full f32 head vector in shared mem to accumulate results
3687        //
3688#define FATTN_SMEM(nsg) (GGML_PAD(((GGML_PAD(ne00, 128) + 4*ncpsg + 2*GGML_PAD(ne20, 128))*(nsg)*nqptg)*(sizeof(float)/2), 16))
3689
3690        int64_t nsg = 1;
3691
3692        // workgroups
3693        // each workgroup handles nsg*nkpsg cache values
3694        int32_t nwg = 1;
3695        if (use_sparse) {
3696            if (ne01 > 32) {
3697                // large sparse batch
3698                nwg = 1;
3699                nsg = 1;
3700                if (n_kv_max_padded == 640) {
3701                    nsg = 4; // 640 % (4*32) == 0
3702                } else {
3703                    while (2*nwg*nsg*ncpsg < n_kv_max_padded && nsg < 4) {
3704                        nsg *= 2;
3705                    }
3706                }
3707            } else {
3708                // small sparse batch
3709                nwg = 32;
3710                nsg = 1;
3711                while (2*nwg*nsg*ncpsg < n_kv_max_padded && nsg < 4) {
3712                    nsg *= 2;
3713                }
3714            }
3715        } else {
3716            nwg = 32;
3717            nsg = 1;
3718            while (2*nwg*nsg*ncpsg < ne11 && nsg < 4) {
3719                nsg *= 2;
3720            }
3721        }
3722
3723        // fall back to baseline (Q=1) if the tuned config exceeds threadgroup memory
3724        if ((size_t) FATTN_SMEM(nsg) > props_dev->max_theadgroup_memory_size) {
3725            cfg   = ggml_metal_tuning::fa_vec_baseline_cfg((int) ne00, (int) ne20);
3726            nqptg = cfg.Q;  // = 1
3727        }
3728
3729        const int32_t ns10 = nb11_attn/nb10_attn;
3730        const int32_t ns20 = nb21_attn/nb20_attn;
3731
3732        ggml_metal_kargs_flash_attn_ext_vec args = {
3733            /*.ne01          =*/ ne01,
3734            /*.ne02          =*/ ne02,
3735            /*.ne03          =*/ ne03,
3736            /*.nb01          =*/ nb01,
3737            /*.nb02          =*/ nb02,
3738            /*.nb03          =*/ nb03,
3739            /*.ne11          =*/ use_sparse ? n_kv_max_padded : ne11,
3740            /*.ne_12_2       =*/ ne12,
3741            /*.ne_12_3       =*/ ne13,
3742            /*.ns10          =*/ ns10,
3743            /*.nb11          =*/ nb11_attn,
3744            /*.nb12          =*/ nb12_attn,
3745            /*.nb13          =*/ nb13_attn,
3746            /*.ns20          =*/ ns20,
3747            /*.nb21          =*/ nb21_attn,
3748            /*.nb22          =*/ nb22_attn,
3749            /*.nb23          =*/ nb23_attn,
3750            /*.ne31          =*/ ne31,
3751            /*.ne32          =*/ ne32,
3752            /*.ne33          =*/ ne33,
3753            /*.nb31          =*/ nb31,
3754            /*.nb32          =*/ nb32,
3755            /*.nb33          =*/ nb33,
3756            /*.ne1           =*/ ne1,
3757            /*.ne2           =*/ ne2,
3758            /*.ne3           =*/ ne3,
3759            /*.scale         =*/ scale,
3760            /*.max_bias      =*/ max_bias,
3761            /*.m0            =*/ m0,
3762            /*.m1            =*/ m1,
3763            /*.n_head_log2   =*/ n_head_log2,
3764            /*.logit_softcap =*/ logit_softcap,
3765            /*.n_kv_max_padded =*/ n_kv_max_padded,
3766        };
3767
3768        auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20);
3769
3770        GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
3771
3772        ggml_metal_encoder_set_pipeline(enc, pipeline);
3773        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
3774        ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
3775        ggml_metal_encoder_set_buffer  (enc, bid_k,    2);
3776        ggml_metal_encoder_set_buffer  (enc, bid_v,    3);
3777        ggml_metal_encoder_set_buffer  (enc, bid_src3, 4);
3778        ggml_metal_encoder_set_buffer  (enc, bid_src4, 5);
3779        ggml_metal_encoder_set_buffer  (enc, use_sparse ? bid_idx : bid_src0, 8);
3780
3781        const size_t smem = FATTN_SMEM(nsg);
3782
3783        //printf("smem: %zu, max: %zu, nsg = %d, nsgmax = %d\n", smem, props_dev->max_theadgroup_memory_size, (int) nsg, (int) nsgmax);
3784        GGML_ASSERT(smem <= props_dev->max_theadgroup_memory_size);
3785
3786        if (nwg == 1) {
3787            // using 1 workgroup -> write the result directly into dst
3788            ggml_metal_encoder_set_buffer(enc, bid_pad, 6);
3789            ggml_metal_encoder_set_buffer(enc, bid_dst, 7);
3790
3791            ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
3792
3793            ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nqptg - 1)/nqptg, (ne02 + nhptg - 1)/nhptg, ne03*nwg, 32, nsg, 1);
3794        } else {
3795            // sanity checks
3796            assert(ggml_metal_op_flash_attn_ext_extra_tmp(op) != 0);
3797
3798            GGML_ASSERT(ne01*ne02*ne03 == ne1*ne2*ne3);
3799            GGML_ASSERT((uint64_t)ne1*ne2*ne3 <= (1u << 31));
3800
3801            // write the results from each workgroup into a temp buffer
3802            ggml_metal_encoder_set_buffer(enc, bid_pad, 6);
3803            ggml_metal_encoder_set_buffer(enc, bid_tmp, 7);
3804
3805            ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
3806            ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nqptg - 1)/nqptg, (ne02 + nhptg - 1)/nhptg, ne03*nwg, 32, nsg, 1);
3807
3808            // sync the 2 kernels
3809            ggml_metal_op_concurrency_reset(ctx);
3810
3811            // reduce the results from the workgroups
3812            {
3813                const int32_t nrows = ne1*ne2*ne3;
3814
3815                ggml_metal_kargs_flash_attn_ext_vec_reduce args0 = {
3816                    nrows,
3817                };
3818
3819                auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_vec_reduce(lib, op, ne20, nwg);
3820
3821                ggml_metal_encoder_set_pipeline(enc, pipeline0);
3822                ggml_metal_encoder_set_bytes   (enc, &args0, sizeof(args0), 0);
3823                ggml_metal_encoder_set_buffer  (enc, bid_tmp, 1);
3824                ggml_metal_encoder_set_buffer  (enc, bid_dst, 2);
3825
3826                ggml_metal_encoder_dispatch_threadgroups(enc, nrows, 1, 1, 32*nwg, 1, 1);
3827            }
3828        }
3829#undef FATTN_SMEM
3830    }
3831
3832    return 1;
3833}
3834
3835int ggml_metal_op_bin(ggml_metal_op_t ctx, int idx) {
3836    int n_fuse = 1;
3837    const ggml_metal_fusion * fusion = nullptr;
3838
3839    if (ctx->use_fusion()) {
3840        int n = 1;
3841        fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n);
3842        n_fuse = n;
3843
3844        // snake activation autofuse: mul -> sin -> sqr -> mul -> add
3845        if (fusion && ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_SNAKE) {
3846            ctx->count_fusions(fusion);
3847            return ggml_metal_op_snake_fused(ctx, idx);
3848        }
3849
3850        // MoE output reduction: experts * weights -> weighted sum
3851        if (fusion && ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_MOE_REDUCE) {
3852            ctx->count_fusions(fusion);
3853            return ggml_metal_op_moe_reduce(ctx, idx);
3854        }
3855    }
3856
3857    ggml_tensor * op = ctx->node(idx);
3858
3859    ggml_metal_library_t lib = ctx->lib;
3860    ggml_metal_encoder_t enc = ctx->enc;
3861
3862    const bool use_fusion = ctx->use_fusion();
3863
3864    const int debug_fusion = ggml_metal_fusion_info_debug(ctx->finfo);
3865
3866    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
3867    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
3868    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
3869    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
3870    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
3871    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
3872
3873    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
3874    GGML_ASSERT(ggml_is_contiguous_rows(op->src[1]));
3875
3876    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
3877    ggml_metal_buffer_id bid_src1 = ggml_metal_get_buffer_id(op->src[1]);
3878    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
3879
3880    ggml_metal_kargs_bin args = {
3881        /*.ne00 =*/ ne00,
3882        /*.ne01 =*/ ne01,
3883        /*.ne02 =*/ ne02,
3884        /*.ne03 =*/ ne03,
3885        /*.nb00 =*/ nb00,
3886        /*.nb01 =*/ nb01,
3887        /*.nb02 =*/ nb02,
3888        /*.nb03 =*/ nb03,
3889        /*.ne10 =*/ ne10,
3890        /*.ne11 =*/ ne11,
3891        /*.ne12 =*/ ne12,
3892        /*.ne13 =*/ ne13,
3893        /*.nb10 =*/ nb10,
3894        /*.nb11 =*/ nb11,
3895        /*.nb12 =*/ nb12,
3896        /*.nb13 =*/ nb13,
3897        /*.ne0  =*/ ne0,
3898        /*.ne1  =*/ ne1,
3899        /*.ne2  =*/ ne2,
3900        /*.ne3  =*/ ne3,
3901        /*.nb0  =*/ nb0,
3902        /*.nb1  =*/ nb1,
3903        /*.nb2  =*/ nb2,
3904        /*.nb3  =*/ nb3,
3905        /*.offs =*/ 0,
3906        /*.o1   =*/ { bid_src1.offs },
3907    };
3908
3909    // c[0] = add(a,    b[0])
3910    // c[1] = add(c[0], b[1])
3911    // c[2] = add(c[1], b[2])
3912    // ...
3913    if (use_fusion && fusion && ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_ADD_CHAIN) {
3914        // the offsets of the fused addends are relative to the start of the src1 buffer
3915        for (int i = 1; i < n_fuse; i++) {
3916            args.o1[i] = ggml_metal_get_buffer_id(ctx->node(idx + i)->src[1]).offs;
3917        }
3918
3919        ctx->count_fusions(fusion);
3920
3921        if (debug_fusion > 1) {
3922            GGML_LOG_DEBUG("%s: fuse: ADD x %d\n", __func__, n_fuse);
3923        }
3924    }
3925
3926    // the offsets of src1 and all fused buffers are relative to the start of the src1 buffer
3927    bid_src1.offs = 0;
3928
3929    struct ggml_metal_pipeline_with_params pipeline;
3930
3931    pipeline = ggml_metal_library_get_pipeline_bin(lib, op, n_fuse);
3932
3933    if (n_fuse > 1) {
3934        bid_dst = ggml_metal_get_buffer_id(ctx->node(idx + n_fuse - 1));
3935
3936        for (int i = 1; i < n_fuse; ++i) {
3937            if (!ggml_metal_op_concurrency_check(ctx, ctx->node(idx + i))) {
3938                ggml_metal_op_concurrency_reset(ctx);
3939
3940                break;
3941            }
3942        }
3943    }
3944
3945    if (pipeline.c4) {
3946        args.ne00 = ne00/4;
3947        args.ne10 = ne10/4;
3948        args.ne0  = ne0/4;
3949    }
3950
3951    ggml_metal_encoder_set_pipeline(enc, pipeline);
3952    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
3953    ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
3954    ggml_metal_encoder_set_buffer  (enc, bid_src1, 2);
3955    ggml_metal_encoder_set_buffer  (enc, bid_dst,  3);
3956
3957    if (pipeline.cnt) {
3958        ggml_metal_encoder_dispatch_threadgroups(enc, args.ne0, ggml_nrows(op), 1, 1, 1, 1);
3959    } else {
3960        const int nth_max = MIN(256, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
3961
3962        int nth = 1;
3963
3964        while (2*nth < args.ne0 && nth < nth_max) {
3965            nth *= 2;
3966        }
3967
3968        ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
3969    }
3970
3971    return n_fuse;
3972}
3973
3974int ggml_metal_op_silu_back(ggml_metal_op_t ctx, int idx) {
3975    ggml_tensor * op = ctx->node(idx);
3976
3977    ggml_metal_library_t lib = ctx->lib;
3978    ggml_metal_encoder_t enc = ctx->enc;
3979
3980    auto pipeline = ggml_metal_library_get_pipeline_silu_back(lib, op);
3981
3982    const int64_t ne = ggml_nelements(op);
3983
3984    ggml_metal_kargs_silu_back args = {
3985        /*.ne =*/ ne,
3986    };
3987
3988    int arg_idx{0};
3989
3990    ggml_metal_encoder_set_pipeline(enc, pipeline);
3991    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), arg_idx++);
3992    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), arg_idx++);
3993    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), arg_idx++);
3994    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op), arg_idx++);
3995
3996    const int nth = std::min<int64_t>(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), ne);
3997    const int64_t n = (ne + nth - 1) / nth;
3998
3999    ggml_metal_encoder_dispatch_threadgroups(enc, n, 1, 1, nth, 1, 1);
4000
4001    return 1;
4002}
4003
4004int ggml_metal_op_l2_norm(ggml_metal_op_t ctx, int idx) {
4005    ggml_tensor * op = ctx->node(idx);
4006
4007    ggml_metal_library_t lib = ctx->lib;
4008    ggml_metal_encoder_t enc = ctx->enc;
4009
4010    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4011    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4012    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4013    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4014
4015    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
4016
4017    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
4018    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
4019
4020    float eps;
4021    memcpy(&eps, op->op_params, sizeof(float));
4022
4023    ggml_metal_kargs_l2_norm args = {
4024        /*.ne00  =*/ ne00,
4025        /*.ne01  =*/ ne01,
4026        /*.ne02  =*/ ne02,
4027        /*.ne03  =*/ ne03,
4028        /*.nb00  =*/ nb00,
4029        /*.nb01  =*/ nb01,
4030        /*.nb02  =*/ nb02,
4031        /*.nb03  =*/ nb03,
4032        /*.ne0   =*/ ne0,
4033        /*.ne1   =*/ ne1,
4034        /*.ne2   =*/ ne2,
4035        /*.ne3   =*/ ne3,
4036        /*.nb0   =*/ nb0,
4037        /*.nb1   =*/ nb1,
4038        /*.nb2   =*/ nb2,
4039        /*.nb3   =*/ nb3,
4040        /*.eps   =*/ eps,
4041    };
4042
4043    auto pipeline = ggml_metal_library_get_pipeline_l2_norm(lib, op);
4044
4045    if (pipeline.c4) {
4046        args.ne00 = ne00/4;
4047        args.ne0  = ne0/4;
4048    }
4049
4050    int nth = 32; // SIMD width
4051
4052    while (nth < ne00 && nth < ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
4053        nth *= 2;
4054    }
4055
4056    nth = std::min(nth, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
4057
4058    const size_t smem = pipeline.smem;
4059
4060    ggml_metal_encoder_set_pipeline(enc, pipeline);
4061    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4062    ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
4063    ggml_metal_encoder_set_buffer  (enc, bid_dst,  2);
4064
4065    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
4066
4067    ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
4068
4069    return 1;
4070}
4071
4072int ggml_metal_op_group_norm(ggml_metal_op_t ctx, int idx) {
4073    ggml_tensor * op = ctx->node(idx);
4074
4075    ggml_metal_library_t lib = ctx->lib;
4076    ggml_metal_encoder_t enc = ctx->enc;
4077
4078    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4079    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4080    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4081    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4082
4083    const int32_t ngrp = ((const int32_t *) op->op_params)[0];
4084
4085    float eps;
4086    memcpy(&eps, op->op_params + 1, sizeof(float));
4087
4088    ggml_metal_kargs_group_norm args = {
4089        /*.ne00 =*/ ne00,
4090        /*.ne01 =*/ ne01,
4091        /*.ne02 =*/ ne02,
4092        /*.nb00 =*/ nb00,
4093        /*.nb01 =*/ nb01,
4094        /*.nb02 =*/ nb02,
4095        /*.ngrp =*/ ngrp,
4096        /*.eps  =*/ eps,
4097    };
4098
4099    auto pipeline = ggml_metal_library_get_pipeline_group_norm(lib, op);
4100
4101    int nth = 32; // SIMD width
4102    //while (nth < ne00/4 && nth < ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
4103    //    nth *= 2;
4104    //}
4105
4106    //nth = std::min(nth, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
4107    //nth = std::min(nth, ne00/4);
4108
4109    const size_t smem = pipeline.smem;
4110
4111    ggml_metal_encoder_set_pipeline(enc, pipeline);
4112    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4113    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4114    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
4115
4116    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
4117
4118    ggml_metal_encoder_dispatch_threadgroups(enc, ngrp, 1, 1, nth, 1, 1);
4119
4120    return 1;
4121}
4122
4123int ggml_metal_op_norm(ggml_metal_op_t ctx, int idx) {
4124    ggml_tensor * op = ctx->node(idx);
4125
4126    ggml_metal_library_t lib = ctx->lib;
4127    ggml_metal_encoder_t enc = ctx->enc;
4128
4129    const bool use_fusion = ctx->use_fusion();
4130
4131    const int debug_fusion = ggml_metal_fusion_info_debug(ctx->finfo);
4132
4133    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4134    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4135    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4136    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4137
4138    float eps;
4139    memcpy(&eps, op->op_params, sizeof(float));
4140
4141    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
4142    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
4143
4144    ggml_metal_kargs_norm args = {
4145        /*.ne00   =*/ ne00,
4146        /*.ne00_t =*/ ne00 % 4 == 0 ? ne00/4 : ne00,
4147        /*.nb1    =*/ nb1,
4148        /*.nb2    =*/ nb2,
4149        /*.nb3    =*/ nb3,
4150        /*.eps    =*/ eps,
4151        /*.nef1   =*/ { ne01 },
4152        /*.nef2   =*/ { ne02 },
4153        /*.nef3   =*/ { ne03 },
4154        /*.nbf1   =*/ { nb01 },
4155        /*.nbf2   =*/ { nb02 },
4156        /*.nbf3   =*/ { nb03 },
4157        /*.scale =*/ 1.0f,
4158    };
4159
4160    int n_fuse = 1;
4161    bool fused_norm_scale = false;
4162
4163    ggml_metal_buffer_id bid_fuse[2] = { bid_src0, bid_src0 };
4164
4165    // d[0] = norm(a)
4166    // d[1] = mul(d[0], b) or scale(d[0])
4167    // d[2] = add(d[1], c)
4168    if (use_fusion) {
4169        int n = 1;
4170        const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n);
4171
4172        if (fusion && (ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_NORM_MUL || ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_NORM_MUL_ADD)) {
4173            n_fuse = n;
4174
4175            ctx->count_fusions(fusion);
4176
4177            for (int i = 1; i < n_fuse; i++) {
4178                const ggml_tensor * fn = ctx->node(idx + i);
4179
4180                bid_fuse[i - 1] = ggml_metal_get_buffer_id(fn->src[1]);
4181
4182                args.nef1[i] = fn->src[1]->ne[1];
4183                args.nef2[i] = fn->src[1]->ne[2];
4184                args.nef3[i] = fn->src[1]->ne[3];
4185
4186                args.nbf1[i] = fn->src[1]->nb[1];
4187                args.nbf2[i] = fn->src[1]->nb[2];
4188                args.nbf3[i] = fn->src[1]->nb[3];
4189            }
4190
4191            if (debug_fusion > 1) {
4192                if (n_fuse == 2) {
4193                    GGML_LOG_DEBUG("%s: fuse: %s + MUL\n", __func__, ggml_op_name(op->op));
4194                }
4195                if (n_fuse == 3) {
4196                    GGML_LOG_DEBUG("%s: fuse: %s + MUL + ADD\n", __func__, ggml_op_name(op->op));
4197                }
4198            }
4199        }
4200
4201        if (fusion && ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_NORM_SCALE) {
4202            n_fuse = n;
4203            fused_norm_scale = true;
4204
4205            ctx->count_fusions(fusion);
4206
4207            const ggml_tensor * scale_node = ctx->node(idx + 1);
4208            args.scale = ggml_get_op_params_f32(scale_node, 0);
4209
4210            if (debug_fusion > 1) {
4211                GGML_LOG_DEBUG("%s: fuse: %s + SCALE\n", __func__, ggml_op_name(op->op));
4212            }
4213        }
4214    }
4215
4216    if (n_fuse > 1) {
4217        bid_dst = ggml_metal_get_buffer_id(ctx->node(idx + n_fuse - 1));
4218
4219        for (int i = 1; i < n_fuse; ++i) {
4220            if (!ggml_metal_op_concurrency_check(ctx, ctx->node(idx + i))) {
4221                ggml_metal_op_concurrency_reset(ctx);
4222
4223                break;
4224            }
4225        }
4226    }
4227
4228    auto pipeline = fused_norm_scale ?
4229        ggml_metal_library_get_pipeline_norm_scale(lib, op) :
4230        ggml_metal_library_get_pipeline_norm(lib, op, n_fuse);
4231
4232    int nth = 32; // SIMD width
4233
4234    while (nth < args.ne00_t && nth < ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
4235        nth *= 2;
4236    }
4237
4238    nth = std::min(nth, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
4239    nth = std::min(nth, (args.ne00_t + 31)/32*32);
4240
4241    const size_t smem = pipeline.smem;
4242
4243    ggml_metal_encoder_set_pipeline(enc, pipeline);
4244    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4245    ggml_metal_encoder_set_buffer  (enc, bid_src0,    1);
4246    ggml_metal_encoder_set_buffer  (enc, bid_fuse[0], 2);
4247    ggml_metal_encoder_set_buffer  (enc, bid_fuse[1], 3);
4248    ggml_metal_encoder_set_buffer  (enc, bid_dst,     4);
4249
4250    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
4251
4252    ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
4253
4254    return n_fuse;
4255}
4256
4257int ggml_metal_op_rope(ggml_metal_op_t ctx, int idx) {
4258    ggml_tensor * op = ctx->node(idx);
4259
4260    ggml_metal_library_t lib = ctx->lib;
4261    ggml_metal_encoder_t enc = ctx->enc;
4262
4263    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4264    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4265    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
4266    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
4267    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4268    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4269
4270    // make sure we have one or more position id(ne10) per token(ne02)
4271    GGML_ASSERT(ne10 % ne02 == 0);
4272    GGML_ASSERT(ne10 >= ne02);
4273
4274    const int nth = std::min(1024, ne00);
4275
4276    const int n_past     = ((const int32_t *) op->op_params)[0];
4277    const int n_dims     = ((const int32_t *) op->op_params)[1];
4278  //const int mode       = ((const int32_t *) op->op_params)[2];
4279    // skip 3, n_ctx, used in GLM RoPE, unimplemented in metal
4280    const int n_ctx_orig = ((const int32_t *) op->op_params)[4];
4281
4282    float freq_base;
4283    float freq_scale;
4284    float ext_factor;
4285    float attn_factor;
4286    float beta_fast;
4287    float beta_slow;
4288
4289    memcpy(&freq_base,   (const int32_t *) op->op_params +  5, sizeof(float));
4290    memcpy(&freq_scale,  (const int32_t *) op->op_params +  6, sizeof(float));
4291    memcpy(&ext_factor,  (const int32_t *) op->op_params +  7, sizeof(float));
4292    memcpy(&attn_factor, (const int32_t *) op->op_params +  8, sizeof(float));
4293    memcpy(&beta_fast,   (const int32_t *) op->op_params +  9, sizeof(float));
4294    memcpy(&beta_slow,   (const int32_t *) op->op_params + 10, sizeof(float));
4295
4296    // mrope
4297    const int sect_0 = ((const int32_t *) op->op_params)[11];
4298    const int sect_1 = ((const int32_t *) op->op_params)[12];
4299    const int sect_2 = ((const int32_t *) op->op_params)[13];
4300    const int sect_3 = ((const int32_t *) op->op_params)[14];
4301
4302    const int n_offs = ((const int32_t *) op->op_params)[15];
4303
4304    // when dst aliases src0, the channels outside the rotated window already hold the correct data
4305    const bool inplace = op->data == op->src[0]->data;
4306
4307    ggml_metal_kargs_rope args = {
4308        /*.ne00        =*/ ne00,
4309        /*.ne01        =*/ ne01,
4310        /*.ne02        =*/ ne02,
4311        /*.ne03        =*/ ne03,
4312        /*.nb00        =*/ nb00,
4313        /*.nb01        =*/ nb01,
4314        /*.nb02        =*/ nb02,
4315        /*.nb03        =*/ nb03,
4316        /*.ne0         =*/ ne0,
4317        /*.ne1         =*/ ne1,
4318        /*.ne2         =*/ ne2,
4319        /*.ne3         =*/ ne3,
4320        /*.nb0         =*/ nb0,
4321        /*.nb1         =*/ nb1,
4322        /*.nb2         =*/ nb2,
4323        /*.nb3         =*/ nb3,
4324        /*.n_past      =*/ n_past,
4325        /*.n_dims      =*/ n_dims,
4326        /*.n_offs      =*/ n_offs,
4327        /*.n_ctx_orig  =*/ n_ctx_orig,
4328        /*.freq_base   =*/ freq_base,
4329        /*.freq_scale  =*/ freq_scale,
4330        /*.ext_factor  =*/ ext_factor,
4331        /*.attn_factor =*/ attn_factor,
4332        /*.beta_fast   =*/ beta_fast,
4333        /*.beta_slow   =*/ beta_slow,
4334        /* sect_0      =*/ sect_0,
4335        /* sect_1      =*/ sect_1,
4336        /* sect_2      =*/ sect_2,
4337        /* sect_3      =*/ sect_3,
4338        /* src2        =*/ op->src[2] != nullptr,
4339        /* inplace     =*/ inplace,
4340    };
4341
4342    auto pipeline = ggml_metal_library_get_pipeline_rope(lib, op);
4343
4344    ggml_metal_encoder_set_pipeline(enc, pipeline);
4345    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4346    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4347    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
4348    if (op->src[2]) {
4349        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[2]), 3);
4350    } else {
4351        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 3);
4352    }
4353    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         4);
4354
4355    ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
4356
4357    return 1;
4358}
4359
4360int ggml_metal_op_im2col(ggml_metal_op_t ctx, int idx) {
4361    ggml_tensor * op = ctx->node(idx);
4362
4363    ggml_metal_library_t lib = ctx->lib;
4364    ggml_metal_encoder_t enc = ctx->enc;
4365
4366    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4367    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4368    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4369    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4370
4371    const int32_t s0 = ((const int32_t *)(op->op_params))[0];
4372    const int32_t s1 = ((const int32_t *)(op->op_params))[1];
4373    const int32_t p0 = ((const int32_t *)(op->op_params))[2];
4374    const int32_t p1 = ((const int32_t *)(op->op_params))[3];
4375    const int32_t d0 = ((const int32_t *)(op->op_params))[4];
4376    const int32_t d1 = ((const int32_t *)(op->op_params))[5];
4377
4378    const bool is_2D = ((const int32_t *)(op->op_params))[6] == 1;
4379
4380    const int32_t N  = op->src[1]->ne[is_2D ? 3 : 2];
4381    const int32_t IC = op->src[1]->ne[is_2D ? 2 : 1];
4382    const int32_t IH = is_2D ? op->src[1]->ne[1] : 1;
4383    const int32_t IW =         op->src[1]->ne[0];
4384
4385    const int32_t KH = is_2D ? op->src[0]->ne[1] : 1;
4386    const int32_t KW =         op->src[0]->ne[0];
4387
4388    const int32_t OH = is_2D ? op->ne[2] : 1;
4389    const int32_t OW =         op->ne[1];
4390
4391    const int32_t CHW = IC * KH * KW;
4392
4393    const uint64_t ofs0 = op->src[1]->nb[is_2D ? 3 : 2] / 4;
4394    const uint64_t ofs1 = op->src[1]->nb[is_2D ? 2 : 1] / 4;
4395
4396    ggml_metal_kargs_im2col args = {
4397        /*.ofs0 =*/ ofs0,
4398        /*.ofs1 =*/ ofs1,
4399        /*.IW   =*/ IW,
4400        /*.IH   =*/ IH,
4401        /*.CHW  =*/ CHW,
4402        /*.s0   =*/ s0,
4403        /*.s1   =*/ s1,
4404        /*.p0   =*/ p0,
4405        /*.p1   =*/ p1,
4406        /*.d0   =*/ d0,
4407        /*.d1   =*/ d1,
4408        /*.N    =*/ N,
4409        /*.KH   =*/ KH,
4410        /*.KW   =*/ KW,
4411        /*.KHW  =*/ KH * KW,
4412    };
4413
4414    auto pipeline = ggml_metal_library_get_pipeline_im2col(lib, op);
4415
4416    if (KH*KW <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
4417        const uint64_t ntptg0 = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)/(KH*KW), N);
4418
4419        ggml_metal_encoder_set_pipeline(enc, pipeline);
4420        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4421        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 1);
4422        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
4423
4424        ggml_metal_encoder_dispatch_threadgroups(enc, IC, OH, OW, ntptg0, KH, KW);
4425    } else {
4426        const uint64_t n_threads = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), N);
4427        const int64_t  quotient  = N / n_threads + (N % n_threads > 0 ? 1 : 0);
4428
4429        ggml_metal_encoder_set_pipeline(enc, pipeline);
4430        ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4431        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 1);
4432        ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
4433
4434        ggml_metal_encoder_dispatch_threadgroups(enc, quotient * CHW, OH, OW, n_threads, 1, 1);
4435    }
4436
4437    return 1;
4438}
4439
4440int ggml_metal_op_conv_2d(ggml_metal_op_t ctx, int idx) {
4441    ggml_tensor * op = ctx->node(idx);
4442
4443    ggml_metal_library_t lib = ctx->lib;
4444    ggml_metal_encoder_t enc = ctx->enc;
4445
4446    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4447    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4448    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
4449    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
4450    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4451    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4452
4453    GGML_ASSERT(ggml_is_contiguous(op->src[0]));
4454    GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
4455    GGML_ASSERT(op->type == GGML_TYPE_F32);
4456    GGML_ASSERT(op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32);
4457
4458    const int32_t s0 = ((const int32_t *) op->op_params)[0];
4459    const int32_t s1 = ((const int32_t *) op->op_params)[1];
4460    const int32_t p0 = ((const int32_t *) op->op_params)[2];
4461    const int32_t p1 = ((const int32_t *) op->op_params)[3];
4462    const int32_t d0 = ((const int32_t *) op->op_params)[4];
4463    const int32_t d1 = ((const int32_t *) op->op_params)[5];
4464
4465    ggml_metal_kargs_conv_2d args = {
4466        /*.nb00 =*/ nb00,
4467        /*.nb01 =*/ nb01,
4468        /*.nb02 =*/ nb02,
4469        /*.nb03 =*/ nb03,
4470        /*.nb10 =*/ nb10,
4471        /*.nb11 =*/ nb11,
4472        /*.nb12 =*/ nb12,
4473        /*.nb13 =*/ nb13,
4474        /*.nb0  =*/ nb0,
4475        /*.nb1  =*/ nb1,
4476        /*.nb2  =*/ nb2,
4477        /*.nb3  =*/ nb3,
4478        /*.IW   =*/ ne10,
4479        /*.IH   =*/ ne11,
4480        /*.KW   =*/ ne00,
4481        /*.KH   =*/ ne01,
4482        /*.IC   =*/ ne02,
4483        /*.OC   =*/ ne03,
4484        /*.OW   =*/ ne0,
4485        /*.OH   =*/ ne1,
4486        /*.N    =*/ ne3,
4487        /*.s0   =*/ s0,
4488        /*.s1   =*/ s1,
4489        /*.p0   =*/ p0,
4490        /*.p1   =*/ p1,
4491        /*.d0   =*/ d0,
4492        /*.d1   =*/ d1,
4493    };
4494
4495    auto pipeline = ggml_metal_library_get_pipeline_conv_2d(lib, op);
4496
4497    int nth = ggml_metal_pipeline_max_theads_per_threadgroup(pipeline);
4498    nth = std::min(nth, 256);
4499    nth = std::max(nth, 1);
4500
4501    const uint64_t n_out = ggml_nelements(op);
4502
4503    uint64_t tg = (n_out + nth - 1)/nth;
4504    tg = std::max<uint64_t>(tg, 1);
4505    tg = std::min<uint64_t>(tg, (uint64_t) std::numeric_limits<int>::max());
4506
4507    ggml_metal_encoder_set_pipeline(enc, pipeline);
4508    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4509    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4510    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
4511    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
4512
4513    ggml_metal_encoder_dispatch_threadgroups(enc, tg, 1, 1, nth, 1, 1);
4514
4515    return 1;
4516}
4517
4518int ggml_metal_op_conv_2d_dw(ggml_metal_op_t ctx, int idx) {
4519    ggml_tensor * op = ctx->node(idx);
4520
4521    ggml_metal_library_t lib = ctx->lib;
4522    ggml_metal_encoder_t enc = ctx->enc;
4523
4524    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4525    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4526    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
4527    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
4528    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4529    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4530
4531    GGML_ASSERT(op->src[1]->type == GGML_TYPE_F32);
4532    GGML_ASSERT(op->type == GGML_TYPE_F32);
4533    GGML_ASSERT(op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32);
4534
4535    const int32_t s0 = ((const int32_t *) op->op_params)[0];
4536    const int32_t s1 = ((const int32_t *) op->op_params)[1];
4537    const int32_t p0 = ((const int32_t *) op->op_params)[2];
4538    const int32_t p1 = ((const int32_t *) op->op_params)[3];
4539    const int32_t d0 = ((const int32_t *) op->op_params)[4];
4540    const int32_t d1 = ((const int32_t *) op->op_params)[5];
4541
4542    ggml_metal_kargs_conv_2d_dw args = {
4543        /*.nb00 =*/ nb00,
4544        /*.nb01 =*/ nb01,
4545        /*.nb02 =*/ nb03,
4546        /*.nb10 =*/ nb10,
4547        /*.nb11 =*/ nb11,
4548        /*.nb12 =*/ nb12,
4549        /*.nb13 =*/ nb13,
4550        /*.nb0  =*/ nb0,
4551        /*.nb1  =*/ nb1,
4552        /*.nb2  =*/ nb2,
4553        /*.nb3  =*/ nb3,
4554        /*.IW   =*/ ne10,
4555        /*.IH   =*/ ne11,
4556        /*.KW   =*/ ne00,
4557        /*.KH   =*/ ne01,
4558        /*.C    =*/ ne12,
4559        /*.OW   =*/ ne0,
4560        /*.OH   =*/ ne1,
4561        /*.N    =*/ ne13,
4562        /*.s0   =*/ s0,
4563        /*.s1   =*/ s1,
4564        /*.p0   =*/ p0,
4565        /*.p1   =*/ p1,
4566        /*.d0   =*/ d0,
4567        /*.d1   =*/ d1,
4568    };
4569
4570    const bool use_tiled = (nb12 < nb10);
4571
4572    auto pipeline = ggml_metal_library_get_pipeline_conv_2d_dw(lib, op, use_tiled);
4573
4574    int nth = ggml_metal_pipeline_max_theads_per_threadgroup(pipeline);
4575    nth = std::min(nth, 256);
4576    nth = std::max(nth, 1);
4577
4578    const int32_t OW = ne0;
4579    const int32_t OH = ne1;
4580    const int32_t C  = ne12;
4581    const int32_t N  = ne13;
4582
4583    const int tg_x = use_tiled ? (C + nth - 1) / nth : (OW + nth - 1) / nth;
4584    const int tg_y = OH;
4585    const int tg_z = use_tiled ? OW * N : C * N;
4586
4587    ggml_metal_encoder_set_pipeline(enc, pipeline);
4588    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4589    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4590    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
4591    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
4592
4593    ggml_metal_encoder_dispatch_threadgroups(enc, tg_x, tg_y, tg_z, nth, 1, 1);
4594
4595    return 1;
4596}
4597
4598int ggml_metal_op_conv_3d(ggml_metal_op_t ctx, int idx) {
4599    ggml_tensor * op = ctx->node(idx);
4600
4601    ggml_metal_library_t lib = ctx->lib;
4602    ggml_metal_encoder_t enc = ctx->enc;
4603
4604    // 1. Extract standard dimensions and byte strides
4605    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4606    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
4607    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4608
4609    // 2. Extract hyperparams from op_params
4610    const int32_t s0 = ((const int32_t *)(op->op_params))[0];
4611    const int32_t s1 = ((const int32_t *)(op->op_params))[1];
4612    const int32_t s2 = ((const int32_t *)(op->op_params))[2];
4613    const int32_t p0 = ((const int32_t *)(op->op_params))[3];
4614    const int32_t p1 = ((const int32_t *)(op->op_params))[4];
4615    const int32_t p2 = ((const int32_t *)(op->op_params))[5];
4616    const int32_t d0 = ((const int32_t *)(op->op_params))[6];
4617    const int32_t d1 = ((const int32_t *)(op->op_params))[7];
4618    const int32_t d2 = ((const int32_t *)(op->op_params))[8];
4619    const int32_t IC = ((const int32_t *)(op->op_params))[9];
4620    const int32_t N  = ((const int32_t *)(op->op_params))[10];
4621    const int32_t OC = ((const int32_t *)(op->op_params))[11];
4622
4623    // 3. Build the parameter struct using the macro-generated variables
4624    ggml_metal_kargs_conv_3d args = {
4625        /*.IW =*/ (int32_t)op->src[1]->ne[0],
4626        /*.IH =*/ (int32_t)op->src[1]->ne[1],
4627        /*.ID =*/ (int32_t)op->src[1]->ne[2],
4628        /*.OW =*/ (int32_t)op->ne[0],
4629        /*.OH =*/ (int32_t)op->ne[1],
4630        /*.OD =*/ (int32_t)op->ne[2],
4631        /*.KW =*/ (int32_t)op->src[0]->ne[0],
4632        /*.KH =*/ (int32_t)op->src[0]->ne[1],
4633        /*.KD =*/ (int32_t)op->src[0]->ne[2],
4634        s0, s1, s2,
4635        p0, p1, p2,
4636        d0, d1, d2,
4637        IC, N, OC,
4638        nb00, nb01, nb02, nb03, // Weight strides
4639        nb10, nb11, nb12, nb13, // Input strides
4640        nb0,  nb1,  nb2,  nb3   // Output strides
4641    };
4642
4643    // 4. Fetch the JIT pipeline
4644    auto pipeline = ggml_metal_library_get_pipeline_conv_3d(lib, op);
4645
4646    // 5. Grid mapping
4647    int nth0 = 32; // Standard SIMD width for Apple Silicon
4648    int nth1 = 1;
4649    int nth2 = 1;
4650
4651    int64_t spatial_volume = args.OW * args.OH * args.OD;
4652
4653    int ntg0 = (spatial_volume + nth0 - 1) / nth0;
4654    int ntg1 = args.OC;
4655    int ntg2 = args.N;
4656
4657    // 6. Bind and Dispatch via the ggml C wrapper
4658    ggml_metal_encoder_set_pipeline(enc, pipeline);
4659    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4660    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4661    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
4662    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
4663
4664    ggml_metal_encoder_dispatch_threadgroups(enc, ntg0, ntg1, ntg2, nth0, nth1, nth2);
4665
4666    return 1;
4667}
4668
4669int ggml_metal_op_conv_transpose_1d(ggml_metal_op_t ctx, int idx) {
4670    ggml_tensor * op = ctx->node(idx);
4671
4672    ggml_metal_library_t lib = ctx->lib;
4673    ggml_metal_encoder_t enc = ctx->enc;
4674
4675    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4676    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4677    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
4678    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
4679    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4680    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4681
4682    const int32_t s0 = ((const int32_t *)(op->op_params))[0];
4683
4684    const int32_t IC = op->src[1]->ne[1];
4685    const int32_t IL = op->src[1]->ne[0];
4686
4687    const int32_t K  = op->src[0]->ne[0];
4688
4689    const int32_t OL = op->ne[0];
4690    const int32_t OC = op->ne[1];
4691
4692    ggml_metal_kargs_conv_transpose_1d args = {
4693        /*.IC  =*/ IC,
4694        /*.IL  =*/ IL,
4695        /*.K   =*/ K,
4696        /*.s0  =*/ s0,
4697        /*.nb0 =*/ nb0,
4698        /*.nb1 =*/ nb1,
4699    };
4700
4701    auto pipeline = ggml_metal_library_get_pipeline_conv_transpose_1d(lib, op);
4702
4703    ggml_metal_encoder_set_pipeline(enc, pipeline);
4704    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4705    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4706    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
4707    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
4708
4709    ggml_metal_encoder_dispatch_threadgroups(enc, OL, OC, 1, 1, 1, 1);
4710
4711    return 1;
4712}
4713
4714int ggml_metal_op_col2im_1d(ggml_metal_op_t ctx, int idx) {
4715    ggml_tensor * op = ctx->node(idx);
4716
4717    ggml_metal_library_t lib = ctx->lib;
4718    ggml_metal_encoder_t enc = ctx->enc;
4719
4720    const int32_t s0 = ((const int32_t *)(op->op_params))[0];
4721    const int32_t OC = ((const int32_t *)(op->op_params))[1];
4722    const int32_t p0 = ((const int32_t *)(op->op_params))[2];
4723
4724    const int32_t K_OC  = (int32_t) op->src[0]->ne[0];
4725    const int32_t T_in  = (int32_t) op->src[0]->ne[1];
4726    const int32_t K     = K_OC / OC;
4727    const int32_t T_out = (int32_t) op->ne[0];
4728
4729    ggml_metal_kargs_col2im_1d args = {
4730        /*.T_in  =*/ T_in,
4731        /*.T_out =*/ T_out,
4732        /*.OC    =*/ OC,
4733        /*.K     =*/ K,
4734        /*.K_OC  =*/ K_OC,
4735        /*.s0    =*/ s0,
4736        /*.p0    =*/ p0,
4737    };
4738
4739    auto pipeline = ggml_metal_library_get_pipeline_col2im_1d(lib, op);
4740
4741    const int total = T_out * OC;
4742    const int nth   = 256;
4743    const int ntg   = (total + nth - 1) / nth;
4744
4745    ggml_metal_encoder_set_pipeline(enc, pipeline);
4746    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4747    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4748    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
4749
4750    ggml_metal_encoder_dispatch_threadgroups(enc, ntg, 1, 1, nth, 1, 1);
4751
4752    return 1;
4753}
4754
4755// Dispatch the fused snake kernel from the matched mul -> sin -> sqr -> mul -> add chain.
4756// idx points at the leading mul. The caller has validated the chain.
4757int ggml_metal_op_snake_fused(ggml_metal_op_t ctx, int idx) {
4758    ggml_metal_library_t lib = ctx->lib;
4759    ggml_metal_encoder_t enc = ctx->enc;
4760
4761    const ggml_tensor * mul0 = ctx->node(idx + 0);
4762    const ggml_tensor * sqr  = ctx->node(idx + 2);
4763    const ggml_tensor * mul1 = ctx->node(idx + 3);
4764    ggml_tensor *       add  = ctx->node(idx + 4);
4765
4766    const ggml_tensor * x = ggml_are_same_shape(mul0, mul0->src[0]) ? mul0->src[0] : mul0->src[1];
4767    const ggml_tensor * a = (x == mul0->src[0]) ? mul0->src[1] : mul0->src[0];
4768    const ggml_tensor * inv_b = (mul1->src[0] == sqr) ? mul1->src[1] : mul1->src[0];
4769
4770    const int T     = (int) x->ne[0];
4771    const int C     = (int) x->ne[1];
4772    const int total = T * C;
4773
4774    // the encode loop pre-checked the leading mul only, check the rest of the chain
4775    for (int i = 1; i < 5; ++i) {
4776        if (!ggml_metal_op_concurrency_check(ctx, ctx->node(idx + i))) {
4777            ggml_metal_op_concurrency_reset(ctx);
4778
4779            break;
4780        }
4781    }
4782
4783    auto pipeline = ggml_metal_library_get_pipeline_snake(lib, x->type);
4784
4785    ggml_metal_kargs_snake args = {
4786        /*.T =*/ T,
4787        /*.C =*/ C,
4788    };
4789
4790    ggml_metal_encoder_set_pipeline(enc, pipeline);
4791    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4792    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(x),     1);
4793    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(a),     2);
4794    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(inv_b), 3);
4795    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(add),   4);
4796
4797    const int nth = 256;
4798    const int ntg = (total + nth - 1) / nth;
4799    ggml_metal_encoder_dispatch_threadgroups(enc, ntg, 1, 1, nth, 1, 1);
4800
4801    return 5;
4802}
4803
4804int ggml_metal_op_conv_transpose_2d(ggml_metal_op_t ctx, int idx) {
4805    ggml_tensor * op = ctx->node(idx);
4806
4807    ggml_metal_library_t lib = ctx->lib;
4808    ggml_metal_encoder_t enc = ctx->enc;
4809
4810    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4811    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4812    GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne);
4813    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
4814    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4815    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4816
4817    const int32_t s0 = ((const int32_t *)(op->op_params))[0];
4818
4819    const int32_t IC = op->src[1]->ne[2];
4820    const int32_t IH = op->src[1]->ne[1];
4821    const int32_t IW = op->src[1]->ne[0];
4822
4823    const int32_t KH = op->src[0]->ne[1];
4824    const int32_t KW = op->src[0]->ne[0];
4825
4826    const int32_t OW = op->ne[0];
4827    const int32_t OH = op->ne[1];
4828    const int32_t OC = op->ne[2];
4829    const int32_t N  = op->src[1]->ne[3];
4830
4831    ggml_metal_kargs_conv_transpose_2d args = {
4832        /*.IC  =*/ IC,
4833        /*.IH  =*/ IH,
4834        /*.IW  =*/ IW,
4835        /*.KH  =*/ KH,
4836        /*.KW  =*/ KW,
4837        /*.OC  =*/ OC,
4838        /*.s0  =*/ s0,
4839        /*.nb0 =*/ nb0,
4840        /*.nb1 =*/ nb1,
4841        /*.nb2 =*/ nb2,
4842        /*.nb3 =*/ nb3,
4843    };
4844
4845    auto pipeline = ggml_metal_library_get_pipeline_conv_transpose_2d(lib, op);
4846
4847    ggml_metal_encoder_set_pipeline(enc, pipeline);
4848    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4849    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4850    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), 2);
4851    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         3);
4852
4853    // Metal requires buffer size to be multiple of 16 bytes
4854    const size_t smem = GGML_PAD(KW * KH * sizeof(float), 16);
4855    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
4856
4857    ggml_metal_encoder_dispatch_threadgroups(enc, OW, OH, OC * N, KW, KH, 1);
4858
4859    return 1;
4860}
4861
4862int ggml_metal_op_upscale(ggml_metal_op_t ctx, int idx) {
4863    ggml_tensor * op = ctx->node(idx);
4864
4865    ggml_metal_library_t lib = ctx->lib;
4866    ggml_metal_encoder_t enc = ctx->enc;
4867
4868    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4869    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4870    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4871    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4872
4873    float sf0 = (float)ne0/op->src[0]->ne[0];
4874    float sf1 = (float)ne1/op->src[0]->ne[1];
4875    float sf2 = (float)ne2/op->src[0]->ne[2];
4876    float sf3 = (float)ne3/op->src[0]->ne[3];
4877
4878    const int32_t mode_flags = ggml_get_op_params_i32(op, 0);
4879
4880    float poffs = 0.5f;
4881
4882    if (mode_flags & GGML_SCALE_FLAG_ALIGN_CORNERS) {
4883        poffs = 0.0f;
4884        sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
4885        sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
4886    }
4887
4888    ggml_metal_kargs_upscale args = {
4889        /*.ne00  =*/ ne00,
4890        /*.ne01  =*/ ne01,
4891        /*.ne02  =*/ ne02,
4892        /*.ne03  =*/ ne03,
4893        /*.nb00  =*/ nb00,
4894        /*.nb01  =*/ nb01,
4895        /*.nb02  =*/ nb02,
4896        /*.nb03  =*/ nb03,
4897        /*.ne0   =*/ ne0,
4898        /*.ne1   =*/ ne1,
4899        /*.ne2   =*/ ne2,
4900        /*.ne3   =*/ ne3,
4901        /*.nb0   =*/ nb0,
4902        /*.nb1   =*/ nb1,
4903        /*.nb2   =*/ nb2,
4904        /*.nb3   =*/ nb3,
4905        /*.sf0   =*/ sf0,
4906        /*.sf1   =*/ sf1,
4907        /*.sf2   =*/ sf2,
4908        /*.sf3   =*/ sf3,
4909        /*.poffs =*/ poffs,
4910    };
4911
4912    auto pipeline = ggml_metal_library_get_pipeline_upscale(lib, op);
4913
4914    const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), ne0);
4915
4916    ggml_metal_encoder_set_pipeline(enc, pipeline);
4917    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4918    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4919    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
4920
4921    ggml_metal_encoder_dispatch_threadgroups(enc, ne1, ne2, ne3, nth, 1, 1);
4922
4923    return 1;
4924}
4925
4926int ggml_metal_op_roll(ggml_metal_op_t ctx, int idx) {
4927    ggml_tensor * op = ctx->node(idx);
4928
4929    ggml_metal_library_t lib = ctx->lib;
4930    ggml_metal_encoder_t enc = ctx->enc;
4931
4932    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4933    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4934    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4935    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4936
4937    const int32_t s0 = ggml_get_op_params_i32(op, 0);
4938    const int32_t s1 = ggml_get_op_params_i32(op, 1);
4939    const int32_t s2 = ggml_get_op_params_i32(op, 2);
4940    const int32_t s3 = ggml_get_op_params_i32(op, 3);
4941
4942    ggml_metal_kargs_roll args = {
4943        /*.ne00 =*/ ne00,
4944        /*.ne01 =*/ ne01,
4945        /*.ne02 =*/ ne02,
4946        /*.ne03 =*/ ne03,
4947        /*.nb00 =*/ nb00,
4948        /*.nb01 =*/ nb01,
4949        /*.nb02 =*/ nb02,
4950        /*.nb03 =*/ nb03,
4951        /*.ne0  =*/ ne0,
4952        /*.ne1  =*/ ne1,
4953        /*.ne2  =*/ ne2,
4954        /*.ne3  =*/ ne3,
4955        /*.nb0  =*/ nb0,
4956        /*.nb1  =*/ nb1,
4957        /*.nb2  =*/ nb2,
4958        /*.nb3  =*/ nb3,
4959        /*.s0   =*/ s0,
4960        /*.s1   =*/ s1,
4961        /*.s2   =*/ s2,
4962        /*.s3   =*/ s3
4963    };
4964
4965    auto pipeline = ggml_metal_library_get_pipeline_roll(lib, op);
4966
4967    const int nth = std::min(1024, ne0);
4968
4969    ggml_metal_encoder_set_pipeline(enc, pipeline);
4970    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
4971    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
4972    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
4973
4974    ggml_metal_encoder_dispatch_threadgroups(enc, ne1, ne2, ne3, nth, 1, 1);
4975
4976    return 1;
4977}
4978
4979int ggml_metal_op_pad(ggml_metal_op_t ctx, int idx) {
4980    ggml_tensor * op = ctx->node(idx);
4981
4982    ggml_metal_library_t lib = ctx->lib;
4983    ggml_metal_encoder_t enc = ctx->enc;
4984
4985    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
4986    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
4987    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
4988    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
4989
4990    ggml_metal_kargs_pad args = {
4991        /*.ne00 =*/ ne00,
4992        /*.ne01 =*/ ne01,
4993        /*.ne02 =*/ ne02,
4994        /*.ne03 =*/ ne03,
4995        /*.nb00 =*/ nb00,
4996        /*.nb01 =*/ nb01,
4997        /*.nb02 =*/ nb02,
4998        /*.nb03 =*/ nb03,
4999        /*.ne0  =*/ ne0,
5000        /*.ne1  =*/ ne1,
5001        /*.ne2  =*/ ne2,
5002        /*.ne3  =*/ ne3,
5003        /*.nb0  =*/ nb0,
5004        /*.nb1  =*/ nb1,
5005        /*.nb2  =*/ nb2,
5006        /*.nb3  =*/ nb3
5007    };
5008
5009    auto pipeline = ggml_metal_library_get_pipeline_pad(lib, op);
5010
5011    if (pipeline.c4) {
5012        args.ne00 = ne00/4;
5013        args.ne0  = ne0/4;
5014    }
5015
5016    const int nth_max = MIN(64, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
5017    const int nth = MIN(args.ne0, nth_max);
5018    const int nk0 = (args.ne0 + 1024 - 1)/1024; // note: 1024 is hardcoded in the kernel!
5019
5020    ggml_metal_encoder_set_pipeline(enc, pipeline);
5021    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5022    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
5023    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
5024
5025    ggml_metal_encoder_dispatch_threadgroups(enc, nk0*ne1, ne2, ne3, nth, 1, 1);
5026
5027    return 1;
5028}
5029
5030int ggml_metal_op_pad_reflect_1d(ggml_metal_op_t ctx, int idx) {
5031    ggml_tensor * op = ctx->node(idx);
5032
5033    ggml_metal_library_t lib = ctx->lib;
5034    ggml_metal_encoder_t enc = ctx->enc;
5035
5036    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
5037    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5038    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
5039    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
5040
5041    ggml_metal_kargs_pad_reflect_1d args = {
5042        /*.ne00 =*/ ne00,
5043        /*.ne01 =*/ ne01,
5044        /*.ne02 =*/ ne02,
5045        /*.ne03 =*/ ne03,
5046        /*.nb00 =*/ nb00,
5047        /*.nb01 =*/ nb01,
5048        /*.nb02 =*/ nb02,
5049        /*.nb03 =*/ nb03,
5050        /*.ne0  =*/ ne0,
5051        /*.ne1  =*/ ne1,
5052        /*.ne2  =*/ ne2,
5053        /*.ne3  =*/ ne3,
5054        /*.nb0  =*/ nb0,
5055        /*.nb1  =*/ nb1,
5056        /*.nb2  =*/ nb2,
5057        /*.nb3  =*/ nb3,
5058        /*.p0 =*/ ((const int32_t *)(op->op_params))[0],
5059        /*.p1 =*/ ((const int32_t *)(op->op_params))[1]
5060    };
5061
5062    auto pipeline = ggml_metal_library_get_pipeline_pad_reflect_1d(lib, op);
5063
5064    const int nth = std::min(1024, ne0);
5065
5066    ggml_metal_encoder_set_pipeline(enc, pipeline);
5067    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5068    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
5069    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
5070
5071    ggml_metal_encoder_dispatch_threadgroups(enc, ne1, ne2, ne3, nth, 1, 1);
5072
5073    return 1;
5074}
5075
5076int ggml_metal_op_arange(ggml_metal_op_t ctx, int idx) {
5077    ggml_tensor * op = ctx->node(idx);
5078
5079    ggml_metal_library_t lib = ctx->lib;
5080    ggml_metal_encoder_t enc = ctx->enc;
5081
5082    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
5083    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
5084
5085    float start;
5086    float step;
5087
5088    memcpy(&start, ((const int32_t *) op->op_params) + 0, sizeof(float));
5089    memcpy(&step,  ((const int32_t *) op->op_params) + 2, sizeof(float));
5090
5091    ggml_metal_kargs_arange args = {
5092        /*.ne0   =*/ ne0,
5093        /*.start =*/ start,
5094        /*.step  =*/ step
5095    };
5096
5097    const int nth = std::min(1024, ne0);
5098
5099    auto pipeline = ggml_metal_library_get_pipeline_arange(lib, op);
5100
5101    ggml_metal_encoder_set_pipeline(enc, pipeline);
5102    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5103    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op), 1);
5104
5105    ggml_metal_encoder_dispatch_threadgroups(enc, 1, 1, 1, nth, 1, 1);
5106
5107    return 1;
5108}
5109
5110int ggml_metal_op_timestep_embedding(ggml_metal_op_t ctx, int idx) {
5111    ggml_tensor * op = ctx->node(idx);
5112
5113    ggml_metal_library_t lib = ctx->lib;
5114    ggml_metal_encoder_t enc = ctx->enc;
5115
5116    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
5117    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5118    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
5119    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
5120
5121    const int dim        = op->op_params[0];
5122    const int max_period = op->op_params[1];
5123
5124    ggml_metal_kargs_timestep_embedding args = {
5125        /*.nb1 =*/ nb1,
5126        /*.dim =*/ dim,
5127        /*.max_period =*/ max_period,
5128    };
5129
5130    auto pipeline = ggml_metal_library_get_pipeline_timestep_embedding(lib, op);
5131
5132    const int nth = std::max(1, std::min(1024, dim/2));
5133
5134    ggml_metal_encoder_set_pipeline(enc, pipeline);
5135    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5136    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
5137    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
5138
5139    ggml_metal_encoder_dispatch_threadgroups(enc, ne00, 1, 1, nth, 1, 1);
5140
5141    return 1;
5142}
5143
5144int ggml_metal_op_argmax(ggml_metal_op_t ctx, int idx) {
5145    ggml_tensor * op = ctx->node(idx);
5146
5147    ggml_metal_library_t lib = ctx->lib;
5148    ggml_metal_encoder_t enc = ctx->enc;
5149
5150    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
5151    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5152    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
5153    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
5154
5155    ggml_metal_kargs_argmax args = {
5156        /*.ne00 = */ ne00,
5157        /*.nb01 = */ nb01,
5158    };
5159
5160    auto pipeline = ggml_metal_library_get_pipeline_argmax(lib, op);
5161
5162    const int64_t nrows = ggml_nrows(op->src[0]);
5163
5164    int nth = 32; // SIMD width
5165    while (nth < ne00 && nth*ne01*ne02*ne03 < 256) {
5166        nth *= 2;
5167    }
5168
5169    const size_t smem = pipeline.smem;
5170
5171    ggml_metal_encoder_set_pipeline(enc, pipeline);
5172    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5173    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
5174    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
5175
5176    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
5177
5178    ggml_metal_encoder_dispatch_threadgroups(enc, nrows, 1, 1, nth, 1, 1);
5179
5180    return 1;
5181}
5182
5183int ggml_metal_op_argsort(ggml_metal_op_t ctx, int idx) {
5184    ggml_tensor * op = ctx->node(idx);
5185
5186    ggml_metal_library_t lib = ctx->lib;
5187    ggml_metal_encoder_t enc = ctx->enc;
5188
5189    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
5190
5191    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
5192    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5193    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
5194    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
5195
5196    auto pipeline = ggml_metal_library_get_pipeline_argsort(lib, op);
5197
5198    // bitonic sort requires the number of elements to be power of 2
5199    int nth = 1;
5200    while (nth < ne00 && 2*nth <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
5201        nth *= 2;
5202    }
5203
5204    const int npr = (ne00 + nth - 1)/nth;
5205
5206    // Metal kernels require the buffer size to be multiple of 16 bytes
5207    // https://developer.apple.com/documentation/metal/mtlcomputecommandencoder/1443142-setthreadgroupmemorylength
5208    const size_t smem = GGML_PAD(nth*sizeof(int32_t), 16);
5209
5210    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
5211    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
5212
5213    ggml_metal_buffer_id bid_tmp = bid_dst;
5214    bid_tmp.offs += ggml_nbytes(op);
5215
5216    if ((int) ceil(std::log(npr) / std::log(2)) % 2 == 1) {
5217        std::swap(bid_dst, bid_tmp);
5218    }
5219
5220    ggml_metal_kargs_argsort args = {
5221        /*.ne00  =*/ ne00,
5222        /*.ne01  =*/ ne01,
5223        /*.ne02  =*/ ne02,
5224        /*.ne03  =*/ ne03,
5225        /*.nb00  =*/ nb00,
5226        /*.nb01  =*/ nb01,
5227        /*.nb02  =*/ nb02,
5228        /*.nb03  =*/ nb03,
5229        /*.ne0   =*/ ne0,
5230        /*.ne1   =*/ ne1,
5231        /*.ne2   =*/ ne2,
5232        /*.ne3   =*/ ne3,
5233        /*.top_k =*/ nth,
5234    };
5235
5236    ggml_metal_encoder_set_pipeline(enc, pipeline);
5237    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5238    ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
5239    ggml_metal_encoder_set_buffer  (enc, bid_dst,  2);
5240
5241    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
5242
5243    ggml_metal_encoder_dispatch_threadgroups(enc, npr*ne01, ne02, ne03, nth, 1, 1);
5244
5245    auto pipeline_merge = ggml_metal_library_get_pipeline_argsort_merge(lib, op);
5246
5247    int len = nth;
5248
5249    while (len < ne00) {
5250        ggml_metal_op_concurrency_reset(ctx);
5251
5252        ggml_metal_kargs_argsort_merge args_merge = {
5253            /*.ne00  =*/ ne00,
5254            /*.ne01  =*/ ne01,
5255            /*.ne02  =*/ ne02,
5256            /*.ne03  =*/ ne03,
5257            /*.nb00  =*/ nb00,
5258            /*.nb01  =*/ nb01,
5259            /*.nb02  =*/ nb02,
5260            /*.nb03  =*/ nb03,
5261            /*.ne0   =*/ ne0,
5262            /*.ne1   =*/ ne1,
5263            /*.ne2   =*/ ne2,
5264            /*.ne3   =*/ ne3,
5265            /*.top_k =*/ ne00,
5266            /*.len   =*/ len,
5267        };
5268
5269        // merges per row
5270        const int nm = (ne00 + 2*len - 1) / (2*len);
5271
5272        const int nth = std::min(512, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline_merge));
5273
5274        ggml_metal_encoder_set_pipeline(enc, pipeline_merge);
5275        ggml_metal_encoder_set_bytes   (enc, &args_merge, sizeof(args_merge), 0);
5276        ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
5277        ggml_metal_encoder_set_buffer  (enc, bid_dst,  2);
5278        ggml_metal_encoder_set_buffer  (enc, bid_tmp,  3);
5279
5280        ggml_metal_encoder_dispatch_threadgroups(enc, nm*ne01, ne02, ne03, nth, 1, 1);
5281
5282        std::swap(bid_dst, bid_tmp);
5283
5284        len <<= 1;
5285    }
5286
5287    return 1;
5288}
5289
5290// bitonic-sort + merge fallback: efficient when k is small and there are few rows,
5291// where the single-workgroup-per-row radix-select cannot reach enough parallelism
5292static void ggml_metal_op_top_k_bitonic(ggml_metal_op_t ctx, int idx) {
5293    ggml_tensor * op = ctx->node(idx);
5294
5295    ggml_metal_library_t lib = ctx->lib;
5296    ggml_metal_encoder_t enc = ctx->enc;
5297
5298    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
5299
5300    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
5301    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5302    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
5303    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
5304
5305    auto pipeline = ggml_metal_library_get_pipeline_top_k(lib, op);
5306
5307    // bitonic sort requires the number of elements to be power of 2
5308    int nth = 1;
5309    while (nth < ne00 && 2*nth <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
5310        nth *= 2;
5311    }
5312
5313    // blocks per row
5314    const int npr = (ne00 + nth - 1)/nth;
5315
5316    const size_t smem = GGML_PAD(nth*sizeof(int32_t), 16);
5317
5318    ggml_metal_buffer_id bid_src0 = ggml_metal_get_buffer_id(op->src[0]);
5319    ggml_metal_buffer_id bid_dst  = ggml_metal_get_buffer_id(op);
5320
5321    ggml_metal_buffer_id bid_tmp = bid_dst;
5322    bid_tmp.offs += sizeof(int32_t)*ggml_nelements(op->src[0]);
5323
5324    if ((int) ceil(std::log(npr) / std::log(2)) % 2 == 1) {
5325        std::swap(bid_dst, bid_tmp);
5326    }
5327
5328    const int top_k = ne0;
5329
5330    ggml_metal_kargs_argsort args = {
5331        /*.ne00  =*/ ne00,
5332        /*.ne01  =*/ ne01,
5333        /*.ne02  =*/ ne02,
5334        /*.ne03  =*/ ne03,
5335        /*.nb00  =*/ nb00,
5336        /*.nb01  =*/ nb01,
5337        /*.nb02  =*/ nb02,
5338        /*.nb03  =*/ nb03,
5339        /*.ne0   =*/ ne0,
5340        /*.ne1   =*/ ne1,
5341        /*.ne2   =*/ ne2,
5342        /*.ne3   =*/ ne3,
5343        /*.top_k =*/ std::min(nth, top_k), // for each block, keep just the top_k indices
5344    };
5345
5346    if (npr > 1) {
5347        args.ne0 = (npr - 1)*args.top_k + std::min(ne00 - (npr - 1)*nth, args.top_k);
5348    }
5349
5350    ggml_metal_encoder_set_pipeline(enc, pipeline);
5351    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5352    ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
5353    ggml_metal_encoder_set_buffer  (enc, bid_dst,  2);
5354
5355    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
5356
5357    ggml_metal_encoder_dispatch_threadgroups(enc, npr*ne01, ne02, ne03, nth, 1, 1);
5358
5359    auto pipeline_merge = ggml_metal_library_get_pipeline_top_k_merge(lib, op);
5360
5361    int len = args.top_k;
5362
5363    while (len < args.ne0) {
5364        ggml_metal_op_concurrency_reset(ctx);
5365
5366        // merges per row
5367        const int nm = (args.ne0 + 2*len - 1) / (2*len);
5368
5369        const int nth = std::min(512, std::min(len, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline_merge)));
5370
5371        ggml_metal_kargs_argsort_merge args_merge = {
5372            /*.ne00  =*/ ne00,
5373            /*.ne01  =*/ ne01,
5374            /*.ne02  =*/ ne02,
5375            /*.ne03  =*/ ne03,
5376            /*.nb00  =*/ nb00,
5377            /*.nb01  =*/ nb01,
5378            /*.nb02  =*/ nb02,
5379            /*.nb03  =*/ nb03,
5380            /*.ne0   =*/ args.ne0,
5381            /*.ne1   =*/ ne1,
5382            /*.ne2   =*/ ne2,
5383            /*.ne3   =*/ ne3,
5384            /*.top_k =*/ nm == 1 ? top_k : args.ne0, // the final merge outputs top_k elements
5385            /*.len   =*/ len,
5386        };
5387
5388        ggml_metal_encoder_set_pipeline(enc, pipeline_merge);
5389        ggml_metal_encoder_set_bytes   (enc, &args_merge, sizeof(args_merge), 0);
5390        ggml_metal_encoder_set_buffer  (enc, bid_src0, 1);
5391        ggml_metal_encoder_set_buffer  (enc, bid_dst,  2);
5392        ggml_metal_encoder_set_buffer  (enc, bid_tmp,  3);
5393
5394        ggml_metal_encoder_dispatch_threadgroups(enc, nm*ne01, ne02, ne03, nth, 1, 1);
5395
5396        std::swap(bid_dst, bid_tmp);
5397
5398        len <<= 1;
5399    }
5400}
5401
5402// radix-select: one workgroup per row. Maps each float to an order-preserving unsigned
5403// key, finds the k-th largest via 4 radix-8 histogram passes, then compacts the top-k
5404// indices. Fast for large k and/or many rows.
5405static void ggml_metal_op_top_k_radix(ggml_metal_op_t ctx, int idx) {
5406    ggml_tensor * op = ctx->node(idx);
5407
5408    ggml_metal_library_t lib = ctx->lib;
5409    ggml_metal_encoder_t enc = ctx->enc;
5410
5411    GGML_ASSERT(ggml_is_contiguous_rows(op->src[0]));
5412
5413    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
5414    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5415
5416    auto pipeline = ggml_metal_library_get_pipeline_top_k_radix(lib, op);
5417
5418    // one workgroup per row; radix-select the k-th largest value
5419    const int nth = std::min(1024, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
5420
5421    ggml_metal_kargs_top_k args = {
5422        /*.ne00  =*/ ne00,
5423        /*.ne01  =*/ ne01,
5424        /*.ne02  =*/ ne02,
5425        /*.ne03  =*/ ne03,
5426        /*.nb01  =*/ nb01,
5427        /*.nb02  =*/ nb02,
5428        /*.nb03  =*/ nb03,
5429        /*.top_k =*/ (int32_t) op->ne[0],
5430    };
5431
5432    // shared memory: 256-entry histogram + bucket/above scalars + output counter
5433    const size_t smem_histo  = GGML_PAD(256*sizeof(uint32_t), 16);
5434    const size_t smem_bucket = GGML_PAD(    sizeof(uint32_t), 16);
5435    const size_t smem_above  = GGML_PAD(    sizeof(uint32_t), 16);
5436    const size_t smem_out    = GGML_PAD(    sizeof(uint32_t), 16);
5437
5438    ggml_metal_encoder_set_pipeline(enc, pipeline);
5439    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5440    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
5441    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
5442
5443    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem_histo,  0);
5444    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem_bucket, 1);
5445    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem_above,  2);
5446    ggml_metal_encoder_set_threadgroup_memory_size(enc, smem_out,    3);
5447
5448    ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
5449}
5450
5451int ggml_metal_op_topk_moe(ggml_metal_op_t ctx, int idx) {
5452    ggml_metal_library_t lib = ctx->lib;
5453    ggml_metal_encoder_t enc = ctx->enc;
5454
5455    int n_fuse = 1;
5456    const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n_fuse);
5457    if (!fusion || ggml_metal_fusion_get_id(fusion) != GGML_METAL_FUSION_TOPK_MOE) {
5458        return 1;
5459    }
5460
5461    ggml_tensor * softmax  = ctx->node(idx);
5462    ggml_tensor * logits   = softmax->src[0];
5463    ggml_tensor * get_rows = ctx->node(idx + 2);
5464    ggml_tensor * ids      = get_rows->src[1];
5465    ggml_tensor * weights  = ctx->node(idx + n_fuse - 1);
5466
5467    const int64_t n_expert      = logits->ne[0];
5468    const int64_t n_tokens      = logits->ne[1];
5469    const int64_t n_expert_used = ids->ne[0];
5470
5471    const bool with_norm  = n_fuse >= 6;
5472    const bool with_scale = n_fuse == 4 || n_fuse == 7;
5473
5474    float clamp = -INFINITY;
5475    if (with_norm) {
5476        ggml_tensor * clamp_node = ctx->node(idx + 4);
5477        clamp = ggml_get_op_params_f32(clamp_node, 0);
5478    }
5479
5480    float scale = 1.0f;
5481    if (with_scale) {
5482        ggml_tensor * scale_node = ctx->node(idx + n_fuse - 1);
5483        scale = ggml_get_op_params_f32(scale_node, 0);
5484    }
5485
5486    ggml_metal_kargs_topk_moe args = {
5487        /*.ne01      =*/ (int32_t) n_tokens,
5488        /*.nb01      =*/ logits->nb[1],
5489        /*.nb1_ids   =*/ ids->nb[1],
5490        /*.clamp =*/ clamp,
5491        /*.scale =*/ scale,
5492    };
5493
5494    auto pipeline = ggml_metal_library_get_pipeline_topk_moe(lib, (int32_t) n_expert, (int32_t) n_expert_used, with_norm);
5495
5496    ggml_metal_encoder_set_pipeline(enc, pipeline);
5497    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5498    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(logits),  1);
5499    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(weights), 2);
5500    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(ids),     3);
5501
5502    ggml_metal_encoder_dispatch_threadgroups(enc, (uint32_t) n_tokens, 1, 1, 32, 1, 1);
5503
5504    ctx->count_fusions(fusion);
5505
5506    if (ggml_metal_fusion_info_debug(ctx->finfo) > 1) {
5507        GGML_LOG_DEBUG("%s: fuse: SOFT_MAX + ARGSORT + GET_ROWS\n", __func__);
5508    }
5509
5510    return n_fuse;
5511}
5512
5513int ggml_metal_op_moe_reduce(ggml_metal_op_t ctx, int idx) {
5514    ggml_metal_library_t lib = ctx->lib;
5515    ggml_metal_encoder_t enc = ctx->enc;
5516
5517    int n_fuse = 1;
5518    const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n_fuse);
5519    if (!fusion || ggml_metal_fusion_get_id(fusion) != GGML_METAL_FUSION_MOE_REDUCE) {
5520        return 1;
5521    }
5522
5523    ggml_tensor * mul     = ctx->node(idx);
5524    ggml_tensor * experts = mul->src[0];
5525    ggml_tensor * weights = mul->src[1];
5526    ggml_tensor * dst     = ctx->node(idx + n_fuse - 1);
5527
5528    ggml_metal_kargs_moe_reduce args = {
5529        /*.ne00 =*/ (int32_t) experts->ne[0],
5530        /*.ne02 =*/ (int32_t) experts->ne[2],
5531    };
5532
5533    auto pipeline = ggml_metal_library_get_pipeline_moe_reduce(lib, (int32_t) experts->ne[1]);
5534
5535    const int nth = std::min(256, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
5536    const int n_col_tiles = (args.ne00 + nth - 1) / nth;
5537
5538    ggml_metal_encoder_set_pipeline(enc, pipeline);
5539    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5540    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(experts), 1);
5541    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(weights), 2);
5542    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(dst),     3);
5543
5544    ggml_metal_encoder_dispatch_threadgroups(enc, (uint32_t) args.ne02, (uint32_t) n_col_tiles, 1, nth, 1, 1);
5545
5546    ctx->count_fusions(fusion);
5547
5548    if (ggml_metal_fusion_info_debug(ctx->finfo) > 1) {
5549        GGML_LOG_DEBUG("%s: fuse: MOE_REDUCE\n", __func__);
5550    }
5551
5552    return n_fuse;
5553}
5554
5555int ggml_metal_op_top_k(ggml_metal_op_t ctx, int idx) {
5556    ggml_tensor * op = ctx->node(idx);
5557
5558    // radix-select has a fixed single-workgroup-per-row cost (~50-60us) that is only
5559    // amortized for long rows, many rows, or a large k; otherwise the bitonic path wins
5560    const int ncols = op->src[0]->ne[0];
5561    const int k     = op->ne[0];
5562    const int nrows = ggml_nrows(op->src[0]);
5563
5564    const bool use_radix =
5565        ncols > 2048 && (k > 64 || (nrows > 4 && ncols >= 8192));
5566
5567    if (use_radix) {
5568        ggml_metal_op_top_k_radix(ctx, idx);
5569    } else {
5570        ggml_metal_op_top_k_bitonic(ctx, idx);
5571    }
5572
5573    return 1;
5574}
5575
5576int ggml_metal_op_tri(ggml_metal_op_t ctx, int idx) {
5577    ggml_tensor * op = ctx->node(idx);
5578
5579    ggml_metal_library_t lib = ctx->lib;
5580    ggml_metal_encoder_t enc = ctx->enc;
5581
5582    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
5583    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5584    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
5585    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
5586
5587    ggml_metal_kargs_tri args = {
5588        /*.ne00  =*/ ne00,
5589        /*.ne01  =*/ ne01,
5590        /*.ne02  =*/ ne02,
5591        /*.ne03  =*/ ne03,
5592        /*.nb00  =*/ nb00,
5593        /*.nb01  =*/ nb01,
5594        /*.nb02  =*/ nb02,
5595        /*.nb03  =*/ nb03,
5596        /*.ne0   =*/ ne0,
5597        /*.ne1   =*/ ne1,
5598        /*.ne2   =*/ ne2,
5599        /*.ne3   =*/ ne3,
5600        /*.nb0   =*/ nb0,
5601        /*.nb1   =*/ nb1,
5602        /*.nb2   =*/ nb2,
5603        /*.nb3   =*/ nb3,
5604    };
5605
5606    auto pipeline = ggml_metal_library_get_pipeline_tri(lib, op);
5607
5608    int nth = 32; // SIMD width
5609
5610    while (nth < ne00 && nth < ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)) {
5611        nth *= 2;
5612    }
5613
5614    nth = std::min(nth, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
5615    nth = std::min(nth, ne00);
5616
5617    ggml_metal_encoder_set_pipeline(enc, pipeline);
5618    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), 0);
5619    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), 1);
5620    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op),         2);
5621
5622    ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
5623
5624    return 1;
5625}
5626
5627int ggml_metal_op_opt_step_adamw(ggml_metal_op_t ctx, int idx) {
5628    ggml_tensor * op = ctx->node(idx);
5629
5630    ggml_metal_library_t lib = ctx->lib;
5631    ggml_metal_encoder_t enc = ctx->enc;
5632
5633    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
5634    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5635    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
5636    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
5637
5638    auto pipeline = ggml_metal_library_get_pipeline_opt_step_adamw(lib, op);
5639
5640    const int64_t np = ggml_nelements(op->src[0]);
5641    ggml_metal_kargs_opt_step_adamw args = {
5642        /*.np =*/ np,
5643    };
5644
5645    int ida = 0;
5646
5647    ggml_metal_encoder_set_pipeline(enc, pipeline);
5648    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), ida++);
5649    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), ida++);
5650    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), ida++);
5651    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[2]), ida++);
5652    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[3]), ida++);
5653    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[4]), ida++);
5654
5655    const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), ne0);
5656    const int64_t n = (np + nth - 1) / nth;
5657
5658    ggml_metal_encoder_dispatch_threadgroups(enc, n, 1, 1, nth, 1, 1);
5659
5660    return 1;
5661}
5662
5663int ggml_metal_op_opt_step_sgd(ggml_metal_op_t ctx, int idx) {
5664    ggml_tensor * op = ctx->node(idx);
5665
5666    ggml_metal_library_t lib = ctx->lib;
5667    ggml_metal_encoder_t enc = ctx->enc;
5668
5669    GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne);
5670    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5671    GGML_TENSOR_LOCALS( int32_t, ne,  op,         ne);
5672    GGML_TENSOR_LOCALS(uint64_t, nb,  op,         nb);
5673
5674    auto pipeline = ggml_metal_library_get_pipeline_opt_step_sgd(lib, op);
5675
5676    const int64_t np = ggml_nelements(op->src[0]);
5677    ggml_metal_kargs_opt_step_sgd args = {
5678        /*.np =*/ np,
5679    };
5680
5681    int ida = 0;
5682
5683    ggml_metal_encoder_set_pipeline(enc, pipeline);
5684    ggml_metal_encoder_set_bytes   (enc, &args, sizeof(args), ida++);
5685    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[0]), ida++);
5686    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[1]), ida++);
5687    ggml_metal_encoder_set_buffer  (enc, ggml_metal_get_buffer_id(op->src[2]), ida++);
5688
5689    const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), ne0);
5690    const int64_t n = (np + nth - 1) / nth;
5691
5692    ggml_metal_encoder_dispatch_threadgroups(enc, n, 1, 1, nth, 1, 1);
5693
5694    return 1;
5695}
5696
5697int ggml_metal_op_count_equal(ggml_metal_op_t ctx, int idx) {
5698    ggml_tensor * op = ctx->node(idx);
5699
5700    ggml_metal_library_t lib = ctx->lib;
5701    ggml_metal_encoder_t enc = ctx->enc;
5702
5703    GGML_TENSOR_LOCALS(int32_t,  ne0, op->src[0], ne);
5704    GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb);
5705    GGML_TENSOR_LOCALS(uint64_t, nb1, op->src[1], nb);
5706
5707    {
5708        ggml_metal_kargs_memset args = { /*.val =*/ 0 };
5709
5710        auto pipeline = ggml_metal_library_get_pipeline_memset(lib, op);
5711
5712        ggml_metal_encoder_set_pipeline(enc, pipeline);
5713        ggml_metal_encoder_set_bytes(enc, &args, sizeof(args), 0);
5714        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op), 1);
5715
5716        ggml_metal_encoder_dispatch_threadgroups(enc, 1, 1, 1, 1, 1, 1);
5717    }
5718
5719    ggml_metal_op_concurrency_reset(ctx);
5720
5721    {
5722        ggml_metal_kargs_count_equal args = {
5723            /*.ne00 =*/ ne00,
5724            /*.ne01 =*/ ne01,
5725            /*.ne02 =*/ ne02,
5726            /*.ne03 =*/ ne03,
5727            /*.nb00 =*/ nb00,
5728            /*.nb01 =*/ nb01,
5729            /*.nb02 =*/ nb02,
5730            /*.nb03 =*/ nb03,
5731            /*.nb10 =*/ nb10,
5732            /*.nb11 =*/ nb11,
5733            /*.nb12 =*/ nb12,
5734            /*.nb13 =*/ nb13,
5735        };
5736
5737        auto pipeline = ggml_metal_library_get_pipeline_count_equal(lib, op);
5738
5739        const size_t smem = pipeline.smem;
5740
5741        const int nth = 32*pipeline.nsg;
5742
5743        GGML_ASSERT(nth <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline));
5744
5745        ggml_metal_encoder_set_pipeline(enc, pipeline);
5746        ggml_metal_encoder_set_bytes(enc, &args, sizeof(args), 0);
5747        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[0]), 1);
5748        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[1]), 2);
5749        ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op), 3);
5750
5751        ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0);
5752        ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne02, ne03, nth, 1, 1);
5753    }
5754
5755    return 1;
5756}