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 { + #[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], taught: &[Vec], ) -> 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, + } + + impl Read for Silent { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } + } + + impl Write for Silent { + fn write(&mut self, buf: &[u8]) -> io::Result { + 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 = (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, 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 = (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); + } }