From 7c585475d2b591e1907f500ccc8d3cac938a01a3 Mon Sep 17 00:00:00 2001 From: ale18V Date: Wed, 18 Nov 2026 16:24:41 +0100 Subject: [PATCH 01/29] docs: add collaborative training architecture design document --- docs/TRAINING_ARCHITECTURE.md | 415 ++++++++++++++++++++++++++++++++++ 1 file changed, 415 insertions(+) create mode 100644 docs/TRAINING_ARCHITECTURE.md diff --git a/docs/TRAINING_ARCHITECTURE.md b/docs/TRAINING_ARCHITECTURE.md new file mode 100644 index 000000000..765ae231f --- /dev/null +++ b/docs/TRAINING_ARCHITECTURE.md @@ -0,0 +1,415 @@ +# Collaborative Training Architecture Design Document + +## 1. Overview & Motivation + +Disco supports collaborative machine learning across local, federated, and decentralized topologies. As the framework grows beyond standard Federated Averaging (FedAvg) to support richer optimization, robustness, and privacy algorithms—such as **FedProx**, **SCAFFOLD**, **FedNova**, **Ditto** (personalized federated learning), **FedOpt** (server-side adaptive optimizers), **Differential Privacy (ALDP-FL)**, **Byzantine-robust aggregation (Centered Clipping)**, and **Secure Aggregation (MPC)**—the current abstractions in `discojs` exhibit structural coupling that makes adding and composing algorithms difficult. + +This design document analyzes the current architectural limitations in `discojs` and proposes a modular, composable target architecture that separates **local client optimization**, **post-round update transformations**, and **inter-client weight aggregation**. + +--- + +## 2. Problem Statement: Current Architectural Limitations + +```mermaid +flowchart TD + subgraph Current["Current Architecture"] + TI["TrainingInformation
aggregationStrategy, maxShareValue, privacy"] + TR["Trainer
#privacy, #bftClippingRadius, #weightNormHistory
#previousRoundWeights, applyOptimalPrivacy()"] + AGG["Aggregator
MeanAggregator | ByzantineRobustAggregator | SecureAggregator"] + MDL["Model (TFJS / GPT)
weights (trainable + non-trainable)"] + + TI --> TR + TI --> AGG + TR --> MDL + end +``` + +### 2.1. Conflation of Orthogonal Algorithmic Axes + +In collaborative and federated learning, a training algorithm is defined along **three orthogonal axes**: + +1. **Intra-Round Local Training Strategy (Client Optimization):** How each client optimizes its local model over its local dataset during a round: + - Standard Empirical Risk Minimization (FedAvg) + - Proximal regularization towards the round's initial weights: $\min_w F_k(w) + \frac{\mu}{2}\|w - w^{(t)}\|^2$ (FedProx) + - Control-variate gradient correction: $g \leftarrow g - c_i + c$ (SCAFFOLD) + - Personalized local regularization against the global model (Ditto) +2. **Post-Round Client Update Transformation & Privacy (Pre-Communication):** How a client transforms its local weight progress $\Delta w_i^{(t)} = w_i^{(t, K)} - w^{(t)}$ after completing local epochs/iterations and before transmitting weights to the server or peers: + - Adaptive layer-wise Frobenius norm clipping + Gaussian noise injection (ALDP-FL Differential Privacy) + - Explicit global or per-layer update norm clipping + - Local step-count normalization $\Delta w_i^{(t)} / \tau_i$ (FedNova) + - Update quantization or sparsification +3. **Inter-Client Weight Aggregation & Protocol (Server / Peer Combination):** How updates from multiple participants are combined across the network: + - Unweighted or sample-weighted arithmetic mean (`MeanAggregator`) + - Iterative Centered Clipping with momentum (`ByzantineRobustAggregator`) + - Multi-round additive secret sharing (`SecureAggregator`) + - Server-side adaptive optimization (`FedOpt` / Server Adam / Yogi) + +Currently, `TrainingInformation` models algorithm selection through a single `aggregationStrategy` field coupled with disjoint parameters (`privacy.byzantineFaultTolerance`, `privacy.differentialPrivacy`, and root-level `maxShareValue`). Under this structure: + +- Client-side local training strategies (such as FedProx) have no dedicated configuration axis. Modeling them as an `aggregationStrategy` forces the aggregator factory (`getAggregator`) to map a client-side optimizer to `MeanAggregator`, and **makes it impossible to combine FedProx with Byzantine-robust aggregation or Secure Aggregation**. +- Adding any new algorithm requires modifying the `aggregationStrategy` union, the task schemas, the CLI parser, and the webapp form in lockstep. + +### 2.2. Responsibility Leak Between `ByzantineRobustAggregator` and `Trainer` + +In `discojs/src/training/trainer.ts` and `discojs/src/privacy.ts`, `ByzantineRobustAggregator`'s configuration leaks directly into client-side execution inside `Trainer`: + +1. **Duplicated and misplaced clipping responsibility:** `ByzantineRobustAggregator` (`discojs/src/aggregator/byzantine.ts`) performs Centered Clipping on the receiving server or peer—which is where Byzantine fault tolerance must be enforced, because malicious peers do not obey client-side clipping. However, `Trainer` also extracts `byzantineFaultTolerance.clippingRadius` and calls `applyOptimalPrivacy` at the end of every client round to pre-clip outgoing weights even when Differential Privacy is disabled. +2. **Mathematical norm mismatch:** `ByzantineRobustAggregator` computes and clips by the **global Euclidean ($L_2$) norm** across all weight tensors: + $$\text{norm}(\Delta w) = \sqrt{\sum_{l=1}^{L} \|\Delta w_l\|_F^2}$$ + Conversely, `Trainer` passes `Repeat(bftClippingRadius).take(numLayers)` into `privacy.clipNorm` (`discojs/src/privacy.ts`), which clips **each layer's Frobenius norm individually** to `bftClippingRadius`. +3. **Conflated `applyOptimalPrivacy` helper:** `applyOptimalPrivacy` in `discojs/src/training/trainer.ts` is invoked even when Differential Privacy is disabled, coupling ALDP-FL adaptive noise calibration with unconditional client update clipping. + +### 2.3. Monolithic `Trainer` State and Duplicated Round Lifecycle + +`Trainer` (`discojs/src/training/trainer.ts`) violates the Open-Closed Principle by accumulating private fields and lifecycle branches for each feature: + +- `#privacy`, `#bftClippingRadius`, `#weightNormHistory`, and `#previousRoundWeights` are hardcoded directly on `Trainer`. +- Every new client-side algorithm (e.g., FedProx, SCAFFOLD control variates, FedNova step counters) forces additional private fields, constructor checks, and round-boundary branches into `Trainer`. +- **Duplicated round loops:** `#runRoundsByEpoch` / `#runRoundByEpoch` and `#runRoundsByIteration` / `#runRoundByIteration` duplicate round-begin communication, `#previousRoundWeights` tensor cloning, pre-aggregation validation, and `#finishRoundCommunication` invocation. + +### 2.4. `Model` Contract Limitations and Trainable vs. Non-Trainable Weights + +The `Model` abstraction (`discojs/src/models/model.ts`) and its implementations (`TFJS` in `discojs/src/models/tfjs.ts` and `GPT` in `discojs/src/models/implementations/gpt/gpt.ts`) have three architectural gaps when supporting custom local training algorithms: + +1. **`Model.weights` mixes trainable parameters with non-trainable state:** + In TensorFlow.js (`tf.LayersModel`), `this.model.weights` includes both `trainableWeights` (kernels, biases) and `nonTrainableWeights` (such as `BatchNormalization`'s `moving_mean` and `moving_variance`). While serialization and aggregation need all `weights`, local objective regularizers (such as FedProx's $\frac{\mu}{2}\|w - w^{(t)}\|^2$) must operate strictly on **trainable parameters**. Computing proximal penalties over `Model.weights` during training mode (`{ training: true }`) includes running-statistic drift in the scalar loss and performs unnecessary tensor operations on non-trainable buffers every batch. +2. **No backend-agnostic contract for local training modifications:** + `Model.train(trainingDataset, validationDataset)` has no declarative way to receive intra-round training modifiers (such as proximal anchor weights or gradient correction terms) without leaking `@tensorflow/tfjs` types into `model.ts`. +3. **Divergent custom training loops across model backends:** + - Standard `TFJS` training delegates to `this.model.fit(xs, ys)`. + - Custom regularized training in `TFJS` requires a custom `optimizer.minimize` loop that must faithfully replicate `tf.LayersModel`'s training behavior (`{ training: true }` forward pass for `Dropout`/`BatchNormalization`, `this.model.calculateLosses()` for layer regularizers, `this.model.trainableWeights` variable filtering, and compiled loss/metric resolution). + - Iteration-based training for `GPT` relies on an unsafe cast (`this.model as unknown as IterationTrainableTextModel`) in `Trainer` instead of a typed method on `Model`. + +### 2.5. Schema & Strategy Duplication Across Packages + +Strategy identifiers and parameter schemas are currently repeated across: + +- `discojs/src/task/training_information.ts` (`networkToSchema.decentralized`, `networkToSchema.federated`, `networkToSchema.local`) +- `cli/src/args.ts` (CLI strategy set, parameter parsing, and scheme validation `switch` statements) +- `webapp/src/components/task_creation_form/TaskCreationForm.vue` (re-declared `nonLocalNetworkSchema`, `trainingInformationNetworks`, and `