From 459dd4f42d487eea4c4de5dd25501b1d996e9483 Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Tue, 20 Oct 2026 14:39:19 +0700 Subject: [PATCH] vocabulary: hc_project -- a control vector's direction, projected out of the wide stream h[s] -= scale * (h[s] . v) * v for each of the hyper-connection streams s llama.cpp's --cvec-mode project semantics: the dot is per stream, because the patch applies it to the [n_embd, hc, tokens] view where mul_mat(v, cur) reduces over dim 0. v is one layer's unit direction (f32), scale is the norm its file stored, and 'on' is a per-row int32 switch: a zero row is skipped without a read or a write, so an unprojected request is byte-identical to a deployment with no vector loaded. libref is the oracle and the host fallback, libavx carries it at every ISA level, libr4d (one workgroup per (row, stream), LDS reduction) serves the card. docs/OPS.md gains the row and the operation's three facts. --- docs/OPS.md | 8 +++ libavx/avx_cases.cpp | 7 ++ libavx/avx_hc.cpp | 58 +++++++++++++++ libavx/avx_isa.h | 22 +++--- libavx/avx_registry.cpp | 10 +++ libr4d/CMakeLists.txt | 3 + libr4d/r4d_hc_project.hip | 144 ++++++++++++++++++++++++++++++++++++++ libr4d/r4d_plugin.h | 2 + libr4d/r4d_rows.cpp | 25 +++++++ libr4d/r4d_shapes.cpp | 13 ++++ libref/ref_hc.cpp | 53 ++++++++++++++ libref/ref_ops.h | 2 + libref/ref_registry.cpp | 15 ++++ libref/ref_shapes.cpp | 11 +++ 14 files changed, 362 insertions(+), 11 deletions(-) create mode 100644 libr4d/r4d_hc_project.hip diff --git a/docs/OPS.md b/docs/OPS.md index cf02fa96..b8be4ef2 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -199,6 +199,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | `mhc_contract` | `M`(range) `n` `hc` `dtype` | `h` → `x` | | `hc_read` | `M`(range) `n` `hc` `lowrank` `eps`:f64 `dtype` `wadd`:f64/opt `inject`/opt `group`/opt `rotate`/opt `mix`/opt | `h`, `w`w, `mix_down`w, `mix_up`w, `inject_w`w? → `x`, `inj`?, `q`?, `scale`?, `rq`?, `rscale`? | | `hc_write` | `M`(range) `n` `hc` `dtype` | `y`, `inj`, `h`:inout | +| `hc_project` | `M`(range) `n` `hc` `scale`:f64 `dtype` | `h`:inout, `v`, `on` | | `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` | | `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | | `grid_embed_aa` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | @@ -307,6 +308,13 @@ so a different op rather than a mode a library could ignore. ### Hyper-connections +`hc_project` is the control vector's projection (core/cvec.h): `h[s] -= +scale * (h[s] . v) * v` for each of the `hc` streams of a row whose `on` flag (an int32 per row) is +1, `v` being that layer's unit direction and `scale` the norm the file stored. It is llama.cpp's +`--cvec-mode project`, applied after a layer's write into the stream. A row whose flag is 0 is +neither read nor written, so an unprojected request's stream is the stock model's; the direction table is f32 and the op is issued only by an architecture that was +declared with one (`RadBuildCtx::cvec`). + `hc_read` and `hc_write` are the gated residual pair a hyper-connection model has instead of a pre-norm and a residual add. The stream is `hc` times the model width; every block reads a mix of the `hc` sub-streams and writes back into all of them, both gated by data: diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index cdc34b1b..1ec95836 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -147,6 +147,13 @@ std::vector build_cases() { HF("lower_bound", -5), HF("scale", 0.1767766952966369), HF("l2_eps", 1e-6), HS("mode", mode), HS("dtype", dt) }); add("hc_write", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) }); + add("hc_project",{ HI("M", 5), HI("n", 128), HI("hc", 4), HF("scale", 1.0), + HS("dtype", dt) }); + /* The model's own width: Qwen3.8-Flash-Next's stream is 2560 wide with hc 4, and a decode + * step is one row per sequence (with speculation, up to 1 + depth). One case at that + * geometry is what says whether 41 of these a step is affordable. */ + add("hc_project",{ HI("M", 4), HI("n", 2560), HI("hc", 4), HF("scale", 1.0), + HS("dtype", "bf16") }); add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8), HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 1), HI("inject", 1), HI("group", 0) }); diff --git a/libavx/avx_hc.cpp b/libavx/avx_hc.cpp index a2462447..4c7cea3c 100644 --- a/libavx/avx_hc.cpp +++ b/libavx/avx_hc.cpp @@ -331,6 +331,64 @@ AVX_KERNEL(hc_write) { return RAD_OK; } +/* ------------------------------------------------------------------ hc_project */ +/* The experimental speed projection (core/cvec.h): h[s] -= scale * (h[s] . v) * v for each of the + * hc streams of a row whose switch is on. v is f32, the stream may be bf16/f16/f32; a row with a + * zero switch is skipped without a read, so an unprojected request is byte-identical to one on a + * deployment with no vector. */ +AVX_KERNEL(hc_project) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor* h = &a->t[0]; + const RadTensor* v = &a->t[1]; + const RadTensor* on = &a->t[2]; + + const int64_t n = p_int(a, "n", 0); + const int64_t hc = p_int(a, "hc", 0); + const float sc = p_f32(a, "scale", 1.0f); + if (n <= 0 || hc <= 1 || numel(v) < n) return RAD_E_SHAPE; + const int64_t hn = hc * n; + const int64_t rows = numel(h) / hn; + if (rows <= 0 || numel(on) < rows) return RAD_E_SHAPE; + + const int64_t vb = rowoff(v, 0, n); + float* vbuf = scratch_f32_c((size_t) n); + const float* vec = in_row(v, vb, n, vbuf); + + AVX_PARALLEL_FOR_IF(rows * hn >= AVX_PAR_MIN) + for (int64_t k = 0; k < rows * hc; ++k) { + const int64_t r = k / hc, c = k % hc; + if (ldi(on, offlin(on, r)) == 0) continue; + const int64_t hb = rowoff(h, r, hn), hs = laststride(h); + const int64_t base = hb + c * n; + float* hv = scratch_f32((size_t) n); + const float* row = in_row(h, base, n, hv); + if (hs != 1) { + float dot = 0.0f; + for (int64_t i = 0; i < n; ++i) dot += row[i] * vec[i]; + const float g = dot * sc; + for (int64_t i = 0; i < n; ++i) + stt(h, base + i * hs, row[i] - g * vec[i]); + continue; + } + if (row != hv) std::memcpy(hv, row, (size_t) n * sizeof(float)); + /* The dot reads the row and the direction; the update then rewrites the same elements, so + * the direction's own copy is not needed (it is never written). */ + vf acc = vf_zero(); + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) + acc = vf_fma(vf_loadu(hv + i), vf_loadu(vec + i), acc); + float dot = vf_hsum(acc); + for (; i < n; ++i) dot += hv[i] * vec[i]; + const vf vg = vf_set1(dot * sc); + i = 0; + for (; i + VF_N <= n; i += VF_N) + vf_storeu(hv + i, vf_sub(vf_loadu(hv + i), vf_mul(vg, vf_loadu(vec + i)))); + for (; i < n; ++i) hv[i] -= (dot * sc) * vec[i]; + out_row(h, base, n, hv); + } + return RAD_OK; +} + /* ================================================================== mtp_enter * * Entry of the multi-token-prediction head for a model with an `hc`-wide residual stream. diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 57fac4df..ddff5118 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -70,17 +70,17 @@ int avx_par_force(int threads); #define AVX_OP_LIST(X) \ /* ---- elementwise and norms */ \ X(rmsnorm) X(rmsnorm_p) X(rmsnorm_add) X(hc_enter) \ - X(hc_read) X(hc_write) X(mtp_enter) X(layernorm) \ - X(mhc_pre) X(mhc_post) X(mhc_contract) X(kda_update) \ - X(mhc_pre_partial) X(mhc_pre_finish) \ - X(swiglu_clamped) \ - X(router_sigmoid_topk) \ - X(dsa_pool) \ - X(dsa_query) \ - X(gemm_nt_f32) \ - X(mla_project) \ - X(dsa_score) \ - X(mla_attn) \ + X(hc_read) X(hc_write) X(hc_project) X(mtp_enter) \ + X(layernorm) X(mhc_pre) X(mhc_post) X(mhc_contract) \ + X(kda_update) X(mhc_pre_partial) X(mhc_pre_finish) \ + X(swiglu_clamped) \ + X(router_sigmoid_topk) \ + X(dsa_pool) \ + X(dsa_query) \ + X(gemm_nt_f32) \ + X(mla_project) \ + X(dsa_score) \ + X(mla_attn) \ X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \ X(mul) X(silu_mul) X(gelu_mul) X(gelu) \ X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 11470960..0d98407c 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -114,6 +114,10 @@ static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_st static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") }; static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") }; static const RadOperandSpec oHcWrite[] = { OPD("y"), OPD("inj"), INOUT("h") }; +/* The speed projection: one unit direction per layer (f32) and an int32 per-row switch. */ +static const RadParamSpec pHcProject[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("scale"), + P_STR("dtype") }; +static const RadOperandSpec oHcProject[] = { INOUT("h"), OPD("v"), OPD("on") }; static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd"), P_INTO("ngroup"), @@ -826,6 +830,9 @@ static const RadOpSchema kSchemas[] = { "gate argument, and hc_write adds into the UNNORMED h). `mix` names the matrices' stored " "format; a host kernel reads them as the dense tensors it is handed." }, { "hc_write", ARR(pHcWrite), ARR(oHcWrite), "h[s] += inj[s] * y, into the unnormed stream." }, +{ "hc_project", ARR(pHcProject), ARR(oHcProject), + "The experimental speed projection (llama.cpp's `--cvec-mode project`): h[s] -= scale * " + "(h[s] . v) * v for each of the hc streams of a row whose flag is on. A zero flag is not read." }, { "mtp_enter", ARR(pMtpEnter), ARR(oMtpEnter), "MTP head entry: two norms, a per-sub-stream fc and a broadcast fc. `fc` names the two " "matrices' stored format; a host kernel reads them as the dense tensors it is handed." }, @@ -1362,6 +1369,9 @@ ROWL("avx_hc_read", "hc_read", "norm", avx_layout_hc), SIMPLE("avx_hc_write", "hc_write", "norm", "gated residual write: h[s] += inj[s] * y", DT_FLOAT, L(hc_write)), +SIMPLE("avx_hc_project", "hc_project", "norm", + "speed projection: h[s] -= scale * (h[s] . v) * v where the row's flag is on", DT_FLOAT, + L(hc_project)), ROWL("avx_mtp_enter", "mtp_enter", "norm", "MTP head entry: two norms, a per-sub-stream fc and a broadcast fc", DT_FLOAT ", or fc matrices of E4M3 / int8 codes with a scale plane, joined", L(mtp_enter), diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 8efe1975..beab445c 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -175,6 +175,9 @@ set(R4D_UNITS # Gemma 4's sandwich-norm joins (norm_add_norm, norm_add_norm_route, join_add_scale) and # expert_scale, each one kernel for a chain of small ones. "r4d_norm_join_bf16|" + # The experimental speed projection (core/cvec.h): one pass of h[s] -= s (h[s].v) v over the wide + # stream, with a per-row switch. + "r4d_hc_project|" "r4d_expert_scale_bf16|" # Runtime LoRA's two halves (lora_shrink, lora_expand), per-row adapter slot: scalar and tiled rows. "r4d_lora_bf16|" diff --git a/libr4d/r4d_hc_project.hip b/libr4d/r4d_hc_project.hip new file mode 100644 index 00000000..4609a513 --- /dev/null +++ b/libr4d/r4d_hc_project.hip @@ -0,0 +1,144 @@ +// r4d_hc_project.hip -- the experimental speed projection on the gated residual's wide stream. +// +// The operation is llama.cpp's `--cvec-mode project`, which the Qwen3.8-Flash-Next control-vector +// package publishes and Strata ports (data/experimental-speed-projection): for each of the hc +// streams of a token's residual row, +// +// h[s] -= scale * (h[s] . v) * v +// +// with `v` that layer's UNIT direction and `scale` the norm the file stored for it. The dot is +// taken per stream, not on the stream mean: llama.cpp's patch applies `build_cvec` to the +// [n_embd, hc, tokens] residual view, where `mul_mat(v, cur)` reduces over dim 0 alone. +// +// The op is issued after a layer's feed-forward write into the stream, which is where the patch's +// `build_cvec(res_hc, il)` sits in the `qwen4exp` graph. +// +// ============================== the per-row switch ============================== +// +// `on` is an int32 per row (core derive.cpp's `projection_on_rows`: the request's own choice, +// expanded across its tokens once a step). A zero row is skipped before any load: no read, no +// write. That is what makes a request without the vector byte-identical to a deployment with no +// vector loaded -- not merely close -- and it costs one load per row per layer. +// +// ============================== shape ============================== +// +// One workgroup per (token row, stream): it holds the whole of `v`'s stream in no memory at all +// (it streams `h` and `v` together), reduces the dot in LDS, and then rewrites the row. Grid +// (rows, hc). At the model's shape (n 2560, hc 4) that is 2560 f32 of `v` re-read per (row, +// stream): 40 KB per token per layer, against 40 KB of `h` -- the same traffic as the write it +// follows, within a fraction of the step's expert traffic. +#include + +#include +#include + +#include "r4d.h" +#include "r4d_args.h" + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kMaxWave = 64; + +__device__ __forceinline__ float bf2f(uint16_t h) { + const uint32_t u = (uint32_t) h << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} + +__device__ __forceinline__ uint16_t f2bf(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return (uint16_t) ((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +/* One workgroup per (row, stream). `h` is the row's stream at `h + row*h_ld + stream*n`, `v` the + * layer's unit direction (f32, `v_ld` may exceed n for a slice of a wider plane). */ +__global__ __launch_bounds__(kThreads) void hc_project_kernel(uint16_t* __restrict__ h, + const float* __restrict__ v, + const int32_t* __restrict__ on, + uint32_t n, uint32_t h_ld, + uint32_t v_ld, float scale) { + const uint32_t row = blockIdx.x; + if (on[row] == 0) return; // this token's request did not ask for the projection + + uint16_t* __restrict__ hr = h + (size_t) row * h_ld + (size_t) blockIdx.y * n; + const float* __restrict__ vr = v + (size_t) blockIdx.y * v_ld; + + float acc = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) acc += bf2f(hr[i]) * vr[i]; + + __shared__ float red[kMaxWave]; + const uint32_t lane = threadIdx.x % kMaxWave; + const uint32_t wave = threadIdx.x / kMaxWave; + for (uint32_t off = kMaxWave / 2; off > 0; off >>= 1) { + acc += __shfl_down(acc, off, kMaxWave); + } + if (lane == 0) red[wave] = acc; + __syncthreads(); + if (threadIdx.x == 0) { + float total = 0.0f; + const uint32_t nw = (blockDim.x + kMaxWave - 1) / kMaxWave; + for (uint32_t w = 0; w < nw; ++w) total += red[w]; + red[0] = total * scale; + } + __syncthreads(); + + const float g = red[0]; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) + hr[i] = f2bf(bf2f(hr[i]) - g * vr[i]); +} + +} // namespace + +/* Host form: rows and the stream count come from the caller (the entry point below, which reads + * them from the operands). */ +extern "C" int r4d_hc_project_bf16(long h, long v, long on, int rows, int n, int hc, int h_ld, + int v_ld, float scale, long stream) { + if (!h || !v || !on) return -1; + if (rows <= 0 || n <= 0 || hc <= 0) return -2; + if (h_ld <= 0) h_ld = hc * n; + if (v_ld <= 0) v_ld = n; + hipLaunchKernelGGL(hc_project_kernel, dim3((uint32_t) rows, (uint32_t) hc), dim3(kThreads), 0, + (hipStream_t) stream, (uint16_t*) h, (const float*) v, + (const int32_t*) on, (uint32_t) n, (uint32_t) h_ld, (uint32_t) v_ld, + scale); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ============================== the entry point ============================== + * + * Operands: h (inout, bf16, [rows, hc*n]), v (f32, [n]), on (int32, [rows]). Parameters: n, hc, + * scale, dtype. `rows` is derived from h's extent, as every per-row op here does: the kernel owns + * whole rows. */ +extern "C" int r4d_rad_hc_project(const RadArgs* a, RadStream s) { + const RadTensor* h = r4d_opt(a, 0); + const RadTensor* v = r4d_opt(a, 1); + const RadTensor* on = r4d_opt(a, 2); + if (!h || !v || !on) return R4D_NO(RAD_E_INVAL); + if (h->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (v->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (on->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + + const long long n = r4d_geti_or(a, "n", 0); + const long long hc = r4d_geti_or(a, "hc", 0); + if (n <= 0 || hc <= 1) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(v) < n) return R4D_NO(RAD_E_SHAPE); + + long long rows = 0, row_n = 0; + if (r4d_rows_of(h, &rows, &row_n) < 0) return R4D_NO(RAD_E_SHAPE); + if (row_n != hc * n || rows <= 0) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(on) < rows) return R4D_NO(RAD_E_SHAPE); + + /* No pitch handling: the architecture passes the model's own wide stream, contiguous rows of + * hc*n. A strided view is refused rather than silently read as contiguous. */ + const long long h_ld = r4d_stride(h, (int) h->rank - 2); + const long long v_ld = r4d_stride(v, (int) v->rank - 1); + if (h_ld != hc * n || v_ld != 1) return R4D_NO(RAD_E_STRIDE); + + const float scale = (float) r4d_getf(a, "scale", 1.0); + return r4d_hc_project_bf16(r4d_addr(h), r4d_addr(v), r4d_addr(on), (int) rows, (int) n, + (int) hc, (int) h_ld, 0, scale, (long) (uintptr_t) s) == 0 + ? RAD_OK : RAD_E_DEVICE; +} diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 689f39cf..337717be 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -339,6 +339,7 @@ int r4d_rad_dflash_select (const RadArgs*, RadStream); /* -- the gated residual (r4d_hc_bf16.hip) -- */ int r4d_rad_hc_enter (const RadArgs*, RadStream); +int r4d_rad_hc_project (const RadArgs*, RadStream); int r4d_rad_mhc_pre(const RadArgs*, RadStream); int r4d_rad_mhc_pre_partial(const RadArgs*, RadStream); int r4d_rad_mhc_pre_finish(const RadArgs*, RadStream); @@ -751,6 +752,7 @@ int r4d_shape_mhc_contract(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_mtp_enter (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_read (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_write (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_hc_project (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_binary (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_mul_weight (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_scatter_rows_bf16(const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index bf59cad7..59f47cbc 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -480,6 +480,16 @@ static const RadOperandSpec oGdnConvRecurrentUpdate[] = { /* The gated residual. `hc_enter` and `hc_write` share a parameter list; `hc_read` adds the two * switches its operand list depends on: `inject` 0 is the final mixer and `group` 0 a read whose * consumer wants bf16. Both default on, as every trunk connection uses both. */ +/* The experimental speed projection (libr4d/r4d_hc_project.hip): a bf16 stream, one unit f32 + * direction per layer, an int32 switch per row. */ +static const RadParamSpec pHcProject[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("scale"), + P_STR("dtype") }; +static const RadOperandSpec oHcProject[] = { + { "h", RAD_OPD_INOUT, 0 }, { "v", RAD_OPD_IN, 0 }, { "on", RAD_OPD_IN, 0 }, +}; +static const RadConstraint cHcProject[] = { + C_GE("M", 1), C_GE("n", 1), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), +}; static const RadParamSpec pHcPlain[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype"), }; @@ -2934,6 +2944,12 @@ static const RadOpSchema kSchemas[] = { "the read half of a gated residual: a grouped rmsnorm, a low-rank sigmoid gate, and " "the mean of the gated streams -- plus the per-branch write gains and, optionally, " "the block-scaled fp8 form of the block input and its Hadamard-rotated twin."), + SCHEMA("hc_project", pHcProject, oHcProject, + "the experimental speed projection (llama.cpp's `--cvec-mode project`): for each of the " + "hc streams of a row whose `on` flag is 1, h[s] -= scale * (h[s] . v) * v, v that " + "layer's unit direction and scale its stored norm. A row whose flag is 0 is neither read " + "nor written, so an unprojected request is byte-identical to a deployment with no " + "vector loaded."), SCHEMA("hc_write", pHcPlain, oHcWrite, "the write half: h[s] += inj[s] * y, into the UNNORMED stream."), SCHEMA("mtp_enter", pMtpEnter, oMtpEnter, @@ -6510,6 +6526,15 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_hc_write, nullptr, nullptr, nullptr, r4d_shape_hc_write }, +{ "hc_project_bf16", "hc_project", "norm", + "speed projection: h[s] -= scale * (h[s] . v) * v where the row's flag is on", + "any M, any n, hc 2..8", + "bf16 stream, f32 direction, i32 switch", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cHcProject), NOTUNE, + nullptr, nullptr, r4d_rad_hc_project, nullptr, nullptr, nullptr, + r4d_shape_hc_project }, + { "mtp_enter_bf16", "mtp_enter", "norm", "MTP head entry: two norms, a per-sub-stream fc and one broadcast fc", "any M, n 128..5734, hc 2..4", diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 7bc5a417..5f8edd16 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -480,6 +480,19 @@ extern "C" int r4d_shape_hc_write(const RadParam* p, int n_p, int operand, RadOp R4D_PICK(l); } +/* hc_project's three: the bf16 stream (in place), the layer's unit f32 direction, and the int32 + * per-row switch. The switch is an index domain: 0 or 1. */ +extern "C" int r4d_shape_hc_project(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { + opd(D, M, hc * n), /* h, in place */ + opd((uint32_t) RAD_F32, n), /* v */ + opd_idx(M, 1, 1, 0), /* on: 0 or 1 */ + }; + R4D_PICK(l); +} + /* hc_write's operands with the all-reduce in front; `y` is also the message. */ extern "C" int r4d_shape_ar_hc_write(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { return r4d_shape_hc_write(p, n_p, operand, out); diff --git a/libref/ref_hc.cpp b/libref/ref_hc.cpp index 287b96fe..70a58d3c 100644 --- a/libref/ref_hc.cpp +++ b/libref/ref_hc.cpp @@ -252,6 +252,59 @@ int ref_hc_write(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ hc_project */ +/* The experimental speed projection: h[row, s*n + i] -= scale * (h . v) * v, for each of the hc + * streams s, on the rows whose `on` flag is 1. + * + * `v` is one layer's unit direction (the engine normalises the file's rows when it uploads them) + * and `scale` is the norm the file stored for that layer, so this is exactly llama.cpp's + * `--cvec-mode project` with its `llama_adapter_cvec` (the package's 02-cvec-projection-mode + * patch): the dot is taken per hyper-connection stream, as `mul_mat` over a [n, hc, tokens] view + * gives it, and not on the stream mean. + * + * A row whose flag is 0 is not touched: no read, no write, so a request that did not ask for the + * vector's activations are the stock model's: no read, no write. (A deployment that merely *has* the + * table loaded is not bit-identical to one without it -- the table's VRAM moves the expert/KV plan -- + * but that is placement, not this op.) + * + * `on` is an int32 per row (core derive.cpp's `projection_on_rows`); the direction is f32. */ +int ref_hc_project(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor* h = &a->t[0]; + const RadTensor* v = &a->t[1]; + const RadTensor* on = &a->t[2]; + + const int64_t n = p_int(a, "n", 0); + const int64_t hc = p_int(a, "hc", 0); + const float sc = p_f32(a, "scale", 1.0f); + if (n <= 0 || hc <= 1) return RAD_E_SHAPE; + if (numel(v) < n) return RAD_E_SHAPE; + const int64_t hn = hc * n; + + const int64_t rows = rows_of(h, hn); + if (rows <= 0 || numel(on) < rows) return RAD_E_SHAPE; + + /* Rows are independent: each dot is over one row's own streams. The parallel index is the + * (row, stream) pair, so one row's hc streams may run on different threads without sharing an + * accumulator. */ + REF_PAR_FOR(rows * hc) + for (int64_t k = 0; k < rows * hc; ++k) { + const int64_t r = k / hc, c = k % hc; + if (ld_int(on->dtype, on->data, offlin(on, r)) == 0) continue; + const int64_t hb = rowoff(h, r, hn), hs = laststride(h); + const int64_t vb = rowoff(v, 0, n), vl = laststride(v); + double acc = 0.0; + for (int64_t i = 0; i < n; ++i) + acc += (double) ldt(h, hb + (c * n + i) * hs) * (double) ldt(v, vb + i * vl); + const float g = (float) (acc * (double) sc); + for (int64_t i = 0; i < n; ++i) { + const int64_t j = hb + (c * n + i) * hs; + stt(h, j, ldt(h, j) - g * ldt(v, vb + i * vl)); + } + } + return RAD_OK; +} + /* ================================================================== mtp_enter * * The multi-token-prediction head's entry for a model whose residual stream is `hc` wide. diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 4c164a65..1f3e078f 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -67,6 +67,7 @@ int ref_mhc_contract (const RadArgs*, RadStream); int ref_kda_update (const RadArgs*, RadStream); int ref_hc_read (const RadArgs*, RadStream); int ref_hc_write (const RadArgs*, RadStream); +int ref_hc_project (const RadArgs*, RadStream); int ref_mtp_enter (const RadArgs*, RadStream); int ref_layernorm (const RadArgs*, RadStream); int ref_grid_embed (const RadArgs*, RadStream); @@ -317,6 +318,7 @@ REF_SHAPE_FN(ref_mhc_contract); REF_SHAPE_FN(ref_kda_update); REF_SHAPE_FN(ref_hc_read); REF_SHAPE_FN(ref_hc_write); +REF_SHAPE_FN(ref_hc_project); REF_SHAPE_FN(ref_mtp_enter); REF_SHAPE_FN(ref_layernorm); REF_SHAPE_FN(ref_grid_embed); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 827188ca..72837cb8 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -118,6 +118,12 @@ static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_st OPD_O("num_accepted"), OUT("y") }; static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") }; +/* The speed projection (libref/ref_hc.cpp, core/cvec.h): one unit direction per layer and a + * per-row switch. `v` is f32 whatever the stream's dtype is, because the engine uploads the table + * in f32; `on` is an int32 row mask (core derive.cpp's `projection_on_rows`). */ +static const RadParamSpec pHcProject[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("scale"), + P_STR("dtype") }; +static const RadOperandSpec oHcProject[] = { INOUT("h"), OPD("v"), OPD("on") }; static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") }; static const RadOperandSpec oHcWrite[] = { OPD("y"), OPD("inj"), INOUT("h") }; static const RadParamSpec pMhcPre[] = { P_INT("M"), P_INT("n"), P_INT("hc"), @@ -1003,6 +1009,12 @@ static const RadOpSchema kSchemas[] = { { "hc_write", ARR(pHcWrite), ARR(oHcWrite), "The write half: h[s] += inj[s] * y, for each of the hc streams of h. In place, and `h` is the " "UNNORMED stream the paired hc_read was handed -- the normalisation never enters the residual." }, +{ "hc_project", ARR(pHcProject), ARR(oHcProject), + "The experimental speed projection (llama.cpp's `--cvec-mode project`): for each of the hc " + "streams of a row whose `on` flag is 1, h[s] -= scale * (h[s] . v) * v, with v that layer's unit " + "direction and scale the norm the file stored. The dot is per stream, not on the stream mean. A " + "row whose flag is 0 is not read and not written, so an unprojected request is byte-identical to " + "a deployment with no vector loaded." }, { "mtp_enter", ARR(pMtpEnter), ARR(oMtpEnter), "The MTP head's entry for a wide residual stream: x[k*n+i] = fc_h[i] . grouped_norm(h)[k] " "+ fc_e[i] . norm(e), for each of the hc sub-streams k. `ngroup` == hc is one rsqrt per " @@ -1957,6 +1969,9 @@ ROWL("ref_mtp_enter", "mtp_enter", "norm", ref_check_dtypes, ref_mtp_enter, ref::ref_layout_mtp), SIMPLE("ref_hc_write", "hc_write", "norm", "gated residual write: h[s] += inj[s] * y", DT_FLOAT, ref_hc_write), +SIMPLE("ref_hc_project", "hc_project", "norm", + "speed projection: h[s] -= scale * (h[s] . v) * v where the row's flag is on", + DT_FLOAT, ref_hc_project), SIMPLE("ref_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT_FLOAT, ref_layernorm), SIMPLE("ref_grid_embed", "grid_embed", "elem", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index f1fd4d8a..cb0d7f21 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -436,6 +436,17 @@ int ref_hc_write_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("hc_write", operand, out); } +int ref_hc_project_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t hc = gi(p, n_p, "hc", 0); + Opd o; + o.t(D, { M, hc * n }); /* h, in place */ + o.t((uint32_t) RAD_F32, { n }); /* v: one layer's unit direction */ + o.t((uint32_t) RAD_I32, { M }); /* on: 1 = this row takes the projection */ + return o.finish("hc_project", operand, out); +} + int ref_mtp_enter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);