@johnhenry/browsermesh-apps 0.1.1 → 0.3.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/README.md +443 -1
- package/package.json +18 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +799 -0
- package/src/compat.mjs +98 -0
- package/src/gpu-kernel.mjs +242 -0
- package/src/gpu.mjs +101 -7
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +32 -2
- package/src/kernel-mesh.mjs +56 -0
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1481 -0
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-relay-backend.mjs +289 -0
- package/src/mesh-relay-host.mjs +362 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-sync.mjs +253 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +127 -19
- package/src/peer-registry.mjs +242 -18
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/signaling.mjs +231 -0
- package/src/webrtc-negotiator.mjs +209 -0
- package/src/peer-session.mjs +0 -937
package/src/compat.mjs
CHANGED
|
@@ -9,6 +9,13 @@
|
|
|
9
9
|
* "Cannot set property name of #<Tool> which has only a getter" for
|
|
10
10
|
* every real subclass, since none of them define a setter (same bug
|
|
11
11
|
* found and fixed in browsermesh-core's compat.mjs).
|
|
12
|
+
*
|
|
13
|
+
* Also exports BrowserToolRegistry, BrowserTool's counterpart: a
|
|
14
|
+
* name-keyed collection of constructed tool instances used to dispatch
|
|
15
|
+
* LLM-requested tool calls (see `registerMeshTools` in tools.mjs, which
|
|
16
|
+
* calls `registry.register(...)`). Mirrors browsermesh-core's
|
|
17
|
+
* compat.mjs's BrowserToolRegistry exactly, kept as a separate copy for
|
|
18
|
+
* the same standalone-use reason BrowserTool itself is duplicated here.
|
|
12
19
|
*/
|
|
13
20
|
export class BrowserTool {
|
|
14
21
|
/** @returns {object} ToolSpec-compatible object */
|
|
@@ -28,3 +35,94 @@ export class BrowserTool {
|
|
|
28
35
|
|
|
29
36
|
async execute(_params) { throw new Error('Not implemented'); }
|
|
30
37
|
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Returns true if `tool` looks like a BrowserTool: it exposes a working
|
|
41
|
+
* `.spec` getter (with a non-empty string `.name`) and an `.execute`
|
|
42
|
+
* method. Duck-typed rather than `instanceof BrowserTool` on purpose —
|
|
43
|
+
* see the module header: this package vendors its own copy of the
|
|
44
|
+
* `BrowserTool` shim (same as browsermesh-core's compat.mjs) for
|
|
45
|
+
* standalone use, so a tool built against one package's `BrowserTool`
|
|
46
|
+
* class is not `instanceof` another package's class even though it has
|
|
47
|
+
* the identical shape. Duck-typing lets `BrowserToolRegistry` accept any
|
|
48
|
+
* of them.
|
|
49
|
+
* @param {unknown} tool
|
|
50
|
+
* @returns {boolean}
|
|
51
|
+
*/
|
|
52
|
+
function looksLikeBrowserTool(tool) {
|
|
53
|
+
if (!tool || (typeof tool !== 'object' && typeof tool !== 'function')) return false;
|
|
54
|
+
if (typeof tool.execute !== 'function') return false;
|
|
55
|
+
let spec;
|
|
56
|
+
try {
|
|
57
|
+
spec = tool.spec;
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
return !!spec && typeof spec.name === 'string' && spec.name.length > 0;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* BrowserToolRegistry -- holds constructed BrowserTool instances, keyed by
|
|
66
|
+
* `.name`, and exposes the `.spec` list an `llmFn` (see the agent-runtime
|
|
67
|
+
* plan) needs for tool-calling.
|
|
68
|
+
*
|
|
69
|
+
* `register()` duck-types its argument (see `looksLikeBrowserTool` above)
|
|
70
|
+
* rather than requiring `instanceof BrowserTool`, for the same
|
|
71
|
+
* cross-package "standalone use" reason `BrowserTool` itself avoids hard
|
|
72
|
+
* class-identity assumptions.
|
|
73
|
+
*
|
|
74
|
+
* Registering a second tool under a name that's already registered
|
|
75
|
+
* throws (it does not silently overwrite) — a name collision usually
|
|
76
|
+
* means two unrelated tools accidentally share a name, and silently
|
|
77
|
+
* dropping one would be a confusing, hard-to-debug failure mode. Call
|
|
78
|
+
* `unregister(name)` first if replacing a tool is genuinely intended.
|
|
79
|
+
*/
|
|
80
|
+
export class BrowserToolRegistry {
|
|
81
|
+
#tools = new Map();
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @param {BrowserTool | { spec: object, execute: Function }} tool
|
|
85
|
+
* @returns {BrowserTool} the same tool, for chaining
|
|
86
|
+
*/
|
|
87
|
+
register(tool) {
|
|
88
|
+
if (!looksLikeBrowserTool(tool)) {
|
|
89
|
+
throw new TypeError(
|
|
90
|
+
'BrowserToolRegistry.register(tool): tool must implement the BrowserTool shape ' +
|
|
91
|
+
'(a `.spec` getter and an `.execute()` method) — got ' +
|
|
92
|
+
(tool && tool.constructor ? tool.constructor.name : String(tool))
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
const { name } = tool;
|
|
96
|
+
if (this.#tools.has(name)) {
|
|
97
|
+
throw new Error(`BrowserToolRegistry.register(tool): a tool named "${name}" is already registered; call unregister("${name}") first to replace it`);
|
|
98
|
+
}
|
|
99
|
+
this.#tools.set(name, tool);
|
|
100
|
+
return tool;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @param {string} name
|
|
105
|
+
* @returns {BrowserTool | undefined}
|
|
106
|
+
*/
|
|
107
|
+
get(name) {
|
|
108
|
+
return this.#tools.get(name);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** @returns {BrowserTool[]} all registered tool instances */
|
|
112
|
+
list() {
|
|
113
|
+
return [...this.#tools.values()];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** @returns {object[]} the `.spec` of every registered tool */
|
|
117
|
+
listSpecs() {
|
|
118
|
+
return this.list().map((tool) => tool.spec);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* @param {string} name
|
|
123
|
+
* @returns {boolean} true if a tool with that name was registered and removed
|
|
124
|
+
*/
|
|
125
|
+
unregister(name) {
|
|
126
|
+
return this.#tools.delete(name);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* gpu-kernel.mjs -- WGSL compute shader for gradient aggregation.
|
|
3
|
+
*
|
|
4
|
+
* One thread per output parameter index; each thread loops serially over
|
|
5
|
+
* the shard axis inside itself (parameter count is expected to vastly
|
|
6
|
+
* outnumber shard count in real training jobs, so a per-parameter thread
|
|
7
|
+
* with a short serial shard loop needs no cross-thread synchronization and
|
|
8
|
+
* no reduction pass). A single shader/pipeline covers both of
|
|
9
|
+
* `GradientAggregator.aggregate()`'s branches via a uniform `useWeights`
|
|
10
|
+
* flag:
|
|
11
|
+
*
|
|
12
|
+
* - federated_avg: weighted elementwise mean (per-shard weights,
|
|
13
|
+
* normalized by their sum inside the shader — mirrors the JS branch in
|
|
14
|
+
* gpu.mjs exactly).
|
|
15
|
+
* - sync_allreduce / async_parameter_server: unweighted elementwise mean.
|
|
16
|
+
*
|
|
17
|
+
* The compiled GPUShaderModule/GPUComputePipeline pair is cached per
|
|
18
|
+
* GPUDevice in a WeakMap, so repeated calls against the same device never
|
|
19
|
+
* recompile, and distinct devices (e.g. one per test) never share or leak
|
|
20
|
+
* cached state -- when a device is garbage collected its cache entry goes
|
|
21
|
+
* with it.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const WORKGROUP_SIZE = 64
|
|
25
|
+
|
|
26
|
+
const SHADER_SOURCE = `
|
|
27
|
+
struct Params {
|
|
28
|
+
vectorLength: u32,
|
|
29
|
+
numShards: u32,
|
|
30
|
+
useWeights: u32,
|
|
31
|
+
totalWeight: f32,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
@group(0) @binding(0) var<uniform> params: Params;
|
|
35
|
+
@group(0) @binding(1) var<storage, read> gradients: array<f32>;
|
|
36
|
+
@group(0) @binding(2) var<storage, read> weights: array<f32>;
|
|
37
|
+
@group(0) @binding(3) var<storage, read_write> output: array<f32>;
|
|
38
|
+
|
|
39
|
+
@compute @workgroup_size(${WORKGROUP_SIZE})
|
|
40
|
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
41
|
+
let i = gid.x;
|
|
42
|
+
if (i >= params.vectorLength) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
var sum: f32 = 0.0;
|
|
47
|
+
|
|
48
|
+
if (params.useWeights == 1u) {
|
|
49
|
+
// federated_avg: weighted elementwise mean, weights normalized by their
|
|
50
|
+
// sum (mirrors GradientAggregator.aggregate()'s JS branch).
|
|
51
|
+
for (var s: u32 = 0u; s < params.numShards; s = s + 1u) {
|
|
52
|
+
let w = weights[s] / params.totalWeight;
|
|
53
|
+
sum = sum + gradients[s * params.vectorLength + i] * w;
|
|
54
|
+
}
|
|
55
|
+
} else {
|
|
56
|
+
// sync_allreduce / async_parameter_server: unweighted elementwise mean.
|
|
57
|
+
for (var s: u32 = 0u; s < params.numShards; s = s + 1u) {
|
|
58
|
+
sum = sum + gradients[s * params.vectorLength + i];
|
|
59
|
+
}
|
|
60
|
+
if (params.numShards > 0u) {
|
|
61
|
+
sum = sum / f32(params.numShards);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
output[i] = sum;
|
|
66
|
+
}
|
|
67
|
+
`
|
|
68
|
+
|
|
69
|
+
/** @type {WeakMap<object, { module: object, pipeline: object }>} */
|
|
70
|
+
const pipelineCache = new WeakMap()
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Get (or lazily create) the compiled shader module + compute pipeline for
|
|
74
|
+
* `device`, caching the result so repeated dispatches on the same device
|
|
75
|
+
* skip recompilation.
|
|
76
|
+
* @param {object} device GPUDevice
|
|
77
|
+
* @returns {{ module: object, pipeline: object }}
|
|
78
|
+
*/
|
|
79
|
+
function getOrCreatePipeline(device) {
|
|
80
|
+
const cached = pipelineCache.get(device)
|
|
81
|
+
if (cached) return cached
|
|
82
|
+
|
|
83
|
+
const module = device.createShaderModule({
|
|
84
|
+
code: SHADER_SOURCE,
|
|
85
|
+
label: 'browsermesh-gradient-aggregate-shader',
|
|
86
|
+
})
|
|
87
|
+
const pipeline = device.createComputePipeline({
|
|
88
|
+
layout: 'auto',
|
|
89
|
+
compute: { module, entryPoint: 'main' },
|
|
90
|
+
label: 'browsermesh-gradient-aggregate-pipeline',
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
const entry = { module, pipeline }
|
|
94
|
+
pipelineCache.set(device, entry)
|
|
95
|
+
return entry
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Run the gradient-aggregation compute kernel on `device`.
|
|
100
|
+
*
|
|
101
|
+
* @param {object} device GPUDevice
|
|
102
|
+
* @param {object} opts
|
|
103
|
+
* @param {number[]} opts.gradients Flat, shard-major gradient values:
|
|
104
|
+
* `gradients[shard * vectorLength + i]` is shard `shard`'s value for
|
|
105
|
+
* parameter `i`. Length must equal `weights.length * vectorLength`.
|
|
106
|
+
* @param {number[]} opts.weights One weight per shard (length = numShards).
|
|
107
|
+
* Only consulted when `useWeights` is true; pass `[1, 1, ...]` (or
|
|
108
|
+
* anything of the right length) when it is false.
|
|
109
|
+
* @param {boolean} opts.useWeights `true` for federated_avg's weighted
|
|
110
|
+
* mean, `false` for sync_allreduce/async_parameter_server's unweighted
|
|
111
|
+
* mean.
|
|
112
|
+
* @returns {Promise<number[]>} The aggregated vector (plain Array, length
|
|
113
|
+
* = vectorLength) -- matches `GradientAggregator.aggregate()`'s return
|
|
114
|
+
* shape so callers never need to special-case typed vs. plain arrays.
|
|
115
|
+
*/
|
|
116
|
+
export async function runAggregateKernel(device, { gradients, weights, useWeights }) {
|
|
117
|
+
// Temporary diagnostic instrumentation (browsermesh#63): a real CI run
|
|
118
|
+
// against a headless software-Vulkan device failed with no JS-catchable
|
|
119
|
+
// error at all (0 suites reported, no stack) -- consistent with the
|
|
120
|
+
// native Dawn/Vulkan process dying rather than a normal JS throw. These
|
|
121
|
+
// markers are flushed to stderr immediately before/after each native
|
|
122
|
+
// call, gated behind GPU_KERNEL_DEBUG so a silent process death still
|
|
123
|
+
// leaves a trail of exactly how far it got, in CI logs, without adding
|
|
124
|
+
// noise to normal runs (this function is never called from the always-on
|
|
125
|
+
// fallback-branch tests, only from the gated real-hardware tier).
|
|
126
|
+
const debug = process.env.GPU_KERNEL_DEBUG
|
|
127
|
+
? (stage) => { console.error(`[gpu-kernel] ${stage}`) }
|
|
128
|
+
: () => {}
|
|
129
|
+
|
|
130
|
+
const numShards = weights.length
|
|
131
|
+
const vectorLength = numShards > 0 ? gradients.length / numShards : 0
|
|
132
|
+
|
|
133
|
+
if (!Number.isInteger(vectorLength)) {
|
|
134
|
+
throw new Error(
|
|
135
|
+
`runAggregateKernel: gradients.length (${gradients.length}) is not evenly ` +
|
|
136
|
+
`divisible by weights.length (${numShards})`
|
|
137
|
+
)
|
|
138
|
+
}
|
|
139
|
+
debug(`start: numShards=${numShards} vectorLength=${vectorLength} useWeights=${useWeights}`)
|
|
140
|
+
|
|
141
|
+
debug('getOrCreatePipeline: start')
|
|
142
|
+
const { pipeline } = getOrCreatePipeline(device)
|
|
143
|
+
debug('getOrCreatePipeline: done')
|
|
144
|
+
|
|
145
|
+
const totalWeight = useWeights ? weights.reduce((a, b) => a + b, 0) : numShards
|
|
146
|
+
|
|
147
|
+
const paramsData = new ArrayBuffer(16)
|
|
148
|
+
const paramsView = new DataView(paramsData)
|
|
149
|
+
paramsView.setUint32(0, vectorLength, true)
|
|
150
|
+
paramsView.setUint32(4, numShards, true)
|
|
151
|
+
paramsView.setUint32(8, useWeights ? 1 : 0, true)
|
|
152
|
+
paramsView.setFloat32(12, totalWeight, true)
|
|
153
|
+
|
|
154
|
+
debug('createBuffer(params): start')
|
|
155
|
+
const paramsBuffer = device.createBuffer({
|
|
156
|
+
size: paramsData.byteLength,
|
|
157
|
+
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
|
|
158
|
+
label: 'browsermesh-gradient-aggregate-params',
|
|
159
|
+
})
|
|
160
|
+
device.queue.writeBuffer(paramsBuffer, 0, paramsData)
|
|
161
|
+
debug('createBuffer(params): done')
|
|
162
|
+
|
|
163
|
+
const gradientsArray = Float32Array.from(gradients)
|
|
164
|
+
debug('createBuffer(gradients): start')
|
|
165
|
+
const gradientsBuffer = device.createBuffer({
|
|
166
|
+
size: Math.max(gradientsArray.byteLength, 4),
|
|
167
|
+
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
|
|
168
|
+
label: 'browsermesh-gradient-aggregate-gradients',
|
|
169
|
+
})
|
|
170
|
+
device.queue.writeBuffer(gradientsBuffer, 0, gradientsArray)
|
|
171
|
+
debug('createBuffer(gradients): done')
|
|
172
|
+
|
|
173
|
+
const weightsArray = Float32Array.from(weights.length > 0 ? weights : [0])
|
|
174
|
+
debug('createBuffer(weights): start')
|
|
175
|
+
const weightsBuffer = device.createBuffer({
|
|
176
|
+
size: Math.max(weightsArray.byteLength, 4),
|
|
177
|
+
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
|
|
178
|
+
label: 'browsermesh-gradient-aggregate-weights',
|
|
179
|
+
})
|
|
180
|
+
device.queue.writeBuffer(weightsBuffer, 0, weightsArray)
|
|
181
|
+
debug('createBuffer(weights): done')
|
|
182
|
+
|
|
183
|
+
const outputByteLength = Math.max(vectorLength * 4, 4)
|
|
184
|
+
debug('createBuffer(output): start')
|
|
185
|
+
const outputBuffer = device.createBuffer({
|
|
186
|
+
size: outputByteLength,
|
|
187
|
+
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
|
|
188
|
+
label: 'browsermesh-gradient-aggregate-output',
|
|
189
|
+
})
|
|
190
|
+
debug('createBuffer(output): done')
|
|
191
|
+
|
|
192
|
+
debug('createBuffer(readback): start')
|
|
193
|
+
const readbackBuffer = device.createBuffer({
|
|
194
|
+
size: outputByteLength,
|
|
195
|
+
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
|
|
196
|
+
label: 'browsermesh-gradient-aggregate-readback',
|
|
197
|
+
})
|
|
198
|
+
debug('createBuffer(readback): done')
|
|
199
|
+
|
|
200
|
+
debug('createBindGroup: start')
|
|
201
|
+
const bindGroup = device.createBindGroup({
|
|
202
|
+
layout: pipeline.getBindGroupLayout(0),
|
|
203
|
+
entries: [
|
|
204
|
+
{ binding: 0, resource: { buffer: paramsBuffer } },
|
|
205
|
+
{ binding: 1, resource: { buffer: gradientsBuffer } },
|
|
206
|
+
{ binding: 2, resource: { buffer: weightsBuffer } },
|
|
207
|
+
{ binding: 3, resource: { buffer: outputBuffer } },
|
|
208
|
+
],
|
|
209
|
+
label: 'browsermesh-gradient-aggregate-bindgroup',
|
|
210
|
+
})
|
|
211
|
+
debug('createBindGroup: done')
|
|
212
|
+
|
|
213
|
+
debug('encode+dispatch: start')
|
|
214
|
+
const encoder = device.createCommandEncoder({ label: 'browsermesh-gradient-aggregate-encoder' })
|
|
215
|
+
const pass = encoder.beginComputePass({ label: 'browsermesh-gradient-aggregate-pass' })
|
|
216
|
+
pass.setPipeline(pipeline)
|
|
217
|
+
pass.setBindGroup(0, bindGroup)
|
|
218
|
+
const workgroupCount = Math.max(1, Math.ceil(vectorLength / WORKGROUP_SIZE))
|
|
219
|
+
pass.dispatchWorkgroups(workgroupCount)
|
|
220
|
+
pass.end()
|
|
221
|
+
encoder.copyBufferToBuffer(outputBuffer, 0, readbackBuffer, 0, outputByteLength)
|
|
222
|
+
debug('encode+dispatch: done, calling queue.submit')
|
|
223
|
+
device.queue.submit([encoder.finish()])
|
|
224
|
+
debug('queue.submit: done')
|
|
225
|
+
|
|
226
|
+
debug('mapAsync: start')
|
|
227
|
+
await readbackBuffer.mapAsync(GPUMapMode.READ)
|
|
228
|
+
debug('mapAsync: done')
|
|
229
|
+
const mapped = readbackBuffer.getMappedRange()
|
|
230
|
+
const resultFloats = new Float32Array(mapped.slice(0, vectorLength * 4))
|
|
231
|
+
readbackBuffer.unmap()
|
|
232
|
+
debug('readback: done, destroying buffers')
|
|
233
|
+
|
|
234
|
+
paramsBuffer.destroy?.()
|
|
235
|
+
gradientsBuffer.destroy?.()
|
|
236
|
+
weightsBuffer.destroy?.()
|
|
237
|
+
outputBuffer.destroy?.()
|
|
238
|
+
readbackBuffer.destroy?.()
|
|
239
|
+
|
|
240
|
+
debug('runAggregateKernel: returning result')
|
|
241
|
+
return Array.from(resultFloats)
|
|
242
|
+
}
|
package/src/gpu.mjs
CHANGED
|
@@ -12,11 +12,34 @@
|
|
|
12
12
|
*
|
|
13
13
|
* No browser-only imports at module level.
|
|
14
14
|
*
|
|
15
|
+
* ## GPU compute: real, optional, and safe to omit
|
|
16
|
+
*
|
|
17
|
+
* `GradientAggregator.aggregateGPU(device)` (see below) dispatches a real
|
|
18
|
+
* WGSL compute shader (`./gpu-kernel.mjs`) when given a usable `GPUDevice`.
|
|
19
|
+
* It is entirely optional: pass no device (or a device whose storage-buffer
|
|
20
|
+
* limits are too small for the flattened gradient buffer) and it falls back
|
|
21
|
+
* to the existing synchronous `aggregate()` CPU path, wrapped in a resolved
|
|
22
|
+
* Promise. Nothing in this package requires WebGPU to be present -- the
|
|
23
|
+
* fallback is a first-class, always-tested code path, not a stub.
|
|
24
|
+
*
|
|
25
|
+
* Always-on coverage of the fallback branch lives in `test/gpu.test.mjs`
|
|
26
|
+
* and needs no GPU. Coverage of the real shader against actual WebGPU
|
|
27
|
+
* hardware/drivers is gated behind an optional devDependency and lives in
|
|
28
|
+
* `test/gpu-real-webgpu/kernel.test.mjs` (run via `npm run test:real-gpu`).
|
|
29
|
+
* It deliberately does NOT run in CI (see `.github/workflows/ci.yml`):
|
|
30
|
+
* verified correct on real hardware and on a local headless-Linux
|
|
31
|
+
* approximation, but a real CI run against this repo's actual
|
|
32
|
+
* GitHub-hosted runner hit a native crash inside the `webgpu` binding
|
|
33
|
+
* itself (a pthread mutex assertion failure during `mapAsync()`) that no
|
|
34
|
+
* JS-level handling can turn into a clean skip or failure -- see that test
|
|
35
|
+
* file and this package's README for the full finding.
|
|
36
|
+
*
|
|
15
37
|
* Run tests:
|
|
16
38
|
* node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-gpu.test.mjs
|
|
17
39
|
*/
|
|
18
40
|
|
|
19
41
|
import { MESH_TYPE } from '@johnhenry/browsermesh-primitives'
|
|
42
|
+
import { runAggregateKernel } from './gpu-kernel.mjs'
|
|
20
43
|
|
|
21
44
|
// ---------------------------------------------------------------------------
|
|
22
45
|
// Wire Constants — imported from canonical registry
|
|
@@ -421,6 +444,46 @@ export class GradientAggregator {
|
|
|
421
444
|
return result
|
|
422
445
|
}
|
|
423
446
|
|
|
447
|
+
/**
|
|
448
|
+
* Aggregate submitted gradients on the GPU when possible, falling back to
|
|
449
|
+
* the synchronous `aggregate()` CPU path otherwise. The fallback covers:
|
|
450
|
+
* - no `device` supplied (falsy),
|
|
451
|
+
* - zero submitted gradients,
|
|
452
|
+
* - a flattened gradient buffer (`shards * vectorLength * 4` bytes)
|
|
453
|
+
* that would exceed `device.limits.maxStorageBufferBindingSize`.
|
|
454
|
+
* In every fallback case this calls the real, unmodified `aggregate()`
|
|
455
|
+
* and wraps its result in a resolved Promise -- the fallback is a real
|
|
456
|
+
* code path (tested in test/gpu.test.mjs), not a placeholder.
|
|
457
|
+
* @param {object} [device] GPUDevice
|
|
458
|
+
* @returns {Promise<number[]>} Aggregated gradient vector
|
|
459
|
+
*/
|
|
460
|
+
async aggregateGPU(device) {
|
|
461
|
+
const entries = [...this.#gradients.entries()]
|
|
462
|
+
if (!device || entries.length === 0) {
|
|
463
|
+
return this.aggregate()
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const vectorLength = entries[0][1].length
|
|
467
|
+
const numShards = entries.length
|
|
468
|
+
const bufferBytes = numShards * vectorLength * 4
|
|
469
|
+
const maxBufferBytes = device.limits?.maxStorageBufferBindingSize
|
|
470
|
+
if (typeof maxBufferBytes === 'number' && bufferBytes > maxBufferBytes) {
|
|
471
|
+
return this.aggregate()
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const useWeights = this.strategy === 'federated_avg'
|
|
475
|
+
const gradients = new Array(numShards * vectorLength)
|
|
476
|
+
const weights = new Array(numShards)
|
|
477
|
+
entries.forEach(([shardId, grads], shardIndex) => {
|
|
478
|
+
weights[shardIndex] = this.#weights.get(shardId) || 1
|
|
479
|
+
for (let i = 0; i < vectorLength; i++) {
|
|
480
|
+
gradients[shardIndex * vectorLength + i] = grads[i]
|
|
481
|
+
}
|
|
482
|
+
})
|
|
483
|
+
|
|
484
|
+
return runAggregateKernel(device, { gradients, weights, useWeights })
|
|
485
|
+
}
|
|
486
|
+
|
|
424
487
|
/**
|
|
425
488
|
* Clear all stored gradients and weights.
|
|
426
489
|
*/
|
|
@@ -453,17 +516,25 @@ export class TrainingOrchestrator {
|
|
|
453
516
|
/** @type {Map<string, GpuCapability>} podId → capability */
|
|
454
517
|
#peerCapabilities = new Map()
|
|
455
518
|
|
|
519
|
+
/** @type {object|null} GPUDevice, used by handleGradientPush's aggregateGPU() call */
|
|
520
|
+
#gpuDevice
|
|
521
|
+
|
|
456
522
|
/**
|
|
457
523
|
* @param {object} opts
|
|
458
524
|
* @param {Function} opts.sendFn Send function: (targetId, msg) => {}
|
|
459
525
|
* @param {GpuCapability} [opts.localCapability] Local GPU capability
|
|
526
|
+
* @param {object} [opts.gpuDevice] Optional GPUDevice. When supplied,
|
|
527
|
+
* `handleGradientPush()` aggregates on the GPU via
|
|
528
|
+
* `GradientAggregator.aggregateGPU()`; when omitted, aggregation runs on
|
|
529
|
+
* the CPU (aggregateGPU()'s own no-device fallback).
|
|
460
530
|
*/
|
|
461
|
-
constructor({ sendFn, localCapability }) {
|
|
531
|
+
constructor({ sendFn, localCapability, gpuDevice }) {
|
|
462
532
|
if (typeof sendFn !== 'function') {
|
|
463
533
|
throw new Error('sendFn is required and must be a function')
|
|
464
534
|
}
|
|
465
535
|
this.#sendFn = sendFn
|
|
466
536
|
this.#localCapability = localCapability || null
|
|
537
|
+
this.#gpuDevice = gpuDevice || null
|
|
467
538
|
}
|
|
468
539
|
|
|
469
540
|
/**
|
|
@@ -523,6 +594,7 @@ export class TrainingOrchestrator {
|
|
|
523
594
|
shards: shardMap,
|
|
524
595
|
aggregator,
|
|
525
596
|
status: 'running',
|
|
597
|
+
result: null,
|
|
526
598
|
})
|
|
527
599
|
|
|
528
600
|
// Send shard assignments to peers
|
|
@@ -583,12 +655,17 @@ export class TrainingOrchestrator {
|
|
|
583
655
|
}
|
|
584
656
|
|
|
585
657
|
/**
|
|
586
|
-
* Handle a gradient push from a shard peer.
|
|
658
|
+
* Handle a gradient push from a shard peer. Once the job's aggregator has
|
|
659
|
+
* received a gradient from every shard, actually runs aggregation
|
|
660
|
+
* (GPU-accelerated when a `gpuDevice` was supplied to the constructor,
|
|
661
|
+
* otherwise the CPU path via `aggregateGPU()`'s own fallback) and stores
|
|
662
|
+
* the result on the job record, retrievable via `getJobResult()`.
|
|
587
663
|
* @param {string} fromId
|
|
588
664
|
* @param {string} shardId
|
|
589
665
|
* @param {number[]} gradients
|
|
666
|
+
* @returns {Promise<void>}
|
|
590
667
|
*/
|
|
591
|
-
handleGradientPush(fromId, shardId, gradients) {
|
|
668
|
+
async handleGradientPush(fromId, shardId, gradients) {
|
|
592
669
|
// Find the job that contains this shard
|
|
593
670
|
for (const [jobId, job] of this.#jobs) {
|
|
594
671
|
if (job.shards.has(shardId)) {
|
|
@@ -597,6 +674,7 @@ export class TrainingOrchestrator {
|
|
|
597
674
|
job.aggregator.submit(shardId, gradients)
|
|
598
675
|
|
|
599
676
|
if (job.aggregator.isReady(job.shards.size)) {
|
|
677
|
+
job.result = await job.aggregator.aggregateGPU(this.#gpuDevice)
|
|
600
678
|
job.status = 'aggregated'
|
|
601
679
|
}
|
|
602
680
|
return
|
|
@@ -646,7 +724,7 @@ export class TrainingOrchestrator {
|
|
|
646
724
|
getJobStatus(jobId) {
|
|
647
725
|
const job = this.#jobs.get(jobId)
|
|
648
726
|
if (!job) {
|
|
649
|
-
return { jobId, status: 'not_found', shardCount: 0, completedShards: 0, aggregated: false }
|
|
727
|
+
return { jobId, status: 'not_found', shardCount: 0, completedShards: 0, aggregated: false, result: null }
|
|
650
728
|
}
|
|
651
729
|
|
|
652
730
|
let completedShards = 0
|
|
@@ -660,9 +738,21 @@ export class TrainingOrchestrator {
|
|
|
660
738
|
shardCount: job.shards.size,
|
|
661
739
|
completedShards,
|
|
662
740
|
aggregated: job.status === 'aggregated',
|
|
741
|
+
result: job.result ?? null,
|
|
663
742
|
}
|
|
664
743
|
}
|
|
665
744
|
|
|
745
|
+
/**
|
|
746
|
+
* Get the aggregated result for a job, or `null` if the job doesn't
|
|
747
|
+
* exist yet or hasn't finished aggregating.
|
|
748
|
+
* @param {string} jobId
|
|
749
|
+
* @returns {number[]|null}
|
|
750
|
+
*/
|
|
751
|
+
getJobResult(jobId) {
|
|
752
|
+
const job = this.#jobs.get(jobId)
|
|
753
|
+
return job ? (job.result ?? null) : null
|
|
754
|
+
}
|
|
755
|
+
|
|
666
756
|
/**
|
|
667
757
|
* Cancel a training job.
|
|
668
758
|
* @param {string} jobId
|
|
@@ -699,11 +789,15 @@ export class TrainingOrchestrator {
|
|
|
699
789
|
}
|
|
700
790
|
|
|
701
791
|
/**
|
|
702
|
-
* Main message handler — dispatches based on msg.type.
|
|
792
|
+
* Main message handler — dispatches based on msg.type. Async because the
|
|
793
|
+
* GPU_GRADIENT_PUSH branch awaits `handleGradientPush()` (which itself
|
|
794
|
+
* awaits GPU/CPU aggregation once a job's shards are all in) — callers
|
|
795
|
+
* must `await` this rather than fire-and-forget it.
|
|
703
796
|
* @param {string} fromId
|
|
704
797
|
* @param {object} msg
|
|
798
|
+
* @returns {Promise<void>}
|
|
705
799
|
*/
|
|
706
|
-
handleMessage(fromId, msg) {
|
|
800
|
+
async handleMessage(fromId, msg) {
|
|
707
801
|
switch (msg.type) {
|
|
708
802
|
case GPU_PROBE:
|
|
709
803
|
// Respond with local capability
|
|
@@ -721,7 +815,7 @@ export class TrainingOrchestrator {
|
|
|
721
815
|
break
|
|
722
816
|
|
|
723
817
|
case GPU_GRADIENT_PUSH:
|
|
724
|
-
this.handleGradientPush(fromId, msg.shardId, msg.gradients)
|
|
818
|
+
await this.handleGradientPush(fromId, msg.shardId, msg.gradients)
|
|
725
819
|
break
|
|
726
820
|
|
|
727
821
|
case GPU_TRAIN_CONTROL:
|