okami.mom/strata

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

Niko1221Merge the Aurora gfx1151 branch (f-halo-int + HCD_EXACT + the expert bundle) onto 0.1.39bc6b6f87a

main
7.0 KiB174 linesraw
1// src/kernels/cuda/cvec.cu - see include/strata/kernels/cvec.hpp.
2#include "strata/kernels/cvec.hpp"
3
4#include <cuda_runtime.h>
5
6#include <stdexcept>
7
8namespace strata::kernels {
9namespace {
10
11constexpr int THREADS = 256;
12constexpr int MAXK = 16;   // n_embd up to 4096, held in registers between the dot and the update
13
14Cvec g_cvec;                 // the description; its device pointers are the uploading device's
15bool g_on_host = false;
16// the tables on every device that holds them (a layer split applies the vector on several)
17constexpr int kDevices = 64;
18struct DevTables { float* dir = nullptr; float* s = nullptr; int* on = nullptr; };
19DevTables g_dev[kDevices];
20std::vector<float> g_dir_host, g_s_host;
21int cur_device() {
22    int d = 0;
23    if (cudaGetDevice(&d) != cudaSuccess || d < 0 || d >= kDevices) d = 0;
24    return d;
25}
26bool upload_here(std::string& err) {
27    DevTables& t = g_dev[cur_device()];
28    if (t.dir != nullptr) return true;
29    const int flag = g_on_host ? 1 : 0;
30    if (cudaMalloc(&t.dir, g_dir_host.size() * sizeof(float)) != cudaSuccess ||
31        cudaMalloc(&t.s, g_s_host.size() * sizeof(float)) != cudaSuccess || cudaMalloc(&t.on, sizeof(int)) != cudaSuccess ||
32        cudaMemcpy(t.dir, g_dir_host.data(), g_dir_host.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess ||
33        cudaMemcpy(t.s, g_s_host.data(), g_s_host.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess ||
34        cudaMemcpy(t.on, &flag, sizeof(int), cudaMemcpyHostToDevice) != cudaSuccess) {
35        err = "control vector: device allocation failed";
36        t = DevTables{};
37        return false;
38    }
39    return true;
40}
41
42// the fused hyper-connection read's gate (fused_gr.cu), so a write done here is bitwise the one it would have folded
43__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); }
44
45// one block per (stream, token): the pending write, then h . v over the stream, then the update
46__global__ void cvec_kernel(float* __restrict__ R, const float* __restrict__ dir, const float* __restrict__ s_l,
47                            const int* __restrict__ on, int mode, int64_t layer, int n, int hc, int64_t r_ld,
48                            const float* __restrict__ bo, int64_t bo_ld, const float* __restrict__ inj,
49                            int64_t inj_ld, int write) {
50    const int c = blockIdx.x;
51    const int64_t t = blockIdx.y;
52    float* r = R + t * r_ld + (int64_t) c * n;
53    const float s = s_l[layer];
54    const bool steer = *on != 0 && s != 0.0f;   // uniform over the block
55    if (!steer && !write) return;
56    const float* v = dir + layer * n;
57    const float w = write ? 2.0f * sigmoidf_(inj[t * inj_ld + c] / (float) hc) : 0.0f;
58    const float* b = write ? bo + t * bo_ld : nullptr;
59    float x[MAXK];
60    float dot = 0.0f;
61#pragma unroll
62    for (int k = 0; k < MAXK; ++k) {
63        const int d = threadIdx.x + k * THREADS;
64        if (d < n) {
65            float xv = r[d];
66            if (write) xv = fmaf(b[d], w, xv);
67            x[k] = xv;
68            if (steer && mode == 0) dot = fmaf(xv, v[d], dot);
69        }
70    }
71    if (steer && mode == 0) {
72        __shared__ float part[THREADS / 32];
73#pragma unroll
74        for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffffu, dot, o);
75        if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = dot;
76        __syncthreads();
77        if (threadIdx.x < 32) {
78            float p = threadIdx.x < THREADS / 32 ? part[threadIdx.x] : 0.0f;
79#pragma unroll
80            for (int o = 16; o > 0; o >>= 1) p += __shfl_xor_sync(0xffffffffu, p, o);
81            if (threadIdx.x == 0) part[0] = p;
82        }
83        __syncthreads();
84        dot = part[0] * s;   // s (h . v)
85    }
86#pragma unroll
87    for (int k = 0; k < MAXK; ++k) {
88        const int d = threadIdx.x + k * THREADS;
89        if (d < n) {
90            float xv = x[k];
91            if (steer) xv = mode == 0 ? fmaf(-dot, v[d], xv) : xv + v[d];
92            r[d] = xv;
93        }
94    }
95}
96
97}  // namespace
98
99const Cvec& cvec() { return g_cvec; }
100
101bool cvec_upload(const std::vector<float>& dir, const std::vector<float>& s, int mode, int first, int last,
102                 int64_t n_embd, int64_t hc, std::string& err) {
103    if (n_embd < 1 || n_embd > (int64_t) THREADS * MAXK) { err = "control vector: unsupported n_embd"; return false; }
104    if (s.empty() || dir.size() != s.size() * (size_t) n_embd) { err = "control vector: bad table sizes"; return false; }
105    int prev = 0;   // a new vector replaces the old one on every device
106    cudaGetDevice(&prev);
107    for (int d = 0; d < kDevices; ++d) {
108        if (g_dev[d].dir == nullptr) continue;
109        cudaSetDevice(d);
110        cudaDeviceSynchronize();
111        cudaFree(g_dev[d].dir);
112        cudaFree(g_dev[d].s);
113        cudaFree(g_dev[d].on);
114        g_dev[d] = DevTables{};
115    }
116    cudaSetDevice(prev);
117    g_dir_host = dir;
118    g_s_host = s;
119    g_on_host = true;
120    if (!upload_here(err)) return false;
121    const DevTables& t = g_dev[cur_device()];
122    g_cvec.dir = t.dir;
123    g_cvec.s = t.s;
124    g_cvec.on = t.on;
125    g_cvec.mode = mode;
126    g_cvec.first = first;
127    g_cvec.last = last;
128    g_cvec.n_embd = n_embd;
129    g_cvec.hc = hc;
130    g_cvec.steered.assign(s.size(), false);
131    for (size_t l = 0; l < s.size(); ++l) g_cvec.steered[l] = s[l] != 0.0f;
132    return true;
133}
134
135bool cvec_replicate(std::string& err) { return !g_cvec.loaded() || upload_here(err); }
136
137void cvec_set_enabled(bool on) {
138    if (!g_cvec.loaded() || on == g_on_host) return;
139    int prev = 0;
140    cudaGetDevice(&prev);
141    const int v = on ? 1 : 0;
142    for (int d = 0; d < kDevices; ++d) {
143        if (g_dev[d].on == nullptr) continue;
144        cudaSetDevice(d);
145        cudaDeviceSynchronize();   // nothing in flight may still read the flag
146        cudaMemcpy(g_dev[d].on, &v, sizeof(int), cudaMemcpyHostToDevice);
147    }
148    cudaSetDevice(prev);
149    g_on_host = on;
150}
151
152bool cvec_enabled() { return g_cvec.loaded() && g_on_host; }
153
154bool cvec_tables(const float** dir, const float** s, const int** on) {
155    if (!g_cvec.loaded()) return false;
156    const DevTables& t = g_dev[cur_device()];
157    if (t.dir == nullptr) return false;
158    *dir = t.dir; *s = t.s; *on = t.on;
159    return true;
160}
161
162void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj,
163                int64_t inj_ld, bool write, void* stream) {
164    if (!g_cvec.loaded() || T < 1) return;
165    const DevTables& t = g_dev[cur_device()];
166    if (t.dir == nullptr) throw std::runtime_error("cvec_apply: the control vector is not on this device (cvec_replicate)");
167    const dim3 grid((unsigned) g_cvec.hc, (unsigned) T);
168    cvec_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(R, t.dir, t.s, t.on, g_cvec.mode, layer,
169                                                            (int) g_cvec.n_embd, (int) g_cvec.hc, r_ld, bo, bo_ld,
170                                                            inj, inj_ld, write ? 1 : 0);
171    if (cudaPeekAtLastError() != cudaSuccess) throw std::runtime_error("cvec_apply: launch failed");
172}
173
174}  // namespace strata::kernels