Download src/gpu/backend_cpu.cpp from Ozomozyan/hkimi: direct link, hf CLI and curl.
- Browser
- Download file 25.7 kB
-
https://huggingface.co/Ozomozyan/hkimi/resolve/main/src/gpu/backend_cpu.cpp
- Command line
-
hf download hf://Ozomozyan/hkimi/src/gpu/backend_cpu.cpp
-
curl -L -o backend_cpu.cpp https://huggingface.co/Ozomozyan/hkimi/resolve/main/src/gpu/backend_cpu.cpp
25.7 kB
| // CPU reference backend, written for clarity first: the CUDA backend is checked | |
| // against it, and it is the fallback without a GPU. Dense weights are expanded to | |
| // float32 at load; bit-plane weights stay packed and are decoded a row at a time. | |
| namespace hk { | |
| namespace { | |
| struct CpuTensor : Tensor { | |
| std::vector<float> d; | |
| float* row(int r) { return d.data() + (size_t)r * (size_t)cols; } | |
| const float* row(int r) const { return d.data() + (size_t)r * (size_t)cols; } | |
| }; | |
| struct CpuWeight : Weight { | |
| std::vector<float> dense; // F32 / BF16 / F16, expanded | |
| std::vector<uint8_t> scales, planes[4]; // PLANES, as stored | |
| PlanesView view() const { | |
| PlanesView v; | |
| v.scales = scales.data(); | |
| for (int p = 0; p < desc.planes.nplanes; ++p) v.planes[p] = planes[p].data(); | |
| return v; | |
| } | |
| int64_t bytes() const { | |
| int64_t n = (int64_t)dense.size() * 4 + (int64_t)scales.size(); | |
| for (int p = 0; p < 4; ++p) n += (int64_t)planes[p].size(); | |
| return n; | |
| } | |
| // row r as floats: a pointer into dense storage, or decoded into tmp | |
| const float* row(int r, std::vector<float>& tmp) const { | |
| if (desc.fmt != WFmt::PLANES) return dense.data() + (size_t)r * (size_t)desc.cols; | |
| tmp.resize((size_t)desc.cols); | |
| planes_decode_row(desc.planes, view(), r, tmp.data()); | |
| return tmp.data(); | |
| } | |
| }; | |
| inline const CpuTensor* T(const Tensor* t) { return static_cast<const CpuTensor*>(t); } | |
| inline CpuTensor* T(Tensor* t) { return static_cast<CpuTensor*>(t); } | |
| inline const CpuWeight* W(const Weight* w) { return static_cast<const CpuWeight*>(w); } | |
| // eight partial sums, so the compiler can vectorize without -ffast-math | |
| inline float dot(const float* a, const float* b, int n) { | |
| float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0}; | |
| int i = 0; | |
| for (; i + 8 <= n; i += 8) | |
| for (int j = 0; j < 8; ++j) acc[j] += a[i + j] * b[i + j]; | |
| float s = ((acc[0] + acc[4]) + (acc[1] + acc[5])) + ((acc[2] + acc[6]) + (acc[3] + acc[7])); | |
| for (; i < n; ++i) s += a[i] * b[i]; | |
| return s; | |
| } | |
| inline void axpy_row(float* y, const float* x, float a, int n) { | |
| for (int i = 0; i < n; ++i) y[i] += a * x[i]; | |
| } | |
| class CpuBackend : public Backend { | |
| public: | |
| const char* name() const override { return "cpu"; } | |
| bool is_gpu() const override { return false; } | |
| std::string device_name() const override { return strfmt("CPU, %d threads", ThreadPool::global().size()); } | |
| int64_t mem_total() const override { return system_ram_bytes(); } | |
| int64_t mem_used() const override { return used_.load(); } | |
| int64_t mem_free() const override { return std::max<int64_t>(0, system_ram_bytes() - used_.load()); } | |
| int64_t dense_bytes(int64_t values, int) const override { return values * 4; } // everything is float32 here | |
| Tensor* alloc(int rows, int cols) override { | |
| HK_CHECK(rows >= 0 && cols >= 0, "bad tensor shape %d x %d", rows, cols); | |
| auto* t = new CpuTensor(); | |
| t->rows = rows; | |
| t->cols = cols; | |
| t->d.assign((size_t)rows * (size_t)cols, 0.0f); | |
| used_ += (int64_t)t->d.size() * 4; | |
| return t; | |
| } | |
| void release(Tensor* t) override { | |
| if (!t) return; | |
| used_ -= (int64_t)T(t)->d.size() * 4; | |
| delete t; | |
| } | |
| void upload(Tensor* t, int row0, int nrows, const float* src) override { | |
| check_rows(t, row0, nrows); | |
| memcpy(T(t)->row(row0), src, (size_t)nrows * (size_t)t->cols * 4); | |
| } | |
| void download(const Tensor* t, int row0, int nrows, float* dst) override { | |
| check_rows(t, row0, nrows); | |
| memcpy(dst, T(t)->row(row0), (size_t)nrows * (size_t)t->cols * 4); | |
| } | |
| void copy(Tensor* dst, int drow, int dcol, const Tensor* src, int srow, int scol, int nrows, int ncols) override { | |
| HK_CHECK(drow >= 0 && dcol >= 0 && srow >= 0 && scol >= 0 && drow + nrows <= dst->rows && dcol + ncols <= dst->cols && | |
| srow + nrows <= src->rows && scol + ncols <= src->cols, | |
| "copy block out of range"); | |
| for (int r = 0; r < nrows; ++r) | |
| memmove(T(dst)->row(drow + r) + dcol, T(src)->row(srow + r) + scol, (size_t)ncols * 4); | |
| } | |
| void fill(Tensor* t, float v) override { std::fill(T(t)->d.begin(), T(t)->d.end(), v); } | |
| Weight* load(const WeightDesc& d, const WeightData& data) override { | |
| auto* w = new CpuWeight(); | |
| w->desc = d; | |
| const size_t n = (size_t)d.rows * (size_t)d.cols; | |
| switch (d.fmt) { | |
| case WFmt::F32: | |
| w->dense.resize(n); | |
| memcpy(w->dense.data(), data.dense, n * 4); | |
| break; | |
| case WFmt::BF16: | |
| w->dense.resize(n); | |
| parallel_for((int64_t)n, 1 << 16, [&](int64_t b, int64_t e) { | |
| for (int64_t i = b; i < e; ++i) w->dense[(size_t)i] = bf16_to_f32(load_le16(data.dense + 2 * i)); | |
| }); | |
| break; | |
| case WFmt::F16: | |
| w->dense.resize(n); | |
| parallel_for((int64_t)n, 1 << 16, [&](int64_t b, int64_t e) { | |
| for (int64_t i = b; i < e; ++i) w->dense[(size_t)i] = f16_to_f32(load_le16(data.dense + 2 * i)); | |
| }); | |
| break; | |
| case WFmt::PLANES: { | |
| const PlanesDesc& p = d.planes; | |
| HK_CHECK(p.rows == d.rows && p.cols == d.cols, "planes descriptor does not match the weight shape"); | |
| HK_CHECK(p.cols % 32 == 0 && p.group % 32 == 0 && p.cols % p.group == 0, "planes weight %d x %d: bad grouping", | |
| p.rows, p.cols); | |
| w->scales.assign(data.planes.scales, data.planes.scales + p.scale_bytes()); | |
| for (int i = 0; i < p.nplanes; ++i) | |
| w->planes[i].assign(data.planes.planes[i], data.planes.planes[i] + p.plane_bytes()); | |
| break; | |
| } | |
| } | |
| used_ += w->bytes(); | |
| return w; | |
| } | |
| void unload(Weight* w) override { | |
| if (!w) return; | |
| used_ -= W(w)->bytes(); | |
| delete w; | |
| } | |
| void linear(const Weight* Wt, const Tensor* X, Tensor* Y, float alpha, bool accumulate) override { | |
| const CpuWeight* w = W(Wt); | |
| const int rows = w->desc.rows, cols = w->desc.cols, n = X->rows; | |
| HK_CHECK(X->cols == cols && Y->cols == rows && Y->rows == n, "linear: shapes X %dx%d, W %dx%d, Y %dx%d", X->rows, | |
| X->cols, rows, cols, Y->rows, Y->cols); | |
| const CpuTensor* x = T(X); | |
| CpuTensor* y = T(Y); | |
| // one weight row at a time: decode once, use it for every input row | |
| int64_t grain = std::max<int64_t>(1, (int64_t)(1 << 18) / std::max<int64_t>(1, (int64_t)cols * n)); | |
| parallel_for(rows, grain, [&](int64_t b, int64_t e) { | |
| std::vector<float> tmp; | |
| for (int64_t o = b; o < e; ++o) { | |
| const float* wr = w->row((int)o, tmp); | |
| for (int t = 0; t < n; ++t) { | |
| float v = alpha * dot(wr, x->row(t), cols); | |
| float* dst = y->row(t) + o; | |
| *dst = accumulate ? *dst + v : v; | |
| } | |
| } | |
| }); | |
| } | |
| void gather(const Weight* Wt, const int32_t* ids, int n, Tensor* Y) override { | |
| const CpuWeight* w = W(Wt); | |
| HK_CHECK(Y->rows >= n && Y->cols == w->desc.cols, "gather: output shape mismatch"); | |
| std::vector<float> tmp; | |
| for (int i = 0; i < n; ++i) { | |
| HK_CHECK(ids[i] >= 0 && ids[i] < w->desc.rows, "gather: row %d out of range", ids[i]); | |
| memcpy(T(Y)->row(i), w->row(ids[i], tmp), (size_t)w->desc.cols * 4); | |
| } | |
| } | |
| void gemm(const Tensor* A, bool ta, const Tensor* B, bool tb, float alpha, float beta, Tensor* C) override { | |
| const CpuTensor *a = T(A), *b = T(B); | |
| CpuTensor* c = T(C); | |
| const int m = ta ? a->cols : a->rows, k = ta ? a->rows : a->cols; | |
| const int kb = tb ? b->cols : b->rows, n = tb ? b->rows : b->cols; | |
| HK_CHECK(k == kb && c->rows == m && c->cols == n, "gemm: shape mismatch (%d x %d) * (%d x %d) -> %d x %d", m, k, kb, n, | |
| c->rows, c->cols); | |
| // small matrices: plain loops with an explicit transposed copy | |
| std::vector<float> at, bt; | |
| const float* ap = a->d.data(); | |
| if (ta) { // make A row-major [m, k] | |
| at.resize((size_t)m * (size_t)k); | |
| for (int i = 0; i < m; ++i) | |
| for (int j = 0; j < k; ++j) at[(size_t)i * k + j] = a->d[(size_t)j * a->cols + i]; | |
| ap = at.data(); | |
| } | |
| // B^T as [n, k] rows, so each output is a dot product | |
| bt.resize((size_t)n * (size_t)k); | |
| for (int j = 0; j < n; ++j) | |
| for (int l = 0; l < k; ++l) bt[(size_t)j * k + l] = tb ? b->d[(size_t)j * b->cols + l] : b->d[(size_t)l * b->cols + j]; | |
| parallel_for(m, std::max<int64_t>(1, (1 << 16) / std::max(1, n * k)), [&](int64_t r0, int64_t r1) { | |
| for (int64_t i = r0; i < r1; ++i) | |
| for (int j = 0; j < n; ++j) { | |
| float v = alpha * dot(ap + (size_t)i * k, bt.data() + (size_t)j * k, k); | |
| float* dst = c->row((int)i) + j; | |
| *dst = beta == 0.0f ? v : beta * *dst + v; | |
| } | |
| }); | |
| } | |
| void rmsnorm(const Tensor* X, const Weight* wt, float eps, int group, Tensor* Y) override { | |
| const CpuWeight* w = W(wt); | |
| HK_CHECK(X->cols % group == 0 && (int)w->dense.size() >= group && Y->rows == X->rows && Y->cols == X->cols, | |
| "rmsnorm: shape mismatch (cols %d, group %d, weight %zu)", X->cols, group, w->dense.size()); | |
| const float* g = w->dense.data(); | |
| parallel_for(X->rows, 16, [&](int64_t b, int64_t e) { | |
| for (int64_t r = b; r < e; ++r) { | |
| const float* x = T(X)->row((int)r); | |
| float* y = T(Y)->row((int)r); | |
| for (int c0 = 0; c0 < X->cols; c0 += group) { | |
| double ss = 0; | |
| for (int j = 0; j < group; ++j) ss += (double)x[c0 + j] * x[c0 + j]; | |
| float inv = 1.0f / std::sqrt((float)(ss / group) + eps); | |
| for (int j = 0; j < group; ++j) y[c0 + j] = x[c0 + j] * inv * g[j]; | |
| } | |
| } | |
| }); | |
| } | |
| void layernorm(const Tensor* X, const Weight* wt, const Weight* bt, float eps, Tensor* Y) override { | |
| const int n = X->cols; | |
| HK_CHECK((int)W(wt)->dense.size() >= n && (int)W(bt)->dense.size() >= n && Y->rows == X->rows && Y->cols == n, | |
| "layernorm: shape mismatch"); | |
| const float* g = W(wt)->dense.data(); | |
| const float* b = W(bt)->dense.data(); | |
| for (int r = 0; r < X->rows; ++r) { | |
| const float* x = T(X)->row(r); | |
| float* y = T(Y)->row(r); | |
| double mean = 0; | |
| for (int j = 0; j < n; ++j) mean += x[j]; | |
| mean /= n; | |
| double var = 0; | |
| for (int j = 0; j < n; ++j) var += (x[j] - mean) * (x[j] - mean); | |
| var /= n; | |
| float inv = 1.0f / std::sqrt((float)var + eps); | |
| for (int j = 0; j < n; ++j) y[j] = (float)(x[j] - mean) * inv * g[j] + b[j]; | |
| } | |
| } | |
| void axpy(Tensor* Y, const Tensor* X, float a) override { | |
| HK_CHECK(Y->rows == X->rows && Y->cols == X->cols, "axpy: shape mismatch"); | |
| axpy_row(T(Y)->d.data(), T(X)->d.data(), a, (int)T(Y)->d.size()); | |
| } | |
| void mul_sigmoid(Tensor* Y, const Tensor* G) override { | |
| HK_CHECK(Y->rows == G->rows && Y->cols == G->cols, "mul_sigmoid: shape mismatch"); | |
| float* y = T(Y)->d.data(); | |
| const float* g = T(G)->d.data(); | |
| for (size_t i = 0; i < T(Y)->d.size(); ++i) y[i] *= sigmoidf(g[i]); | |
| } | |
| void glu(const Tensor* G, const Tensor* U, const Act& act, Tensor* Y) override { | |
| HK_CHECK(G->rows == U->rows && G->cols == U->cols && Y->rows == G->rows && Y->cols == G->cols, "glu: shape mismatch"); | |
| const float* g = T(G)->d.data(); | |
| const float* u = T(U)->d.data(); | |
| float* y = T(Y)->d.data(); | |
| const size_t n = T(G)->d.size(); | |
| if (act.kind == ActKind::SILU) { | |
| for (size_t i = 0; i < n; ++i) y[i] = g[i] * sigmoidf(g[i]) * u[i]; | |
| } else { | |
| for (size_t i = 0; i < n; ++i) { | |
| float a = act.beta * std::tanh(g[i] / act.beta) * sigmoidf(g[i]); | |
| float b = act.lbeta > 0 ? act.lbeta * std::tanh(u[i] / act.lbeta) : u[i]; | |
| y[i] = a * b; | |
| } | |
| } | |
| } | |
| void take_rows(const Tensor* X, const int32_t* rows, int n, Tensor* Y) override { | |
| HK_CHECK(Y->rows >= n && Y->cols == X->cols, "take_rows: shape mismatch"); | |
| for (int i = 0; i < n; ++i) { | |
| HK_CHECK(rows[i] >= 0 && rows[i] < X->rows, "take_rows: row out of range"); | |
| memcpy(T(Y)->row(i), T(X)->row(rows[i]), (size_t)X->cols * 4); | |
| } | |
| } | |
| void scatter_add_rows(Tensor* Y, const int32_t* rows, const float* coef, int n, const Tensor* X) override { | |
| HK_CHECK(X->rows >= n && Y->cols == X->cols, "scatter_add_rows: shape mismatch"); | |
| for (int i = 0; i < n; ++i) { | |
| HK_CHECK(rows[i] >= 0 && rows[i] < Y->rows, "scatter_add_rows: row out of range"); | |
| axpy_row(T(Y)->row(rows[i]), T(X)->row(i), coef[i], X->cols); | |
| } | |
| } | |
| void kda_conv(const Tensor* P, const Weight* wt, Tensor* ring, Tensor* Y) override { | |
| const CpuWeight* w = W(wt); | |
| const int C = P->cols, K = w->desc.cols, n = P->rows; | |
| HK_CHECK(w->desc.rows == C && ring->rows == K - 1 && ring->cols == C && Y->rows == n && Y->cols == C, | |
| "kda_conv: shape mismatch"); | |
| const CpuTensor* p = T(P); | |
| CpuTensor* rg = T(ring); | |
| CpuTensor* y = T(Y); | |
| // seq(i) for i in [0, K-1) is the ring, then the new rows | |
| auto seq = [&](int i) -> const float* { return i < K - 1 ? rg->row(i) : p->row(i - (K - 1)); }; | |
| const float* k = w->dense.data(); | |
| for (int t = 0; t < n; ++t) { | |
| float* out = y->row(t); | |
| for (int c = 0; c < C; ++c) out[c] = 0; | |
| for (int i = 0; i < K; ++i) { | |
| const float* s = seq(t + i); | |
| for (int c = 0; c < C; ++c) out[c] += k[(size_t)c * K + i] * s[c]; | |
| } | |
| for (int c = 0; c < C; ++c) out[c] = out[c] * sigmoidf(out[c]); | |
| } | |
| // new ring: the last K-1 rows of the sequence | |
| std::vector<float> nr((size_t)(K - 1) * C); | |
| for (int i = 0; i < K - 1; ++i) memcpy(nr.data() + (size_t)i * C, seq(n + i), (size_t)C * 4); | |
| memcpy(rg->d.data(), nr.data(), nr.size() * 4); | |
| } | |
| void kda_gate(const Tensor* Z, const Weight* A_log, const Weight* dt_bias, int heads, bool bounded, float lb, | |
| Tensor* G) override { | |
| const int HD = Z->cols, D = HD / heads; | |
| HK_CHECK(HD % heads == 0 && (int)W(A_log)->dense.size() >= heads && (int)W(dt_bias)->dense.size() >= HD && | |
| G->rows == Z->rows && G->cols == HD, | |
| "kda_gate: shape mismatch"); | |
| const float* a = W(A_log)->dense.data(); | |
| const float* bias = W(dt_bias)->dense.data(); | |
| for (int t = 0; t < Z->rows; ++t) { | |
| const float* z = T(Z)->row(t); | |
| float* g = T(G)->row(t); | |
| for (int h = 0; h < heads; ++h) { | |
| float ea = std::exp(a[h]); | |
| for (int k = 0; k < D; ++k) { | |
| float v = z[h * D + k] + bias[h * D + k]; | |
| g[h * D + k] = bounded ? lb * sigmoidf(ea * v) : -ea * softplusf(v); | |
| } | |
| } | |
| } | |
| } | |
| void kda_recur(const Tensor* Q, const Tensor* K, const Tensor* V, const Tensor* G, const Tensor* Blogit, int heads, | |
| Tensor* S, Tensor* O) override { | |
| const int n = Q->rows, HD = Q->cols, D = HD / heads; | |
| HK_CHECK(HD % heads == 0 && K->cols == HD && V->cols == HD && G->cols == HD && Blogit->cols == heads && S->rows == HD && | |
| S->cols == D && O->rows == n && O->cols == HD && K->rows == n && V->rows == n && G->rows == n && | |
| Blogit->rows == n, | |
| "kda_recur: shape mismatch"); | |
| const float qscale = 1.0f / std::sqrt((float)D); | |
| parallel_for(heads, 1, [&](int64_t h0, int64_t h1) { | |
| std::vector<float> qn((size_t)D), kn((size_t)D), u((size_t)D), dlt((size_t)D); | |
| for (int64_t h = h0; h < h1; ++h) { | |
| float* s = T(S)->row((int)h * D); // D rows of D | |
| for (int t = 0; t < n; ++t) { | |
| const float* q = T(Q)->row(t) + h * D; | |
| const float* k = T(K)->row(t) + h * D; | |
| const float* v = T(V)->row(t) + h * D; | |
| const float* g = T(G)->row(t) + h * D; | |
| float beta = sigmoidf(T(Blogit)->row(t)[h]); | |
| // F.normalize: x / max(||x||, 1e-12) | |
| float qq = std::sqrt(dot(q, q, D)), kk = std::sqrt(dot(k, k, D)); | |
| float qi = qscale / std::max(qq, 1e-12f), ki = 1.0f / std::max(kk, 1e-12f); | |
| for (int i = 0; i < D; ++i) { | |
| qn[(size_t)i] = q[i] * qi; | |
| kn[(size_t)i] = k[i] * ki; | |
| } | |
| // decay rows, u = S^T k | |
| for (int j = 0; j < D; ++j) u[(size_t)j] = 0; | |
| for (int i = 0; i < D; ++i) { | |
| float dec = std::exp(g[i]); | |
| float* si = s + (size_t)i * D; | |
| float ki2 = kn[(size_t)i]; | |
| for (int j = 0; j < D; ++j) { | |
| si[j] *= dec; | |
| u[(size_t)j] += ki2 * si[j]; | |
| } | |
| } | |
| for (int j = 0; j < D; ++j) dlt[(size_t)j] = beta * (v[j] - u[(size_t)j]); | |
| // rank-1 update and output o = S^T q | |
| float* o = T(O)->row(t) + h * D; | |
| for (int j = 0; j < D; ++j) o[j] = 0; | |
| for (int i = 0; i < D; ++i) { | |
| float* si = s + (size_t)i * D; | |
| float ki2 = kn[(size_t)i], qi2 = qn[(size_t)i]; | |
| for (int j = 0; j < D; ++j) { | |
| si[j] += ki2 * dlt[(size_t)j]; | |
| o[j] += qi2 * si[j]; | |
| } | |
| } | |
| } | |
| } | |
| }); | |
| } | |
| void mla_attend(const MlaShape& sh, const Tensor* Q, const Weight* kv_b, const Tensor* C, const Tensor* R, int S, | |
| int pos0, const uint8_t* sel, Tensor* O) override { | |
| const int H = sh.heads, n = sh.nope, r = sh.rope, v = sh.vdim, kr = sh.kv_rank, qd = n + r, nq = Q->rows; | |
| const CpuWeight* kb = W(kv_b); | |
| HK_CHECK(kb->desc.fmt != WFmt::PLANES, "kv_b_proj must be a dense weight"); | |
| HK_CHECK(Q->cols == H * qd && kb->desc.rows == H * (n + v) && kb->desc.cols == kr && C->cols == kr && R->cols == r && | |
| C->rows >= S && R->rows >= S && O->rows == nq && O->cols == H * v && pos0 + nq <= S, | |
| "mla_attend: shape mismatch"); | |
| const float scale = 1.0f / std::sqrt((float)qd); | |
| const float* wkb = kb->dense.data(); | |
| parallel_for(nq, 1, [&](int64_t t0, int64_t t1) { | |
| std::vector<float> qa((size_t)kr), sc((size_t)S), mix((size_t)kr); | |
| for (int64_t t = t0; t < t1; ++t) { | |
| const int nkeys = pos0 + (int)t + 1; | |
| const float* q = T(Q)->row((int)t); | |
| float* out = T(O)->row((int)t); | |
| const uint8_t* mask = sel ? sel + (size_t)t * (size_t)S : nullptr; | |
| for (int h = 0; h < H; ++h) { | |
| const float* qh = q + h * qd; | |
| const float* wk = wkb + (size_t)h * (n + v) * kr; // [n, kr] | |
| const float* wv = wk + (size_t)n * kr; // [v, kr] | |
| for (int c = 0; c < kr; ++c) qa[(size_t)c] = 0; | |
| for (int i = 0; i < n; ++i) axpy_row(qa.data(), wk + (size_t)i * kr, qh[i], kr); | |
| float mx = -1e30f; | |
| for (int s = 0; s < nkeys; ++s) { | |
| if (mask && !mask[s]) { | |
| sc[(size_t)s] = -1e30f; | |
| continue; | |
| } | |
| float a = (dot(qa.data(), T(C)->row(s), kr) + dot(qh + n, T(R)->row(s), r)) * scale; | |
| sc[(size_t)s] = a; | |
| mx = std::max(mx, a); | |
| } | |
| double sum = 0; | |
| for (int s = 0; s < nkeys; ++s) { | |
| float e = sc[(size_t)s] <= -1e29f ? 0.0f : std::exp(sc[(size_t)s] - mx); | |
| sc[(size_t)s] = e; | |
| sum += e; | |
| } | |
| float inv = sum > 0 ? (float)(1.0 / sum) : 0.0f; | |
| for (int c = 0; c < kr; ++c) mix[(size_t)c] = 0; | |
| for (int s = 0; s < nkeys; ++s) | |
| if (sc[(size_t)s] != 0.0f) axpy_row(mix.data(), T(C)->row(s), sc[(size_t)s] * inv, kr); | |
| for (int j = 0; j < v; ++j) out[h * v + j] = dot(wv + (size_t)j * kr, mix.data(), kr); | |
| } | |
| } | |
| }); | |
| } | |
| void dsa_scores(const Tensor* Qi, const Tensor* Wh, const Tensor* Keys, int S, int heads, Tensor* Sc) override { | |
| const int D = Keys->cols, nq = Qi->rows; | |
| HK_CHECK(Qi->cols == heads * D && Wh->rows == nq && Wh->cols == heads && Keys->rows >= S && Sc->rows == nq && | |
| Sc->cols >= S, | |
| "dsa_scores: shape mismatch"); | |
| parallel_for(nq, 1, [&](int64_t t0, int64_t t1) { | |
| for (int64_t t = t0; t < t1; ++t) { | |
| const float* q = T(Qi)->row((int)t); | |
| const float* w = T(Wh)->row((int)t); | |
| float* out = T(Sc)->row((int)t); | |
| for (int s = 0; s < S; ++s) { | |
| const float* key = T(Keys)->row(s); | |
| float acc = 0; | |
| for (int h = 0; h < heads; ++h) { | |
| float d = dot(q + h * D, key, D); | |
| if (d > 0) acc += w[h] * d; | |
| } | |
| out[s] = acc; | |
| } | |
| } | |
| }); | |
| } | |
| void attn_res(const Tensor* ps, Tensor* const* blocks, int nb, const Weight* wn, const Weight* wp, float eps, | |
| Tensor* Y) override { | |
| const int d = ps->cols, n = ps->rows; | |
| HK_CHECK((int)W(wn)->dense.size() >= d && (int)W(wp)->dense.size() >= d && Y->rows == n && Y->cols == d, | |
| "attn_res: shape mismatch"); | |
| for (int i = 0; i < nb; ++i) HK_CHECK(blocks[i]->rows == n && blocks[i]->cols == d, "attn_res: block shape mismatch"); | |
| std::vector<float> wq((size_t)d); | |
| for (int c = 0; c < d; ++c) wq[(size_t)c] = W(wn)->dense[(size_t)c] * W(wp)->dense[(size_t)c]; | |
| parallel_for(n, 8, [&](int64_t t0, int64_t t1) { | |
| std::vector<float> sc((size_t)nb + 1), out((size_t)d); | |
| for (int64_t t = t0; t < t1; ++t) { | |
| float mx = -1e30f; | |
| for (int i = 0; i <= nb; ++i) { | |
| const float* v = i < nb ? T(blocks[i])->row((int)t) : T(ps)->row((int)t); | |
| float inv = 1.0f / std::sqrt(dot(v, v, d) / (float)d + eps); | |
| sc[(size_t)i] = dot(v, wq.data(), d) * inv; | |
| mx = std::max(mx, sc[(size_t)i]); | |
| } | |
| float sum = 0; | |
| for (int i = 0; i <= nb; ++i) { | |
| sc[(size_t)i] = std::exp(sc[(size_t)i] - mx); | |
| sum += sc[(size_t)i]; | |
| } | |
| std::fill(out.begin(), out.end(), 0.0f); | |
| for (int i = 0; i <= nb; ++i) { | |
| const float* v = i < nb ? T(blocks[i])->row((int)t) : T(ps)->row((int)t); | |
| axpy_row(out.data(), v, sc[(size_t)i] / sum, d); | |
| } | |
| memcpy(T(Y)->row((int)t), out.data(), (size_t)d * 4); // after reading ps: Y may alias it | |
| } | |
| }); | |
| } | |
| private: | |
| static void check_rows(const Tensor* t, int row0, int nrows) { | |
| HK_CHECK(row0 >= 0 && nrows >= 0 && row0 + nrows <= t->rows, "row range [%d, +%d) outside a tensor with %d rows", row0, | |
| nrows, t->rows); | |
| } | |
| std::atomic<int64_t> used_{0}; | |
| }; | |
| } // namespace | |
| std::unique_ptr<Backend> make_cpu_backend() { return std::unique_ptr<Backend>(new CpuBackend()); } | |
| std::unique_ptr<Backend> Backend::create(const std::string& which) { | |
| HK_CHECK(which == "auto" || which == "cpu" || which == "cuda", "unknown backend \"%s\" (use auto, cpu or cuda)", which.c_str()); | |
| if (which != "cpu") { | |
| std::string why; | |
| std::unique_ptr<Backend> b = make_cuda_backend(&why); | |
| if (b) return b; | |
| HK_CHECK(which == "auto", "CUDA backend unavailable: %s", why.c_str()); | |
| HK_INFO("no CUDA backend (%s): running on the CPU", why.c_str()); | |
| } | |
| return make_cpu_backend(); | |
| } | |
| std::unique_ptr<Backend> make_cuda_backend(std::string* why) { | |
| if (why) *why = "this build was compiled without CUDA"; | |
| return nullptr; | |
| } | |
| } // namespace hk | |