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.
This commit is contained in:
C_Tamas authored and StillDeadcode committed 2026-10-21 09:26:17 +02:00
1 parent 64adee3ece
commit 459dd4f42d
14 files changed
+362 -11

No files matched your search

+3
View File
@@ -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|"
+144
View File
@@ -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 <hip/hip_runtime.h>
#include <cstdint>
#include <cstring>
#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;
}
+2
View File
@@ -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*);
+25
View File
@@ -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",
+13
View File
@@ -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);