okami.mom/strata

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

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
7.7 KiB165 linesraw
1// src/kernels/dequant_s2_parity.cpp - P2.S2's parity test for the S2 decode.
2//
3// THE REFERENCE IS THE CHAIN, NOT A SECOND OPINION.  `strata::dequantize_q2_0` (include/strata/artifact/
4// dequant.hpp) is a scalar transcription that `bench/micro/dequant_xcheck` checks against **ggml's own**
5// dequantizer on real block bytes; and `tools/canonical_xcheck.py --full` checks that the canonical form
6// decodes to the same values on every block of the artifact.  So this compares "GPU canonical decode" against
7// "CPU decode already proven equal to ggml", and a fault in either the canonicaliser or the kernel shows up
8// here.  A parity test whose two sides were written together would show neither.
9#define DPCT_PROFILING_ENABLED
10#include <sycl/sycl.hpp>
11#include <dpct/dpct.hpp>
12#include "strata/artifact/dequant.hpp"
13#include "strata/kernels/dequant_s2.hpp"
14
15#include <cstdint>
16#include <cstdio>
17#include <cstring>
18#include <random>
19#include <vector>
20
21namespace {
22
23constexpr int QK = 64;
24
25void check(dpct::err0 e, const char *what) {
26}
27
28// fp16 patterns that are finite, normal and exactly representable.  Random 16-bit patterns would include NaN
29// and infinity, and a NaN makes `!=` true for a reason that has nothing to do with the kernel - the test
30// would fail for the wrong cause, or worse, a real fault would hide behind a NaN it caused itself.
31const uint16_t kScales[] = {0x3C00, 0x3800, 0x3400, 0x3000, 0x2C00, 0x2800, 0x2000,
32                            0xBC00, 0xB800, 0xB400, 0xB000, 0xAC00, 0x1800, 0x1400};
33
34}  // namespace
35
36int main(int argc, char** argv) {
37    long long n_blocks = 200000;
38    bool selftest = false;
39    for (int i = 1; i < argc; ++i) {
40        if (std::strcmp(argv[i], "--selftest") == 0) selftest = true;
41        else if (std::strcmp(argv[i], "--blocks") == 0 && i + 1 < argc) n_blocks = std::atoll(argv[++i]);
42        else {
43            std::fprintf(stderr, "usage: dequant_s2_parity [--selftest] [--blocks N]\n");
44            return 2;
45        }
46    }
47    if (n_blocks <= 0) { std::fprintf(stderr, "--blocks must be positive\n"); return 2; }
48
49    std::mt19937 rng(12345);
50    const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0]));
51
52    // raw Q2_0 blocks: { fp16 d ; uint8 qs[16] } - what ggml produced and what the artifact stores
53    std::vector<uint8_t> raw((size_t) n_blocks * 18);
54    for (long long b = 0; b < n_blocks; ++b) {
55        const uint16_t d = kScales[rng() % n_scales];
56        raw[(size_t) b * 18 + 0] = (uint8_t) (d & 0xFF);
57        raw[(size_t) b * 18 + 1] = (uint8_t) (d >> 8);
58        for (int t = 0; t < 16; ++t) raw[(size_t) b * 18 + 2 + t] = (uint8_t) (rng() & 0xFF);
59    }
60
61    // the CPU reference, over the RAW blocks
62    std::vector<float> cpu((size_t) n_blocks * QK);
63    for (long long b = 0; b < n_blocks; ++b) {
64        strata::dequantize_q2_0(&raw[(size_t) b * 18], &cpu[(size_t) b * QK]);
65    }
66
67    // canonical planes: S2 packs 4 codes per byte exactly as Q2_0 stores them, so the codes plane is the raw
68    // qs bytes; the scales plane is the fp16 `d` widened.  Copied into planes of their own rather than
69    // aliased, because that is what the kernel will read in the engine.
70    std::vector<uint8_t> codes((size_t) n_blocks * 16);
71    std::vector<float> scales((size_t) n_blocks);
72    for (long long b = 0; b < n_blocks; ++b) {
73        std::memcpy(&codes[(size_t) b * 16], &raw[(size_t) b * 18 + 2], 16);
74        const uint16_t d = (uint16_t) (raw[(size_t) b * 18] | (raw[(size_t) b * 18 + 1] << 8));
75        scales[(size_t) b] = strata::fp16_to_fp32(d);
76    }
77
78    uint8_t* d_codes = nullptr;
79    float *d_scales = nullptr, *d_out = nullptr;
80    check(DPCT_CHECK_ERROR(d_codes = (uint8_t *)sycl::malloc_device(
81                               codes.size(), dpct::get_in_order_queue())),
82          "cudaMalloc codes");
83    check(DPCT_CHECK_ERROR(d_scales = sycl::malloc_device<float>(
84                               scales.size(), dpct::get_in_order_queue())),
85          "cudaMalloc scales");
86    check(DPCT_CHECK_ERROR(d_out = sycl::malloc_device<float>(
87                               cpu.size(), dpct::get_in_order_queue())),
88          "cudaMalloc out");
89    /*
90    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
91    the original code the source host memory is pageable memory. If the memory
92    is not pageable, call wait() on event return by memcpy API to ensure
93    synchronization behavior.
94    */
95    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
96              d_codes, codes.data(), codes.size()).wait()),
97          "copy codes");
98    /*
99    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
100    the original code the source host memory is pageable memory. If the memory
101    is not pageable, call wait() on event return by memcpy API to ensure
102    synchronization behavior.
103    */
104    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
105              d_scales, scales.data(), scales.size() * sizeof(float)).wait()),
106          "copy scales");
107
108    strata::kernels::dequant_s2(d_codes, d_scales, d_out, n_blocks);
109
110    std::vector<float> gpu(cpu.size());
111    check(DPCT_CHECK_ERROR(
112              (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
113                  .memcpy(gpu.data(), d_out, gpu.size() * sizeof(float))
114                  .wait()),
115          "copy back");
116
117    long long bad = 0, first_bad = -1;
118    for (size_t i = 0; i < cpu.size(); ++i) {
119        // bit comparison, not a tolerance: S2's decode is exact integer-to-float arithmetic, so ANY
120        // difference is a bug and a tolerance would only hide which one
121        if (std::memcmp(&cpu[i], &gpu[i], sizeof(float)) != 0) {
122            if (first_bad < 0) first_bad = (long long) i;
123            ++bad;
124        }
125    }
126
127    // NON-VACUITY.  Two buffers of zeros compare equal, and so do two buffers a broken test filled with the
128    // same constant - an agreement check that cannot distinguish "both correct" from "both empty" is the
129    // failure this project keeps finding.  So the data must actually vary, and the four codes must all occur:
130    // an S2 decode that only ever saw one code would agree while being unable to tell -1 from +2.
131    bool seen[4] = {false, false, false, false};
132    for (size_t i = 0; i < codes.size(); ++i) {
133        for (int t = 0; t < 4; ++t) seen[(codes[i] >> (2 * t)) & 3] = true;
134    }
135    int distinct = 0;
136    for (bool s : seen) distinct += s ? 1 : 0;
137    long long distinct_vals = 0;
138    for (size_t i = 0; i < cpu.size() && distinct_vals < 8; ++i) {
139        bool dup = false;
140        for (size_t j = 0; j < i && !dup; ++j) dup = (cpu[j] == cpu[i]);
141        if (!dup) ++distinct_vals;
142    }
143    std::printf("  non-vacuity: %d of 4 codes present, %lld distinct values in the first elements\n", distinct,
144                distinct_vals);
145    if (distinct != 4 || distinct_vals < 4) {
146        std::fprintf(stderr, "VACUOUS: the comparison could not have distinguished a wrong decode\n");
147        return 1;
148    }
149
150    std::printf("dequant_s2: %lld blocks, %lld elements, %lld mismatched\n", n_blocks, (long long) cpu.size(),
151                bad);
152    if (bad) {
153        std::printf("  first mismatch at element %lld (block %lld, offset %d): cpu %.9g gpu %.9g\n",
154                    (long long) first_bad, (long long) (first_bad / QK), (int) (first_bad % QK),
155                    (double) cpu[(size_t) first_bad], (double) gpu[(size_t) first_bad]);
156        return 1;
157    }
158    std::printf("  bit-exact against the scalar dequantizer that dequant_xcheck proved equal to ggml\n");
159    if (selftest) std::printf("dequant_s2_parity OK\n");
160
161    sycl::free(d_codes, dpct::get_in_order_queue());
162    sycl::free(d_scales, dpct::get_in_order_queue());
163    sycl::free(d_out, dpct::get_in_order_queue());
164    return 0;
165}