Repository navigation
perf(attention): native faster than a JS loop (2.0-5.5x), computeFlat, full typings; @ruvector/attention 2.3.0 - #1390
Merged
Merged
Conversation
… typings; @ruvector/attention 2.3.0 The native binding was slower than a naive JS loop (dim 384, flash 1000 keys: 1117 us native vs 413 us JS). The Rust kernel alone took 163 us, so ~85% of the time was the boundary: Vec<Float32Array> makes napi-rs create and delete a persistent reference (plus an Arc and finalizer box) per element, and the binding then copied every key and value into a Vec<f32>. - validate::F32Rows borrows a Float32Array[] for one sync call (napi_get_element + napi_get_typedarray_info, no references, no copies); used by every sync compute in attention.rs and graph.rs. - computeFlat(query, keysFlat, valuesFlat) on the seven core mechanisms: three typed arrays cross the boundary instead of 2n + 1. - Kernel: 8-lane dot product (utils::dot_f32) and axpy, a reused score buffer in flash, borrowed head sub-slices in multi-head (no split copies). - Commit the napi-generated index.js/index.d.ts (55 exports) and make publish-all ship them instead of a hand-written 4-function index.d.ts; build-attention runs the node tests against the committed files. Co-Authored-By: claude-flow <ruv@ruv.net>
…th_const_size under -D warnings) Same codegen class; kernel timing within noise of the previous version. Co-Authored-By: claude-flow <ruv@ruv.net>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
agentic-flow measured
@ruvector/attentionnative slower than a naive JS loop at dim 384 (flash 20/200/1000 keys native 19.8 µs / 358 µs / 3.4 ms vs JS 17.1 / 149 / 730 µs; multi_head 20 keys 47.4 vs 16.6 µs). Reproduced here, then split kernel vs boundary:Vec<Float32Array>: napi-rs 2 creates and deletes a persistent reference for every element, plus anArcand a finalizer box. The binding then copied every key and value into aVec<f32>(validate::to_vecs). At 1000 keys that is 2000 reference round trips and 2000 copies per call.iter().zip().map().sum()dependency chain, which LLVM may not reassociate. Flash also allocated aVec<&[f32]>and a scoreVecper block, and multi-head copied every key and value into per-headVecs.The published
index.d.ts(2.2.3) declared 4 functions (scaledDotProductAttention,multiHeadAttention,flashAttention,hyperbolicAttention) that the binary never exported.publish-all.ymlwrote that file by hand, and none of the 39 real exports were typed.Changes
validate::F32Rowsborrows a JSFloat32Array[]for the length of one synchronous call (napi_get_element+napi_get_typedarray_info, no references, no copies). Every synccompute/computeWithMask/computeWithEdges/computeWithPositions/getSpaceContributionsinattention.rsandgraph.rsuses it. TS signatures are unchanged (Float32Array[], viats_arg_type). Async/batch paths still copy, because they leave the JS thread.computeFlat(query, keys, values)on Dot/MultiHead/Hyperbolic/Flash/Linear/LocalGlobal/MoE.keysandvaluesare row-majorn * dimFloat32Arrays, so 3 typed arrays cross the boundary instead of2n + 1.ruvector-attention):utils::dot_f32(8 independent accumulators) andutils::axpy; flash reuses one score buffer and slices keys in place; multi-head runs heads on borrowed sub-slices. Outputs match the old ones to max |Δ| ≤ 5e-8 at dim 384 (summation order differs).index.js/index.d.tsare committed (55 declarations, every native export), using the same pattern as gnn-node.publish-all.ymlnow copies them and README.md into the main package and setsfiles. It also asserts thatclass FlashAttentionandcomputeFlat(are present.build-attention.ymlrunsnode --testagainst the committed files on linux-x64.test/flat-and-types.test.js: flat == nested for all 7 mechanisms, malformed flat input throws, non-Float32Array rows throw, and everyObject.keys(native)export is declared inindex.d.ts(the 2.2.3 file fails this). Thenpm testscript is fixed for node 22 (node --test test/*.test.js).@ruvector/attentionand the platform manifests go to 2.3.0.computeFlatis new API, andruvector's^2.2.3range picks it up.MultiHeadAttention.computeAsyncis removed from the docs.Breaking for TypeScript only: the 4 phantom function declarations are gone. They never existed at runtime.
Measurements
Host ruvultra (x86-64, 32 cores). Load average was 90–92 during every run (
uptime06:39:load average: 91.65, 90.56, 88.91). Every run wastaskset-pinned to one core, and before/after binaries ran interleaved in the same script. Each value is the median of 3 runs of per-call medians (1500–6000 iterations each). Latencies are noisy under this load, so the ratios carry the result.Rust kernel alone (
cargo run --release -p ruvector-attention --example kernel_timing, µs):Through Node (node 22, µs per call; JS = a straightforward softmax-attention loop over the same
Float32Array[]):compute(before)compute(after)computeFlat(after)Rerun on the final commit (after the clippy fix to
dot_f32, load 90.4–90.7; JS / before / after-nested / after-flat µs): flash 20 = 8.82 / 15.22 / 5.82 / 4.76, multi_head 20 = 26.19 / 34.22 / 6.85 / 4.98, flash 200 = 98.18 / 173.8 / 60.7 / 27.14, flash 1000 = 615.52 / 1343.73 / 328.16 / 165.09. The conclusion is the same.Native now beats the JS loop at every size, through both the nested and the flat API. Before, it was 1.3–2.7x slower.
Tests
cargo test -p ruvector-attention --all-features -p ruvector-attention-node: 279 passed, 0 failednode --test test/*.test.js(local release build): 12/12 passcargo clippy -p ruvector-attention -p ruvector-attention-node --all-targets -- -D warnings: cleanRelease plan
After merge:
publish-all.ymlworkflow_dispatch withversion=2.3.0,publish_crates=false,publish_wasm=false. Then a fresh-install verification, a benchmark rerun against the published artifact, a tarball diff and a leak scan.🤖 Generated with claude-flow