liblloyal 1.0.0
Branched Inference for llama.cpp
Loading...
Searching...
No Matches
model_registry.hpp
Go to the documentation of this file.
1#pragma once
2
3// SPDX-License-Identifier: Apache-2.0
4// Copyright 2026 Lloyal Labs
5
6#include "common.hpp"
7#include <functional>
8#include <llama/llama.h>
9#include <memory>
10#include <mutex>
11#include <string>
12#include <unordered_map>
13
27namespace lloyal {
28
35struct ModelKey {
36 std::string canonPath;
38 bool use_mmap;
39
40 bool operator==(const ModelKey &o) const {
41 return n_gpu_layers == o.n_gpu_layers && use_mmap == o.use_mmap &&
43 }
44};
45
52// Compiler-specific sanitizer suppression (GCC/Clang only; no-op on MSVC)
53#if defined(__GNUC__) || defined(__clang__)
54 #define LLOYAL_NO_SANITIZE_OVERFLOW __attribute__((no_sanitize("unsigned-integer-overflow")))
55#else
56 #define LLOYAL_NO_SANITIZE_OVERFLOW
57#endif
58
69 size_t operator()(const ModelKey &k) const {
70 std::hash<std::string> Hs;
71 std::hash<int> Hi;
72 std::hash<bool> Hb;
73 return Hs(k.canonPath) ^
74 (Hi(k.n_gpu_layers) + 0x9e3779b9 + (Hb(k.use_mmap) << 6));
75 }
76};
77
78#undef LLOYAL_NO_SANITIZE_OVERFLOW
79
116public:
128 static std::shared_ptr<llama_model> acquire(const std::string &fsPath,
129 const llama_model_params &params);
130
131private:
133 inline static std::mutex mu_;
134
136 inline static std::unordered_map<ModelKey, std::weak_ptr<llama_model>,
138 cache_;
139
150 static ModelKey makeKey(const std::string &fsPath,
151 const llama_model_params &params);
152};
153
154} // namespace lloyal
155
156namespace lloyal::detail {
157
166inline void freeModel(llama_model *model) {
168 "[ModelRegistry] Freeing model: ptr=%p (last reference released)",
169 (void *)model);
170 llama_model_free(model);
171 LLOYAL_LOG_DEBUG("[ModelRegistry] Model freed: ptr=%p", (void *)model);
172}
173
174} // namespace lloyal::detail
175
176namespace lloyal {
177
178// ===== IMPLEMENTATION =====
179
180// Normalize path to ensure "file:///path" and "/path" map to same key
181inline ModelKey ModelRegistry::makeKey(const std::string &fsPath,
182 const llama_model_params &params) {
183 // Inline path normalization (removes file:// prefix if present)
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());
188 }
189
190 return {canonPath, params.n_gpu_layers, params.use_mmap};
191}
192
193// Acquire model from cache or load new
194// 1. Check cache (thread-safe)
195// 2. Return existing if found (cache hit)
196// 3. Load new if expired (cache miss)
197// 4. Store as weak_ptr, return shared_ptr
198inline std::shared_ptr<llama_model>
199ModelRegistry::acquire(const std::string &fsPath,
200 const llama_model_params &params) {
201 ModelKey key = makeKey(fsPath, params);
202
203 LLOYAL_LOG_DEBUG("[ModelRegistry] Acquiring model: path='%s', "
204 "n_gpu_layers=%d, use_mmap=%s",
205 key.canonPath.c_str(), key.n_gpu_layers,
206 key.use_mmap ? "true" : "false");
207
208 std::lock_guard<std::mutex> lock(mu_);
209
210 auto cacheEntry = cache_.find(key);
211 if (cacheEntry != cache_.end()) {
212 // Try to upgrade weak_ptr to shared_ptr
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;
219 } else {
220 LLOYAL_LOG_DEBUG("[ModelRegistry] Cache entry expired (model was freed), "
221 "removing stale entry");
222 cache_.erase(cacheEntry);
223 }
224 }
225
226 LLOYAL_LOG_DEBUG("[ModelRegistry] Cache MISS - Loading NEW model from disk");
227 LLOYAL_LOG_DEBUG("[ModelRegistry] Path: %s", key.canonPath.c_str());
228 LLOYAL_LOG_DEBUG("[ModelRegistry] GPU layers: %d", key.n_gpu_layers);
229 LLOYAL_LOG_DEBUG("[ModelRegistry] Memory mapping: %s",
230 key.use_mmap ? "enabled" : "disabled");
231
232 llama_model *rawModel =
233 llama_model_load_from_file(key.canonPath.c_str(), params);
234
235 if (!rawModel) {
236 // Let caller handle error (will throw structured error)
238 "[ModelRegistry] ERROR: llama_model_load_from_file returned NULL");
239 return nullptr;
240 }
241
242 size_t modelSize = llama_model_size(rawModel);
243 LLOYAL_LOG_DEBUG("[ModelRegistry] Model loaded:");
244 LLOYAL_LOG_DEBUG("[ModelRegistry] Pointer: %p", (void *)rawModel);
245 LLOYAL_LOG_DEBUG("[ModelRegistry] Size: %zu bytes (%.2f MB)", modelSize,
246 modelSize / (1024.0 * 1024.0));
247
248 auto sharedModel = std::shared_ptr<llama_model>(rawModel, detail::freeModel);
249
250 // Store as weak_ptr (allows automatic cleanup when all contexts release the
251 // model)
252 cache_[key] = sharedModel;
253 LLOYAL_LOG_DEBUG("[ModelRegistry] Model cached as weak_ptr, returning "
254 "shared_ptr (refcount=1)");
255
256 return sharedModel;
257}
258
259} // namespace lloyal
static std::shared_ptr< llama_model > acquire(const std::string &fsPath, const llama_model_params &params)
Acquire a model from cache, or load from disk on cache miss.
#define LLOYAL_LOG_DEBUG(...)
liblloyal - Common definitions and logging
Definition common.hpp:47
#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