Using multiple GPUs helps train machine learning models faster by sharing the work. It lets you handle bigger data and more complex models efficiently.
Multi-GPU training basics in TensorFlow
import tensorflow as tf strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = tf.keras.Sequential([...]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(train_data, epochs=5)
tf.distribute.MirroredStrategy() automatically copies your model on each GPU and keeps them in sync.
All model creation and compilation must happen inside strategy.scope() to use multiple GPUs.
strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='relu'), tf.keras.layers.Dense(2, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
strategy = tf.distribute.MirroredStrategy(devices=['/GPU:0', '/GPU:1']) with strategy.scope(): model = tf.keras.Sequential([...]) model.compile(...) model.fit(train_data, epochs=3)
This code trains a simple model on random data using all available GPUs. It shows how to set up the strategy, build the model inside the scope, and train it.
import tensorflow as tf import numpy as np # Create dummy data x_train = np.random.random((1000, 20)).astype('float32') y_train = np.random.randint(0, 2, 1000) # Setup multi-GPU strategy strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = tf.keras.Sequential([ tf.keras.layers.Dense(64, activation='relu', input_shape=(20,)), tf.keras.layers.Dense(2, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Train the model history = model.fit(x_train, y_train, epochs=3, batch_size=32) # Print final accuracy print(f"Final training accuracy: {history.history['accuracy'][-1]:.4f}")
Make sure your system has multiple GPUs and TensorFlow can detect them with tf.config.list_physical_devices('GPU').
Batch size should be large enough to split across GPUs; otherwise, speedup may be limited.
Multi-GPU training works best when the model and data are large enough to benefit from parallelism.
Multi-GPU training uses tf.distribute.MirroredStrategy() to run your model on several GPUs at once.
Build and compile your model inside the strategy scope to enable multi-GPU support.
This approach speeds up training and allows bigger models or datasets to be handled efficiently.
Practice
tf.distribute.MirroredStrategy() in TensorFlow?Solution
Step 1: Understand the role of MirroredStrategy
tf.distribute.MirroredStrategy()is designed to distribute training across multiple GPUs to speed up the process.Step 2: Compare options with the purpose
Options A, B, and C do not relate to multi-GPU training. Only training a model on multiple GPUs simultaneously correctly states the purpose.Final Answer:
To train a model on multiple GPUs simultaneously -> Option AQuick Check:
Multi-GPU training = MirroredStrategy usage [OK]
- Thinking it reduces dataset size
- Confusing with CPU-only training
- Assuming it changes model saving format
Solution
Step 1: Identify correct usage of strategy.scope()
Model building and compiling must happen insidestrategy.scope()to enable multi-GPU support.Step 2: Check each option for correct order
Onlystrategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = build_model()builds the model inside the strategy scope. Others build or compile outside, which disables multi-GPU benefits.Final Answer:
strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = build_model() -> Option BQuick Check:
Build model inside strategy.scope() =strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = build_model()[OK]
- Building model before strategy.scope()
- Compiling model outside strategy.scope()
- Calling fit before defining strategy
strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
import numpy as np
inputs = np.random.random((64, 20))
predictions = model.predict(inputs)
print(predictions.shape)Solution
Step 1: Understand batch size and MirroredStrategy behavior
MirroredStrategy splits the batch across GPUs internally but the output predictions shape matches the input batch size.Step 2: Check model output shape
The model outputs 10 classes per input. Input batch size is 64, so output shape is (64, 10).Final Answer:
(64, 10) -> Option DQuick Check:
Output shape = (batch_size, classes) = (64, 10) [OK]
- Multiplying batch size by number of GPUs
- Confusing output shape dimensions
- Assuming output shape is (10, 64)
RuntimeError: tf.distribute.MirroredStrategy() must be used with model creation inside its scope. What is the likely mistake?
strategy = tf.distribute.MirroredStrategy()
model = build_model()
with strategy.scope():
model.compile(optimizer='adam', loss='mse')Solution
Step 1: Analyze error message and code
The error says model creation must be inside strategy.scope(). Here, model is built before entering the scope.Step 2: Identify correct fix
Building the model inside the scope fixes the error. Compiling inside scope is correct.Final Answer:
Model was built outside the strategy.scope() -> Option CQuick Check:
Build model inside scope to avoid RuntimeError [OK]
- Building model before strategy.scope()
- Thinking compile() causes error
- Blaming optimizer choice
Solution
Step 1: Apply MirroredStrategy correctly
Usetf.distribute.MirroredStrategy()and build/compile the model inside its scope to enable multi-GPU training.Step 2: Adjust batch size for efficiency
Increasing batch size inmodel.fit()leverages multiple GPUs to handle larger data efficiently.Final Answer:
Use tf.distribute.MirroredStrategy(), build and compile the model inside its scope, then increase batch size in model.fit() -> Option AQuick Check:
Build inside scope + increase batch size = efficient multi-GPU training [OK]
- Building model outside strategy scope
- Not increasing batch size to use GPUs fully
- Manually averaging weights instead of using MirroredStrategy
Ready to prove it?
Pass the test and this pattern moves unknown
