perf(coordinator): copy, digest and encode the round base once per round (#35, first cut)
openb4f9cee28aa6ba92 #64 · opened 2026-11-06 20:41 UTC
Imported from GitHub aien-dev/open-humanity#64, by drakestapleton
Base d929a34d61716a347506fe3e64e2a09a0fddf317 · Head 758d1c0d33cded6c56d6f860775c577655326989
drakestapleton wrote on 2026-11-06 20:41 UTC
perf(coordinator): copy, digest and encode the round base once per round (#35, first cut)
Tracking issue: Refs aien-dev/open-humanity#35. This is a first cut only; it does not close the issue.
Head SHA:758d1c0d33cded6c56d6f860775c577655326989 (branch fix/issue-35-round-base-snapshot, base main @ d929a34)
Problem
On main, Coordinator::begin_round copies the parameters once. After that, work_unit runs oh_core::params_digest(&self.model.params()) for every volunteer: one full Vec<f32> clone and one full BLAKE3 pass each. run_round also re-encodes the same BaseModel with bincode for each connection. For V volunteers, one round costs 1+V parameter copies, V digests and V encodes.
begin_round copies the parameters once and digests that copy once. The digest is stored in a private field, round_base_digest: Option<[u8; 32]>, on the coordinator, so it belongs to this round.
work_unit signs the stored digest. Outside a round (before begin_round, or after finish_round), it digests the live model, which is what main does.
finish_round_with_teaching clears the stored digest. Model parameters change only inside this function; Scorer::score and score_text restore them.
run_round encodes the BaseModel frame once per round with send into a Vec. It then writes the same payload to each connection with write_frame, so each connection gets the same calls and bytes that send produced before. Each existing stream still encrypts the frame with its own keys. Ciphertext is not shared, the encoded bytes are not exposed, and there is no process-wide cache.
Test-only instrumentation: a #[cfg(test)] thread-local tally of (parameter copies, digests), recorded by two private helpers. The public API does not change.
Out of scope
Transport buffering and encrypted streams (#31).
signed_message cloning (#36).
Network traffic: the bytes sent are unchanged at Θ(V·B), so this PR makes no claim about network traffic.
Allocation, CPU and wall-time measurements, and V=32 runs. The issue asks for these, but they are not done here.
BEFORE: commit a9278f0 (the tests and tally on top of main's logic), cargo test -p oh-coordinator --lib -- test_round_ test_work_unit_digest
101
left: [(1,1,2,1), (1,2,2,1), (2,1,3,2), (2,2,3,2), (8,1,9,8), (8,2,9,8)] vs right: [... (v,r,1,1) ...]. Tuples are (volunteers, round, copies, digests), so copies = 1+V and digests = V. The parity and stale tests pass on the old path.
AFTER: 758d1c0, cargo test -p oh-coordinator (all targets)
0
lib 13 passed; aienet0-run 15; encrypted_transport 1; loopback 5; teaching 3; teaching_steps 2 (+1 ignored). test result: ok.
NEG 1: work_unit back to base_digest(&base_params(&self.model)) (copy and digest on every call)
101
left: [(1,1,2,2), … (8,2,9,9)]. The repro fails.
NEG 2: invalidation in finish_round_with_teaching removed
101
test_work_unit_digest_follows_the_model_after_finish_round panicked. A stale digest was signed after the model changed.
NEG 3: base frame written with its length prefix doubled (&base_frame instead of &base_frame[4..])
101
test_round_frames_match_per_volunteer_copy_digest_and_encode panicked on frame bytes.
CI job commands locally: anchore/syft:v1.54.0 (the version pinned by sbom-action@66cbf4bc) dir:/src -o spdx-json at head
0
SPDX-2.3, 289 packages
The parity test covers V = 1, 2 and 8 over two rounds, with one parameter changed between rounds. It uses a fixed signing key from Keypair::from_seed([7; 32]), a fixed corpus and seed 5. Every connection's bytes must equal the old per-volunteer path: copy, params_digest, WorkUnit::new_signed, then send(base) and send(unit). The test also checks the decoded base parameters, work-unit ID (digest()), base_digest, signature and verify_from(pubkey).
rustfmt --check of this file reports only the three diffs already on main, at lines 9, 51 and 867; this PR adds none. cargo rewrote Cargo.lock during the build (main's lockfile is stale after the dependency bumps). That change was reverted and is not part of this PR.
Labels: IMPLEMENTED, EXERCISED (host-local) PASS. Hosted CI on this head: NOT_RUN (PR desk gate). These are host results, not hardware evidence.
Apply it
git checkout -b patch-b4f9cee28aa6ba92d929a34d61716a347506fe3e64e2a09a0fddf317
curl -fsSL https://interplane.io/drakestapleton/open-humanity/patches/b4f9cee28aa6ba92.patch | git am
diff --git a/crates/oh-coordinator/src/lib.rs b/crates/oh-coordinator/src/lib.rs
index 208a186..33708e5 100644
--- a/crates/oh-coordinator/src/lib.rs
+++ b/crates/oh-coordinator/src/lib.rs
@@ -12,7 +12,7 @@
use beacon_core::Keypair;
use oh_core::{
- apply, coordinator_handshake, pseudo_gradient, recv_submission, send, BaseModel,
+ apply, coordinator_handshake, pseudo_gradient, recv_submission, send, write_frame, BaseModel,
CompressedDelta, Learner, Ledger, LedgerError, Receipt, Scorer, Submission, TeachingBatch,
TinyByteModel, Update, WorkUnit,
};
@@ -193,6 +193,27 @@ fn bits_per_byte(bits: f64, data: &[u8]) -> f64 {
bits / (data.len() - 1) as f64
}
+#[cfg(test)]
+thread_local! {
+ /// Test-only tally of (full parameter copies, parameter digests) taken
+ /// to hand out round bases and work units.
+ static BASE_COST: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
+}
+
+/// A full copy of the model's parameters, as the base of a round.
+fn base_params(model: &TinyByteModel) -> Vec<f32> {
+ #[cfg(test)]
+ BASE_COST.with(|c| c.set((c.get().0 + 1, c.get().1)));
+ model.params()
+}
+
+/// `params_digest` of a round base, as signed into every work unit.
+fn base_digest(params: &[f32]) -> [u8; 32] {
+ #[cfg(test)]
+ BASE_COST.with(|c| c.set((c.get().0, c.get().1 + 1)));
+ oh_core::params_digest(params)
+}
+
fn check_settings(train: &[u8], s: &Settings) -> Result<(), String> {
if s.volunteers_per_round == 0 || s.dim == 0 {
return Err("volunteers per round and dim must be at least 1".into());
@@ -222,6 +243,10 @@ pub struct Coordinator {
round: u32,
ledger: Ledger,
approved_volunteers: HashSet<[u8; 32]>,
+ /// Digest of the current round's base, taken once in `begin_round` and
+ /// dropped in `finish_round_with_teaching`, the only place the model
+ /// changes (scoring restores it).
+ round_base_digest: Option<[u8; 32]>,
}
impl Coordinator {
@@ -264,6 +289,7 @@ impl Coordinator {
round: 0,
ledger,
approved_volunteers: HashSet::new(),
+ round_base_digest: None,
})
}
@@ -299,19 +325,26 @@ impl Coordinator {
}
/// Starts the next round and returns the model volunteers start from.
+ /// The base is copied and digested once here for every work unit of the
+ /// round.
pub fn begin_round(&mut self) -> BaseModel {
self.round += 1;
+ let params = base_params(&self.model);
+ self.round_base_digest = Some(base_digest(¶ms));
BaseModel {
dim: self.dim as u32,
- params: self.model.params(),
+ params,
}
}
/// The signed work unit for volunteer `slot` in the current round. Each
- /// slot gets its own shard of the training part.
+ /// slot gets its own shard of the training part. Outside a round (before
+ /// `begin_round` or after `finish_round`) it pins the model as it stands.
pub fn work_unit(&self, slot: usize) -> WorkUnit {
let shard = self.train[self.shards[slot].clone()].to_vec();
- let base_digest = oh_core::params_digest(&self.model.params());
+ let base_digest = self
+ .round_base_digest
+ .unwrap_or_else(|| base_digest(&base_params(&self.model)));
WorkUnit::new_signed(
&self.keypair,
self.run_id,
@@ -447,6 +480,7 @@ impl Coordinator {
accepted: &[Vec<f32>],
taught: &[Vec<u8>],
) -> RoundReport {
+ self.round_base_digest = None;
let mut aggregate_turings = 0.0;
let mut applied = false;
if let Some(mean) = aggregate(accepted, self.outer_lr) {
@@ -495,10 +529,22 @@ impl Coordinator {
));
}
let base = self.begin_round();
+ // Encode the base once per round. `send` into a Vec writes the 4-byte
+ // length and then the payload; `write_frame` re-adds the length on
+ // each connection, so every volunteer gets the bytes `send` gives.
+ let mut base_frame = Vec::new();
+ let base_encoded = send(&mut base_frame, &base).map_err(|e| e.to_string());
+ drop(base);
let mut units = Vec::with_capacity(conns.len());
for (slot, conn) in conns.iter_mut().enumerate() {
let unit = self.work_unit(slot);
- match send(conn, &base).and_then(|_| send(conn, &unit)) {
+ let sent = match &base_encoded {
+ Ok(()) => write_frame(conn, &base_frame[4..])
+ .and_then(|_| send(conn, &unit))
+ .map_err(|e| e.to_string()),
+ Err(e) => Err(e.clone()),
+ };
+ match sent {
Ok(()) => units.push(Some(unit)),
Err(e) => {
eprintln!("round {}: volunteer {slot}: send failed: {e}", self.round);
@@ -1055,4 +1101,122 @@ mod tests {
assert!(r.heldout_bpb <= fixed.start_bpb);
}
}
+
+ /// A connection that records what the coordinator sends and never
+ /// answers, so `run_round` sends every work unit and then gets no update.
+ #[derive(Default)]
+ struct Silent {
+ sent: Vec<u8>,
+ }
+
+ impl Read for Silent {
+ fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
+ Ok(0)
+ }
+ }
+
+ impl Write for Silent {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ self.sent.extend_from_slice(buf);
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+ }
+
+ fn fixed_coordinator(volunteers: usize, name: &str) -> Coordinator {
+ let text = corpus(6000, 4);
+ let s = settings(volunteers, 1.0);
+ let keypair = Keypair::from_seed(&[7; 32]);
+ Coordinator::with_keypair(&text, &s, fresh_ledger(name), keypair).unwrap()
+ }
+
+ #[test]
+ fn test_round_copies_and_digests_the_base_once_for_any_volunteer_count() {
+ // (volunteers, round, parameter copies, digests)
+ let mut cost = Vec::new();
+ for v in [1, 2, 8] {
+ let mut c = fixed_coordinator(v, &format!("base-cost-{v}"));
+ for round in 1..=2 {
+ let mut conns: Vec<Silent> = (0..v).map(|_| Silent::default()).collect();
+ BASE_COST.with(|n| n.set((0, 0)));
+ c.run_round(&mut conns).unwrap();
+ let (copies, digests) = BASE_COST.with(|n| n.get());
+ cost.push((v, round, copies, digests));
+ }
+ }
+ let once: Vec<_> = cost.iter().map(|&(v, r, _, _)| (v, r, 1, 1)).collect();
+ assert_eq!(cost, once, "one base copy and one digest per round");
+ }
+
+ #[test]
+ fn test_round_frames_match_per_volunteer_copy_digest_and_encode() {
+ for v in [1, 2, 8] {
+ let mut c = fixed_coordinator(v, &format!("parity-{v}"));
+ for round in 1..=2 {
+ // The fan-out before #35: copy, digest and encode the base
+ // again for every volunteer.
+ let expected: Vec<(Vec<u8>, WorkUnit)> = (0..v)
+ .map(|slot| {
+ let base = BaseModel {
+ dim: c.dim as u32,
+ params: c.model.params(),
+ };
+ let unit = WorkUnit::new_signed(
+ &c.keypair,
+ c.run_id,
+ round,
+ oh_core::params_digest(&c.model.params()),
+ c.train[c.shards[slot].clone()].to_vec(),
+ c.steps,
+ );
+ let mut frames = Vec::new();
+ send(&mut frames, &base).unwrap();
+ send(&mut frames, &unit).unwrap();
+ (frames, unit)
+ })
+ .collect();
+ let mut conns: Vec<Silent> = (0..v).map(|_| Silent::default()).collect();
+ c.run_round(&mut conns).unwrap();
+ for (slot, (conn, (frames, unit))) in conns.iter().zip(&expected).enumerate() {
+ let at = format!("{v} volunteers, round {round}, slot {slot}");
+ assert_eq!(conn.sent, *frames, "{at}: frame bytes");
+ let mut r = conn.sent.as_slice();
+ let base: BaseModel = oh_core::recv(&mut r).unwrap();
+ let got: WorkUnit = oh_core::recv(&mut r).unwrap();
+ assert_eq!(base.params, c.model.params(), "{at}: base");
+ assert_eq!(got.digest(), unit.digest(), "{at}: work unit id");
+ assert_eq!(got.base_digest, base.digest(), "{at}: base digest");
+ assert_eq!(got.sig, unit.sig, "{at}: signature");
+ got.verify_from(&c.pubkey()).unwrap();
+ }
+ // Change one parameter at the round boundary; the next
+ // round's base, digest and signatures must follow it.
+ let mut params = c.model.params();
+ params[0] += 0.5;
+ c.model.set_params(¶ms);
+ }
+ }
+ }
+
+ #[test]
+ fn test_work_unit_digest_follows_the_model_after_finish_round() {
+ let mut c = fixed_coordinator(1, "base-after-finish");
+ let base = c.begin_round();
+ let first = c.work_unit(0);
+ assert_eq!(first.base_digest, base.digest());
+ let mut worker = TinyByteModel::new(c.dim, 0);
+ worker.set_params(&base.params);
+ worker.train_steps(&c.train, 20, 9);
+ let delta = pseudo_gradient(&base.params, &worker.params());
+ assert!(c.finish_round(&[delta]).applied);
+ let live = oh_core::params_digest(&c.model.params());
+ assert_ne!(live, first.base_digest);
+ // Between rounds the work unit pins the model as it now stands.
+ assert_eq!(c.work_unit(0).base_digest, live);
+ assert_eq!(c.begin_round().digest(), live);
+ assert_eq!(c.work_unit(0).base_digest, live);
+ }
}