defuss-multicore 0.1.0 → 0.1.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 +104 -37
- package/dist/worker.cjs +6 -5
- package/dist/worker.mjs +6 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,13 +1,67 @@
|
|
|
1
1
|
# defuss-multicore
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](LICENSE)
|
|
4
|
+
[](package.json)
|
|
5
|
+
[](tsconfig.base.json)
|
|
6
|
+
[](package.json)
|
|
4
7
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
**Multi**core for JavaScript: one `await` for every CPU core, zero dependencies.
|
|
9
|
+
|
|
10
|
+
Web Workers in the browser and `worker_threads` in Node.js behind the same API and the same types. Pure functions are auto-split across cores, typed module workers get a real task pool, and the vector/matrix kernels are JIT loop-unrolled on the caller thread.
|
|
11
|
+
|
|
12
|
+
## TL;DR
|
|
13
|
+
|
|
14
|
+
A JavaScript runtime gives your code one thread. Heavy compute blocks the UI or the event loop, and no amount of `Promise.all` buys a second core.
|
|
15
|
+
|
|
16
|
+
defuss-multicore moves compute to the cores you already have. It splits arrays and TypedArrays into compact partitions, runs each partition in a real worker, and hands the results back through one `await` — the same code in the browser and in Node.
|
|
17
|
+
|
|
18
|
+
- 🔁 **Isomorphic:** Web Workers (browser) and `worker_threads` (Node.js) behind one API
|
|
19
|
+
- ⚡ **Loop-unrolled kernels:** `matmul`, `dotProduct`, `matadd`, `matsub`, `matdiv` JIT-select 4x/8x/16x unroll factors
|
|
20
|
+
- 🧮 **Parallel array methods:** `map`, `filter`, `reduce` for any array, auto-partitioned across cores
|
|
21
|
+
- 🧩 **Typed module workers:** real ESM imports and module-local state, driven by an explicit task pool
|
|
22
|
+
- 🚏 **A pool with a contract:** bounded queue, stable priorities, per-task timeouts, cancellation that stops running work
|
|
23
|
+
- 🔒 **Explicit ownership:** `multicore()` transfers only internal partition copies — your buffers are never detached; pool transfers are opt-in and listed by you
|
|
24
|
+
- 🧯 **Predictable failure:** a crashed worker rejects only its own active job; nothing is retried silently
|
|
25
|
+
- 🪶 **Tiny:** zero runtime dependencies, ESM + CJS dual output, Node ≥ 18.17.1 and every modern browser
|
|
26
|
+
|
|
27
|
+
## How it works
|
|
28
|
+
|
|
29
|
+
```mermaid
|
|
30
|
+
flowchart LR
|
|
31
|
+
U(["🙋 you"]) -->|"array + pure function"| S
|
|
32
|
+
|
|
33
|
+
subgraph split ["🔀 multicore()"]
|
|
34
|
+
S["partition
|
|
35
|
+
auto-split arrays · broadcast scalars"]
|
|
36
|
+
S --> W1["worker 1"]
|
|
37
|
+
S --> W2["worker n"]
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
W1 --> R["reduce
|
|
41
|
+
partials → one value"]
|
|
42
|
+
W2 --> R
|
|
43
|
+
R --> U
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
For real application code — imports, module state, async handlers — the second path is a typed task pool:
|
|
47
|
+
|
|
48
|
+
```mermaid
|
|
49
|
+
flowchart LR
|
|
50
|
+
A["your app"] -->|"run · batch · stream"| Q["bounded queue
|
|
51
|
+
priority · timeout · signal"]
|
|
52
|
+
Q --> P["pool
|
|
53
|
+
warmup → ready workers"]
|
|
54
|
+
P --> W["worker module
|
|
55
|
+
expose(tasks) · init"]
|
|
56
|
+
W -->|"result · transfer(buffers)"| A
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
| API | When you reach for it | What it does |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| **`multicore(fn, options?)`** | batch data + a pure function | Wraps `fn` for parallel execution. Array/TypedArray args are auto-split across cores, scalars are broadcast to every worker, partial results are collected — or reduced to one value via `reduce`. Falls back to the main thread below `threshold`. |
|
|
62
|
+
| **`map` / `filter` / `reduce`** | big arrays, familiar semantics | Parallel counterparts of the `Array.prototype` methods; the reducer must be associative. Pools are cached per callback and released explicitly via `releaseArrayWorkers`. |
|
|
63
|
+
| **`createPool()` + `expose()`** | real application code | Typed module workers with normal ESM imports and module-local state: batching, streaming, priorities, timeouts, cancellation. Always worker execution — no size threshold, no silent main-thread fallback. |
|
|
64
|
+
| **`dotProduct`, `matmul`, `matadd`, …** | numeric kernels | JIT loop-unrolled (4x/8x/16x, auto-selected) vector/matrix math, synchronous on the caller thread. Combine with `multicore()` or a pool to move them into workers. |
|
|
11
65
|
|
|
12
66
|
## Install
|
|
13
67
|
|
|
@@ -131,7 +185,7 @@ export const tasks = {
|
|
|
131
185
|
await expose(tasks, { init: async () => { calls = 0; } });
|
|
132
186
|
```
|
|
133
187
|
|
|
134
|
-
Application side (browser shown; Node is identical with `Worker` from `node:worker_threads`):
|
|
188
|
+
Application side (browser shown; Node.js is identical with `Worker` from `node:worker_threads`, and Bun takes either that one or its global `Worker`):
|
|
135
189
|
|
|
136
190
|
```ts
|
|
137
191
|
import { createPool } from "defuss-multicore";
|
|
@@ -153,7 +207,7 @@ try {
|
|
|
153
207
|
}
|
|
154
208
|
```
|
|
155
209
|
|
|
156
|
-
Keep the `new Worker(new URL(..., import.meta.url), { type: "module" })` expression at the application call site so Vite can bundle the worker graph (use `worker.format: "es"` for top-level await). See
|
|
210
|
+
Keep the `new Worker(new URL(..., import.meta.url), { type: "module" })` expression at the application call site so Vite can bundle the worker graph (use `worker.format: "es"` for top-level await). See [examples/node](examples/node) and [examples/vite](examples/vite).
|
|
157
211
|
|
|
158
212
|
#### Pool contract
|
|
159
213
|
|
|
@@ -231,7 +285,7 @@ import { getPoolSize } from "defuss-multicore";
|
|
|
231
285
|
console.log(`Using ${getPoolSize()} cores`);
|
|
232
286
|
```
|
|
233
287
|
|
|
234
|
-
|
|
288
|
+
### Types
|
|
235
289
|
|
|
236
290
|
```ts
|
|
237
291
|
type NumericArray = number[] | Float32Array | Float64Array | Int8Array | ...;
|
|
@@ -241,11 +295,11 @@ type Vectors<T> = T[]; // Array of vectors
|
|
|
241
295
|
interface ParallelResult<R> extends AsyncIterable<R>, PromiseLike<R[]> {}
|
|
242
296
|
```
|
|
243
297
|
|
|
244
|
-
##
|
|
298
|
+
## Speed
|
|
245
299
|
|
|
246
300
|
All benchmarks measured on Node.js (worker_threads) on Apple Silicon (10 cores). Median of 5 runs, 2 warmup. Reproduce with `bun run bench` (or `npm run bench`).
|
|
247
301
|
|
|
248
|
-
### Loop-
|
|
302
|
+
### Loop-unrolled ops vs naive baseline
|
|
249
303
|
|
|
250
304
|
Single-threaded comparison — same thread, unrolled kernels vs naive loops:
|
|
251
305
|
|
|
@@ -260,7 +314,7 @@ Single-threaded comparison — same thread, unrolled kernels vs naive loops:
|
|
|
260
314
|
|
|
261
315
|
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.
|
|
262
316
|
|
|
263
|
-
### Multicore
|
|
317
|
+
### Multicore workers vs single-thread
|
|
264
318
|
|
|
265
319
|
Worker parallelism — dispatching across all CPU cores vs running on the main thread:
|
|
266
320
|
|
|
@@ -287,18 +341,18 @@ Worker parallelism — dispatching across all CPU cores vs running on the main t
|
|
|
287
341
|
|
|
288
342
|
Four warmed workers were ~2.55x faster than the caller thread, but cold startup exceeded the task duration, and one worker was *slower* than no workers. Persistent reuse and sufficiently large jobs matter.
|
|
289
343
|
|
|
290
|
-
## When to
|
|
344
|
+
## When to use it
|
|
291
345
|
|
|
292
346
|
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.
|
|
293
347
|
|
|
294
|
-
### DO:
|
|
348
|
+
### DO: parallelize these
|
|
295
349
|
|
|
296
350
|
- **Key derivation / password hashing** — thousands of rounds per item (4.9x speedup)
|
|
297
351
|
- **Batch checksumming** (CRC32, SHA, etc.) of large messages — enough work per chunk to amortize dispatch
|
|
298
352
|
- **Heavy per-element computation** — image processing, physics simulation, compression
|
|
299
353
|
- **Any workload where each chunk runs >5ms** on a single core
|
|
300
354
|
|
|
301
|
-
### DON'T:
|
|
355
|
+
### DON'T: parallelize these
|
|
302
356
|
|
|
303
357
|
- **Simple reductions** (sum, min, max) — main-thread loop is faster than worker dispatch
|
|
304
358
|
- **Trivial transforms** (multiply, add constant) — memory-bandwidth bound, not CPU-bound
|
|
@@ -306,13 +360,13 @@ The benchmarks tell a clear story: **worker parallelism pays off when each chunk
|
|
|
306
360
|
- **Single function calls** — multicore is for **batches**, not individual invocations
|
|
307
361
|
- **I/O-bound work** — fetch, file reads, DB queries are already async; workers add overhead
|
|
308
362
|
|
|
309
|
-
### DO:
|
|
363
|
+
### DO: use loop-unrolled ops
|
|
310
364
|
|
|
311
365
|
- **`matmul`** for matrix multiplication, neural network layers (2x+ speedup)
|
|
312
366
|
- **`matadd`** for accumulating matrices (2.1x)
|
|
313
367
|
- **`dotProduct`** for embedding similarity, cosine distance, attention scores (1.5x+ speedup)
|
|
314
368
|
|
|
315
|
-
### Key
|
|
369
|
+
### Key principles
|
|
316
370
|
|
|
317
371
|
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.
|
|
318
372
|
|
|
@@ -324,7 +378,9 @@ The benchmarks tell a clear story: **worker parallelism pays off when each chunk
|
|
|
324
378
|
|
|
325
379
|
5. **Use `eager: true` (or `warmup()`) for latency-sensitive paths.** By default, worker pools are created lazily on first call. Pre-spawn workers when the first call must be fast.
|
|
326
380
|
|
|
327
|
-
##
|
|
381
|
+
## Patterns
|
|
382
|
+
|
|
383
|
+
### Crypto/compression worker
|
|
328
384
|
|
|
329
385
|
```ts
|
|
330
386
|
import { multicore } from "defuss-multicore";
|
|
@@ -364,7 +420,7 @@ const parallelCRC32 = multicore(
|
|
|
364
420
|
const checksums = await parallelCRC32(messageIndices);
|
|
365
421
|
```
|
|
366
422
|
|
|
367
|
-
|
|
423
|
+
### Streaming results
|
|
368
424
|
|
|
369
425
|
```ts
|
|
370
426
|
const parallel = multicore(heavyComputation);
|
|
@@ -380,7 +436,7 @@ for await (const { index, value } of pool.stream("taskName", jobs)) {
|
|
|
380
436
|
}
|
|
381
437
|
```
|
|
382
438
|
|
|
383
|
-
|
|
439
|
+
### Cancellation
|
|
384
440
|
|
|
385
441
|
```ts
|
|
386
442
|
const controller = new AbortController();
|
|
@@ -398,26 +454,21 @@ try {
|
|
|
398
454
|
}
|
|
399
455
|
```
|
|
400
456
|
|
|
401
|
-
##
|
|
457
|
+
## What "verified" means
|
|
402
458
|
|
|
403
|
-
|
|
404
|
-
# Unit tests (293 tests, Node)
|
|
405
|
-
bun run test
|
|
406
|
-
|
|
407
|
-
# Browser E2E tests via Playwright (25 tests, real Chromium)
|
|
408
|
-
bun run test:browser
|
|
459
|
+
Every claim in this README is backed by a suite you can run. A missing check counts as unverified, and unverified fails `bun run verify`.
|
|
409
460
|
|
|
410
|
-
|
|
411
|
-
bun run test:
|
|
461
|
+
- `bun run test` — 293 unit tests on Node.js (`worker_threads`): partitioning, transfer ownership, cancellation, crash isolation, queue bounds
|
|
462
|
+
- `bun run test:browser` — 25 E2E tests in real Chromium via Playwright (Web Workers, no mocks)
|
|
463
|
+
- `bun run test:production` — builds the Vite example with the production bundler and runs real browser workers against the built artifact
|
|
464
|
+
- `bun run test:package` — installs the published tarball in an isolated directory and exercises both the ESM and the CJS entry points
|
|
465
|
+
- `bun run verify` — all of the above plus `tsc` typechecks, including compile-time negative tests for wrong result types
|
|
412
466
|
|
|
413
|
-
|
|
414
|
-
bun run test:package
|
|
467
|
+
Browser tests need Chromium: `bunx playwright install chromium`, or set `PLAYWRIGHT_CHROMIUM_EXECUTABLE` to an existing executable. All `npm run ...` equivalents work as well.
|
|
415
468
|
|
|
416
|
-
|
|
417
|
-
bun run verify
|
|
418
|
-
```
|
|
469
|
+
### Deliberate limits
|
|
419
470
|
|
|
420
|
-
|
|
471
|
+
No automatic retries, no worker affinity, no cross-worker state synchronization, no shared-memory protocol, no distributed execution, no automatic tuning. The math kernels are synchronous and stay on the caller thread. `close()` waits for non-terminating tasks that lack timeouts — use `terminate()` to stop them. Stale-result checks and authoritative state commits remain caller responsibilities. Implementation history and compatibility notes live in [CHANGELOG.md](CHANGELOG.md).
|
|
421
472
|
|
|
422
473
|
## Requirements
|
|
423
474
|
|
|
@@ -425,6 +476,22 @@ All `npm run ...` equivalents work as well. Browser tests need Chromium: `bunx p
|
|
|
425
476
|
- **Bun** 1.x works as installer, script runner and runtime
|
|
426
477
|
- **Browser** — any browser with Web Workers + structured clone (module workers require ES module worker support)
|
|
427
478
|
|
|
479
|
+
## Citation
|
|
480
|
+
|
|
481
|
+
If you use defuss-multicore in research or want to reference it, cite it as:
|
|
482
|
+
|
|
483
|
+
```bibtex
|
|
484
|
+
@misc{homberg2026defussmulticore,
|
|
485
|
+
author = {Homberg, Aron},
|
|
486
|
+
affiliation = {Independent Researcher},
|
|
487
|
+
title = {defuss-multicore: Isomorphic Multicore Execution and Loop-Unrolled Linear Algebra for JavaScript},
|
|
488
|
+
year = {2026},
|
|
489
|
+
version = {0.1.0},
|
|
490
|
+
howpublished = {\url{https://www.npmjs.com/package/defuss-multicore}},
|
|
491
|
+
note = {npm package, MIT License}
|
|
492
|
+
}
|
|
493
|
+
```
|
|
494
|
+
|
|
428
495
|
## License
|
|
429
496
|
|
|
430
|
-
MIT
|
|
497
|
+
MIT — see [LICENSE](LICENSE).
|
package/dist/worker.cjs
CHANGED
|
@@ -5,15 +5,16 @@ var transfer = require('./transfer-B05kHQLB.cjs');
|
|
|
5
5
|
async function expose(tasks, options = {}) {
|
|
6
6
|
let send;
|
|
7
7
|
let listen;
|
|
8
|
-
|
|
8
|
+
const parentPort = typeof process !== "undefined" && typeof process.versions?.node === "string" ? (await import('node:worker_threads')).parentPort : null;
|
|
9
|
+
if (parentPort) {
|
|
10
|
+
send = (data, list = []) => parentPort.postMessage(data, list);
|
|
11
|
+
listen = (handler) => parentPort.on("message", handler);
|
|
12
|
+
} else if (typeof self !== "undefined" && typeof self.postMessage === "function" && typeof document === "undefined") {
|
|
9
13
|
const scope = self;
|
|
10
14
|
send = (data, list = []) => scope.postMessage(data, list);
|
|
11
15
|
listen = (handler) => scope.addEventListener("message", (event) => handler(event.data));
|
|
12
16
|
} else {
|
|
13
|
-
|
|
14
|
-
if (!parentPort) throw new Error("expose() must run inside a worker");
|
|
15
|
-
send = (data, list = []) => parentPort.postMessage(data, list);
|
|
16
|
-
listen = (handler) => parentPort.on("message", handler);
|
|
17
|
+
throw new Error("expose() must run inside a worker");
|
|
17
18
|
}
|
|
18
19
|
try {
|
|
19
20
|
await options.init?.();
|
package/dist/worker.mjs
CHANGED
|
@@ -4,15 +4,16 @@ export { t as transfer } from './transfer-DPiKlTfq.mjs';
|
|
|
4
4
|
async function expose(tasks, options = {}) {
|
|
5
5
|
let send;
|
|
6
6
|
let listen;
|
|
7
|
-
|
|
7
|
+
const parentPort = typeof process !== "undefined" && typeof process.versions?.node === "string" ? (await import('node:worker_threads')).parentPort : null;
|
|
8
|
+
if (parentPort) {
|
|
9
|
+
send = (data, list = []) => parentPort.postMessage(data, list);
|
|
10
|
+
listen = (handler) => parentPort.on("message", handler);
|
|
11
|
+
} else if (typeof self !== "undefined" && typeof self.postMessage === "function" && typeof document === "undefined") {
|
|
8
12
|
const scope = self;
|
|
9
13
|
send = (data, list = []) => scope.postMessage(data, list);
|
|
10
14
|
listen = (handler) => scope.addEventListener("message", (event) => handler(event.data));
|
|
11
15
|
} else {
|
|
12
|
-
|
|
13
|
-
if (!parentPort) throw new Error("expose() must run inside a worker");
|
|
14
|
-
send = (data, list = []) => parentPort.postMessage(data, list);
|
|
15
|
-
listen = (handler) => parentPort.on("message", handler);
|
|
16
|
+
throw new Error("expose() must run inside a worker");
|
|
16
17
|
}
|
|
17
18
|
try {
|
|
18
19
|
await options.init?.();
|