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-extra.cpp

669 lines · 27392 bytes Raw Blame History
1#include "ggml-openvino-extra.h"
2
3#include "ggml-impl.h"
4#include "ggml.h"
5#include "model-cache.h"
6
7#include <algorithm>
8#include <cstdlib>
9#include <cstring>
10#include <openvino/runtime/intel_gpu/ocl/ocl.hpp>
11#include <openvino/runtime/intel_npu/level_zero/level_zero.hpp>
12#include <openvino/runtime/properties.hpp>
13#include <mutex>
14#include <optional>
15
16ov::Core & ov_singleton_core() {
17 static ov::Core core;
18 return core;
19}
20
21static bool has_prefix(const std::string & s, const std::string & prefix) {
22 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
23}
24
25static bool is_virtual_routing_device(const std::string & device_name) {
26 return has_prefix(device_name, "AUTO") || has_prefix(device_name, "MULTI") || has_prefix(device_name, "HETERO");
27}
28
29static std::vector<std::string> ov_enumerate_devices() {
30 std::vector<std::string> result;
31
32 for (const auto & device : ov_singleton_core().get_available_devices()) {
33 if (!is_virtual_routing_device(device)) {
34 result.push_back(device);
35 }
36 }
37
38 if (result.empty()) {
39 result.push_back("CPU");
40 }
41
42 std::sort(result.begin(), result.end());
43 result.erase(std::unique(result.begin(), result.end()), result.end());
44 return result;
45}
46
47std::string ggml_openvino_get_device_description(const std::string & device_name) {
48 std::string description = device_name;
49 try {
50 description = ov_singleton_core().get_property(device_name, ov::device::full_name);
51 } catch (...) {
52 return device_name;
53 }
54
55 if (has_prefix(device_name, "NPU")) {
56 try {
57 const std::string arch = ov_singleton_core().get_property(device_name, "DEVICE_ARCHITECTURE").as<std::string>();
58 if (!arch.empty()) {
59 description += " (NPU " + arch + ")";
60 }
61 } catch (...) {
62 }
63 }
64
65 return description;
66}
67
68// requested: GGML_OPENVINO_DEVICE, nullptr if unset. available_devices is never empty (see ov_enumerate_devices)
69static std::string resolve_openvino_device_name(const std::vector<std::string> & available_devices,
70 const char * requested) {
71 auto available = [&](const std::string & name) {
72 return std::find(available_devices.begin(), available_devices.end(), name) != available_devices.end();
73 };
74 if (requested == nullptr) {
75 return available("CPU") ? "CPU" : available_devices.front();
76 }
77 if (!available(requested)) {
78 // No fallback to CPU (easy to miss) and no GPU -> GPU.0 alias (with iGPU + dGPU, GPU.0 is often the
79 // wrong one). List the devices here: --list-devices initializes this backend and would abort too.
80 std::string list;
81 for (const std::string & name : available_devices) {
82 list += "\n " + name + ": " + ggml_openvino_get_device_description(name);
83 }
84 GGML_ABORT("GGML OpenVINO Backend: GGML_OPENVINO_DEVICE=%s is not available. "
85 "Set it to one of the available OpenVINO devices:%s",
86 requested, list.c_str());
87 }
88 return requested;
89}
90
91// =====================================================
92// Device Configuration Implementations
93// =====================================================
94
95void ggml_openvino_device_config::init() {
96 static std::mutex mutex;
97 std::lock_guard<std::mutex> lock(mutex);
98 if (initialized) {
99 return;
100 }
101 // Set up front: a failed OpenCL setup below is not retried on every call
102 initialized = true;
103
104 // All recognized GGML_OPENVINO_* env vars. Their values are cached here
105 // once at backend init time and read back via ggml_openvino_getenv_str()
106 // (raw string) or ggml_openvino_getenv_int() (integer / boolean toggle).
107 static constexpr const char * env_var_names[] = {
108 // String values (use ggml_openvino_getenv_str)
109 "GGML_OPENVINO_DEVICE",
110 "GGML_OPENVINO_CACHE_DIR",
111 "GGML_OPENVINO_SPILL_DIR",
112 "GGML_OPENVINO_DEBUG_NODE",
113 "GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR",
114 "GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY",
115 "GGML_OPENVINO_NPU_COMPILE_CONFIG",
116 // Integer values (use ggml_openvino_getenv_int)
117 "GGML_OPENVINO_PREFILL_CHUNK_SIZE",
118 // Boolean toggles (treated as int flags via ggml_openvino_getenv_int)
119 "GGML_OPENVINO_STATEFUL_EXECUTION",
120 "GGML_OPENVINO_PROFILING",
121 "GGML_OPENVINO_DUMP_CGRAPH",
122 "GGML_OPENVINO_DUMP_IR",
123 "GGML_OPENVINO_DEBUG_INPUT",
124 "GGML_OPENVINO_DEBUG_OUTPUT",
125 // Force the static (NPU-shape) compute path on any device, e.g. GGML_OPENVINO_DEVICE=CPU,
126 // to test the static-shape translation without NPUW/real NPU hardware in the loop.
127 "GGML_OPENVINO_FORCE_STATIC",
128 "GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS",
129 "GGML_OPENVINO_ENABLE_CACHE",
130 "GGML_OPENVINO_DISABLE_CACHE",
131 "GGML_OPENVINO_DISABLE_KV_SLICE",
132 "GGML_OPENVINO_ENABLE_FALLBACK",
133 "GGML_OPENVINO_MANUAL_GQA_ATTN",
134 "GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN",
135 "GGML_OPENVINO_MOE_OP",
136 "GGML_OPENVINO_MEMORY_OPTIMIZE",
137 "GGML_OPENVINO_RELEASE_WEIGHTS",
138 "GGML_OPENVINO_REDUCE_COMPILE_MEM",
139 "GGML_OPENVINO_LOG_UNSUPPORTED_OPS",
140 "GGML_OPENVINO_LOG_SWA_LAYERS",
141 "GGML_OPENVINO_NATIVE_SOFTPLUS",
142 "GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS",
143 "GGML_OPENVINO_REQUANT_KQUANT",
144 "GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT",
145 // Build the precise (but O(n_nodes)) graph cache key. Needed by op tests.
146 "GGML_OPENVINO_FULL_GRAPH_KEY",
147 };
148
149 for (const char * const & env_var : env_var_names) {
150 auto * env = getenv(env_var);
151 if (env) {
152 environment_variables[env_var] = env;
153 }
154 }
155
156 available_devices = ov_enumerate_devices();
157 device_name = resolve_openvino_device_name(available_devices, ggml_openvino_getenv_str("GGML_OPENVINO_DEVICE"));
158 is_npu = has_prefix(device_name, "NPU");
159
160 ggml_openvino_model_cache_init();
161
162 const char * cache_dir = ggml_openvino_getenv_str("GGML_OPENVINO_CACHE_DIR");
163 if (has_prefix(device_name, "NPU")) {
164 compile_config = {
165 {"NPU_COMPILER_DYNAMIC_QUANTIZATION", "YES" },
166 {"NPU_USE_NPUW", "YES" },
167 {"NPUW_DEVICES", "NPU" },
168 {"NPUW_FOLD", "YES" },
169 {"NPUW_WEIGHTS_BANK", "shared"},
170 {"NPUW_FUNCALL_FOR_ALL", "YES" },
171 {"NPUW_FUNCALL_ASYNC", "YES" },
172 {"NPUW_DQ", "YES" },
173 {"NPUW_DQ_FULL", "NO" },
174 };
175 if (cache_dir && strlen(cache_dir) > 0) {
176 compile_config["NPUW_CACHE_DIR"] = cache_dir;
177 compile_config.insert(ov::cache_mode(ov::CacheMode::OPTIMIZE_SIZE));
178 }
179 const char * compilation_mode_params =
180 ggml_openvino_getenv_str("GGML_OPENVINO_NPU_COMPILE_CONFIG");
181 if (compilation_mode_params && strlen(compilation_mode_params) > 0) {
182 compile_config["NPU_COMPILATION_MODE_PARAMS"] = compilation_mode_params;
183 }
184 } else if (cache_dir && strlen(cache_dir) > 0) {
185 compile_config.insert(ov::cache_dir(cache_dir));
186 compile_config.insert(ov::cache_mode(ov::CacheMode::OPTIMIZE_SIZE));
187 }
188
189 if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2) {
190 compile_config.insert(ov::enable_profiling(true));
191 }
192
193 // Initialize remote context with queue sharing for GPU
194 if (has_prefix(device_name, "GPU")) {
195 // Use the OpenCL context OpenVINO created for this device, so GPU.N gets its own device
196 cl_context cl_ctx;
197 try {
198 auto ov_ctx = ov_singleton_core().get_default_context(device_name).as<ov::intel_gpu::ocl::ClContext>();
199 cl_ctx = ov_ctx.get();
200 } catch (const std::exception & e) {
201 // The consumers of the remote context have no host fallback, and OpenVINO
202 // already reported the device as present.
203 GGML_ABORT("ggml-openvino: failed to get the OpenCL context for %s: %s", device_name.c_str(), e.what());
204 }
205
206 cl_int err;
207 cl_device_id cl_device;
208 err = clGetContextInfo(cl_ctx, CL_CONTEXT_DEVICES, sizeof(cl_device), &cl_device, nullptr);
209 if (err != CL_SUCCESS) {
210 GGML_ABORT("ggml-openvino: failed to get the OpenCL device for %s: %d", device_name.c_str(), err);
211 }
212
213 cl_platform_id cl_platform;
214 err = clGetDeviceInfo(cl_device, CL_DEVICE_PLATFORM, sizeof(cl_platform), &cl_platform, nullptr);
215 if (err != CL_SUCCESS) {
216 GGML_ABORT("ggml-openvino: failed to get the OpenCL platform for %s: %d", device_name.c_str(), err);
217 }
218
219 cl_mem_fill_fn =
220 (clEnqueueMemFillINTEL_fn) clGetExtensionFunctionAddressForPlatform(cl_platform, "clEnqueueMemFillINTEL");
221 cl_mem_cpy_fn =
222 (clEnqueueMemcpyINTEL_fn) clGetExtensionFunctionAddressForPlatform(cl_platform, "clEnqueueMemcpyINTEL");
223
224 cl_ulong device_max_alloc = 0;
225 err = clGetDeviceInfo(cl_device, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(device_max_alloc), &device_max_alloc,
226 nullptr);
227 if (err == CL_SUCCESS) {
228 max_alloc_size = device_max_alloc;
229 } else {
230 // not fatal, ggml then allocates one buffer
231 GGML_LOG_WARN("Failed to get OpenCL max allocation size: %d\n", err);
232 }
233
234 const cl_queue_properties profiling_properties[] = {
235 CL_QUEUE_PROPERTIES,
236 CL_QUEUE_PROFILING_ENABLE,
237 0,
238 };
239 const cl_queue_properties * queue_properties =
240 ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? profiling_properties : nullptr;
241 cl_queue = clCreateCommandQueueWithProperties(cl_ctx, cl_device, queue_properties, &err);
242 if (err != CL_SUCCESS) {
243 GGML_ABORT("ggml-openvino: failed to create the OpenCL queue for %s: %d", device_name.c_str(), err);
244 }
245
246 // Create OpenVINO remote context with queue sharing
247 remote_context = ov::intel_gpu::ocl::ClContext(ov_singleton_core(), cl_queue);
248 } else if (has_prefix(device_name, "NPU")) {
249 // remote tensor is not used for NPU yet
250 // remote_context = ov_singleton_core().get_default_context(device_name);
251 }
252}
253
254ggml_openvino_device_config::~ggml_openvino_device_config() {
255 if (cl_queue != nullptr) {
256 clReleaseCommandQueue(cl_queue);
257 cl_queue = nullptr;
258 }
259}
260
261// Get the global device config singleton
262ggml_openvino_device_config & ggml_openvino_get_device_config() {
263 static ggml_openvino_device_config config;
264 return config;
265}
266
267// Initialize device config (call during backend init)
268void ggml_openvino_init_device_config() {
269 ggml_openvino_get_device_config().init();
270}
271
272// Get the device name
273const std::string & ggml_openvino_get_device_name() {
274 return ggml_openvino_get_device_config().device_name;
275}
276
277std::vector<std::string> ggml_openvino_get_available_devices() {
278 auto & config = ggml_openvino_get_device_config();
279 config.init();
280 return config.available_devices;
281}
282
283// Get the value of a GGML_OPENVINO_* env var as a string. Returns
284// default_value when the var is unset or set to an empty string.
285const char * ggml_openvino_getenv_str(const char * var, const char * default_value) {
286 auto & env_map = ggml_openvino_get_device_config().environment_variables;
287 auto it = env_map.find(var);
288 return (it == env_map.end() || it->second.empty()) ? default_value : it->second.c_str();
289}
290
291// Get the value of a GGML_OPENVINO_* env var as an int (via std::atoi).
292// Returns default_value (0) when the var is unset or empty. Used for both
293// integer settings (e.g. GGML_OPENVINO_PREFILL_CHUNK_SIZE) and boolean
294// toggles: "0" disables, any non-zero integer enables.
295int ggml_openvino_getenv_int(const char * var, int default_value) {
296 const char * v = ggml_openvino_getenv_str(var, nullptr);
297 return v ? std::atoi(v) : default_value;
298}
299
300bool ggml_openvino_reduce_compile_mem_enabled() {
301 const char * reduce_compile_mem = ggml_openvino_getenv_str("GGML_OPENVINO_REDUCE_COMPILE_MEM");
302 if (reduce_compile_mem != nullptr) {
303 return ggml_openvino_getenv_int("GGML_OPENVINO_REDUCE_COMPILE_MEM") != 0;
304 }
305 return ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
306}
307
308bool ggml_openvino_release_weights_enabled() {
309 const char * release_weights = ggml_openvino_getenv_str("GGML_OPENVINO_RELEASE_WEIGHTS");
310 if (release_weights != nullptr) {
311 return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS") != 0;
312 }
313 return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
314}
315
316// Check if running on NPU
317bool ggml_openvino_is_npu() {
318 return ggml_openvino_get_device_config().is_npu;
319}
320
321bool ggml_openvino_is_gpu() {
322 return has_prefix(ggml_openvino_get_device_name(), "GPU");
323}
324
325size_t ggml_openvino_max_alloc_size() {
326 return ggml_openvino_get_device_config().max_alloc_size;
327}
328
329// Get the remote context for the current device (returns empty optional for CPU)
330std::optional<ov::RemoteContext> ggml_openvino_get_remote_context() {
331 return ggml_openvino_get_device_config().remote_context;
332}
333
334// Get the compile config for the current device
335const ov::AnyMap & ggml_openvino_get_compile_config() {
336 return ggml_openvino_get_device_config().compile_config;
337}
338
339// Get the OpenCL command queue for GPU operations
340cl_command_queue ggml_openvino_get_cl_queue() {
341 return ggml_openvino_get_device_config().cl_queue;
342}
343
344// Get the clEnqueueMemFillINTEL function pointer
345clEnqueueMemFillINTEL_fn ggml_openvino_get_clEnqueueMemFillINTEL() {
346 return ggml_openvino_get_device_config().cl_mem_fill_fn;
347}
348
349// Get the clEnqueueMemcpyINTEL function pointer
350clEnqueueMemcpyINTEL_fn ggml_openvino_get_clEnqueueMemcpyINTEL() {
351 return ggml_openvino_get_device_config().cl_mem_cpy_fn;
352}
353
354// Get requantization type for a tensor type (returns nullopt if no requant needed)
355std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor * tensor, bool no_requant) {
356 if (no_requant) {
357 return std::nullopt;
358 }
359 if (strncmp(tensor->name, "token_embd.weight", 17) == 0) {
360 return ((ggml_openvino_is_npu() && tensor->type == GGML_TYPE_Q6_K) ? ExtraQuantType::F16 :
361 ExtraQuantType::Q8_0_C);
362 }
363 if (strncmp(tensor->name, "output.weight", 13) == 0) {
364 return ExtraQuantType::Q8_0_C;
365 }
366 if (ggml_openvino_is_npu()) {
367 return ExtraQuantType::Q4_0_128;
368 }
369 // By default Q6_K/Q5_K are requantized to Q8_0_C, which *inflates* 6- and 5-bit weights to 8
370 // while the rest of the model stays at 4 bits, and Q4_K keeps its native group-32 layout
371 // (an f16 scale plus an f16 zero point per 32 weights = 0.125 B/weight of metadata).
372 // Decode of a large model is bandwidth-bound, so both cost throughput.
373 //
374 // GGML_OPENVINO_REQUANT_KQUANT selects a 4-bit target instead. Names are
375 // q4_<sym|asym><group>[_all]: <sym|asym> says whether a per-group zero point is kept, <group>
376 // is the group size, and the _all suffix sends Q4_K down the same path (without it only
377 // Q6_K/Q5_K are touched):
378 // q4_sym128 Q6_K/Q5_K -> Q4_0_128 (u4, group 128, symmetric)
379 // q4_sym128_all and Q4_K too -- drops Q4_K's per-32 zero point, which costs some accuracy
380 // q4_asym64 Q6_K/Q5_K -> Q4_1_64 (u4, group 64, asymmetric)
381 // q4_asym64_all Q6_K/Q5_K and Q4_K -> Q4_1_64 (u4, group 64, asymmetric)
382 // native no requantization at all (keep Q6_K/Q5_K as they are)
383 //
384 // q4_asym64 leaves Q4_K at its native group 32. Use q4_asym64_all to keep the group size uniform.
385 const char * rq = ggml_openvino_getenv_str("GGML_OPENVINO_REQUANT_KQUANT");
386 auto is_opt = [rq](const char * name) {
387 return rq && strcmp(rq, name) == 0;
388 };
389 const bool sym128 = is_opt("q4_sym128");
390 const bool sym128_all = is_opt("q4_sym128_all");
391 const bool asym64_all = is_opt("q4_asym64_all");
392 const bool asym64 = is_opt("q4_asym64");
393
394 if (tensor->type == GGML_TYPE_Q4_K) {
395 if (sym128_all) {
396 return ExtraQuantType::Q4_0_128;
397 }
398 if (asym64_all) {
399 return ExtraQuantType::Q4_1_64;
400 }
401 }
402 // MoE expert weights (3D, ne[2] = n_expert) stored as Q5_1/Q8_0 are the expert-side
403 // equivalent of Q6_K/Q5_K: kept at 8 bits by default while the rest of the model is at 4
404 // (gemma-4 26B-A4B keeps its down projection there). Send them to 4 bits under the same
405 // option, at group 64 rather than 128: the down expert has k=704, which 64 divides
406 // (704/64 = 11) and 128 does not.
407 if (tensor->ne[2] > 1 && (tensor->type == GGML_TYPE_Q5_1 || tensor->type == GGML_TYPE_Q8_0)) {
408 if (sym128 || sym128_all) {
409 return ExtraQuantType::Q4_0_64;
410 }
411 if (asym64 || asym64_all) {
412 return ExtraQuantType::Q4_1_64;
413 }
414 // TODO: temporary workaround for a known OpenVINO GPU-plugin bug -- remove once the
415 // plugin computes grouped 8-bit GatherMatmulCompressed correctly. This costs accuracy
416 // (5/8-bit -> 4-bit) on any model it applies to, so it must not outlive the bug.
417 //
418 // On GPU these would otherwise stay in their native *grouped 8-bit* layout, which the GPU
419 // plugin's GatherMatmulCompressed computes incorrectly -- gemma-4 26B-A4B (whose down
420 // projection is Q5_1) produces garbage, while the same graph is correct on CPU. It is
421 // specific to grouped 8 bit: the gate/up experts are grouped u4 *with* a zero point and
422 // are fine, and Qwen3.5 / granite are fine because their Q5_K/Q6_K down projections
423 // already requantize to per-channel Q8_0_C (grouped=0). Sending these to grouped 4 bit
424 // avoids the broken layout and restores correct output.
425 // Opt out with GGML_OPENVINO_REQUANT_KQUANT=native.
426 if (ggml_openvino_is_gpu() && !is_opt("native")) {
427 return ExtraQuantType::Q4_0_64;
428 }
429 }
430 switch (tensor->type) {
431 case GGML_TYPE_Q6_K:
432 case GGML_TYPE_Q5_K:
433 if (sym128 || sym128_all) {
434 return ExtraQuantType::Q4_0_128;
435 }
436 if (asym64 || asym64_all) {
437 return ExtraQuantType::Q4_1_64;
438 }
439 if (is_opt("native")) {
440 return std::nullopt;
441 }
442 return ExtraQuantType::Q8_0_C;
443 default:
444 return std::nullopt;
445 }
446}
447
448// =====================================================
449// Extracted Layout Calculation
450// =====================================================
451
452ggml_openvino_extracted_layout ggml_openvino_get_extracted_layout(const ggml_tensor * tensor, bool use_bias) {
453 ggml_openvino_extracted_layout layout = {};
454 layout.is_symmetric = false;
455
456 if (!ggml_is_quantized(tensor->type)) {
457 return layout;
458 }
459
460 // Most quantized weights use the existing 2D extraction path. 3D expert weights for
461 // MUL_MAT_ID (MoE) are also supported, either as MXFP4 (packed, dedicated branch below) or via the
462 // generic sizing math below, which is shape-agnostic (based on total element count). Only reject 4D.
463 if (tensor->ne[3] != 1) {
464 return layout;
465 }
466
467 // 3D MoE expert weights that are not requantized (see below) always use the exact f16
468 // zero-point extraction (see extract_quantized_weights), which needs a wider zp slot than
469 // the packed integer zero point -- must be kept in sync with that function so the buffer
470 // sizing here matches what process_weight_tensor actually writes.
471 const bool for_gather_matmul = tensor->ne[2] > 1;
472
473 int64_t n_elements = ggml_nelements(tensor);
474 const size_t alignment = 64; // Good for SIMD
475
476 if (tensor->type == GGML_TYPE_MXFP4 && (tensor->ne[2] > 1 || tensor->ne[3] > 1)) {
477 layout.weights_per_block = 32;
478 layout.is_symmetric = true;
479 layout.weights_size = ggml_nbytes(tensor);
480 layout.weights_offset = 0;
481 layout.total_size = layout.weights_size;
482 return layout;
483 }
484
485 // Check if requantization is needed (NPU-specific)
486 auto requant_type = ggml_openvino_get_requant_type(tensor, use_bias);
487 if (requant_type.has_value()) {
488 layout.is_requant = true;
489 layout.requant_type = requant_type;
490
491 // Special case: requant to F16 - just store F16 weights, no scales/zp
492 if (requant_type.value() == ExtraQuantType::F16) {
493 layout.weights_size = n_elements * sizeof(uint16_t); // F16 = 2 bytes
494 layout.total_size = layout.weights_size;
495 layout.weights_offset = 0;
496 // No scales/zp for F16
497 return layout;
498 }
499
500 // Requant to different quantized format (e.g., Q4_0_128)
501 switch (requant_type.value()) {
502 case ExtraQuantType::Q4_0_128:
503 layout.is_u4 = true;
504 layout.weights_per_block = 128;
505 layout.is_symmetric = true;
506 break;
507 case ExtraQuantType::Q4_1_64:
508 layout.is_u4 = true;
509 layout.weights_per_block = 64;
510 layout.is_symmetric = false;
511 break;
512 case ExtraQuantType::Q4_0_64:
513 layout.is_u4 = true;
514 layout.weights_per_block = 64;
515 layout.is_symmetric = true;
516 break;
517 case ExtraQuantType::Q4_0_C:
518 layout.is_u4 = true;
519 layout.weights_per_block = tensor->ne[0];
520 layout.is_symmetric = true;
521 break;
522 case ExtraQuantType::Q8_0_32:
523 layout.is_u4 = false;
524 layout.weights_per_block = 32;
525 layout.is_symmetric = true;
526 break;
527 case ExtraQuantType::Q8_0_C:
528 layout.is_u4 = false;
529 layout.weights_per_block = tensor->ne[0];
530 layout.is_symmetric = true;
531 break;
532 case ExtraQuantType::Q8_1_C:
533 layout.is_u4 = false;
534 layout.weights_per_block = tensor->ne[0];
535 break;
536 default:
537 GGML_ABORT("Code of re-quantizing to channel-wise is not updated");
538 }
539
540 if (layout.is_requant) {
541 // Calculate sizes for requantized format
542 layout.weights_size = layout.is_u4 ? (n_elements / 2) : n_elements;
543 int64_t n_blocks = n_elements / layout.weights_per_block;
544 layout.scales_size = n_blocks * sizeof(uint16_t);
545 // For symmetric quantization, no zp needed (weights stored as signed)
546 if (layout.is_symmetric) {
547 layout.zp_size = 0;
548 } else {
549 layout.zp_size = layout.is_u4 ? ((n_blocks + 1) / 2) : n_blocks;
550 }
551
552 layout.weights_offset = 0;
553 layout.scales_offset = ((layout.weights_size + alignment - 1) / alignment) * alignment;
554 layout.zp_offset = layout.scales_offset + ((layout.scales_size + alignment - 1) / alignment) * alignment;
555 layout.total_size = layout.zp_offset + layout.zp_size;
556 layout.total_size = std::max(layout.total_size, ggml_nbytes(tensor));
557 return layout;
558 }
559 }
560
561 // Normal extraction (no requant) - determine format based on tensor type
562 layout.is_u4 = false;
563 layout.weights_per_block = 32;
564 layout.is_symmetric = false;
565
566 switch (tensor->type) {
567 case GGML_TYPE_MXFP4:
568 case GGML_TYPE_Q4_0:
569 layout.is_u4 = true;
570 layout.is_symmetric = true;
571 break;
572
573 case GGML_TYPE_Q4_1:
574 case GGML_TYPE_Q4_K:
575 layout.is_u4 = true;
576 break;
577
578 case GGML_TYPE_Q8_0:
579 layout.is_symmetric = true;
580 break;
581
582 case GGML_TYPE_Q5_1:
583 // u8 weights (5-bit values), asymmetric (scale + zero point)
584 break;
585
586 case GGML_TYPE_Q6_K:
587 layout.weights_per_block = 16;
588 layout.is_symmetric = true;
589 break;
590
591 case GGML_TYPE_Q5_K:
592 break;
593
594 default:
595 // Unsupported quantization type
596 return layout;
597 }
598
599 // Calculate sizes
600 // Weights: U4 = n_elements/2 bytes, U8 = n_elements bytes
601 layout.weights_size = layout.is_u4 ? (n_elements / 2) : n_elements;
602
603 // Scales: F16 per block, except MXFP4 which stores one E8M0 byte per block.
604 int64_t n_blocks = n_elements / layout.weights_per_block;
605 layout.scales_size = n_blocks * (tensor->type == GGML_TYPE_MXFP4 ? sizeof(uint8_t) : sizeof(uint16_t));
606 // For symmetric quantization, no zp needed (weights stored as signed). Asymmetric
607 // for_gather_matmul (3D MoE expert) weights use an exact f16 zero point (see
608 // extract_quantized_weights/make_int8_weights/make_int4_weights), which needs one f16 per
609 // block instead of a packed u4/u8 integer zero point.
610 if (layout.is_symmetric) {
611 layout.zp_size = 0;
612 } else if (use_bias || for_gather_matmul) {
613 layout.zp_size = n_blocks * sizeof(uint16_t);
614 } else {
615 layout.zp_size = layout.is_u4 ? ((n_blocks + 1) / 2) : n_blocks;
616 }
617
618 // Layout in buffer: [weights | scales | zp] with alignment
619 layout.weights_offset = 0;
620 layout.scales_offset = ((layout.weights_size + alignment - 1) / alignment) * alignment;
621 layout.zp_offset = layout.scales_offset + ((layout.scales_size + alignment - 1) / alignment) * alignment;
622 layout.total_size = layout.zp_offset + layout.zp_size;
623 layout.total_size = std::max(layout.total_size, ggml_nbytes(tensor));
624
625 return layout;
626}
627
628ggml_openvino_tensor_extra * ggml_openvino_create_tensor_extra(const ggml_tensor * tensor, bool is_remote) {
629 ov::Shape shape;
630 for (int i = GGML_MAX_DIMS - 1; i >= 0; --i) {
631 shape.push_back(static_cast<size_t>(tensor->ne[i]));
632 }
633
634 ov::element::Type element_type;
635 switch (tensor->type) {
636 case GGML_TYPE_F32:
637 element_type = ov::element::f32;
638 break;
639 case GGML_TYPE_F16:
640 element_type = ov::element::f16;
641 break;
642 case GGML_TYPE_BF16:
643 element_type = ov::element::bf16;
644 break;
645 case GGML_TYPE_I32:
646 element_type = ov::element::i32;
647 break;
648 case GGML_TYPE_I64:
649 element_type = ov::element::i64;
650 break;
651 default:
652 // GGML_LOG_WARN("%s: unsupported tensor type for ov::Tensor: %s\n", __func__, ggml_type_name(tensor->type));
653 return nullptr;
654 }
655
656 auto remote_context = ggml_openvino_get_remote_context();
657
658 std::shared_ptr<ov::Tensor> ov_tensor;
659 if (is_remote) {
660 GGML_ASSERT(ggml_openvino_is_gpu());
661 auto gpu_context = remote_context->as<ov::intel_gpu::ocl::ClContext>();
662 auto usm_tensor = gpu_context.create_tensor(element_type, shape, tensor->data);
663 ov_tensor = std::make_shared<ov::intel_gpu::ocl::USMTensor>(std::move(usm_tensor));
664 } else {
665 ov_tensor = std::make_shared<ov::Tensor>(element_type, shape, tensor->data);
666 }
667
668 return new ggml_openvino_tensor_extra(ov_tensor);
669}