interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-openvino / ggml-openvino.cpp

2022 lines · 89844 bytes Raw Blame History
1#include "ggml-openvino.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#include "ggml-openvino/openvino/op_table.h"
8#include "ggml-openvino/utils.h"
9#include "ggml-quants.h"
10#include "ggml.h"
11#include "model-cache.h"
12
13#include <algorithm>
14#include <atomic>
15#include <cerrno>
16#include <climits>
17#include <cstdint>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <memory>
22#include <mutex>
23#include <openvino/core/type/element_type.hpp>
24#include <openvino/openvino.hpp>
25#include <openvino/runtime/allocator.hpp>
26#include <openvino/runtime/intel_gpu/ocl/ocl.hpp>
27#include <openvino/runtime/intel_npu/level_zero/level_zero.hpp>
28#include <openvino/runtime/properties.hpp>
29#include <openvino/runtime/tensor.hpp>
30#include <algorithm>
31#include <map>
32#include <set>
33#include <string>
34#include <vector>
35
36#ifdef _WIN32
37# define WIN32_LEAN_AND_MEAN
38# ifndef NOMINMAX
39# define NOMINMAX
40# endif
41# include <windows.h>
42#else
43# include <sys/mman.h>
44# include <unistd.h>
45#endif
46
47// =====================================================
48// OpenVINO Buffer Implementation using ov::Tensor
49// =====================================================
50//
51// Design: This implementation uses a hybrid approach:
52// 1. For weight tensors: Store a pre-built ov::op::v0::Constant in tensor->extra
53// - This avoids the memcpy during graph construction
54// - For quantized weights, the constant is already converted to OpenVINO format
55// 2. For KV cache / compute tensors: Store an ov::Tensor in tensor->extra
56// - This can be directly passed to infer_request
57// - Future: can be changed to ov::RemoteTensor for GPU/NPU
58//
59// This design is similar to:
60// - CUDA split buffer: tensor->extra stores device pointers
61// - CPU repack buffer: tensor->extra stores tensor_traits with repacked data
62// =====================================================
63
64namespace {
65// Buffer context that manages per-tensor allocations (no contiguous buffer for weights)
66struct ggml_backend_openvino_buffer_context {
67 int device;
68 std::string name;
69 size_t id;
70
71 // For non-weight buffers (KV cache, compute), we still use contiguous allocation
72 void * data;
73 size_t size;
74 bool is_remote;
75
76 // File-backed spill or cache-only virtual memory.
77 void * spill_mapping = nullptr;
78 size_t spill_size = 0;
79
80 // Wrapping of the buffer
81 std::shared_ptr<ov::Tensor> ov_buffer;
82
83 // Track all extras for cleanup
84 std::map<ggml_tensor *, ggml_openvino_extra_base *> tensor_extras;
85 std::map<const void *, uint64_t> weight_fingerprints;
86 std::vector<ggml_openvino_source_mapping> source_mappings;
87
88 // Used for re-allocation on device for kvcache
89 void * data_prev;
90
91 ggml_backend_openvino_buffer_context(int device, size_t size, bool is_remote = false) :
92 device(device),
93 name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)),
94 id([]() {
95 static std::atomic<size_t> next_id{1};
96 return next_id.fetch_add(1);
97 }()),
98 data(nullptr),
99 size(size),
100 is_remote(is_remote) {
101 if (size == 0) {
102 return;
103 }
104
105 const auto & device_name = ggml_openvino_get_device_name();
106
107 if (is_remote) {
108 GGML_ASSERT(ggml_openvino_is_gpu());
109 auto remote_context = ggml_openvino_get_remote_context();
110 auto gpu_context = remote_context->as<ov::intel_gpu::ocl::ClContext>();
111 ov::intel_gpu::ocl::USMTensor usm_tensor =
112 gpu_context.create_usm_device_tensor(ov::element::u8, ov::Shape{size});
113 data = usm_tensor.get();
114 ov_buffer = std::make_shared<ov::intel_gpu::ocl::USMTensor>(std::move(usm_tensor));
115 } else {
116#ifdef _WIN32
117 if (ggml_openvino_model_cache_only()) {
118 data = spill_mapping = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
119 if (data == nullptr) {
120 return;
121 }
122 spill_size = size;
123 ov_buffer = std::make_shared<ov::Tensor>(ov::element::u8, ov::Shape{size}, data);
124 } else
125#else
126 if (ggml_openvino_model_cache_only()) {
127 void * m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
128 if (m == MAP_FAILED) {
129 return;
130 }
131 data = spill_mapping = m;
132 spill_size = size;
133 ov_buffer = std::make_shared<ov::Tensor>(ov::element::u8, ov::Shape{size}, data);
134 } else if (const char * spill_dir = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) {
135 // Disk-backed weight buffer: back the repacked weights with a temp file via MAP_SHARED
136 // instead of anonymous memory. Anonymous pages can only be evicted to swap, so the
137 // repacked buffer stays pinned alongside the mmap'd source and both are resident at once
138 // -- that double residency is the load-time peak. File-backed pages are reclaimable: the
139 // kernel can write them back and drop them under pressure, then re-read on demand, so RSS
140 // becomes a working set rather than the whole buffer. The file is unlinked immediately,
141 // so it disappears when the process exits.
142 //
143 // The directory must be real storage. Pointing this at a tmpfs mount (/tmp on many
144 // systems) backs the "spill" with RAM and makes matters worse.
145 char path[PATH_MAX];
146 snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", spill_dir, (int) getpid());
147 int fd = mkstemp(path);
148 if (fd < 0) {
149 GGML_LOG_ERROR("%s: mkstemp(%s) failed: %s\n", __func__, path, strerror(errno));
150 return;
151 }
152 unlink(path); // anonymous-but-file-backed: freed on process exit
153 if (ftruncate(fd, (off_t) size) != 0) {
154 GGML_LOG_ERROR("%s: ftruncate(%zu) failed: %s\n", __func__, size, strerror(errno));
155 close(fd);
156 return;
157 }
158 void * m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
159 close(fd); // the mapping keeps the file alive
160 if (m == MAP_FAILED) {
161 GGML_LOG_ERROR("%s: mmap(%zu) failed: %s\n", __func__, size, strerror(errno));
162 return;
163 }
164 data = m;
165 spill_mapping = m;
166 spill_size = size;
167 GGML_LOG_INFO("%s: weight buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir,
168 size / 1024 / 1024);
169 ov_buffer = std::make_shared<ov::Tensor>(ov::element::u8, ov::Shape{size}, data);
170 } else
171#endif
172 {
173#ifdef _WIN32
174 if (ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) {
175 GGML_LOG_WARN("%s: GGML_OPENVINO_SPILL_DIR is not supported on Windows, ignoring\n", __func__);
176 }
177#endif
178 data = ggml_aligned_malloc(size);
179 GGML_ASSERT(data);
180 memset(data, 0, size);
181 ov_buffer = std::make_shared<ov::Tensor>(ov::element::u8, ov::Shape{size}, data);
182 }
183 }
184
185 if (data == nullptr) {
186 GGML_LOG_ERROR("%s: failed to allocate %zu bytes\n", __func__, size);
187 return;
188 }
189
190 if (reinterpret_cast<uintptr_t>(data) % TENSOR_ALIGNMENT != 0) {
191 GGML_LOG_ERROR("%s: %s buffer is not aligned to %d bytes\n", __func__, device_name.c_str(),
192 TENSOR_ALIGNMENT);
193 GGML_ABORT("fatal error");
194 }
195 }
196
197 ~ggml_backend_openvino_buffer_context() {
198 // Clean up all tensor extras
199 // GGML_LOG_DEBUG("Deleting OpenVINO buffer context #%zu for device %d, size %zu MB\n", id, device,
200 // size / 1024 / 1024);
201 for (auto & pair : tensor_extras) {
202 delete pair.second;
203 }
204 tensor_extras.clear();
205#ifdef _WIN32
206 if (spill_mapping != nullptr) {
207 VirtualFree(spill_mapping, 0, MEM_RELEASE);
208 } else
209#else
210 if (spill_mapping != nullptr) {
211 munmap(spill_mapping, spill_size);
212 } else
213#endif
214 if (!is_remote && data != nullptr) {
215 ggml_aligned_free(data, size);
216 }
217 }
218};
219
220// Buffer type context (per-device)
221struct ggml_backend_openvino_buffer_type_context {
222 int device;
223 std::string name;
224};
225} // namespace
226
227// =====================================================
228// Host weight-buffer release (GGML_OPENVINO_RELEASE_WEIGHTS)
229// =====================================================
230// The OpenVINO weight Constants are zero-copy views into the host buffers
231// allocated here (ggml_aligned_malloc, anonymous memory). On GPU the plugin
232// holds its own device copy after compile_model, so the host pages are dead
233// weight for inference and can be dropped to reclaim RSS (~weights size).
234//
235// We do NOT free the buffer (ggml owns its lifetime and tensors still point
236// into it); instead madvise(MADV_DONTNEED) drops the resident pages while
237// keeping the mapping valid. A later recompile would re-read these Constants
238// from now-zeroed memory and produce garbage, so once released we fail fast
239// if the cache-miss compile branch is reached again (see utils.cpp).
240namespace {
241struct ov_weight_buffer_registry {
242 std::mutex mutex;
243 // (data, size) of every non-remote weight buffer, for madvise.
244 std::vector<std::pair<void *, size_t>> buffers;
245 bool released = false;
246};
247
248ov_weight_buffer_registry & ov_weight_registry() {
249 static ov_weight_buffer_registry reg;
250 return reg;
251}
252} // namespace
253
254void ggml_openvino_register_weight_buffer(void * data, size_t size) {
255 if (data == nullptr || size == 0) {
256 return;
257 }
258 auto & reg = ov_weight_registry();
259 std::lock_guard<std::mutex> lock(reg.mutex);
260 for (const auto & b : reg.buffers) {
261 if (b.first == data) {
262 return; // already registered
263 }
264 }
265 reg.buffers.emplace_back(data, size);
266}
267
268bool ggml_openvino_weight_buffers_released() {
269 auto & reg = ov_weight_registry();
270 std::lock_guard<std::mutex> lock(reg.mutex);
271 return reg.released;
272}
273
274void ggml_openvino_release_weight_buffers() {
275 auto & reg = ov_weight_registry();
276 std::lock_guard<std::mutex> lock(reg.mutex);
277 if (reg.released) {
278 return;
279 }
280 size_t total = 0;
281#if !defined(_WIN32)
282 for (const auto & b : reg.buffers) {
283 // Align down/up to page boundaries so madvise only drops whole pages
284 // fully owned by this buffer.
285 const size_t page = (size_t) sysconf(_SC_PAGESIZE);
286 const uintptr_t ustart = reinterpret_cast<uintptr_t>(b.first);
287 const size_t offset_to_page = (page - (ustart & (page - 1))) & (page - 1);
288 if (b.second > offset_to_page) {
289 const size_t aligned_len = (b.second - offset_to_page) & ~(page - 1);
290 if (aligned_len > 0) {
291 char * astart = static_cast<char *>(b.first) + offset_to_page;
292 if (madvise(astart, aligned_len, MADV_DONTNEED) == 0) {
293 total += aligned_len;
294 }
295 }
296 }
297 }
298#endif
299 reg.released = true;
300 GGML_LOG_INFO("%s: released %zu MB of host weight buffers (%zu buffers)\n", __func__, total / 1024 / 1024,
301 reg.buffers.size());
302}
303
304// Buffer interface functions
305static void ggml_backend_openvino_buffer_free_buffer(ggml_backend_buffer_t buffer) {
306 ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
307 delete ctx;
308}
309
310static void * ggml_backend_openvino_buffer_get_base(ggml_backend_buffer_t buffer) {
311 ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
312 return ctx->data;
313}
314
315static bool is_stateful_enabled() {
316 return ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") != 0;
317}
318
319static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
320 // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
321 ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
322
323 // Put kvcache on device memory for GPU (NPU memory is too small even for kvcache)
324 if (strncmp(tensor->name, "cache_", 6) == 0 && !ctx->is_remote && ggml_openvino_is_gpu() &&
325 !is_stateful_enabled()) {
326 GGML_ASSERT(ctx->tensor_extras.empty());
327 auto device = ctx->device;
328 auto size = ctx->size;
329 auto * data_prev = ctx->data;
330 delete ctx;
331 ctx = new ggml_backend_openvino_buffer_context(device, size, true);
332 buffer->context = ctx;
333 tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev);
334 }
335
336 // Views share the extra from view_src
337 if (tensor->view_src != nullptr) {
338 GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
339 if (tensor->view_src->extra != nullptr) {
340 // The cached ov::Tensor carries the shape it was built with, so sharing view_src's
341 // extra hands out the wrong shape for a reshaping view (e.g. Vcur reshaped from
342 // [n_embd, n_tokens] to [head_size, n_heads_kv, n_tokens]). When such a view is a
343 // graph input, binding it fails the shape check. Give it its own extra instead;
344 // ggml_openvino_create_tensor_extra reads ne and data off the view, so the offset is
345 // handled too. Only safe for a contiguous view - the ov::Tensor assumes dense strides.
346 // Skip empty views: they have no data, and on GPU one can sit at the end of the USM buffer.
347 if (!ggml_are_same_shape(tensor, tensor->view_src) && ggml_is_contiguous(tensor) &&
348 !ggml_is_quantized(tensor->type) && tensor->data != nullptr && ggml_nbytes(tensor) > 0) {
349 if (ggml_openvino_tensor_extra * extra =
350 ggml_openvino_create_tensor_extra(tensor, ctx->is_remote)) {
351 auto it = ctx->tensor_extras.find(tensor);
352 if (it != ctx->tensor_extras.end()) {
353 delete it->second;
354 }
355 ctx->tensor_extras[tensor] = extra;
356 tensor->extra = extra;
357 return GGML_STATUS_SUCCESS;
358 }
359 }
360 tensor->extra = tensor->view_src->extra;
361 }
362 return GGML_STATUS_SUCCESS;
363 }
364
365 ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
366
367 if (tensor->data != nullptr && !ggml_is_quantized(tensor->type)) {
368 ggml_openvino_tensor_extra * extra = ggml_openvino_create_tensor_extra(tensor, ctx->is_remote);
369 if (extra != nullptr) {
370 auto it = ctx->tensor_extras.find(tensor);
371 if (it != ctx->tensor_extras.end()) {
372 delete it->second;
373 }
374 ctx->tensor_extras[tensor] = extra;
375 tensor->extra = extra;
376 }
377 }
378
379 return GGML_STATUS_SUCCESS;
380}
381
382static void ggml_backend_openvino_buffer_memset_tensor(ggml_backend_buffer_t buffer,
383 ggml_tensor * tensor,
384 uint8_t value,
385 size_t offset,
386 size_t size) {
387 // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
388 GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
389 ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
390
391 if (ctx->is_remote) {
392 // For remote (device) buffers, use OpenCL USM memfill
393 cl_command_queue queue = ggml_openvino_get_cl_queue();
394 auto mem_fill_fn = ggml_openvino_get_clEnqueueMemFillINTEL();
395 if (mem_fill_fn != nullptr) {
396 uint8_t pattern = value;
397 cl_int err = mem_fill_fn(queue, (char *) tensor->data + offset, &pattern, sizeof(pattern), size, 0, nullptr,
398 nullptr);
399 if (err != CL_SUCCESS) {
400 GGML_LOG_ERROR("%s: clEnqueueMemFillINTEL failed with error %d\n", __func__, err);
401 }
402 clFinish(queue);
403 } else {
404 GGML_LOG_ERROR("%s: clEnqueueMemFillINTEL not available for GPU buffer\n", __func__);
405 }
406 } else {
407 memset((char *) tensor->data + offset, value, size);
408 }
409}
410
411static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer,
412 ggml_tensor * tensor,
413 const void * data,
414 size_t offset,
415 size_t size) {
416 // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
417 GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
418 ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
419
420 // Check if this is a weight buffer (usage is set BEFORE set_tensor is called, except in test-backend-ops)
421 bool is_weight_buffer = (buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
422 // Full tensor set: offset=0, full size, not a view
423 bool is_full_tensor_set = (offset == 0 && size == ggml_nbytes(tensor) && tensor->view_src == nullptr);
424 if (is_weight_buffer && ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR")) {
425 if (is_full_tensor_set) {
426 ctx->weight_fingerprints[tensor->data] = ggml_openvino_source_fingerprint(data, size, ctx->source_mappings);
427 }
428 if (ggml_openvino_model_cache_only()) {
429 if (!is_full_tensor_set) {
430 GGML_ABORT("ggml-openvino: cache-only mode requires whole mmap weight uploads");
431 }
432 return;
433 }
434 }
435 // 2D tensor (typical weight shape), or a 3D quantized MoE expert weight (MUL_MAT_ID). Dense 3D
436 // expert weights are handled later in create_weight_node instead.
437 bool is_2d = (tensor->ne[2] == 1 && tensor->ne[3] == 1);
438 bool is_supported_weight_shape = is_2d || (tensor->ne[3] == 1 && ggml_is_quantized(tensor->type));
439
440 if (is_weight_buffer && is_full_tensor_set && is_supported_weight_shape) {
441 try {
442 auto result = process_weight_tensor(tensor, data, tensor->data);
443 result.weight_node->set_friendly_name(tensor->name);
444
445 // const auto & layout = result.layout;
446 ggml_openvino_extra_base * extra;
447
448 // Quantized path with extracted weight/scale/zp tensors
449 if (result.is_quantized()) {
450 extra = new ggml_openvino_quantized_weight_extra(std::move(result.weights), std::move(result.scales),
451 std::move(result.zp), result.weight_node);
452
453 // if (layout.is_requant) {
454 // GGML_LOG_DEBUG("%s: requantized %s to %s (u%d, block_size=%ld)\n", __func__, tensor->name,
455 // extra_quant_type_name(layout.requant_type.value()), layout.is_u4 ? 4 : 8,
456 // layout.weights_per_block);
457 // } else {
458 // int64_t n_blocks = ggml_nelements(tensor) / layout.weights_per_block;
459 // GGML_LOG_DEBUG("%s: extracted quantized weight node for %s (u%d, %zu weights, %ld blocks)\n",
460 // __func__, tensor->name, layout.is_u4 ? 4 : 8, layout.weights_size, n_blocks);
461 // }
462 } else {
463 // F16/F32/BF16 weight or F16-requant
464 extra = new ggml_openvino_weight_extra(std::move(result.weights), result.weight_node);
465
466 // if (layout.total_size > 0) {
467 // GGML_LOG_DEBUG("%s: requantized %s to F16\n", __func__, tensor->name);
468 // } else {
469 // GGML_LOG_DEBUG("%s: created shared-memory weight node for %s\n", __func__, tensor->name);
470 // }
471 }
472
473 ctx->tensor_extras[tensor] = extra;
474 tensor->extra = extra;
475
476 // Register the host buffer so its pages can be dropped after the GPU
477 // plugin has its own device copy (GGML_OPENVINO_RELEASE_WEIGHTS).
478 if (!ctx->is_remote) {
479 // Weights are set once at model load. Setting a weight after a release
480 // means a second model is loading while the first's compiled graph is
481 // pinned — that graph would be wrongly reused with this model's key.
482 // Fail loud rather than return silently-wrong results.
483 if (ggml_openvino_weight_buffers_released()) {
484 GGML_ABORT(
485 "ggml-openvino: loading a new model while GGML_OPENVINO_RELEASE_WEIGHTS pinned a previous "
486 "model's compiled graph. This mode supports a single model per process; unset it for "
487 "multi-model runs.");
488 }
489 ggml_openvino_register_weight_buffer(ctx->data, ctx->size);
490 }
491
492 } catch (const std::exception & e) {
493 GGML_LOG_ERROR("%s: failed to process weight tensor for %s: %s\n", __func__, tensor->name, e.what());
494 memcpy((char *) tensor->data + offset, data, size);
495 }
496 } else {
497 // Non-weight tensor (KV cache, activations, etc.) - copy data. test-backend-ops also goes here
498 if (ctx->is_remote) {
499 cl_command_queue queue = ggml_openvino_get_cl_queue();
500 auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL();
501 if (mem_cpy_fn != nullptr) {
502 cl_int err =
503 mem_cpy_fn(queue, CL_TRUE, (char *) tensor->data + offset, data, size, 0, nullptr, nullptr);
504 if (err != CL_SUCCESS) {
505 GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL failed with error %d\n", __func__, err);
506 }
507 } else {
508 GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL not available for GPU buffer\n", __func__);
509 }
510 } else {
511 memcpy((char *) tensor->data + offset, data, size);
512 }
513
514 ggml_openvino_tensor_extra * extra = ggml_openvino_create_tensor_extra(tensor, ctx->is_remote);
515 if (extra == nullptr) {
516 // GGML_LOG_ERROR("%s: failed to create tensor extra for %s\n", __func__, tensor->name);
517 return;
518 }
519
520 auto it = ctx->tensor_extras.find(tensor);
521 if (it != ctx->tensor_extras.end()) {
522 delete it->second;
523 }
524 ctx->tensor_extras[tensor] = extra;
525 tensor->extra = extra;
526 }
527}
528
529static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer,
530 const ggml_tensor * tensor,
531 void * data,
532 size_t offset,
533 size_t size) {
534 // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
535 GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
536 ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
537
538 if (ggml_openvino_model_cache_only() && buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
539 GGML_ABORT("ggml-openvino: cannot read unloaded weights in cache-only mode");
540 }
541
542 if (ctx->is_remote) {
543 // For remote (device) buffers, use OpenCL USM memcpy (device-to-host)
544 cl_command_queue queue = ggml_openvino_get_cl_queue();
545 auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL();
546 if (mem_cpy_fn != nullptr) {
547 cl_int err =
548 mem_cpy_fn(queue, CL_TRUE, data, (const char *) tensor->data + offset, size, 0, nullptr, nullptr);
549 if (err != CL_SUCCESS) {
550 GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL failed with error %d\n", __func__, err);
551 }
552 } else {
553 GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL not available for GPU buffer\n", __func__);
554 }
555 } else {
556 memcpy(data, (const char *) tensor->data + offset, size);
557 }
558}
559
560static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer,
561 const ggml_tensor * src,
562 ggml_tensor * dst) {
563 // GGML_LOG_DEBUG("%s: src tensor name=%s, dst tensor name=%s\n", __func__, src->name, dst->name);
564 GGML_ASSERT(src != nullptr && dst != nullptr);
565 ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
566
567 if (ctx->is_remote) {
568 // For remote (device) buffers, use OpenCL USM memcpy
569 cl_command_queue queue = ggml_openvino_get_cl_queue();
570 auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL();
571 if (mem_cpy_fn == nullptr) {
572 GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL not available for GPU buffer\n", __func__);
573 return false;
574 }
575 // Can copy from host to device
576 if (ggml_backend_buffer_is_host(src->buffer)) {
577 cl_int err = mem_cpy_fn(queue, CL_TRUE, dst->data, src->data, ggml_nbytes(src), 0, nullptr, nullptr);
578 if (err != CL_SUCCESS) {
579 GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL (host-to-device) failed with error %d\n", __func__, err);
580 return false;
581 }
582 return true;
583 }
584 // Can also copy from device to device if both are OpenVINO remote buffers
585 if (ggml_backend_buffer_is_openvino(src->buffer)) {
586 ggml_backend_openvino_buffer_context * src_ctx =
587 (ggml_backend_openvino_buffer_context *) src->buffer->context;
588 if (src_ctx->is_remote) {
589 cl_int err = mem_cpy_fn(queue, CL_TRUE, dst->data, src->data, ggml_nbytes(src), 0, nullptr, nullptr);
590 if (err != CL_SUCCESS) {
591 GGML_LOG_ERROR("%s: clEnqueueMemcpyINTEL (device-to-device) failed with error %d\n", __func__, err);
592 return false;
593 }
594 return true;
595 }
596 }
597 return false;
598 }
599
600 // Host buffer - can copy from any host buffer
601 if (ggml_backend_buffer_is_host(src->buffer)) {
602 memcpy(dst->data, src->data, ggml_nbytes(src));
603 return true;
604 }
605 return false;
606}
607
608static void ggml_backend_openvino_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
609 ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
610 GGML_ASSERT(ctx->data != nullptr);
611 if (ctx->is_remote) {
612 cl_command_queue queue = ggml_openvino_get_cl_queue();
613 auto mem_fill_fn = ggml_openvino_get_clEnqueueMemFillINTEL();
614 if (mem_fill_fn != nullptr) {
615 uint8_t pattern = value;
616 cl_int err = mem_fill_fn(queue, ctx->data, &pattern, sizeof(pattern), ctx->size, 0, nullptr, nullptr);
617 if (err != CL_SUCCESS) {
618 GGML_LOG_WARN("%s: clEnqueueMemFillINTEL failed with error %d\n", __func__, err);
619 }
620 clFinish(queue);
621 } else {
622 GGML_LOG_WARN("%s: clEnqueueMemFillINTEL not available for GPU buffer clear\n", __func__);
623 }
624 } else {
625 memset(ctx->data, value, ctx->size);
626 }
627}
628
629static const ggml_backend_buffer_i ggml_backend_openvino_buffer_interface = {
630 /* .free_buffer = */ ggml_backend_openvino_buffer_free_buffer,
631 /* .get_base = */ ggml_backend_openvino_buffer_get_base,
632 /* .init_tensor = */ ggml_backend_openvino_buffer_init_tensor,
633 /* .memset_tensor = */ ggml_backend_openvino_buffer_memset_tensor,
634 /* .set_tensor = */ ggml_backend_openvino_buffer_set_tensor,
635 /* .get_tensor = */ ggml_backend_openvino_buffer_get_tensor,
636 /* .set_tensor_2d = */ NULL,
637 /* .get_tensor_2d = */ NULL,
638 /* .cpy_tensor = */ ggml_backend_openvino_buffer_cpy_tensor,
639 /* .clear = */ ggml_backend_openvino_buffer_clear,
640 /* .reset = */ NULL,
641 /* .set_tensor_n = */ NULL,
642 /* .get_tensor_n = */ NULL,
643 /* .cpy_tensor_n = */ NULL,
644};
645
646// Buffer type interface functions
647static const char * ggml_backend_openvino_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
648 ggml_backend_openvino_buffer_type_context * ctx = (ggml_backend_openvino_buffer_type_context *) buft->context;
649 return ctx->name.c_str();
650}
651
652static ggml_backend_buffer_t ggml_backend_openvino_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft,
653 size_t size) {
654 ggml_backend_openvino_buffer_type_context * buft_ctx = (ggml_backend_openvino_buffer_type_context *) buft->context;
655
656 // Create buffer context with contiguous memory allocation
657 ggml_backend_openvino_buffer_context * ctx = new ggml_backend_openvino_buffer_context(buft_ctx->device, size);
658
659 if (ctx->data == nullptr && size > 0) {
660 GGML_LOG_ERROR("%s: failed to allocate buffer of size %zu\n", __func__, size);
661 delete ctx;
662 return nullptr;
663 }
664
665 return ggml_backend_buffer_init(buft, ggml_backend_openvino_buffer_interface, ctx, size);
666}
667
668static size_t ggml_backend_openvino_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
669 GGML_UNUSED(buft);
670 return TENSOR_ALIGNMENT;
671}
672
673static size_t ggml_backend_openvino_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
674 GGML_UNUSED(buft);
675 // A GPU caps a single memory object, so let ggml split a large buffer into parts that fit
676 return ggml_openvino_max_alloc_size();
677}
678
679static size_t ggml_backend_openvino_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft,
680 const ggml_tensor * tensor) {
681 GGML_UNUSED(buft);
682
683 // For quantized weight tensors, we need extra space for extracted data.
684 if (!ggml_openvino_model_cache_only() && ggml_is_quantized(tensor->type) && tensor->ne[3] == 1) {
685 ggml_openvino_extracted_layout layout = ggml_openvino_get_extracted_layout(tensor);
686 if (layout.total_size > 0) {
687 // GGML_LOG_DEBUG("%s: tensor %s needs %zu bytes (original %zu, extracted: weights=%zu scales=%zu zp=%zu)\n",
688 // __func__, tensor->name, layout.total_size, ggml_nbytes(tensor), layout.weights_size,
689 // layout.scales_size, layout.zp_size);
690 return layout.total_size;
691 }
692 }
693
694 return ggml_nbytes(tensor);
695}
696
697static const ggml_backend_buffer_type_i ggml_backend_openvino_buffer_type_interface = {
698 /* .get_name = */ ggml_backend_openvino_buffer_type_get_name,
699 /* .alloc_buffer = */ ggml_backend_openvino_buffer_type_alloc_buffer,
700 /* .alloc_buffer_n = */ NULL,
701 /* .get_alignment = */ ggml_backend_openvino_buffer_type_get_alignment,
702 /* .get_max_size = */ ggml_backend_openvino_buffer_type_get_max_size,
703 /* .get_alloc_size = */ ggml_backend_openvino_buffer_type_get_alloc_size,
704 /* .get_alloc_size_n = */ NULL,
705 /* .is_host = */ nullptr,
706};
707
708// Get buffer type for a specific device
709GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_openvino_buffer_type(int device) {
710 GGML_ASSERT(device >= 0 && device < ggml_backend_openvino_get_device_count());
711
712 static std::mutex mutex;
713 std::lock_guard<std::mutex> lock(mutex);
714
715 static std::vector<ggml_backend_buffer_type> buffer_types;
716 static std::vector<ggml_backend_openvino_buffer_type_context> buffer_type_contexts;
717
718 if (buffer_types.empty()) {
719 int device_count = ggml_backend_openvino_get_device_count();
720 buffer_types.resize(device_count);
721 buffer_type_contexts.resize(device_count);
722
723 for (int i = 0; i < device_count; i++) {
724 buffer_type_contexts[i].device = i;
725 buffer_type_contexts[i].name = std::string(GGML_OPENVINO_NAME) + std::to_string(i);
726
727 buffer_types[i] = ggml_backend_buffer_type{
728 /* .iface = */ ggml_backend_openvino_buffer_type_interface,
729 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_openvino_reg(), i),
730 /* .context = */ &buffer_type_contexts[i],
731 };
732 }
733 }
734
735 return &buffer_types[device];
736}
737
738// =====================================================
739// OpenVINO Host Buffer Implementation
740// =====================================================
741
742static const char * ggml_backend_openvino_host_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
743 ggml_backend_openvino_buffer_type_context * ctx = (ggml_backend_openvino_buffer_type_context *) buft->context;
744 return ctx->name.c_str();
745}
746
747static bool ggml_backend_openvino_host_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
748 GGML_UNUSED(buft);
749 return true;
750}
751
752static const ggml_backend_buffer_type_i ggml_backend_openvino_host_buffer_type_interface = {
753 /* .get_name = */ ggml_backend_openvino_host_buffer_type_get_name,
754 /* .alloc_buffer = */ ggml_backend_openvino_buffer_type_alloc_buffer,
755 /* .alloc_buffer_n = */ NULL,
756 /* .get_alignment = */ ggml_backend_openvino_buffer_type_get_alignment,
757 /* .get_max_size = */ ggml_backend_openvino_buffer_type_get_max_size,
758 /* .get_alloc_size = */ ggml_backend_openvino_buffer_type_get_alloc_size,
759 /* .get_alloc_size_n = */ NULL,
760 /* .is_host = */ ggml_backend_openvino_host_buffer_type_is_host,
761};
762
763GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_openvino_host_buffer_type(int device) {
764 GGML_ASSERT(device >= 0 && device < ggml_backend_openvino_get_device_count());
765
766 static std::mutex mutex;
767 std::lock_guard<std::mutex> lock(mutex);
768
769 static std::vector<ggml_backend_buffer_type> buffer_types;
770 static std::vector<ggml_backend_openvino_buffer_type_context> buffer_type_contexts;
771
772 if (buffer_types.empty()) {
773 int device_count = ggml_backend_openvino_get_device_count();
774 buffer_types.resize(device_count);
775 buffer_type_contexts.resize(device_count);
776
777 for (int i = 0; i < device_count; i++) {
778 buffer_type_contexts[i].device = i;
779 buffer_type_contexts[i].name = std::string(GGML_OPENVINO_NAME) + std::to_string(i) + "_HOST";
780
781 buffer_types[i] = ggml_backend_buffer_type{
782 /* .iface = */ ggml_backend_openvino_host_buffer_type_interface,
783 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_openvino_reg(), i),
784 /* .context = */ &buffer_type_contexts[i],
785 };
786 }
787 }
788
789 return &buffer_types[device];
790}
791
792bool ggml_backend_buffer_is_openvino(ggml_backend_buffer_t buffer) {
793 return buffer->iface.free_buffer == ggml_backend_openvino_buffer_free_buffer;
794}
795
796size_t ggml_backend_openvino_buffer_get_ctx_id(ggml_backend_buffer_t buffer) {
797 if (!ggml_backend_buffer_is_openvino(buffer)) {
798 return 0;
799 }
800 ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
801 return ctx->id;
802}
803
804bool ggml_openvino_buffer_is_remote(const ggml_tensor * tensor) {
805 if (tensor == nullptr || tensor->buffer == nullptr) {
806 return false;
807 }
808 if (!ggml_backend_buffer_is_openvino(tensor->buffer)) {
809 return false;
810 }
811 auto * ctx = static_cast<ggml_backend_openvino_buffer_context *>(tensor->buffer->context);
812 return ctx->is_remote;
813}
814
815void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_extra_base * extra) {
816 GGML_ASSERT(tensor != nullptr);
817 GGML_ASSERT(tensor->buffer != nullptr);
818 GGML_ASSERT(ggml_backend_buffer_is_openvino(tensor->buffer));
819
820 auto * ctx = static_cast<ggml_backend_openvino_buffer_context *>(tensor->buffer->context);
821
822 auto it = ctx->tensor_extras.find(tensor);
823 if (it != ctx->tensor_extras.end()) {
824 delete it->second;
825 }
826
827 ctx->tensor_extras[tensor] = extra;
828 tensor->extra = extra;
829}
830
831bool ggml_backend_buft_is_openvino(ggml_backend_buffer_type_t buft) {
832 return buft->iface.get_name == ggml_backend_openvino_buffer_type_get_name;
833}
834
835bool ggml_backend_buft_is_openvino_host(ggml_backend_buffer_type_t buft) {
836 return buft->iface.get_name == ggml_backend_openvino_host_buffer_type_get_name;
837}
838
839uint64_t ggml_backend_openvino_weight_fingerprint(const ggml_tensor * tensor) {
840 if (ggml_backend_buffer_is_openvino(tensor->buffer)) {
841 auto * ctx = static_cast<ggml_backend_openvino_buffer_context *>(tensor->buffer->context);
842 auto it = ctx->weight_fingerprints.find(tensor->data);
843 if (it != ctx->weight_fingerprints.end()) {
844 return it->second;
845 }
846 GGML_ABORT("ggml-openvino: missing source identity for weight %s", tensor->name);
847 }
848 std::vector<ggml_openvino_source_mapping> mappings;
849 return ggml_openvino_source_fingerprint(tensor->data, ggml_nbytes(tensor), mappings);
850}
851
852static void ggml_backend_openvino_free(ggml_backend_t backend) {
853 ggml_backend_openvino_context * ctx = (ggml_backend_openvino_context *) backend->context;
854
855 if (ctx->runtime_context) {
856 auto r_ctx = std::static_pointer_cast<ov_runtime_context>(ctx->runtime_context);
857 auto cache = r_ctx->compiled_cache;
858 r_ctx->clear_caches();
859 std::lock_guard<std::mutex> cache_lock(cache->mutex);
860 if (--cache->backend_count == 0) {
861 // If host weight buffers were released (GGML_OPENVINO_RELEASE_WEIGHTS), the
862 // dropped pages can never be repopulated, so a recompile is impossible. Keep
863 // the compiled-model cache alive across backend teardown so the next context
864 // reuses it instead of recompiling against zeroed weights.
865 if (!ggml_openvino_weight_buffers_released()) {
866 cache->graphs.clear();
867 }
868 }
869 }
870
871 delete ctx;
872 delete backend;
873}
874
875static const char * ggml_backend_openvino_get_name(ggml_backend_t backend) {
876 return GGML_OPENVINO_NAME;
877 GGML_UNUSED(backend);
878}
879
880static enum ggml_status ggml_backend_openvino_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
881 return ov_graph_compute(cgraph, backend);
882 GGML_UNUSED(backend);
883}
884
885static const ggml_backend_i ggml_backend_openvino_interface = {
886 /* .get_name = */ ggml_backend_openvino_get_name,
887 /* .free = */ ggml_backend_openvino_free,
888 /* .set_tensor_async = */ NULL,
889 /* .get_tensor_async = */ NULL,
890 /* .set_tensor_2d_async = */ NULL,
891 /* .get_tensor_2d_async = */ NULL,
892 /* .cpy_tensor_async = */ NULL,
893 /* .synchronize = */ NULL,
894 /* .graph_plan_create = */ NULL,
895 /* .graph_plan_free = */ NULL,
896 /* .graph_plan_update = */ NULL,
897 /* .graph_plan_compute = */ NULL,
898 /* .graph_compute = */ ggml_backend_openvino_graph_compute,
899 /* .event_record = */ NULL,
900 /* .event_wait = */ NULL,
901 /* .graph_optimize = */ NULL,
902};
903
904int ggml_backend_openvino_get_device_count() {
905 return (int) ggml_openvino_get_available_devices().size();
906}
907
908static ggml_guid_t ggml_backend_openvino_guid(void) {
909 static ggml_guid guid = {0x12, 0xa8, 0xae, 0xf4, 0xc0, 0x1e, 0x61, 0x97,
910 0x8f, 0xeb, 0x33, 0x04, 0xa1, 0x33, 0x51, 0x2d};
911 return &guid;
912}
913
914static std::shared_ptr<ov_runtime_context> get_ov_runtime_context_ptr() {
915 // Share compiled models, but give every backend its own requests and KV state.
916 static auto cache = std::make_shared<ov_compiled_model_cache>();
917 auto r_ctx = std::make_shared<ov_runtime_context>();
918 r_ctx->device = ggml_openvino_get_device_name();
919 r_ctx->stateful = is_stateful_enabled() && !ggml_openvino_is_npu();
920 r_ctx->compiled_cache = cache;
921 std::lock_guard<std::mutex> cache_lock(cache->mutex);
922 ++cache->backend_count;
923 return r_ctx;
924}
925
926// backend API
927GGML_BACKEND_API ggml_backend_t ggml_backend_openvino_init(int device) {
928 if (device < 0 || device >= ggml_backend_openvino_get_device_count()) {
929 GGML_LOG_ERROR("%s: invalid device %d\n", __func__, device);
930 return nullptr;
931 }
932
933 ggml_backend_openvino_context * ctx = new ggml_backend_openvino_context;
934 if (ctx == nullptr) {
935 GGML_LOG_ERROR("%s: failed to allocate context\n", __func__);
936 return nullptr;
937 }
938
939 ctx->runtime_context = get_ov_runtime_context_ptr();
940 if (ctx->runtime_context == nullptr) {
941 GGML_LOG_ERROR("%s: failed to allocate runtime context\n", __func__);
942 delete ctx;
943 return nullptr;
944 }
945
946 ggml_backend_t openvino_backend = new ggml_backend{
947 /* .guid = */ ggml_backend_openvino_guid(),
948 /* .interface = */ ggml_backend_openvino_interface,
949 /* .device = */ ggml_backend_reg_dev_get(ggml_backend_openvino_reg(), device),
950 /* .context = */ ctx,
951 };
952
953 return openvino_backend;
954}
955
956GGML_BACKEND_API bool ggml_backend_is_openvino(ggml_backend_t backend) {
957 return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_openvino_guid());
958}
959
960namespace {
961struct ggml_backend_openvino_device_context {
962 int device;
963 std::string name;
964 std::string ov_name; // OpenVINO device id: CPU, GPU, GPU.1, NPU, ...
965 std::string description;
966 size_t total_memory;
967};
968}
969
970static bool ov_device_has_prefix(const std::string & s, const std::string & prefix) {
971 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
972}
973
974static bool ov_try_get_size_t_property(const std::string & device, const std::string & property, size_t & out) {
975 try {
976 const ov::Any value = ov_singleton_core().get_property(device, property);
977 if (value.is<size_t>()) {
978 out = value.as<size_t>();
979 return true;
980 }
981 if (value.is<uint64_t>()) {
982 out = (size_t) value.as<uint64_t>();
983 return true;
984 }
985 if (value.is<unsigned long long>()) {
986 out = (size_t) value.as<unsigned long long>();
987 return true;
988 }
989 if (value.is<int64_t>()) {
990 const int64_t v = value.as<int64_t>();
991 if (v >= 0) {
992 out = (size_t) v;
993 return true;
994 }
995 }
996 } catch (...) {
997 }
998 return false;
999}
1000
1001// System memory available to new allocations (MemAvailable on Linux), SIZE_MAX if unknown
1002static size_t ov_system_available_memory() {
1003#ifdef _WIN32
1004 MEMORYSTATUSEX status;
1005 status.dwLength = sizeof(status);
1006 if (GlobalMemoryStatusEx(&status)) {
1007 return (size_t) status.ullAvailPhys;
1008 }
1009#else
1010 if (FILE * f = fopen("/proc/meminfo", "r")) {
1011 char line[256];
1012 unsigned long long kb = 0;
1013 bool found = false;
1014 while (!found && fgets(line, sizeof(line), f)) {
1015 found = sscanf(line, "MemAvailable: %llu kB", &kb) == 1;
1016 }
1017 fclose(f);
1018 if (found) {
1019 return (size_t) std::min<unsigned long long>(kb * 1024, SIZE_MAX);
1020 }
1021 }
1022#endif
1023 return SIZE_MAX;
1024}
1025
1026// iGPU and NPU allocate from system RAM, so their free memory can't exceed what the OS has available
1027static bool ov_device_shares_system_memory(const std::string & device) {
1028 if (ov_device_has_prefix(device, "NPU")) {
1029 return true;
1030 }
1031 if (!ov_device_has_prefix(device, "GPU")) {
1032 return false;
1033 }
1034 try {
1035 return ov_singleton_core().get_property(device, ov::device::type) == ov::device::Type::INTEGRATED;
1036 } catch (...) {
1037 return false;
1038 }
1039}
1040
1041// usm_host / usm_shared allocations live in system RAM on a discrete GPU
1042static bool ov_gpu_stat_is_host_memory(const std::string & key) {
1043 return key == "usm_host" || key == "usm_shared";
1044}
1045
1046static bool ov_try_get_gpu_used_memory(const std::string & device, size_t & out) {
1047 out = 0;
1048 try {
1049 const ov::Any stats_any = ov_singleton_core().get_property(device, "GPU_MEMORY_STATISTICS");
1050 if (stats_any.is<std::map<std::string, uint64_t>>()) {
1051 const auto stats = stats_any.as<std::map<std::string, uint64_t>>();
1052 for (const auto & kv : stats) {
1053 if (!ov_gpu_stat_is_host_memory(kv.first)) {
1054 out += (size_t) kv.second;
1055 }
1056 }
1057 return true;
1058 }
1059 if (stats_any.is<ov::AnyMap>()) {
1060 const auto stats = stats_any.as<ov::AnyMap>();
1061 for (const auto & kv : stats) {
1062 if (ov_gpu_stat_is_host_memory(kv.first)) {
1063 continue;
1064 }
1065 if (kv.second.is<size_t>()) {
1066 out += kv.second.as<size_t>();
1067 } else if (kv.second.is<uint64_t>()) {
1068 out += (size_t) kv.second.as<uint64_t>();
1069 } else if (kv.second.is<unsigned long long>()) {
1070 out += (size_t) kv.second.as<unsigned long long>();
1071 }
1072 }
1073 return true;
1074 }
1075 } catch (...) {
1076 }
1077 return false;
1078}
1079
1080static const char * ggml_backend_openvino_device_get_name(ggml_backend_dev_t dev) {
1081 ggml_backend_openvino_device_context * ctx = (ggml_backend_openvino_device_context *) dev->context;
1082 return ctx->name.c_str();
1083}
1084
1085static const char * ggml_backend_openvino_device_get_description(ggml_backend_dev_t dev) {
1086 ggml_backend_openvino_device_context * ctx = (ggml_backend_openvino_device_context *) dev->context;
1087 return ctx->description.c_str();
1088}
1089
1090static void ggml_backend_openvino_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) {
1091 ggml_backend_openvino_device_context * ctx = (ggml_backend_openvino_device_context *) dev->context;
1092
1093 // total_memory is only set for GPU/NPU; used = this process's OpenVINO allocations on the device
1094 size_t used = 0;
1095 const bool known = ctx->total_memory > 0 &&
1096 (ov_device_has_prefix(ctx->ov_name, "GPU") ?
1097 ov_try_get_gpu_used_memory(ctx->ov_name, used) :
1098 ov_try_get_size_t_property(ctx->ov_name, "NPU_DEVICE_ALLOC_MEM_SIZE", used));
1099 if (known) {
1100 *total = ctx->total_memory;
1101 *free = (used >= *total) ? 0 : (*total - used);
1102 } else {
1103 // CPU, or a plugin without memory properties: report system memory
1104#ifdef _WIN32
1105 MEMORYSTATUSEX status;
1106 status.dwLength = sizeof(status);
1107 GlobalMemoryStatusEx(&status);
1108 *total = status.ullTotalPhys;
1109 *free = status.ullAvailPhys;
1110#else
1111 long pages = sysconf(_SC_PHYS_PAGES);
1112 long page_size = sysconf(_SC_PAGE_SIZE);
1113 *total = pages * page_size;
1114
1115 // "free" system memory is ill-defined, for practical purposes assume that all of it is free:
1116 *free = *total;
1117#endif // _WIN32
1118 }
1119
1120 if (ov_device_shares_system_memory(ctx->ov_name)) {
1121 *free = std::min(*free, ov_system_available_memory());
1122 }
1123}
1124
1125static enum ggml_backend_dev_type ggml_backend_openvino_device_get_type(ggml_backend_dev_t dev) {
1126 ggml_backend_openvino_device_context * ctx = (ggml_backend_openvino_device_context *) dev->context;
1127 // Only the device selected by GGML_OPENVINO_DEVICE is offered for offload. The others are
1128 // registered for discovery (--list-devices) only; llama.cpp skips IGPU devices when a GPU exists.
1129 return ctx->ov_name == ggml_openvino_get_device_name() ? GGML_BACKEND_DEVICE_TYPE_GPU : GGML_BACKEND_DEVICE_TYPE_IGPU;
1130}
1131
1132static void ggml_backend_openvino_device_get_props(ggml_backend_dev_t dev, ggml_backend_dev_props * props) {
1133 props->name = ggml_backend_openvino_device_get_name(dev);
1134 props->description = ggml_backend_openvino_device_get_description(dev);
1135 props->type = ggml_backend_openvino_device_get_type(dev);
1136 ggml_backend_openvino_device_get_memory(dev, &props->memory_free, &props->memory_total);
1137
1138 props->caps = {
1139 /* .async = */ false,
1140 /* .host_buffer = */ false,
1141 /* .buffer_from_host_ptr = */ false,
1142 /* .events = */ false,
1143 /* .mmap_support = */ true,
1144 };
1145}
1146
1147static ggml_backend_t ggml_backend_openvino_device_init(ggml_backend_dev_t dev, const char * params) {
1148 GGML_UNUSED(params);
1149 ggml_backend_openvino_device_context * ctx = (ggml_backend_openvino_device_context *) dev->context;
1150 if (ctx->ov_name != ggml_openvino_get_device_name()) {
1151 // Not an error: test-backend-ops initializes every device
1152 GGML_LOG_WARN("%s: %s (OpenVINO %s) is not the selected device, no ops will run on it; "
1153 "set GGML_OPENVINO_DEVICE=%s to use it\n",
1154 __func__, ctx->name.c_str(), ctx->ov_name.c_str(), ctx->ov_name.c_str());
1155 }
1156 return ggml_backend_openvino_init(ctx->device);
1157}
1158
1159static ggml_backend_buffer_type_t ggml_backend_openvino_device_get_buffer_type(ggml_backend_dev_t dev) {
1160 ggml_backend_openvino_device_context * ctx = (ggml_backend_openvino_device_context *) dev->context;
1161 return ggml_backend_openvino_buffer_type(ctx->device);
1162}
1163
1164static ggml_backend_buffer_type_t ggml_backend_openvino_device_get_host_buffer_type(ggml_backend_dev_t dev) {
1165 ggml_backend_openvino_device_context * ctx = (ggml_backend_openvino_device_context *) dev->context;
1166 return ggml_backend_openvino_host_buffer_type(ctx->device);
1167}
1168
1169static bool has_view_op_input(const ggml_tensor * op) {
1170 for (int i = 0; i < GGML_MAX_SRC; i++) {
1171 if (op->src[i] == nullptr) {
1172 break;
1173 }
1174 if (op->src[i]->op == GGML_OP_VIEW) {
1175 return true;
1176 }
1177 }
1178 return false;
1179}
1180
1181// OV slices whole elements per axis, so each stride must be a multiple of the next smaller one
1182// (e.g. a batch stride of m*nb[1] + pad bytes cannot be expressed and would be read wrongly).
1183static bool has_strides_on_element_grid(const ggml_tensor * t) {
1184 std::vector<size_t> strides;
1185 for (int i = 0; i < GGML_MAX_DIMS; i++) {
1186 if (t->ne[i] > 1) {
1187 strides.push_back(t->nb[i]);
1188 }
1189 }
1190 std::sort(strides.begin(), strides.end());
1191 for (size_t i = 1; i < strides.size(); i++) {
1192 if (strides[i - 1] == 0 || strides[i] % strides[i - 1] != 0) {
1193 return false;
1194 }
1195 }
1196 return true;
1197}
1198
1199static bool has_non_contiguous_view_input(const ggml_tensor * op) {
1200 for (int i = 0; i < GGML_MAX_SRC; i++) {
1201 if (op->src[i] == nullptr) {
1202 break;
1203 }
1204 if (op->src[i]->op == GGML_OP_VIEW && !ggml_is_contiguous(op->src[i])) {
1205 return true;
1206 }
1207 }
1208 return false;
1209}
1210
1211static bool is_supported_flash_attn_pattern(const ggml_tensor * op) {
1212 // Each Q/K/V input must follow one of:
1213 // PERMUTE -> VIEW -> base (view_src==nullptr) (llama KV-cache path)
1214 // PERMUTE -> RESHAPE -> base (view_src==nullptr) (whisper Q)
1215 // VIEW -> base (view_src==nullptr) (whisper K/V from kv_pad)
1216 for (int i = 0; i < 3; i++) {
1217 const ggml_tensor * src = op->src[i];
1218 if (src->op == GGML_OP_PERMUTE) {
1219 if (src->src[0] == nullptr) {
1220 return false;
1221 }
1222 if (src->src[0]->op != GGML_OP_VIEW && src->src[0]->op != GGML_OP_RESHAPE) {
1223 return false;
1224 }
1225 if (src->src[0]->src[0] == nullptr || src->src[0]->src[0]->view_src != nullptr) {
1226 return false;
1227 }
1228 } else if (src->op == GGML_OP_VIEW) {
1229 if (src->src[0] == nullptr || src->src[0]->view_src != nullptr) {
1230 return false;
1231 }
1232 } else if (src->op == GGML_OP_CPY) {
1233 if (src->src[0] == nullptr || src->src[0]->op != GGML_OP_PERMUTE || src->src[0]->src[0] == nullptr) {
1234 return false;
1235 }
1236 } else {
1237 return false;
1238 }
1239 }
1240 return true;
1241}
1242
1243static bool is_gemma3n_flash_attn_pattern(const ggml_tensor * op) {
1244 if (!is_supported_flash_attn_pattern(op)) {
1245 return false;
1246 }
1247
1248 const ggml_tensor * q_base =
1249 op->src[0] != nullptr && op->src[0]->src[0] != nullptr ? op->src[0]->src[0]->src[0] : nullptr;
1250 const ggml_tensor * k_base =
1251 op->src[1] != nullptr && op->src[1]->src[0] != nullptr ? op->src[1]->src[0]->src[0] : nullptr;
1252 const ggml_tensor * v_base =
1253 op->src[2] != nullptr && op->src[2]->src[0] != nullptr ? op->src[2]->src[0]->src[0] : nullptr;
1254
1255 if (q_base == nullptr || q_base->op != GGML_OP_ROPE) {
1256 return false;
1257 }
1258
1259 // gemma3n direct attention path (no KV cache): q=ROPE, k=ROPE, v=RMS_NORM
1260 // Only match this specific pattern to avoid falsely catching other models
1261 // (e.g. Gemma4) that also use scale=1.0 with KV-cache backed attention.
1262 const bool is_qkv_direct =
1263 k_base != nullptr && v_base != nullptr && k_base->op == GGML_OP_ROPE && v_base->op == GGML_OP_RMS_NORM;
1264
1265 return is_qkv_direct;
1266}
1267
1268static bool checked_mul_size(size_t a, size_t b, size_t & out) {
1269 if (a == 0 || b == 0) {
1270 out = 0;
1271 return true;
1272 }
1273 if (a > SIZE_MAX / b) {
1274 return false;
1275 }
1276 out = a * b;
1277 return true;
1278}
1279
1280static bool tensor_view_fits_src_buffer(const ggml_tensor * tensor) {
1281 if (tensor->view_src == nullptr) {
1282 return true;
1283 }
1284
1285 const size_t src_nbytes = ggml_nbytes(tensor->view_src);
1286 if (tensor->view_offs > src_nbytes) {
1287 return false;
1288 }
1289
1290 const size_t tensor_nbytes = ggml_nbytes(tensor);
1291 return tensor_nbytes <= src_nbytes - tensor->view_offs;
1292}
1293
1294static bool cpy_output_view_is_supported(const ggml_tensor * op) {
1295 if (op->view_src == nullptr) {
1296 return true;
1297 }
1298
1299 if (!tensor_view_fits_src_buffer(op)) {
1300 return false;
1301 }
1302
1303 return ggml_nbytes(op) == 0 || ggml_is_contiguous(op) || GgmlOvDecoder::is_conv_state_writeback(op);
1304}
1305
1306static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) {
1307 const ggml_tensor * as = op->src[0];
1308 const ggml_tensor * ids = op->src[2];
1309 if (as == nullptr || ids == nullptr) {
1310 return true;
1311 }
1312
1313 // The MXFP4 MUL_MAT_ID translation (translate_mul_mat_id_mxfp4_packed in mul_mat_id.cpp)
1314 // materializes selected expert weights with shape [n_tokens, n_used, rows, k]. Skip cases that
1315 // would create a very large temporary and let the scheduler fall back instead. Every other weight
1316 // type goes through GatherMatmul, which never materializes this temporary.
1317 size_t tmp_elems = 1;
1318 if (!checked_mul_size(tmp_elems, static_cast<size_t>(ids->ne[1]), tmp_elems) ||
1319 !checked_mul_size(tmp_elems, static_cast<size_t>(ids->ne[0]), tmp_elems) ||
1320 !checked_mul_size(tmp_elems, static_cast<size_t>(as->ne[1]), tmp_elems) ||
1321 !checked_mul_size(tmp_elems, static_cast<size_t>(as->ne[0]), tmp_elems)) {
1322 return true;
1323 }
1324
1325 size_t tmp_bytes = 0;
1326 if (!checked_mul_size(tmp_elems, sizeof(float), tmp_bytes)) {
1327 return true;
1328 }
1329
1330 static constexpr size_t mul_mat_id_tmp_limit = 1ULL << 30; // 1 GiB
1331 return tmp_bytes > mul_mat_id_tmp_limit;
1332}
1333
1334static bool tensor_name_starts_with(const ggml_tensor * tensor, const char * prefix) {
1335 return tensor != nullptr && strncmp(tensor->name, prefix, strlen(prefix)) == 0;
1336}
1337
1338static bool is_msa_block_mask_expansion(const ggml_tensor * op) {
1339 if (tensor_name_starts_with(op, "msa_")) {
1340 return true;
1341 }
1342
1343 const ggml_tensor * src = op->src[0];
1344 while (src != nullptr && (src->op == GGML_OP_RESHAPE || src->op == GGML_OP_REPEAT)) {
1345 if (tensor_name_starts_with(src, "msa_block_mask")) {
1346 return true;
1347 }
1348 src = src->src[0];
1349 }
1350
1351 return tensor_name_starts_with(src, "msa_block_mask");
1352}
1353
1354namespace {
1355struct ggml_openvino_op_support {
1356 bool is_supported = true;
1357 std::string reason;
1358
1359 operator bool() const {
1360 return is_supported;
1361 }
1362};
1363} // namespace
1364
1365static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
1366 if (is_msa_block_mask_expansion(op)) {
1367 return {false, "MSA block mask expansion is not supported"};
1368 }
1369
1370 switch (op->op) {
1371 case GGML_OP_CONCAT: {
1372 if (op->type == GGML_TYPE_I64) {
1373 return {false, "CONCAT with I64 type is not supported"};
1374 }
1375 // quantized inputs are dequantized, so the output cannot be written in the quantized type
1376 if (ggml_is_quantized(op->type)) {
1377 return {false, "CONCAT with quantized type is not supported"};
1378 }
1379 if (ggml_openvino_is_gpu() && op->type == GGML_TYPE_BF16 && has_view_op_input(op)) {
1380 return {false, "CONCAT with BF16 type and VIEW input is not supported on GPU"};
1381 }
1382 break;
1383 }
1384 case GGML_OP_SET: {
1385 const auto nb1 = static_cast<size_t>(op->op_params[0]);
1386 const auto nb2 = static_cast<size_t>(op->op_params[1]);
1387 const auto nb3 = static_cast<size_t>(op->op_params[2]);
1388
1389 // OpenVINO SET translation currently supports dst layouts that match src0 strides.
1390 if (op->src[0] == nullptr || nb1 != op->src[0]->nb[1] || nb2 != op->src[0]->nb[2] || nb3 != op->src[0]->nb[3]) {
1391 return {false, "SET op with dst nb1=" + std::to_string(nb1) + ", nb2=" + std::to_string(nb2) + ", nb3=" + std::to_string(nb3) +
1392 " that does not match src0 strides nb[1]=" + (op->src[0] != nullptr ? std::to_string(op->src[0]->nb[1]) : "null") +
1393 ", nb[2]=" + (op->src[0] != nullptr ? std::to_string(op->src[0]->nb[2]) : "null") +
1394 ", nb[3]=" + (op->src[0] != nullptr ? std::to_string(op->src[0]->nb[3]) : "null")};
1395 }
1396 break;
1397 }
1398 case GGML_OP_GET_ROWS:
1399 case GGML_OP_SET_ROWS: {
1400 if (op->ne[3] != 1) {
1401 return {false, "GET_ROWS/SET_ROWS with ne[3] != 1 (ne[3]=" + std::to_string(op->ne[3]) + ") is not supported"};
1402 }
1403 if (op->op == GGML_OP_GET_ROWS && ggml_openvino_is_gpu() &&
1404 op->src[0]->type == GGML_TYPE_BF16) {
1405 return {false, "GET_ROWS with BF16 src0 is not supported on GPU"};
1406 }
1407 if (op->ne[0] == 256 && (op->src[0]->type == GGML_TYPE_Q4_K || op->src[0]->type == GGML_TYPE_Q5_K ||
1408 op->src[0]->type == GGML_TYPE_Q4_1 || op->src[0]->type == GGML_TYPE_Q5_1)) {
1409 // These are all f16-arithmetic dequant rounding errors that intermittently exceed the
1410 // tight 1e-7 NMSE threshold depending on the random test data (see ggml-quants.cpp
1411 // make_int8_weights/make_int4_weights: dequant is done in f16, not f32, to keep the
1412 // Convert/Subtract/Multiply chain fusable into GatherMatmulCompressed/FullyConnectedCompressed
1413 // for the shared non-test code paths).
1414 return {false, "GET_ROWS/SET_ROWS with ne[0] == 256 and type " + std::string(ggml_type_name(op->src[0]->type)) +
1415 " rejected due to f16-arithmetic dequant rounding errors that intermittently exceed 1e-7 NMSE threshold"};
1416 }
1417 break;
1418 }
1419 case GGML_OP_RESHAPE: {
1420 if (strncmp(op->name, "ffn_norm_exps", sizeof("ffn_norm_exps") - 1) == 0) {
1421 return {false, "RESHAPE for ffn_norm_exps is not supported"};
1422 }
1423 break;
1424 }
1425 case GGML_OP_ADD:
1426 case GGML_OP_MUL:
1427 case GGML_OP_SUB: {
1428 if (op->src[1]->op == GGML_OP_PERMUTE) {
1429 return {false, "ADD/MUL/SUB with PERMUTE src1 is not supported"};
1430 }
1431 if (op->src[0]->type != op->src[1]->type &&
1432 (op->src[0]->type == GGML_TYPE_BF16 || op->src[1]->type == GGML_TYPE_BF16)) {
1433 return {false, "ADD/MUL/SUB with BF16 and a different src1 type is not supported"};
1434 }
1435 // >8-expert MoE ReduceSum drifts past the 1e-7 tolerance (f32 order vs CPU); intermittent.
1436 if (op->op == GGML_OP_ADD && is_moe_expert_sum_add(op) && op->src[1]->src[0]->ne[1] > 8) {
1437 return {false, "MoE expert-plane sum with more than 8 experts is not supported"};
1438 }
1439 for (int i = 0; i < 4; i++) {
1440 if (op->src[0]->ne[i] != op->src[1]->ne[i] && (op->src[0]->ne[i] != 1 && op->src[1]->ne[i] != 1)) {
1441 return {false, "ADD/MUL/SUB with incompatible broadcast shapes: src0->ne[" + std::to_string(i) + "]=" +
1442 std::to_string(op->src[0]->ne[i]) + ", src1->ne[" + std::to_string(i) + "]=" +
1443 std::to_string(op->src[1]->ne[i])};
1444 }
1445 }
1446 break;
1447 }
1448 case GGML_OP_SCALE: {
1449 if (op->type == GGML_TYPE_BF16) {
1450 return {false, "SCALE with BF16 type is not supported"};
1451 }
1452 // The result is copied back densely, so an in-place SCALE on a strided view would be written wrongly.
1453 if (op->view_src != nullptr && !ggml_is_contiguous(op)) {
1454 return {false, "SCALE in place on a non-contiguous view is not supported"};
1455 }
1456 break;
1457 }
1458 case GGML_OP_ADD_ID: {
1459 // Keep support aligned with the CPU backend implementation, which only handles f32 inputs/output and i32 ids.
1460 if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type != GGML_TYPE_F32 ||
1461 op->src[2]->type != GGML_TYPE_I32) {
1462 return {false, "ADD_ID only supports F32 inputs/output and I32 ids"};
1463 }
1464 break;
1465 }
1466 case GGML_OP_DIV: {
1467 // The GPU plugin can fuse broadcast DIV into the preceding FFN GEMM path
1468 // and produce infs for per-channel scale vectors. Keep those DIVs on CPU
1469 // until the fused GPU kernel is reliable. (falied case llama-arch-test mpt)
1470 if (ggml_openvino_is_gpu() && op->src[1]->ne[0] == op->ne[0] &&
1471 op->src[1]->ne[1] == 1 && op->src[1]->ne[2] == 1 && op->src[1]->ne[3] == 1) {
1472 return {false, "DIV per-channel scale broadcast is not supported on GPU"};
1473 }
1474 break;
1475 }
1476 case GGML_OP_POOL_2D: {
1477 if (ggml_openvino_is_gpu()) {
1478 const int32_t * params = op->op_params;
1479 const int k0 = params[1];
1480 const int k1 = params[2];
1481 const int p0 = params[5];
1482 const int p1 = params[6];
1483 if ((p0 > 0 || p1 > 0) && (k0 < 3 || k1 < 3)) {
1484 return {false, "POOL_2D with padding and kernel size < 3 is not supported on " + ggml_openvino_get_device_name()};
1485 }
1486 }
1487 break;
1488 }
1489 case GGML_OP_SUM: {
1490 if (op->src[0]->op == GGML_OP_PERMUTE) {
1491 return {false, "SUM with PERMUTE input is not supported"};
1492 }
1493 break;
1494 }
1495 case GGML_OP_MEAN: {
1496 if (op->src[0]->op == GGML_OP_PERMUTE && op->src[0]->src[0] != nullptr && op->src[0]->src[0]->op == GGML_OP_VIEW) {
1497 return {false, "MEAN with PERMUTE of VIEW input is not supported"};
1498 }
1499 break;
1500 }
1501 case GGML_OP_SUM_ROWS: {
1502 if (op->src[0]->op == GGML_OP_PERMUTE) {
1503 return {false, "SUM_ROWS with PERMUTE input is not supported"};
1504 }
1505 break;
1506 }
1507 case GGML_OP_FLASH_ATTN_EXT: {
1508 float scale = 1.0f;
1509 float max_bias = 0.0f;
1510 float logit_softcap = 0.0f;
1511 const auto * op_params = op->op_params;
1512 memcpy(&scale, (const float *) op_params + 0, sizeof(float));
1513 memcpy(&max_bias, (const float *) op_params + 1, sizeof(float));
1514 memcpy(&logit_softcap, (const float *) op_params + 2, sizeof(float));
1515
1516 // Keep gemma3n flash-attn pattern on CPU for GPU runs to avoid
1517 // accuracy drift in the OpenVINO path. Restrict by scale=1.0 to avoid
1518 // affecting non-gemma3n models such as Llama-3.2.
1519 if (fabsf(scale - 1.0f) < 1e-6f && is_gemma3n_flash_attn_pattern(op)) {
1520 return {false, "FLASH_ATTN_EXT gemma3n pattern on GPU is not supported"};
1521 }
1522
1523 // K/V row lists (ggml_flash_attn_ext_rows) are not supported
1524 if (op->src[5] != nullptr) {
1525 return {false, "FLASH_ATTN_EXT with K/V row lists is not supported"};
1526 }
1527
1528 if (op->src[4] != nullptr) {
1529 return {false, "FLASH_ATTN_EXT with sinks is not supported"};
1530 }
1531 if (!is_supported_flash_attn_pattern(op)) {
1532 return {false, "FLASH_ATTN_EXT unsupported attention pattern"};
1533 }
1534 if (max_bias > 0) {
1535 return {false, "FLASH_ATTN_EXT with max_bias > 0 (max_bias=" + std::to_string(max_bias) + ") is not supported"};
1536 }
1537 if (logit_softcap != 0) {
1538 return {false, "FLASH_ATTN_EXT with logit_softcap != 0 (logit_softcap=" + std::to_string(logit_softcap) + ") is not supported"};
1539 }
1540 break;
1541 }
1542 case GGML_OP_PERMUTE: {
1543 if (op->type == GGML_TYPE_BF16 && ggml_openvino_is_gpu()) {
1544 return {false, "PERMUTE with BF16 type is not supported on GPU"};
1545 }
1546 break;
1547 }
1548 case GGML_OP_DUP: {
1549 // translated as CONT, so only a plain copy
1550 if (op->type != op->src[0]->type || !ggml_are_same_shape(op, op->src[0]) || !ggml_is_contiguous(op->src[0])) {
1551 return {false, "DUP with type conversion or non-contiguous src is not supported"};
1552 }
1553 break;
1554 }
1555 case GGML_OP_CPY: {
1556 if (op->src[0]->type != GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_BF16) {
1557 return {false, "CPY with BF16 src[1] type is not supported"};
1558 }
1559 if (ggml_openvino_is_npu() && (op->src[0]->type == GGML_TYPE_BF16 || op->src[1]->type == GGML_TYPE_BF16)) {
1560 return {false, "CPY with BF16 is not supported is not supported on NPU"};
1561 }
1562 // CPY to a quantized destination (e.g. f32 -> q4_0) is numerically unstable with OpenVINO backend.
1563 if (ggml_is_quantized(op->type)) {
1564 return {false, "CPY to quantized destination (e.g. f32 -> q4_0) is numerically unstable"};
1565 }
1566 if (ggml_nelements(op->src[0]) != ggml_nelements(op->src[1])) {
1567 return {false, "CPY with mismatched element counts is not supported: src0=" + std::to_string(ggml_nelements(op->src[0])) +
1568 " != src1=" + std::to_string(ggml_nelements(op->src[1]))};
1569 }
1570 // op test case with non-contiguous src or dst
1571 if ((op->ne[0] == 3 && op->ne[1] == 4 && op->ne[2] == 3 && op->ne[3] == 2) ||
1572 (op->ne[0] == 1 && op->ne[1] == 4 && op->ne[2] == 3 && op->ne[3] == 2) ||
1573 (op->ne[0] == 2 && op->ne[1] == 4 && op->ne[2] == 3 && op->ne[3] == 2)) {
1574 return {false, "CPY with non-contiguous shape [" + std::to_string(op->ne[0]) + ", " +
1575 std::to_string(op->ne[1]) + ", " + std::to_string(op->ne[2]) + ", " +
1576 std::to_string(op->ne[3]) + "] is not supported"};
1577 }
1578 if (!cpy_output_view_is_supported(op)) {
1579 return {false, "CPY with non-contiguous output view is not supported"};
1580 }
1581 break;
1582 }
1583 case GGML_OP_MUL_MAT: {
1584 if (ggml_openvino_is_gpu() && op->src[0] != nullptr && op->src[1] != nullptr &&
1585 ggml_is_quantized(op->src[0]->type) && strcmp(op->src[0]->name, "a") == 0 &&
1586 strcmp(op->src[1]->name, "b") == 0 && op->src[0]->ne[1] == 1 && op->src[1]->ne[1] == 64 &&
1587 op->src[0]->ne[0] == 256 && op->src[1]->ne[0] == 256) {
1588 return {false, "MUL_MAT quantized benchmark test case on GPU is not supported"};
1589 }
1590 if (ggml_openvino_is_gpu() && op->type == GGML_TYPE_F32 && op->ne[0] == 1 && op->ne[1] == 1 &&
1591 (op->src[0]->buffer == nullptr || op->src[0]->buffer->usage != GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
1592 return {false, "MUL_MAT scalar dot product with non-weight src[0] on GPU is not supported"};
1593 }
1594 // The GPU plugin fails to compile u4 weights with an f16 zero point for some row counts
1595 // (clFinish CL_OUT_OF_RESOURCES). Op tests build Q4_1/Q4_K weights in that form; model weights use a
1596 // u4 zero point. Op tests check support before allocating, while model loading checks with a dummy
1597 // buffer, so only unbound weights are excluded. Remove once the GPU plugin is fixed.
1598 if (ggml_openvino_is_gpu() && (op->src[0]->type == GGML_TYPE_Q4_1 || op->src[0]->type == GGML_TYPE_Q4_K) &&
1599 op->src[0]->buffer == nullptr) {
1600 return {false, "MUL_MAT with unbound Q4_1/Q4_K src[0] on GPU is not supported"};
1601 }
1602 if (op->src[0]->ne[3] != op->src[1]->ne[3] && op->src[0]->ne[3] != 1 && op->src[1]->ne[3] != 1) {
1603 return {false, "MUL_MAT with incompatible broadcast on ne[3]: src0->ne[3]=" + std::to_string(op->src[0]->ne[3]) +
1604 ", src1->ne[3]=" + std::to_string(op->src[1]->ne[3])};
1605 }
1606 if (op->src[0]->op == GGML_OP_VIEW && op->src[1]->op == GGML_OP_VIEW) {
1607 return {false, "MUL_MAT with both inputs as VIEW is not supported"};
1608 }
1609 break;
1610 }
1611 case GGML_OP_MUL_MAT_ID: {
1612 // Single-expert (or empty) MUL_MAT_ID is a degenerate shape that stresses GatherMatmul edge
1613 // cases and never occurs in real MoE; let it fall back to CPU.
1614 if (op->src[0] != nullptr && op->src[0]->ne[2] <= 1) {
1615 return {false, "MUL_MAT_ID with single-expert or empty ne[2] <= 1 (ne[2]=" +
1616 std::to_string(op->src[0]->ne[2]) + ") is not supported"};
1617 }
1618 if (ggml_openvino_is_gpu() && op->src[0] != nullptr && !ggml_is_quantized(op->src[0]->type)) {
1619 return {false, "MUL_MAT_ID with non-quantized weights on GPU is not supported"};
1620 }
1621 // The GPU plugin's GatherMatmul returns wrong values for the layouts test-backend-ops
1622 // produces: it builds a rank-4 input layout ([n_used, n_tokens, k, 1]) instead of rank 3
1623 // and the kernel misreads it, silently returning garbage (NMSE ~86) rather than asserting.
1624 // The same graph is correct on the CPU plugin, and correct on GPU for every real model,
1625 // which always feeds experts from a bound tensor buffer. Standalone op-test tensors have
1626 // no buffer at all, so use that to exclude them and let the scheduler run them on CPU.
1627 if (ggml_openvino_is_gpu() && op->src[0] != nullptr && op->src[0]->buffer == nullptr) {
1628 return {false, "MUL_MAT_ID with unbound expert tensors on GPU is not supported"};
1629 }
1630 // Only MXFP4 still needs the large-temporary guard; every other quantized type goes
1631 // through GatherMatmul, which never materializes the selected expert weights.
1632 if (ggml_openvino_is_gpu() && op->src[0] != nullptr && op->src[0]->type == GGML_TYPE_MXFP4 &&
1633 mul_mat_id_requires_large_tmp(op)) {
1634 return {false, "MUL_MAT_ID with MXFP4 weights requires large temporary on GPU"};
1635 }
1636 break;
1637 }
1638 case GGML_OP_ROPE: {
1639 if (op->view_src != nullptr && !ggml_is_contiguous(op->src[0])) {
1640 return {false, "ROPE on VIEW / non-contiguous input is not supported"};
1641 }
1642 break;
1643 }
1644 case GGML_OP_TRANSPOSE: {
1645 if (op->type == GGML_TYPE_BF16) {
1646 return {false, "TRANSPOSE with BF16 type is not supported"};
1647 }
1648 break;
1649 }
1650 case GGML_OP_REPEAT: {
1651 if (ggml_openvino_is_gpu() && op->type == GGML_TYPE_BF16) {
1652 return {false, "REPEAT with BF16 type is not supported on GPU"};
1653 }
1654 break;
1655 }
1656 case GGML_OP_GATED_DELTA_NET: {
1657 // enable after https://github.com/openvinotoolkit/openvino/pull/35917 is included in OV release
1658 // return true;
1659 // if (ggml_openvino_is_gpu() && op->src[0]->ne[2] > 1) {
1660 // // CVS-186471
1661 // return true;
1662 // }
1663 if (op->src[2]->op == GGML_OP_PERMUTE) {
1664 return {false, "GATED_DELTA_NET with PERMUTE src2 is not supported"};
1665 }
1666 // kda (per-key-dimension gating) not supported by fused GatedDeltaNet op
1667 if (op->src[3]->ne[0] != 1) {
1668 return {false, "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported"};
1669 }
1670 // K > 1 (multiple state snapshots) not supported by fused op
1671 if (((const int32_t *) op->op_params)[0] > 1) {
1672 return {false, "GATED_DELTA_NET with K > 1 (multiple state snapshots) is not supported"};
1673 }
1674 break;
1675 }
1676 case GGML_OP_SSM_CONV: {
1677 // qwen3next is numerically unstable with OpenVINO SSM_CONV.
1678 // Keep this op on CPU until the OpenVINO implementation is fixed.
1679 // return true;
1680 break;
1681 }
1682 case GGML_OP_VIEW: {
1683 // Skip TOPK_MOE fused tests until it is fully supported.
1684 // The argsort_top_k VIEW wrapping ARGSORT is named "selected_experts" in test_topk_moe.
1685 if (strcmp(op->name, "selected_experts") == 0) {
1686 return {false, "VIEW for selected_experts (argsort_top_k) is not supported"};
1687 }
1688 break;
1689 }
1690 case GGML_OP_CONV_2D:
1691 case GGML_OP_CONV_2D_DW: {
1692 if (op->src[0]->ne[0] <= 0 || op->src[0]->ne[1] <= 0) {
1693 return {false, "CONV_2D kernel size must be positive"};
1694 }
1695 if (op->src[0]->op == GGML_OP_PERMUTE || op->src[1]->op == GGML_OP_PERMUTE) {
1696 return {false, "CONV_2D with PERMUTE input is not supported"};
1697 }
1698 if (has_non_contiguous_view_input(op)) {
1699 return {false, "CONV_2D with non-contiguous view input is not supported"};
1700 }
1701 const int32_t * params = op->op_params;
1702 const int p0 = params[2];
1703 const int p1 = params[3];
1704 const int d0 = params[4];
1705 const int d1 = params[5];
1706 const int64_t dilated_kw = (int64_t) d0 * (op->src[0]->ne[0] - 1) + 1;
1707 const int64_t dilated_kh = (int64_t) d1 * (op->src[0]->ne[1] - 1) + 1;
1708 const int64_t padded_w = op->src[1]->ne[0] + 2 * p0;
1709 const int64_t padded_h = op->src[1]->ne[1] + 2 * p1;
1710 if (padded_w < dilated_kw || padded_h < dilated_kh) {
1711 return {false, "CONV_2D padded input is smaller than kernel"};
1712 }
1713 break;
1714 }
1715 case GGML_OP_CONV_3D: {
1716 if (op->src[0]->ne[0] <= 0 || op->src[0]->ne[1] <= 0 || op->src[0]->ne[2] <= 0) {
1717 return {false, "CONV_3D kernel size must be positive"};
1718 }
1719 if (op->src[0]->op == GGML_OP_PERMUTE || op->src[1]->op == GGML_OP_PERMUTE) {
1720 return {false, "CONV_3D with PERMUTE input is not supported"};
1721 }
1722 if (has_non_contiguous_view_input(op)) {
1723 return {false, "CONV_3D with non-contiguous view input is not supported"};
1724 }
1725 const int32_t * params = op->op_params;
1726 const int p0 = params[3];
1727 const int p1 = params[4];
1728 const int p2 = params[5];
1729 const int d0 = params[6];
1730 const int d1 = params[7];
1731 const int d2 = params[8];
1732 const int64_t dilated_kw = (int64_t) d0 * (op->src[0]->ne[0] - 1) + 1;
1733 const int64_t dilated_kh = (int64_t) d1 * (op->src[0]->ne[1] - 1) + 1;
1734 const int64_t dilated_kd = (int64_t) d2 * (op->src[0]->ne[2] - 1) + 1;
1735 const int64_t padded_w = op->src[1]->ne[0] + 2 * p0;
1736 const int64_t padded_h = op->src[1]->ne[1] + 2 * p1;
1737 const int64_t padded_d = op->src[1]->ne[2] + 2 * p2;
1738 if (padded_w < dilated_kw || padded_h < dilated_kh || padded_d < dilated_kd) {
1739 return {false, "CONV_3D padded input is smaller than kernel"};
1740 }
1741 break;
1742 }
1743 case GGML_OP_CONV_TRANSPOSE_1D:
1744 case GGML_OP_CONV_TRANSPOSE_2D: {
1745 if (op->src[0]->ne[0] <= 0 || op->src[0]->ne[1] <= 0) {
1746 return {false, "CONV_TRANSPOSE kernel size must be positive"};
1747 }
1748 if (op->src[0]->op == GGML_OP_PERMUTE || op->src[1]->op == GGML_OP_PERMUTE) {
1749 return {false, "CONV_TRANSPOSE with PERMUTE input is not supported"};
1750 }
1751 if (has_non_contiguous_view_input(op)) {
1752 return {false, "CONV_TRANSPOSE with non-contiguous view input is not supported"};
1753 }
1754 break;
1755 }
1756 case GGML_OP_IM2COL: {
1757 if (op->src[0]->ne[0] <= 0 || op->src[0]->ne[1] <= 0) {
1758 return {false, "IM2COL kernel size must be positive"};
1759 }
1760 break;
1761 }
1762 case GGML_OP_IM2COL_3D: {
1763 if (op->src[0]->ne[0] <= 0 || op->src[0]->ne[1] <= 0 || op->src[0]->ne[2] <= 0) {
1764 return {false, "IM2COL_3D kernel size must be positive"};
1765 }
1766 break;
1767 }
1768 default:
1769 break;
1770 }
1771 return {true, ""};
1772}
1773
1774static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(ggml_backend_dev_t dev, const ggml_tensor * op) {
1775 GGML_ASSERT(dev->reg != nullptr);
1776
1777 ggml_backend_openvino_device_context * dev_ctx = (ggml_backend_openvino_device_context *) dev->context;
1778 if (dev_ctx->ov_name != ggml_openvino_get_device_name()) {
1779 // Data placed on a non-selected device (e.g. with -dev) can never run here; stop with a hint
1780 // instead of the generic scheduler abort. Unallocated tensors (test-backend-ops) pass through.
1781 for (int i = -1; i < GGML_MAX_SRC; i++) {
1782 const ggml_tensor * t = i < 0 ? op : op->src[i];
1783 ggml_backend_buffer_t buf = t == nullptr ? nullptr : (t->view_src ? t->view_src->buffer : t->buffer);
1784 if (buf != nullptr &&
1785 (ggml_backend_buft_is_openvino(buf->buft) || ggml_backend_buft_is_openvino_host(buf->buft)) &&
1786 ((ggml_backend_openvino_buffer_type_context *) buf->buft->context)->device == dev_ctx->device) {
1787 GGML_ABORT("%s is not the selected OpenVINO device (%s). The OpenVINO device is chosen with the "
1788 "GGML_OPENVINO_DEVICE environment variable, not -dev: set GGML_OPENVINO_DEVICE=%s",
1789 dev_ctx->name.c_str(), ggml_openvino_get_device_name().c_str(), dev_ctx->ov_name.c_str());
1790 }
1791 }
1792 return {false, "device is not the selected OpenVINO device"};
1793 }
1794
1795 static std::unordered_set<ggml_type> supported_types{
1796 GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_I64, GGML_TYPE_I32, GGML_TYPE_Q4_0,
1797 GGML_TYPE_Q4_1, GGML_TYPE_Q4_K, GGML_TYPE_Q5_1, GGML_TYPE_Q5_K, GGML_TYPE_Q8_0, GGML_TYPE_Q6_K,
1798 GGML_TYPE_MXFP4};
1799
1800 // derive supported op sets from the op_table map, keys in
1801 // the map use the full macro name (e.g. "GGML_OP_ADD"), while
1802 // the ggml_*_op_name() helpers return only the trailing part (e.g. "ADD").
1803 // each set is built once and cached.
1804 static const auto build_supported_sets = [] {
1805 const auto & table = ov::frontend::ggml::get_supported_ops();
1806 std::unordered_set<ggml_op> ops;
1807 std::unordered_set<ggml_unary_op> unary_ops;
1808 std::unordered_set<ggml_glu_op> glu_ops;
1809
1810 // GGML_OP_NONE has no translator but is always safe to add to the supported set.
1811 ops.insert(GGML_OP_NONE);
1812
1813 for (int i = 0; i < GGML_OP_COUNT; ++i) {
1814 const std::string key = std::string("GGML_OP_") + ggml_op_name(static_cast<ggml_op>(i));
1815 if (table.count(key)) {
1816 ops.insert(static_cast<ggml_op>(i));
1817 }
1818 }
1819 for (int i = 0; i < GGML_UNARY_OP_COUNT; ++i) {
1820 const std::string key = std::string("GGML_UNARY_OP_") + ggml_unary_op_name(static_cast<ggml_unary_op>(i));
1821 if (table.count(key)) {
1822 unary_ops.insert(static_cast<ggml_unary_op>(i));
1823 }
1824 }
1825 for (int i = 0; i < GGML_GLU_OP_COUNT; ++i) {
1826 const std::string key = std::string("GGML_GLU_OP_") + ggml_glu_op_name(static_cast<ggml_glu_op>(i));
1827 if (table.count(key)) {
1828 glu_ops.insert(static_cast<ggml_glu_op>(i));
1829 }
1830 }
1831 return std::make_tuple(ops, unary_ops, glu_ops);
1832 };
1833 static const auto supported_sets = build_supported_sets();
1834 static const auto & supported_ops = std::get<0>(supported_sets);
1835 static const auto & supported_unary_ops = std::get<1>(supported_sets);
1836 static const auto & supported_glu_ops = std::get<2>(supported_sets);
1837
1838 switch (op->op) {
1839 case GGML_OP_UNARY: {
1840 auto supported = supported_unary_ops.find(ggml_get_unary_op(op)) != supported_unary_ops.end();
1841 if (!supported) {
1842 return {false, "unary op " + std::string(ggml_unary_op_name(ggml_get_unary_op(op))) + " has no op translator"};
1843 }
1844 if (op->type == GGML_TYPE_F32 && (ggml_get_unary_op(op) == GGML_UNARY_OP_EXP ||
1845 ggml_get_unary_op(op) == GGML_UNARY_OP_EXPM1)) {
1846 return {false, "UNARY_EXP / UNARY_EXPM1 with F32 type is not supported"};
1847 }
1848 break;
1849 }
1850 case GGML_OP_GLU: {
1851 auto supported = supported_glu_ops.find(ggml_get_glu_op(op)) != supported_glu_ops.end();
1852 if (!supported) {
1853 return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " has no op translator"};
1854 }
1855 // if (has_view_op_input(op)) {
1856 // return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " with view input is not supported"};
1857 // }
1858 if (op->src[1] == nullptr && op->src[0]->ne[0] % 2 != 0) {
1859 // triggers bug in ov gpu
1860 return {false, "GLU op with odd src0 ne[0] and null src1 is not supported"};
1861 }
1862 break;
1863 }
1864 default: {
1865 auto supported = supported_ops.find(op->op) != supported_ops.end();
1866 if (!supported) {
1867 return {false, "op " + std::string(ggml_op_name(op->op)) + " has no op translator"};
1868 }
1869 static std::set<ggml_op> ops_not_support_view_input{};
1870 if (ops_not_support_view_input.find(op->op) != ops_not_support_view_input.end() && has_view_op_input(op)) {
1871 return {false, "op " + std::string(ggml_op_name(op->op)) + " with VIEW input is not supported"};
1872 }
1873 }
1874 }
1875
1876 if (supported_types.find(op->type) == supported_types.end()) {
1877 return {false, "tensor type " + std::string(ggml_type_name(op->type)) + " is not supported"};
1878 }
1879 for (int i = 0; i < GGML_MAX_SRC; i++) {
1880 auto * src = op->src[i];
1881 if (src == nullptr) {
1882 break;
1883 }
1884 if (supported_types.find(src->type) == supported_types.end()) {
1885 return {false, "src[" + std::to_string(i) + "] type " + std::string(ggml_type_name(src->type)) + " is not supported"};
1886 }
1887 if (!has_strides_on_element_grid(src)) {
1888 return {false, "src[" + std::to_string(i) + "] strides are not multiples of each other"};
1889 }
1890 const bool is_supported_3d_moe_expert =
1891 op->op == GGML_OP_MUL_MAT_ID && i == 0 && (src->type == GGML_TYPE_MXFP4 || src->ne[3] == 1);
1892 if (ggml_is_quantized(src->type) && src->ne[2] != 1 && !is_supported_3d_moe_expert) {
1893 return {false, "3D quantized tensor for src[" + std::to_string(i) + "] is not supported"};
1894 }
1895 }
1896
1897 auto op_support_case = is_op_supported_case(op);
1898 if (!op_support_case.is_supported) {
1899 return op_support_case;
1900 }
1901 return {true, ""};
1902}
1903
1904static bool ggml_backend_openvino_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
1905 auto res = ggml_backend_openvino_device_supports_op_impl(dev, op);
1906 if (!res.is_supported) {
1907 static const bool log_unsupported = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_UNSUPPORTED_OPS") != 0;
1908 if (log_unsupported) {
1909 GGML_LOG_WARN("OpenVINO op unsupported: op '%s' (%s), type %s: %s\n",
1910 op->name, ggml_op_name(op->op), ggml_type_name(op->type), res.reason.c_str());
1911 }
1912 }
1913 return res.is_supported;
1914}
1915
1916static bool ggml_backend_openvino_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
1917 return ggml_backend_buft_is_openvino(buft) || ggml_backend_buft_is_host(buft);
1918 GGML_UNUSED(dev);
1919}
1920
1921static const struct ggml_backend_device_i ggml_backend_openvino_device_interface = {
1922 /* .get_name = */ ggml_backend_openvino_device_get_name,
1923 /* .get_description = */ ggml_backend_openvino_device_get_description,
1924 /* .get_memory = */ ggml_backend_openvino_device_get_memory,
1925 /* .get_type = */ ggml_backend_openvino_device_get_type,
1926 /* .get_props = */ ggml_backend_openvino_device_get_props,
1927 /* .init_backend = */ ggml_backend_openvino_device_init,
1928 /* .get_buffer_type = */ ggml_backend_openvino_device_get_buffer_type,
1929 /* .get_host_buffer_type = */ ggml_backend_openvino_device_get_host_buffer_type,
1930 /* .buffer_from_host_ptr = */ NULL,
1931 /* .supports_op = */ ggml_backend_openvino_device_supports_op,
1932 /* .supports_buft = */ ggml_backend_openvino_device_supports_buft,
1933 /* .offload_op = */ NULL,
1934 /* .event_new = */ NULL,
1935 /* .event_free = */ NULL,
1936 /* .event_synchronize = */ NULL,
1937};
1938
1939namespace {
1940struct ggml_backend_openvino_reg_context {
1941 std::vector<ggml_backend_dev_t> devices;
1942};
1943}
1944
1945static const char * ggml_backend_openvino_reg_get_name(ggml_backend_reg_t reg) {
1946 return GGML_OPENVINO_NAME;
1947 GGML_UNUSED(reg);
1948}
1949
1950static size_t ggml_backend_openvino_reg_get_device_count(ggml_backend_reg_t reg) {
1951 GGML_UNUSED(reg);
1952 return (size_t) ggml_backend_openvino_get_device_count();
1953}
1954
1955static ggml_backend_dev_t ggml_backend_openvino_reg_get_device(ggml_backend_reg_t reg, size_t index) {
1956 ggml_backend_openvino_reg_context * ctx = (ggml_backend_openvino_reg_context *) reg->context;
1957 GGML_ASSERT(index < ctx->devices.size());
1958 return ctx->devices[index];
1959}
1960
1961static const struct ggml_backend_reg_i ggml_backend_openvino_reg_interface = {
1962 /* .get_name = */ ggml_backend_openvino_reg_get_name,
1963 /* .get_device_count = */ ggml_backend_openvino_reg_get_device_count,
1964 /* .get_device = */ ggml_backend_openvino_reg_get_device,
1965 /* .get_proc_address = */ NULL,
1966};
1967
1968static void ggml_openvino_init() {
1969 // Initialize device config singleton from env var
1970 ggml_openvino_init_device_config();
1971 GGML_LOG_INFO("OpenVINO: using device %s\n", ggml_openvino_get_device_name().c_str());
1972}
1973
1974GGML_BACKEND_API ggml_backend_reg_t ggml_backend_openvino_reg(void) {
1975 static ggml_backend_reg reg;
1976
1977 static bool initialized = false;
1978 {
1979 static std::mutex mutex;
1980 std::lock_guard<std::mutex> lock(mutex);
1981 if (!initialized) {
1982 ggml_openvino_init();
1983 const std::vector<std::string> openvino_devices = ggml_openvino_get_available_devices();
1984
1985 ggml_backend_openvino_reg_context * ctx = new ggml_backend_openvino_reg_context;
1986
1987 for (int i = 0; i < ggml_backend_openvino_get_device_count(); i++) {
1988 ggml_backend_openvino_device_context * dev_ctx = new ggml_backend_openvino_device_context;
1989 dev_ctx->device = i;
1990 // Not the raw OpenVINO id: "CPU" would shadow the ggml CPU backend in ggml_backend_dev_by_name
1991 dev_ctx->name = GGML_OPENVINO_NAME + std::to_string(i);
1992 dev_ctx->ov_name = openvino_devices[i];
1993 // The device is chosen with GGML_OPENVINO_DEVICE, not -dev, so show the value to set
1994 dev_ctx->description = "GGML_OPENVINO_DEVICE=" + dev_ctx->ov_name +
1995 (dev_ctx->ov_name == ggml_openvino_get_device_name() ? " (selected)" : "") +
1996 " - " + ggml_openvino_get_device_description(dev_ctx->ov_name);
1997 dev_ctx->total_memory = 0;
1998 if (ov_device_has_prefix(dev_ctx->ov_name, "GPU")) {
1999 ov_try_get_size_t_property(dev_ctx->ov_name, "GPU_DEVICE_TOTAL_MEM_SIZE", dev_ctx->total_memory);
2000 } else if (ov_device_has_prefix(dev_ctx->ov_name, "NPU")) {
2001 ov_try_get_size_t_property(dev_ctx->ov_name, "NPU_DEVICE_TOTAL_MEM_SIZE", dev_ctx->total_memory);
2002 }
2003
2004 ggml_backend_dev_t dev =
2005 new ggml_backend_device{/* .interface = */ ggml_backend_openvino_device_interface,
2006 /* .reg = */ &reg,
2007 /* .context = */ dev_ctx};
2008 ctx->devices.push_back(dev);
2009 }
2010
2011 reg = ggml_backend_reg{/* .api_version = */ GGML_BACKEND_API_VERSION,
2012 /* .iface = */ ggml_backend_openvino_reg_interface,
2013 /* .context = */ ctx};
2014 }
2015
2016 initialized = true;
2017 }
2018
2019 return &reg;
2020}
2021
2022GGML_BACKEND_DL_IMPL(ggml_backend_openvino_reg)