8#include <llama/llama.h>
12#include <unordered_map>
53#if defined(__GNUC__) || defined(__clang__)
54 #define LLOYAL_NO_SANITIZE_OVERFLOW __attribute__((no_sanitize("unsigned-integer-overflow")))
56 #define LLOYAL_NO_SANITIZE_OVERFLOW
70 std::hash<std::string> Hs;
78#undef LLOYAL_NO_SANITIZE_OVERFLOW
128 static std::shared_ptr<llama_model>
acquire(
const std::string &fsPath,
129 const llama_model_params ¶ms);
133 inline static std::mutex mu_;
136 inline static std::unordered_map<ModelKey, std::weak_ptr<llama_model>,
150 static ModelKey makeKey(
const std::string &fsPath,
151 const llama_model_params ¶ms);
166inline void freeModel(llama_model *model) {
168 "[ModelRegistry] Freeing model: ptr=%p (last reference released)",
170 llama_model_free(model);
181inline ModelKey ModelRegistry::makeKey(
const std::string &fsPath,
182 const llama_model_params ¶ms) {
184 std::string canonPath = fsPath;
185 const std::string filePrefix =
"file://";
186 if (canonPath.substr(0, filePrefix.length()) == filePrefix) {
187 canonPath = canonPath.substr(filePrefix.length());
190 return {canonPath, params.
n_gpu_layers, params.use_mmap};
198inline std::shared_ptr<llama_model>
200 const llama_model_params ¶ms) {
201 ModelKey key = makeKey(fsPath, params);
204 "n_gpu_layers=%d, use_mmap=%s",
208 std::lock_guard<std::mutex> lock(mu_);
210 auto cacheEntry = cache_.find(key);
211 if (cacheEntry != cache_.end()) {
213 if (
auto existingModel = cacheEntry->second.lock()) {
214 long refCount = existingModel.use_count();
216 "[ModelRegistry] Cache HIT - Reusing model: ptr=%p, refcount=%ld",
217 (
void *)existingModel.get(), refCount);
218 return existingModel;
221 "removing stale entry");
222 cache_.erase(cacheEntry);
226 LLOYAL_LOG_DEBUG(
"[ModelRegistry] Cache MISS - Loading NEW model from disk");
230 key.
use_mmap ?
"enabled" :
"disabled");
232 llama_model *rawModel =
233 llama_model_load_from_file(key.
canonPath.c_str(), params);
238 "[ModelRegistry] ERROR: llama_model_load_from_file returned NULL");
242 size_t modelSize = llama_model_size(rawModel);
246 modelSize / (1024.0 * 1024.0));
248 auto sharedModel = std::shared_ptr<llama_model>(rawModel, detail::freeModel);
252 cache_[key] = sharedModel;
254 "shared_ptr (refcount=1)");
static std::shared_ptr< llama_model > acquire(const std::string &fsPath, const llama_model_params ¶ms)
Acquire a model from cache, or load from disk on cache miss.
#define LLOYAL_LOG_DEBUG(...)
liblloyal - Common definitions and logging
#define LLOYAL_NO_SANITIZE_OVERFLOW
Hash functor for ModelKey.
Boundary Tracker Stub for OSS liblloyal.
size_t operator()(const ModelKey &k) const
Compute hash for ModelKey.
Model cache key combining file path and GPU configuration.
std::string canonPath
Normalized file path (file:// prefix removed)
bool use_mmap
Whether to use memory mapping.
int n_gpu_layers
Number of layers offloaded to GPU (-1 = all)
bool operator==(const ModelKey &o) const