@aigentic/attention-unified-wasm 0.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,401 @@
1
+ # @aigentic/attention-unified-wasm - 18+ Attention Mechanisms in WASM
2
+
3
+ [![npm version](https://img.shields.io/npm/v/ruvector-attention-unified-wasm.svg)](https://www.npmjs.com/package/ruvector-attention-unified-wasm)
4
+ [![License: MIT OR Apache-2.0](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](https://github.com/ruvnet/ruvector)
5
+ [![Bundle Size](https://img.shields.io/badge/bundle%20size-331KB%20gzip-green.svg)](https://www.npmjs.com/package/ruvector-attention-unified-wasm)
6
+ [![WebAssembly](https://img.shields.io/badge/WebAssembly-654FF0?logo=webassembly&logoColor=white)](https://webassembly.org/)
7
+
8
+ **Unified WebAssembly library** with 18+ attention mechanisms spanning Neural, DAG, Graph, and State Space Model categories. Single import for all your attention needs in browser and edge environments.
9
+
10
+ ## Key Features
11
+
12
+ - **7 Neural Attention**: Scaled dot-product, multi-head, hyperbolic, linear, flash, local-global, MoE
13
+ - **7 DAG Attention**: Topological, causal cone, critical path, MinCut-gated, hierarchical Lorentz, parallel branch, temporal BTSP
14
+ - **3 Graph Attention**: GAT, GCN, GraphSAGE
15
+ - **1 State Space**: Mamba SSM with hybrid attention
16
+ - **Unified API**: Single selector for all mechanisms
17
+ - **WASM-Optimized**: Runs in browsers, Node.js, and edge runtimes
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install ruvector-attention-unified-wasm
23
+ # or
24
+ yarn add ruvector-attention-unified-wasm
25
+ # or
26
+ pnpm add ruvector-attention-unified-wasm
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ ```typescript
32
+ import init, {
33
+ UnifiedAttention,
34
+ availableMechanisms,
35
+ scaledDotAttention,
36
+ WasmMultiHeadAttention,
37
+ MambaSSMAttention,
38
+ MambaConfig
39
+ } from 'ruvector-attention-unified-wasm';
40
+
41
+ await init();
42
+
43
+ // List all available mechanisms
44
+ const mechanisms = availableMechanisms();
45
+ console.log(mechanisms);
46
+ // { neural: [...], dag: [...], graph: [...], ssm: [...] }
47
+
48
+ // Use unified selector
49
+ const attention = new UnifiedAttention("multi_head");
50
+ console.log(`Category: ${attention.category}`); // "neural"
51
+ console.log(`Supports sequences: ${attention.supportsSequences()}`);
52
+
53
+ // Direct attention computation
54
+ const query = new Float32Array([1.0, 0.5, 0.3, 0.1]);
55
+ const keys = [new Float32Array([0.9, 0.4, 0.2, 0.1])];
56
+ const values = [new Float32Array([1.0, 1.0, 1.0, 1.0])];
57
+ const output = scaledDotAttention(query, keys, values);
58
+ ```
59
+
60
+ ## Attention Categories
61
+
62
+ ### Neural Attention (7 mechanisms)
63
+
64
+ Standard transformer-style attention mechanisms for sequence processing.
65
+
66
+ ```typescript
67
+ import {
68
+ scaledDotAttention,
69
+ WasmMultiHeadAttention,
70
+ WasmHyperbolicAttention,
71
+ WasmLinearAttention,
72
+ WasmFlashAttention,
73
+ WasmLocalGlobalAttention,
74
+ WasmMoEAttention
75
+ } from 'ruvector-attention-unified-wasm';
76
+
77
+ // Scaled Dot-Product Attention
78
+ const output = scaledDotAttention(query, keys, values, scale);
79
+
80
+ // Multi-Head Attention
81
+ const mha = new WasmMultiHeadAttention(256, 8); // 256 dim, 8 heads
82
+ const attended = mha.compute(query, keys, values);
83
+ console.log(`Heads: ${mha.numHeads}, Head dim: ${mha.headDim}`);
84
+
85
+ // Hyperbolic Attention (for hierarchical data)
86
+ const hyperbolic = new WasmHyperbolicAttention(64, -1.0); // curvature = -1
87
+ const hypOut = hyperbolic.compute(query, keys, values);
88
+
89
+ // Linear Attention (O(n) complexity)
90
+ const linear = new WasmLinearAttention(64, 32); // 32 random features
91
+ const linOut = linear.compute(query, keys, values);
92
+
93
+ // Flash Attention (memory-efficient)
94
+ const flash = new WasmFlashAttention(64, 32); // block size 32
95
+ const flashOut = flash.compute(query, keys, values);
96
+
97
+ // Local-Global Attention (sparse)
98
+ const localGlobal = new WasmLocalGlobalAttention(64, 128, 4); // window=128, 4 global
99
+ const lgOut = localGlobal.compute(query, keys, values);
100
+
101
+ // Mixture of Experts Attention
102
+ const moe = new WasmMoEAttention(64, 8, 2); // 8 experts, top-2
103
+ const moeOut = moe.compute(query, keys, values);
104
+ ```
105
+
106
+ ### DAG Attention (7 mechanisms)
107
+
108
+ Specialized attention for Directed Acyclic Graphs, query plans, and workflow optimization.
109
+
110
+ ```typescript
111
+ import {
112
+ WasmQueryDag,
113
+ WasmTopologicalAttention,
114
+ WasmCausalConeAttention,
115
+ WasmCriticalPathAttention,
116
+ WasmMinCutGatedAttention,
117
+ WasmHierarchicalLorentzAttention,
118
+ WasmParallelBranchAttention,
119
+ WasmTemporalBTSPAttention
120
+ } from 'ruvector-attention-unified-wasm';
121
+
122
+ // Create a query DAG
123
+ const dag = new WasmQueryDag();
124
+ const scan = dag.addNode("scan", 10.0);
125
+ const filter = dag.addNode("filter", 5.0);
126
+ const join = dag.addNode("join", 20.0);
127
+ const aggregate = dag.addNode("aggregate", 15.0);
128
+
129
+ dag.addEdge(scan, filter);
130
+ dag.addEdge(filter, join);
131
+ dag.addEdge(scan, join);
132
+ dag.addEdge(join, aggregate);
133
+
134
+ // Topological Attention (position-aware)
135
+ const topo = new WasmTopologicalAttention(0.9); // decay factor
136
+ const topoScores = topo.forward(dag);
137
+
138
+ // Causal Cone Attention (lightcone-based)
139
+ const causal = new WasmCausalConeAttention(0.8, 0.6); // future discount, ancestor weight
140
+ const causalScores = causal.forward(dag);
141
+
142
+ // Critical Path Attention
143
+ const critical = new WasmCriticalPathAttention(2.0, 0.5); // path weight, branch penalty
144
+ const criticalScores = critical.forward(dag);
145
+
146
+ // MinCut-Gated Attention (flow-based)
147
+ const mincut = new WasmMinCutGatedAttention(0.5); // gate threshold
148
+ const mincutScores = mincut.forward(dag);
149
+
150
+ // Hierarchical Lorentz Attention (hyperbolic DAG)
151
+ const lorentz = new WasmHierarchicalLorentzAttention(-1.0, 0.1); // curvature, temperature
152
+ const lorentzScores = lorentz.forward(dag);
153
+
154
+ // Parallel Branch Attention
155
+ const parallel = new WasmParallelBranchAttention(4, 0.2); // max branches, sync penalty
156
+ const parallelScores = parallel.forward(dag);
157
+
158
+ // Temporal BTSP Attention
159
+ const btsp = new WasmTemporalBTSPAttention(0.95, 0.1); // decay, baseline
160
+ const btspScores = btsp.forward(dag);
161
+ ```
162
+
163
+ ### Graph Attention (3 mechanisms)
164
+
165
+ Attention mechanisms for graph-structured data.
166
+
167
+ ```typescript
168
+ import {
169
+ WasmGNNLayer,
170
+ GraphAttentionFactory,
171
+ graphHierarchicalForward,
172
+ graphDifferentiableSearch,
173
+ WasmSearchConfig
174
+ } from 'ruvector-attention-unified-wasm';
175
+
176
+ // Create GNN layer with attention
177
+ const gnn = new WasmGNNLayer(
178
+ 64, // input dimension
179
+ 128, // hidden dimension
180
+ 4, // attention heads
181
+ 0.1 // dropout
182
+ );
183
+
184
+ // Forward pass for a node
185
+ const nodeEmbed = new Float32Array(64);
186
+ const neighborEmbeds = [
187
+ new Float32Array(64),
188
+ new Float32Array(64)
189
+ ];
190
+ const edgeWeights = new Float32Array([0.8, 0.6]);
191
+
192
+ const updated = gnn.forward(nodeEmbed, neighborEmbeds, edgeWeights);
193
+ console.log(`Output dim: ${gnn.outputDim}`);
194
+
195
+ // Get available graph attention types
196
+ const types = GraphAttentionFactory.availableTypes(); // ["GAT", "GCN", "GraphSAGE"]
197
+
198
+ // Differentiable search
199
+ const config = new WasmSearchConfig(5, 0.1); // top-5, temperature
200
+ const candidates = [query, ...keys];
201
+ const searchResults = graphDifferentiableSearch(query, candidates, config);
202
+
203
+ // Hierarchical forward through multiple layers
204
+ const layers = [gnn, gnn2, gnn3];
205
+ const final = graphHierarchicalForward(query, layerEmbeddings, layers);
206
+ ```
207
+
208
+ ### Mamba SSM (State Space Model)
209
+
210
+ Selective State Space Model for efficient sequence processing with O(n) complexity.
211
+
212
+ ```typescript
213
+ import {
214
+ MambaConfig,
215
+ MambaSSMAttention,
216
+ HybridMambaAttention
217
+ } from 'ruvector-attention-unified-wasm';
218
+
219
+ // Configure Mamba
220
+ const config = new MambaConfig(256) // d_model = 256
221
+ .withStateDim(16) // state space dimension
222
+ .withExpandFactor(2) // expansion factor
223
+ .withConvKernelSize(4); // conv kernel
224
+
225
+ console.log(`Dim: ${config.dim}, State: ${config.state_dim}`);
226
+
227
+ // Create Mamba SSM Attention
228
+ const mamba = new MambaSSMAttention(config);
229
+ console.log(`Inner dim: ${mamba.innerDim}`);
230
+
231
+ // Or use defaults
232
+ const mambaDefault = MambaSSMAttention.withDefaults(128);
233
+
234
+ // Forward pass (seq_len, dim) flattened to 1D
235
+ const seqLen = 32;
236
+ const input = new Float32Array(seqLen * 256);
237
+ const output = mamba.forward(input, seqLen);
238
+
239
+ // Get pseudo-attention scores for visualization
240
+ const scores = mamba.getAttentionScores(input, seqLen);
241
+
242
+ // Hybrid Mamba + Local Attention
243
+ const hybrid = new HybridMambaAttention(config, 64); // local window = 64
244
+ const hybridOut = hybrid.forward(input, seqLen);
245
+ console.log(`Local window: ${hybrid.localWindow}`);
246
+ ```
247
+
248
+ ## Unified Selector API
249
+
250
+ ```typescript
251
+ import { UnifiedAttention } from 'ruvector-attention-unified-wasm';
252
+
253
+ // Create selector for any mechanism
254
+ const attention = new UnifiedAttention("mamba");
255
+
256
+ // Query capabilities
257
+ console.log(`Mechanism: ${attention.mechanism}`); // "mamba"
258
+ console.log(`Category: ${attention.category}`); // "ssm"
259
+ console.log(`Supports sequences: ${attention.supportsSequences()}`); // true
260
+ console.log(`Supports graphs: ${attention.supportsGraphs()}`); // false
261
+ console.log(`Supports hyperbolic: ${attention.supportsHyperbolic()}`); // false
262
+
263
+ // Valid mechanisms:
264
+ // Neural: scaled_dot_product, multi_head, hyperbolic, linear, flash, local_global, moe
265
+ // DAG: topological, causal_cone, critical_path, mincut_gated, hierarchical_lorentz, parallel_branch, temporal_btsp
266
+ // Graph: gat, gcn, graphsage
267
+ // SSM: mamba
268
+ ```
269
+
270
+ ## Utility Functions
271
+
272
+ ```typescript
273
+ import { softmax, temperatureSoftmax, cosineSimilarity, getStats } from 'ruvector-attention-unified-wasm';
274
+
275
+ // Softmax normalization
276
+ const logits = new Float32Array([1.0, 2.0, 3.0]);
277
+ const probs = softmax(logits);
278
+
279
+ // Temperature-scaled softmax
280
+ const sharper = temperatureSoftmax(logits, 0.5); // More peaked
281
+ const flatter = temperatureSoftmax(logits, 2.0); // More uniform
282
+
283
+ // Cosine similarity
284
+ const a = new Float32Array([1, 0, 0]);
285
+ const b = new Float32Array([0.7, 0.7, 0]);
286
+ const sim = cosineSimilarity(a, b);
287
+
288
+ // Library statistics
289
+ const stats = getStats();
290
+ console.log(`Total mechanisms: ${stats.total_mechanisms}`); // 18
291
+ console.log(`Neural: ${stats.neural_count}`); // 7
292
+ console.log(`DAG: ${stats.dag_count}`); // 7
293
+ console.log(`Graph: ${stats.graph_count}`); // 3
294
+ console.log(`SSM: ${stats.ssm_count}`); // 1
295
+ ```
296
+
297
+ ## Tensor Compression
298
+
299
+ ```typescript
300
+ import { WasmTensorCompress } from 'ruvector-attention-unified-wasm';
301
+
302
+ const compressor = new WasmTensorCompress();
303
+ const embedding = new Float32Array(256);
304
+
305
+ // Compress based on access frequency
306
+ const compressed = compressor.compress(embedding, 0.5); // 50% access frequency
307
+ const decompressed = compressor.decompress(compressed);
308
+
309
+ // Or specify compression level directly
310
+ const pq8 = compressor.compressWithLevel(embedding, "pq8"); // 8-bit product quantization
311
+
312
+ // Compression levels: "none", "half", "pq8", "pq4", "binary"
313
+ const ratio = compressor.getCompressionRatio(0.5);
314
+ ```
315
+
316
+ ## Performance Benchmarks
317
+
318
+ | Mechanism | Complexity | Latency (256-dim) |
319
+ |-----------|------------|-------------------|
320
+ | Scaled Dot-Product | O(n^2) | ~50us |
321
+ | Multi-Head (8 heads) | O(n^2) | ~200us |
322
+ | Linear | O(n) | ~30us |
323
+ | Flash | O(n^2) | ~100us (memory-efficient) |
324
+ | Mamba SSM | O(n) | ~80us |
325
+ | Topological DAG | O(V+E) | ~40us |
326
+ | GAT | O(E*h) | ~150us |
327
+
328
+ ## API Reference Summary
329
+
330
+ ### Neural Attention
331
+
332
+ | Class | Description |
333
+ |-------|-------------|
334
+ | `WasmMultiHeadAttention` | Parallel attention heads |
335
+ | `WasmHyperbolicAttention` | Hyperbolic space attention |
336
+ | `WasmLinearAttention` | O(n) performer-style |
337
+ | `WasmFlashAttention` | Memory-efficient blocked |
338
+ | `WasmLocalGlobalAttention` | Sparse with global tokens |
339
+ | `WasmMoEAttention` | Mixture of experts |
340
+
341
+ ### DAG Attention
342
+
343
+ | Class | Description |
344
+ |-------|-------------|
345
+ | `WasmTopologicalAttention` | Position in topological order |
346
+ | `WasmCausalConeAttention` | Lightcone causality |
347
+ | `WasmCriticalPathAttention` | Critical path weighting |
348
+ | `WasmMinCutGatedAttention` | Flow-based gating |
349
+ | `WasmHierarchicalLorentzAttention` | Multi-scale hyperbolic |
350
+ | `WasmParallelBranchAttention` | Parallel DAG branches |
351
+ | `WasmTemporalBTSPAttention` | Temporal eligibility traces |
352
+
353
+ ### Graph Attention
354
+
355
+ | Class | Description |
356
+ |-------|-------------|
357
+ | `WasmGNNLayer` | Multi-head graph attention |
358
+ | `GraphAttentionFactory` | Factory for graph attention types |
359
+
360
+ ### State Space
361
+
362
+ | Class | Description |
363
+ |-------|-------------|
364
+ | `MambaSSMAttention` | Selective state space model |
365
+ | `HybridMambaAttention` | Mamba + local attention |
366
+ | `MambaConfig` | Mamba configuration |
367
+
368
+ ## Use Cases
369
+
370
+ - **Transformers**: Standard and efficient attention variants
371
+ - **Query Optimization**: DAG-aware attention for SQL planners
372
+ - **Knowledge Graphs**: Graph attention for entity reasoning
373
+ - **Long Sequences**: O(n) attention with Mamba SSM
374
+ - **Hierarchical Data**: Hyperbolic attention for trees
375
+ - **Sparse Attention**: Local-global for long documents
376
+
377
+ ## Bundle Size
378
+
379
+ - **WASM binary**: ~331KB (uncompressed)
380
+ - **Gzip compressed**: ~120KB
381
+ - **JavaScript glue**: ~12KB
382
+
383
+ ## Related Packages
384
+
385
+ - [ruvector-learning-wasm](https://www.npmjs.com/package/ruvector-learning-wasm) - MicroLoRA adaptation
386
+ - [ruvector-nervous-system-wasm](https://www.npmjs.com/package/ruvector-nervous-system-wasm) - Bio-inspired neural
387
+ - [ruvector-economy-wasm](https://www.npmjs.com/package/ruvector-economy-wasm) - CRDT credit economy
388
+
389
+ ## License
390
+
391
+ MIT OR Apache-2.0
392
+
393
+ ## Links
394
+
395
+ - [GitHub Repository](https://github.com/ruvnet/ruvector)
396
+ - [Full Documentation](https://ruv.io)
397
+ - [Bug Reports](https://github.com/ruvnet/ruvector/issues)
398
+
399
+ ---
400
+
401
+ **Keywords**: attention mechanism, transformer, multi-head attention, DAG attention, graph neural network, GAT, GCN, GraphSAGE, Mamba, SSM, state space model, WebAssembly, WASM, hyperbolic attention, linear attention, flash attention, query optimization, neural network, deep learning, browser ML
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@aigentic/attention-unified-wasm",
3
+ "type": "module",
4
+ "collaborators": [
5
+ "RuVector Team"
6
+ ],
7
+ "author": "RuVector Team <ruvnet@users.noreply.github.com>",
8
+ "description": "Unified WebAssembly bindings for 18+ attention mechanisms: Neural, DAG, Graph, and Mamba SSM",
9
+ "version": "0.1.29",
10
+ "license": "MIT OR Apache-2.0",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/ruvnet/ruvector"
14
+ },
15
+ "bugs": {
16
+ "url": "https://github.com/ruvnet/ruvector/issues"
17
+ },
18
+ "files": [
19
+ "ruvector_attention_unified_wasm_bg.wasm",
20
+ "ruvector_attention_unified_wasm.js",
21
+ "ruvector_attention_unified_wasm.d.ts",
22
+ "ruvector_attention_unified_wasm_bg.wasm.d.ts",
23
+ "README.md"
24
+ ],
25
+ "main": "ruvector_attention_unified_wasm.js",
26
+ "homepage": "https://ruv.io",
27
+ "types": "ruvector_attention_unified_wasm.d.ts",
28
+ "sideEffects": [
29
+ "./snippets/*"
30
+ ],
31
+ "keywords": [
32
+ "attention",
33
+ "wasm",
34
+ "neural",
35
+ "dag",
36
+ "mamba",
37
+ "ruvector",
38
+ "webassembly",
39
+ "transformer",
40
+ "graph-attention",
41
+ "state-space-models"
42
+ ]
43
+ }