2023-09-03 20:34:09 +02:00
|
|
|
// defines MAP_ANONYMOUS
|
|
|
|
#ifndef _GNU_SOURCE
|
|
|
|
#define _GNU_SOURCE
|
|
|
|
#endif
|
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
#include "ggml-alloc.h"
|
|
|
|
#include "ggml.h"
|
|
|
|
#include <assert.h>
|
|
|
|
#include <stdarg.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
2023-09-03 20:34:09 +02:00
|
|
|
#ifdef __has_include
|
|
|
|
#if __has_include(<unistd.h>)
|
|
|
|
#include <unistd.h>
|
|
|
|
#if defined(_POSIX_MAPPED_FILES)
|
|
|
|
#include <sys/types.h>
|
|
|
|
#include <sys/mman.h>
|
|
|
|
#endif
|
|
|
|
#endif
|
|
|
|
#endif
|
|
|
|
|
|
|
|
#if defined(_WIN32)
|
|
|
|
#define WIN32_LEAN_AND_MEAN
|
|
|
|
#ifndef NOMINMAX
|
|
|
|
#define NOMINMAX
|
|
|
|
#endif
|
|
|
|
#include <windows.h>
|
|
|
|
#include <memoryapi.h>
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
#define UNUSED(x) (void)(x)
|
|
|
|
#define MAX(a, b) ((a) > (b) ? (a) : (b))
|
2023-08-25 07:58:00 +02:00
|
|
|
#define GGML_MAX_CONCUR (2*GGML_MAX_NODES)
|
2023-07-30 15:58:01 +02:00
|
|
|
|
|
|
|
//#define GGML_ALLOCATOR_DEBUG
|
|
|
|
|
|
|
|
//#define AT_PRINTF printf
|
|
|
|
#define AT_PRINTF(...) ((void)0)
|
|
|
|
|
|
|
|
struct hash_node {
|
|
|
|
struct ggml_tensor * t;
|
|
|
|
int n_children;
|
|
|
|
int n_views;
|
|
|
|
};
|
|
|
|
|
|
|
|
static size_t hash(void * p) {
|
|
|
|
return (size_t)p % GGML_GRAPH_HASHTABLE_SIZE;
|
|
|
|
}
|
|
|
|
|
|
|
|
static struct hash_node * hash_get(struct hash_node hash_table[], struct ggml_tensor * t) {
|
|
|
|
size_t h = hash(t);
|
|
|
|
|
|
|
|
// linear probing
|
|
|
|
size_t i = h;
|
|
|
|
while (hash_table[i].t != NULL) {
|
|
|
|
if (hash_table[i].t == t) {
|
|
|
|
return &hash_table[i];
|
|
|
|
}
|
|
|
|
i = (i + 1) % GGML_GRAPH_HASHTABLE_SIZE;
|
|
|
|
if (i == h) {
|
|
|
|
// hash table is full
|
|
|
|
GGML_ASSERT(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
hash_table[i].t = t;
|
|
|
|
return &hash_table[i];
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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;
|
|
|
|
}
|
|
|
|
|
|
|
|
struct free_block {
|
|
|
|
void * addr;
|
|
|
|
size_t size;
|
|
|
|
};
|
|
|
|
|
|
|
|
#define MAX_FREE_BLOCKS 128
|
|
|
|
|
|
|
|
struct ggml_allocr {
|
|
|
|
void * data;
|
|
|
|
size_t size;
|
|
|
|
size_t alignment;
|
|
|
|
int n_free_blocks;
|
|
|
|
struct free_block free_blocks[MAX_FREE_BLOCKS];
|
|
|
|
struct hash_node hash_table[GGML_GRAPH_HASHTABLE_SIZE];
|
|
|
|
size_t max_size;
|
|
|
|
bool measure;
|
2023-08-25 07:58:00 +02:00
|
|
|
int parse_seq[GGML_MAX_CONCUR];
|
2023-08-24 18:27:25 +02:00
|
|
|
int parse_seq_len;
|
2023-07-30 15:58:01 +02:00
|
|
|
|
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
|
|
|
struct ggml_tensor * allocated_tensors[1024];
|
|
|
|
#endif
|
|
|
|
};
|
|
|
|
|
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
2023-08-22 13:22:08 +02:00
|
|
|
static void add_allocated_tensor(struct ggml_allocr * alloc, struct ggml_tensor * tensor) {
|
2023-07-30 15:58:01 +02:00
|
|
|
for (int i = 0; i < 1024; i++) {
|
|
|
|
if (alloc->allocated_tensors[i] == NULL) {
|
|
|
|
alloc->allocated_tensors[i] = tensor;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
GGML_ASSERT(!"out of allocated_tensors");
|
|
|
|
}
|
2023-08-22 13:22:08 +02:00
|
|
|
static void remove_allocated_tensor(struct ggml_allocr * alloc, struct ggml_tensor * tensor) {
|
2023-07-30 15:58:01 +02:00
|
|
|
for (int i = 0; i < 1024; i++) {
|
|
|
|
if (alloc->allocated_tensors[i] == tensor ||
|
|
|
|
(alloc->allocated_tensors[i] != NULL && alloc->allocated_tensors[i]->data == tensor->data)) {
|
|
|
|
alloc->allocated_tensors[i] = NULL;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
printf("tried to free tensor %s not found\n", tensor->name);
|
|
|
|
GGML_ASSERT(!"tensor not found");
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
2023-09-03 20:34:09 +02:00
|
|
|
static size_t ggml_allocr_get_alloc_size(struct ggml_allocr * alloc, struct ggml_tensor * tensor) {
|
2023-07-30 15:58:01 +02:00
|
|
|
return ggml_nbytes(tensor);
|
|
|
|
|
|
|
|
UNUSED(alloc);
|
|
|
|
}
|
|
|
|
|
2023-09-03 20:34:09 +02:00
|
|
|
// check if a tensor is allocated by this buffer
|
|
|
|
static bool ggml_allocr_is_own(struct ggml_allocr * alloc, const struct ggml_tensor * tensor) {
|
|
|
|
void * ptr = tensor->data;
|
|
|
|
return ptr >= alloc->data && (char *)ptr < (char *)alloc->data + alloc->max_size;
|
|
|
|
}
|
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
void ggml_allocr_alloc(struct ggml_allocr * alloc, struct ggml_tensor * tensor) {
|
train : mem usage and other improvements (#2439)
* 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 missing lctx argument to get_example_targets_batch
* implement llama model file saving using gguf
checkpoint loading and saving disabled, to be replaced by loading and saving via gguf
* implement loading/saving of checkpointing files using GGUF
* bug fixes
* add checkpoint file version for future compatibility
* update readme with gguf filenames
* save & load opt->just_initialized value
* add first draft for checkpoint conversion script
* add gguf arch and ftype
* save opt parameter counter as uint64
* add gguf key and tensor names for optimizer and training
* add layer_norm_rms_eps to checkpoint convert script
* use same GGUF_GET_KEY macro as in llama.cpp
* use norm_rms_eps, and rope parameters and command line options to set them
* fix memory corruption bug in gguf
ctx->kv and ctx->infos was reallocated using not-aligned realloc, but freed with aligned free.
to fix this a GGML_ALIGNED_REALLOC was added, but there is no posix_memalign_realloc function.
so on non-windows and non-mingw32 platforms we fall back to aligned malloc, followed by copying
and freeing the old data.
* add gguf example cmake file
* bug fixes in tokenize_file
* bug fixes in load_llama_model_gguf
* bug fix: init model when no checkpoint was loaded
* bug fix in read_tensor_by_name
* bug fix in load_opt_context_gguf
* avoid printing lots of spaced on the unusual case that loss gets nan
* set name of tensors with empty name from what was read from gguf
* remove trailing whitespace
* print data checksums before saving and after loading to verify correctness
* bug fixes for convert-train-checkpoint-to-gguf
* temporarily add code to write old checkpoint files
used to verify that old checkpoint files are correctly converted to gguf
* bug fixes for convert-train-checkpoint-to-gguf.py loading checkpoints with opt_version=0
* remove code used to verify correctness of checkpoint file conversion
* remove trailing whitespace
* remove prediction related code
use main for prediction, it is better optimized
* update train-text-from-scratch README.md
* fix non-windows GGML_ALIGNED_REALLOC
* add missing blank line at end of file
* remove GGML_ALIGNED_REALLOC and use normal malloc/realloc/free for gguf ctx->kv & ctx->infos
* train : fix compile warnings
---------
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2023-08-28 21:51:47 +02:00
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
|
|
|
GGML_ASSERT(ggml_is_view(tensor) == false); // views generally get data pointer from one of their sources
|
|
|
|
GGML_ASSERT(tensor->data == NULL); // avoid allocating tensor which already has memory allocated
|
|
|
|
#endif
|
2023-09-03 20:34:09 +02:00
|
|
|
size_t size = ggml_allocr_get_alloc_size(alloc, 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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
AT_PRINTF("block %d\n", best_fit_block);
|
|
|
|
|
|
|
|
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];
|
|
|
|
if (block->size >= size) {
|
|
|
|
best_fit_block = alloc->n_free_blocks - 1;
|
|
|
|
max_avail = MAX(max_avail, block->size);
|
|
|
|
} else {
|
|
|
|
fprintf(stderr, "%s: not enough space in the buffer (needed %zu, largest block available %zu)\n",
|
|
|
|
__func__, size, max_avail);
|
|
|
|
GGML_ASSERT(!"not enough space in the buffer");
|
2023-07-30 15:58:01 +02:00
|
|
|
return;
|
2023-08-17 09:35:53 +02:00
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
struct free_block * block = &alloc->free_blocks[best_fit_block];
|
|
|
|
void * addr = block->addr;
|
|
|
|
block->addr = (char*)block->addr + size;
|
|
|
|
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];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
tensor->data = addr;
|
|
|
|
|
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
|
|
|
add_allocated_tensor(alloc, tensor);
|
|
|
|
size_t cur_max = (char*)addr - (char*)alloc->data + size;
|
|
|
|
if (cur_max > alloc->max_size) {
|
|
|
|
printf("max_size = %.2f MB: tensors: ", cur_max / 1024.0 / 1024.0);
|
|
|
|
for (int i = 0; i < 1024; i++) {
|
|
|
|
if (alloc->allocated_tensors[i]) {
|
|
|
|
printf("%s (%.2f MB) ", alloc->allocated_tensors[i]->name, ggml_nbytes(alloc->allocated_tensors[i]) / 1024.0 / 1024.0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
printf("\n");
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
|
|
|
alloc->max_size = MAX(alloc->max_size, (char*)addr - (char*)alloc->data + size);
|
|
|
|
}
|
|
|
|
|
|
|
|
// this is a very naive implementation, but for our case the number of free blocks should be very small
|
2023-09-03 20:34:09 +02:00
|
|
|
static void ggml_allocr_free_tensor(struct ggml_allocr * alloc, struct ggml_tensor * tensor) {
|
2023-07-30 15:58:01 +02:00
|
|
|
void * ptr = tensor->data;
|
|
|
|
|
2023-09-03 20:34:09 +02:00
|
|
|
if (ggml_allocr_is_own(alloc, tensor) == false) {
|
2023-07-30 15:58:01 +02:00
|
|
|
// the tensor was not allocated in this buffer
|
|
|
|
// this can happen because the graph allocator will try to free weights and other tensors from different buffers
|
|
|
|
// the easiest way to deal with this is just to ignore it
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-09-03 20:34:09 +02:00
|
|
|
size_t size = ggml_allocr_get_alloc_size(alloc, tensor);
|
2023-07-30 15:58:01 +02:00
|
|
|
size = aligned_offset(NULL, size, alloc->alignment);
|
|
|
|
AT_PRINTF("%s: freeing %s (%zu bytes) - n_free_blocks = %d\n", __func__, tensor->name, size, alloc->n_free_blocks);
|
|
|
|
|
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
|
|
|
remove_allocated_tensor(alloc, tensor);
|
|
|
|
#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
|
|
|
|
if ((char*)block->addr + block->size == ptr) {
|
|
|
|
block->size += size;
|
|
|
|
// check if we can merge with the next block
|
|
|
|
if (i < alloc->n_free_blocks - 1 && (char*)block->addr + block->size == alloc->free_blocks[i+1].addr) {
|
|
|
|
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
|
|
|
|
if ((char*)ptr + size == block->addr) {
|
|
|
|
block->addr = ptr;
|
|
|
|
block->size += size;
|
|
|
|
// check if we can merge with the previous block
|
|
|
|
if (i > 0 && (char*)alloc->free_blocks[i-1].addr + alloc->free_blocks[i-1].size == block->addr) {
|
|
|
|
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;
|
|
|
|
while (insert_pos < alloc->n_free_blocks && alloc->free_blocks[insert_pos].addr < ptr) {
|
|
|
|
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
|
|
|
|
alloc->free_blocks[insert_pos].addr = ptr;
|
|
|
|
alloc->free_blocks[insert_pos].size = size;
|
|
|
|
alloc->n_free_blocks++;
|
|
|
|
}
|
|
|
|
|
2023-08-23 22:08:04 +02:00
|
|
|
void ggml_allocr_set_parse_seq(struct ggml_allocr * alloc, const int * list, int n) {
|
2023-08-16 22:08:28 +02:00
|
|
|
for (int i = 0; i < n; i++) {
|
2023-08-24 18:27:25 +02:00
|
|
|
alloc->parse_seq[i] = list[i];
|
2023-08-16 22:08:28 +02:00
|
|
|
}
|
2023-08-24 18:27:25 +02:00
|
|
|
alloc->parse_seq_len = n;
|
2023-08-16 22:08:28 +02:00
|
|
|
}
|
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
void ggml_allocr_reset(struct ggml_allocr * alloc) {
|
|
|
|
alloc->n_free_blocks = 1;
|
|
|
|
size_t align_offset = aligned_offset(alloc->data, 0, alloc->alignment);
|
|
|
|
alloc->free_blocks[0].addr = (char *)alloc->data + align_offset;
|
|
|
|
alloc->free_blocks[0].size = alloc->size - align_offset;
|
|
|
|
}
|
|
|
|
|
|
|
|
struct ggml_allocr * ggml_allocr_new(void * data, size_t size, size_t alignment) {
|
|
|
|
struct ggml_allocr * alloc = (struct ggml_allocr *)malloc(sizeof(struct ggml_allocr) /* + n_free_blocks * sizeof(struct free_block) */);
|
|
|
|
|
|
|
|
*alloc = (struct ggml_allocr){
|
|
|
|
/*.data = */ data,
|
|
|
|
/*.size = */ size,
|
|
|
|
/*.alignment = */ alignment,
|
|
|
|
/*.n_free_blocks = */ 0,
|
|
|
|
/*.free_blocks = */ {{0}},
|
|
|
|
/*.hash_table = */ {{0}},
|
|
|
|
/*.max_size = */ 0,
|
|
|
|
/*.measure = */ false,
|
2023-08-16 22:08:28 +02:00
|
|
|
/*.parse_seq = */ {0},
|
2023-08-24 18:27:25 +02:00
|
|
|
/*.parse_seq_len = */ 0,
|
2023-07-30 15:58:01 +02:00
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
2023-08-28 13:24:53 +02:00
|
|
|
/*.allocated_tensors = */ {0},
|
2023-07-30 15:58:01 +02:00
|
|
|
#endif
|
|
|
|
};
|
|
|
|
|
|
|
|
ggml_allocr_reset(alloc);
|
|
|
|
|
|
|
|
return alloc;
|
|
|
|
}
|
|
|
|
|
2023-09-03 20:34:09 +02:00
|
|
|
// OS specific functions to allocate and free uncommitted virtual memory
|
|
|
|
static void * alloc_vmem(size_t size) {
|
|
|
|
#if defined(_WIN32)
|
|
|
|
return VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);
|
|
|
|
#elif defined(_POSIX_MAPPED_FILES)
|
|
|
|
return mmap(NULL, size, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
|
2023-09-02 14:23:45 +02:00
|
|
|
#else
|
2023-09-03 20:34:09 +02:00
|
|
|
// use a fixed address for other platforms
|
|
|
|
uintptr_t base_addr = (uintptr_t)-size - 0x100;
|
|
|
|
return (void *)base_addr;
|
2023-09-02 14:23:45 +02:00
|
|
|
#endif
|
2023-09-03 20:34:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
static void free_vmem(void * base_addr, size_t size) {
|
|
|
|
#if defined(_WIN32)
|
|
|
|
VirtualFree(base_addr, 0, MEM_RELEASE);
|
|
|
|
UNUSED(size);
|
|
|
|
#elif defined(_POSIX_MAPPED_FILES)
|
|
|
|
munmap(base_addr, size);
|
|
|
|
#else
|
|
|
|
// nothing to do
|
|
|
|
UNUSED(base_addr);
|
|
|
|
UNUSED(size);
|
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
// allocate uncommitted virtual memory to measure the size of the graph
|
|
|
|
static void alloc_measure_vmem(void ** base_addr, size_t * size) {
|
|
|
|
// 1TB for 64-bit, 1GB for 32-bit
|
|
|
|
*size = sizeof(void *) == 4 ? 1ULL<<30 : 1ULL<<40;
|
|
|
|
do {
|
|
|
|
*base_addr = alloc_vmem(*size);
|
|
|
|
if (*base_addr != NULL) {
|
|
|
|
AT_PRINTF("allocated %.2f GB of virtual memory for measure buffer at %p\n", *size / 1024.0 / 1024.0 / 1024.0, *base_addr);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// try again with half the size
|
|
|
|
*size /= 2;
|
|
|
|
} while (*size > 0);
|
|
|
|
|
|
|
|
GGML_ASSERT(!"failed to allocate virtual memory for measure buffer");
|
|
|
|
}
|
|
|
|
|
|
|
|
static void free_measure_vmem(void * base_addr, size_t size) {
|
|
|
|
free_vmem(base_addr, size);
|
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
|
|
|
|
struct ggml_allocr * ggml_allocr_new_measure(size_t alignment) {
|
|
|
|
struct ggml_allocr * alloc = (struct ggml_allocr *)malloc(sizeof(struct ggml_allocr) /* + n_free_blocks * sizeof(struct free_block) */);
|
|
|
|
|
2023-09-03 20:34:09 +02:00
|
|
|
void * base_addr;
|
|
|
|
size_t size;
|
|
|
|
|
|
|
|
alloc_measure_vmem(&base_addr, &size);
|
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
*alloc = (struct ggml_allocr){
|
2023-09-03 20:34:09 +02:00
|
|
|
/*.data = */ base_addr,
|
|
|
|
/*.size = */ size,
|
2023-07-30 15:58:01 +02:00
|
|
|
/*.alignment = */ alignment,
|
|
|
|
/*.n_free_blocks = */ 0,
|
|
|
|
/*.free_blocks = */ {{0}},
|
|
|
|
/*.hash_table = */ {{0}},
|
|
|
|
/*.max_size = */ 0,
|
|
|
|
/*.measure = */ true,
|
2023-08-16 22:08:28 +02:00
|
|
|
/*.parse_seq = */ {0},
|
2023-08-24 18:27:25 +02:00
|
|
|
/*.parse_seq_len = */ 0,
|
2023-07-30 15:58:01 +02:00
|
|
|
#ifdef GGML_ALLOCATOR_DEBUG
|
2023-08-28 13:24:53 +02:00
|
|
|
/*.allocated_tensors = */ {0},
|
2023-07-30 15:58:01 +02:00
|
|
|
#endif
|
|
|
|
};
|
|
|
|
|
|
|
|
ggml_allocr_reset(alloc);
|
|
|
|
|
|
|
|
return alloc;
|
|
|
|
}
|
|
|
|
|
|
|
|
void ggml_allocr_free(struct ggml_allocr * alloc) {
|
2023-09-03 20:34:09 +02:00
|
|
|
if (alloc->measure) {
|
|
|
|
free_measure_vmem(alloc->data, alloc->size);
|
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
free(alloc);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool ggml_allocr_is_measure(struct ggml_allocr * alloc) {
|
|
|
|
return alloc->measure;
|
|
|
|
}
|
|
|
|
|
|
|
|
//////////// compute graph allocator
|
|
|
|
|
|
|
|
static bool ggml_is_view(struct ggml_tensor * t) {
|
2023-08-29 23:24:42 +02:00
|
|
|
return t->view_src != NULL;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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:
|
|
|
|
case GGML_OP_CONT:
|
|
|
|
return true;
|
|
|
|
|
|
|
|
default:
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static void allocate_node(struct ggml_allocr * alloc, struct ggml_tensor * node) {
|
|
|
|
struct hash_node * ht = alloc->hash_table;
|
|
|
|
if (node->data == NULL) {
|
|
|
|
if (ggml_is_view(node)) {
|
2023-08-29 23:24:42 +02:00
|
|
|
assert(node->view_src->data != NULL);
|
|
|
|
node->data = (char *)node->view_src->data + node->view_offs;
|
2023-07-30 15:58:01 +02:00
|
|
|
} else {
|
|
|
|
// see if we can 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-08-09 22:47:42 +02:00
|
|
|
|
|
|
|
// if the node's data is external, then we cannot re-use it
|
2023-09-03 20:34:09 +02:00
|
|
|
if (ggml_allocr_is_own(alloc, parent) == false) {
|
2023-08-09 22:47:42 +02:00
|
|
|
AT_PRINTF("not reusing parent %s for %s as %p is external\n", parent->name, node->name, parent->data);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
struct hash_node * p_hn = hash_get(ht, parent);
|
|
|
|
if (parent->data != NULL && p_hn->n_children == 1 && p_hn->n_views == 0 && ggml_are_same_layout(node, parent)) {
|
|
|
|
if (ggml_is_view(parent)) {
|
2023-08-29 23:24:42 +02:00
|
|
|
struct ggml_tensor * view_src = parent->view_src;
|
2023-07-30 15:58:01 +02:00
|
|
|
struct hash_node * view_src_hn = hash_get(ht, view_src);
|
|
|
|
if (view_src_hn->n_views == 1 && view_src_hn->n_children == 0 && view_src->data == parent->data) {
|
|
|
|
// TODO: the offset of the view parent must be kept to ensure that the op doesn't overwrite
|
|
|
|
// the parent's data that it will need later (same layout requirement). the problem is that then
|
|
|
|
// we cannot free the tensor because the original address of the allocation is lost.
|
|
|
|
// adding a view_src pointer to the tensor would solve this and simplify the code dealing with views
|
|
|
|
// for now, we only reuse the parent's data if the offset is zero (view_src->data == parent->data)
|
|
|
|
AT_PRINTF("reusing view parent %s (%s) for %s\n", parent->name, view_src->name, node->name);
|
|
|
|
node->data = parent->data;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
AT_PRINTF("reusing parent %s for %s\n", parent->name, node->name);
|
|
|
|
node->data = parent->data;
|
2023-08-24 18:27:25 +02:00
|
|
|
return;
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ggml_allocr_alloc(alloc, node);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-03 20:34:09 +02:00
|
|
|
static size_t ggml_allocr_alloc_graph_tensors_n(
|
2023-07-30 15:58:01 +02:00
|
|
|
struct ggml_allocr * alloc,
|
|
|
|
struct ggml_cgraph ** graphs, int n_graphs,
|
|
|
|
struct ggml_tensor *** inputs, struct ggml_tensor *** outputs) {
|
|
|
|
|
|
|
|
// reset hash table
|
|
|
|
struct hash_node * ht = alloc->hash_table;
|
|
|
|
memset(ht, 0, sizeof(struct hash_node) * GGML_GRAPH_HASHTABLE_SIZE);
|
|
|
|
|
|
|
|
// count number of children and views
|
|
|
|
for (int g = 0; g < n_graphs; g++) {
|
|
|
|
struct ggml_cgraph * gf = graphs[g];
|
|
|
|
for (int i = 0; i < gf->n_nodes; i++) {
|
|
|
|
struct ggml_tensor * node = gf->nodes[i];
|
|
|
|
|
|
|
|
if (ggml_is_view(node)) {
|
2023-08-29 23:24:42 +02:00
|
|
|
struct ggml_tensor * view_src = node->view_src;
|
2023-07-30 15:58:01 +02:00
|
|
|
hash_get(ht, view_src)->n_views += 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
struct ggml_tensor * parent = node->src[j];
|
|
|
|
if (parent == NULL) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
hash_get(ht, parent)->n_children += 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// allocate tensors
|
|
|
|
for (int g = 0; g < n_graphs; g++) {
|
|
|
|
struct ggml_cgraph * gf = graphs[g];
|
|
|
|
AT_PRINTF("####### graph %d/%d\n", g, n_graphs);
|
|
|
|
// graph inputs are allocated first to ensure that they are not overwritten by each other
|
|
|
|
if (inputs != NULL && inputs[g] != NULL) {
|
|
|
|
for (int i = 0; inputs[g][i] != NULL; i++) {
|
|
|
|
struct ggml_tensor * input = inputs[g][i];
|
|
|
|
AT_PRINTF("input: %s\n", input->name);
|
|
|
|
allocate_node(alloc, input);
|
|
|
|
}
|
|
|
|
}
|
2023-08-24 18:27:25 +02:00
|
|
|
// if we have parse_seq then we allocate nodes following the list, and we only free nodes at barriers
|
|
|
|
int last_barrier_pos = 0;
|
|
|
|
int n_nodes = alloc->parse_seq_len ? alloc->parse_seq_len : gf->n_nodes;
|
|
|
|
|
|
|
|
for (int ind = 0; ind < n_nodes; ind++) {
|
|
|
|
// allocate a node if there is no parse_seq or this is not a barrier
|
|
|
|
if ((alloc->parse_seq_len==0) || alloc->parse_seq[ind] != -1) {
|
|
|
|
int i = alloc->parse_seq_len ? alloc->parse_seq[ind] : ind;
|
|
|
|
struct ggml_tensor * node = gf->nodes[i];
|
|
|
|
|
|
|
|
// allocate parents (leafs)
|
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
|
|
struct ggml_tensor * parent = node->src[j];
|
|
|
|
if (parent == NULL) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
allocate_node(alloc, parent);
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
|
2023-08-24 18:27:25 +02:00
|
|
|
// allocate node
|
|
|
|
allocate_node(alloc, node);
|
2023-07-30 15:58:01 +02:00
|
|
|
|
2023-08-24 18:27:25 +02:00
|
|
|
AT_PRINTF("exec: %s (%s) <= ", ggml_op_name(node->op), 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
|
|
|
}
|
2023-08-24 18:27:25 +02:00
|
|
|
AT_PRINTF("\n");
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
2023-08-24 18:27:25 +02:00
|
|
|
|
2023-07-30 15:58:01 +02:00
|
|
|
// update parents
|
2023-08-24 18:27:25 +02:00
|
|
|
// update immediately if there is no parse_seq
|
|
|
|
// update only at barriers if there is parse_seq
|
2023-09-03 20:34:09 +02:00
|
|
|
if ((alloc->parse_seq_len == 0) || alloc->parse_seq[ind] == -1) {
|
2023-08-24 18:27:25 +02:00
|
|
|
int update_start = alloc->parse_seq_len ? last_barrier_pos : ind;
|
|
|
|
int update_end = alloc->parse_seq_len ? ind : ind + 1;
|
|
|
|
for (int i = update_start; i < update_end; i++) {
|
|
|
|
int node_i = alloc->parse_seq_len ? alloc->parse_seq[i] : i;
|
|
|
|
struct ggml_tensor * node = gf->nodes[node_i];
|
|
|
|
|
|
|
|
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
|
|
|
}
|
2023-08-24 18:27:25 +02:00
|
|
|
struct hash_node * p_hn = hash_get(ht, parent);
|
|
|
|
p_hn->n_children -= 1;
|
|
|
|
|
|
|
|
//AT_PRINTF("parent %s: %d children, %d views\n", parent->name, parent->n_children, parent->n_views);
|
|
|
|
|
|
|
|
if (p_hn->n_children == 0 && p_hn->n_views == 0) {
|
|
|
|
if (ggml_is_view(parent)) {
|
2023-08-29 23:24:42 +02:00
|
|
|
struct ggml_tensor * view_src = parent->view_src;
|
2023-08-24 18:27:25 +02:00
|
|
|
struct hash_node * view_src_hn = hash_get(ht, view_src);
|
|
|
|
view_src_hn->n_views -= 1;
|
2023-08-28 13:24:53 +02:00
|
|
|
AT_PRINTF("view_src %s: %d children, %d views\n", view_src->name, view_src_hn->n_children, view_src_hn->n_views);
|
2023-08-24 18:27:25 +02:00
|
|
|
if (view_src_hn->n_views == 0 && view_src_hn->n_children == 0 && view_src->data != node->data) {
|
2023-09-03 20:34:09 +02:00
|
|
|
ggml_allocr_free_tensor(alloc, view_src);
|
2023-08-24 18:27:25 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
if (parent->data != node->data) {
|
2023-09-03 20:34:09 +02:00
|
|
|
ggml_allocr_free_tensor(alloc, parent);
|
2023-08-24 18:27:25 +02:00
|
|
|
}
|
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-08-24 18:27:25 +02:00
|
|
|
AT_PRINTF("\n");
|
|
|
|
if (alloc->parse_seq_len) {
|
|
|
|
last_barrier_pos = ind + 1;
|
|
|
|
}
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// free graph outputs here that wouldn't be freed otherwise because they have no children
|
|
|
|
if (outputs != NULL && outputs[g] != NULL) {
|
|
|
|
for (int i = 0; outputs[g][i] != NULL; i++) {
|
|
|
|
struct ggml_tensor * output = outputs[g][i];
|
|
|
|
AT_PRINTF("output: %s\n", output->name);
|
2023-09-03 20:34:09 +02:00
|
|
|
ggml_allocr_free_tensor(alloc, output);
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return alloc->max_size;
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t ggml_allocr_alloc_graph(struct ggml_allocr * alloc, struct ggml_cgraph * graph) {
|
2023-09-03 20:34:09 +02:00
|
|
|
return ggml_allocr_alloc_graph_tensors_n(alloc, &graph, 1, NULL, NULL);
|
2023-07-30 15:58:01 +02:00
|
|
|
}
|