Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
perf(semantic): quantize the resident semantic vectors (rotated 4-bit SQ)
Martin Vogeld83ab50a19f5
diff --git a/Makefile.cbm b/Makefile.cbmindex d94192e05..bc2f55ce1 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -220,7 +220,7 @@ PIPELINE_SRCS = \SIMHASH_SRCS = src/simhash/minhash.c# Semantic embedding module-SEMANTIC_SRCS = src/semantic/semantic.c src/semantic/ast_profile.c+SEMANTIC_SRCS = src/semantic/semantic.c src/semantic/ast_profile.c src/semantic/rotsq.c# nomic-embed-code pretrained vectors (assembler blob)UNIXCODER_BLOB_SRC = vendored/nomic/code_vectors_blob.Sdiff --git a/src/pipeline/pass_semantic_edges.c b/src/pipeline/pass_semantic_edges.cindex 188fdc1c7..7524c41d5 100644--- a/src/pipeline/pass_semantic_edges.c+++ b/src/pipeline/pass_semantic_edges.c@@ -663,21 +663,25 @@ static void vec_build_worker(int worker_id, void *ctx_ptr) {vc->funcs[f].tfidf_weights = weights;vc->funcs[f].tfidf_len = tfidf_len;- /* RI vector: sum of enriched token vectors weighted by IDF */- memset(&vc->funcs[f].ri_vec, 0, sizeof(cbm_sem_vec_t));+ /* RI vector: sum of enriched token vectors weighted by IDF. Built in a+ * LOCAL dense buffer; only the quantized code is retained per func+ * (the resident dense floats were ~9.4 GB on the kernel). */+ cbm_sem_vec_t ri_dense;+ memset(&ri_dense, 0, sizeof(cbm_sem_vec_t));for (int t = 0; t < tc; t++) {const cbm_sem_vec_t *ri = cbm_sem_corpus_ri_vec(vc->corpus, tokens[t]);if (ri) {float idf = cbm_sem_corpus_idf(vc->corpus, tokens[t]);- cbm_sem_vec_add_scaled(&vc->funcs[f].ri_vec, ri, idf);+ cbm_sem_vec_add_scaled(&ri_dense, ri, idf);}}- cbm_sem_normalize(&vc->funcs[f].ri_vec);+ cbm_sem_normalize(&ri_dense);+ cbm_rsq_encode(ri_dense.v, &vc->funcs[f].ri_code);/* Int8 quantize into pre-allocated output array (parallel-safe) */uint8_t *qv = &vc->qvecs[(ptrdiff_t)f * CBM_SEM_DIM];for (int d = 0; d < CBM_SEM_DIM; d++) {- float v = vc->funcs[f].ri_vec.v[d];+ float v = ri_dense.v[d];if (v > PSE_UNIT_POS) {v = PSE_UNIT_POS;}@@ -701,8 +705,11 @@ enum {SEM_MAX_CANDIDATES = 200,};-/* Row of a hyperplane matrix: float[CBM_SEM_DIM]. */-typedef float hyperplane_row_t[CBM_SEM_DIM];+/* Row of a hyperplane matrix in the ROTATED (quantized) basis: LSH only+ * needs signs of dots against random directions, and a random direction in+ * the rotated basis is as random as one in the original — so signatures are+ * computed from dequantized codes without keeping dense originals. */+typedef float hyperplane_row_t[CBM_RSQ_DIM];typedef struct {cbm_sem_func_t *funcs;@@ -721,11 +728,13 @@ static void sig_build_worker(int worker_id, void *ctx_ptr) {break;}+ float dec[CBM_RSQ_DIM];+ cbm_rsq_decode(&sc->funcs[f].ri_code, dec);uint64_t sig = 0;for (int h = 0; h < NUM_HYPERPLANES; h++) {float dot = 0.0F;- for (int d = 0; d < CBM_SEM_DIM; d++) {- dot += sc->funcs[f].ri_vec.v[d] * sc->hyperplanes[h][d];+ for (int d = 0; d < CBM_RSQ_DIM; d++) {+ dot += dec[d] * sc->hyperplanes[h][d];}if (dot > 0.0F) {sig |= (PSE_ONE_ULL << h);@@ -880,9 +889,13 @@ static void collect_worker(int worker_id, void *ctx_ptr) {const cbm_gbuf_node_t *n = cc->node_ptrs[i];decode_minhash(n->properties_json, &cc->funcs[i]);decode_struct_profile(n->properties_json, cc->funcs[i].struct_profile);- build_api_vec(cc->gbuf, n->id, &cc->funcs[i].api_vec);- build_type_vec(n->properties_json, &cc->funcs[i].type_vec);- build_deco_vec(n->properties_json, &cc->funcs[i].deco_vec);+ cbm_sem_vec_t tmp_vec;+ build_api_vec(cc->gbuf, n->id, &tmp_vec);+ cbm_rsq_encode(tmp_vec.v, &cc->funcs[i].api_code);+ build_type_vec(n->properties_json, &tmp_vec);+ cbm_rsq_encode(tmp_vec.v, &cc->funcs[i].type_code);+ build_deco_vec(n->properties_json, &tmp_vec);+ cbm_rsq_encode(tmp_vec.v, &cc->funcs[i].deco_code);}}}@@ -1101,8 +1114,8 @@ static hyperplane_row_t *phase5a_build_hyperplanes(void) {return NULL;}for (int h = 0; h < NUM_HYPERPLANES; h++) {- for (int d = 0; d < CBM_SEM_DIM; d++) {- uint64_t seed = XXH3_64bits_withSeed(&d, sizeof(d), (uint64_t)h * CBM_SEM_DIM);+ for (int d = 0; d < CBM_RSQ_DIM; d++) {+ uint64_t seed = XXH3_64bits_withSeed(&d, sizeof(d), (uint64_t)h * CBM_RSQ_DIM);hyperplanes[h][d] = ((float)(seed & UINT32_MAX) / (float)UINT32_MAX) - PSE_ROUND_BIAS;}}diff --git a/src/semantic/rotsq.c b/src/semantic/rotsq.cnew file mode 100644index 000000000..41ac0636a--- /dev/null+++ b/src/semantic/rotsq.c@@ -0,0 +1,127 @@+/*+ * rotsq.c — see rotsq.h. From-paper implementation, no dependencies.+ */+#include "semantic/rotsq.h"++#include <string.h>++#define XXH_INLINE_ALL+#include "xxhash/xxhash.h"++/* ── Deterministic ±1 diagonal (seeded, generated once) ─────────────── */++static float g_rsq_diag[CBM_RSQ_DIM];+static int g_rsq_diag_ready = 0;++static void rsq_init_diag(void) {+ if (g_rsq_diag_ready) {+ return;+ }+ for (int d = 0; d < CBM_RSQ_DIM; d++) {+ uint64_t h = XXH3_64bits_withSeed(&d, sizeof(d), 0x5bd1e995u);+ g_rsq_diag[d] = (h & 1u) ? 1.0F : -1.0F;+ }+ g_rsq_diag_ready = 1;+}++/* ── Fast Walsh–Hadamard Transform (in place, unnormalized) ─────────── */++static void rsq_fwht(float *v) {+ for (int len = 1; len < CBM_RSQ_DIM; len <<= 1) {+ for (int i = 0; i < CBM_RSQ_DIM; i += len << 1) {+ for (int j = i; j < i + len; j++) {+ float a = v[j];+ float b = v[j + len];+ v[j] = a + b;+ v[j + len] = a - b;+ }+ }+ }+}++/* ── Encode ─────────────────────────────────────────────────────────── */++void cbm_rsq_encode(const float *v, cbm_rsq_code_t *out) {+ rsq_init_diag();++ float rot[CBM_RSQ_DIM];+ for (int d = 0; d < CBM_RSQ_IN_DIM; d++) {+ rot[d] = v[d] * g_rsq_diag[d];+ }+ for (int d = CBM_RSQ_IN_DIM; d < CBM_RSQ_DIM; d++) {+ rot[d] = 0.0F;+ }+ rsq_fwht(rot);+ /* Normalize the transform so the rotation is orthonormal (H/√D): keeps+ * the coordinates in a data-independent range and makes the estimated IP+ * directly comparable to the pre-rotation IP. */+ const float inv_sqrt_d = 1.0F / 32.0F; /* 1/√1024 */+ float lo = rot[0] * inv_sqrt_d;+ float hi = lo;+ for (int d = 0; d < CBM_RSQ_DIM; d++) {+ rot[d] *= inv_sqrt_d;+ if (rot[d] < lo) {+ lo = rot[d];+ }+ if (rot[d] > hi) {+ hi = rot[d];+ }+ }++ /* Per-vector scalar quantization over [lo, hi] at CBM_RSQ_BITS. */+ float range = hi - lo;+ float step = range > 0.0F ? range / (float)CBM_RSQ_LEVELS : 1.0F;+ out->offset = lo;+ out->scale = step;++ int32_t sum = 0;+ memset(out->codes, 0, sizeof(out->codes));+ for (int d = 0; d < CBM_RSQ_DIM; d++) {+ float q = (rot[d] - lo) / step;+ int32_t c = (int32_t)(q + 0.5F);+ if (c < 0) {+ c = 0;+ }+ if (c > CBM_RSQ_LEVELS) {+ c = CBM_RSQ_LEVELS;+ }+ sum += c;+ if (d & 1) {+ out->codes[d >> 1] |= (uint8_t)(c << 4);+ } else {+ out->codes[d >> 1] |= (uint8_t)c;+ }+ }+ out->code_sum = sum;+}++/* ── Estimated inner product from two codes ─────────────────────────── */++float cbm_rsq_ip(const cbm_rsq_code_t *a, const cbm_rsq_code_t *b) {+ /* Integer dot of the 4-bit codes. */+ int64_t dot = 0;+ for (int i = 0; i < CBM_RSQ_CODE_BYTES; i++) {+ uint8_t ba = a->codes[i];+ uint8_t bb = b->codes[i];+ dot += (int64_t)(ba & 0x0F) * (bb & 0x0F);+ dot += (int64_t)(ba >> 4) * (bb >> 4);+ }+ /* x_i ≈ oa + sa·ca_i, y_i ≈ ob + sb·cb_i (in the rotated space, where the+ * IP equals the original IP because the rotation is orthonormal). */+ double d = (double)CBM_RSQ_DIM;+ double ip = d * (double)a->offset * (double)b->offset ++ (double)a->offset * (double)b->scale * (double)b->code_sum ++ (double)b->offset * (double)a->scale * (double)a->code_sum ++ (double)a->scale * (double)b->scale * (double)dot;+ return (float)ip;+}++/* ── Dequantize into the rotated basis ──────────────────────────────── */++void cbm_rsq_decode(const cbm_rsq_code_t *c, float *out) {+ for (int i = 0; i < CBM_RSQ_CODE_BYTES; i++) {+ uint8_t b = c->codes[i];+ out[i * 2] = c->offset + c->scale * (float)(b & 0x0F);+ out[i * 2 + 1] = c->offset + c->scale * (float)(b >> 4);+ }+}diff --git a/src/semantic/rotsq.h b/src/semantic/rotsq.hnew file mode 100644index 000000000..32afca39c--- /dev/null+++ b/src/semantic/rotsq.h@@ -0,0 +1,65 @@+/*+ * rotsq.h — RaBitQ-style B-bit vector quantization (from-paper, plain C11).+ *+ * Implements the core of Extended RaBitQ (Gao et al., SIGMOD 2024/2025;+ * arXiv:2405.12497, arXiv:2409.09913) without the reference library (which is+ * C++ and bundles Eigen/MPL-2.0). Named rotsq, not rabitq: this is the+ * FAMILY core (randomized rotation + per-vector scalar quantization + exact+ * code-expansion estimator), not the papers' exact codebook construction —+ * the name should not overclaim fidelity. Rotate each vector with a deterministic+ * randomized transform, then scalar-quantize the rotated coordinates to B+ * bits. The rotation spreads a vector's mass evenly across coordinates+ * (rotated coords of a unit vector are near-Gaussian), which makes plain+ * scalar quantization behave near-optimally — that observation IS RaBitQ.+ *+ * Rotation: random ±1 diagonal (XXH3-seeded, reproducible — same idiom as the+ * LSH hyperplanes) followed by a Fast Walsh–Hadamard Transform, inputs padded+ * to the next power of two (768 → 1024). Orthogonal up to a known 1/√D scale.+ *+ * Inner product between two ENCODED vectors is estimated from the codes with+ * the exact SQ expansion (deterministic — a pure function of the two codes):+ * x_i ≈ ox + sx·cx_i ⇒ ⟨x,y⟩ ≈ D·ox·oy + ox·sy·Σcy + oy·sx·Σcx+ * + sx·sy·Σ(cx_i·cy_i)+ * with Σcx/Σcy precomputed per vector, so scoring one pair is one integer+ * dot product (u8×u8) plus four multiplies.+ *+ * Memory at B=4, D=1024: 512 B codes + 12 B metadata per vector, vs 3 072 B+ * for 768 raw floats — ~6× per vector. Cosine of normalized inputs is the+ * estimated IP directly (rotation preserves norms up to the fixed scale,+ * which cancels in the scale factors).+ */+#ifndef CBM_SEMANTIC_ROTSQ_H+#define CBM_SEMANTIC_ROTSQ_H++#include <stdint.h>++enum {+ CBM_RSQ_IN_DIM = 768, /* input dimension (CBM_SEM_DIM) */+ CBM_RSQ_DIM = 1024, /* padded pow2 rotation dimension */+ CBM_RSQ_BITS = 4, /* bits per coordinate */+ CBM_RSQ_LEVELS = 15, /* (1 << CBM_RSQ_BITS) - 1 */+ CBM_RSQ_CODE_BYTES = CBM_RSQ_DIM / 2, /* two 4-bit codes per byte */+};++typedef struct {+ uint8_t codes[CBM_RSQ_CODE_BYTES]; /* packed 4-bit codes, little nibble first */+ float scale; /* per-vector dequant scale */+ float offset; /* per-vector dequant offset */+ int32_t code_sum; /* Σ codes (for the IP expansion) */+} cbm_rsq_code_t;++/* Encode a CBM_RSQ_IN_DIM float vector (zero-padded to CBM_RSQ_DIM, rotated,+ * quantized). Deterministic: the rotation is fixed at build time. */+void cbm_rsq_encode(const float *v, cbm_rsq_code_t *out);++/* Estimated inner product of the two ORIGINAL vectors from their codes.+ * Deterministic pure function of the codes. */+float cbm_rsq_ip(const cbm_rsq_code_t *a, const cbm_rsq_code_t *b);++/* Dequantize a code into the ROTATED space (CBM_RSQ_DIM floats). Note: this+ * is the rotated basis, not the original one — fine for basis-agnostic+ * consumers (LSH hyperplane signs), wrong for anything expecting original+ * coordinates. */+void cbm_rsq_decode(const cbm_rsq_code_t *c, float *out);++#endif /* CBM_SEMANTIC_ROTSQ_H */diff --git a/src/semantic/semantic.c b/src/semantic/semantic.cindex 5218d9da5..8023e70cd 100644--- a/src/semantic/semantic.c+++ b/src/semantic/semantic.c@@ -1620,7 +1620,7 @@ float cbm_sem_combined_score(const cbm_sem_func_t *a, const cbm_sem_func_t *b,float score = cfg->w_tfidf * sparse_tfidf_cosine(a, b);/* Signal 2: Random Indexing */- score += cfg->w_ri * cbm_sem_cosine(&a->ri_vec, &b->ri_vec);+ score += cfg->w_ri * cbm_rsq_ip(&a->ri_code, &b->ri_code);/* Signal 3: MinHash Jaccard */if (a->has_minhash && b->has_minhash) {@@ -1630,13 +1630,13 @@ float cbm_sem_combined_score(const cbm_sem_func_t *a, const cbm_sem_func_t *b,}/* Signal 4: API Signatures */- score += cfg->w_api * cbm_sem_cosine(&a->api_vec, &b->api_vec);+ score += cfg->w_api * cbm_rsq_ip(&a->api_code, &b->api_code);/* Signal 5: Type Signatures */- score += cfg->w_type * cbm_sem_cosine(&a->type_vec, &b->type_vec);+ score += cfg->w_type * cbm_rsq_ip(&a->type_code, &b->type_code);/* Signal 7: Decorator Pattern */- score += cfg->w_decorator * cbm_sem_cosine(&a->deco_vec, &b->deco_vec);+ score += cfg->w_decorator * cbm_rsq_ip(&a->deco_code, &b->deco_code);/* Signal 8+9+11: Structural profile + data flow + Halstead */float sp_score = small_cosine(a->struct_profile, b->struct_profile, CBM_SEM_AST_PROFILE_DIMS);diff --git a/src/semantic/semantic.h b/src/semantic/semantic.hindex 9d9771826..ddb5f5896 100644--- a/src/semantic/semantic.h+++ b/src/semantic/semantic.h@@ -27,6 +27,8 @@#include <stdbool.h>#include <stdint.h>+#include "semantic/rotsq.h"+/* ── Configuration ───────────────────────────────────────────────── *//* Random Indexing dimension. 256 is sufficient for <500K functions. */@@ -134,10 +136,15 @@ typedef struct {int tfidf_len;/* Dense vectors for RI, API, Type, Decorator. */- cbm_sem_vec_t ri_vec;- cbm_sem_vec_t api_vec;- cbm_sem_vec_t type_vec;- cbm_sem_vec_t deco_vec;+ /* Quantized semantic vectors (rotated 4-bit scalar quantization — see+ * rotsq.h). The dense 768-float versions exist only transiently in the+ * build workers: 4 x 3 KB resident floats per function were ~9.4 GB on+ * the linux kernel; the codes are ~0.5 KB each. Scoring uses the exact+ * code-expansion inner-product estimator (deterministic). */+ cbm_rsq_code_t ri_code;+ cbm_rsq_code_t api_code;+ cbm_rsq_code_t type_code;+ cbm_rsq_code_t deco_code;/* AST profile as float vector (decoded from "sp" property). */float struct_profile[CBM_SEM_AST_PROFILE_DIMS];diff --git a/tests/test_semantic.c b/tests/test_semantic.cindex d7d2066d7..f8d7787ac 100644--- a/tests/test_semantic.c+++ b/tests/test_semantic.c@@ -5,6 +5,7 @@* proximity, diffuse, corpus lifecycle, get_config.*/#include "test_framework.h"+#include <semantic/rotsq.h>#include <semantic/semantic.h>#include <math.h>@@ -338,9 +339,68 @@ TEST(sem_get_config_defaults) {PASS();}+/* ── RaBitQ estimator quality (from-paper 4-bit quantization) ────── */++/* Deterministic pseudo-random unit vectors; validates that the quantized+ * inner-product estimator tracks the exact float IP within tight bounds.+ * These bounds gate the semantic pass's use of the codes: cosine scores are+ * thresholded at ~0.75, so the estimator error must be well under the+ * decision margin for typical pairs. */+TEST(sem_rotsq_ip_error_bounds) {+ enum { N = 64 };+ static float vecs[N][CBM_RSQ_IN_DIM];+ static cbm_rsq_code_t codes[N];+ uint32_t state = 0xC0FFEEu;+ for (int i = 0; i < N; i++) {+ double norm = 0.0;+ for (int d = 0; d < CBM_RSQ_IN_DIM; d++) {+ /* xorshift32 → roughly uniform in [-1, 1] */+ state ^= state << 13;+ state ^= state >> 17;+ state ^= state << 5;+ vecs[i][d] = ((float)(state & 0xFFFFFF) / (float)0x7FFFFF) - 1.0F;+ norm += (double)vecs[i][d] * (double)vecs[i][d];+ }+ float inv = norm > 0.0 ? (float)(1.0 / sqrt(norm)) : 0.0F;+ for (int d = 0; d < CBM_RSQ_IN_DIM; d++) {+ vecs[i][d] *= inv;+ }+ cbm_rsq_encode(vecs[i], &codes[i]);+ }+ double max_err = 0.0;+ double sum_err = 0.0;+ int pairs = 0;+ for (int i = 0; i < N; i++) {+ for (int j = i; j < N; j++) {+ double exact = 0.0;+ for (int d = 0; d < CBM_RSQ_IN_DIM; d++) {+ exact += (double)vecs[i][d] * (double)vecs[j][d];+ }+ double est = (double)cbm_rsq_ip(&codes[i], &codes[j]);+ double err = fabs(est - exact);+ sum_err += err;+ if (err > max_err) {+ max_err = err;+ }+ pairs++;+ }+ }+ double mean_err = sum_err / pairs;+ /* Self-IP of a unit vector must estimate ~1. */+ double self_est = (double)cbm_rsq_ip(&codes[0], &codes[0]);+ ASSERT_TRUE(fabs(self_est - 1.0) < 0.05);+ /* 4-bit RaBitQ-style SQ after rotation: expect mean error well under 1%+ * of the unit scale and max under ~4% — comfortably inside the semantic+ * threshold's decision margin. */+ ASSERT_TRUE(mean_err < 0.01);+ ASSERT_TRUE(max_err < 0.04);+ PASS();+}+/* ── Suite ───────────────────────────────────────────────────────── */SUITE(semantic) {+ RUN_TEST(sem_rotsq_ip_error_bounds);RUN_TEST(sem_tokenize_camel);RUN_TEST(sem_tokenize_snake);RUN_TEST(sem_tokenize_dot);