Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into clip_by_norm
updatemobile_baidu
commit
c8c4b6e427
@ -0,0 +1,213 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
from paddle.trainer_config_helpers import *
|
||||||
|
|
||||||
|
height = 224
|
||||||
|
width = 224
|
||||||
|
num_class = 1000
|
||||||
|
batch_size = get_config_arg('batch_size', int, 64)
|
||||||
|
layer_num = get_config_arg("layer_num", int, 50)
|
||||||
|
is_test = get_config_arg("is_test", bool, False)
|
||||||
|
|
||||||
|
args = {'height': height, 'width': width, 'color': True, 'num_class': num_class}
|
||||||
|
define_py_data_sources2(
|
||||||
|
"train.list", None, module="provider", obj="process", args=args)
|
||||||
|
|
||||||
|
settings(
|
||||||
|
batch_size=batch_size,
|
||||||
|
learning_rate=0.01 / batch_size,
|
||||||
|
learning_method=MomentumOptimizer(0.9),
|
||||||
|
regularization=L2Regularization(0.0005 * batch_size))
|
||||||
|
|
||||||
|
|
||||||
|
#######################Network Configuration #############
|
||||||
|
def conv_bn_layer(name,
|
||||||
|
input,
|
||||||
|
filter_size,
|
||||||
|
num_filters,
|
||||||
|
stride,
|
||||||
|
padding,
|
||||||
|
channels=None,
|
||||||
|
active_type=ReluActivation()):
|
||||||
|
"""
|
||||||
|
A wrapper for conv layer with batch normalization layers.
|
||||||
|
Note:
|
||||||
|
conv layer has no activation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
tmp = img_conv_layer(
|
||||||
|
name=name + "_conv",
|
||||||
|
input=input,
|
||||||
|
filter_size=filter_size,
|
||||||
|
num_channels=channels,
|
||||||
|
num_filters=num_filters,
|
||||||
|
stride=stride,
|
||||||
|
padding=padding,
|
||||||
|
act=LinearActivation(),
|
||||||
|
bias_attr=False)
|
||||||
|
return batch_norm_layer(
|
||||||
|
name=name + "_bn", input=tmp, act=active_type, use_global_stats=is_test)
|
||||||
|
|
||||||
|
|
||||||
|
def bottleneck_block(name, input, num_filters1, num_filters2):
|
||||||
|
"""
|
||||||
|
A wrapper for bottlenect building block in ResNet.
|
||||||
|
Last conv_bn_layer has no activation.
|
||||||
|
Addto layer has activation of relu.
|
||||||
|
"""
|
||||||
|
last_name = conv_bn_layer(
|
||||||
|
name=name + '_branch2a',
|
||||||
|
input=input,
|
||||||
|
filter_size=1,
|
||||||
|
num_filters=num_filters1,
|
||||||
|
stride=1,
|
||||||
|
padding=0)
|
||||||
|
last_name = conv_bn_layer(
|
||||||
|
name=name + '_branch2b',
|
||||||
|
input=last_name,
|
||||||
|
filter_size=3,
|
||||||
|
num_filters=num_filters1,
|
||||||
|
stride=1,
|
||||||
|
padding=1)
|
||||||
|
last_name = conv_bn_layer(
|
||||||
|
name=name + '_branch2c',
|
||||||
|
input=last_name,
|
||||||
|
filter_size=1,
|
||||||
|
num_filters=num_filters2,
|
||||||
|
stride=1,
|
||||||
|
padding=0,
|
||||||
|
active_type=LinearActivation())
|
||||||
|
|
||||||
|
return addto_layer(
|
||||||
|
name=name + "_addto", input=[input, last_name], act=ReluActivation())
|
||||||
|
|
||||||
|
|
||||||
|
def mid_projection(name, input, num_filters1, num_filters2, stride=2):
|
||||||
|
"""
|
||||||
|
A wrapper for middile projection in ResNet.
|
||||||
|
projection shortcuts are used for increasing dimensions,
|
||||||
|
and other shortcuts are identity
|
||||||
|
branch1: projection shortcuts are used for increasing
|
||||||
|
dimensions, has no activation.
|
||||||
|
branch2x: bottleneck building block, shortcuts are identity.
|
||||||
|
"""
|
||||||
|
# stride = 2
|
||||||
|
branch1 = conv_bn_layer(
|
||||||
|
name=name + '_branch1',
|
||||||
|
input=input,
|
||||||
|
filter_size=1,
|
||||||
|
num_filters=num_filters2,
|
||||||
|
stride=stride,
|
||||||
|
padding=0,
|
||||||
|
active_type=LinearActivation())
|
||||||
|
|
||||||
|
last_name = conv_bn_layer(
|
||||||
|
name=name + '_branch2a',
|
||||||
|
input=input,
|
||||||
|
filter_size=1,
|
||||||
|
num_filters=num_filters1,
|
||||||
|
stride=stride,
|
||||||
|
padding=0)
|
||||||
|
last_name = conv_bn_layer(
|
||||||
|
name=name + '_branch2b',
|
||||||
|
input=last_name,
|
||||||
|
filter_size=3,
|
||||||
|
num_filters=num_filters1,
|
||||||
|
stride=1,
|
||||||
|
padding=1)
|
||||||
|
|
||||||
|
last_name = conv_bn_layer(
|
||||||
|
name=name + '_branch2c',
|
||||||
|
input=last_name,
|
||||||
|
filter_size=1,
|
||||||
|
num_filters=num_filters2,
|
||||||
|
stride=1,
|
||||||
|
padding=0,
|
||||||
|
active_type=LinearActivation())
|
||||||
|
|
||||||
|
return addto_layer(
|
||||||
|
name=name + "_addto", input=[branch1, last_name], act=ReluActivation())
|
||||||
|
|
||||||
|
|
||||||
|
img = data_layer(name='image', size=height * width * 3)
|
||||||
|
|
||||||
|
|
||||||
|
def deep_res_net(res2_num=3, res3_num=4, res4_num=6, res5_num=3):
|
||||||
|
"""
|
||||||
|
A wrapper for 50,101,152 layers of ResNet.
|
||||||
|
res2_num: number of blocks stacked in conv2_x
|
||||||
|
res3_num: number of blocks stacked in conv3_x
|
||||||
|
res4_num: number of blocks stacked in conv4_x
|
||||||
|
res5_num: number of blocks stacked in conv5_x
|
||||||
|
"""
|
||||||
|
# For ImageNet
|
||||||
|
# conv1: 112x112
|
||||||
|
tmp = conv_bn_layer(
|
||||||
|
"conv1",
|
||||||
|
input=img,
|
||||||
|
filter_size=7,
|
||||||
|
channels=3,
|
||||||
|
num_filters=64,
|
||||||
|
stride=2,
|
||||||
|
padding=3)
|
||||||
|
tmp = img_pool_layer(name="pool1", input=tmp, pool_size=3, stride=2)
|
||||||
|
|
||||||
|
# conv2_x: 56x56
|
||||||
|
tmp = mid_projection(
|
||||||
|
name="res2_1", input=tmp, num_filters1=64, num_filters2=256, stride=1)
|
||||||
|
for i in xrange(2, res2_num + 1, 1):
|
||||||
|
tmp = bottleneck_block(
|
||||||
|
name="res2_" + str(i), input=tmp, num_filters1=64, num_filters2=256)
|
||||||
|
|
||||||
|
# conv3_x: 28x28
|
||||||
|
tmp = mid_projection(
|
||||||
|
name="res3_1", input=tmp, num_filters1=128, num_filters2=512)
|
||||||
|
for i in xrange(2, res3_num + 1, 1):
|
||||||
|
tmp = bottleneck_block(
|
||||||
|
name="res3_" + str(i),
|
||||||
|
input=tmp,
|
||||||
|
num_filters1=128,
|
||||||
|
num_filters2=512)
|
||||||
|
|
||||||
|
# conv4_x: 14x14
|
||||||
|
tmp = mid_projection(
|
||||||
|
name="res4_1", input=tmp, num_filters1=256, num_filters2=1024)
|
||||||
|
for i in xrange(2, res4_num + 1, 1):
|
||||||
|
tmp = bottleneck_block(
|
||||||
|
name="res4_" + str(i),
|
||||||
|
input=tmp,
|
||||||
|
num_filters1=256,
|
||||||
|
num_filters2=1024)
|
||||||
|
|
||||||
|
# conv5_x: 7x7
|
||||||
|
tmp = mid_projection(
|
||||||
|
name="res5_1", input=tmp, num_filters1=512, num_filters2=2048)
|
||||||
|
for i in xrange(2, res5_num + 1, 1):
|
||||||
|
tmp = bottleneck_block(
|
||||||
|
name="res5_" + str(i),
|
||||||
|
input=tmp,
|
||||||
|
num_filters1=512,
|
||||||
|
num_filters2=2048)
|
||||||
|
|
||||||
|
tmp = img_pool_layer(
|
||||||
|
name='avgpool',
|
||||||
|
input=tmp,
|
||||||
|
pool_size=7,
|
||||||
|
stride=1,
|
||||||
|
pool_type=AvgPooling())
|
||||||
|
|
||||||
|
return fc_layer(input=tmp, size=num_class, act=SoftmaxActivation())
|
||||||
|
|
||||||
|
|
||||||
|
if layer_num == 50:
|
||||||
|
resnet = deep_res_net(3, 4, 6, 3)
|
||||||
|
elif layer_num == 101:
|
||||||
|
resnet = deep_res_net(3, 4, 23, 3)
|
||||||
|
elif layer_num == 152:
|
||||||
|
resnet = deep_res_net(3, 8, 36, 3)
|
||||||
|
else:
|
||||||
|
print("Wrong layer number.")
|
||||||
|
|
||||||
|
lbl = data_layer(name="label", size=num_class)
|
||||||
|
loss = cross_entropy(name='loss', input=resnet, label=lbl)
|
||||||
|
inputs(img, lbl)
|
||||||
|
outputs(loss)
|
@ -0,0 +1,60 @@
|
|||||||
|
# Design Doc: float16
|
||||||
|
|
||||||
|
## Why float16
|
||||||
|
Half precision (float16) is a binary floating-point format that occupies 16 bits in memory. float16 is half the size of traditional 32-bit single precision format (float) and has lower precision and smaller range.
|
||||||
|
|
||||||
|
When high precision computation is not required, using float16 data type could potentially
|
||||||
|
|
||||||
|
- reduce storage space, memory bandwidth, and power usages;
|
||||||
|
- increase the chance of data fitting into a smaller cache of lower latency;
|
||||||
|
- provide arithmetic speed up if supported by hardware.
|
||||||
|
|
||||||
|
## Survey of current float16 support
|
||||||
|
A brief survey of float16 support on different compilers, hardwares, and libraries can be found below. Interested readers can refer to [link1](https://github.com/PaddlePaddle/Paddle/issues/4853) and [link2](https://github.com/Xreki/Xreki.github.io/blob/master/multi_data_types_in_dl_framework/ppt/float16_and_quantized_type.md) for more info.
|
||||||
|
|
||||||
|
The goal of float16 is to serve as a key for the executor to find and run the correct version of compute method specialized for float16 in operator kernel. It should be compatible with various natively supported float16 implementations including `__half` for cuda, `float16_t` for ARM, and `Eigen::half` for Eigen to make writing customized float16 kernels easier.
|
||||||
|
|
||||||
|
### Compiler
|
||||||
|
- nvcc supports `__half` data type after CUDA 7.5.
|
||||||
|
- `__fp16` or `float16_t` is supported as storage type for gcc >= 6.1 and clang >= 3.4.
|
||||||
|
- `__fp16` or `float16_t` is supported as arithmetic type for gcc >= 7.1 and clang >= 3.9.
|
||||||
|
|
||||||
|
### Hardware
|
||||||
|
- `__half` is supported on GPU with compute capability >= 5.3.
|
||||||
|
- `__fp16` is supported as storage type for ARMv7-A, ARMv8-A, and above.
|
||||||
|
- `__fp16` is supported as arithmetic type after ARMv8.2-A (currently, the only microarchitecture implementing ARMv8.2-A is ARM Cortex-A75, which is announced in May 2017. There seems to be no application processors currently available on market that adopts this architecture. It is reported that Qualcomm Snapdragon 845 uses Cortex-A75 design and will be available in mobile devices in early 2018).
|
||||||
|
|
||||||
|
### Libraries
|
||||||
|
- [Eigen](https://github.com/RLovelett/eigen) >= 3.3 supports float16 calculation on both GPU and CPU using the `Eigen::half` class. It is mostly useful for Nvidia GPUs because of the overloaded arithmetic operators using cuda intrinsics. It falls back to using software emulation on CPU for calculation and there is no special treatment to ARM processors.
|
||||||
|
- [ARM compute library](https://github.com/ARM-software/ComputeLibrary) >= 17.02.01 supports NEON FP16 kernels (requires ARMv8.2-A CPU).
|
||||||
|
|
||||||
|
|
||||||
|
## Implementation
|
||||||
|
The float16 class holds a 16-bit `uint16_t` data internally.
|
||||||
|
```
|
||||||
|
struct float16 {
|
||||||
|
uint16_t x;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
float16 supports the following features:
|
||||||
|
- constructors / assignment operators that take input from primitive data types including bool, integers of various length, float, and double.
|
||||||
|
- constructors / assignment operators that take input from `__half` on cuda, `float16_t` on ARM, and `Eigen::half` on Eigen.
|
||||||
|
- conversion operators to primitive data types and half precision data types on cuda, ARM and Eigen.
|
||||||
|
- overloaded arithmetic operators for cuda, arm, and non-arm cpu, respectively. These operators will take advantage of the cuda and ARM intrinsics on the corresponding hardware.
|
||||||
|
|
||||||
|
To support the above features, two fundamental conversion functions are provided:
|
||||||
|
```
|
||||||
|
float16 float_to_half_rn(float f); // convert to half precision in round-to-nearest-even mode
|
||||||
|
float half_to_float(float16 h);
|
||||||
|
```
|
||||||
|
which provides one-to-one conversion between float32 and float16. These twos functions will do different conversion routines based on the current hardware. CUDA/ARM instrinsics will be used when the corresonding hardware is available. If the hardware or compiler level does not support float32 to float16 conversion, software emulation will be performed to do the conversion.
|
||||||
|
|
||||||
|
## To do
|
||||||
|
After float16 class is available, some of the future items are below:
|
||||||
|
|
||||||
|
- Update pybind/tensor_py.h to bind c++ float16 with numpy float16.
|
||||||
|
|
||||||
|
- Modify `GetKernelType()` method in `framework/operator.h` to make it compatible with float16.
|
||||||
|
|
||||||
|
- Create a type-casting operator that can convert the data type in tensor between float16 and other types.
|
After Width: | Height: | Size: 620 B |
After Width: | Height: | Size: 156 B |
@ -0,0 +1,72 @@
|
|||||||
|
# Averaging Parameter in PaddlePaddle
|
||||||
|
|
||||||
|
## Why Averaging
|
||||||
|
In a large scale machine learning setup where the size of the training data is huge, it could take us a large number of iterations over the training data before we can achieve the optimal values of parameters of our model. Looking at the problem setup, it is desirable if we can obtain the optimal values of parameters by going through the data in as few passes as we can.
|
||||||
|
|
||||||
|
Polyak and Juditsky (1992) showed that the test performance of simple average of parameters obtained by Stochastic Gradient Descent (SGD) is as good as that of parameter values that are obtained by training the model over and over again, over the training dataset.
|
||||||
|
|
||||||
|
Hence, to accelerate the speed of Stochastic Gradient Descent, Averaged Stochastic Gradient Descent (ASGD) was proposed in Polyak and Juditsky (1992). For ASGD, the running average of parameters obtained by SGD, is used as the estimator for <img src="./images/theta_star.gif"/><br/> . The averaging is done as follows:
|
||||||
|
|
||||||
|
<img src="./images/asgd.gif" align="center"/><br/>
|
||||||
|
|
||||||
|
We propose averaging for any optimizer similar to how ASGD performs it, as mentioned above.
|
||||||
|
|
||||||
|
### How to perform Parameter Averaging in PaddlePaddle
|
||||||
|
|
||||||
|
Parameter Averaging in PaddlePaddle works in the following way during training :
|
||||||
|
1. It will take in an instance of a normal optimizer as an input, e.g. RMSPropOptimizer
|
||||||
|
2. The optimizer itself is responsible for updating the parameters.
|
||||||
|
3. The ParameterAverageOptimizer maintains a separate copy of the parameters for itself:
|
||||||
|
1. In concept, the values of this copy are the average of the values of the parameters in the most recent N batches.
|
||||||
|
2. However, saving all the N instances of the parameters in memory is not feasible.
|
||||||
|
3. Therefore, an approximation algorithm is used.
|
||||||
|
|
||||||
|
Hence, overall we have have two copies of the parameters: one for the optimizer itself, and one for the ParameterAverageOptimizer. The former should be used in back propagation, while the latter should be used during testing and should be saved.
|
||||||
|
|
||||||
|
During the testing/ saving the model phase, we perform the following steps:
|
||||||
|
1. Perform the delayed operations.
|
||||||
|
2. Save current values of the parameters to a temporary variable.
|
||||||
|
3. Replace the values of the parameters with the averaged values.
|
||||||
|
4. Perform testing and/or save the parameters.
|
||||||
|
5. Restore the values of the parameters once done.
|
||||||
|
|
||||||
|
### How to implement Averaging of Parameter in PaddlePaddle
|
||||||
|
|
||||||
|
We can add the ParameterAverageOptimizer op to the graph through Python API. Using this approach, we manually add this op to the graph and direct the output of the optimizer op to this op during training.
|
||||||
|
|
||||||
|
**Advantages**:
|
||||||
|
- Allows for greater flexibility to the users of PaddlePaddle. Using this approach, the users can plug different optimizers into ParameterAverageOptimizer by passing in the optimizer to the op.
|
||||||
|
- Makes it easy for the users to customize and extend the framework.
|
||||||
|
|
||||||
|
**Disadvantages**:
|
||||||
|
- Implementation requires re-writing the averaging methodology in Python.
|
||||||
|
|
||||||
|
### Low-Level implementation
|
||||||
|
|
||||||
|
In the new design, we propose to create a new operation for averaging parameter updates (ParameterAverageOptimizer). For now, we can add an op that takes in the following as input:
|
||||||
|
- the optimizer
|
||||||
|
- the window_size to keep the updates
|
||||||
|
|
||||||
|
The ParameterAverageOptimizer op can be like any other operator with its own CPU/GPU implementation either using Eigen or separate CPU and GPU kernels. As the initial implementation, we can implement the kernel using Eigen following the abstraction pattern implemented for [Operators](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/rmsprop_op.h). We also want to support the case when the Trainer/Optimizer runs on the GPU while ParameterAverageOptimizer runs on a CPU.
|
||||||
|
|
||||||
|
The idea of building an op for averaging is in sync with the refactored PaddlePaddle philosophy of using operators to represent any computation unit. The way the op will be added to the computation graph will be decided by the [layer functions](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/python_api.md#layer-function) in Python API.
|
||||||
|
|
||||||
|
### Python API implementation for ParameterAverageOptimizer
|
||||||
|
|
||||||
|
Based on Polyak and Juditsky (1992), we can generalize the averaging of updates to any optimizer. The input to the op would be the following:
|
||||||
|
- Any optimizer (RMSProp , AdaGrad etc.)
|
||||||
|
- A window size. The op keeps accumulating updated parameter values over a window of N batches and takes an average. Move the averaged value to a buffer when window is full to avoid loss of precision.
|
||||||
|
|
||||||
|
Using the ParameterAverageOptimizer op, any user can add the operation to their computation graphs. However, this will require a lot of lines of code and we should design Python APIs that support averaging. As per the PaddlePaddle [Python API design](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/python_api.md), the layer functions are responsible for creating operators, operator parameters and variables. Since ParameterAverageOptimizer will be an operator, it makes sense to create it in the layer functions.
|
||||||
|
We will have a wrapper written in Python that will support the functionality and implement the actual core computation in C++ core as we have done for other [Optimizers](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/operators/rmsprop_op.cc)
|
||||||
|
|
||||||
|
#### Creation of the ParameterAverageOptimizer operator
|
||||||
|
There are two ways for creating the ParameterAverageOptimizer op:
|
||||||
|
1. We create the op immediately while building the computation graph.
|
||||||
|
2. We add the op in a lazy manner, just before the backward pass, similar to the way the optimization ops are added.
|
||||||
|
|
||||||
|
The proposal is to add the op immediately while building the computation graph.
|
||||||
|
|
||||||
|
#### High-level API
|
||||||
|
|
||||||
|
In PaddlePaddle Python API, users will primarily rely on [layer functions](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/python_api.md#layer-function) to create neural network layers. Hence, we also need to provide parameter average functionality in layer functions.
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue