TensorFlow Distributed Training
TensorFlow distributed training refers to the technique of using multiple machines or computing devices (such as GPU/TPU) working together to jointly complete model training tasks. Through distributed training, we can:
- Accelerate the model training process
- Handle extremely large datasets
- Train complex models with huge parameter counts
Core Concepts
1. Distribution Strategy
TensorFlow provides multiple distribution strategies:
Example
Common distribution strategies
strategy
=
tf.
distribute
.
MirroredStrategy
(
)
Single machine, multiple GPUs
strategy
=
tf.
distribute
.
MultiWorkerMirroredStrategy
(
)
Multiple machines, multiple GPUs
strategy
=
tf.
distribute
.
TPUStrategy
(
)
TPU clusters
strategy
=
tf.
distribute
.
ParameterServerStrategy
(
)
Parameter server architecture
2. Data parallelism vs model parallelism
| Type | Data parallelism | Model parallelism |
|---|---|---|
| Principle | Each device processes different data batches | The model is split across different devices |
| Advantages | Simple to implement, suitable for most scenarios | Suitable for extremely large models |
| Disadvantages | Requires gradient synchronization | Complex to implement |
3. Synchronous update vs asynchronous update
- Synchronous update: All devices update the model uniformly after completing computation
- Asynchronous update: Devices compute and update independently, no waiting required
Implementation Steps
1. Set up the distributed environment
Example
import
tensorflow
as
tf
Initialize the distribution strategy
strategy
=
tf.
distribute
.
MirroredStrategy
(
)
Check the number of available devices
(
f
"Number of devices: {strategy.num_replicas_in_sync}"
)
2. Build the model within the strategy scope
Example
with
strategy.
scope
(
)
:
All variables defined within this scope will be mirrored to all devices
model
=
tf.
keras
.
Sequential
(
[
tf.
keras
.
layers
.
Dense
(
128
,
activation
=
'relu'
)
,
tf.
keras
.
layers
.
Dense
(
10
)
]
)
model.
compile
(
optimizer
=
'adam'
,
loss
=
tf.
keras
.
losses
.
SparseCategoricalCrossentropy
(
from_logits
=
True
)
,
metrics
=
[
'accuracy'
]
)
3. Prepare a distributed dataset
Example
Load the dataset
dataset
=
tf.
data
.
Dataset
.
from_tensor_slices
(
(
x_train
,
y_train
)
)
Batch and shard
batch_size
=
64
- strategy.
num_replicas_in_sync
Adjust batch size according to the number of devices
dataset
=
dataset.
shuffle
(
buffer_size
=
10000
)
.
batch
(
batch_size
)
4. Train the model
Example
Regular training approach
model.
fit
(
dataset
,
epochs
=
10
)
Advanced configuration
1. Multi-machine configuration
Example
Set the TF_CONFIG environment variable on each worker node
import
json
import
os
os
.
environ
[
'TF_CONFIG'
]
=
json.
dumps
(
{
'cluster'
:
{
'worker'
:
[
"worker1.example.com:12345"
,
"worker2.example.com:23456"
]
}
,
'task'
:
{
'type'
:
'worker'
,
'index'
:
0
}
Each worker has a different index
}
)
2. Custom training loop
Example
@
tf.
function
def
train_step
(
inputs
)
:
x
,
y
=
inputs
with
tf.
GradientTape
(
)
as
tape:
predictions
=
model
(
x
,
training
=
True
)
loss
=
loss_object
(
y
,
predictions
)
gradients
=
tape.
gradient
(
loss
,
model.
trainable_variables
)
optimizer.
apply_gradients
(
zip
(
gradients
,
model.
trainable_variables
)
)
return
loss
Distributed training steps
@
tf.
function
def
distributed_train_step
(
dataset_inputs
)
:
per_replica_losses
=
strategy.
run
(
train_step
,
args
=
(
dataset_inputs
,
)
)
return
strategy.
reduce
(
tf.
distribute
.
ReduceOp
.
SUM
,
per_replica_losses
,
axis
=
None
)
Performance optimization tips
- Batch size adjustment: Total batch size = per-device batch size × number of devices
- Data preprocessing: When using
dataset.prefetch()anddataset.cache()Improve data loading efficiency - Gradient compression: For cross-device communication, consider using gradient compression to reduce bandwidth requirements
- Mixed-precision training: Combine with
tf.keras.mixed_precisionIncrease training speed
Example
Mixed precision example
policy
=
tf.
keras
.
mixed_precision
.
Policy
(
'mixed_float16'
)
tf.
keras
.
mixed_precision
.
set_global_policy
(
policy
)
Common Problem Solutions
1. Out of memory
- Reduce per-device batch size
- Use gradient accumulation techniques
- Enable memory growth option
Example
gpus
=
tf.
config
.
experimental
.
list_physical_devices
(
'GPU'
)
for
gpu
in
gpus:
tf.
config
.
experimental
.
set_memory_growth
(
gpu
,
True
)
2. Inter-device communication bottleneck
- Use
NCCLImplement as cross-device communication - Consider reducing synchronization frequency (appropriately increasing update steps)
Example
Configure communication implementation
os
.
environ
[
'TF_GPU_ALLOCATOR'
]
=
'cuda_malloc_async'
os
.
environ
[
'TF_FORCE_GPU_ALLOW_GROWTH'
]
=
'true'
Practical Exercise
Exercise 1: Single-machine multi-GPU training
- Prepare a simple CNN model
- Use
MirroredStrategyTrain the CIFAR-10 dataset on multiple local GPUs - Compare the training speed difference between single and multiple GPUs
Exercise 2: Multi-machine configuration simulation
- Use
MultiWorkerMirroredStrategy - Simulate a multi-worker environment on the same machine (via different ports)
- Observe logs to understand the coordination process among workers