2023-07-30 15:58:01 +02:00
|
|
|
#include "ggml-alloc.h"
|
2023-11-13 13:16:23 +01:00
|
|
|
#include "ggml-backend-impl.h"
|
2023-07-30 15:58:01 +02:00
|
|
|
#include "ggml.h"
|
2023-11-13 13:16:23 +01:00
|
|
|
#include "ggml-impl.h"
|
2023-07-30 15:58:01 +02:00
|
|
|
#include <assert.h>
|
2023-11-13 13:16:23 +01:00
|
|
|
#include <limits.h>
|
2023-07-30 15:58:01 +02:00
|
|
|
#include <stdarg.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
#define MAX(a, b) ((a) > (b) ? (a) : (b))
|
2023-11-13 13:16:23 +01:00
|
|
|
#define MAX_FREE_BLOCKS 256
|
2023-07-30 15:58:01 +02:00
|
|
|
|
|
|
|
//#define GGML_ALLOCATOR_DEBUG
|
|
|
|
|
2023-11-13 13:16:23 +01:00
|
|
|
//#define AT_PRINTF(...) fprintf(stderr, __VA_ARGS__)
|
|
|
|
#define AT_PRINTF(...)
|
2023-07-30 15:58:01 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
|
|
|
|
static bool ggml_is_view(const struct ggml_tensor * t) {
|
|
|
|
return t->view_src != NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
static bool ggml_are_same_layout(const struct ggml_tensor * a, const struct ggml_tensor * b) {
|
|
|
|
if (a->type != b->type) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
for (int i = 0; i < GGML_MAX_DIMS; i++) {
|
|
|
|
if (a->ne[i] != b->ne[i]) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if (a->nb[i] != b->nb[i]) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
static bool ggml_op_can_inplace(enum ggml_op op) {
|
|
|
|
switch (op) {
|
|
|
|
case GGML_OP_SCALE:
|
|
|
|
case GGML_OP_DIAG_MASK_ZERO:
|
|
|
|
case GGML_OP_DIAG_MASK_INF:
|
|
|
|
case GGML_OP_ADD:
|
|
|
|
case GGML_OP_ADD1:
|
|
|
|
case GGML_OP_SUB:
|
|
|
|
case GGML_OP_MUL:
|
|
|
|
case GGML_OP_DIV:
|
|
|
|
case GGML_OP_SQR:
|
|
|
|
case GGML_OP_SQRT:
|
|
|
|
case GGML_OP_LOG:
|
|
|
|
case GGML_OP_UNARY:
|
|
|
|
case GGML_OP_ROPE:
|
|
|
|
case GGML_OP_RMS_NORM:
|
|
|
|
case GGML_OP_SOFT_MAX:
|
|
|
|
return true;
|
|
|
|
|
|
|
|
default:
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
// TODO: GGML_PAD ?
|
|
|
|
static size_t aligned_offset(const void * buffer, size_t offset, size_t alignment) {
|
|
|
|
assert(alignment && !(alignment & (alignment - 1))); // power of 2
|
|
|
|
size_t align = (alignment - (((uintptr_t)buffer + offset) % alignment)) % alignment;
|
|
|
|
return offset + align;
|
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// tallocr
|
|
|
|
struct ggml_tallocr {
|
|
|
|
ggml_backend_buffer_t buffer;
|
|
|
|
void * base;
|
|
|
|
size_t alignment;
|
|
|
|
size_t offset;
|
|
|
|
};
|
|
|
|
|
|
|
|
ggml_tallocr_t ggml_tallocr_new(ggml_backend_buffer_t buffer) {
|
|
|
|
ggml_tallocr_t talloc = malloc(sizeof(struct ggml_tallocr));
|
|
|
|
if (talloc == NULL) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
void * base = ggml_backend_buffer_get_base(buffer);
|
|
|
|
size_t align = ggml_backend_buffer_get_alignment(buffer);
|
|
|
|
|
|
|
|
assert(align && !(align & (align - 1))); // power of 2
|
|
|
|
|
|
|
|
*talloc = (struct ggml_tallocr) {
|
|
|
|
/*.buffer = */ buffer,
|
|
|
|
/*.base = */ base,
|
|
|
|
/*.alignment = */ align,
|
|
|
|
/*.offset = */ aligned_offset(base, 0, align),
|
|
|
|
};
|
|
|
|
return talloc;
|
|
|
|
}
|
|
|
|
|
|
|
|
void ggml_tallocr_free(ggml_tallocr_t talloc) {
|
|
|
|
free(talloc);
|
|
|
|
}
|
|
|
|
|
|
|
|
void ggml_tallocr_alloc(ggml_tallocr_t talloc, struct ggml_tensor * tensor) {
|
|
|
|
size_t size = ggml_backend_buffer_get_alloc_size(talloc->buffer, tensor);
|
|
|
|
size = GGML_PAD(size, talloc->alignment);
|
|
|
|
|
|
|
|
if (talloc->offset + size > ggml_backend_buffer_get_size(talloc->buffer)) {
|
|
|
|
fprintf(stderr, "%s: not enough space in the buffer to allocate %s (needed %zu, available %zu)\n",
|
|
|
|
__func__, tensor->name, size, ggml_backend_buffer_get_size(talloc->buffer) - talloc->offset);
|
|
|
|
GGML_ASSERT(!"not enough space in the buffer");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
void * addr = (char *)ggml_backend_buffer_get_base(talloc->buffer) + talloc->offset;
|
|
|
|
talloc->offset += size;
|
|
|
|
|
|
|
|
assert(((uintptr_t)addr % talloc->alignment) == 0);
|
|
|
|
|
|
|
|
ggml_backend_tensor_alloc(talloc->buffer, tensor, addr);
|
|
|
|
}
|
|
|
|
|
|
|
|
// dynamic tensor allocator
|
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
struct free_block {
|
2024-02-12 08:16:06 +01:00
|
|
|
size_t offset;
|
2023-07-30 15:58:01 +02:00
|
|
|
size_t size;
|
|
|
|
};
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
struct ggml_dyn_tallocr {
|
2023-07-30 15:58:01 +02:00
|
|
|
size_t alignment;
|
|
|
|
int n_free_blocks;
|
|
|
|
struct free_block free_blocks[MAX_FREE_BLOCKS];
|
|
|
|
size_t max_size;
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
2024-02-12 08:16:06 +01:00
|
|
|
struct {
|
|
|
|
const struct ggml_tensor * tensor;
|
|
|
|
size_t offset;
|
|
|
|
} allocated_tensors[1024];
|
2023-07-30 15:58:01 +02:00
|
|
|
#endif
|
|
|
|
};
|
|
|
|
|
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
2024-02-12 08:16:06 +01:00
|
|
|
static void add_allocated_tensor(struct ggml_dyn_tallocr * alloc, size_t offset, const struct ggml_tensor * tensor) {
|
2023-07-30 15:58:01 +02:00
|
|
|
for (int i = 0; i < 1024; i++) {
|
2024-02-12 08:16:06 +01:00
|
|
|
if (alloc->allocated_tensors[i].tensor == NULL) {
|
|
|
|
alloc->allocated_tensors[i].tensor = tensor;
|
|
|
|
alloc->allocated_tensors[i].offset = offset;
|
2023-07-30 15:58:01 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
GGML_ASSERT(!"out of allocated_tensors");
|
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
static void remove_allocated_tensor(struct ggml_dyn_tallocr * alloc, size_t offset, const struct ggml_tensor * tensor) {
|
2023-07-30 15:58:01 +02:00
|
|
|
for (int i = 0; i < 1024; i++) {
|
2024-02-12 08:16:06 +01:00
|
|
|
if (alloc->allocated_tensors[i].offset == offset) {
|
|
|
|
alloc->allocated_tensors[i].tensor = NULL;
|
2023-07-30 15:58:01 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
fprintf(stderr, "tried to free tensor %s not found\n", tensor->name);
|
2023-07-30 15:58:01 +02:00
|
|
|
GGML_ASSERT(!"tensor not found");
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static size_t ggml_dyn_tallocr_alloc(struct ggml_dyn_tallocr * alloc, size_t size, const struct ggml_tensor * tensor) {
|
2023-07-30 15:58:01 +02:00
|
|
|
size = aligned_offset(NULL, size, alloc->alignment);
|
|
|
|
|
|
|
|
AT_PRINTF("%s: allocating %s (%zu bytes) - ", __func__, tensor->name, size);
|
|
|
|
|
|
|
|
size_t max_avail = 0;
|
|
|
|
|
2023-08-17 09:35:53 +02:00
|
|
|
// find the best fitting free block besides the last block
|
2023-07-30 15:58:01 +02:00
|
|
|
int best_fit_block = -1;
|
|
|
|
size_t best_fit_size = SIZE_MAX;
|
2023-08-17 09:35:53 +02:00
|
|
|
for (int i = 0; i < alloc->n_free_blocks - 1; i++) {
|
2023-07-30 15:58:01 +02:00
|
|
|
struct free_block * block = &alloc->free_blocks[i];
|
|
|
|
max_avail = MAX(max_avail, block->size);
|
|
|
|
if (block->size >= size && block->size <= best_fit_size) {
|
|
|
|
best_fit_block = i;
|
|
|
|
best_fit_size = block->size;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (best_fit_block == -1) {
|
2023-08-17 09:35:53 +02:00
|
|
|
// the last block is our last resort
|
|
|
|
struct free_block * block = &alloc->free_blocks[alloc->n_free_blocks - 1];
|
2023-09-07 19:22:29 +02:00
|
|
|
max_avail = MAX(max_avail, block->size);
|
2023-08-17 09:35:53 +02:00
|
|
|
if (block->size >= size) {
|
|
|
|
best_fit_block = alloc->n_free_blocks - 1;
|
|
|
|
} else {
|
2024-02-12 08:16:06 +01:00
|
|
|
// this should never happen
|
|
|
|
fprintf(stderr, "%s: not enough space in the buffer to allocate %zu bytes, largest block available %zu bytes\n",
|
|
|
|
__func__, size, max_avail);
|
2023-08-17 09:35:53 +02:00
|
|
|
GGML_ASSERT(!"not enough space in the buffer");
|
2024-02-12 08:16:06 +01:00
|
|
|
GGML_UNREACHABLE();
|
2023-08-17 09:35:53 +02:00
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
2024-01-12 20:07:38 +01:00
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
struct free_block * block = &alloc->free_blocks[best_fit_block];
|
2024-02-12 08:16:06 +01:00
|
|
|
size_t offset = block->offset;
|
|
|
|
block->offset = offset + size;
|
2023-07-30 15:58:01 +02:00
|
|
|
block->size -= size;
|
|
|
|
if (block->size == 0) {
|
|
|
|
// remove block if empty
|
|
|
|
alloc->n_free_blocks--;
|
|
|
|
for (int j = best_fit_block; j < alloc->n_free_blocks; j++) {
|
|
|
|
alloc->free_blocks[j] = alloc->free_blocks[j+1];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
AT_PRINTF("block %d, offset %zu\n", best_fit_block, offset);
|
2023-07-30 15:58:01 +02:00
|
|
|
|
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
2024-02-12 08:16:06 +01:00
|
|
|
add_allocated_tensor(alloc, offset, tensor);
|
|
|
|
size_t cur_max = offset + size;
|
2023-07-30 15:58:01 +02:00
|
|
|
if (cur_max > alloc->max_size) {
|
2024-02-12 08:16:06 +01:00
|
|
|
// sort allocated_tensors by offset
|
|
|
|
for (int i = 0; i < 1024; i++) {
|
|
|
|
for (int j = i + 1; j < 1024; j++) {
|
|
|
|
if (alloc->allocated_tensors[i].offset > alloc->allocated_tensors[j].offset) {
|
|
|
|
const struct ggml_tensor * tmp_tensor = alloc->allocated_tensors[i].tensor;
|
|
|
|
size_t tmp_offset = alloc->allocated_tensors[i].offset;
|
|
|
|
alloc->allocated_tensors[i].tensor = alloc->allocated_tensors[j].tensor;
|
|
|
|
alloc->allocated_tensors[i].offset = alloc->allocated_tensors[j].offset;
|
|
|
|
alloc->allocated_tensors[j].tensor = tmp_tensor;
|
|
|
|
alloc->allocated_tensors[j].offset = tmp_offset;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fprintf(stderr, "max_size = %.2f MB: tensors: ", cur_max / 1024.0 / 1024.0);
|
2023-07-30 15:58:01 +02:00
|
|
|
for (int i = 0; i < 1024; i++) {
|
2024-02-12 08:16:06 +01:00
|
|
|
if (alloc->allocated_tensors[i].tensor) {
|
|
|
|
fprintf(stderr, "%s [%zx-%zx] (%.2f MB) ", alloc->allocated_tensors[i].tensor->name,
|
|
|
|
alloc->allocated_tensors[i].offset,
|
|
|
|
alloc->allocated_tensors[i].offset + ggml_nbytes(alloc->allocated_tensors[i].tensor),
|
|
|
|
ggml_nbytes(alloc->allocated_tensors[i].tensor) / 1024.0 / 1024.0);
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
fprintf(stderr, "\n");
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
alloc->max_size = MAX(alloc->max_size, offset + size);
|
2023-07-30 15:58:01 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
return offset;
|
2023-07-30 15:58:01 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
GGML_UNUSED(tensor);
|
|
|
|
}
|
2023-10-08 19:19:14 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// this is a very naive implementation, but for our case the number of free blocks should be very small
|
|
|
|
static void ggml_dyn_tallocr_free_tensor(struct ggml_dyn_tallocr * alloc, size_t offset, size_t size, const struct ggml_tensor * tensor) {
|
2023-07-30 15:58:01 +02:00
|
|
|
size = aligned_offset(NULL, size, alloc->alignment);
|
2024-02-12 08:16:06 +01:00
|
|
|
|
|
|
|
AT_PRINTF("%s: freeing %s at %zu (%zu bytes) - n_free_blocks = %d\n", __func__, tensor->name, offset, size, alloc->n_free_blocks);
|
2023-10-08 19:19:14 +02:00
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
2024-02-12 08:16:06 +01:00
|
|
|
remove_allocated_tensor(alloc, offset, tensor);
|
2023-07-30 15:58:01 +02:00
|
|
|
#endif
|
|
|
|
|
|
|
|
// see if we can merge with an existing block
|
|
|
|
for (int i = 0; i < alloc->n_free_blocks; i++) {
|
|
|
|
struct free_block * block = &alloc->free_blocks[i];
|
|
|
|
// check if ptr is at the end of the block
|
2024-02-12 08:16:06 +01:00
|
|
|
if (block->offset + block->size == offset) {
|
2023-07-30 15:58:01 +02:00
|
|
|
block->size += size;
|
|
|
|
// check if we can merge with the next block
|
2024-02-12 08:16:06 +01:00
|
|
|
if (i < alloc->n_free_blocks - 1 && block->offset + block->size == alloc->free_blocks[i+1].offset) {
|
2023-07-30 15:58:01 +02:00
|
|
|
block->size += alloc->free_blocks[i+1].size;
|
|
|
|
alloc->n_free_blocks--;
|
|
|
|
for (int j = i+1; j < alloc->n_free_blocks; j++) {
|
|
|
|
alloc->free_blocks[j] = alloc->free_blocks[j+1];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// check if ptr is at the beginning of the block
|
2024-02-12 08:16:06 +01:00
|
|
|
if (offset + size == block->offset) {
|
|
|
|
block->offset = offset;
|
2023-07-30 15:58:01 +02:00
|
|
|
block->size += size;
|
|
|
|
// check if we can merge with the previous block
|
2024-02-12 08:16:06 +01:00
|
|
|
if (i > 0 && alloc->free_blocks[i-1].offset + alloc->free_blocks[i-1].size == block->offset) {
|
2023-07-30 15:58:01 +02:00
|
|
|
alloc->free_blocks[i-1].size += block->size;
|
|
|
|
alloc->n_free_blocks--;
|
|
|
|
for (int j = i; j < alloc->n_free_blocks; j++) {
|
|
|
|
alloc->free_blocks[j] = alloc->free_blocks[j+1];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// otherwise, add a new block
|
|
|
|
GGML_ASSERT(alloc->n_free_blocks < MAX_FREE_BLOCKS && "out of free blocks");
|
|
|
|
// insert the new block in the correct position to keep the array sorted by address (to make merging blocks faster)
|
|
|
|
int insert_pos = 0;
|
2024-02-12 08:16:06 +01:00
|
|
|
while (insert_pos < alloc->n_free_blocks && alloc->free_blocks[insert_pos].offset < offset) {
|
2023-07-30 15:58:01 +02:00
|
|
|
insert_pos++;
|
|
|
|
}
|
|
|
|
// shift all blocks from insert_pos onward to make room for the new block
|
|
|
|
for (int i = alloc->n_free_blocks; i > insert_pos; i--) {
|
|
|
|
alloc->free_blocks[i] = alloc->free_blocks[i-1];
|
|
|
|
}
|
|
|
|
// insert the new block
|
2024-02-12 08:16:06 +01:00
|
|
|
alloc->free_blocks[insert_pos].offset = offset;
|
2023-07-30 15:58:01 +02:00
|
|
|
alloc->free_blocks[insert_pos].size = size;
|
|
|
|
alloc->n_free_blocks++;
|
2024-02-12 08:16:06 +01:00
|
|
|
|
|
|
|
GGML_UNUSED(tensor);
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static void ggml_dyn_tallocr_reset(struct ggml_dyn_tallocr * alloc) {
|
2023-07-30 15:58:01 +02:00
|
|
|
alloc->n_free_blocks = 1;
|
2024-02-12 08:16:06 +01:00
|
|
|
alloc->free_blocks[0].offset = 0;
|
|
|
|
alloc->free_blocks[0].size = SIZE_MAX/2; // restrict maximum size of a measure allocator to half size_t max to avoid overflows
|
|
|
|
alloc->max_size = 0;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static struct ggml_dyn_tallocr * ggml_dyn_tallocr_new(size_t alignment) {
|
|
|
|
struct ggml_dyn_tallocr * alloc = (struct ggml_dyn_tallocr *)malloc(sizeof(struct ggml_dyn_tallocr));
|
2023-07-30 15:58:01 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
*alloc = (struct ggml_dyn_tallocr) {
|
2023-07-30 15:58:01 +02:00
|
|
|
/*.alignment = */ alignment,
|
|
|
|
/*.n_free_blocks = */ 0,
|
|
|
|
/*.free_blocks = */ {{0}},
|
|
|
|
/*.max_size = */ 0,
|
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
2024-02-12 08:16:06 +01:00
|
|
|
/*.allocated_tensors = */ {{0}},
|
2023-07-30 15:58:01 +02:00
|
|
|
#endif
|
|
|
|
};
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
ggml_dyn_tallocr_reset(alloc);
|
2023-07-30 15:58:01 +02:00
|
|
|
|
|
|
|
return alloc;
|
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static void ggml_dyn_tallocr_free(struct ggml_dyn_tallocr * alloc) {
|
2023-07-30 15:58:01 +02:00
|
|
|
free(alloc);
|
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static size_t ggml_dyn_tallocr_max_size(struct ggml_dyn_tallocr * alloc) {
|
|
|
|
return alloc->max_size;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
|
|
|
|
/////////////////////////////////////
|
2023-11-13 13:16:23 +01:00
|
|
|
|
|
|
|
// graph allocator
|
|
|
|
|
|
|
|
struct hash_node {
|
|
|
|
int n_children;
|
|
|
|
int n_views;
|
2024-02-12 08:16:06 +01:00
|
|
|
int buffer_id;
|
|
|
|
size_t offset; // offset within the buffer
|
|
|
|
bool allocated;
|
|
|
|
};
|
|
|
|
|
|
|
|
//
|
|
|
|
struct tensor_alloc {
|
|
|
|
size_t offset;
|
|
|
|
size_t size_max; // 0 = pre-allocated, unused, or view
|
|
|
|
};
|
|
|
|
|
|
|
|
struct node_alloc {
|
|
|
|
int buffer_id;
|
|
|
|
struct tensor_alloc dst;
|
|
|
|
struct tensor_alloc src[GGML_MAX_SRC];
|
2023-11-13 13:16:23 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
struct ggml_gallocr {
|
2024-02-12 08:16:06 +01:00
|
|
|
ggml_backend_buffer_type_t * bufts; // [n_buffers]
|
|
|
|
ggml_backend_buffer_t * buffers; // [n_buffers]
|
|
|
|
struct ggml_dyn_tallocr ** buf_tallocs; // [n_buffers]
|
|
|
|
int n_buffers;
|
|
|
|
|
2023-11-13 13:16:23 +01:00
|
|
|
struct ggml_hash_set hash_set;
|
2024-02-12 08:16:06 +01:00
|
|
|
struct hash_node * hash_values; // [hash_set.size]
|
|
|
|
|
|
|
|
struct node_alloc * node_allocs; // [n_nodes]
|
|
|
|
int n_nodes;
|
2023-11-13 13:16:23 +01:00
|
|
|
};
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
ggml_gallocr_t ggml_gallocr_new_n(ggml_backend_buffer_type_t * bufts, int n_bufs) {
|
|
|
|
ggml_gallocr_t galloc = (ggml_gallocr_t)calloc(sizeof(struct ggml_gallocr), 1);
|
|
|
|
GGML_ASSERT(galloc != NULL);
|
|
|
|
|
|
|
|
galloc->bufts = calloc(sizeof(ggml_backend_buffer_type_t) * n_bufs, 1);
|
|
|
|
GGML_ASSERT(galloc->bufts != NULL);
|
|
|
|
|
|
|
|
galloc->buffers = calloc(sizeof(ggml_backend_buffer_t) * n_bufs, 1);
|
|
|
|
GGML_ASSERT(galloc->buffers != NULL);
|
|
|
|
|
|
|
|
galloc->buf_tallocs = calloc(sizeof(struct ggml_dyn_tallocr *) * n_bufs, 1);
|
|
|
|
GGML_ASSERT(galloc->buf_tallocs != NULL);
|
|
|
|
|
|
|
|
for (int i = 0; i < n_bufs; i++) {
|
|
|
|
galloc->bufts[i] = bufts[i];
|
|
|
|
galloc->buffers[i] = NULL;
|
|
|
|
size_t alignment = ggml_backend_buft_get_alignment(bufts[i]);
|
|
|
|
galloc->buf_tallocs[i] = ggml_dyn_tallocr_new(alignment);
|
|
|
|
}
|
|
|
|
galloc->n_buffers = n_bufs;
|
2023-11-13 13:16:23 +01:00
|
|
|
|
|
|
|
return galloc;
|
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
ggml_gallocr_t ggml_gallocr_new(ggml_backend_buffer_type_t buft) {
|
|
|
|
return ggml_gallocr_new_n(&buft, 1);
|
|
|
|
}
|
|
|
|
|
2023-11-13 13:16:23 +01:00
|
|
|
void ggml_gallocr_free(ggml_gallocr_t galloc) {
|
|
|
|
if (galloc == NULL) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
for (int i = 0; i < galloc->n_buffers; i++) {
|
|
|
|
if (galloc->buffers != NULL) {
|
|
|
|
ggml_backend_buffer_free(galloc->buffers[i]);
|
|
|
|
}
|
|
|
|
if (galloc->buf_tallocs != NULL) {
|
|
|
|
ggml_dyn_tallocr_free(galloc->buf_tallocs[i]);
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
|
|
|
|
free(galloc->hash_set.keys);
|
|
|
|
free(galloc->hash_values);
|
|
|
|
free(galloc->bufts);
|
|
|
|
free(galloc->buffers);
|
|
|
|
free(galloc->buf_tallocs);
|
|
|
|
free(galloc->node_allocs);
|
2023-11-13 13:16:23 +01:00
|
|
|
free(galloc);
|
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
typedef struct ggml_gallocr * ggml_gallocr_t;
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static struct hash_node * ggml_gallocr_hash_get(ggml_gallocr_t galloc, struct ggml_tensor * t) {
|
2023-11-13 13:16:23 +01:00
|
|
|
size_t i = ggml_hash_find_or_insert(galloc->hash_set, t);
|
|
|
|
return &galloc->hash_values[i];
|
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static bool ggml_gallocr_is_own(ggml_gallocr_t galloc, struct ggml_tensor * t) {
|
|
|
|
return ggml_gallocr_hash_get(galloc, t)->allocated;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static void ggml_gallocr_set_node_offset(ggml_gallocr_t galloc, struct ggml_tensor * node, int buffer_id, size_t offset) {
|
|
|
|
struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
|
|
|
|
hn->buffer_id = buffer_id;
|
|
|
|
hn->offset = offset;
|
|
|
|
hn->allocated = true;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static bool ggml_gallocr_is_allocated(ggml_gallocr_t galloc, struct ggml_tensor * t) {
|
|
|
|
return t->data != NULL || ggml_gallocr_hash_get(galloc, t)->allocated;
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static void ggml_gallocr_allocate_node(ggml_gallocr_t galloc, struct ggml_tensor * node, int buffer_id) {
|
|
|
|
struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
|
2023-10-08 19:19:14 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
if (!ggml_gallocr_is_allocated(galloc, node) && !ggml_is_view(node)) {
|
|
|
|
hn->allocated = true;
|
|
|
|
assert(hn->offset == 0);
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// try to reuse a parent's buffer (inplace)
|
|
|
|
if (ggml_op_can_inplace(node->op)) {
|
|
|
|
for (int i = 0; i < GGML_MAX_SRC; i++) {
|
|
|
|
struct ggml_tensor * parent = node->src[i];
|
|
|
|
if (parent == NULL) {
|
|
|
|
break;
|
|
|
|
}
|
2023-10-08 19:19:14 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// if the node's data is external, then we cannot re-use it
|
|
|
|
if (!ggml_gallocr_is_own(galloc, parent)) {
|
|
|
|
AT_PRINTF("not reusing parent %s for %s as %p is external\n", parent->name, node->name, parent->data);
|
|
|
|
continue;
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// outputs cannot be reused
|
|
|
|
if (parent->flags & GGML_TENSOR_FLAG_OUTPUT || (parent->view_src != NULL && parent->view_src->flags & GGML_TENSOR_FLAG_OUTPUT)) {
|
|
|
|
AT_PRINTF("not reusing parent %s for %s as it is an output\n", parent->name, node->name);
|
|
|
|
continue;
|
|
|
|
}
|
2023-08-09 22:47:42 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
if (!ggml_are_same_layout(node, parent)) {
|
|
|
|
AT_PRINTF("not reusing parent %s for %s as layouts are different\n", parent->name, node->name);
|
|
|
|
continue;
|
|
|
|
}
|
2023-08-09 22:47:42 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
struct hash_node * p_hn = ggml_gallocr_hash_get(galloc, parent);
|
|
|
|
if (p_hn->n_children == 1 && p_hn->n_views == 0) {
|
|
|
|
if (ggml_is_view(parent)) {
|
|
|
|
struct ggml_tensor * view_src = parent->view_src;
|
|
|
|
struct hash_node * view_src_hn = ggml_gallocr_hash_get(galloc, view_src);
|
|
|
|
if (view_src_hn->n_views == 1 && view_src_hn->n_children == 0 && view_src->data == parent->data) {
|
|
|
|
AT_PRINTF("reusing view parent %s (%s) for %s\n", parent->name, view_src->name, node->name);
|
|
|
|
assert(view_src_hn->offset == p_hn->offset);
|
|
|
|
hn->buffer_id = p_hn->buffer_id;
|
|
|
|
hn->offset = p_hn->offset;
|
|
|
|
p_hn->allocated = false; // avoid freeing the parent
|
|
|
|
view_src_hn->allocated = false;
|
2023-08-24 18:27:25 +02:00
|
|
|
return;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
} else {
|
|
|
|
AT_PRINTF("reusing parent %s for %s\n", parent->name, node->name);
|
|
|
|
hn->buffer_id = p_hn->buffer_id;
|
|
|
|
hn->offset = p_hn->offset;
|
|
|
|
p_hn->allocated = false; // avoid freeing the parent
|
|
|
|
return;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
// allocate tensor from the buffer
|
|
|
|
struct ggml_dyn_tallocr * alloc = galloc->buf_tallocs[buffer_id];
|
|
|
|
ggml_backend_buffer_type_t buft = galloc->bufts[buffer_id];
|
|
|
|
size_t size = ggml_backend_buft_get_alloc_size(buft, node);
|
|
|
|
size_t offset = ggml_dyn_tallocr_alloc(alloc, size, node);
|
|
|
|
hn->buffer_id = buffer_id;
|
|
|
|
hn->offset = offset;
|
|
|
|
return;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static void ggml_gallocr_free_node(ggml_gallocr_t galloc, struct ggml_tensor * node, int buffer_id) {
|
|
|
|
// graph outputs are never freed
|
|
|
|
if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
|
|
|
|
AT_PRINTF("not freeing output %s\n", node->name);
|
|
|
|
return;
|
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
struct ggml_dyn_tallocr * alloc = galloc->buf_tallocs[buffer_id];
|
|
|
|
ggml_backend_buffer_type_t buft = galloc->bufts[buffer_id];
|
|
|
|
struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
|
|
|
|
size_t offset = hn->offset;
|
|
|
|
size_t size = ggml_backend_buft_get_alloc_size(buft, node);
|
|
|
|
ggml_dyn_tallocr_free_tensor(alloc, offset, size, node);
|
|
|
|
hn->allocated = false;
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static int get_node_buffer_id(const int * node_buffer_ids, int i) {
|
|
|
|
return node_buffer_ids ? node_buffer_ids[i] : 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
static void ggml_gallocr_alloc_graph_impl(ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids) {
|
|
|
|
// clear hash tables
|
|
|
|
memset(galloc->hash_set.keys, 0, galloc->hash_set.size * sizeof(struct ggml_tensor *));
|
|
|
|
memset(galloc->hash_values, 0, galloc->hash_set.size * sizeof(struct hash_node));
|
|
|
|
|
|
|
|
// allocate all graph inputs first to avoid overwriting them
|
|
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
|
|
if (graph->nodes[i]->flags & GGML_TENSOR_FLAG_INPUT) {
|
|
|
|
ggml_gallocr_allocate_node(galloc, graph->nodes[i], get_node_buffer_id(node_buffer_ids, i));
|
|
|
|
}
|
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
if (graph->nodes[i]->src[j] == NULL) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if (graph->nodes[i]->src[j]->flags & GGML_TENSOR_FLAG_INPUT) {
|
|
|
|
ggml_gallocr_allocate_node(galloc, graph->nodes[i]->src[j], get_node_buffer_id(node_buffer_ids, i));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
|
|
|
|
// count number of children and views
|
2024-02-12 08:16:06 +01:00
|
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
|
|
struct ggml_tensor * node = graph->nodes[i];
|
2023-11-13 13:16:23 +01:00
|
|
|
|
|
|
|
if (ggml_is_view(node)) {
|
|
|
|
struct ggml_tensor * view_src = node->view_src;
|
2024-02-12 08:16:06 +01:00
|
|
|
ggml_gallocr_hash_get(galloc, view_src)->n_views += 1;
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
struct ggml_tensor * parent = node->src[j];
|
|
|
|
if (parent == NULL) {
|
|
|
|
break;
|
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
ggml_gallocr_hash_get(galloc, parent)->n_children += 1;
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// allocate tensors
|
2024-02-12 08:16:06 +01:00
|
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
|
|
int buffer_id = get_node_buffer_id(node_buffer_ids, i);
|
|
|
|
|
|
|
|
// allocate parents (only leafs need to be allocated at this point)
|
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
struct ggml_tensor * parent = node->src[j];
|
|
|
|
if (parent == NULL) {
|
|
|
|
break;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
ggml_gallocr_allocate_node(galloc, parent, buffer_id);
|
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// allocate node
|
|
|
|
ggml_gallocr_allocate_node(galloc, node, buffer_id);
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
AT_PRINTF("exec: %s (%s) <= ", ggml_op_desc(node), node->name);
|
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
struct ggml_tensor * parent = node->src[j];
|
|
|
|
if (parent == NULL) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
AT_PRINTF("%s", parent->name);
|
|
|
|
if (j < GGML_MAX_SRC - 1 && node->src[j + 1] != NULL) {
|
|
|
|
AT_PRINTF(", ");
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
AT_PRINTF("\n");
|
2023-08-24 18:27:25 +02:00
|
|
|
|
2023-11-13 13:16:23 +01:00
|
|
|
// update parents
|
2024-02-12 08:16:06 +01:00
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
struct ggml_tensor * parent = node->src[j];
|
|
|
|
if (parent == NULL) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
struct hash_node * p_hn = ggml_gallocr_hash_get(galloc, parent);
|
|
|
|
p_hn->n_children -= 1;
|
|
|
|
|
|
|
|
AT_PRINTF("parent %s: %d children, %d views, allocated: %d\n",
|
|
|
|
parent->name, p_hn->n_children, p_hn->n_views, p_hn->allocated);
|
|
|
|
|
|
|
|
if (p_hn->n_children == 0 && p_hn->n_views == 0) {
|
|
|
|
if (ggml_is_view(parent)) {
|
|
|
|
struct ggml_tensor * view_src = parent->view_src;
|
|
|
|
struct hash_node * view_src_hn = ggml_gallocr_hash_get(galloc, view_src);
|
|
|
|
view_src_hn->n_views -= 1;
|
|
|
|
AT_PRINTF("view_src %s: %d children, %d views\n",
|
|
|
|
view_src->name, view_src_hn->n_children, view_src_hn->n_views);
|
|
|
|
if (view_src_hn->n_views == 0 && view_src_hn->n_children == 0 && view_src_hn->allocated) {
|
|
|
|
ggml_gallocr_free_node(galloc, view_src, buffer_id);
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
else if (p_hn->allocated) {
|
|
|
|
ggml_gallocr_free_node(galloc, parent, buffer_id);
|
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
AT_PRINTF("\n");
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
bool ggml_gallocr_reserve_n(ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids) {
|
2023-11-13 13:16:23 +01:00
|
|
|
size_t hash_size = graph->visited_hash_table.size;
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// initialize hash table
|
2023-11-13 13:16:23 +01:00
|
|
|
if (galloc->hash_set.size < hash_size) {
|
2024-02-12 08:16:06 +01:00
|
|
|
free(galloc->hash_set.keys);
|
|
|
|
free(galloc->hash_values);
|
2023-11-13 13:16:23 +01:00
|
|
|
galloc->hash_set.size = hash_size;
|
2024-02-12 08:16:06 +01:00
|
|
|
galloc->hash_set.keys = calloc(sizeof(struct ggml_tensor *), hash_size);
|
|
|
|
galloc->hash_values = calloc(sizeof(struct hash_node), hash_size);
|
|
|
|
GGML_ASSERT(galloc->hash_set.keys != NULL);
|
|
|
|
GGML_ASSERT(galloc->hash_values != NULL);
|
|
|
|
} else {
|
|
|
|
// reset hash table
|
|
|
|
memset(galloc->hash_set.keys, 0, sizeof(struct ggml_tensor *) * galloc->hash_set.size);
|
|
|
|
memset(galloc->hash_values, 0, sizeof(struct hash_node) * galloc->hash_set.size);
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// reset allocators
|
|
|
|
for (int i = 0; i < galloc->n_buffers; i++) {
|
|
|
|
ggml_dyn_tallocr_reset(galloc->buf_tallocs[i]);
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// allocate in hash table
|
|
|
|
ggml_gallocr_alloc_graph_impl(galloc, graph, node_buffer_ids);
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// set the node_allocs from the hash table
|
|
|
|
if (galloc->n_nodes < graph->n_nodes) {
|
|
|
|
free(galloc->node_allocs);
|
|
|
|
galloc->node_allocs = calloc(sizeof(struct node_alloc), graph->n_nodes);
|
|
|
|
GGML_ASSERT(galloc->node_allocs != NULL);
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
2024-02-12 08:16:06 +01:00
|
|
|
galloc->n_nodes = graph->n_nodes;
|
|
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
|
|
struct node_alloc * node_alloc = &galloc->node_allocs[i];
|
|
|
|
node_alloc->buffer_id = get_node_buffer_id(node_buffer_ids, i);
|
|
|
|
if (node->view_src || node->data) {
|
|
|
|
node_alloc->dst.offset = SIZE_MAX;
|
|
|
|
node_alloc->dst.size_max = 0;
|
|
|
|
} else {
|
|
|
|
struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
|
|
|
|
node_alloc->dst.offset = hn->offset;
|
|
|
|
node_alloc->dst.size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], node);
|
|
|
|
}
|
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
struct ggml_tensor * src = node->src[j];
|
|
|
|
if (!src || src->view_src || src->data) {
|
|
|
|
node_alloc->src[j].offset = SIZE_MAX;
|
|
|
|
node_alloc->src[j].size_max = 0;
|
|
|
|
} else {
|
|
|
|
struct hash_node * hn = ggml_gallocr_hash_get(galloc, src);
|
|
|
|
node_alloc->src[j].offset = hn->offset;
|
|
|
|
node_alloc->src[j].size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], src);
|
|
|
|
}
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// reallocate buffers if needed
|
|
|
|
for (int i = 0; i < galloc->n_buffers; i++) {
|
|
|
|
size_t cur_size = galloc->buffers[i] ? ggml_backend_buffer_get_size(galloc->buffers[i]) : 0;
|
|
|
|
size_t new_size = ggml_dyn_tallocr_max_size(galloc->buf_tallocs[i]);
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
if (new_size > cur_size) {
|
|
|
|
#ifndef NDEBUG
|
|
|
|
fprintf(stderr, "%s: reallocating %s buffer from size %.02f MiB to %.02f MiB\n", __func__, ggml_backend_buft_name(galloc->bufts[i]), cur_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
|
|
|
|
#endif
|
|
|
|
ggml_backend_buffer_free(galloc->buffers[i]);
|
|
|
|
galloc->buffers[i] = ggml_backend_buft_alloc_buffer(galloc->bufts[i], new_size);
|
|
|
|
if (galloc->buffers[i] == NULL) {
|
|
|
|
fprintf(stderr, "%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(galloc->bufts[i]), new_size);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
return true;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
train : finetune LORA (#2632)
* fix track_max_mem in forward_batch_wo_cache_flash_attn_train
* remove unnecessary Adam(W) optimizer tensors.
reduces optimizer memory overhead from 7*modelsize to 2*modelsize.
additionally allows to optimize models with more than 2^31 parameters by replacing int with int64_t.
bumps training checkpoint file version, but old checkpoints can still be read.
new version with less tensors is saved.
* add gradient clipping to AdamW
* Fix reset of unused g->nodes and g->grads to NULL
* implement gradient checkpointing for training
reduces memory overhead from O(n_layer) to O(sqrt(n_layer))
as explained in readme of https://github.com/cybertronai/gradient-checkpointing
* remove unused compute buffer 3
* add and use function ggml_build_backward_expand to avoid stack overflows with large maximum number of nodes
GGML_API void ggml_build_backward_expand(struct ggml_context * ctx, struct ggml_cgraph * gf, struct ggml_cgraph * gb, bool keep);
* change AdamW decay parameter to work like the torch AdamW decay parameter
It is now relative to Adam learning rate `alpha*sched`.
Before that it was relative to `sched` only.
`alpha` being the maximum learning rate and `sched` being a scaling parameter in [0..1]
* change default AdamW weight decay parameter used in training to 0.1 as used in nanoGPT
* change default AdamW weight decay parameter defined in ggml to 0.0, making Adam default instead of AdamW
btw: the default weight decay parameter for torch.optim.AdamW is 0.01
* bug fixes for cross entropy loss
ggml_cross_entropy_loss: sums where not correctly added in workload of each thread
ggml_cross_entropy_loss_back: simplify backward process, reducing numerical issues
guard usage of exp f16 lookup in cross entropy by #define GGML_CROSS_ENTROPY_EXP_FP16
cross entropy loss is only used once during training, but it is quite sensitive to numerical errors introduced by exp-f16-lookup.
so exp-f16-lookup for cross entropy loss is disabled by default, trading better gradients for very slightly worse runtime performance.
* fix test-grad0 for cross_entropy_loss
the second argument to cross_entropy_loss must sum up to 1 for each row
* fix test-grad0 for soft_max
dont use only sum as aggregation, because sum of softmax is always 1 -> finite differences should not work
instead use sum(log(soft_max()*(1-eps)+eps)); use eps to avoid log(0)
* improve finite differences of test-grad0 by using double instead of float
* change cross_entropy_loss to output average over all rows
this helps keeping the loss and gradients in a sane range
* improve gradient checkpointing
sqrt(n_layers) is only the best checkpoint step when mem size of checkpoints and mem size of layers are equal.
since layers require more memory than the single-tensor-checkpoint we use, the optimal values are compute different:
```
given: n, u, v
objective: minimize(a*u+b*v) where a*b=n, a>0, b>0
b=n/a
minimize(a*u+v*n/a)
diff(a*u+v*n/a, a) = u - (v*n/a)/a
diff(a*u+v*n/a, a) == 0
u - (v*n/a)/a == 0
u == v*n/(a*a)
u*a*a = v*n
a*a = v*n/u
a = sqrt(n*v/u)
```
this change results in more checkpoints, requiring less layers to store between checkpoints, overall improving memory usage.
* disable gradient checkpointing debug output
* llama : fix rope usage in train-text-from-scratch after ChatGLM change
* add more training parameters:
--enable-restart N Only for Adam optimizer. Enable restarts of cos-decay
--disable-restart N Only for Adam optimizer. Disable restarts of cos-decay
--opt-past N Number of optimization iterations to track for delta convergence test. Disabled when zero.
--opt-delta N Maximum delta for delta convergence test. Disabled when <= zero.
--opt-max-no-improvement N Maximum number of optimization iterations with no improvement. Disabled when <= zero.
--adam-epsf N AdamW epsilon for convergence test. Disabled when <= zero.
--adam-min-alpha N Adam minimum learning rate alpha, usually 0.1 * alpha
* replace memcpy with reshape operation so that the graph is not cut at the input
this makes it possible to store other values into the input tensor and then simply recompute the graph without rebuilding it
* remove unused function argument from get_example_targets_batch
* measure and print total training time
* add optimization callback to ggml_opt_resume_g
this callback is called before each iteration with custom data and pointer to learning schedule parameter (only used in Adam(W)).
can be used for dynamic learning schedule and setting input data for batches before each iteration
* use optimization callback in training
allows dynamic learning schedule and different batch data for each iteration without relying on low n_iter and high n_examples parameters
reduces runtime by avoiding restart of optimization function and improves training convergence by providing a different batch for each iteration
* add minimum number of tensor dimensions to apply weight decay (default 2)
this allows to not apply weight decay to bias parameters
* rename training parameter cos-decay-alpha to cos-decay-min and clarify that adam-min-alpha also applies to warmup
* fix increase of model.train_samples and model.train_tokens
now that each optimizer iteration gets its own batch we need to multiply by number of opt iterations
* change sampling parameters for prediction after training to defaults of common.h
and clarify what is context for prediction and what are generated tokens
* tighten abs error bounds for cross_entropy_loss in test-grad0
* add conditional compilation of using F16 exp in flash attention
uncomment `// #define GGML_FLASH_ATTN_EXP_FP16` to enable usage of f16 exp in flash attention
* tighten abs error bounds for flash_attn in test-grad0
* tighten abs error bounds for sqrt in test-grad0
* remove out-commented vectorized code of opt_adam
the vectorized code might be bit faster for low number of parameters, but it had a big memory usage overhead
* ggml : update ggml_rms_norm_back with configurable eps
* llama training : fix ggml_rms_norm_back calls to pass configurable eps
* remove trailing whitespace
* add train function using automatic gradient checkpointing backward pass and allocator
* in train function replace add_inplace by regular add
because using add_inplace seems to result in different gradients
* don't use allocate hash_map on context
because the context has no_alloc=True when using memory allocator resulting in NULL data pointers
* correctly clone reshape and permute operations by also cloning tensor->nb values
* fix variable name and add missing type cast
* terminate recursive tensor cloning when reaching tensor without src tensors
* correctly clone view tensors by setting data pointers
without this the checkpointing would only work when being used together with memory allocator
* fix variable names
* swap arguments to commutative ops to be the same as in `forward_batch_wo_cache_flash_attn`
* add input tensors as checkpoints
so that recursive tensor cloning of gradient checkpointing terminates on input tensors
* fix variable name and add missing boolean negation
* make sure some tensors are not reallocated by inserting new temporary nodes depending on them:
output and parameter gradient tensors need to be available at the end of the graph execution
parameter gradient tensors also need to be available before the graph execution because they are set to zero before each optimizer iteration
checkpoint tensors are allocated all together to reduce memory allocator fragmentation
afterwards, in addition to the temporary nodes, we also need to reset the temporary leafs
* fix ASSERT to work with zero layers
* add training options whether to use allocator and/or unified training function
* integrate unified training function which may use memory allocator
the unified training function also supports arguments whether to use flash attention and/or gradient checkpointing
* format name of cloned tensors with " (clone)" suffix
* set names for tensors in unified train function for easier debugging
* allocate graph on context using ggml_new_graph
* remove handwritten training functions
* remove unused training parameters "use_scratch" and "use_unified"
* remove trailing whitespace
* remove unused train params: mem_compute1_gb & mem_compute2_gb
mem_compute_gb is used for compute when automatic memory allocator is not enabled, otherwise it can be very small to only hold the tensor definitions
mem_compute0_gb is used for automatic memory allocator (as long as measurement of max required size is not implemented)
* remove unused forward_batch function
* add debug asserts in ggml_allocr_alloc to some common pitfalls when using this function directly
* only use ggml_allocr_alloc when tensor has NULL data and is no view
* fix test when to create temporary backward graph
temporary backward graph is only necessary when using checkpointing
* fix memory "leak" in optimizers
each iteration a new cplan with new memory for work data was allocated.
now cplan creation only happens at the start of optimization, with each iteration reusing the cplan and its work data.
* reverse order of for loop in ggml_build_backward_expand to save memory when using gradient checkpointing and allocator
with this loop order gradient checkpointing with allocator on 16 layer model saves 13% memory; 2 layer memory it saves 2% memory.
the computation results are the same
* add API functions to access llama model tensors
* add stub example for finetuning, based on train-text-from-scratch
* move and remove code
* add API functions to access remaining model parameters:
mult, head and rot
* first draft for LORA finetune training
* remove const model and layer arguments in API functions for accessing model tensors
* bug fixes to make finetune compile
automatic allocator does not work yet
* add debug prints for training memory improvements
* fix names of lora tensors
* avoid stack overflow resulting from big ggml_cgraph
replace stack allocation and ggml_build_forward by ggml_new_graph in combination with ggml_build_forward_expand
* replace llama API functions to get model tensors by one function to get model tensor by name
LLAMA_API struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name);
* remove unused call to not existing llama_get_layer_from_model
* implement ggml_compute_forward_out_prod_q_f32
* remove trailing whitespace
* add lora finetune support on quantized base model tensors
* add ggml_add_cast API function
this function works like ggml_add, but accepts a data type for the resulting tensor.
only supported for quantized src0 input.
* use ggml_add_cast in finetuning
lora-applied weights will now have data type F32, which improves gradients when finetuning quantized base models
* bug fix: actually use result type passed to ggml_add_cast
* make sure base model tensors data cannot be used in viewable operations
memory allocator would try to make lora application inplace on base model tensors.
since those are memory mapped this will result in memory access violations
* fix bug in ggml_out_prod which resulted in wrong n_dims of result tensors
* avoid keeping in memory ALL of the gradients
The problem here stems from ggml_graph_reset. This function is called in the optimization function, before each graph computation, to reset the gradients to zero. This required a unique memory slot for each gradient: allocating memory from a previosly freed memory location might lead to non-zero input gradients.
During ggml_compute_backward the gradients are build stepwise by adding or substracting new values, starting from a OP_NONE tensor which needs to contain zero-values. This requires the graph reset.
To avoid this I now remember in ggml_build_backward_expand the original OP_NONE gradient tensors in a hash table, which is passed to ggml_compute_backward. There instead of using add (or sub or similar) I test whether the existing gradient to be changed is a zero-valued-tensor by looking up its existence in the hash table. When it is such a zero-tensor it will not be modified, but replaced by the value to be added, otherwise the regular add (not inplace, allocator will take care of this) will be used. This way none of those zero-tensor values will be necessary in the final backward graph and more importantly they won't need a unique memory slot, just to make them zero.
* remove trailing whitespace
* remove debug prints and function to compute tensor data hash
* improve optimization iteration prints
* adjust maximal values to support finetuning 3B models
* change default finetune params lora_r and lora_alpha to match the n_rank parameters of 4
* bug fix: make sure finetune input gradient is allocated at begin and kept until end
* remove unnecessary src tensor from ggml_get_rows_back
we don't need data of src[2] for computation, only to setup the correct output shape.
remove dependency on src[2], so that allocator can work more freely.
the computational graph is still completely determined, because the output shape is naturally included.
this is similar to how ggml_reshape does it.
* remove unnecessary src tensor from ggml_repeat & ggml_repeat_back
we don't need data of src[1] for computation, only to setup the correct output shape.
remove dependency on src[1], so that allocator can work more freely.
the computational graph is still completely determined, because the output shape is naturally included
* resolve todo
allocator will only make it inplace when they are of the same type
* mixing multiple LORA adapters is now possible
pass more than one '--lora FNAME' argument to apply more than one LORA.
use '--lora-scaled FNAME S' when you want to specify a user-defined scale for an adapter.
* add option to save finetune output every N iterations
* also save latest finetune output with ITERATION="LATEST" and print where files are saved
saving with LATEST makes it easier to resume training from the latest checkpoint
the string "LATEST" can be configured with command line option "--fn-latest STR"
* update checkpoint train stats before saving via "--save-every"
* add command line option `--rank-wo N` for rank of wo tensor
* update finetune README
* fix dump_non_result_info_yaml to output multiple lora adapters
* bug fix: replace GGML_TYPE_SIZE[t] by ggml_type_size(t)
* replace llama_n_mult by llama_n_ff
* finetune bug fixes to compile with merged in code from master
* remove prediction related code to reduce duplicated code with main
use main instead
* reduce large memory overhead in train-text-from-scratch
all gradients had to be pinned so that graph_reset works correctly.
this is no longer necessary with the changes to ggml_compute_backward introduced in this PR.
* add comment explaining why finetune checkpoints are allocated in one block
* make default value of float member a float literal
* handle rms_norm and rope parameters the same as in train-text-from-scratch
* remove unused code
* remove vocab related code as it is unnecessary
* add LLM_KV_TRAINING_TYPE to train-text-from-scratch checkpoints
so that they can be differentiated from lora finetune checkpoints
* add gguf constants and load/save functions from train-text-from-scratch
* add load & save lora finetune checkpoints via gguf
* add python script to convert old finetune checkpoint files to gguf
* remove old checkpoint save & load code
* remove code to print data checksums which was used to verify correctness of new gguf code
* omit tokenization when training is disabled, only save llama lora adapter
training can be disabled by passing '-n 0' to finetune
* remove trailing whitespace
* update README.md
* implement ggml_compute_forward_repeat_f16
* avoid stack overflow of large cgraphs in test-grad0
* add ggml API functions ggml_unravel_index, ggml_get_i32_nd and its analogs for set and for f32
ggml_get_i32_1d, ggml_set_i32_1d, ggml_get_f32_1d, ggml_set_f32_1d now support non-contiguous tensors.
in case of non-contiguous tensor, the 1d index is unraveled into a multi index using ggml_unravel_index to be passed to '_nd' function equivalent.
this fixes a bug in test-grad0 which happens due to ggml_build_backward not building purely contiguous tensors anymore
* increase test-grad0 context mem size to accommodate for bigger cgraph
* add sanity check to ggml_compute_backward, asserting the correct shape of gradients
* fix ggml_acc_or_set to return tensor of correct shape
* remove unused 'inplace' argument from ggml_compute_backward function
inplace operations to add gradients are no longer created by ggml_compute_backward
use allocator to automatically make inplace operations
* add missing argument 'int i0' to ggml_get_i32_nd & ggml_set_i32_nd header declarations
* fix error message in ggml_allocr_alloc to display actual max_avail
* fix check_gradient
ggml_build_backward_expand was previously replaced by ggml_build_backward, but the assignment of forward graph to backward graph missing
* use tensor->view_src instead of ggml_is_view and get_view_source
* move gradient checkpointing code into ggml, new API function:
// build gradient checkpointing backward graph gb for gf using provided checkpoints
// gb_tmp will contain original backward graph with rewritten backward process nodes,
// but without the second forward pass nodes.
GGML_API void ggml_build_backward_gradient_checkpointing(
struct ggml_context * ctx,
struct ggml_cgraph * gf,
struct ggml_cgraph * gb,
struct ggml_cgraph * gb_tmp,
struct ggml_tensor * * checkpoints,
int n_checkpoints);
* replace custom data getters and setters by ggml functions
* train-text-from-scratch can train (full finetune) gguf models
just pass the gguf model via `--checkpoint-in FN`.
after this, to continue training, pass the generated checkpoint instead of the original gguf model.
tested with smaller models, bigger models may exceed available memory.
use (LORA) finetune for those.
* remove trailing whitespace
* add option to save train-text-from-scratch output every N iterations
* update README.md
* fix warnings
* fix warnings
* remove finetune option to disable allocator
the allocator should always be used.
by making sure that it is always used it gets easier to implement automatic memory requirements computation
* add tensor checkpoints only when gradient checkpointing is enabled
* initialize opt ggml context if none was provided
* add ggml-alloc API function 'ggml_allocr_max_size' to get max size of alloc
GGML_API size_t ggml_allocr_max_size(struct ggml_allocr * alloc);
* finetune: automatically allocate all memory and changes to command line options
remove '--n_examples N' parameter, as it no longer makes sense to call optimization process multiple times in a loop.
add '--only_write_lora' command line option: will skip tokenization and training, to only write a llama.cpp comptabile LORA adapter.
remove memory buffer related command line options.
improve iteration console output.
* add finetune to Makefile
* update README.md
* print time per iteration and estimate remaining time
* increase measured alloc size by tensor_alignment
ggml_allocr_reset will reduce the given size by up to tensor_alignment-1
* fix README.md
* add some more allocator debug prints
* bug fix, probably solves the 'ggml_allocr_alloc: not enough space in the buffer' issue
* revert last commit
"bug fix, probably solves the 'ggml_allocr_alloc: not enough space in the buffer' issue"
"alloc was freeing an externally allocated tensor, because it calculated the end of allocator memory as alloc->data + alloc->max_size instead of alloc->data + alloc->size."
This is intentional to reduce the risk of freeing external tensors when measuring. Unless max_size is not properly calculated, I don't see why this is an issue.
* remove unnecessary "0x" before "%p" output
* move measurement memory segment to upper region of the address space
* update README.md
* fix printf format warnings
* add missing gguf_free in load_checkpoint_lora_file
* load default rms_norm and rope parameters from base model
* add gradient accumulation
specify number accumulation steps with '--grad-acc N'.
this will simulate a bigger batch size of grad_acc*batch.
* fix tracking of train_samples and train_tokens
* build : fix compile warnings
* ggml : fix L-BFGS linesearch loop
* improve finetune time measurement
fix printf warnings on system where int64_t is (long int).
change time datatypes to double because values get big with long training times.
exclude file saving from time measurement.
converge faster to actual time per iteration by removing very small first duration before first iteration was performed.
fix bug in output of total training time, the reported value was 1000 times to small.
* specify default lora rank with '--lora-r N'
'--lora-r N' will specify default rank for all tensors
'--rank-wq N', etc. will override this default rank for specific tensor types.
* fix gradient accumulation bug where the same batch was used for each microstep
* fix gradient accumulation bug where the same batch was used for each microstep
* support grouped-query-attention in ggml_flash_attn and ggml_flash_attn_back
k and v can now be repeated in q along ne[2]
in forward pass just use modulo to compute k and v indices, like ik2 = iq2 % nek2.
in backard pass this won't work as easy, because multiple threads will compete to accumulate to the same k->grad[:,ik1,ik2,ik3] and v->grad[:,iv1,iv2,iv3].
so we change the parallelization over q rows to be over k rows. this ensures non-overlapping (ik2,ik3) across threads.
in each thread we then iterate over the number of repetitions of k/v in q to compute iq2 as iq2 = ik2 + irep*nek2.
since ne2 is not the same for q,k and v we also change how the gradients are concatenated into the result tensor.
additionally the offsets of gradq, gradk and gradv in the result tensor are now memory aligned.
we also simplify the compute_backward part of flash_attn to use ggml_reshape instead of switching over the number of dimensions.
this needs a small change to ggml_reshape, removing the assertion of second argument to be contiguous.
since only the shape (ne) of the second reshape argument is of relevance, its memory layout (nb) is irrelevant -> it can very well be non-contiguous.
change test-grad0 to also test for repeated k/v in q.
this changes the rng and now results in small gradient differences in softmax. these solely come from using f16 exp table lookup in forward softmax: when temporarily changing softmax to use actual exp function, the reported gradient differences go away. gradient differences coming solely from f16 table lookup are acceptable.
added a note to explain this.
* add llama API functions to get grouped-query-attention n_head parameter 'n_head_kv'.
* fix finetune to support grouped-query-attention (using flash-attention)
note: ggml changes to ggml_out_prod are necessary to support grouped-query-attention without flash-attention.
* support broadcastable a in out_prod(a, b) and backward pass of broadcasting mul_mat(a, b)
* test broadcasting mul_mat backward pass
* decouple random number generator of each operation test
when changing one test the rng of others tests is not influenced anymore
* add comment briefly describing what ggml_repeat_back does
* simplify broadcasting mul_mat backward using ggml_repeat_back
* add cgraph evaluation order member and corresponding enum type
this controls in which order ggml_build_forward visits source nodes.
by default the nodes are visited left to right, i.e. src[0] first.
in some cases it is beneficial for ggml-alloc to visit in a different order.
two possible orders are supported: left-to-right (src[0] first) and right-to-left (src[0] last).
* measure max compute size for each cgraph eval order and use best order
this can bring huge memory savings:
e.g. codellama-34b with n_ctx=64, n_batch=1 goes from 92927.8mb down to 4627.6 MB
* remove unused command line options
* add sample start patterns and options to force new or by default resume last shuffling
* update shuffle rng state on reshuffle
* exclude known zero values from computations in flash_attn_f32 & flash_attn_back_f32
* remove probably unnecessary exception type flags from stringstream
* pass correct max number of tokens to llama_tokenize
* account for possible leading whitespace that will be added by tokenizer
e.g. '\t' will be tokenized by llama spm tokenizer to [29871, 12]
* use unrolled vec_mad in out_prod
y is vec_mad result vec.
x is vec_mad input vec.
v is vec_mad input scalar.
ggml_vec_mad_f32_unroll will internally loop over x and v with same y.
GGML_VEC_MAD_UNROLL is by default defined to 32.
This value is empirical optimized using performance test runs of out-prod in openllama-3b finetune with 256 context length and batch size 1. It gives 23% performance boost for out_prod.
Full measurements of out-prod runtime in ms:
unroll_xv unroll_yv
1 67014.643 87826.469
2 77117.552 89077.656
4 72091.311 109121.657
8 61077.543 88678.334
16 56914.67 79514.947
24 59024.595 84350.254
28 55952.446 83368.73
32 51476.658 85177.745
36 55973.792 84659.92
40 55139.616 93844.738
48 60736.392 93330.267
64 99856.878 116994.99
Second column is when unrollying yv instead of xv
* set lora_alpha to value of lora_r if it is not set via command line
otherwise only changing lora_r will change scaling of lora adapter used in prediction
* reshuffle original sample order instead of the previous shuffled order
otherwise resumed reshuffle will not result in same sample order
* block tiling for out-prod inspired by mul-mat
block sizes are empirically optimized
roughly doubles the flops of out-prod
* exclude some more known zero values from computations in flash_attn_f32 & flash_attn_back_f32
* add static keywords
* remove outcommented old code
* update train-text-from-scratch with tokenization, sample selection and shuffling from finetune
* remove lbfgs related train parameters
* move common train functions into common/train.[h|cpp]
* move train state into struct train_state
* move train data saving code into callback to unify code of opt_callback
train_params are still different in finetune and train-text-from-scratch, so it can't yet be moved to train.h|cpp
* move common train params into common/train
* move common opt_callback into common/train
* fix consume_common_train_arg
* save and load head_count_kv in lora checkpoints
* increase train_samples by used_samples instead of number of batches
on batch can contain more than one sample when option "fill_with_next_samples" is used
* fix usage of llama_tokenize
* remove static from process_escape since we need it exposed in header
* fix code formating of long function declarations
* fix condition in load_train_state_gguf
* use die("msg") instead of replace GGML_ASSERT(!"msg") or throw std::runtime_error("msg")
* fix saving and loading of training type
* remove terminating '\0' from tokenization
(llama_tokenize is now passed the string length instead of relying on terminating '\0')
* fix compile warnings
* fix compile warnings
* use new/delete for train_state instead of malloc/free
using malloc may result in seg faults when trying to assign string fields
* assert that sample_count > 0, avoiding division by zero
* fix frand to return value in interval [0,1)
* add train option "--sample-random-offsets"
Use samples beginning at random offsets.
The offset is only applied to the first sample in each batch context window.
Together with "--fill-with-next-samples" this may help for training endless text generation.
For example given a dataset containing samples "abcd", "ABCD", "0123".
With context size of 8 and options "--fill-with-next-samples", "--no-separate-with-eos", "--no-separate-with-bos",
the context windows of batches could only be filled with "abcdABCD", "ABCDabcd", "0123abcd", etc.
With "--sample-random-offsets" it can also be filled with "23abcdAB", "bcd0123A", etc.
* deduplicate code into function
* remove n_rot hparam, as it must always be hparam.n_embd_head()
* align code
* assert correct base model tensor shapes
* move some params from lora hparams into model hparams and load model params from gguf
this equalizes the model definition in finetune and text-from-scratch and removes the need for additional llama api functions to get model parameters
* remove now unnecessary llama API functions to get model params that where added by this PR
* train-text-from-scratch: automatically allocate model tensors, remove option '--mem-model N'
* train-text-from-scratch: automatically allocate opt context
* train-text-from-scratch: automatically allocate input tensors
* train-text-from-scratch: automatically allocate compute memory
* remove unused options and equalize train-text-from-scratch with finetune
* initialize opt->loss_after with zero
* add export-lora program
* remove trailing whitespace
* add export-lora build in Makefile
* remove unused struct tensor_info from export-lora
* add export-lora build dependency to llama
because it depends on common, which depends on llama
* update finetune README.md
* cancel optimization when specified number of epochs is completed
* improve handling of export-lora arguments
print errors and warnings when files could not be read or created
* Fix export-lora.cpp "not enough space in the context's memory pool" (#1)
* Fix export-lora.cpp "not enough space in the context's memory pool"
Without this patch, export-lora would sometimes error with "not enough space in the context's memory pool (needed 656784, available 656800)".
* increase required context size by 5*GGML_MEM_ALIGN instead of plain 16
---------
Co-authored-by: xaedes <xaedes@gmail.com>
* improve handling of not yet supported tensor types
---------
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
Co-authored-by: meatbag-18a <145869052+meatbag-18a@users.noreply.github.com>
2023-09-28 20:40:11 +02:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
bool ggml_gallocr_reserve(ggml_gallocr_t galloc, struct ggml_cgraph *graph) {
|
|
|
|
return ggml_gallocr_reserve_n(galloc, graph, NULL);
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static void ggml_gallocr_init_tensor(ggml_gallocr_t galloc, struct ggml_tensor * node, struct node_alloc * node_alloc, struct tensor_alloc * tensor_alloc) {
|
|
|
|
assert(node->data || node->view_src || ggml_backend_buffer_get_alloc_size(galloc->buffers[node_alloc->buffer_id], node) <= tensor_alloc->size_max);
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
if (node->view_src != NULL) {
|
|
|
|
if (node->buffer == NULL) {
|
|
|
|
assert(tensor_alloc->offset == SIZE_MAX);
|
|
|
|
if (node->view_src->buffer == NULL) {
|
|
|
|
// this tensor was allocated without ggml-backend
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
ggml_backend_view_init(galloc->buffers[node_alloc->buffer_id], node);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (node->data == NULL) {
|
|
|
|
assert(tensor_alloc->offset != SIZE_MAX);
|
|
|
|
assert(ggml_backend_buffer_get_alloc_size(galloc->buffers[node_alloc->buffer_id], node) <= tensor_alloc->size_max);
|
|
|
|
void * base = ggml_backend_buffer_get_base(galloc->buffers[node_alloc->buffer_id]);
|
|
|
|
void * addr = (char *)base + tensor_alloc->offset;
|
|
|
|
ggml_backend_tensor_alloc(galloc->buffers[node_alloc->buffer_id], node, addr);
|
|
|
|
} else {
|
|
|
|
if (node->buffer == NULL) {
|
|
|
|
// this tensor was allocated without ggml-backend
|
|
|
|
return;
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
#ifndef NDEBUG
|
|
|
|
size_t offset =
|
|
|
|
(char *)node->data -
|
|
|
|
(char *)ggml_backend_buffer_get_base(node->buffer);
|
|
|
|
size_t size = ggml_backend_buffer_get_alloc_size(node->buffer, node);
|
|
|
|
assert(tensor_alloc->offset == SIZE_MAX || offset == tensor_alloc->offset);
|
|
|
|
assert(tensor_alloc->offset == SIZE_MAX || size <= tensor_alloc->size_max);
|
|
|
|
#endif
|
|
|
|
}
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static bool ggml_gallocr_node_needs_realloc(ggml_gallocr_t galloc, struct ggml_tensor * node, struct node_alloc * nalloc, struct tensor_alloc * talloc) {
|
|
|
|
ggml_backend_buffer_type_t buft = galloc->bufts[nalloc->buffer_id];
|
|
|
|
size_t node_size = (node->data || node->view_src) ? 0 : ggml_backend_buft_get_alloc_size(buft, node);
|
|
|
|
return talloc->size_max >= node_size;
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
static bool ggml_gallocr_needs_realloc(ggml_gallocr_t galloc, struct ggml_cgraph * graph) {
|
|
|
|
if (galloc->n_nodes != graph->n_nodes) {
|
|
|
|
#ifndef NDEBUG
|
|
|
|
fprintf(stderr, "%s: graph has different number of nodes\n", __func__);
|
|
|
|
#endif
|
|
|
|
return true;
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
|
|
struct node_alloc * node_alloc = &galloc->node_allocs[i];
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
if (!ggml_gallocr_node_needs_realloc(galloc, node, node_alloc, &node_alloc->dst)) {
|
|
|
|
#ifndef NDEBUG
|
|
|
|
fprintf(stderr, "%s: node %s is not valid\n", __func__, node->name);
|
|
|
|
#endif
|
|
|
|
return true;
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
struct ggml_tensor * src = node->src[j];
|
|
|
|
if (src == NULL) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if (!ggml_gallocr_node_needs_realloc(galloc, src, node_alloc, &node_alloc->src[j])) {
|
|
|
|
#ifndef NDEBUG
|
|
|
|
fprintf(stderr, "%s: src %d (%s) of node %s is not valid\n", __func__, j, src->name, node->name);
|
|
|
|
#endif
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
2023-12-21 21:07:46 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
return false;
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
bool ggml_gallocr_alloc_graph(ggml_gallocr_t galloc, struct ggml_cgraph * graph) {
|
|
|
|
if (ggml_gallocr_needs_realloc(galloc, graph)) {
|
|
|
|
if (galloc->n_buffers == 1) {
|
|
|
|
#ifndef NDEBUG
|
|
|
|
fprintf(stderr, "%s: reallocating buffers automatically\n", __func__);
|
|
|
|
#endif
|
|
|
|
if (!ggml_gallocr_reserve(galloc, graph)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
#ifndef NDEBUG
|
|
|
|
fprintf(stderr, "%s: cannot reallocate multi buffer graph automatically, call reserve\n", __func__);
|
|
|
|
#endif
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// reset buffers
|
|
|
|
for (int i = 0; i < galloc->n_buffers; i++) {
|
|
|
|
// zero size buffers are not allocated
|
|
|
|
if (galloc->buffers[i] != NULL) {
|
|
|
|
ggml_backend_buffer_reset(galloc->buffers[i]);
|
|
|
|
}
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
// allocate the graph tensors from the previous assignments
|
|
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
|
|
struct node_alloc * node_alloc = &galloc->node_allocs[i];
|
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
struct ggml_tensor * src = node->src[j];
|
|
|
|
if (src == NULL) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
ggml_gallocr_init_tensor(galloc, src, node_alloc, &node_alloc->src[j]);
|
|
|
|
}
|
|
|
|
ggml_gallocr_init_tensor(galloc, node, node_alloc, &node_alloc->dst);
|
|
|
|
}
|
2023-11-13 13:16:23 +01:00
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
return true;
|
2023-11-13 13:16:23 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
size_t ggml_gallocr_get_buffer_size(ggml_gallocr_t galloc, int buffer_id) {
|
|
|
|
GGML_ASSERT(buffer_id >= 0 && buffer_id < galloc->n_buffers);
|
|
|
|
|
|
|
|
if (galloc->buffers[buffer_id] == NULL) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
return ggml_backend_buffer_get_size(galloc->buffers[buffer_id]);
|
train : finetune LORA (#2632)
* fix track_max_mem in forward_batch_wo_cache_flash_attn_train
* remove unnecessary Adam(W) optimizer tensors.
reduces optimizer memory overhead from 7*modelsize to 2*modelsize.
additionally allows to optimize models with more than 2^31 parameters by replacing int with int64_t.
bumps training checkpoint file version, but old checkpoints can still be read.
new version with less tensors is saved.
* add gradient clipping to AdamW
* Fix reset of unused g->nodes and g->grads to NULL
* implement gradient checkpointing for training
reduces memory overhead from O(n_layer) to O(sqrt(n_layer))
as explained in readme of https://github.com/cybertronai/gradient-checkpointing
* remove unused compute buffer 3
* add and use function ggml_build_backward_expand to avoid stack overflows with large maximum number of nodes
GGML_API void ggml_build_backward_expand(struct ggml_context * ctx, struct ggml_cgraph * gf, struct ggml_cgraph * gb, bool keep);
* change AdamW decay parameter to work like the torch AdamW decay parameter
It is now relative to Adam learning rate `alpha*sched`.
Before that it was relative to `sched` only.
`alpha` being the maximum learning rate and `sched` being a scaling parameter in [0..1]
* change default AdamW weight decay parameter used in training to 0.1 as used in nanoGPT
* change default AdamW weight decay parameter defined in ggml to 0.0, making Adam default instead of AdamW
btw: the default weight decay parameter for torch.optim.AdamW is 0.01
* bug fixes for cross entropy loss
ggml_cross_entropy_loss: sums where not correctly added in workload of each thread
ggml_cross_entropy_loss_back: simplify backward process, reducing numerical issues
guard usage of exp f16 lookup in cross entropy by #define GGML_CROSS_ENTROPY_EXP_FP16
cross entropy loss is only used once during training, but it is quite sensitive to numerical errors introduced by exp-f16-lookup.
so exp-f16-lookup for cross entropy loss is disabled by default, trading better gradients for very slightly worse runtime performance.
* fix test-grad0 for cross_entropy_loss
the second argument to cross_entropy_loss must sum up to 1 for each row
* fix test-grad0 for soft_max
dont use only sum as aggregation, because sum of softmax is always 1 -> finite differences should not work
instead use sum(log(soft_max()*(1-eps)+eps)); use eps to avoid log(0)
* improve finite differences of test-grad0 by using double instead of float
* change cross_entropy_loss to output average over all rows
this helps keeping the loss and gradients in a sane range
* improve gradient checkpointing
sqrt(n_layers) is only the best checkpoint step when mem size of checkpoints and mem size of layers are equal.
since layers require more memory than the single-tensor-checkpoint we use, the optimal values are compute different:
```
given: n, u, v
objective: minimize(a*u+b*v) where a*b=n, a>0, b>0
b=n/a
minimize(a*u+v*n/a)
diff(a*u+v*n/a, a) = u - (v*n/a)/a
diff(a*u+v*n/a, a) == 0
u - (v*n/a)/a == 0
u == v*n/(a*a)
u*a*a = v*n
a*a = v*n/u
a = sqrt(n*v/u)
```
this change results in more checkpoints, requiring less layers to store between checkpoints, overall improving memory usage.
* disable gradient checkpointing debug output
* llama : fix rope usage in train-text-from-scratch after ChatGLM change
* add more training parameters:
--enable-restart N Only for Adam optimizer. Enable restarts of cos-decay
--disable-restart N Only for Adam optimizer. Disable restarts of cos-decay
--opt-past N Number of optimization iterations to track for delta convergence test. Disabled when zero.
--opt-delta N Maximum delta for delta convergence test. Disabled when <= zero.
--opt-max-no-improvement N Maximum number of optimization iterations with no improvement. Disabled when <= zero.
--adam-epsf N AdamW epsilon for convergence test. Disabled when <= zero.
--adam-min-alpha N Adam minimum learning rate alpha, usually 0.1 * alpha
* replace memcpy with reshape operation so that the graph is not cut at the input
this makes it possible to store other values into the input tensor and then simply recompute the graph without rebuilding it
* remove unused function argument from get_example_targets_batch
* measure and print total training time
* add optimization callback to ggml_opt_resume_g
this callback is called before each iteration with custom data and pointer to learning schedule parameter (only used in Adam(W)).
can be used for dynamic learning schedule and setting input data for batches before each iteration
* use optimization callback in training
allows dynamic learning schedule and different batch data for each iteration without relying on low n_iter and high n_examples parameters
reduces runtime by avoiding restart of optimization function and improves training convergence by providing a different batch for each iteration
* add minimum number of tensor dimensions to apply weight decay (default 2)
this allows to not apply weight decay to bias parameters
* rename training parameter cos-decay-alpha to cos-decay-min and clarify that adam-min-alpha also applies to warmup
* fix increase of model.train_samples and model.train_tokens
now that each optimizer iteration gets its own batch we need to multiply by number of opt iterations
* change sampling parameters for prediction after training to defaults of common.h
and clarify what is context for prediction and what are generated tokens
* tighten abs error bounds for cross_entropy_loss in test-grad0
* add conditional compilation of using F16 exp in flash attention
uncomment `// #define GGML_FLASH_ATTN_EXP_FP16` to enable usage of f16 exp in flash attention
* tighten abs error bounds for flash_attn in test-grad0
* tighten abs error bounds for sqrt in test-grad0
* remove out-commented vectorized code of opt_adam
the vectorized code might be bit faster for low number of parameters, but it had a big memory usage overhead
* ggml : update ggml_rms_norm_back with configurable eps
* llama training : fix ggml_rms_norm_back calls to pass configurable eps
* remove trailing whitespace
* add train function using automatic gradient checkpointing backward pass and allocator
* in train function replace add_inplace by regular add
because using add_inplace seems to result in different gradients
* don't use allocate hash_map on context
because the context has no_alloc=True when using memory allocator resulting in NULL data pointers
* correctly clone reshape and permute operations by also cloning tensor->nb values
* fix variable name and add missing type cast
* terminate recursive tensor cloning when reaching tensor without src tensors
* correctly clone view tensors by setting data pointers
without this the checkpointing would only work when being used together with memory allocator
* fix variable names
* swap arguments to commutative ops to be the same as in `forward_batch_wo_cache_flash_attn`
* add input tensors as checkpoints
so that recursive tensor cloning of gradient checkpointing terminates on input tensors
* fix variable name and add missing boolean negation
* make sure some tensors are not reallocated by inserting new temporary nodes depending on them:
output and parameter gradient tensors need to be available at the end of the graph execution
parameter gradient tensors also need to be available before the graph execution because they are set to zero before each optimizer iteration
checkpoint tensors are allocated all together to reduce memory allocator fragmentation
afterwards, in addition to the temporary nodes, we also need to reset the temporary leafs
* fix ASSERT to work with zero layers
* add training options whether to use allocator and/or unified training function
* integrate unified training function which may use memory allocator
the unified training function also supports arguments whether to use flash attention and/or gradient checkpointing
* format name of cloned tensors with " (clone)" suffix
* set names for tensors in unified train function for easier debugging
* allocate graph on context using ggml_new_graph
* remove handwritten training functions
* remove unused training parameters "use_scratch" and "use_unified"
* remove trailing whitespace
* remove unused train params: mem_compute1_gb & mem_compute2_gb
mem_compute_gb is used for compute when automatic memory allocator is not enabled, otherwise it can be very small to only hold the tensor definitions
mem_compute0_gb is used for automatic memory allocator (as long as measurement of max required size is not implemented)
* remove unused forward_batch function
* add debug asserts in ggml_allocr_alloc to some common pitfalls when using this function directly
* only use ggml_allocr_alloc when tensor has NULL data and is no view
* fix test when to create temporary backward graph
temporary backward graph is only necessary when using checkpointing
* fix memory "leak" in optimizers
each iteration a new cplan with new memory for work data was allocated.
now cplan creation only happens at the start of optimization, with each iteration reusing the cplan and its work data.
* reverse order of for loop in ggml_build_backward_expand to save memory when using gradient checkpointing and allocator
with this loop order gradient checkpointing with allocator on 16 layer model saves 13% memory; 2 layer memory it saves 2% memory.
the computation results are the same
* add API functions to access llama model tensors
* add stub example for finetuning, based on train-text-from-scratch
* move and remove code
* add API functions to access remaining model parameters:
mult, head and rot
* first draft for LORA finetune training
* remove const model and layer arguments in API functions for accessing model tensors
* bug fixes to make finetune compile
automatic allocator does not work yet
* add debug prints for training memory improvements
* fix names of lora tensors
* avoid stack overflow resulting from big ggml_cgraph
replace stack allocation and ggml_build_forward by ggml_new_graph in combination with ggml_build_forward_expand
* replace llama API functions to get model tensors by one function to get model tensor by name
LLAMA_API struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name);
* remove unused call to not existing llama_get_layer_from_model
* implement ggml_compute_forward_out_prod_q_f32
* remove trailing whitespace
* add lora finetune support on quantized base model tensors
* add ggml_add_cast API function
this function works like ggml_add, but accepts a data type for the resulting tensor.
only supported for quantized src0 input.
* use ggml_add_cast in finetuning
lora-applied weights will now have data type F32, which improves gradients when finetuning quantized base models
* bug fix: actually use result type passed to ggml_add_cast
* make sure base model tensors data cannot be used in viewable operations
memory allocator would try to make lora application inplace on base model tensors.
since those are memory mapped this will result in memory access violations
* fix bug in ggml_out_prod which resulted in wrong n_dims of result tensors
* avoid keeping in memory ALL of the gradients
The problem here stems from ggml_graph_reset. This function is called in the optimization function, before each graph computation, to reset the gradients to zero. This required a unique memory slot for each gradient: allocating memory from a previosly freed memory location might lead to non-zero input gradients.
During ggml_compute_backward the gradients are build stepwise by adding or substracting new values, starting from a OP_NONE tensor which needs to contain zero-values. This requires the graph reset.
To avoid this I now remember in ggml_build_backward_expand the original OP_NONE gradient tensors in a hash table, which is passed to ggml_compute_backward. There instead of using add (or sub or similar) I test whether the existing gradient to be changed is a zero-valued-tensor by looking up its existence in the hash table. When it is such a zero-tensor it will not be modified, but replaced by the value to be added, otherwise the regular add (not inplace, allocator will take care of this) will be used. This way none of those zero-tensor values will be necessary in the final backward graph and more importantly they won't need a unique memory slot, just to make them zero.
* remove trailing whitespace
* remove debug prints and function to compute tensor data hash
* improve optimization iteration prints
* adjust maximal values to support finetuning 3B models
* change default finetune params lora_r and lora_alpha to match the n_rank parameters of 4
* bug fix: make sure finetune input gradient is allocated at begin and kept until end
* remove unnecessary src tensor from ggml_get_rows_back
we don't need data of src[2] for computation, only to setup the correct output shape.
remove dependency on src[2], so that allocator can work more freely.
the computational graph is still completely determined, because the output shape is naturally included.
this is similar to how ggml_reshape does it.
* remove unnecessary src tensor from ggml_repeat & ggml_repeat_back
we don't need data of src[1] for computation, only to setup the correct output shape.
remove dependency on src[1], so that allocator can work more freely.
the computational graph is still completely determined, because the output shape is naturally included
* resolve todo
allocator will only make it inplace when they are of the same type
* mixing multiple LORA adapters is now possible
pass more than one '--lora FNAME' argument to apply more than one LORA.
use '--lora-scaled FNAME S' when you want to specify a user-defined scale for an adapter.
* add option to save finetune output every N iterations
* also save latest finetune output with ITERATION="LATEST" and print where files are saved
saving with LATEST makes it easier to resume training from the latest checkpoint
the string "LATEST" can be configured with command line option "--fn-latest STR"
* update checkpoint train stats before saving via "--save-every"
* add command line option `--rank-wo N` for rank of wo tensor
* update finetune README
* fix dump_non_result_info_yaml to output multiple lora adapters
* bug fix: replace GGML_TYPE_SIZE[t] by ggml_type_size(t)
* replace llama_n_mult by llama_n_ff
* finetune bug fixes to compile with merged in code from master
* remove prediction related code to reduce duplicated code with main
use main instead
* reduce large memory overhead in train-text-from-scratch
all gradients had to be pinned so that graph_reset works correctly.
this is no longer necessary with the changes to ggml_compute_backward introduced in this PR.
* add comment explaining why finetune checkpoints are allocated in one block
* make default value of float member a float literal
* handle rms_norm and rope parameters the same as in train-text-from-scratch
* remove unused code
* remove vocab related code as it is unnecessary
* add LLM_KV_TRAINING_TYPE to train-text-from-scratch checkpoints
so that they can be differentiated from lora finetune checkpoints
* add gguf constants and load/save functions from train-text-from-scratch
* add load & save lora finetune checkpoints via gguf
* add python script to convert old finetune checkpoint files to gguf
* remove old checkpoint save & load code
* remove code to print data checksums which was used to verify correctness of new gguf code
* omit tokenization when training is disabled, only save llama lora adapter
training can be disabled by passing '-n 0' to finetune
* remove trailing whitespace
* update README.md
* implement ggml_compute_forward_repeat_f16
* avoid stack overflow of large cgraphs in test-grad0
* add ggml API functions ggml_unravel_index, ggml_get_i32_nd and its analogs for set and for f32
ggml_get_i32_1d, ggml_set_i32_1d, ggml_get_f32_1d, ggml_set_f32_1d now support non-contiguous tensors.
in case of non-contiguous tensor, the 1d index is unraveled into a multi index using ggml_unravel_index to be passed to '_nd' function equivalent.
this fixes a bug in test-grad0 which happens due to ggml_build_backward not building purely contiguous tensors anymore
* increase test-grad0 context mem size to accommodate for bigger cgraph
* add sanity check to ggml_compute_backward, asserting the correct shape of gradients
* fix ggml_acc_or_set to return tensor of correct shape
* remove unused 'inplace' argument from ggml_compute_backward function
inplace operations to add gradients are no longer created by ggml_compute_backward
use allocator to automatically make inplace operations
* add missing argument 'int i0' to ggml_get_i32_nd & ggml_set_i32_nd header declarations
* fix error message in ggml_allocr_alloc to display actual max_avail
* fix check_gradient
ggml_build_backward_expand was previously replaced by ggml_build_backward, but the assignment of forward graph to backward graph missing
* use tensor->view_src instead of ggml_is_view and get_view_source
* move gradient checkpointing code into ggml, new API function:
// build gradient checkpointing backward graph gb for gf using provided checkpoints
// gb_tmp will contain original backward graph with rewritten backward process nodes,
// but without the second forward pass nodes.
GGML_API void ggml_build_backward_gradient_checkpointing(
struct ggml_context * ctx,
struct ggml_cgraph * gf,
struct ggml_cgraph * gb,
struct ggml_cgraph * gb_tmp,
struct ggml_tensor * * checkpoints,
int n_checkpoints);
* replace custom data getters and setters by ggml functions
* train-text-from-scratch can train (full finetune) gguf models
just pass the gguf model via `--checkpoint-in FN`.
after this, to continue training, pass the generated checkpoint instead of the original gguf model.
tested with smaller models, bigger models may exceed available memory.
use (LORA) finetune for those.
* remove trailing whitespace
* add option to save train-text-from-scratch output every N iterations
* update README.md
* fix warnings
* fix warnings
* remove finetune option to disable allocator
the allocator should always be used.
by making sure that it is always used it gets easier to implement automatic memory requirements computation
* add tensor checkpoints only when gradient checkpointing is enabled
* initialize opt ggml context if none was provided
* add ggml-alloc API function 'ggml_allocr_max_size' to get max size of alloc
GGML_API size_t ggml_allocr_max_size(struct ggml_allocr * alloc);
* finetune: automatically allocate all memory and changes to command line options
remove '--n_examples N' parameter, as it no longer makes sense to call optimization process multiple times in a loop.
add '--only_write_lora' command line option: will skip tokenization and training, to only write a llama.cpp comptabile LORA adapter.
remove memory buffer related command line options.
improve iteration console output.
* add finetune to Makefile
* update README.md
* print time per iteration and estimate remaining time
* increase measured alloc size by tensor_alignment
ggml_allocr_reset will reduce the given size by up to tensor_alignment-1
* fix README.md
* add some more allocator debug prints
* bug fix, probably solves the 'ggml_allocr_alloc: not enough space in the buffer' issue
* revert last commit
"bug fix, probably solves the 'ggml_allocr_alloc: not enough space in the buffer' issue"
"alloc was freeing an externally allocated tensor, because it calculated the end of allocator memory as alloc->data + alloc->max_size instead of alloc->data + alloc->size."
This is intentional to reduce the risk of freeing external tensors when measuring. Unless max_size is not properly calculated, I don't see why this is an issue.
* remove unnecessary "0x" before "%p" output
* move measurement memory segment to upper region of the address space
* update README.md
* fix printf format warnings
* add missing gguf_free in load_checkpoint_lora_file
* load default rms_norm and rope parameters from base model
* add gradient accumulation
specify number accumulation steps with '--grad-acc N'.
this will simulate a bigger batch size of grad_acc*batch.
* fix tracking of train_samples and train_tokens
* build : fix compile warnings
* ggml : fix L-BFGS linesearch loop
* improve finetune time measurement
fix printf warnings on system where int64_t is (long int).
change time datatypes to double because values get big with long training times.
exclude file saving from time measurement.
converge faster to actual time per iteration by removing very small first duration before first iteration was performed.
fix bug in output of total training time, the reported value was 1000 times to small.
* specify default lora rank with '--lora-r N'
'--lora-r N' will specify default rank for all tensors
'--rank-wq N', etc. will override this default rank for specific tensor types.
* fix gradient accumulation bug where the same batch was used for each microstep
* fix gradient accumulation bug where the same batch was used for each microstep
* support grouped-query-attention in ggml_flash_attn and ggml_flash_attn_back
k and v can now be repeated in q along ne[2]
in forward pass just use modulo to compute k and v indices, like ik2 = iq2 % nek2.
in backard pass this won't work as easy, because multiple threads will compete to accumulate to the same k->grad[:,ik1,ik2,ik3] and v->grad[:,iv1,iv2,iv3].
so we change the parallelization over q rows to be over k rows. this ensures non-overlapping (ik2,ik3) across threads.
in each thread we then iterate over the number of repetitions of k/v in q to compute iq2 as iq2 = ik2 + irep*nek2.
since ne2 is not the same for q,k and v we also change how the gradients are concatenated into the result tensor.
additionally the offsets of gradq, gradk and gradv in the result tensor are now memory aligned.
we also simplify the compute_backward part of flash_attn to use ggml_reshape instead of switching over the number of dimensions.
this needs a small change to ggml_reshape, removing the assertion of second argument to be contiguous.
since only the shape (ne) of the second reshape argument is of relevance, its memory layout (nb) is irrelevant -> it can very well be non-contiguous.
change test-grad0 to also test for repeated k/v in q.
this changes the rng and now results in small gradient differences in softmax. these solely come from using f16 exp table lookup in forward softmax: when temporarily changing softmax to use actual exp function, the reported gradient differences go away. gradient differences coming solely from f16 table lookup are acceptable.
added a note to explain this.
* add llama API functions to get grouped-query-attention n_head parameter 'n_head_kv'.
* fix finetune to support grouped-query-attention (using flash-attention)
note: ggml changes to ggml_out_prod are necessary to support grouped-query-attention without flash-attention.
* support broadcastable a in out_prod(a, b) and backward pass of broadcasting mul_mat(a, b)
* test broadcasting mul_mat backward pass
* decouple random number generator of each operation test
when changing one test the rng of others tests is not influenced anymore
* add comment briefly describing what ggml_repeat_back does
* simplify broadcasting mul_mat backward using ggml_repeat_back
* add cgraph evaluation order member and corresponding enum type
this controls in which order ggml_build_forward visits source nodes.
by default the nodes are visited left to right, i.e. src[0] first.
in some cases it is beneficial for ggml-alloc to visit in a different order.
two possible orders are supported: left-to-right (src[0] first) and right-to-left (src[0] last).
* measure max compute size for each cgraph eval order and use best order
this can bring huge memory savings:
e.g. codellama-34b with n_ctx=64, n_batch=1 goes from 92927.8mb down to 4627.6 MB
* remove unused command line options
* add sample start patterns and options to force new or by default resume last shuffling
* update shuffle rng state on reshuffle
* exclude known zero values from computations in flash_attn_f32 & flash_attn_back_f32
* remove probably unnecessary exception type flags from stringstream
* pass correct max number of tokens to llama_tokenize
* account for possible leading whitespace that will be added by tokenizer
e.g. '\t' will be tokenized by llama spm tokenizer to [29871, 12]
* use unrolled vec_mad in out_prod
y is vec_mad result vec.
x is vec_mad input vec.
v is vec_mad input scalar.
ggml_vec_mad_f32_unroll will internally loop over x and v with same y.
GGML_VEC_MAD_UNROLL is by default defined to 32.
This value is empirical optimized using performance test runs of out-prod in openllama-3b finetune with 256 context length and batch size 1. It gives 23% performance boost for out_prod.
Full measurements of out-prod runtime in ms:
unroll_xv unroll_yv
1 67014.643 87826.469
2 77117.552 89077.656
4 72091.311 109121.657
8 61077.543 88678.334
16 56914.67 79514.947
24 59024.595 84350.254
28 55952.446 83368.73
32 51476.658 85177.745
36 55973.792 84659.92
40 55139.616 93844.738
48 60736.392 93330.267
64 99856.878 116994.99
Second column is when unrollying yv instead of xv
* set lora_alpha to value of lora_r if it is not set via command line
otherwise only changing lora_r will change scaling of lora adapter used in prediction
* reshuffle original sample order instead of the previous shuffled order
otherwise resumed reshuffle will not result in same sample order
* block tiling for out-prod inspired by mul-mat
block sizes are empirically optimized
roughly doubles the flops of out-prod
* exclude some more known zero values from computations in flash_attn_f32 & flash_attn_back_f32
* add static keywords
* remove outcommented old code
* update train-text-from-scratch with tokenization, sample selection and shuffling from finetune
* remove lbfgs related train parameters
* move common train functions into common/train.[h|cpp]
* move train state into struct train_state
* move train data saving code into callback to unify code of opt_callback
train_params are still different in finetune and train-text-from-scratch, so it can't yet be moved to train.h|cpp
* move common train params into common/train
* move common opt_callback into common/train
* fix consume_common_train_arg
* save and load head_count_kv in lora checkpoints
* increase train_samples by used_samples instead of number of batches
on batch can contain more than one sample when option "fill_with_next_samples" is used
* fix usage of llama_tokenize
* remove static from process_escape since we need it exposed in header
* fix code formating of long function declarations
* fix condition in load_train_state_gguf
* use die("msg") instead of replace GGML_ASSERT(!"msg") or throw std::runtime_error("msg")
* fix saving and loading of training type
* remove terminating '\0' from tokenization
(llama_tokenize is now passed the string length instead of relying on terminating '\0')
* fix compile warnings
* fix compile warnings
* use new/delete for train_state instead of malloc/free
using malloc may result in seg faults when trying to assign string fields
* assert that sample_count > 0, avoiding division by zero
* fix frand to return value in interval [0,1)
* add train option "--sample-random-offsets"
Use samples beginning at random offsets.
The offset is only applied to the first sample in each batch context window.
Together with "--fill-with-next-samples" this may help for training endless text generation.
For example given a dataset containing samples "abcd", "ABCD", "0123".
With context size of 8 and options "--fill-with-next-samples", "--no-separate-with-eos", "--no-separate-with-bos",
the context windows of batches could only be filled with "abcdABCD", "ABCDabcd", "0123abcd", etc.
With "--sample-random-offsets" it can also be filled with "23abcdAB", "bcd0123A", etc.
* deduplicate code into function
* remove n_rot hparam, as it must always be hparam.n_embd_head()
* align code
* assert correct base model tensor shapes
* move some params from lora hparams into model hparams and load model params from gguf
this equalizes the model definition in finetune and text-from-scratch and removes the need for additional llama api functions to get model parameters
* remove now unnecessary llama API functions to get model params that where added by this PR
* train-text-from-scratch: automatically allocate model tensors, remove option '--mem-model N'
* train-text-from-scratch: automatically allocate opt context
* train-text-from-scratch: automatically allocate input tensors
* train-text-from-scratch: automatically allocate compute memory
* remove unused options and equalize train-text-from-scratch with finetune
* initialize opt->loss_after with zero
* add export-lora program
* remove trailing whitespace
* add export-lora build in Makefile
* remove unused struct tensor_info from export-lora
* add export-lora build dependency to llama
because it depends on common, which depends on llama
* update finetune README.md
* cancel optimization when specified number of epochs is completed
* improve handling of export-lora arguments
print errors and warnings when files could not be read or created
* Fix export-lora.cpp "not enough space in the context's memory pool" (#1)
* Fix export-lora.cpp "not enough space in the context's memory pool"
Without this patch, export-lora would sometimes error with "not enough space in the context's memory pool (needed 656784, available 656800)".
* increase required context size by 5*GGML_MEM_ALIGN instead of plain 16
---------
Co-authored-by: xaedes <xaedes@gmail.com>
* improve handling of not yet supported tensor types
---------
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
Co-authored-by: meatbag-18a <145869052+meatbag-18a@users.noreply.github.com>
2023-09-28 20:40:11 +02:00
|
|
|
}
|
2023-12-07 21:26:54 +01:00
|
|
|
|
|
|
|
// utils
|
|
|
|
|
ggml : add Vulkan backend (#2059)
* Vulkan loader code
* Fix matmul kernel, continue implementation
* Continue implementation
* Vulkan memory management
* Vulkan development
* Matmul call
* Add aligned malloc and free for VMA
* Continue implementation
* First matmul success
* GEMM Kernel optimization
* 1D Blocktiling
* 2D Blocktiling
* Write coalescing
* Continue vulkan implementation and optimization
* First FP16 attempt, disabled for now
* Code abstraction, FP16 implementation, fix kernel, add FP16 to FP32 kernel
* Enable device extensions properly, restore fp16 matmul op
* Fix mulmat_f16
* Output FP32 in fp16 matmul shader
* Fix f16_to_f32 kernel
* dequant_q4_0 kernel
* Add VMA library
* Avoid requesting dedicated memory, VMA can decide that by itself
* Add bounds checking to matmul kernels, improve implementation, fix command buffers not freed properly
* add cmake commands
* Add 2d write operation, profiling code
* Fix 2d write
* Fix queue selection for AMD RADV
* Fix trailing whitespace in vk_mem_alloc.h
* Add WIP warp tile mat mul shaders
* Disable glslc optimization
* Disable glslc optimization for CMake
* Optimize warptile matmul shader, replace blocktile with it
* Add split-k optimization for small matrix multiplication
Use semaphores for synchronization instead of fences or waitidle
Rework async write/read for synchronization
* Fix validation errors, improve compatibility with AMD GPUs
* Rework command buffer handling
* Variable matmul kernel using specialization constants
* Fix synchronization on AMD, add barriers for buffer ownership transfer, add debug flag and prints
* Reuse semaphores
* Handle stage flags during command buffer submission properly
* Increase matmul test runs for consistent results
* Fix F32 matmul
* Add vectorized loading and zeropadding for matrix multiplication
* Use pinned memory for f16 preprocessing
* Don't force aligned matmul
* Don't free before queue done
* Replace VMA library with native Vulkan buffer management
* Basic offloading support with mul_f32 and dmmv for q4_0
* Run glslc commands in parallel
* Unroll loops in dmmv shader
* Reduce usage of waitIdle
* Reuse pinned allocation for f16 conversion
* Handle devices with only a single queue
* Fix trailing whitespace in CMakeLists.txt
* Allow parallel execution of kernels, parallelize third and fourth dimension calls
* Add fallback for devices only supporting one DescriptorSet per DescriptorPool
* Move to graph function similar to CUDA implementation
* Use F16 kernel for most things, replace q_f32 with mul_mat_q_f16 function
* Add F32 dmmv shaders
* Batch submissions
* Add .spv to gitignore
* Split off matrix vector multiplication for separate optimization
* Use single command buffer for matrix vector multiplication ops
* Reduce overhead of mul_f32 calls by using a single command buffer
* Add submission batching to mul_f32
* Fix tests
* Add missing barrier
* Add further missing barrier
* Add further ops
* Replace vk::QueueFamilyIgnored with VK_QUEUE_FAMILY_IGNORED to support more Vulkan header versions
* Remove unnecessary cblas link
* Fix descriptor set pre-allocation assert
* Add runtime shader compilation, start transferring shaders to this approach
* Transfer remaining shaders to header and compile on runtime
* Fix fp32 fallback if device doesn't support fp16, add force disable env var GGML_VULKAN_DISABLE_F16
* Add support for q4_1, q5_0, q5_1 and q8_0
* Remove unnecessary scalar layout extension
* Parse graph early to pre-record command buffers
* Add q6_k support
* Add multi-submit for command buffers
* Fix q6_k dequant shader for AMD
* Fix q6_k for GPUs without fp16 support
* Simplify q6_k fp16 fix
* Minor fixes
* Fix wg_denom of m-mulmat shaders
* Add Python-based Vulkan shader generator
* Replace shaderc dependency with precompiled shaders
Fix python script to generate shaders
* Clean up code
* Fix shader generator script Windows compatibility
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
* Close file before deletion
* Fix vulkan shader fp32 name
* Add q2_k and q3_k support
Add validation check to compare shader results to cpu results
* Add q4_k support
* Add q5_k support
* Bake SPIR-V bytecode into the library instead of loading shaders from file
* Switch to signal semaphores for flexibility
Prepare broadcasting support for mul mat
* Finish broadcasting mul mat support for GQA
* Clean up unused functions
Add repeat op
* Add further ops, not yet enabled. Improve semaphore code
* Reduce number of used semaphores by utilizing timelines more properly
* Remove queue information
* Reuse timeline semaphores, allow parallel operation with binary semaphores to work around nvidia driver limitations
* Add Vulkan to llama-bench
* Remove cblas dependency
* Fix matmul k-split bug
* Fix q4_k dmmv K_QUANTS_PER_ITERATION 1 shader
* Add RMS Norm shader, rework op_f32 shader setup, fix matmul bug
* Fix issues with float16 overflows in shaders
* Fix issues with older Vulkan headers on Ubuntu 22.04
* Allow multi-op partial offloading by parsing the graph to preallocate enough between-op buffers
* Implement further ops, rework op_f32 calls, fix bugs
* Finish full offloading support, add last remaining ops, fix bugs, remove redundant code
* Upload generated file ggml-vulkan-shaders.hpp, remove redundant shaders
* Merge upstream changes, fix conflicts, adapt soft_max op
* Fix Python and shader header format
* Free model gpu buffers on exit
* Use single queue per device to simplify code
* Add matmul shader support for running multiple calculations in parallel
* Switch from semaphore-synchronized multiple command buffers per op to single command buffer for multiple ops, whole graph if possible
* Fix missing event cast
* Replace uint64_t(-1) with UINT64_MAX, rename function for clarity
* Fix warning about empty C function parameters
* Fix compiler warnings
* Properly implement Vulkan backend buffer handling
* Fix oversized host staging buffers
* Simplify barrier synchronization calls
* Fix gcc warnings
* Implement max_size for backend buffer types to limit the size of a single allocation
* Use min of maxMemoryAllocationSize and maxBufferSize for device max allocation size
* refactor multi buf
* Disable unsupported ops to fix tests
* Check for maintenance4 support before using it
* Handle devices with only a single queue
* Fix single queue logic
* propagate buffer usage in multi buffers
* Implement rope_neox op
* Cleanup header and other files
* Simplify gpu_extras by removing events and putting staging memcpys into contexts
* Move queue into context
Add not-yet-enabled async backend ops
* Simplify context use, optimize matmul shader for warp size 64 (AMD GCN), fix split_k matmul shader optimization
* Add get_max_size to SYCL backend.
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
* llama : fix trailing whitespace
---------
Co-authored-by: Henri Vasserman <henv@hot.ee>
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
Co-authored-by: slaren <slarengh@gmail.com>
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2024-01-28 18:03:59 +01:00
|
|
|
static bool alloc_tensor_range(struct ggml_context * ctx,
|
|
|
|
struct ggml_tensor * first, struct ggml_tensor * last,
|
|
|
|
ggml_backend_buffer_type_t buft, size_t size,
|
|
|
|
ggml_backend_buffer_t ** buffers, size_t * n_buffers) {
|
|
|
|
ggml_backend_buffer_t buffer = ggml_backend_buft_alloc_buffer(buft, size);
|
2024-01-12 20:07:38 +01:00
|
|
|
if (buffer == NULL) {
|
|
|
|
#ifndef NDEBUG
|
ggml : add Vulkan backend (#2059)
* Vulkan loader code
* Fix matmul kernel, continue implementation
* Continue implementation
* Vulkan memory management
* Vulkan development
* Matmul call
* Add aligned malloc and free for VMA
* Continue implementation
* First matmul success
* GEMM Kernel optimization
* 1D Blocktiling
* 2D Blocktiling
* Write coalescing
* Continue vulkan implementation and optimization
* First FP16 attempt, disabled for now
* Code abstraction, FP16 implementation, fix kernel, add FP16 to FP32 kernel
* Enable device extensions properly, restore fp16 matmul op
* Fix mulmat_f16
* Output FP32 in fp16 matmul shader
* Fix f16_to_f32 kernel
* dequant_q4_0 kernel
* Add VMA library
* Avoid requesting dedicated memory, VMA can decide that by itself
* Add bounds checking to matmul kernels, improve implementation, fix command buffers not freed properly
* add cmake commands
* Add 2d write operation, profiling code
* Fix 2d write
* Fix queue selection for AMD RADV
* Fix trailing whitespace in vk_mem_alloc.h
* Add WIP warp tile mat mul shaders
* Disable glslc optimization
* Disable glslc optimization for CMake
* Optimize warptile matmul shader, replace blocktile with it
* Add split-k optimization for small matrix multiplication
Use semaphores for synchronization instead of fences or waitidle
Rework async write/read for synchronization
* Fix validation errors, improve compatibility with AMD GPUs
* Rework command buffer handling
* Variable matmul kernel using specialization constants
* Fix synchronization on AMD, add barriers for buffer ownership transfer, add debug flag and prints
* Reuse semaphores
* Handle stage flags during command buffer submission properly
* Increase matmul test runs for consistent results
* Fix F32 matmul
* Add vectorized loading and zeropadding for matrix multiplication
* Use pinned memory for f16 preprocessing
* Don't force aligned matmul
* Don't free before queue done
* Replace VMA library with native Vulkan buffer management
* Basic offloading support with mul_f32 and dmmv for q4_0
* Run glslc commands in parallel
* Unroll loops in dmmv shader
* Reduce usage of waitIdle
* Reuse pinned allocation for f16 conversion
* Handle devices with only a single queue
* Fix trailing whitespace in CMakeLists.txt
* Allow parallel execution of kernels, parallelize third and fourth dimension calls
* Add fallback for devices only supporting one DescriptorSet per DescriptorPool
* Move to graph function similar to CUDA implementation
* Use F16 kernel for most things, replace q_f32 with mul_mat_q_f16 function
* Add F32 dmmv shaders
* Batch submissions
* Add .spv to gitignore
* Split off matrix vector multiplication for separate optimization
* Use single command buffer for matrix vector multiplication ops
* Reduce overhead of mul_f32 calls by using a single command buffer
* Add submission batching to mul_f32
* Fix tests
* Add missing barrier
* Add further missing barrier
* Add further ops
* Replace vk::QueueFamilyIgnored with VK_QUEUE_FAMILY_IGNORED to support more Vulkan header versions
* Remove unnecessary cblas link
* Fix descriptor set pre-allocation assert
* Add runtime shader compilation, start transferring shaders to this approach
* Transfer remaining shaders to header and compile on runtime
* Fix fp32 fallback if device doesn't support fp16, add force disable env var GGML_VULKAN_DISABLE_F16
* Add support for q4_1, q5_0, q5_1 and q8_0
* Remove unnecessary scalar layout extension
* Parse graph early to pre-record command buffers
* Add q6_k support
* Add multi-submit for command buffers
* Fix q6_k dequant shader for AMD
* Fix q6_k for GPUs without fp16 support
* Simplify q6_k fp16 fix
* Minor fixes
* Fix wg_denom of m-mulmat shaders
* Add Python-based Vulkan shader generator
* Replace shaderc dependency with precompiled shaders
Fix python script to generate shaders
* Clean up code
* Fix shader generator script Windows compatibility
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
* Close file before deletion
* Fix vulkan shader fp32 name
* Add q2_k and q3_k support
Add validation check to compare shader results to cpu results
* Add q4_k support
* Add q5_k support
* Bake SPIR-V bytecode into the library instead of loading shaders from file
* Switch to signal semaphores for flexibility
Prepare broadcasting support for mul mat
* Finish broadcasting mul mat support for GQA
* Clean up unused functions
Add repeat op
* Add further ops, not yet enabled. Improve semaphore code
* Reduce number of used semaphores by utilizing timelines more properly
* Remove queue information
* Reuse timeline semaphores, allow parallel operation with binary semaphores to work around nvidia driver limitations
* Add Vulkan to llama-bench
* Remove cblas dependency
* Fix matmul k-split bug
* Fix q4_k dmmv K_QUANTS_PER_ITERATION 1 shader
* Add RMS Norm shader, rework op_f32 shader setup, fix matmul bug
* Fix issues with float16 overflows in shaders
* Fix issues with older Vulkan headers on Ubuntu 22.04
* Allow multi-op partial offloading by parsing the graph to preallocate enough between-op buffers
* Implement further ops, rework op_f32 calls, fix bugs
* Finish full offloading support, add last remaining ops, fix bugs, remove redundant code
* Upload generated file ggml-vulkan-shaders.hpp, remove redundant shaders
* Merge upstream changes, fix conflicts, adapt soft_max op
* Fix Python and shader header format
* Free model gpu buffers on exit
* Use single queue per device to simplify code
* Add matmul shader support for running multiple calculations in parallel
* Switch from semaphore-synchronized multiple command buffers per op to single command buffer for multiple ops, whole graph if possible
* Fix missing event cast
* Replace uint64_t(-1) with UINT64_MAX, rename function for clarity
* Fix warning about empty C function parameters
* Fix compiler warnings
* Properly implement Vulkan backend buffer handling
* Fix oversized host staging buffers
* Simplify barrier synchronization calls
* Fix gcc warnings
* Implement max_size for backend buffer types to limit the size of a single allocation
* Use min of maxMemoryAllocationSize and maxBufferSize for device max allocation size
* refactor multi buf
* Disable unsupported ops to fix tests
* Check for maintenance4 support before using it
* Handle devices with only a single queue
* Fix single queue logic
* propagate buffer usage in multi buffers
* Implement rope_neox op
* Cleanup header and other files
* Simplify gpu_extras by removing events and putting staging memcpys into contexts
* Move queue into context
Add not-yet-enabled async backend ops
* Simplify context use, optimize matmul shader for warp size 64 (AMD GCN), fix split_k matmul shader optimization
* Add get_max_size to SYCL backend.
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
* llama : fix trailing whitespace
---------
Co-authored-by: Henri Vasserman <henv@hot.ee>
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
Co-authored-by: slaren <slarengh@gmail.com>
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2024-01-28 18:03:59 +01:00
|
|
|
fprintf(stderr, "%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(buft), size);
|
2024-01-12 20:07:38 +01:00
|
|
|
#endif
|
ggml : add Vulkan backend (#2059)
* Vulkan loader code
* Fix matmul kernel, continue implementation
* Continue implementation
* Vulkan memory management
* Vulkan development
* Matmul call
* Add aligned malloc and free for VMA
* Continue implementation
* First matmul success
* GEMM Kernel optimization
* 1D Blocktiling
* 2D Blocktiling
* Write coalescing
* Continue vulkan implementation and optimization
* First FP16 attempt, disabled for now
* Code abstraction, FP16 implementation, fix kernel, add FP16 to FP32 kernel
* Enable device extensions properly, restore fp16 matmul op
* Fix mulmat_f16
* Output FP32 in fp16 matmul shader
* Fix f16_to_f32 kernel
* dequant_q4_0 kernel
* Add VMA library
* Avoid requesting dedicated memory, VMA can decide that by itself
* Add bounds checking to matmul kernels, improve implementation, fix command buffers not freed properly
* add cmake commands
* Add 2d write operation, profiling code
* Fix 2d write
* Fix queue selection for AMD RADV
* Fix trailing whitespace in vk_mem_alloc.h
* Add WIP warp tile mat mul shaders
* Disable glslc optimization
* Disable glslc optimization for CMake
* Optimize warptile matmul shader, replace blocktile with it
* Add split-k optimization for small matrix multiplication
Use semaphores for synchronization instead of fences or waitidle
Rework async write/read for synchronization
* Fix validation errors, improve compatibility with AMD GPUs
* Rework command buffer handling
* Variable matmul kernel using specialization constants
* Fix synchronization on AMD, add barriers for buffer ownership transfer, add debug flag and prints
* Reuse semaphores
* Handle stage flags during command buffer submission properly
* Increase matmul test runs for consistent results
* Fix F32 matmul
* Add vectorized loading and zeropadding for matrix multiplication
* Use pinned memory for f16 preprocessing
* Don't force aligned matmul
* Don't free before queue done
* Replace VMA library with native Vulkan buffer management
* Basic offloading support with mul_f32 and dmmv for q4_0
* Run glslc commands in parallel
* Unroll loops in dmmv shader
* Reduce usage of waitIdle
* Reuse pinned allocation for f16 conversion
* Handle devices with only a single queue
* Fix trailing whitespace in CMakeLists.txt
* Allow parallel execution of kernels, parallelize third and fourth dimension calls
* Add fallback for devices only supporting one DescriptorSet per DescriptorPool
* Move to graph function similar to CUDA implementation
* Use F16 kernel for most things, replace q_f32 with mul_mat_q_f16 function
* Add F32 dmmv shaders
* Batch submissions
* Add .spv to gitignore
* Split off matrix vector multiplication for separate optimization
* Use single command buffer for matrix vector multiplication ops
* Reduce overhead of mul_f32 calls by using a single command buffer
* Add submission batching to mul_f32
* Fix tests
* Add missing barrier
* Add further missing barrier
* Add further ops
* Replace vk::QueueFamilyIgnored with VK_QUEUE_FAMILY_IGNORED to support more Vulkan header versions
* Remove unnecessary cblas link
* Fix descriptor set pre-allocation assert
* Add runtime shader compilation, start transferring shaders to this approach
* Transfer remaining shaders to header and compile on runtime
* Fix fp32 fallback if device doesn't support fp16, add force disable env var GGML_VULKAN_DISABLE_F16
* Add support for q4_1, q5_0, q5_1 and q8_0
* Remove unnecessary scalar layout extension
* Parse graph early to pre-record command buffers
* Add q6_k support
* Add multi-submit for command buffers
* Fix q6_k dequant shader for AMD
* Fix q6_k for GPUs without fp16 support
* Simplify q6_k fp16 fix
* Minor fixes
* Fix wg_denom of m-mulmat shaders
* Add Python-based Vulkan shader generator
* Replace shaderc dependency with precompiled shaders
Fix python script to generate shaders
* Clean up code
* Fix shader generator script Windows compatibility
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
* Close file before deletion
* Fix vulkan shader fp32 name
* Add q2_k and q3_k support
Add validation check to compare shader results to cpu results
* Add q4_k support
* Add q5_k support
* Bake SPIR-V bytecode into the library instead of loading shaders from file
* Switch to signal semaphores for flexibility
Prepare broadcasting support for mul mat
* Finish broadcasting mul mat support for GQA
* Clean up unused functions
Add repeat op
* Add further ops, not yet enabled. Improve semaphore code
* Reduce number of used semaphores by utilizing timelines more properly
* Remove queue information
* Reuse timeline semaphores, allow parallel operation with binary semaphores to work around nvidia driver limitations
* Add Vulkan to llama-bench
* Remove cblas dependency
* Fix matmul k-split bug
* Fix q4_k dmmv K_QUANTS_PER_ITERATION 1 shader
* Add RMS Norm shader, rework op_f32 shader setup, fix matmul bug
* Fix issues with float16 overflows in shaders
* Fix issues with older Vulkan headers on Ubuntu 22.04
* Allow multi-op partial offloading by parsing the graph to preallocate enough between-op buffers
* Implement further ops, rework op_f32 calls, fix bugs
* Finish full offloading support, add last remaining ops, fix bugs, remove redundant code
* Upload generated file ggml-vulkan-shaders.hpp, remove redundant shaders
* Merge upstream changes, fix conflicts, adapt soft_max op
* Fix Python and shader header format
* Free model gpu buffers on exit
* Use single queue per device to simplify code
* Add matmul shader support for running multiple calculations in parallel
* Switch from semaphore-synchronized multiple command buffers per op to single command buffer for multiple ops, whole graph if possible
* Fix missing event cast
* Replace uint64_t(-1) with UINT64_MAX, rename function for clarity
* Fix warning about empty C function parameters
* Fix compiler warnings
* Properly implement Vulkan backend buffer handling
* Fix oversized host staging buffers
* Simplify barrier synchronization calls
* Fix gcc warnings
* Implement max_size for backend buffer types to limit the size of a single allocation
* Use min of maxMemoryAllocationSize and maxBufferSize for device max allocation size
* refactor multi buf
* Disable unsupported ops to fix tests
* Check for maintenance4 support before using it
* Handle devices with only a single queue
* Fix single queue logic
* propagate buffer usage in multi buffers
* Implement rope_neox op
* Cleanup header and other files
* Simplify gpu_extras by removing events and putting staging memcpys into contexts
* Move queue into context
Add not-yet-enabled async backend ops
* Simplify context use, optimize matmul shader for warp size 64 (AMD GCN), fix split_k matmul shader optimization
* Add get_max_size to SYCL backend.
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
* llama : fix trailing whitespace
---------
Co-authored-by: Henri Vasserman <henv@hot.ee>
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
Co-authored-by: slaren <slarengh@gmail.com>
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2024-01-28 18:03:59 +01:00
|
|
|
for (size_t i = 0; i < *n_buffers; i++) {
|
|
|
|
ggml_backend_buffer_free(*buffers[i]);
|
|
|
|
}
|
2024-01-29 23:19:29 +01:00
|
|
|
free(*buffers);
|
ggml : add Vulkan backend (#2059)
* Vulkan loader code
* Fix matmul kernel, continue implementation
* Continue implementation
* Vulkan memory management
* Vulkan development
* Matmul call
* Add aligned malloc and free for VMA
* Continue implementation
* First matmul success
* GEMM Kernel optimization
* 1D Blocktiling
* 2D Blocktiling
* Write coalescing
* Continue vulkan implementation and optimization
* First FP16 attempt, disabled for now
* Code abstraction, FP16 implementation, fix kernel, add FP16 to FP32 kernel
* Enable device extensions properly, restore fp16 matmul op
* Fix mulmat_f16
* Output FP32 in fp16 matmul shader
* Fix f16_to_f32 kernel
* dequant_q4_0 kernel
* Add VMA library
* Avoid requesting dedicated memory, VMA can decide that by itself
* Add bounds checking to matmul kernels, improve implementation, fix command buffers not freed properly
* add cmake commands
* Add 2d write operation, profiling code
* Fix 2d write
* Fix queue selection for AMD RADV
* Fix trailing whitespace in vk_mem_alloc.h
* Add WIP warp tile mat mul shaders
* Disable glslc optimization
* Disable glslc optimization for CMake
* Optimize warptile matmul shader, replace blocktile with it
* Add split-k optimization for small matrix multiplication
Use semaphores for synchronization instead of fences or waitidle
Rework async write/read for synchronization
* Fix validation errors, improve compatibility with AMD GPUs
* Rework command buffer handling
* Variable matmul kernel using specialization constants
* Fix synchronization on AMD, add barriers for buffer ownership transfer, add debug flag and prints
* Reuse semaphores
* Handle stage flags during command buffer submission properly
* Increase matmul test runs for consistent results
* Fix F32 matmul
* Add vectorized loading and zeropadding for matrix multiplication
* Use pinned memory for f16 preprocessing
* Don't force aligned matmul
* Don't free before queue done
* Replace VMA library with native Vulkan buffer management
* Basic offloading support with mul_f32 and dmmv for q4_0
* Run glslc commands in parallel
* Unroll loops in dmmv shader
* Reduce usage of waitIdle
* Reuse pinned allocation for f16 conversion
* Handle devices with only a single queue
* Fix trailing whitespace in CMakeLists.txt
* Allow parallel execution of kernels, parallelize third and fourth dimension calls
* Add fallback for devices only supporting one DescriptorSet per DescriptorPool
* Move to graph function similar to CUDA implementation
* Use F16 kernel for most things, replace q_f32 with mul_mat_q_f16 function
* Add F32 dmmv shaders
* Batch submissions
* Add .spv to gitignore
* Split off matrix vector multiplication for separate optimization
* Use single command buffer for matrix vector multiplication ops
* Reduce overhead of mul_f32 calls by using a single command buffer
* Add submission batching to mul_f32
* Fix tests
* Add missing barrier
* Add further missing barrier
* Add further ops
* Replace vk::QueueFamilyIgnored with VK_QUEUE_FAMILY_IGNORED to support more Vulkan header versions
* Remove unnecessary cblas link
* Fix descriptor set pre-allocation assert
* Add runtime shader compilation, start transferring shaders to this approach
* Transfer remaining shaders to header and compile on runtime
* Fix fp32 fallback if device doesn't support fp16, add force disable env var GGML_VULKAN_DISABLE_F16
* Add support for q4_1, q5_0, q5_1 and q8_0
* Remove unnecessary scalar layout extension
* Parse graph early to pre-record command buffers
* Add q6_k support
* Add multi-submit for command buffers
* Fix q6_k dequant shader for AMD
* Fix q6_k for GPUs without fp16 support
* Simplify q6_k fp16 fix
* Minor fixes
* Fix wg_denom of m-mulmat shaders
* Add Python-based Vulkan shader generator
* Replace shaderc dependency with precompiled shaders
Fix python script to generate shaders
* Clean up code
* Fix shader generator script Windows compatibility
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
* Close file before deletion
* Fix vulkan shader fp32 name
* Add q2_k and q3_k support
Add validation check to compare shader results to cpu results
* Add q4_k support
* Add q5_k support
* Bake SPIR-V bytecode into the library instead of loading shaders from file
* Switch to signal semaphores for flexibility
Prepare broadcasting support for mul mat
* Finish broadcasting mul mat support for GQA
* Clean up unused functions
Add repeat op
* Add further ops, not yet enabled. Improve semaphore code
* Reduce number of used semaphores by utilizing timelines more properly
* Remove queue information
* Reuse timeline semaphores, allow parallel operation with binary semaphores to work around nvidia driver limitations
* Add Vulkan to llama-bench
* Remove cblas dependency
* Fix matmul k-split bug
* Fix q4_k dmmv K_QUANTS_PER_ITERATION 1 shader
* Add RMS Norm shader, rework op_f32 shader setup, fix matmul bug
* Fix issues with float16 overflows in shaders
* Fix issues with older Vulkan headers on Ubuntu 22.04
* Allow multi-op partial offloading by parsing the graph to preallocate enough between-op buffers
* Implement further ops, rework op_f32 calls, fix bugs
* Finish full offloading support, add last remaining ops, fix bugs, remove redundant code
* Upload generated file ggml-vulkan-shaders.hpp, remove redundant shaders
* Merge upstream changes, fix conflicts, adapt soft_max op
* Fix Python and shader header format
* Free model gpu buffers on exit
* Use single queue per device to simplify code
* Add matmul shader support for running multiple calculations in parallel
* Switch from semaphore-synchronized multiple command buffers per op to single command buffer for multiple ops, whole graph if possible
* Fix missing event cast
* Replace uint64_t(-1) with UINT64_MAX, rename function for clarity
* Fix warning about empty C function parameters
* Fix compiler warnings
* Properly implement Vulkan backend buffer handling
* Fix oversized host staging buffers
* Simplify barrier synchronization calls
* Fix gcc warnings
* Implement max_size for backend buffer types to limit the size of a single allocation
* Use min of maxMemoryAllocationSize and maxBufferSize for device max allocation size
* refactor multi buf
* Disable unsupported ops to fix tests
* Check for maintenance4 support before using it
* Handle devices with only a single queue
* Fix single queue logic
* propagate buffer usage in multi buffers
* Implement rope_neox op
* Cleanup header and other files
* Simplify gpu_extras by removing events and putting staging memcpys into contexts
* Move queue into context
Add not-yet-enabled async backend ops
* Simplify context use, optimize matmul shader for warp size 64 (AMD GCN), fix split_k matmul shader optimization
* Add get_max_size to SYCL backend.
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
* llama : fix trailing whitespace
---------
Co-authored-by: Henri Vasserman <henv@hot.ee>
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
Co-authored-by: slaren <slarengh@gmail.com>
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2024-01-28 18:03:59 +01:00
|
|
|
return false;
|
2024-01-12 20:07:38 +01:00
|
|
|
}
|
|
|
|
|
2024-02-12 08:16:06 +01:00
|
|
|
struct ggml_tallocr * tallocr = ggml_tallocr_new(buffer);
|
2023-12-07 21:26:54 +01:00
|
|
|
|
ggml : add Vulkan backend (#2059)
* Vulkan loader code
* Fix matmul kernel, continue implementation
* Continue implementation
* Vulkan memory management
* Vulkan development
* Matmul call
* Add aligned malloc and free for VMA
* Continue implementation
* First matmul success
* GEMM Kernel optimization
* 1D Blocktiling
* 2D Blocktiling
* Write coalescing
* Continue vulkan implementation and optimization
* First FP16 attempt, disabled for now
* Code abstraction, FP16 implementation, fix kernel, add FP16 to FP32 kernel
* Enable device extensions properly, restore fp16 matmul op
* Fix mulmat_f16
* Output FP32 in fp16 matmul shader
* Fix f16_to_f32 kernel
* dequant_q4_0 kernel
* Add VMA library
* Avoid requesting dedicated memory, VMA can decide that by itself
* Add bounds checking to matmul kernels, improve implementation, fix command buffers not freed properly
* add cmake commands
* Add 2d write operation, profiling code
* Fix 2d write
* Fix queue selection for AMD RADV
* Fix trailing whitespace in vk_mem_alloc.h
* Add WIP warp tile mat mul shaders
* Disable glslc optimization
* Disable glslc optimization for CMake
* Optimize warptile matmul shader, replace blocktile with it
* Add split-k optimization for small matrix multiplication
Use semaphores for synchronization instead of fences or waitidle
Rework async write/read for synchronization
* Fix validation errors, improve compatibility with AMD GPUs
* Rework command buffer handling
* Variable matmul kernel using specialization constants
* Fix synchronization on AMD, add barriers for buffer ownership transfer, add debug flag and prints
* Reuse semaphores
* Handle stage flags during command buffer submission properly
* Increase matmul test runs for consistent results
* Fix F32 matmul
* Add vectorized loading and zeropadding for matrix multiplication
* Use pinned memory for f16 preprocessing
* Don't force aligned matmul
* Don't free before queue done
* Replace VMA library with native Vulkan buffer management
* Basic offloading support with mul_f32 and dmmv for q4_0
* Run glslc commands in parallel
* Unroll loops in dmmv shader
* Reduce usage of waitIdle
* Reuse pinned allocation for f16 conversion
* Handle devices with only a single queue
* Fix trailing whitespace in CMakeLists.txt
* Allow parallel execution of kernels, parallelize third and fourth dimension calls
* Add fallback for devices only supporting one DescriptorSet per DescriptorPool
* Move to graph function similar to CUDA implementation
* Use F16 kernel for most things, replace q_f32 with mul_mat_q_f16 function
* Add F32 dmmv shaders
* Batch submissions
* Add .spv to gitignore
* Split off matrix vector multiplication for separate optimization
* Use single command buffer for matrix vector multiplication ops
* Reduce overhead of mul_f32 calls by using a single command buffer
* Add submission batching to mul_f32
* Fix tests
* Add missing barrier
* Add further missing barrier
* Add further ops
* Replace vk::QueueFamilyIgnored with VK_QUEUE_FAMILY_IGNORED to support more Vulkan header versions
* Remove unnecessary cblas link
* Fix descriptor set pre-allocation assert
* Add runtime shader compilation, start transferring shaders to this approach
* Transfer remaining shaders to header and compile on runtime
* Fix fp32 fallback if device doesn't support fp16, add force disable env var GGML_VULKAN_DISABLE_F16
* Add support for q4_1, q5_0, q5_1 and q8_0
* Remove unnecessary scalar layout extension
* Parse graph early to pre-record command buffers
* Add q6_k support
* Add multi-submit for command buffers
* Fix q6_k dequant shader for AMD
* Fix q6_k for GPUs without fp16 support
* Simplify q6_k fp16 fix
* Minor fixes
* Fix wg_denom of m-mulmat shaders
* Add Python-based Vulkan shader generator
* Replace shaderc dependency with precompiled shaders
Fix python script to generate shaders
* Clean up code
* Fix shader generator script Windows compatibility
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
* Close file before deletion
* Fix vulkan shader fp32 name
* Add q2_k and q3_k support
Add validation check to compare shader results to cpu results
* Add q4_k support
* Add q5_k support
* Bake SPIR-V bytecode into the library instead of loading shaders from file
* Switch to signal semaphores for flexibility
Prepare broadcasting support for mul mat
* Finish broadcasting mul mat support for GQA
* Clean up unused functions
Add repeat op
* Add further ops, not yet enabled. Improve semaphore code
* Reduce number of used semaphores by utilizing timelines more properly
* Remove queue information
* Reuse timeline semaphores, allow parallel operation with binary semaphores to work around nvidia driver limitations
* Add Vulkan to llama-bench
* Remove cblas dependency
* Fix matmul k-split bug
* Fix q4_k dmmv K_QUANTS_PER_ITERATION 1 shader
* Add RMS Norm shader, rework op_f32 shader setup, fix matmul bug
* Fix issues with float16 overflows in shaders
* Fix issues with older Vulkan headers on Ubuntu 22.04
* Allow multi-op partial offloading by parsing the graph to preallocate enough between-op buffers
* Implement further ops, rework op_f32 calls, fix bugs
* Finish full offloading support, add last remaining ops, fix bugs, remove redundant code
* Upload generated file ggml-vulkan-shaders.hpp, remove redundant shaders
* Merge upstream changes, fix conflicts, adapt soft_max op
* Fix Python and shader header format
* Free model gpu buffers on exit
* Use single queue per device to simplify code
* Add matmul shader support for running multiple calculations in parallel
* Switch from semaphore-synchronized multiple command buffers per op to single command buffer for multiple ops, whole graph if possible
* Fix missing event cast
* Replace uint64_t(-1) with UINT64_MAX, rename function for clarity
* Fix warning about empty C function parameters
* Fix compiler warnings
* Properly implement Vulkan backend buffer handling
* Fix oversized host staging buffers
* Simplify barrier synchronization calls
* Fix gcc warnings
* Implement max_size for backend buffer types to limit the size of a single allocation
* Use min of maxMemoryAllocationSize and maxBufferSize for device max allocation size
* refactor multi buf
* Disable unsupported ops to fix tests
* Check for maintenance4 support before using it
* Handle devices with only a single queue
* Fix single queue logic
* propagate buffer usage in multi buffers
* Implement rope_neox op
* Cleanup header and other files
* Simplify gpu_extras by removing events and putting staging memcpys into contexts
* Move queue into context
Add not-yet-enabled async backend ops
* Simplify context use, optimize matmul shader for warp size 64 (AMD GCN), fix split_k matmul shader optimization
* Add get_max_size to SYCL backend.
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
* llama : fix trailing whitespace
---------
Co-authored-by: Henri Vasserman <henv@hot.ee>
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
Co-authored-by: slaren <slarengh@gmail.com>
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2024-01-28 18:03:59 +01:00
|
|
|
for (struct ggml_tensor * t = first; t != last; t = ggml_get_next_tensor(ctx, t)) {
|
2023-12-07 21:26:54 +01:00
|
|
|
if (t->data == NULL) {
|
|
|
|
if (t->view_src == NULL) {
|
|
|
|
ggml_tallocr_alloc(tallocr, t);
|
2024-02-12 08:16:06 +01:00
|
|
|
} else if (t->buffer == NULL) {
|
2023-12-07 21:26:54 +01:00
|
|
|
ggml_backend_view_init(buffer, t);
|
|
|
|
}
|
2023-12-21 21:07:46 +01:00
|
|
|
} else {
|
2024-02-12 08:16:06 +01:00
|
|
|
if (t->view_src != NULL && t->buffer == NULL) {
|
2023-12-21 21:07:46 +01:00
|
|
|
// view of a pre-allocated tensor
|
|
|
|
ggml_backend_view_init(buffer, t);
|
|
|
|
}
|
2023-12-07 21:26:54 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ggml_tallocr_free(tallocr);
|
|
|
|
|
ggml : add Vulkan backend (#2059)
* Vulkan loader code
* Fix matmul kernel, continue implementation
* Continue implementation
* Vulkan memory management
* Vulkan development
* Matmul call
* Add aligned malloc and free for VMA
* Continue implementation
* First matmul success
* GEMM Kernel optimization
* 1D Blocktiling
* 2D Blocktiling
* Write coalescing
* Continue vulkan implementation and optimization
* First FP16 attempt, disabled for now
* Code abstraction, FP16 implementation, fix kernel, add FP16 to FP32 kernel
* Enable device extensions properly, restore fp16 matmul op
* Fix mulmat_f16
* Output FP32 in fp16 matmul shader
* Fix f16_to_f32 kernel
* dequant_q4_0 kernel
* Add VMA library
* Avoid requesting dedicated memory, VMA can decide that by itself
* Add bounds checking to matmul kernels, improve implementation, fix command buffers not freed properly
* add cmake commands
* Add 2d write operation, profiling code
* Fix 2d write
* Fix queue selection for AMD RADV
* Fix trailing whitespace in vk_mem_alloc.h
* Add WIP warp tile mat mul shaders
* Disable glslc optimization
* Disable glslc optimization for CMake
* Optimize warptile matmul shader, replace blocktile with it
* Add split-k optimization for small matrix multiplication
Use semaphores for synchronization instead of fences or waitidle
Rework async write/read for synchronization
* Fix validation errors, improve compatibility with AMD GPUs
* Rework command buffer handling
* Variable matmul kernel using specialization constants
* Fix synchronization on AMD, add barriers for buffer ownership transfer, add debug flag and prints
* Reuse semaphores
* Handle stage flags during command buffer submission properly
* Increase matmul test runs for consistent results
* Fix F32 matmul
* Add vectorized loading and zeropadding for matrix multiplication
* Use pinned memory for f16 preprocessing
* Don't force aligned matmul
* Don't free before queue done
* Replace VMA library with native Vulkan buffer management
* Basic offloading support with mul_f32 and dmmv for q4_0
* Run glslc commands in parallel
* Unroll loops in dmmv shader
* Reduce usage of waitIdle
* Reuse pinned allocation for f16 conversion
* Handle devices with only a single queue
* Fix trailing whitespace in CMakeLists.txt
* Allow parallel execution of kernels, parallelize third and fourth dimension calls
* Add fallback for devices only supporting one DescriptorSet per DescriptorPool
* Move to graph function similar to CUDA implementation
* Use F16 kernel for most things, replace q_f32 with mul_mat_q_f16 function
* Add F32 dmmv shaders
* Batch submissions
* Add .spv to gitignore
* Split off matrix vector multiplication for separate optimization
* Use single command buffer for matrix vector multiplication ops
* Reduce overhead of mul_f32 calls by using a single command buffer
* Add submission batching to mul_f32
* Fix tests
* Add missing barrier
* Add further missing barrier
* Add further ops
* Replace vk::QueueFamilyIgnored with VK_QUEUE_FAMILY_IGNORED to support more Vulkan header versions
* Remove unnecessary cblas link
* Fix descriptor set pre-allocation assert
* Add runtime shader compilation, start transferring shaders to this approach
* Transfer remaining shaders to header and compile on runtime
* Fix fp32 fallback if device doesn't support fp16, add force disable env var GGML_VULKAN_DISABLE_F16
* Add support for q4_1, q5_0, q5_1 and q8_0
* Remove unnecessary scalar layout extension
* Parse graph early to pre-record command buffers
* Add q6_k support
* Add multi-submit for command buffers
* Fix q6_k dequant shader for AMD
* Fix q6_k for GPUs without fp16 support
* Simplify q6_k fp16 fix
* Minor fixes
* Fix wg_denom of m-mulmat shaders
* Add Python-based Vulkan shader generator
* Replace shaderc dependency with precompiled shaders
Fix python script to generate shaders
* Clean up code
* Fix shader generator script Windows compatibility
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
* Close file before deletion
* Fix vulkan shader fp32 name
* Add q2_k and q3_k support
Add validation check to compare shader results to cpu results
* Add q4_k support
* Add q5_k support
* Bake SPIR-V bytecode into the library instead of loading shaders from file
* Switch to signal semaphores for flexibility
Prepare broadcasting support for mul mat
* Finish broadcasting mul mat support for GQA
* Clean up unused functions
Add repeat op
* Add further ops, not yet enabled. Improve semaphore code
* Reduce number of used semaphores by utilizing timelines more properly
* Remove queue information
* Reuse timeline semaphores, allow parallel operation with binary semaphores to work around nvidia driver limitations
* Add Vulkan to llama-bench
* Remove cblas dependency
* Fix matmul k-split bug
* Fix q4_k dmmv K_QUANTS_PER_ITERATION 1 shader
* Add RMS Norm shader, rework op_f32 shader setup, fix matmul bug
* Fix issues with float16 overflows in shaders
* Fix issues with older Vulkan headers on Ubuntu 22.04
* Allow multi-op partial offloading by parsing the graph to preallocate enough between-op buffers
* Implement further ops, rework op_f32 calls, fix bugs
* Finish full offloading support, add last remaining ops, fix bugs, remove redundant code
* Upload generated file ggml-vulkan-shaders.hpp, remove redundant shaders
* Merge upstream changes, fix conflicts, adapt soft_max op
* Fix Python and shader header format
* Free model gpu buffers on exit
* Use single queue per device to simplify code
* Add matmul shader support for running multiple calculations in parallel
* Switch from semaphore-synchronized multiple command buffers per op to single command buffer for multiple ops, whole graph if possible
* Fix missing event cast
* Replace uint64_t(-1) with UINT64_MAX, rename function for clarity
* Fix warning about empty C function parameters
* Fix compiler warnings
* Properly implement Vulkan backend buffer handling
* Fix oversized host staging buffers
* Simplify barrier synchronization calls
* Fix gcc warnings
* Implement max_size for backend buffer types to limit the size of a single allocation
* Use min of maxMemoryAllocationSize and maxBufferSize for device max allocation size
* refactor multi buf
* Disable unsupported ops to fix tests
* Check for maintenance4 support before using it
* Handle devices with only a single queue
* Fix single queue logic
* propagate buffer usage in multi buffers
* Implement rope_neox op
* Cleanup header and other files
* Simplify gpu_extras by removing events and putting staging memcpys into contexts
* Move queue into context
Add not-yet-enabled async backend ops
* Simplify context use, optimize matmul shader for warp size 64 (AMD GCN), fix split_k matmul shader optimization
* Add get_max_size to SYCL backend.
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
* llama : fix trailing whitespace
---------
Co-authored-by: Henri Vasserman <henv@hot.ee>
Co-authored-by: Concedo <39025047+LostRuins@users.noreply.github.com>
Co-authored-by: slaren <slarengh@gmail.com>
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2024-01-28 18:03:59 +01:00
|
|
|
*buffers = realloc(*buffers, sizeof(ggml_backend_buffer_t) * (*n_buffers + 1));
|
|
|
|
(*buffers)[(*n_buffers)++] = buffer;
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
ggml_backend_buffer_t ggml_backend_alloc_ctx_tensors_from_buft(struct ggml_context * ctx, ggml_backend_buffer_type_t buft) {
|
|
|
|
GGML_ASSERT(ggml_get_no_alloc(ctx) == true);
|
|
|
|
|
|
|
|
size_t alignment = ggml_backend_buft_get_alignment(buft);
|
|
|
|
size_t max_size = ggml_backend_buft_get_max_size(buft);
|
|
|
|
|
|
|
|
ggml_backend_buffer_t * buffers = NULL;
|
|
|
|
size_t n_buffers = 0;
|
|
|
|
|
|
|
|
size_t cur_buf_size = 0;
|
|
|
|
struct ggml_tensor * first = ggml_get_first_tensor(ctx);
|
|
|
|
for (struct ggml_tensor * t = first; t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
|
|
|
size_t this_size = 0;
|
|
|
|
if (t->data == NULL && t->view_src == NULL) {
|
|
|
|
this_size = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, t), alignment);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this_size > max_size) {
|
|
|
|
fprintf(stderr, "%s: tensor %s is too large to fit in a %s buffer (tensor size: %zu, max buffer size: %zu)\n",
|
|
|
|
__func__, t->name,
|
|
|
|
ggml_backend_buft_name(buft),
|
|
|
|
this_size, max_size);
|
|
|
|
for (size_t i = 0; i < n_buffers; i++) {
|
|
|
|
ggml_backend_buffer_free(buffers[i]);
|
|
|
|
}
|
|
|
|
free(buffers);
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ((cur_buf_size + this_size) > max_size) {
|
|
|
|
// allocate tensors in the current buffer
|
|
|
|
if (!alloc_tensor_range(ctx, first, t, buft, cur_buf_size, &buffers, &n_buffers)) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
first = t;
|
|
|
|
cur_buf_size = this_size;
|
|
|
|
} else {
|
|
|
|
cur_buf_size += this_size;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// allocate remaining tensors
|
|
|
|
if (cur_buf_size > 0) {
|
|
|
|
if (!alloc_tensor_range(ctx, first, NULL, buft, cur_buf_size, &buffers, &n_buffers)) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (n_buffers == 0) {
|
|
|
|
#ifndef NDEBUG
|
|
|
|
fprintf(stderr, "%s: all tensors in the context are already allocated\n", __func__);
|
|
|
|
#endif
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
ggml_backend_buffer_t buffer;
|
|
|
|
if (n_buffers == 1) {
|
|
|
|
buffer = buffers[0];
|
|
|
|
} else {
|
|
|
|
buffer = ggml_backend_multi_buffer_alloc_buffer(buffers, n_buffers);
|
|
|
|
}
|
|
|
|
free(buffers);
|
2023-12-07 21:26:54 +01:00
|
|
|
return buffer;
|
|
|
|
}
|
|
|
|
|
|
|
|
ggml_backend_buffer_t ggml_backend_alloc_ctx_tensors(struct ggml_context * ctx, ggml_backend_t backend) {
|
|
|
|
return ggml_backend_alloc_ctx_tensors_from_buft(ctx, ggml_backend_get_default_buffer_type(backend));
|
|
|
|
}
|