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: LicenseRef-FSL-1.1-Apache-2.0
4// Copyright 2026 Lloyal Labs
5
6
7#include "common.hpp"
8#include <functional>
9#include <llama/llama.h>
10#include <memory>
11#include <mutex>
12#include <string>
13#include <unordered_map>
14
28namespace lloyal {
29
36struct ModelKey {
37 std::string canonPath;
40
41 bool operator==(const ModelKey &o) const {
42 return n_gpu_layers == o.n_gpu_layers && load_mode == o.load_mode &&
44 }
45};
46
53// Compiler-specific sanitizer suppression (GCC/Clang only; no-op on MSVC)
54#if defined(__GNUC__) || defined(__clang__)
55 #define LLOYAL_NO_SANITIZE_OVERFLOW __attribute__((no_sanitize("unsigned-integer-overflow")))
56#else
57 #define LLOYAL_NO_SANITIZE_OVERFLOW
58#endif
59
70 size_t operator()(const ModelKey &k) const {
71 std::hash<std::string> Hs;
72 std::hash<int> Hi;
73 return Hs(k.canonPath) ^
74 (Hi(k.n_gpu_layers) + 0x9e3779b9 + (Hi(k.load_mode) << 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, static_cast<int>(params.load_mode)};
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, load_mode=%d",
205 key.canonPath.c_str(), key.n_gpu_layers, key.load_mode);
206
207 std::lock_guard<std::mutex> lock(mu_);
208
209 auto cacheEntry = cache_.find(key);
210 if (cacheEntry != cache_.end()) {
211 // Try to upgrade weak_ptr to shared_ptr
212 if (auto existingModel = cacheEntry->second.lock()) {
213 long refCount = existingModel.use_count();
215 "[ModelRegistry] Cache HIT - Reusing model: ptr=%p, refcount=%ld",
216 (void *)existingModel.get(), refCount);
217 return existingModel;
218 } else {
219 LLOYAL_LOG_DEBUG("[ModelRegistry] Cache entry expired (model was freed), "
220 "removing stale entry");
221 cache_.erase(cacheEntry);
222 }
223 }
224
225 LLOYAL_LOG_DEBUG("[ModelRegistry] Cache MISS - Loading NEW model from disk");
226 LLOYAL_LOG_DEBUG("[ModelRegistry] Path: %s", key.canonPath.c_str());
227 LLOYAL_LOG_DEBUG("[ModelRegistry] GPU layers: %d", key.n_gpu_layers);
228 LLOYAL_LOG_DEBUG("[ModelRegistry] Load mode: %d", key.load_mode);
229
230 llama_model *rawModel =
231 llama_model_load_from_file(key.canonPath.c_str(), params);
232
233 if (!rawModel) {
234 // Let caller handle error (will throw structured error)
236 "[ModelRegistry] ERROR: llama_model_load_from_file returned NULL");
237 return nullptr;
238 }
239
240 size_t modelSize = llama_model_size(rawModel);
241 LLOYAL_LOG_DEBUG("[ModelRegistry] Model loaded:");
242 LLOYAL_LOG_DEBUG("[ModelRegistry] Pointer: %p", (void *)rawModel);
243 LLOYAL_LOG_DEBUG("[ModelRegistry] Size: %zu bytes (%.2f MB)", modelSize,
244 modelSize / (1024.0 * 1024.0));
245
246 auto sharedModel = std::shared_ptr<llama_model>(rawModel, detail::freeModel);
247
248 // Store as weak_ptr (allows automatic cleanup when all contexts release the
249 // model)
250 cache_[key] = sharedModel;
251 LLOYAL_LOG_DEBUG("[ModelRegistry] Model cached as weak_ptr, returning "
252 "shared_ptr (refcount=1)");
253
254 return sharedModel;
255}
256
257} // 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:48
#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)
int n_gpu_layers
Number of layers offloaded to GPU (-1 = all)
bool operator==(const ModelKey &o) const
int load_mode
llama_load_mode the model was loaded with