@danielsimonjr/mathts-matrix 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +391 -804
  2. package/dist/index.js +1740 -2359
  3. package/package.json +6 -5
package/dist/index.d.ts CHANGED
@@ -1,4 +1,8 @@
1
+ /// <reference types="@webgpu/types" />
2
+ import * as workerpool from 'workerpool';
1
3
  import { ComputePool, ComputePoolConfig } from '@danielsimonjr/mathts-parallel';
4
+ import { GPUContextOptions, GPUCapabilities, GPUContext, BufferPool, ShaderManager } from '@danielsimonjr/mathts-gpu';
5
+ export { BufferPool, GPUCapabilities, GPUContext, GPUContextOptions, ShaderManager, destroyGlobalGPU, detectGPUCapabilities, getGlobalGPUContext, getRecommendedWorkgroupSize, hasWebGPU } from '@danielsimonjr/mathts-gpu';
2
6
  import * as typed_function from 'typed-function';
3
7
 
4
8
  /**
@@ -854,96 +858,6 @@ declare class JSBackend implements MatrixBackend {
854
858
  */
855
859
  declare const jsBackend: JSBackend;
856
860
 
857
- /**
858
- * Stub type declarations for workerpool.
859
- * The actual workerpool package ships raw .ts sources without pre-built .d.ts files.
860
- * This stub prevents TypeScript from diving into the raw source during type-checking.
861
- */
862
- declare module 'workerpool' {
863
- export interface ExecOptions<T = unknown> {
864
- on?: (payload: unknown) => void;
865
- transfer?: Transferable[];
866
- metadata?: T;
867
- }
868
-
869
- export interface PoolStats {
870
- totalWorkers: number;
871
- busyWorkers: number;
872
- idleWorkers: number;
873
- pendingTasks: number;
874
- activeTasks: number;
875
- }
876
-
877
- export interface PoolOptions {
878
- minWorkers?: number | 'max';
879
- maxWorkers?: number;
880
- maxQueueSize?: number;
881
- workerType?: 'auto' | 'web' | 'process' | 'thread';
882
- queueStrategy?: 'fifo' | 'lifo';
883
- script?: string;
884
- workerTerminateTimeout?: number;
885
- forkArgs?: string[];
886
- forkOpts?: Record<string, unknown>;
887
- workerOpts?: Record<string, unknown>;
888
- workerThreadOpts?: Record<string, unknown>;
889
- emitStdStreams?: boolean;
890
- onCreateWorker?: (arg: Record<string, unknown>) => Record<string, unknown> | void;
891
- onTerminateWorker?: (arg: Record<string, unknown>) => void;
892
- debugPortStart?: number;
893
- }
894
-
895
- export interface WorkerpoolPromise<T> extends Promise<T> {
896
- readonly resolved: boolean;
897
- readonly rejected: boolean;
898
- readonly pending: boolean;
899
- cancel(): this;
900
- timeout(delay: number): this;
901
- }
902
-
903
- export type WorkerProxy<T extends Record<string, (...args: unknown[]) => unknown>> = {
904
- [K in keyof T]: (...args: Parameters<T[K]>) => WorkerpoolPromise<ReturnType<T[K]>>;
905
- };
906
-
907
- export class Pool {
908
- constructor(script?: string | PoolOptions, options?: PoolOptions);
909
- exec<T>(
910
- method: string | ((...args: unknown[]) => T),
911
- params?: unknown[],
912
- options?: ExecOptions
913
- ): WorkerpoolPromise<T>;
914
- proxy<T extends Record<string, (...args: unknown[]) => unknown>>(): Promise<WorkerProxy<T>>;
915
- stats(): PoolStats;
916
- terminate(force?: boolean, timeout?: number): Promise<void>;
917
- }
918
-
919
- export interface TransferDescriptor<T = unknown> {
920
- message: T;
921
- transfer: Transferable[];
922
- }
923
-
924
- export class Transfer<T = unknown> {
925
- message: T;
926
- transfer: Transferable[];
927
- constructor(message: T, transfer: Transferable[]);
928
- }
929
-
930
- export class CancellationError extends Error {}
931
- export class TimeoutError extends Error {}
932
- export class TerminateError extends Error {}
933
-
934
- export function pool(script?: string | PoolOptions, options?: PoolOptions): Pool;
935
-
936
- export function worker(
937
- methods?: Record<string, (...args: unknown[]) => unknown>,
938
- options?: {
939
- onTerminate?: (code: number | undefined) => void | PromiseLike<void>;
940
- abortListenerTimeout?: number;
941
- }
942
- ): void;
943
-
944
- export function workerEmit(payload: unknown): void;
945
- }
946
-
947
861
  /**
948
862
  * Configuration for ParallelBackend
949
863
  */
@@ -1050,7 +964,7 @@ declare class ParallelBackend {
1050
964
  /**
1051
965
  * Get pool statistics
1052
966
  */
1053
- getStats(): undefined;
967
+ getStats(): workerpool.PoolStats;
1054
968
  private checkDimensionsMatch;
1055
969
  private checkMultiplyDimensions;
1056
970
  }
@@ -1276,118 +1190,51 @@ declare const wasmBackend: WASMBackend;
1276
1190
  declare function createWASMBackend(config?: WASMBackendConfig): WASMBackend;
1277
1191
 
1278
1192
  /**
1279
- * WebGPU Detection and Capability Checking
1280
- *
1281
- * Provides runtime detection of WebGPU support and adapter capabilities.
1282
- */
1283
- /**
1284
- * WebGPU adapter information
1285
- */
1286
- interface GPUAdapterInfo {
1287
- /** Adapter vendor */
1288
- vendor: string;
1289
- /** Adapter architecture */
1290
- architecture: string;
1291
- /** Device description */
1292
- device: string;
1293
- /** Driver description */
1294
- description: string;
1295
- }
1296
- /**
1297
- * WebGPU capability information
1298
- */
1299
- interface GPUCapabilities {
1300
- /** Whether WebGPU is supported */
1301
- supported: boolean;
1302
- /** Adapter information if available */
1303
- adapterInfo: GPUAdapterInfo | null;
1304
- /** Maximum buffer size in bytes */
1305
- maxBufferSize: number;
1306
- /** Maximum compute workgroup size */
1307
- maxWorkgroupSize: [number, number, number];
1308
- /** Maximum storage buffer binding size */
1309
- maxStorageBufferBindingSize: number;
1310
- /** Maximum compute invocations per workgroup */
1311
- maxComputeInvocationsPerWorkgroup: number;
1312
- /** Maximum workgroups per dimension */
1313
- maxComputeWorkgroupsPerDimension: number;
1314
- /** Whether the adapter is a fallback/software adapter */
1315
- isFallbackAdapter: boolean;
1316
- /** Supported features */
1317
- features: string[];
1318
- }
1319
- /**
1320
- * Check if WebGPU is available in the current environment
1321
- */
1322
- declare function hasWebGPU(): boolean;
1323
- /**
1324
- * Detect WebGPU capabilities
1325
- * @param preferHighPerformance - Whether to prefer high-performance GPU
1326
- */
1327
- declare function detectGPUCapabilities(preferHighPerformance?: boolean): Promise<GPUCapabilities>;
1328
- /**
1329
- * Recommended workgroup size based on GPU capabilities
1330
- */
1331
- declare function getRecommendedWorkgroupSize(capabilities: GPUCapabilities): [number, number, number];
1332
-
1333
- /**
1334
- * WebGPU Context Management
1193
+ * GPU Backend for Matrix Operations
1335
1194
  *
1336
- * Manages WebGPU device, queue, and command encoding.
1195
+ * WebGPU-accelerated matrix operations for large matrices.
1337
1196
  */
1338
1197
 
1339
1198
  /**
1340
- * Options for GPUContext initialization
1341
- */
1342
- interface GPUContextOptions {
1343
- /** Prefer high-performance GPU */
1344
- preferHighPerformance?: boolean;
1345
- /** Required features for the device */
1346
- requiredFeatures?: GPUFeatureName[];
1347
- /** Required limits for the device */
1348
- requiredLimits?: Record<string, number>;
1349
- /** Label for debugging */
1350
- label?: string;
1351
- }
1352
- /**
1353
- * Status of the GPU context
1199
+ * GPU Backend status
1354
1200
  */
1355
- type GPUContextStatus = 'uninitialized' | 'initializing' | 'ready' | 'error' | 'lost';
1201
+ type GPUBackendStatus = 'uninitialized' | 'initializing' | 'ready' | 'error' | 'unsupported';
1356
1202
  /**
1357
- * Event emitted when device is lost
1203
+ * Options for GPU backend
1358
1204
  */
1359
- interface DeviceLostEvent {
1360
- reason: GPUDeviceLostReason;
1361
- message: string;
1205
+ interface GPUBackendOptions extends GPUContextOptions {
1206
+ /** Use global GPU context instead of creating a new one */
1207
+ useGlobalContext?: boolean;
1208
+ /** Buffer pool options */
1209
+ bufferPoolOptions?: {
1210
+ maxCacheSize?: number;
1211
+ evictionTimeout?: number;
1212
+ };
1213
+ /** Threshold for using GPU (matrix size) */
1214
+ threshold?: number;
1362
1215
  }
1363
1216
  /**
1364
- * GPU Context manages the lifecycle of WebGPU resources
1217
+ * GPU Backend for accelerated matrix operations
1365
1218
  */
1366
- declare class GPUContext {
1367
- private adapter;
1368
- private device;
1219
+ declare class GPUBackend {
1220
+ private context;
1221
+ private bufferPool;
1222
+ private shaderManager;
1369
1223
  private _status;
1370
1224
  private _capabilities;
1371
1225
  private _lastError;
1372
- private deviceLostCallbacks;
1373
- private label;
1374
- constructor(options?: GPUContextOptions);
1226
+ private threshold;
1227
+ private workgroupSize;
1228
+ private useGlobalContext;
1229
+ constructor(options?: GPUBackendOptions);
1375
1230
  /**
1376
1231
  * Get the current status
1377
1232
  */
1378
- get status(): GPUContextStatus;
1233
+ get status(): GPUBackendStatus;
1379
1234
  /**
1380
- * Check if context is ready
1235
+ * Check if backend is ready
1381
1236
  */
1382
1237
  get isReady(): boolean;
1383
- /**
1384
- * Get the GPU device (throws if not initialized)
1385
- */
1386
- getDevice(): GPUDevice;
1387
- /**
1388
- * Get the GPU queue
1389
- */
1390
- getQueue(): GPUQueue;
1391
1238
  /**
1392
1239
  * Get capabilities
1393
1240
  */
@@ -1397,256 +1244,447 @@ declare class GPUContext {
1397
1244
  */
1398
1245
  get lastError(): Error | null;
1399
1246
  /**
1400
- * Initialize the GPU context
1401
- */
1402
- initialize(options?: GPUContextOptions): Promise<boolean>;
1403
- /**
1404
- * Register callback for device lost event
1405
- */
1406
- onDeviceLost(callback: (event: DeviceLostEvent) => void): void;
1407
- /**
1408
- * Create a command encoder
1409
- */
1410
- createCommandEncoder(label?: string): GPUCommandEncoder;
1411
- /**
1412
- * Create a buffer
1247
+ * Initialize the GPU backend
1413
1248
  */
1414
- createBuffer(size: number, usage: GPUBufferUsageFlags, label?: string, mappedAtCreation?: boolean): GPUBuffer;
1249
+ initialize(options?: GPUBackendOptions): Promise<boolean>;
1415
1250
  /**
1416
- * Create a storage buffer for compute operations
1251
+ * Check if GPU should be used for the given matrix size
1417
1252
  */
1418
- createStorageBuffer(size: number, label?: string, readable?: boolean, writable?: boolean): GPUBuffer;
1253
+ shouldUseGPU(rows: number, cols: number): boolean;
1419
1254
  /**
1420
- * Create a staging buffer for reading back data
1255
+ * Calculate workgroup counts for a matrix
1421
1256
  */
1422
- createStagingBuffer(size: number, label?: string): GPUBuffer;
1257
+ calculateWorkgroups(rows: number, cols: number): [number, number, number];
1423
1258
  /**
1424
- * Create a compute pipeline
1259
+ * Get the GPU context
1425
1260
  */
1426
- createComputePipeline(shaderModule: GPUShaderModule, entryPoint: string, layout?: GPUPipelineLayout | 'auto', label?: string): GPUComputePipeline;
1261
+ getContext(): GPUContext;
1427
1262
  /**
1428
- * Create a shader module from WGSL source
1263
+ * Get the buffer pool
1429
1264
  */
1430
- createShaderModule(code: string, label?: string): GPUShaderModule;
1265
+ getBufferPool(): BufferPool;
1431
1266
  /**
1432
- * Create a bind group
1267
+ * Get the shader manager
1433
1268
  */
1434
- createBindGroup(layout: GPUBindGroupLayout, entries: GPUBindGroupEntry[], label?: string): GPUBindGroup;
1269
+ getShaderManager(): ShaderManager;
1435
1270
  /**
1436
- * Submit commands to the GPU queue
1271
+ * Add two matrices element-wise
1437
1272
  */
1438
- submitCommands(commandBuffers: GPUCommandBuffer[]): void;
1273
+ add(a: Float32Array, b: Float32Array, rows: number, cols: number): Promise<Float32Array>;
1439
1274
  /**
1440
- * Write data to a buffer
1275
+ * Multiply two matrices
1441
1276
  */
1442
- writeBuffer(buffer: GPUBuffer, data: ArrayBufferView | ArrayBuffer | SharedArrayBuffer, bufferOffset?: number, dataOffset?: number, size?: number): void;
1277
+ matmul(a: Float32Array, b: Float32Array, M: number, K: number, N: number): Promise<Float32Array>;
1443
1278
  /**
1444
- * Read data from a buffer (async)
1279
+ * Transpose a matrix
1445
1280
  */
1446
- readBuffer(buffer: GPUBuffer, offset?: number, size?: number): Promise<ArrayBuffer>;
1281
+ transpose(a: Float32Array, rows: number, cols: number): Promise<Float32Array>;
1447
1282
  /**
1448
- * Dispatch a compute shader
1283
+ * Scale a matrix by a scalar
1449
1284
  */
1450
- dispatchCompute(pipeline: GPUComputePipeline, bindGroups: GPUBindGroup[], workgroupCounts: [number, number, number]): void;
1285
+ scale(a: Float32Array, scalar: number): Promise<Float32Array>;
1451
1286
  /**
1452
- * Wait for all GPU operations to complete
1287
+ * Get backend statistics
1453
1288
  */
1454
- waitForCompletion(): Promise<void>;
1289
+ getStats(): {
1290
+ status: GPUBackendStatus;
1291
+ capabilities: GPUCapabilities | null;
1292
+ bufferPool: {
1293
+ totalBuffers: number;
1294
+ inUseBuffers: number;
1295
+ cachedBuffers: number;
1296
+ } | null;
1297
+ shaders: {
1298
+ cachedShaders: number;
1299
+ cachedPipelines: number;
1300
+ } | null;
1301
+ };
1455
1302
  /**
1456
- * Destroy the context and release resources
1303
+ * Destroy the backend
1457
1304
  */
1458
1305
  destroy(): void;
1459
1306
  }
1460
1307
  /**
1461
- * Get the global GPU context
1308
+ * Get the global GPU backend
1309
+ */
1310
+ declare function getGlobalGPUBackend(): GPUBackend;
1311
+ /**
1312
+ * Initialize the global GPU backend
1462
1313
  */
1463
- declare function getGlobalGPUContext(): GPUContext;
1314
+ declare function initializeGlobalGPUBackend(options?: GPUBackendOptions): Promise<boolean>;
1464
1315
  /**
1465
- * Destroy the global GPU context
1316
+ * Destroy the global GPU backend
1466
1317
  */
1467
- declare function destroyGlobalGPU(): void;
1318
+ declare function destroyGlobalGPUBackend(): void;
1468
1319
 
1469
1320
  /**
1470
- * GPU Buffer Pool
1321
+ * GPU Matrix Backend Adapter
1322
+ *
1323
+ * Adapts GPUBackend to implement the MatrixBackend interface,
1324
+ * enabling seamless integration with the backend selection system.
1471
1325
  *
1472
- * Manages GPU buffer allocation, deallocation, and reuse.
1473
- * Reduces allocation overhead by recycling buffers.
1326
+ * @packageDocumentation
1474
1327
  */
1475
1328
 
1476
1329
  /**
1477
- * Options for buffer pool
1478
- */
1479
- interface BufferPoolOptions {
1480
- /** Maximum total memory to cache (bytes) */
1481
- maxCacheSize?: number;
1482
- /** Time after which unused buffers are evicted (ms) */
1483
- evictionTimeout?: number;
1484
- /** Whether to enable automatic eviction */
1485
- autoEvict?: boolean;
1486
- /** Interval for automatic eviction (ms) */
1487
- evictionInterval?: number;
1330
+ * Configuration for GPU Matrix Backend
1331
+ */
1332
+ interface GPUMatrixBackendConfig {
1333
+ /** Minimum elements to use GPU (default: 65536 = 256x256) */
1334
+ minElements?: number;
1335
+ /** Use global GPU backend instance */
1336
+ useGlobalBackend?: boolean;
1337
+ /** GPU backend options */
1338
+ gpuOptions?: GPUBackendOptions;
1339
+ /** Fall back to JS on GPU errors */
1340
+ fallbackOnError?: boolean;
1488
1341
  }
1489
1342
  /**
1490
- * GPU Buffer Pool for efficient buffer management
1343
+ * GPU Matrix Backend
1344
+ *
1345
+ * Implements MatrixBackend interface using WebGPU compute shaders.
1346
+ * Provides significant acceleration for large matrices.
1347
+ *
1348
+ * @example
1349
+ * ```typescript
1350
+ * const gpu = new GPUMatrixBackend();
1351
+ * await gpu.initialize();
1352
+ *
1353
+ * const result = gpu.multiply(matrixA, matrixB);
1354
+ * ```
1491
1355
  */
1492
- declare class BufferPool {
1493
- private context;
1494
- private buffers;
1495
- private maxCacheSize;
1496
- private evictionTimeout;
1497
- private evictionTimer;
1498
- private currentCacheSize;
1499
- constructor(context: GPUContext, options?: BufferPoolOptions);
1500
- /**
1501
- * Generate a key for buffer categorization
1502
- */
1503
- private getBufferKey;
1356
+ declare class GPUMatrixBackend implements MatrixBackend {
1357
+ readonly type: BackendType;
1358
+ private config;
1359
+ private backend;
1360
+ private capabilities;
1361
+ private initPromise;
1362
+ private _available;
1363
+ constructor(config?: GPUMatrixBackendConfig);
1504
1364
  /**
1505
- * Round up to nearest power of 2
1365
+ * Check if GPU is available in the current environment
1506
1366
  */
1507
- private roundUpToPowerOf2;
1367
+ isAvailable(): boolean;
1508
1368
  /**
1509
- * Acquire a buffer from the pool or create a new one
1369
+ * Initialize the GPU backend
1510
1370
  */
1511
- acquire(size: number, usage: GPUBufferUsageFlags, label?: string): GPUBuffer;
1371
+ initialize(): Promise<void>;
1372
+ private doInitialize;
1512
1373
  /**
1513
- * Release a buffer back to the pool
1374
+ * Check if operation should use GPU
1514
1375
  */
1515
- release(buffer: GPUBuffer): void;
1376
+ private shouldUseGPU;
1516
1377
  /**
1517
- * Create a storage buffer from the pool
1378
+ * Execute GPU operation with fallback
1518
1379
  */
1519
- acquireStorageBuffer(size: number, label?: string, readable?: boolean, writable?: boolean): GPUBuffer;
1380
+ private executeWithFallback;
1520
1381
  /**
1521
- * Create a staging buffer from the pool
1382
+ * Get GPU capabilities
1522
1383
  */
1523
- acquireStagingBuffer(size: number, label?: string): GPUBuffer;
1384
+ getCapabilities(): GPUCapabilities | null;
1524
1385
  /**
1525
- * Create a uniform buffer from the pool
1386
+ * Get backend statistics
1526
1387
  */
1527
- acquireUniformBuffer(size: number, label?: string): GPUBuffer;
1388
+ getStats(): ReturnType<GPUBackend['getStats']> | null;
1389
+ add(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1528
1390
  /**
1529
- * Evict old unused buffers
1391
+ * Async add operation using GPU
1530
1392
  */
1531
- evictOldBuffers(): void;
1393
+ addAsync(a: DenseMatrix, b: DenseMatrix): Promise<DenseMatrix>;
1394
+ subtract(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1395
+ multiplyElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1396
+ divideElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1397
+ scale(a: DenseMatrix, scalar: number): DenseMatrix;
1532
1398
  /**
1533
- * Force eviction to reduce cache to target size
1399
+ * Async scale operation using GPU
1534
1400
  */
1535
- evictToSize(targetSize: number): void;
1401
+ scaleAsync(a: DenseMatrix, scalar: number): Promise<DenseMatrix>;
1402
+ abs(a: DenseMatrix): DenseMatrix;
1403
+ negate(a: DenseMatrix): DenseMatrix;
1404
+ multiply(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1536
1405
  /**
1537
- * Start automatic eviction timer
1406
+ * Async matrix multiplication using GPU
1538
1407
  */
1539
- startAutoEviction(interval: number): void;
1408
+ multiplyAsync(a: DenseMatrix, b: DenseMatrix): Promise<DenseMatrix>;
1409
+ transpose(a: DenseMatrix): DenseMatrix;
1540
1410
  /**
1541
- * Stop automatic eviction timer
1411
+ * Async transpose using GPU
1542
1412
  */
1543
- stopAutoEviction(): void;
1413
+ transposeAsync(a: DenseMatrix): Promise<DenseMatrix>;
1414
+ sum(a: DenseMatrix): number;
1415
+ sumAxis(a: DenseMatrix, axis: 0 | 1): DenseMatrix;
1416
+ norm(a: DenseMatrix): number;
1417
+ dot(a: DenseMatrix, b: DenseMatrix): number;
1544
1418
  /**
1545
- * Get pool statistics
1419
+ * Update configuration
1546
1420
  */
1547
- getStats(): {
1548
- totalBuffers: number;
1549
- inUseBuffers: number;
1550
- cachedBuffers: number;
1551
- currentCacheSize: number;
1552
- maxCacheSize: number;
1553
- };
1421
+ updateConfig(config: Partial<GPUMatrixBackendConfig>): void;
1554
1422
  /**
1555
- * Clear all buffers and reset pool
1423
+ * Get current configuration
1556
1424
  */
1557
- clear(): void;
1425
+ getConfig(): Required<GPUMatrixBackendConfig>;
1558
1426
  /**
1559
- * Destroy the pool
1427
+ * Destroy the backend
1560
1428
  */
1561
1429
  destroy(): void;
1562
1430
  }
1563
-
1564
1431
  /**
1565
- * GPU Shader Manager
1566
- *
1567
- * Manages WGSL shader loading, compilation, and caching.
1432
+ * Global GPU matrix backend instance
1433
+ */
1434
+ declare const gpuMatrixBackend: GPUMatrixBackend;
1435
+ /**
1436
+ * Create a GPU matrix backend with custom configuration
1568
1437
  */
1438
+ declare function createGPUMatrixBackend(config?: GPUMatrixBackendConfig): GPUMatrixBackend;
1569
1439
 
1570
1440
  /**
1571
- * Built-in shader library
1441
+ * MathTS Matrix Configuration
1442
+ *
1443
+ * Centralized configuration for matrix operations, backend selection,
1444
+ * and performance tuning.
1445
+ *
1446
+ * @packageDocumentation
1572
1447
  */
1573
- declare const BUILTIN_SHADERS: {
1574
- /** Matrix addition shader */
1575
- matrixAdd: string;
1576
- /** Matrix subtraction shader */
1577
- matrixSub: string;
1578
- /** Element-wise multiplication shader */
1579
- matrixMul: string;
1580
- /** Scalar multiplication shader */
1581
- scalarMul: string;
1582
- /** Matrix multiplication (naive) shader */
1583
- matmul: string;
1584
- /** Matrix transpose shader */
1585
- transpose: string;
1586
- /** Sum reduction shader (first pass) */
1587
- sumReduce: string;
1588
- };
1448
+
1589
1449
  /**
1590
- * Shader Manager for compiling and caching GPU shaders
1450
+ * Operation type hints for backend selection.
1451
+ *
1452
+ * Defined here rather than in `BackendManager.ts` so that `config.ts` (the
1453
+ * lower-level module) owns it — `BackendManager` already imports `config`, so
1454
+ * sourcing the type the other way round closed an import cycle.
1591
1455
  */
1592
- declare class ShaderManager {
1593
- private context;
1594
- private cache;
1595
- constructor(context: GPUContext);
1596
- /**
1597
- * Get or compile a shader module
1598
- */
1599
- getShaderModule(name: string, code: string): GPUShaderModule;
1600
- /**
1601
- * Get a builtin shader module
1602
- */
1603
- getBuiltinShader(name: keyof typeof BUILTIN_SHADERS): GPUShaderModule;
1604
- /**
1605
- * Get or create a compute pipeline
1606
- */
1607
- getPipeline(shaderName: string, entryPoint: string, code?: string, layout?: GPUPipelineLayout | 'auto'): GPUComputePipeline;
1608
- /**
1609
- * Get a builtin compute pipeline
1610
- */
1611
- getBuiltinPipeline(name: keyof typeof BUILTIN_SHADERS, entryPoint?: string): GPUComputePipeline;
1612
- /**
1613
- * Precompile all builtin shaders
1614
- */
1615
- precompileBuiltins(): void;
1616
- /**
1617
- * Clear shader cache
1618
- */
1619
- clearCache(): void;
1620
- /**
1621
- * Get cache statistics
1622
- */
1623
- getStats(): {
1624
- cachedShaders: number;
1625
- cachedPipelines: number;
1626
- };
1627
- }
1456
+ type OperationType = 'add' | 'subtract' | 'multiply' | 'multiplyElementwise' | 'transpose' | 'scale' | 'decomposition' | 'solve' | 'fft' | 'eig' | 'svd';
1628
1457
 
1629
1458
  /**
1630
- * GPU Batch Executor
1459
+ * Backend Manager
1631
1460
  *
1632
- * Manages batched GPU command submission for reduced overhead.
1633
- * Queues multiple operations and executes them together for efficiency.
1461
+ * Centralized management for matrix operation backends with automatic
1462
+ * selection based on matrix size, operation type, and availability.
1463
+ * Includes adaptive threshold tuning based on runtime profiling.
1634
1464
  *
1635
1465
  * @packageDocumentation
1636
1466
  */
1637
1467
 
1638
1468
  /**
1639
- * Result of batch execution
1469
+ * Extended backend hints with operation-specific thresholds
1640
1470
  */
1641
- interface BatchResult {
1642
- /** Success status */
1643
- success: boolean;
1644
- /** Number of operations executed */
1645
- operationCount: number;
1646
- /** Execution time in milliseconds */
1647
- duration: number;
1648
- /** Error message if failed */
1649
- error?: string;
1471
+ interface ExtendedBackendHints extends BackendHints {
1472
+ /** Specific thresholds by operation type */
1473
+ operationThresholds?: Partial<Record<OperationType, {
1474
+ wasm?: number;
1475
+ gpu?: number;
1476
+ }>>;
1477
+ /** Enable automatic SIMD detection for WASM */
1478
+ autoSIMD?: boolean;
1479
+ /** Fallback to JS on backend failure */
1480
+ fallbackOnError?: boolean;
1481
+ }
1482
+ /**
1483
+ * Default extended hints
1484
+ */
1485
+ declare const DEFAULT_EXTENDED_HINTS: Required<ExtendedBackendHints>;
1486
+ /**
1487
+ * Centralized Backend Manager
1488
+ *
1489
+ * Provides a unified interface for executing matrix operations with
1490
+ * automatic backend selection based on matrix size and operation type.
1491
+ * Features adaptive threshold tuning based on runtime profiling.
1492
+ */
1493
+ declare class BackendManager {
1494
+ private hints;
1495
+ private initialized;
1496
+ private initializationPromise;
1497
+ private adaptiveState;
1498
+ private configUnsubscribe;
1499
+ constructor(hints?: ExtendedBackendHints);
1500
+ /**
1501
+ * Sync manager state with global config
1502
+ */
1503
+ private syncWithConfig;
1504
+ /**
1505
+ * Initialize all available backends
1506
+ */
1507
+ initialize(): Promise<void>;
1508
+ private doInitialize;
1509
+ /**
1510
+ * Update backend hints
1511
+ */
1512
+ setHints(hints: ExtendedBackendHints): void;
1513
+ /**
1514
+ * Get current hints
1515
+ */
1516
+ getHints(): Required<ExtendedBackendHints>;
1517
+ /**
1518
+ * Get the best backend for a given operation and matrix size.
1519
+ *
1520
+ * Selection priority:
1521
+ * 1. Preferred backend (if explicitly set)
1522
+ * 2. Elements > gpuThreshold -> GPU (if available)
1523
+ * 3. Elements > wasmThreshold -> AS WASM (if loaded)
1524
+ * 4. JS fallback
1525
+ */
1526
+ selectBackend(elementCount: number, operation?: OperationType): MatrixBackend;
1527
+ /**
1528
+ * Execute an operation with automatic backend selection
1529
+ */
1530
+ private executeWithFallback;
1531
+ /**
1532
+ * Matrix addition with auto backend selection
1533
+ */
1534
+ add(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1535
+ /**
1536
+ * Matrix subtraction with auto backend selection
1537
+ */
1538
+ subtract(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1539
+ /**
1540
+ * Element-wise multiplication with auto backend selection
1541
+ */
1542
+ multiplyElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1543
+ /**
1544
+ * Element-wise division with auto backend selection
1545
+ */
1546
+ divideElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1547
+ /**
1548
+ * Scalar multiplication with auto backend selection
1549
+ */
1550
+ scale(a: DenseMatrix, scalar: number): DenseMatrix;
1551
+ /**
1552
+ * Element-wise absolute value with auto backend selection
1553
+ */
1554
+ abs(a: DenseMatrix): DenseMatrix;
1555
+ /**
1556
+ * Element-wise negation with auto backend selection
1557
+ */
1558
+ negate(a: DenseMatrix): DenseMatrix;
1559
+ /**
1560
+ * Matrix multiplication with auto backend selection
1561
+ */
1562
+ multiply(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1563
+ /**
1564
+ * Matrix transpose with auto backend selection
1565
+ */
1566
+ transpose(a: DenseMatrix): DenseMatrix;
1567
+ /**
1568
+ * Sum of all elements with auto backend selection
1569
+ */
1570
+ sum(a: DenseMatrix): Promise<number>;
1571
+ /**
1572
+ * Sum along axis with auto backend selection
1573
+ */
1574
+ sumAxis(a: DenseMatrix, axis: 0 | 1): DenseMatrix;
1575
+ /**
1576
+ * Frobenius norm with auto backend selection
1577
+ */
1578
+ norm(a: DenseMatrix): number;
1579
+ /**
1580
+ * Dot product with auto backend selection
1581
+ */
1582
+ dot(a: DenseMatrix, b: DenseMatrix): Promise<number>;
1583
+ /**
1584
+ * Get list of available backends
1585
+ */
1586
+ getAvailableBackends(): BackendType[];
1587
+ /**
1588
+ * Check if a specific backend is available
1589
+ */
1590
+ hasBackend(type: BackendType): boolean;
1591
+ /**
1592
+ * Get current active backend for a given operation size
1593
+ */
1594
+ getActiveBackend(elementCount: number, operation?: OperationType): BackendType;
1595
+ /**
1596
+ * Force a specific backend for all operations
1597
+ */
1598
+ forceBackend(type: BackendType | null): void;
1599
+ /**
1600
+ * Record a performance sample for adaptive tuning
1601
+ */
1602
+ recordSample(operation: OperationType, elementCount: number, backend: BackendType, durationMs: number): void;
1603
+ /**
1604
+ * Adjust thresholds based on collected samples
1605
+ */
1606
+ private maybeAdjustThresholds;
1607
+ /**
1608
+ * Get current adaptive thresholds
1609
+ */
1610
+ getAdaptiveThresholds(): Map<OperationType, {
1611
+ wasm: number;
1612
+ gpu: number;
1613
+ }>;
1614
+ /**
1615
+ * Reset adaptive tuning state
1616
+ */
1617
+ resetAdaptiveState(): void;
1618
+ /**
1619
+ * Get performance statistics
1620
+ */
1621
+ getPerformanceStats(): {
1622
+ sampleCount: number;
1623
+ operationStats: Map<OperationType, {
1624
+ avgDuration: number;
1625
+ samples: number;
1626
+ backendUsage: Record<BackendType, number>;
1627
+ }>;
1628
+ };
1629
+ /**
1630
+ * Cleanup resources
1631
+ */
1632
+ destroy(): void;
1633
+ }
1634
+ /**
1635
+ * Default backend manager instance
1636
+ */
1637
+ declare const backendManager: BackendManager;
1638
+ /**
1639
+ * Create a new backend manager with custom hints
1640
+ */
1641
+ declare function createBackendManager(hints?: ExtendedBackendHints): BackendManager;
1642
+
1643
+ /**
1644
+ * Matrix-domain WGSL kernels.
1645
+ *
1646
+ * These live in matrix — the @danielsimonjr/mathts-gpu foundation ships no
1647
+ * domain kernels. GPUBackend registers them onto a ShaderManager at init.
1648
+ */
1649
+
1650
+ declare const BUILTIN_SHADERS: {
1651
+ /** Matrix addition shader */
1652
+ readonly matrixAdd: "\n @group(0) @binding(0) var<storage, read> a: array<f32>;\n @group(0) @binding(1) var<storage, read> b: array<f32>;\n @group(0) @binding(2) var<storage, read_write> result: array<f32>;\n @group(0) @binding(3) var<uniform> params: vec4<u32>; // rows, cols, _, _\n\n @compute @workgroup_size(16, 16)\n fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n let rows = params.x;\n let cols = params.y;\n let row = gid.y;\n let col = gid.x;\n\n if (row >= rows || col >= cols) { return; }\n\n let idx = row * cols + col;\n result[idx] = a[idx] + b[idx];\n }\n ";
1653
+ /** Matrix subtraction shader */
1654
+ readonly matrixSub: "\n @group(0) @binding(0) var<storage, read> a: array<f32>;\n @group(0) @binding(1) var<storage, read> b: array<f32>;\n @group(0) @binding(2) var<storage, read_write> result: array<f32>;\n @group(0) @binding(3) var<uniform> params: vec4<u32>;\n\n @compute @workgroup_size(16, 16)\n fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n let rows = params.x;\n let cols = params.y;\n let row = gid.y;\n let col = gid.x;\n\n if (row >= rows || col >= cols) { return; }\n\n let idx = row * cols + col;\n result[idx] = a[idx] - b[idx];\n }\n ";
1655
+ /** Element-wise multiplication shader */
1656
+ readonly matrixMul: "\n @group(0) @binding(0) var<storage, read> a: array<f32>;\n @group(0) @binding(1) var<storage, read> b: array<f32>;\n @group(0) @binding(2) var<storage, read_write> result: array<f32>;\n @group(0) @binding(3) var<uniform> params: vec4<u32>;\n\n @compute @workgroup_size(16, 16)\n fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n let rows = params.x;\n let cols = params.y;\n let row = gid.y;\n let col = gid.x;\n\n if (row >= rows || col >= cols) { return; }\n\n let idx = row * cols + col;\n result[idx] = a[idx] * b[idx];\n }\n ";
1657
+ /** Scalar multiplication shader */
1658
+ readonly scalarMul: "\n @group(0) @binding(0) var<storage, read> a: array<f32>;\n @group(0) @binding(1) var<storage, read_write> result: array<f32>;\n @group(0) @binding(2) var<uniform> params: vec4<f32>; // scalar, length, _, _\n\n @compute @workgroup_size(256)\n fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n let scalar = params.x;\n let length = u32(params.y);\n let idx = gid.x;\n\n if (idx >= length) { return; }\n\n result[idx] = a[idx] * scalar;\n }\n ";
1659
+ /** Matrix multiplication (naive) shader */
1660
+ readonly matmul: "\n @group(0) @binding(0) var<storage, read> a: array<f32>;\n @group(0) @binding(1) var<storage, read> b: array<f32>;\n @group(0) @binding(2) var<storage, read_write> result: array<f32>;\n @group(0) @binding(3) var<uniform> params: vec4<u32>; // M, N, K, _\n\n @compute @workgroup_size(16, 16)\n fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n let M = params.x;\n let N = params.y;\n let K = params.z;\n let row = gid.y;\n let col = gid.x;\n\n if (row >= M || col >= N) { return; }\n\n var sum: f32 = 0.0;\n for (var k: u32 = 0u; k < K; k = k + 1u) {\n sum = sum + a[row * K + k] * b[k * N + col];\n }\n\n result[row * N + col] = sum;\n }\n ";
1661
+ /** Matrix transpose shader */
1662
+ readonly transpose: "\n @group(0) @binding(0) var<storage, read> a: array<f32>;\n @group(0) @binding(1) var<storage, read_write> result: array<f32>;\n @group(0) @binding(2) var<uniform> params: vec4<u32>; // rows, cols, _, _\n\n @compute @workgroup_size(16, 16)\n fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n let rows = params.x;\n let cols = params.y;\n let row = gid.y;\n let col = gid.x;\n\n if (row >= rows || col >= cols) { return; }\n\n result[col * rows + row] = a[row * cols + col];\n }\n ";
1663
+ /** Sum reduction shader (first pass) */
1664
+ readonly sumReduce: "\n @group(0) @binding(0) var<storage, read> input: array<f32>;\n @group(0) @binding(1) var<storage, read_write> output: array<f32>;\n @group(0) @binding(2) var<uniform> params: vec4<u32>; // inputLength, outputLength, _, _\n\n // NOTE: 'shared' is a RESERVED KEYWORD in WGSL — naming this workgroup\n // array 'shared' made this shader fail to compile, which (because\n // GPUBackend.initialize() precompiles every registered shader) poisoned\n // backend init and silently forced ALL GPU ops onto the CPU fallback.\n var<workgroup> sdata: array<f32, 256>;\n\n @compute @workgroup_size(256)\n fn main(\n @builtin(local_invocation_id) lid: vec3<u32>,\n @builtin(workgroup_id) wid: vec3<u32>\n ) {\n let inputLength = params.x;\n let idx = wid.x * 512u + lid.x;\n\n // Load two elements and sum\n var sum: f32 = 0.0;\n if (idx < inputLength) {\n sum = input[idx];\n }\n if (idx + 256u < inputLength) {\n sum = sum + input[idx + 256u];\n }\n sdata[lid.x] = sum;\n\n workgroupBarrier();\n\n // Reduce within workgroup\n for (var s: u32 = 128u; s > 0u; s = s >> 1u) {\n if (lid.x < s) {\n sdata[lid.x] = sdata[lid.x] + sdata[lid.x + s];\n }\n workgroupBarrier();\n }\n\n // Write result\n if (lid.x == 0u) {\n output[wid.x] = sdata[0];\n }\n }\n ";
1665
+ };
1666
+
1667
+ /**
1668
+ * GPU Batch Executor
1669
+ *
1670
+ * Manages batched GPU command submission for reduced overhead.
1671
+ * Queues multiple operations and executes them together for efficiency.
1672
+ *
1673
+ * @packageDocumentation
1674
+ */
1675
+
1676
+ /**
1677
+ * Result of batch execution
1678
+ */
1679
+ interface BatchResult {
1680
+ /** Success status */
1681
+ success: boolean;
1682
+ /** Number of operations executed */
1683
+ operationCount: number;
1684
+ /** Execution time in milliseconds */
1685
+ duration: number;
1686
+ /** Error message if failed */
1687
+ error?: string;
1650
1688
  }
1651
1689
  /**
1652
1690
  * Options for batch execution
@@ -1934,457 +1972,6 @@ declare class SyncManager {
1934
1972
  */
1935
1973
  declare function createSyncManager(context: GPUContext, bufferPool: BufferPool, strategy?: SyncStrategy): SyncManager;
1936
1974
 
1937
- /**
1938
- * GPU Backend for Matrix Operations
1939
- *
1940
- * WebGPU-accelerated matrix operations for large matrices.
1941
- */
1942
-
1943
- /**
1944
- * GPU Backend status
1945
- */
1946
- type GPUBackendStatus = 'uninitialized' | 'initializing' | 'ready' | 'error' | 'unsupported';
1947
- /**
1948
- * Options for GPU backend
1949
- */
1950
- interface GPUBackendOptions extends GPUContextOptions {
1951
- /** Use global GPU context instead of creating a new one */
1952
- useGlobalContext?: boolean;
1953
- /** Buffer pool options */
1954
- bufferPoolOptions?: {
1955
- maxCacheSize?: number;
1956
- evictionTimeout?: number;
1957
- };
1958
- /** Threshold for using GPU (matrix size) */
1959
- threshold?: number;
1960
- }
1961
- /**
1962
- * GPU Backend for accelerated matrix operations
1963
- */
1964
- declare class GPUBackend {
1965
- private context;
1966
- private bufferPool;
1967
- private shaderManager;
1968
- private _status;
1969
- private _capabilities;
1970
- private _lastError;
1971
- private threshold;
1972
- private workgroupSize;
1973
- private useGlobalContext;
1974
- constructor(options?: GPUBackendOptions);
1975
- /**
1976
- * Get the current status
1977
- */
1978
- get status(): GPUBackendStatus;
1979
- /**
1980
- * Check if backend is ready
1981
- */
1982
- get isReady(): boolean;
1983
- /**
1984
- * Get capabilities
1985
- */
1986
- get capabilities(): GPUCapabilities | null;
1987
- /**
1988
- * Get last error
1989
- */
1990
- get lastError(): Error | null;
1991
- /**
1992
- * Initialize the GPU backend
1993
- */
1994
- initialize(options?: GPUBackendOptions): Promise<boolean>;
1995
- /**
1996
- * Check if GPU should be used for the given matrix size
1997
- */
1998
- shouldUseGPU(rows: number, cols: number): boolean;
1999
- /**
2000
- * Calculate workgroup counts for a matrix
2001
- */
2002
- calculateWorkgroups(rows: number, cols: number): [number, number, number];
2003
- /**
2004
- * Get the GPU context
2005
- */
2006
- getContext(): GPUContext;
2007
- /**
2008
- * Get the buffer pool
2009
- */
2010
- getBufferPool(): BufferPool;
2011
- /**
2012
- * Get the shader manager
2013
- */
2014
- getShaderManager(): ShaderManager;
2015
- /**
2016
- * Add two matrices element-wise
2017
- */
2018
- add(a: Float32Array, b: Float32Array, rows: number, cols: number): Promise<Float32Array>;
2019
- /**
2020
- * Multiply two matrices
2021
- */
2022
- matmul(a: Float32Array, b: Float32Array, M: number, K: number, N: number): Promise<Float32Array>;
2023
- /**
2024
- * Transpose a matrix
2025
- */
2026
- transpose(a: Float32Array, rows: number, cols: number): Promise<Float32Array>;
2027
- /**
2028
- * Scale a matrix by a scalar
2029
- */
2030
- scale(a: Float32Array, scalar: number): Promise<Float32Array>;
2031
- /**
2032
- * Get backend statistics
2033
- */
2034
- getStats(): {
2035
- status: GPUBackendStatus;
2036
- capabilities: GPUCapabilities | null;
2037
- bufferPool: {
2038
- totalBuffers: number;
2039
- inUseBuffers: number;
2040
- cachedBuffers: number;
2041
- } | null;
2042
- shaders: {
2043
- cachedShaders: number;
2044
- cachedPipelines: number;
2045
- } | null;
2046
- };
2047
- /**
2048
- * Destroy the backend
2049
- */
2050
- destroy(): void;
2051
- }
2052
- /**
2053
- * Get the global GPU backend
2054
- */
2055
- declare function getGlobalGPUBackend(): GPUBackend;
2056
- /**
2057
- * Initialize the global GPU backend
2058
- */
2059
- declare function initializeGlobalGPUBackend(options?: GPUBackendOptions): Promise<boolean>;
2060
- /**
2061
- * Destroy the global GPU backend
2062
- */
2063
- declare function destroyGlobalGPUBackend(): void;
2064
-
2065
- /**
2066
- * GPU Matrix Backend Adapter
2067
- *
2068
- * Adapts GPUBackend to implement the MatrixBackend interface,
2069
- * enabling seamless integration with the backend selection system.
2070
- *
2071
- * @packageDocumentation
2072
- */
2073
-
2074
- /**
2075
- * Configuration for GPU Matrix Backend
2076
- */
2077
- interface GPUMatrixBackendConfig {
2078
- /** Minimum elements to use GPU (default: 65536 = 256x256) */
2079
- minElements?: number;
2080
- /** Use global GPU backend instance */
2081
- useGlobalBackend?: boolean;
2082
- /** GPU backend options */
2083
- gpuOptions?: GPUBackendOptions;
2084
- /** Fall back to JS on GPU errors */
2085
- fallbackOnError?: boolean;
2086
- }
2087
- /**
2088
- * GPU Matrix Backend
2089
- *
2090
- * Implements MatrixBackend interface using WebGPU compute shaders.
2091
- * Provides significant acceleration for large matrices.
2092
- *
2093
- * @example
2094
- * ```typescript
2095
- * const gpu = new GPUMatrixBackend();
2096
- * await gpu.initialize();
2097
- *
2098
- * const result = gpu.multiply(matrixA, matrixB);
2099
- * ```
2100
- */
2101
- declare class GPUMatrixBackend implements MatrixBackend {
2102
- readonly type: BackendType;
2103
- private config;
2104
- private backend;
2105
- private capabilities;
2106
- private initPromise;
2107
- private _available;
2108
- constructor(config?: GPUMatrixBackendConfig);
2109
- /**
2110
- * Check if GPU is available in the current environment
2111
- */
2112
- isAvailable(): boolean;
2113
- /**
2114
- * Initialize the GPU backend
2115
- */
2116
- initialize(): Promise<void>;
2117
- private doInitialize;
2118
- /**
2119
- * Check if operation should use GPU
2120
- */
2121
- private shouldUseGPU;
2122
- /**
2123
- * Execute GPU operation with fallback
2124
- */
2125
- private executeWithFallback;
2126
- /**
2127
- * Get GPU capabilities
2128
- */
2129
- getCapabilities(): GPUCapabilities | null;
2130
- /**
2131
- * Get backend statistics
2132
- */
2133
- getStats(): ReturnType<GPUBackend['getStats']> | null;
2134
- add(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2135
- /**
2136
- * Async add operation using GPU
2137
- */
2138
- addAsync(a: DenseMatrix, b: DenseMatrix): Promise<DenseMatrix>;
2139
- subtract(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2140
- multiplyElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2141
- divideElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2142
- scale(a: DenseMatrix, scalar: number): DenseMatrix;
2143
- /**
2144
- * Async scale operation using GPU
2145
- */
2146
- scaleAsync(a: DenseMatrix, scalar: number): Promise<DenseMatrix>;
2147
- abs(a: DenseMatrix): DenseMatrix;
2148
- negate(a: DenseMatrix): DenseMatrix;
2149
- multiply(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2150
- /**
2151
- * Async matrix multiplication using GPU
2152
- */
2153
- multiplyAsync(a: DenseMatrix, b: DenseMatrix): Promise<DenseMatrix>;
2154
- transpose(a: DenseMatrix): DenseMatrix;
2155
- /**
2156
- * Async transpose using GPU
2157
- */
2158
- transposeAsync(a: DenseMatrix): Promise<DenseMatrix>;
2159
- sum(a: DenseMatrix): number;
2160
- sumAxis(a: DenseMatrix, axis: 0 | 1): DenseMatrix;
2161
- norm(a: DenseMatrix): number;
2162
- dot(a: DenseMatrix, b: DenseMatrix): number;
2163
- /**
2164
- * Update configuration
2165
- */
2166
- updateConfig(config: Partial<GPUMatrixBackendConfig>): void;
2167
- /**
2168
- * Get current configuration
2169
- */
2170
- getConfig(): Required<GPUMatrixBackendConfig>;
2171
- /**
2172
- * Destroy the backend
2173
- */
2174
- destroy(): void;
2175
- }
2176
- /**
2177
- * Global GPU matrix backend instance
2178
- */
2179
- declare const gpuMatrixBackend: GPUMatrixBackend;
2180
- /**
2181
- * Create a GPU matrix backend with custom configuration
2182
- */
2183
- declare function createGPUMatrixBackend(config?: GPUMatrixBackendConfig): GPUMatrixBackend;
2184
-
2185
- /**
2186
- * MathTS Matrix Configuration
2187
- *
2188
- * Centralized configuration for matrix operations, backend selection,
2189
- * and performance tuning.
2190
- *
2191
- * @packageDocumentation
2192
- */
2193
-
2194
- /**
2195
- * Operation type hints for backend selection.
2196
- *
2197
- * Defined here rather than in `BackendManager.ts` so that `config.ts` (the
2198
- * lower-level module) owns it — `BackendManager` already imports `config`, so
2199
- * sourcing the type the other way round closed an import cycle.
2200
- */
2201
- type OperationType = 'add' | 'subtract' | 'multiply' | 'multiplyElementwise' | 'transpose' | 'scale' | 'decomposition' | 'solve' | 'fft' | 'eig' | 'svd';
2202
-
2203
- /**
2204
- * Backend Manager
2205
- *
2206
- * Centralized management for matrix operation backends with automatic
2207
- * selection based on matrix size, operation type, and availability.
2208
- * Includes adaptive threshold tuning based on runtime profiling.
2209
- *
2210
- * @packageDocumentation
2211
- */
2212
-
2213
- /**
2214
- * Extended backend hints with operation-specific thresholds
2215
- */
2216
- interface ExtendedBackendHints extends BackendHints {
2217
- /** Specific thresholds by operation type */
2218
- operationThresholds?: Partial<Record<OperationType, {
2219
- wasm?: number;
2220
- gpu?: number;
2221
- }>>;
2222
- /** Enable automatic SIMD detection for WASM */
2223
- autoSIMD?: boolean;
2224
- /** Fallback to JS on backend failure */
2225
- fallbackOnError?: boolean;
2226
- }
2227
- /**
2228
- * Default extended hints
2229
- */
2230
- declare const DEFAULT_EXTENDED_HINTS: Required<ExtendedBackendHints>;
2231
- /**
2232
- * Centralized Backend Manager
2233
- *
2234
- * Provides a unified interface for executing matrix operations with
2235
- * automatic backend selection based on matrix size and operation type.
2236
- * Features adaptive threshold tuning based on runtime profiling.
2237
- */
2238
- declare class BackendManager {
2239
- private hints;
2240
- private initialized;
2241
- private initializationPromise;
2242
- private adaptiveState;
2243
- private configUnsubscribe;
2244
- constructor(hints?: ExtendedBackendHints);
2245
- /**
2246
- * Sync manager state with global config
2247
- */
2248
- private syncWithConfig;
2249
- /**
2250
- * Initialize all available backends
2251
- */
2252
- initialize(): Promise<void>;
2253
- private doInitialize;
2254
- /**
2255
- * Update backend hints
2256
- */
2257
- setHints(hints: ExtendedBackendHints): void;
2258
- /**
2259
- * Get current hints
2260
- */
2261
- getHints(): Required<ExtendedBackendHints>;
2262
- /**
2263
- * Get the best backend for a given operation and matrix size.
2264
- *
2265
- * Selection priority:
2266
- * 1. Preferred backend (if explicitly set)
2267
- * 2. Elements > gpuThreshold -> GPU (if available)
2268
- * 3. Elements > wasmThreshold -> AS WASM (if loaded)
2269
- * 4. JS fallback
2270
- */
2271
- selectBackend(elementCount: number, operation?: OperationType): MatrixBackend;
2272
- /**
2273
- * Execute an operation with automatic backend selection
2274
- */
2275
- private executeWithFallback;
2276
- /**
2277
- * Matrix addition with auto backend selection
2278
- */
2279
- add(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2280
- /**
2281
- * Matrix subtraction with auto backend selection
2282
- */
2283
- subtract(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2284
- /**
2285
- * Element-wise multiplication with auto backend selection
2286
- */
2287
- multiplyElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2288
- /**
2289
- * Element-wise division with auto backend selection
2290
- */
2291
- divideElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2292
- /**
2293
- * Scalar multiplication with auto backend selection
2294
- */
2295
- scale(a: DenseMatrix, scalar: number): DenseMatrix;
2296
- /**
2297
- * Element-wise absolute value with auto backend selection
2298
- */
2299
- abs(a: DenseMatrix): DenseMatrix;
2300
- /**
2301
- * Element-wise negation with auto backend selection
2302
- */
2303
- negate(a: DenseMatrix): DenseMatrix;
2304
- /**
2305
- * Matrix multiplication with auto backend selection
2306
- */
2307
- multiply(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2308
- /**
2309
- * Matrix transpose with auto backend selection
2310
- */
2311
- transpose(a: DenseMatrix): DenseMatrix;
2312
- /**
2313
- * Sum of all elements with auto backend selection
2314
- */
2315
- sum(a: DenseMatrix): Promise<number>;
2316
- /**
2317
- * Sum along axis with auto backend selection
2318
- */
2319
- sumAxis(a: DenseMatrix, axis: 0 | 1): DenseMatrix;
2320
- /**
2321
- * Frobenius norm with auto backend selection
2322
- */
2323
- norm(a: DenseMatrix): number;
2324
- /**
2325
- * Dot product with auto backend selection
2326
- */
2327
- dot(a: DenseMatrix, b: DenseMatrix): Promise<number>;
2328
- /**
2329
- * Get list of available backends
2330
- */
2331
- getAvailableBackends(): BackendType[];
2332
- /**
2333
- * Check if a specific backend is available
2334
- */
2335
- hasBackend(type: BackendType): boolean;
2336
- /**
2337
- * Get current active backend for a given operation size
2338
- */
2339
- getActiveBackend(elementCount: number, operation?: OperationType): BackendType;
2340
- /**
2341
- * Force a specific backend for all operations
2342
- */
2343
- forceBackend(type: BackendType | null): void;
2344
- /**
2345
- * Record a performance sample for adaptive tuning
2346
- */
2347
- recordSample(operation: OperationType, elementCount: number, backend: BackendType, durationMs: number): void;
2348
- /**
2349
- * Adjust thresholds based on collected samples
2350
- */
2351
- private maybeAdjustThresholds;
2352
- /**
2353
- * Get current adaptive thresholds
2354
- */
2355
- getAdaptiveThresholds(): Map<OperationType, {
2356
- wasm: number;
2357
- gpu: number;
2358
- }>;
2359
- /**
2360
- * Reset adaptive tuning state
2361
- */
2362
- resetAdaptiveState(): void;
2363
- /**
2364
- * Get performance statistics
2365
- */
2366
- getPerformanceStats(): {
2367
- sampleCount: number;
2368
- operationStats: Map<OperationType, {
2369
- avgDuration: number;
2370
- samples: number;
2371
- backendUsage: Record<BackendType, number>;
2372
- }>;
2373
- };
2374
- /**
2375
- * Cleanup resources
2376
- */
2377
- destroy(): void;
2378
- }
2379
- /**
2380
- * Default backend manager instance
2381
- */
2382
- declare const backendManager: BackendManager;
2383
- /**
2384
- * Create a new backend manager with custom hints
2385
- */
2386
- declare function createBackendManager(hints?: ExtendedBackendHints): BackendManager;
2387
-
2388
1975
  /**
2389
1976
  * Eigenvalue and Eigenvector Decomposition
2390
1977
  *
@@ -3304,4 +2891,4 @@ declare function initializeParallelMatrix(): Promise<void>;
3304
2891
  */
3305
2892
  declare function terminateParallelMatrix(): Promise<void>;
3306
2893
 
3307
- export { BUILTIN_SHADERS, type BackendHints, BackendManager, BackendRegistry, type BackendType, BatchExecutor, BufferPool, type CholeskyResult, DEFAULT_BACKEND_HINTS, DEFAULT_EXTENDED_HINTS, DenseMatrix, type EigOptions, type EigResult, type ExpmOptions, type ExtendedBackendHints, GPUBackend, type GPUBackendOptions, type GPUBackendStatus, type GPUCapabilities, GPUContext, type GPUContextOptions, GPUMatrixBackend, type GPUMatrixBackendConfig, JSBackend, type LUResult, type LogmOptions, Matrix, type MatrixBackend, type MatrixDimensions, type MatrixEntry, type MatrixIndex, type MatrixType, type OperationType, ParallelBackend, type ParallelBackendConfig, type PinvOptions, type QROptions, type QRResult, type SVDOptions, type SVDResult, type SchurOptions, type SchurResult, ShaderManager, type SliceSpec, SparseMatrix, type SqrtmOptions, type SyncConfig, SyncManager, type SyncStrategy, WASMBackend, type WASMBackendConfig, type WasmFeatures, abs, add, backendManager, backendRegistry, cholesky, clearFeatureCache, column, cond, createBackendManager, createGPUMatrixBackend, createParallelBackend, createSyncManager, createWASMBackend, destroyGlobalGPU, destroyGlobalGPUBackend, detectGPUCapabilities, detectWasmFeatures, diag, diagonal, divide, dotMultiply, eig, eigWasm, eigvals, eigvalsWasm, exp, getCachedFeatures, getGlobalGPUBackend, getGlobalGPUContext, getRecommendedWorkgroupSize, gpuMatrixBackend, hasWebGPU, identity, initializeGlobalGPUBackend, initializeParallelMatrix, isAtomicsAvailable, isDenseMatrix, isMatrix, isSharedMemoryAvailable, isSparseMatrix, isWasmAvailable, jsBackend, log, lowRankApprox, lu, matrix, matrixExpm, matrixLogm, pinv as matrixPinv, matrixSchur, matrixSqrtm, max, mean, min, multiply, norm, norm2, normFro, ones, parallelBackend, parallelDiag, parallelDotMultiply, parallelIdentity, parallelMatrix, parallelMatrixAbs, parallelMatrixAdd, parallelMatrixColumn, parallelMatrixCos, parallelMatrixDiagonal, parallelMatrixDistance, parallelMatrixDivide, parallelMatrixDot, parallelMatrixExp, parallelMatrixHistogram, parallelMatrixLog, parallelMatrixMatvec, parallelMatrixMax, parallelMatrixMean, parallelMatrixMin, parallelMatrixMultiply, parallelMatrixNorm, parallelMatrixOperations, parallelMatrixOuter, parallelMatrixRow, parallelMatrixSin, parallelMatrixSize, parallelMatrixSqrt, parallelMatrixSquare, parallelMatrixStd, parallelMatrixSubset, parallelMatrixSubtract, parallelMatrixSum, parallelMatrixTan, parallelMatrixTrace, parallelMatrixTranspose, parallelMatrixVariance, parallelOnes, parallelRandom, parallelUnaryMinus, parallelZeros, pinv$1 as pinv, pow, powerIteration, qr, random, row, singularValues, size, spectralRadiusWasm, sqrt, square, subset, subtract, sum, svd, svdWasm, terminateParallelMatrix, trace, transpose, typedMatrixOperations, unaryMinus, wasmBackend, zeros };
2894
+ export { BUILTIN_SHADERS, type BackendHints, BackendManager, BackendRegistry, type BackendType, BatchExecutor, type CholeskyResult, DEFAULT_BACKEND_HINTS, DEFAULT_EXTENDED_HINTS, DenseMatrix, type EigOptions, type EigResult, type ExpmOptions, type ExtendedBackendHints, GPUBackend, type GPUBackendOptions, type GPUBackendStatus, GPUMatrixBackend, type GPUMatrixBackendConfig, JSBackend, type LUResult, type LogmOptions, Matrix, type MatrixBackend, type MatrixDimensions, type MatrixEntry, type MatrixIndex, type MatrixType, type OperationType, ParallelBackend, type ParallelBackendConfig, type PinvOptions, type QROptions, type QRResult, type SVDOptions, type SVDResult, type SchurOptions, type SchurResult, type SliceSpec, SparseMatrix, type SqrtmOptions, type SyncConfig, SyncManager, type SyncStrategy, WASMBackend, type WASMBackendConfig, type WasmFeatures, abs, add, backendManager, backendRegistry, cholesky, clearFeatureCache, column, cond, createBackendManager, createGPUMatrixBackend, createParallelBackend, createSyncManager, createWASMBackend, destroyGlobalGPUBackend, detectWasmFeatures, diag, diagonal, divide, dotMultiply, eig, eigWasm, eigvals, eigvalsWasm, exp, getCachedFeatures, getGlobalGPUBackend, gpuMatrixBackend, identity, initializeGlobalGPUBackend, initializeParallelMatrix, isAtomicsAvailable, isDenseMatrix, isMatrix, isSharedMemoryAvailable, isSparseMatrix, isWasmAvailable, jsBackend, log, lowRankApprox, lu, matrix, matrixExpm, matrixLogm, pinv as matrixPinv, matrixSchur, matrixSqrtm, max, mean, min, multiply, norm, norm2, normFro, ones, parallelBackend, parallelDiag, parallelDotMultiply, parallelIdentity, parallelMatrix, parallelMatrixAbs, parallelMatrixAdd, parallelMatrixColumn, parallelMatrixCos, parallelMatrixDiagonal, parallelMatrixDistance, parallelMatrixDivide, parallelMatrixDot, parallelMatrixExp, parallelMatrixHistogram, parallelMatrixLog, parallelMatrixMatvec, parallelMatrixMax, parallelMatrixMean, parallelMatrixMin, parallelMatrixMultiply, parallelMatrixNorm, parallelMatrixOperations, parallelMatrixOuter, parallelMatrixRow, parallelMatrixSin, parallelMatrixSize, parallelMatrixSqrt, parallelMatrixSquare, parallelMatrixStd, parallelMatrixSubset, parallelMatrixSubtract, parallelMatrixSum, parallelMatrixTan, parallelMatrixTrace, parallelMatrixTranspose, parallelMatrixVariance, parallelOnes, parallelRandom, parallelUnaryMinus, parallelZeros, pinv$1 as pinv, pow, powerIteration, qr, random, row, singularValues, size, spectralRadiusWasm, sqrt, square, subset, subtract, sum, svd, svdWasm, terminateParallelMatrix, trace, transpose, typedMatrixOperations, unaryMinus, wasmBackend, zeros };