π Scaling Deep Learning Across Multiple GPUs and Clusters
As neural network architectures and datasets grow larger, single-GPU training becomes a major computational bottleneck. Distributed Training enables you to scale training across multiple GPUs on a single workstation or across entire compute clusters. TensorFlow simplifies this via `tf.distribute.Strategy`, allowing developers to scale model training with minimal code modifications.
1. Overview of Distribution Strategies
Comparing `MirroredStrategy`, `MultiWorkerMirroredStrategy`, and `ParameterServerStrategy` for different hardware topologies.
Distribution Strategies Matrix
TF.DISTRIBUTE STRATEGIES:
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
β STRATEGY β TOPOLOGY β PRIMARY USE CASE β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β `MirroredStrategy` β Synchronous training across β Single machine with multiple GPUs β
β β multiple GPUs on one machine. β (data parallelism). β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β `MultiWorkerMirrored` β Synchronous training across β Multi-machine cluster nodes β
β β multiple cluster machines. β (Enterprise / Cloud scale). β
ββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
Architectural Definition: `MirroredStrategy` implements synchronous data parallelism by replicating all model variables across each available GPU and averaging gradients across devices at every batch step.
2. The `MirroredStrategy` Workflow
How model construction and compilation must occur within the strategy scope `with strategy.scope():`.
Strategy Scope Pattern
STRATEGY SCOPE WORKFLOW:
1. Initialize Strategy: `strategy = tf.distribute.MirroredStrategy()`
2. Open Scope: `with strategy.scope():`
3. Build & Compile Model: Instantiate layers, models, and optimizers inside the scope block so variables are mirrored across GPUs.
4. Train Model: Execute `model.fit()` normally; TensorFlow automatically distributes batches across replicas.
Engineering Insight: Instantiating models inside `strategy.scope()` ensures that model weights and optimizer variables are correctly created and mirrored across all target accelerator devices.
3. Python Code Example: Multi-GPU Training with MirroredStrategy
A production Python script demonstrating how to configure `MirroredStrategy`, build a model within its scope, and train across multiple GPUs.
Python (distributed_training_demo.py)
import tensorflow as tf
from tensorflow.keras import layers, Sequential
def configure_distributed_training():
# 1. Initialize MirroredStrategy (detects available GPUs automatically)
strategy = tf.distribute.MirroredStrategy()
print(f"[*] Number of devices operating: {strategy.num_replicas_in_sync}")
# 2. Open strategy scope for model construction and compilation
with strategy.scope():
model = Sequential([
layers.Input(shape=(20,)),
layers.Dense(64, activation='relu'),
layers.Dense(32, activation='relu'),
layers.Dense(2, activation='softmax')
], name="distributed_mlp")
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
print("[+] Model built and compiled successfully within MirroredStrategy scope.")
# 3. Generate Synthetic Training Data
X_train = tf.random.normal(shape=(200, 20))
y_train = tf.random.uniform(shape=(200,), minval=0, maxval=2, dtype=tf.int32)
# 4. Train Model (Batches are automatically distributed across replicas)
print("\n[+] Starting distributed training across replicas...")
model.fit(X_train, y_train, epochs=2, batch_size=32, verbose=1)
print("[+] Distributed training session complete!")
if __name__ == "__main__":
configure_distributed_training()
Execution Output:
[*] Number of devices operating: 1
[+] Model built and compiled successfully within MirroredStrategy scope.
[+] Starting distributed training across replicas...
Epoch 1/2
7/7 [==============================] - 1s 6ms/step - loss: 0.7512 - accuracy: 0.4900
Epoch 2/2
7/7 [==============================] - 0s 2ms/step - loss: 0.6924 - accuracy: 0.5400
[+] Distributed training session complete!
4. Scaling Batch Size Across Replicas
Understanding global batch sizing when scaling across multiple GPUs and adjusting learning rates accordingly.
Global Batch Size Scaling
GLOBAL VS. PER-REPLICA BATCH SIZING:
- Global Batch Size: The total number of samples processed across all GPUs per step.
- Scaling Rule: When using $N$ GPUs, your global batch size is multiplied by $N$. If per-replica batch size is 32 across 4 GPUs, global batch size is $32 \times 4 = 128$.
- Learning Rate Adjustment: Scale initial learning rates proportionally with global batch size (e.g., Linear Scaling Rule: $LR = Base \cdot \frac{GlobalBatch}{256}$).
Strategic Insight: Scaling batch sizes across multiple GPUs requires proportional learning rate adjustments to maintain gradient descent convergence stability.
5. Best Practices for Distributed Training
Software engineering standards for structuring datasets, scope placement, and hardware utilization.
Distributed Training Best Practices Checklist
DISTRIBUTED TRAINING CHECKLIST:
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BEST PRACTICE β IMPLEMENTATION & OBJECTIVE β
ββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Scope Placement β Ensure model instantiation, compilation, and metric definitions occur strictlyβ
β β inside `with strategy.scope():`. β
ββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Use `tf.data` Datasets β Feed data using `tf.data.Dataset` pipelines so TensorFlow can automatically β
β β shard data across multiple GPU replicas. β
ββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Scale Batch Sizes β Adjust global batch sizes and learning rates proportionally to match your β
β β total GPU replica count. β
ββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Masterclass Rule: Feeding data via `tf.data.Dataset` pipelines allows TensorFlow to automatically shard batches across all active GPU replicas.
6. Chapter Summary & Next Steps
Reviewing distributed training and previewing model export and serving.
Chapter Review Checklist
CHAPTER REVIEW CHECKLIST:
1. `tf.distribute.MirroredStrategy` enables synchronous data parallelism across multiple GPUs on a single machine.
2. Model instantiation and compilation must occur strictly within `strategy.scope()`.
3. Feeding data through `tf.data.Dataset` enables automatic batch sharding across replicas.
4. Next Chapter: We cover Chapter 27 ("Model Deployment and Export: SavedModel, TensorFlow Lite, and ONNX").
Next Chapter Preview: In Chapter 27, we explore model deploymentβexamining how to serialize and export trained models using SavedModel, TensorFlow Lite, and ONNX for production serving.