okami.mom/strata

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

Niko1221Merge branch 'f-1402-y' into f-14025af104b51

main
11.1 KiB218 linesraw
1// src/kernels/qsa_topk_parity.cpp - the QSA top-k the engine dispatches (qsa_block_topk) against the original kernel
2// (qsa_block_topk_ref): the selected cells must be identical (GPU, synthetic, no model).
3//
4// A case is a context under a capacity (the engine's --max-context; max_blocks = capacity / 4 + 2, and without an
5// active-block count the dispatch follows it), with consecutive queries at the context's end so that the tail block
6// holds 0 to 3 cells.  Three score sets per case: continuous, 64 levels (many ties at the threshold) and all equal
7// (the rule's ties go to the lowest index).  The dispatch is called as a decode window calls it (no block count) and as
8// the prompt path does (with the call's largest block count).  The reference and the dispatched kernel are also timed.
9//
10// Usage: qsa_topk_parity --selftest
11//        qsa_topk_parity CONTEXT [QUERIES=256] [REPS=10] [CAPACITY=CONTEXT] [COUNT=1]   (COUNT=0: no block count)
12#define DPCT_PROFILING_ENABLED
13#include <sycl/sycl.hpp>
14#include <dpct/dpct.hpp>
15#include "strata/kernels/qsa.hpp"
16#include "strata/kernels/qsa_select.hpp"
17
18#include <algorithm>
19#include <cmath>
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <random>
24#include <vector>
25
26namespace k = strata::kernels;
27
28namespace {
29void ck(dpct::err0 e, const char *w) {
30    /*
31    DPCT1009: SYCL reports errors using exceptions and does not use error
32    codes. Please replace the "get_error_string_dummy(...)" with a real
33    error-handling function.
34    */
35}
36
37bool run_case(int64_t ctx, int64_t nq, int reps, int64_t capacity, bool counted) {
38    const k::QsaShapes s = k::qsa_real_shapes();
39    const int64_t max_blocks = capacity / s.idx_block + 2, cap = k::qsa_selection_width(k::kTopkMaxCells, s);
40    std::vector<int32_t> steps((size_t) (nq * k::kStepCount));
41    for (int64_t i = 0; i < nq; ++i) {
42        int32_t* st = steps.data() + i * k::kStepCount;
43        const int64_t pos = ctx - nq + i;
44        st[k::kStepPos] = (int32_t) pos;
45        st[k::kStepNKv] = (int32_t) (pos + 1);
46        st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);
47        st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);
48    }
49    std::mt19937 rng((uint32_t) (ctx * 31 + capacity));
50    std::normal_distribution<float> nd(0.f, 1.f);
51    std::vector<float> scores((size_t) (nq * max_blocks)), tied(scores.size()), equal(scores.size(), 0.25f);
52    for (int64_t i = 0; i < nq; ++i) {
53        const int32_t* st = steps.data() + i * k::kStepCount;
54        float* row = scores.data() + i * max_blocks;
55        for (int64_t b = 0; b < max_blocks; ++b) row[b] = nd(rng);
56        // the tail block as the scorers leave it: far above the others when it holds cells
57        if (st[k::kStepNKv] % s.idx_block != 0) row[st[k::kStepNBid]] += 1e9f;
58        for (int64_t b = 0; b < max_blocks; ++b)
59            tied[(size_t) (i * max_blocks + b)] = row[b] > 1e8f ? row[b] : std::floor(row[b] * 8.0f) / 8.0f;   // ~64 levels
60    }
61    int32_t *d_steps = nullptr, *ids_ref = nullptr, *ids_new = nullptr;
62    float* d_scores = nullptr;
63    ck(DPCT_CHECK_ERROR(d_steps = (int32_t *)sycl::malloc_device(
64                            steps.size() * 4, dpct::get_in_order_queue())),
65       "malloc");
66    ck(DPCT_CHECK_ERROR(d_scores = (float *)sycl::malloc_device(
67                            scores.size() * 4, dpct::get_in_order_queue())),
68       "malloc");
69    ck(DPCT_CHECK_ERROR(
70           ids_ref = (int32_t *)sycl::malloc_device(
71               (size_t)(nq * cap) * 4, dpct::get_in_order_queue())),
72       "malloc");
73    ck(DPCT_CHECK_ERROR(
74           ids_new = (int32_t *)sycl::malloc_device(
75               (size_t)(nq * cap) * 4, dpct::get_in_order_queue())),
76       "malloc");
77    /*
78    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
79    in the original code the source host memory is pageable memory. If the
80    memory is not pageable, call wait() on event return by memcpy API to ensure
81    synchronization behavior.
82    */
83    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_steps, steps.data(),
84                                                          steps.size() * 4).wait()),
85       "upload");
86    const int64_t active = counted ? steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1 : -1;
87    std::vector<int32_t> a((size_t) (nq * cap)), b(a.size());
88    auto same = [&](const std::vector<float> &sc) -> int64_t {
89        /*
90        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
91        assuming in the original code the source host memory is pageable memory.
92        If the memory is not pageable, call wait() on event return by memcpy API
93        to ensure synchronization behavior.
94        */
95        try {
96    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_scores, sc.data(),
97                                                          sc.size() * 4).wait()),
98       "upload");
99        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
100                                .memset(ids_ref, 0xff, a.size() * 4)
101                                .wait()),
102           "memset");
103        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
104                                .memset(ids_new, 0xff, a.size() * 4)
105                                .wait()),
106           "memset");
107        k::qsa_block_topk_ref(d_scores, d_steps, nq, max_blocks, cap, s, ids_ref, nullptr);
108        k::qsa_block_topk(d_scores, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active);
109        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
110           "sync");
111        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
112                                .memcpy(a.data(), ids_ref, a.size() * 4)
113                                .wait()),
114           "down");
115        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
116                                .memcpy(b.data(), ids_new, b.size() * 4)
117                                .wait()),
118           "down");
119        int64_t n = 0;
120        for (int64_t i = 0; i < nq; ++i) {
121            const int64_t w = steps[(size_t) (i * k::kStepCount + k::kStepWidth)];
122            n += std::equal(a.begin() + i * cap, a.begin() + i * cap + w, b.begin() + i * cap);
123        }
124        return n;
125    }
126    catch (sycl::exception const &exc) {
127      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
128                << ", line:" << __LINE__ << std::endl;
129      std::exit(1);
130    }
131    };
132    const int64_t same_tied = same(tied), same_equal = same(equal), same_cont = same(scores);   // d_scores: continuous
133    dpct::event_ptr e0, e1;
134    ck(DPCT_CHECK_ERROR(e0 = new sycl::event()), "event");
135    ck(DPCT_CHECK_ERROR(e1 = new sycl::event()), "event");
136    auto timed = [&](auto f) {
137        /*
138        DPCT1024: The original code returned the error code that was
139        further consumed by the program logic. This original code was replaced
140        with 0. You may need to rewrite the program logic consuming the error
141        code.
142        */
143        try {
144    ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e0)), "record");
145        for (int r = 0; r < reps; ++r) f();
146        /*
147        DPCT1024: The original code returned the error code that was
148        further consumed by the program logic. This original code was replaced
149        with 0. You may need to rewrite the program logic consuming the error
150        code.
151        */
152        ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e1)), "record");
153        ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "time");
154        float ms = 0;
155        ck(DPCT_CHECK_ERROR(
156               ms = (e1->get_profiling_info<
157                         sycl::info::event_profiling::command_end>() -
158                     e0->get_profiling_info<
159                         sycl::info::event_profiling::command_start>()) /
160                    1000000.0f),
161           "elapsed");
162        return ms / (float) reps;
163    }
164    catch (sycl::exception const &exc) {
165      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
166                << ", line:" << __LINE__ << std::endl;
167      std::exit(1);
168    }
169    };
170    const float t_ref = timed([&] { k::qsa_block_topk_ref(d_scores, d_steps, nq, max_blocks, cap, s, ids_ref, nullptr); });
171    const float t_new = timed([&] { k::qsa_block_topk(d_scores, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active); });
172    dpct::destroy_event(e0); dpct::destroy_event(e1);
173    sycl::free(d_steps, dpct::get_in_order_queue());
174        sycl::free(d_scores, dpct::get_in_order_queue());
175        sycl::free(ids_ref, dpct::get_in_order_queue());
176        sycl::free(ids_new, dpct::get_in_order_queue());
177    const bool ok = same_cont == nq && same_tied == nq && same_equal == nq;
178    std::printf("%s context %lld under a capacity of %lld (%lld blocks), %lld queries %s: reference %.3f ms, "
179                "dispatched %.3f ms (%.1fx); identical ids: continuous %lld/%lld, 64 levels %lld/%lld, equal scores "
180                "%lld/%lld\n", ok ? "PASS" : "FAIL", (long long) ctx, (long long) capacity, (long long) max_blocks,
181                (long long) nq, counted ? "with their block count" : "without a block count", t_ref, t_new, t_ref / t_new,
182                (long long) same_cont, (long long) nq, (long long) same_tied,
183                (long long) nq, (long long) same_equal, (long long) nq);
184    return ok;
185}
186}  // namespace
187
188int main(int argc, char** argv) {
189    if (argc > 1 && std::strcmp(argv[1], "--selftest") == 0) {
190        // {context, capacity}: both sides of the register kernel's reach (33,792 blocks = 135,168 cells), short
191        // contexts under a long capacity (fewer blocks than the kernel's threads; a prompt batch below the dispatch's
192        // 4,608 blocks), and the long contexts themselves
193        const int64_t cases[][2] = {{9000, 9000},    {135160, 135160}, {135176, 135176}, {2100, 262144},
194                                    {9000, 262144},  {32768, 262144},  {262144, 262144}, {300001, 524288},
195                                    {524288, 524288}};
196        bool ok = true;
197        for (const auto& c : cases) {
198            ok = run_case(c[0], 8, 3, c[1], false) && ok;     // a decode window's call
199            ok = run_case(c[0], 64, 3, c[1], true) && ok;     // the prompt path's
200        }
201        std::printf("%s\n", ok ? "qsa_topk_parity: PASS" : "qsa_topk_parity: FAIL");
202        return ok ? 0 : 1;
203    }
204    if (argc < 2) {
205        std::fprintf(stderr, "usage: qsa_topk_parity --selftest | CONTEXT [QUERIES=256] [REPS=10] [CAPACITY=CONTEXT] "
206                             "[COUNT=1]\n");
207        return 2;
208    }
209    const int64_t ctx = std::atoll(argv[1]);
210    const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256;
211    const int reps = argc > 3 ? std::atoi(argv[3]) : 10;
212    const int64_t capacity = argc > 4 ? std::atoll(argv[4]) : ctx;
213    if (ctx < nq || nq <= 0 || reps <= 0 || capacity < ctx) {
214        std::fprintf(stderr, "qsa_topk_parity: CONTEXT >= QUERIES > 0, REPS > 0, CAPACITY >= CONTEXT\n");
215        return 2;
216    }
217    return run_case(ctx, nq, reps, capacity, argc <= 5 || std::atoi(argv[5]) != 0) ? 0 : 1;
218}