Web demo: multi-device sync + connection fixes
Browse files- web/.claude/launch.json +11 -0
- web/public/app.js +58 -14
- web/public/traincore.js +3 -0
web/.claude/launch.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": "0.0.1",
|
| 3 |
+
"configurations": [
|
| 4 |
+
{
|
| 5 |
+
"name": "daisychain-web",
|
| 6 |
+
"runtimeExecutable": "node",
|
| 7 |
+
"runtimeArgs": ["server.js"],
|
| 8 |
+
"port": 8787
|
| 9 |
+
}
|
| 10 |
+
]
|
| 11 |
+
}
|
web/public/app.js
CHANGED
|
@@ -4,7 +4,15 @@
|
|
| 4 |
|
| 5 |
// model + task now live in transformer.js β a mini transformer LM trained
|
| 6 |
// through the verified INT8 units. Settings come from the sliders.
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
const ui = {
|
| 10 |
status: document.getElementById("status"),
|
|
@@ -155,17 +163,30 @@ function initiatePeer(peerId) {
|
|
| 155 |
setupChannel(peerId, dc);
|
| 156 |
pc.createOffer().then(o => pc.setLocalDescription(o)).then(() => signal(peerId, { sdp: pc.localDescription }));
|
| 157 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
async function onSignal(from, data) {
|
| 159 |
let pc = pcs.get(from);
|
| 160 |
if (data.sdp) {
|
| 161 |
if (!pc) { pc = newPC(from); pc.ondatachannel = (e) => setupChannel(from, e.channel); }
|
| 162 |
await pc.setRemoteDescription(data.sdp);
|
|
|
|
|
|
|
|
|
|
| 163 |
if (data.sdp.type === "offer") {
|
| 164 |
const ans = await pc.createAnswer(); await pc.setLocalDescription(ans);
|
| 165 |
signal(from, { sdp: pc.localDescription });
|
| 166 |
}
|
| 167 |
-
} else if (data.candidate
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
}
|
| 170 |
}
|
| 171 |
function setupChannel(peerId, dc) {
|
|
@@ -174,7 +195,7 @@ function setupChannel(peerId, dc) {
|
|
| 174 |
dc.onclose = () => { chans.delete(peerId); updatePeers(); wake(); };
|
| 175 |
dc.onmessage = (e) => onGrad(peerId, e.data);
|
| 176 |
}
|
| 177 |
-
function cleanupPeer(id) { const pc = pcs.get(id); if (pc) pc.close(); pcs.delete(id); chans.delete(id); wake(); }
|
| 178 |
|
| 179 |
// ---- checkpoints ------------------------------------------------------------
|
| 180 |
// File layout (also the broadcast payload after the sentinel):
|
|
@@ -337,13 +358,30 @@ function onConfig(peerId, buf) {
|
|
| 337 |
// [int32 -5][int32 msgId][int32 seq][int32 total][bytes...]
|
| 338 |
// Channels are ordered+reliable, so chunks arrive in order per peer.
|
| 339 |
const FRAG_SENTINEL = -5, FRAG_CHUNK = 48 * 1024;
|
|
|
|
| 340 |
let fragSeq = 1;
|
| 341 |
const fragIn = new Map(); // peerId -> {id, parts, got, total}
|
| 342 |
-
function
|
| 343 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
const id = fragSeq++, src = new Uint8Array(buf);
|
| 345 |
const total = Math.ceil(src.length / FRAG_CHUNK);
|
| 346 |
for (let s = 0; s < total; s++) {
|
|
|
|
|
|
|
| 347 |
const part = src.subarray(s * FRAG_CHUNK, Math.min((s + 1) * FRAG_CHUNK, src.length));
|
| 348 |
const msg = new ArrayBuffer(16 + part.length);
|
| 349 |
new Int32Array(msg, 0, 4).set([FRAG_SENTINEL, id, s, total]);
|
|
@@ -351,7 +389,7 @@ function dcSend(dc, buf) {
|
|
| 351 |
dc.send(msg);
|
| 352 |
}
|
| 353 |
}
|
| 354 |
-
function broadcast(buf) { for (const dc of chans.values()) if (dc.readyState === "open") dcSend(dc, buf); }
|
| 355 |
function onFragment(peerId, buf) { // returns full message when complete
|
| 356 |
const [, id, seq, total] = new Int32Array(buf, 0, 4);
|
| 357 |
let st = fragIn.get(peerId);
|
|
@@ -427,7 +465,7 @@ function onGrad(peerId, buf) {
|
|
| 427 |
peerHashes.get(step).set(peerId, { hash: whash, loss });
|
| 428 |
wake(); // resolve waits immediately (no polling)
|
| 429 |
}
|
| 430 |
-
function broadcastGrad(step, whash, loss, grad) { broadcast(packGrad(step, whash, loss, grad)); }
|
| 431 |
// Event-driven: re-checked on every gradient arrival and peer departure, plus a
|
| 432 |
// coarse fallback timer (background tabs throttle timers to ~1s, so the old
|
| 433 |
// 15ms poll was the bottleneck there). Peers that left are dropped from the
|
|
@@ -488,7 +526,7 @@ async function train(cfg) {
|
|
| 488 |
for (let s = 0; s < steps; s++) {
|
| 489 |
const whash = hashWeights(); // pre-step fingerprint, sent with the grad
|
| 490 |
const { loss, grad } = await localStep();
|
| 491 |
-
broadcastGrad(s, whash, loss, grad);
|
| 492 |
let all;
|
| 493 |
if (!cohort.length) {
|
| 494 |
all = [grad]; // solo run
|
|
@@ -496,9 +534,14 @@ async function train(cfg) {
|
|
| 496 |
const ids = await waitForGradIds(s, cohort);
|
| 497 |
// sync guard: publish the exact contributor set so every device
|
| 498 |
// averages the same gradients (or stops) β never a silent fork
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
rosters.set(s,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 502 |
} else {
|
| 503 |
// follower: apply the leader's roster verbatim, or stop
|
| 504 |
await waitFor(() => rosters.has(s) || !chans.has(leaderId), 15000);
|
|
@@ -515,8 +558,9 @@ async function train(cfg) {
|
|
| 515 |
halted = `missing a roster gradient at step ${s + 1} β applying a partial average would fork the weights`;
|
| 516 |
break;
|
| 517 |
}
|
| 518 |
-
|
| 519 |
-
|
|
|
|
| 520 |
}
|
| 521 |
// divergence check: every contributor's pre-step weight hash must match mine
|
| 522 |
const hs = peerHashes.get(s);
|
|
|
|
| 4 |
|
| 5 |
// model + task now live in transformer.js β a mini transformer LM trained
|
| 6 |
// through the verified INT8 units. Settings come from the sliders.
|
| 7 |
+
// STUN discovers the direct path; the TURN relays (Open Relay, free) carry the
|
| 8 |
+
// traffic when both sides sit behind symmetric NATs (mobile carriers, corp
|
| 9 |
+
// networks) β without TURN those users can never connect across networks.
|
| 10 |
+
const STUN = [
|
| 11 |
+
{ urls: "stun:stun.l.google.com:19302" },
|
| 12 |
+
{ urls: "turn:openrelay.metered.ca:80", username: "openrelayproject", credential: "openrelayproject" },
|
| 13 |
+
{ urls: "turn:openrelay.metered.ca:443", username: "openrelayproject", credential: "openrelayproject" },
|
| 14 |
+
{ urls: "turns:openrelay.metered.ca:443?transport=tcp", username: "openrelayproject", credential: "openrelayproject" },
|
| 15 |
+
];
|
| 16 |
|
| 17 |
const ui = {
|
| 18 |
status: document.getElementById("status"),
|
|
|
|
| 163 |
setupChannel(peerId, dc);
|
| 164 |
pc.createOffer().then(o => pc.setLocalDescription(o)).then(() => signal(peerId, { sdp: pc.localDescription }));
|
| 165 |
}
|
| 166 |
+
// ICE candidates can arrive while setRemoteDescription is still awaiting (the
|
| 167 |
+
// async handlers interleave) β adding one before the description is set throws
|
| 168 |
+
// and the candidate is lost, so the connection silently fails. Queue them and
|
| 169 |
+
// flush once the remote description lands.
|
| 170 |
+
const pendingCand = new Map(); // peerId -> [candidate,...]
|
| 171 |
async function onSignal(from, data) {
|
| 172 |
let pc = pcs.get(from);
|
| 173 |
if (data.sdp) {
|
| 174 |
if (!pc) { pc = newPC(from); pc.ondatachannel = (e) => setupChannel(from, e.channel); }
|
| 175 |
await pc.setRemoteDescription(data.sdp);
|
| 176 |
+
for (const c of pendingCand.get(from) || [])
|
| 177 |
+
try { await pc.addIceCandidate(c); } catch (e) {}
|
| 178 |
+
pendingCand.delete(from);
|
| 179 |
if (data.sdp.type === "offer") {
|
| 180 |
const ans = await pc.createAnswer(); await pc.setLocalDescription(ans);
|
| 181 |
signal(from, { sdp: pc.localDescription });
|
| 182 |
}
|
| 183 |
+
} else if (data.candidate) {
|
| 184 |
+
if (pc && pc.remoteDescription) {
|
| 185 |
+
try { await pc.addIceCandidate(data.candidate); } catch (e) {}
|
| 186 |
+
} else { // pc missing or not ready: hold it
|
| 187 |
+
if (!pendingCand.has(from)) pendingCand.set(from, []);
|
| 188 |
+
pendingCand.get(from).push(data.candidate);
|
| 189 |
+
}
|
| 190 |
}
|
| 191 |
}
|
| 192 |
function setupChannel(peerId, dc) {
|
|
|
|
| 195 |
dc.onclose = () => { chans.delete(peerId); updatePeers(); wake(); };
|
| 196 |
dc.onmessage = (e) => onGrad(peerId, e.data);
|
| 197 |
}
|
| 198 |
+
function cleanupPeer(id) { const pc = pcs.get(id); if (pc) pc.close(); pcs.delete(id); chans.delete(id); pendingCand.delete(id); wake(); }
|
| 199 |
|
| 200 |
// ---- checkpoints ------------------------------------------------------------
|
| 201 |
// File layout (also the broadcast payload after the sentinel):
|
|
|
|
| 358 |
// [int32 -5][int32 msgId][int32 seq][int32 total][bytes...]
|
| 359 |
// Channels are ordered+reliable, so chunks arrive in order per peer.
|
| 360 |
const FRAG_SENTINEL = -5, FRAG_CHUNK = 48 * 1024;
|
| 361 |
+
const DC_MAXBUF = 4 * 1024 * 1024; // pause sending above this backlog
|
| 362 |
let fragSeq = 1;
|
| 363 |
const fragIn = new Map(); // peerId -> {id, parts, got, total}
|
| 364 |
+
function dcDrain(dc) { // wait for the send buffer to empty out
|
| 365 |
+
return new Promise((res) => {
|
| 366 |
+
if (dc.bufferedAmount <= DC_MAXBUF || dc.readyState !== "open") return res();
|
| 367 |
+
const t = setInterval(() => {
|
| 368 |
+
if (dc.bufferedAmount <= DC_MAXBUF || dc.readyState !== "open") { clearInterval(t); res(); }
|
| 369 |
+
}, 50);
|
| 370 |
+
});
|
| 371 |
+
}
|
| 372 |
+
async function dcSend(dc, buf) {
|
| 373 |
+
// multi-MB gradients can overflow the channel's send buffer, which makes
|
| 374 |
+
// dc.send throw and kills the training loop β so apply backpressure
|
| 375 |
+
if (buf.byteLength <= FRAG_CHUNK) {
|
| 376 |
+
await dcDrain(dc);
|
| 377 |
+
if (dc.readyState === "open") dc.send(buf);
|
| 378 |
+
return;
|
| 379 |
+
}
|
| 380 |
const id = fragSeq++, src = new Uint8Array(buf);
|
| 381 |
const total = Math.ceil(src.length / FRAG_CHUNK);
|
| 382 |
for (let s = 0; s < total; s++) {
|
| 383 |
+
await dcDrain(dc);
|
| 384 |
+
if (dc.readyState !== "open") return; // peer left mid-send
|
| 385 |
const part = src.subarray(s * FRAG_CHUNK, Math.min((s + 1) * FRAG_CHUNK, src.length));
|
| 386 |
const msg = new ArrayBuffer(16 + part.length);
|
| 387 |
new Int32Array(msg, 0, 4).set([FRAG_SENTINEL, id, s, total]);
|
|
|
|
| 389 |
dc.send(msg);
|
| 390 |
}
|
| 391 |
}
|
| 392 |
+
async function broadcast(buf) { for (const dc of chans.values()) if (dc.readyState === "open") await dcSend(dc, buf); }
|
| 393 |
function onFragment(peerId, buf) { // returns full message when complete
|
| 394 |
const [, id, seq, total] = new Int32Array(buf, 0, 4);
|
| 395 |
let st = fragIn.get(peerId);
|
|
|
|
| 465 |
peerHashes.get(step).set(peerId, { hash: whash, loss });
|
| 466 |
wake(); // resolve waits immediately (no polling)
|
| 467 |
}
|
| 468 |
+
function broadcastGrad(step, whash, loss, grad) { return broadcast(packGrad(step, whash, loss, grad)); }
|
| 469 |
// Event-driven: re-checked on every gradient arrival and peer departure, plus a
|
| 470 |
// coarse fallback timer (background tabs throttle timers to ~1s, so the old
|
| 471 |
// 15ms poll was the bottleneck there). Peers that left are dropped from the
|
|
|
|
| 526 |
for (let s = 0; s < steps; s++) {
|
| 527 |
const whash = hashWeights(); // pre-step fingerprint, sent with the grad
|
| 528 |
const { loss, grad } = await localStep();
|
| 529 |
+
await broadcastGrad(s, whash, loss, grad);
|
| 530 |
let all;
|
| 531 |
if (!cohort.length) {
|
| 532 |
all = [grad]; // solo run
|
|
|
|
| 534 |
const ids = await waitForGradIds(s, cohort);
|
| 535 |
// sync guard: publish the exact contributor set so every device
|
| 536 |
// averages the same gradients (or stops) β never a silent fork
|
| 537 |
+
const roster = [myId, ...ids];
|
| 538 |
+
broadcastRoster(s, roster);
|
| 539 |
+
rosters.set(s, roster);
|
| 540 |
+
// CRITICAL: average strictly in roster order. Float addition is
|
| 541 |
+
// commutative but NOT associative β if any device sums in a different
|
| 542 |
+
// order (e.g. self-first), 3+ devices each get a microscopically
|
| 543 |
+
// different average and the weights fork. Roster order is the canon.
|
| 544 |
+
all = roster.map(id => id === myId ? grad : incoming.get(s).get(id));
|
| 545 |
} else {
|
| 546 |
// follower: apply the leader's roster verbatim, or stop
|
| 547 |
await waitFor(() => rosters.has(s) || !chans.has(leaderId), 15000);
|
|
|
|
| 558 |
halted = `missing a roster gradient at step ${s + 1} β applying a partial average would fork the weights`;
|
| 559 |
break;
|
| 560 |
}
|
| 561 |
+
// same canonical order as the leader (self's grad in its roster slot);
|
| 562 |
+
// if the leader dropped my late grad from the roster, I skip it too
|
| 563 |
+
all = roster.map(id => id === myId ? grad : incoming.get(s).get(id)).filter(Boolean);
|
| 564 |
}
|
| 565 |
// divergence check: every contributor's pre-step weight hash must match mine
|
| 566 |
const hs = peerHashes.get(s);
|
web/public/traincore.js
CHANGED
|
@@ -51,6 +51,9 @@
|
|
| 51 |
}
|
| 52 |
|
| 53 |
// average a list of gradient Float32Arrays (equal weight)
|
|
|
|
|
|
|
|
|
|
| 54 |
function averageGrads(grads) {
|
| 55 |
const out = new Float32Array(grads[0].length);
|
| 56 |
for (const g of grads) for (let i = 0; i < g.length; i++) out[i] += g[i];
|
|
|
|
| 51 |
}
|
| 52 |
|
| 53 |
// average a list of gradient Float32Arrays (equal weight)
|
| 54 |
+
// ORDER MATTERS: float addition is not associative, so every replica MUST
|
| 55 |
+
// pass the gradients in the same order (the leader's roster order) or their
|
| 56 |
+
// averages differ in the last bits and the weights fork. Never self-first.
|
| 57 |
function averageGrads(grads) {
|
| 58 |
const out = new Float32Array(grads[0].length);
|
| 59 |
for (const g of grads) for (let i = 0; i < g.length; i++) out[i] += g[i];
|