Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/ggml/blob/master/src/ggml-openvino/model-cache.cpp # ggml [Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `ggml / src / ggml-openvino / model-cache.cpp` 484 lines ยท 18452 bytes Raw Blame History 1 #include "model-cache.h" 2 3 #include "ggml-backend-impl.h" 4 #include "ggml-backend.h" 5 #include "ggml-impl.h" 6 #include "ggml-openvino-extra.h" 7 8 #include 9 #include 10 #include 11 #include 12 #include 13 #include 14 #include 15 #include 16 #include 17 #include 18 #include 19 #include 20 #include 21 22 #if defined(_WIN32) 23 # define WIN32_LEAN_AND_MEAN 24 # ifndef NOMINMAX 25 # define NOMINMAX 26 # endif 27 # include 28 # include 29 # include 30 # include 31 #else 32 # include 33 #endif 34 #ifdef __linux__ 35 # include 36 #endif 37 38 namespace { 39 40 // 64-bit FNV-1a, the mixing primitive for all fingerprints here. 41 inline uint64_t fnv1a(uint64_t h, const void * data, size_t n) { 42 const uint8_t * p = static_cast(data); 43 for (size_t i = 0; i < n; ++i) { 44 h ^= p[i]; 45 h *= 0x100000001b3ull; 46 } 47 return h; 48 } 49 50 inline uint64_t fnv1a_u64(uint64_t h, uint64_t v) { 51 return fnv1a(h, &v, sizeof(v)); 52 } 53 54 constexpr uint64_t FNV_OFFSET = 0xcbf29ce484222325ull; 55 56 // Fallback when source-file identity is unavailable outside cache-only mode. 57 constexpr size_t WEIGHT_SAMPLE_BYTES = 4096; 58 59 // Is this src a model weight, mirroring create_weight_nodes()'s selection: 60 // non-view tensor whose buffer is USAGE_WEIGHTS or whose type is quantized. 61 bool is_weight_src(const ggml_tensor * src) { 62 if (src == nullptr || src->view_src != nullptr || src->buffer == nullptr) { 63 return false; 64 } 65 return src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS || ggml_is_quantized(src->type); 66 } 67 68 // Weight metadata and source identity; do not read repacked or unloaded buffers. 69 uint64_t weight_fingerprint(const ggml_tensor * t) { 70 uint64_t h = FNV_OFFSET; 71 h = fnv1a(h, t->name, strlen(t->name)); 72 for (int i = 0; i < GGML_MAX_DIMS; ++i) { 73 h = fnv1a_u64(h, static_cast(t->ne[i])); 74 } 75 h = fnv1a_u64(h, static_cast(t->type)); 76 const size_t nbytes = ggml_nbytes(t); 77 h = fnv1a_u64(h, nbytes); 78 return fnv1a_u64(h, ggml_backend_openvino_weight_fingerprint(t)); 79 } 80 81 // Walk the cgraph and invoke fn(weight_tensor) for each distinct weight, in node 82 // order. De-duplicates by tensor pointer so a weight used by several nodes is 83 // fingerprinted once, deterministically. 84 template 85 void for_each_weight(const ggml_cgraph * cgraph, F && fn) { 86 std::vector seen; 87 for (int i = 0; i < cgraph->n_nodes; ++i) { 88 const ggml_tensor * node = cgraph->nodes[i]; 89 for (int s = 0; s < GGML_MAX_SRC; ++s) { 90 const ggml_tensor * src = node->src[s]; 91 if (!is_weight_src(src)) { 92 continue; 93 } 94 bool dup = false; 95 for (const auto * p : seen) { 96 if (p == src) { 97 dup = true; 98 break; 99 } 100 } 101 if (dup) { 102 continue; 103 } 104 seen.push_back(src); 105 fn(src); 106 } 107 } 108 } 109 110 std::string ov_version_string() { 111 const ov::Version v = ov::get_openvino_version(); 112 return std::string(v.buildNumber ? v.buildNumber : "unknown"); 113 } 114 115 std::string hex64(uint64_t v) { 116 char buf[17]; 117 snprintf(buf, sizeof(buf), "%016llx", static_cast(v)); 118 return std::string(buf); 119 } 120 121 // Portable mkdir for a single path component. Returns true if the directory 122 // exists after the call (created now or already present). 123 bool make_dir(const std::string & path) { 124 #if defined(_WIN32) 125 int rc = _mkdir(path.c_str()); 126 #else 127 int rc = ::mkdir(path.c_str(), 0755); 128 #endif 129 if (rc == 0 || errno == EEXIST) { 130 return true; 131 } 132 return false; 133 } 134 135 // Create `path` and any missing parents (like `mkdir -p`). Best-effort: 136 // returns true only if the full directory exists afterwards. 137 bool make_dirs(const std::string & path) { 138 if (path.empty()) { 139 return false; 140 } 141 std::string acc; 142 for (size_t i = 0; i < path.size(); ++i) { 143 const char c = path[i]; 144 acc.push_back(c); 145 const bool sep = (c == '/' 146 #if defined(_WIN32) 147 || c == '\\' 148 #endif 149 ); 150 // Create each intermediate component (skip a leading "/" root). 151 if (sep && acc.size() > 1) { 152 std::string component = acc.substr(0, acc.size() - 1); 153 if (!make_dir(component)) { 154 return false; 155 } 156 } 157 } 158 return make_dir(path); 159 } 160 161 } // namespace 162 163 bool ggml_openvino_model_cache_only() { 164 return ggml_openvino_getenv_int("GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY") != 0; 165 } 166 167 static const char * cache_settings[] = { 168 "GGML_OPENVINO_REQUANT_KQUANT", 169 "GGML_OPENVINO_NATIVE_SOFTPLUS", 170 "GGML_OPENVINO_DISABLE_KV_SLICE", 171 "GGML_OPENVINO_MANUAL_GQA_ATTN", 172 "GGML_OPENVINO_STATEFUL_EXECUTION", 173 "GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT", 174 "GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", 175 "GGML_OPENVINO_REDUCE_COMPILE_MEM", 176 "GGML_OPENVINO_MEMORY_OPTIMIZE", 177 "GGML_OPENVINO_PROFILING", 178 }; 179 180 void ggml_openvino_model_cache_init() { 181 const bool cache_only = ggml_openvino_model_cache_only(); 182 const std::string dir = ggml_openvino_model_cache_dir(); 183 if (dir.empty()) { 184 if (cache_only) { 185 GGML_ABORT("ggml-openvino: cache-only mode requires GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR"); 186 } 187 return; 188 } 189 if (cache_only && (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC") || 190 ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE") || 191 ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_FALLBACK"))) { 192 GGML_ABORT("ggml-openvino: cache-only mode requires dynamic CPU/GPU execution with caching and without fallback"); 193 } 194 #if !defined(__linux__) && !defined(_WIN32) 195 if (cache_only) { 196 GGML_ABORT("ggml-openvino: cache-only mmap identification requires Linux or Windows"); 197 } 198 #endif 199 if (cache_only) { 200 auto & config = ggml_openvino_get_device_config(); 201 config.environment_variables.erase("GGML_OPENVINO_SPILL_DIR"); 202 config.environment_variables["GGML_OPENVINO_RELEASE_WEIGHTS"] = "0"; 203 } 204 } 205 206 uint64_t ggml_openvino_source_fingerprint(const void * data, size_t size, std::vector & mappings) { 207 const uintptr_t address = reinterpret_cast(data); 208 auto contains = [&](const ggml_openvino_source_mapping & m) { 209 return address >= m.begin && address < m.end && size <= m.end - address; 210 }; 211 auto fingerprint = [&](const ggml_openvino_source_mapping & m) { 212 return fnv1a_u64(m.identity, m.offset + address - m.begin); 213 }; 214 for (const auto & m : mappings) { 215 if (contains(m)) { 216 return fingerprint(m); 217 } 218 } 219 #ifdef __linux__ 220 std::ifstream maps("/proc/self/maps"); 221 std::string line; 222 while (std::getline(maps, line)) { 223 unsigned long long begin, end, offset, inode; 224 unsigned int dev_major, dev_minor; 225 char permissions[5]; 226 int path_start = 0; 227 if (sscanf(line.c_str(), "%llx-%llx %4s %llx %x:%x %llu %n", &begin, &end, permissions, 228 &offset, &dev_major, &dev_minor, &inode, &path_start) != 7 || inode == 0) { 229 continue; 230 } 231 ggml_openvino_source_mapping m{uintptr_t(begin), uintptr_t(end), offset, FNV_OFFSET}; 232 if (!contains(m)) { 233 continue; 234 } 235 struct stat st; 236 const std::string path = line.substr(path_start); 237 if (stat(path.c_str(), &st) != 0 || !S_ISREG(st.st_mode) || uint64_t(st.st_ino) != inode || 238 major(st.st_dev) != dev_major || minor(st.st_dev) != dev_minor) { 239 break; 240 } 241 m.identity = fnv1a_u64(m.identity, st.st_dev); 242 m.identity = fnv1a_u64(m.identity, st.st_ino); 243 m.identity = fnv1a_u64(m.identity, st.st_size); 244 m.identity = fnv1a_u64(m.identity, st.st_mtim.tv_sec); 245 m.identity = fnv1a_u64(m.identity, st.st_mtim.tv_nsec); 246 m.identity = fnv1a_u64(m.identity, st.st_ctim.tv_sec); 247 m.identity = fnv1a_u64(m.identity, st.st_ctim.tv_nsec); 248 mappings.push_back(m); 249 return fingerprint(m); 250 } 251 #elif defined(_WIN32) 252 MEMORY_BASIC_INFORMATION memory; 253 if (VirtualQuery(data, &memory, sizeof(memory)) == sizeof(memory) && memory.Type == MEM_MAPPED) { 254 std::wstring name(MAX_PATH, L'\0'); 255 DWORD length = 0; 256 while (name.size() <= 32768) { 257 length = GetMappedFileNameW(GetCurrentProcess(), const_cast(data), name.data(), static_cast(name.size())); 258 if (length == 0 || length < name.size() - 1) { 259 break; 260 } 261 name.resize(name.size() * 2); 262 } 263 if (length > 0 && length < name.size() - 1) { 264 name.resize(length); 265 const std::wstring path = L"\\\\?\\GLOBALROOT" + name; 266 HANDLE file = CreateFileW(path.c_str(), FILE_READ_ATTRIBUTES, 267 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, 268 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); 269 if (file != INVALID_HANDLE_VALUE) { 270 BY_HANDLE_FILE_INFORMATION info; 271 FILE_BASIC_INFO basic; 272 const bool valid = GetFileInformationByHandle(file, &info) && 273 GetFileInformationByHandleEx(file, FileBasicInfo, &basic, sizeof(basic)); 274 CloseHandle(file); 275 if (valid) { 276 const uint64_t file_size = (uint64_t(info.nFileSizeHigh) << 32) | info.nFileSizeLow; 277 const uintptr_t begin = reinterpret_cast(memory.AllocationBase); 278 if (file_size <= std::numeric_limits::max() - begin) { 279 ggml_openvino_source_mapping m{begin, begin + static_cast(file_size), 0, 280 fnv1a(FNV_OFFSET, "win32", 5)}; 281 if (contains(m)) { 282 m.identity = fnv1a_u64(m.identity, info.dwVolumeSerialNumber); 283 m.identity = fnv1a_u64(m.identity, (uint64_t(info.nFileIndexHigh) << 32) | info.nFileIndexLow); 284 m.identity = fnv1a_u64(m.identity, file_size); 285 m.identity = fnv1a_u64(m.identity, (uint64_t(info.ftLastWriteTime.dwHighDateTime) << 32) | 286 info.ftLastWriteTime.dwLowDateTime); 287 m.identity = fnv1a_u64(m.identity, static_cast(basic.ChangeTime.QuadPart)); 288 mappings.push_back(m); 289 return fingerprint(m); 290 } 291 } 292 } 293 } 294 } 295 } 296 #endif 297 if (ggml_openvino_model_cache_only()) { 298 GGML_ABORT("ggml-openvino: could not identify mapped GGUF weight; use --load-mode mmap"); 299 } 300 uint64_t h = FNV_OFFSET; 301 const size_t head = std::min(size, WEIGHT_SAMPLE_BYTES); 302 h = fnv1a(h, data, head); 303 if (size > head) { 304 const size_t tail = std::min(size - head, WEIGHT_SAMPLE_BYTES); 305 h = fnv1a(h, static_cast(data) + size - tail, tail); 306 } 307 return h; 308 } 309 310 std::string ggml_openvino_model_cache_dir() { 311 const char * dir = ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR"); 312 if (!dir || strlen(dir) == 0) { 313 return std::string(); 314 } 315 std::string path(dir); 316 if (ggml_openvino_model_cache_only()) { 317 return path; 318 } 319 // Create the cache directory (and parents) on first use so callers don't 320 // have to pre-create it; a missing dir would otherwise silently disable the 321 // cache (manifest/blob writes fail with no directory to write into). 322 if (!make_dirs(path)) { 323 GGML_LOG_WARN("ggml-openvino: could not create model cache dir '%s' (errno=%d); caching disabled\n", 324 path.c_str(), errno); 325 return std::string(); 326 } 327 return path; 328 } 329 330 std::string ggml_openvino_model_cache_temp_path(const std::string & path) { 331 #ifdef _WIN32 332 const int pid = _getpid(); 333 #else 334 const int pid = getpid(); 335 #endif 336 return path + ".tmp." + std::to_string(pid) + "." + std::to_string(ggml_time_us()); 337 } 338 339 uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, 340 const std::string & device, 341 bool fa, 342 const int32_t * rope_params, 343 int rope_len, 344 uint64_t extra_cfg, 345 const std::string & graph_signature) { 346 uint64_t h = FNV_OFFSET; 347 h = fnv1a_u64(h, 2); 348 h = fnv1a(h, graph_signature.data(), graph_signature.size()); 349 for (const char * name : cache_settings) { 350 const char * value = ggml_openvino_getenv_str(name, ""); 351 h = fnv1a(h, value, strlen(value) + 1); 352 } 353 if (const char * debug_nodes = ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) { 354 h = fnv1a(h, "GGML_OPENVINO_DEBUG_NODE", sizeof("GGML_OPENVINO_DEBUG_NODE")); 355 h = fnv1a(h, debug_nodes, strlen(debug_nodes) + 1); 356 } 357 if (ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_MOE_OP", 1) == 0) { 358 h = fnv1a(h, "GGML_OPENVINO_MOE_OP=0", sizeof("GGML_OPENVINO_MOE_OP=0")); 359 } 360 361 // Topology: node count + each node's op and name (cheap, and distinguishes 362 // graphs that share weights but differ structurally). 363 h = fnv1a_u64(h, static_cast(cgraph->n_nodes)); 364 for (int i = 0; i < cgraph->n_nodes; ++i) { 365 const ggml_tensor * node = cgraph->nodes[i]; 366 h = fnv1a_u64(h, static_cast(node->op)); 367 h = fnv1a(h, node->name, strlen(node->name)); 368 } 369 370 // Weights: the model identity. 371 for_each_weight(cgraph, [&](const ggml_tensor * t) { h = fnv1a_u64(h, weight_fingerprint(t)); }); 372 373 // Device, model parameters, and backend configuration. 374 h = fnv1a(h, device.data(), device.size()); 375 h = fnv1a_u64(h, fa ? 1u : 0u); 376 if (rope_params && rope_len > 0) { 377 h = fnv1a(h, rope_params, sizeof(int32_t) * static_cast(rope_len)); 378 } 379 h = fnv1a_u64(h, extra_cfg); 380 const std::string ver = ov_version_string(); 381 h = fnv1a(h, ver.data(), ver.size()); 382 383 return h; 384 } 385 386 std::string ggml_openvino_model_cache_blob_path(const std::string & dir, uint64_t fingerprint) { 387 return dir + "/" + hex64(fingerprint) + ".blob"; 388 } 389 390 std::string ggml_openvino_model_cache_manifest_path(const std::string & dir, uint64_t fingerprint) { 391 return dir + "/" + hex64(fingerprint) + ".manifest"; 392 } 393 394 bool ggml_openvino_model_cache_write_manifest(const std::string & path, 395 const ggml_cgraph * cgraph, 396 uint64_t fingerprint, 397 const std::vector & inputs, 398 const std::vector & outputs) { 399 std::ofstream f(path, std::ios::trunc); 400 if (!f.is_open()) { 401 return false; 402 } 403 f << "fingerprint " << hex64(fingerprint) << "\n"; 404 f << "ov_version " << ov_version_string() << "\n"; 405 for_each_weight(cgraph, [&](const ggml_tensor * t) { 406 f << t->name << " " << t->ne[0] << " " << t->ne[1] << " " << t->ne[2] << " " << t->ne[3] << " " 407 << static_cast(t->type) << " " << hex64(weight_fingerprint(t)) << "\n"; 408 }); 409 f << "ports\n"; 410 for (const auto * names : { &inputs, &outputs }) { 411 f << names->size() << '\n'; 412 for (const auto & name : *names) { 413 f << std::quoted(name) << '\n'; 414 } 415 } 416 return f.good(); 417 } 418 419 bool ggml_openvino_model_cache_verify_manifest(const std::string & path, 420 const ggml_cgraph * cgraph, 421 uint64_t fingerprint, 422 std::vector & inputs, 423 std::vector & outputs) { 424 std::ifstream f(path); 425 if (!f.is_open()) { 426 return false; 427 } 428 std::string tag; 429 std::string val; 430 // header: fingerprint 431 if (!(f >> tag >> val) || tag != "fingerprint" || val != hex64(fingerprint)) { 432 return false; 433 } 434 // header: ov_version 435 if (!(f >> tag >> val) || tag != "ov_version" || val != ov_version_string()) { 436 return false; 437 } 438 439 // Build the expected per-weight lines from the live cgraph, then require an 440 // exact match (same set, same order) against the manifest. 441 std::vector expected; 442 for_each_weight(cgraph, [&](const ggml_tensor * t) { 443 expected.push_back(std::string(t->name) + " " + std::to_string(t->ne[0]) + " " + std::to_string(t->ne[1]) + 444 " " + std::to_string(t->ne[2]) + " " + std::to_string(t->ne[3]) + " " + 445 std::to_string(static_cast(t->type)) + " " + hex64(weight_fingerprint(t))); 446 }); 447 448 size_t idx = 0; 449 std::string line; 450 std::getline(f, line); // consume rest of ov_version line 451 while (idx < expected.size() && std::getline(f, line)) { 452 if (line.empty()) { 453 continue; 454 } 455 if (idx >= expected.size() || line != expected[idx]) { 456 return false; 457 } 458 ++idx; 459 } 460 if (idx != expected.size()) { 461 return false; 462 } 463 if (!std::getline(f, line)) { 464 return true; 465 } 466 if (line != "ports") { 467 return false; 468 } 469 for (auto * names : { &inputs, &outputs }) { 470 size_t count; 471 if (!(f >> count) || count > 100000) { 472 return false; 473 } 474 for (size_t i = 0; i < count; ++i) { 475 std::string name; 476 if (!(f >> std::quoted(name))) { 477 return false; 478 } 479 names->push_back(name); 480 } 481 } 482 f >> std::ws; 483 return f.eof(); 484 }