defuss-multicore 0.0.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.
- package/README.md +314 -0
- package/dist/index.cjs +601 -0
- package/dist/index.d.cts +162 -0
- package/dist/index.d.mts +162 -0
- package/dist/index.mjs +590 -0
- package/dist/pool-DhG3ybwo.mjs +151 -0
- package/dist/pool-DqNSYahJ.cjs +153 -0
- package/dist/pool-browser-BsBdOUwc.cjs +43 -0
- package/dist/pool-browser-IHMOtzRq.mjs +41 -0
- package/dist/pool-node-Chmgg6NZ.mjs +35 -0
- package/dist/pool-node-DKGzL78_.cjs +38 -0
- package/package.json +73 -0
package/README.md
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
# defuss-multicore
|
|
2
|
+
|
|
3
|
+
Isomorphic multicore execution + loop-unrolled linear algebra for JavaScript/TypeScript.
|
|
4
|
+
|
|
5
|
+
- **Web Workers** in the browser, **worker_threads** in Node.js — same API
|
|
6
|
+
- Auto-splits arrays/TypedArrays across CPU cores
|
|
7
|
+
- JIT loop-unrolled vector/matrix ops (4x/8x/16x unroll factors, auto-selected)
|
|
8
|
+
- Parallel `map`, `filter`, `reduce` for any array
|
|
9
|
+
- Zero dependencies, ESM + CJS dual output
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
bun add defuss-multicore
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Quick Start
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { multicore, dotProduct, matmul, matadd } from "defuss-multicore";
|
|
21
|
+
|
|
22
|
+
// 1. Wrap any pure function for parallel execution
|
|
23
|
+
const parallelSum = multicore(
|
|
24
|
+
(chunk: number[]) => chunk.reduce((a, b) => a + b, 0),
|
|
25
|
+
{ reduce: (a: number, b: number) => a + b },
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
const total = await parallelSum([1, 2, 3, /* ...millions of items */ ]);
|
|
29
|
+
|
|
30
|
+
// 2. Use built-in optimized ops
|
|
31
|
+
const scores = dotProduct(embeddings, queries); // Float32Array
|
|
32
|
+
const C = matmul(A, B); // Float64Array[]
|
|
33
|
+
const sum = matadd(A, B); // Float64Array[]
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## API
|
|
37
|
+
|
|
38
|
+
### `multicore(fn, options?)`
|
|
39
|
+
|
|
40
|
+
Higher-order function that wraps a **pure function** for parallel execution across CPU cores.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
const parallel = multicore(fn, options?);
|
|
44
|
+
const results = await parallel(data); // collect all results
|
|
45
|
+
for await (const r of parallel(data)) { ... } // stream as workers finish
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
- Array/TypedArray args are **auto-split** across cores
|
|
49
|
+
- Scalar args are **broadcast** to every worker
|
|
50
|
+
- Returns `ParallelResult<R>` — both `PromiseLike<R[]>` and `AsyncIterable<R>`
|
|
51
|
+
|
|
52
|
+
#### `MulticoreOptions<R>`
|
|
53
|
+
|
|
54
|
+
| Option | Type | Default | Description |
|
|
55
|
+
|-------------|---------------------------|------------------------|-------------|
|
|
56
|
+
| `cores` | `number` | `navigator.hardwareConcurrency` | Number of worker threads |
|
|
57
|
+
| `threshold` | `number` | `1024` | Min array length before parallelizing (falls back to main thread below this) |
|
|
58
|
+
| `reduce` | `(a: R, b: R) => R` | — | Reduce partial results into a single value |
|
|
59
|
+
| `eager` | `boolean` | `false` | Pre-spawn workers immediately instead of on first call |
|
|
60
|
+
|
|
61
|
+
#### `CallOptions` (per-call overrides)
|
|
62
|
+
|
|
63
|
+
| Option | Type | Default | Description |
|
|
64
|
+
|------------|----------------|----------|-------------|
|
|
65
|
+
| `cores` | `number` | — | Override core count for this call |
|
|
66
|
+
| `signal` | `AbortSignal` | — | Cancel in-flight workers |
|
|
67
|
+
| `transfer` | `boolean` | `true` | Auto-detect and transfer ArrayBuffer ownership (zero-copy) |
|
|
68
|
+
|
|
69
|
+
### `map(array, fn, options?)`
|
|
70
|
+
|
|
71
|
+
Parallel `Array.prototype.map`. Distributes work across cores, flattens results.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { map } from "defuss-multicore";
|
|
75
|
+
|
|
76
|
+
const doubled = await map(hugeArray, (x) => x * 2);
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### `filter(array, fn, options?)`
|
|
80
|
+
|
|
81
|
+
Parallel `Array.prototype.filter`.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { filter } from "defuss-multicore";
|
|
85
|
+
|
|
86
|
+
const evens = await filter(hugeArray, (x) => x % 2 === 0);
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### `reduce(array, fn, initial, options?)`
|
|
90
|
+
|
|
91
|
+
Parallel `Array.prototype.reduce`. Each worker reduces its chunk, then partial results are reduced on the main thread.
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { reduce } from "defuss-multicore";
|
|
95
|
+
|
|
96
|
+
const sum = await reduce(hugeArray, (a, b) => a + b, 0);
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### `dotProduct(as, bs)`
|
|
100
|
+
|
|
101
|
+
Batch dot product of vector pairs. JIT loop-unrolled (up to 16× unroll).
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import { dotProduct } from "defuss-multicore";
|
|
105
|
+
|
|
106
|
+
// 100K pairs of 768-dim vectors (e.g. embedding similarity)
|
|
107
|
+
const scores: Float32Array = dotProduct(embeddings, queries);
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
- Input: `Float64Array[]` pairs (each inner array is one vector)
|
|
111
|
+
- Output: `Float32Array` of dot products
|
|
112
|
+
|
|
113
|
+
### `matmul(A, B)`
|
|
114
|
+
|
|
115
|
+
Matrix multiplication with transpose optimization + loop unrolling.
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { matmul } from "defuss-multicore";
|
|
119
|
+
|
|
120
|
+
// A: M×K, B: K×N → C: M×N
|
|
121
|
+
const C: Float64Array[] = matmul(A, B);
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### `matadd(A, B)` / `matsub(A, B)` / `matdiv(A, B)`
|
|
125
|
+
|
|
126
|
+
Element-wise matrix operations with loop unrolling.
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { matadd, matsub, matdiv } from "defuss-multicore";
|
|
130
|
+
|
|
131
|
+
const sum = matadd(A, B);
|
|
132
|
+
const diff = matsub(A, B);
|
|
133
|
+
const quot = matdiv(A, B);
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
All matrix ops use `Matrix<Float64Array>` — an array of row vectors (`Float64Array[]`).
|
|
137
|
+
|
|
138
|
+
### `getPoolSize()`
|
|
139
|
+
|
|
140
|
+
Returns the number of available CPU cores (used as default worker count).
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import { getPoolSize } from "defuss-multicore";
|
|
144
|
+
|
|
145
|
+
console.log(`Using ${getPoolSize()} cores`);
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## Types
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
type NumericArray = number[] | Float32Array | Float64Array | Int8Array | ...;
|
|
152
|
+
type Matrix<T> = T[]; // Array of row vectors (e.g. Float64Array[])
|
|
153
|
+
type Vectors<T> = T[]; // Array of vectors
|
|
154
|
+
|
|
155
|
+
interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Benchmark Results
|
|
159
|
+
|
|
160
|
+
All benchmarks measured on Node.js (worker_threads) on Apple Silicon (10 cores). Median of 5 runs, 2 warmup. Reproduce with `bun run bench`.
|
|
161
|
+
|
|
162
|
+
### Loop-Unrolled Ops vs Naive Baseline
|
|
163
|
+
|
|
164
|
+
Single-threaded comparison — same thread, unrolled kernels vs naive loops:
|
|
165
|
+
|
|
166
|
+
| Operation | Size | Speedup |
|
|
167
|
+
|-----------|------|---------|
|
|
168
|
+
| **matmul** | 200 × 300 × 200 | **2.36×** |
|
|
169
|
+
| **matadd** | 1000 × 1000 | **2.11×** |
|
|
170
|
+
| **matmul** | 500 × 500 | **2.06×** |
|
|
171
|
+
| **dotProduct** | 100K × 768-dim | **1.46×** |
|
|
172
|
+
| **matsub** | 1000 × 1000 | 0.49× |
|
|
173
|
+
| **matdiv** | 1000 × 1000 | 0.37× |
|
|
174
|
+
|
|
175
|
+
Loop unrolling shines on **compute-heavy inner loops** like matrix multiplication, where the unrolled kernel avoids branch overhead and allows the CPU to pipeline instructions. Element-wise ops (add/sub/div) benefit less because the operation per element is trivial — the memory access pattern dominates.
|
|
176
|
+
|
|
177
|
+
### Multicore Workers vs Single-Thread
|
|
178
|
+
|
|
179
|
+
Worker parallelism — dispatching across all CPU cores vs running on the main thread:
|
|
180
|
+
|
|
181
|
+
| Workload | Size | Speedup |
|
|
182
|
+
|----------|------|---------|
|
|
183
|
+
| **Key stretching** (PBKDF2-like) | 100K × 1000 rounds | **4.89×** |
|
|
184
|
+
| **CRC32** (network packets) | 10K × 4KB | **1.31×** |
|
|
185
|
+
| **CRC32** (small messages) | 500K × 64B | 0.80× |
|
|
186
|
+
| **Transform** (sin+cos) | 5M items | 0.60× |
|
|
187
|
+
| **FNV-1a** hash | 1M × 128B | 0.44× |
|
|
188
|
+
| **Filter** elements | 2M items | 0.39× |
|
|
189
|
+
| **Sum** (accumulate) | 10M items | 0.06× |
|
|
190
|
+
|
|
191
|
+
## When to Use `multicore()`
|
|
192
|
+
|
|
193
|
+
The benchmarks tell a clear story: **worker parallelism pays off when each chunk does meaningful CPU work**. The overhead of serializing data, posting messages, and collecting results is ~2-10ms per dispatch. If the per-chunk work is under that threshold, you lose.
|
|
194
|
+
|
|
195
|
+
### DO: Parallelize These
|
|
196
|
+
|
|
197
|
+
- **Key derivation / password hashing** — thousands of rounds per item (4.9× speedup)
|
|
198
|
+
- **Batch checksumming** (CRC32, SHA, etc.) of large messages — enough work per chunk to amortize dispatch
|
|
199
|
+
- **Heavy per-element computation** — image processing, physics simulation, compression
|
|
200
|
+
- **Any workload where each chunk runs >5ms** on a single core
|
|
201
|
+
|
|
202
|
+
### DON'T: Parallelize These
|
|
203
|
+
|
|
204
|
+
- **Simple reductions** (sum, min, max) — main-thread loop is faster than worker dispatch
|
|
205
|
+
- **Trivial transforms** (multiply, add constant) — memory-bandwidth bound, not CPU-bound
|
|
206
|
+
- **Small arrays** (<1024 elements) — the `threshold` option exists for this reason
|
|
207
|
+
- **Single function calls** — multicore is for **batches**, not individual invocations
|
|
208
|
+
- **I/O-bound work** — fetch, file reads, DB queries are already async; workers add overhead
|
|
209
|
+
|
|
210
|
+
### DO: Use Loop-Unrolled Ops
|
|
211
|
+
|
|
212
|
+
- **`matmul`** for matrix multiplication, neural network layers (2×+ speedup)
|
|
213
|
+
- **`matadd`** for accumulating matrices (2.1×)
|
|
214
|
+
- **`dotProduct`** for embedding similarity, cosine distance, attention scores (1.5×+ speedup)
|
|
215
|
+
|
|
216
|
+
### Key Principles
|
|
217
|
+
|
|
218
|
+
1. **Measure first.** The `threshold` option exists so small inputs fall back to the main thread automatically. But "small" depends on your workload — a 10K-element array of simple additions is too small; a 10K-element array of 1000-round hash stretches is perfect.
|
|
219
|
+
|
|
220
|
+
2. **Worker functions must be pure.** They run in isolated contexts — no closures, no imports, no DOM access. Everything the function needs must be passed as arguments or computed inline.
|
|
221
|
+
|
|
222
|
+
3. **Transferables are auto-detected.** ArrayBuffers are transferred (zero-copy) by default. Disable with `{ transfer: false }` if you need to reuse the buffer after the call.
|
|
223
|
+
|
|
224
|
+
4. **Use `reduce` for aggregation.** Without it, you get back an array of partial results (one per worker). With `reduce`, partial results are combined into a single value.
|
|
225
|
+
|
|
226
|
+
5. **Use `eager: true` for latency-sensitive paths.** By default, the worker pool is created lazily on first call. Set `eager: true` to pre-spawn workers at wrap time.
|
|
227
|
+
|
|
228
|
+
## Pattern: Crypto/Compression Worker
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
import { multicore } from "defuss-multicore";
|
|
232
|
+
|
|
233
|
+
const parallelCRC32 = multicore(
|
|
234
|
+
(seeds: number[]) => {
|
|
235
|
+
// Build CRC32 lookup table inside worker (no closures!)
|
|
236
|
+
const table = new Uint32Array(256);
|
|
237
|
+
for (let i = 0; i < 256; i++) {
|
|
238
|
+
let c = i;
|
|
239
|
+
for (let j = 0; j < 8; j++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1;
|
|
240
|
+
table[i] = c;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const results = new Uint32Array(seeds.length);
|
|
244
|
+
for (let idx = 0; idx < seeds.length; idx++) {
|
|
245
|
+
const buf = generateMessage(seeds[idx]); // deterministic from seed
|
|
246
|
+
let crc = 0xFFFFFFFF;
|
|
247
|
+
for (let i = 0; i < buf.length; i++) {
|
|
248
|
+
crc = table[(crc ^ buf[i]) & 0xFF] ^ (crc >>> 8);
|
|
249
|
+
}
|
|
250
|
+
results[idx] = (crc ^ 0xFFFFFFFF) >>> 0;
|
|
251
|
+
}
|
|
252
|
+
return results;
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
threshold: 256,
|
|
256
|
+
reduce: (a: Uint32Array, b: Uint32Array) => {
|
|
257
|
+
const merged = new Uint32Array(a.length + b.length);
|
|
258
|
+
merged.set(a, 0);
|
|
259
|
+
merged.set(b, a.length);
|
|
260
|
+
return merged;
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
);
|
|
264
|
+
|
|
265
|
+
const checksums = await parallelCRC32(messageIndices);
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
## Pattern: Streaming Results
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
const parallel = multicore(heavyComputation);
|
|
272
|
+
|
|
273
|
+
// Stream results as each worker finishes (submission order)
|
|
274
|
+
for await (const result of parallel(data)) {
|
|
275
|
+
console.log("Worker finished:", result);
|
|
276
|
+
}
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
## Pattern: Cancellation
|
|
280
|
+
|
|
281
|
+
```ts
|
|
282
|
+
const controller = new AbortController();
|
|
283
|
+
const parallel = multicore(expensiveFn);
|
|
284
|
+
|
|
285
|
+
const result = parallel(data, { signal: controller.signal });
|
|
286
|
+
|
|
287
|
+
// Cancel after 5 seconds
|
|
288
|
+
setTimeout(() => controller.abort(), 5000);
|
|
289
|
+
|
|
290
|
+
try {
|
|
291
|
+
await result;
|
|
292
|
+
} catch (e) {
|
|
293
|
+
console.log("Cancelled");
|
|
294
|
+
}
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
## Testing
|
|
298
|
+
|
|
299
|
+
```bash
|
|
300
|
+
# Unit tests (272 tests)
|
|
301
|
+
bun run test
|
|
302
|
+
|
|
303
|
+
# Browser E2E tests via Playwright (21 tests)
|
|
304
|
+
bun run test:browser
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
## Requirements
|
|
308
|
+
|
|
309
|
+
- **Node.js** ^18.17.1 || ^20.3.0 || >=21.0.0
|
|
310
|
+
- **Browser** Any browser with Web Workers + structured clone
|
|
311
|
+
|
|
312
|
+
## License
|
|
313
|
+
|
|
314
|
+
MIT
|