@johnhenry/browsermesh-apps 0.0.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/src/gpu.mjs ADDED
@@ -0,0 +1,732 @@
1
+ /**
2
+ * clawser-mesh-gpu.js -- WebGPU Training Orchestration.
3
+ *
4
+ * Distributed training across mesh peers using WebGPU and wsh backends:
5
+ *
6
+ * - GpuCapability: describes a peer's GPU resources.
7
+ * - GpuProbe: detect local GPU capabilities.
8
+ * - TrainingSpec: defines a distributed training job.
9
+ * - TrainingShard: one peer's portion of training work.
10
+ * - GradientAggregator: combine gradients from shards.
11
+ * - TrainingOrchestrator: manages distributed training lifecycle.
12
+ *
13
+ * No browser-only imports at module level.
14
+ *
15
+ * Run tests:
16
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-gpu.test.mjs
17
+ */
18
+
19
+ import { MESH_TYPE } from '@johnhenry/browsermesh-primitives'
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Wire Constants — imported from canonical registry
23
+ // ---------------------------------------------------------------------------
24
+
25
+ /** Wire type for GPU capability probe. */
26
+ export const GPU_PROBE = MESH_TYPE.GPU_PROBE
27
+
28
+ /** Wire type for shard assignment message. */
29
+ export const GPU_SHARD_ASSIGN = MESH_TYPE.GPU_SHARD_ASSIGN
30
+
31
+ /** Wire type for gradient push from a shard peer. */
32
+ export const GPU_GRADIENT_PUSH = MESH_TYPE.GPU_GRADIENT_PUSH
33
+
34
+ /** Wire type for training control messages (start/cancel/status). */
35
+ export const GPU_TRAIN_CONTROL = MESH_TYPE.GPU_TRAIN_CONTROL
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // GpuCapability
39
+ // ---------------------------------------------------------------------------
40
+
41
+ /**
42
+ * Describes a peer's GPU resources.
43
+ */
44
+ export class GpuCapability {
45
+ /**
46
+ * @param {object} opts
47
+ * @param {string} opts.podId Peer pod ID
48
+ * @param {boolean} [opts.hasWebGPU] Whether WebGPU is available
49
+ * @param {boolean} [opts.hasWsh] Whether wsh connections are available
50
+ * @param {number} [opts.maxBufferSize] Maximum buffer size in bytes
51
+ * @param {object} [opts.adapterInfo] WebGPU adapter info
52
+ * @param {object} [opts.limits] WebGPU limit info
53
+ */
54
+ constructor({ podId, hasWebGPU = false, hasWsh = false, maxBufferSize = 0, adapterInfo, limits }) {
55
+ if (!podId || typeof podId !== 'string') {
56
+ throw new Error('podId is required and must be a non-empty string')
57
+ }
58
+ this.podId = podId
59
+ this.hasWebGPU = hasWebGPU
60
+ this.hasWsh = hasWsh
61
+ this.maxBufferSize = maxBufferSize
62
+ this.adapterInfo = adapterInfo || null
63
+ this.limits = limits || null
64
+ }
65
+
66
+ /**
67
+ * Check whether this peer can participate in training for the given spec.
68
+ * Requires WebGPU or wsh, and sufficient buffer size if spec defines one.
69
+ * @param {TrainingSpec} [spec]
70
+ * @returns {boolean}
71
+ */
72
+ canTrain(spec) {
73
+ if (!this.hasWebGPU && !this.hasWsh) return false
74
+ if (spec && spec.modelConfig && typeof spec.modelConfig.minBufferSize === 'number') {
75
+ if (this.maxBufferSize < spec.modelConfig.minBufferSize) return false
76
+ }
77
+ return true
78
+ }
79
+
80
+ toJSON() {
81
+ return {
82
+ podId: this.podId,
83
+ hasWebGPU: this.hasWebGPU,
84
+ hasWsh: this.hasWsh,
85
+ maxBufferSize: this.maxBufferSize,
86
+ adapterInfo: this.adapterInfo,
87
+ limits: this.limits,
88
+ }
89
+ }
90
+
91
+ static fromJSON(json) {
92
+ return new GpuCapability(json)
93
+ }
94
+ }
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // GpuProbe
98
+ // ---------------------------------------------------------------------------
99
+
100
+ /**
101
+ * Detects local GPU capabilities by probing navigator.gpu and wsh.
102
+ */
103
+ export class GpuProbe {
104
+ /**
105
+ * Probe the local environment for GPU capabilities.
106
+ * @param {string} podId - This peer's pod ID
107
+ * @returns {Promise<GpuCapability>}
108
+ */
109
+ static async probe(podId) {
110
+ let hasWebGPU = false
111
+ let maxBufferSize = 0
112
+ let adapterInfo = null
113
+ let limits = null
114
+
115
+ // Try WebGPU
116
+ try {
117
+ const gpu = typeof navigator !== 'undefined' ? navigator.gpu : undefined
118
+ if (gpu) {
119
+ const adapter = await gpu.requestAdapter()
120
+ if (adapter) {
121
+ hasWebGPU = true
122
+ // Extract adapter info
123
+ if (adapter.info) {
124
+ const info = adapter.info
125
+ adapterInfo = {
126
+ vendor: info.vendor || '',
127
+ architecture: info.architecture || '',
128
+ device: info.device || '',
129
+ description: info.description || '',
130
+ }
131
+ }
132
+ // Extract limits
133
+ if (adapter.limits) {
134
+ const lim = adapter.limits
135
+ limits = {}
136
+ // Copy enumerable limit properties
137
+ for (const key of Object.keys(lim)) {
138
+ limits[key] = lim[key]
139
+ }
140
+ if (typeof lim.maxBufferSize === 'number') {
141
+ maxBufferSize = lim.maxBufferSize
142
+ } else if (typeof lim.maxStorageBufferBindingSize === 'number') {
143
+ maxBufferSize = lim.maxStorageBufferBindingSize
144
+ }
145
+ }
146
+ }
147
+ }
148
+ } catch {
149
+ // WebGPU not available — continue
150
+ }
151
+
152
+ // Check for wsh connections
153
+ let hasWsh = false
154
+ try {
155
+ if (typeof globalThis.getWshConnections === 'function') {
156
+ const connections = globalThis.getWshConnections()
157
+ if (connections && (Array.isArray(connections) ? connections.length > 0 : Object.keys(connections).length > 0)) {
158
+ hasWsh = true
159
+ }
160
+ }
161
+ } catch {
162
+ // wsh not available
163
+ }
164
+
165
+ return new GpuCapability({ podId, hasWebGPU, hasWsh, maxBufferSize, adapterInfo, limits })
166
+ }
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // TrainingSpec
171
+ // ---------------------------------------------------------------------------
172
+
173
+ const VALID_STRATEGIES = ['sync_allreduce', 'async_parameter_server', 'federated_avg']
174
+
175
+ /**
176
+ * Defines a distributed training job.
177
+ */
178
+ export class TrainingSpec {
179
+ /**
180
+ * @param {object} opts
181
+ * @param {string} opts.jobId Unique job ID
182
+ * @param {object} opts.modelConfig Model architecture description
183
+ * @param {string} opts.datasetRef Reference to dataset
184
+ * @param {number} [opts.epochs] Number of epochs (default 1)
185
+ * @param {number} [opts.batchSize] Batch size (default 32)
186
+ * @param {number} [opts.learningRate] Learning rate (default 0.001)
187
+ * @param {string} [opts.strategy] Distribution strategy
188
+ * @param {number} [opts.shardCount] Number of shards (default 1)
189
+ */
190
+ constructor({
191
+ jobId,
192
+ modelConfig,
193
+ datasetRef,
194
+ epochs = 1,
195
+ batchSize = 32,
196
+ learningRate = 0.001,
197
+ strategy = 'sync_allreduce',
198
+ shardCount = 1,
199
+ }) {
200
+ this.jobId = jobId
201
+ this.modelConfig = modelConfig
202
+ this.datasetRef = datasetRef
203
+ this.epochs = epochs
204
+ this.batchSize = batchSize
205
+ this.learningRate = learningRate
206
+ this.strategy = strategy
207
+ this.shardCount = shardCount
208
+ }
209
+
210
+ /**
211
+ * Validate the spec. Throws on invalid configuration.
212
+ */
213
+ validate() {
214
+ if (!this.jobId || typeof this.jobId !== 'string') {
215
+ throw new Error('jobId is required and must be a non-empty string')
216
+ }
217
+ if (!this.modelConfig || typeof this.modelConfig !== 'object') {
218
+ throw new Error('modelConfig is required and must be an object')
219
+ }
220
+ if (!this.datasetRef || typeof this.datasetRef !== 'string') {
221
+ throw new Error('datasetRef is required and must be a non-empty string')
222
+ }
223
+ if (!VALID_STRATEGIES.includes(this.strategy)) {
224
+ throw new Error(`strategy must be one of: ${VALID_STRATEGIES.join(', ')}`)
225
+ }
226
+ }
227
+
228
+ toJSON() {
229
+ return {
230
+ jobId: this.jobId,
231
+ modelConfig: this.modelConfig,
232
+ datasetRef: this.datasetRef,
233
+ epochs: this.epochs,
234
+ batchSize: this.batchSize,
235
+ learningRate: this.learningRate,
236
+ strategy: this.strategy,
237
+ shardCount: this.shardCount,
238
+ }
239
+ }
240
+
241
+ static fromJSON(json) {
242
+ return new TrainingSpec(json)
243
+ }
244
+ }
245
+
246
+ // ---------------------------------------------------------------------------
247
+ // TrainingShard
248
+ // ---------------------------------------------------------------------------
249
+
250
+ /**
251
+ * One peer's portion of training work.
252
+ */
253
+ export class TrainingShard {
254
+ /** @type {{ gradients: number[], metrics: object } | null} */
255
+ #result = null
256
+
257
+ /**
258
+ * @param {object} opts
259
+ * @param {string} opts.shardId Unique shard ID
260
+ * @param {string} opts.jobId Parent job ID
261
+ * @param {string} [opts.podId] Assigned peer pod ID
262
+ * @param {object} [opts.dataRange] Data range {start, end}
263
+ * @param {object} [opts.parameters] Model parameters for this shard
264
+ * @param {string} [opts.status] Shard status
265
+ */
266
+ constructor({
267
+ shardId,
268
+ jobId,
269
+ podId = null,
270
+ dataRange = null,
271
+ parameters = null,
272
+ status = 'pending',
273
+ }) {
274
+ if (!shardId || typeof shardId !== 'string') {
275
+ throw new Error('shardId is required and must be a non-empty string')
276
+ }
277
+ if (!jobId || typeof jobId !== 'string') {
278
+ throw new Error('jobId is required and must be a non-empty string')
279
+ }
280
+ this.shardId = shardId
281
+ this.jobId = jobId
282
+ this.podId = podId
283
+ this.dataRange = dataRange
284
+ this.parameters = parameters
285
+ this.status = status
286
+ }
287
+
288
+ /**
289
+ * Store training result and mark shard as completed.
290
+ * @param {number[]} gradients Gradient vector
291
+ * @param {object} metrics Training metrics
292
+ */
293
+ setResult(gradients, metrics) {
294
+ this.#result = { gradients, metrics }
295
+ this.status = 'completed'
296
+ }
297
+
298
+ /**
299
+ * Get stored result or null if not yet completed.
300
+ * @returns {{ gradients: number[], metrics: object } | null}
301
+ */
302
+ getResult() {
303
+ return this.#result
304
+ }
305
+
306
+ toJSON() {
307
+ return {
308
+ shardId: this.shardId,
309
+ jobId: this.jobId,
310
+ podId: this.podId,
311
+ dataRange: this.dataRange,
312
+ parameters: this.parameters,
313
+ status: this.status,
314
+ result: this.#result,
315
+ }
316
+ }
317
+
318
+ static fromJSON(json) {
319
+ const shard = new TrainingShard({
320
+ shardId: json.shardId,
321
+ jobId: json.jobId,
322
+ podId: json.podId,
323
+ dataRange: json.dataRange,
324
+ parameters: json.parameters,
325
+ status: json.status,
326
+ })
327
+ if (json.result) {
328
+ shard.setResult(json.result.gradients, json.result.metrics)
329
+ // Restore original status if it was set before result (e.g. 'completed')
330
+ shard.status = json.status || 'completed'
331
+ }
332
+ return shard
333
+ }
334
+ }
335
+
336
+ // ---------------------------------------------------------------------------
337
+ // GradientAggregator
338
+ // ---------------------------------------------------------------------------
339
+
340
+ /**
341
+ * Combines gradients from multiple shards using the configured strategy.
342
+ */
343
+ export class GradientAggregator {
344
+ /** @type {Map<string, number[]>} shardId → gradient array */
345
+ #gradients = new Map()
346
+
347
+ /** @type {Map<string, number>} shardId → weight (for federated_avg) */
348
+ #weights = new Map()
349
+
350
+ /**
351
+ * @param {object} opts
352
+ * @param {string} opts.strategy Aggregation strategy
353
+ * @param {number} opts.parameterCount Expected gradient vector length
354
+ */
355
+ constructor({ strategy, parameterCount }) {
356
+ if (!VALID_STRATEGIES.includes(strategy)) {
357
+ throw new Error(`strategy must be one of: ${VALID_STRATEGIES.join(', ')}`)
358
+ }
359
+ this.strategy = strategy
360
+ this.parameterCount = parameterCount
361
+ }
362
+
363
+ /**
364
+ * Submit a gradient vector from a shard.
365
+ * @param {string} shardId Shard ID
366
+ * @param {number[]} gradients Gradient vector
367
+ * @param {number} [weight=1] Weight for federated averaging
368
+ */
369
+ submit(shardId, gradients, weight = 1) {
370
+ this.#gradients.set(shardId, gradients)
371
+ this.#weights.set(shardId, weight)
372
+ }
373
+
374
+ /**
375
+ * Check if enough gradients have been submitted.
376
+ * @param {number} expectedCount Number of shards expected
377
+ * @returns {boolean}
378
+ */
379
+ isReady(expectedCount) {
380
+ return this.#gradients.size >= expectedCount
381
+ }
382
+
383
+ /**
384
+ * Aggregate submitted gradients based on the strategy.
385
+ * @returns {number[]} Aggregated gradient vector
386
+ */
387
+ aggregate() {
388
+ const entries = [...this.#gradients.entries()]
389
+ if (entries.length === 0) {
390
+ return new Array(this.parameterCount).fill(0)
391
+ }
392
+
393
+ const vectorLength = entries[0][1].length
394
+
395
+ if (this.strategy === 'federated_avg') {
396
+ // Weighted average
397
+ let totalWeight = 0
398
+ for (const [shardId] of entries) {
399
+ totalWeight += this.#weights.get(shardId) || 1
400
+ }
401
+ const result = new Array(vectorLength).fill(0)
402
+ for (const [shardId, grads] of entries) {
403
+ const w = (this.#weights.get(shardId) || 1) / totalWeight
404
+ for (let i = 0; i < vectorLength; i++) {
405
+ result[i] += grads[i] * w
406
+ }
407
+ }
408
+ return result
409
+ }
410
+
411
+ // sync_allreduce and async_parameter_server: element-wise average
412
+ const result = new Array(vectorLength).fill(0)
413
+ for (const [, grads] of entries) {
414
+ for (let i = 0; i < vectorLength; i++) {
415
+ result[i] += grads[i]
416
+ }
417
+ }
418
+ for (let i = 0; i < vectorLength; i++) {
419
+ result[i] /= entries.length
420
+ }
421
+ return result
422
+ }
423
+
424
+ /**
425
+ * Clear all stored gradients and weights.
426
+ */
427
+ reset() {
428
+ this.#gradients.clear()
429
+ this.#weights.clear()
430
+ }
431
+ }
432
+
433
+ // ---------------------------------------------------------------------------
434
+ // TrainingOrchestrator
435
+ // ---------------------------------------------------------------------------
436
+
437
+ let _jobSeq = 0
438
+ let _shardSeq = 0
439
+
440
+ /**
441
+ * Manages the distributed training lifecycle across mesh peers.
442
+ */
443
+ export class TrainingOrchestrator {
444
+ /** @type {Function} (targetId, msg) => void */
445
+ #sendFn
446
+
447
+ /** @type {GpuCapability|null} */
448
+ #localCapability
449
+
450
+ /** @type {Map<string, { spec: TrainingSpec, shards: Map<string, TrainingShard>, aggregator: GradientAggregator, status: string }>} */
451
+ #jobs = new Map()
452
+
453
+ /** @type {Map<string, GpuCapability>} podId → capability */
454
+ #peerCapabilities = new Map()
455
+
456
+ /**
457
+ * @param {object} opts
458
+ * @param {Function} opts.sendFn Send function: (targetId, msg) => {}
459
+ * @param {GpuCapability} [opts.localCapability] Local GPU capability
460
+ */
461
+ constructor({ sendFn, localCapability }) {
462
+ if (typeof sendFn !== 'function') {
463
+ throw new Error('sendFn is required and must be a function')
464
+ }
465
+ this.#sendFn = sendFn
466
+ this.#localCapability = localCapability || null
467
+ }
468
+
469
+ /**
470
+ * Register a peer's GPU capability.
471
+ * @param {string} podId
472
+ * @param {GpuCapability} capability
473
+ */
474
+ registerPeer(podId, capability) {
475
+ this.#peerCapabilities.set(podId, capability)
476
+ }
477
+
478
+ /**
479
+ * Remove a peer from the capabilities map.
480
+ * @param {string} podId
481
+ */
482
+ removePeer(podId) {
483
+ this.#peerCapabilities.delete(podId)
484
+ }
485
+
486
+ /**
487
+ * Start a distributed training job.
488
+ * @param {TrainingSpec} spec
489
+ * @returns {string} The job ID
490
+ */
491
+ startJob(spec) {
492
+ spec.validate()
493
+
494
+ // Find capable peers
495
+ const capablePeers = []
496
+ for (const [podId, cap] of this.#peerCapabilities) {
497
+ if (cap.canTrain(spec)) {
498
+ capablePeers.push(podId)
499
+ }
500
+ }
501
+ // Include local peer if capable
502
+ if (this.#localCapability && this.#localCapability.canTrain(spec)) {
503
+ capablePeers.push(this.#localCapability.podId)
504
+ }
505
+
506
+ if (capablePeers.length === 0) {
507
+ throw new Error('No capable peers available for training')
508
+ }
509
+
510
+ const shards = this.#assignShards(spec, capablePeers)
511
+ const shardMap = new Map()
512
+ for (const shard of shards) {
513
+ shardMap.set(shard.shardId, shard)
514
+ }
515
+
516
+ const aggregator = new GradientAggregator({
517
+ strategy: spec.strategy,
518
+ parameterCount: spec.modelConfig.parameterCount || 0,
519
+ })
520
+
521
+ this.#jobs.set(spec.jobId, {
522
+ spec,
523
+ shards: shardMap,
524
+ aggregator,
525
+ status: 'running',
526
+ })
527
+
528
+ // Send shard assignments to peers
529
+ for (const shard of shards) {
530
+ if (shard.podId && shard.podId !== (this.#localCapability?.podId)) {
531
+ this.#sendFn(shard.podId, {
532
+ type: GPU_SHARD_ASSIGN,
533
+ jobId: spec.jobId,
534
+ shard: shard.toJSON(),
535
+ spec: spec.toJSON(),
536
+ })
537
+ }
538
+ }
539
+
540
+ return spec.jobId
541
+ }
542
+
543
+ /**
544
+ * Distribute data ranges across capable peers (round-robin).
545
+ * @param {TrainingSpec} spec
546
+ * @param {string[]} peers
547
+ * @returns {TrainingShard[]}
548
+ */
549
+ #assignShards(spec, peers) {
550
+ const count = spec.shardCount
551
+ const shards = []
552
+ const totalDataSize = spec.modelConfig.dataSize || 1000
553
+
554
+ for (let i = 0; i < count; i++) {
555
+ const rangeSize = Math.ceil(totalDataSize / count)
556
+ const start = i * rangeSize
557
+ const end = Math.min(start + rangeSize, totalDataSize)
558
+ const podId = peers[i % peers.length]
559
+
560
+ shards.push(new TrainingShard({
561
+ shardId: `shard_${spec.jobId}_${++_shardSeq}`,
562
+ jobId: spec.jobId,
563
+ podId,
564
+ dataRange: { start, end },
565
+ parameters: spec.modelConfig,
566
+ status: 'running',
567
+ }))
568
+ }
569
+
570
+ return shards
571
+ }
572
+
573
+ /**
574
+ * Handle a probe response from a peer.
575
+ * @param {string} fromId
576
+ * @param {GpuCapability|object} capability
577
+ */
578
+ handleProbeResponse(fromId, capability) {
579
+ const cap = capability instanceof GpuCapability
580
+ ? capability
581
+ : GpuCapability.fromJSON(capability)
582
+ this.registerPeer(fromId, cap)
583
+ }
584
+
585
+ /**
586
+ * Handle a gradient push from a shard peer.
587
+ * @param {string} fromId
588
+ * @param {string} shardId
589
+ * @param {number[]} gradients
590
+ */
591
+ handleGradientPush(fromId, shardId, gradients) {
592
+ // Find the job that contains this shard
593
+ for (const [jobId, job] of this.#jobs) {
594
+ if (job.shards.has(shardId)) {
595
+ const shard = job.shards.get(shardId)
596
+ shard.setResult(gradients, { fromId })
597
+ job.aggregator.submit(shardId, gradients)
598
+
599
+ if (job.aggregator.isReady(job.shards.size)) {
600
+ job.status = 'aggregated'
601
+ }
602
+ return
603
+ }
604
+ }
605
+ }
606
+
607
+ /**
608
+ * Handle a training control message.
609
+ * @param {string} fromId
610
+ * @param {object} msg
611
+ */
612
+ handleTrainControl(fromId, msg) {
613
+ switch (msg.action) {
614
+ case 'start': {
615
+ if (msg.spec) {
616
+ const spec = TrainingSpec.fromJSON(msg.spec)
617
+ this.startJob(spec)
618
+ }
619
+ break
620
+ }
621
+ case 'cancel': {
622
+ if (msg.jobId) {
623
+ this.cancelJob(msg.jobId)
624
+ }
625
+ break
626
+ }
627
+ case 'status': {
628
+ if (msg.jobId) {
629
+ const status = this.getJobStatus(msg.jobId)
630
+ this.#sendFn(fromId, {
631
+ type: GPU_TRAIN_CONTROL,
632
+ action: 'status_response',
633
+ ...status,
634
+ })
635
+ }
636
+ break
637
+ }
638
+ }
639
+ }
640
+
641
+ /**
642
+ * Get the status of a training job.
643
+ * @param {string} jobId
644
+ * @returns {object}
645
+ */
646
+ getJobStatus(jobId) {
647
+ const job = this.#jobs.get(jobId)
648
+ if (!job) {
649
+ return { jobId, status: 'not_found', shardCount: 0, completedShards: 0, aggregated: false }
650
+ }
651
+
652
+ let completedShards = 0
653
+ for (const [, shard] of job.shards) {
654
+ if (shard.status === 'completed') completedShards++
655
+ }
656
+
657
+ return {
658
+ jobId,
659
+ status: job.status,
660
+ shardCount: job.shards.size,
661
+ completedShards,
662
+ aggregated: job.status === 'aggregated',
663
+ }
664
+ }
665
+
666
+ /**
667
+ * Cancel a training job.
668
+ * @param {string} jobId
669
+ */
670
+ cancelJob(jobId) {
671
+ const job = this.#jobs.get(jobId)
672
+ if (!job) return
673
+
674
+ job.status = 'cancelled'
675
+
676
+ // Send cancel to all shard peers
677
+ for (const [, shard] of job.shards) {
678
+ if (shard.podId && shard.podId !== (this.#localCapability?.podId)) {
679
+ this.#sendFn(shard.podId, {
680
+ type: GPU_TRAIN_CONTROL,
681
+ action: 'cancel',
682
+ jobId,
683
+ })
684
+ }
685
+ }
686
+ }
687
+
688
+ /**
689
+ * Broadcast GPU_PROBE to a list of peers.
690
+ * @param {string[]} peerIds
691
+ */
692
+ probeAllPeers(peerIds) {
693
+ for (const peerId of peerIds) {
694
+ this.#sendFn(peerId, {
695
+ type: GPU_PROBE,
696
+ podId: this.#localCapability?.podId || null,
697
+ })
698
+ }
699
+ }
700
+
701
+ /**
702
+ * Main message handler — dispatches based on msg.type.
703
+ * @param {string} fromId
704
+ * @param {object} msg
705
+ */
706
+ handleMessage(fromId, msg) {
707
+ switch (msg.type) {
708
+ case GPU_PROBE:
709
+ // Respond with local capability
710
+ if (this.#localCapability) {
711
+ this.#sendFn(fromId, {
712
+ type: GPU_PROBE,
713
+ capability: this.#localCapability.toJSON(),
714
+ response: true,
715
+ })
716
+ }
717
+ break
718
+
719
+ case GPU_SHARD_ASSIGN:
720
+ // Received a shard assignment — acknowledge
721
+ break
722
+
723
+ case GPU_GRADIENT_PUSH:
724
+ this.handleGradientPush(fromId, msg.shardId, msg.gradients)
725
+ break
726
+
727
+ case GPU_TRAIN_CONTROL:
728
+ this.handleTrainControl(fromId, msg)
729
+ break
730
+ }
731
+ }
732
+ }