Skip to content

Commit 45bbc6e

Browse files
authored
Merge pull request #5 from PaddlePaddle/develop
keep update
2 parents 8634ecc + f01477b commit 45bbc6e

File tree

378 files changed

+22129
-17018
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

378 files changed

+22129
-17018
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
11
.vscode/
2+
/doc/fluid/menu.zh.json
3+
/doc/fluid/menu.en.json
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
.. _api_guide_cpu_training_best_practice:
22

3-
##################
3+
####################
44
分布式CPU训练最佳实践
5-
##################
5+
####################
66

77
提高CPU分布式训练的训练速度,主要要从两个方面来考虑:
88
1)提高训练速度,主要是提高CPU的使用率;2)提高通信速度,主要是减少通信传输的数据量。
@@ -46,7 +46,7 @@ API详细使用方法参考 :ref:`cn_api_fluid_ParallelExecutor` ,简单实例
4646
提高通信速度
4747
==========
4848

49-
要减少通信数据量,提高通信速度,主要是使用稀疏更新 ,目前支持 `稀疏更新 <../distributed/sparse_update.html>`_ 的主要是 :ref:`cn_api_fluid_layers_embedding` 。
49+
要减少通信数据量,提高通信速度,主要是使用稀疏更新 ,目前支持 :ref:`api_guide_sparse_update` 的主要是 :ref:`cn_api_fluid_layers_embedding` 。
5050

5151
.. code-block:: python
5252
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
.. _api_guide_cpu_training_best_practice_en:
2+
3+
######################################################
4+
Best practices of distributed training on CPU
5+
######################################################
6+
7+
To improve the training speed of CPU distributed training, we must consider two aspects:
8+
9+
1. Improve the training speed mainly by improving utilization rate of CPU;
10+
2. Improve the communication speed mainly by reducing the amount of data transmitted in the communication.
11+
12+
Improve CPU utilization
13+
=============================
14+
15+
The CPU utilization mainly depends on :code:`ParallelExecutor`, which can make full use of the computing power of multiple CPUs to speed up the calculation.
16+
17+
For detailed API usage, please refer to :ref:`api_fluid_ParallelExecutor` . A simple example:
18+
19+
.. code-block:: python
20+
21+
# Configure the execution strategy, mainly to set the number of threads
22+
exec_strategy = fluid.ExecutionStrategy()
23+
exec_strategy.num_threads = 8
24+
25+
# Configure the composition strategy, for CPU training, you should use the Reduce mode for training.
26+
build_strategy = fluid.BuildStrategy()
27+
if int(os.getenv("CPU_NUM")) > 1:
28+
build_strategy.reduce_strategy=fluid.BuildStrategy.ReduceStrategy.Reduce
29+
30+
pe = fluid.ParallelExecutor(
31+
use_cuda=False,
32+
loss_name=avg_cost.name,
33+
main_program=main_program,
34+
build_strategy=build_strategy,
35+
exec_strategy=exec_strategy)
36+
37+
Among the parameters above:
38+
39+
- :code:`num_threads` : the number of threads used by the model training. It is preferably close to the number of the physical CPU cores of the machine where the training is performed.
40+
- :code:`reduce_strategy` : For CPU training, you should choose fluid.BuildStrategy.ReduceStrategy.Reduce
41+
42+
43+
Configuration of general environment variables:
44+
45+
- :code:`CPU_NUM`: The number of replicas of the model, preferably the same as num_threads
46+
47+
48+
Improve communication speed
49+
==============================
50+
51+
To reduce the amount of communication data and improve communication speed is achieved mainly by using sparse updates, the current support for `sparse update <../layers/sparse_update_en.html>`_ is mainly :ref:`api_fluid_layers_embedding`.
52+
53+
.. code-block:: python
54+
55+
data = fluid.layers.data(name='ids', shape=[1], dtype='int64')
56+
fc = fluid.layers.embedding(input=data, size=[dict_size, 16], is_sparse=True)
57+
58+
Among the parameters above:
59+
60+
- :code:`is_sparse`: Use sparse updates to configure embedding. If the dict_size of embedding is large but the number of data are very small each time, it is recommended to use the sparse update method.
Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
.. _best_practice_dist_training_gpu:
2+
3+
#####################
4+
分布式GPU训练最佳实践
5+
#####################
6+
7+
开始优化您的GPU分布式训练任务
8+
-------------------------
9+
10+
PaddlePaddle Fluid可以支持在现代GPU [#]_ 服务器集群上完成高性能分布式训练。
11+
通常可以通过以下方法优化在多机多卡环境训练性能,建议在进行性能优化时,
12+
检查每项优化点并验证对应提升,最终获得最优性能。
13+
14+
一个简单的验证当前的训练程序是否需要进一步优化性能的方法,
15+
是查看GPU的计算利用率 [#]_ ,通常用 :code:`nvidia-smi`命令查看。
16+
如果GPU利用率较低,则可能存在较大的优化空间。
17+
18+
下列表格中列出本文将介绍的所有可优化点的概述:
19+
20+
可配置项一览
21+
++++++++++
22+
23+
.. csv-table:: GPU分布式训练性能调节项
24+
:header: "调节项", "可选值说明", "配置方法"
25+
:widths: 3, 3, 5
26+
27+
"通信模式", "pserver模式;NCCL2模式(collective [#]_ )", "配置方法参考: `这里 <../../user_guides/howto/training/cluster_howto.html#permalink-8--nccl2->`_ "
28+
"执行模式", "单进程;单进程ParallelGraph;多进程", "配置方法参考: `这里 <../../user_guides/howto/training/cluster_howto.html#permalink-9--nccl2->`_ "
29+
"同步AllReduce操作", "开启则使每次调用等待AllReduce同步", "设置环境变量 :code:`FLAGS_sync_nccl_allreduce`"
30+
"CPU线程数", "int值,配置使用的CPU线程数", "参考本片后续说明"
31+
"预先分配足够的显存", "0~1之间的float值,预先分配显存的占比", "设置环境变量 :code:`FLAGS_fraction_of_gpu_memory_to_use`"
32+
"scope drop频率", "int值,设置每隔N个batch的迭代之后执行一次清理scope", "设置 :code:`fluid.ExecutionStrategy().num_iteration_per_drop_scope`"
33+
"fetch频率", "代码配置", "参考本片后续说明"
34+
"启用RDMA多机通信", "如果机器硬件支持,可以选择开启RDMA支持", "配置环境变量 :code:`NCCL_IB_DISABLE` "
35+
"使用GPU完成部分图片预处理", "代码配置", "参考本片后续说明"
36+
"设置通信频率(batch merge)", "代码配置", "参考本片后续说明"
37+
"优化reader性能", "代码优化", "参考本片后续说明"
38+
"混合精度", "FP32训练;混合FP32,FP16训练(在V100下启用TensorCore)", "参考项目:`图像分类 <https://github.com/PaddlePaddle/models/tree/develop/fluid/PaddleCV/image_classification>`_ "
39+
40+
41+
选择通信模式和执行模式
42+
+++++++++++++++++++
43+
44+
GPU分布式训练场景,使用多进程+NCCL2模式(collective)通常可以获得最好的性能。参考 `这里 <../../user_guides/howto/training/cluster_howto.html#permalink-8--nccl2->`_ 配置您的程序使用多进程NCCL2模式训练。
45+
46+
在进程模式下,每台服务器的每个GPU卡都会对应启动一个训练进程,
47+
集群中的所有进程之间会互相通信完成训练。以此方式最大限度的降低进程内部资源抢占的开销。
48+
对比在单进程开启ParallelGraph方法,多进程模式不但可以获得更高性能,
49+
而且无需考虑reader在多卡下io性能不足的问题,直接使用多进程提升数据读取IO效率。
50+
51+
使用ParallelGraph模式相对而言会减少多进程管理,并提升性能,而且可以无需修改代码,只需要开启下列开关即可:
52+
53+
.. code-block:: bash
54+
:linenos:
55+
56+
export FLAGS_enable_parallel_graph=1
57+
58+
如果是单机多卡模式,同样可以通过开启ParallelGraph来提升性能:
59+
60+
.. code-block:: bash
61+
:linenos:
62+
63+
export FLAGS_enable_parallel_graph=1
64+
export FLAGS_sync_nccl_allreduce=1
65+
66+
注:在单机多卡ParallelGraph模式下,
67+
配置 :code:`FLAGS_sync_nccl_allreduce=1` 让每次allreduce操作都等待完成,可以提升性能,
68+
详细原因和分析可以参考:https://github.com/PaddlePaddle/Paddle/issues/15049
69+
70+
71+
设置合适的CPU线程数
72+
+++++++++++++++++
73+
74+
PaddlePaddle Fluid使用“线程池” [#]_ 模型调度并执行Op,Op在启动GPU计算之前,
75+
通常需要CPU的协助,然而如果Op本身占用时间很小,“线程池”模型下又回带来额外的调度开销。
76+
使用多进程模式时,如果神经网络的计算图 [#]_ 节点间有较高的并发度,
77+
即使每个进程只在一个GPU上运行,使用多个线程可以更大限度的提升GPU利用率。
78+
这项配置需要根据运行模型的情况来配置,通常在多进程模式,设置线程数为1和4,
79+
然后观察是否存在提升,然后逐步调整此项配置。设置CPU线程数的方法参考:
80+
81+
.. code-block:: python
82+
:linenos:
83+
84+
exe_st = fluid.ExecutionStrategy()
85+
exe_st.num_threads = 1
86+
exe = fluid.ParallelExecutor(
87+
True,
88+
avg_loss.name,
89+
main_program=train_prog,
90+
exec_strategy=exe_st,
91+
num_trainers=num_trainers,
92+
trainer_id=trainer_id)
93+
94+
95+
预先分配足够的显存
96+
+++++++++++++++
97+
98+
通过设置环境变量 :code:`FLAGS_fraction_of_gpu_memory_to_use=0.95` 设置预先分配的显存占比,
99+
比如0.95是指95%的显存会预先分配。设置的范围是0.0~1.0。注意,
100+
设置成0.0会让每次显存分配都调用 :code:`cudaMalloc` 这样会极大的降低训练性能。
101+
102+
降低scope drop频率和fetch频率
103+
+++++++++++++++++++++++++++
104+
105+
减少scope drop和fetch频率,可以减少频繁的变量内存申请、释放和拷贝,
106+
从而提升性能。配置这两项的方法参考下面代码:
107+
108+
.. code-block:: python
109+
:linenos:
110+
111+
exe_st = fluid.ExecutionStrategy()
112+
strategy.num_iteration_per_drop_scope = 30
113+
exe = fluid.ParallelExecutor(
114+
True,
115+
avg_loss.name,
116+
main_program=train_prog,
117+
exec_strategy=exe_st,
118+
num_trainers=num_trainers,
119+
trainer_id=trainer_id)
120+
for pass_id in xrange(PASS_NUM):
121+
batch_id = 0
122+
while True:
123+
if batch_id % 30 == 0:
124+
fetched = exe.run(fetch_list)
125+
else:
126+
exe.run([])
127+
128+
129+
启用RDMA多机通信
130+
++++++++++++++
131+
132+
在使用NCCL2模式训练时,其会默认尝试开启RDMA通信,如果系统不支持,
133+
则会自动降级为使用TCP通信。
134+
可以通过打开环境变量 :code:`NCCL_DEBUG=INFO` 查看NCCL是否选择了开启RDMA通信。
135+
如果需要强制使用TCP方式通信,可以设置 :code:`NCCL_IB_DISABLE=1` 。
136+
137+
138+
使用GPU完成部分图片预处理
139+
++++++++++++++++++++++
140+
141+
如果可能,使用GPU完成可以部分数据预处理,比如图片Tensor的归一化:
142+
143+
.. code-block:: python
144+
:linenos:
145+
146+
image = fluid.layers.data()
147+
img_mean = fluid.layers.create_global_var([3, 1, 1], 0.0, "float32", name="img_mean", persistable=True)
148+
img_std = fluid.layers.create_global_var([3, 1, 1], 0.0, "float32", name="img_std", persistable=True)
149+
t1 = fluid.layers.elementwise_sub(image / 255.0, img_mean, axis=1)
150+
image = fluid.layers.elementwise_div(t1, img_std, axis=1)
151+
152+
对输入的图片Tensor,使用 :code:`fluid.layers` 完成图片数据归一化预处理,
153+
这样可以减轻CPU预处理数据的负担,提升总体训练速度。
154+
155+
增大batch_size或使用设置通信频率(batch merge)
156+
++++++++++++++++++++++++++++++++++++++++++
157+
158+
分布式同步训练,跨界点通信或多或少会带来性能影响,增大训练的batch_size,
159+
可以保持通信开销不变的情况下,增大计算吞吐从而降低通信在整个训练过程中的占比来提升总体的训练吞吐。
160+
161+
然而增大batch_size会带来同等比例的显存消耗提升,为了进一步的增大batch_size,Fluid提供“batch merge”功能,
162+
通过在一个GPU上串行计算多个小的batch并积累梯度,然后再执行多机多卡之间的通信,
163+
此模式同样也可以被称为“可变通信频率“。使用batch merge功能,在同样的模型,
164+
可以极大的增加batch size,提升多机训练的总吞吐。
165+
使用方法可以参考实例:https://github.com/PaddlePaddle/models/tree/develop/fluid/PaddleCV/image_classification/dist_train
166+
167+
168+
优化reader性能
169+
+++++++++++++
170+
171+
数据读取的优化在GPU训练中至关重要,尤其在不断增加batch_size提升吞吐时,计算对reader性能会有更高对要求,
172+
优化reader性能需要考虑的点包括:
173+
174+
1. 使用 :code:`pyreader`
175+
参考 `这里 <../../user_guides/howto/prepare_data/use_py_reader.html>`_
176+
使用pyreader,并开启 :code:`use_double_buffer`
177+
2. reader返回uint8类型数据
178+
图片在解码后一般会以uint8类型存储,如果在reader中转换成float类型数据,会将数据体积扩大4倍。直接返回uint8数据,然后在GPU
179+
上转化成float类型进行训练
180+
3. reader pin memory
181+
reader读取的数据会在训练时组成batch,并从CPU拷贝到GPU上,如果在CPU上分配pin memory内存,这个拷贝过程可以通过硬件
182+
DMA完成拷贝提升性能。在使用pyreader的方式下,可以使用下面的实例代码开启pin memory batch reader:
183+
184+
.. code-block:: python
185+
:linenos:
186+
187+
def batch_feeder(batch_reader, pin_memory=True, img_dtype="uint8"):
188+
# batch((sample, label)) => batch(sample), batch(label)
189+
def _feeder():
190+
for batch_data in batch_reader():
191+
sample_batch = []
192+
label_batch = []
193+
for sample, label in batch_data:
194+
sample_batch.append(sample)
195+
label_batch.append([label])
196+
tensor = core.LoDTensor()
197+
label = core.LoDTensor()
198+
place = core.CUDAPinnedPlace() if pin_memory else core.CPUPlace()
199+
tensor.set(np.array(sample_batch, dtype=img_dtype, copy=False), place)
200+
label.set(np.array(label_batch, dtype="int64", copy=False), place)
201+
yield [tensor, label]
202+
return _feeder
203+
pyreader.decorate_tensor_provider(
204+
batch_feeder(
205+
paddle.batch(rd, batch_size=batch_size_per_gpu),
206+
pin_memory=True,
207+
img_dtype='uint8'
208+
)
209+
)
210+
211+
4. 减少reader初始化时间 (infinite read)
212+
在训练任务开始执行第一轮训练时,reader开始异步的,不断的从磁盘或其他存储中读取数据并执行预处理,然后将处理好的数据
213+
填充到队列中供计算使用。从0开始填充这个队列直到数据可以源源不断供给计算,需要一定时间的预热。所以,如果每轮训练
214+
都重新填充队列,会产生一些时间的开销。所以,在使用pyreader时,可以让reader函数不断的产生数据,直到训练循环手动break:
215+
216+
.. code-block:: python
217+
:linenos:
218+
219+
def infinite_reader(file_path):
220+
while True:
221+
with open(file_path) as fn:
222+
for line in fn:
223+
yield process(line)
224+
225+
def train():
226+
...
227+
for pass_id in xrange(NUM_PASSES):
228+
if pass_id == 0:
229+
pyreader.start()
230+
for batch_id in (iters_per_pass):
231+
exe.run()
232+
pyreader.reset()
233+
234+
235+
使用混合精度训练
236+
++++++++++++++
237+
238+
V100 GPU提供了 `Tensor Core <https://www.nvidia.com/en-us/data-center/tensorcore/>`_ 可以在混合精度计算
239+
场景极大的提升性能。使用混合精度计算的例子可以参考:
240+
https://github.com/PaddlePaddle/models/tree/develop/fluid/PaddleCV/image_classification#using-mixed-precision-training
241+
242+
目前Paddle只提供在两个模型(ResNet, BERT)的混合精度计算实现并支持static loss scaling,其他模型使用混合精度也
243+
可以参考以上的实现完成验证。
244+
245+
附录
246+
----
247+
248+
.. [#] 现代GPU:指至少支持运行 `CUDA <https://developer.nvidia.com/cuda-downloads>`_ 版本7.5以上的GPU
249+
.. [#] GPU利用率:这里指GPU计算能力被使用部分所占的百分比
250+
.. [#] Collective定义参考:https://en.wikipedia.org/wiki/Message_Passing_Interface#Collective_basics
251+
.. [#] https://en.wikipedia.org/wiki/Thread_pool
252+
.. [#] https://en.wikipedia.org/wiki/Data-flow_diagram
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#########
2+
最佳实践
3+
#########
4+
5+
.. toctree::
6+
:maxdepth: 1
7+
8+
cpu_train_best_practice.rst
9+
dist_training_gpu.rst
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
###############
2+
Best Practice
3+
###############
4+
5+
.. toctree::
6+
:hidden:
7+
8+
cpu_train_best_practice_en.rst

0 commit comments

Comments
 (0)