Coverage Report

Created: 2026-07-16 06:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/ggml/src/ggml-alloc.c
Line
Count
Source
1
#include "ggml-alloc.h"
2
#include "ggml-backend-impl.h"
3
#include "ggml.h"
4
#include "ggml-impl.h"
5
6
#include <assert.h>
7
#include <limits.h>
8
#include <stdarg.h>
9
#include <stdio.h>
10
#include <stdlib.h>
11
#include <string.h>
12
13
0
#define MAX(a, b) ((a) > (b) ? (a) : (b))
14
#define MAX_FREE_BLOCKS 256
15
16
//#define GGML_ALLOCATOR_DEBUG
17
18
//#define AT_PRINTF(...) GGML_LOG_DEBUG(__VA_ARGS__)
19
#define AT_PRINTF(...)
20
21
// ops that return true for this function must not use restrict pointers for their backend implementations
22
0
bool ggml_op_can_inplace(enum ggml_op op) {
23
0
    switch (op) {
24
0
        case GGML_OP_FILL:
25
0
        case GGML_OP_SCALE:
26
0
        case GGML_OP_DIAG_MASK_ZERO:
27
0
        case GGML_OP_DIAG_MASK_INF:
28
0
        case GGML_OP_ADD:
29
0
        case GGML_OP_ADD_ID:
30
0
        case GGML_OP_ADD1:
31
0
        case GGML_OP_SUB:
32
0
        case GGML_OP_MUL:
33
0
        case GGML_OP_DIV:
34
0
        case GGML_OP_SQR:
35
0
        case GGML_OP_SQRT:
36
0
        case GGML_OP_LOG:
37
0
        case GGML_OP_UNARY:
38
0
        case GGML_OP_ROPE:
39
0
        case GGML_OP_ROPE_BACK:
40
0
        case GGML_OP_SILU_BACK:
41
0
        case GGML_OP_RMS_NORM:
42
0
        case GGML_OP_RMS_NORM_BACK:
43
0
        case GGML_OP_SOFT_MAX:
44
0
        case GGML_OP_SOFT_MAX_BACK:
45
0
            return true;
46
47
0
        default:
48
0
            return false;
49
0
    }
50
0
}
51
52
0
static size_t aligned_offset(const void * buffer, size_t offset, size_t alignment) {
53
0
    assert(alignment && !(alignment & (alignment - 1))); // power of 2
54
0
    size_t align = (alignment - (((uintptr_t)buffer + offset) % alignment)) % alignment;
55
0
    return offset + align;
56
0
}
57
58
// tallocr
59
60
0
struct ggml_tallocr ggml_tallocr_new(ggml_backend_buffer_t buffer) {
61
0
    void * base = ggml_backend_buffer_get_base(buffer);
62
0
    size_t align = ggml_backend_buffer_get_alignment(buffer);
63
64
0
    assert(align && !(align & (align - 1))); // power of 2
65
66
0
    struct ggml_tallocr talloc = (struct ggml_tallocr) {
67
0
        /*.buffer    = */ buffer,
68
0
        /*.base      = */ base,
69
0
        /*.alignment = */ align,
70
0
        /*.offset    = */ aligned_offset(base, 0, align),
71
0
    };
72
0
    return talloc;
73
0
}
74
75
0
enum ggml_status ggml_tallocr_alloc(struct ggml_tallocr * talloc, struct ggml_tensor * tensor) {
76
0
    size_t size = ggml_backend_buffer_get_alloc_size(talloc->buffer, tensor);
77
0
    size = GGML_PAD(size, talloc->alignment);
78
79
0
    if (talloc->offset + size > ggml_backend_buffer_get_size(talloc->buffer)) {
80
0
        GGML_LOG_ERROR("%s: not enough space in the buffer to allocate %s (needed %zu, available %zu)\n",
81
0
                __func__, tensor->name, size, ggml_backend_buffer_get_size(talloc->buffer) - talloc->offset);
82
0
        GGML_ABORT("not enough space in the buffer");
83
0
    }
84
85
0
    void * addr = (char *)ggml_backend_buffer_get_base(talloc->buffer) + talloc->offset;
86
0
    talloc->offset += size;
87
88
0
    assert(((uintptr_t)addr % talloc->alignment) == 0);
89
90
0
    return ggml_backend_tensor_alloc(talloc->buffer, tensor, addr);
91
0
}
92
93
// dynamic tensor allocator
94
95
0
#define GGML_VBUFFER_MAX_CHUNKS 16
96
97
// relative memory address within an allocation that can be split into multiple buffers (chunks)
98
struct buffer_address {
99
    int chunk;     // index of a backend buffer
100
    size_t offset; // local memory offset within the buffer
101
};
102
103
static const struct buffer_address GGML_BUFFER_ADDRESS_INVALID = { -1, SIZE_MAX };
104
105
0
static bool ggml_buffer_address_less(struct buffer_address a, struct buffer_address b) {
106
0
    return a.chunk != b.chunk ? a.chunk < b.chunk : a.offset < b.offset;
107
0
}
108
109
struct free_block {
110
    size_t offset;
111
    size_t size;
112
};
113
114
struct tallocr_chunk {
115
    struct free_block free_blocks[MAX_FREE_BLOCKS];
116
    int n_free_blocks;
117
    size_t max_size;
118
};
119
120
struct ggml_dyn_tallocr {
121
    size_t alignment;
122
    size_t max_chunk_size;
123
    struct tallocr_chunk * chunks[GGML_VBUFFER_MAX_CHUNKS];
124
    int n_chunks;
125
126
#ifdef GGML_ALLOCATOR_DEBUG
127
    struct {
128
        const struct ggml_tensor * tensor;
129
        struct buffer_address addr;
130
    } allocated_tensors[1024];
131
#endif
132
};
133
134
0
static void ggml_dyn_tallocr_insert_block(struct tallocr_chunk * chunk, size_t offset, size_t size) {
135
0
    GGML_ASSERT(chunk->n_free_blocks < MAX_FREE_BLOCKS && "out of free blocks");
136
    // insert the new block in the correct position to keep the array sorted by address (to make merging blocks faster)
137
0
    int insert_pos = 0;
138
0
    while (insert_pos < chunk->n_free_blocks && chunk->free_blocks[insert_pos].offset < offset) {
139
0
        insert_pos++;
140
0
    }
141
    // shift all blocks from insert_pos onward to make room for the new block
142
0
    for (int i = chunk->n_free_blocks; i > insert_pos; i--) {
143
0
        chunk->free_blocks[i] = chunk->free_blocks[i-1];
144
0
    }
145
    // insert the new block
146
0
    chunk->free_blocks[insert_pos].offset = offset;
147
0
    chunk->free_blocks[insert_pos].size = size;
148
0
    chunk->n_free_blocks++;
149
0
}
150
151
0
static void ggml_dyn_tallocr_remove_block(struct tallocr_chunk * chunk, int idx) {
152
    // shift all elements after idx by 1 to the left, overwriting the element at idx
153
0
    for (int i = idx; i < chunk->n_free_blocks - 1; i++) {
154
0
        chunk->free_blocks[i] = chunk->free_blocks[i+1];
155
0
    }
156
0
    chunk->n_free_blocks--;
157
0
}
158
159
0
static int ggml_dyn_tallocr_new_chunk(struct ggml_dyn_tallocr * alloc, size_t min_size) {
160
0
    if (alloc->n_chunks >= GGML_VBUFFER_MAX_CHUNKS) {
161
0
        return -1;
162
0
    }
163
0
    struct tallocr_chunk * chunk = calloc(1, sizeof(struct tallocr_chunk));
164
0
    chunk->n_free_blocks = 1;
165
0
    chunk->free_blocks[0].offset = 0;
166
    // available space in a chunk is limited to max_chunk_size, but can be higher if:
167
    // 1. a single tensor exceeds the maximum, and cannot fit any other way
168
    // 2. we are running out of chunks
169
    // backends will either manage to allocate the larger size, or report an error.
170
0
    chunk->free_blocks[0].size = MAX(min_size, alloc->max_chunk_size);
171
0
    if (alloc->n_chunks == GGML_VBUFFER_MAX_CHUNKS - 1) {
172
0
        chunk->free_blocks[0].size = SIZE_MAX/2;
173
0
    }
174
0
    alloc->chunks[alloc->n_chunks] = chunk;
175
0
    alloc->n_chunks++;
176
0
    return alloc->n_chunks - 1;
177
0
}
178
179
#ifdef GGML_ALLOCATOR_DEBUG
180
static void add_allocated_tensor(struct ggml_dyn_tallocr * alloc, struct buffer_address addr, const struct ggml_tensor * tensor) {
181
    for (int i = 0; i < 1024; i++) {
182
        if (alloc->allocated_tensors[i].tensor == NULL) {
183
            alloc->allocated_tensors[i].tensor = tensor;
184
            alloc->allocated_tensors[i].addr = addr;
185
            return;
186
        }
187
    }
188
    GGML_ABORT("out of allocated_tensors");
189
}
190
static void remove_allocated_tensor(struct ggml_dyn_tallocr * alloc, struct buffer_address addr, const struct ggml_tensor * tensor) {
191
    for (int i = 0; i < 1024; i++) {
192
        if (alloc->allocated_tensors[i].addr.chunk == addr.chunk && alloc->allocated_tensors[i].addr.offset == addr.offset) {
193
            alloc->allocated_tensors[i].tensor = NULL;
194
            return;
195
        }
196
    }
197
    GGML_ABORT("tried to free tensor %s not found\n", tensor->name);
198
}
199
#endif
200
201
0
static struct buffer_address ggml_dyn_tallocr_alloc(struct ggml_dyn_tallocr * alloc, size_t size, const struct ggml_tensor * tensor) {
202
0
    size = aligned_offset(NULL, size, alloc->alignment);
203
204
0
    AT_PRINTF("%s: allocating %s (%zu bytes) - ", __func__, tensor->name, size);
205
206
0
    int best_fit_chunk = -1;
207
0
    int best_fit_block = -1;
208
0
    size_t max_avail = 0;
209
210
    // find the best fitting free block besides the last block, within any chunk
211
0
    for (int c = 0; c < alloc->n_chunks; ++c) {
212
0
        struct tallocr_chunk * chunk = alloc->chunks[c];
213
0
        size_t best_fit_size = SIZE_MAX;
214
0
        for (int i = 0; i < chunk->n_free_blocks - 1; i++) {
215
0
            struct free_block * block = &chunk->free_blocks[i];
216
0
            max_avail = MAX(max_avail, block->size);
217
0
            if (block->size >= size && block->size <= best_fit_size) {
218
0
                best_fit_chunk = c;
219
0
                best_fit_block = i;
220
0
                best_fit_size = block->size;
221
0
            }
222
0
        }
223
0
    }
224
225
0
    if (best_fit_block == -1) {
226
        // no suitable block found, try the last block (this may grow a chunks size)
227
0
        int64_t best_reuse = INT64_MIN;
228
0
        for (int c = 0; c < alloc->n_chunks; ++c) {
229
0
            struct tallocr_chunk * chunk = alloc->chunks[c];
230
0
            if (chunk->n_free_blocks > 0) {
231
0
                struct free_block * block = &chunk->free_blocks[chunk->n_free_blocks - 1];
232
0
                max_avail = MAX(max_avail, block->size);
233
0
                int64_t reuse_factor = chunk->max_size - block->offset - size;
234
                // reuse_factor < 0 : amount of extra memory that needs to be allocated
235
                // reuse_factor = 0 : allocated free space exactly matches tensor size
236
                // reuse_factor > 0 : superfluous memory that will remain unused
237
0
                bool better_reuse = best_reuse < 0 && reuse_factor > best_reuse;
238
0
                bool better_fit = reuse_factor >= 0 && reuse_factor < best_reuse;
239
0
                if (block->size >= size && (better_reuse || better_fit)) {
240
0
                    best_fit_chunk = c;
241
0
                    best_fit_block = chunk->n_free_blocks - 1;
242
0
                    best_reuse = reuse_factor;
243
0
                }
244
0
            }
245
0
        }
246
0
    }
247
248
0
    if (best_fit_block == -1) {
249
        // none of the existing chunks have enough space left
250
0
        best_fit_chunk = ggml_dyn_tallocr_new_chunk(alloc, size);
251
0
        best_fit_block = 0;
252
0
    }
253
0
    if (best_fit_chunk == -1) {
254
        // since the last chunk always has virtually endless memory, this should never happen
255
0
        GGML_LOG_ERROR("%s: not enough space in the buffer to allocate %zu bytes, largest block available %zu bytes\n",
256
0
            __func__, size, max_avail);
257
0
        GGML_ABORT("graph allocation: failed to reserve memory");
258
0
    }
259
260
0
    struct tallocr_chunk * chunk = alloc->chunks[best_fit_chunk];
261
0
    struct free_block    * block = &chunk->free_blocks[best_fit_block];
262
0
    struct buffer_address  addr  = {.chunk = best_fit_chunk, .offset = block->offset };
263
0
    block->offset += size;
264
0
    block->size -= size;
265
0
    if (block->size == 0) {
266
        // remove block if empty
267
0
        ggml_dyn_tallocr_remove_block(chunk, best_fit_block);
268
0
    }
269
270
0
    AT_PRINTF("block %d, offset %zu, chunk %d\n", best_fit_block, addr.offset, addr.chunk);
271
272
#ifdef GGML_ALLOCATOR_DEBUG
273
    add_allocated_tensor(alloc, addr, tensor);
274
    size_t cur_max = addr.offset + size;
275
    if (cur_max > chunk->max_size) {
276
        // sort allocated_tensors by chunk/offset
277
        for (int i = 0; i < 1024; i++) {
278
            for (int j = i + 1; j < 1024; j++) {
279
                if (ggml_buffer_address_less(alloc->allocated_tensors[j].addr, alloc->allocated_tensors[i].addr)) {
280
                    const struct ggml_tensor * tmp_tensor = alloc->allocated_tensors[i].tensor;
281
                    struct buffer_address tmp_addr = alloc->allocated_tensors[i].addr;
282
                    alloc->allocated_tensors[i].tensor = alloc->allocated_tensors[j].tensor;
283
                    alloc->allocated_tensors[i].addr = alloc->allocated_tensors[j].addr;
284
                    alloc->allocated_tensors[j].tensor = tmp_tensor;
285
                    alloc->allocated_tensors[j].addr = tmp_addr;
286
                }
287
            }
288
        }
289
        GGML_LOG_DEBUG("max_size[%d] = %.2f MB: tensors: ", addr.chunk, cur_max / 1024.0 / 1024.0);
290
        for (int i = 0; i < 1024; i++) {
291
            if (alloc->allocated_tensors[i].tensor) {
292
                GGML_LOG_DEBUG("%s [%d: %zx-%zx] (%.2f MB) ", alloc->allocated_tensors[i].tensor->name,
293
                    alloc->allocated_tensors[i].addr.chunk,
294
                    alloc->allocated_tensors[i].addr.offset,
295
                    alloc->allocated_tensors[i].addr.offset + ggml_nbytes(alloc->allocated_tensors[i].tensor),
296
                    ggml_nbytes(alloc->allocated_tensors[i].tensor) / 1024.0 / 1024.0);
297
            }
298
        }
299
        GGML_LOG_DEBUG("\n");
300
    }
301
#endif
302
303
0
    chunk->max_size = MAX(chunk->max_size, addr.offset + size);
304
305
0
    return addr;
306
307
0
    GGML_UNUSED(tensor);
308
0
}
309
310
// this is a very naive implementation, but for our case the number of free blocks should be very small
311
0
static void ggml_dyn_tallocr_free_bytes(struct ggml_dyn_tallocr * alloc, struct buffer_address addr, size_t size) {
312
0
    size = aligned_offset(NULL, size, alloc->alignment);
313
314
0
    struct tallocr_chunk * chunk = alloc->chunks[addr.chunk];
315
316
    // see if we can merge with an existing block
317
0
    for (int i = 0; i < chunk->n_free_blocks; i++) {
318
0
        struct free_block * block = &chunk->free_blocks[i];
319
        // check if ptr is at the end of the block
320
0
        if (block->offset + block->size == addr.offset) {
321
0
            block->size += size;
322
            // check if we can merge with the next block
323
0
            if (i < chunk->n_free_blocks - 1) {
324
0
                struct free_block * next = &chunk->free_blocks[i+1];
325
0
                if (block->offset + block->size == next->offset) {
326
0
                    block->size += next->size;
327
0
                    ggml_dyn_tallocr_remove_block(chunk, i+1);
328
0
                }
329
0
            }
330
0
            return;
331
0
        }
332
        // check if ptr is at the beginning of the block
333
0
        if (addr.offset + size == block->offset) {
334
0
            block->offset = addr.offset;
335
0
            block->size += size;
336
            // check if we can merge with the previous block
337
0
            if (i > 0) {
338
0
                struct free_block * prev = &chunk->free_blocks[i-1];
339
0
                if (prev->offset + prev->size == block->offset) {
340
0
                    prev->size += block->size;
341
0
                    ggml_dyn_tallocr_remove_block(chunk, i);
342
0
                }
343
0
            }
344
0
            return;
345
0
        }
346
0
    }
347
    // otherwise, add a new block
348
0
    ggml_dyn_tallocr_insert_block(chunk, addr.offset, size);
349
0
}
350
351
0
static void ggml_dyn_tallocr_reset(struct ggml_dyn_tallocr * alloc) {
352
0
    for (int i = 0; i < GGML_VBUFFER_MAX_CHUNKS; i++) {
353
0
        free(alloc->chunks[i]);
354
0
        alloc->chunks[i] = NULL;
355
0
    }
356
0
    alloc->n_chunks = 0;
357
358
#ifdef GGML_ALLOCATOR_DEBUG
359
    for (int i = 0; i < 1024; i++) {
360
        alloc->allocated_tensors[i].tensor = NULL;
361
    }
362
#endif
363
0
}
364
365
0
static struct ggml_dyn_tallocr * ggml_dyn_tallocr_new(size_t alignment, size_t max_buffer_size) {
366
0
    struct ggml_dyn_tallocr * alloc = (struct ggml_dyn_tallocr *)malloc(sizeof(struct ggml_dyn_tallocr));
367
368
0
    *alloc = (struct ggml_dyn_tallocr) {
369
0
        /*.alignment      = */ alignment,
370
0
        /*.max_chunk_size = */ MIN(max_buffer_size, SIZE_MAX/2), // clamp to avoid overflows
371
0
        /*.chunks         = */ {NULL},
372
0
        /*.n_chunks       = */ 0,
373
#ifdef GGML_ALLOCATOR_DEBUG
374
        /*.allocated_tensors = */ {{0}},
375
#endif
376
0
    };
377
378
0
    ggml_dyn_tallocr_reset(alloc);
379
380
0
    return alloc;
381
0
}
382
383
0
static void ggml_dyn_tallocr_free(struct ggml_dyn_tallocr * alloc) {
384
0
    for (int i = 0; i < alloc->n_chunks; ++i) {
385
0
        free(alloc->chunks[i]);
386
0
    }
387
0
    free(alloc);
388
0
}
389
390
0
static size_t ggml_dyn_tallocr_max_size(struct ggml_dyn_tallocr * alloc, int chunk) {
391
0
    return chunk < alloc->n_chunks ? alloc->chunks[chunk]->max_size : 0;
392
0
}
393
394
395
// virtual buffer with contiguous memory range, split into multiple backend buffers (chunks)
396
397
struct vbuffer {
398
    ggml_backend_buffer_t chunks[GGML_VBUFFER_MAX_CHUNKS];
399
};
400
401
0
static void ggml_vbuffer_free(struct vbuffer * buf) {
402
0
    if (buf == NULL) {
403
0
        return;
404
0
    }
405
0
    for (int i = 0; i < GGML_VBUFFER_MAX_CHUNKS; ++i) {
406
0
        ggml_backend_buffer_free(buf->chunks[i]);
407
0
    }
408
0
    free(buf);
409
0
}
410
411
0
static size_t ggml_vbuffer_chunk_size(struct vbuffer * buf, int chunk) {
412
0
    return buf->chunks[chunk] ? ggml_backend_buffer_get_size(buf->chunks[chunk]) : 0;
413
0
}
414
415
0
static size_t ggml_vbuffer_size(struct vbuffer * buf) {
416
0
    size_t size = 0;
417
0
    for (int i = 0; i < GGML_VBUFFER_MAX_CHUNKS && buf->chunks[i]; ++i) {
418
0
        size += ggml_backend_buffer_get_size(buf->chunks[i]);
419
0
    }
420
0
    return size;
421
0
}
422
423
0
static struct vbuffer * ggml_vbuffer_alloc(ggml_backend_buffer_type_t buft, const struct ggml_dyn_tallocr * talloc, enum ggml_backend_buffer_usage usage) {
424
0
    struct vbuffer * buf = (struct vbuffer *)calloc(1, sizeof(struct vbuffer));
425
0
    if (buf == NULL) {
426
0
        return NULL;
427
0
    }
428
429
0
    for (int n = 0; n < talloc->n_chunks; n++) {
430
0
        size_t chunk_size = talloc->chunks[n]->max_size;
431
0
        buf->chunks[n] = ggml_backend_buft_alloc_buffer(buft, chunk_size);
432
0
        if (buf->chunks[n] == NULL) {
433
0
            ggml_vbuffer_free(buf);
434
0
            return NULL;
435
0
        }
436
0
        ggml_backend_buffer_set_usage(buf->chunks[n], usage);
437
0
    }
438
0
    return buf;
439
0
}
440
441
0
static void ggml_vbuffer_tensor_alloc(struct vbuffer * buf, struct ggml_tensor * tensor, struct buffer_address buf_addr) {
442
0
    void * base = ggml_backend_buffer_get_base(buf->chunks[buf_addr.chunk]);
443
0
    void * addr = (char *)base + buf_addr.offset;
444
0
    ggml_backend_tensor_alloc(buf->chunks[buf_addr.chunk], tensor, addr);
445
0
}
446
447
0
static void ggml_vbuffer_reset(struct vbuffer * buf) {
448
0
    for (int i = 0; i < GGML_VBUFFER_MAX_CHUNKS && buf->chunks[i]; ++i) {
449
0
        ggml_backend_buffer_reset(buf->chunks[i]);
450
0
    }
451
0
}
452
453
454
/////////////////////////////////////
455
456
// graph allocator
457
458
struct hash_node {
459
    int n_children;
460
    int n_views;
461
    int buffer_id;
462
    struct buffer_address addr;
463
    bool allocated;
464
};
465
466
struct tensor_alloc {
467
    int buffer_id;
468
    struct buffer_address addr;
469
    size_t size_max; // 0 = pre-allocated, unused, or view
470
};
471
472
struct leaf_alloc {
473
    struct tensor_alloc leaf;
474
};
475
476
struct node_alloc {
477
    struct tensor_alloc dst;
478
    struct tensor_alloc src[GGML_MAX_SRC];
479
};
480
481
struct ggml_gallocr {
482
    ggml_backend_buffer_type_t * bufts; // [n_buffers]
483
    struct vbuffer ** buffers; // [n_buffers]
484
    struct ggml_dyn_tallocr ** buf_tallocs; // [n_buffers]
485
    int n_buffers;
486
487
    struct ggml_hash_set hash_set;
488
    struct hash_node * hash_values; // [hash_set.size]
489
490
    struct node_alloc * node_allocs; // [n_nodes]
491
    int n_nodes;
492
493
    struct leaf_alloc * leaf_allocs; // [n_leafs]
494
    int n_leafs;
495
};
496
497
0
ggml_gallocr_t ggml_gallocr_new_n(ggml_backend_buffer_type_t * bufts, int n_bufs) {
498
0
    ggml_gallocr_t galloc = (ggml_gallocr_t)calloc(1, sizeof(struct ggml_gallocr));
499
0
    GGML_ASSERT(galloc != NULL);
500
501
0
    galloc->bufts = calloc(n_bufs, sizeof(ggml_backend_buffer_type_t));
502
0
    GGML_ASSERT(galloc->bufts != NULL);
503
504
0
    galloc->buffers = calloc(n_bufs, sizeof(struct vbuffer *));
505
0
    GGML_ASSERT(galloc->buffers != NULL);
506
507
0
    galloc->buf_tallocs = calloc(n_bufs, sizeof(struct ggml_dyn_tallocr *));
508
0
    GGML_ASSERT(galloc->buf_tallocs != NULL);
509
510
0
    for (int i = 0; i < n_bufs; i++) {
511
0
        galloc->bufts[i] = bufts[i];
512
0
        galloc->buffers[i] = NULL;
513
514
        // check if the same buffer type is used multiple times and reuse the same allocator
515
0
        for (int j = 0; j < i; j++) {
516
0
            if (bufts[i] == bufts[j]) {
517
0
                galloc->buf_tallocs[i] = galloc->buf_tallocs[j];
518
0
                break;
519
0
            }
520
0
        }
521
522
0
        if (galloc->buf_tallocs[i] == NULL) {
523
0
            size_t alignment = ggml_backend_buft_get_alignment(bufts[i]);
524
0
            size_t max_size = ggml_backend_buft_get_max_size(bufts[i]);
525
0
            galloc->buf_tallocs[i] = ggml_dyn_tallocr_new(alignment, max_size);
526
0
        }
527
0
    }
528
0
    galloc->n_buffers = n_bufs;
529
530
0
    return galloc;
531
0
}
532
533
0
ggml_gallocr_t ggml_gallocr_new(ggml_backend_buffer_type_t buft) {
534
0
    return ggml_gallocr_new_n(&buft, 1);
535
0
}
536
537
0
void ggml_gallocr_free(ggml_gallocr_t galloc) {
538
0
    if (galloc == NULL) {
539
0
        return;
540
0
    }
541
542
0
    for (int i = 0; i < galloc->n_buffers; i++) {
543
0
        if (galloc->buffers != NULL) {
544
            // skip if already freed
545
0
            bool freed = false;
546
0
            for (int j = 0; j < i; j++) {
547
0
                if (galloc->buffers[j] == galloc->buffers[i]) {
548
0
                    freed = true;
549
0
                    break;
550
0
                }
551
0
            }
552
0
            if (!freed) {
553
0
                ggml_vbuffer_free(galloc->buffers[i]);
554
0
            }
555
0
        }
556
0
        if (galloc->buf_tallocs != NULL) {
557
            // skip if already freed
558
0
            bool freed = false;
559
0
            for (int j = 0; j < i; j++) {
560
0
                if (galloc->buf_tallocs[j] == galloc->buf_tallocs[i]) {
561
0
                    freed = true;
562
0
                    break;
563
0
                }
564
0
            }
565
0
            if (!freed) {
566
0
                ggml_dyn_tallocr_free(galloc->buf_tallocs[i]);
567
0
            }
568
0
        }
569
0
    }
570
571
0
    ggml_hash_set_free(&galloc->hash_set);
572
0
    free(galloc->hash_values);
573
0
    free(galloc->bufts);
574
0
    free(galloc->buffers);
575
0
    free(galloc->buf_tallocs);
576
0
    free(galloc->node_allocs);
577
0
    free(galloc->leaf_allocs);
578
0
    free(galloc);
579
0
}
580
581
typedef struct ggml_gallocr * ggml_gallocr_t;
582
583
0
static struct hash_node * ggml_gallocr_hash_get(ggml_gallocr_t galloc, struct ggml_tensor * t) {
584
0
    size_t i = ggml_hash_find_or_insert(&galloc->hash_set, t);
585
0
    return &galloc->hash_values[i];
586
0
}
587
588
0
static bool ggml_gallocr_is_own(ggml_gallocr_t galloc, struct ggml_tensor * t) {
589
0
    return ggml_gallocr_hash_get(galloc, t)->allocated;
590
0
}
591
592
0
static bool ggml_gallocr_is_allocated(ggml_gallocr_t galloc, struct ggml_tensor * t) {
593
0
    return t->data != NULL // tensor data already set externally
594
0
        || t->buffer // tensor on external buffer (but not yet allocated)
595
0
        || ggml_gallocr_is_own(galloc, t); // tensor will be allocated by galloc
596
0
}
597
598
// free the extra space at the end if the new tensor is smaller
599
0
static void ggml_gallocr_free_extra_space(ggml_gallocr_t galloc, struct ggml_tensor * node, struct ggml_tensor * parent) {
600
0
    struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
601
0
    struct hash_node * p_hn = ggml_gallocr_hash_get(galloc, parent);
602
603
0
    size_t parent_size = ggml_backend_buft_get_alloc_size(galloc->bufts[p_hn->buffer_id], parent);
604
0
    size_t node_size = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], node);
605
606
0
    GGML_ASSERT(parent_size >= node_size);
607
608
    // note: we want after the freeing the chunks to continue to be aligned
609
0
    struct ggml_dyn_tallocr * p_alloc = galloc->buf_tallocs[p_hn->buffer_id];
610
0
    parent_size = aligned_offset(NULL, parent_size, p_alloc->alignment);
611
0
    node_size = aligned_offset(NULL, node_size, p_alloc->alignment);
612
613
0
    if (parent_size > node_size) {
614
0
        struct buffer_address p_addr = p_hn->addr;
615
0
        p_addr.offset += node_size;
616
0
        size_t extra_size = parent_size - node_size;
617
0
        AT_PRINTF("freeing extra %zu bytes from parent %s for %s\n", extra_size, parent->name, node->name);
618
0
        ggml_dyn_tallocr_free_bytes(p_alloc, p_addr, extra_size);
619
0
    }
620
0
}
621
622
0
static void ggml_gallocr_allocate_node(ggml_gallocr_t galloc, struct ggml_tensor * node, int buffer_id) {
623
0
    GGML_ASSERT(buffer_id >= 0);
624
0
    struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
625
626
0
    if (!ggml_gallocr_is_allocated(galloc, node) && !ggml_impl_is_view(node)) {
627
0
        hn->allocated = true;
628
0
        assert(hn->addr.offset == 0);
629
630
        // try to reuse a parent's buffer (inplace)
631
0
        if (ggml_op_can_inplace(node->op)) {
632
0
            for (int i = 0; i < GGML_MAX_SRC; i++) {
633
0
                struct ggml_tensor * parent = node->src[i];
634
0
                if (parent == NULL) {
635
0
                    continue;
636
0
                }
637
638
                // if the node's data is external, then we cannot re-use it
639
0
                if (!ggml_gallocr_is_own(galloc, parent)) {
640
0
                    AT_PRINTF("not reusing parent %s for %s as %p is external\n", parent->name, node->name, parent->data);
641
0
                    continue;
642
0
                }
643
644
                // outputs cannot be reused
645
0
                if (parent->flags & GGML_TENSOR_FLAG_OUTPUT || (parent->view_src != NULL && parent->view_src->flags & GGML_TENSOR_FLAG_OUTPUT)) {
646
0
                    AT_PRINTF("not reusing parent %s for %s as it is an output\n", parent->name, node->name);
647
0
                    continue;
648
0
                }
649
650
0
                if (!ggml_are_same_layout(node, parent)) {
651
0
                    AT_PRINTF("not reusing parent %s for %s as layouts are different\n", parent->name, node->name);
652
0
                    continue;
653
0
                }
654
655
0
                struct hash_node * p_hn = ggml_gallocr_hash_get(galloc, parent);
656
0
                if (p_hn->n_children == 1 && p_hn->n_views == 0) {
657
0
                    if (ggml_impl_is_view(parent)) {
658
0
                        struct ggml_tensor * view_src = parent->view_src;
659
0
                        struct hash_node * view_src_hn = ggml_gallocr_hash_get(galloc, view_src);
660
0
                        if (view_src_hn->n_views == 1 && view_src_hn->n_children == 0 && view_src->data == parent->data) {
661
0
                            AT_PRINTF("reusing view parent %s (%s) for %s\n", parent->name, view_src->name, node->name);
662
0
                            assert(view_src_hn->addr.chunk == p_hn->addr.chunk && view_src_hn->addr.offset == p_hn->addr.offset);
663
0
                            hn->buffer_id = p_hn->buffer_id;
664
0
                            hn->addr = p_hn->addr;
665
0
                            p_hn->allocated = false; // avoid freeing the parent
666
0
                            view_src_hn->allocated = false;
667
0
                            ggml_gallocr_free_extra_space(galloc, node, view_src);
668
0
                            return;
669
0
                        }
670
0
                    } else {
671
0
                        AT_PRINTF("reusing parent %s for %s\n", parent->name, node->name);
672
0
                        hn->buffer_id = p_hn->buffer_id;
673
0
                        hn->addr = p_hn->addr;
674
0
                        p_hn->allocated = false; // avoid freeing the parent
675
0
                        ggml_gallocr_free_extra_space(galloc, node, parent);
676
0
                        return;
677
0
                    }
678
0
                }
679
0
            }
680
0
        }
681
        // allocate tensor from the buffer
682
0
        struct ggml_dyn_tallocr * alloc = galloc->buf_tallocs[buffer_id];
683
0
        ggml_backend_buffer_type_t buft = galloc->bufts[buffer_id];
684
0
        size_t size = ggml_backend_buft_get_alloc_size(buft, node);
685
0
        hn->buffer_id = buffer_id;
686
0
        hn->addr = ggml_dyn_tallocr_alloc(alloc, size, node);
687
0
    }
688
0
}
689
690
0
static void ggml_gallocr_free_node(ggml_gallocr_t galloc, struct ggml_tensor * node) {
691
    // graph outputs are never freed
692
0
    if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
693
0
        AT_PRINTF("not freeing output %s\n", node->name);
694
0
        return;
695
0
    }
696
697
0
    struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
698
0
    int buffer_id = hn->buffer_id;
699
0
    struct ggml_dyn_tallocr * alloc = galloc->buf_tallocs[buffer_id];
700
0
    ggml_backend_buffer_type_t buft = galloc->bufts[buffer_id];
701
0
    size_t size = ggml_backend_buft_get_alloc_size(buft, node);
702
703
0
    AT_PRINTF("%s: freeing %s at {chunk=%d, offset=%zu} (%zu bytes) - n_free_blocks = %d\n",
704
0
        __func__, node->name, hn->addr.chunk, hn->addr.offset, size, alloc->chunks[hn->addr.chunk]->n_free_blocks);
705
#ifdef GGML_ALLOCATOR_DEBUG
706
    remove_allocated_tensor(alloc, hn->addr, node);
707
#endif
708
709
0
    ggml_dyn_tallocr_free_bytes(alloc, hn->addr, size);
710
0
    hn->allocated = false;
711
0
}
712
713
0
static int get_node_buffer_id(const int * node_buffer_ids, int i) {
714
0
    return node_buffer_ids ? node_buffer_ids[i] : 0;
715
0
}
716
717
0
static void ggml_gallocr_alloc_graph_impl(ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids, const int * leaf_buffer_ids) {
718
    // clear hash tables
719
0
    ggml_hash_set_reset(&galloc->hash_set);
720
0
    memset(galloc->hash_values, 0, sizeof(struct hash_node) * galloc->hash_set.size);
721
722
    // allocate leafs
723
    // these may be tensors that the application is not using in the graph, but may still want to allocate for other purposes
724
0
    for (int i = 0; i < graph->n_leafs; i++) {
725
0
        struct ggml_tensor * leaf = graph->leafs[i];
726
0
        ggml_gallocr_allocate_node(galloc, leaf, get_node_buffer_id(leaf_buffer_ids, i));
727
0
    }
728
729
    // count number of children and views
730
    // allocate other graph inputs and leafs first to avoid overwriting them
731
0
    for (int i = 0; i < graph->n_nodes; i++) {
732
0
        struct ggml_tensor * node = graph->nodes[i];
733
734
        // TODO: better way to add external dependencies
735
        // GGML_OP_NONE does not appear normally in the graph nodes, but is used by ggml-backend to add dependencies to
736
        // control when some tensors are allocated and freed. in this case, the dependencies are in `src`, but the node
737
        // itself is never used and should not be considered a dependency
738
0
        if (ggml_impl_is_view(node) && node->op != GGML_OP_NONE) {
739
0
            struct ggml_tensor * view_src = node->view_src;
740
0
            ggml_gallocr_hash_get(galloc, view_src)->n_views += 1;
741
0
        }
742
743
0
        if (node->flags & GGML_TENSOR_FLAG_INPUT) {
744
0
            ggml_gallocr_allocate_node(galloc, graph->nodes[i], get_node_buffer_id(node_buffer_ids, i));
745
0
        }
746
747
0
        for (int j = 0; j < GGML_MAX_SRC; j++) {
748
0
            struct ggml_tensor * src = node->src[j];
749
0
            if (src == NULL) {
750
0
                continue;
751
0
            }
752
753
0
            ggml_gallocr_hash_get(galloc, src)->n_children += 1;
754
755
            // allocate explicit inputs
756
0
            if (src->flags & GGML_TENSOR_FLAG_INPUT) {
757
0
                ggml_gallocr_allocate_node(galloc, src, get_node_buffer_id(node_buffer_ids, i));
758
0
            }
759
0
        }
760
0
    }
761
762
    // allocate tensors
763
0
    for (int i = 0; i < graph->n_nodes; i++) {
764
0
        struct ggml_tensor * node = graph->nodes[i];
765
0
        int buffer_id = get_node_buffer_id(node_buffer_ids, i);
766
767
        // allocate parents (only leafs need to be allocated at this point)
768
0
        for (int j = 0; j < GGML_MAX_SRC; j++) {
769
0
            struct ggml_tensor * parent = node->src[j];
770
0
            if (parent == NULL) {
771
0
                continue;
772
0
            }
773
0
            ggml_gallocr_allocate_node(galloc, parent, buffer_id);
774
0
        }
775
776
        // allocate node
777
0
        ggml_gallocr_allocate_node(galloc, node, buffer_id);
778
779
0
        AT_PRINTF("exec: %s (%s) <= ", ggml_op_desc(node), node->name);
780
0
        for (int j = 0; j < GGML_MAX_SRC; j++) {
781
0
            struct ggml_tensor * parent = node->src[j];
782
0
            if (parent == NULL) {
783
0
                continue;
784
0
            }
785
0
            AT_PRINTF("%s", parent->name);
786
0
            if (j < GGML_MAX_SRC - 1 && node->src[j + 1] != NULL) {
787
0
                AT_PRINTF(", ");
788
0
            }
789
0
        }
790
0
        AT_PRINTF("\n");
791
792
        // update parents
793
0
        for (int j = 0; j < GGML_MAX_SRC; j++) {
794
0
            struct ggml_tensor * parent = node->src[j];
795
0
            if (parent == NULL) {
796
0
                continue;
797
0
            }
798
0
            struct hash_node * p_hn = ggml_gallocr_hash_get(galloc, parent);
799
0
            p_hn->n_children -= 1;
800
801
0
            AT_PRINTF("parent %s: %d children, %d views, allocated: %d\n",
802
0
                parent->name, p_hn->n_children, p_hn->n_views, p_hn->allocated);
803
804
0
            if (p_hn->n_children == 0 && p_hn->n_views == 0) {
805
0
                if (ggml_impl_is_view(parent)) {
806
0
                    struct ggml_tensor * view_src = parent->view_src;
807
0
                    struct hash_node * view_src_hn = ggml_gallocr_hash_get(galloc, view_src);
808
0
                    view_src_hn->n_views -= 1;
809
0
                    AT_PRINTF("view_src %s: %d children, %d views\n",
810
0
                        view_src->name, view_src_hn->n_children, view_src_hn->n_views);
811
0
                    if (view_src_hn->n_views == 0 && view_src_hn->n_children == 0 && view_src_hn->allocated) {
812
0
                        ggml_gallocr_free_node(galloc, view_src);
813
0
                    }
814
0
                }
815
0
                else if (p_hn->allocated) {
816
0
                    ggml_gallocr_free_node(galloc, parent);
817
0
                }
818
0
            }
819
0
            AT_PRINTF("\n");
820
0
        }
821
0
    }
822
0
}
823
824
static bool ggml_gallocr_reserve_n_impl(
825
0
        ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids, const int * leaf_buffer_ids, bool no_alloc) {
826
0
    size_t min_hash_size = graph->n_nodes + graph->n_leafs;
827
    // add 25% margin to avoid hash collisions
828
0
    min_hash_size += min_hash_size / 4;
829
830
    // initialize hash table
831
0
    if (galloc->hash_set.size < min_hash_size) {
832
0
        ggml_hash_set_free(&galloc->hash_set);
833
0
        galloc->hash_set = ggml_hash_set_new(min_hash_size);
834
0
        GGML_ASSERT(galloc->hash_set.keys != NULL);
835
836
0
        free(galloc->hash_values);
837
0
        galloc->hash_values = malloc(sizeof(struct hash_node) * galloc->hash_set.size);
838
0
        GGML_ASSERT(galloc->hash_values != NULL);
839
0
    }
840
841
    // reset allocators
842
0
    for (int i = 0; i < galloc->n_buffers; i++) {
843
0
        ggml_dyn_tallocr_reset(galloc->buf_tallocs[i]);
844
0
    }
845
846
    // allocate in hash table
847
0
    ggml_gallocr_alloc_graph_impl(galloc, graph, node_buffer_ids, leaf_buffer_ids);
848
849
    // set the node_allocs from the hash table
850
0
    if (galloc->n_nodes < graph->n_nodes) {
851
0
        free(galloc->node_allocs);
852
0
        galloc->node_allocs = calloc(graph->n_nodes, sizeof(struct node_alloc));
853
0
        GGML_ASSERT(galloc->node_allocs != NULL);
854
0
    }
855
0
    galloc->n_nodes = graph->n_nodes;
856
0
    for (int i = 0; i < graph->n_nodes; i++) {
857
0
        struct ggml_tensor * node = graph->nodes[i];
858
0
        struct node_alloc * node_alloc = &galloc->node_allocs[i];
859
0
        if (node->view_src || node->data) {
860
0
            node_alloc->dst.buffer_id = -1;
861
0
            node_alloc->dst.addr = GGML_BUFFER_ADDRESS_INVALID;
862
0
            node_alloc->dst.size_max = 0;
863
0
        } else {
864
0
            struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
865
0
            node_alloc->dst.buffer_id = hn->buffer_id;
866
0
            node_alloc->dst.addr = hn->addr;
867
0
            node_alloc->dst.size_max  = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], node);
868
0
        }
869
0
        for (int j = 0; j < GGML_MAX_SRC; j++) {
870
0
            struct ggml_tensor * src = node->src[j];
871
0
            if (!src || src->view_src || src->data) {
872
0
                node_alloc->src[j].buffer_id = -1;
873
0
                node_alloc->src[j].addr = GGML_BUFFER_ADDRESS_INVALID;
874
0
                node_alloc->src[j].size_max = 0;
875
0
            } else {
876
0
                struct hash_node * hn = ggml_gallocr_hash_get(galloc, src);
877
0
                node_alloc->src[j].buffer_id = hn->buffer_id;
878
0
                node_alloc->src[j].addr = hn->addr;
879
0
                node_alloc->src[j].size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], src);
880
0
            }
881
0
        }
882
0
    }
883
0
    if (galloc->n_leafs < graph->n_leafs) {
884
0
        free(galloc->leaf_allocs);
885
0
        galloc->leaf_allocs = calloc(graph->n_leafs, sizeof(galloc->leaf_allocs[0]));
886
0
        GGML_ASSERT(galloc->leaf_allocs != NULL);
887
0
    }
888
0
    galloc->n_leafs = graph->n_leafs;
889
0
    for (int i = 0; i < graph->n_leafs; i++) {
890
0
        struct ggml_tensor * leaf = graph->leafs[i];
891
0
        struct hash_node * hn = ggml_gallocr_hash_get(galloc, leaf);
892
0
        if (leaf->view_src || leaf->data) {
893
0
            galloc->leaf_allocs[i].leaf.buffer_id = -1;
894
0
            galloc->leaf_allocs[i].leaf.addr = GGML_BUFFER_ADDRESS_INVALID;
895
0
            galloc->leaf_allocs[i].leaf.size_max = 0;
896
0
        } else {
897
0
            galloc->leaf_allocs[i].leaf.buffer_id = hn->buffer_id;
898
0
            galloc->leaf_allocs[i].leaf.addr = hn->addr;
899
0
            galloc->leaf_allocs[i].leaf.size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], leaf);
900
0
        }
901
0
    }
902
903
    // reallocate buffers if needed
904
0
    for (int i = 0; i < galloc->n_buffers; i++) {
905
        // if the buffer type is used multiple times, we reuse the same buffer
906
0
        for (int j = 0; j < i; j++) {
907
0
            if (galloc->buf_tallocs[j] == galloc->buf_tallocs[i]) {
908
0
                galloc->buffers[i] = galloc->buffers[j];
909
0
                break;
910
0
            }
911
0
        }
912
913
        // even if there are no tensors allocated in this buffer, we still need to allocate it to initialize views
914
0
        bool realloc = galloc->buffers[i] == NULL;
915
0
        size_t new_size = 0;
916
0
        for (int c = 0; c < galloc->buf_tallocs[i]->n_chunks; c++) {
917
0
            size_t cur_chunk_size = galloc->buffers[i] ? ggml_vbuffer_chunk_size(galloc->buffers[i], c) : 0;
918
0
            size_t new_chunk_size = ggml_dyn_tallocr_max_size(galloc->buf_tallocs[i], c);
919
0
            new_size += new_chunk_size;
920
0
            if (new_chunk_size > cur_chunk_size) {
921
0
                realloc = true;
922
0
            }
923
0
        }
924
0
        if (realloc) {
925
#ifndef NDEBUG
926
            {
927
                size_t cur_size = galloc->buffers[i] ? ggml_vbuffer_size(galloc->buffers[i]) : 0;
928
                if (cur_size > 0) {
929
                    GGML_LOG_DEBUG("%s: reallocating %s buffer from size %.02f MiB to %.02f MiB\n",
930
                        __func__, ggml_backend_buft_name(galloc->bufts[i]), cur_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
931
                }
932
            }
933
#endif
934
0
            ggml_vbuffer_free(galloc->buffers[i]);
935
0
            if (no_alloc) {
936
0
                galloc->buffers[i] = NULL;
937
0
            } else {
938
0
                galloc->buffers[i] = ggml_vbuffer_alloc(galloc->bufts[i], galloc->buf_tallocs[i], GGML_BACKEND_BUFFER_USAGE_COMPUTE);
939
0
                if (galloc->buffers[i] == NULL) {
940
0
                    GGML_LOG_ERROR("%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(galloc->bufts[i]), new_size);
941
0
                    return false;
942
0
                }
943
0
            }
944
0
        }
945
0
    }
946
947
0
    return true;
948
0
}
949
950
void ggml_gallocr_reserve_n_size(
951
0
        ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids, const int * leaf_buffer_ids, size_t * sizes) {
952
0
    GGML_ASSERT(ggml_gallocr_reserve_n_impl(galloc, graph, node_buffer_ids, leaf_buffer_ids, /*no_alloc =*/ true));
953
0
    for (int i = 0; i < galloc->n_buffers; i++) {
954
0
        sizes[i] = 0;
955
0
        for (int c = 0; c < galloc->buf_tallocs[i]->n_chunks; c++) {
956
0
            sizes[i] += galloc->buf_tallocs[i]->chunks[c]->max_size;
957
0
        }
958
0
    }
959
0
}
960
961
0
bool ggml_gallocr_reserve_n(ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids, const int * leaf_buffer_ids) {
962
0
    return ggml_gallocr_reserve_n_impl(galloc, graph, node_buffer_ids, leaf_buffer_ids, /*no_alloc =*/ false);
963
0
}
964
965
0
bool ggml_gallocr_reserve(ggml_gallocr_t galloc, struct ggml_cgraph *graph) {
966
0
    return ggml_gallocr_reserve_n(galloc, graph, NULL, NULL);
967
0
}
968
969
0
static void ggml_gallocr_init_tensor(ggml_gallocr_t galloc, struct ggml_tensor * tensor, struct tensor_alloc * tensor_alloc) {
970
0
    int buffer_id = tensor_alloc->buffer_id;
971
0
    assert(tensor->data || tensor->view_src || ggml_backend_buft_get_alloc_size(galloc->bufts[buffer_id], tensor) <= tensor_alloc->size_max);
972
973
0
    if (tensor->view_src != NULL) {
974
0
        if (tensor->buffer == NULL) {
975
0
            assert(tensor_alloc->addr.offset == SIZE_MAX);
976
0
            if (tensor->view_src->buffer == NULL) {
977
                // this tensor was allocated without ggml-backend
978
0
                return;
979
0
            }
980
0
            ggml_backend_view_init(tensor);
981
0
        }
982
0
    } else {
983
0
        if (tensor->data == NULL) {
984
0
            assert(tensor_alloc->addr.offset != SIZE_MAX);
985
0
            assert(ggml_backend_buft_get_alloc_size(galloc->bufts[buffer_id], tensor) <= tensor_alloc->size_max);
986
0
            ggml_vbuffer_tensor_alloc(galloc->buffers[buffer_id], tensor, tensor_alloc->addr);
987
0
        } else {
988
0
            if (tensor->buffer == NULL) {
989
                // this tensor was allocated without ggml-backend
990
0
                return;
991
0
            }
992
0
        }
993
0
    }
994
0
}
995
996
0
static bool ggml_gallocr_node_needs_realloc(ggml_gallocr_t galloc, struct ggml_tensor * node, struct tensor_alloc * talloc) {
997
0
    size_t node_size = 0;
998
0
    if (!node->data && !node->view_src) {
999
        // If we previously had data but don't now then reallocate
1000
0
        if (talloc->buffer_id < 0) {
1001
0
            return false;
1002
0
        }
1003
0
        node_size = ggml_backend_buft_get_alloc_size(galloc->bufts[talloc->buffer_id], node);
1004
0
    }
1005
0
    return talloc->size_max >= node_size;
1006
0
}
1007
1008
0
static bool ggml_gallocr_needs_realloc(ggml_gallocr_t galloc, struct ggml_cgraph * graph) {
1009
0
    if (galloc->n_nodes != graph->n_nodes) {
1010
#ifndef NDEBUG
1011
        GGML_LOG_DEBUG("%s: graph has different number of nodes\n", __func__);
1012
#endif
1013
0
        return true;
1014
0
    }
1015
1016
0
    if (galloc->n_leafs != graph->n_leafs) {
1017
#ifndef NDEBUG
1018
        GGML_LOG_DEBUG("%s: graph has different number of leafs\n", __func__);
1019
#endif
1020
0
        return true;
1021
0
    }
1022
1023
0
    for (int i = 0; i < graph->n_nodes; i++) {
1024
0
        struct ggml_tensor * node = graph->nodes[i];
1025
0
        struct node_alloc * node_alloc = &galloc->node_allocs[i];
1026
1027
0
        if (!ggml_gallocr_node_needs_realloc(galloc, node, &node_alloc->dst)) {
1028
#ifndef NDEBUG
1029
            GGML_LOG_DEBUG("%s: node %s is not valid\n", __func__, node->name);
1030
#endif
1031
0
            return true;
1032
0
        }
1033
1034
0
        for (int j = 0; j < GGML_MAX_SRC; j++) {
1035
0
            struct ggml_tensor * src = node->src[j];
1036
0
            if (src == NULL) {
1037
0
                continue;
1038
0
            }
1039
0
            if (!ggml_gallocr_node_needs_realloc(galloc, src, &node_alloc->src[j])) {
1040
#ifndef NDEBUG
1041
                GGML_LOG_DEBUG("%s: src %d (%s) of node %s is not valid\n", __func__, j, src->name, node->name);
1042
#endif
1043
0
                return true;
1044
0
            }
1045
0
        }
1046
0
    }
1047
1048
0
    return false;
1049
0
}
1050
1051
0
bool ggml_gallocr_alloc_graph(ggml_gallocr_t galloc, struct ggml_cgraph * graph) {
1052
0
    if (ggml_gallocr_needs_realloc(galloc, graph)) {
1053
0
        if (galloc->n_buffers == 1) {
1054
#ifndef NDEBUG
1055
            GGML_LOG_DEBUG("%s: reallocating buffers automatically\n", __func__);
1056
#endif
1057
0
            if (!ggml_gallocr_reserve(galloc, graph)) {
1058
0
                return false;
1059
0
            }
1060
0
        } else {
1061
#ifndef NDEBUG
1062
            GGML_LOG_DEBUG("%s: cannot reallocate multi buffer graph automatically, call reserve\n", __func__);
1063
#endif
1064
0
            return false;
1065
0
        }
1066
0
    }
1067
1068
    // reset buffers
1069
0
    for (int i = 0; i < galloc->n_buffers; i++) {
1070
0
        if (galloc->buffers[i] != NULL) {
1071
0
            ggml_vbuffer_reset(galloc->buffers[i]);
1072
0
        }
1073
0
    }
1074
1075
    // allocate the graph tensors from the previous assignments
1076
    // leafs
1077
0
    for (int i = 0; i < graph->n_leafs; i++) {
1078
0
        struct ggml_tensor * leaf = graph->leafs[i];
1079
0
        struct leaf_alloc * leaf_alloc = &galloc->leaf_allocs[i];
1080
0
        ggml_gallocr_init_tensor(galloc, leaf, &leaf_alloc->leaf);
1081
0
    }
1082
    // nodes
1083
0
    for (int i = 0; i < graph->n_nodes; i++) {
1084
0
        struct ggml_tensor * node = graph->nodes[i];
1085
0
        struct node_alloc * node_alloc = &galloc->node_allocs[i];
1086
0
        for (int j = 0; j < GGML_MAX_SRC; j++) {
1087
0
            struct ggml_tensor * src = node->src[j];
1088
0
            if (src == NULL) {
1089
0
                continue;
1090
0
            }
1091
0
            ggml_gallocr_init_tensor(galloc, src, &node_alloc->src[j]);
1092
0
        }
1093
0
        ggml_gallocr_init_tensor(galloc, node, &node_alloc->dst);
1094
0
    }
1095
1096
0
    return true;
1097
0
}
1098
1099
0
size_t ggml_gallocr_get_buffer_size(ggml_gallocr_t galloc, int buffer_id) {
1100
0
    GGML_ASSERT(buffer_id >= 0 && buffer_id < galloc->n_buffers);
1101
1102
0
    if (galloc->buffers[buffer_id] == NULL) {
1103
0
        return 0;
1104
0
    }
1105
1106
0
    for (int i = 0; i < buffer_id; i++) {
1107
0
        if (galloc->buffers[i] == galloc->buffers[buffer_id]) {
1108
            // this buffer is the same as a previous one due to the same buffer type being used multiple times
1109
            // only return the buffer size the first time it appears to avoid double counting
1110
0
            return 0;
1111
0
        }
1112
0
    }
1113
1114
0
    return ggml_vbuffer_size(galloc->buffers[buffer_id]);
1115
0
}
1116
1117
// utils
1118
1119
0
static void free_buffers(ggml_backend_buffer_t ** buffers, const size_t * n_buffers) {
1120
0
    for (size_t i = 0; i < *n_buffers; i++) {
1121
0
        ggml_backend_buffer_free((*buffers)[i]);
1122
0
    }
1123
0
    free(*buffers);
1124
0
}
1125
1126
static bool alloc_tensor_range(struct ggml_context * ctx,
1127
        struct ggml_tensor * first, struct ggml_tensor * last,
1128
        ggml_backend_buffer_type_t buft, size_t size,
1129
0
        ggml_backend_buffer_t ** buffers, size_t * n_buffers) {
1130
1131
0
    ggml_backend_buffer_t buffer = ggml_backend_buft_alloc_buffer(buft, size);
1132
0
    if (buffer == NULL) {
1133
0
        GGML_LOG_ERROR("%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(buft), size);
1134
0
        free_buffers(buffers, n_buffers);
1135
0
        return false;
1136
0
    }
1137
1138
0
    *buffers = realloc(*buffers, sizeof(ggml_backend_buffer_t) * (*n_buffers + 1));
1139
0
    (*buffers)[(*n_buffers)++] = buffer;
1140
1141
0
    struct ggml_tallocr tallocr = ggml_tallocr_new(buffer);
1142
1143
0
    for (struct ggml_tensor * t = first; t != last; t = ggml_get_next_tensor(ctx, t)) {
1144
0
        enum ggml_status status = GGML_STATUS_SUCCESS;
1145
0
        if (t->data == NULL) {
1146
0
            if (t->view_src == NULL) {
1147
0
                status = ggml_tallocr_alloc(&tallocr, t);
1148
0
            } else if (t->buffer == NULL) {
1149
0
                status = ggml_backend_view_init(t);
1150
0
            }
1151
0
        } else {
1152
0
            if (t->view_src != NULL && t->buffer == NULL) {
1153
                // view of a pre-allocated tensor
1154
0
                status = ggml_backend_view_init(t);
1155
0
            }
1156
0
        }
1157
0
        if (status != GGML_STATUS_SUCCESS) {
1158
0
            GGML_LOG_ERROR("%s: failed to initialize tensor %s\n", __func__, t->name);
1159
0
            free_buffers(buffers, n_buffers);
1160
0
            return false;
1161
0
        }
1162
0
    }
1163
1164
0
    return true;
1165
0
}
1166
1167
static ggml_backend_buffer_t ggml_backend_alloc_ctx_tensors_from_buft_impl(
1168
0
        struct ggml_context * ctx, ggml_backend_buffer_type_t buft, size_t * nbytes_total, bool no_alloc) {
1169
0
    GGML_ASSERT(ggml_get_no_alloc(ctx) == true);
1170
1171
0
    size_t alignment = ggml_backend_buft_get_alignment(buft);
1172
0
    size_t max_size = ggml_backend_buft_get_max_size(buft);
1173
1174
0
    ggml_backend_buffer_t * buffers = NULL;
1175
0
    size_t n_buffers = 0;
1176
0
    *nbytes_total = 0;
1177
1178
0
    size_t cur_buf_size = 0;
1179
0
    struct ggml_tensor * first = ggml_get_first_tensor(ctx);
1180
0
    for (struct ggml_tensor * t = first; t != NULL; t = ggml_get_next_tensor(ctx, t)) {
1181
0
        size_t this_size = 0;
1182
0
        if (t->data == NULL && t->view_src == NULL) {
1183
0
            this_size = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, t), alignment);
1184
0
        }
1185
1186
0
        if (cur_buf_size > 0 && (cur_buf_size + this_size) > max_size) {
1187
            // allocate tensors in the current buffer
1188
0
            if (!no_alloc && !alloc_tensor_range(ctx, first, t, buft, cur_buf_size, &buffers, &n_buffers)) {
1189
0
                return NULL;
1190
0
            }
1191
0
            first = t;
1192
0
            *nbytes_total += cur_buf_size;
1193
0
            cur_buf_size = this_size;
1194
0
        } else {
1195
0
            cur_buf_size += this_size;
1196
0
        }
1197
0
    }
1198
1199
    // allocate remaining tensors
1200
0
    if (cur_buf_size > 0) {
1201
0
        *nbytes_total += cur_buf_size;
1202
0
        if (!no_alloc && !alloc_tensor_range(ctx, first, NULL, buft, cur_buf_size, &buffers, &n_buffers)) {
1203
0
            return NULL;
1204
0
        }
1205
0
    }
1206
1207
0
    if (no_alloc) {
1208
0
        return NULL;
1209
0
    }
1210
1211
0
    if (n_buffers == 0) {
1212
#ifndef NDEBUG
1213
        GGML_LOG_DEBUG("%s: all tensors in the context are already allocated\n", __func__);
1214
#endif
1215
0
        GGML_ASSERT(!buffers);
1216
0
        return NULL;
1217
0
    }
1218
1219
0
    ggml_backend_buffer_t buffer;
1220
0
    if (n_buffers == 1) {
1221
0
        buffer = buffers[0];
1222
0
    } else {
1223
0
        buffer = ggml_backend_multi_buffer_alloc_buffer(buffers, n_buffers);
1224
0
    }
1225
0
    if (buffers) {
1226
0
        free(buffers); // can be NULL if context is empty or no_alloc
1227
0
    }
1228
0
    return buffer;
1229
0
}
1230
1231
0
size_t ggml_backend_alloc_ctx_tensors_from_buft_size(struct ggml_context * ctx, ggml_backend_buffer_type_t buft) {
1232
0
    size_t nbytes_total = 0;
1233
0
    ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft_impl(ctx, buft, &nbytes_total, /*no_alloc=*/ true);
1234
0
    GGML_ASSERT(!buf);
1235
0
    return nbytes_total;
1236
0
}
1237
1238
0
ggml_backend_buffer_t ggml_backend_alloc_ctx_tensors_from_buft(struct ggml_context * ctx, ggml_backend_buffer_type_t buft) {
1239
0
    size_t nbytes_total = 0;
1240
0
    if (ggml_backend_buft_is_meta(buft)) {
1241
0
        return ggml_backend_meta_alloc_ctx_tensors_from_buft(ctx, buft);
1242
0
    }
1243
0
    return ggml_backend_alloc_ctx_tensors_from_buft_impl(ctx, buft, &nbytes_total, /*no_alloc =*/ false);
1244
0
}
1245
1246
0
ggml_backend_buffer_t ggml_backend_alloc_ctx_tensors(struct ggml_context * ctx, ggml_backend_t backend) {
1247
0
    return ggml_backend_alloc_ctx_tensors_from_buft(ctx, ggml_backend_get_default_buffer_type(backend));
1248
0
}