| 1 | #ifndef _ggml_memory_pool_h_ |
| 2 | #define _ggml_memory_pool_h_ |
| 3 | /* ggml-memory-pool.cpp |
| 4 | * |
| 5 | * Copyright (C) 2026 Anastasia Shchupak |
| 6 | * |
| 7 | * This code is free software; you can redistribute it and/or modify |
| 8 | * it under the terms of the GNU General Public License as published by |
| 9 | * the Free Software Foundation; either version 3 of the License, or (at |
| 10 | * your option) any later version. |
| 11 | * |
| 12 | * This code is distributed in the hope that it will be useful, but |
| 13 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 15 | * See the GNU General Public License for more details. |
| 16 | * |
| 17 | * You should have received a copy of the GNU General Public License |
| 18 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 19 | */ |
| 20 | |
| 21 | /* |
| 22 | * A memory tracking pool for GGML memory allocations within Praat. |
| 23 | * |
| 24 | * All memory allocations by malloc, calloc, realloc, _aligned_malloc, hbw_posix_memalign, vm_allocate |
| 25 | * made in GGML are added to this pool. If an allocation fails, instead of abort |
| 26 | * (which causes Praat to crash), we will free all the memory registered in the pool. This will allow |
| 27 | * Praat to continue running after a graceful end of whatever was using GGML: |
| 28 | * transcription, speech activity detection, or diarizarion. |
| 29 | */ |
| 30 | |
| 31 | #include <unordered_map> |
| 32 | |
| 33 | struct Allocation { |
| 34 | size_t size; |
| 35 | bool aligned; |
| 36 | }; |
| 37 | |
| 38 | class GgmlMemoryPool { |
| 39 | private: |
| 40 | std::unordered_map <void *, Allocation> allocations; |
| 41 | |
| 42 | public: |
| 43 | void add(void *ptr, size_t size, bool aligned); // registers a successful allocation |
| 44 | bool remove(void *ptr); // removes allocation after freeing the memory normally by GGML_FREE(), returns true on success (if there was smth to be removed) |
| 45 | bool remove(void *ptr, size_t size); // removes allocation after freeing the memory normally by ggml_aligned_free() |
| 46 | void clear(); // free all registered allocations and clear the pool |
| 47 | size_t n_allocations() const; |
| 48 | size_t sizeInBytes() const; |
| 49 | }; |
| 50 | |
| 51 | extern GgmlMemoryPool theGgmlMemoryPool; |
| 52 | |
| 53 | /* End of file ggml-memory-pool.h */ |
| 54 | #endif |