okami.mom/strata

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

Niko1221Merge the AMD HIP backend (PR #121 by Konstantinos Korres, rebased onto 0.1.24) and its setup support36ef9d6e6

main
9.4 KiB202 linesraw
1// Real PLE IQ3_XXS/IQ4_XS matrix parity: ggml CPU dequantization versus HIP native MMVQ.
2// Usage: hip_ple_iq4 <model-shard-1.gguf> [expected-type-id]
3#include <hip/hip_runtime.h>
4
5#include "ggml.h"
6#include "strata/artifact/gguf_reader.hpp"
7#include "strata/kernels/f16_bits.hpp"
8#include "strata/kernels/native_mmvq.hpp"
9
10#include <algorithm>
11#include <cmath>
12#include <cstdint>
13#include <cstdio>
14#include <cstdlib>
15#include <random>
16#include <string>
17#include <vector>
18
19namespace {
20
21constexpr int kNIn = 2560;
22constexpr int kNOut = 10240;
23constexpr int kTypeIq3Xxs = 18;
24constexpr int kTypeIq4Xs = 23;
25constexpr int kReplayCount = 3;
26
27#define CHECK(call)                                                                                                  \
28    do {                                                                                                             \
29        const hipError_t error = (call);                                                                             \
30        if (error != hipSuccess) {                                                                                   \
31            std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(error));                                    \
32            return 2;                                                                                                \
33        }                                                                                                            \
34    } while (0)
35
36struct Q8Reference {
37    std::vector<float> dequantized;
38};
39
40Q8Reference quantize_q8_1_reference(const std::vector<float>& x) {
41    Q8Reference result;
42    result.dequantized.resize(x.size());
43    for (size_t offset = 0; offset < x.size(); offset += 32) {
44        float amax = 0.0f;
45        for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(x[offset + i]));
46        if (amax == 0.0f) {
47            std::fill(result.dequantized.begin() + offset, result.dequantized.begin() + offset + 32, 0.0f);
48            continue;
49        }
50        const float scale_f32 = amax / 127.0f;
51        const float scale_f16 = strata::kernels::f32_from_f16(strata::kernels::f16_from_f32(scale_f32));
52        for (int i = 0; i < 32; ++i) {
53            const int q = static_cast<int>(std::round(x[offset + i] / scale_f32));
54            result.dequantized[offset + i] = static_cast<float>(static_cast<int8_t>(q)) * scale_f16;
55        }
56    }
57    return result;
58}
59
60struct Parity {
61    double rel_l1_q8 = 0.0;
62    double worst_terms_q8 = 0.0;
63    double rel_l1_f32 = 0.0;
64    double max_abs_q8 = 0.0;
65    bool finite = true;
66};
67
68Parity compare(const uint8_t* weights, size_t row_bytes, const ggml_type_traits* traits,
69               const std::vector<float>& x, const std::vector<float>& x_q8,
70               const std::vector<float>& actual) {
71    std::vector<float> row(kNIn);
72    double q8_error = 0.0, q8_magnitude = 0.0;
73    double f32_error = 0.0, f32_magnitude = 0.0;
74    Parity result;
75    for (int r = 0; r < kNOut; ++r) {
76        traits->to_float(weights + static_cast<size_t>(r) * row_bytes, row.data(), kNIn);
77        double expected_q8 = 0.0, terms_q8 = 0.0, expected_f32 = 0.0;
78        for (int i = 0; i < kNIn; ++i) {
79            const double term_q8 = static_cast<double>(row[i]) * x_q8[i];
80            const double term_f32 = static_cast<double>(row[i]) * x[i];
81            expected_q8 += term_q8;
82            terms_q8 += std::fabs(term_q8);
83            expected_f32 += term_f32;
84        }
85        const double got = actual[r];
86        if (!std::isfinite(got) || !std::isfinite(expected_q8) || !std::isfinite(expected_f32)) result.finite = false;
87        q8_error += std::fabs(got - expected_q8);
88        q8_magnitude += std::fabs(expected_q8);
89        f32_error += std::fabs(got - expected_f32);
90        f32_magnitude += std::fabs(expected_f32);
91        result.max_abs_q8 = std::fmax(result.max_abs_q8, std::fabs(got - expected_q8));
92        result.worst_terms_q8 = std::fmax(result.worst_terms_q8,
93                                         std::fabs(got - expected_q8) / std::fmax(terms_q8, 1e-30));
94    }
95    result.rel_l1_q8 = q8_error / std::fmax(q8_magnitude, 1e-30);
96    result.rel_l1_f32 = f32_error / std::fmax(f32_magnitude, 1e-30);
97    return result;
98}
99
100std::vector<float> make_input(uint32_t seed) {
101    std::mt19937 rng(seed);
102    std::normal_distribution<float> normal(0.0f, 0.6f);
103    std::vector<float> x(kNIn);
104    for (int i = 0; i < kNIn; ++i)
105        x[i] = normal(rng) + 0.1f * std::sin(static_cast<float>(i) * 0.013f);
106    return x;
107}
108
109}  // namespace
110
111int main(int argc, char** argv) {
112    if (argc != 2 && argc != 3) {
113        std::fprintf(stderr, "usage: hip_ple_iq4 <model-shard-1.gguf> [expected-type-id]\n");
114        return 2;
115    }
116
117    try {
118        strata::GgufFile gguf(argv[1]);
119        const strata::TensorInfo* tensor = gguf.find("blk.1.ple_key.weight");
120        if (!tensor || (tensor->type != kTypeIq3Xxs && tensor->type != kTypeIq4Xs) || tensor->shape.size() != 2 ||
121            tensor->shape[0] != kNIn || tensor->shape[1] != kNOut) {
122            std::fprintf(stderr, "expected blk.1.ple_key.weight IQ3_XXS or IQ4_XS [2560,10240] in %s\n", argv[1]);
123            return 1;
124        }
125        if (argc == 3 && std::atoi(argv[2]) != static_cast<int>(tensor->type)) {
126            std::fprintf(stderr, "requested GGML type %s but blk.1.ple_key.weight is type %u (%s)\n",
127                         argv[2], tensor->type, tensor->type_name());
128            return 1;
129        }
130        const auto* traits = ggml_get_type_traits(static_cast<ggml_type>(tensor->type));
131        if (!traits || !traits->to_float) {
132            std::fprintf(stderr, "ggml has no %s CPU dequantizer\n", tensor->type_name());
133            return 1;
134        }
135        const uint8_t* host_weights = gguf.tensor_data(*tensor);
136        const size_t weight_bytes = strata::kernels::native_mmvq_weight_bytes(static_cast<int>(tensor->type), kNIn, kNOut);
137        const size_t row_bytes = weight_bytes / kNOut;
138        const size_t expected_bytes_per_block = tensor->type == kTypeIq3Xxs ? 98 : 136;
139        if (weight_bytes != static_cast<size_t>(tensor->elements()) / 256 * expected_bytes_per_block ||
140            row_bytes != static_cast<size_t>(kNIn / 256) * expected_bytes_per_block) {
141            std::fprintf(stderr, "unexpected %s storage geometry: %zu bytes, row %zu\n",
142                         tensor->type_name(), weight_bytes, row_bytes);
143            return 1;
144        }
145
146        uint8_t* device_weights = nullptr;
147        float* device_x = nullptr;
148        float* device_y = nullptr;
149        void* device_q8_1 = nullptr;
150        CHECK(hipMalloc(reinterpret_cast<void**>(&device_weights), weight_bytes));
151        CHECK(hipMalloc(reinterpret_cast<void**>(&device_x), kNIn * sizeof(float)));
152        CHECK(hipMalloc(reinterpret_cast<void**>(&device_y), kNOut * sizeof(float)));
153        CHECK(hipMalloc(&device_q8_1, strata::kernels::native_q8_1_bytes(kNIn)));
154        CHECK(hipMemcpy(device_weights, host_weights, weight_bytes, hipMemcpyHostToDevice));
155
156        hipStream_t stream = nullptr;
157        CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking));
158        CHECK(hipStreamBeginCapture(stream, hipStreamCaptureModeThreadLocal));
159        strata::kernels::native_quantize_q8_1(device_x, device_q8_1, kNIn, 1, static_cast<void*>(stream));
160        strata::kernels::native_mmvq(static_cast<int>(tensor->type), device_weights, device_q8_1, device_y,
161                                     kNIn, kNOut, 1, static_cast<void*>(stream));
162        hipGraph_t graph = nullptr;
163        CHECK(hipStreamEndCapture(stream, &graph));
164        hipGraphExec_t graph_exec = nullptr;
165        CHECK(hipGraphInstantiate(&graph_exec, graph, nullptr, nullptr, 0));
166
167        std::vector<float> actual(kNOut);
168        bool ok = true;
169        for (int replay = 0; replay < kReplayCount; ++replay) {
170            const std::vector<float> x = make_input(0x1572u + static_cast<uint32_t>(replay));
171            const Q8Reference q8 = quantize_q8_1_reference(x);
172            CHECK(hipMemcpyAsync(device_x, x.data(), x.size() * sizeof(float), hipMemcpyHostToDevice, stream));
173            CHECK(hipGraphLaunch(graph_exec, stream));
174            CHECK(hipMemcpyAsync(actual.data(), device_y, actual.size() * sizeof(float), hipMemcpyDeviceToHost, stream));
175            CHECK(hipStreamSynchronize(stream));
176
177            const Parity parity = compare(host_weights, row_bytes, traits, x, q8.dequantized, actual);
178            const bool pass = parity.finite && parity.rel_l1_q8 <= 5e-5 && parity.worst_terms_q8 <= 1e-4 &&
179                              parity.rel_l1_f32 <= 3e-2;
180            std::printf("%s PLE graph replay %d/%d: q8-ref rel-L1 %.3e, worst terms %.3e, "
181                        "original-f32 rel-L1 %.3e, max q8 abs %.3e %s\n",
182                        tensor->type_name(), replay + 1, kReplayCount, parity.rel_l1_q8, parity.worst_terms_q8,
183                        parity.rel_l1_f32, parity.max_abs_q8, pass ? "PASS" : "FAIL");
184            ok = ok && pass;
185        }
186
187        CHECK(hipGraphExecDestroy(graph_exec));
188        CHECK(hipGraphDestroy(graph));
189        CHECK(hipStreamDestroy(stream));
190        CHECK(hipFree(device_q8_1));
191        CHECK(hipFree(device_y));
192        CHECK(hipFree(device_x));
193        CHECK(hipFree(device_weights));
194        if (!ok) return 1;
195        std::printf("PLE %s native MMVQ parity OK: real GGUF matrix, CPU dequant reference, %d graph replays\n",
196                    tensor->type_name(), kReplayCount);
197        return 0;
198    } catch (const std::exception& error) {
199        std::fprintf(stderr, "hip_ple_iq4: %s\n", error.what());
200        return 1;
201    }
202}