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
15.4 KiB500 linesraw
1#include "ggml-metal-common.h"
2#include "ggml-metal-fusion.h"
3
4#include "ggml.h"
5#include "ggml-impl.h"
6#include "ggml-backend-impl.h"
7
8#include <vector>
9
10// must stay in sync with the kernel_fwht_<type>_<N> templates in misc.metal
11static bool ggml_metal_fwht_supported_size(int64_t n) {
12    return n == 64 || n == 128 || n == 256 || n == 512;
13}
14
15// the FWHT kernels handle a Hadamard-hinted MUL_MAT only under these conditions. supports_op
16// and the dispatch must ask the same question: an F16 src1 that is admitted but then falls
17// through reaches the generic path, which has no F32 src0 by F16 src1 kernel.
18bool ggml_metal_op_mul_mat_use_fwht(const struct ggml_tensor * op) {
19    return ggml_get_op_params_i32(op, 1) == GGML_HINT_SRC0_IS_HADAMARD &&
20           op->type == GGML_TYPE_F32 &&
21           (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
22           ggml_is_contiguous(op->src[1]) &&
23           ggml_is_contiguous(op) &&
24           ggml_are_same_shape(op->src[1], op) &&
25           ggml_metal_fwht_supported_size(op->src[1]->ne[0]);
26}
27
28bool ggml_metal_op_mul_mat_use_mm(const struct ggml_tensor * op, bool has_simdgroup_mm) {
29    const int64_t ne00 = op->src[0]->ne[0];
30    const int64_t ne11 = op->src[1]->ne[1];
31
32    return !ggml_is_transposed(op->src[0]) &&
33           !ggml_is_transposed(op->src[1]) &&
34           has_simdgroup_mm && ne00 >= 64 && ne11 > 8;
35}
36
37bool ggml_metal_op_mul_mat_id_use_mm(const struct ggml_tensor * op, bool has_simdgroup_mm) {
38    const int64_t ne00 = op->src[0]->ne[0];
39    const int64_t ne21 = op->src[2]->ne[1];
40
41    return has_simdgroup_mm && ne00 >= 64 && ne21 >= 32;
42}
43
44// represents a memory range (i.e. an interval from a starting address p0 to an ending address p1 in a given buffer pb)
45// the type indicates whether it is a source range (i.e. ops read data from it) or a destination range (i.e. ops write data to it)
46struct ggml_mem_range {
47    uint64_t pb; // buffer id
48
49    uint64_t p0; // begin
50    uint64_t p1; // end
51
52    ggml_mem_range_type pt;
53};
54
55struct ggml_mem_ranges {
56    std::vector<ggml_mem_range> ranges;
57
58    int debug = 0;
59};
60
61ggml_mem_ranges_t ggml_mem_ranges_init(int debug) {
62    auto * res = new ggml_mem_ranges;
63
64    res->ranges.reserve(256);
65    res->debug = debug;
66
67    return res;
68}
69
70void ggml_mem_ranges_free(ggml_mem_ranges_t mrs) {
71    delete mrs;
72}
73
74void ggml_mem_ranges_reset(ggml_mem_ranges_t mrs) {
75    mrs->ranges.clear();
76}
77
78static bool ggml_mem_ranges_add(ggml_mem_ranges_t mrs, ggml_mem_range mr) {
79    mrs->ranges.push_back(mr);
80
81    return true;
82}
83
84static ggml_mem_range ggml_mem_range_from_tensor(const ggml_tensor * tensor, ggml_mem_range_type pt) {
85    // always use the base tensor
86    tensor = tensor->view_src ? tensor->view_src : tensor;
87
88    GGML_ASSERT(!tensor->view_src);
89
90    ggml_mem_range mr;
91
92    if (tensor->buffer) {
93        // when the tensor is allocated, use the actual memory address range in the buffer
94        //
95        // take the actual allocated size with ggml_backend_buft_get_alloc_size()
96        // this can be larger than the tensor size if the buffer type allocates extra memory
97        // ref: https://github.com/ggml-org/llama.cpp/pull/15966
98        mr = {
99            /*.pb =*/ (uint64_t) tensor->buffer,
100            /*.p0 =*/ (uint64_t) tensor->data,
101            /*.p1 =*/ (uint64_t) tensor->data + ggml_backend_buft_get_alloc_size(tensor->buffer->buft, tensor),
102            /*.pt =*/ pt,
103        };
104    } else {
105        // otherwise, the pointer address is used as an unique id of the memory ranges
106        //   that the tensor will be using when it is allocated
107        mr = {
108            /*.pb =*/ (uint64_t) tensor,
109            /*.p0 =*/ 0,    //
110            /*.p1 =*/ 1024, // [0, 1024) is a dummy range, not used
111            /*.pt =*/ pt,
112        };
113    };
114
115    return mr;
116}
117
118static ggml_mem_range ggml_mem_range_from_tensor_src(const ggml_tensor * tensor) {
119    return ggml_mem_range_from_tensor(tensor, MEM_RANGE_TYPE_SRC);
120}
121
122static ggml_mem_range ggml_mem_range_from_tensor_dst(const ggml_tensor * tensor) {
123    return ggml_mem_range_from_tensor(tensor, MEM_RANGE_TYPE_DST);
124}
125
126static bool ggml_mem_ranges_add_src(ggml_mem_ranges_t mrs, const ggml_tensor * tensor) {
127    GGML_ASSERT(tensor);
128
129    ggml_mem_range mr = ggml_mem_range_from_tensor_src(tensor);
130
131    if (mrs->debug > 2) {
132        GGML_LOG_DEBUG("%s: add src range buf=%lld, [%lld, %lld)\n", __func__, mr.pb, mr.p0, mr.p1);
133    }
134
135    return ggml_mem_ranges_add(mrs, mr);
136}
137
138static bool ggml_mem_ranges_add_dst(ggml_mem_ranges_t mrs, const ggml_tensor * tensor) {
139    GGML_ASSERT(tensor);
140
141    ggml_mem_range mr = ggml_mem_range_from_tensor_dst(tensor);
142
143    if (mrs->debug > 2) {
144        GGML_LOG_DEBUG("%s: add dst range buf=%lld, [%lld, %lld)\n", __func__, mr.pb, mr.p0, mr.p1);
145    }
146
147    return ggml_mem_ranges_add(mrs, mr);
148}
149
150bool ggml_mem_ranges_add(ggml_mem_ranges_t mrs, const ggml_tensor * tensor) {
151    for (int i = 0; i < GGML_MAX_SRC; i++) {
152        if (tensor->src[i]) {
153            ggml_mem_ranges_add_src(mrs, tensor->src[i]);
154        }
155    }
156
157    return ggml_mem_ranges_add_dst(mrs, tensor);
158}
159
160static bool ggml_mem_ranges_check(ggml_mem_ranges_t mrs, ggml_mem_range mr) {
161    for (size_t i = 0; i < mrs->ranges.size(); i++) {
162        const auto & cmp = mrs->ranges[i];
163
164        // two memory ranges cannot intersect if they are in different buffers
165        if (mr.pb != cmp.pb) {
166            continue;
167        }
168
169        // intersecting source ranges are allowed
170        if (mr.pt == MEM_RANGE_TYPE_SRC && cmp.pt == MEM_RANGE_TYPE_SRC) {
171            continue;
172        }
173
174        if (mr.p0 < cmp.p1 && mr.p1 >= cmp.p0) {
175            if (mrs->debug > 2) {
176                GGML_LOG_DEBUG("%s: the %s range buf=%lld, [%lld, %lld) overlaps with a previous %s range buf=%lld, [%lld, %lld)\n",
177                        __func__,
178                        mr.pt == MEM_RANGE_TYPE_SRC ? "src" : "dst",
179                        mr.pb, mr.p0, mr.p1,
180                        cmp.pt == MEM_RANGE_TYPE_SRC ? "src" : "dst",
181                        cmp.pb, cmp.p0, cmp.p1);
182            }
183
184            return false;
185        }
186    }
187
188    return true;
189}
190
191static bool ggml_mem_ranges_check_src(ggml_mem_ranges_t mrs, const ggml_tensor * tensor) {
192    GGML_ASSERT(tensor);
193
194    ggml_mem_range mr = ggml_mem_range_from_tensor_src(tensor);
195
196    const bool res = ggml_mem_ranges_check(mrs, mr);
197
198    return res;
199}
200
201static bool ggml_mem_ranges_check_dst(ggml_mem_ranges_t mrs, const ggml_tensor * tensor) {
202    GGML_ASSERT(tensor);
203
204    ggml_mem_range mr = ggml_mem_range_from_tensor_dst(tensor);
205
206    const bool res = ggml_mem_ranges_check(mrs, mr);
207
208    return res;
209}
210
211bool ggml_mem_ranges_check(ggml_mem_ranges_t mrs, const ggml_tensor * tensor) {
212    for (int i = 0; i < GGML_MAX_SRC; i++) {
213        if (tensor->src[i]) {
214            if (!ggml_mem_ranges_check_src(mrs, tensor->src[i])) {
215                return false;
216            }
217        }
218    }
219
220    return ggml_mem_ranges_check_dst(mrs, tensor);
221}
222
223struct node_info {
224    ggml_tensor * node;
225
226    std::vector<ggml_tensor *> fused;
227
228    ggml_op op() const {
229        return node->op;
230    }
231
232    const ggml_tensor * dst() const {
233        return fused.empty() ? node : fused.back();
234    }
235
236    bool is_empty() const {
237        return ggml_op_is_empty(node->op);
238    }
239
240    void add_fused(ggml_tensor * t) {
241        fused.push_back(t);
242    }
243
244    bool is_output(const ggml_tensor * t) const {
245        if (t == node) {
246            return true;
247        }
248        for (const auto * f : fused) {
249            if (t == f) {
250                return true;
251            }
252        }
253        return false;
254    }
255};
256
257static std::vector<int> ggml_metal_graph_optimize_reorder(const std::vector<node_info> & nodes) {
258    // helper to add node src and dst ranges
259    const auto & h_add = [](ggml_mem_ranges_t mrs, const node_info & node) {
260        // only external sources matter: sources produced by the fused group are internal
261        for (int i = 0; i < GGML_MAX_SRC; i++) {
262            const ggml_tensor * src = node.node->src[i];
263            if (src && !node.is_output(src)) {
264                if (!ggml_mem_ranges_add_src(mrs, src)) {
265                    return false;
266                }
267            }
268        }
269
270        for (const auto * fused : node.fused) {
271            for (int i = 0; i < GGML_MAX_SRC; i++) {
272                const ggml_tensor * src = fused->src[i];
273                if (src && !node.is_output(src)) {
274                    if (!ggml_mem_ranges_add_src(mrs, src)) {
275                        return false;
276                    }
277                }
278            }
279        }
280
281        // all fused tensors are produced by the fused kernel
282        if (!ggml_mem_ranges_add_dst(mrs, node.node)) {
283            return false;
284        }
285        for (const auto * fused : node.fused) {
286            if (!ggml_mem_ranges_add_dst(mrs, fused)) {
287                return false;
288            }
289        }
290
291        return true;
292    };
293
294    // helper to check if a node can run concurrently with the existing set of nodes
295    const auto & h_check = [](ggml_mem_ranges_t mrs, const node_info & node) {
296        for (int i = 0; i < GGML_MAX_SRC; i++) {
297            const ggml_tensor * src = node.node->src[i];
298            if (src && !node.is_output(src)) {
299                if (!ggml_mem_ranges_check_src(mrs, src)) {
300                    return false;
301                }
302            }
303        }
304
305        for (const auto * fused : node.fused) {
306            for (int i = 0; i < GGML_MAX_SRC; i++) {
307                const ggml_tensor * src = fused->src[i];
308                if (src && !node.is_output(src)) {
309                    if (!ggml_mem_ranges_check_src(mrs, src)) {
310                        return false;
311                    }
312                }
313            }
314        }
315
316        if (!ggml_mem_ranges_check_dst(mrs, node.node)) {
317            return false;
318        }
319        for (const auto * fused : node.fused) {
320            if (!ggml_mem_ranges_check_dst(mrs, fused)) {
321                return false;
322            }
323        }
324
325        return true;
326    };
327
328    // perform reorders only across these types of ops
329    // can be expanded when needed
330    const auto & h_safe = [](ggml_op op) {
331        switch (op) {
332            case GGML_OP_MUL_MAT:
333            case GGML_OP_MUL_MAT_ID:
334            case GGML_OP_ROPE:
335            case GGML_OP_NORM:
336            case GGML_OP_RMS_NORM:
337            case GGML_OP_GROUP_NORM:
338            case GGML_OP_L2_NORM:
339            case GGML_OP_SUM_ROWS:
340            case GGML_OP_SSM_CONV:
341            case GGML_OP_SSM_SCAN:
342            case GGML_OP_CLAMP:
343            case GGML_OP_TRI:
344            case GGML_OP_DIAG:
345            case GGML_OP_MUL:
346            case GGML_OP_ADD:
347            case GGML_OP_SUB:
348            case GGML_OP_DIV:
349            case GGML_OP_GLU:
350            case GGML_OP_SCALE:
351            case GGML_OP_UNARY:
352            case GGML_OP_GET_ROWS:
353            case GGML_OP_SET_ROWS:
354            case GGML_OP_SET:
355            case GGML_OP_CPY:
356            case GGML_OP_CONT:
357            case GGML_OP_REPEAT:
358                return true;
359            default:
360                return ggml_op_is_empty(op);
361        }
362    };
363
364    const int n = nodes.size();
365
366    std::vector<int> res;
367    res.reserve(n);
368
369    std::vector<bool> used(n, false);
370
371    // the memory ranges for the set of currently concurrent nodes
372    ggml_mem_ranges_t mrs0 = ggml_mem_ranges_init(0);
373
374    // the memory ranges for the set of nodes that haven't been processed yet, when looking forward for a node to reorder
375    ggml_mem_ranges_t mrs1 = ggml_mem_ranges_init(0);
376
377    for (int i0 = 0; i0 < n; i0++) {
378        if (used[i0]) {
379            continue;
380        }
381
382        const auto & node0 = nodes[i0];
383
384        // the node is not concurrent with the existing concurrent set, so we have to "put a barrier" (i.e reset mrs0)
385        // but before we do that, look forward for some other nodes that can be added to the concurrent set mrs0
386        //
387        // note: we can always add empty nodes to the concurrent set as they don't read nor write anything
388        if (!node0.is_empty() && !h_check(mrs0, node0)) {
389            // this will hold the set of memory ranges from the nodes that haven't been processed yet
390            // if a node is not concurrent with this set, we cannot reorder it
391            ggml_mem_ranges_reset(mrs1);
392
393            // initialize it with the current node
394            h_add(mrs1, node0);
395
396            // that many nodes forward to search for a concurrent node
397            constexpr int N_FORWARD = 64;
398
399            for (int i1 = i0 + 1; i1 < i0 + N_FORWARD && i1 < n; i1++) {
400                if (used[i1]) {
401                    continue;
402                }
403
404                const auto & node1 = nodes[i1];
405
406                // disallow reordering of certain ops
407                if (!h_safe(node1.op())) {
408                    break;
409                }
410
411                const bool is_empty = node1.is_empty();
412
413                // to reorder a node and add it to the concurrent set, it has to be:
414                //   + empty or concurrent with all nodes in the existing concurrent set (mrs0)
415                //   + concurrent with all nodes prior to it that haven't been processed yet (mrs1)
416                if ((is_empty || h_check(mrs0, node1)) && h_check(mrs1, node1)) {
417                    // add the node to the existing concurrent set (i.e. reorder it for early execution)
418                    h_add(mrs0, node1);
419                    res.push_back(i1);
420
421                    // mark as used, so we skip re-processing it later
422                    used[i1] = true;
423                } else {
424                    // expand the set of nodes that haven't been processed yet
425                    h_add(mrs1, node1);
426                }
427            }
428
429            // finalize the concurrent set and begin a new one
430            ggml_mem_ranges_reset(mrs0);
431        }
432
433        // expand the concurrent set with the current node
434        {
435            h_add(mrs0, node0);
436            res.push_back(i0);
437        }
438    }
439
440    ggml_mem_ranges_free(mrs0);
441    ggml_mem_ranges_free(mrs1);
442
443    return res;
444}
445
446void ggml_graph_optimize(ggml_cgraph * gf) {
447    const int n = gf->n_nodes;
448
449    std::vector<node_info> nodes;
450    nodes.reserve(gf->n_nodes);
451
452    // fuse nodes:
453    // we don't want to make reorders that break fusing, so we first pack all fusable tensors
454    //   and perform the reorder over the fused nodes. after the reorder is done, we unfuse
455    //
456    // the fusable sequences are declared in the fusion table (ggml-metal-fuse.cpp), so the
457    // packing here is driven by the same patterns that the op encoders will later use
458    for (int i = 0; i < n; i++) {
459        node_info node = {
460            /*.node =*/ gf->nodes[i],
461            /*.fused =*/ {},
462        };
463
464        const int f = ggml_metal_fusion_max(gf, i);
465
466        // add the fused tensors into the node info so we can unfuse them later
467        for (int k = 1; k < f; k++) {
468            ++i;
469
470            // the .dst() becomes the last fused tensor
471            node.add_fused(gf->nodes[i]);
472        }
473
474        nodes.push_back(std::move(node));
475    }
476
477#if 1
478    // reorder to improve concurrency
479    const auto order = ggml_metal_graph_optimize_reorder(nodes);
480#else
481    std::vector<int> order(nodes.size());
482    for (size_t i = 0; i < nodes.size(); i++) {
483        order[i] = i;
484    }
485#endif
486
487    // unfuse
488    {
489        int j = 0;
490        for (const auto i : order) {
491            const auto & node = nodes[i];
492
493            gf->nodes[j++] = node.node;
494
495            for (auto * fused : node.fused) {
496                gf->nodes[j++] = fused;
497            }
498        }
499    }
500}