Merge commit 'd803bfe2b1fe7f5e219e50ac20d6801a0a58ac75' as 'vendor/ruvector'
This commit is contained in:
180
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.d.ts
vendored
Normal file
180
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.d.ts
vendored
Normal file
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Attention Engine
|
||||
*
|
||||
* Provides 14+ attention mechanisms including:
|
||||
* - 7 Neural attention mechanisms (scaled-dot, multi-head, hyperbolic, linear, flash, local-global, MoE, Mamba)
|
||||
* - 7 DAG attention mechanisms (topological, mincut-gated, hierarchical, spectral, flow, causal, sparse)
|
||||
*/
|
||||
import type { MultiHeadConfig, MoEResult, MambaResult, AttentionScores, QueryDag, GatePacket, AttentionConfig } from './types';
|
||||
/**
|
||||
* Core attention engine providing all neural and DAG attention mechanisms
|
||||
*/
|
||||
export interface AttentionEngine {
|
||||
/**
|
||||
* Scaled dot-product attention: softmax(QK^T / sqrt(d_k)) * V
|
||||
* @param Q Query tensor [batch, seq_len, d_k]
|
||||
* @param K Key tensor [batch, seq_len, d_k]
|
||||
* @param V Value tensor [batch, seq_len, d_v]
|
||||
* @param mask Optional attention mask
|
||||
* @returns Attention output [batch, seq_len, d_v]
|
||||
*/
|
||||
scaledDot(Q: Float32Array, K: Float32Array, V: Float32Array, mask?: Float32Array): Float32Array;
|
||||
/**
|
||||
* Multi-head attention with configurable heads
|
||||
* @param query Query tensor
|
||||
* @param keys Array of key tensors for each head
|
||||
* @param values Array of value tensors for each head
|
||||
* @param config Multi-head configuration
|
||||
* @returns Concatenated and projected attention output
|
||||
*/
|
||||
multiHead(query: Float32Array, keys: Float32Array[], values: Float32Array[], config: MultiHeadConfig): Float32Array;
|
||||
/**
|
||||
* Hyperbolic attention in Poincare ball model
|
||||
* Uses Mobius operations for attention in hyperbolic space
|
||||
* @param query Query in hyperbolic space
|
||||
* @param keys Keys in hyperbolic space
|
||||
* @param values Values in hyperbolic space
|
||||
* @param curvature Negative curvature of the manifold (default: -1)
|
||||
* @returns Attention output in hyperbolic space
|
||||
*/
|
||||
hyperbolic(query: Float32Array, keys: Float32Array[], values: Float32Array[], curvature?: number): Float32Array;
|
||||
/**
|
||||
* Linear attention with kernel feature maps
|
||||
* O(n) complexity instead of O(n^2)
|
||||
* @param query Query tensor
|
||||
* @param keys Key tensors
|
||||
* @param values Value tensors
|
||||
* @param kernel Kernel function: 'elu' | 'relu' | 'softmax' (default: 'elu')
|
||||
* @returns Linear attention output
|
||||
*/
|
||||
linear(query: Float32Array, keys: Float32Array[], values: Float32Array[], kernel?: 'elu' | 'relu' | 'softmax'): Float32Array;
|
||||
/**
|
||||
* Flash attention with memory-efficient tiling
|
||||
* Reduces memory from O(n^2) to O(n)
|
||||
* @param query Query tensor
|
||||
* @param keys Key tensors
|
||||
* @param values Value tensors
|
||||
* @param blockSize Tile size for chunked computation (default: 256)
|
||||
* @returns Flash attention output
|
||||
*/
|
||||
flash(query: Float32Array, keys: Float32Array[], values: Float32Array[], blockSize?: number): Float32Array;
|
||||
/**
|
||||
* Local-global attention combining sliding window with global tokens
|
||||
* @param query Query tensor
|
||||
* @param keys Key tensors
|
||||
* @param values Value tensors
|
||||
* @param windowSize Local attention window size
|
||||
* @param globalIndices Indices of global attention tokens
|
||||
* @returns Local-global attention output
|
||||
*/
|
||||
localGlobal(query: Float32Array, keys: Float32Array[], values: Float32Array[], windowSize: number, globalIndices?: number[]): Float32Array;
|
||||
/**
|
||||
* Mixture of Experts attention with top-k routing
|
||||
* @param query Query tensor
|
||||
* @param keys Key tensors
|
||||
* @param values Value tensors
|
||||
* @param numExperts Number of expert heads
|
||||
* @param topK Number of experts to route to per token
|
||||
* @param balanceLoss Whether to compute load balancing loss
|
||||
* @returns MoE result with output and routing info
|
||||
*/
|
||||
moe(query: Float32Array, keys: Float32Array[], values: Float32Array[], numExperts: number, topK: number, balanceLoss?: boolean): MoEResult;
|
||||
/**
|
||||
* Mamba selective state space attention
|
||||
* Linear-time sequence modeling with selective state spaces
|
||||
* @param input Input sequence
|
||||
* @param state Previous hidden state
|
||||
* @param config Mamba configuration
|
||||
* @returns Mamba result with output and new state
|
||||
*/
|
||||
mamba(input: Float32Array, state: Float32Array, config?: MambaConfig): MambaResult;
|
||||
/**
|
||||
* Topological attention following DAG structure
|
||||
* Respects topological ordering for information flow
|
||||
* @param dag Query DAG with nodes and edges
|
||||
* @returns Attention scores following topological order
|
||||
*/
|
||||
dagTopological(dag: QueryDag): AttentionScores;
|
||||
/**
|
||||
* Mincut-gated attention with selective information flow
|
||||
* Uses graph cuts for attention gating
|
||||
* @param dag Query DAG
|
||||
* @param gatePacket Gating configuration
|
||||
* @returns Gated attention scores
|
||||
*/
|
||||
dagMincutGated(dag: QueryDag, gatePacket: GatePacket): AttentionScores;
|
||||
/**
|
||||
* Hierarchical DAG attention with multi-scale aggregation
|
||||
* @param dag Query DAG
|
||||
* @param levels Number of hierarchy levels
|
||||
* @returns Hierarchical attention scores
|
||||
*/
|
||||
dagHierarchical(dag: QueryDag, levels?: number): AttentionScores;
|
||||
/**
|
||||
* Spectral attention using graph Laplacian eigenvectors
|
||||
* @param dag Query DAG
|
||||
* @param numEigenvectors Number of spectral components
|
||||
* @returns Spectral attention scores
|
||||
*/
|
||||
dagSpectral(dag: QueryDag, numEigenvectors?: number): AttentionScores;
|
||||
/**
|
||||
* Flow-based attention using max-flow algorithms
|
||||
* @param dag Query DAG
|
||||
* @param sourceIds Source node IDs
|
||||
* @param sinkIds Sink node IDs
|
||||
* @returns Flow-based attention scores
|
||||
*/
|
||||
dagFlow(dag: QueryDag, sourceIds: string[], sinkIds: string[]): AttentionScores;
|
||||
/**
|
||||
* Causal DAG attention respecting temporal ordering
|
||||
* @param dag Query DAG with temporal annotations
|
||||
* @returns Causally-masked attention scores
|
||||
*/
|
||||
dagCausal(dag: QueryDag): AttentionScores;
|
||||
/**
|
||||
* Sparse DAG attention with adaptive sparsity
|
||||
* @param dag Query DAG
|
||||
* @param sparsityRatio Target sparsity ratio (0-1)
|
||||
* @returns Sparse attention scores
|
||||
*/
|
||||
dagSparse(dag: QueryDag, sparsityRatio?: number): AttentionScores;
|
||||
}
|
||||
/** Mamba configuration */
|
||||
export interface MambaConfig {
|
||||
dState: number;
|
||||
dConv: number;
|
||||
expand: number;
|
||||
dt_rank: 'auto' | number;
|
||||
dt_min: number;
|
||||
dt_max: number;
|
||||
dt_init: 'constant' | 'random';
|
||||
dt_scale: number;
|
||||
conv_bias: boolean;
|
||||
bias: boolean;
|
||||
}
|
||||
/** Attention mechanism type */
|
||||
export type AttentionMechanism = 'scaled-dot' | 'multi-head' | 'hyperbolic' | 'linear' | 'flash' | 'local-global' | 'moe' | 'mamba' | 'dag-topological' | 'dag-mincut' | 'dag-hierarchical' | 'dag-spectral' | 'dag-flow' | 'dag-causal' | 'dag-sparse';
|
||||
/**
|
||||
* Create an attention engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized attention engine
|
||||
*/
|
||||
export declare function createAttentionEngine(config?: AttentionConfig): AttentionEngine;
|
||||
/**
|
||||
* Get list of available attention mechanisms
|
||||
*/
|
||||
export declare function listAttentionMechanisms(): AttentionMechanism[];
|
||||
/**
|
||||
* Benchmark attention mechanism performance
|
||||
* @param mechanism Mechanism to benchmark
|
||||
* @param inputSize Input tensor size
|
||||
* @param iterations Number of iterations
|
||||
* @returns Benchmark results
|
||||
*/
|
||||
export declare function benchmarkAttention(mechanism: AttentionMechanism, inputSize: number, iterations?: number): Promise<{
|
||||
mechanism: AttentionMechanism;
|
||||
avgTimeMs: number;
|
||||
throughputOpsPerSec: number;
|
||||
memoryPeakBytes: number;
|
||||
}>;
|
||||
//# sourceMappingURL=attention.d.ts.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.d.ts.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.d.ts.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"attention.d.ts","s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EAAE,MAAM,CAAC;IACf,OAAO,EAAE,UAAU,GAAG,QAAQ,CAAC;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,EAAE,OAAO,CAAC;CACf;AAED,+BAA+B;AAC/B,MAAM,MAAM,kBAAkB,GAC1B,YAAY,GACZ,YAAY,GACZ,YAAY,GACZ,QAAQ,GACR,OAAO,GACP,cAAc,GACd,KAAK,GACL,OAAO,GACP,iBAAiB,GACjB,YAAY,GACZ,kBAAkB,GAClB,cAAc,GACd,UAAU,GACV,YAAY,GACZ,YAAY,CAAC;AAMjB;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,CAAC,EAAE,eAAe,GAAG,eAAe,CA4E/E;AAeD;;GAEG;AACH,wBAAgB,uBAAuB,IAAI,kBAAkB,EAAE,CAkB9D;AAED;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CACtC,SAAS,EAAE,kBAAkB,EAC7B,SAAS,EAAE,MAAM,EACjB,UAAU,GAAE,MAAY,GACvB,OAAO,CAAC;IACT,SAAS,EAAE,kBAAkB,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,eAAe,EAAE,MAAM,CAAC;CACzB,CAAC,CAQD"}
|
||||
148
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.js
vendored
Normal file
148
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.js
vendored
Normal file
@@ -0,0 +1,148 @@
|
||||
"use strict";
|
||||
/**
|
||||
* RuVector WASM Unified - Attention Engine
|
||||
*
|
||||
* Provides 14+ attention mechanisms including:
|
||||
* - 7 Neural attention mechanisms (scaled-dot, multi-head, hyperbolic, linear, flash, local-global, MoE, Mamba)
|
||||
* - 7 DAG attention mechanisms (topological, mincut-gated, hierarchical, spectral, flow, causal, sparse)
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createAttentionEngine = createAttentionEngine;
|
||||
exports.listAttentionMechanisms = listAttentionMechanisms;
|
||||
exports.benchmarkAttention = benchmarkAttention;
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
/**
|
||||
* Create an attention engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized attention engine
|
||||
*/
|
||||
function createAttentionEngine(config) {
|
||||
// Implementation delegated to WASM module
|
||||
return {
|
||||
scaledDot: (Q, K, V, mask) => {
|
||||
// WASM call: ruvector_attention_scaled_dot(Q, K, V, mask)
|
||||
const dk = Math.sqrt(Q.length / K.length);
|
||||
const scores = new Float32Array(Q.length);
|
||||
// Placeholder for WASM implementation
|
||||
return scores;
|
||||
},
|
||||
multiHead: (query, keys, values, config) => {
|
||||
// WASM call: ruvector_attention_multi_head(query, keys, values, config)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
hyperbolic: (query, keys, values, curvature = -1) => {
|
||||
// WASM call: ruvector_attention_hyperbolic(query, keys, values, curvature)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
linear: (query, keys, values, kernel = 'elu') => {
|
||||
// WASM call: ruvector_attention_linear(query, keys, values, kernel)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
flash: (query, keys, values, blockSize = 256) => {
|
||||
// WASM call: ruvector_attention_flash(query, keys, values, blockSize)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
localGlobal: (query, keys, values, windowSize, globalIndices = []) => {
|
||||
// WASM call: ruvector_attention_local_global(...)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
moe: (query, keys, values, numExperts, topK, balanceLoss = true) => {
|
||||
// WASM call: ruvector_attention_moe(...)
|
||||
return {
|
||||
output: new Float32Array(query.length),
|
||||
routerLogits: new Float32Array(numExperts),
|
||||
expertUsage: new Float32Array(numExperts),
|
||||
loadBalanceLoss: 0,
|
||||
};
|
||||
},
|
||||
mamba: (input, state, config) => {
|
||||
// WASM call: ruvector_attention_mamba(input, state, config)
|
||||
return {
|
||||
output: new Float32Array(input.length),
|
||||
newState: new Float32Array(state.length),
|
||||
deltaTime: 0,
|
||||
};
|
||||
},
|
||||
dagTopological: (dag) => {
|
||||
// WASM call: ruvector_dag_topological(dag)
|
||||
return createEmptyScores('dag-topological');
|
||||
},
|
||||
dagMincutGated: (dag, gatePacket) => {
|
||||
// WASM call: ruvector_dag_mincut_gated(dag, gatePacket)
|
||||
return createEmptyScores('dag-mincut');
|
||||
},
|
||||
dagHierarchical: (dag, levels = 3) => {
|
||||
// WASM call: ruvector_dag_hierarchical(dag, levels)
|
||||
return createEmptyScores('dag-hierarchical');
|
||||
},
|
||||
dagSpectral: (dag, numEigenvectors = 16) => {
|
||||
// WASM call: ruvector_dag_spectral(dag, numEigenvectors)
|
||||
return createEmptyScores('dag-spectral');
|
||||
},
|
||||
dagFlow: (dag, sourceIds, sinkIds) => {
|
||||
// WASM call: ruvector_dag_flow(dag, sourceIds, sinkIds)
|
||||
return createEmptyScores('dag-flow');
|
||||
},
|
||||
dagCausal: (dag) => {
|
||||
// WASM call: ruvector_dag_causal(dag)
|
||||
return createEmptyScores('dag-causal');
|
||||
},
|
||||
dagSparse: (dag, sparsityRatio = 0.9) => {
|
||||
// WASM call: ruvector_dag_sparse(dag, sparsityRatio)
|
||||
return createEmptyScores('dag-sparse');
|
||||
},
|
||||
};
|
||||
}
|
||||
/** Create empty attention scores for placeholder returns */
|
||||
function createEmptyScores(mechanism) {
|
||||
return {
|
||||
scores: new Float32Array(0),
|
||||
weights: new Float32Array(0),
|
||||
metadata: {
|
||||
mechanism,
|
||||
computeTimeMs: 0,
|
||||
memoryUsageBytes: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Get list of available attention mechanisms
|
||||
*/
|
||||
function listAttentionMechanisms() {
|
||||
return [
|
||||
'scaled-dot',
|
||||
'multi-head',
|
||||
'hyperbolic',
|
||||
'linear',
|
||||
'flash',
|
||||
'local-global',
|
||||
'moe',
|
||||
'mamba',
|
||||
'dag-topological',
|
||||
'dag-mincut',
|
||||
'dag-hierarchical',
|
||||
'dag-spectral',
|
||||
'dag-flow',
|
||||
'dag-causal',
|
||||
'dag-sparse',
|
||||
];
|
||||
}
|
||||
/**
|
||||
* Benchmark attention mechanism performance
|
||||
* @param mechanism Mechanism to benchmark
|
||||
* @param inputSize Input tensor size
|
||||
* @param iterations Number of iterations
|
||||
* @returns Benchmark results
|
||||
*/
|
||||
async function benchmarkAttention(mechanism, inputSize, iterations = 100) {
|
||||
// Placeholder for benchmark implementation
|
||||
return {
|
||||
mechanism,
|
||||
avgTimeMs: 0,
|
||||
throughputOpsPerSec: 0,
|
||||
memoryPeakBytes: 0,
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=attention.js.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.js.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.js.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"attention.js","sourceRoot":"","sources":["attention.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAgQH,sDA4EC;AAkBD,0DAkBC;AASD,gDAiBC;AAnJD,+EAA+E;AAC/E,wBAAwB;AACxB,+EAA+E;AAE/E;;;;GAIG;AACH,SAAgB,qBAAqB,CAAC,MAAwB;IAC5D,0CAA0C;IAC1C,OAAO;QACL,SAAS,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE;YAC3B,0DAA0D;YAC1D,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;YAC1C,MAAM,MAAM,GAAG,IAAI,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;YAC1C,sCAAsC;YACtC,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,SAAS,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE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CAAC,CAAC;QAC3B,OAAO,EAAE,IAAI,YAAY,CAAC,CAAC,CAAC;QAC5B,QAAQ,EAAE;YACR,SAAS;YACT,aAAa,EAAE,CAAC;YAChB,gBAAgB,EAAE,CAAC;SACpB;KACF,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,SAAgB,uBAAuB;IACrC,OAAO;QACL,YAAY;QACZ,YAAY;QACZ,YAAY;QACZ,QAAQ;QACR,OAAO;QACP,cAAc;QACd,KAAK;QACL,OAAO;QACP,iBAAiB;QACjB,YAAY;QACZ,kBAAkB;QAClB,cAAc;QACd,UAAU;QACV,YAAY;QACZ,YAAY;KACb,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACI,KAAK,UAAU,kBAAkB,CACtC,SAA6B,EAC7B,SAAiB,EACjB,aAAqB,GAAG;IAOxB,2CAA2C;IAC3C,OAAO;QACL,SAAS;QACT,SAAS,EAAE,CAAC;QACZ,mBAAmB,EAAE,CAAC;QACtB,eAAe,EAAE,CAAC;KACnB,CAAC;AACJ,CAAC"}
|
||||
401
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.ts
vendored
Normal file
401
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/attention.ts
vendored
Normal file
@@ -0,0 +1,401 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Attention Engine
|
||||
*
|
||||
* Provides 14+ attention mechanisms including:
|
||||
* - 7 Neural attention mechanisms (scaled-dot, multi-head, hyperbolic, linear, flash, local-global, MoE, Mamba)
|
||||
* - 7 DAG attention mechanisms (topological, mincut-gated, hierarchical, spectral, flow, causal, sparse)
|
||||
*/
|
||||
|
||||
import type {
|
||||
MultiHeadConfig,
|
||||
MoEResult,
|
||||
MambaResult,
|
||||
AttentionScores,
|
||||
AttentionMetadata,
|
||||
QueryDag,
|
||||
GatePacket,
|
||||
AttentionConfig,
|
||||
Tensor,
|
||||
} from './types';
|
||||
|
||||
// ============================================================================
|
||||
// Attention Engine Interface
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Core attention engine providing all neural and DAG attention mechanisms
|
||||
*/
|
||||
export interface AttentionEngine {
|
||||
// -------------------------------------------------------------------------
|
||||
// Neural Attention Mechanisms (7)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Scaled dot-product attention: softmax(QK^T / sqrt(d_k)) * V
|
||||
* @param Q Query tensor [batch, seq_len, d_k]
|
||||
* @param K Key tensor [batch, seq_len, d_k]
|
||||
* @param V Value tensor [batch, seq_len, d_v]
|
||||
* @param mask Optional attention mask
|
||||
* @returns Attention output [batch, seq_len, d_v]
|
||||
*/
|
||||
scaledDot(Q: Float32Array, K: Float32Array, V: Float32Array, mask?: Float32Array): Float32Array;
|
||||
|
||||
/**
|
||||
* Multi-head attention with configurable heads
|
||||
* @param query Query tensor
|
||||
* @param keys Array of key tensors for each head
|
||||
* @param values Array of value tensors for each head
|
||||
* @param config Multi-head configuration
|
||||
* @returns Concatenated and projected attention output
|
||||
*/
|
||||
multiHead(
|
||||
query: Float32Array,
|
||||
keys: Float32Array[],
|
||||
values: Float32Array[],
|
||||
config: MultiHeadConfig
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Hyperbolic attention in Poincare ball model
|
||||
* Uses Mobius operations for attention in hyperbolic space
|
||||
* @param query Query in hyperbolic space
|
||||
* @param keys Keys in hyperbolic space
|
||||
* @param values Values in hyperbolic space
|
||||
* @param curvature Negative curvature of the manifold (default: -1)
|
||||
* @returns Attention output in hyperbolic space
|
||||
*/
|
||||
hyperbolic(
|
||||
query: Float32Array,
|
||||
keys: Float32Array[],
|
||||
values: Float32Array[],
|
||||
curvature?: number
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Linear attention with kernel feature maps
|
||||
* O(n) complexity instead of O(n^2)
|
||||
* @param query Query tensor
|
||||
* @param keys Key tensors
|
||||
* @param values Value tensors
|
||||
* @param kernel Kernel function: 'elu' | 'relu' | 'softmax' (default: 'elu')
|
||||
* @returns Linear attention output
|
||||
*/
|
||||
linear(
|
||||
query: Float32Array,
|
||||
keys: Float32Array[],
|
||||
values: Float32Array[],
|
||||
kernel?: 'elu' | 'relu' | 'softmax'
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Flash attention with memory-efficient tiling
|
||||
* Reduces memory from O(n^2) to O(n)
|
||||
* @param query Query tensor
|
||||
* @param keys Key tensors
|
||||
* @param values Value tensors
|
||||
* @param blockSize Tile size for chunked computation (default: 256)
|
||||
* @returns Flash attention output
|
||||
*/
|
||||
flash(
|
||||
query: Float32Array,
|
||||
keys: Float32Array[],
|
||||
values: Float32Array[],
|
||||
blockSize?: number
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Local-global attention combining sliding window with global tokens
|
||||
* @param query Query tensor
|
||||
* @param keys Key tensors
|
||||
* @param values Value tensors
|
||||
* @param windowSize Local attention window size
|
||||
* @param globalIndices Indices of global attention tokens
|
||||
* @returns Local-global attention output
|
||||
*/
|
||||
localGlobal(
|
||||
query: Float32Array,
|
||||
keys: Float32Array[],
|
||||
values: Float32Array[],
|
||||
windowSize: number,
|
||||
globalIndices?: number[]
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Mixture of Experts attention with top-k routing
|
||||
* @param query Query tensor
|
||||
* @param keys Key tensors
|
||||
* @param values Value tensors
|
||||
* @param numExperts Number of expert heads
|
||||
* @param topK Number of experts to route to per token
|
||||
* @param balanceLoss Whether to compute load balancing loss
|
||||
* @returns MoE result with output and routing info
|
||||
*/
|
||||
moe(
|
||||
query: Float32Array,
|
||||
keys: Float32Array[],
|
||||
values: Float32Array[],
|
||||
numExperts: number,
|
||||
topK: number,
|
||||
balanceLoss?: boolean
|
||||
): MoEResult;
|
||||
|
||||
/**
|
||||
* Mamba selective state space attention
|
||||
* Linear-time sequence modeling with selective state spaces
|
||||
* @param input Input sequence
|
||||
* @param state Previous hidden state
|
||||
* @param config Mamba configuration
|
||||
* @returns Mamba result with output and new state
|
||||
*/
|
||||
mamba(
|
||||
input: Float32Array,
|
||||
state: Float32Array,
|
||||
config?: MambaConfig
|
||||
): MambaResult;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// DAG Attention Mechanisms (7)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Topological attention following DAG structure
|
||||
* Respects topological ordering for information flow
|
||||
* @param dag Query DAG with nodes and edges
|
||||
* @returns Attention scores following topological order
|
||||
*/
|
||||
dagTopological(dag: QueryDag): AttentionScores;
|
||||
|
||||
/**
|
||||
* Mincut-gated attention with selective information flow
|
||||
* Uses graph cuts for attention gating
|
||||
* @param dag Query DAG
|
||||
* @param gatePacket Gating configuration
|
||||
* @returns Gated attention scores
|
||||
*/
|
||||
dagMincutGated(dag: QueryDag, gatePacket: GatePacket): AttentionScores;
|
||||
|
||||
/**
|
||||
* Hierarchical DAG attention with multi-scale aggregation
|
||||
* @param dag Query DAG
|
||||
* @param levels Number of hierarchy levels
|
||||
* @returns Hierarchical attention scores
|
||||
*/
|
||||
dagHierarchical(dag: QueryDag, levels?: number): AttentionScores;
|
||||
|
||||
/**
|
||||
* Spectral attention using graph Laplacian eigenvectors
|
||||
* @param dag Query DAG
|
||||
* @param numEigenvectors Number of spectral components
|
||||
* @returns Spectral attention scores
|
||||
*/
|
||||
dagSpectral(dag: QueryDag, numEigenvectors?: number): AttentionScores;
|
||||
|
||||
/**
|
||||
* Flow-based attention using max-flow algorithms
|
||||
* @param dag Query DAG
|
||||
* @param sourceIds Source node IDs
|
||||
* @param sinkIds Sink node IDs
|
||||
* @returns Flow-based attention scores
|
||||
*/
|
||||
dagFlow(dag: QueryDag, sourceIds: string[], sinkIds: string[]): AttentionScores;
|
||||
|
||||
/**
|
||||
* Causal DAG attention respecting temporal ordering
|
||||
* @param dag Query DAG with temporal annotations
|
||||
* @returns Causally-masked attention scores
|
||||
*/
|
||||
dagCausal(dag: QueryDag): AttentionScores;
|
||||
|
||||
/**
|
||||
* Sparse DAG attention with adaptive sparsity
|
||||
* @param dag Query DAG
|
||||
* @param sparsityRatio Target sparsity ratio (0-1)
|
||||
* @returns Sparse attention scores
|
||||
*/
|
||||
dagSparse(dag: QueryDag, sparsityRatio?: number): AttentionScores;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Supporting Types
|
||||
// ============================================================================
|
||||
|
||||
/** Mamba configuration */
|
||||
export interface MambaConfig {
|
||||
dState: number;
|
||||
dConv: number;
|
||||
expand: number;
|
||||
dt_rank: 'auto' | number;
|
||||
dt_min: number;
|
||||
dt_max: number;
|
||||
dt_init: 'constant' | 'random';
|
||||
dt_scale: number;
|
||||
conv_bias: boolean;
|
||||
bias: boolean;
|
||||
}
|
||||
|
||||
/** Attention mechanism type */
|
||||
export type AttentionMechanism =
|
||||
| 'scaled-dot'
|
||||
| 'multi-head'
|
||||
| 'hyperbolic'
|
||||
| 'linear'
|
||||
| 'flash'
|
||||
| 'local-global'
|
||||
| 'moe'
|
||||
| 'mamba'
|
||||
| 'dag-topological'
|
||||
| 'dag-mincut'
|
||||
| 'dag-hierarchical'
|
||||
| 'dag-spectral'
|
||||
| 'dag-flow'
|
||||
| 'dag-causal'
|
||||
| 'dag-sparse';
|
||||
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Create an attention engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized attention engine
|
||||
*/
|
||||
export function createAttentionEngine(config?: AttentionConfig): AttentionEngine {
|
||||
// Implementation delegated to WASM module
|
||||
return {
|
||||
scaledDot: (Q, K, V, mask) => {
|
||||
// WASM call: ruvector_attention_scaled_dot(Q, K, V, mask)
|
||||
const dk = Math.sqrt(Q.length / K.length);
|
||||
const scores = new Float32Array(Q.length);
|
||||
// Placeholder for WASM implementation
|
||||
return scores;
|
||||
},
|
||||
multiHead: (query, keys, values, config) => {
|
||||
// WASM call: ruvector_attention_multi_head(query, keys, values, config)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
hyperbolic: (query, keys, values, curvature = -1) => {
|
||||
// WASM call: ruvector_attention_hyperbolic(query, keys, values, curvature)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
linear: (query, keys, values, kernel = 'elu') => {
|
||||
// WASM call: ruvector_attention_linear(query, keys, values, kernel)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
flash: (query, keys, values, blockSize = 256) => {
|
||||
// WASM call: ruvector_attention_flash(query, keys, values, blockSize)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
localGlobal: (query, keys, values, windowSize, globalIndices = []) => {
|
||||
// WASM call: ruvector_attention_local_global(...)
|
||||
return new Float32Array(query.length);
|
||||
},
|
||||
moe: (query, keys, values, numExperts, topK, balanceLoss = true) => {
|
||||
// WASM call: ruvector_attention_moe(...)
|
||||
return {
|
||||
output: new Float32Array(query.length),
|
||||
routerLogits: new Float32Array(numExperts),
|
||||
expertUsage: new Float32Array(numExperts),
|
||||
loadBalanceLoss: 0,
|
||||
};
|
||||
},
|
||||
mamba: (input, state, config) => {
|
||||
// WASM call: ruvector_attention_mamba(input, state, config)
|
||||
return {
|
||||
output: new Float32Array(input.length),
|
||||
newState: new Float32Array(state.length),
|
||||
deltaTime: 0,
|
||||
};
|
||||
},
|
||||
dagTopological: (dag) => {
|
||||
// WASM call: ruvector_dag_topological(dag)
|
||||
return createEmptyScores('dag-topological');
|
||||
},
|
||||
dagMincutGated: (dag, gatePacket) => {
|
||||
// WASM call: ruvector_dag_mincut_gated(dag, gatePacket)
|
||||
return createEmptyScores('dag-mincut');
|
||||
},
|
||||
dagHierarchical: (dag, levels = 3) => {
|
||||
// WASM call: ruvector_dag_hierarchical(dag, levels)
|
||||
return createEmptyScores('dag-hierarchical');
|
||||
},
|
||||
dagSpectral: (dag, numEigenvectors = 16) => {
|
||||
// WASM call: ruvector_dag_spectral(dag, numEigenvectors)
|
||||
return createEmptyScores('dag-spectral');
|
||||
},
|
||||
dagFlow: (dag, sourceIds, sinkIds) => {
|
||||
// WASM call: ruvector_dag_flow(dag, sourceIds, sinkIds)
|
||||
return createEmptyScores('dag-flow');
|
||||
},
|
||||
dagCausal: (dag) => {
|
||||
// WASM call: ruvector_dag_causal(dag)
|
||||
return createEmptyScores('dag-causal');
|
||||
},
|
||||
dagSparse: (dag, sparsityRatio = 0.9) => {
|
||||
// WASM call: ruvector_dag_sparse(dag, sparsityRatio)
|
||||
return createEmptyScores('dag-sparse');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Create empty attention scores for placeholder returns */
|
||||
function createEmptyScores(mechanism: string): AttentionScores {
|
||||
return {
|
||||
scores: new Float32Array(0),
|
||||
weights: new Float32Array(0),
|
||||
metadata: {
|
||||
mechanism,
|
||||
computeTimeMs: 0,
|
||||
memoryUsageBytes: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of available attention mechanisms
|
||||
*/
|
||||
export function listAttentionMechanisms(): AttentionMechanism[] {
|
||||
return [
|
||||
'scaled-dot',
|
||||
'multi-head',
|
||||
'hyperbolic',
|
||||
'linear',
|
||||
'flash',
|
||||
'local-global',
|
||||
'moe',
|
||||
'mamba',
|
||||
'dag-topological',
|
||||
'dag-mincut',
|
||||
'dag-hierarchical',
|
||||
'dag-spectral',
|
||||
'dag-flow',
|
||||
'dag-causal',
|
||||
'dag-sparse',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Benchmark attention mechanism performance
|
||||
* @param mechanism Mechanism to benchmark
|
||||
* @param inputSize Input tensor size
|
||||
* @param iterations Number of iterations
|
||||
* @returns Benchmark results
|
||||
*/
|
||||
export async function benchmarkAttention(
|
||||
mechanism: AttentionMechanism,
|
||||
inputSize: number,
|
||||
iterations: number = 100
|
||||
): Promise<{
|
||||
mechanism: AttentionMechanism;
|
||||
avgTimeMs: number;
|
||||
throughputOpsPerSec: number;
|
||||
memoryPeakBytes: number;
|
||||
}> {
|
||||
// Placeholder for benchmark implementation
|
||||
return {
|
||||
mechanism,
|
||||
avgTimeMs: 0,
|
||||
throughputOpsPerSec: 0,
|
||||
memoryPeakBytes: 0,
|
||||
};
|
||||
}
|
||||
227
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.d.ts
vendored
Normal file
227
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.d.ts
vendored
Normal file
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Economy Engine
|
||||
*
|
||||
* Provides compute credit economy including:
|
||||
* - Credit balance management
|
||||
* - Contribution multipliers
|
||||
* - Staking mechanisms
|
||||
* - Transaction history
|
||||
* - Reward distribution
|
||||
*/
|
||||
import type { CreditAccount, Transaction, StakingPosition, EconomyMetrics, EconomyConfig } from './types';
|
||||
/**
|
||||
* Core economy engine for compute credit management
|
||||
*/
|
||||
export interface EconomyEngine {
|
||||
/**
|
||||
* Get current credit balance
|
||||
* @returns Current balance in credits
|
||||
*/
|
||||
creditBalance(): number;
|
||||
/**
|
||||
* Get contribution multiplier
|
||||
* Based on staking, history, and activity
|
||||
* @returns Multiplier value (1.0 = base rate)
|
||||
*/
|
||||
contributionMultiplier(): number;
|
||||
/**
|
||||
* Get full account state
|
||||
* @returns Complete credit account information
|
||||
*/
|
||||
getAccount(): CreditAccount;
|
||||
/**
|
||||
* Check if account can afford operation
|
||||
* @param cost Operation cost
|
||||
* @returns Whether balance is sufficient
|
||||
*/
|
||||
canAfford(cost: number): boolean;
|
||||
/**
|
||||
* Deposit credits into staking
|
||||
* @param amount Amount to stake
|
||||
* @param lockDuration Optional lock duration in seconds
|
||||
* @returns Staking position
|
||||
*/
|
||||
stakeDeposit(amount: number, lockDuration?: number): StakingPosition;
|
||||
/**
|
||||
* Withdraw from staking
|
||||
* @param amount Amount to withdraw
|
||||
* @returns Withdrawn amount (may include penalties)
|
||||
*/
|
||||
stakeWithdraw(amount: number): number;
|
||||
/**
|
||||
* Get current staking positions
|
||||
* @returns Array of staking positions
|
||||
*/
|
||||
getStakingPositions(): StakingPosition[];
|
||||
/**
|
||||
* Get total staked amount
|
||||
* @returns Total credits staked
|
||||
*/
|
||||
getTotalStaked(): number;
|
||||
/**
|
||||
* Estimate staking rewards
|
||||
* @param amount Amount to stake
|
||||
* @param duration Duration in seconds
|
||||
* @returns Estimated reward
|
||||
*/
|
||||
estimateStakingReward(amount: number, duration: number): number;
|
||||
/**
|
||||
* Transfer credits to another account
|
||||
* @param targetId Target account ID
|
||||
* @param amount Amount to transfer
|
||||
* @returns Transaction record
|
||||
*/
|
||||
transfer(targetId: string, amount: number): Transaction;
|
||||
/**
|
||||
* Deposit credits from external source
|
||||
* @param amount Amount to deposit
|
||||
* @param source Source identifier
|
||||
* @returns Transaction record
|
||||
*/
|
||||
deposit(amount: number, source?: string): Transaction;
|
||||
/**
|
||||
* Withdraw credits to external destination
|
||||
* @param amount Amount to withdraw
|
||||
* @param destination Destination identifier
|
||||
* @returns Transaction record
|
||||
*/
|
||||
withdraw(amount: number, destination?: string): Transaction;
|
||||
/**
|
||||
* Get transaction history
|
||||
* @param options Filter options
|
||||
* @returns Array of transactions
|
||||
*/
|
||||
getTransactionHistory(options?: TransactionFilter): Transaction[];
|
||||
/**
|
||||
* Get transaction by ID
|
||||
* @param transactionId Transaction ID
|
||||
* @returns Transaction or undefined
|
||||
*/
|
||||
getTransaction(transactionId: string): Transaction | undefined;
|
||||
/**
|
||||
* Claim pending rewards
|
||||
* @returns Amount claimed
|
||||
*/
|
||||
claimRewards(): number;
|
||||
/**
|
||||
* Get pending rewards
|
||||
* @returns Amount of unclaimed rewards
|
||||
*/
|
||||
getPendingRewards(): number;
|
||||
/**
|
||||
* Record contribution for rewards
|
||||
* @param contributionType Type of contribution
|
||||
* @param value Contribution value
|
||||
*/
|
||||
recordContribution(contributionType: ContributionType, value: number): void;
|
||||
/**
|
||||
* Get contribution history
|
||||
* @param startTime Start of period
|
||||
* @param endTime End of period
|
||||
* @returns Contribution records
|
||||
*/
|
||||
getContributions(startTime?: number, endTime?: number): ContributionRecord[];
|
||||
/**
|
||||
* Get cost for operation type
|
||||
* @param operation Operation identifier
|
||||
* @param params Operation parameters
|
||||
* @returns Cost in credits
|
||||
*/
|
||||
getCost(operation: OperationType, params?: Record<string, unknown>): number;
|
||||
/**
|
||||
* Spend credits for operation
|
||||
* @param operation Operation type
|
||||
* @param params Operation parameters
|
||||
* @returns Transaction record
|
||||
*/
|
||||
spend(operation: OperationType, params?: Record<string, unknown>): Transaction;
|
||||
/**
|
||||
* Get pricing table
|
||||
* @returns Map of operations to base costs
|
||||
*/
|
||||
getPricingTable(): Map<OperationType, number>;
|
||||
/**
|
||||
* Get economy-wide metrics
|
||||
* @returns Global economy metrics
|
||||
*/
|
||||
getMetrics(): EconomyMetrics;
|
||||
/**
|
||||
* Get account analytics
|
||||
* @param period Time period
|
||||
* @returns Account analytics
|
||||
*/
|
||||
getAnalytics(period?: 'day' | 'week' | 'month'): AccountAnalytics;
|
||||
/**
|
||||
* Get leaderboard
|
||||
* @param metric Ranking metric
|
||||
* @param limit Number of entries
|
||||
* @returns Leaderboard entries
|
||||
*/
|
||||
getLeaderboard(metric: LeaderboardMetric, limit?: number): LeaderboardEntry[];
|
||||
}
|
||||
/** Transaction filter options */
|
||||
export interface TransactionFilter {
|
||||
type?: Transaction['type'];
|
||||
startTime?: number;
|
||||
endTime?: number;
|
||||
minAmount?: number;
|
||||
maxAmount?: number;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
/** Contribution type */
|
||||
export type ContributionType = 'compute' | 'storage' | 'bandwidth' | 'validation' | 'training' | 'inference';
|
||||
/** Contribution record */
|
||||
export interface ContributionRecord {
|
||||
type: ContributionType;
|
||||
value: number;
|
||||
timestamp: number;
|
||||
rewardEarned: number;
|
||||
}
|
||||
/** Operation type for pricing */
|
||||
export type OperationType = 'attention_scaled_dot' | 'attention_multi_head' | 'attention_flash' | 'attention_moe' | 'learning_lora' | 'learning_btsp' | 'nervous_step' | 'nervous_propagate' | 'exotic_quantum' | 'exotic_hyperbolic' | 'storage_read' | 'storage_write';
|
||||
/** Account analytics */
|
||||
export interface AccountAnalytics {
|
||||
period: string;
|
||||
totalSpent: number;
|
||||
totalEarned: number;
|
||||
netFlow: number;
|
||||
topOperations: {
|
||||
operation: OperationType;
|
||||
count: number;
|
||||
cost: number;
|
||||
}[];
|
||||
stakingYield: number;
|
||||
multiplierHistory: {
|
||||
time: number;
|
||||
value: number;
|
||||
}[];
|
||||
}
|
||||
/** Leaderboard metric */
|
||||
export type LeaderboardMetric = 'total_staked' | 'contributions' | 'compute_usage' | 'rewards_earned';
|
||||
/** Leaderboard entry */
|
||||
export interface LeaderboardEntry {
|
||||
rank: number;
|
||||
accountId: string;
|
||||
value: number;
|
||||
change: number;
|
||||
}
|
||||
/**
|
||||
* Create an economy engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized economy engine
|
||||
*/
|
||||
export declare function createEconomyEngine(config?: EconomyConfig): EconomyEngine;
|
||||
/**
|
||||
* Calculate APY for staking
|
||||
* @param baseRate Base reward rate
|
||||
* @param compoundingFrequency Annual compounding frequency
|
||||
*/
|
||||
export declare function calculateStakingApy(baseRate: number, compoundingFrequency?: number): number;
|
||||
/**
|
||||
* Format credit amount for display
|
||||
* @param amount Amount in credits
|
||||
* @param decimals Decimal places
|
||||
*/
|
||||
export declare function formatCredits(amount: number, decimals?: number): string;
|
||||
//# sourceMappingURL=economy.d.ts.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.d.ts.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.d.ts.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"economy.d.ts","sourceRoot":"","sources":["economy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,eAAe,EACf,cAAc,EACd,aAAa,EACd,MAAM,SAAS,CAAC;AAMjB;;GAEG;AACH,MAAM,WAAW,aAAa;IAK5B;;;OAGG;IACH,aAAa,IAAI,MAAM,C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
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.js
vendored
Normal file
261
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.js
vendored
Normal file
@@ -0,0 +1,261 @@
|
||||
"use strict";
|
||||
/**
|
||||
* RuVector WASM Unified - Economy Engine
|
||||
*
|
||||
* Provides compute credit economy including:
|
||||
* - Credit balance management
|
||||
* - Contribution multipliers
|
||||
* - Staking mechanisms
|
||||
* - Transaction history
|
||||
* - Reward distribution
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createEconomyEngine = createEconomyEngine;
|
||||
exports.calculateStakingApy = calculateStakingApy;
|
||||
exports.formatCredits = formatCredits;
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
/**
|
||||
* Create an economy engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized economy engine
|
||||
*/
|
||||
function createEconomyEngine(config) {
|
||||
const defaultConfig = {
|
||||
initialBalance: 1000,
|
||||
stakingEnabled: true,
|
||||
rewardRate: 0.05,
|
||||
...config,
|
||||
};
|
||||
// Internal state
|
||||
let balance = defaultConfig.initialBalance;
|
||||
let stakedAmount = 0;
|
||||
let contributionMultiplier = 1.0;
|
||||
const transactions = [];
|
||||
const stakingPositions = [];
|
||||
const contributions = [];
|
||||
let pendingRewards = 0;
|
||||
let transactionIdCounter = 0;
|
||||
// Pricing table
|
||||
const pricingTable = new Map([
|
||||
['attention_scaled_dot', 0.001],
|
||||
['attention_multi_head', 0.005],
|
||||
['attention_flash', 0.003],
|
||||
['attention_moe', 0.01],
|
||||
['learning_lora', 0.02],
|
||||
['learning_btsp', 0.005],
|
||||
['nervous_step', 0.0001],
|
||||
['nervous_propagate', 0.001],
|
||||
['exotic_quantum', 0.05],
|
||||
['exotic_hyperbolic', 0.02],
|
||||
['storage_read', 0.0001],
|
||||
['storage_write', 0.0005],
|
||||
]);
|
||||
function createTransaction(type, amount, metadata) {
|
||||
const tx = {
|
||||
id: `tx_${transactionIdCounter++}`,
|
||||
type,
|
||||
amount,
|
||||
timestamp: Date.now(),
|
||||
metadata,
|
||||
};
|
||||
transactions.push(tx);
|
||||
return tx;
|
||||
}
|
||||
return {
|
||||
creditBalance: () => balance,
|
||||
contributionMultiplier: () => contributionMultiplier,
|
||||
getAccount: () => ({
|
||||
balance,
|
||||
stakedAmount,
|
||||
contributionMultiplier,
|
||||
lastUpdate: Date.now(),
|
||||
}),
|
||||
canAfford: (cost) => balance >= cost,
|
||||
stakeDeposit: (amount, lockDuration = 86400 * 30) => {
|
||||
if (amount > balance) {
|
||||
throw new Error('Insufficient balance for staking');
|
||||
}
|
||||
balance -= amount;
|
||||
stakedAmount += amount;
|
||||
const position = {
|
||||
amount,
|
||||
lockDuration,
|
||||
startTime: Date.now(),
|
||||
expectedReward: amount * defaultConfig.rewardRate * (lockDuration / (86400 * 365)),
|
||||
};
|
||||
stakingPositions.push(position);
|
||||
createTransaction('stake', amount);
|
||||
// Update multiplier based on staking
|
||||
contributionMultiplier = 1.0 + Math.log10(1 + stakedAmount / 1000) * 0.5;
|
||||
return position;
|
||||
},
|
||||
stakeWithdraw: (amount) => {
|
||||
if (amount > stakedAmount) {
|
||||
throw new Error('Insufficient staked amount');
|
||||
}
|
||||
stakedAmount -= amount;
|
||||
balance += amount;
|
||||
createTransaction('unstake', amount);
|
||||
contributionMultiplier = 1.0 + Math.log10(1 + stakedAmount / 1000) * 0.5;
|
||||
return amount;
|
||||
},
|
||||
getStakingPositions: () => [...stakingPositions],
|
||||
getTotalStaked: () => stakedAmount,
|
||||
estimateStakingReward: (amount, duration) => {
|
||||
return amount * defaultConfig.rewardRate * (duration / (86400 * 365));
|
||||
},
|
||||
transfer: (targetId, amount) => {
|
||||
if (amount > balance) {
|
||||
throw new Error('Insufficient balance for transfer');
|
||||
}
|
||||
balance -= amount;
|
||||
return createTransaction('withdraw', amount, { targetId });
|
||||
},
|
||||
deposit: (amount, source) => {
|
||||
balance += amount;
|
||||
return createTransaction('deposit', amount, { source });
|
||||
},
|
||||
withdraw: (amount, destination) => {
|
||||
if (amount > balance) {
|
||||
throw new Error('Insufficient balance for withdrawal');
|
||||
}
|
||||
balance -= amount;
|
||||
return createTransaction('withdraw', amount, { destination });
|
||||
},
|
||||
getTransactionHistory: (options) => {
|
||||
let result = [...transactions];
|
||||
if (options?.type) {
|
||||
result = result.filter(t => t.type === options.type);
|
||||
}
|
||||
if (options?.startTime) {
|
||||
result = result.filter(t => t.timestamp >= options.startTime);
|
||||
}
|
||||
if (options?.endTime) {
|
||||
result = result.filter(t => t.timestamp <= options.endTime);
|
||||
}
|
||||
if (options?.minAmount) {
|
||||
result = result.filter(t => t.amount >= options.minAmount);
|
||||
}
|
||||
if (options?.maxAmount) {
|
||||
result = result.filter(t => t.amount <= options.maxAmount);
|
||||
}
|
||||
if (options?.offset) {
|
||||
result = result.slice(options.offset);
|
||||
}
|
||||
if (options?.limit) {
|
||||
result = result.slice(0, options.limit);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
getTransaction: (transactionId) => {
|
||||
return transactions.find(t => t.id === transactionId);
|
||||
},
|
||||
claimRewards: () => {
|
||||
const claimed = pendingRewards;
|
||||
balance += claimed;
|
||||
pendingRewards = 0;
|
||||
if (claimed > 0) {
|
||||
createTransaction('reward', claimed);
|
||||
}
|
||||
return claimed;
|
||||
},
|
||||
getPendingRewards: () => pendingRewards,
|
||||
recordContribution: (contributionType, value) => {
|
||||
const reward = value * 0.1 * contributionMultiplier;
|
||||
contributions.push({
|
||||
type: contributionType,
|
||||
value,
|
||||
timestamp: Date.now(),
|
||||
rewardEarned: reward,
|
||||
});
|
||||
pendingRewards += reward;
|
||||
},
|
||||
getContributions: (startTime, endTime) => {
|
||||
let result = [...contributions];
|
||||
if (startTime) {
|
||||
result = result.filter(c => c.timestamp >= startTime);
|
||||
}
|
||||
if (endTime) {
|
||||
result = result.filter(c => c.timestamp <= endTime);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
getCost: (operation, params) => {
|
||||
const baseCost = pricingTable.get(operation) ?? 0;
|
||||
// Apply multiplier discount
|
||||
return baseCost / contributionMultiplier;
|
||||
},
|
||||
spend: (operation, params) => {
|
||||
const cost = pricingTable.get(operation) ?? 0;
|
||||
const adjustedCost = cost / contributionMultiplier;
|
||||
if (adjustedCost > balance) {
|
||||
throw new Error(`Insufficient balance for ${operation}`);
|
||||
}
|
||||
balance -= adjustedCost;
|
||||
return createTransaction('withdraw', adjustedCost, { operation, params });
|
||||
},
|
||||
getPricingTable: () => new Map(pricingTable),
|
||||
getMetrics: () => ({
|
||||
totalSupply: 1000000,
|
||||
totalStaked: stakedAmount,
|
||||
circulatingSupply: 1000000 - stakedAmount,
|
||||
averageMultiplier: contributionMultiplier,
|
||||
}),
|
||||
getAnalytics: (period = 'week') => {
|
||||
const periodMs = {
|
||||
day: 86400000,
|
||||
week: 604800000,
|
||||
month: 2592000000,
|
||||
}[period];
|
||||
const startTime = Date.now() - periodMs;
|
||||
const periodTx = transactions.filter(t => t.timestamp >= startTime);
|
||||
const spent = periodTx
|
||||
.filter(t => t.type === 'withdraw')
|
||||
.reduce((sum, t) => sum + t.amount, 0);
|
||||
const earned = periodTx
|
||||
.filter(t => t.type === 'deposit' || t.type === 'reward')
|
||||
.reduce((sum, t) => sum + t.amount, 0);
|
||||
return {
|
||||
period,
|
||||
totalSpent: spent,
|
||||
totalEarned: earned,
|
||||
netFlow: earned - spent,
|
||||
topOperations: [],
|
||||
stakingYield: defaultConfig.rewardRate * 100,
|
||||
multiplierHistory: [],
|
||||
};
|
||||
},
|
||||
getLeaderboard: (metric, limit = 10) => {
|
||||
// Placeholder - would connect to global state
|
||||
return [];
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Calculate APY for staking
|
||||
* @param baseRate Base reward rate
|
||||
* @param compoundingFrequency Annual compounding frequency
|
||||
*/
|
||||
function calculateStakingApy(baseRate, compoundingFrequency = 365) {
|
||||
return Math.pow(1 + baseRate / compoundingFrequency, compoundingFrequency) - 1;
|
||||
}
|
||||
/**
|
||||
* Format credit amount for display
|
||||
* @param amount Amount in credits
|
||||
* @param decimals Decimal places
|
||||
*/
|
||||
function formatCredits(amount, decimals = 4) {
|
||||
if (amount >= 1e9) {
|
||||
return `${(amount / 1e9).toFixed(2)}B`;
|
||||
}
|
||||
if (amount >= 1e6) {
|
||||
return `${(amount / 1e6).toFixed(2)}M`;
|
||||
}
|
||||
if (amount >= 1e3) {
|
||||
return `${(amount / 1e3).toFixed(2)}K`;
|
||||
}
|
||||
return amount.toFixed(decimals);
|
||||
}
|
||||
//# sourceMappingURL=economy.js.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.js.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
553
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.ts
vendored
Normal file
553
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/economy.ts
vendored
Normal file
@@ -0,0 +1,553 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Economy Engine
|
||||
*
|
||||
* Provides compute credit economy including:
|
||||
* - Credit balance management
|
||||
* - Contribution multipliers
|
||||
* - Staking mechanisms
|
||||
* - Transaction history
|
||||
* - Reward distribution
|
||||
*/
|
||||
|
||||
import type {
|
||||
CreditAccount,
|
||||
Transaction,
|
||||
StakingPosition,
|
||||
EconomyMetrics,
|
||||
EconomyConfig,
|
||||
} from './types';
|
||||
|
||||
// ============================================================================
|
||||
// Economy Engine Interface
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Core economy engine for compute credit management
|
||||
*/
|
||||
export interface EconomyEngine {
|
||||
// -------------------------------------------------------------------------
|
||||
// Account Management
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get current credit balance
|
||||
* @returns Current balance in credits
|
||||
*/
|
||||
creditBalance(): number;
|
||||
|
||||
/**
|
||||
* Get contribution multiplier
|
||||
* Based on staking, history, and activity
|
||||
* @returns Multiplier value (1.0 = base rate)
|
||||
*/
|
||||
contributionMultiplier(): number;
|
||||
|
||||
/**
|
||||
* Get full account state
|
||||
* @returns Complete credit account information
|
||||
*/
|
||||
getAccount(): CreditAccount;
|
||||
|
||||
/**
|
||||
* Check if account can afford operation
|
||||
* @param cost Operation cost
|
||||
* @returns Whether balance is sufficient
|
||||
*/
|
||||
canAfford(cost: number): boolean;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Staking Operations
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Deposit credits into staking
|
||||
* @param amount Amount to stake
|
||||
* @param lockDuration Optional lock duration in seconds
|
||||
* @returns Staking position
|
||||
*/
|
||||
stakeDeposit(amount: number, lockDuration?: number): StakingPosition;
|
||||
|
||||
/**
|
||||
* Withdraw from staking
|
||||
* @param amount Amount to withdraw
|
||||
* @returns Withdrawn amount (may include penalties)
|
||||
*/
|
||||
stakeWithdraw(amount: number): number;
|
||||
|
||||
/**
|
||||
* Get current staking positions
|
||||
* @returns Array of staking positions
|
||||
*/
|
||||
getStakingPositions(): StakingPosition[];
|
||||
|
||||
/**
|
||||
* Get total staked amount
|
||||
* @returns Total credits staked
|
||||
*/
|
||||
getTotalStaked(): number;
|
||||
|
||||
/**
|
||||
* Estimate staking rewards
|
||||
* @param amount Amount to stake
|
||||
* @param duration Duration in seconds
|
||||
* @returns Estimated reward
|
||||
*/
|
||||
estimateStakingReward(amount: number, duration: number): number;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Transactions
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Transfer credits to another account
|
||||
* @param targetId Target account ID
|
||||
* @param amount Amount to transfer
|
||||
* @returns Transaction record
|
||||
*/
|
||||
transfer(targetId: string, amount: number): Transaction;
|
||||
|
||||
/**
|
||||
* Deposit credits from external source
|
||||
* @param amount Amount to deposit
|
||||
* @param source Source identifier
|
||||
* @returns Transaction record
|
||||
*/
|
||||
deposit(amount: number, source?: string): Transaction;
|
||||
|
||||
/**
|
||||
* Withdraw credits to external destination
|
||||
* @param amount Amount to withdraw
|
||||
* @param destination Destination identifier
|
||||
* @returns Transaction record
|
||||
*/
|
||||
withdraw(amount: number, destination?: string): Transaction;
|
||||
|
||||
/**
|
||||
* Get transaction history
|
||||
* @param options Filter options
|
||||
* @returns Array of transactions
|
||||
*/
|
||||
getTransactionHistory(options?: TransactionFilter): Transaction[];
|
||||
|
||||
/**
|
||||
* Get transaction by ID
|
||||
* @param transactionId Transaction ID
|
||||
* @returns Transaction or undefined
|
||||
*/
|
||||
getTransaction(transactionId: string): Transaction | undefined;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Rewards & Penalties
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Claim pending rewards
|
||||
* @returns Amount claimed
|
||||
*/
|
||||
claimRewards(): number;
|
||||
|
||||
/**
|
||||
* Get pending rewards
|
||||
* @returns Amount of unclaimed rewards
|
||||
*/
|
||||
getPendingRewards(): number;
|
||||
|
||||
/**
|
||||
* Record contribution for rewards
|
||||
* @param contributionType Type of contribution
|
||||
* @param value Contribution value
|
||||
*/
|
||||
recordContribution(contributionType: ContributionType, value: number): void;
|
||||
|
||||
/**
|
||||
* Get contribution history
|
||||
* @param startTime Start of period
|
||||
* @param endTime End of period
|
||||
* @returns Contribution records
|
||||
*/
|
||||
getContributions(startTime?: number, endTime?: number): ContributionRecord[];
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Pricing & Costs
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get cost for operation type
|
||||
* @param operation Operation identifier
|
||||
* @param params Operation parameters
|
||||
* @returns Cost in credits
|
||||
*/
|
||||
getCost(operation: OperationType, params?: Record<string, unknown>): number;
|
||||
|
||||
/**
|
||||
* Spend credits for operation
|
||||
* @param operation Operation type
|
||||
* @param params Operation parameters
|
||||
* @returns Transaction record
|
||||
*/
|
||||
spend(operation: OperationType, params?: Record<string, unknown>): Transaction;
|
||||
|
||||
/**
|
||||
* Get pricing table
|
||||
* @returns Map of operations to base costs
|
||||
*/
|
||||
getPricingTable(): Map<OperationType, number>;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Metrics & Analytics
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get economy-wide metrics
|
||||
* @returns Global economy metrics
|
||||
*/
|
||||
getMetrics(): EconomyMetrics;
|
||||
|
||||
/**
|
||||
* Get account analytics
|
||||
* @param period Time period
|
||||
* @returns Account analytics
|
||||
*/
|
||||
getAnalytics(period?: 'day' | 'week' | 'month'): AccountAnalytics;
|
||||
|
||||
/**
|
||||
* Get leaderboard
|
||||
* @param metric Ranking metric
|
||||
* @param limit Number of entries
|
||||
* @returns Leaderboard entries
|
||||
*/
|
||||
getLeaderboard(metric: LeaderboardMetric, limit?: number): LeaderboardEntry[];
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Supporting Types
|
||||
// ============================================================================
|
||||
|
||||
/** Transaction filter options */
|
||||
export interface TransactionFilter {
|
||||
type?: Transaction['type'];
|
||||
startTime?: number;
|
||||
endTime?: number;
|
||||
minAmount?: number;
|
||||
maxAmount?: number;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
/** Contribution type */
|
||||
export type ContributionType =
|
||||
| 'compute'
|
||||
| 'storage'
|
||||
| 'bandwidth'
|
||||
| 'validation'
|
||||
| 'training'
|
||||
| 'inference';
|
||||
|
||||
/** Contribution record */
|
||||
export interface ContributionRecord {
|
||||
type: ContributionType;
|
||||
value: number;
|
||||
timestamp: number;
|
||||
rewardEarned: number;
|
||||
}
|
||||
|
||||
/** Operation type for pricing */
|
||||
export type OperationType =
|
||||
| 'attention_scaled_dot'
|
||||
| 'attention_multi_head'
|
||||
| 'attention_flash'
|
||||
| 'attention_moe'
|
||||
| 'learning_lora'
|
||||
| 'learning_btsp'
|
||||
| 'nervous_step'
|
||||
| 'nervous_propagate'
|
||||
| 'exotic_quantum'
|
||||
| 'exotic_hyperbolic'
|
||||
| 'storage_read'
|
||||
| 'storage_write';
|
||||
|
||||
/** Account analytics */
|
||||
export interface AccountAnalytics {
|
||||
period: string;
|
||||
totalSpent: number;
|
||||
totalEarned: number;
|
||||
netFlow: number;
|
||||
topOperations: { operation: OperationType; count: number; cost: number }[];
|
||||
stakingYield: number;
|
||||
multiplierHistory: { time: number; value: number }[];
|
||||
}
|
||||
|
||||
/** Leaderboard metric */
|
||||
export type LeaderboardMetric =
|
||||
| 'total_staked'
|
||||
| 'contributions'
|
||||
| 'compute_usage'
|
||||
| 'rewards_earned';
|
||||
|
||||
/** Leaderboard entry */
|
||||
export interface LeaderboardEntry {
|
||||
rank: number;
|
||||
accountId: string;
|
||||
value: number;
|
||||
change: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Create an economy engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized economy engine
|
||||
*/
|
||||
export function createEconomyEngine(config?: EconomyConfig): EconomyEngine {
|
||||
const defaultConfig: EconomyConfig = {
|
||||
initialBalance: 1000,
|
||||
stakingEnabled: true,
|
||||
rewardRate: 0.05,
|
||||
...config,
|
||||
};
|
||||
|
||||
// Internal state
|
||||
let balance = defaultConfig.initialBalance!;
|
||||
let stakedAmount = 0;
|
||||
let contributionMultiplier = 1.0;
|
||||
const transactions: Transaction[] = [];
|
||||
const stakingPositions: StakingPosition[] = [];
|
||||
const contributions: ContributionRecord[] = [];
|
||||
let pendingRewards = 0;
|
||||
let transactionIdCounter = 0;
|
||||
|
||||
// Pricing table
|
||||
const pricingTable = new Map<OperationType, number>([
|
||||
['attention_scaled_dot', 0.001],
|
||||
['attention_multi_head', 0.005],
|
||||
['attention_flash', 0.003],
|
||||
['attention_moe', 0.01],
|
||||
['learning_lora', 0.02],
|
||||
['learning_btsp', 0.005],
|
||||
['nervous_step', 0.0001],
|
||||
['nervous_propagate', 0.001],
|
||||
['exotic_quantum', 0.05],
|
||||
['exotic_hyperbolic', 0.02],
|
||||
['storage_read', 0.0001],
|
||||
['storage_write', 0.0005],
|
||||
]);
|
||||
|
||||
function createTransaction(
|
||||
type: Transaction['type'],
|
||||
amount: number,
|
||||
metadata?: Record<string, unknown>
|
||||
): Transaction {
|
||||
const tx: Transaction = {
|
||||
id: `tx_${transactionIdCounter++}`,
|
||||
type,
|
||||
amount,
|
||||
timestamp: Date.now(),
|
||||
metadata,
|
||||
};
|
||||
transactions.push(tx);
|
||||
return tx;
|
||||
}
|
||||
|
||||
return {
|
||||
creditBalance: () => balance,
|
||||
contributionMultiplier: () => contributionMultiplier,
|
||||
getAccount: () => ({
|
||||
balance,
|
||||
stakedAmount,
|
||||
contributionMultiplier,
|
||||
lastUpdate: Date.now(),
|
||||
}),
|
||||
canAfford: (cost) => balance >= cost,
|
||||
stakeDeposit: (amount, lockDuration = 86400 * 30) => {
|
||||
if (amount > balance) {
|
||||
throw new Error('Insufficient balance for staking');
|
||||
}
|
||||
balance -= amount;
|
||||
stakedAmount += amount;
|
||||
const position: StakingPosition = {
|
||||
amount,
|
||||
lockDuration,
|
||||
startTime: Date.now(),
|
||||
expectedReward: amount * defaultConfig.rewardRate! * (lockDuration / (86400 * 365)),
|
||||
};
|
||||
stakingPositions.push(position);
|
||||
createTransaction('stake', amount);
|
||||
// Update multiplier based on staking
|
||||
contributionMultiplier = 1.0 + Math.log10(1 + stakedAmount / 1000) * 0.5;
|
||||
return position;
|
||||
},
|
||||
stakeWithdraw: (amount) => {
|
||||
if (amount > stakedAmount) {
|
||||
throw new Error('Insufficient staked amount');
|
||||
}
|
||||
stakedAmount -= amount;
|
||||
balance += amount;
|
||||
createTransaction('unstake', amount);
|
||||
contributionMultiplier = 1.0 + Math.log10(1 + stakedAmount / 1000) * 0.5;
|
||||
return amount;
|
||||
},
|
||||
getStakingPositions: () => [...stakingPositions],
|
||||
getTotalStaked: () => stakedAmount,
|
||||
estimateStakingReward: (amount, duration) => {
|
||||
return amount * defaultConfig.rewardRate! * (duration / (86400 * 365));
|
||||
},
|
||||
transfer: (targetId, amount) => {
|
||||
if (amount > balance) {
|
||||
throw new Error('Insufficient balance for transfer');
|
||||
}
|
||||
balance -= amount;
|
||||
return createTransaction('withdraw', amount, { targetId });
|
||||
},
|
||||
deposit: (amount, source) => {
|
||||
balance += amount;
|
||||
return createTransaction('deposit', amount, { source });
|
||||
},
|
||||
withdraw: (amount, destination) => {
|
||||
if (amount > balance) {
|
||||
throw new Error('Insufficient balance for withdrawal');
|
||||
}
|
||||
balance -= amount;
|
||||
return createTransaction('withdraw', amount, { destination });
|
||||
},
|
||||
getTransactionHistory: (options) => {
|
||||
let result = [...transactions];
|
||||
if (options?.type) {
|
||||
result = result.filter(t => t.type === options.type);
|
||||
}
|
||||
if (options?.startTime) {
|
||||
result = result.filter(t => t.timestamp >= options.startTime!);
|
||||
}
|
||||
if (options?.endTime) {
|
||||
result = result.filter(t => t.timestamp <= options.endTime!);
|
||||
}
|
||||
if (options?.minAmount) {
|
||||
result = result.filter(t => t.amount >= options.minAmount!);
|
||||
}
|
||||
if (options?.maxAmount) {
|
||||
result = result.filter(t => t.amount <= options.maxAmount!);
|
||||
}
|
||||
if (options?.offset) {
|
||||
result = result.slice(options.offset);
|
||||
}
|
||||
if (options?.limit) {
|
||||
result = result.slice(0, options.limit);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
getTransaction: (transactionId) => {
|
||||
return transactions.find(t => t.id === transactionId);
|
||||
},
|
||||
claimRewards: () => {
|
||||
const claimed = pendingRewards;
|
||||
balance += claimed;
|
||||
pendingRewards = 0;
|
||||
if (claimed > 0) {
|
||||
createTransaction('reward', claimed);
|
||||
}
|
||||
return claimed;
|
||||
},
|
||||
getPendingRewards: () => pendingRewards,
|
||||
recordContribution: (contributionType, value) => {
|
||||
const reward = value * 0.1 * contributionMultiplier;
|
||||
contributions.push({
|
||||
type: contributionType,
|
||||
value,
|
||||
timestamp: Date.now(),
|
||||
rewardEarned: reward,
|
||||
});
|
||||
pendingRewards += reward;
|
||||
},
|
||||
getContributions: (startTime, endTime) => {
|
||||
let result = [...contributions];
|
||||
if (startTime) {
|
||||
result = result.filter(c => c.timestamp >= startTime);
|
||||
}
|
||||
if (endTime) {
|
||||
result = result.filter(c => c.timestamp <= endTime);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
getCost: (operation, params) => {
|
||||
const baseCost = pricingTable.get(operation) ?? 0;
|
||||
// Apply multiplier discount
|
||||
return baseCost / contributionMultiplier;
|
||||
},
|
||||
spend: (operation, params) => {
|
||||
const cost = pricingTable.get(operation) ?? 0;
|
||||
const adjustedCost = cost / contributionMultiplier;
|
||||
if (adjustedCost > balance) {
|
||||
throw new Error(`Insufficient balance for ${operation}`);
|
||||
}
|
||||
balance -= adjustedCost;
|
||||
return createTransaction('withdraw', adjustedCost, { operation, params });
|
||||
},
|
||||
getPricingTable: () => new Map(pricingTable),
|
||||
getMetrics: () => ({
|
||||
totalSupply: 1000000,
|
||||
totalStaked: stakedAmount,
|
||||
circulatingSupply: 1000000 - stakedAmount,
|
||||
averageMultiplier: contributionMultiplier,
|
||||
}),
|
||||
getAnalytics: (period = 'week') => {
|
||||
const periodMs = {
|
||||
day: 86400000,
|
||||
week: 604800000,
|
||||
month: 2592000000,
|
||||
}[period];
|
||||
const startTime = Date.now() - periodMs;
|
||||
const periodTx = transactions.filter(t => t.timestamp >= startTime);
|
||||
const spent = periodTx
|
||||
.filter(t => t.type === 'withdraw')
|
||||
.reduce((sum, t) => sum + t.amount, 0);
|
||||
const earned = periodTx
|
||||
.filter(t => t.type === 'deposit' || t.type === 'reward')
|
||||
.reduce((sum, t) => sum + t.amount, 0);
|
||||
return {
|
||||
period,
|
||||
totalSpent: spent,
|
||||
totalEarned: earned,
|
||||
netFlow: earned - spent,
|
||||
topOperations: [],
|
||||
stakingYield: defaultConfig.rewardRate! * 100,
|
||||
multiplierHistory: [],
|
||||
};
|
||||
},
|
||||
getLeaderboard: (metric, limit = 10) => {
|
||||
// Placeholder - would connect to global state
|
||||
return [];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate APY for staking
|
||||
* @param baseRate Base reward rate
|
||||
* @param compoundingFrequency Annual compounding frequency
|
||||
*/
|
||||
export function calculateStakingApy(
|
||||
baseRate: number,
|
||||
compoundingFrequency: number = 365
|
||||
): number {
|
||||
return Math.pow(1 + baseRate / compoundingFrequency, compoundingFrequency) - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format credit amount for display
|
||||
* @param amount Amount in credits
|
||||
* @param decimals Decimal places
|
||||
*/
|
||||
export function formatCredits(amount: number, decimals: number = 4): string {
|
||||
if (amount >= 1e9) {
|
||||
return `${(amount / 1e9).toFixed(2)}B`;
|
||||
}
|
||||
if (amount >= 1e6) {
|
||||
return `${(amount / 1e6).toFixed(2)}M`;
|
||||
}
|
||||
if (amount >= 1e3) {
|
||||
return `${(amount / 1e3).toFixed(2)}K`;
|
||||
}
|
||||
return amount.toFixed(decimals);
|
||||
}
|
||||
327
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.d.ts
vendored
Normal file
327
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.d.ts
vendored
Normal file
@@ -0,0 +1,327 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Exotic Computation Engine
|
||||
*
|
||||
* Provides advanced computation paradigms including:
|
||||
* - Quantum-inspired algorithms (superposition, entanglement, interference)
|
||||
* - Hyperbolic geometry operations (Poincare, Lorentz, Klein models)
|
||||
* - Topological data analysis (persistent homology, Betti numbers)
|
||||
* - Fractal and chaos-based computation
|
||||
* - Non-Euclidean neural operations
|
||||
*/
|
||||
import type { QuantumState, HyperbolicPoint, TopologicalFeature, ExoticConfig } from './types';
|
||||
/**
|
||||
* Core exotic computation engine for advanced algorithmic paradigms
|
||||
*/
|
||||
export interface ExoticEngine {
|
||||
/**
|
||||
* Initialize quantum-inspired state
|
||||
* @param numQubits Number of qubits to simulate
|
||||
* @returns Initial quantum state
|
||||
*/
|
||||
quantumInit(numQubits: number): QuantumState;
|
||||
/**
|
||||
* Apply Hadamard gate for superposition
|
||||
* @param state Current quantum state
|
||||
* @param qubit Target qubit index
|
||||
* @returns New quantum state
|
||||
*/
|
||||
quantumHadamard(state: QuantumState, qubit: number): QuantumState;
|
||||
/**
|
||||
* Apply CNOT gate for entanglement
|
||||
* @param state Current quantum state
|
||||
* @param control Control qubit
|
||||
* @param target Target qubit
|
||||
* @returns Entangled quantum state
|
||||
*/
|
||||
quantumCnot(state: QuantumState, control: number, target: number): QuantumState;
|
||||
/**
|
||||
* Apply phase rotation gate
|
||||
* @param state Current quantum state
|
||||
* @param qubit Target qubit
|
||||
* @param phase Phase angle in radians
|
||||
* @returns Rotated quantum state
|
||||
*/
|
||||
quantumPhase(state: QuantumState, qubit: number, phase: number): QuantumState;
|
||||
/**
|
||||
* Measure quantum state
|
||||
* @param state Quantum state to measure
|
||||
* @param qubits Qubits to measure (empty = all)
|
||||
* @returns Measurement result and collapsed state
|
||||
*/
|
||||
quantumMeasure(state: QuantumState, qubits?: number[]): QuantumMeasurement;
|
||||
/**
|
||||
* Quantum amplitude amplification (Grover-like)
|
||||
* @param state Initial state
|
||||
* @param oracle Oracle function marking solutions
|
||||
* @param iterations Number of amplification iterations
|
||||
* @returns Amplified state
|
||||
*/
|
||||
quantumAmplify(state: QuantumState, oracle: (amplitudes: Float32Array) => Float32Array, iterations?: number): QuantumState;
|
||||
/**
|
||||
* Variational quantum eigensolver simulation
|
||||
* @param hamiltonian Hamiltonian matrix
|
||||
* @param ansatz Variational ansatz circuit
|
||||
* @param optimizer Optimizer type
|
||||
* @returns Ground state energy estimate
|
||||
*/
|
||||
quantumVqe(hamiltonian: Float32Array, ansatz?: QuantumCircuit, optimizer?: 'cobyla' | 'spsa' | 'adam'): VqeResult;
|
||||
/**
|
||||
* Create point in hyperbolic space
|
||||
* @param coordinates Euclidean coordinates
|
||||
* @param manifold Target manifold model
|
||||
* @param curvature Negative curvature value
|
||||
* @returns Hyperbolic point
|
||||
*/
|
||||
hyperbolicPoint(coordinates: Float32Array, manifold?: 'poincare' | 'lorentz' | 'klein', curvature?: number): HyperbolicPoint;
|
||||
/**
|
||||
* Compute hyperbolic distance
|
||||
* @param p1 First point
|
||||
* @param p2 Second point
|
||||
* @returns Hyperbolic distance
|
||||
*/
|
||||
hyperbolicDistance(p1: HyperbolicPoint, p2: HyperbolicPoint): number;
|
||||
/**
|
||||
* Mobius addition in Poincare ball
|
||||
* @param x First point
|
||||
* @param y Second point
|
||||
* @param c Curvature parameter
|
||||
* @returns Sum in hyperbolic space
|
||||
*/
|
||||
mobiusAdd(x: HyperbolicPoint, y: HyperbolicPoint, c?: number): HyperbolicPoint;
|
||||
/**
|
||||
* Mobius matrix-vector multiplication
|
||||
* @param M Matrix
|
||||
* @param x Point
|
||||
* @param c Curvature parameter
|
||||
* @returns Transformed point
|
||||
*/
|
||||
mobiusMatvec(M: Float32Array, x: HyperbolicPoint, c?: number): HyperbolicPoint;
|
||||
/**
|
||||
* Exponential map (tangent space to hyperbolic)
|
||||
* @param v Tangent vector
|
||||
* @param base Base point
|
||||
* @returns Point in hyperbolic space
|
||||
*/
|
||||
hyperbolicExp(v: Float32Array, base?: HyperbolicPoint): HyperbolicPoint;
|
||||
/**
|
||||
* Logarithmic map (hyperbolic to tangent space)
|
||||
* @param y Target point
|
||||
* @param base Base point
|
||||
* @returns Tangent vector
|
||||
*/
|
||||
hyperbolicLog(y: HyperbolicPoint, base?: HyperbolicPoint): Float32Array;
|
||||
/**
|
||||
* Parallel transport in hyperbolic space
|
||||
* @param v Tangent vector
|
||||
* @param from Source point
|
||||
* @param to Target point
|
||||
* @returns Transported vector
|
||||
*/
|
||||
hyperbolicTransport(v: Float32Array, from: HyperbolicPoint, to: HyperbolicPoint): Float32Array;
|
||||
/**
|
||||
* Hyperbolic centroid (Frechet mean)
|
||||
* @param points Points to average
|
||||
* @param weights Optional weights
|
||||
* @returns Centroid in hyperbolic space
|
||||
*/
|
||||
hyperbolicCentroid(points: HyperbolicPoint[], weights?: Float32Array): HyperbolicPoint;
|
||||
/**
|
||||
* Compute persistent homology
|
||||
* @param data Point cloud data
|
||||
* @param maxDimension Maximum homology dimension
|
||||
* @param threshold Filtration threshold
|
||||
* @returns Topological features
|
||||
*/
|
||||
persistentHomology(data: Float32Array[], maxDimension?: number, threshold?: number): TopologicalFeature[];
|
||||
/**
|
||||
* Compute Betti numbers
|
||||
* @param features Topological features from persistent homology
|
||||
* @param threshold Persistence threshold
|
||||
* @returns Betti numbers by dimension
|
||||
*/
|
||||
bettiNumbers(features: TopologicalFeature[], threshold?: number): number[];
|
||||
/**
|
||||
* Generate persistence diagram
|
||||
* @param features Topological features
|
||||
* @returns Birth-death pairs for visualization
|
||||
*/
|
||||
persistenceDiagram(features: TopologicalFeature[]): PersistencePair[];
|
||||
/**
|
||||
* Compute bottleneck distance between persistence diagrams
|
||||
* @param diagram1 First persistence diagram
|
||||
* @param diagram2 Second persistence diagram
|
||||
* @returns Bottleneck distance
|
||||
*/
|
||||
bottleneckDistance(diagram1: PersistencePair[], diagram2: PersistencePair[]): number;
|
||||
/**
|
||||
* Compute Wasserstein distance between persistence diagrams
|
||||
* @param diagram1 First persistence diagram
|
||||
* @param diagram2 Second persistence diagram
|
||||
* @param p Order of Wasserstein distance
|
||||
* @returns Wasserstein distance
|
||||
*/
|
||||
wassersteinDistance(diagram1: PersistencePair[], diagram2: PersistencePair[], p?: number): number;
|
||||
/**
|
||||
* Mapper algorithm for topological visualization
|
||||
* @param data Input data
|
||||
* @param lens Lens function
|
||||
* @param numBins Number of bins per dimension
|
||||
* @param overlap Overlap between bins
|
||||
* @returns Mapper graph
|
||||
*/
|
||||
mapper(data: Float32Array[], lens?: (point: Float32Array) => number[], numBins?: number, overlap?: number): MapperGraph;
|
||||
/**
|
||||
* Compute fractal dimension (box-counting)
|
||||
* @param data Point cloud or image data
|
||||
* @returns Estimated fractal dimension
|
||||
*/
|
||||
fractalDimension(data: Float32Array[]): number;
|
||||
/**
|
||||
* Generate Mandelbrot/Julia set embedding
|
||||
* @param c Julia set constant (undefined for Mandelbrot)
|
||||
* @param resolution Grid resolution
|
||||
* @param maxIterations Maximum iterations
|
||||
* @returns Escape time embedding
|
||||
*/
|
||||
fractalEmbedding(c?: {
|
||||
re: number;
|
||||
im: number;
|
||||
}, resolution?: number, maxIterations?: number): Float32Array;
|
||||
/**
|
||||
* Compute Lyapunov exponents for chaotic dynamics
|
||||
* @param trajectory Time series trajectory
|
||||
* @param embeddingDim Embedding dimension
|
||||
* @param delay Time delay
|
||||
* @returns Lyapunov exponents
|
||||
*/
|
||||
lyapunovExponents(trajectory: Float32Array, embeddingDim?: number, delay?: number): Float32Array;
|
||||
/**
|
||||
* Recurrence plot analysis
|
||||
* @param trajectory Time series
|
||||
* @param threshold Recurrence threshold
|
||||
* @returns Recurrence plot matrix
|
||||
*/
|
||||
recurrencePlot(trajectory: Float32Array, threshold?: number): Uint8Array;
|
||||
/**
|
||||
* Hyperbolic neural network layer forward pass
|
||||
* @param input Input in hyperbolic space
|
||||
* @param weights Weight matrix
|
||||
* @param bias Bias vector
|
||||
* @returns Output in hyperbolic space
|
||||
*/
|
||||
hyperbolicLayer(input: HyperbolicPoint[], weights: Float32Array, bias?: Float32Array): HyperbolicPoint[];
|
||||
/**
|
||||
* Spherical neural network layer (on n-sphere)
|
||||
* @param input Input on sphere
|
||||
* @param weights Weight matrix
|
||||
* @returns Output on sphere
|
||||
*/
|
||||
sphericalLayer(input: Float32Array[], weights: Float32Array): Float32Array[];
|
||||
/**
|
||||
* Mixed-curvature neural network
|
||||
* @param input Input embeddings
|
||||
* @param curvatures Curvature for each dimension
|
||||
* @param weights Weight matrices
|
||||
* @returns Output in product manifold
|
||||
*/
|
||||
productManifoldLayer(input: Float32Array[], curvatures: Float32Array, weights: Float32Array[]): Float32Array[];
|
||||
/**
|
||||
* Get exotic computation statistics
|
||||
* @returns Resource usage and statistics
|
||||
*/
|
||||
getStats(): ExoticStats;
|
||||
/**
|
||||
* Configure exotic engine
|
||||
* @param config Configuration options
|
||||
*/
|
||||
configure(config: Partial<ExoticConfig>): void;
|
||||
}
|
||||
/** Quantum measurement result */
|
||||
export interface QuantumMeasurement {
|
||||
bitstring: number[];
|
||||
probability: number;
|
||||
collapsedState: QuantumState;
|
||||
}
|
||||
/** Quantum circuit representation */
|
||||
export interface QuantumCircuit {
|
||||
numQubits: number;
|
||||
gates: QuantumGate[];
|
||||
parameters?: Float32Array;
|
||||
}
|
||||
/** Quantum gate */
|
||||
export interface QuantumGate {
|
||||
type: 'H' | 'X' | 'Y' | 'Z' | 'CNOT' | 'RX' | 'RY' | 'RZ' | 'CZ' | 'SWAP';
|
||||
targets: number[];
|
||||
parameter?: number;
|
||||
}
|
||||
/** VQE result */
|
||||
export interface VqeResult {
|
||||
energy: number;
|
||||
optimalParameters: Float32Array;
|
||||
iterations: number;
|
||||
converged: boolean;
|
||||
}
|
||||
/** Persistence pair for diagrams */
|
||||
export interface PersistencePair {
|
||||
birth: number;
|
||||
death: number;
|
||||
dimension: number;
|
||||
}
|
||||
/** Mapper graph structure */
|
||||
export interface MapperGraph {
|
||||
nodes: MapperNode[];
|
||||
edges: MapperEdge[];
|
||||
}
|
||||
/** Mapper node */
|
||||
export interface MapperNode {
|
||||
id: string;
|
||||
members: number[];
|
||||
centroid: Float32Array;
|
||||
}
|
||||
/** Mapper edge */
|
||||
export interface MapperEdge {
|
||||
source: string;
|
||||
target: string;
|
||||
weight: number;
|
||||
}
|
||||
/** Exotic engine statistics */
|
||||
export interface ExoticStats {
|
||||
quantumOperations: number;
|
||||
hyperbolicOperations: number;
|
||||
topologicalOperations: number;
|
||||
totalComputeTimeMs: number;
|
||||
peakMemoryBytes: number;
|
||||
}
|
||||
/**
|
||||
* Create an exotic computation engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized exotic engine
|
||||
*/
|
||||
export declare function createExoticEngine(config?: ExoticConfig): ExoticEngine;
|
||||
/**
|
||||
* Create quantum circuit builder
|
||||
* @param numQubits Number of qubits
|
||||
* @returns Circuit builder
|
||||
*/
|
||||
export declare function createCircuitBuilder(numQubits: number): {
|
||||
h: (qubit: number) => void;
|
||||
x: (qubit: number) => void;
|
||||
cnot: (control: number, target: number) => void;
|
||||
rx: (qubit: number, angle: number) => void;
|
||||
ry: (qubit: number, angle: number) => void;
|
||||
rz: (qubit: number, angle: number) => void;
|
||||
build: () => QuantumCircuit;
|
||||
};
|
||||
/**
|
||||
* Utility: Project from Euclidean to Poincare ball
|
||||
* @param x Euclidean coordinates
|
||||
* @param c Curvature parameter
|
||||
*/
|
||||
export declare function projectToPoincare(x: Float32Array, c?: number): Float32Array;
|
||||
/**
|
||||
* Utility: Project from Poincare to Lorentz model
|
||||
* @param x Poincare coordinates
|
||||
* @param c Curvature parameter
|
||||
*/
|
||||
export declare function poincareToLorentz(x: Float32Array, c?: number): Float32Array;
|
||||
//# sourceMappingURL=exotic.d.ts.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.d.ts.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.d.ts.map
vendored
Normal file
File diff suppressed because one or more lines are too long
262
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.js
vendored
Normal file
262
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.js
vendored
Normal file
@@ -0,0 +1,262 @@
|
||||
"use strict";
|
||||
/**
|
||||
* RuVector WASM Unified - Exotic Computation Engine
|
||||
*
|
||||
* Provides advanced computation paradigms including:
|
||||
* - Quantum-inspired algorithms (superposition, entanglement, interference)
|
||||
* - Hyperbolic geometry operations (Poincare, Lorentz, Klein models)
|
||||
* - Topological data analysis (persistent homology, Betti numbers)
|
||||
* - Fractal and chaos-based computation
|
||||
* - Non-Euclidean neural operations
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createExoticEngine = createExoticEngine;
|
||||
exports.createCircuitBuilder = createCircuitBuilder;
|
||||
exports.projectToPoincare = projectToPoincare;
|
||||
exports.poincareToLorentz = poincareToLorentz;
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
/**
|
||||
* Create an exotic computation engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized exotic engine
|
||||
*/
|
||||
function createExoticEngine(config) {
|
||||
const defaultConfig = {
|
||||
quantumSimulationDepth: 10,
|
||||
hyperbolicPrecision: 1e-10,
|
||||
topologicalMaxDimension: 3,
|
||||
...config,
|
||||
};
|
||||
let stats = {
|
||||
quantumOperations: 0,
|
||||
hyperbolicOperations: 0,
|
||||
topologicalOperations: 0,
|
||||
totalComputeTimeMs: 0,
|
||||
peakMemoryBytes: 0,
|
||||
};
|
||||
return {
|
||||
// Quantum operations
|
||||
quantumInit: (numQubits) => {
|
||||
stats.quantumOperations++;
|
||||
const size = Math.pow(2, numQubits);
|
||||
const amplitudes = new Float32Array(size);
|
||||
amplitudes[0] = 1.0; // |00...0> state
|
||||
return {
|
||||
amplitudes,
|
||||
phases: new Float32Array(size),
|
||||
entanglementMap: new Map(),
|
||||
};
|
||||
},
|
||||
quantumHadamard: (state, qubit) => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_hadamard(state, qubit)
|
||||
return { ...state };
|
||||
},
|
||||
quantumCnot: (state, control, target) => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_cnot(state, control, target)
|
||||
const newMap = new Map(state.entanglementMap);
|
||||
newMap.set(control, [...(newMap.get(control) || []), target]);
|
||||
return { ...state, entanglementMap: newMap };
|
||||
},
|
||||
quantumPhase: (state, qubit, phase) => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_phase(state, qubit, phase)
|
||||
return { ...state };
|
||||
},
|
||||
quantumMeasure: (state, qubits) => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_measure(state, qubits)
|
||||
return {
|
||||
bitstring: [],
|
||||
probability: 1.0,
|
||||
collapsedState: state,
|
||||
};
|
||||
},
|
||||
quantumAmplify: (state, oracle, iterations = 1) => {
|
||||
stats.quantumOperations += iterations;
|
||||
// WASM call: ruvector_quantum_amplify(state, oracle, iterations)
|
||||
return { ...state };
|
||||
},
|
||||
quantumVqe: (hamiltonian, ansatz, optimizer = 'cobyla') => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_vqe(hamiltonian, ansatz, optimizer)
|
||||
return {
|
||||
energy: 0,
|
||||
optimalParameters: new Float32Array(0),
|
||||
iterations: 0,
|
||||
converged: false,
|
||||
};
|
||||
},
|
||||
// Hyperbolic operations
|
||||
hyperbolicPoint: (coordinates, manifold = 'poincare', curvature = -1) => {
|
||||
stats.hyperbolicOperations++;
|
||||
return { coordinates, curvature, manifold };
|
||||
},
|
||||
hyperbolicDistance: (p1, p2) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_distance(p1, p2)
|
||||
return 0;
|
||||
},
|
||||
mobiusAdd: (x, y, c = 1) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_mobius_add(x, y, c)
|
||||
return x;
|
||||
},
|
||||
mobiusMatvec: (M, x, c = 1) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_mobius_matvec(M, x, c)
|
||||
return x;
|
||||
},
|
||||
hyperbolicExp: (v, base) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_exp(v, base)
|
||||
return {
|
||||
coordinates: v,
|
||||
curvature: base?.curvature ?? -1,
|
||||
manifold: base?.manifold ?? 'poincare',
|
||||
};
|
||||
},
|
||||
hyperbolicLog: (y, base) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_log(y, base)
|
||||
return y.coordinates;
|
||||
},
|
||||
hyperbolicTransport: (v, from, to) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_transport(v, from, to)
|
||||
return v;
|
||||
},
|
||||
hyperbolicCentroid: (points, weights) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_centroid(points, weights)
|
||||
return points[0];
|
||||
},
|
||||
// Topological operations
|
||||
persistentHomology: (data, maxDimension = 2, threshold = Infinity) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_persistent_homology(data, maxDimension, threshold)
|
||||
return [];
|
||||
},
|
||||
bettiNumbers: (features, threshold = 0) => {
|
||||
stats.topologicalOperations++;
|
||||
const maxDim = features.reduce((max, f) => Math.max(max, f.dimension), 0);
|
||||
return new Array(maxDim + 1).fill(0);
|
||||
},
|
||||
persistenceDiagram: (features) => {
|
||||
stats.topologicalOperations++;
|
||||
return features.map(f => ({
|
||||
birth: f.birthTime,
|
||||
death: f.deathTime,
|
||||
dimension: f.dimension,
|
||||
}));
|
||||
},
|
||||
bottleneckDistance: (diagram1, diagram2) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_bottleneck_distance(diagram1, diagram2)
|
||||
return 0;
|
||||
},
|
||||
wassersteinDistance: (diagram1, diagram2, p = 2) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_wasserstein_distance(diagram1, diagram2, p)
|
||||
return 0;
|
||||
},
|
||||
mapper: (data, lens, numBins = 10, overlap = 0.5) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_mapper(data, lens, numBins, overlap)
|
||||
return { nodes: [], edges: [] };
|
||||
},
|
||||
// Fractal operations
|
||||
fractalDimension: (data) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_fractal_dimension(data)
|
||||
return 0;
|
||||
},
|
||||
fractalEmbedding: (c, resolution = 256, maxIterations = 100) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_fractal_embedding(c, resolution, maxIterations)
|
||||
return new Float32Array(resolution * resolution);
|
||||
},
|
||||
lyapunovExponents: (trajectory, embeddingDim = 3, delay = 1) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_lyapunov_exponents(trajectory, embeddingDim, delay)
|
||||
return new Float32Array(embeddingDim);
|
||||
},
|
||||
recurrencePlot: (trajectory, threshold = 0.1) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_recurrence_plot(trajectory, threshold)
|
||||
const size = trajectory.length;
|
||||
return new Uint8Array(size * size);
|
||||
},
|
||||
// Non-Euclidean neural
|
||||
hyperbolicLayer: (input, weights, bias) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_layer(input, weights, bias)
|
||||
return input;
|
||||
},
|
||||
sphericalLayer: (input, weights) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_spherical_layer(input, weights)
|
||||
return input;
|
||||
},
|
||||
productManifoldLayer: (input, curvatures, weights) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_product_manifold_layer(input, curvatures, weights)
|
||||
return input;
|
||||
},
|
||||
// Utility
|
||||
getStats: () => ({ ...stats }),
|
||||
configure: (newConfig) => {
|
||||
Object.assign(defaultConfig, newConfig);
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create quantum circuit builder
|
||||
* @param numQubits Number of qubits
|
||||
* @returns Circuit builder
|
||||
*/
|
||||
function createCircuitBuilder(numQubits) {
|
||||
const gates = [];
|
||||
return {
|
||||
h: (qubit) => gates.push({ type: 'H', targets: [qubit] }),
|
||||
x: (qubit) => gates.push({ type: 'X', targets: [qubit] }),
|
||||
cnot: (control, target) => gates.push({ type: 'CNOT', targets: [control, target] }),
|
||||
rx: (qubit, angle) => gates.push({ type: 'RX', targets: [qubit], parameter: angle }),
|
||||
ry: (qubit, angle) => gates.push({ type: 'RY', targets: [qubit], parameter: angle }),
|
||||
rz: (qubit, angle) => gates.push({ type: 'RZ', targets: [qubit], parameter: angle }),
|
||||
build: () => ({ numQubits, gates }),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Utility: Project from Euclidean to Poincare ball
|
||||
* @param x Euclidean coordinates
|
||||
* @param c Curvature parameter
|
||||
*/
|
||||
function projectToPoincare(x, c = 1) {
|
||||
const normSq = x.reduce((sum, v) => sum + v * v, 0);
|
||||
const maxNorm = (1 - 1e-5) / Math.sqrt(c);
|
||||
if (normSq > maxNorm * maxNorm) {
|
||||
const scale = maxNorm / Math.sqrt(normSq);
|
||||
return new Float32Array(x.map(v => v * scale));
|
||||
}
|
||||
return x;
|
||||
}
|
||||
/**
|
||||
* Utility: Project from Poincare to Lorentz model
|
||||
* @param x Poincare coordinates
|
||||
* @param c Curvature parameter
|
||||
*/
|
||||
function poincareToLorentz(x, c = 1) {
|
||||
const normSq = x.reduce((sum, v) => sum + v * v, 0);
|
||||
const denom = 1 - c * normSq;
|
||||
const result = new Float32Array(x.length + 1);
|
||||
result[0] = (1 + c * normSq) / denom; // Time component
|
||||
for (let i = 0; i < x.length; i++) {
|
||||
result[i + 1] = 2 * Math.sqrt(c) * x[i] / denom;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
//# sourceMappingURL=exotic.js.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.js.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
681
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.ts
vendored
Normal file
681
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/exotic.ts
vendored
Normal file
@@ -0,0 +1,681 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Exotic Computation Engine
|
||||
*
|
||||
* Provides advanced computation paradigms including:
|
||||
* - Quantum-inspired algorithms (superposition, entanglement, interference)
|
||||
* - Hyperbolic geometry operations (Poincare, Lorentz, Klein models)
|
||||
* - Topological data analysis (persistent homology, Betti numbers)
|
||||
* - Fractal and chaos-based computation
|
||||
* - Non-Euclidean neural operations
|
||||
*/
|
||||
|
||||
import type {
|
||||
QuantumState,
|
||||
HyperbolicPoint,
|
||||
TopologicalFeature,
|
||||
ExoticResult,
|
||||
ResourceUsage,
|
||||
ExoticConfig,
|
||||
} from './types';
|
||||
|
||||
// ============================================================================
|
||||
// Exotic Computation Engine Interface
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Core exotic computation engine for advanced algorithmic paradigms
|
||||
*/
|
||||
export interface ExoticEngine {
|
||||
// -------------------------------------------------------------------------
|
||||
// Quantum-Inspired Operations
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Initialize quantum-inspired state
|
||||
* @param numQubits Number of qubits to simulate
|
||||
* @returns Initial quantum state
|
||||
*/
|
||||
quantumInit(numQubits: number): QuantumState;
|
||||
|
||||
/**
|
||||
* Apply Hadamard gate for superposition
|
||||
* @param state Current quantum state
|
||||
* @param qubit Target qubit index
|
||||
* @returns New quantum state
|
||||
*/
|
||||
quantumHadamard(state: QuantumState, qubit: number): QuantumState;
|
||||
|
||||
/**
|
||||
* Apply CNOT gate for entanglement
|
||||
* @param state Current quantum state
|
||||
* @param control Control qubit
|
||||
* @param target Target qubit
|
||||
* @returns Entangled quantum state
|
||||
*/
|
||||
quantumCnot(state: QuantumState, control: number, target: number): QuantumState;
|
||||
|
||||
/**
|
||||
* Apply phase rotation gate
|
||||
* @param state Current quantum state
|
||||
* @param qubit Target qubit
|
||||
* @param phase Phase angle in radians
|
||||
* @returns Rotated quantum state
|
||||
*/
|
||||
quantumPhase(state: QuantumState, qubit: number, phase: number): QuantumState;
|
||||
|
||||
/**
|
||||
* Measure quantum state
|
||||
* @param state Quantum state to measure
|
||||
* @param qubits Qubits to measure (empty = all)
|
||||
* @returns Measurement result and collapsed state
|
||||
*/
|
||||
quantumMeasure(state: QuantumState, qubits?: number[]): QuantumMeasurement;
|
||||
|
||||
/**
|
||||
* Quantum amplitude amplification (Grover-like)
|
||||
* @param state Initial state
|
||||
* @param oracle Oracle function marking solutions
|
||||
* @param iterations Number of amplification iterations
|
||||
* @returns Amplified state
|
||||
*/
|
||||
quantumAmplify(
|
||||
state: QuantumState,
|
||||
oracle: (amplitudes: Float32Array) => Float32Array,
|
||||
iterations?: number
|
||||
): QuantumState;
|
||||
|
||||
/**
|
||||
* Variational quantum eigensolver simulation
|
||||
* @param hamiltonian Hamiltonian matrix
|
||||
* @param ansatz Variational ansatz circuit
|
||||
* @param optimizer Optimizer type
|
||||
* @returns Ground state energy estimate
|
||||
*/
|
||||
quantumVqe(
|
||||
hamiltonian: Float32Array,
|
||||
ansatz?: QuantumCircuit,
|
||||
optimizer?: 'cobyla' | 'spsa' | 'adam'
|
||||
): VqeResult;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Hyperbolic Geometry Operations
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create point in hyperbolic space
|
||||
* @param coordinates Euclidean coordinates
|
||||
* @param manifold Target manifold model
|
||||
* @param curvature Negative curvature value
|
||||
* @returns Hyperbolic point
|
||||
*/
|
||||
hyperbolicPoint(
|
||||
coordinates: Float32Array,
|
||||
manifold?: 'poincare' | 'lorentz' | 'klein',
|
||||
curvature?: number
|
||||
): HyperbolicPoint;
|
||||
|
||||
/**
|
||||
* Compute hyperbolic distance
|
||||
* @param p1 First point
|
||||
* @param p2 Second point
|
||||
* @returns Hyperbolic distance
|
||||
*/
|
||||
hyperbolicDistance(p1: HyperbolicPoint, p2: HyperbolicPoint): number;
|
||||
|
||||
/**
|
||||
* Mobius addition in Poincare ball
|
||||
* @param x First point
|
||||
* @param y Second point
|
||||
* @param c Curvature parameter
|
||||
* @returns Sum in hyperbolic space
|
||||
*/
|
||||
mobiusAdd(x: HyperbolicPoint, y: HyperbolicPoint, c?: number): HyperbolicPoint;
|
||||
|
||||
/**
|
||||
* Mobius matrix-vector multiplication
|
||||
* @param M Matrix
|
||||
* @param x Point
|
||||
* @param c Curvature parameter
|
||||
* @returns Transformed point
|
||||
*/
|
||||
mobiusMatvec(M: Float32Array, x: HyperbolicPoint, c?: number): HyperbolicPoint;
|
||||
|
||||
/**
|
||||
* Exponential map (tangent space to hyperbolic)
|
||||
* @param v Tangent vector
|
||||
* @param base Base point
|
||||
* @returns Point in hyperbolic space
|
||||
*/
|
||||
hyperbolicExp(v: Float32Array, base?: HyperbolicPoint): HyperbolicPoint;
|
||||
|
||||
/**
|
||||
* Logarithmic map (hyperbolic to tangent space)
|
||||
* @param y Target point
|
||||
* @param base Base point
|
||||
* @returns Tangent vector
|
||||
*/
|
||||
hyperbolicLog(y: HyperbolicPoint, base?: HyperbolicPoint): Float32Array;
|
||||
|
||||
/**
|
||||
* Parallel transport in hyperbolic space
|
||||
* @param v Tangent vector
|
||||
* @param from Source point
|
||||
* @param to Target point
|
||||
* @returns Transported vector
|
||||
*/
|
||||
hyperbolicTransport(
|
||||
v: Float32Array,
|
||||
from: HyperbolicPoint,
|
||||
to: HyperbolicPoint
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Hyperbolic centroid (Frechet mean)
|
||||
* @param points Points to average
|
||||
* @param weights Optional weights
|
||||
* @returns Centroid in hyperbolic space
|
||||
*/
|
||||
hyperbolicCentroid(points: HyperbolicPoint[], weights?: Float32Array): HyperbolicPoint;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Topological Data Analysis
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Compute persistent homology
|
||||
* @param data Point cloud data
|
||||
* @param maxDimension Maximum homology dimension
|
||||
* @param threshold Filtration threshold
|
||||
* @returns Topological features
|
||||
*/
|
||||
persistentHomology(
|
||||
data: Float32Array[],
|
||||
maxDimension?: number,
|
||||
threshold?: number
|
||||
): TopologicalFeature[];
|
||||
|
||||
/**
|
||||
* Compute Betti numbers
|
||||
* @param features Topological features from persistent homology
|
||||
* @param threshold Persistence threshold
|
||||
* @returns Betti numbers by dimension
|
||||
*/
|
||||
bettiNumbers(features: TopologicalFeature[], threshold?: number): number[];
|
||||
|
||||
/**
|
||||
* Generate persistence diagram
|
||||
* @param features Topological features
|
||||
* @returns Birth-death pairs for visualization
|
||||
*/
|
||||
persistenceDiagram(features: TopologicalFeature[]): PersistencePair[];
|
||||
|
||||
/**
|
||||
* Compute bottleneck distance between persistence diagrams
|
||||
* @param diagram1 First persistence diagram
|
||||
* @param diagram2 Second persistence diagram
|
||||
* @returns Bottleneck distance
|
||||
*/
|
||||
bottleneckDistance(diagram1: PersistencePair[], diagram2: PersistencePair[]): number;
|
||||
|
||||
/**
|
||||
* Compute Wasserstein distance between persistence diagrams
|
||||
* @param diagram1 First persistence diagram
|
||||
* @param diagram2 Second persistence diagram
|
||||
* @param p Order of Wasserstein distance
|
||||
* @returns Wasserstein distance
|
||||
*/
|
||||
wassersteinDistance(
|
||||
diagram1: PersistencePair[],
|
||||
diagram2: PersistencePair[],
|
||||
p?: number
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Mapper algorithm for topological visualization
|
||||
* @param data Input data
|
||||
* @param lens Lens function
|
||||
* @param numBins Number of bins per dimension
|
||||
* @param overlap Overlap between bins
|
||||
* @returns Mapper graph
|
||||
*/
|
||||
mapper(
|
||||
data: Float32Array[],
|
||||
lens?: (point: Float32Array) => number[],
|
||||
numBins?: number,
|
||||
overlap?: number
|
||||
): MapperGraph;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Fractal and Chaos Operations
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Compute fractal dimension (box-counting)
|
||||
* @param data Point cloud or image data
|
||||
* @returns Estimated fractal dimension
|
||||
*/
|
||||
fractalDimension(data: Float32Array[]): number;
|
||||
|
||||
/**
|
||||
* Generate Mandelbrot/Julia set embedding
|
||||
* @param c Julia set constant (undefined for Mandelbrot)
|
||||
* @param resolution Grid resolution
|
||||
* @param maxIterations Maximum iterations
|
||||
* @returns Escape time embedding
|
||||
*/
|
||||
fractalEmbedding(
|
||||
c?: { re: number; im: number },
|
||||
resolution?: number,
|
||||
maxIterations?: number
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Compute Lyapunov exponents for chaotic dynamics
|
||||
* @param trajectory Time series trajectory
|
||||
* @param embeddingDim Embedding dimension
|
||||
* @param delay Time delay
|
||||
* @returns Lyapunov exponents
|
||||
*/
|
||||
lyapunovExponents(
|
||||
trajectory: Float32Array,
|
||||
embeddingDim?: number,
|
||||
delay?: number
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Recurrence plot analysis
|
||||
* @param trajectory Time series
|
||||
* @param threshold Recurrence threshold
|
||||
* @returns Recurrence plot matrix
|
||||
*/
|
||||
recurrencePlot(trajectory: Float32Array, threshold?: number): Uint8Array;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Non-Euclidean Neural Operations
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Hyperbolic neural network layer forward pass
|
||||
* @param input Input in hyperbolic space
|
||||
* @param weights Weight matrix
|
||||
* @param bias Bias vector
|
||||
* @returns Output in hyperbolic space
|
||||
*/
|
||||
hyperbolicLayer(
|
||||
input: HyperbolicPoint[],
|
||||
weights: Float32Array,
|
||||
bias?: Float32Array
|
||||
): HyperbolicPoint[];
|
||||
|
||||
/**
|
||||
* Spherical neural network layer (on n-sphere)
|
||||
* @param input Input on sphere
|
||||
* @param weights Weight matrix
|
||||
* @returns Output on sphere
|
||||
*/
|
||||
sphericalLayer(input: Float32Array[], weights: Float32Array): Float32Array[];
|
||||
|
||||
/**
|
||||
* Mixed-curvature neural network
|
||||
* @param input Input embeddings
|
||||
* @param curvatures Curvature for each dimension
|
||||
* @param weights Weight matrices
|
||||
* @returns Output in product manifold
|
||||
*/
|
||||
productManifoldLayer(
|
||||
input: Float32Array[],
|
||||
curvatures: Float32Array,
|
||||
weights: Float32Array[]
|
||||
): Float32Array[];
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Utility Methods
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get exotic computation statistics
|
||||
* @returns Resource usage and statistics
|
||||
*/
|
||||
getStats(): ExoticStats;
|
||||
|
||||
/**
|
||||
* Configure exotic engine
|
||||
* @param config Configuration options
|
||||
*/
|
||||
configure(config: Partial<ExoticConfig>): void;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Supporting Types
|
||||
// ============================================================================
|
||||
|
||||
/** Quantum measurement result */
|
||||
export interface QuantumMeasurement {
|
||||
bitstring: number[];
|
||||
probability: number;
|
||||
collapsedState: QuantumState;
|
||||
}
|
||||
|
||||
/** Quantum circuit representation */
|
||||
export interface QuantumCircuit {
|
||||
numQubits: number;
|
||||
gates: QuantumGate[];
|
||||
parameters?: Float32Array;
|
||||
}
|
||||
|
||||
/** Quantum gate */
|
||||
export interface QuantumGate {
|
||||
type: 'H' | 'X' | 'Y' | 'Z' | 'CNOT' | 'RX' | 'RY' | 'RZ' | 'CZ' | 'SWAP';
|
||||
targets: number[];
|
||||
parameter?: number;
|
||||
}
|
||||
|
||||
/** VQE result */
|
||||
export interface VqeResult {
|
||||
energy: number;
|
||||
optimalParameters: Float32Array;
|
||||
iterations: number;
|
||||
converged: boolean;
|
||||
}
|
||||
|
||||
/** Persistence pair for diagrams */
|
||||
export interface PersistencePair {
|
||||
birth: number;
|
||||
death: number;
|
||||
dimension: number;
|
||||
}
|
||||
|
||||
/** Mapper graph structure */
|
||||
export interface MapperGraph {
|
||||
nodes: MapperNode[];
|
||||
edges: MapperEdge[];
|
||||
}
|
||||
|
||||
/** Mapper node */
|
||||
export interface MapperNode {
|
||||
id: string;
|
||||
members: number[];
|
||||
centroid: Float32Array;
|
||||
}
|
||||
|
||||
/** Mapper edge */
|
||||
export interface MapperEdge {
|
||||
source: string;
|
||||
target: string;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
/** Exotic engine statistics */
|
||||
export interface ExoticStats {
|
||||
quantumOperations: number;
|
||||
hyperbolicOperations: number;
|
||||
topologicalOperations: number;
|
||||
totalComputeTimeMs: number;
|
||||
peakMemoryBytes: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Create an exotic computation engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized exotic engine
|
||||
*/
|
||||
export function createExoticEngine(config?: ExoticConfig): ExoticEngine {
|
||||
const defaultConfig: ExoticConfig = {
|
||||
quantumSimulationDepth: 10,
|
||||
hyperbolicPrecision: 1e-10,
|
||||
topologicalMaxDimension: 3,
|
||||
...config,
|
||||
};
|
||||
|
||||
let stats: ExoticStats = {
|
||||
quantumOperations: 0,
|
||||
hyperbolicOperations: 0,
|
||||
topologicalOperations: 0,
|
||||
totalComputeTimeMs: 0,
|
||||
peakMemoryBytes: 0,
|
||||
};
|
||||
|
||||
return {
|
||||
// Quantum operations
|
||||
quantumInit: (numQubits) => {
|
||||
stats.quantumOperations++;
|
||||
const size = Math.pow(2, numQubits);
|
||||
const amplitudes = new Float32Array(size);
|
||||
amplitudes[0] = 1.0; // |00...0> state
|
||||
return {
|
||||
amplitudes,
|
||||
phases: new Float32Array(size),
|
||||
entanglementMap: new Map(),
|
||||
};
|
||||
},
|
||||
quantumHadamard: (state, qubit) => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_hadamard(state, qubit)
|
||||
return { ...state };
|
||||
},
|
||||
quantumCnot: (state, control, target) => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_cnot(state, control, target)
|
||||
const newMap = new Map(state.entanglementMap);
|
||||
newMap.set(control, [...(newMap.get(control) || []), target]);
|
||||
return { ...state, entanglementMap: newMap };
|
||||
},
|
||||
quantumPhase: (state, qubit, phase) => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_phase(state, qubit, phase)
|
||||
return { ...state };
|
||||
},
|
||||
quantumMeasure: (state, qubits) => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_measure(state, qubits)
|
||||
return {
|
||||
bitstring: [],
|
||||
probability: 1.0,
|
||||
collapsedState: state,
|
||||
};
|
||||
},
|
||||
quantumAmplify: (state, oracle, iterations = 1) => {
|
||||
stats.quantumOperations += iterations;
|
||||
// WASM call: ruvector_quantum_amplify(state, oracle, iterations)
|
||||
return { ...state };
|
||||
},
|
||||
quantumVqe: (hamiltonian, ansatz, optimizer = 'cobyla') => {
|
||||
stats.quantumOperations++;
|
||||
// WASM call: ruvector_quantum_vqe(hamiltonian, ansatz, optimizer)
|
||||
return {
|
||||
energy: 0,
|
||||
optimalParameters: new Float32Array(0),
|
||||
iterations: 0,
|
||||
converged: false,
|
||||
};
|
||||
},
|
||||
|
||||
// Hyperbolic operations
|
||||
hyperbolicPoint: (coordinates, manifold = 'poincare', curvature = -1) => {
|
||||
stats.hyperbolicOperations++;
|
||||
return { coordinates, curvature, manifold };
|
||||
},
|
||||
hyperbolicDistance: (p1, p2) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_distance(p1, p2)
|
||||
return 0;
|
||||
},
|
||||
mobiusAdd: (x, y, c = 1) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_mobius_add(x, y, c)
|
||||
return x;
|
||||
},
|
||||
mobiusMatvec: (M, x, c = 1) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_mobius_matvec(M, x, c)
|
||||
return x;
|
||||
},
|
||||
hyperbolicExp: (v, base) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_exp(v, base)
|
||||
return {
|
||||
coordinates: v,
|
||||
curvature: base?.curvature ?? -1,
|
||||
manifold: base?.manifold ?? 'poincare',
|
||||
};
|
||||
},
|
||||
hyperbolicLog: (y, base) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_log(y, base)
|
||||
return y.coordinates;
|
||||
},
|
||||
hyperbolicTransport: (v, from, to) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_transport(v, from, to)
|
||||
return v;
|
||||
},
|
||||
hyperbolicCentroid: (points, weights) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_centroid(points, weights)
|
||||
return points[0];
|
||||
},
|
||||
|
||||
// Topological operations
|
||||
persistentHomology: (data, maxDimension = 2, threshold = Infinity) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_persistent_homology(data, maxDimension, threshold)
|
||||
return [];
|
||||
},
|
||||
bettiNumbers: (features, threshold = 0) => {
|
||||
stats.topologicalOperations++;
|
||||
const maxDim = features.reduce((max, f) => Math.max(max, f.dimension), 0);
|
||||
return new Array(maxDim + 1).fill(0);
|
||||
},
|
||||
persistenceDiagram: (features) => {
|
||||
stats.topologicalOperations++;
|
||||
return features.map(f => ({
|
||||
birth: f.birthTime,
|
||||
death: f.deathTime,
|
||||
dimension: f.dimension,
|
||||
}));
|
||||
},
|
||||
bottleneckDistance: (diagram1, diagram2) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_bottleneck_distance(diagram1, diagram2)
|
||||
return 0;
|
||||
},
|
||||
wassersteinDistance: (diagram1, diagram2, p = 2) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_wasserstein_distance(diagram1, diagram2, p)
|
||||
return 0;
|
||||
},
|
||||
mapper: (data, lens, numBins = 10, overlap = 0.5) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_mapper(data, lens, numBins, overlap)
|
||||
return { nodes: [], edges: [] };
|
||||
},
|
||||
|
||||
// Fractal operations
|
||||
fractalDimension: (data) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_fractal_dimension(data)
|
||||
return 0;
|
||||
},
|
||||
fractalEmbedding: (c, resolution = 256, maxIterations = 100) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_fractal_embedding(c, resolution, maxIterations)
|
||||
return new Float32Array(resolution * resolution);
|
||||
},
|
||||
lyapunovExponents: (trajectory, embeddingDim = 3, delay = 1) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_lyapunov_exponents(trajectory, embeddingDim, delay)
|
||||
return new Float32Array(embeddingDim);
|
||||
},
|
||||
recurrencePlot: (trajectory, threshold = 0.1) => {
|
||||
stats.topologicalOperations++;
|
||||
// WASM call: ruvector_recurrence_plot(trajectory, threshold)
|
||||
const size = trajectory.length;
|
||||
return new Uint8Array(size * size);
|
||||
},
|
||||
|
||||
// Non-Euclidean neural
|
||||
hyperbolicLayer: (input, weights, bias) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_hyperbolic_layer(input, weights, bias)
|
||||
return input;
|
||||
},
|
||||
sphericalLayer: (input, weights) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_spherical_layer(input, weights)
|
||||
return input;
|
||||
},
|
||||
productManifoldLayer: (input, curvatures, weights) => {
|
||||
stats.hyperbolicOperations++;
|
||||
// WASM call: ruvector_product_manifold_layer(input, curvatures, weights)
|
||||
return input;
|
||||
},
|
||||
|
||||
// Utility
|
||||
getStats: () => ({ ...stats }),
|
||||
configure: (newConfig) => {
|
||||
Object.assign(defaultConfig, newConfig);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create quantum circuit builder
|
||||
* @param numQubits Number of qubits
|
||||
* @returns Circuit builder
|
||||
*/
|
||||
export function createCircuitBuilder(numQubits: number): {
|
||||
h: (qubit: number) => void;
|
||||
x: (qubit: number) => void;
|
||||
cnot: (control: number, target: number) => void;
|
||||
rx: (qubit: number, angle: number) => void;
|
||||
ry: (qubit: number, angle: number) => void;
|
||||
rz: (qubit: number, angle: number) => void;
|
||||
build: () => QuantumCircuit;
|
||||
} {
|
||||
const gates: QuantumGate[] = [];
|
||||
|
||||
return {
|
||||
h: (qubit) => gates.push({ type: 'H', targets: [qubit] }),
|
||||
x: (qubit) => gates.push({ type: 'X', targets: [qubit] }),
|
||||
cnot: (control, target) => gates.push({ type: 'CNOT', targets: [control, target] }),
|
||||
rx: (qubit, angle) => gates.push({ type: 'RX', targets: [qubit], parameter: angle }),
|
||||
ry: (qubit, angle) => gates.push({ type: 'RY', targets: [qubit], parameter: angle }),
|
||||
rz: (qubit, angle) => gates.push({ type: 'RZ', targets: [qubit], parameter: angle }),
|
||||
build: () => ({ numQubits, gates }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility: Project from Euclidean to Poincare ball
|
||||
* @param x Euclidean coordinates
|
||||
* @param c Curvature parameter
|
||||
*/
|
||||
export function projectToPoincare(x: Float32Array, c: number = 1): Float32Array {
|
||||
const normSq = x.reduce((sum, v) => sum + v * v, 0);
|
||||
const maxNorm = (1 - 1e-5) / Math.sqrt(c);
|
||||
if (normSq > maxNorm * maxNorm) {
|
||||
const scale = maxNorm / Math.sqrt(normSq);
|
||||
return new Float32Array(x.map(v => v * scale));
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility: Project from Poincare to Lorentz model
|
||||
* @param x Poincare coordinates
|
||||
* @param c Curvature parameter
|
||||
*/
|
||||
export function poincareToLorentz(x: Float32Array, c: number = 1): Float32Array {
|
||||
const normSq = x.reduce((sum, v) => sum + v * v, 0);
|
||||
const denom = 1 - c * normSq;
|
||||
const result = new Float32Array(x.length + 1);
|
||||
result[0] = (1 + c * normSq) / denom; // Time component
|
||||
for (let i = 0; i < x.length; i++) {
|
||||
result[i + 1] = 2 * Math.sqrt(c) * x[i] / denom;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/index.d.ts.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/index.d.ts.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAOH,cAAc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,MAAM,CAAC;QACnB,aAAa,EAAE,MAAM,CAAC;QACtB,cAAc,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,MAAM,EAAE;QACN,gBAAgB,EAAE,MAAM,CAAC;QACzB,aAAa,EAAE,MAAM,CAAC;QACtB,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;CACH;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,CAAC,EAAE,aAAa,GAAG,YAAY,GACpC,OAAO,CAAC,aAAa,CAAC,CAsExB;AASD;;;GAGG;AACH,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,aAAa,CAAC,CAM/D;AAED;;GAEG;AACH,wBAAgB,kBAAkB,IAAI,IAAI,CAKzC;AAMD,sBAAsB;AACtB,eAAO,MAAM,OAAO,UAAU,CAAC;AAE/B,yBAAyB;AACzB,eAAO,MAAM,QAAQ;;;;;;CAgEX,CAAC"}
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/index.js.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/index.js.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;GAYG;;;;;;;;;;;;;;;;;AA4LH,kDAwEC;AAaD,4CAMC;AAKD,gDAKC;AA/RD,+EAA+E;AAC/E,8BAA8B;AAC9B,+EAA+E;AAE/E,QAAQ;AACR,0CAAwB;AAExB,mBAAmB;AACnB,yCAOqB;AAHnB,kHAAA,qBAAqB,OAAA;AACrB,oHAAA,uBAAuB,OAAA;AACvB,+GAAA,kBAAkB,OAAA;AAGpB,kBAAkB;AAClB,uCAaoB;AALlB,gHAAA,oBAAoB,OAAA;AACpB,iHAAA,qBAAqB,OAAA;AACrB,4GAAA,gBAAgB,OAAA;AAChB,6GAAA,iBAAiB,OAAA;AACjB,oGAAA,QAAQ,OAAA;AAGV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T,yBAAyB;QACzB,cAAc;KACf;IACD,MAAM,EAAE;QACN,uBAAuB;QACvB,sBAAsB;QACtB,aAAa;QACb,qBAAqB;QACrB,oBAAoB;QACpB,mBAAmB;QACnB,qBAAqB;QACrB,QAAQ;QACR,mBAAmB;QACnB,oBAAoB;KACrB;CACO,CAAC"}
|
||||
376
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/index.ts
vendored
Normal file
376
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/index.ts
vendored
Normal file
@@ -0,0 +1,376 @@
|
||||
/**
|
||||
* RuVector WASM Unified API
|
||||
*
|
||||
* A unified TypeScript surface for all RuVector WASM capabilities:
|
||||
* - Attention: 14+ attention mechanisms (neural + DAG)
|
||||
* - Learning: Micro-LoRA, SONA, BTSP, RL, Meta-learning
|
||||
* - Nervous: Biological neural network simulation
|
||||
* - Economy: Compute credit management
|
||||
* - Exotic: Quantum, Hyperbolic, Topological computation
|
||||
*
|
||||
* @module @ruvector/wasm-unified
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
// ============================================================================
|
||||
// Re-exports from all modules
|
||||
// ============================================================================
|
||||
|
||||
// Types
|
||||
export * from './types';
|
||||
|
||||
// Attention Engine
|
||||
export {
|
||||
type AttentionEngine,
|
||||
type MambaConfig,
|
||||
type AttentionMechanism,
|
||||
createAttentionEngine,
|
||||
listAttentionMechanisms,
|
||||
benchmarkAttention,
|
||||
} from './attention';
|
||||
|
||||
// Learning Engine
|
||||
export {
|
||||
type LearningEngine,
|
||||
type RLAlgorithm,
|
||||
type PolicyUpdate,
|
||||
type ReplayBatch,
|
||||
type TaskDataset,
|
||||
type LearningStats,
|
||||
type LoraLayerInfo,
|
||||
createLearningEngine,
|
||||
createMicroLoraConfig,
|
||||
createBtspConfig,
|
||||
cosineAnnealingLr,
|
||||
warmupLr,
|
||||
} from './learning';
|
||||
|
||||
// Nervous System Engine
|
||||
export {
|
||||
type NervousEngine,
|
||||
type NeuronConfig,
|
||||
type NeuronModel,
|
||||
type SynapseConfig,
|
||||
type StdpConfig,
|
||||
type NeuronFilter,
|
||||
type SimulationResult,
|
||||
type PlasticityStats,
|
||||
type TopologyStats,
|
||||
type RecordedActivity,
|
||||
createNervousEngine,
|
||||
createStdpConfig,
|
||||
izhikevichParams,
|
||||
} from './nervous';
|
||||
|
||||
// Economy Engine
|
||||
export {
|
||||
type EconomyEngine,
|
||||
type TransactionFilter,
|
||||
type ContributionType,
|
||||
type ContributionRecord,
|
||||
type OperationType,
|
||||
type AccountAnalytics,
|
||||
type LeaderboardMetric,
|
||||
type LeaderboardEntry,
|
||||
createEconomyEngine,
|
||||
calculateStakingApy,
|
||||
formatCredits,
|
||||
} from './economy';
|
||||
|
||||
// Exotic Engine
|
||||
export {
|
||||
type ExoticEngine,
|
||||
type QuantumMeasurement,
|
||||
type QuantumCircuit,
|
||||
type QuantumGate,
|
||||
type VqeResult,
|
||||
type PersistencePair,
|
||||
type MapperGraph,
|
||||
type MapperNode,
|
||||
type MapperEdge,
|
||||
type ExoticStats,
|
||||
createExoticEngine,
|
||||
createCircuitBuilder,
|
||||
projectToPoincare,
|
||||
poincareToLorentz,
|
||||
} from './exotic';
|
||||
|
||||
// ============================================================================
|
||||
// Unified Engine
|
||||
// ============================================================================
|
||||
|
||||
import { createAttentionEngine, type AttentionEngine } from './attention';
|
||||
import { createLearningEngine, type LearningEngine } from './learning';
|
||||
import { createNervousEngine, type NervousEngine } from './nervous';
|
||||
import { createEconomyEngine, type EconomyEngine } from './economy';
|
||||
import { createExoticEngine, type ExoticEngine } from './exotic';
|
||||
import type { UnifiedConfig, ModuleConfig } from './types';
|
||||
|
||||
/**
|
||||
* Unified RuVector WASM Engine combining all capabilities
|
||||
*/
|
||||
export interface UnifiedEngine {
|
||||
/** Attention mechanisms (14+) */
|
||||
attention: AttentionEngine;
|
||||
|
||||
/** Learning and adaptation */
|
||||
learning: LearningEngine;
|
||||
|
||||
/** Biological neural simulation */
|
||||
nervous: NervousEngine;
|
||||
|
||||
/** Compute credit economy */
|
||||
economy: EconomyEngine;
|
||||
|
||||
/** Exotic computation paradigms */
|
||||
exotic: ExoticEngine;
|
||||
|
||||
/** Get engine version */
|
||||
version(): string;
|
||||
|
||||
/** Get all engine statistics */
|
||||
getStats(): UnifiedStats;
|
||||
|
||||
/** Initialize WASM module */
|
||||
init(): Promise<void>;
|
||||
|
||||
/** Cleanup and release resources */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/** Unified statistics from all engines */
|
||||
export interface UnifiedStats {
|
||||
attention: {
|
||||
operationCount: number;
|
||||
cacheHitRate: number;
|
||||
};
|
||||
learning: {
|
||||
stepsCompleted: number;
|
||||
patternsLearned: number;
|
||||
};
|
||||
nervous: {
|
||||
neuronCount: number;
|
||||
synapseCount: number;
|
||||
spikeRate: number;
|
||||
};
|
||||
economy: {
|
||||
balance: number;
|
||||
stakedAmount: number;
|
||||
transactionCount: number;
|
||||
};
|
||||
exotic: {
|
||||
quantumOps: number;
|
||||
hyperbolicOps: number;
|
||||
topologicalOps: number;
|
||||
};
|
||||
system: {
|
||||
memoryUsageBytes: number;
|
||||
wasmHeapBytes: number;
|
||||
uptime: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a unified RuVector WASM engine
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { createUnifiedEngine } from '@ruvector/wasm-unified';
|
||||
*
|
||||
* const engine = await createUnifiedEngine();
|
||||
*
|
||||
* // Use attention mechanisms
|
||||
* const output = engine.attention.scaledDot(Q, K, V);
|
||||
*
|
||||
* // Use learning capabilities
|
||||
* engine.learning.btspOneShotLearn(pattern, reward);
|
||||
*
|
||||
* // Simulate nervous system
|
||||
* engine.nervous.step();
|
||||
*
|
||||
* // Manage economy
|
||||
* const balance = engine.economy.creditBalance();
|
||||
*
|
||||
* // Exotic computations
|
||||
* const qstate = engine.exotic.quantumInit(4);
|
||||
* ```
|
||||
*
|
||||
* @param config Optional configuration
|
||||
* @returns Unified engine instance
|
||||
*/
|
||||
export async function createUnifiedEngine(
|
||||
config?: UnifiedConfig & ModuleConfig
|
||||
): Promise<UnifiedEngine> {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Initialize all engines
|
||||
const attention = createAttentionEngine(config?.attention);
|
||||
const learning = createLearningEngine(config?.learning);
|
||||
const nervous = createNervousEngine(config?.nervous);
|
||||
const economy = createEconomyEngine(config?.economy);
|
||||
const exotic = createExoticEngine(config?.exotic);
|
||||
|
||||
// Track operation counts
|
||||
let attentionOps = 0;
|
||||
let transactionCount = 0;
|
||||
|
||||
return {
|
||||
attention,
|
||||
learning,
|
||||
nervous,
|
||||
economy,
|
||||
exotic,
|
||||
|
||||
version: () => '1.0.0',
|
||||
|
||||
getStats: () => ({
|
||||
attention: {
|
||||
operationCount: attentionOps,
|
||||
cacheHitRate: 0,
|
||||
},
|
||||
learning: {
|
||||
stepsCompleted: learning.getStats().totalSteps,
|
||||
patternsLearned: learning.getStats().patternsLearned,
|
||||
},
|
||||
nervous: {
|
||||
neuronCount: nervous.getTopologyStats().neuronCount,
|
||||
synapseCount: nervous.getTopologyStats().synapseCount,
|
||||
spikeRate: 0,
|
||||
},
|
||||
economy: {
|
||||
balance: economy.creditBalance(),
|
||||
stakedAmount: economy.getTotalStaked(),
|
||||
transactionCount,
|
||||
},
|
||||
exotic: {
|
||||
quantumOps: exotic.getStats().quantumOperations,
|
||||
hyperbolicOps: exotic.getStats().hyperbolicOperations,
|
||||
topologicalOps: exotic.getStats().topologicalOperations,
|
||||
},
|
||||
system: {
|
||||
memoryUsageBytes: 0,
|
||||
wasmHeapBytes: 0,
|
||||
uptime: Date.now() - startTime,
|
||||
},
|
||||
}),
|
||||
|
||||
init: async () => {
|
||||
// WASM initialization would happen here
|
||||
// await wasmModule.init();
|
||||
if (config?.logLevel === 'debug') {
|
||||
console.log('[ruvector-wasm-unified] Initialized');
|
||||
}
|
||||
},
|
||||
|
||||
dispose: () => {
|
||||
nervous.reset(false);
|
||||
// WASM cleanup would happen here
|
||||
if (config?.logLevel === 'debug') {
|
||||
console.log('[ruvector-wasm-unified] Disposed');
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Convenience exports
|
||||
// ============================================================================
|
||||
|
||||
/** Default unified engine instance (lazy initialized) */
|
||||
let defaultEngine: UnifiedEngine | null = null;
|
||||
|
||||
/**
|
||||
* Get or create the default unified engine
|
||||
* @returns Default engine instance
|
||||
*/
|
||||
export async function getDefaultEngine(): Promise<UnifiedEngine> {
|
||||
if (!defaultEngine) {
|
||||
defaultEngine = await createUnifiedEngine();
|
||||
await defaultEngine.init();
|
||||
}
|
||||
return defaultEngine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the default engine
|
||||
*/
|
||||
export function resetDefaultEngine(): void {
|
||||
if (defaultEngine) {
|
||||
defaultEngine.dispose();
|
||||
defaultEngine = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Version and metadata
|
||||
// ============================================================================
|
||||
|
||||
/** Package version */
|
||||
export const VERSION = '1.0.0';
|
||||
|
||||
/** Supported features */
|
||||
export const FEATURES = {
|
||||
attention: [
|
||||
'scaled-dot',
|
||||
'multi-head',
|
||||
'hyperbolic',
|
||||
'linear',
|
||||
'flash',
|
||||
'local-global',
|
||||
'moe',
|
||||
'mamba',
|
||||
'dag-topological',
|
||||
'dag-mincut',
|
||||
'dag-hierarchical',
|
||||
'dag-spectral',
|
||||
'dag-flow',
|
||||
'dag-causal',
|
||||
'dag-sparse',
|
||||
],
|
||||
learning: [
|
||||
'micro-lora',
|
||||
'sona-pre-query',
|
||||
'btsp-one-shot',
|
||||
'ppo',
|
||||
'a2c',
|
||||
'dqn',
|
||||
'sac',
|
||||
'td3',
|
||||
'reinforce',
|
||||
'ewc',
|
||||
'progressive-nets',
|
||||
'experience-replay',
|
||||
'maml',
|
||||
'reptile',
|
||||
],
|
||||
nervous: [
|
||||
'lif',
|
||||
'izhikevich',
|
||||
'hodgkin-huxley',
|
||||
'adex',
|
||||
'srm',
|
||||
'stdp',
|
||||
'btsp',
|
||||
'hebbian',
|
||||
'homeostasis',
|
||||
],
|
||||
economy: [
|
||||
'credit-balance',
|
||||
'staking',
|
||||
'rewards',
|
||||
'contribution-multiplier',
|
||||
'transactions',
|
||||
],
|
||||
exotic: [
|
||||
'quantum-superposition',
|
||||
'quantum-entanglement',
|
||||
'quantum-vqe',
|
||||
'hyperbolic-poincare',
|
||||
'hyperbolic-lorentz',
|
||||
'mobius-operations',
|
||||
'persistent-homology',
|
||||
'mapper',
|
||||
'fractal-dimension',
|
||||
'lyapunov-exponents',
|
||||
],
|
||||
} as const;
|
||||
201
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.d.ts
vendored
Normal file
201
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.d.ts
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Learning Engine
|
||||
*
|
||||
* Provides adaptive learning mechanisms including:
|
||||
* - Micro-LoRA adaptation for efficient fine-tuning
|
||||
* - SONA pre-query processing for enhanced embeddings
|
||||
* - BTSP one-shot learning for rapid pattern acquisition
|
||||
* - Reinforcement learning integration
|
||||
* - Continual learning support
|
||||
*/
|
||||
import type { EnhancedEmbedding, LearningTrajectory, MicroLoraConfig, BtspConfig, QueryDag, LearningConfig } from './types';
|
||||
/**
|
||||
* Core learning engine for adaptive model updates and pattern learning
|
||||
*/
|
||||
export interface LearningEngine {
|
||||
/**
|
||||
* Micro-LoRA adaptation for operation-specific fine-tuning
|
||||
* Applies low-rank updates based on operation type
|
||||
* @param embedding Input embedding to adapt
|
||||
* @param opType Operation type identifier (e.g., 'attention', 'ffn', 'norm')
|
||||
* @param config Optional LoRA configuration
|
||||
* @returns Adapted embedding with low-rank modifications
|
||||
*/
|
||||
microLoraAdapt(embedding: Float32Array, opType: string, config?: Partial<MicroLoraConfig>): Float32Array;
|
||||
/**
|
||||
* SONA (Self-Organizing Neural Architecture) pre-query processing
|
||||
* Enhances embeddings before attention computation
|
||||
* @param dag Query DAG with embeddings
|
||||
* @param contextWindow Context window size
|
||||
* @returns Enhanced embedding with context
|
||||
*/
|
||||
sonaPreQuery(dag: QueryDag, contextWindow?: number): EnhancedEmbedding;
|
||||
/**
|
||||
* BTSP (Behavioral Timescale Synaptic Plasticity) one-shot learning
|
||||
* Rapidly acquires new patterns with single exposure
|
||||
* @param pattern Pattern to learn
|
||||
* @param signal Reward/error signal for reinforcement
|
||||
* @param config Optional BTSP configuration
|
||||
*/
|
||||
btspOneShotLearn(pattern: Float32Array, signal: number, config?: Partial<BtspConfig>): void;
|
||||
/**
|
||||
* Update policy from trajectory
|
||||
* @param trajectory Learning trajectory with states, actions, rewards
|
||||
* @param algorithm RL algorithm to use
|
||||
* @returns Policy gradient and metrics
|
||||
*/
|
||||
updateFromTrajectory(trajectory: LearningTrajectory, algorithm?: RLAlgorithm): PolicyUpdate;
|
||||
/**
|
||||
* Compute advantage estimates for policy gradient
|
||||
* @param rewards Reward sequence
|
||||
* @param values Value estimates
|
||||
* @param gamma Discount factor
|
||||
* @param lambda GAE lambda parameter
|
||||
* @returns Advantage estimates
|
||||
*/
|
||||
computeAdvantages(rewards: Float32Array, values: Float32Array, gamma?: number, lambda?: number): Float32Array;
|
||||
/**
|
||||
* Get action from current policy
|
||||
* @param state Current state embedding
|
||||
* @param temperature Sampling temperature
|
||||
* @returns Action index and log probability
|
||||
*/
|
||||
sampleAction(state: Float32Array, temperature?: number): {
|
||||
action: number;
|
||||
logProb: number;
|
||||
};
|
||||
/**
|
||||
* Elastic weight consolidation for preventing catastrophic forgetting
|
||||
* @param taskId Current task identifier
|
||||
* @param importance Fisher information matrix diagonal
|
||||
*/
|
||||
ewcRegularize(taskId: string, importance?: Float32Array): void;
|
||||
/**
|
||||
* Progressive neural networks - add new column for task
|
||||
* @param taskId New task identifier
|
||||
* @param hiddenSize Size of hidden layers in new column
|
||||
*/
|
||||
progressiveAddColumn(taskId: string, hiddenSize?: number): void;
|
||||
/**
|
||||
* Experience replay for continual learning
|
||||
* @param bufferSize Maximum replay buffer size
|
||||
* @param batchSize Batch size for replay
|
||||
* @returns Replayed batch
|
||||
*/
|
||||
experienceReplay(bufferSize?: number, batchSize?: number): ReplayBatch;
|
||||
/**
|
||||
* MAML-style meta-learning inner loop
|
||||
* @param supportSet Support set for few-shot learning
|
||||
* @param innerSteps Number of inner loop steps
|
||||
* @param innerLr Inner loop learning rate
|
||||
* @returns Adapted parameters
|
||||
*/
|
||||
mamlInnerLoop(supportSet: TaskDataset, innerSteps?: number, innerLr?: number): Float32Array;
|
||||
/**
|
||||
* Reptile meta-learning update
|
||||
* @param taskBatch Batch of tasks for meta-learning
|
||||
* @param epsilon Interpolation factor
|
||||
*/
|
||||
reptileUpdate(taskBatch: TaskDataset[], epsilon?: number): void;
|
||||
/**
|
||||
* Get current learning statistics
|
||||
*/
|
||||
getStats(): LearningStats;
|
||||
/**
|
||||
* Reset learning state
|
||||
* @param keepWeights Whether to keep learned weights
|
||||
*/
|
||||
reset(keepWeights?: boolean): void;
|
||||
/**
|
||||
* Save learning checkpoint
|
||||
* @param path Checkpoint path
|
||||
*/
|
||||
saveCheckpoint(path: string): Promise<void>;
|
||||
/**
|
||||
* Load learning checkpoint
|
||||
* @param path Checkpoint path
|
||||
*/
|
||||
loadCheckpoint(path: string): Promise<void>;
|
||||
}
|
||||
/** Reinforcement learning algorithm */
|
||||
export type RLAlgorithm = 'ppo' | 'a2c' | 'dqn' | 'sac' | 'td3' | 'reinforce';
|
||||
/** Policy update result */
|
||||
export interface PolicyUpdate {
|
||||
gradient: Float32Array;
|
||||
loss: number;
|
||||
entropy: number;
|
||||
klDivergence: number;
|
||||
clipFraction?: number;
|
||||
}
|
||||
/** Experience replay batch */
|
||||
export interface ReplayBatch {
|
||||
states: Float32Array[];
|
||||
actions: number[];
|
||||
rewards: number[];
|
||||
nextStates: Float32Array[];
|
||||
dones: boolean[];
|
||||
priorities?: Float32Array;
|
||||
}
|
||||
/** Task dataset for meta-learning */
|
||||
export interface TaskDataset {
|
||||
taskId: string;
|
||||
supportInputs: Float32Array[];
|
||||
supportLabels: number[];
|
||||
queryInputs: Float32Array[];
|
||||
queryLabels: number[];
|
||||
}
|
||||
/** Learning statistics */
|
||||
export interface LearningStats {
|
||||
totalSteps: number;
|
||||
totalEpisodes: number;
|
||||
averageReward: number;
|
||||
averageLoss: number;
|
||||
learningRate: number;
|
||||
memoryUsage: number;
|
||||
patternsLearned: number;
|
||||
adaptationCount: number;
|
||||
}
|
||||
/** LoRA layer info */
|
||||
export interface LoraLayerInfo {
|
||||
layerName: string;
|
||||
rank: number;
|
||||
alpha: number;
|
||||
enabled: boolean;
|
||||
parameterCount: number;
|
||||
}
|
||||
/**
|
||||
* Create a learning engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized learning engine
|
||||
*/
|
||||
export declare function createLearningEngine(config?: LearningConfig): LearningEngine;
|
||||
/**
|
||||
* Create Micro-LoRA configuration
|
||||
* @param rank LoRA rank (default: 8)
|
||||
* @param alpha LoRA alpha scaling (default: 16)
|
||||
* @param targetModules Modules to apply LoRA to
|
||||
*/
|
||||
export declare function createMicroLoraConfig(rank?: number, alpha?: number, targetModules?: string[]): MicroLoraConfig;
|
||||
/**
|
||||
* Create BTSP configuration for one-shot learning
|
||||
* @param learningRate Learning rate for plasticity
|
||||
* @param eligibilityDecay Decay rate for eligibility traces
|
||||
* @param rewardWindow Time window for reward integration
|
||||
*/
|
||||
export declare function createBtspConfig(learningRate?: number, eligibilityDecay?: number, rewardWindow?: number): BtspConfig;
|
||||
/**
|
||||
* Compute cosine annealing learning rate
|
||||
* @param step Current step
|
||||
* @param totalSteps Total training steps
|
||||
* @param lrMax Maximum learning rate
|
||||
* @param lrMin Minimum learning rate
|
||||
*/
|
||||
export declare function cosineAnnealingLr(step: number, totalSteps: number, lrMax?: number, lrMin?: number): number;
|
||||
/**
|
||||
* Compute warmup learning rate
|
||||
* @param step Current step
|
||||
* @param warmupSteps Number of warmup steps
|
||||
* @param targetLr Target learning rate after warmup
|
||||
*/
|
||||
export declare function warmupLr(step: number, warmupSteps: number, targetLr?: number): number;
|
||||
//# sourceMappingURL=learning.d.ts.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.d.ts.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.d.ts.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"learning.d.ts","sourceRoot":"","sources":["learning.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EACV,iBAAiB,EACjB,kBAAkB,EAClB,eAAe,EACf,UAAU,EACV,QAAQ,EACR,cAAc,EACf,MAAM,SAAS,CAAC;AAMjB;;GAEG;AACH,MAAM,WAAW,cAAc;IAK7B;;;;;;;OAOG;IACH,cAAc,CACZ,SAAS,EAAE,YAAY,EACvB,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,GAChC,YAAY,CAAC;IAEhB;;;;;;OAMG;IACH,YAAY,CAAC,GAAG,EAAE,QAAQ,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,iBAAiB,CAAC;IAEvE;;;;;;OAMG;IACH,gBAAgB,CACd,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,OAAO,CAAC,UAAU,CAAC,GAC3B,IAAI,CAAC;IAMR;;;;;OAKG;IACH,oBAAoB,CAClB,UAAU,EAAE,kBAAkB,EAC9B,SAAS,CAAC,EAAE,WAAW,GACtB,YAAY,CAAC;IAEhB;;;;;;;OAOG;IACH,iBAAiB,CACf,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,YAAY,EACpB,KAAK,CAAC,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,MAAM,GACd,YAAY,CAAC;IAEhB;;;;;OAKG;IACH,YAAY,CACV,KAAK,EAAE,YAAY,EACnB,WAAW,CAAC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BAAgB,gBAAgB,CAC9B,YAAY,GAAE,MAAY,EAC1B,gBAAgB,GAAE,MAAa,EAC/B,YAAY,GAAE,MAAY,GACzB,UAAU,CAMZ;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM,EAClB,KAAK,GAAE,MAAc,EACrB,KAAK,GAAE,MAAgB,GACtB,MAAM,CAER;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CACtB,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,QAAQ,GAAE,MAAc,GACvB,MAAM,CAKR"}
|
||||
162
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.js
vendored
Normal file
162
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.js
vendored
Normal file
@@ -0,0 +1,162 @@
|
||||
"use strict";
|
||||
/**
|
||||
* RuVector WASM Unified - Learning Engine
|
||||
*
|
||||
* Provides adaptive learning mechanisms including:
|
||||
* - Micro-LoRA adaptation for efficient fine-tuning
|
||||
* - SONA pre-query processing for enhanced embeddings
|
||||
* - BTSP one-shot learning for rapid pattern acquisition
|
||||
* - Reinforcement learning integration
|
||||
* - Continual learning support
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createLearningEngine = createLearningEngine;
|
||||
exports.createMicroLoraConfig = createMicroLoraConfig;
|
||||
exports.createBtspConfig = createBtspConfig;
|
||||
exports.cosineAnnealingLr = cosineAnnealingLr;
|
||||
exports.warmupLr = warmupLr;
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
/**
|
||||
* Create a learning engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized learning engine
|
||||
*/
|
||||
function createLearningEngine(config) {
|
||||
// Default configuration
|
||||
const defaultConfig = {
|
||||
defaultLearningRate: 0.001,
|
||||
batchSize: 32,
|
||||
enableGradientCheckpointing: false,
|
||||
...config,
|
||||
};
|
||||
// Implementation delegated to WASM module
|
||||
return {
|
||||
microLoraAdapt: (embedding, opType, loraConfig) => {
|
||||
// WASM call: ruvector_learning_micro_lora(embedding, opType, config)
|
||||
return new Float32Array(embedding.length);
|
||||
},
|
||||
sonaPreQuery: (dag, contextWindow = 128) => {
|
||||
// WASM call: ruvector_learning_sona_pre_query(dag, contextWindow)
|
||||
return {
|
||||
original: new Float32Array(0),
|
||||
enhanced: new Float32Array(0),
|
||||
contextVector: new Float32Array(0),
|
||||
confidence: 0,
|
||||
};
|
||||
},
|
||||
btspOneShotLearn: (pattern, signal, btspConfig) => {
|
||||
// WASM call: ruvector_learning_btsp(pattern, signal, config)
|
||||
},
|
||||
updateFromTrajectory: (trajectory, algorithm = 'ppo') => {
|
||||
// WASM call: ruvector_learning_update_trajectory(trajectory, algorithm)
|
||||
return {
|
||||
gradient: new Float32Array(0),
|
||||
loss: 0,
|
||||
entropy: 0,
|
||||
klDivergence: 0,
|
||||
};
|
||||
},
|
||||
computeAdvantages: (rewards, values, gamma = 0.99, lambda = 0.95) => {
|
||||
// WASM call: ruvector_learning_compute_gae(rewards, values, gamma, lambda)
|
||||
return new Float32Array(rewards.length);
|
||||
},
|
||||
sampleAction: (state, temperature = 1.0) => {
|
||||
// WASM call: ruvector_learning_sample_action(state, temperature)
|
||||
return { action: 0, logProb: 0 };
|
||||
},
|
||||
ewcRegularize: (taskId, importance) => {
|
||||
// WASM call: ruvector_learning_ewc(taskId, importance)
|
||||
},
|
||||
progressiveAddColumn: (taskId, hiddenSize = 256) => {
|
||||
// WASM call: ruvector_learning_progressive_add(taskId, hiddenSize)
|
||||
},
|
||||
experienceReplay: (bufferSize = 10000, batchSize = 32) => {
|
||||
// WASM call: ruvector_learning_replay(bufferSize, batchSize)
|
||||
return {
|
||||
states: [],
|
||||
actions: [],
|
||||
rewards: [],
|
||||
nextStates: [],
|
||||
dones: [],
|
||||
};
|
||||
},
|
||||
mamlInnerLoop: (supportSet, innerSteps = 5, innerLr = 0.01) => {
|
||||
// WASM call: ruvector_learning_maml_inner(supportSet, innerSteps, innerLr)
|
||||
return new Float32Array(0);
|
||||
},
|
||||
reptileUpdate: (taskBatch, epsilon = 0.1) => {
|
||||
// WASM call: ruvector_learning_reptile(taskBatch, epsilon)
|
||||
},
|
||||
getStats: () => ({
|
||||
totalSteps: 0,
|
||||
totalEpisodes: 0,
|
||||
averageReward: 0,
|
||||
averageLoss: 0,
|
||||
learningRate: defaultConfig.defaultLearningRate,
|
||||
memoryUsage: 0,
|
||||
patternsLearned: 0,
|
||||
adaptationCount: 0,
|
||||
}),
|
||||
reset: (keepWeights = false) => {
|
||||
// WASM call: ruvector_learning_reset(keepWeights)
|
||||
},
|
||||
saveCheckpoint: async (path) => {
|
||||
// WASM call: ruvector_learning_save(path)
|
||||
},
|
||||
loadCheckpoint: async (path) => {
|
||||
// WASM call: ruvector_learning_load(path)
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create Micro-LoRA configuration
|
||||
* @param rank LoRA rank (default: 8)
|
||||
* @param alpha LoRA alpha scaling (default: 16)
|
||||
* @param targetModules Modules to apply LoRA to
|
||||
*/
|
||||
function createMicroLoraConfig(rank = 8, alpha = 16, targetModules = ['attention', 'ffn']) {
|
||||
return {
|
||||
rank,
|
||||
alpha,
|
||||
dropout: 0.05,
|
||||
targetModules,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create BTSP configuration for one-shot learning
|
||||
* @param learningRate Learning rate for plasticity
|
||||
* @param eligibilityDecay Decay rate for eligibility traces
|
||||
* @param rewardWindow Time window for reward integration
|
||||
*/
|
||||
function createBtspConfig(learningRate = 0.1, eligibilityDecay = 0.95, rewardWindow = 100) {
|
||||
return {
|
||||
learningRate,
|
||||
eligibilityDecay,
|
||||
rewardWindow,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Compute cosine annealing learning rate
|
||||
* @param step Current step
|
||||
* @param totalSteps Total training steps
|
||||
* @param lrMax Maximum learning rate
|
||||
* @param lrMin Minimum learning rate
|
||||
*/
|
||||
function cosineAnnealingLr(step, totalSteps, lrMax = 0.001, lrMin = 0.00001) {
|
||||
return lrMin + 0.5 * (lrMax - lrMin) * (1 + Math.cos(Math.PI * step / totalSteps));
|
||||
}
|
||||
/**
|
||||
* Compute warmup learning rate
|
||||
* @param step Current step
|
||||
* @param warmupSteps Number of warmup steps
|
||||
* @param targetLr Target learning rate after warmup
|
||||
*/
|
||||
function warmupLr(step, warmupSteps, targetLr = 0.001) {
|
||||
if (step < warmupSteps) {
|
||||
return targetLr * (step / warmupSteps);
|
||||
}
|
||||
return targetLr;
|
||||
}
|
||||
//# sourceMappingURL=learning.js.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.js.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.js.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"learning.js","sourceRoot":"","sources":["learning.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;AAyPH,oDAuFC;AAQD,sDAWC;AAQD,4CAUC;AASD,8CAOC;AAQD,4BASC;AAtKD,+EAA+E;AAC/E,wBAAwB;AACxB,+EAA+E;AAE/E;;;;GAIG;AACH,SAAgB,oBAAoB,CAAC,MAAuB;IAC1D,wBAAwB;IACxB,MAAM,aAAa,GAAmB;QACpC,mBAAmB,EAAE,KAAK;QAC1B,SAAS,EAAE,EAAE;QACb,2BAA2B,EAAE,KAAK;QAClC,GAAG,MAAM;KACV,CAAC;IAEF,0CAA0C;IAC1C,OAAO;QACL,cAAc,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE;YAChD,qEAAqE;YACrE,OAAO,IAAI,YAAY,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QAC5C,CAAC;QACD,YAAY,EAAE,CAAC,GAAG,EAAE,aAAa,GAAG,GAAG,EAAE,EAAE;YACzC,kEAAkE;YAClE,OAAO;gBACL,QAAQ,EAAE,IAAI,YAAY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AAgB,iBAAiB,CAC/B,IAAY,EACZ,UAAkB,EAClB,QAAgB,KAAK,EACrB,QAAgB,OAAO;IAEvB,OAAO,KAAK,GAAG,GAAG,GAAG,CAAC,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,GAAG,UAAU,CAAC,CAAC,CAAC;AACrF,CAAC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CACtB,IAAY,EACZ,WAAmB,EACnB,WAAmB,KAAK;IAExB,IAAI,IAAI,GAAG,WAAW,EAAE,CAAC;QACvB,OAAO,QAAQ,GAAG,CAAC,IAAI,GAAG,WAAW,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
|
||||
416
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.ts
vendored
Normal file
416
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/learning.ts
vendored
Normal file
@@ -0,0 +1,416 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Learning Engine
|
||||
*
|
||||
* Provides adaptive learning mechanisms including:
|
||||
* - Micro-LoRA adaptation for efficient fine-tuning
|
||||
* - SONA pre-query processing for enhanced embeddings
|
||||
* - BTSP one-shot learning for rapid pattern acquisition
|
||||
* - Reinforcement learning integration
|
||||
* - Continual learning support
|
||||
*/
|
||||
|
||||
import type {
|
||||
EnhancedEmbedding,
|
||||
LearningTrajectory,
|
||||
MicroLoraConfig,
|
||||
BtspConfig,
|
||||
QueryDag,
|
||||
LearningConfig,
|
||||
} from './types';
|
||||
|
||||
// ============================================================================
|
||||
// Learning Engine Interface
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Core learning engine for adaptive model updates and pattern learning
|
||||
*/
|
||||
export interface LearningEngine {
|
||||
// -------------------------------------------------------------------------
|
||||
// Core Learning Methods
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Micro-LoRA adaptation for operation-specific fine-tuning
|
||||
* Applies low-rank updates based on operation type
|
||||
* @param embedding Input embedding to adapt
|
||||
* @param opType Operation type identifier (e.g., 'attention', 'ffn', 'norm')
|
||||
* @param config Optional LoRA configuration
|
||||
* @returns Adapted embedding with low-rank modifications
|
||||
*/
|
||||
microLoraAdapt(
|
||||
embedding: Float32Array,
|
||||
opType: string,
|
||||
config?: Partial<MicroLoraConfig>
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* SONA (Self-Organizing Neural Architecture) pre-query processing
|
||||
* Enhances embeddings before attention computation
|
||||
* @param dag Query DAG with embeddings
|
||||
* @param contextWindow Context window size
|
||||
* @returns Enhanced embedding with context
|
||||
*/
|
||||
sonaPreQuery(dag: QueryDag, contextWindow?: number): EnhancedEmbedding;
|
||||
|
||||
/**
|
||||
* BTSP (Behavioral Timescale Synaptic Plasticity) one-shot learning
|
||||
* Rapidly acquires new patterns with single exposure
|
||||
* @param pattern Pattern to learn
|
||||
* @param signal Reward/error signal for reinforcement
|
||||
* @param config Optional BTSP configuration
|
||||
*/
|
||||
btspOneShotLearn(
|
||||
pattern: Float32Array,
|
||||
signal: number,
|
||||
config?: Partial<BtspConfig>
|
||||
): void;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Reinforcement Learning
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Update policy from trajectory
|
||||
* @param trajectory Learning trajectory with states, actions, rewards
|
||||
* @param algorithm RL algorithm to use
|
||||
* @returns Policy gradient and metrics
|
||||
*/
|
||||
updateFromTrajectory(
|
||||
trajectory: LearningTrajectory,
|
||||
algorithm?: RLAlgorithm
|
||||
): PolicyUpdate;
|
||||
|
||||
/**
|
||||
* Compute advantage estimates for policy gradient
|
||||
* @param rewards Reward sequence
|
||||
* @param values Value estimates
|
||||
* @param gamma Discount factor
|
||||
* @param lambda GAE lambda parameter
|
||||
* @returns Advantage estimates
|
||||
*/
|
||||
computeAdvantages(
|
||||
rewards: Float32Array,
|
||||
values: Float32Array,
|
||||
gamma?: number,
|
||||
lambda?: number
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Get action from current policy
|
||||
* @param state Current state embedding
|
||||
* @param temperature Sampling temperature
|
||||
* @returns Action index and log probability
|
||||
*/
|
||||
sampleAction(
|
||||
state: Float32Array,
|
||||
temperature?: number
|
||||
): { action: number; logProb: number };
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Continual Learning
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Elastic weight consolidation for preventing catastrophic forgetting
|
||||
* @param taskId Current task identifier
|
||||
* @param importance Fisher information matrix diagonal
|
||||
*/
|
||||
ewcRegularize(taskId: string, importance?: Float32Array): void;
|
||||
|
||||
/**
|
||||
* Progressive neural networks - add new column for task
|
||||
* @param taskId New task identifier
|
||||
* @param hiddenSize Size of hidden layers in new column
|
||||
*/
|
||||
progressiveAddColumn(taskId: string, hiddenSize?: number): void;
|
||||
|
||||
/**
|
||||
* Experience replay for continual learning
|
||||
* @param bufferSize Maximum replay buffer size
|
||||
* @param batchSize Batch size for replay
|
||||
* @returns Replayed batch
|
||||
*/
|
||||
experienceReplay(bufferSize?: number, batchSize?: number): ReplayBatch;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Meta-Learning
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* MAML-style meta-learning inner loop
|
||||
* @param supportSet Support set for few-shot learning
|
||||
* @param innerSteps Number of inner loop steps
|
||||
* @param innerLr Inner loop learning rate
|
||||
* @returns Adapted parameters
|
||||
*/
|
||||
mamlInnerLoop(
|
||||
supportSet: TaskDataset,
|
||||
innerSteps?: number,
|
||||
innerLr?: number
|
||||
): Float32Array;
|
||||
|
||||
/**
|
||||
* Reptile meta-learning update
|
||||
* @param taskBatch Batch of tasks for meta-learning
|
||||
* @param epsilon Interpolation factor
|
||||
*/
|
||||
reptileUpdate(taskBatch: TaskDataset[], epsilon?: number): void;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Learning State Management
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get current learning statistics
|
||||
*/
|
||||
getStats(): LearningStats;
|
||||
|
||||
/**
|
||||
* Reset learning state
|
||||
* @param keepWeights Whether to keep learned weights
|
||||
*/
|
||||
reset(keepWeights?: boolean): void;
|
||||
|
||||
/**
|
||||
* Save learning checkpoint
|
||||
* @param path Checkpoint path
|
||||
*/
|
||||
saveCheckpoint(path: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Load learning checkpoint
|
||||
* @param path Checkpoint path
|
||||
*/
|
||||
loadCheckpoint(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Supporting Types
|
||||
// ============================================================================
|
||||
|
||||
/** Reinforcement learning algorithm */
|
||||
export type RLAlgorithm =
|
||||
| 'ppo'
|
||||
| 'a2c'
|
||||
| 'dqn'
|
||||
| 'sac'
|
||||
| 'td3'
|
||||
| 'reinforce';
|
||||
|
||||
/** Policy update result */
|
||||
export interface PolicyUpdate {
|
||||
gradient: Float32Array;
|
||||
loss: number;
|
||||
entropy: number;
|
||||
klDivergence: number;
|
||||
clipFraction?: number;
|
||||
}
|
||||
|
||||
/** Experience replay batch */
|
||||
export interface ReplayBatch {
|
||||
states: Float32Array[];
|
||||
actions: number[];
|
||||
rewards: number[];
|
||||
nextStates: Float32Array[];
|
||||
dones: boolean[];
|
||||
priorities?: Float32Array;
|
||||
}
|
||||
|
||||
/** Task dataset for meta-learning */
|
||||
export interface TaskDataset {
|
||||
taskId: string;
|
||||
supportInputs: Float32Array[];
|
||||
supportLabels: number[];
|
||||
queryInputs: Float32Array[];
|
||||
queryLabels: number[];
|
||||
}
|
||||
|
||||
/** Learning statistics */
|
||||
export interface LearningStats {
|
||||
totalSteps: number;
|
||||
totalEpisodes: number;
|
||||
averageReward: number;
|
||||
averageLoss: number;
|
||||
learningRate: number;
|
||||
memoryUsage: number;
|
||||
patternsLearned: number;
|
||||
adaptationCount: number;
|
||||
}
|
||||
|
||||
/** LoRA layer info */
|
||||
export interface LoraLayerInfo {
|
||||
layerName: string;
|
||||
rank: number;
|
||||
alpha: number;
|
||||
enabled: boolean;
|
||||
parameterCount: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Create a learning engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized learning engine
|
||||
*/
|
||||
export function createLearningEngine(config?: LearningConfig): LearningEngine {
|
||||
// Default configuration
|
||||
const defaultConfig: LearningConfig = {
|
||||
defaultLearningRate: 0.001,
|
||||
batchSize: 32,
|
||||
enableGradientCheckpointing: false,
|
||||
...config,
|
||||
};
|
||||
|
||||
// Implementation delegated to WASM module
|
||||
return {
|
||||
microLoraAdapt: (embedding, opType, loraConfig) => {
|
||||
// WASM call: ruvector_learning_micro_lora(embedding, opType, config)
|
||||
return new Float32Array(embedding.length);
|
||||
},
|
||||
sonaPreQuery: (dag, contextWindow = 128) => {
|
||||
// WASM call: ruvector_learning_sona_pre_query(dag, contextWindow)
|
||||
return {
|
||||
original: new Float32Array(0),
|
||||
enhanced: new Float32Array(0),
|
||||
contextVector: new Float32Array(0),
|
||||
confidence: 0,
|
||||
};
|
||||
},
|
||||
btspOneShotLearn: (pattern, signal, btspConfig) => {
|
||||
// WASM call: ruvector_learning_btsp(pattern, signal, config)
|
||||
},
|
||||
updateFromTrajectory: (trajectory, algorithm = 'ppo') => {
|
||||
// WASM call: ruvector_learning_update_trajectory(trajectory, algorithm)
|
||||
return {
|
||||
gradient: new Float32Array(0),
|
||||
loss: 0,
|
||||
entropy: 0,
|
||||
klDivergence: 0,
|
||||
};
|
||||
},
|
||||
computeAdvantages: (rewards, values, gamma = 0.99, lambda = 0.95) => {
|
||||
// WASM call: ruvector_learning_compute_gae(rewards, values, gamma, lambda)
|
||||
return new Float32Array(rewards.length);
|
||||
},
|
||||
sampleAction: (state, temperature = 1.0) => {
|
||||
// WASM call: ruvector_learning_sample_action(state, temperature)
|
||||
return { action: 0, logProb: 0 };
|
||||
},
|
||||
ewcRegularize: (taskId, importance) => {
|
||||
// WASM call: ruvector_learning_ewc(taskId, importance)
|
||||
},
|
||||
progressiveAddColumn: (taskId, hiddenSize = 256) => {
|
||||
// WASM call: ruvector_learning_progressive_add(taskId, hiddenSize)
|
||||
},
|
||||
experienceReplay: (bufferSize = 10000, batchSize = 32) => {
|
||||
// WASM call: ruvector_learning_replay(bufferSize, batchSize)
|
||||
return {
|
||||
states: [],
|
||||
actions: [],
|
||||
rewards: [],
|
||||
nextStates: [],
|
||||
dones: [],
|
||||
};
|
||||
},
|
||||
mamlInnerLoop: (supportSet, innerSteps = 5, innerLr = 0.01) => {
|
||||
// WASM call: ruvector_learning_maml_inner(supportSet, innerSteps, innerLr)
|
||||
return new Float32Array(0);
|
||||
},
|
||||
reptileUpdate: (taskBatch, epsilon = 0.1) => {
|
||||
// WASM call: ruvector_learning_reptile(taskBatch, epsilon)
|
||||
},
|
||||
getStats: () => ({
|
||||
totalSteps: 0,
|
||||
totalEpisodes: 0,
|
||||
averageReward: 0,
|
||||
averageLoss: 0,
|
||||
learningRate: defaultConfig.defaultLearningRate!,
|
||||
memoryUsage: 0,
|
||||
patternsLearned: 0,
|
||||
adaptationCount: 0,
|
||||
}),
|
||||
reset: (keepWeights = false) => {
|
||||
// WASM call: ruvector_learning_reset(keepWeights)
|
||||
},
|
||||
saveCheckpoint: async (path) => {
|
||||
// WASM call: ruvector_learning_save(path)
|
||||
},
|
||||
loadCheckpoint: async (path) => {
|
||||
// WASM call: ruvector_learning_load(path)
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Micro-LoRA configuration
|
||||
* @param rank LoRA rank (default: 8)
|
||||
* @param alpha LoRA alpha scaling (default: 16)
|
||||
* @param targetModules Modules to apply LoRA to
|
||||
*/
|
||||
export function createMicroLoraConfig(
|
||||
rank: number = 8,
|
||||
alpha: number = 16,
|
||||
targetModules: string[] = ['attention', 'ffn']
|
||||
): MicroLoraConfig {
|
||||
return {
|
||||
rank,
|
||||
alpha,
|
||||
dropout: 0.05,
|
||||
targetModules,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create BTSP configuration for one-shot learning
|
||||
* @param learningRate Learning rate for plasticity
|
||||
* @param eligibilityDecay Decay rate for eligibility traces
|
||||
* @param rewardWindow Time window for reward integration
|
||||
*/
|
||||
export function createBtspConfig(
|
||||
learningRate: number = 0.1,
|
||||
eligibilityDecay: number = 0.95,
|
||||
rewardWindow: number = 100
|
||||
): BtspConfig {
|
||||
return {
|
||||
learningRate,
|
||||
eligibilityDecay,
|
||||
rewardWindow,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute cosine annealing learning rate
|
||||
* @param step Current step
|
||||
* @param totalSteps Total training steps
|
||||
* @param lrMax Maximum learning rate
|
||||
* @param lrMin Minimum learning rate
|
||||
*/
|
||||
export function cosineAnnealingLr(
|
||||
step: number,
|
||||
totalSteps: number,
|
||||
lrMax: number = 0.001,
|
||||
lrMin: number = 0.00001
|
||||
): number {
|
||||
return lrMin + 0.5 * (lrMax - lrMin) * (1 + Math.cos(Math.PI * step / totalSteps));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute warmup learning rate
|
||||
* @param step Current step
|
||||
* @param warmupSteps Number of warmup steps
|
||||
* @param targetLr Target learning rate after warmup
|
||||
*/
|
||||
export function warmupLr(
|
||||
step: number,
|
||||
warmupSteps: number,
|
||||
targetLr: number = 0.001
|
||||
): number {
|
||||
if (step < warmupSteps) {
|
||||
return targetLr * (step / warmupSteps);
|
||||
}
|
||||
return targetLr;
|
||||
}
|
||||
274
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.d.ts
vendored
Normal file
274
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.d.ts
vendored
Normal file
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Nervous System Engine
|
||||
*
|
||||
* Provides biological neural network simulation including:
|
||||
* - Spiking neural networks (SNN)
|
||||
* - Synaptic plasticity rules (STDP, BTSP, Hebbian)
|
||||
* - Neuron dynamics (LIF, Izhikevich, Hodgkin-Huxley)
|
||||
* - Network topology management
|
||||
* - Signal propagation
|
||||
*/
|
||||
import type { Neuron, Synapse, PlasticityRule, NervousState, PropagationResult, NervousConfig } from './types';
|
||||
/**
|
||||
* Core nervous system engine for biological neural network simulation
|
||||
*/
|
||||
export interface NervousEngine {
|
||||
/**
|
||||
* Create a new neuron in the network
|
||||
* @param config Neuron configuration
|
||||
* @returns Neuron ID
|
||||
*/
|
||||
createNeuron(config: NeuronConfig): string;
|
||||
/**
|
||||
* Remove a neuron from the network
|
||||
* @param neuronId Neuron to remove
|
||||
*/
|
||||
removeNeuron(neuronId: string): void;
|
||||
/**
|
||||
* Get neuron by ID
|
||||
* @param neuronId Neuron ID
|
||||
* @returns Neuron state
|
||||
*/
|
||||
getNeuron(neuronId: string): Neuron | undefined;
|
||||
/**
|
||||
* Update neuron parameters
|
||||
* @param neuronId Neuron to update
|
||||
* @param params New parameters
|
||||
*/
|
||||
updateNeuron(neuronId: string, params: Partial<NeuronConfig>): void;
|
||||
/**
|
||||
* List all neurons
|
||||
* @param filter Optional filter criteria
|
||||
* @returns Array of neurons
|
||||
*/
|
||||
listNeurons(filter?: NeuronFilter): Neuron[];
|
||||
/**
|
||||
* Create a synapse between neurons
|
||||
* @param presynapticId Source neuron
|
||||
* @param postsynapticId Target neuron
|
||||
* @param config Synapse configuration
|
||||
* @returns Synapse ID
|
||||
*/
|
||||
createSynapse(presynapticId: string, postsynapticId: string, config?: SynapseConfig): string;
|
||||
/**
|
||||
* Remove a synapse
|
||||
* @param presynapticId Source neuron
|
||||
* @param postsynapticId Target neuron
|
||||
*/
|
||||
removeSynapse(presynapticId: string, postsynapticId: string): void;
|
||||
/**
|
||||
* Get synapse between neurons
|
||||
* @param presynapticId Source neuron
|
||||
* @param postsynapticId Target neuron
|
||||
* @returns Synapse or undefined
|
||||
*/
|
||||
getSynapse(presynapticId: string, postsynapticId: string): Synapse | undefined;
|
||||
/**
|
||||
* Update synapse parameters
|
||||
* @param presynapticId Source neuron
|
||||
* @param postsynapticId Target neuron
|
||||
* @param params New parameters
|
||||
*/
|
||||
updateSynapse(presynapticId: string, postsynapticId: string, params: Partial<SynapseConfig>): void;
|
||||
/**
|
||||
* List synapses for a neuron
|
||||
* @param neuronId Neuron ID
|
||||
* @param direction 'incoming' | 'outgoing' | 'both'
|
||||
* @returns Array of synapses
|
||||
*/
|
||||
listSynapses(neuronId: string, direction?: 'incoming' | 'outgoing' | 'both'): Synapse[];
|
||||
/**
|
||||
* Step the simulation forward
|
||||
* @param dt Time step in milliseconds
|
||||
* @returns Simulation result
|
||||
*/
|
||||
step(dt?: number): SimulationResult;
|
||||
/**
|
||||
* Inject current into neurons
|
||||
* @param injections Map of neuron ID to current value
|
||||
*/
|
||||
injectCurrent(injections: Map<string, number>): void;
|
||||
/**
|
||||
* Propagate signal through network
|
||||
* @param sourceIds Source neuron IDs
|
||||
* @param signal Signal strength
|
||||
* @returns Propagation result
|
||||
*/
|
||||
propagate(sourceIds: string[], signal: number): PropagationResult;
|
||||
/**
|
||||
* Get current network state
|
||||
* @returns Complete nervous system state
|
||||
*/
|
||||
getState(): NervousState;
|
||||
/**
|
||||
* Set network state
|
||||
* @param state State to restore
|
||||
*/
|
||||
setState(state: NervousState): void;
|
||||
/**
|
||||
* Reset network to initial state
|
||||
* @param keepTopology Keep neurons and synapses, reset potentials
|
||||
*/
|
||||
reset(keepTopology?: boolean): void;
|
||||
/**
|
||||
* Apply plasticity rule to all synapses
|
||||
* @param rule Plasticity rule to apply
|
||||
* @param learningRate Global learning rate modifier
|
||||
*/
|
||||
applyPlasticity(rule?: PlasticityRule, learningRate?: number): void;
|
||||
/**
|
||||
* Apply STDP (Spike-Timing Dependent Plasticity)
|
||||
* @param config STDP configuration
|
||||
*/
|
||||
applyStdp(config?: StdpConfig): void;
|
||||
/**
|
||||
* Apply homeostatic plasticity
|
||||
* @param targetRate Target firing rate
|
||||
*/
|
||||
applyHomeostasis(targetRate?: number): void;
|
||||
/**
|
||||
* Get plasticity statistics
|
||||
* @returns Plasticity metrics
|
||||
*/
|
||||
getPlasticityStats(): PlasticityStats;
|
||||
/**
|
||||
* Create a feedforward network
|
||||
* @param layerSizes Neurons per layer
|
||||
* @param connectivity Connection probability between layers
|
||||
*/
|
||||
createFeedforward(layerSizes: number[], connectivity?: number): void;
|
||||
/**
|
||||
* Create a recurrent network
|
||||
* @param size Number of neurons
|
||||
* @param connectivity Recurrent connection probability
|
||||
*/
|
||||
createRecurrent(size: number, connectivity?: number): void;
|
||||
/**
|
||||
* Create a reservoir network (Echo State Network style)
|
||||
* @param size Reservoir size
|
||||
* @param spectralRadius Target spectral radius
|
||||
* @param inputSize Number of input neurons
|
||||
*/
|
||||
createReservoir(size: number, spectralRadius?: number, inputSize?: number): void;
|
||||
/**
|
||||
* Create small-world network topology
|
||||
* @param size Number of neurons
|
||||
* @param k Number of nearest neighbors
|
||||
* @param beta Rewiring probability
|
||||
*/
|
||||
createSmallWorld(size: number, k?: number, beta?: number): void;
|
||||
/**
|
||||
* Get network statistics
|
||||
* @returns Topology metrics
|
||||
*/
|
||||
getTopologyStats(): TopologyStats;
|
||||
/**
|
||||
* Start recording neuron activity
|
||||
* @param neuronIds Neurons to record (empty = all)
|
||||
*/
|
||||
startRecording(neuronIds?: string[]): void;
|
||||
/**
|
||||
* Stop recording
|
||||
* @returns Recorded activity
|
||||
*/
|
||||
stopRecording(): RecordedActivity;
|
||||
/**
|
||||
* Get spike raster
|
||||
* @param startTime Start time
|
||||
* @param endTime End time
|
||||
* @returns Spike times per neuron
|
||||
*/
|
||||
getSpikeRaster(startTime?: number, endTime?: number): Map<string, number[]>;
|
||||
}
|
||||
/** Neuron configuration */
|
||||
export interface NeuronConfig {
|
||||
id?: string;
|
||||
neuronType?: 'excitatory' | 'inhibitory' | 'modulatory';
|
||||
model?: NeuronModel;
|
||||
threshold?: number;
|
||||
restPotential?: number;
|
||||
resetPotential?: number;
|
||||
refractoryPeriod?: number;
|
||||
leakConductance?: number;
|
||||
capacitance?: number;
|
||||
}
|
||||
/** Neuron model type */
|
||||
export type NeuronModel = 'lif' | 'izhikevich' | 'hh' | 'adex' | 'srm' | 'if';
|
||||
/** Synapse configuration */
|
||||
export interface SynapseConfig {
|
||||
weight?: number;
|
||||
delay?: number;
|
||||
plasticity?: PlasticityRule;
|
||||
synapseType?: 'ampa' | 'nmda' | 'gaba_a' | 'gaba_b' | 'generic';
|
||||
timeConstant?: number;
|
||||
}
|
||||
/** STDP configuration */
|
||||
export interface StdpConfig {
|
||||
tauPlus: number;
|
||||
tauMinus: number;
|
||||
aPlus: number;
|
||||
aMinus: number;
|
||||
wMax: number;
|
||||
wMin: number;
|
||||
}
|
||||
/** Neuron filter criteria */
|
||||
export interface NeuronFilter {
|
||||
type?: 'excitatory' | 'inhibitory' | 'modulatory';
|
||||
model?: NeuronModel;
|
||||
minPotential?: number;
|
||||
maxPotential?: number;
|
||||
isActive?: boolean;
|
||||
}
|
||||
/** Simulation result */
|
||||
export interface SimulationResult {
|
||||
timestep: number;
|
||||
spikes: string[];
|
||||
averagePotential: number;
|
||||
averageFiringRate: number;
|
||||
energyConsumed: number;
|
||||
}
|
||||
/** Plasticity statistics */
|
||||
export interface PlasticityStats {
|
||||
averageWeightChange: number;
|
||||
potentiationCount: number;
|
||||
depressionCount: number;
|
||||
synapsesPruned: number;
|
||||
synapsesCreated: number;
|
||||
}
|
||||
/** Topology statistics */
|
||||
export interface TopologyStats {
|
||||
neuronCount: number;
|
||||
synapseCount: number;
|
||||
averageConnectivity: number;
|
||||
clusteringCoefficient: number;
|
||||
averagePathLength: number;
|
||||
spectralRadius: number;
|
||||
}
|
||||
/** Recorded neural activity */
|
||||
export interface RecordedActivity {
|
||||
duration: number;
|
||||
neuronIds: string[];
|
||||
potentials: Float32Array[];
|
||||
spikeTimes: Map<string, number[]>;
|
||||
samplingRate: number;
|
||||
}
|
||||
/**
|
||||
* Create a nervous system engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized nervous engine
|
||||
*/
|
||||
export declare function createNervousEngine(config?: NervousConfig): NervousEngine;
|
||||
/**
|
||||
* Create default STDP configuration
|
||||
*/
|
||||
export declare function createStdpConfig(): StdpConfig;
|
||||
/**
|
||||
* Create Izhikevich neuron parameters for different types
|
||||
*/
|
||||
export declare function izhikevichParams(type: 'regular' | 'bursting' | 'chattering' | 'fast'): {
|
||||
a: number;
|
||||
b: number;
|
||||
c: number;
|
||||
d: number;
|
||||
};
|
||||
//# sourceMappingURL=nervous.d.ts.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.d.ts.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.d.ts.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"nervous.d.ts","sourceRoot":"","sources":["nervous.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EACV,MAAM,EACN,OAAO,EACP,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,aAAa,EACd,MAAM,SAAS,CAAC;AAMjB;;GAEG;AACH,MAAM,WAAW,aAAa;IAK5B;;;;OAIG;IACH,YAAY,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAAC;IAE3C;;;OAGG;IACH,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IAErC;;;;OAIG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IAEhD;;;;OAIG;IACH,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC;IAEpE;;;;OAIG;IACH,WAAW,CAAC,MAAM,CAAC,EAAE,YAAY,GAAG,MAAM,EAAE,CAAC;IAM7C;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C5B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,eAAe,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,MAAM,CAAC;CACzB;AAED,0BAA0B;AAC1B,MAAM,WAAW,aAAa;IAC5B,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,+BAA+B;AAC/B,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,UAAU,EAAE,YAAY,EAAE,CAAC;IAC3B,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAClC,YAAY,EAAE,MAAM,CAAC;CACtB;AAMD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,CAAC,EAAE,aAAa,GAAG,aAAa,CAsLzE;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,UAAU,CAS7C;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,SAAS,GAAG,UAAU,GAAG,YAAY,GAAG,MAAM,GAAG;IACtF,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;CACX,CAQA"}
|
||||
228
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.js
vendored
Normal file
228
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.js
vendored
Normal file
@@ -0,0 +1,228 @@
|
||||
"use strict";
|
||||
/**
|
||||
* RuVector WASM Unified - Nervous System Engine
|
||||
*
|
||||
* Provides biological neural network simulation including:
|
||||
* - Spiking neural networks (SNN)
|
||||
* - Synaptic plasticity rules (STDP, BTSP, Hebbian)
|
||||
* - Neuron dynamics (LIF, Izhikevich, Hodgkin-Huxley)
|
||||
* - Network topology management
|
||||
* - Signal propagation
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createNervousEngine = createNervousEngine;
|
||||
exports.createStdpConfig = createStdpConfig;
|
||||
exports.izhikevichParams = izhikevichParams;
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
/**
|
||||
* Create a nervous system engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized nervous engine
|
||||
*/
|
||||
function createNervousEngine(config) {
|
||||
const defaultConfig = {
|
||||
maxNeurons: 10000,
|
||||
simulationDt: 0.1,
|
||||
enablePlasticity: true,
|
||||
...config,
|
||||
};
|
||||
// Internal state
|
||||
const neurons = new Map();
|
||||
const synapses = [];
|
||||
let neuronIdCounter = 0;
|
||||
let currentTime = 0;
|
||||
return {
|
||||
createNeuron: (neuronConfig) => {
|
||||
const id = neuronConfig.id || `neuron_${neuronIdCounter++}`;
|
||||
const neuron = {
|
||||
id,
|
||||
potential: neuronConfig.restPotential ?? -70,
|
||||
threshold: neuronConfig.threshold ?? -55,
|
||||
refractory: 0,
|
||||
neuronType: neuronConfig.neuronType ?? 'excitatory',
|
||||
};
|
||||
neurons.set(id, neuron);
|
||||
return id;
|
||||
},
|
||||
removeNeuron: (neuronId) => {
|
||||
neurons.delete(neuronId);
|
||||
},
|
||||
getNeuron: (neuronId) => neurons.get(neuronId),
|
||||
updateNeuron: (neuronId, params) => {
|
||||
const neuron = neurons.get(neuronId);
|
||||
if (neuron) {
|
||||
Object.assign(neuron, params);
|
||||
}
|
||||
},
|
||||
listNeurons: (filter) => {
|
||||
let result = Array.from(neurons.values());
|
||||
if (filter) {
|
||||
if (filter.type) {
|
||||
result = result.filter(n => n.neuronType === filter.type);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
createSynapse: (presynapticId, postsynapticId, synapseConfig) => {
|
||||
const synapse = {
|
||||
presynapticId,
|
||||
postsynapticId,
|
||||
weight: synapseConfig?.weight ?? 1.0,
|
||||
delay: synapseConfig?.delay ?? 1.0,
|
||||
plasticity: synapseConfig?.plasticity ?? { type: 'stdp', params: {} },
|
||||
};
|
||||
synapses.push(synapse);
|
||||
return `${presynapticId}->${postsynapticId}`;
|
||||
},
|
||||
removeSynapse: (presynapticId, postsynapticId) => {
|
||||
const idx = synapses.findIndex(s => s.presynapticId === presynapticId && s.postsynapticId === postsynapticId);
|
||||
if (idx >= 0)
|
||||
synapses.splice(idx, 1);
|
||||
},
|
||||
getSynapse: (presynapticId, postsynapticId) => {
|
||||
return synapses.find(s => s.presynapticId === presynapticId && s.postsynapticId === postsynapticId);
|
||||
},
|
||||
updateSynapse: (presynapticId, postsynapticId, params) => {
|
||||
const synapse = synapses.find(s => s.presynapticId === presynapticId && s.postsynapticId === postsynapticId);
|
||||
if (synapse) {
|
||||
Object.assign(synapse, params);
|
||||
}
|
||||
},
|
||||
listSynapses: (neuronId, direction = 'both') => {
|
||||
return synapses.filter(s => {
|
||||
if (direction === 'outgoing')
|
||||
return s.presynapticId === neuronId;
|
||||
if (direction === 'incoming')
|
||||
return s.postsynapticId === neuronId;
|
||||
return s.presynapticId === neuronId || s.postsynapticId === neuronId;
|
||||
});
|
||||
},
|
||||
step: (dt = defaultConfig.simulationDt) => {
|
||||
currentTime += dt;
|
||||
const spikes = [];
|
||||
// Placeholder: actual simulation delegated to WASM
|
||||
return {
|
||||
timestep: currentTime,
|
||||
spikes,
|
||||
averagePotential: 0,
|
||||
averageFiringRate: 0,
|
||||
energyConsumed: 0,
|
||||
};
|
||||
},
|
||||
injectCurrent: (injections) => {
|
||||
// WASM call: ruvector_nervous_inject(injections)
|
||||
},
|
||||
propagate: (sourceIds, signal) => {
|
||||
// WASM call: ruvector_nervous_propagate(sourceIds, signal)
|
||||
return {
|
||||
activatedNeurons: [],
|
||||
spikeTimings: new Map(),
|
||||
totalActivity: 0,
|
||||
};
|
||||
},
|
||||
getState: () => ({
|
||||
neurons,
|
||||
synapses,
|
||||
globalModulation: 1.0,
|
||||
timestamp: currentTime,
|
||||
}),
|
||||
setState: (state) => {
|
||||
neurons.clear();
|
||||
state.neurons.forEach((v, k) => neurons.set(k, v));
|
||||
synapses.length = 0;
|
||||
synapses.push(...state.synapses);
|
||||
currentTime = state.timestamp;
|
||||
},
|
||||
reset: (keepTopology = false) => {
|
||||
if (!keepTopology) {
|
||||
neurons.clear();
|
||||
synapses.length = 0;
|
||||
}
|
||||
else {
|
||||
neurons.forEach(n => {
|
||||
n.potential = -70;
|
||||
n.refractory = 0;
|
||||
});
|
||||
}
|
||||
currentTime = 0;
|
||||
},
|
||||
applyPlasticity: (rule, learningRate = 1.0) => {
|
||||
// WASM call: ruvector_nervous_plasticity(rule, learningRate)
|
||||
},
|
||||
applyStdp: (stdpConfig) => {
|
||||
// WASM call: ruvector_nervous_stdp(config)
|
||||
},
|
||||
applyHomeostasis: (targetRate = 10) => {
|
||||
// WASM call: ruvector_nervous_homeostasis(targetRate)
|
||||
},
|
||||
getPlasticityStats: () => ({
|
||||
averageWeightChange: 0,
|
||||
potentiationCount: 0,
|
||||
depressionCount: 0,
|
||||
synapsesPruned: 0,
|
||||
synapsesCreated: 0,
|
||||
}),
|
||||
createFeedforward: (layerSizes, connectivity = 1.0) => {
|
||||
// WASM call: ruvector_nervous_create_feedforward(layerSizes, connectivity)
|
||||
},
|
||||
createRecurrent: (size, connectivity = 0.1) => {
|
||||
// WASM call: ruvector_nervous_create_recurrent(size, connectivity)
|
||||
},
|
||||
createReservoir: (size, spectralRadius = 0.9, inputSize = 10) => {
|
||||
// WASM call: ruvector_nervous_create_reservoir(size, spectralRadius, inputSize)
|
||||
},
|
||||
createSmallWorld: (size, k = 4, beta = 0.1) => {
|
||||
// WASM call: ruvector_nervous_create_small_world(size, k, beta)
|
||||
},
|
||||
getTopologyStats: () => ({
|
||||
neuronCount: neurons.size,
|
||||
synapseCount: synapses.length,
|
||||
averageConnectivity: neurons.size > 0 ? synapses.length / neurons.size : 0,
|
||||
clusteringCoefficient: 0,
|
||||
averagePathLength: 0,
|
||||
spectralRadius: 0,
|
||||
}),
|
||||
startRecording: (neuronIds) => {
|
||||
// WASM call: ruvector_nervous_start_recording(neuronIds)
|
||||
},
|
||||
stopRecording: () => ({
|
||||
duration: 0,
|
||||
neuronIds: [],
|
||||
potentials: [],
|
||||
spikeTimes: new Map(),
|
||||
samplingRate: 1000,
|
||||
}),
|
||||
getSpikeRaster: (startTime = 0, endTime = currentTime) => {
|
||||
// WASM call: ruvector_nervous_get_raster(startTime, endTime)
|
||||
return new Map();
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create default STDP configuration
|
||||
*/
|
||||
function createStdpConfig() {
|
||||
return {
|
||||
tauPlus: 20,
|
||||
tauMinus: 20,
|
||||
aPlus: 0.01,
|
||||
aMinus: 0.012,
|
||||
wMax: 1.0,
|
||||
wMin: 0.0,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create Izhikevich neuron parameters for different types
|
||||
*/
|
||||
function izhikevichParams(type) {
|
||||
const params = {
|
||||
regular: { a: 0.02, b: 0.2, c: -65, d: 8 },
|
||||
bursting: { a: 0.02, b: 0.2, c: -50, d: 2 },
|
||||
chattering: { a: 0.02, b: 0.2, c: -50, d: 2 },
|
||||
fast: { a: 0.1, b: 0.2, c: -65, d: 2 },
|
||||
};
|
||||
return params[type];
|
||||
}
|
||||
//# sourceMappingURL=nervous.js.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.js.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
570
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.ts
vendored
Normal file
570
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/nervous.ts
vendored
Normal file
@@ -0,0 +1,570 @@
|
||||
/**
|
||||
* RuVector WASM Unified - Nervous System Engine
|
||||
*
|
||||
* Provides biological neural network simulation including:
|
||||
* - Spiking neural networks (SNN)
|
||||
* - Synaptic plasticity rules (STDP, BTSP, Hebbian)
|
||||
* - Neuron dynamics (LIF, Izhikevich, Hodgkin-Huxley)
|
||||
* - Network topology management
|
||||
* - Signal propagation
|
||||
*/
|
||||
|
||||
import type {
|
||||
Neuron,
|
||||
Synapse,
|
||||
PlasticityRule,
|
||||
NervousState,
|
||||
PropagationResult,
|
||||
NervousConfig,
|
||||
} from './types';
|
||||
|
||||
// ============================================================================
|
||||
// Nervous System Engine Interface
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Core nervous system engine for biological neural network simulation
|
||||
*/
|
||||
export interface NervousEngine {
|
||||
// -------------------------------------------------------------------------
|
||||
// Neuron Management
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a new neuron in the network
|
||||
* @param config Neuron configuration
|
||||
* @returns Neuron ID
|
||||
*/
|
||||
createNeuron(config: NeuronConfig): string;
|
||||
|
||||
/**
|
||||
* Remove a neuron from the network
|
||||
* @param neuronId Neuron to remove
|
||||
*/
|
||||
removeNeuron(neuronId: string): void;
|
||||
|
||||
/**
|
||||
* Get neuron by ID
|
||||
* @param neuronId Neuron ID
|
||||
* @returns Neuron state
|
||||
*/
|
||||
getNeuron(neuronId: string): Neuron | undefined;
|
||||
|
||||
/**
|
||||
* Update neuron parameters
|
||||
* @param neuronId Neuron to update
|
||||
* @param params New parameters
|
||||
*/
|
||||
updateNeuron(neuronId: string, params: Partial<NeuronConfig>): void;
|
||||
|
||||
/**
|
||||
* List all neurons
|
||||
* @param filter Optional filter criteria
|
||||
* @returns Array of neurons
|
||||
*/
|
||||
listNeurons(filter?: NeuronFilter): Neuron[];
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Synapse Management
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a synapse between neurons
|
||||
* @param presynapticId Source neuron
|
||||
* @param postsynapticId Target neuron
|
||||
* @param config Synapse configuration
|
||||
* @returns Synapse ID
|
||||
*/
|
||||
createSynapse(
|
||||
presynapticId: string,
|
||||
postsynapticId: string,
|
||||
config?: SynapseConfig
|
||||
): string;
|
||||
|
||||
/**
|
||||
* Remove a synapse
|
||||
* @param presynapticId Source neuron
|
||||
* @param postsynapticId Target neuron
|
||||
*/
|
||||
removeSynapse(presynapticId: string, postsynapticId: string): void;
|
||||
|
||||
/**
|
||||
* Get synapse between neurons
|
||||
* @param presynapticId Source neuron
|
||||
* @param postsynapticId Target neuron
|
||||
* @returns Synapse or undefined
|
||||
*/
|
||||
getSynapse(presynapticId: string, postsynapticId: string): Synapse | undefined;
|
||||
|
||||
/**
|
||||
* Update synapse parameters
|
||||
* @param presynapticId Source neuron
|
||||
* @param postsynapticId Target neuron
|
||||
* @param params New parameters
|
||||
*/
|
||||
updateSynapse(
|
||||
presynapticId: string,
|
||||
postsynapticId: string,
|
||||
params: Partial<SynapseConfig>
|
||||
): void;
|
||||
|
||||
/**
|
||||
* List synapses for a neuron
|
||||
* @param neuronId Neuron ID
|
||||
* @param direction 'incoming' | 'outgoing' | 'both'
|
||||
* @returns Array of synapses
|
||||
*/
|
||||
listSynapses(neuronId: string, direction?: 'incoming' | 'outgoing' | 'both'): Synapse[];
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Simulation
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Step the simulation forward
|
||||
* @param dt Time step in milliseconds
|
||||
* @returns Simulation result
|
||||
*/
|
||||
step(dt?: number): SimulationResult;
|
||||
|
||||
/**
|
||||
* Inject current into neurons
|
||||
* @param injections Map of neuron ID to current value
|
||||
*/
|
||||
injectCurrent(injections: Map<string, number>): void;
|
||||
|
||||
/**
|
||||
* Propagate signal through network
|
||||
* @param sourceIds Source neuron IDs
|
||||
* @param signal Signal strength
|
||||
* @returns Propagation result
|
||||
*/
|
||||
propagate(sourceIds: string[], signal: number): PropagationResult;
|
||||
|
||||
/**
|
||||
* Get current network state
|
||||
* @returns Complete nervous system state
|
||||
*/
|
||||
getState(): NervousState;
|
||||
|
||||
/**
|
||||
* Set network state
|
||||
* @param state State to restore
|
||||
*/
|
||||
setState(state: NervousState): void;
|
||||
|
||||
/**
|
||||
* Reset network to initial state
|
||||
* @param keepTopology Keep neurons and synapses, reset potentials
|
||||
*/
|
||||
reset(keepTopology?: boolean): void;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Plasticity
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Apply plasticity rule to all synapses
|
||||
* @param rule Plasticity rule to apply
|
||||
* @param learningRate Global learning rate modifier
|
||||
*/
|
||||
applyPlasticity(rule?: PlasticityRule, learningRate?: number): void;
|
||||
|
||||
/**
|
||||
* Apply STDP (Spike-Timing Dependent Plasticity)
|
||||
* @param config STDP configuration
|
||||
*/
|
||||
applyStdp(config?: StdpConfig): void;
|
||||
|
||||
/**
|
||||
* Apply homeostatic plasticity
|
||||
* @param targetRate Target firing rate
|
||||
*/
|
||||
applyHomeostasis(targetRate?: number): void;
|
||||
|
||||
/**
|
||||
* Get plasticity statistics
|
||||
* @returns Plasticity metrics
|
||||
*/
|
||||
getPlasticityStats(): PlasticityStats;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Topology
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a feedforward network
|
||||
* @param layerSizes Neurons per layer
|
||||
* @param connectivity Connection probability between layers
|
||||
*/
|
||||
createFeedforward(layerSizes: number[], connectivity?: number): void;
|
||||
|
||||
/**
|
||||
* Create a recurrent network
|
||||
* @param size Number of neurons
|
||||
* @param connectivity Recurrent connection probability
|
||||
*/
|
||||
createRecurrent(size: number, connectivity?: number): void;
|
||||
|
||||
/**
|
||||
* Create a reservoir network (Echo State Network style)
|
||||
* @param size Reservoir size
|
||||
* @param spectralRadius Target spectral radius
|
||||
* @param inputSize Number of input neurons
|
||||
*/
|
||||
createReservoir(size: number, spectralRadius?: number, inputSize?: number): void;
|
||||
|
||||
/**
|
||||
* Create small-world network topology
|
||||
* @param size Number of neurons
|
||||
* @param k Number of nearest neighbors
|
||||
* @param beta Rewiring probability
|
||||
*/
|
||||
createSmallWorld(size: number, k?: number, beta?: number): void;
|
||||
|
||||
/**
|
||||
* Get network statistics
|
||||
* @returns Topology metrics
|
||||
*/
|
||||
getTopologyStats(): TopologyStats;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Recording
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Start recording neuron activity
|
||||
* @param neuronIds Neurons to record (empty = all)
|
||||
*/
|
||||
startRecording(neuronIds?: string[]): void;
|
||||
|
||||
/**
|
||||
* Stop recording
|
||||
* @returns Recorded activity
|
||||
*/
|
||||
stopRecording(): RecordedActivity;
|
||||
|
||||
/**
|
||||
* Get spike raster
|
||||
* @param startTime Start time
|
||||
* @param endTime End time
|
||||
* @returns Spike times per neuron
|
||||
*/
|
||||
getSpikeRaster(startTime?: number, endTime?: number): Map<string, number[]>;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Supporting Types
|
||||
// ============================================================================
|
||||
|
||||
/** Neuron configuration */
|
||||
export interface NeuronConfig {
|
||||
id?: string;
|
||||
neuronType?: 'excitatory' | 'inhibitory' | 'modulatory';
|
||||
model?: NeuronModel;
|
||||
threshold?: number;
|
||||
restPotential?: number;
|
||||
resetPotential?: number;
|
||||
refractoryPeriod?: number;
|
||||
leakConductance?: number;
|
||||
capacitance?: number;
|
||||
}
|
||||
|
||||
/** Neuron model type */
|
||||
export type NeuronModel =
|
||||
| 'lif' // Leaky Integrate-and-Fire
|
||||
| 'izhikevich' // Izhikevich model
|
||||
| 'hh' // Hodgkin-Huxley
|
||||
| 'adex' // Adaptive Exponential
|
||||
| 'srm' // Spike Response Model
|
||||
| 'if'; // Integrate-and-Fire
|
||||
|
||||
/** Synapse configuration */
|
||||
export interface SynapseConfig {
|
||||
weight?: number;
|
||||
delay?: number;
|
||||
plasticity?: PlasticityRule;
|
||||
synapseType?: 'ampa' | 'nmda' | 'gaba_a' | 'gaba_b' | 'generic';
|
||||
timeConstant?: number;
|
||||
}
|
||||
|
||||
/** STDP configuration */
|
||||
export interface StdpConfig {
|
||||
tauPlus: number; // Time constant for potentiation
|
||||
tauMinus: number; // Time constant for depression
|
||||
aPlus: number; // Amplitude for potentiation
|
||||
aMinus: number; // Amplitude for depression
|
||||
wMax: number; // Maximum weight
|
||||
wMin: number; // Minimum weight
|
||||
}
|
||||
|
||||
/** Neuron filter criteria */
|
||||
export interface NeuronFilter {
|
||||
type?: 'excitatory' | 'inhibitory' | 'modulatory';
|
||||
model?: NeuronModel;
|
||||
minPotential?: number;
|
||||
maxPotential?: number;
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
/** Simulation result */
|
||||
export interface SimulationResult {
|
||||
timestep: number;
|
||||
spikes: string[]; // IDs of neurons that spiked
|
||||
averagePotential: number;
|
||||
averageFiringRate: number;
|
||||
energyConsumed: number;
|
||||
}
|
||||
|
||||
/** Plasticity statistics */
|
||||
export interface PlasticityStats {
|
||||
averageWeightChange: number;
|
||||
potentiationCount: number;
|
||||
depressionCount: number;
|
||||
synapsesPruned: number;
|
||||
synapsesCreated: number;
|
||||
}
|
||||
|
||||
/** Topology statistics */
|
||||
export interface TopologyStats {
|
||||
neuronCount: number;
|
||||
synapseCount: number;
|
||||
averageConnectivity: number;
|
||||
clusteringCoefficient: number;
|
||||
averagePathLength: number;
|
||||
spectralRadius: number;
|
||||
}
|
||||
|
||||
/** Recorded neural activity */
|
||||
export interface RecordedActivity {
|
||||
duration: number;
|
||||
neuronIds: string[];
|
||||
potentials: Float32Array[]; // Time series per neuron
|
||||
spikeTimes: Map<string, number[]>;
|
||||
samplingRate: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Factory and Utilities
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Create a nervous system engine instance
|
||||
* @param config Optional configuration
|
||||
* @returns Initialized nervous engine
|
||||
*/
|
||||
export function createNervousEngine(config?: NervousConfig): NervousEngine {
|
||||
const defaultConfig: NervousConfig = {
|
||||
maxNeurons: 10000,
|
||||
simulationDt: 0.1,
|
||||
enablePlasticity: true,
|
||||
...config,
|
||||
};
|
||||
|
||||
// Internal state
|
||||
const neurons = new Map<string, Neuron>();
|
||||
const synapses: Synapse[] = [];
|
||||
let neuronIdCounter = 0;
|
||||
let currentTime = 0;
|
||||
|
||||
return {
|
||||
createNeuron: (neuronConfig) => {
|
||||
const id = neuronConfig.id || `neuron_${neuronIdCounter++}`;
|
||||
const neuron: Neuron = {
|
||||
id,
|
||||
potential: neuronConfig.restPotential ?? -70,
|
||||
threshold: neuronConfig.threshold ?? -55,
|
||||
refractory: 0,
|
||||
neuronType: neuronConfig.neuronType ?? 'excitatory',
|
||||
};
|
||||
neurons.set(id, neuron);
|
||||
return id;
|
||||
},
|
||||
removeNeuron: (neuronId) => {
|
||||
neurons.delete(neuronId);
|
||||
},
|
||||
getNeuron: (neuronId) => neurons.get(neuronId),
|
||||
updateNeuron: (neuronId, params) => {
|
||||
const neuron = neurons.get(neuronId);
|
||||
if (neuron) {
|
||||
Object.assign(neuron, params);
|
||||
}
|
||||
},
|
||||
listNeurons: (filter) => {
|
||||
let result = Array.from(neurons.values());
|
||||
if (filter) {
|
||||
if (filter.type) {
|
||||
result = result.filter(n => n.neuronType === filter.type);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
createSynapse: (presynapticId, postsynapticId, synapseConfig) => {
|
||||
const synapse: Synapse = {
|
||||
presynapticId,
|
||||
postsynapticId,
|
||||
weight: synapseConfig?.weight ?? 1.0,
|
||||
delay: synapseConfig?.delay ?? 1.0,
|
||||
plasticity: synapseConfig?.plasticity ?? { type: 'stdp', params: {} },
|
||||
};
|
||||
synapses.push(synapse);
|
||||
return `${presynapticId}->${postsynapticId}`;
|
||||
},
|
||||
removeSynapse: (presynapticId, postsynapticId) => {
|
||||
const idx = synapses.findIndex(
|
||||
s => s.presynapticId === presynapticId && s.postsynapticId === postsynapticId
|
||||
);
|
||||
if (idx >= 0) synapses.splice(idx, 1);
|
||||
},
|
||||
getSynapse: (presynapticId, postsynapticId) => {
|
||||
return synapses.find(
|
||||
s => s.presynapticId === presynapticId && s.postsynapticId === postsynapticId
|
||||
);
|
||||
},
|
||||
updateSynapse: (presynapticId, postsynapticId, params) => {
|
||||
const synapse = synapses.find(
|
||||
s => s.presynapticId === presynapticId && s.postsynapticId === postsynapticId
|
||||
);
|
||||
if (synapse) {
|
||||
Object.assign(synapse, params);
|
||||
}
|
||||
},
|
||||
listSynapses: (neuronId, direction = 'both') => {
|
||||
return synapses.filter(s => {
|
||||
if (direction === 'outgoing') return s.presynapticId === neuronId;
|
||||
if (direction === 'incoming') return s.postsynapticId === neuronId;
|
||||
return s.presynapticId === neuronId || s.postsynapticId === neuronId;
|
||||
});
|
||||
},
|
||||
step: (dt = defaultConfig.simulationDt!) => {
|
||||
currentTime += dt;
|
||||
const spikes: string[] = [];
|
||||
// Placeholder: actual simulation delegated to WASM
|
||||
return {
|
||||
timestep: currentTime,
|
||||
spikes,
|
||||
averagePotential: 0,
|
||||
averageFiringRate: 0,
|
||||
energyConsumed: 0,
|
||||
};
|
||||
},
|
||||
injectCurrent: (injections) => {
|
||||
// WASM call: ruvector_nervous_inject(injections)
|
||||
},
|
||||
propagate: (sourceIds, signal) => {
|
||||
// WASM call: ruvector_nervous_propagate(sourceIds, signal)
|
||||
return {
|
||||
activatedNeurons: [],
|
||||
spikeTimings: new Map(),
|
||||
totalActivity: 0,
|
||||
};
|
||||
},
|
||||
getState: () => ({
|
||||
neurons,
|
||||
synapses,
|
||||
globalModulation: 1.0,
|
||||
timestamp: currentTime,
|
||||
}),
|
||||
setState: (state) => {
|
||||
neurons.clear();
|
||||
state.neurons.forEach((v, k) => neurons.set(k, v));
|
||||
synapses.length = 0;
|
||||
synapses.push(...state.synapses);
|
||||
currentTime = state.timestamp;
|
||||
},
|
||||
reset: (keepTopology = false) => {
|
||||
if (!keepTopology) {
|
||||
neurons.clear();
|
||||
synapses.length = 0;
|
||||
} else {
|
||||
neurons.forEach(n => {
|
||||
n.potential = -70;
|
||||
n.refractory = 0;
|
||||
});
|
||||
}
|
||||
currentTime = 0;
|
||||
},
|
||||
applyPlasticity: (rule, learningRate = 1.0) => {
|
||||
// WASM call: ruvector_nervous_plasticity(rule, learningRate)
|
||||
},
|
||||
applyStdp: (stdpConfig) => {
|
||||
// WASM call: ruvector_nervous_stdp(config)
|
||||
},
|
||||
applyHomeostasis: (targetRate = 10) => {
|
||||
// WASM call: ruvector_nervous_homeostasis(targetRate)
|
||||
},
|
||||
getPlasticityStats: () => ({
|
||||
averageWeightChange: 0,
|
||||
potentiationCount: 0,
|
||||
depressionCount: 0,
|
||||
synapsesPruned: 0,
|
||||
synapsesCreated: 0,
|
||||
}),
|
||||
createFeedforward: (layerSizes, connectivity = 1.0) => {
|
||||
// WASM call: ruvector_nervous_create_feedforward(layerSizes, connectivity)
|
||||
},
|
||||
createRecurrent: (size, connectivity = 0.1) => {
|
||||
// WASM call: ruvector_nervous_create_recurrent(size, connectivity)
|
||||
},
|
||||
createReservoir: (size, spectralRadius = 0.9, inputSize = 10) => {
|
||||
// WASM call: ruvector_nervous_create_reservoir(size, spectralRadius, inputSize)
|
||||
},
|
||||
createSmallWorld: (size, k = 4, beta = 0.1) => {
|
||||
// WASM call: ruvector_nervous_create_small_world(size, k, beta)
|
||||
},
|
||||
getTopologyStats: () => ({
|
||||
neuronCount: neurons.size,
|
||||
synapseCount: synapses.length,
|
||||
averageConnectivity: neurons.size > 0 ? synapses.length / neurons.size : 0,
|
||||
clusteringCoefficient: 0,
|
||||
averagePathLength: 0,
|
||||
spectralRadius: 0,
|
||||
}),
|
||||
startRecording: (neuronIds) => {
|
||||
// WASM call: ruvector_nervous_start_recording(neuronIds)
|
||||
},
|
||||
stopRecording: () => ({
|
||||
duration: 0,
|
||||
neuronIds: [],
|
||||
potentials: [],
|
||||
spikeTimes: new Map(),
|
||||
samplingRate: 1000,
|
||||
}),
|
||||
getSpikeRaster: (startTime = 0, endTime = currentTime) => {
|
||||
// WASM call: ruvector_nervous_get_raster(startTime, endTime)
|
||||
return new Map();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create default STDP configuration
|
||||
*/
|
||||
export function createStdpConfig(): StdpConfig {
|
||||
return {
|
||||
tauPlus: 20,
|
||||
tauMinus: 20,
|
||||
aPlus: 0.01,
|
||||
aMinus: 0.012,
|
||||
wMax: 1.0,
|
||||
wMin: 0.0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Izhikevich neuron parameters for different types
|
||||
*/
|
||||
export function izhikevichParams(type: 'regular' | 'bursting' | 'chattering' | 'fast'): {
|
||||
a: number;
|
||||
b: number;
|
||||
c: number;
|
||||
d: number;
|
||||
} {
|
||||
const params = {
|
||||
regular: { a: 0.02, b: 0.2, c: -65, d: 8 },
|
||||
bursting: { a: 0.02, b: 0.2, c: -50, d: 2 },
|
||||
chattering: { a: 0.02, b: 0.2, c: -50, d: 2 },
|
||||
fast: { a: 0.1, b: 0.2, c: -65, d: 2 },
|
||||
};
|
||||
return params[type];
|
||||
}
|
||||
262
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.d.ts
vendored
Normal file
262
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.d.ts
vendored
Normal file
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* RuVector WASM Unified Types
|
||||
* Core type definitions shared across all modules
|
||||
*/
|
||||
/** Tensor representation for neural computations */
|
||||
export interface Tensor {
|
||||
data: Float32Array;
|
||||
shape: number[];
|
||||
dtype: 'float32' | 'float16' | 'int32' | 'uint8';
|
||||
}
|
||||
/** Result wrapper for fallible operations */
|
||||
export interface Result<T, E = Error> {
|
||||
ok: boolean;
|
||||
value?: T;
|
||||
error?: E;
|
||||
}
|
||||
/** Async result for operations that may be pending */
|
||||
export interface AsyncResult<T> extends Result<T> {
|
||||
pending: boolean;
|
||||
progress?: number;
|
||||
}
|
||||
/** Configuration for multi-head attention */
|
||||
export interface MultiHeadConfig {
|
||||
numHeads: number;
|
||||
headDim: number;
|
||||
dropout?: number;
|
||||
useBias?: boolean;
|
||||
scaleFactor?: number;
|
||||
}
|
||||
/** Result from Mixture of Experts attention */
|
||||
export interface MoEResult {
|
||||
output: Float32Array;
|
||||
routerLogits: Float32Array;
|
||||
expertUsage: Float32Array;
|
||||
loadBalanceLoss: number;
|
||||
}
|
||||
/** Result from Mamba state-space model */
|
||||
export interface MambaResult {
|
||||
output: Float32Array;
|
||||
newState: Float32Array;
|
||||
deltaTime: number;
|
||||
}
|
||||
/** Attention scores with metadata */
|
||||
export interface AttentionScores {
|
||||
scores: Float32Array;
|
||||
weights: Float32Array;
|
||||
metadata: AttentionMetadata;
|
||||
}
|
||||
/** Metadata for attention computation */
|
||||
export interface AttentionMetadata {
|
||||
mechanism: string;
|
||||
computeTimeMs: number;
|
||||
memoryUsageBytes: number;
|
||||
sparsityRatio?: number;
|
||||
}
|
||||
/** Node in a query DAG */
|
||||
export interface QueryNode {
|
||||
id: string;
|
||||
embedding: Float32Array;
|
||||
nodeType: 'query' | 'key' | 'value' | 'gate' | 'aggregate';
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
/** Edge in a query DAG */
|
||||
export interface QueryEdge {
|
||||
source: string;
|
||||
target: string;
|
||||
weight: number;
|
||||
edgeType: 'attention' | 'dependency' | 'gate' | 'skip';
|
||||
}
|
||||
/** Directed Acyclic Graph for query processing */
|
||||
export interface QueryDag {
|
||||
nodes: QueryNode[];
|
||||
edges: QueryEdge[];
|
||||
rootIds: string[];
|
||||
leafIds: string[];
|
||||
}
|
||||
/** Gating packet for mincut operations */
|
||||
export interface GatePacket {
|
||||
gateValues: Float32Array;
|
||||
threshold: number;
|
||||
mode: 'hard' | 'soft' | 'stochastic';
|
||||
}
|
||||
/** Enhanced embedding with SONA pre-query processing */
|
||||
export interface EnhancedEmbedding {
|
||||
original: Float32Array;
|
||||
enhanced: Float32Array;
|
||||
contextVector: Float32Array;
|
||||
confidence: number;
|
||||
}
|
||||
/** Learning trajectory for reinforcement */
|
||||
export interface LearningTrajectory {
|
||||
states: Float32Array[];
|
||||
actions: number[];
|
||||
rewards: number[];
|
||||
dones: boolean[];
|
||||
}
|
||||
/** Micro-LoRA adaptation config */
|
||||
export interface MicroLoraConfig {
|
||||
rank: number;
|
||||
alpha: number;
|
||||
dropout?: number;
|
||||
targetModules: string[];
|
||||
}
|
||||
/** BTSP (Behavioral Timescale Synaptic Plasticity) config */
|
||||
export interface BtspConfig {
|
||||
learningRate: number;
|
||||
eligibilityDecay: number;
|
||||
rewardWindow: number;
|
||||
}
|
||||
/** Synapse connection between neurons */
|
||||
export interface Synapse {
|
||||
presynapticId: string;
|
||||
postsynapticId: string;
|
||||
weight: number;
|
||||
delay: number;
|
||||
plasticity: PlasticityRule;
|
||||
}
|
||||
/** Plasticity rule for synapse adaptation */
|
||||
export interface PlasticityRule {
|
||||
type: 'stdp' | 'btsp' | 'hebbian' | 'oja' | 'bcm';
|
||||
params: Record<string, number>;
|
||||
}
|
||||
/** Neuron in the nervous system */
|
||||
export interface Neuron {
|
||||
id: string;
|
||||
potential: number;
|
||||
threshold: number;
|
||||
refractory: number;
|
||||
neuronType: 'excitatory' | 'inhibitory' | 'modulatory';
|
||||
}
|
||||
/** Nervous system state snapshot */
|
||||
export interface NervousState {
|
||||
neurons: Map<string, Neuron>;
|
||||
synapses: Synapse[];
|
||||
globalModulation: number;
|
||||
timestamp: number;
|
||||
}
|
||||
/** Signal propagation result */
|
||||
export interface PropagationResult {
|
||||
activatedNeurons: string[];
|
||||
spikeTimings: Map<string, number>;
|
||||
totalActivity: number;
|
||||
}
|
||||
/** Credit account state */
|
||||
export interface CreditAccount {
|
||||
balance: number;
|
||||
stakedAmount: number;
|
||||
contributionMultiplier: number;
|
||||
lastUpdate: number;
|
||||
}
|
||||
/** Transaction record */
|
||||
export interface Transaction {
|
||||
id: string;
|
||||
type: 'deposit' | 'withdraw' | 'stake' | 'unstake' | 'reward' | 'penalty';
|
||||
amount: number;
|
||||
timestamp: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
/** Staking position */
|
||||
export interface StakingPosition {
|
||||
amount: number;
|
||||
lockDuration: number;
|
||||
startTime: number;
|
||||
expectedReward: number;
|
||||
}
|
||||
/** Economy metrics */
|
||||
export interface EconomyMetrics {
|
||||
totalSupply: number;
|
||||
totalStaked: number;
|
||||
circulatingSupply: number;
|
||||
averageMultiplier: number;
|
||||
}
|
||||
/** Quantum-inspired state */
|
||||
export interface QuantumState {
|
||||
amplitudes: Float32Array;
|
||||
phases: Float32Array;
|
||||
entanglementMap: Map<number, number[]>;
|
||||
}
|
||||
/** Hyperbolic embedding */
|
||||
export interface HyperbolicPoint {
|
||||
coordinates: Float32Array;
|
||||
curvature: number;
|
||||
manifold: 'poincare' | 'lorentz' | 'klein';
|
||||
}
|
||||
/** Topological feature */
|
||||
export interface TopologicalFeature {
|
||||
dimension: number;
|
||||
persistence: number;
|
||||
birthTime: number;
|
||||
deathTime: number;
|
||||
}
|
||||
/** Exotic computation result */
|
||||
export interface ExoticResult<T> {
|
||||
value: T;
|
||||
computationType: 'quantum' | 'hyperbolic' | 'topological' | 'fractal';
|
||||
fidelity: number;
|
||||
resourceUsage: ResourceUsage;
|
||||
}
|
||||
/** Resource usage metrics */
|
||||
export interface ResourceUsage {
|
||||
cpuTimeMs: number;
|
||||
memoryBytes: number;
|
||||
wasmCycles?: number;
|
||||
}
|
||||
/** Event emitted by the system */
|
||||
export interface SystemEvent {
|
||||
type: string;
|
||||
timestamp: number;
|
||||
source: string;
|
||||
payload: unknown;
|
||||
}
|
||||
/** Event listener callback */
|
||||
export type EventCallback<T = unknown> = (event: SystemEvent & {
|
||||
payload: T;
|
||||
}) => void;
|
||||
/** Subscription handle */
|
||||
export interface Subscription {
|
||||
unsubscribe(): void;
|
||||
readonly active: boolean;
|
||||
}
|
||||
/** Global configuration */
|
||||
export interface UnifiedConfig {
|
||||
wasmPath?: string;
|
||||
enableSimd?: boolean;
|
||||
enableThreads?: boolean;
|
||||
memoryLimit?: number;
|
||||
logLevel?: 'debug' | 'info' | 'warn' | 'error';
|
||||
}
|
||||
/** Module-specific configuration */
|
||||
export interface ModuleConfig {
|
||||
attention?: AttentionConfig;
|
||||
learning?: LearningConfig;
|
||||
nervous?: NervousConfig;
|
||||
economy?: EconomyConfig;
|
||||
exotic?: ExoticConfig;
|
||||
}
|
||||
export interface AttentionConfig {
|
||||
defaultMechanism?: string;
|
||||
cacheSize?: number;
|
||||
precisionMode?: 'fp32' | 'fp16' | 'mixed';
|
||||
}
|
||||
export interface LearningConfig {
|
||||
defaultLearningRate?: number;
|
||||
batchSize?: number;
|
||||
enableGradientCheckpointing?: boolean;
|
||||
}
|
||||
export interface NervousConfig {
|
||||
maxNeurons?: number;
|
||||
simulationDt?: number;
|
||||
enablePlasticity?: boolean;
|
||||
}
|
||||
export interface EconomyConfig {
|
||||
initialBalance?: number;
|
||||
stakingEnabled?: boolean;
|
||||
rewardRate?: number;
|
||||
}
|
||||
export interface ExoticConfig {
|
||||
quantumSimulationDepth?: number;
|
||||
hyperbolicPrecision?: number;
|
||||
topologicalMaxDimension?: number;
|
||||
}
|
||||
//# sourceMappingURL=types.d.ts.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.d.ts.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.d.ts.map
vendored
Normal file
File diff suppressed because one or more lines are too long
7
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.js
vendored
Normal file
7
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.js
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
/**
|
||||
* RuVector WASM Unified Types
|
||||
* Core type definitions shared across all modules
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=types.js.map
|
||||
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.js.map
vendored
Normal file
1
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.js.map
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":";AAAA;;;GAGG"}
|
||||
335
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.ts
vendored
Normal file
335
vendor/ruvector/npm/packages/ruvector-wasm-unified/src/types.ts
vendored
Normal file
@@ -0,0 +1,335 @@
|
||||
/**
|
||||
* RuVector WASM Unified Types
|
||||
* Core type definitions shared across all modules
|
||||
*/
|
||||
|
||||
// ============================================================================
|
||||
// Core Types
|
||||
// ============================================================================
|
||||
|
||||
/** Tensor representation for neural computations */
|
||||
export interface Tensor {
|
||||
data: Float32Array;
|
||||
shape: number[];
|
||||
dtype: 'float32' | 'float16' | 'int32' | 'uint8';
|
||||
}
|
||||
|
||||
/** Result wrapper for fallible operations */
|
||||
export interface Result<T, E = Error> {
|
||||
ok: boolean;
|
||||
value?: T;
|
||||
error?: E;
|
||||
}
|
||||
|
||||
/** Async result for operations that may be pending */
|
||||
export interface AsyncResult<T> extends Result<T> {
|
||||
pending: boolean;
|
||||
progress?: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Attention Types
|
||||
// ============================================================================
|
||||
|
||||
/** Configuration for multi-head attention */
|
||||
export interface MultiHeadConfig {
|
||||
numHeads: number;
|
||||
headDim: number;
|
||||
dropout?: number;
|
||||
useBias?: boolean;
|
||||
scaleFactor?: number;
|
||||
}
|
||||
|
||||
/** Result from Mixture of Experts attention */
|
||||
export interface MoEResult {
|
||||
output: Float32Array;
|
||||
routerLogits: Float32Array;
|
||||
expertUsage: Float32Array;
|
||||
loadBalanceLoss: number;
|
||||
}
|
||||
|
||||
/** Result from Mamba state-space model */
|
||||
export interface MambaResult {
|
||||
output: Float32Array;
|
||||
newState: Float32Array;
|
||||
deltaTime: number;
|
||||
}
|
||||
|
||||
/** Attention scores with metadata */
|
||||
export interface AttentionScores {
|
||||
scores: Float32Array;
|
||||
weights: Float32Array;
|
||||
metadata: AttentionMetadata;
|
||||
}
|
||||
|
||||
/** Metadata for attention computation */
|
||||
export interface AttentionMetadata {
|
||||
mechanism: string;
|
||||
computeTimeMs: number;
|
||||
memoryUsageBytes: number;
|
||||
sparsityRatio?: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DAG Types
|
||||
// ============================================================================
|
||||
|
||||
/** Node in a query DAG */
|
||||
export interface QueryNode {
|
||||
id: string;
|
||||
embedding: Float32Array;
|
||||
nodeType: 'query' | 'key' | 'value' | 'gate' | 'aggregate';
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Edge in a query DAG */
|
||||
export interface QueryEdge {
|
||||
source: string;
|
||||
target: string;
|
||||
weight: number;
|
||||
edgeType: 'attention' | 'dependency' | 'gate' | 'skip';
|
||||
}
|
||||
|
||||
/** Directed Acyclic Graph for query processing */
|
||||
export interface QueryDag {
|
||||
nodes: QueryNode[];
|
||||
edges: QueryEdge[];
|
||||
rootIds: string[];
|
||||
leafIds: string[];
|
||||
}
|
||||
|
||||
/** Gating packet for mincut operations */
|
||||
export interface GatePacket {
|
||||
gateValues: Float32Array;
|
||||
threshold: number;
|
||||
mode: 'hard' | 'soft' | 'stochastic';
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Learning Types
|
||||
// ============================================================================
|
||||
|
||||
/** Enhanced embedding with SONA pre-query processing */
|
||||
export interface EnhancedEmbedding {
|
||||
original: Float32Array;
|
||||
enhanced: Float32Array;
|
||||
contextVector: Float32Array;
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
/** Learning trajectory for reinforcement */
|
||||
export interface LearningTrajectory {
|
||||
states: Float32Array[];
|
||||
actions: number[];
|
||||
rewards: number[];
|
||||
dones: boolean[];
|
||||
}
|
||||
|
||||
/** Micro-LoRA adaptation config */
|
||||
export interface MicroLoraConfig {
|
||||
rank: number;
|
||||
alpha: number;
|
||||
dropout?: number;
|
||||
targetModules: string[];
|
||||
}
|
||||
|
||||
/** BTSP (Behavioral Timescale Synaptic Plasticity) config */
|
||||
export interface BtspConfig {
|
||||
learningRate: number;
|
||||
eligibilityDecay: number;
|
||||
rewardWindow: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Nervous System Types
|
||||
// ============================================================================
|
||||
|
||||
/** Synapse connection between neurons */
|
||||
export interface Synapse {
|
||||
presynapticId: string;
|
||||
postsynapticId: string;
|
||||
weight: number;
|
||||
delay: number;
|
||||
plasticity: PlasticityRule;
|
||||
}
|
||||
|
||||
/** Plasticity rule for synapse adaptation */
|
||||
export interface PlasticityRule {
|
||||
type: 'stdp' | 'btsp' | 'hebbian' | 'oja' | 'bcm';
|
||||
params: Record<string, number>;
|
||||
}
|
||||
|
||||
/** Neuron in the nervous system */
|
||||
export interface Neuron {
|
||||
id: string;
|
||||
potential: number;
|
||||
threshold: number;
|
||||
refractory: number;
|
||||
neuronType: 'excitatory' | 'inhibitory' | 'modulatory';
|
||||
}
|
||||
|
||||
/** Nervous system state snapshot */
|
||||
export interface NervousState {
|
||||
neurons: Map<string, Neuron>;
|
||||
synapses: Synapse[];
|
||||
globalModulation: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
/** Signal propagation result */
|
||||
export interface PropagationResult {
|
||||
activatedNeurons: string[];
|
||||
spikeTimings: Map<string, number>;
|
||||
totalActivity: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Economy Types
|
||||
// ============================================================================
|
||||
|
||||
/** Credit account state */
|
||||
export interface CreditAccount {
|
||||
balance: number;
|
||||
stakedAmount: number;
|
||||
contributionMultiplier: number;
|
||||
lastUpdate: number;
|
||||
}
|
||||
|
||||
/** Transaction record */
|
||||
export interface Transaction {
|
||||
id: string;
|
||||
type: 'deposit' | 'withdraw' | 'stake' | 'unstake' | 'reward' | 'penalty';
|
||||
amount: number;
|
||||
timestamp: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Staking position */
|
||||
export interface StakingPosition {
|
||||
amount: number;
|
||||
lockDuration: number;
|
||||
startTime: number;
|
||||
expectedReward: number;
|
||||
}
|
||||
|
||||
/** Economy metrics */
|
||||
export interface EconomyMetrics {
|
||||
totalSupply: number;
|
||||
totalStaked: number;
|
||||
circulatingSupply: number;
|
||||
averageMultiplier: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Exotic Types
|
||||
// ============================================================================
|
||||
|
||||
/** Quantum-inspired state */
|
||||
export interface QuantumState {
|
||||
amplitudes: Float32Array;
|
||||
phases: Float32Array;
|
||||
entanglementMap: Map<number, number[]>;
|
||||
}
|
||||
|
||||
/** Hyperbolic embedding */
|
||||
export interface HyperbolicPoint {
|
||||
coordinates: Float32Array;
|
||||
curvature: number;
|
||||
manifold: 'poincare' | 'lorentz' | 'klein';
|
||||
}
|
||||
|
||||
/** Topological feature */
|
||||
export interface TopologicalFeature {
|
||||
dimension: number;
|
||||
persistence: number;
|
||||
birthTime: number;
|
||||
deathTime: number;
|
||||
}
|
||||
|
||||
/** Exotic computation result */
|
||||
export interface ExoticResult<T> {
|
||||
value: T;
|
||||
computationType: 'quantum' | 'hyperbolic' | 'topological' | 'fractal';
|
||||
fidelity: number;
|
||||
resourceUsage: ResourceUsage;
|
||||
}
|
||||
|
||||
/** Resource usage metrics */
|
||||
export interface ResourceUsage {
|
||||
cpuTimeMs: number;
|
||||
memoryBytes: number;
|
||||
wasmCycles?: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Event Types
|
||||
// ============================================================================
|
||||
|
||||
/** Event emitted by the system */
|
||||
export interface SystemEvent {
|
||||
type: string;
|
||||
timestamp: number;
|
||||
source: string;
|
||||
payload: unknown;
|
||||
}
|
||||
|
||||
/** Event listener callback */
|
||||
export type EventCallback<T = unknown> = (event: SystemEvent & { payload: T }) => void;
|
||||
|
||||
/** Subscription handle */
|
||||
export interface Subscription {
|
||||
unsubscribe(): void;
|
||||
readonly active: boolean;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Configuration Types
|
||||
// ============================================================================
|
||||
|
||||
/** Global configuration */
|
||||
export interface UnifiedConfig {
|
||||
wasmPath?: string;
|
||||
enableSimd?: boolean;
|
||||
enableThreads?: boolean;
|
||||
memoryLimit?: number;
|
||||
logLevel?: 'debug' | 'info' | 'warn' | 'error';
|
||||
}
|
||||
|
||||
/** Module-specific configuration */
|
||||
export interface ModuleConfig {
|
||||
attention?: AttentionConfig;
|
||||
learning?: LearningConfig;
|
||||
nervous?: NervousConfig;
|
||||
economy?: EconomyConfig;
|
||||
exotic?: ExoticConfig;
|
||||
}
|
||||
|
||||
export interface AttentionConfig {
|
||||
defaultMechanism?: string;
|
||||
cacheSize?: number;
|
||||
precisionMode?: 'fp32' | 'fp16' | 'mixed';
|
||||
}
|
||||
|
||||
export interface LearningConfig {
|
||||
defaultLearningRate?: number;
|
||||
batchSize?: number;
|
||||
enableGradientCheckpointing?: boolean;
|
||||
}
|
||||
|
||||
export interface NervousConfig {
|
||||
maxNeurons?: number;
|
||||
simulationDt?: number;
|
||||
enablePlasticity?: boolean;
|
||||
}
|
||||
|
||||
export interface EconomyConfig {
|
||||
initialBalance?: number;
|
||||
stakingEnabled?: boolean;
|
||||
rewardRate?: number;
|
||||
}
|
||||
|
||||
export interface ExoticConfig {
|
||||
quantumSimulationDepth?: number;
|
||||
hyperbolicPrecision?: number;
|
||||
topologicalMaxDimension?: number;
|
||||
}
|
||||
Reference in New Issue
Block a user