/** * BrowserGNN by Dr. Lee * Core Tensor Operations * * Provides fundamental tensor operations for graph neural networks * with support for both CPU (TypedArrays) and GPU (WebGPU) backends. * WASM-accelerated for optimal performance. */ type TypedArray = Float32Array | Float64Array | Int32Array | Uint32Array; type DataType = 'float32' | 'float64' | 'int32' | 'uint32'; /** * Shape descriptor for multi-dimensional tensors */ type Shape = number[]; /** * Tensor class for numerical computations * Wraps TypedArrays with shape information and operations */ declare class Tensor { readonly data: Float32Array; readonly shape: Shape; readonly dtype: DataType; constructor(data: Float32Array | number[], shape: Shape, dtype?: DataType); /** * Get the number of dimensions */ get ndim(): number; /** * Get total number of elements */ get size(): number; /** * Create a tensor of zeros */ static zeros(shape: Shape): Tensor; /** * Create a tensor of ones */ static ones(shape: Shape): Tensor; /** * Create a tensor with random values from uniform distribution [0, 1) */ static rand(shape: Shape): Tensor; /** * Create a tensor with random values from normal distribution * Using Box-Muller transform */ static randn(shape: Shape): Tensor; /** * Create identity matrix */ static eye(n: number): Tensor; /** * Reshape tensor to new shape */ reshape(newShape: Shape): Tensor; /** * Transpose 2D tensor */ transpose(): Tensor; /** * Get value at index (for 1D) or [row, col] (for 2D) */ get(...indices: number[]): number; /** * Set value at index */ set(value: number, ...indices: number[]): void; /** * Clone the tensor */ clone(): Tensor; /** * Element-wise addition * Uses WASM kernel with 8x loop unrolling for tensor-tensor addition */ add(other: Tensor | number): Tensor; /** * Element-wise subtraction */ sub(other: Tensor | number): Tensor; /** * Element-wise multiplication */ mul(other: Tensor | number): Tensor; /** * Element-wise division */ div(other: Tensor | number): Tensor; /** * Negate all elements (multiply by -1) */ neg(): Tensor; /** * Matrix multiplication for 2D tensors * Uses WASM kernel with 4x loop unrolling for optimal performance */ matmul(other: Tensor): Tensor; /** * Sum all elements */ sum(): number; /** * Sum along axis */ sumAxis(axis: number): Tensor; /** * Mean of all elements */ mean(): number; /** * Maximum value */ max(): number; /** * Minimum value */ min(): number; /** * Apply ReLU activation * Uses WASM kernel with 8x loop unrolling for optimal performance */ relu(): Tensor; /** * Apply Leaky ReLU activation */ leakyRelu(negativeSlope?: number): Tensor; /** * Apply sigmoid activation */ sigmoid(): Tensor; /** * Apply tanh activation */ tanh(): Tensor; /** * Apply softmax along last axis */ softmax(): Tensor; /** * Apply log softmax along last axis */ logSoftmax(): Tensor; /** * Check if shapes are equal */ shapeEquals(other: Tensor): boolean; /** * Convert to string representation */ toString(): string; /** * Pretty print tensor data */ print(): void; } /** * Concatenate tensors along axis */ declare function concat(tensors: Tensor[], axis?: number): Tensor; /** * Stack tensors along new axis */ declare function stack(tensors: Tensor[], axis?: number): Tensor; /** * BrowserGNN by Dr. Lee * Graph Data Structure * * Core data structure for representing graphs in GNN computations. * Follows PyTorch Geometric conventions for compatibility. */ /** * Configuration for creating a GraphData instance */ interface GraphDataConfig { /** Node features as flat array [numNodes * numFeatures] */ x: Float32Array | number[]; /** Number of nodes in the graph */ numNodes: number; /** Number of features per node */ numFeatures: number; /** Edge index in COO format [2 * numEdges]: [src0, src1, ..., tgt0, tgt1, ...] */ edgeIndex: Uint32Array | number[]; /** Number of edges */ numEdges: number; /** Optional edge attributes [numEdges * edgeFeatures] */ edgeAttr?: Float32Array | number[]; /** Number of edge features (required if edgeAttr provided) */ numEdgeFeatures?: number; /** Optional node labels [numNodes] or [numNodes * numClasses] */ y?: Float32Array | number[]; /** Optional graph-level label */ graphLabel?: number; /** Optional batch assignment for batched graphs [numNodes] */ batch?: Uint32Array | number[]; } /** * GraphData class - Core data structure for graph neural networks * * Stores node features, edge connectivity, and optional attributes * in a format optimized for message passing operations. */ declare class GraphData { /** Node feature tensor [numNodes, numFeatures] */ readonly x: Tensor; /** Number of nodes */ readonly numNodes: number; /** Number of features per node */ readonly numFeatures: number; /** Edge index tensor [2, numEdges] */ readonly edgeIndex: Uint32Array; /** Number of edges */ readonly numEdges: number; /** Optional edge attributes tensor [numEdges, numEdgeFeatures] */ readonly edgeAttr?: Tensor; /** Number of edge features */ readonly numEdgeFeatures: number; /** Optional node labels tensor */ readonly y?: Tensor; /** Optional graph-level label */ readonly graphLabel?: number; /** Batch assignment for batched graphs */ readonly batch?: Uint32Array; constructor(config: GraphDataConfig); /** * Get source nodes from edge index */ get sourceNodes(): Uint32Array; /** * Get target nodes from edge index */ get targetNodes(): Uint32Array; /** * Get edge as [source, target] pair */ getEdge(idx: number): [number, number]; /** * Get neighbors of a node */ getNeighbors(nodeIdx: number): number[]; /** * Get in-degree of each node */ getInDegrees(): Uint32Array; /** * Get out-degree of each node */ getOutDegrees(): Uint32Array; /** * Check if graph is directed (has asymmetric edges) */ isDirected(): boolean; /** * Check if graph has self-loops */ hasSelfLoops(): boolean; /** * Add self-loops to the graph */ addSelfLoops(): GraphData; /** * Remove self-loops from the graph */ removeSelfLoops(): GraphData; /** * Create a copy with new node features */ withFeatures(newX: Tensor): GraphData; /** * Convert to adjacency list representation */ toAdjacencyList(): Map; /** * Convert edge index to dense adjacency matrix */ toAdjacencyMatrix(): Tensor; /** * Get normalized adjacency matrix with self-loops (for GCN) * D^{-1/2} * (A + I) * D^{-1/2} */ getNormalizedAdjacency(): Tensor; /** * Clone the graph */ clone(): GraphData; /** * String representation */ toString(): string; /** * Print graph summary */ print(): void; } /** * Batch multiple graphs into a single GraphData object * Used for mini-batch training/inference */ declare function batchGraphs(graphs: GraphData[]): GraphData; /** * Create a simple graph from edge list */ declare function fromEdgeList(edges: [number, number][], numNodes?: number, nodeFeatures?: Float32Array | number[]): GraphData; /** * Create a random graph using Erdos-Renyi model */ declare function randomGraph(numNodes: number, edgeProbability: number, numFeatures?: number): GraphData; /** * BrowserGNN by Dr. Lee * Sparse Tensor Utilities * * Efficient sparse matrix operations for graph neural networks. * Supports COO, CSR, and CSC formats. * WASM-accelerated for optimal performance. */ /** * Sparse matrix in COO (Coordinate) format * Most flexible format, good for construction */ declare class SparseCOO { readonly rows: Uint32Array; readonly cols: Uint32Array; readonly values: Float32Array; readonly shape: [number, number]; readonly nnz: number; constructor(rows: Uint32Array | number[], cols: Uint32Array | number[], values: Float32Array | number[], shape: [number, number]); /** * Create from dense tensor */ static fromDense(dense: Tensor): SparseCOO; /** * Create from edge index (adjacency matrix) */ static fromEdgeIndex(edgeIndex: Uint32Array, numEdges: number, numNodes: number, values?: Float32Array): SparseCOO; /** * Convert to dense tensor */ toDense(): Tensor; /** * Convert to CSR format */ toCSR(): SparseCSR; /** * Sparse matrix-vector multiplication */ matvec(x: Tensor): Tensor; /** * Sparse matrix - dense matrix multiplication * Result: [M, K] where this is [M, N] and dense is [N, K] */ matmul(dense: Tensor): Tensor; /** * Transpose the sparse matrix */ transpose(): SparseCOO; /** * Scale all values */ scale(scalar: number): SparseCOO; /** * Element-wise multiplication with another sparse matrix (same sparsity pattern) */ multiply(other: SparseCOO): SparseCOO; /** * Get sparsity (fraction of zeros) */ get sparsity(): number; toString(): string; } /** * Sparse matrix in CSR (Compressed Sparse Row) format * Efficient for row slicing and matrix-vector multiplication */ declare class SparseCSR { readonly rowPtr: Uint32Array; readonly colIndices: Uint32Array; readonly values: Float32Array; readonly shape: [number, number]; readonly nnz: number; constructor(rowPtr: Uint32Array, colIndices: Uint32Array, values: Float32Array, shape: [number, number]); /** * Create from COO format */ static fromCOO(coo: SparseCOO): SparseCSR; /** * Sparse matrix-vector multiplication (efficient in CSR) */ matvec(x: Tensor): Tensor; /** * Sparse matrix - dense matrix multiplication */ matmul(dense: Tensor): Tensor; /** * Get row as dense array */ getRow(row: number): Float32Array; /** * Convert to COO format */ toCOO(): SparseCOO; /** * Convert to dense tensor */ toDense(): Tensor; toString(): string; } /** * Message passing utilities for GNNs * WASM-accelerated with loop unrolling for optimal performance */ declare class MessagePassing { /** * Scatter-add operation: aggregate values by target indices * Used for message aggregation in GNNs * Uses WASM kernel with 8x loop unrolling * * @param src Source values [numMessages, features] * @param index Target indices [numMessages] * @param numNodes Number of output nodes * @returns Aggregated values [numNodes, features] */ static scatterAdd(src: Tensor, index: Uint32Array, numNodes: number): Tensor; /** * Scatter-mean operation: average values by target indices * Uses WASM kernel with 8x loop unrolling */ static scatterMean(src: Tensor, index: Uint32Array, numNodes: number): Tensor; /** * Scatter-max operation: max values by target indices * Uses WASM kernel with 8x loop unrolling */ static scatterMax(src: Tensor, index: Uint32Array, numNodes: number): Tensor; /** * Gather operation: select values by indices * Used to gather source node features for each edge * Uses WASM kernel with 8x loop unrolling * * @param src Source values [numNodes, features] * @param index Indices to gather [numIndices] * @returns Gathered values [numIndices, features] */ static gather(src: Tensor, index: Uint32Array): Tensor; } /** * Compute normalized edge weights for GCN * Returns D^{-1/2} weights for each edge */ declare function computeGCNNorm(edgeIndex: Uint32Array, numEdges: number, numNodes: number, addSelfLoops?: boolean): Float32Array; /** * BrowserGNN by Dr. Lee * GPU Buffer Pool for Memory Management * * Efficient buffer reuse to minimize GPU memory allocations * and improve performance for repeated operations. */ interface BufferDescriptor { size: number; usage: GPUBufferUsageFlags; label?: string; } /** * GPU Buffer Pool * * Manages a pool of GPU buffers for reuse, reducing allocation overhead. * Implements a simple least-recently-used (LRU) eviction policy. */ declare class GPUBufferPool { private device; private buffers; private maxPoolSize; private currentPoolSize; private hitCount; private missCount; constructor(device: GPUDevice, maxPoolSizeMB?: number); /** * Get a buffer from the pool or create a new one */ acquire(descriptor: BufferDescriptor): GPUBuffer; /** * Release a buffer back to the pool */ release(buffer: GPUBuffer): void; /** * Create a staging buffer for CPU-GPU data transfer */ createStagingBuffer(size: number, forRead?: boolean): GPUBuffer; /** * Create a uniform buffer */ createUniformBuffer(size: number, label?: string): GPUBuffer; /** * Create a storage buffer */ createStorageBuffer(size: number, label?: string): GPUBuffer; /** * Evict least recently used buffers */ private evict; /** * Get pool key for buffer usage */ private getKey; /** * Round up to nearest power of 2 */ private roundUpToPowerOf2; /** * Get pool statistics */ getStats(): { poolSizeBytes: number; numBuffers: number; numInUse: number; hitRate: number; }; /** * Clear all buffers in the pool */ clear(): void; /** * Destroy the pool */ destroy(): void; } /** * BrowserGNN by Dr. Lee * WebGPU Compute Pipeline Infrastructure * * Manages shader compilation, pipeline creation, and compute dispatch * for high-performance graph neural network operations. */ interface ComputePipelineConfig { maxBufferSize?: number; enableProfiling?: boolean; } /** * WebGPU Compute Manager * * Central manager for all WebGPU compute operations. * Handles shader compilation, pipeline caching, and execution. */ declare class WebGPUComputeManager { private device; private bufferPool; private pipelines; private shaderModules; private profiling; private querySet; private queryBuffer; constructor(device: GPUDevice, config?: ComputePipelineConfig); /** * Get or compile a shader module */ private getShaderModule; /** * Get or create a compute pipeline */ private getPipeline; /** * Sparse Matrix-Dense Matrix Multiplication (SpMM) using CSR format * * Computes: output = sparse @ dense * Where sparse is in CSR format [numRows, numCols] and dense is [numCols, numFeatures] * * This is the core operation for GNN message passing. */ spmm(rowPtr: Uint32Array, colIndices: Uint32Array, values: Float32Array, dense: Float32Array, numRows: number, numCols: number, numFeatures: number): Promise; /** * Scatter-Add operation for message aggregation */ scatterAdd(src: Float32Array, indices: Uint32Array, numNodes: number, numFeatures: number): Promise; /** * Scatter-Max operation for max-pooling aggregation */ scatterMax(src: Float32Array, indices: Uint32Array, numNodes: number, numFeatures: number): Promise; /** * Gather operation for collecting node features */ gather(src: Float32Array, indices: Uint32Array, numFeatures: number): Promise; /** * Dense matrix multiplication: C = A @ B */ matmul(a: Float32Array, b: Float32Array, m: number, k: number, n: number): Promise; /** * ReLU activation in-place */ relu(data: Float32Array): Promise; /** * Element-wise addition: result = a + b */ add(a: Float32Array, b: Float32Array): Promise; /** * Get buffer pool statistics */ getStats(): ReturnType; /** * Clear pipeline and shader caches */ clearCache(): void; /** * Destroy the compute manager */ destroy(): void; } /** * BrowserGNN by Dr. Lee * GPU-Accelerated Sparse Operations * * Provides WebGPU-accelerated versions of sparse matrix operations * with automatic fallback to CPU when WebGPU is not available. */ /** * GPU-accelerated sparse operations * * Automatically uses WebGPU when available, falls back to CPU otherwise. */ declare class GPUSparse { /** * Sparse matrix-dense matrix multiplication * * @param sparse Sparse matrix in COO or CSR format * @param dense Dense matrix [N, K] * @returns Result matrix [M, K] */ static matmul(sparse: SparseCOO | SparseCSR, dense: Tensor): Promise; /** * GPU-accelerated SpMM */ private static gpuSpMM; /** * Scatter-add operation: aggregate values by target indices * * @param src Source values [numMessages, features] * @param index Target indices [numMessages] * @param numNodes Number of output nodes * @returns Aggregated values [numNodes, features] */ static scatterAdd(src: Tensor, index: Uint32Array, numNodes: number): Promise; /** * Scatter-mean operation: average values by target indices * * @param src Source values [numMessages, features] * @param index Target indices [numMessages] * @param numNodes Number of output nodes * @returns Averaged values [numNodes, features] */ static scatterMean(src: Tensor, index: Uint32Array, numNodes: number): Promise; /** * Scatter-max operation: max values by target indices * * @param src Source values [numMessages, features] * @param index Target indices [numMessages] * @param numNodes Number of output nodes * @returns Max values [numNodes, features] */ static scatterMax(src: Tensor, index: Uint32Array, numNodes: number): Promise; /** * Gather operation: collect values by indices * * @param src Source values [numNodes, features] * @param index Indices to gather [numIndices] * @returns Gathered values [numIndices, features] */ static gather(src: Tensor, index: Uint32Array): Promise; } /** * GPU-accelerated tensor operations */ declare class GPUTensor { /** * Matrix multiplication: C = A @ B * * @param a Matrix A [M, K] * @param b Matrix B [K, N] * @returns Result C [M, N] */ static matmul(a: Tensor, b: Tensor): Promise; /** * ReLU activation * * @param x Input tensor * @returns Output tensor with ReLU applied */ static relu(x: Tensor): Promise; /** * Element-wise addition * * @param a First tensor * @param b Second tensor * @returns Sum tensor */ static add(a: Tensor, b: Tensor): Promise; } /** * Check if GPU acceleration is available */ declare function isGPUAvailable(): boolean; /** * Get GPU statistics */ declare function getGPUStats(): { available: boolean; backend: string; bufferPoolStats?: ReturnType; }; /** * BrowserGNN by Dr. Lee * Neural Network Module Base * * Base class for all neural network modules in BrowserGNN. */ /** * Parameter storage for modules */ interface Parameter { name: string; tensor: Tensor; requiresGrad: boolean; } /** * Base class for all neural network modules */ declare abstract class Module { protected _training: boolean; protected _parameters: Map; protected _modules: Map; protected _buffers: Map; /** * Forward pass - must be implemented by subclasses */ abstract forward(input: Tensor | GraphData): Tensor | GraphData | Promise; /** * Register a parameter */ protected registerParameter(name: string, tensor: Tensor, requiresGrad?: boolean): void; /** * Register a submodule */ protected registerModule(name: string, module: Module): void; /** * Register a buffer (non-trainable tensor) */ protected registerBuffer(name: string, tensor: Tensor): void; /** * Get all parameters (including from submodules) */ parameters(): Parameter[]; /** * Get named parameters */ namedParameters(prefix?: string): Map; /** * Set training mode */ train(mode?: boolean): this; /** * Set evaluation mode */ eval(): this; /** * Check if in training mode */ get training(): boolean; /** * Count total parameters */ numParameters(): number; /** * Get module summary */ summary(): string; } /** * Sequential container - runs modules in sequence */ declare class Sequential extends Module { private modules; constructor(modules: Module[]); forward(input: Tensor | GraphData): Promise; /** * Add a module to the end */ add(module: Module): void; /** * Get number of modules */ get length(): number; } /** * BrowserGNN by Dr. Lee * Linear Layer * * Fully connected linear transformation layer. */ interface LinearConfig { inFeatures: number; outFeatures: number; bias?: boolean; } /** * Linear layer: y = xW^T + b */ declare class Linear extends Module { readonly inFeatures: number; readonly outFeatures: number; readonly useBias: boolean; constructor(config: LinearConfig); forward(input: Tensor): Tensor; } /** * BrowserGNN by Dr. Lee * Activation Functions * * Common activation functions as Module wrappers. */ /** * ReLU activation: max(0, x) */ declare class ReLU extends Module { forward(input: Tensor | GraphData): Tensor | GraphData; } /** * Leaky ReLU activation: max(negative_slope * x, x) */ declare class LeakyReLU extends Module { private negativeSlope; constructor(negativeSlope?: number); forward(input: Tensor | GraphData): Tensor | GraphData; } /** * ELU activation: x if x > 0, alpha * (exp(x) - 1) otherwise */ declare class ELU extends Module { private alpha; constructor(alpha?: number); forward(input: Tensor | GraphData): Tensor | GraphData; } /** * Sigmoid activation: 1 / (1 + exp(-x)) */ declare class Sigmoid extends Module { forward(input: Tensor | GraphData): Tensor | GraphData; } /** * Tanh activation */ declare class Tanh extends Module { forward(input: Tensor | GraphData): Tensor | GraphData; } /** * Softmax activation (along last axis) */ declare class Softmax extends Module { forward(input: Tensor | GraphData): Tensor | GraphData; } /** * Log Softmax activation (along last axis) */ declare class LogSoftmax extends Module { forward(input: Tensor | GraphData): Tensor | GraphData; } /** * GELU activation: x * Φ(x) where Φ is the CDF of standard normal * Approximation: 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x^3))) */ declare class GELU extends Module { forward(input: Tensor | GraphData): Tensor | GraphData; } /** * SiLU/Swish activation: x * sigmoid(x) */ declare class SiLU extends Module { forward(input: Tensor | GraphData): Tensor | GraphData; } /** * PReLU activation: max(0, x) + a * min(0, x) * Learnable parameter 'a' */ declare class PReLU extends Module { constructor(numParameters?: number, init?: number); forward(input: Tensor | GraphData): Tensor | GraphData; } /** * Dropout layer */ declare class Dropout extends Module { private p; constructor(p?: number); forward(input: Tensor | GraphData): Tensor | GraphData; } /** * BrowserGNN by Dr. Lee * Graph Convolutional Network (GCN) Layer * * Implementation of GCN layer from: * "Semi-Supervised Classification with Graph Convolutional Networks" * by Kipf & Welling (2017) * * Formula: H' = σ(D̃^{-1/2} à D̃^{-1/2} H W) * where à = A + I (adjacency with self-loops) * and D̃ is the degree matrix of à */ interface GCNConvConfig { inChannels: number; outChannels: number; bias?: boolean; addSelfLoops?: boolean; normalize?: boolean; } /** * Graph Convolutional Layer * * Performs message passing with symmetric normalization: * x_i' = W · Σ_{j∈N(i)∪{i}} (1/√(d_i·d_j)) · x_j */ declare class GCNConv extends Module { readonly inChannels: number; readonly outChannels: number; readonly addSelfLoops: boolean; readonly normalize: boolean; readonly useBias: boolean; private cachedNorm; private cachedGraphId; constructor(config: GCNConvConfig); /** * Forward pass * * @param input GraphData with node features * @returns GraphData with updated node features */ forward(input: GraphData): GraphData; /** * Async forward pass with GPU acceleration * * Uses WebGPU compute shaders when available for 5-10x speedup * on graphs with 1000+ nodes. Falls back to CPU otherwise. * * @param input GraphData with node features * @returns Promise with updated node features */ forwardAsync(input: GraphData): Promise; /** * Reset parameters to initial values */ resetParameters(): void; /** * Get layer description */ toString(): string; } /** * BrowserGNN by Dr. Lee * Graph Attention Network (GAT) Layer * * Implementation of GAT layer from: * "Graph Attention Networks" by Velickovic et al. (2018) * * Uses attention mechanism to weight neighbor contributions: * α_ij = softmax_j(LeakyReLU(a^T [Wh_i || Wh_j])) * h_i' = σ(Σ_j α_ij W h_j) */ interface GATConvConfig { inChannels: number; outChannels: number; heads?: number; concat?: boolean; negativeSlope?: number; dropout?: number; addSelfLoops?: boolean; bias?: boolean; } /** * Graph Attention Layer * * Multi-head attention mechanism for graph neural networks. * Each head learns different attention patterns. */ declare class GATConv extends Module { readonly inChannels: number; readonly outChannels: number; readonly heads: number; readonly concat: boolean; readonly negativeSlope: number; readonly dropout: number; readonly addSelfLoops: boolean; readonly useBias: boolean; constructor(config: GATConvConfig); /** * Get output dimension */ get outputDim(): number; /** * Forward pass */ forward(input: GraphData): GraphData; /** * Async forward pass with GPU acceleration * * Uses WebGPU compute shaders when available for: * - Linear transformation (matmul) * - Attention score computation */ forwardAsync(input: GraphData): Promise; /** * Reset parameters */ resetParameters(): void; /** * Get layer description */ toString(): string; } /** * BrowserGNN by Dr. Lee * GraphSAGE Layer * * Implementation of GraphSAGE from: * "Inductive Representation Learning on Large Graphs" * by Hamilton et al. (2017) * * Supports multiple aggregation methods: * - mean: Average neighbor features * - max: Element-wise max of neighbor features * - sum: Sum neighbor features * - lstm: LSTM-based aggregation (sequential) */ type SAGEAggregator = 'mean' | 'max' | 'sum' | 'pool'; interface SAGEConvConfig { inChannels: number; outChannels: number; aggregator?: SAGEAggregator; normalize?: boolean; rootWeight?: boolean; bias?: boolean; projectNeighbors?: boolean; } /** * GraphSAGE Convolution Layer * * Aggregates neighbor features and combines with self features: * h_i' = W · [h_i || AGG({h_j : j ∈ N(i)})] * * Or with root_weight=false: * h_i' = W · AGG({h_j : j ∈ N(i)}) */ declare class SAGEConv extends Module { readonly inChannels: number; readonly outChannels: number; readonly aggregator: SAGEAggregator; readonly normalize: boolean; readonly rootWeight: boolean; readonly useBias: boolean; readonly projectNeighbors: boolean; constructor(config: SAGEConvConfig); /** * Forward pass */ forward(input: GraphData): GraphData; /** * Async forward pass with GPU acceleration * * Uses WebGPU compute shaders when available. */ forwardAsync(input: GraphData): Promise; /** * Reset parameters */ resetParameters(): void; /** * Get layer description */ toString(): string; } /** * BrowserGNN by Dr. Lee * Graph Isomorphism Network (GIN) Layer * * Implementation of GIN layer from: * "How Powerful are Graph Neural Networks?" * by Xu et al. (2019) * * Formula: h_v' = MLP((1 + ε) · h_v + Σ_{u∈N(v)} h_u) * where ε is a learnable parameter (or fixed at 0) * * GIN is one of the most powerful GNN architectures for graph isomorphism testing * and is widely used for graph-level tasks like molecule classification. */ interface GINConvConfig { inChannels: number; outChannels: number; hiddenChannels?: number; epsilon?: number; trainEpsilon?: boolean; bias?: boolean; numLayers?: number; } /** * Graph Isomorphism Network Layer * * GIN aggregates neighbor features and applies an MLP: * x_i' = MLP((1 + ε) · x_i + Σ_{j∈N(i)} x_j) * * This is proven to be as powerful as the Weisfeiler-Lehman test * for distinguishing non-isomorphic graphs. */ declare class GINConv extends Module { readonly inChannels: number; readonly outChannels: number; readonly hiddenChannels: number; readonly trainEpsilon: boolean; readonly useBias: boolean; readonly numLayers: number; constructor(config: GINConvConfig); /** * Apply ReLU activation in-place */ private relu; /** * Forward pass * * @param input GraphData with node features * @returns GraphData with updated node features */ forward(input: GraphData): GraphData; /** * Async forward pass with GPU acceleration * * Uses WebGPU compute shaders when available for acceleration. * Falls back to CPU otherwise. * * @param input GraphData with node features * @returns Promise with updated node features */ forwardAsync(input: GraphData): Promise; /** * Reset parameters to initial values */ resetParameters(): void; /** * Get layer description */ toString(): string; } /** * BrowserGNN by Dr. Lee * EdgeConv Layer (Dynamic Graph CNN) * * Implementation of EdgeConv from: * "Dynamic Graph CNN for Learning on Point Clouds" * by Wang et al. (DGCNN, 2019) * * Formula: x_i' = max_{j ∈ N(i)} h_Θ(x_i, x_j - x_i) * * EdgeConv computes edge features from both the source node and the * difference between source and target nodes, enabling the network * to capture local geometric structure. * * Commonly used for: * - Point cloud classification/segmentation * - 3D shape analysis * - Molecular property prediction */ interface EdgeConvConfig { inChannels: number; outChannels: number; hiddenChannels?: number; aggregation?: 'max' | 'mean' | 'sum'; bias?: boolean; } /** * EdgeConv Layer (Dynamic Graph CNN) * * Computes edge features using both node features and pairwise differences: * e_ij = MLP([x_i || x_j - x_i]) * x_i' = aggregate_{j ∈ N(i)} e_ij * * The concatenation [x_i || x_j - x_i] captures both absolute position * and relative geometric information. */ declare class EdgeConv extends Module { readonly inChannels: number; readonly outChannels: number; readonly hiddenChannels: number; readonly aggregation: 'max' | 'mean' | 'sum'; readonly useBias: boolean; constructor(config: EdgeConvConfig); /** * Apply ReLU activation */ private relu; /** * Compute edge features for all edges * e_ij = MLP([x_i || x_j - x_i]) */ private computeEdgeFeatures; /** * Forward pass * * @param input GraphData with node features * @returns GraphData with updated node features */ forward(input: GraphData): GraphData; /** * Async forward pass with GPU acceleration * * @param input GraphData with node features * @returns Promise with updated node features */ forwardAsync(input: GraphData): Promise; /** * Reset parameters */ resetParameters(): void; /** * Get layer description */ toString(): string; } /** * BrowserGNN by Dr. Lee * ChebConv Layer (Chebyshev Spectral Graph Convolution) * * Implementation of Chebyshev spectral convolution from: * "Convolutional Neural Networks on Graphs with Fast Localized Spectral Filtering" * by Defferrard et al. (2016) * * Formula: x' = Σ_{k=0}^{K-1} T_k(L̃) · X · Θ_k * * where: * - T_k(L̃) is the kth Chebyshev polynomial of the scaled Laplacian * - L̃ = 2L/λ_max - I (rescaled Laplacian for numerical stability) * - Θ_k is the kth filter parameter matrix * * ChebConv provides a localized spectral graph filter with K-hop support, * avoiding expensive eigen-decomposition of the graph Laplacian. */ interface ChebConvConfig { inChannels: number; outChannels: number; K?: number; bias?: boolean; normalization?: 'sym' | 'rw'; lambdaMax?: number; } /** * Chebyshev Spectral Graph Convolution Layer * * Uses Chebyshev polynomials to approximate spectral convolution: * x' = Σ_{k=0}^{K-1} T_k(L̃) X Θ_k * * Properties: * - K-localized: each layer considers K-hop neighborhoods * - Avoids eigen-decomposition: O(K|E|) complexity * - Spectral filtering in Chebyshev basis */ declare class ChebConv extends Module { readonly inChannels: number; readonly outChannels: number; readonly K: number; readonly useBias: boolean; readonly normalization: 'sym' | 'rw'; readonly lambdaMax: number; constructor(config: ChebConvConfig); /** * Compute node degrees from edge index */ private computeDegrees; /** * Apply scaled Laplacian: L̃ = 2L/λ_max - I * For symmetric normalization: L = I - D^{-1/2} A D^{-1/2} * So L̃ = 2(I - D^{-1/2} A D^{-1/2})/λ_max - I * = -2 D^{-1/2} A D^{-1/2}/λ_max + (2/λ_max - 1)I */ private applyScaledLaplacian; /** * Forward pass * * @param input GraphData with node features * @returns GraphData with updated node features */ forward(input: GraphData): GraphData; /** * Async forward pass with GPU acceleration */ forwardAsync(input: GraphData): Promise; /** * Reset parameters */ resetParameters(): void; /** * Get layer description */ toString(): string; } /** * BrowserGNN by Dr. Lee * TopKPool Layer (Top-K Graph Pooling) * * Implementation of TopKPool from: * "Graph U-Nets" by Gao & Ji (2019) * and "Towards Sparse Hierarchical Graph Classifiers" by Cangea et al. (2018) * * Formula: * 1. Compute node scores: y = σ(X·p / ||p||) * 2. Select top-k nodes based on scores * 3. Gate selected features: X' = X[idx] ⊙ y[idx] * 4. Update edges to only include selected nodes * * TopKPool learns which nodes are important for graph-level tasks, * enabling hierarchical graph representations. */ interface TopKPoolConfig { inChannels: number; ratio?: number; minScore?: number; multiplier?: number; nonlinearity?: 'tanh' | 'sigmoid' | 'none'; } interface PoolingResult { /** * Pooled graph with selected nodes */ graph: GraphData; /** * Indices of selected nodes in original graph */ selectedIndices: number[]; /** * Node scores before selection */ scores: Float32Array; /** * Permutation from new to old node indices */ perm: Uint32Array; } /** * Top-K Graph Pooling Layer * * Selects top-k nodes based on learned projection scores. * Used for hierarchical graph classification and graph generation. * * Key operations: * 1. Project features to scalar scores * 2. Select top-k nodes by score * 3. Gate features by scores (multiplicative attention) * 4. Induce subgraph on selected nodes */ declare class TopKPool extends Module { readonly inChannels: number; readonly ratio: number; readonly minScore: number; readonly multiplier: number; readonly nonlinearity: 'tanh' | 'sigmoid' | 'none'; constructor(config: TopKPoolConfig); /** * Apply nonlinearity to scores */ private applyNonlinearity; /** * Compute node scores from features */ private computeScores; /** * Select top-k nodes based on scores */ private selectTopK; /** * Filter edges to only include selected nodes */ private filterEdges; /** * Pool operation - performs top-k pooling * * @param input GraphData with node features * @returns PoolingResult with pooled graph and metadata */ pool(input: GraphData): PoolingResult; /** * Forward pass - performs top-k pooling and returns just the pooled graph * For Module compatibility. Use pool() to get full metadata. * * @param input GraphData with node features * @returns GraphData with pooled nodes */ forward(input: GraphData): GraphData; /** * Unpool - restore features to original positions * Useful for U-Net style architectures */ unpool(pooledFeatures: Tensor, perm: Uint32Array, originalNumNodes: number): Tensor; /** * Reset parameters */ resetParameters(): void; /** * Get layer description */ toString(): string; } /** * Global pooling operations for graph-level representations */ declare class GlobalPool { /** * Global mean pooling over nodes * * @param x Node features [numNodes, numFeatures] * @param batchIndex Optional batch assignment for batched graphs * @returns Graph-level features [batchSize, numFeatures] */ static mean(x: Tensor, batchIndex?: Uint32Array): Tensor; /** * Global max pooling over nodes */ static max(x: Tensor, batchIndex?: Uint32Array): Tensor; /** * Global sum pooling over nodes */ static sum(x: Tensor, batchIndex?: Uint32Array): Tensor; /** * Global attention pooling over nodes * Uses a learnable attention mechanism to weight nodes */ static attention(x: Tensor, gate: Tensor, batchIndex?: Uint32Array): Tensor; } /** * BrowserGNN by Dr. Lee * Planetoid Dataset Loaders (Cora, Citeseer, PubMed) * * Citation network datasets from: * "Revisiting Semi-Supervised Learning with Graph Embeddings" * by Yang et al. (2016) * * Datasets: * - Cora: 2708 nodes, 5429 edges, 7 classes, 1433 features * - Citeseer: 3327 nodes, 4732 edges, 6 classes, 3703 features * - PubMed: 19717 nodes, 44338 edges, 3 classes, 500 features * * This module provides: * 1. Synthetic versions for quick testing (similar statistics) * 2. Fetch functions for loading real datasets from URLs */ interface DatasetInfo { name: string; numNodes: number; numEdges: number; numFeatures: number; numClasses: number; trainMask: boolean[]; valMask: boolean[]; testMask: boolean[]; } interface CitationNetworkData { graph: GraphData; labels: Uint32Array; info: DatasetInfo; } /** * Planetoid Dataset Base Class * * Provides synthetic data generation and dataset loading utilities * for citation network datasets. */ declare class Planetoid { private config; private datasetName; constructor(name: 'cora' | 'citeseer' | 'pubmed'); /** * Generate a synthetic dataset with similar statistics * Useful for testing and development without downloading data */ generateSynthetic(scale?: number, seed?: number): CitationNetworkData; /** * Seeded random number generator (mulberry32) */ private seededRandom; /** * Get dataset metadata */ getInfo(): { name: string; numNodes: number; numEdges: number; numFeatures: number; numClasses: number; }; } /** * Cora Dataset * * Citation network of machine learning papers. * - 2708 scientific publications (nodes) * - 5429 citation links (edges) * - 7 classes (Neural Networks, Rule Learning, etc.) * - 1433 unique words (features, bag-of-words) */ declare class CoraDataset extends Planetoid { constructor(); /** * Load synthetic Cora-like dataset for testing */ static load(scale?: number, seed?: number): CitationNetworkData; /** * Get Cora dataset info */ static info(): { numNodes: number; numEdges: number; numFeatures: number; numClasses: number; }; } /** * Citeseer Dataset * * Citation network of computer science papers. * - 3327 scientific publications (nodes) * - 4732 citation links (edges) * - 6 classes (Agents, AI, DB, IR, ML, HCI) * - 3703 unique words (features, bag-of-words) */ declare class CiteseerDataset extends Planetoid { constructor(); /** * Load synthetic Citeseer-like dataset for testing */ static load(scale?: number, seed?: number): CitationNetworkData; /** * Get Citeseer dataset info */ static info(): { numNodes: number; numEdges: number; numFeatures: number; numClasses: number; }; } /** * PubMed Dataset * * Citation network of diabetes-related publications. * - 19717 scientific publications (nodes) * - 44338 citation links (edges) * - 3 classes (Diabetes Mellitus Type 1, Type 2, Experimental) * - 500 TF-IDF weighted words (features) */ declare class PubMedDataset extends Planetoid { constructor(); /** * Load synthetic PubMed-like dataset for testing */ static load(scale?: number, seed?: number): CitationNetworkData; /** * Get PubMed dataset info */ static info(): { numNodes: number; numEdges: number; numFeatures: number; numClasses: number; }; } /** * BrowserGNN by Dr. Lee * Karate Club Dataset * * Zachary's Karate Club network from: * "An Information Flow Model for Conflict and Fission in Small Groups" * by Wayne W. Zachary (1977) * * Dataset: * - 34 members (nodes) * - 78 edges (bidirectional friendships) * - 2 classes (factions after club split) * - Famous benchmark for community detection */ interface KarateClubData { graph: GraphData; labels: Uint32Array; numClasses: number; nodeNames: string[]; } /** * Karate Club Dataset * * Classic social network dataset showing the social ties * between members of a university karate club. * * The club eventually split into two factions: * - Faction 0: Members loyal to Mr. Hi (instructor) * - Faction 1: Members loyal to John A. (administrator) */ declare class KarateClub { /** * Load the Karate Club dataset * * @param numFeatures Number of random features per node (default: 34) * @returns KarateClubData with graph, labels, and metadata */ static load(numFeatures?: number): KarateClubData; /** * Get dataset statistics */ static info(): { numNodes: number; numEdges: number; numClasses: number; description: string; }; } /** * BrowserGNN by Dr. Lee * Backend Management * * Handles compute backend selection and initialization. * Supports WebGPU (preferred) with WASM/CPU fallback. */ type BackendType = 'webgpu' | 'wasm' | 'cpu'; interface BackendCapabilities { webgpu: boolean; wasm: boolean; sharedArrayBuffer: boolean; simd: boolean; } interface BackendConfig { preferredBackend?: BackendType; enableProfiling?: boolean; memoryLimit?: number; } /** * Initialize BrowserGNN backend * Call this before using any GNN operations */ declare function initBrowserGNN(config?: BackendConfig): Promise; /** * Get current backend type */ declare function getBackend(): BackendType; /** * Check backend capabilities */ declare function checkCapabilities(): Promise; /** * Get backend info */ declare function getBackendInfo(): string; /** * BrowserGNN by Dr. Lee * Performance Benchmarks * * Compare CPU vs WebGPU performance for GNN operations. * Phase 3: Training benchmarks for autograd, loss, and optimizer performance. */ interface BenchmarkResult { name: string; numNodes: number; numEdges: number; cpuTimeMs: number; gpuTimeMs: number | null; speedup: number | null; iterations: number; } interface BenchmarkConfig { warmupIterations?: number; benchmarkIterations?: number; nodeSizes?: number[]; edgeDensity?: number; } /** * Run GCN benchmarks */ declare function benchmarkGCN(userConfig?: BenchmarkConfig): Promise; /** * Run GraphSAGE benchmarks */ declare function benchmarkSAGE(userConfig?: BenchmarkConfig): Promise; /** * Run GAT benchmarks */ declare function benchmarkGAT(userConfig?: BenchmarkConfig): Promise; /** * Run all benchmarks */ declare function runAllBenchmarks(userConfig?: BenchmarkConfig): Promise<{ gcn: BenchmarkResult[]; sage: BenchmarkResult[]; gat: BenchmarkResult[]; backendInfo: ReturnType; gpuStats: ReturnType | null; }>; /** * Format benchmark results as a table */ declare function formatBenchmarkTable(results: BenchmarkResult[]): string; /** * Quick benchmark for demo purposes */ declare function quickBenchmark(): Promise; /** * BrowserGNN by Dr. Lee * Autograd Variable System * * Implements automatic differentiation with computational graph tracking. * Inspired by PyTorch's autograd system. */ /** * Backward function type - computes gradients with respect to inputs */ type BackwardFn = (grad: Tensor) => Tensor[]; /** * Computational graph node representing an operation */ interface GradNode { inputs: Variable[]; backward: BackwardFn; name: string; } /** * Variable - A tensor wrapper with gradient tracking * * Variables form a computational graph during forward pass, * which is then traversed backward to compute gradients. */ declare class Variable { readonly data: Tensor; grad: Tensor | null; readonly requiresGrad: boolean; readonly gradNode: GradNode | null; readonly name: string; private _gradAccumulated; constructor(data: Tensor, options?: { requiresGrad?: boolean; gradNode?: GradNode | null; name?: string; }); /** * Get tensor shape */ get shape(): number[]; /** * Get tensor size */ get size(): number; /** * Create a variable from raw data */ static fromArray(data: number[] | Float32Array, shape: number[], requiresGrad?: boolean, name?: string): Variable; /** * Create zeros variable */ static zeros(shape: number[], requiresGrad?: boolean): Variable; /** * Create ones variable */ static ones(shape: number[], requiresGrad?: boolean): Variable; /** * Create random variable (uniform 0-1) */ static rand(shape: number[], requiresGrad?: boolean): Variable; /** * Create random variable (normal distribution) */ static randn(shape: number[], requiresGrad?: boolean): Variable; /** * Detach from computational graph */ detach(): Variable; /** * Zero gradients */ zeroGrad(): void; /** * Accumulate gradient */ accumulateGrad(grad: Tensor): void; /** * Backward pass - compute gradients through the graph * * @param grad Optional upstream gradient (defaults to ones for scalar loss) */ backward(grad?: Tensor): void; /** * Matrix multiplication: this @ other */ matmul(other: Variable): Variable; /** * Element-wise addition */ add(other: Variable): Variable; /** * Element-wise subtraction */ sub(other: Variable): Variable; /** * Element-wise multiplication */ mul(other: Variable): Variable; /** * Element-wise division */ div(other: Variable): Variable; /** * ReLU activation */ relu(): Variable; /** * Sigmoid activation */ sigmoid(): Variable; /** * Tanh activation */ tanh(): Variable; /** * Softmax (along last dimension) */ softmax(): Variable; /** * Log softmax (more numerically stable for cross-entropy) */ logSoftmax(): Variable; /** * Sum all elements */ sum(): Variable; /** * Mean of all elements */ mean(): Variable; /** * Negation */ neg(): Variable; /** * Transpose (2D only) */ transpose(): Variable; /** * Helper: Reduce gradient for broadcasting */ private _reduceBroadcast; } /** * BrowserGNN by Dr. Lee * Loss Functions for Training */ /** * Cross-Entropy Loss * * For classification tasks. Combines log-softmax and NLL loss. * loss = -sum(target * log(softmax(input))) */ declare function crossEntropyLoss(input: Variable, target: Uint32Array | number[], options?: { reduction?: 'mean' | 'sum' | 'none'; }): Variable; /** * Mean Squared Error Loss * * For regression tasks. * loss = mean((input - target)^2) */ declare function mseLoss(input: Variable, target: Variable, options?: { reduction?: 'mean' | 'sum' | 'none'; }): Variable; /** * Binary Cross-Entropy Loss * * For binary classification with sigmoid output. * loss = -mean(target * log(input) + (1 - target) * log(1 - input)) */ declare function binaryCrossEntropyLoss(input: Variable, target: Variable, options?: { reduction?: 'mean' | 'sum' | 'none'; eps?: number; }): Variable; /** * Negative Log Likelihood Loss * * Use after log_softmax for classification. */ declare function nllLoss(input: Variable, target: Uint32Array | number[], options?: { reduction?: 'mean' | 'sum' | 'none'; }): Variable; /** * L1 Loss (Mean Absolute Error) */ declare function l1Loss(input: Variable, target: Variable, options?: { reduction?: 'mean' | 'sum' | 'none'; }): Variable; /** * Smooth L1 Loss (Huber Loss) * * Less sensitive to outliers than MSE. */ declare function smoothL1Loss(input: Variable, target: Variable, options?: { reduction?: 'mean' | 'sum' | 'none'; beta?: number; }): Variable; /** * BrowserGNN by Dr. Lee * Optimizers for Training */ /** * Parameter group with optional per-group settings */ interface ParamGroup { params: Variable[]; lr?: number; weightDecay?: number; } /** * Base Optimizer class */ declare abstract class Optimizer { protected paramGroups: ParamGroup[]; protected defaults: Record; protected _step: number; constructor(params: Variable[] | ParamGroup[], defaults?: Record); /** * Zero all gradients */ zeroGrad(): void; /** * Get current step count */ get step(): number; /** * Perform a single optimization step */ abstract stepOptimizer(): void; /** * Get all parameters */ getParams(): Variable[]; /** * Get state dict for serialization */ abstract stateDict(): Record; /** * Load state dict */ abstract loadStateDict(stateDict: Record): void; } /** * Stochastic Gradient Descent Optimizer * * Supports momentum and weight decay. * * v_t = momentum * v_{t-1} + grad * param = param - lr * v_t - lr * weightDecay * param */ declare class SGD extends Optimizer { private momentum; private dampening; private nesterov; private velocities; constructor(params: Variable[] | ParamGroup[], options?: { lr?: number; momentum?: number; dampening?: number; weightDecay?: number; nesterov?: boolean; }); stepOptimizer(): void; stateDict(): Record; loadStateDict(stateDict: Record): void; } /** * Adam Optimizer * * Adaptive Moment Estimation with bias correction. * * m_t = beta1 * m_{t-1} + (1 - beta1) * grad * v_t = beta2 * v_{t-1} + (1 - beta2) * grad^2 * m_hat = m_t / (1 - beta1^t) * v_hat = v_t / (1 - beta2^t) * param = param - lr * m_hat / (sqrt(v_hat) + eps) */ declare class Adam extends Optimizer { private beta1; private beta2; private eps; private amsgrad; private m; private v; private vMax; constructor(params: Variable[] | ParamGroup[], options?: { lr?: number; beta1?: number; beta2?: number; eps?: number; weightDecay?: number; amsgrad?: boolean; }); stepOptimizer(): void; stateDict(): Record; loadStateDict(stateDict: Record): void; } /** * AdaGrad Optimizer * * Adaptive gradient with accumulated squared gradients. */ declare class Adagrad extends Optimizer { private eps; private sumSquares; constructor(params: Variable[] | ParamGroup[], options?: { lr?: number; eps?: number; weightDecay?: number; }); stepOptimizer(): void; stateDict(): Record; loadStateDict(stateDict: Record): void; } /** * RMSprop Optimizer */ declare class RMSprop extends Optimizer { private alpha; private eps; private momentum; private centered; private squareAvg; private gradAvg; private momentumBuffer; constructor(params: Variable[] | ParamGroup[], options?: { lr?: number; alpha?: number; eps?: number; weightDecay?: number; momentum?: number; centered?: boolean; }); stepOptimizer(): void; stateDict(): Record; loadStateDict(stateDict: Record): void; } /** * Learning Rate Scheduler Base */ declare abstract class LRScheduler { protected optimizer: Optimizer; protected baseLrs: number[]; protected lastEpoch: number; constructor(optimizer: Optimizer); abstract getLr(): number[]; step(epoch?: number): void; get currentLr(): number; } /** * Step Learning Rate Scheduler * * Decays the learning rate by gamma every step_size epochs. */ declare class StepLR extends LRScheduler { private stepSize; private gamma; constructor(optimizer: Optimizer, stepSize: number, gamma?: number); getLr(): number[]; } /** * Exponential Learning Rate Scheduler */ declare class ExponentialLR extends LRScheduler { private gamma; constructor(optimizer: Optimizer, gamma: number); getLr(): number[]; } /** * Cosine Annealing Learning Rate Scheduler */ declare class CosineAnnealingLR extends LRScheduler { private tMax; private etaMin; constructor(optimizer: Optimizer, tMax: number, etaMin?: number); getLr(): number[]; } /** * BrowserGNN by Dr. Lee * Trainer Module - High-level Training API */ /** * Training metrics for a single epoch */ interface TrainingMetrics { epoch: number; loss: number; accuracy?: number; valLoss?: number; valAccuracy?: number; learningRate: number; duration: number; timestamp: number; } /** * Callback for training events */ type TrainingCallback = (metrics: TrainingMetrics) => void | Promise; /** * Trainer configuration */ interface TrainerConfig { optimizer: Optimizer; lossFunction?: 'cross_entropy' | 'mse' | 'nll'; maxEpochs?: number; patience?: number; minDelta?: number; logEvery?: number; evalEvery?: number; callbacks?: TrainingCallback[]; } /** * Trainable GNN Layer interface */ interface TrainableLayer { forward(input: GraphData): GraphData; getTrainableVariables(): Variable[]; } /** * Simple GNN model wrapper for training */ declare class GNNModel { private layers; private _variables; constructor(); /** * Add a layer to the model */ addLayer(layer: TrainableLayer): this; /** * Forward pass through all layers */ forward(input: GraphData): GraphData; /** * Get all trainable variables */ getVariables(): Variable[]; /** * Get number of parameters */ numParameters(): number; } /** * High-level Trainer class * * Provides training loop, metrics tracking, and callbacks for GNN models. */ declare class Trainer { private config; private history; private bestLoss; private patienceCounter; private _isTraining; private _stopRequested; constructor(config: TrainerConfig); /** * Get training history */ getHistory(): TrainingMetrics[]; /** * Check if currently training */ get isTraining(): boolean; /** * Request training to stop */ stop(): void; /** * Train a model on node classification task * * @param model The model to train * @param graph The graph data * @param labels Node labels (class indices) * @param trainMask Boolean mask for training nodes * @param valMask Optional boolean mask for validation nodes */ train(model: GNNModel, graph: GraphData, labels: Uint32Array | number[], trainMask: boolean[], valMask?: boolean[]): Promise; /** * Single training step (for manual training loops) */ trainStep(model: GNNModel, graph: GraphData, labels: Uint32Array | number[], trainMask: boolean[]): { loss: number; accuracy: number; }; /** * Evaluate model on masked nodes */ evaluate(model: GNNModel, graph: GraphData, labels: Uint32Array | number[], mask: boolean[]): { loss: number; accuracy: number; }; /** * Helper: Gather rows from a variable */ private _gatherRows; /** * Helper: Compute accuracy */ private _computeAccuracy; /** * Helper: Get current learning rate */ private _getCurrentLr; /** * Helper: Copy gradients from output back to model variables * This is a simplified gradient propagation for the GNN layers */ private _copyGradients; } /** * BrowserGNN by Dr. Lee * Model Serialization * * Save and load trained GNN models to/from JSON format. * Enables persistence of trained models in browser storage or file download. */ /** * Serialized model format */ interface SerializedModel { version: string; name: string; timestamp: string; architecture: string; parameters: SerializedParameter[]; metadata?: Record; } /** * Serialized parameter format */ interface SerializedParameter { name: string; shape: number[]; data: number[]; requiresGrad: boolean; } /** * State dict format (like PyTorch) */ type StateDict = Map; /** * Serialize a module's parameters to a state dict */ declare function getStateDict(module: Module): StateDict; /** * Load parameters from a state dict into a module */ declare function loadStateDict(module: Module, stateDict: StateDict, strict?: boolean): { missing: string[]; unexpected: string[]; }; /** * Serialize a module to JSON-compatible format */ declare function serializeModel(module: Module, name?: string, metadata?: Record): SerializedModel; /** * Deserialize parameters from a serialized model format */ declare function deserializeModel(serialized: SerializedModel): StateDict; /** * Save model to JSON string */ declare function saveModelToJSON(module: Module, name?: string, metadata?: Record): string; /** * Load model from JSON string */ declare function loadModelFromJSON(module: Module, json: string, strict?: boolean): { model: SerializedModel; missing: string[]; unexpected: string[]; }; /** * Download model as JSON file (browser only) */ declare function downloadModel(module: Module, filename?: string, metadata?: Record): void; /** * Save model to localStorage (browser only) */ declare function saveModelToStorage(module: Module, key: string, metadata?: Record): void; /** * Load model from localStorage (browser only) */ declare function loadModelFromStorage(module: Module, key: string, strict?: boolean): { model: SerializedModel; missing: string[]; unexpected: string[]; } | null; /** * List all saved models in localStorage */ declare function listSavedModels(): string[]; /** * Delete a saved model from localStorage */ declare function deleteSavedModel(key: string): boolean; /** * Calculate model size in bytes */ declare function getModelSize(module: Module): { parameters: number; bytes: number; formatted: string; }; /** * BrowserGNN by Dr. Lee * Student Mastery Predictor * * A GNN model for predicting student mastery levels in a knowledge graph. * Designed for integration with learning platforms like LearningScience.ai. * * Use Cases: * - Knowledge tracing: Predict student mastery of concepts * - Learning analytics: Identify knowledge gaps * - Personalized learning: Recommend focus areas * * Graph Structure: * - Nodes: Concepts/skills in a curriculum * - Node Features: Concept embeddings, difficulty, student performance history * - Edges: Prerequisite relationships, semantic similarity * - Output: Mastery probability for each concept (0-1) */ interface StudentMasteryPredictorConfig { /** * Number of input features per concept node. * Includes: concept embedding, difficulty, historical performance, etc. */ inputFeatures: number; /** * Hidden dimension for GNN layers. * Default: 64 */ hiddenDim?: number; /** * Number of GNN layers. * Default: 2 */ numLayers?: number; /** * Whether to use attention mechanism (GAT) instead of GCN. * Default: false */ useAttention?: boolean; /** * Number of attention heads (if useAttention=true). * Default: 4 */ numHeads?: number; /** * Dropout rate for regularization. * Default: 0.1 */ dropout?: number; /** * Whether to use residual connections. * Default: true */ residual?: boolean; } /** * Student Mastery Predictor Model * * Architecture: * 1. Input projection: Linear(inputFeatures -> hiddenDim) * 2. GNN layers (GCN or GAT) for message passing * 3. Output head: Linear(hiddenDim -> 1) + Sigmoid * * The model propagates mastery information through the knowledge graph, * allowing prerequisites to influence predicted mastery. */ declare class StudentMasteryPredictor extends Module { readonly config: Required; private inputProj; private gnnLayers; private dropout; private outputHead; constructor(config: StudentMasteryPredictorConfig); /** * Forward pass to predict mastery levels. * * @param graph Knowledge graph with concept nodes * @returns Tensor of shape [numNodes, 1] with mastery probabilities */ forward(graph: GraphData): Promise; /** * Predict mastery for all concepts in the graph. * * @param graph Knowledge graph * @returns Object with mastery scores and predictions */ predict(graph: GraphData): Promise<{ mastery: number[]; predictions: { nodeIndex: number; score: number; mastered: boolean; }[]; }>; /** * Get concepts that need the most attention. * * @param graph Knowledge graph * @param topK Number of concepts to return * @returns Indices and scores of concepts needing attention */ getWeakConcepts(graph: GraphData, topK?: number): Promise<{ nodeIndex: number; score: number; }[]>; /** * Create a sample knowledge graph for testing. * Represents a simple math curriculum. */ static createSampleGraph(numConcepts?: number): GraphData; toString(): string; } /** * BrowserGNN by Dr. Lee * Learning Path Recommender * * A GNN model for recommending optimal learning paths through a curriculum. * Uses graph structure to find the best sequence of concepts to learn. * * Use Cases: * - Curriculum sequencing: Determine optimal order of topics * - Adaptive learning: Personalize paths based on student state * - Gap filling: Identify missing prerequisite knowledge * * Graph Structure: * - Nodes: Concepts/skills in a curriculum * - Node Features: Concept embeddings, difficulty, learning time, mastery level * - Edges: Prerequisite relationships (directed), semantic similarity * - Edge Features: Strength of prerequisite relationship * - Output: Priority scores for next concepts to learn */ interface LearningPathRecommenderConfig { /** * Number of input features per concept node. */ inputFeatures: number; /** * Hidden dimension for GNN layers. * Default: 64 */ hiddenDim?: number; /** * Number of GNN layers. * Default: 3 */ numLayers?: number; /** * Aggregation method for GraphSAGE. * Default: 'mean' */ aggregator?: 'mean' | 'max' | 'sum' | 'pool'; /** * Whether to use GIN layers instead of SAGE. * GIN is more expressive for graph isomorphism tasks. * Default: false */ useGIN?: boolean; /** * Dropout rate for regularization. * Default: 0.1 */ dropout?: number; /** * Whether to normalize output scores (softmax). * Default: true */ normalizeScores?: boolean; } /** * Learning Path Recommender Model * * Architecture: * 1. Input projection with LeakyReLU * 2. GraphSAGE or GIN layers for neighborhood aggregation * 3. MLP scoring head * 4. Optional softmax normalization * * The model learns to score concepts based on: * - Current mastery levels of prerequisites * - Structural position in the knowledge graph * - Concept difficulty and learning time */ declare class LearningPathRecommender extends Module { readonly config: Required; private inputProj; private gnnLayers; private dropout; private scoringHead; private softmax; constructor(config: LearningPathRecommenderConfig); /** * Forward pass to compute priority scores. * * @param graph Knowledge graph with concept nodes * @param maskMastered Optional boolean array to mask already mastered concepts * @returns Tensor of shape [numNodes, 1] with priority scores */ forward(graph: GraphData, maskMastered?: boolean[]): Promise; /** * Recommend next concepts to learn. * * @param graph Knowledge graph * @param masteredNodes Indices of already mastered nodes * @param topK Number of recommendations * @returns Ranked list of concept recommendations */ recommend(graph: GraphData, masteredNodes?: number[], topK?: number): Promise<{ recommendations: { nodeIndex: number; score: number; rank: number; }[]; allScores: number[]; }>; /** * Get a complete learning path from current state to goal. * * @param graph Knowledge graph * @param masteredNodes Currently mastered nodes * @param goalNodes Target nodes to reach * @param maxSteps Maximum path length * @returns Ordered learning path */ getLearningPath(graph: GraphData, masteredNodes: number[], goalNodes: number[], maxSteps?: number): Promise<{ path: number[]; scores: number[]; }>; /** * Create a sample curriculum graph for testing. */ static createSampleCurriculum(numConcepts?: number): GraphData; toString(): string; } /** * BrowserGNN by Dr. Lee * Concept Prerequisite Mapper * * A GNN model for discovering and predicting prerequisite relationships * between concepts in an educational domain. * * Use Cases: * - Curriculum design: Automatically discover prerequisite structure * - Knowledge gap detection: Find missing prerequisite connections * - Transfer learning: Map concepts across different curricula * - Dependency analysis: Identify critical path concepts * * Graph Structure: * - Nodes: Concepts/skills * - Node Features: Concept embeddings, metadata * - Edges: Known prerequisite relationships (can be sparse/incomplete) * - Output: Link prediction scores for potential prerequisite edges */ interface ConceptPrerequisiteMapperConfig { /** * Number of input features per concept node. */ inputFeatures: number; /** * Hidden dimension for GNN layers and embeddings. * Default: 64 */ hiddenDim?: number; /** * Number of GNN layers for encoding. * Default: 2 */ numLayers?: number; /** * Whether to use attention mechanism. * Default: true (GAT better captures asymmetric relationships) */ useAttention?: boolean; /** * Number of attention heads. * Default: 4 */ numHeads?: number; /** * Dropout rate. * Default: 0.2 */ dropout?: number; /** * Link prediction method: 'dot' (dot product), 'bilinear', or 'mlp' * Default: 'mlp' */ linkPredictor?: 'dot' | 'bilinear' | 'mlp'; } /** * Concept Prerequisite Mapper Model * * Architecture: * 1. Input projection * 2. GNN encoder (GCN or GAT) for node embeddings * 3. Link prediction head for prerequisite scoring * * The model learns embeddings such that prerequisite relationships * can be predicted from the embeddings of source and target concepts. */ declare class ConceptPrerequisiteMapper extends Module { readonly config: Required; private inputProj; private gnnLayers; private dropout; private linkPredictor; private bilinearWeight; private sigmoid; constructor(config: ConceptPrerequisiteMapperConfig); /** * Encode nodes to get embeddings. * * @param graph Knowledge graph * @returns Node embeddings [numNodes, hiddenDim] */ encode(graph: GraphData): Promise; /** * Predict prerequisite probability for given node pairs. * * @param embeddings Node embeddings from encode() * @param srcNodes Source node indices * @param tgtNodes Target node indices * @returns Prerequisite probabilities for each pair */ predictLinks(embeddings: Tensor, srcNodes: number[], tgtNodes: number[]): number[]; /** * Forward pass to get node embeddings. * Use predictAllLinks for link prediction. * * @param graph Knowledge graph * @returns Node embeddings */ forward(graph: GraphData): Promise; /** * Full forward pass: encode graph and predict all potential links. * * @param graph Knowledge graph * @param candidatePairs Optional specific pairs to evaluate * @returns Link predictions */ predictAllLinks(graph: GraphData, candidatePairs?: { src: number[]; tgt: number[]; }): Promise<{ embeddings: Tensor; scores: number[]; pairs: { src: number; tgt: number; score: number; }[]; }>; /** * Discover new prerequisite relationships. * * @param graph Knowledge graph with known prerequisites * @param threshold Score threshold for prediction * @param topK Maximum number of new edges to return * @returns Predicted new prerequisite edges */ discoverPrerequisites(graph: GraphData, threshold?: number, topK?: number): Promise<{ newEdges: { src: number; tgt: number; score: number; }[]; existingEdges: Set; }>; /** * Find critical prerequisite chains (longest paths). * * @param graph Knowledge graph * @param startNode Starting concept * @returns Critical path information */ findCriticalPath(graph: GraphData, startNode: number): { path: number[]; length: number; }; /** * Create a sample concept graph for testing. */ static createSampleConceptGraph(numConcepts?: number): GraphData; toString(): string; } /** * BrowserGNN by Dr. Lee * * The first comprehensive Graph Neural Network library for the browser. * Enables client-side graph learning with WebGPU acceleration and WASM fallback. * * @packageDocumentation */ declare const VERSION = "0.6.0"; declare const AUTHOR = "Dr. Lee"; declare function createBrowserGNN(config?: { preferredBackend?: 'webgpu' | 'wasm' | 'cpu'; enableProfiling?: boolean; }): Promise<{ backend: string; info: string; }>; declare const _default: { VERSION: string; AUTHOR: string; createBrowserGNN: typeof createBrowserGNN; }; export { AUTHOR, Adagrad, Adam, type BackendCapabilities, type BackendConfig, type BackendType, type BackwardFn, type BenchmarkConfig, type BenchmarkResult, ChebConv, type ChebConvConfig, type CitationNetworkData, CiteseerDataset, ConceptPrerequisiteMapper, type ConceptPrerequisiteMapperConfig, CoraDataset, CosineAnnealingLR, type DataType, type DatasetInfo, Dropout, ELU, EdgeConv, type EdgeConvConfig, ExponentialLR, GATConv, type GATConvConfig, GCNConv, type GCNConvConfig, GELU, GINConv, type GINConvConfig, GPUSparse, GPUTensor, GlobalPool, type GradNode, GraphData, type GraphDataConfig, KarateClub, LRScheduler, LeakyReLU, LearningPathRecommender, type LearningPathRecommenderConfig, Linear, type LinearConfig, LogSoftmax, MessagePassing, Module, Optimizer, PReLU, type ParamGroup, type Parameter, Planetoid, type PoolingResult, PubMedDataset, RMSprop, ReLU, type SAGEAggregator, SAGEConv, type SAGEConvConfig, SGD, Sequential, type SerializedModel, type SerializedParameter, type Shape, SiLU, Sigmoid, Softmax, SparseCOO, SparseCSR, type StateDict, StepLR, StudentMasteryPredictor, type StudentMasteryPredictorConfig, Tanh, Tensor, TopKPool, type TopKPoolConfig, Trainer, type TrainerConfig, type TrainingMetrics, type TypedArray, VERSION, Variable, batchGraphs, benchmarkGAT, benchmarkGCN, benchmarkSAGE, binaryCrossEntropyLoss, checkCapabilities, computeGCNNorm, concat, createBrowserGNN, crossEntropyLoss, _default as default, deleteSavedModel, deserializeModel, downloadModel, formatBenchmarkTable, fromEdgeList, getBackend, getBackendInfo, getGPUStats, getModelSize, getStateDict, initBrowserGNN, isGPUAvailable, l1Loss, listSavedModels, loadModelFromJSON, loadModelFromStorage, loadStateDict, mseLoss, nllLoss, quickBenchmark, randomGraph, runAllBenchmarks, saveModelToJSON, saveModelToStorage, serializeModel, smoothL1Loss, stack };