okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-140' into f-140-j0fff115df

main
1.9 KiB40 linesraw
1// dequantize_q5_1 (strata/artifact/dequant.hpp: the PLE table of a Q5_1 GGUF) against ggml's dequantize_row_q5_1,
2// on synthetic blocks: random codes, high bits and scales, plus the edge codes 0 and 31 and a negative minimum.
3// No model, no GPU.
4#include "strata/artifact/dequant.hpp"
5#include "ggml.h"
6
7#include <cmath>
8#include <cstdint>
9#include <cstdio>
10#include <cstring>
11#include <random>
12#include <vector>
13
14int main() {
15    constexpr int kBlocks = 4096;
16    constexpr int kBlockBytes = 24;
17    std::mt19937 rng(20261002);
18    std::uniform_int_distribution<int> byte(0, 255);
19    std::uniform_real_distribution<float> scale(-0.05f, 0.05f);
20    std::vector<uint8_t> blocks((size_t) kBlocks * kBlockBytes);
21    for (int b = 0; b < kBlocks; ++b) {
22        uint8_t* blk = blocks.data() + (size_t) b * kBlockBytes;
23        const ggml_fp16_t d = ggml_fp32_to_fp16(scale(rng));
24        const ggml_fp16_t m = ggml_fp32_to_fp16(b == 1 ? -1.5f : scale(rng) * 20.0f);
25        std::memcpy(blk, &d, 2);
26        std::memcpy(blk + 2, &m, 2);
27        for (int i = 4; i < kBlockBytes; ++i) blk[i] = (uint8_t) byte(rng);
28        if (b == 0) std::memset(blk + 4, 0x00, 20);   // every code 0: the value is m
29        if (b == 1) std::memset(blk + 4, 0xFF, 20);   // every code 31 (all high bits set)
30    }
31    const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_1);
32    std::vector<float> want((size_t) kBlocks * 32), got((size_t) kBlocks * 32);
33    traits->to_float(blocks.data(), want.data(), (int64_t) want.size());
34    for (int b = 0; b < kBlocks; ++b) strata::dequantize_q5_1(blocks.data() + (size_t) b * kBlockBytes, got.data() + b * 32);
35    double max_abs = 0.0;
36    for (size_t i = 0; i < want.size(); ++i) max_abs = std::fmax(max_abs, std::fabs((double) got[i] - want[i]));
37    const bool ok = max_abs <= 1e-6;
38    std::printf("Q5_1 dequant: %d blocks, max_abs %.3e %s\n", kBlocks, max_abs, ok ? "PASS" : "FAIL");
39    return ok ? 0 : 1;
40}