Repository navigation
docs: collaborative training architecture design document #1298
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ale18V
wants to merge
29
commits into
main
Choose a base branch
from
docs/collaborative-training-architecture
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+378
−0
Open
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
7c58547
docs: add collaborative training architecture design document
ale18V 5dedee3
docs: refine architecture with unified TrainingHook and autograd loss…
ale18V 576ab30
docs: compare TFJS autograd hook options and clarify client-side clip…
ale18V c2c2f49
docs: present Section 3.3 TFJS hook options neutrally
ale18V 359900a
style: format TRAINING_ARCHITECTURE.md with Prettier
ale18V 9b93c7d
docs: unify aggregation and trainingStrategy schemas under { strategy…
ale18V b12f741
docs: reframe Section 4 as Future Extensions for protocol-level metadata
ale18V c7585b2
docs: separate high-level problem overview from code-level details in…
ale18V b598ecc
Revert "docs: separate high-level problem overview from code-level de…
ale18V f5509af
docs: keep Section 2 high-level and link issues #1300 and #1301 for s…
ale18V 12decc5
docs: expand Section 2.3 Trainer smells and round-loop duplication de…
ale18V 77787f6
docs: merge BFT/client-clipping coupling into Section 2.2 Trainer lim…
ale18V 3203fbc
Remove implementation plan and detail how 3.2 suggestion is similar t…
ale18V 7c048ac
style: format TRAINING_ARCHITECTURE.md with Prettier
ale18V 96af87d
docs: streamline design doc to conceptual level with collapsible mini…
ale18V 493577e
docs: keep Axis 3 as privacy only and note future updateTransforms/mo…
ale18V a06f769
Revert unrequested full-document rewrite back to 7c048acc
ale18V e12dba4
docs: shorten 3.1/3.2 snippets into collapsible axis blocks and bare …
ale18V 7e4814e
docs: tighten Section 2.1 to configuration conflation and remove over…
ale18V e990768
docs: remove non-architectural trainable-buffer bug from Section 2.3
ale18V 1100776
docs: move BFT/client-clipping coupling note into Section 2.1
ale18V be5472a
docs: move BFT/privacy coupling point into Section 2.1 bullet list
ale18V 759b310
docs: restructure Axis 2 as composable training object and fix paste …
ale18V eb05820
Deslop document and rewrite/correct some parts
ale18V 57b7473
docs: extract TFJS autograd integration options into TFJS_TRAINING_HO…
ale18V 2070549
Last refinements on the training architecuture doc
ale18V 62f6f12
docs: add Overview & Motivation to TFJS_TRAINING_HOOKS.md
ale18V 7d15f91
Polish hooks document
ale18V 02dadb0
style: format TRAINING_ARCHITECTURE.md with Prettier
ale18V File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| # TensorFlow.js Integration for `TrainingHook` | ||
|
|
||
| Companion document to [TRAINING_ARCHITECTURE.md](./TRAINING_ARCHITECTURE.md#33-backend-agnostic-model-boundary). | ||
|
|
||
| ## Overview & Motivation | ||
|
|
||
| The [target architecture](./TRAINING_ARCHITECTURE.md) introduces a `TrainingHook` lifecycle so collaborative algorithms—such as FedProx loss regularization, gradient clipping, or SCAFFOLD—can participate in local training without adding algorithm-specific branches to `Trainer` or `Model`. | ||
|
|
||
| In Disco today, both model implementations (`TFJS` and `GPT`) are backed by TensorFlow.js, yet they run local training differently: | ||
|
|
||
| - **`TFJS`** delegates batches to `tf.LayersModel.fit()`, which hides the forward/backward pass and optimizer step behind Keras-style configuration. | ||
| - **`GPT`** already runs an explicit `optimizer.computeGradients` $\rightarrow$ `applyGradients` loop. | ||
|
|
||
| In Python TensorFlow/Keras, an `addLoss` API is available to attach regularizers dynamically and still train with `model.fit()`. However, TensorFlow.js does not provide equivalent model-level `addLoss` support during `model.fit()`. Any integration must therefore connect `TrainingHook.computeLoss` (and, if needed, gradient transforms) into TensorFlow.js autograd while preserving the user's model architecture, base loss, and optimizer state. | ||
|
|
||
| ## Design Options | ||
|
|
||
| Below are three candidate mechanisms for wiring `TrainingHook` into `TFJS` and `GPT`, trading off `model.fit()` compatibility against uniformity and generality: | ||
|
|
||
| | Option | Mechanism | `TFJS` keeps `model.fit()`? | Modifies TFJS runtime API? | Supports gradient hooks (gradient clipping, SCAFFOLD)? | | ||
| | :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------: | :------------------------: | :---------------------------------------------------------------------: | | ||
| | **Option 1** | `TFJS` wraps the compiled loss via public `model.compile({ loss })`; `GPTModel` calls `hooks.computeLoss` directly in its existing `computeGradients` loop. | **Yes** | **No** | Loss hooks only (requires a separate path if a gradient hook is active) | | ||
| | **Option 2** | Both `TFJS` and `GPT` share one ~40-line `runTFJSStep` helper using `optimizer.computeGradients` $\rightarrow$ `transformGradients` $\rightarrow$ `applyGradients`. | **No** | **No** | **Yes** (uniformly for `TFJS` and `GPT`) | | ||
| | **Option 3** | Temporarily wrap `optimizer.computeGradients` on the `tf.Optimizer` instance for the duration of a round. | **Yes** | **Yes** | **Yes** (uniformly for `TFJS` and `GPT`) | | ||
|
|
||
| --- | ||
|
|
||
| ## Option 1: Public `model.compile({ loss })` in `TFJS` + Direct Call in `GPTModel` | ||
|
|
||
| - **How it works:** | ||
| - When no hook implements `computeLoss` (standard FedAvg, local training, Byzantine, DP), `TFJS` calls `this.model.fit(xs, ys, { epochs: 1, verbose: 0 })` completely untouched. | ||
| - When one or more hooks implement `computeLoss`, `TFJS` resolves the base loss function from `this.model.loss` (which may be a string identifier such as `"categoricalCrossentropy"` or a custom `LossOrMetricFn`) and wraps it via TFJS's public `model.compile(...)` API while passing the existing `this.model.optimizer` instance (in `@tensorflow/tfjs-layers`, passing a `tf.Optimizer` instance assigns `this.optimizer_ = args.optimizer` directly, preserving Adam moments and iteration count): | ||
| ```ts | ||
| const baseLossFn = resolveLossFn(this.model.loss); | ||
| this.model.compile({ | ||
| optimizer: this.model.optimizer, | ||
| loss: (yTrue: tf.Tensor, yPred: tf.Tensor) => { | ||
| let totalLoss = baseLossFn(yTrue, yPred).mean().asScalar(); | ||
| for (const hook of lossHooks) { | ||
| totalLoss = hook.computeLoss(totalLoss, getContext()); | ||
| } | ||
| return totalLoss; | ||
| }, | ||
| metrics: resolvedMetrics, | ||
| }); | ||
| ``` | ||
| - `GPTModel` (`discojs/src/models/implementations/gpt/model.ts`) already executes its own explicit `optimizer.computeGradients(...)` loop, so it invokes `hook.computeLoss(totalLoss, ctx)` directly inside that closure with no `compile` re-wrapping. | ||
| - **Pros:** | ||
| - Keeps `this.model.fit(xs, ys)` in the loop for `TFJS`, preserving TFJS's built-in handling of `{ training: true }`, `calculateLosses()`, compiled metrics, and tensor disposal. | ||
| - Uses only public TFJS APIs (no runtime method patching). | ||
| - **Cons:** | ||
| - Handles different cases differently (`TFJS` vs. `GPT`, and loss hooks vs. future gradient hooks), adding branching complexity. | ||
| - Only covers **loss-level** hooks inside `model.fit()`; supporting batch **gradient** hooks (`transformGradients`, e.g., gradient clipping or SCAFFOLD) on `TFJS` would still require a separate fallback step or migrating to Option 2. | ||
| - **`model.compile({ loss })` side effects in TFJS 4.22:** Recompiling with a closure `loss` requires explicitly resolving `metrics` and restoring the original `this.model.loss` before `evaluate()` or `serialize()`. Otherwise, `LayersModel.compile` resolves `"accuracy"` by checking `lossFunctions[i] === binaryCrossentropy` / `sparseCategoricalCrossentropy` by function identity (switching `"accuracy"` from `binaryAccuracy` to `categoricalAccuracy` on 2-unit `binaryCrossentropy` models such as `LUSClassifierModel`), `TFJS.serialize()` persists closure losses as `"loss": {}` in `trainingConfig` (breaking `deserialize()`), and `evaluate()` (`evaluateDataset`) includes training regularizers in validation loss. | ||
|
|
||
| --- | ||
|
|
||
| ## Option 2: Shared Explicit TFJS Training Step (`runTFJSStep`) for Both `TFJS` and `GPT` | ||
|
|
||
| - **How it works:** | ||
| - Because both `TFJS` and `GPT` wrap a `tf.LayersModel`, extract a single ~40-line helper that runs the autograd step directly for both models: | ||
|
|
||
| ```ts | ||
| const { value: loss, grads } = optimizer.computeGradients(() => { | ||
| const preds = tfModel.apply(xs, { training: true }) as tf.Tensor; | ||
| let totalLoss = computeDataLoss(ys, preds).mean().asScalar(); | ||
| for (const reg of tfModel.calculateLosses()) { | ||
| totalLoss = totalLoss.add(reg).asScalar(); | ||
| } | ||
| for (const hook of lossHooks) { | ||
| totalLoss = hook.computeLoss(totalLoss, ctx); | ||
| } | ||
| return totalLoss; | ||
| }, trainableVars); | ||
|
|
||
| let finalGrads = grads; | ||
| try { | ||
| for (const hook of gradHooks) { | ||
| finalGrads = hook.transformGradients(finalGrads, ctx); | ||
| } | ||
| optimizer.applyGradients(finalGrads); | ||
| } finally { | ||
| if (finalGrads !== grads) tf.dispose(finalGrads); | ||
| tf.dispose(grads); | ||
| } | ||
| ``` | ||
|
|
||
| - `TFJS` supplies its compiled loss + accuracy metric; `GPT` supplies next-token cross-entropy (+ optional Goldfish masking), its `AdamW` optimizer, and a global-norm clipping hook—allowing the `GPTModel.fitDataset` override and 1-batch-dataset indirection to be removed. | ||
|
|
||
| - **Pros:** | ||
| - Uses only public TFJS APIs (no runtime method patching). | ||
| - Handles training generically and uniformly across `TFJS` and `GPT` for both loss and batch gradient hooks (FedProx, gradient clipping, SCAFFOLD; note that true DP-SGD additionally requires per-sample microbatching rather than batch-averaged `transformGradients`). | ||
| - Reduces duplicated training-loop code by unifying `TFJS` and `GPTModel.fitDataset` around one step primitive. | ||
| - **Cons:** | ||
| - **Robustness trade-off for `TFJS`:** replacing `model.fit()` means Disco explicitly owns `{ training: true }` (Dropout/BatchNorm), `model.calculateLosses()` (layer L1/L2 regularizers), explicit `grads` / `finalGrads` tensor disposal, compiled loss lookup, and TFJS's 3-way `"accuracy"` metric dispatch (`binaryAccuracy` vs. `categoricalAccuracy` vs. `sparseCategoricalAccuracy`), which may be less battle-tested on exotic custom Keras models than `model.fit()`. | ||
|
|
||
| --- | ||
|
|
||
| ## Option 3: Scoped Runtime Wrapping of `optimizer.computeGradients` | ||
|
|
||
| - **How it works:** | ||
| - Temporarily reassign `layersModel.optimizer.computeGradients = ...` for the duration of a round via a `Disposable` scope, intercepting both `TFJS.model.fit()` (via `optimizer.minimize` $\rightarrow$ `computeGradients`) and `GPTModel.fitDataset()`. | ||
| - **Pros:** | ||
| - Keeps `model.fit()` untouched for `TFJS` while handling both `TFJS` and `GPT` (and both loss and batch gradient hooks) uniformly in one place. | ||
| - **Cons:** | ||
| - **API- and internals-dependent:** mutates a method on a `@tensorflow/tfjs-core` `tf.Optimizer` instance at runtime and relies on TFJS's internal call chain (`Sequential` vs. functional `LayersModel` optimizer forwarding, `minimize` $\rightarrow$ `computeGradients`). | ||
| - **Lifecycle fragility:** requires strict `try` / `finally` (or `using`) unwrapping so round aborts or mid-training errors never leave a stale hook wrapper attached to the optimizer instance. | ||
|
|
||
| --- | ||
|
|
||
| ## Critical TensorFlow.js Invariants (Relevant Across Options) | ||
|
|
||
| 1. **Multi-Client Process Isolation (`varList`):** | ||
| When calling `optimizer.computeGradients(f, varList)` directly (in `GPTModel` or Option 2), always pass `layersModel.trainableWeights.map(w => w.read() as tf.Variable)` rather than leaving `varList` undefined (which causes `tf.variableGrads` to sweep every registered `tf.Variable` in the global TFJS engine, including other clients' models in CLI simulations). | ||
| 2. **Interaction with `AdamW` and Gradient Clipping in `GPTModel`:** | ||
| In `discojs/src/models/implementations/gpt/optimizers.ts`, `AdamW` overrides `applyGradients` for decoupled weight decay, and `GPTModel` clips the global gradient norm between `computeGradients` and `applyGradients`. Adding `hooks.computeLoss` inside `computeGradients` guarantees that regularized gradients flow properly through global norm clipping and `AdamW`. | ||
| 3. **Trainable-Only Regularization:** | ||
| Hooks such as `FedProxHook` must compute penalties over `model.trainableWeights` (excluding non-trainable `BatchNormalization` moving statistics) so running-stat drift is never penalized. | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.