// The compute interface. All model math that touches big arrays goes through it, so // the same forward pass runs on the CPU reference backend and on CUDA. // // Two kinds of objects live on the device: // Tensor : float32 activations, [rows, cols], row major. // Weight : a read-only matrix in its storage format (F32, BF16, F16 or bit planes). // Kernels decode it on the fly. // // The CPU backend is the reference: `hkimi selftest` runs every op on both with // random data and compares. #pragma once #include #include #include #include "format/planes.h" namespace hk { enum class WFmt : uint8_t { F32 = 0, BF16 = 1, F16 = 2, PLANES = 3 }; struct WeightDesc { WFmt fmt = WFmt::F32; int rows = 0, cols = 0; PlanesDesc planes; // used when fmt == PLANES (its rows / cols equal the ones above) // A dense weight some kernel reads as float32 whatever its size (the attention's kv_b). // A GPU expands it at load, so its memory is known from the start and its packed copy // leaves no hole among the weights loaded after it. bool as_f32 = false; }; struct WeightData { const uint8_t* dense = nullptr; // F32 / BF16 / F16: rows * cols little-endian elements PlanesView planes; // PLANES: scales + nplanes plane pointers }; struct Tensor { int rows = 0, cols = 0; virtual ~Tensor() = default; }; struct Weight { WeightDesc desc; virtual ~Weight() = default; }; enum class ActKind : uint8_t { SILU = 0, SITU = 1 }; struct Act { ActKind kind = ActKind::SILU; float beta = 1.0f; // SiTU: gate = beta * tanh(g / beta) * sigmoid(g) float lbeta = 0.0f; // SiTU: up = lbeta * tanh(u / lbeta); 0 = leave u as it is }; struct MlaShape { int heads = 0, nope = 0, rope = 0, vdim = 0, kv_rank = 0; }; // On a GPU, dense weights of at most this many numbers are expanded to float32 at load // (norm gains, biases, convolution kernels, small projections). Larger ones stay as // stored and are decoded on the fly: K3.1's router gates alone (6.4 million numbers in // each of 92 layers) would take 1.2 GB more of the card. constexpr int64_t kGpuExpandValues = (int64_t)1 << 20; class Backend { public: // which: "auto" (CUDA if this build has it and a GPU answers, else CPU), "cpu", "cuda" static std::unique_ptr create(const std::string& which); virtual ~Backend() = default; virtual const char* name() const = 0; virtual bool is_gpu() const = 0; virtual std::string device_name() const = 0; virtual int64_t mem_total() const = 0; // device memory (VRAM), or system RAM for the CPU backend virtual int64_t mem_used() const = 0; // bytes currently allocated through this backend // The most device memory ever held from the driver at one time, with what is kept // for reuse. 0 where it is not counted (CPU). virtual int64_t mem_peak() const { return 0; } // What could still be allocated right now: on a GPU, what the driver reports free plus // what the backend holds idle. Budgets start from this, not from mem_total(). virtual int64_t mem_free() const = 0; // Bytes on the device of a dense weight of `values` numbers stored with `stored_bytes` // each (2 for BF16). Small ones become float32, see kGpuExpandValues. virtual int64_t dense_bytes(int64_t values, int stored_bytes) const = 0; // ---- tensors ----------------------------------------------------------- virtual Tensor* alloc(int rows, int cols) = 0; virtual void release(Tensor* t) = 0; virtual void upload(Tensor* t, int row0, int nrows, const float* src) = 0; virtual void download(const Tensor* t, int row0, int nrows, float* dst) = 0; // dst[drow.., dcol..] = src[srow.., scol..] for an nrows x ncols block virtual void copy(Tensor* dst, int drow, int dcol, const Tensor* src, int srow, int scol, int nrows, int ncols) = 0; virtual void fill(Tensor* t, float v) = 0; // ---- weights ----------------------------------------------------------- virtual Weight* load(const WeightDesc& d, const WeightData& data) = 0; virtual void unload(Weight* w) = 0; // Several bit-plane weights whose bytes lie in one host block (an expert record: three // matrices with their scales and planes). Same result as `count` calls of load(), but a // GPU takes the block in one allocation and one copy, the weights pointing into it. virtual void load_block(const WeightDesc* descs, const WeightData* datas, int count, const uint8_t* block, int64_t block_bytes, Weight** out) { (void)block; (void)block_bytes; int done = 0; try { for (; done < count; ++done) out[done] = load(descs[done], datas[done]); } catch (...) { while (done > 0) unload(out[--done]); throw; } } // Host memory the backend will copy from again and again (the buffers expert records // are read into). A GPU page-locks it, so copies go straight from it. False: not locked // (no GPU, or the system refused), which only costs speed. unpin before freeing. virtual bool pin(void* p, int64_t bytes) { (void)p; (void)bytes; return false; } virtual void unpin(void* p) { (void)p; } // load_async is load() that may return before the bytes are on the device: `data` must // stay as it is, and the weight must not be used, until wait_loads() has returned. A GPU // copies on a stream of its own, so a layer's trunk can travel while the layer before // still works. It only overlaps when the bytes lie in page-locked memory (pin). Without // can_load_async, load_async is load(). virtual bool can_load_async() const { return false; } virtual Weight* load_async(const WeightDesc& d, const WeightData& data) { return load(d, data); } virtual void wait_loads() {} // ---- linear algebra ---------------------------------------------------- // Y[T, rows(W)] = alpha * X[T, cols(W)] * W^T, added to Y if accumulate. virtual void linear(const Weight* W, const Tensor* X, Tensor* Y, float alpha = 1.0f, bool accumulate = false) = 0; // Y[i, :] = row ids[i] of W (embedding lookup) virtual void gather(const Weight* W, const int32_t* ids, int n, Tensor* Y) = 0; // C = alpha * op(A) * op(B) + beta * C on plain tensors virtual void gemm(const Tensor* A, bool transpose_a, const Tensor* B, bool transpose_b, float alpha, float beta, Tensor* C) = 0; // ---- elementwise / normalization -------------------------------------- // RMSNorm over consecutive groups of `group` columns (group == cols: the usual RMSNorm). w is [1, group]. virtual void rmsnorm(const Tensor* X, const Weight* w, float eps, int group, Tensor* Y) = 0; // LayerNorm over the whole row (mean removed), weight and bias [1, cols] virtual void layernorm(const Tensor* X, const Weight* w, const Weight* b, float eps, Tensor* Y) = 0; virtual void axpy(Tensor* Y, const Tensor* X, float a) = 0; // Y += a * X virtual void mul_sigmoid(Tensor* Y, const Tensor* G) = 0; // Y *= sigmoid(G) virtual void glu(const Tensor* G, const Tensor* U, const Act& act, Tensor* Y) = 0; // gated linear unit virtual void take_rows(const Tensor* X, const int32_t* rows, int n, Tensor* Y) = 0; // Y[i] = X[rows[i]] virtual void scatter_add_rows(Tensor* Y, const int32_t* rows, const float* coef, int n, const Tensor* X) = 0; // Y[rows[i]] += coef[i] * X[i] // ---- Kimi Delta Attention --------------------------------------------- // Causal depthwise convolution over time followed by SiLU. // P [T, C] projections, w [C, K] kernel, ring [K-1, C] the previous K-1 inputs (updated in place). // y[t][c] = silu( sum_i w[c][i] * seq[t + i][c] ), seq = ring rows then P rows. virtual void kda_conv(const Tensor* P, const Weight* w, Tensor* ring, Tensor* Y) = 0; // Log-decay gate. Z [T, H*D]; A_log has at least H entries (one per head); dt_bias [1, H*D]. // bounded : G = lower_bound * sigmoid(exp(A_h) * (z + bias)) (K3) // else : G = -exp(A_h) * softplus(z + bias) (Kimi-Linear) virtual void kda_gate(const Tensor* Z, const Weight* A_log, const Weight* dt_bias, int heads, bool bounded, float lower_bound, Tensor* G) = 0; // The delta-rule recurrence, one head = one D x D state matrix (rows indexed by key dim). // q, k are L2-normalized per head here; q is also scaled by D^-0.5. // S <- diag(exp(g_t)) S ; S <- S + beta_t k_t (v_t - S^T k_t)^T ; o_t = S^T q_t // Blogit [T, H] (beta = sigmoid), S [H*D, D] carried across calls, O [T, H*D]. virtual void kda_recur(const Tensor* Q, const Tensor* K, const Tensor* V, const Tensor* G, const Tensor* Blogit, int heads, Tensor* S, Tensor* O) = 0; // ---- full attention (MLA), in latent form ------------------------------ // Keys and values are never expanded per head. The cache holds, per token, // C [kv_rank] (normalized latent) and R [rope] (the shared positional slice). // score(t,h,s) = ( (Wk_h^T q_nope) . C_s + q_rope . R_s ) / sqrt(nope + rope) // out(t,h) = Wv_h ( sum_s softmax(score)_s C_s ) // where Wk_h / Wv_h are the rows of kv_b that belong to head h. // Q [T, H*(nope+rope)], kv_b [H*(nope+vdim), kv_rank], C [>=S, kv_rank], R [>=S, rope]. // Query t sits at absolute position pos0 + t and sees keys 0..pos0+t. // sel (optional, host, T*S bytes): 0 = key not selected for that query (sparse attention). virtual 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) = 0; // indexer scores: Sc[t, s] = sum_h Wh[t, h] * relu( Qi[t, h, :] . Keys[s, :] ), s < S virtual void dsa_scores(const Tensor* Qi, const Tensor* Wh, const Tensor* Keys, int S, int heads, Tensor* Sc) = 0; // ---- attention residuals ---------------------------------------------- // Softmax attention over depth. Candidates are blocks[0..nb-1] and ps (all [T, d]). // key_i = v_i * rsqrt(mean(v_i^2) + eps); score_i = key_i . (wn * wp); Y = sum_i softmax(score)_i v_i // Y may be the same tensor as ps. virtual void attn_res(const Tensor* ps, Tensor* const* blocks, int nb, const Weight* wn, const Weight* wp, float eps, Tensor* Y) = 0; // wait until queued device work is done (no-op on the CPU); for timing virtual void sync() {} }; // in backend_cpu.cpp / backend_cuda.cu std::unique_ptr make_cpu_backend(); std::unique_ptr make_cuda_backend(std::string* why_not); // nullptr when unavailable // RAII, so that forward code cannot leak device memory on an exception class TensorRef { public: TensorRef() = default; TensorRef(Backend* b, int rows, int cols) : b_(b), t_(b->alloc(rows, cols)) {} ~TensorRef() { reset(); } TensorRef(TensorRef&& o) noexcept : b_(o.b_), t_(o.t_) { o.t_ = nullptr; } TensorRef& operator=(TensorRef&& o) noexcept { if (this != &o) { reset(); b_ = o.b_; t_ = o.t_; o.t_ = nullptr; } return *this; } TensorRef(const TensorRef&) = delete; TensorRef& operator=(const TensorRef&) = delete; void reset() { if (t_) b_->release(t_); t_ = nullptr; } // gives up ownership (the caller releases the tensor) Tensor* detach() { Tensor* t = t_; t_ = nullptr; return t; } Tensor* get() const { return t_; } operator Tensor*() const { return t_; } Tensor* operator->() const { return t_; } explicit operator bool() const { return t_ != nullptr; } private: Backend* b_ = nullptr; Tensor* t_ = nullptr; }; class WeightRef { public: WeightRef() = default; WeightRef(Backend* b, Weight* w) : b_(b), w_(w) {} ~WeightRef() { reset(); } WeightRef(WeightRef&& o) noexcept : b_(o.b_), w_(o.w_) { o.w_ = nullptr; } WeightRef& operator=(WeightRef&& o) noexcept { if (this != &o) { reset(); b_ = o.b_; w_ = o.w_; o.w_ = nullptr; } return *this; } WeightRef(const WeightRef&) = delete; WeightRef& operator=(const WeightRef&) = delete; void reset() { if (w_) b_->unload(w_); w_ = nullptr; } Weight* get() const { return w_; } operator const Weight*() const { return w_; } explicit operator bool() const { return w_ != nullptr; } private: Backend* b_ = nullptr; Weight* w_ = nullptr; }; } // namespace hk