engram: real Metal batch-cosine kernel for vindex_bench's brute-force oracle #114
Closed
will.anderson
wants to merge 0 commits from
feat/engram-metal-cosine-batch into feat/reframe-region-setop
pull from: feat/engram-metal-cosine-batch
merge into: :feat/reframe-region-setop
:main
:fix/runtime-extract-text
:fix/runtime-growth-guard
:fix/runtime-shim-retire
:feat/el-speaks
:wire/write-realizes-signal
:fix/singleton-guards-the-state
:dev
:fix/transduce-decomposition
:design/correspondence-and-censorship
:docs/correspondence-and-ownership-2026-08-16
:fix/geometry-readable
:docs/builtin-recipe-gate
:fix/sigpipe
:feat/grounding-gradient
:fix/utf8-truncation
:fix/ground-echo-and-self
:fix/think-stance
:fix/cross-cutting-concerns
:feat/el-geometry-transduce
:fix/awareness-thread-engram-race
:fix/think-anchor
:fix/geometry-ingest
:fix/state-get-leak
:wt/soul-runtime-reconcile
:fix/bool-is-int-like
:fix/eq-operand-inference
:fix/missing-import-is-an-error
:feat/alloc-accounting-containers
:fix/math-log-base10
:fix/compiler-quadratic-strlen
:feat/alloc-accounting
:fix/elc-rebuildable-compiler-builtins
:fix/engram-query-param-and-seed-link
:merge-pr103-v2
:merge-swarm-ccr-v2
:feat/engram-ggml-cosine-batch
:improve/ggml-cosine-fp32-and-init
:fix/nsbx-tooling-hardening
:stage
:feat/transduce-unify
:fix/engram-search-latency-reconciled
:feat/engram-metal-cosine-batch
:feat/reframe-region-setop
:worktree-agent-a1bb8ac67d9006e08
:feat/neuron-sandbox
:worktree-agent-af50f3458d7754f19
:worktree-agent-acc02900ef4ade35e
:worktree-agent-aaf04b0a9714c4070
:worktree-agent-a6577c8211c332c5b
:worktree-agent-a6177cda24c71d1df
:worktree-agent-a55d5c2d0e8f2c88b
:worktree-agent-a7e7a591a07291058
:worktree-agent-a456e0cf8cd2ee361
:worktree-agent-a0dc4a33cf5558d4e
:worktree-agent-ac2381b0b9615ab20
:wt/swarm-ccr
:integration/langfaculty-20260814
:feat/nsbx-dev-env
:stage-elp-native-lang
:docs/operator-naming-convention
:stage-elp-lang-consolidation
:stage-elp-es-port
:engram-tiered-storage
:feat/engram-reseed-route
:feat/el-route-decorators
:test/dev-ci-baseline
:fix/cgi-identity-emission-clean
:fix/cgi-identity-emission
:reconcile/el-cluster-windows-runtime
:fix/durable-response-truncation
:fix/engram-lexical-tokenized-search
:fix/http-fs-read-len
:hotfix/ci-stage-main-publish-hardening
:hotfix/ci-dev-publish-hardening
:hotfix/stage-elc-engram-integration
:feat/ranked-engram-search
:hotfix/win-runtime-portability
:hotfix/runtime-engram-get-node-by-label
:feat/engram-semantic-search
:hotfix/elc-fixes
:hotfix/el-runtime-leak-and-persist
:integrate/local-main-commits
:fix/runtime-load-merge-2026-06-30
:fix/windows-rusage-guard
:fix/http-response-truncation
:salvage/tim-wip-presync-20260625
:feat/windows-el-runtime
:fix/runtime-integrity-reconcile
:fix/engram-save-atomic-darwin
:chore/live-darwin-runtime
:feat/wm-api-and-http-serve-async
:fix/engram-node-full-field-corruption
:fix/llm-model-and-utf8
:fix/elb-monolithic-link
:fix/ci-gcloud-install-order
:fix/native-test-precompile-runtime
:fix/ci-base-dev-first-run
:fix/elc-parser-elb-build
:fix/elc-oom-checkout
:fix/css-str-join-separator
:fix/html-template-if-style-script
:fix/elb-gcc-bracket-depth
:fix/ci-openssl-linker
:feat/ci-hook-test
:feat/native-testing
:runtime/integrate
:fix/http-serve-1-arg-compat
:feat/el-html-templates
:feat/js-browser-runtime
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Delete Branch "feat/engram-metal-cosine-batch"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Relationship to #109 / #105
This branches from #109 (
feat/reframe-region-setop), notdevdirectly — the only genuine batch-cosine call site (vindex_bench.c) exists solely on that branch. That's a deliberate deviation from the original brief's "PR against dev," flagged here explicitly: this PR should land after/alongside #109, not independently against dev. No overlap with #105 (separate latency fix, different files).Why this target, not engram_activate
The original ask was to GPU-accelerate
engram_activate's O(N·D) cosine prescan. #109 (this PR's base) already retires that loop algorithmically — HNSW seed selection (vindex_search) + a lazy-memoizedeg_cosq_at()replace the full scan with per-candidate lookups. GPU-accelerating a loop that's being deleted isn't real work, so I dropped that target rather than force it.Re-investigated for a genuine remaining fit, with code, not assumption:
ENGRAM_SELF_REIFY=1is live in prod,route_tickrebuilds the whole vindex from scratch every 10 min), wrong shape for this primitive.ENGRAM_DEDUP_COSonly checks against the K=8 already-selected seed slots, O(K) not O(N²).server.el: "nothing in production calls /api/activate on this store — the soul's curiosity loop activates its own in-process graph." Single serial caller.vindex_bench.c'sbrute_topkoracle — real, genuine, unforced fit: 1-query-vs-N-vectors, no adaptivity, embarrassingly parallel. It's the correctness oracle this same PR (#109) adds to validate HNSW recall against ground truth.What's added
eg_cosine_batch.metal— batched cosine kernel (single- and multi-query variants), same-2.0dim-mismatch/zero-norm sentinel aseg_cosine().eg_metal_cosine.h/.m— C-callable Objective-C bridge. Lazy one-time device/pipeline init,MTLResourceStorageModeSharedbuffers (unified memory, no explicit upload step). Returnsfalseon any failure — no device, compile error, alloc failure — so callers fall back to the scalar CPU loop unconditionally. Never partial, never throws.eg_metal_cosine_stub.c— zero-dependency CPU-only implementation for non-Darwin (Linux CI). Same symbols, always returnsfalse. No#ifdefneeded at any call site — platform selection happens at the build/link step.build_vindex_bench.sh— one-command build: real bridge +-framework Metal -framework Foundationon Darwin, stub everywhere else.vindex_bench.c—brute_topk_metal/brute_topk_metal_batchcall the bridge, falling back to the existing CPUbrute_topkon failure orEL_METAL_COSINE=0.Not wired into
engram_activateor the daemon build (nsbx's_build_binary) —vindex_benchis a standalone offline tool, not part of the request-serving binary. No server-latency claim is made here; the bridge is a reusable primitive (eg_cosine_batch_metal+ batchedeg_cosine_batch_metal_multi) other call sites can adopt later without re-deriving any of this.Correctness + performance — real numbers, real data
Measured against an
nsbx-sandboxed clone of the live store (isolated port, never:8742/:7770, destroyed after), 13,671 real embedded nodes, dim=768, 300 real queries:The first version of this was measured slower than CPU (re-uploaded the full N×D matrix on every single query). Fixed by adding a real multi-query batched kernel that uploads the matrix once per query batch — see commit message for the before/after.
Synthetic scaling sweep (13k → 50k nodes, same dim/queries, no real data touched) shows the GPU speedup holding (~11x) as N grows toward the mathematical-foundations doc's 1.3M-node target, CPU brute-force cost growing linearly as expected.
Open items for Will
devitself has none of this code (noengram_vindex.c, noengram_geometry.c, no self-reify) — the live production binary and #109 both descend from an unmerged private worktree lineage. Worth knowing regardless of this PR.ENGRAM_SELF_REIFY=1is live on the production launchd job right now, rebuilding the entire HNSW index from scratch every 10-minute tick — real, currently-running cost, but the wrong shape for this GPU primitive (see above). Flagging for awareness, not fixing here.Superseded by #116, which restructures this work into an Adapter/Strategy/Factory (rather than a hand-rolled-Metal-only bridge) and adds ggml as the preferred backend strategy, per Will's directive to stop hand-rolling GPU kernels. This branch's content is NOT discarded — eg_cosine_batch.metal and eg_metal_cosine.m are preserved almost verbatim in #116 as one of three selectable strategies (eg_cosine_batch_strategy_metal_hand.m), still real, still verified, still selectable via EL_COSINE_BATCH_STRATEGY=metal. #116 also lands this work onto current dev (this branch predates #109's HNSW merge and a lot of other dev history since). Closing this PR in favor of #116: #116
Pull request closed