Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TensorFlow Distributed Training

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:

  1. Accelerate the model training process
  2. Handle extremely large datasets
  3. 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


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

print

(

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

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

  1. Batch size adjustment: Total batch size = per-device batch size × number of devices
  2. Data preprocessing: When using dataset.prefetch() and dataset.cache() Improve data loading efficiency
  3. Gradient compression: For cross-device communication, consider using gradient compression to reduce bandwidth requirements
  4. Mixed-precision training: Combine with tf.keras.mixed_precision Increase 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

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

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

  1. Prepare a simple CNN model
  2. Use MirroredStrategy Train the CIFAR-10 dataset on multiple local GPUs
  3. Compare the training speed difference between single and multiple GPUs

Exercise 2: Multi-machine configuration simulation

  1. Use MultiWorkerMirroredStrategy
  2. Simulate a multi-worker environment on the same machine (via different ports)
  3. Observe logs to understand the coordination process among workers