okami.mom/strata

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

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

main
12.5 KiB311 linesraw
1// src/kernels/cuda/cvec.cu - see include/strata/kernels/cvec.hpp.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include "strata/kprof.hpp"
5#include <dpct/dpct.hpp>
6#include "strata/sycl_queue.hpp"
7#include "strata/kernels/cvec.hpp"
8
9#include <stdexcept>
10
11namespace strata::kernels {
12namespace {
13
14constexpr int THREADS = 256;
15constexpr int MAXK = 16;   // n_embd up to 4096, held in registers between the dot and the update
16
17Cvec g_cvec;                 // the description; its device pointers are the uploading device's
18bool g_on_host = false;
19// the tables on every device that holds them (a layer split applies the vector on several)
20constexpr int kDevices = 64;
21struct DevTables { float* dir = nullptr; float* s = nullptr; int* on = nullptr; };
22DevTables g_dev[kDevices];
23std::vector<float> g_dir_host, g_s_host;
24int cur_device() try {
25    int d = 0;
26    if (DPCT_CHECK_ERROR(d = dpct::get_current_device_id()) != 0 || d < 0 ||
27        d >= kDevices) d = 0;
28    return d;
29}
30catch (sycl::exception const &exc) {
31  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
32            << ", line:" << __LINE__ << std::endl;
33  std::exit(1);
34}
35bool upload_here(std::string &err) try {
36    DevTables& t = g_dev[cur_device()];
37    if (t.dir != nullptr) return true;
38    const int flag = g_on_host ? 1 : 0;
39    if (DPCT_CHECK_ERROR(t.dir = sycl::malloc_device<float>(
40                             g_dir_host.size(), dpct::get_in_order_queue())) !=
41            0 ||
42        DPCT_CHECK_ERROR(t.s = sycl::malloc_device<float>(
43                             g_s_host.size(), dpct::get_in_order_queue())) !=
44            0 ||
45        DPCT_CHECK_ERROR(t.on = sycl::malloc_device<int>(
46                             1, dpct::get_in_order_queue())) != 0 ||
47        /*
48        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
49        assuming in the original code the source host memory is pageable memory.
50        If the memory is not pageable, call wait() on event return by memcpy API
51        to ensure synchronization behavior.
52        */
53        DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
54            t.dir, g_dir_host.data(), g_dir_host.size() * sizeof(float)).wait()) !=
55            0 ||
56        /*
57        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
58        assuming in the original code the source host memory is pageable memory.
59        If the memory is not pageable, call wait() on event return by memcpy API
60        to ensure synchronization behavior.
61        */
62        DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
63            t.s, g_s_host.data(), g_s_host.size() * sizeof(float)).wait()) != 0 ||
64        DPCT_CHECK_ERROR(dpct::get_in_order_queue()
65                             .memcpy(t.on, &flag, sizeof(int))
66                             .wait()) != 0) {
67        err = "control vector: device allocation failed";
68        t = DevTables{};
69        return false;
70    }
71    return true;
72}
73catch (sycl::exception const &exc) {
74  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
75            << ", line:" << __LINE__ << std::endl;
76  std::exit(1);
77}
78
79// the fused hyper-connection read's gate (fused_gr.cu), so a write done here is bitwise the one it would have folded
80__dpct_inline__ float sigmoidf_(float x) {
81    return 1.0f / (1.0f + sycl::native::exp(-x));
82}
83
84// one block per (stream, token): the pending write, then h . v over the stream, then the update
85/*
86DPCT1110: The total declared local variable size in device function
87cvec_kernel exceeds 128 bytes and may cause high register pressure. Consult with
88your hardware vendor to find the total register size available and adjust the
89code, or use smaller sub-group size to avoid high register pressure.
90*/
91__dpct_inline__ void
92cvec_kernel(float *__restrict__ R, const float *__restrict__ dir,
93            const float *__restrict__ s_l, const int *__restrict__ on, int mode,
94            int64_t layer, int n, int hc, int64_t r_ld,
95            const float *__restrict__ bo, int64_t bo_ld,
96            const float *__restrict__ inj, int64_t inj_ld, int write) {
97    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
98    const int c = item_ct1.get_group(2);
99    const int64_t t = item_ct1.get_group(1);
100    float* r = R + t * r_ld + (int64_t) c * n;
101    const float s = s_l[layer];
102    const bool steer = *on != 0 && s != 0.0f;   // uniform over the block
103    if (!steer && !write) return;
104    const float* v = dir + layer * n;
105    const float w = write ? 2.0f * sigmoidf_(inj[t * inj_ld + c] / (float) hc) : 0.0f;
106    const float* b = write ? bo + t * bo_ld : nullptr;
107    float x[MAXK];
108    float dot = 0.0f;
109#pragma unroll
110    for (int k = 0; k < MAXK; ++k) {
111        const int d = item_ct1.get_local_id(2) + k * THREADS;
112        if (d < n) {
113            float xv = r[d];
114            if (write) xv = sycl::fma((float)(b[d]), (float)w, xv);
115            x[k] = xv;
116            if (steer && mode == 0) dot = sycl::fma(xv, (float)(v[d]), dot);
117        }
118    }
119    if (steer && mode == 0) {
120        auto &part = *sycl::ext::oneapi::group_local_memory_for_overwrite<
121            float[THREADS / 32]>(
122            sycl::ext::oneapi::this_work_item::get_work_group<3>());
123#pragma unroll
124        /*
125        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
126        feature masked sub_group function which may not be supported by all
127        compilers or runtimes. You may need to adjust the code.
128        */
129        for (int o = 16; o > 0; o >>= 1) dot +=
130            dpct::experimental::permute_sub_group_by_xor(
131                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
132                dot, o);
133        if ((item_ct1.get_local_id(2) & 31) == 0)
134            part[item_ct1.get_local_id(2) >> 5] = dot;
135        /*
136        DPCT1118: SYCL group functions and algorithms must be encountered in
137        converged control flow. You may need to adjust the code.
138        */
139        /*
140        DPCT1065: Consider replacing sycl::nd_item::barrier() with
141        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
142        better performance if there is no access to global memory.
143        */
144        item_ct1.barrier();
145        if (item_ct1.get_local_id(2) < 32) {
146            float p = item_ct1.get_local_id(2) < THREADS / 32
147                          ? part[item_ct1.get_local_id(2)]
148                          : 0.0f;
149#pragma unroll
150            /*
151            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
152            feature masked sub_group function which may not be supported by all
153            compilers or runtimes. You may need to adjust the code.
154            */
155            for (int o = 16; o > 0; o >>= 1) p +=
156                dpct::experimental::permute_sub_group_by_xor(
157                    0xffffffffu,
158                    sycl::ext::oneapi::this_work_item::get_sub_group(), p, o);
159            if (item_ct1.get_local_id(2) == 0) part[0] = p;
160        }
161        /*
162        DPCT1118: SYCL group functions and algorithms must be encountered in
163        converged control flow. You may need to adjust the code.
164        */
165        /*
166        DPCT1065: Consider replacing sycl::nd_item::barrier() with
167        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
168        better performance if there is no access to global memory.
169        */
170        item_ct1.barrier();
171        dot = part[0] * s;   // s (h . v)
172    }
173#pragma unroll
174    for (int k = 0; k < MAXK; ++k) {
175        const int d = item_ct1.get_local_id(2) + k * THREADS;
176        if (d < n) {
177            float xv = x[k];
178            if (steer) xv =
179                mode == 0 ? sycl::fma(-dot, (float)(v[d]), xv) : xv + v[d];
180            r[d] = xv;
181        }
182    }
183}
184
185}  // namespace
186
187const Cvec& cvec() { return g_cvec; }
188
189bool cvec_upload(const std::vector<float>& dir, const std::vector<float>& s, int mode, int first, int last,
190                 int64_t n_embd, int64_t hc, std::string& err) {
191    if (n_embd < 1 || n_embd > (int64_t) THREADS * MAXK) { err = "control vector: unsupported n_embd"; return false; }
192    if (s.empty() || dir.size() != s.size() * (size_t) n_embd) { err = "control vector: bad table sizes"; return false; }
193    int prev = 0;   // a new vector replaces the old one on every device
194    prev = dpct::get_current_device_id();
195    for (int d = 0; d < kDevices; ++d) {
196        if (g_dev[d].dir == nullptr) continue;
197        /*
198        DPCT1093: The "d" device may be not the one intended for use.
199        Adjust the selected device if needed.
200        */
201        dpct::select_device(d);
202        dpct::get_current_device().queues_wait_and_throw();
203        sycl::free(g_dev[d].dir, dpct::get_in_order_queue());
204        sycl::free(g_dev[d].s, dpct::get_in_order_queue());
205        sycl::free(g_dev[d].on, dpct::get_in_order_queue());
206        g_dev[d] = DevTables{};
207    }
208    /*
209    DPCT1093: The "prev" device may be not the one intended for use. Adjust
210    the selected device if needed.
211    */
212    dpct::select_device(prev);
213    g_dir_host = dir;
214    g_s_host = s;
215    g_on_host = true;
216    if (!upload_here(err)) return false;
217    const DevTables& t = g_dev[cur_device()];
218    g_cvec.dir = t.dir;
219    g_cvec.s = t.s;
220    g_cvec.on = t.on;
221    g_cvec.mode = mode;
222    g_cvec.first = first;
223    g_cvec.last = last;
224    g_cvec.n_embd = n_embd;
225    g_cvec.hc = hc;
226    g_cvec.steered.assign(s.size(), false);
227    for (size_t l = 0; l < s.size(); ++l) g_cvec.steered[l] = s[l] != 0.0f;
228    return true;
229}
230
231bool cvec_replicate(std::string& err) { return !g_cvec.loaded() || upload_here(err); }
232
233void cvec_set_enabled(bool on) {
234    if (!g_cvec.loaded() || on == g_on_host) return;
235    int prev = 0;
236    prev = dpct::get_current_device_id();
237    const int v = on ? 1 : 0;
238    for (int d = 0; d < kDevices; ++d) {
239        if (g_dev[d].on == nullptr) continue;
240        /*
241        DPCT1093: The "d" device may be not the one intended for use.
242        Adjust the selected device if needed.
243        */
244        dpct::select_device(d);
245        dpct::get_current_device()
246            .queues_wait_and_throw(); // nothing in flight may still read the
247                                      // flag
248        dpct::get_in_order_queue().memcpy(g_dev[d].on, &v, sizeof(int)).wait();
249    }
250    /*
251    DPCT1093: The "prev" device may be not the one intended for use. Adjust
252    the selected device if needed.
253    */
254    dpct::select_device(prev);
255    g_on_host = on;
256}
257
258bool cvec_enabled() { return g_cvec.loaded() && g_on_host; }
259
260bool cvec_tables(const float** dir, const float** s, const int** on) {
261    if (!g_cvec.loaded()) return false;
262    const DevTables& t = g_dev[cur_device()];
263    if (t.dir == nullptr) return false;
264    *dir = t.dir; *s = t.s; *on = t.on;
265    return true;
266}
267
268void cvec_apply(float *R, int64_t layer, int64_t T, int64_t r_ld,
269                const float *bo, int64_t bo_ld, const float *inj,
270                int64_t inj_ld, bool write, void *stream) try {
271    if (!g_cvec.loaded() || T < 1) return;
272    const DevTables& t = g_dev[cur_device()];
273    if (t.dir == nullptr) throw std::runtime_error("cvec_apply: the control vector is not on this device (cvec_replicate)");
274    const dpct::dim3 grid((unsigned)g_cvec.hc, (unsigned)T);
275    {
276        auto exp_props = sycl::ext::oneapi::experimental::properties{
277            sycl::ext::oneapi::experimental::use_root_sync};
278
279        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
280            ->submit([&](sycl::handler &cgh) {
281                auto g_cvec_mode_ct4 = g_cvec.mode;
282                auto g_cvec_n_embd_ct6 = (int)g_cvec.n_embd;
283                auto g_cvec_hc_ct7 = (int)g_cvec.hc;
284
285                cgh.parallel_for<dpct_kernel_name<class cvec_kernel_a17328>>(
286                    sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
287                                      sycl::range(1, 1, THREADS)),
288                    exp_props,
289                    [=](sycl::nd_item<3> item_ct1)
290                        [[sycl::reqd_sub_group_size(32)]] {
291                            cvec_kernel(R, t.dir, t.s, t.on, g_cvec_mode_ct4,
292                                        layer, g_cvec_n_embd_ct6, g_cvec_hc_ct7,
293                                        r_ld, bo, bo_ld, inj, inj_ld,
294                                        write ? 1 : 0);
295                        });
296            });
297    }
298    /*
299    DPCT1010: SYCL uses exceptions to report errors and does not use the
300    error codes. The cudaPeekAtLastError function call was replaced with 0. You
301    need to rewrite this code.
302    */
303    if (0 != 0) throw std::runtime_error("cvec_apply: launch failed");
304}
305catch (sycl::exception const &exc) {
306  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
307            << ", line:" << __LINE__ << std::endl;
308  std::exit(1);
309}
310
311}  // namespace strata::kernels