defuss-multicore 0.0.2 → 0.1.0

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/dist/index.cjs CHANGED
@@ -1,601 +1,20 @@
1
1
  'use strict';
2
2
 
3
- const isTypedArray = (v) => ArrayBuffer.isView(v) && !(v instanceof DataView);
4
- const isCallOptions = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && !ArrayBuffer.isView(v) && ("cores" in v || "signal" in v || "transfer" in v);
5
-
6
- const warnIfClosure = (fn) => {
7
- const src = fn.toString();
8
- const bodyMatch = src.match(/\{([\s\S]*)\}$/);
9
- if (!bodyMatch) return;
10
- const body = bodyMatch[1];
11
- if (/\bthis\b/.test(body) && src.startsWith("(")) {
12
- console.warn(
13
- "[defuss-multicore] Warning: function references `this` which will be undefined in a worker context."
14
- );
15
- }
16
- };
17
- const serializeFunction = (fn) => {
18
- warnIfClosure(fn);
19
- const fnString = fn.toString();
20
- return `
21
- 'use strict';
22
-
23
- const __fn = ${fnString};
24
-
25
- const __isTypedArray = (v) =>
26
- ArrayBuffer.isView(v) && !(v instanceof DataView);
27
-
28
- const __getTransferables = (value) => {
29
- if (__isTypedArray(value)) return [value.buffer];
30
- if (value instanceof ArrayBuffer) return [value];
31
- if (Array.isArray(value)) {
32
- const transfers = [];
33
- for (let i = 0; i < value.length; i++) {
34
- if (__isTypedArray(value[i])) transfers.push(value[i].buffer);
35
- else if (value[i] instanceof ArrayBuffer) transfers.push(value[i]);
36
- }
37
- return transfers;
38
- }
39
- return [];
40
- };
41
-
42
- const __handleMessage = (data) => {
43
- if (data.type === 'execute') {
44
- try {
45
- const result = __fn(...data.args);
46
- const transfer = __getTransferables(result);
47
- const msg = { type: 'result', id: data.id, value: result };
48
- if (typeof postMessage === 'function') {
49
- postMessage(msg, transfer);
50
- } else {
51
- const { parentPort } = require('node:worker_threads');
52
- parentPort.postMessage(msg, transfer);
53
- }
54
- } catch (err) {
55
- const msg = {
56
- type: 'error',
57
- id: data.id,
58
- error: err instanceof Error ? err.message : String(err),
59
- stack: err instanceof Error ? err.stack : undefined,
60
- };
61
- if (typeof postMessage === 'function') {
62
- postMessage(msg);
63
- } else {
64
- const { parentPort } = require('node:worker_threads');
65
- parentPort.postMessage(msg);
66
- }
67
- }
68
- }
69
- // 'abort' type is a no-op; the caller terminates the worker externally
70
- };
71
-
72
- // Browser Web Worker
73
- if (typeof self !== 'undefined' && typeof self.onmessage !== 'undefined') {
74
- self.onmessage = (e) => __handleMessage(e.data);
75
- }
76
-
77
- // Node.js worker_threads
78
- if (typeof require !== 'undefined') {
79
- try {
80
- const { parentPort } = require('node:worker_threads');
81
- if (parentPort) {
82
- parentPort.on('message', __handleMessage);
83
- }
84
- } catch (_) {
85
- // Not in worker_threads context - ignore
86
- }
87
- }
88
- `.trim();
89
- };
90
-
91
- const partitionArgs = (args, cores) => {
92
- const perWorker = Array.from({ length: cores }, () => []);
93
- for (const arg of args) {
94
- if (Array.isArray(arg)) {
95
- const chunks = splitArray(arg, cores);
96
- for (let w = 0; w < cores; w++) {
97
- perWorker[w].push(chunks[w]);
98
- }
99
- } else if (isTypedArray(arg)) {
100
- const chunks = splitTypedArray(arg, cores);
101
- for (let w = 0; w < cores; w++) {
102
- perWorker[w].push(chunks[w]);
103
- }
104
- } else {
105
- for (let w = 0; w < cores; w++) {
106
- perWorker[w].push(arg);
107
- }
108
- }
109
- }
110
- return perWorker;
111
- };
112
- const splitArray = (arr, n) => {
113
- const len = arr.length;
114
- const base = Math.floor(len / n);
115
- const remainder = len % n;
116
- const chunks = [];
117
- let offset = 0;
118
- for (let i = 0; i < n; i++) {
119
- const size = base + (i < remainder ? 1 : 0);
120
- chunks.push(arr.slice(offset, offset + size));
121
- offset += size;
122
- }
123
- return chunks;
124
- };
125
- const splitTypedArray = (arr, n) => {
126
- const len = arr.length;
127
- const base = Math.floor(len / n);
128
- const remainder = len % n;
129
- const chunks = [];
130
- let offset = 0;
131
- for (let i = 0; i < n; i++) {
132
- const size = base + (i < remainder ? 1 : 0);
133
- chunks.push(arr.subarray(offset, offset + size));
134
- offset += size;
135
- }
136
- return chunks;
137
- };
138
- const shouldFallback = (args, threshold) => {
139
- let maxLen = 0;
140
- for (const arg of args) {
141
- if (Array.isArray(arg)) {
142
- maxLen = Math.max(maxLen, arg.length);
143
- } else if (isTypedArray(arg)) {
144
- maxLen = Math.max(maxLen, arg.length);
145
- }
146
- }
147
- return maxLen < threshold;
148
- };
149
- const detectTransferables = (args) => {
150
- const buffers = [];
151
- for (const arg of args) {
152
- if (arg instanceof ArrayBuffer) {
153
- buffers.push(arg);
154
- } else if (isTypedArray(arg)) {
155
- const ta = arg;
156
- if (ta.byteOffset === 0 && ta.byteLength === ta.buffer.byteLength) {
157
- buffers.push(ta.buffer);
158
- }
159
- }
160
- }
161
- return buffers;
162
- };
163
- const getCoreCount = () => {
164
- if (typeof navigator !== "undefined" && navigator.hardwareConcurrency) {
165
- return navigator.hardwareConcurrency;
166
- }
167
- try {
168
- const os = require("node:os");
169
- return os.cpus().length;
170
- } catch {
171
- return 4;
172
- }
173
- };
174
-
175
- const isBrowser = () => typeof globalThis !== "undefined" && typeof globalThis.Worker === "function";
176
- let createPoolFn = null;
177
- const getPoolFactory = async () => {
178
- if (createPoolFn) return createPoolFn;
179
- if (isBrowser()) {
180
- const { createBrowserPool } = await Promise.resolve().then(function () { return require('./pool-browser-BsBdOUwc.cjs'); });
181
- createPoolFn = createBrowserPool;
182
- } else {
183
- const { createNodePool } = await Promise.resolve().then(function () { return require('./pool-node-DKGzL78_.cjs'); });
184
- createPoolFn = createNodePool;
185
- }
186
- return createPoolFn;
187
- };
188
- const multicore = (fn, options) => {
189
- const defaultCores = options?.cores ?? getCoreCount();
190
- const threshold = options?.threshold ?? 1024;
191
- const reduceFn = options?.reduce;
192
- const eager = options?.eager ?? false;
193
- const script = serializeFunction(fn);
194
- let pool = null;
195
- const getPool = async () => {
196
- if (!pool) {
197
- const factory = await getPoolFactory();
198
- pool = factory(script, { maxWorkers: defaultCores });
199
- }
200
- return pool;
201
- };
202
- if (eager) {
203
- getPool().then((p) => p.warmup(defaultCores));
204
- }
205
- const parallelFn = (...rawArgs) => {
206
- let callOpts;
207
- let args;
208
- if (rawArgs.length > 0 && isCallOptions(rawArgs[rawArgs.length - 1])) {
209
- callOpts = rawArgs[rawArgs.length - 1];
210
- args = rawArgs.slice(0, -1);
211
- } else {
212
- args = rawArgs;
213
- }
214
- const cores = callOpts?.cores ?? defaultCores;
215
- const signal = callOpts?.signal;
216
- const transferOpt = callOpts?.transfer;
217
- if (shouldFallback(args, threshold)) {
218
- return createMainThreadResult(fn, args, reduceFn);
219
- }
220
- const partitioned = partitionArgs(args, cores);
221
- const shouldTransfer = transferOpt !== false;
222
- const workerPromises = partitioned.map((workerArgs) => {
223
- const transfer = shouldTransfer ? detectTransferables(workerArgs) : [];
224
- return getPool().then((p) => p.execute(workerArgs, transfer, signal));
225
- });
226
- return createParallelResult(workerPromises, reduceFn);
227
- };
228
- return parallelFn;
229
- };
230
- const createParallelResult = (promises, reduceFn) => {
231
- const result = {
232
- // PromiseLike: await resolves to R[] (or R if reduce is set)
233
- then(onfulfilled, onrejected) {
234
- const collected = Promise.all(promises).then((results) => {
235
- if (reduceFn && results.length > 0) {
236
- return results.reduce(reduceFn);
237
- }
238
- return results;
239
- });
240
- return collected.then(onfulfilled, onrejected);
241
- },
242
- // AsyncIterable: yields results as workers complete
243
- [Symbol.asyncIterator]() {
244
- let index = 0;
245
- return {
246
- async next() {
247
- if (index >= promises.length) {
248
- return { done: true, value: void 0 };
249
- }
250
- const value = await promises[index++];
251
- return { done: false, value };
252
- }
253
- };
254
- }
255
- };
256
- return result;
257
- };
258
- const createMainThreadResult = (fn, args, reduceFn) => {
259
- let resultValue;
260
- let error = null;
261
- try {
262
- resultValue = fn(...args);
263
- } catch (e) {
264
- error = e instanceof Error ? e : new Error(String(e));
265
- resultValue = void 0;
266
- }
267
- const result = {
268
- then(onfulfilled, onrejected) {
269
- if (error) {
270
- return Promise.reject(error).then(onfulfilled, onrejected);
271
- }
272
- const val = reduceFn ? resultValue : [resultValue];
273
- return Promise.resolve(val).then(onfulfilled, onrejected);
274
- },
275
- [Symbol.asyncIterator]() {
276
- let yielded = false;
277
- return {
278
- async next() {
279
- if (error) throw error;
280
- if (yielded) return { done: true, value: void 0 };
281
- yielded = true;
282
- return { done: false, value: resultValue };
283
- }
284
- };
285
- }
286
- };
287
- return result;
288
- };
289
-
290
- const map = (array, fn, options) => {
291
- const fnStr = fn.toString();
292
- const chunkFn = new Function(
293
- "chunk",
294
- `const __mapFn = ${fnStr}; return chunk.map(__mapFn);`
295
- );
296
- const parallel = multicore(chunkFn, { threshold: 1024, ...options });
297
- const result = parallel(array, options);
298
- return {
299
- then(onfulfilled, onrejected) {
300
- return result.then(
301
- (chunks) => chunks.flat ? chunks.flat() : [].concat(...chunks),
302
- void 0
303
- ).then(onfulfilled, onrejected);
304
- },
305
- [Symbol.asyncIterator]() {
306
- return result[Symbol.asyncIterator]();
307
- }
308
- };
309
- };
310
- const filter = (array, fn, options) => {
311
- const fnStr = fn.toString();
312
- const chunkFn = new Function(
313
- "chunk",
314
- `const __filterFn = ${fnStr}; return chunk.filter(__filterFn);`
315
- );
316
- const parallel = multicore(chunkFn, { threshold: 1024, ...options });
317
- const result = parallel(array, options);
318
- return {
319
- then(onfulfilled, onrejected) {
320
- return result.then(
321
- (chunks) => chunks.flat ? chunks.flat() : [].concat(...chunks),
322
- void 0
323
- ).then(onfulfilled, onrejected);
324
- },
325
- [Symbol.asyncIterator]() {
326
- return result[Symbol.asyncIterator]();
327
- }
328
- };
329
- };
330
- const reduce = (array, fn, initial, options) => {
331
- const fnStr = fn.toString();
332
- const chunkFn = new Function(
333
- "chunk",
334
- `const __reduceFn = ${fnStr}; return chunk.reduce(__reduceFn);`
335
- );
336
- const parallel = multicore(chunkFn, { threshold: 1024, ...options });
337
- const result = parallel(array, options);
338
- return result.then((partials) => {
339
- return partials.reduce(fn, initial);
340
- });
341
- };
342
-
343
- const selectUnrollFactor = (dims) => {
344
- if (dims < 16) return 4;
345
- if (dims < 64) return 8;
346
- return 16;
347
- };
348
- const opFn = {
349
- add: (a, b) => a + b,
350
- sub: (a, b) => a - b,
351
- mul: (a, b) => a * b,
352
- div: (a, b) => a / b
353
- };
354
- const createElementWiseKernel = (op, factor) => {
355
- const fn = opFn[op];
356
- return (a, b, out, offset, length) => {
357
- const end = offset + length;
358
- const unrolledEnd = offset + length - length % factor;
359
- let j = offset;
360
- if (factor === 4) {
361
- for (; j < unrolledEnd; j += 4) {
362
- out[j] = fn(a[j], b[j]);
363
- out[j + 1] = fn(a[j + 1], b[j + 1]);
364
- out[j + 2] = fn(a[j + 2], b[j + 2]);
365
- out[j + 3] = fn(a[j + 3], b[j + 3]);
366
- }
367
- } else if (factor === 8) {
368
- for (; j < unrolledEnd; j += 8) {
369
- out[j] = fn(a[j], b[j]);
370
- out[j + 1] = fn(a[j + 1], b[j + 1]);
371
- out[j + 2] = fn(a[j + 2], b[j + 2]);
372
- out[j + 3] = fn(a[j + 3], b[j + 3]);
373
- out[j + 4] = fn(a[j + 4], b[j + 4]);
374
- out[j + 5] = fn(a[j + 5], b[j + 5]);
375
- out[j + 6] = fn(a[j + 6], b[j + 6]);
376
- out[j + 7] = fn(a[j + 7], b[j + 7]);
377
- }
378
- } else {
379
- for (; j < unrolledEnd; j += 16) {
380
- out[j] = fn(a[j], b[j]);
381
- out[j + 1] = fn(a[j + 1], b[j + 1]);
382
- out[j + 2] = fn(a[j + 2], b[j + 2]);
383
- out[j + 3] = fn(a[j + 3], b[j + 3]);
384
- out[j + 4] = fn(a[j + 4], b[j + 4]);
385
- out[j + 5] = fn(a[j + 5], b[j + 5]);
386
- out[j + 6] = fn(a[j + 6], b[j + 6]);
387
- out[j + 7] = fn(a[j + 7], b[j + 7]);
388
- out[j + 8] = fn(a[j + 8], b[j + 8]);
389
- out[j + 9] = fn(a[j + 9], b[j + 9]);
390
- out[j + 10] = fn(a[j + 10], b[j + 10]);
391
- out[j + 11] = fn(a[j + 11], b[j + 11]);
392
- out[j + 12] = fn(a[j + 12], b[j + 12]);
393
- out[j + 13] = fn(a[j + 13], b[j + 13]);
394
- out[j + 14] = fn(a[j + 14], b[j + 14]);
395
- out[j + 15] = fn(a[j + 15], b[j + 15]);
396
- }
397
- }
398
- for (; j < end; j++) {
399
- out[j] = fn(a[j], b[j]);
400
- }
401
- };
402
- };
403
- const createDotKernel = (factor) => {
404
- return (a, b, dims) => {
405
- const unrolledEnd = dims - dims % factor;
406
- let j = 0;
407
- if (factor === 4) {
408
- let acc02 = 0, acc16 = 0, acc22 = 0, acc32 = 0;
409
- for (; j < unrolledEnd; j += 4) {
410
- acc02 += a[j] * b[j];
411
- acc16 += a[j + 1] * b[j + 1];
412
- acc22 += a[j + 2] * b[j + 2];
413
- acc32 += a[j + 3] * b[j + 3];
414
- }
415
- let sum2 = acc02 + acc16 + acc22 + acc32;
416
- for (; j < dims; j++) sum2 += a[j] * b[j];
417
- return sum2;
418
- }
419
- if (factor === 8) {
420
- let acc02 = 0, acc16 = 0, acc22 = 0, acc32 = 0;
421
- let acc42 = 0, acc52 = 0, acc62 = 0, acc72 = 0;
422
- for (; j < unrolledEnd; j += 8) {
423
- acc02 += a[j] * b[j];
424
- acc16 += a[j + 1] * b[j + 1];
425
- acc22 += a[j + 2] * b[j + 2];
426
- acc32 += a[j + 3] * b[j + 3];
427
- acc42 += a[j + 4] * b[j + 4];
428
- acc52 += a[j + 5] * b[j + 5];
429
- acc62 += a[j + 6] * b[j + 6];
430
- acc72 += a[j + 7] * b[j + 7];
431
- }
432
- let sum2 = acc02 + acc16 + (acc22 + acc32) + (acc42 + acc52) + (acc62 + acc72);
433
- for (; j < dims; j++) sum2 += a[j] * b[j];
434
- return sum2;
435
- }
436
- let acc0 = 0, acc1 = 0, acc2 = 0, acc3 = 0;
437
- let acc4 = 0, acc5 = 0, acc6 = 0, acc7 = 0;
438
- let acc8 = 0, acc9 = 0, acc10 = 0, acc11 = 0;
439
- let acc12 = 0, acc13 = 0, acc14 = 0, acc15 = 0;
440
- for (; j < unrolledEnd; j += 16) {
441
- acc0 += a[j] * b[j];
442
- acc1 += a[j + 1] * b[j + 1];
443
- acc2 += a[j + 2] * b[j + 2];
444
- acc3 += a[j + 3] * b[j + 3];
445
- acc4 += a[j + 4] * b[j + 4];
446
- acc5 += a[j + 5] * b[j + 5];
447
- acc6 += a[j + 6] * b[j + 6];
448
- acc7 += a[j + 7] * b[j + 7];
449
- acc8 += a[j + 8] * b[j + 8];
450
- acc9 += a[j + 9] * b[j + 9];
451
- acc10 += a[j + 10] * b[j + 10];
452
- acc11 += a[j + 11] * b[j + 11];
453
- acc12 += a[j + 12] * b[j + 12];
454
- acc13 += a[j + 13] * b[j + 13];
455
- acc14 += a[j + 14] * b[j + 14];
456
- acc15 += a[j + 15] * b[j + 15];
457
- }
458
- let sum = acc0 + acc1 + acc2 + acc3 + (acc4 + acc5 + acc6 + acc7) + (acc8 + acc9 + acc10 + acc11) + (acc12 + acc13 + acc14 + acc15);
459
- for (; j < dims; j++) sum += a[j] * b[j];
460
- return sum;
461
- };
462
- };
463
- const ewCache = /* @__PURE__ */ new Map();
464
- const getElementWiseKernel = (op, factor) => {
465
- const key = `${op}_${factor}`;
466
- let kernel = ewCache.get(key);
467
- if (!kernel) {
468
- kernel = createElementWiseKernel(op, factor);
469
- ewCache.set(key, kernel);
470
- }
471
- return kernel;
472
- };
473
- const dotCache = /* @__PURE__ */ new Map();
474
- const getDotKernel = (factor) => {
475
- let kernel = dotCache.get(factor);
476
- if (!kernel) {
477
- kernel = createDotKernel(factor);
478
- dotCache.set(factor, kernel);
479
- }
480
- return kernel;
481
- };
482
-
483
- const dotProduct = (vectorsA, vectorsB, options) => {
484
- const count = vectorsA.length;
485
- if (count !== vectorsB.length) {
486
- throw new RangeError(
487
- `dotProduct: vectorsA.length (${count}) !== vectorsB.length (${vectorsB.length})`
488
- );
489
- }
490
- if (count === 0) return new Float32Array(0);
491
- const dims = vectorsA[0].length;
492
- const factor = options?.unroll ?? selectUnrollFactor(dims);
493
- const kernel = getDotKernel(factor);
494
- const results = new Float32Array(count);
495
- for (let i = 0; i < count; i++) {
496
- results[i] = kernel(vectorsA[i], vectorsB[i], dims);
497
- }
498
- return results;
499
- };
500
-
501
- const matmul = (A, B, options) => {
502
- const M = A.length;
503
- if (M === 0) return [];
504
- const K = A[0].length;
505
- const bRows = B.length;
506
- if (K !== bRows) {
507
- throw new RangeError(
508
- `matmul: A.cols (${K}) !== B.rows (${bRows})`
509
- );
510
- }
511
- const N = B[0].length;
512
- const factor = options?.unroll ?? selectUnrollFactor(K);
513
- const dotKernel = getDotKernel(factor);
514
- const Ctor = A[0].constructor;
515
- const BT = new Array(N);
516
- for (let col = 0; col < N; col++) {
517
- const column = new B[0].constructor(K);
518
- for (let row = 0; row < K; row++) {
519
- column[row] = B[row][col];
520
- }
521
- BT[col] = column;
522
- }
523
- const C = new Array(M);
524
- for (let i = 0; i < M; i++) {
525
- const row = new Ctor(N);
526
- const aRow = A[i];
527
- for (let j = 0; j < N; j++) {
528
- row[j] = dotKernel(aRow, BT[j], K);
529
- }
530
- C[i] = row;
531
- }
532
- return C;
533
- };
534
-
535
- const matadd = (A, B, options) => {
536
- const rows = A.length;
537
- if (rows !== B.length) {
538
- throw new RangeError(`matadd: row count mismatch (${rows} vs ${B.length})`);
539
- }
540
- if (rows === 0) return [];
541
- const cols = A[0].length;
542
- const factor = options?.unroll ?? selectUnrollFactor(cols);
543
- const kernel = getElementWiseKernel("add", factor);
544
- const Ctor = A[0].constructor;
545
- const C = new Array(rows);
546
- for (let i = 0; i < rows; i++) {
547
- const out = new Ctor(cols);
548
- kernel(A[i], B[i], out, 0, cols);
549
- C[i] = out;
550
- }
551
- return C;
552
- };
553
-
554
- const matsub = (A, B, options) => {
555
- const rows = A.length;
556
- if (rows !== B.length) {
557
- throw new RangeError(`matsub: row count mismatch (${rows} vs ${B.length})`);
558
- }
559
- if (rows === 0) return [];
560
- const cols = A[0].length;
561
- const factor = options?.unroll ?? selectUnrollFactor(cols);
562
- const kernel = getElementWiseKernel("sub", factor);
563
- const Ctor = A[0].constructor;
564
- const C = new Array(rows);
565
- for (let i = 0; i < rows; i++) {
566
- const out = new Ctor(cols);
567
- kernel(A[i], B[i], out, 0, cols);
568
- C[i] = out;
569
- }
570
- return C;
571
- };
572
-
573
- const matdiv = (A, B, options) => {
574
- const rows = A.length;
575
- if (rows !== B.length) {
576
- throw new RangeError(`matdiv: row count mismatch (${rows} vs ${B.length})`);
577
- }
578
- if (rows === 0) return [];
579
- const cols = A[0].length;
580
- const factor = options?.unroll ?? selectUnrollFactor(cols);
581
- const kernel = getElementWiseKernel("div", factor);
582
- const Ctor = A[0].constructor;
583
- const C = new Array(rows);
584
- for (let i = 0; i < rows; i++) {
585
- const out = new Ctor(cols);
586
- kernel(A[i], B[i], out, 0, cols);
587
- C[i] = out;
588
- }
589
- return C;
590
- };
591
-
592
- exports.dotProduct = dotProduct;
593
- exports.filter = filter;
594
- exports.getPoolSize = getCoreCount;
595
- exports.map = map;
596
- exports.matadd = matadd;
597
- exports.matdiv = matdiv;
598
- exports.matmul = matmul;
599
- exports.matsub = matsub;
600
- exports.multicore = multicore;
601
- exports.reduce = reduce;
3
+ var index = require('./index-BxtfU1K8.cjs');
4
+ var transfer = require('./transfer-B05kHQLB.cjs');
5
+
6
+
7
+
8
+ exports.createPool = index.createPool$1;
9
+ exports.dotProduct = index.dotProduct;
10
+ exports.filter = index.filter;
11
+ exports.getPoolSize = index.getCoreCount;
12
+ exports.map = index.map;
13
+ exports.matadd = index.matadd;
14
+ exports.matdiv = index.matdiv;
15
+ exports.matmul = index.matmul;
16
+ exports.matsub = index.matsub;
17
+ exports.multicore = index.multicore;
18
+ exports.reduce = index.reduce;
19
+ exports.releaseArrayWorkers = index.releaseArrayWorkers;
20
+ exports.transfer = transfer.transfer;