@johnhenry/browsermesh-apps 0.1.0 → 0.2.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 +211 -0
- package/package.json +33 -7
- package/src/gpu-kernel.mjs +242 -0
- package/src/gpu.mjs +101 -7
- package/src/index.mjs +7 -0
- package/src/kernel-mesh.mjs +56 -0
- package/src/mesh-bootstrap.mjs +362 -0
- package/src/mesh-relay-backend.mjs +289 -0
- package/src/mesh-relay-host.mjs +362 -0
- package/src/mesh-sync.mjs +253 -0
- package/src/peer-node.mjs +95 -18
- package/src/peer-registry.mjs +242 -18
- package/src/signaling.mjs +231 -0
- package/src/webrtc-negotiator.mjs +209 -0
package/README.md
CHANGED
|
@@ -45,6 +45,74 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
45
45
|
| peer-torrent | `TorrentManager` |
|
|
46
46
|
| peer-verification | `VerificationQuorum`, `Attestation` |
|
|
47
47
|
| marketplace-ui | `SkillMarketplace` |
|
|
48
|
+
| mesh-relay-host | `MeshRelayHost` |
|
|
49
|
+
| mesh-relay-backend | `MeshRelayBackend` |
|
|
50
|
+
|
|
51
|
+
## GPU compute
|
|
52
|
+
|
|
53
|
+
`GradientAggregator.aggregateGPU(device)` runs a real WGSL compute shader
|
|
54
|
+
(`src/gpu-kernel.mjs`) to aggregate submitted gradients when given a usable
|
|
55
|
+
`GPUDevice` -- one thread per output parameter index, covering both
|
|
56
|
+
`aggregate()`'s aggregation strategies (weighted `federated_avg`, unweighted
|
|
57
|
+
`sync_allreduce`/`async_parameter_server`) via a uniform flag. The compiled
|
|
58
|
+
shader module/pipeline is cached per-device.
|
|
59
|
+
|
|
60
|
+
It is entirely optional and degrades safely: called with no device, or a
|
|
61
|
+
device whose `limits.maxStorageBufferBindingSize` is too small for the
|
|
62
|
+
flattened gradient buffer, it falls back to the existing synchronous
|
|
63
|
+
`aggregate()` CPU implementation (wrapped in a resolved Promise). That
|
|
64
|
+
fallback is exercised unconditionally in `test/gpu.test.mjs` and needs no
|
|
65
|
+
GPU -- it is what keeps this package's normal `npm test` green everywhere,
|
|
66
|
+
including CI.
|
|
67
|
+
|
|
68
|
+
`TrainingOrchestrator` accepts an optional `{ gpuDevice }` constructor
|
|
69
|
+
option; when supplied, `handleGradientPush()` uses it once a job's
|
|
70
|
+
aggregator has every shard's gradient, and stores the result on the job
|
|
71
|
+
record (retrievable via `getJobResult(jobId)`, and included in
|
|
72
|
+
`getJobStatus()`'s return).
|
|
73
|
+
|
|
74
|
+
Coverage against a *real* WebGPU implementation (not just the fallback
|
|
75
|
+
branch) lives in `test/gpu-real-webgpu/kernel.test.mjs`, gated behind the
|
|
76
|
+
optional `webgpu` devDependency, run via `npm run test:real-gpu`
|
|
77
|
+
(`REQUIRE_WEBGPU=1 npm run test:real-gpu` to make an absent/non-functional
|
|
78
|
+
binding a hard failure rather than a silent skip -- see that file for the
|
|
79
|
+
full rationale, which mirrors `browsermesh-transport`'s `test:real-peer`
|
|
80
|
+
pattern).
|
|
81
|
+
|
|
82
|
+
**Headless CI finding**: this tier is deliberately **not** wired into CI
|
|
83
|
+
(see `.github/workflows/ci.yml`) -- run it locally/manually via
|
|
84
|
+
`npm run test:real-gpu`. Getting a real adapter/device at all took work: on
|
|
85
|
+
a bare `ubuntu-latest`-equivalent image with no GPU hardware,
|
|
86
|
+
`requestAdapter()` returns `null` -- Dawn's Vulkan backend has no ICD to
|
|
87
|
+
talk to at all (`libvulkan.so.1` isn't installed by default, so there's
|
|
88
|
+
nothing to even attempt a software fallback through). Installing
|
|
89
|
+
`libvulkan1` and `mesa-vulkan-drivers` (Mesa's `llvmpipe`/lavapipe software
|
|
90
|
+
rasterizer) does make a real adapter/device available headlessly, and the
|
|
91
|
+
shader's actual compute output (both the weighted and unweighted branches)
|
|
92
|
+
was verified correct against it, cross-checked against the CPU
|
|
93
|
+
`aggregate()` path -- confirmed on a local emulated approximation of that
|
|
94
|
+
environment.
|
|
95
|
+
|
|
96
|
+
But wiring that into an actual CI step and running it against this repo's
|
|
97
|
+
real GitHub-hosted `ubuntu-latest` runner surfaced a second problem the
|
|
98
|
+
local approximation didn't: a deterministic **native crash** inside the
|
|
99
|
+
`webgpu` binding itself, partway through the very first test, right as
|
|
100
|
+
`GPUBuffer.mapAsync()`'s cross-thread completion callback fires:
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
Fatal glibc error: pthread_mutex_lock.c:94 (___pthread_mutex_lock): assertion failed: mutex->__data.__owner == 0
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
That's a threading bug in `dawn.node`'s own native code (a pthread mutex
|
|
107
|
+
locked from the wrong owning thread), not in this package's WGSL or JS --
|
|
108
|
+
and it didn't reproduce locally, most likely because the local
|
|
109
|
+
approximation ran the same Ubuntu image under QEMU emulation, which serializes/
|
|
110
|
+
slows execution enough to mask a real-hardware timing race. There is no
|
|
111
|
+
JS-level try/catch that can turn a native process crash into a clean test
|
|
112
|
+
failure, let alone a graceful skip, so this tier cannot be safely made a
|
|
113
|
+
required CI check today. It stays a real, valuable, but local-only/manual
|
|
114
|
+
verification path until either the upstream binding fixes this, or a
|
|
115
|
+
different Node WebGPU binding is adopted.
|
|
48
116
|
|
|
49
117
|
## Install
|
|
50
118
|
|
|
@@ -58,6 +126,149 @@ npm install @johnhenry/browsermesh-apps @johnhenry/browsermesh-primitives @johnh
|
|
|
58
126
|
import { MeshChat, AppRegistry, MeshOrchestrator } from 'browsermesh-apps';
|
|
59
127
|
```
|
|
60
128
|
|
|
129
|
+
## Connecting a real mesh node: `createMeshNode()`
|
|
130
|
+
|
|
131
|
+
`mesh-bootstrap.mjs`'s `createMeshNode(options)` is the composition root that
|
|
132
|
+
wires a real Ed25519 identity, discovery, and a real WebRTC transport
|
|
133
|
+
negotiator into a booted `PeerNode`. A minimal call needs only an injectable
|
|
134
|
+
signaling transport (see `signaling.mjs`) to relay WebRTC offer/answer/ICE
|
|
135
|
+
messages between peers:
|
|
136
|
+
|
|
137
|
+
```js
|
|
138
|
+
import { createMeshNode } from '@johnhenry/browsermesh-apps';
|
|
139
|
+
|
|
140
|
+
const node = await createMeshNode({
|
|
141
|
+
signalingTransport, // a {send(msg), onMessage(cb)} bus -- see signaling.mjs
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### TURN server configuration
|
|
146
|
+
|
|
147
|
+
By default, `createMeshNode()` gathers **no ICE servers at all** (no STUN,
|
|
148
|
+
no TURN) -- host candidates only, which is enough for peers on the same LAN
|
|
149
|
+
and discloses nothing to a third party. That's fine for typical NAT, but
|
|
150
|
+
peers behind symmetric or restrictive NATs need a STUN and/or TURN server to
|
|
151
|
+
connect at all.
|
|
152
|
+
|
|
153
|
+
Pass standard `RTCIceServer`-shaped entries via `options.iceServers`:
|
|
154
|
+
|
|
155
|
+
```js
|
|
156
|
+
import { createMeshNode } from '@johnhenry/browsermesh-apps';
|
|
157
|
+
import { PUBLIC_STUN_SERVERS } from '@johnhenry/browsermesh-transport';
|
|
158
|
+
|
|
159
|
+
const node = await createMeshNode({
|
|
160
|
+
signalingTransport,
|
|
161
|
+
iceServers: [
|
|
162
|
+
...PUBLIC_STUN_SERVERS, // opt-in public STUN (see browsermesh-transport's webrtc.mjs)
|
|
163
|
+
{ urls: 'turn:turn.example.com:3478', username: 'alice', credential: 's3cr3t' },
|
|
164
|
+
],
|
|
165
|
+
});
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`iceServers` is merged with `DEFAULT_ICE_SERVERS` via
|
|
169
|
+
`@johnhenry/browsermesh-transport`'s `mergeIceServers()` -- the same
|
|
170
|
+
extension point `webrtc.mjs` already exposes, reused here rather than
|
|
171
|
+
reimplemented:
|
|
172
|
+
|
|
173
|
+
- Omit the option, or pass `undefined`/`null`, to keep the default (no ICE
|
|
174
|
+
servers).
|
|
175
|
+
- Pass a non-empty array (TURN and/or STUN entries) to **add** them
|
|
176
|
+
alongside the defaults; malformed entries (missing `urls`) are silently
|
|
177
|
+
dropped rather than passed through to `RTCPeerConnection`.
|
|
178
|
+
- Pass an explicit `iceServers: []` to mean "no ICE servers at all" --
|
|
179
|
+
honoured as given, never replaced by the defaults. This is what this
|
|
180
|
+
package's own `test/real-peer/mesh-bootstrap.test.mjs` uses for a
|
|
181
|
+
hermetic, loopback-only connection in CI.
|
|
182
|
+
|
|
183
|
+
This reaches the `WebRTCMeshManager` that `createMeshNode()` attaches to the
|
|
184
|
+
returned node as `node.meshManager`, and from there every
|
|
185
|
+
`WebRTCPeerConnection` it creates.
|
|
186
|
+
|
|
187
|
+
## Sharing a `VirtualNetwork` with specific peers: mesh relay
|
|
188
|
+
|
|
189
|
+
Real-world scenario: your peer already reaches a real local service (e.g. an
|
|
190
|
+
S3-compatible emulator, via `@johnhenry/browsermesh-netway`'s `GatewayBackend`
|
|
191
|
+
tunneling real TCP through a local `wsh` server) on its own `VirtualNetwork`.
|
|
192
|
+
`MeshRelayHost`/`MeshRelayBackend` let you share *that specific access* with
|
|
193
|
+
specific, authorized mesh peers over the real WebRTC connection you already
|
|
194
|
+
have -- gated per-peer, per-service, per-action, with zero new authorization
|
|
195
|
+
machinery.
|
|
196
|
+
|
|
197
|
+
On the host side (the peer whose `VirtualNetwork` is being shared), either
|
|
198
|
+
pass `{ enableRelayHost: true, relayHostNetwork }` to `createMeshNode()`:
|
|
199
|
+
|
|
200
|
+
```js
|
|
201
|
+
import { createMeshNode } from '@johnhenry/browsermesh-apps';
|
|
202
|
+
|
|
203
|
+
const alice = await createMeshNode({
|
|
204
|
+
signalingTransport,
|
|
205
|
+
enableRelayHost: true,
|
|
206
|
+
relayHostNetwork: aliceNetwork, // alice's own VirtualNetwork
|
|
207
|
+
relayHostServices: { 's3-local': 'tcp://127.0.0.1:9000' },
|
|
208
|
+
});
|
|
209
|
+
// alice.relayHost.exposeService(name, targetAddress) / .hideService(name)
|
|
210
|
+
// are also available for exposing services after boot.
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
or construct a `MeshRelayHost` directly against any booted `PeerNode`. Then
|
|
214
|
+
grant specific peers access to specific services via `PeerRegistry`'s
|
|
215
|
+
existing capability API -- no new scope grammar, just
|
|
216
|
+
`mesh-relay:<service>:connect` (wildcards like `mesh-relay:*:connect` work
|
|
217
|
+
too, since `MeshACL`'s scope matching already supports them):
|
|
218
|
+
|
|
219
|
+
```js
|
|
220
|
+
alice.registry.grantCapabilities(bob.podId, ['mesh-relay:s3-local:connect']);
|
|
221
|
+
// ...later, to cut Bob off:
|
|
222
|
+
alice.registry.revokeCapabilities(bob.podId, ['mesh-relay:s3-local:connect']);
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
On the client side (the peer being granted access), `MeshRelayBackend` is a
|
|
226
|
+
`browsermesh-netway` `Backend` -- register it on your own `VirtualNetwork`
|
|
227
|
+
under any scheme you like, and connect through the normal API, treating the
|
|
228
|
+
service name as the "host":
|
|
229
|
+
|
|
230
|
+
```js
|
|
231
|
+
import { MeshRelayBackend } from '@johnhenry/browsermesh-apps';
|
|
232
|
+
import { VirtualNetwork } from '@johnhenry/browsermesh-netway';
|
|
233
|
+
|
|
234
|
+
const bobNetwork = new VirtualNetwork();
|
|
235
|
+
bobNetwork.addBackend('via-alice', new MeshRelayBackend({ node: bob, relayPeerPubKey: alice.podId }));
|
|
236
|
+
|
|
237
|
+
const socket = await bobNetwork.connect('via-alice://s3-local'); // refused (ConnectionRefusedError) until granted
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
TCP-only for now (`listen()`/`bindDatagram()` on `MeshRelayBackend` are the
|
|
241
|
+
inherited `Backend` "not implemented" throws). See
|
|
242
|
+
`examples/06-mesh-relay.mjs` for a full runnable walkthrough (in-process
|
|
243
|
+
simulated mesh connection) and
|
|
244
|
+
`test/real-peer/mesh-relay.test.mjs` for the real-WebRTC, real-TCP proof.
|
|
245
|
+
|
|
246
|
+
## Putting it all together: sync + kernel-gated mesh + relay on one connection
|
|
247
|
+
|
|
248
|
+
Every composition layer above (`enableSync`, a `Kernel` wired via
|
|
249
|
+
`createMeshKernel({ peerNode })`, and `enableRelayHost`) attaches to the
|
|
250
|
+
*same* `PeerNode` independently -- nothing about wiring one requires or
|
|
251
|
+
excludes the others, and each dispatches on `PeerNode`'s shared
|
|
252
|
+
`onIncomingData()` bus, filtering by its own `envelope.type` (`'mesh-sync'`,
|
|
253
|
+
`'mesh-relay'`; the kernel's `caps.mesh` view is unfiltered -- see below).
|
|
254
|
+
|
|
255
|
+
`test/real-peer/full-pipeline.test.mjs` proves all three actually compose on
|
|
256
|
+
one live, real WebRTC connection: CRDT sync converges, a kernel tenant's
|
|
257
|
+
`caps.mesh.send()`/`onReceive()` moves real bytes, and a mesh-relay round
|
|
258
|
+
trip completes, all interleaved on the same `PeerNode` pair, with no
|
|
259
|
+
envelope-type collisions or dispatch corruption between them.
|
|
260
|
+
`examples/07-full-mesh-pipeline.mjs` is the same story narrated for a human
|
|
261
|
+
reader (in-process simulated connection, like `06`).
|
|
262
|
+
|
|
263
|
+
One property worth knowing if you wire a kernel mesh capability alongside
|
|
264
|
+
sync/relay: `Kernel#meshFor()`'s `onReceive` is **not** scoped by
|
|
265
|
+
`envelope.type` the way `MeshSyncBinding`/`MeshRelayHost` are -- a kernel
|
|
266
|
+
tenant's `caps.mesh.onReceive` callback sees every inbound payload on the
|
|
267
|
+
connection, including `mesh-sync`/`mesh-relay`-typed envelopes not meant for
|
|
268
|
+
it (harmless -- those envelopes are just plain objects with a `.type` field
|
|
269
|
+
tenant code can filter on itself if it cares, but worth knowing rather than
|
|
270
|
+
assuming the view is pre-filtered).
|
|
271
|
+
|
|
61
272
|
## License
|
|
62
273
|
|
|
63
274
|
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-apps",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -20,14 +20,40 @@
|
|
|
20
20
|
"directory": "packages/browsermesh-apps"
|
|
21
21
|
},
|
|
22
22
|
"peerDependencies": {
|
|
23
|
-
"@johnhenry/browsermesh-primitives": ">=0.0.0",
|
|
24
|
-
"@johnhenry/browsermesh-core": ">=0.0.0",
|
|
25
|
-
"@johnhenry/browsermesh-transport": ">=0.0.0",
|
|
26
|
-
"@johnhenry/browsermesh-sync": ">=0.0.0",
|
|
27
|
-
"@johnhenry/browsermesh-discovery": ">=0.0.0"
|
|
23
|
+
"@johnhenry/browsermesh-primitives": ">=0.0.1 <1.0.0",
|
|
24
|
+
"@johnhenry/browsermesh-core": ">=0.1.0 <1.0.0",
|
|
25
|
+
"@johnhenry/browsermesh-transport": ">=0.1.0 <1.0.0",
|
|
26
|
+
"@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
|
|
27
|
+
"@johnhenry/browsermesh-discovery": ">=0.0.1 <1.0.0",
|
|
28
|
+
"@johnhenry/browsermesh-kernel": ">=0.0.0 <1.0.0",
|
|
29
|
+
"@johnhenry/browsermesh-netway": ">=0.0.0 <1.0.0"
|
|
30
|
+
},
|
|
31
|
+
"peerDependenciesMeta": {
|
|
32
|
+
"@johnhenry/browsermesh-transport": {
|
|
33
|
+
"optional": true
|
|
34
|
+
},
|
|
35
|
+
"@johnhenry/browsermesh-core": {
|
|
36
|
+
"optional": true
|
|
37
|
+
},
|
|
38
|
+
"@johnhenry/browsermesh-discovery": {
|
|
39
|
+
"optional": true
|
|
40
|
+
},
|
|
41
|
+
"@johnhenry/browsermesh-kernel": {
|
|
42
|
+
"optional": true
|
|
43
|
+
},
|
|
44
|
+
"@johnhenry/browsermesh-netway": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"node-datachannel": "^0.33.2",
|
|
50
|
+
"fake-indexeddb": "^6.2.5",
|
|
51
|
+
"webgpu": "^0.6.1"
|
|
28
52
|
},
|
|
29
53
|
"scripts": {
|
|
30
|
-
"test": "node --import ./test/_setup-globals.mjs --test test/*.test.mjs"
|
|
54
|
+
"test": "node --import ./test/_setup-globals.mjs --test test/*.test.mjs",
|
|
55
|
+
"test:real-peer": "node --import ./test/_setup-globals.mjs --test --test-concurrency=1 test/real-peer/*.test.mjs",
|
|
56
|
+
"test:real-gpu": "node --import ./test/_setup-globals.mjs --test test/gpu-real-webgpu/*.test.mjs"
|
|
31
57
|
},
|
|
32
58
|
"homepage": "https://opensource.johnhenry.me/browsermesh/",
|
|
33
59
|
"engines": {
|
|
@@ -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
|
+
}
|