Skip to content

Commit d060a7f

Browse files
jamesbingabhinavarora
authored andcommitted
Update faq/local/index_en.rst (#9947)
* Update index_en.rst translation version 1.0 * Update index_en.rst
1 parent bfafcbe commit d060a7f

File tree

1 file changed

+245
-2
lines changed

1 file changed

+245
-2
lines changed

doc/v2/faq/local/index_en.rst

Lines changed: 245 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,248 @@
11
#############################
2-
Local Training and Prediction
2+
Parameter Setting
33
#############################
44

5-
TBD
5+
.. contents::
6+
7+
1. Reduce Memory Consumption
8+
-------------------
9+
10+
The training procedure of neural networks demands dozens of gigabytes of host memory or serval gigabytes of device memory, which is a rather memory consuming work. The memory consumed by PaddlePaddle framework mainly includes:
11+
\:
12+
13+
* Cache memory for DataProvider (only on host memory),
14+
* Memory for neurons' activation information (on both host memory and device memory),
15+
* Memory for parameters (on both host memory and device memory),
16+
* Other memory demands.
17+
18+
Other memory demands is mainly used to support the running demand of PaddlePaddle framework itself, such as string allocation,temporary variables, which are not considered currently.
19+
20+
Reduce DataProvider Cache Memory
21+
++++++++++++++++++++++++++
22+
23+
PyDataProvider works under asynchronous mechanism, it loads together with the data fetch and shuffle procedure in host memory:
24+
25+
.. graphviz::
26+
27+
digraph {
28+
rankdir=LR;
29+
Data Files -> Host Memory Pool -> PaddlePaddle Training
30+
}
31+
32+
Thus the reduction of the DataProvider cache memory can reduce memory occupancy, meanwhile speed up the data loading procedure before training. However, the size of the memory pool can actually affect the granularity of shuffle,which means a shuffle operation is needed before each data file reading process to ensure the randomness of data when try to reduce the size of the memory pool.
33+
34+
.. literalinclude:: src/reduce_min_pool_size.py
35+
36+
In this way, the memory consumption can be significantly reduced and hence the training procedure can be accelerated. More details are demonstrated in :ref:`api_pydataprovider2`.
37+
38+
The Neurons Activation Memory
39+
++++++++++++++
40+
41+
Each neuron activation operating in a neural network training process contains certain amount of temporary data such as the activation data (like the output value of a neuron). These data will be used to update parameters in back propagation period. The scale of memory consumed by these data is mainly related with two parameters, which are batch size and the length of each Sequence. Therefore, the neurons activation memory consuming is actually in proportion to the information contains in each mini-batch training.
42+
43+
Two practical ways:
44+
45+
* Reduce batch size. Set a smaller value in network configuration settings(batch_size=1000) can be helpful. But setting batch size to a smaller value may affect the training result due to it is a super parameter of the neural network itself.
46+
* Shorten the sequence length or cut off those excessively long sequences. For example, if the length of sequences in a dataset are mostly varies between 100 and 200, but there is sequence lengthen out to 10,000, then it’s quite potentially leads to OOM (out of memory), especially in RNN models such as LSTM.
47+
48+
The Parameters Memory
49+
++++++++
50+
51+
The PaddlePaddle framework supports almost all popular optimizers. Different optimizers have different memory requirement. For example, the :code:`adadelta` consumes approximately 5 times memory
52+
53+
space than the weights parameter’s scale, which means the :code:`adadelta` needs at least :code:`500M` memory if the model file contains all
54+
55+
parameters needs :code:`100M`.
56+
57+
Some optimization algorithms such as :code:`momentum` are worth giving a shot.
58+
59+
2. Tricks To Speed Up Training
60+
-------------------
61+
62+
The training procedure of PaddlePaddle may be speed up when considering following aspects:\:
63+
64+
* Reduce the time consumption of data loading
65+
* Speed up training epochs
66+
* Introduce more computing resources with the utilization of distribute training frameworks
67+
68+
Reduce The Time Consumption of Data Loading
69+
++++++++++++++++++
70+
71+
72+
The \ :code:`pydataprovider`\ holds big potential to speed up the data loading procedure if the cache pool and enable memory cache when use it. The principle of the reduction of :code:`DataProvider` cache pool is basically the same with the method which reduct the memory occupation with the set of a smaller cache pool.
73+
74+
.. literalinclude:: src/reduce_min_pool_size.py
75+
76+
Beside, the interface :code:`@provider` provides a parameter :code:`cache` to control cache. If set it to :code:`CacheType.CACHE_PASS_IN_MEM`, the data after the first :code:`pass` ( a pass means all data have be fed into the network for training) will be cached in memory and no new data will be read from the :code:`python` side in following :code:`pass` , instead from the cached data in memory. This strategy can also drop the time consuming in data loading process.
77+
78+
79+
Accelerating Training Epochs
80+
++++++++++++
81+
82+
Sparse training is supported in PaddlePaddle. The features needs to be trained is any of :code:`sparse_binary_vector`, :code:`sparse_vector` and :code:`integer_value` . Meanwhile, the Layer interacts with the training data need to turn the Parameter to sparse updating mode by setting :code:`sparse_update=True`.
83+
Take :code:`word2vec` as an example, to train a language distance, one needs to predict the middle word with two words prior to it and next to it. The DataProvider of this task is:
84+
85+
.. literalinclude:: src/word2vec_dataprovider.py
86+
87+
The configuration of this task is:
88+
89+
.. literalinclude:: src/word2vec_config.py
90+
91+
Introduce More Computing Resources
92+
++++++++++++++++++
93+
94+
More computing resources can be introduced with following manners:
95+
* Single CPU platform training
96+
97+
* Use multi-threading by set :code:`trainer_count`。
98+
99+
* Single GPU platform training
100+
101+
* Set :code:`use_gpu` to train on single GPU.
102+
* Set :code:`use_gpu` and :code:`trainer_count` to enable multiple GPU training support.
103+
104+
* Cluster Training
105+
106+
* Refer to :ref:`cluster_train` 。
107+
108+
3. Assign GPU Devices
109+
------------------
110+
111+
Assume a computing platform consists of 4 GPUs which serial number from 0 to 3:
112+
113+
* Method1: specify a GPU as computing device by set:
114+
`CUDA_VISIBLE_DEVICES <http://www.acceleware.com/blog/cudavisibledevices-masking-gpus>`_
115+
116+
.. code-block:: bash
117+
118+
env CUDA_VISIBLE_DEVICES=2,3 paddle train --use_gpu=true --trainer_count=2
119+
120+
* Method2: Assign by —gpu_id:
121+
122+
.. code-block:: bash
123+
124+
paddle train --use_gpu=true --trainer_count=2 --gpu_id=2
125+
126+
127+
4. How to Fix Training Termination Caused By :code:`Floating point exception` During Training.
128+
------------------------------------------------------------------------
129+
130+
Paddle binary catches floating exceptions during runtime, it will be terminated when NaN or Inf occurs. Floating exceptions are mostly caused by float overflow, divide by zero. There are three main reasons may raise such exception:
131+
132+
* Parameters or gradients during training are oversize, which leads to float overflow during calculation.
133+
* The model failed to converge and diverges to a big value.
134+
* Parameters may converge to a singular value due to bad training data. If the scale of input data is too big and contains millions of parameter values, float overflow error may arise when operating matrix multiplication.
135+
136+
Two ways to solve this problem:
137+
138+
1. Set :code:`gradient_clipping_threshold` as:
139+
140+
.. code-block:: python
141+
142+
optimizer = paddle.optimizer.RMSProp(
143+
learning_rate=1e-3,
144+
gradient_clipping_threshold=10.0,
145+
regularization=paddle.optimizer.L2Regularization(rate=8e-4))
146+
147+
Details can refer to example `nmt_without_attention <https://github.com/PaddlePaddle/models/blob/develop/nmt_without_attention/train.py#L35>`_ 示例。
148+
149+
2. Set :code:`error_clipping_threshold` as:
150+
151+
.. code-block:: python
152+
153+
decoder_inputs = paddle.layer.fc(
154+
act=paddle.activation.Linear(),
155+
size=decoder_size * 3,
156+
bias_attr=False,
157+
input=[context, current_word],
158+
layer_attr=paddle.attr.ExtraLayerAttribute(
159+
error_clipping_threshold=100.0))
160+
161+
Details can refer to example `machine translation <https://github.com/PaddlePaddle/book/blob/develop/08.machine_translation/train.py#L66>`_ 。
162+
163+
The main difference between these two methods are:
164+
165+
1. They both block the gradient, but happen in different occasions,the former one happens when then :code:`optimzier` updates the network parameters while the latter happens when the back propagation computing of activation functions.
166+
2. The block target are different, the former blocks the trainable parameters’ gradient while the later blocks the gradient to be propagated to prior layers.
167+
168+
Moreover, Such problems may be fixed with smaller learning rates or data normalization.
169+
170+
5. Fetch Multi Layers’ Prediction Result With Infer Interface
171+
-----------------------------------------------
172+
173+
* Join the layer to be used as :code:`output_layer` layer to the input parameters of :code:`paddle.inference.Inference()` interface with:
174+
175+
.. code-block:: python
176+
177+
inferer = paddle.inference.Inference(output_layer=[layer1, layer2], parameters=parameters)
178+
179+
* Assign certain fields to output. Take :code:`value` as example, it can be down with following code:
180+
181+
.. code-block:: python
182+
183+
out = inferer.infer(input=data_batch, field=["value"])
184+
185+
It is important to note that:
186+
187+
* If 2 layers are assigned as output layer, then the output results consists of 2 matrixes.
188+
* Assume the output of first layer A is a matrix sizes N1 * M1, the output of second layer B is a matrix sizes N2 * M2;
189+
* By default, paddle.v2 will transverse join A and B, when N1 not equal to N2, it will raise following error:
190+
191+
.. code-block:: python
192+
193+
ValueError: all the input array dimensions except for the concatenation axis must match exactly
194+
195+
The transverse of different matrixes of multi layers mainly happens when:
196+
197+
* Output sequence layer and non sequence layer;
198+
* Multiple output layers process multiple sequence with different length;
199+
200+
Such issue can be avoided by calling infer interface and set :code:`flatten_result=False`. Thus, the infer interface returns a python list, in which
201+
202+
* The number of elements equals to the number of output layers in the network;
203+
* Each element in list is a result matrix of a layer, which type is numpy.ndarray;
204+
* The height of each matrix outputted by each layer equals to the number of samples under non sequential mode or equals to the number of elements in the input sequence under sequential mode. Their width are both equal to the layer size in configuration.
205+
206+
6. Fetch the Output of A Certain Layer During Training
207+
-----------------------------------------------
208+
209+
In event_handler, the interface :code:`event.gm.getLayerOutputs("layer_name")` gives the forward output value organized in :code:`numpy.ndarray` corresponding to :code:`layer_name` in the mini-batch.
210+
The output can be used in custom measurements in following way:
211+
212+
.. code-block:: python
213+
214+
def score_diff(right_score, left_score):
215+
return np.average(np.abs(right_score - left_score))
216+
217+
def event_handler(event):
218+
if isinstance(event, paddle.event.EndIteration):
219+
if event.batch_id % 25 == 0:
220+
diff = score_diff(
221+
event.gm.getLayerOutputs("right_score")["right_score"][
222+
"value"],
223+
event.gm.getLayerOutputs("left_score")["left_score"][
224+
"value"])
225+
logger.info(("Pass %d Batch %d : Cost %.6f, "
226+
"average absolute diff scores: %.6f") %
227+
(event.pass_id, event.batch_id, event.cost, diff))
228+
229+
Note: this function can not get content of :code:`paddle.layer.recurrent_group` step, but output of :code:`paddle.layer.recurrent_group` can be fetched.
230+
231+
7. Fetch Parameters’ Weight and Gradient During Training
232+
-----------------------------------------------
233+
234+
Under certain situations, knowing the weights of currently training mini-batch can provide more inceptions of many problems. Their value can be acquired by printing values in :code:`event_handler` (note that to gain such parameters when training on GPU, you should set :code:`paddle.event.EndForwardBackward`). Detailed code is as following:
235+
236+
.. code-block:: python
237+
238+
...
239+
parameters = paddle.parameters.create(cost)
240+
...
241+
def event_handler(event):
242+
if isinstance(event, paddle.event.EndForwardBackward):
243+
if event.batch_id % 25 == 0:
244+
for p in parameters.keys():
245+
logger.info("Param %s, Grad %s",
246+
parameters.get(p), parameters.get_grad(p))
247+
248+
Note that “acquire the output of a certain layer during training” or “acquire the weights and gradients of parameters during training ” both needs to copy training data from C++ environment to numpy, which have certain degree of influence on training performance. Don’t use these two functions when the training procedure cares about the performance.

0 commit comments

Comments
 (0)