如果使用多GPU训练模型,推荐使用内置fit方法,较为方便,仅需添加2行代码。
在Colab笔记本中:修改->笔记本设置->硬件加速器 中选择 GPU
注:以下代码只能在Colab 上才能正确执行。
https://colab.research.google.com/drive/1j2kp_t0S_cofExSN7IyJ4QtMscbVlXU-
MirroredStrategy过程简介:
- 训练开始前,该策略在所有 N 个计算设备上均各复制一份完整的模型;
- 每次训练传入一个批次的数据时,将数据分成 N 份,分别传入 N 个计算设备(即数据并行);
- N 个计算设备使用本地变量(镜像变量)分别计算自己所获得的部分数据的梯度;
- 使用分布式计算的 All-reduce 操作,在计算设备间高效交换梯度数据并进行求和,使得最终每个设备都有了所有设备的梯度之和;
- 使用梯度求和的结果更新本地变量(镜像变量);
- 当所有设备均更新本地变量后,进行下一轮训练(即该并行策略是同步的)。
tensorflow_version 2.x import tensorflow as tf print(tf.__version__) from tensorflow.keras import * # 此处在colab上使用1个GPU模拟出两个逻辑GPU进行多GPU训练 gpus = tf.config.experimental.list_physical_devices('GPU'if gpus: 设置两个逻辑GPU模拟多GPU训练 try: tf.config.experimental.set_virtual_device_configuration(gpus[0],[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024),tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)]) logical_gpus = tf.config.experimental.list_logical_devices() print(len(gpus),"Physical GPU,",len(logical_gpus),1)">Logical GPUs") except RuntimeError as e: print(e)