tensorflow使用horovod多gpu訓練
要使用Horovod,在程序中添加以下內容。此示例使用TensorFlow。
-
運行
hvd.init()
-
使用固定服務器GPU,以供此過程使用
config.gpu_options.visible_device_list
通過每個進程一個GPU的典型設置,您可以將其設置為local rank。在這種情況下,服務器上的第一個進程將被分配第一GPU,第二個進程將被分配第二GPU,依此類推。
-
通過工人人數來衡量學習率
同步分布式培訓中的有效批處理規模是根據工人人數來衡量的。學習率的提高彌補了批量大小的增加。
-
將優化器包裝在中
hvd.DistributedOptimizer
分布式優化器將梯度計算委派給原始優化器,使用allreduce或allgather對梯度求平均,然后應用這些平均梯度。
-
添加
hvd.BroadcastGlobalVariablesHook(0)
到播放初始變量狀態從0級到所有其他進程當使用隨機權重開始訓練或從檢查點恢復訓練時,這是確保所有工人進行一致初始化的必要步驟。另外,如果您不使用
MonitoredTrainingSession
,則可以hvd.broadcast_global_variables
在初始化全局變量之后執行op。
-
修改您的代碼以僅在工作程序0上保存檢查點,以防止其他工作程序破壞它們
通過傳遞
checkpoint_dir=None
給tf.train.MonitoredTrainingSession
if 來完成此操作。hvd.rank() != 0
簡單示例代碼
1 import tensorflow as tf 2 import horovod.tensorflow as hvd 3 4 5 # Initialize Horovod 6 hvd.init() 7 8 # Pin GPU to be used to process local rank (one GPU per process) 9 config = tf.ConfigProto() 10 config.gpu_options.visible_device_list = str(hvd.local_rank()) 11 12 # Build model... 13 loss = ... 14 opt = tf.train.AdagradOptimizer(0.01 * hvd.size()) 15 16 # Add Horovod Distributed Optimizer 17 opt = hvd.DistributedOptimizer(opt) 18 19 # Add hook to broadcast variables from rank 0 to all other processes during 20 # initialization. 21 hooks = [hvd.BroadcastGlobalVariablesHook(0)] 22 23 # Make training operation 24 train_op = opt.minimize(loss) 25 26 # Save checkpoints only on worker 0 to prevent other workers from corrupting them. 27 checkpoint_dir = '/tmp/train_logs' if hvd.rank() == 0 else None 28 29 # The MonitoredTrainingSession takes care of session initialization, 30 # restoring from a checkpoint, saving to a checkpoint, and closing when done 31 # or an error occurs. 32 with tf.train.MonitoredTrainingSession(checkpoint_dir=checkpoint_dir, 33 config=config, 34 hooks=hooks) as mon_sess: 35 while not mon_sess.should_stop(): 36 # Perform synchronous training. 37 mon_sess.run(train_op)