okami.mom/strata

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

Niko1221Merge f-029-gdn-amd01ef87656

main
11.9 KiB235 linesraw
1// Exercise the public opt-in dispatch, including tails, padded rows and a nonzero carried state.  The FP32
2// recurrence is the all-head reference; short cases also use an independent double-precision CPU recurrence.
3#include "strata/prefill/kernels.hpp"
4#include "strata/kernels/gfx_arch.hpp"
5#include <cuda_runtime.h>
6#include <cuda_fp16.h>
7#include <algorithm>
8#include <cmath>
9#include <cstdint>
10#include <cstdio>
11#include <cstdlib>
12#include <cstring>
13#include <random>
14#include <vector>
15
16namespace {
17constexpr int S = 128, HK = 16, HV = 48, C = 10240, ROW = HV * S;
18constexpr uint16_t SENTINEL = 0x7bff;
19void ck(cudaError_t e, const char* where) {
20    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", where, cudaGetErrorString(e)); std::exit(2); }
21}
22void setting(const char* key, const char* value) {
23#ifdef _WIN32
24    if (_putenv_s(key, value)) std::exit(2);
25#else
26    if (setenv(key, value, 1)) std::exit(2);
27#endif
28}
29template<class X> X* upload(const std::vector<X>& v) {
30    X* p = nullptr;
31    ck(cudaMalloc(&p, v.size() * sizeof(X)), "malloc");
32    ck(cudaMemcpy(p, v.data(), v.size() * sizeof(X), cudaMemcpyHostToDevice), "upload");
33    return p;
34}
35template<class X> std::vector<X> download(const X* p, size_t n) {
36    std::vector<X> v(n);
37    ck(cudaMemcpy(v.data(), p, n * sizeof(X), cudaMemcpyDeviceToHost), "download");
38    return v;
39}
40float half(uint16_t bits) { __half_raw x; x.x = bits; return __half2float(__half(x)); }
41struct Error {
42    double square = 0, reference = 0, max_error = 0, max_reference = 0;
43    bool finite = true;
44    void add(double a, double b) {
45        finite &= std::isfinite(a) && std::isfinite(b);
46        square += (a - b) * (a - b); reference += a * a;
47        max_error = std::max(max_error, std::fabs(a - b)); max_reference = std::max(max_reference, std::fabs(a));
48    }
49    double rms() const { return std::sqrt(square / std::max(reference, 1e-30)); }
50    bool ok() const { return finite && rms() <= 0.003 && max_error <= 0.02 * max_reference + 1e-5; }
51};
52struct Input {
53    int64_t n;
54    std::vector<float> h, gate, beta, z, gamma, state;
55    Input(int64_t t, float decay, float scale, bool no_update) : n(t), h(std::max<int64_t>(t, 1) * C),
56        gate(std::max<int64_t>(t, 1) * HV), beta(gate.size()), z(std::max<int64_t>(t, 1) * ROW),
57        gamma(S), state(S * ROW) {
58        std::mt19937 rng(11);
59        std::normal_distribution<float> normal(0, 1);
60        std::uniform_real_distribution<float> uniform(0, 1);
61        for (auto& x : h) x = normal(rng);
62        for (int64_t i = 0; i < t; ++i) {
63            float* row = h.data() + i * C;
64            for (int head = 0; head < 2 * HK; ++head) {
65                double norm = 0;
66                for (int d = 0; d < S; ++d) norm += double(row[head * S + d]) * row[head * S + d];
67                for (int d = 0; d < S; ++d) row[head * S + d] /= std::sqrt(norm + 1e-6);
68            }
69            for (int d = 2 * HK * S; d < C; ++d) row[d] *= scale;
70        }
71        for (auto& x : gate) x = -decay * uniform(rng);
72        for (auto& x : beta) x = no_update ? 0 : uniform(rng);
73        for (auto& x : z) x = normal(rng);
74        for (auto& x : gamma) x = 0.5f + uniform(rng);
75        for (auto& x : state) x = 0.1f * scale * normal(rng);
76    }
77};
78struct Output { std::vector<uint16_t> y; std::vector<float> state; };
79Output run(const Input& in, int ld, bool reference, int64_t split = 0) {
80    auto h = upload(in.h), g = upload(in.gate), b = upload(in.beta), z = upload(in.z), gm = upload(in.gamma);
81    auto state = upload(in.state);
82    auto y = upload(std::vector<uint16_t>(std::max<int64_t>(in.n, 1) * ld + 8, SENTINEL));
83    // The chunked path owns y as temporary storage; only y16 and state are observable outputs.
84    auto scratch = upload(std::vector<float>(std::max<int64_t>(in.n, 1) * ROW));
85    auto call = [&](int64_t start, int64_t n) {
86        if (reference)
87            strata::prefill::gdn_recurrence_variant(5, state, h + start * C, g + start * HV, b + start * HV,
88                z + start * ROW, gm, 1e-6f, scratch, y + start * ld, n, nullptr, ld);
89        else
90            strata::prefill::gdn_recurrence(state, h + start * C, g + start * HV, b + start * HV,
91                z + start * ROW, gm, 1e-6f, scratch, y + start * ld, n, nullptr, ld);
92        ck(cudaDeviceSynchronize(), "recurrence");
93    };
94    if (split) { call(0, split); call(split, in.n - split); }
95    else call(0, in.n);
96    Output out{download(y, std::max<int64_t>(in.n, 1) * ld + 8), download(state, in.state.size())};
97    ck(cudaFree(h), "free"); ck(cudaFree(g), "free"); ck(cudaFree(b), "free"); ck(cudaFree(z), "free");
98    ck(cudaFree(gm), "free"); ck(cudaFree(state), "free"); ck(cudaFree(y), "free"); ck(cudaFree(scratch), "free");
99    return out;
100}
101bool compare(const Input& in, int ld, const Output& ref, const Output& got, bool exact, const char* label) {
102    Error y, state;
103    bool guards = true, bits = true;
104    for (int64_t t = 0; t < in.n; ++t) {
105        for (int d = 0; d < ROW; ++d) {
106            y.add(half(ref.y[t * ld + d]), half(got.y[t * ld + d]));
107            bits &= ref.y[t * ld + d] == got.y[t * ld + d];
108        }
109        for (int d = ROW; d < ld; ++d) guards &= got.y[t * ld + d] == SENTINEL;
110    }
111    for (size_t i = in.n * ld; i < got.y.size(); ++i) guards &= got.y[i] == SENTINEL;
112    for (size_t i = 0; i < got.state.size(); ++i) {
113        state.add(ref.state[i], got.state[i]);
114        bits &= std::memcmp(&ref.state[i], &got.state[i], sizeof(float)) == 0;
115    }
116    const bool ok = guards && (exact ? bits : y.ok() && state.ok());
117    std::printf("%s %s T=%lld ld=%d exact=%d y_rms=%.3e y_max=%.3e state_rms=%.3e guards=%d\n",
118        ok ? "PASS" : "FAIL", label, (long long) in.n, ld, exact, y.rms(), y.max_error, state.rms(), guards);
119    return ok;
120}
121bool cpu_check(const Input& in, int ld, const Output& got) {
122    Error y, state;
123    for (int vh : {0, 23, 47}) {
124        const int qh = vh % HK;
125        std::vector<double> s(S * S), output(S), delta(S);
126        for (int r = 0; r < S; ++r)
127            for (int c = 0; c < S; ++c) s[r * S + c] = in.state[r * ROW + vh * S + c];
128        for (int64_t t = 0; t < in.n; ++t) {
129            const float* row = in.h.data() + t * C;
130            const float* q = row + qh * S;
131            const float* k = row + HK * S + qh * S;
132            const float* v = row + 2 * HK * S + vh * S;
133            const double decay = std::exp(in.gate[t * HV + vh]), beta = in.beta[t * HV + vh];
134            for (auto& x : s) x *= decay;
135            for (int c = 0; c < S; ++c) {
136                double prediction = 0;
137                for (int r = 0; r < S; ++r) prediction += k[r] * s[r * S + c];
138                delta[c] = beta * (v[c] - prediction);
139            }
140            double norm = 0;
141            for (int c = 0; c < S; ++c) {
142                double o = 0;
143                for (int r = 0; r < S; ++r) { s[r * S + c] += k[r] * delta[c]; o += q[r] * s[r * S + c]; }
144                output[c] = o / std::sqrt(double(S)); norm += output[c] * output[c];
145            }
146            for (int c = 0; c < S; ++c) {
147                const double value = output[c] / std::sqrt(norm / S + 1e-6) * in.gamma[c]
148                    / (1 + std::exp(-in.z[t * ROW + vh * S + c]));
149                y.add(value, half(got.y[t * ld + vh * S + c]));
150            }
151        }
152        for (int r = 0; r < S; ++r)
153            for (int c = 0; c < S; ++c) state.add(s[r * S + c], got.state[r * ROW + vh * S + c]);
154    }
155    const bool ok = y.ok() && state.ok();
156    std::printf("%s CPU T=%lld y_rms=%.3e state_rms=%.3e\n", ok ? "PASS" : "FAIL", (long long) in.n, y.rms(), state.rms());
157    return ok;
158}
159// One path's time for one layer's recurrence + norm (GPU-event median of 7 runs after 2 warmups, the same start state each
160// run).  STRATA_GDN_CHUNKED is read once per process, so --bench (this path) and --bench-default (gfx1151's default: the
161// existing kernels with STRATA_GDN_PP=2 and STRATA_GDN_NOY=1) are separate runs of this binary.
162void bench(const char* path) {
163    for (int64_t t : {64, 256, 2048, 16384, 32768}) {
164        const Input in(t, 2, 1, false);
165        auto h = upload(in.h), g = upload(in.gate), b = upload(in.beta), z = upload(in.z), gm = upload(in.gamma);
166        auto state = upload(in.state);
167        auto y = upload(std::vector<uint16_t>(t * (ROW + 8)));
168        auto scratch = upload(std::vector<float>(t * ROW));
169        cudaEvent_t start, end;
170        ck(cudaEventCreate(&start), "event"); ck(cudaEventCreate(&end), "event");
171        std::vector<float> times;
172        for (int round = -2; round < 7; ++round) {
173            ck(cudaMemcpy(state, in.state.data(), in.state.size() * sizeof(float), cudaMemcpyHostToDevice), "reset");
174            ck(cudaEventRecord(start), "event");
175            strata::prefill::gdn_recurrence(state, h, g, b, z, gm, 1e-6f, scratch, y, t, nullptr, ROW + 8);
176            ck(cudaEventRecord(end), "event"); ck(cudaEventSynchronize(end), "time");
177            float ms = 0;
178            ck(cudaEventElapsedTime(&ms, start, end), "time");
179            if (round >= 0) times.push_back(ms);
180        }
181        std::sort(times.begin(), times.end());
182        std::printf("BENCH path=%s T=%lld ms=%.6f repeats=7\n", path, (long long) t, times[3]);
183        ck(cudaEventDestroy(start), "event"); ck(cudaEventDestroy(end), "event");
184        ck(cudaFree(h), "free"); ck(cudaFree(g), "free"); ck(cudaFree(b), "free"); ck(cudaFree(z), "free");
185        ck(cudaFree(gm), "free"); ck(cudaFree(state), "free"); ck(cudaFree(y), "free"); ck(cudaFree(scratch), "free");
186    }
187}
188}
189int main(int argc, char** argv) {
190    const bool bench_default = argc > 1 && std::strcmp(argv[1], "--bench-default") == 0;
191    const bool off = argc > 1 && (std::strcmp(argv[1], "--off") == 0 || std::strcmp(argv[1], "--default") == 0 || bench_default);
192    setting("STRATA_GDN_CHUNKED", off ? "0" : "1");
193    setting("STRATA_GDN_HEAD", "1"); setting("STRATA_GDN_PP", "2");
194    if (argc > 1 && std::strncmp(argv[1], "--bench", 7) == 0) setting("STRATA_GDN_NOY", "1");   // gfx1151's default
195#ifdef _WIN32
196    _putenv_s("STRATA_GDN_REC_HEADS", "");
197    if (argc > 1 && std::strcmp(argv[1], "--default") == 0) _putenv_s("STRATA_GDN_CHUNKED", "");
198#else
199    unsetenv("STRATA_GDN_REC_HEADS");
200    if (argc > 1 && std::strcmp(argv[1], "--default") == 0) unsetenv("STRATA_GDN_CHUNKED");
201#endif
202    int device = 0;
203    cudaDeviceProp props{};
204    ck(cudaGetDevice(&device), "device"); ck(cudaGetDeviceProperties(&props, device), "properties");
205    const bool wmma = strata::kernels::gfx_arch_is_gfx11_wmma(props.gcnArchName) || strata::kernels::gfx_arch_is_gfx12_wmma(props.gcnArchName);
206    std::printf("device=%s chunked=%d wmma=%d\n", props.gcnArchName, !off, wmma);
207    if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { bench("chunked"); return 0; }
208    if (bench_default) { bench("default"); return 0; }
209    int failures = 0;
210    for (int64_t t : {0, 1, 15, 16, 17, 63, 64, 65, 79, 80, 81, 257, 2051, 16385}) {
211        if (off && t > 2051) continue;
212        const Input in(t, 2, 1, false);
213        for (int padding : {0, 8, 1}) {
214            if (t > 257 && padding != 8) continue;
215            const int ld = ROW + padding;
216            const auto ref = run(in, ld, true), got = run(in, ld, false);
217            const bool exact = off || !wmma || t < 64 || ld % 8;
218            failures += !compare(in, ld, ref, got, exact, "dispatch");
219            if (t == 65 && padding == 8) failures += !cpu_check(in, ld, got);
220            if (t == 257 && padding == 8) failures += !compare(in, ld, got, run(in, ld, false, 129), false, "continuation");
221        }
222    }
223    if (!off) {
224        for (const float decay : {0.f, 0.01f}) {
225            const Input in(2051, decay, 16, false);
226            failures += !compare(in, ROW + 8, run(in, ROW + 8, true), run(in, ROW + 8, false), !wmma, "weak-decay");
227        }
228        const Input in(65, 0.01f, 1, true);
229        const auto got = run(in, ROW, false);
230        failures += !compare(in, ROW, run(in, ROW, true), got, !wmma, "beta-zero");
231        failures += !cpu_check(in, ROW, got);
232    }
233    std::printf("FAILURES: %d\n", failures);
234    return failures ? 1 : 0;
235}