Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

48.6 KB
Raw Blame
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//

#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <limits>
#include <memory>
#include <numeric>
#include <sstream>
#include <utility>

#include "gguf.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/core/type/element_type_traits.hpp"
#include "weights.hpp"

namespace ov::frontend::gguf {

using namespace std;

// K-quant 256-element super-block byte sizes (ggml layout), used by fill_* / dequant_row_* / requant.
static constexpr uint64_t kQ4K_BLOCK_BYTES = 2 + 2 + 12 + 128;       // d + dmin + 12 scales + 128 ql
static constexpr uint64_t kQ5K_BLOCK_BYTES = 2 + 2 + 12 + 32 + 128;  // Q4_K + 32 qh
static constexpr uint64_t kQ6K_BLOCK_BYTES = 128 + 64 + 16 + 2;      // ql + qh + 16 scales + d

// Round a fractional zero-point to u8, clamping to avoid a modulo-256 wrap when min/scale > 255.
static inline uint8_t quantize_zp_u8(float zpval) {
    OPENVINO_ASSERT(std::isfinite(zpval), "[GGUF] cannot quantize a non-finite zero-point");
    long r = std::lround(zpval);
    return static_cast<uint8_t>(std::clamp(r, 0L, 255L));
}

// A block's zero-point in quantized units: its affine offset divided by its scale. A zero scale
// means every value in the block is the same, so any zero-point reconstructs it.
static inline float zp_from_offset(float offset, float scale) {
    return (scale != 0.f) ? (offset / scale) : 0.f;
}

// 6-bit packed sub-scale/min extraction for K-quants (Q4_K/Q5_K 12-byte scale block).
static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t* d, uint8_t* m) {
    if (j < 4) {
        *d = q[j] & 63;
        *m = q[j + 4] & 63;
    } else {
        *d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
        *m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
    }
}

// Writes per-block zero-points in whichever representation the destination tensor selected:
//   - u8  -> INTEGER zp: keeps the dequant in the low-precision form the CPU plugin fuses into
//            the MatMul (matches the original ggml-openvino backend).
//   - f16 -> FRACTIONAL zp: numerically faithful, used on the requant path where the dequant is
//            consumed by channel-wise Q8_0_C rather than fed to the compressed MatMul.
// See fill_q4_k for the full rationale.
class ZeroPointWriter {
public:
    explicit ZeroPointWriter(ov::Tensor& zp_arr) : m_integer(zp_arr.get_element_type() == ov::element::u8) {
        if (m_integer) {
            m_u8 = static_cast<uint8_t*>(zp_arr.data());
        } else {
            m_f16 = zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
        }
    }

    bool is_integer() const {
        return m_integer;
    }

    void store(size_t idx, float zpval) const {
        if (m_integer) {
            m_u8[idx] = quantize_zp_u8(zpval);
        } else {
            m_f16[idx] = ov::float16(zpval);
        }
    }

    // Store an already-integral zero-point produced by a requantization.
    void store_integer(size_t idx, uint8_t zpval) const {
        OPENVINO_ASSERT(m_integer, "[GGUF] integer zero-point written to a fractional zero-point tensor");
        m_u8[idx] = zpval;
    }

private:
    bool m_integer;
    uint8_t* m_u8 = nullptr;
    ov::element_type_traits<ov::element::f16>::value_type* m_f16 = nullptr;
};

// Quantize one row to Q8_0_C: a single channel-wise f16 scale (amax/127) plus signed int8
// weights. Shared by every requant source so the rounding and the zero-row rule live in one
// place.
void quantize_row_q8_0_c(const float* x, size_t cols, int8_t* out_weights, ov::float16& out_scale) {
    float amax = 0.0f;
    for (size_t c = 0; c < cols; ++c) {
        amax = std::max(amax, std::fabs(x[c]));
    }
    if (amax == 0.0f) {
        out_scale = ov::float16(0.0f);
        std::fill_n(out_weights, cols, int8_t{0});
        return;
    }
    const float d = amax / 127.0f;
    out_scale = ov::float16(d);
    if (d < std::numeric_limits<float>::min()) {
        // Avoid an underflowed scale or overflowing reciprocal for tiny nonzero rows.
        const double id = 127.0 / static_cast<double>(amax);
        for (size_t c = 0; c < cols; ++c) {
            out_weights[c] = static_cast<int8_t>(std::lround(static_cast<double>(x[c]) * id));
        }
        return;
    }
    const float id = 1.0f / d;
    for (size_t c = 0; c < cols; ++c) {
        out_weights[c] = static_cast<int8_t>(std::lround(x[c] * id));
    }
}

void unpack_32_4(const uint8_t* data, uint8_t* dst) {
    std::fill_n(dst, 16, 0);
    for (int j = 0; j < 16; ++j) {
        uint8_t x = (data[j] & 0x0F);
        uint8_t y = (data[j] >> 4);
        if (j % 2 != 0) {
            x <<= 4;
            y <<= 4;
        }
        dst[j / 2] |= x;
        dst[8 + j / 2] |= y;  // Last 16 weights are in the higher bits
    }
}

// Q5_0/Q5_1 block body: |32-bit qh|16 bytes ql (32x4bit low)|. weight = lo | (hi << 4) in
// [0..31]; `bias` centers it (-16 for Q5_0's symmetric layout, 0 for Q5_1's raw asymmetric one).
static inline void unpack_q5_block(const uint8_t* qh_ql, int8_t* dst, int bias) {
    uint32_t qh;
    std::memcpy(&qh, qh_ql, sizeof(qh));
    const uint8_t* ql = qh_ql + 4;
    for (uint64_t j = 0; j < 32; ++j) {
        const uint8_t lo = (j < 16) ? (ql[j] & 0x0F) : (ql[j - 16] >> 4);
        const uint8_t hi = (qh >> j) & 1;
        dst[j] = static_cast<int8_t>((lo | (hi << 4)) + bias);
    }
}

// Requantize one 32-value group with source values sc * source_q[k] - offset (source_q in
// [0..15]) onto a NEW u4 grid with an integer zero-point, and pack it as 16 bytes of nibbles.
// The algorithm follows NNCF's data-free INT4_ASYM baseline (range includes zero, min/max scale,
// integral clipped zp), followed by one cheap least-squares scale refinement. Candidate errors
// are evaluated with the actually stored f16 scale. A candidate is used only when it reduces
// squared error without increasing the maximum error versus the rounded-zp representation of
// the source nibbles.
static void requantize_group_u4(const uint8_t* source_q,
                                float sc,
                                float offset,
                                ov::float16& out_scale,
                                uint8_t& out_zp,
                                uint8_t* out_packed) {
    float values[32];
    float min_value = 0.0f;
    float max_value = 0.0f;
    for (int k = 0; k < 32; ++k) {
        values[k] = sc * static_cast<float>(source_q[k]) - offset;
        min_value = std::min(min_value, values[k]);
        max_value = std::max(max_value, values[k]);
    }

    struct Error {
        double squared;
        float max_abs;
    };
    const auto measure = [&](float runtime_scale, uint8_t zp, const uint8_t* quantized) {
        Error error{0.0, 0.0f};
        for (int k = 0; k < 32; ++k) {
            const float diff = values[k] - runtime_scale * (static_cast<int>(quantized[k]) - zp);
            error.squared += static_cast<double>(diff) * diff;
            error.max_abs = std::max(error.max_abs, std::fabs(diff));
        }
        return error;
    };

    // Start from the previous compressed-FC representation. Requantization must not
    // regress either its total error or its worst reconstructed value.
    uint8_t best_q[32];
    std::copy_n(source_q, 32, best_q);
    ov::float16 best_scale(sc);
    uint8_t best_zp = quantize_zp_u8(zp_from_offset(offset, sc));
    Error best_error = measure(static_cast<float>(best_scale), best_zp, best_q);
    const float fallback_max_error = best_error.max_abs;

    float initial_scale = (max_value - min_value) / 15.0f;
    if (std::fabs(initial_scale) < std::numeric_limits<float>::epsilon()) {
        initial_scale = std::numeric_limits<float>::epsilon();
    }
    const auto rounded_zp = static_cast<long>(std::nearbyint(-min_value / initial_scale));
    const uint8_t zp = static_cast<uint8_t>(std::clamp(rounded_zp, 0L, 15L));

    const auto evaluate = [&](float scale_candidate, uint8_t* quantized) {
        const ov::float16 scale_f16(scale_candidate);
        const float runtime_scale = static_cast<float>(scale_f16);
        if (!(runtime_scale > 0.0f) || !std::isfinite(runtime_scale)) {
            return std::make_pair(
                scale_f16,
                Error{std::numeric_limits<double>::infinity(), std::numeric_limits<float>::infinity()});
        }
        for (int k = 0; k < 32; ++k) {
            const long rounded = static_cast<long>(std::nearbyint(values[k] / runtime_scale)) + zp;
            quantized[k] = static_cast<uint8_t>(std::clamp(rounded, 0L, 15L));
        }
        return std::make_pair(scale_f16, measure(runtime_scale, zp, quantized));
    };

    const auto accept = [&](const std::pair<ov::float16, Error>& candidate, const uint8_t* candidate_q) {
        const auto& [scale, error] = candidate;
        if (error.squared < best_error.squared && error.max_abs <= fallback_max_error) {
            best_scale = scale;
            best_zp = zp;
            best_error = error;
            std::copy_n(candidate_q, 32, best_q);
        }
    };

    uint8_t candidate_q[32];
    auto candidate = evaluate(initial_scale, candidate_q);
    accept(candidate, candidate_q);

    // With the min/max assignments fixed, this is the least-squares optimal scale for
    // x ~= scale * (q-zp). Requantize once more with it and retain it only if the actual
    // f16-scale reconstruction improves both criteria versus the retained representation.
    double numerator = 0.0;
    double denominator = 0.0;
    for (int k = 0; k < 32; ++k) {
        const int centered = static_cast<int>(candidate_q[k]) - zp;
        numerator += static_cast<double>(values[k]) * centered;
        denominator += static_cast<double>(centered) * centered;
    }
    if (denominator != 0.0) {
        candidate = evaluate(static_cast<float>(numerator / denominator), candidate_q);
        accept(candidate, candidate_q);
    }

    out_scale = best_scale;
    out_zp = best_zp;
    std::fill_n(out_packed, 16, 0);
    for (int k = 0; k < 32; ++k) {
        out_packed[k / 2] |= static_cast<uint8_t>(best_q[k] << (4 * (k % 2)));
    }
}

// Q4_1 asymmetric: block = |f16 scale|f16 min|32x4bit weights|.
// Dequant w = sc*q + mn = sc*(q - zp), zp = -mn/sc.
// Outputs u32-packed u4 weights + f16 scales + zero-points (one per block). With a u8 zp the
// block is requantized to a new u4 grid with an integer zero-point, like Q4_K. Unlike Q4_K, a
// Q4_1 block need not contain zero, and a one-sided block then gets a coarser grid that does.
void fill_q4_1(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
    const uint64_t bytes_per_block = 20;  // 2 bytes scale, 2 bytes min, 32x0.5 byte weights
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<uint8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    const ZeroPointWriter zp(zp_arr);
    if (zp.is_integer()) {
        notify_lossy_weight_approximation(LossyWeightApproximation::Q4_REQUANT);
    }
    ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
        const uint8_t* block = data + i * bytes_per_block;
        const float sc = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block)));
        const float mn = static_cast<float>(ov::float16::from_bits(*((uint16_t*)(block + 2))));
        if (!zp.is_integer()) {
            scales[i] = ov::float16(sc);
            zp.store(i, zp_from_offset(-mn, sc));
            unpack_32_4(block + 4, weights + i * 16);
            return;
        }
        OPENVINO_ASSERT(std::isfinite(sc) && std::isfinite(mn),
                        "[GGUF] Q4_1 block ",
                        i,
                        " has non-finite scale metadata");
        uint8_t source_q[32];
        for (int k = 0; k < 16; ++k) {
            source_q[k] = block[4 + k] & 0x0F;
            source_q[k + 16] = block[4 + k] >> 4;
        }
        uint8_t zp_value = 0;
        requantize_group_u4(source_q, sc, -mn, scales[i], zp_value, weights + i * 16);
        zp.store_integer(i, zp_value);
    });
}

// Q8_0 symmetric: block = |f16 scale|32x i8 weights|. Weights are stored as i8 on disk.
// No zero-point. Output: i8 weights (direct copy) + f16 scales.
void fill_q8_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {
    const uint64_t weights_per_block = 32;
    const uint64_t bytes_per_block = 34;  // 2 bytes scale, 32x1 byte weights (i8)
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<int8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
        const uint8_t* block_data = data + i * bytes_per_block;
        scales[i] = ov::float16::from_bits(*(uint16_t*)block_data);
        std::memcpy(weights + i * weights_per_block, block_data + 2, weights_per_block);
    });
}

void fill_q8_1(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {
    constexpr size_t weights_per_block = 32;
    constexpr size_t bytes_per_block = 36;
    OPENVINO_ASSERT(tensor.num_weights % weights_per_block == 0 && weights_arr.get_size() == tensor.num_weights &&
                        scales_arr.get_size() == tensor.num_weights / weights_per_block,
                    "[GGUF] invalid Q8_1 output sizes");
    OPENVINO_ASSERT(tensor.bsize % bytes_per_block == 0 && tensor.bsize / bytes_per_block == scales_arr.get_size(),
                    "[GGUF] invalid Q8_1 payload size");
    const auto* data = static_cast<const uint8_t*>(tensor.weights_data);
    auto* weights = weights_arr.data<int8_t>();
    auto* scales = scales_arr.data<ov::float16>();
    ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
        const auto* block = data + i * bytes_per_block;
        uint16_t scale_bits;
        std::memcpy(&scale_bits, block, sizeof(scale_bits));
        scales[i] = ov::float16::from_bits(scale_bits);
        // The second F16 field is a dot-product sum, not a weight offset.
        std::memcpy(weights + i * weights_per_block, block + 4, weights_per_block);
    });
}

// Q5_0 symmetric: block = |f16 scale d|32-bit qh|16 bytes ql (32x4bit low)|.
// weight = lo|(hi<<4) in [0..31]; dequant = d*(w - 16). Output: i8 weights [-16..15].
void fill_q5_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {
    const uint64_t weights_per_block = 32;
    const uint64_t bytes_per_block = 2 + 4 + 16;
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<int8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
        const uint8_t* block_data = data + i * bytes_per_block;
        scales[i] = ov::float16::from_bits(*(uint16_t*)block_data);
        unpack_q5_block(block_data + 2, weights + i * weights_per_block, -16);
    });
}

void unpack_256_4(const uint8_t* data, uint8_t* dst) {
    // Initialize the output array with zeros
    std::fill_n(dst, 128, 0);

    for (size_t i = 0; i < 4; ++i) {
        for (int j = 0; j < 32; ++j) {
            uint8_t x = (data[i * 32 + j] & 0x0F);
            uint8_t y = (data[i * 32 + j] >> 4);
            if (j % 2 != 0) {
                x <<= 4;
                y <<= 4;
            }
            dst[i * 32 + j / 2] |= x;
            dst[i * 32 + 16 + j / 2] |= y;  // Last 16 weights are in the higher bits
        }
    }
}

// Q4_K asymmetric: super-block = |f16 d|f16 dmin|12 bytes scales/mins|128 bytes ql|.
// 8 sub-blocks of 32 with 6-bit scale and 6-bit min each.
// Outputs: u32-packed u4 weights + f16 scales + zp (one per sub-block).
// Dequant is w = scale*q - min, scale = d*sc_raw, min = dmin*m_raw.
//
// With an f16 zp, preserve the source nibbles and express the exact affine offset as min/scale.
// With a u8 zp, faithfully decode one 32-value group to f32 and requantize it to a NEW u4 grid
// (see requantize_group_u4). Only 32 f32 values are live per worker.
void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
    const uint64_t bytes_per_block = kQ4K_BLOCK_BYTES;
    const uint64_t n_super_block = tensor.bsize / bytes_per_block;
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<uint8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    const ZeroPointWriter zp_out(zp_arr);
    if (zp_out.is_integer()) {
        // An integer zero-point means this tensor is being requantized onto a new u4 grid below.
        notify_lossy_weight_approximation(LossyWeightApproximation::Q4_REQUANT);
    }

    ov::parallel_for(n_super_block, [&](size_t i) {
        const uint8_t* block_data = data + i * bytes_per_block;
        const float d = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data)));
        const float dmin = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data + 1)));
        OPENVINO_ASSERT(std::isfinite(d) && std::isfinite(dmin),
                        "[GGUF] Q4_K block ",
                        i,
                        " has non-finite scale metadata");
        const uint8_t* qs1 = block_data + 4;

        for (int j = 0; j < 8; ++j) {
            // 8 sub-blocks: 6-bit scale and 6-bit min packed in 12 bytes.
            uint8_t sc_raw, m_raw;
            get_scale_min_k4(j, qs1, &sc_raw, &m_raw);
            const float sc = d * sc_raw;
            const float mn = dmin * m_raw;
            if (!zp_out.is_integer()) {
                scales[i * 8 + j] = ov::float16(sc);
                zp_out.store(i * 8 + j, zp_from_offset(mn, sc));
                continue;
            }

            uint8_t source_q[32];
            const uint8_t* source = block_data + 16 + (j / 2) * 32;
            for (int k = 0; k < 32; ++k) {
                source_q[k] = (j % 2 == 0) ? (source[k] & 0x0F) : (source[k] >> 4);
            }
            uint8_t zp_value = 0;
            requantize_group_u4(source_q, sc, mn, scales[i * 8 + j], zp_value, weights + i * 128 + j * 16);
            zp_out.store_integer(i * 8 + j, zp_value);
        }
        if (!zp_out.is_integer()) {
            unpack_256_4(block_data + 16, weights + i * 128);
        }
    });
}

// ---------------------------------------------------------------------------------------------
// Bit-exact per-row K-quant dequant used ONLY as the source for the Q8_0_C requant of the
// token_embd/output/Q6_K/Q5_K tensors (see requantize_q8_0_channelwise_faithful). These are verbatim
// ports of ggml's dequantize_row_q{4,5,6}_K: they compute w = (d*sc)*q - (dmin*m) with the products
// kept in f32 (d/dmin are the f16 super-block scales widened to f32), matching what the upstream
// backend feeds into its Q8_0_C requant. This is NOT the general dequant path -- the compressed
// matmul weights still go through fill_*/make_int4 unchanged. Each function
// fills ONE row (`cols` floats) so the caller never materializes the whole f32 weight.
// Q4_K and Q5_K share this layout exactly; Q5_K only adds a fifth bit per value, taken from a
// 32-byte qh section that sits between the scales and the nibbles.
template <bool HAS_QH>
static void dequant_row_q45_k_f32(const uint8_t* row, size_t cols, float* y) {
    constexpr uint64_t bpb = HAS_QH ? kQ5K_BLOCK_BYTES : kQ4K_BLOCK_BYTES;
    for (size_t b = 0; b < cols / 256; ++b, y += 256) {
        const uint8_t* blk = row + b * bpb;
        const float d = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk)));
        const float dmin = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk + 1)));
        const uint8_t* sc = blk + 4;
        const uint8_t* qh = blk + 16;
        const uint8_t* ql = HAS_QH ? blk + 48 : blk + 16;
        int is = 0;
        uint8_t u1 = 1, u2 = 2;
        float* yy = y;
        for (int j = 0; j < 256; j += 64) {
            uint8_t s1, m1, s2, m2;
            get_scale_min_k4(is + 0, sc, &s1, &m1);
            get_scale_min_k4(is + 1, sc, &s2, &m2);
            const float d1 = d * s1, mn1 = dmin * m1, d2 = d * s2, mn2 = dmin * m2;
            for (int l = 0; l < 32; ++l) {
                const int hi = (HAS_QH && (qh[l] & u1)) ? 16 : 0;
                yy[l] = d1 * static_cast<float>((ql[l] & 0xF) + hi) - mn1;
            }
            for (int l = 0; l < 32; ++l) {
                const int hi = (HAS_QH && (qh[l] & u2)) ? 16 : 0;
                yy[32 + l] = d2 * static_cast<float>((ql[l] >> 4) + hi) - mn2;
            }
            ql += 32;
            is += 2;
            u1 <<= 2;
            u2 <<= 2;
            yy += 64;
        }
    }
}

static void dequant_row_q6_k_f32(const uint8_t* row, size_t cols, float* y) {
    const uint64_t bpb = kQ6K_BLOCK_BYTES;  // ql(128) + qh(64) + scales(16) + d(2)
    for (size_t b = 0; b < cols / 256; ++b, y += 256) {
        const uint8_t* blk = row + b * bpb;
        const uint8_t* ql = blk;
        const uint8_t* qh = blk + 128;
        const int8_t* sc = reinterpret_cast<const int8_t*>(blk + 192);
        const float d = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)(blk + 208))));
        float* yy = y;
        for (int n = 0; n < 256; n += 128) {
            for (int l = 0; l < 32; ++l) {
                const int is = l / 16;
                const int8_t q1 = (int8_t)((ql[l + 0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32;
                const int8_t q2 = (int8_t)((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32;
                const int8_t q3 = (int8_t)((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32;
                const int8_t q4 = (int8_t)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32;
                yy[l + 0] = d * sc[is + 0] * q1;
                yy[l + 32] = d * sc[is + 2] * q2;
                yy[l + 64] = d * sc[is + 4] * q3;
                yy[l + 96] = d * sc[is + 6] * q4;
            }
            yy += 128;
            ql += 64;
            qh += 32;
            sc += 8;
        }
    }
}

void gguf_fill_q5_k_i8(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales) {
    constexpr size_t group_size = 32;
    OPENVINO_ASSERT(tensor.type == GGUF_TYPE_Q5_K, "[GGUF] invalid Q5_K symmetric requantization group");
    OPENVINO_ASSERT(tensor.num_weights % 256 == 0 && tensor.bsize / kQ5K_BLOCK_BYTES == tensor.num_weights / 256 &&
                        tensor.bsize % kQ5K_BLOCK_BYTES == 0,
                    "[GGUF] invalid Q5_K symmetric requantization payload");
    OPENVINO_ASSERT(weights.get_element_type() == ov::element::i8 && weights.get_size() == tensor.num_weights &&
                        scales.get_element_type() == ov::element::f16 &&
                        scales.get_size() == tensor.num_weights / group_size,
                    "[GGUF] invalid Q5_K symmetric requantization buffers");
    auto* dst = weights.data<int8_t>();
    auto* scale_data = scales.data<ov::float16>();
    ov::parallel_for(tensor.num_weights / 256, [&](size_t block) {
        std::array<float, 256> values;
        dequant_row_q45_k_f32<true>(tensor.weights_data + block * kQ5K_BLOCK_BYTES, 256, values.data());
        for (size_t offset = 0; offset < 256; offset += group_size) {
            float amax = 0.0f;
            for (size_t k = offset; k < offset + group_size; ++k) {
                OPENVINO_ASSERT(std::isfinite(values[k]), "[GGUF] cannot requantize non-finite Q5_K values");
                amax = std::max(amax, std::fabs(values[k]));
            }
            const ov::float16 scale_f16(amax / 127.0f);
            const float scale = static_cast<float>(scale_f16);
            OPENVINO_ASSERT(std::isfinite(scale), "[GGUF] Q5_K symmetric scale exceeds f16 range");
            scale_data[(block * 256 + offset) / group_size] = scale_f16;
            for (size_t k = offset; k < offset + group_size; ++k) {
                const float code = scale > 0.0f ? std::round(values[k] / scale) : 0.0f;
                dst[block * 256 + k] = static_cast<int8_t>(std::clamp(code, -127.0f, 127.0f));
            }
        }
    });
    if (tensor.num_weights != 0) {
        notify_lossy_weight_approximation(LossyWeightApproximation::Q5_K_SYMMETRIC_REQUANT);
    }
}

// Fused faithful dequant + channel-wise Q8_0_C requant, streaming one row at a time so the full f32
// weight is never materialized (holds only `cols` floats). Fills i8 weights [rows,cols] + f16 scales
// [rows,1], matching the upstream Q8_0_C path (amax/127 per row, roundf). qtype selects the exact
// ggml row dequant. Returns false if qtype is not a supported requant source.
bool requantize_q8_0_channelwise_faithful(const GgufTensor& tensor,
                                          size_t rows,
                                          size_t cols,
                                          GgufTensorType qtype,
                                          int8_t* out_weights,
                                          ov::float16* out_scales) {
    void (*dq)(const uint8_t*, size_t, float*) = nullptr;
    uint64_t bytes_per_row = 0;
    switch (qtype) {
    case GGUF_TYPE_Q4_K:
        dq = dequant_row_q45_k_f32<false>;
        bytes_per_row = (cols / 256) * kQ4K_BLOCK_BYTES;
        break;
    case GGUF_TYPE_Q5_K:
        dq = dequant_row_q45_k_f32<true>;
        bytes_per_row = (cols / 256) * kQ5K_BLOCK_BYTES;
        break;
    case GGUF_TYPE_Q6_K:
        dq = dequant_row_q6_k_f32;
        bytes_per_row = (cols / 256) * kQ6K_BLOCK_BYTES;
        break;
    default:
        return false;
    }
    const uint8_t* data = static_cast<const uint8_t*>(tensor.weights_data);
    ov::parallel_for(rows, [&](size_t r) {
        // Reuse scratch across rows; capacity follows the largest row seen and is retained
        // until the worker thread exits. dq() overwrites all cols, avoiding per-row allocation.
        thread_local std::vector<float> rowf;
        rowf.resize(cols);
        dq(data + r * bytes_per_row, cols, rowf.data());
        quantize_row_q8_0_c(rowf.data(), cols, out_weights + r * cols, out_scales[r]);
    });
    return true;
}

// Test-only thin wrappers exposing the file-static per-row dequant to the unit tests.
void dequant_row_q4_k_f32_for_test(const uint8_t* row, size_t cols, float* y) {
    dequant_row_q45_k_f32<false>(row, cols, y);
}
void dequant_row_q5_k_f32_for_test(const uint8_t* row, size_t cols, float* y) {
    dequant_row_q45_k_f32<true>(row, cols, y);
}
void dequant_row_q6_k_f32_for_test(const uint8_t* row, size_t cols, float* y) {
    dequant_row_q6_k_f32(row, cols, y);
}

// Q5_K asymmetric: super-block = 2(d) + 2(dmin) + 12(scales) + 32(qh) + 128(ql).
// 8 sub-blocks of 32 with 6-bit scale and 6-bit min. Output: u8 weights + f16 scales + zp.
// Like Q4_K, dequant is w = scale*q - dmin*m; zp = dmin*m/scale. With an f16 zp the source
// 5-bit values [0..31] are kept as they are (faithful). With a u8 zp each 32-value group is
// decoded to f32 and requantized to a NEW 8-bit grid: min/max range including zero, integral
// zp. The 8-bit grid is ~8x finer than the 5-bit source, so the added error stays far below
// one source step, and the integer zp lets the dequant fold into a compressed FullyConnected.
void fill_q5_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
    const uint64_t bytes_per_block = kQ5K_BLOCK_BYTES;
    const uint64_t n_super_block = tensor.bsize / bytes_per_block;
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<uint8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    const ZeroPointWriter zp(zp_arr);
    if (zp.is_integer()) {
        notify_lossy_weight_approximation(LossyWeightApproximation::Q5_K_REQUANT);
    }

    // Store one 32-value group whose source values are q[k] in [0..31], w = d1*q - m1.
    const auto store_group =
        [&](size_t group, float d1, float m1, float source_min_scale, const uint8_t* q, uint8_t* dst) {
            if (!zp.is_integer()) {
                if (d1 == 0.f && m1 != 0.f) {
                    const float scale = std::fabs(source_min_scale);
                    scales[group] = ov::float16(scale);
                    zp.store(group, m1 / scale);
                    std::fill_n(dst, 32, 0);
                    return;
                }
                scales[group] = ov::float16(d1);
                zp.store(group, zp_from_offset(m1, d1));
                std::copy_n(q, 32, dst);
                return;
            }
            float values[32];
            float lo = 0.0f, hi = 0.0f;
            for (int k = 0; k < 32; ++k) {
                values[k] = d1 * static_cast<float>(q[k]) - m1;
                lo = std::min(lo, values[k]);
                hi = std::max(hi, values[k]);
            }
            const ov::float16 scale_f16((hi - lo) / 255.0f);
            const float scale = static_cast<float>(scale_f16);
            if (!(scale > 0.0f) || !std::isfinite(scale)) {
                // A (near-)zero range: every value rounds to zero.
                scales[group] = ov::float16(0.0f);
                zp.store_integer(group, 0);
                std::fill_n(dst, 32, 0);
                return;
            }
            const long zpi = std::clamp(std::lround(-lo / scale), 0L, 255L);
            scales[group] = scale_f16;
            zp.store_integer(group, static_cast<uint8_t>(zpi));
            for (int k = 0; k < 32; ++k) {
                dst[k] = static_cast<uint8_t>(std::clamp(std::lround(values[k] / scale) + zpi, 0L, 255L));
            }
        };

    ov::parallel_for(n_super_block, [&](size_t i) {
        const uint8_t* block_data = data + i * bytes_per_block;
        const float d = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data)));
        const float dmin = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data + 1)));
        const uint8_t* scales_data = block_data + 4;
        const uint8_t* qh = block_data + 16;  // 32 bytes high bits
        const uint8_t* ql = block_data + 48;  // 128 bytes low bits

        int is = 0;
        uint8_t u1 = 1, u2 = 2;
        for (int j = 0; j < 256; j += 64) {
            uint8_t sc, m;
            get_scale_min_k4(is + 0, scales_data, &sc, &m);
            const float d1 = d * sc, m1 = dmin * m;
            get_scale_min_k4(is + 1, scales_data, &sc, &m);
            const float d2 = d * sc, m2 = dmin * m;
            uint8_t q1[32], q2[32];
            for (int l = 0; l < 32; ++l) {
                q1[l] = static_cast<uint8_t>((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0));
                q2[l] = static_cast<uint8_t>((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0));
            }
            store_group(i * 8 + is, d1, m1, dmin, q1, weights + i * 256 + j);
            store_group(i * 8 + is + 1, d2, m2, dmin, q2, weights + i * 256 + j + 32);
            ql += 32;
            is += 2;
            u1 <<= 2;
            u2 <<= 2;
        }
    });
}

// Q5_1 asymmetric: block = |f16 d|f16 m|32-bit qh|16 bytes ql (32x4bit low)|.
// weight = lo|(hi<<4) in [0..31]; dequant = d*w + m = d*(w - zp), zp = -m/d.
// Output: i8 weights [0..31] (raw, not centered) + f16 scales + zp (u8 integer or f16
// fractional per element type -- see fill_q4_k).
void fill_q5_1(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
    const uint64_t weights_per_block = 32;
    const uint64_t bytes_per_block = 2 + 2 + 4 + 16;  // d, m, qh, ql
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<int8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    const ZeroPointWriter zp(zp_arr);
    ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
        const uint8_t* block = data + i * bytes_per_block;
        const float d = static_cast<float>(ov::float16::from_bits(*(uint16_t*)block));
        const float m = static_cast<float>(ov::float16::from_bits(*(uint16_t*)(block + 2)));
        scales[i] = ov::float16(d);
        zp.store(i, zp_from_offset(-m, d));
        unpack_q5_block(block + 4, weights + i * weights_per_block, 0);
    });
}

// Q3_K symmetric: super-block = 32(hmask) + 64(qs) + 12(scales 6-bit) + 2(f16 d) = 110 bytes.
// 16 sub-blocks of 16; 3-bit values (2 low bits from qs, 1 inverted high bit from hmask) centered
// to [-4..3]. Mirrors ggml dequantize_row_q3_K: kmask1/kmask2 scale interleave + strided qs order.
// Output: i4 weights (2 per byte, low nibble first) + f16 scales (d * (scale6 - 32)). No zp.
void fill_q3_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {
    const uint64_t bytes_per_block = 32 + 64 + 12 + 2;  // 110
    const uint64_t n_super_block = tensor.bsize / bytes_per_block;
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<uint8_t*>(weights_arr.data());  // packed i4 nibbles
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    ov::parallel_for(n_super_block, [&](size_t i) {
        const uint8_t* block = data + i * bytes_per_block;
        const uint8_t* hmask = block;         // 32 bytes: 1 high bit per weight
        const uint8_t* qs = block + 32;       // 64 bytes: 2 low bits per weight
        const uint8_t* sc = block + 32 + 64;  // 12 bytes: 16 x 6-bit sub-scales
        const float d = static_cast<float>(ov::float16::from_bits(*(uint16_t*)(block + 32 + 64 + 12)));

        // 16 signed 6-bit sub-scales, interleaved as in ggml dequantize_row_q3_K.
        constexpr uint32_t kmask1 = 0x03030303, kmask2 = 0x0f0f0f0f;
        uint32_t aux[4];
        std::memcpy(aux, sc, 12);
        const uint32_t tmp = aux[2];
        aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4);
        aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4);
        aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4);
        aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4);
        const int8_t* isc = reinterpret_cast<const int8_t*>(aux);
        for (int j = 0; j < 16; ++j) {
            scales[i * 16 + j] = ov::float16(d * static_cast<float>(isc[j] - 32));
        }

        // Unpack in ggml element order; the hmask bit is inverted (set means high bit 0).
        uint8_t* wdst = weights + i * 128;
        std::fill_n(wdst, 128, 0);
        size_t out = 0;
        const auto put = [&](int8_t c) {
            wdst[out / 2] |= static_cast<uint8_t>((static_cast<uint8_t>(c) & 0xF) << ((out % 2) * 4));
            ++out;
        };
        uint8_t m = 1;
        for (int n = 0; n < 2; ++n) {
            const uint8_t* q = qs + n * 32;
            for (int shift = 0; shift < 8; shift += 2) {
                for (int l = 0; l < 16; ++l)
                    put(static_cast<int8_t>(((q[l] >> shift) & 3) - ((hmask[l] & m) ? 0 : 4)));
                for (int l = 0; l < 16; ++l)
                    put(static_cast<int8_t>(((q[l + 16] >> shift) & 3) - ((hmask[l + 16] & m) ? 0 : 4)));
                m <<= 1;
            }
        }
    });
}

// Q2_K asymmetric: super-block = 16(scales 4+4 bit) + 64(qs) + 2(f16 d) + 2(f16 dmin) = 84 bytes,
// matching ggml block_q2_K (scales first, then qs). 16 sub-blocks of 16; 2-bit values [0..3],
// scales[j] lower nibble = sub-scale, upper nibble = sub-min. qs is not in element order, so unpack
// per element into element-order u2 (4 per byte, LSB-first) like ggml dequantize_row_q2_K.
// Output: u2 weights + f16 scales (d * sub_scale) + zp = ml/dl per sub-block (see fill_q4_k).
void fill_q2_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
    const uint64_t bytes_per_block = 16 + 64 + 2 + 2;  // 84
    const uint64_t n_super_block = tensor.bsize / bytes_per_block;
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<uint8_t*>(weights_arr.data());  // packed u2 (4 per byte, LSB-first)
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    const ZeroPointWriter zp(zp_arr);
    ov::parallel_for(n_super_block, [&](size_t i) {
        const uint8_t* block = data + i * bytes_per_block;
        const uint8_t* sc = block;       // 16 bytes: per-sub-block scale+min nibbles
        const uint8_t* qs = block + 16;  // 64 bytes: 4 weights per byte, 2 bits each
        const float d = static_cast<float>(ov::float16::from_bits(*(uint16_t*)(block + 80)));
        const float dmin = static_cast<float>(ov::float16::from_bits(*(uint16_t*)(block + 82)));
        for (int j = 0; j < 16; ++j) {
            const float dl = d * static_cast<float>(sc[j] & 0xF);
            const float ml = dmin * static_cast<float>(sc[j] >> 4);
            scales[i * 16 + j] = ov::float16(dl);
            zp.store(i * 16 + j, zp_from_offset(ml, dl));
        }
        // Unpack in ggml element order (see dequantize_row_q2_K).
        uint8_t* wdst = weights + i * 64;
        std::fill_n(wdst, 64, 0);
        size_t out = 0;
        const auto put = [&](uint8_t q2) {
            wdst[out / 4] |= static_cast<uint8_t>((q2 & 3) << ((out % 4) * 2));
            ++out;
        };
        for (int n = 0; n < 2; ++n) {
            const uint8_t* q = qs + n * 32;
            for (int shift = 0; shift < 8; shift += 2) {
                for (int l = 0; l < 16; ++l)
                    put((q[l] >> shift) & 3);
                for (int l = 0; l < 16; ++l)
                    put((q[l + 16] >> shift) & 3);
            }
        }
    });
}

// Q6_K symmetric: super-block = 128(ql) + 64(qh) + 16(scales i8) + 2(f16 d).
// 16 sub-blocks of 16 with i8 scale each. Values in [0..63]; center = 32 → i8 [-32..31].
// Output: i8 weights (value - 32) + f16 scales. No zero-point.
void fill_q6_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {
    const uint64_t bytes_per_block = kQ6K_BLOCK_BYTES;
    const uint64_t n_super_block = tensor.bsize / bytes_per_block;
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<int8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    // Each super-block writes a disjoint 256-element region, so parallelize like the other fill_*
    // functions (Q6_K is used for the largest tensors -- output/embed -- so the serial loop left
    // most cores idle on the biggest weight in the model).
    ov::parallel_for(n_super_block, [&](size_t i) {
        const uint8_t* block_data = data + i * bytes_per_block;
        const float d = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data + 104)));  // (128+64+16)/2
        for (size_t j = 0; j < 16; j++) {
            scales[j + i * 16] = ov::float16(d * static_cast<float>(*((int8_t*)(block_data + 128 + 64 + j))));
        }
        const uint8_t* ql = block_data;
        const uint8_t* qh = block_data + 128;
        for (int64_t j = 0; j < 32; ++j) {
            weights[i * 256 + j] = static_cast<int8_t>(((ql[j] & 0xF) | (((qh[j] >> 0) & 3) << 4)) - 32);
            weights[i * 256 + j + 32] = static_cast<int8_t>(((ql[32 + j] & 0xF) | (((qh[j] >> 2) & 3) << 4)) - 32);
            weights[i * 256 + j + 64] = static_cast<int8_t>(((ql[j] >> 4) | (((qh[j] >> 4) & 3) << 4)) - 32);
            weights[i * 256 + j + 96] = static_cast<int8_t>(((ql[32 + j] >> 4) | (((qh[j] >> 6) & 3) << 4)) - 32);
            weights[i * 256 + j + 128] =
                static_cast<int8_t>(((ql[64 + j] & 0xF) | (((qh[32 + j] >> 0) & 3) << 4)) - 32);
            weights[i * 256 + j + 160] =
                static_cast<int8_t>(((ql[96 + j] & 0xF) | (((qh[32 + j] >> 2) & 3) << 4)) - 32);
            weights[i * 256 + j + 192] = static_cast<int8_t>(((ql[64 + j] >> 4) | (((qh[32 + j] >> 4) & 3) << 4)) - 32);
            weights[i * 256 + j + 224] = static_cast<int8_t>(((ql[96 + j] >> 4) | (((qh[32 + j] >> 6) & 3) << 4)) - 32);
        }
    });
}

// MXFP4 (gpt-oss): per-32 block = 1-byte E8M0 scale + 16 bytes of 4-bit E2M1 indices.
// On disk, within a block the low nibble of qs[j] is element j and the high nibble is
// element j+16. We deinterleave into NATURAL element order and store as two compressed
// OpenVINO Constants the CPU plugin handles natively: a f4e2m1 weight tensor [rows, cols]
// and an f8e8m0 scale tensor [rows, cols/32]. (No host dequant.)
//
// Value equivalence: gguf MXFP4 value = kvalues_mxfp4[idx] * 2^(e-128); OpenVINO's
// f4e2m1 LUT equals kvalues_mxfp4/2 and f8e8m0->f32 = 2^(e-127), so
//   f4e2m1[idx] * f8e8m0(e) = (kvalues/2) * 2^(e-127) = kvalues * 2^(e-128)  -- exact.
void gguf_fill_mxfp4(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales) {
    const uint64_t bytes_per_block = 17;
    const uint64_t qk = 32;
    // GGUF stores dims fastest-first: dim[0] is the innermost (cols); the remaining dims fold
    // into rows. (Equivalent to the OV-order shape [.., cols] the caller sets.)
    const uint64_t cols = tensor.dim[0];
    uint64_t rows = 1;
    for (uint32_t i = 1; i < tensor.ndim; ++i) {
        rows *= tensor.dim[i];
    }
    const uint64_t groups = cols / qk;

    auto* wdst = static_cast<uint8_t*>(weights.data());
    auto* sdst = static_cast<uint8_t*>(scales.data());
    const auto* data = static_cast<const uint8_t*>(tensor.weights_data);

    ov::parallel_for(rows, [&](size_t r) {
        for (uint64_t g = 0; g < groups; ++g) {
            const uint8_t* block = data + (r * groups + g) * bytes_per_block;
            sdst[r * groups + g] = block[0];
            const uint8_t* qs = block + 1;
            // `cols` and qk are both multiples of 32, so the block's first element index is even
            // and every output byte packs a known pair of source nibbles. Write whole bytes
            // rather than read-modify-writing each nibble: the low half of the block takes the
            // low nibbles of qs[2t], qs[2t+1], the high half their high nibbles.
            uint8_t* out = wdst + (r * cols + g * qk) / 2;
            for (uint64_t t = 0; t < qk / 4; ++t) {
                out[t] = static_cast<uint8_t>((qs[2 * t] & 0x0F) | ((qs[2 * t + 1] & 0x0F) << 4));
                out[qk / 4 + t] = static_cast<uint8_t>((qs[2 * t] >> 4) | (qs[2 * t + 1] & 0xF0));
            }
        }
    });
}

// Q4_0 symmetric: unpack each GGML block and XOR every packed byte with 0x88 to
// flip the MSB of every nibble, converting u4 [0..15] to i4 [-8..7] in-place. No bias
// tensor is produced (zp is exactly -8 * scale = a fixed shift, not per-element).
static void fill_q4_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {
    const uint64_t bytes_per_block = 18;
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<uint8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();

    ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
        scales[i] = ov::float16::from_bits(*((uint16_t*)(data + i * bytes_per_block)));
        unpack_32_4(data + i * bytes_per_block + 2, weights + i * 16);
        for (int b = 0; b < 16; ++b)
            weights[i * 16 + b] ^= 0x88;  // u4→i4: flip MSB of both nibbles per byte
    });
}

// GGML binary codes are LSB-first; OpenVINO u1 codes are MSB-first.
static void fill_q1_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {
    const uint64_t bytes_per_block = 18;
    const uint64_t out_bytes_per_block = 16;
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<uint8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();

    ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
        const uint8_t* block = data + i * bytes_per_block;
        uint16_t scale_bits;
        std::memcpy(&scale_bits, block, sizeof(scale_bits));
        scales[i] = ov::float16::from_bits(scale_bits);
        const uint8_t* qs = block + 2;
        uint8_t* out = weights + i * out_bytes_per_block;
        for (size_t j = 0; j < out_bytes_per_block; ++j) {
            uint8_t bits = qs[j];
            bits = ((bits & 0x55) << 1) | ((bits & 0xaa) >> 1);
            bits = ((bits & 0x33) << 2) | ((bits & 0xcc) >> 2);
            out[j] = (bits << 4) | (bits >> 4);
        }
    });
}

// Q8_K symmetric: block = |f32 d|i8 qs[256]|i16 bsums[16]| (292 bytes/block).
// bsums are partial sums for dot-product acceleration; unused in dequant-then-multiply.
void fill_q8_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {
    const uint64_t weights_per_block = 256;
    const uint64_t bytes_per_block = 292;  // 4(f32 d) + 256(i8) + 32(i16 bsums)
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<int8_t*>(weights_arr.data());
    auto scales = static_cast<float*>(scales_arr.data());
    ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
        const uint8_t* block = data + i * bytes_per_block;
        float d;
        std::memcpy(&d, block, sizeof(d));  // f32 scale
        scales[i] = d;
        std::memcpy(weights + i * weights_per_block, block + 4, weights_per_block);  // i8 qs
        // bsums at block+260 are ignored
    });
}

// Q2_0 ternary: block = |f16 d|u2 qs[64]| (18 bytes / 64 weights), value = (code - 1) * d with
// code in [0..3] -> {-1, 0, +1, +2}. ggml packs the codes 4 per byte LSB-first
// (dequantize_row_q2_0: `(qs[j/4] >> ((j%4)*2)) & 3`), which is exactly the order OpenVINO's u2
// Constant reads, so the 16 code bytes are copied verbatim. The zero-point is the constant 1.
void gguf_fill_q2_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
    const bool dense_trits = tensor.type == GGUF_TYPE_PTQ1_0;
    const uint64_t bytes_per_block_codes = tensor.type == GGUF_TYPE_Q2_0 ? 16 : 32;
    const uint64_t bytes_per_block = dense_trits ? 28 : bytes_per_block_codes + 2;
    auto data = static_cast<const uint8_t*>(tensor.weights_data);
    auto weights = static_cast<uint8_t*>(weights_arr.data());
    auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
    const ZeroPointWriter zp(zp_arr);

    ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
        const uint8_t* block = data + i * bytes_per_block;
        uint16_t scale_bits;
        std::memcpy(&scale_bits, block + (dense_trits ? 26 : 0), sizeof(scale_bits));
        scales[i] = ov::float16::from_bits(scale_bits);
        auto* codes = weights + i * bytes_per_block_codes;
        if (dense_trits) {
            std::memset(codes, 0, bytes_per_block_codes);
            constexpr uint8_t powers[] = {1, 3, 9, 27, 81};
            size_t index = 0;
            const auto unpack = [&](size_t start, size_t count, size_t trits) {
                for (size_t n = 0; n < trits; ++n) {
                    for (size_t m = 0; m < count; ++m) {
                        const uint8_t q = block[start + m] * powers[n];
                        const uint8_t code = (static_cast<uint16_t>(q) * 3) >> 8;
                        codes[index / 4] |= code << (2 * (index % 4));
                        ++index;
                    }
                }
            };
            unpack(0, 16, 5);
            unpack(16, 8, 5);
            unpack(24, 2, 4);
        } else {
            std::memcpy(codes, block + 2, bytes_per_block_codes);
        }
        zp.store(i, 1.0f);
    });
}

// Symmetric types (Q1_0, Q4_0, Q8_0, Q8_1, Q5_0, Q6_K, Q3_K): fill weights + scales (f16), no
// zero-point. Q8_K uses f32 scales and is handled by a separate overload dispatched on
// tensor.type.
void gguf_fill_sym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales) {
    switch (tensor.type) {
    case GGUF_TYPE_Q1_0:
        return fill_q1_0(tensor, weights, scales);
    case GGUF_TYPE_Q4_0:
        return fill_q4_0(tensor, weights, scales);
    case GGUF_TYPE_Q8_0:
        return fill_q8_0(tensor, weights, scales);
    case GGUF_TYPE_Q8_1:
        return fill_q8_1(tensor, weights, scales);
    case GGUF_TYPE_Q5_0:
        return fill_q5_0(tensor, weights, scales);
    case GGUF_TYPE_Q6_K:
        return fill_q6_k(tensor, weights, scales);
    case GGUF_TYPE_Q3_K:
        return fill_q3_k(tensor, weights, scales);
    case GGUF_TYPE_Q8_K:
        return fill_q8_k(tensor, weights, scales);
    default:
        OPENVINO_THROW("Unsupported tensor type in 'gguf_fill_sym': ", tensor.type);
    }
}

// Asymmetric types (Q4_1, Q4_K, Q5_K, Q5_1, Q2_K): fill weights, scales, and zero-points.
void gguf_fill_asym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales, ov::Tensor& zp) {
    switch (tensor.type) {
    case GGUF_TYPE_Q4_1:
        return fill_q4_1(tensor, weights, scales, zp);
    case GGUF_TYPE_Q4_K:
        return fill_q4_k(tensor, weights, scales, zp);
    case GGUF_TYPE_Q5_K:
        return fill_q5_k(tensor, weights, scales, zp);
    case GGUF_TYPE_Q5_1:
        return fill_q5_1(tensor, weights, scales, zp);
    case GGUF_TYPE_Q2_K:
        return fill_q2_k(tensor, weights, scales, zp);
    default:
        OPENVINO_THROW("Unsupported tensor type in 'gguf_fill_asym': ", tensor.type);
    }
}

}  // namespace ov::frontend::gguf