tensorflow使用horovod進行多gpu訓練


tensorflow使用horovod多gpu訓練

要使用Horovod,在程序中添加以下內容。此示例使用TensorFlow。

  1. 運行hvd.init()

 

  1. 使用固定服務器GPU,以供此過程使用config.gpu_options.visible_device_list

    通過每個進程一個GPU的典型設置,您可以將其設置為local rank在這種情況下,服務器上的第一個進程將被分配第一GPU,第二個進程將被分配第二GPU,依此類推。

 

  1. 通過工人人數來衡量學習率

    同步分布式培訓中的有效批處理規模是根據工人人數來衡量的。學習率的提高彌補了批量大小的增加。

 

  1. 將優化器包裝在中hvd.DistributedOptimizer

    分布式優化器將梯度計算委派給原始優化器,使用allreduceallgather對梯度平均,然后應用這些平均梯度。

 

  1. 添加hvd.BroadcastGlobalVariablesHook(0)到播放初始變量狀態從0級到所有其他進程

    當使用隨機權重開始訓練或從檢查點恢復訓練時,這是確保所有工人進行一致初始化的必要步驟。另外,如果您不使用MonitoredTrainingSession,則可以hvd.broadcast_global_variables在初始化全局變量之后執行op。

 

  1. 修改您的代碼以僅在工作程序0上保存檢查點,以防止其他工作程序破壞它們

    通過傳遞checkpoint_dir=Nonetf.train.MonitoredTrainingSessionif 完成此操作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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM