okami.mom/strata

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

Niko1221Merge f-own-5b 9b242bb5b into f-own-int (round 15: the own text encoder and tokenizer as test programs, the DiT reference tool and position tables; committed work only)11c8c701a

main
7.2 KiB170 linesraw
1// src/image/te/te_dequant_check_main.cpp - test program strata-te-dequant-check (not shipped): the device decoders of
2// include/strata/image/te_dequant.hpp against the host reference, bit for bit.
3//
4//   strata-te-dequant-check <file.gguf> [--max-tensors N]
5//   strata-te-dequant-check --synthetic
6//
7// With a file: every tensor of a supported type, decoded on the device and on the host, must give the same f16 bits;
8// prints per type the tensors, values and mismatches, and the device decode rate (GB of f16 written per second).
9// --synthetic: random blocks of every supported type (Q8_0, BF16 and F16 do not occur in the text encoder's file).
10// Exit 0 only when nothing differs.
11#include "strata/image/te_dequant.hpp"
12
13#define STRATA_GGUF_MAIN_DISABLED 1
14#include "strata/artifact/gguf_reader.hpp"
15#include "strata/kernels/f16_bits.hpp"
16
17#if defined(__HIP__) || defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__)
18#include "strata/hip_compat/cuda_runtime.h"
19#else
20#include <cuda_runtime.h>
21#endif
22
23#include <chrono>
24#include <cstdio>
25#include <cstring>
26#include <map>
27#include <random>
28#include <string>
29#include <vector>
30
31using namespace strata::image;
32
33namespace {
34
35struct Tally { int tensors = 0; uint64_t values = 0, mismatches = 0; double dev_s = 0; };
36
37bool check_one(uint32_t type, const uint8_t* raw, int64_t ne0, int64_t rows, Tally& t, std::string& err) {
38    const size_t rb = te_row_bytes(type, ne0);
39    const size_t n = (size_t) ne0 * (size_t) rows;
40    std::vector<uint16_t> host(n), dev(n);
41    err = te_dequant_f16_host(type, raw, ne0, rows, host.data());
42    if (!err.empty()) return false;
43    void* d_src = nullptr;
44    uint16_t* d_dst = nullptr;
45    if (cudaMalloc(&d_src, rb * rows) != cudaSuccess || cudaMalloc((void**) &d_dst, n * 2) != cudaSuccess) {
46        err = "cudaMalloc failed";
47        return false;
48    }
49    cudaMemcpy(d_src, raw, rb * rows, cudaMemcpyHostToDevice);
50    cudaDeviceSynchronize();
51    const auto t0 = std::chrono::steady_clock::now();
52    err = te_dequant_f16(type, d_src, ne0, rows, d_dst, nullptr);
53    cudaDeviceSynchronize();
54    t.dev_s += std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
55    if (err.empty()) {
56        const cudaError_t e = cudaMemcpy(dev.data(), d_dst, n * 2, cudaMemcpyDeviceToHost);
57        if (e != cudaSuccess) err = cudaGetErrorString(e);
58    }
59    cudaFree(d_src);
60    cudaFree(d_dst);
61    if (!err.empty()) return false;
62    uint64_t bad = 0;
63    for (size_t i = 0; i < n; ++i) {
64        if (host[i] != dev[i]) {
65            if (bad < 3)
66                std::fprintf(stderr, "  type %u value %zu: host %04x device %04x\n", type, i, host[i], dev[i]);
67            ++bad;
68        }
69    }
70    t.tensors++;
71    t.values += n;
72    t.mismatches += bad;
73    return true;
74}
75
76void put_f16(uint8_t* p, std::mt19937& rng) {
77    std::uniform_real_distribution<float> u(-0.02f, 0.02f);
78    const uint16_t h = strata::kernels::f16_from_f32(u(rng));
79    p[0] = (uint8_t) (h & 0xFF);
80    p[1] = (uint8_t) (h >> 8);
81}
82
83int synthetic() {
84    std::mt19937 rng(11);
85    std::map<uint32_t, Tally> tally;
86    const uint32_t types[] = {TE_Q4_K, TE_Q5_K, TE_Q6_K, TE_IQ4_XS, TE_Q8_0, TE_F32, TE_F16, TE_BF16};
87    const int64_t ne0 = 1024, rows = 37;
88    for (uint32_t type : types) {
89        const size_t rb = te_row_bytes(type, ne0);
90        std::vector<uint8_t> raw(rb * rows);
91        for (auto& b : raw) b = (uint8_t) (rng() & 0xFF);
92        // finite, modest scales where the format keeps an f16 scale; finite values for the plain types
93        if (type == TE_Q4_K || type == TE_Q5_K) {
94            const size_t bs = type == TE_Q4_K ? 144 : 176;
95            for (size_t o = 0; o < raw.size(); o += bs) { put_f16(&raw[o], rng); put_f16(&raw[o + 2], rng); }
96        } else if (type == TE_Q6_K) {
97            for (size_t o = 0; o < raw.size(); o += 210) put_f16(&raw[o + 208], rng);
98        } else if (type == TE_IQ4_XS) {
99            for (size_t o = 0; o < raw.size(); o += 136) put_f16(&raw[o], rng);
100        } else if (type == TE_Q8_0) {
101            for (size_t o = 0; o < raw.size(); o += 34) put_f16(&raw[o], rng);
102        } else if (type == TE_F32) {
103            std::normal_distribution<float> nd(0.f, 3.f);
104            for (size_t o = 0; o < raw.size(); o += 4) { const float f = nd(rng); std::memcpy(&raw[o], &f, 4); }
105            // values that land between two f16 numbers and in the f16 subnormal range
106            const float edge[] = {65504.f, 65520.f, 6.0e-8f, 3.0e-5f, -1.00048828125f};
107            for (int i = 0; i < 5; ++i) std::memcpy(&raw[4 * (size_t) (i * 97)], &edge[i], 4);
108        } else {   // F16 / BF16: random bit patterns except NaN / inf exponents
109            for (size_t o = 0; o < raw.size(); o += 2) {
110                if (type == TE_F16 && (raw[o + 1] & 0x7C) == 0x7C) raw[o + 1] &= 0xBF;
111                if (type == TE_BF16 && (raw[o + 1] & 0x7F) == 0x7F && (raw[o] & 0x80)) raw[o + 1] &= 0xBF;
112            }
113        }
114        std::string err;
115        if (!check_one(type, raw.data(), ne0, rows, tally[type], err)) {
116            std::fprintf(stderr, "type %u: %s\n", type, err.c_str());
117            return 2;
118        }
119    }
120    uint64_t bad = 0;
121    for (auto& [type, t] : tally) {
122        std::printf("synthetic type %2u: %llu values, %llu mismatches\n", type, (unsigned long long) t.values,
123                    (unsigned long long) t.mismatches);
124        bad += t.mismatches;
125    }
126    std::printf("TE-DEQUANT-SYNTHETIC %s\n", bad ? "FAIL" : "PASS");
127    return bad ? 1 : 0;
128}
129
130}  // namespace
131
132int main(int argc, char** argv) {
133    if (argc >= 2 && std::strcmp(argv[1], "--synthetic") == 0) return synthetic();
134    if (argc < 2) {
135        std::fprintf(stderr, "usage: strata-te-dequant-check <file.gguf> [--max-tensors N] | --synthetic\n");
136        return 2;
137    }
138    int max_t = 1 << 30;
139    for (int i = 2; i + 1 < argc; ++i)
140        if (std::strcmp(argv[i], "--max-tensors") == 0) max_t = std::atoi(argv[i + 1]);
141    try {
142        strata::GgufFile g(argv[1]);
143        std::map<uint32_t, Tally> tally;
144        int done = 0, skipped = 0;
145        for (const auto& ti : g.tensors()) {
146            if (done >= max_t) break;
147            if (!te_type_supported(ti.type) || te_row_bytes(ti.type, (int64_t) ti.shape[0]) == 0) { ++skipped; continue; }
148            const int64_t ne0 = (int64_t) ti.shape[0], rows = (int64_t) (ti.elements() / ti.shape[0]);
149            std::string err;
150            if (!check_one(ti.type, g.tensor_data(ti), ne0, rows, tally[ti.type], err)) {
151                std::fprintf(stderr, "%s: %s\n", ti.name.c_str(), err.c_str());
152                return 2;
153            }
154            ++done;
155        }
156        uint64_t bad = 0;
157        for (auto& [type, t] : tally) {
158            std::printf("type %-6s: %3d tensors, %llu values, %llu mismatches, device decode %.1f GB/s of f16\n",
159                        strata::ggml_type_name(type), t.tensors, (unsigned long long) t.values,
160                        (unsigned long long) t.mismatches, t.dev_s > 0 ? t.values * 2 / t.dev_s / 1e9 : 0.0);
161            bad += t.mismatches;
162        }
163        std::printf("tensors checked %d, skipped %d (unsupported type)\nTE-DEQUANT-FILE %s\n", done, skipped,
164                    bad ? "FAIL" : "PASS");
165        return bad ? 1 : 0;
166    } catch (const std::exception& e) {
167        std::fprintf(stderr, "%s\n", e.what());
168        return 2;
169    }
170}