From 2bb09cf10416a54e40380dddc3ae2d2b6337d8e3 Mon Sep 17 00:00:00 2001 From: luotao02 Date: Wed, 31 Aug 2016 07:35:17 +0000 Subject: [PATCH] adjust format of new_layer and rnn, refine seq2seq doc ISSUE=4604739 git-svn-id: https://svn.baidu.com/idl/trunk/paddle@1453 1ad973e4-5ce8-4261-8a94-b56d1f490c56 --- doc/demo/new_layer/index.rst | 372 ++++++++++---------- doc/demo/text_generation/text_generation.md | 1 + doc/ui/api/rnn/index.rst | 113 +++--- 3 files changed, 240 insertions(+), 246 deletions(-) diff --git a/doc/demo/new_layer/index.rst b/doc/demo/new_layer/index.rst index 0f12e952ad4..bd4a4c46c87 100644 --- a/doc/demo/new_layer/index.rst +++ b/doc/demo/new_layer/index.rst @@ -1,5 +1,5 @@ Writing New Layers -======================= +================== This tutorial will guide you to write customized layers in PaddlePaddle. We will utilize fully connected layer as an example to guide you through the following steps for writing a new layer. @@ -8,68 +8,69 @@ This tutorial will guide you to write customized layers in PaddlePaddle. We will - Write gradient check unit test to make sure the gradients are correctly computed. - Implement Python wrapper for the layer. -================= Derive Equations -================= +================ First we need to derive equations of the *forward* and *backward* part of the layer. The forward part computes the output given an input. The backward part computes the gradients of the input and the parameters given the the gradients of the output. The illustration of a fully connected layer is shown in the following figure. In a fully connected layer, all output nodes are connected to all the input nodes. -.. image:: ./FullyConnected.jpg +.. image:: FullyConnected.jpg + :align: center + :scale: 60 % The *forward part* of a layer transforms an input into the corresponding output. -Fully connected layer takes a dense input vector with dimension :math:`D_i`. It uses a transformation matrix :math:`W` with size :math:`D_i \times D_o` to project x into a :math:`D_o` dimensional vector, and add a bias vector :math:`b` with dimension :math:`D_o` to the vector. +Fully connected layer takes a dense input vector with dimension :math:`D_i`. It uses a transformation matrix :math:`W` with size :math:`D_i \times D_o` to project :math:`x` into a :math:`D_o` dimensional vector, and add a bias vector :math:`b` with dimension :math:`D_o` to the vector. .. math:: - y = f(W^T x + b) + y = f(W^T x + b) where :math:`f(.)` is an nonlinear *activation* function, such as sigmoid, tanh, and Relu. -The transformation matrix :math:`W` and bias vector :math:`b` are the *parameters* of the layer. The *parameters* of a layer are learned during training in the *backward pass*. The backward pass computes the gradients of the output function with respect to all parameters and inputs. The optimizer can use chain rule to compute the gradients of the loss function with respect to each parameter. Suppose our loss function is :math:`c(y)`, then +The transformation matrix :math:`W` and bias vector :math:`b` are the *parameters* of the layer. The *parameters* of a layer are learned during training in the *backward pass*. The backward pass computes the gradients of the output function with respect to all parameters and inputs. The optimizer can use chain rule to compute the gradients of the loss function with respect to each parameter. + +Suppose our loss function is :math:`c(y)`, then .. math:: - \frac{\partial c(y)}{\partial x} = \frac{\partial c(y)}{\partial y} \frac{\partial y}{\partial x} + \frac{\partial c(y)}{\partial x} = \frac{\partial c(y)}{\partial y} \frac{\partial y}{\partial x} Suppose :math:`z = f(W^T x + b)`, then .. math:: - \frac{\partial y}{\partial z} = \frac{\partial f(z)}{\partial z} - + \frac{\partial y}{\partial z} = \frac{\partial f(z)}{\partial z} This derivative can be automatically computed by our base layer class. -Then, for fully connected layer, we need to compute :math:`\frac{\partial z}{\partial x}`, and :math:`\frac{\partial z}{\partial W}`, and :math:`\frac{\partial z}{\partial b}` -. +Then, for fully connected layer, we need to compute: .. math:: - \frac{\partial z}{\partial x} = W \\ - \frac{\partial z_j}{\partial W_{ij}} = x_i \\ - \frac{\partial z}{\partial b} = \mathbf 1 \\ + + \frac{\partial z}{\partial x} = W, \frac{\partial z_j}{\partial W_{ij}} = x_i, \frac{\partial z}{\partial b} = \mathbf 1 -where .. math::`\mathbf 1` is an all one vector, .. math::`W_{ij}` is the number at the i-th row and j-th column of the matrix .. math::`W`, .. math::`z_j` is the j-th component of the vector .. math::`z`, and .. math::`x_i` is the i-th component of the vector .. math::`x`. +where :math:`\mathbf 1` is an all one vector, :math:`W_{ij}` is the number at the i-th row and j-th column of the matrix :math:`W`, :math:`z_j` is the j-th component of the vector :math:`z`, and :math:`x_i` is the i-th component of the vector :math:`x`. -Then we can use chain rule to calculate .. math::`\frac{\partial z}{\partial x}`, and .. math::`\frac{\partial z}{\partial W}`. The details of the computation will be given in the next section. +Finally we can use chain rule to calculate :math:`\frac{\partial z}{\partial x}`, and :math:`\frac{\partial z}{\partial W}`. The details of the computation will be given in the next section. -================= Implement C++ Class -================= +=================== -The C++ class of the layer implements the initialization, forward, and backward part of the layer. The fully connected layer is at `paddle/gserver/layers/FullyConnectedLayer.h` and `paddle/gserver/layers/FullyConnectedLayer.cpp`. We list simplified version of the code below. +The C++ class of the layer implements the initialization, forward, and backward part of the layer. The fully connected layer is at :code:`paddle/gserver/layers/FullyConnectedLayer.h` and :code:`paddle/gserver/layers/FullyConnectedLayer.cpp`. We list simplified version of the code below. -It needs to derive the base class `paddle::BaseLayer`, and it needs to override the following functions: +It needs to derive the base class :code:`paddle::BaseLayer`, and it needs to override the following functions: - constructor and destructor. -- `init` function. It is used to initialize the parameters and settings. -- `forward`. It implements the forward part of the layer. -- `backward`. It implements the backward part of the layer. -- `prefetch`. It is utilized to determine the rows corresponding parameter matrix to prefetch from parameter server. You do not need to override this function if your layer does not need remote sparse update. (most layers do not need to support remote sparse update) +- :code:`init` function. It is used to initialize the parameters and settings. +- :code:`forward`. It implements the forward part of the layer. +- :code:`backward`. It implements the backward part of the layer. +- :code:`prefetch`. It is utilized to determine the rows corresponding parameter matrix to prefetch from parameter server. You do not need to override this function if your layer does not need remote sparse update. (most layers do not need to support remote sparse update) + +The header file is listed below: -The header file is listed below:: +.. code-block:: c++ namespace paddle { /** @@ -87,7 +88,7 @@ The header file is listed below:: public: explicit FullyConnectedLayer(const LayerConfig& config) - : Layer(config) {} + : Layer(config) {} ~FullyConnectedLayer() {} bool init(const LayerMap& layerMap, const ParameterMap& parameterMap); @@ -100,60 +101,63 @@ The header file is listed below:: }; } // namespace paddle +It defines the parameters as class variables. We use :code:`Weight` class as abstraction of parameters. It supports multi-thread update. The details of this class will be described in details in the implementations. -It defines the parameters as class variables. We use `Weight` class as abstraction of parameters. It supports multi-thread update. The details of this class will be described in details in the implementations. -- `weights_` is a list of weights for the transformation matrices. The current implementation can have more than one inputs. Thus, it has a list of weights. One weight corresponds to an input. -- `biases_` is a weight for the bias vector. +- :code:`weights_` is a list of weights for the transformation matrices. The current implementation can have more than one inputs. Thus, it has a list of weights. One weight corresponds to an input. +- :code:`biases_` is a weight for the bias vector. -The fully connected layer does not have layer configuration hyper-parameters. If there are some layer hyper-parameters, a common practice is to store it in `LayerConfig& config`, and put it into a class variable in the constructor. +The fully connected layer does not have layer configuration hyper-parameters. If there are some layer hyper-parameters, a common practice is to store it in :code:`LayerConfig& config`, and put it into a class variable in the constructor. -The following code snippet implements the `init` function. -- First, every `init` function must call the `init` function of the base class `Layer::init(layerMap, parameterMap);`. This statement will initialize the required variables and connections for each layer. +The following code snippet implements the :code:`init` function. + +- First, every :code:`init` function must call the :code:`init` function of the base class :code:`Layer::init(layerMap, parameterMap);`. This statement will initialize the required variables and connections for each layer. - The it initializes all the weights matrices :math:`W`. The current implementation can have more than one inputs. Thus, it has a list of weights. - Finally, it initializes the bias. -The code is listed below:: +.. code-block:: c++ bool FullyConnectedLayer::init(const LayerMap& layerMap, - const ParameterMap& parameterMap) { + const ParameterMap& parameterMap) { /* Initialize the basic parent class */ Layer::init(layerMap, parameterMap); /* initialize the weightList */ CHECK(inputLayers_.size() == parameters_.size()); for (size_t i = 0; i < inputLayers_.size(); i++) { - // Option the parameters - size_t height = inputLayers_[i]->getSize(); - size_t width = getSize(); - - // create a new weight - if (parameters_[i]->isSparse()) { - CHECK_LE(parameters_[i]->getSize(), width * height); - } else { - CHECK_EQ(parameters_[i]->getSize(), width * height); - } - Weight* w = new Weight(height, width, parameters_[i]); - - // append the new weight to the list - weights_.emplace_back(w); + // Option the parameters + size_t height = inputLayers_[i]->getSize(); + size_t width = getSize(); + + // create a new weight + if (parameters_[i]->isSparse()) { + CHECK_LE(parameters_[i]->getSize(), width * height); + } else { + CHECK_EQ(parameters_[i]->getSize(), width * height); + } + Weight* w = new Weight(height, width, parameters_[i]); + + // append the new weight to the list + weights_.emplace_back(w); } /* initialize biases_ */ if (biasParameter_.get() != NULL) { - biases_ = std::unique_ptr(new Weight(1, getSize(), biasParameter_)); + biases_ = std::unique_ptr(new Weight(1, getSize(), biasParameter_)); } return true; } The implementation of the forward part has the following steps. -- Every layer must call `Layer::forward(passType);` at the beginning of its `forward` function. -- Then it allocates memory for the output using `reserveOutput(batchSize, size);`. This step is necessary because we support the batches to have different batch sizes. `reserveOutput` will change the size of the output accordingly. For the sake of efficiency, we will allocate new memory if we want to expand the matrix, but we will reuse the existing memory block if we want to shrink the matrix. -- Then it computes :math:`\sum_i W_i x + b` using Matrix operations. `getInput(i).value` retrieve the matrix of the i-th input. Each input is a :math:`batchSize \times dim` matrix, where each row represents an single input in a batch. For a complete lists of supported matrix operations, please refer to `paddle/math/Matrix.h` and `paddle/math/BaseMatrix.h`. -- Finally it applies the activation function using `forwardActivation();`. It will automatically applies the corresponding activation function specifies in the network configuration. -The code is listed below:: +- Every layer must call :code:`Layer::forward(passType);` at the beginning of its :code:`forward` function. +- Then it allocates memory for the output using :code:`reserveOutput(batchSize, size);`. This step is necessary because we support the batches to have different batch sizes. :code:`reserveOutput` will change the size of the output accordingly. For the sake of efficiency, we will allocate new memory if we want to expand the matrix, but we will reuse the existing memory block if we want to shrink the matrix. +- Then it computes :math:`\sum_i W_i x + b` using Matrix operations. :code:`getInput(i).value` retrieve the matrix of the i-th input. Each input is a :math:`batchSize \times dim` matrix, where each row represents an single input in a batch. For a complete lists of supported matrix operations, please refer to :code:`paddle/math/Matrix.h` and :code:`paddle/math/BaseMatrix.h`. +- Finally it applies the activation function using :code:`forwardActivation();`. It will automatically applies the corresponding activation function specifies in the network configuration. + + +.. code-block:: c++ void FullyConnectedLayer::forward(PassType passType) { Layer::forward(passType); @@ -163,149 +167,141 @@ The code is listed below:: int size = getSize(); { - // Settup the size of the output. - reserveOutput(batchSize, size); + // Settup the size of the output. + reserveOutput(batchSize, size); } MatrixPtr outV = getOutputValue(); // Apply the the transformation matrix to each input. for (size_t i = 0; i != inputLayers_.size(); ++i) { - auto input = getInput(i); - CHECK(input.value) << "The input of 'fc' layer must be matrix"; - i == 0 ? outV->mul(input.value, weights_[i]->getW(), 1, 0) - : outV->mul(input.value, weights_[i]->getW(), 1, 1); + auto input = getInput(i); + CHECK(input.value) << "The input of 'fc' layer must be matrix"; + i == 0 ? outV->mul(input.value, weights_[i]->getW(), 1, 0) + : outV->mul(input.value, weights_[i]->getW(), 1, 1); } /* add the bias-vector */ if (biases_.get() != NULL) { - outV->addBias(*(biases_->getW()), 1); + outV->addBias(*(biases_->getW()), 1); } /* activation */ { - forwardActivation(); + forwardActivation(); } } - The implementation of the backward part has the following steps. -- ` backwardActivation();` computes the gradients of the activation. The gradients will be multiplies in place to the gradients of the output, which can be retrieved using `getOutputGrad()`. -- Compute the gradients of bias. Notice that we an use `biases_->getWGrad()` to get the gradient matrix of the corresponding parameter. After the gradient of one parameter is updated, it *MUST* call `getParameterPtr()->incUpdate(callback);`. This is utilize for parameter update over multiple threads or multiple machines. -- Then it computes the gradients of the transformation matrices and inputs, and it calls `incUpdate` for the corresponding parameter. This gives the framework the chance to know whether it has gathered all the gradient to one parameter so that it can do some overlapping work (e.g., network communication) + +- :code:`backwardActivation()` computes the gradients of the activation. The gradients will be multiplies in place to the gradients of the output, which can be retrieved using :code:`getOutputGrad()`. +- Compute the gradients of bias. Notice that we an use :code:`biases_->getWGrad()` to get the gradient matrix of the corresponding parameter. After the gradient of one parameter is updated, it **MUST** call :code:`getParameterPtr()->incUpdate(callback);`. This is utilize for parameter update over multiple threads or multiple machines. +- Then it computes the gradients of the transformation matrices and inputs, and it calls :code:`incUpdate` for the corresponding parameter. This gives the framework the chance to know whether it has gathered all the gradient to one parameter so that it can do some overlapping work (e.g., network communication) -The code is listed below:: +.. code-block:: c++ void FullyConnectedLayer::backward(const UpdateCallback& callback) { /* Do derivation for activations.*/ { - backwardActivation(); + backwardActivation(); } if (biases_ && biases_->getWGrad()) { - biases_->getWGrad()->collectBias(*getOutputGrad(), 1); + biases_->getWGrad()->collectBias(*getOutputGrad(), 1); - /* Increasing the number of gradient */ - biases_->getParameterPtr()->incUpdate(callback); + /* Increasing the number of gradient */ + biases_->getParameterPtr()->incUpdate(callback); } bool syncFlag = hl_get_sync_flag(); for (size_t i = 0; i != inputLayers_.size(); ++i) { - /* Calculate the W-gradient for the current layer */ - if (weights_[i]->getWGrad()) { - MatrixPtr input_T = getInputValue(i)->getTranspose(); - MatrixPtr oGrad = getOutputGrad(); - { - weights_[i]->getWGrad()->mul(input_T, oGrad, 1, 1); - } - } - - - /* Calculate the input layers error */ - MatrixPtr preGrad = getInputGrad(i); - if (NULL != preGrad) { - MatrixPtr weights_T = weights_[i]->getW()->getTranspose(); - preGrad->mul(getOutputGrad(), weights_T, 1, 1); - } - - { - weights_[i]->getParameterPtr()->incUpdate(callback); - } + /* Calculate the W-gradient for the current layer */ + if (weights_[i]->getWGrad()) { + MatrixPtr input_T = getInputValue(i)->getTranspose(); + MatrixPtr oGrad = getOutputGrad(); + { + weights_[i]->getWGrad()->mul(input_T, oGrad, 1, 1); + } + } + + + /* Calculate the input layers error */ + MatrixPtr preGrad = getInputGrad(i); + if (NULL != preGrad) { + MatrixPtr weights_T = weights_[i]->getW()->getTranspose(); + preGrad->mul(getOutputGrad(), weights_T, 1, 1); + } + + { + weights_[i]->getParameterPtr()->incUpdate(callback); + } } } +The :code:`prefetch` function specifies the rows that need to be fetched from parameter server during training. It is only useful for remote sparse training. In remote sparse training, the full parameter matrix is stored distributedly at the parameter server. When the layer uses a batch for training, only a subset of locations of the input is non-zero in this batch. Thus, this layer only needs the rows of the transformation matrix corresponding to the locations of these non-zero entries. The :code:`prefetch` function specifies the ids of these rows. -The `prefetch` function specifies the rows that need to be fetched from parameter server during training. It is only useful for remote sparse training. In remote sparse training, the full parameter matrix is stored distributedly at the parameter server. When the layer uses a batch for training, only a subset of locations of the input is non-zero in this batch. Thus, this layer only needs the rows of the transformation matrix corresponding to the locations of these non-zero entries. The `prefetch` function specifies the ids of these rows. +Most of the layers do not need remote sparse training function. You do not need to override this function in this case. -Most of the layers do not need remote sparse training function. You do not need to override this function in this case:: +.. code-block:: c++ void FullyConnectedLayer::prefetch() { for (size_t i = 0; i != inputLayers_.size(); ++i) { - auto* sparseParam = - dynamic_cast(weights_[i]->getW().get()); - if (sparseParam) { - MatrixPtr input = getInputValue(i); - sparseParam->addRows(input); - } + auto* sparseParam = + dynamic_cast(weights_[i]->getW().get()); + if (sparseParam) { + MatrixPtr input = getInputValue(i); + sparseParam->addRows(input); + } } } +Finally, you can use :code:`REGISTER_LAYER(fc, FullyConnectedLayer);` to register the layer. :code:`fc` is the identifier of the layer, and :code:`FullyConnectedLayer` is the class name of the layer. -Finally, you can use `REGISTER_LAYER(fc, FullyConnectedLayer);` to register the layer. `fc` is the identifier of the layer, and `FullyConnectedLayer` is the class name of the layer:: +.. code-block:: c++ namespace paddle { REGISTER_LAYER(fc, FullyConnectedLayer); } +If the :code:`cpp` file is put into :code:`paddle/gserver/layers`, it will be automatically added to the compilation list. -If the `cpp` file is put into `paddle/gserver/layers`, it will be automatically added to the compilation list. -================= Write Gradient Check Unit Test -================= - -An easy way to verify the correctness of new layer's implementation is to write a gradient check unit test. Gradient check unit test utilizes finite difference method to verify the gradient of a layer. It modifies the input with a small perturbation :math:`\Delta x` and observes the changes of output :math:`\Delta y`, the gradient can be computed as :math:`\frac{\Delta y}{\Delta x }`. This gradient can be compared with the gradient computed by the `backward` function of the layer to ensure the correctness of the gradient computation. Notice that the gradient check only tests the correctness of the gradient computation, it does not necessarily guarantee the correctness of the implementation of the `forward` and `backward` function. You need to write more sophisticated unit tests to make sure your layer is implemented correctly. +=============================== +An easy way to verify the correctness of new layer's implementation is to write a gradient check unit test. Gradient check unit test utilizes finite difference method to verify the gradient of a layer. It modifies the input with a small perturbation :math:`\Delta x` and observes the changes of output :math:`\Delta y`, the gradient can be computed as :math:`\frac{\Delta y}{\Delta x }`. This gradient can be compared with the gradient computed by the :code:`backward` function of the layer to ensure the correctness of the gradient computation. Notice that the gradient check only tests the correctness of the gradient computation, it does not necessarily guarantee the correctness of the implementation of the :code:`forward` and :code:`backward` function. You need to write more sophisticated unit tests to make sure your layer is implemented correctly. -All the gradient check unit tests are located in `paddle/gserver/tests/test_LayerGrad.cpp`. You are recommended to put your test into a new test file if you are planning to write a new layer. The gradient test of the gradient check unit test of the fully connected layer is listed below. It has the following steps. +All the gradient check unit tests are located in :code:`paddle/gserver/tests/test_LayerGrad.cpp`. You are recommended to put your test into a new test file if you are planning to write a new layer. The gradient test of the gradient check unit test of the fully connected layer is listed below. It has the following steps. + Create layer configuration. A layer configuration can include the following attributes: - - - size of the bias parameter. (4096 in our example) - - type of the layer. (fc in our example) - - size of the layer. (4096 in our example) - - activation type. (softmax in our example) - - dropout rate. (0.1 in our example) - + - size of the bias parameter. (4096 in our example) + - type of the layer. (fc in our example) + - size of the layer. (4096 in our example) + - activation type. (softmax in our example) + - dropout rate. (0.1 in our example) + configure the input of the layer. In our example, we have only one input. - - - type of the input (`INPUT_DATA`) in our example. It can be one of the following types - - - `INPUT_DATA`: dense vector. - - `INPUT_LABEL`: integer. - - `INPUT_DATA_TARGET`: dense vector, but it does not used to compute gradient. - - `INPUT_SEQUENCE_DATA`: dense vector with sequence information. - - `INPUT_HASSUB_SEQUENCE_DATA`: dense vector with both sequence and sub-sequence information. - - `INPUT_SEQUENCE_LABEL`: integer with sequence information. - - `INPUT_SPARSE_NON_VALUE_DATA`: 0-1 sparse data. - - `INPUT_SPARSE_FLOAT_VALUE_DATA`: float sparse data. - - - name of the input. (`layer_0` in our example) + - type of the input (:code:`INPUT_DATA`) in our example. It can be one of the following types + - :code:`INPUT_DATA`: dense vector. + - :code:`INPUT_LABEL`: integer. + - :code:`INPUT_DATA_TARGET`: dense vector, but it does not used to compute gradient. + - :code:`INPUT_SEQUENCE_DATA`: dense vector with sequence information. + - :code:`INPUT_HASSUB_SEQUENCE_DATA`: dense vector with both sequence and sub-sequence information. + - :code:`INPUT_SEQUENCE_LABEL`: integer with sequence information. + - :code:`INPUT_SPARSE_NON_VALUE_DATA`: 0-1 sparse data. + - :code:`INPUT_SPARSE_FLOAT_VALUE_DATA`: float sparse data. + - name of the input. (:code:`layer_0` in our example) - size of the input. (8192 in our example) - number of non-zeros, only useful for sparse inputs. - format of sparse data, only useful for sparse inputs. - -+ each inputs needs to call `config.layerConfig.add_inputs();` once. -+ call `testLayerGrad` to perform gradient checks. It has the following arguments. - - - layer and input configurations. (`config` in our example) - - type of the input. (`fc` in our example) ++ each inputs needs to call :code:`config.layerConfig.add_inputs();` once. ++ call :code:`testLayerGrad` to perform gradient checks. It has the following arguments. + - layer and input configurations. (:code:`config` in our example) + - type of the input. (:code:`fc` in our example) - batch size of the gradient check. (100 in our example) - - whether the input is transpose. Most layers need to set it to `false`. (`false` in our example) - - whether to use weights. Some layers or activations perform normalization so that the sum of their output is a constant. For example, the sum of output of a softmax activation is one. In this case, we cannot correctly compute the gradients using regular gradient check techniques. A weighted sum of the output, which is not a constant, is utilized to compute the gradients. (`true` in our example, because the activation of a fully connected layer can be softmax) - + - whether the input is transpose. Most layers need to set it to :code:`false`. (:code:`false` in our example) + - whether to use weights. Some layers or activations perform normalization so that the sum of their output is a constant. For example, the sum of output of a softmax activation is one. In this case, we cannot correctly compute the gradients using regular gradient check techniques. A weighted sum of the output, which is not a constant, is utilized to compute the gradients. (:code:`true` in our example, because the activation of a fully connected layer can be softmax) -The code is listed below:: +.. code-block:: c++ void testFcLayer(string format, size_t nnz) { // Create layer configuration. @@ -317,80 +313,78 @@ The code is listed below:: config.layerConfig.set_drop_rate(0.1); // Setup inputs. config.inputDefs.push_back( - {INPUT_DATA, "layer_0", 8192, nnz, ParaSparse(format)}); - config.layerConfig.add_inputs(); + {INPUT_DATA, "layer_0", 8192, nnz, ParaSparse(format)}); + config.layerConfig.add_inputs(); LOG(INFO) << config.inputDefs[0].sparse.sparse << " " - << config.inputDefs[0].sparse.format; + << config.inputDefs[0].sparse.format; for (auto useGpu : {false, true}) { - testLayerGrad(config, "fc", 100, /* trans */ false, useGpu, - /* weight */ true); + testLayerGrad(config, "fc", 100, /* trans */ false, useGpu, + /* weight */ true); } } + +If you are creating a new file for the test, such as :code:`paddle/gserver/tests/testFCGrad.cpp`, you need to add the file to :code:`paddle/gserver/tests/CMakeLists.txt`. An example is given below. All the unit tests will run when you execute the command :code:`make tests`. Notice that some layers might need high accuracy for the gradient check unit tests to work well. You need to configure :code:`WITH_DOUBLE` to `ON` when configuring cmake. -If you are creating a new file for the test, such as `paddle/gserver/tests/testFCGrad.cpp`, you need to add the file to `paddle/gserver/tests/CMakeLists.txt`. An example is given below. All the unit tests will run when you execute the command `make tests`. Notice that some layers might need high accuracy for the gradient check unit tests to work well. You need to configure `WITH_DOUBLE` to `ON` when configuring cmake. - -The code is listed below:: - +.. code-block:: bash add_unittest_without_exec(test_FCGrad - test_FCGrad.cpp - LayerGradUtil.cpp - TestUtil.cpp) + test_FCGrad.cpp + LayerGradUtil.cpp + TestUtil.cpp) add_test(NAME test_FCGrad - COMMAND test_FCGrad) + COMMAND test_FCGrad) -================= Implement Python Wrapper -================= -Implementing Python wrapper allows us to use the added layer in configuration files. All the Python wrappers are in file `python/paddle/trainer/config_parser.py`. An example of the Python wrapper for fully connected layer is listed below. It has the following steps: +======================== -- Use `@config_layer('fc’)` at the decorator for all the Python wrapper class. `fc` is the identifier of the layer. -- Implements `__init__` constructor function. +Implementing Python wrapper allows us to use the added layer in configuration files. All the Python wrappers are in file :code:`python/paddle/trainer/config_parser.py`. An example of the Python wrapper for fully connected layer is listed below. It has the following steps: - - It first call `super(FCLayer, self).__init__(name, 'fc', size, inputs=inputs, **xargs)` base constructor function. `FCLayer` is the Python wrapper class name, and `fc` is the layer identifier name. They must be correct in order for the wrapper to work. +- Use :code:`@config_layer('fc')` at the decorator for all the Python wrapper class. :code:`fc` is the identifier of the layer. +- Implements :code:`__init__` constructor function. + - It first call :code:`super(FCLayer, self).__init__(name, 'fc', size, inputs=inputs, **xargs)` base constructor function. :code:`FCLayer` is the Python wrapper class name, and :code:`fc` is the layer identifier name. They must be correct in order for the wrapper to work. - Then it computes the size and format (whether sparse) of each transformation matrix as well as the size. -The code is listed below:: + +.. code-block:: python @config_layer('fc') class FCLayer(LayerBase): - def __init__( - self, - name, - size, - inputs, - bias=True, - **xargs): - super(FCLayer, self).__init__(name, 'fc', size, inputs=inputs, **xargs) - for input_index in xrange(len(self.inputs)): - input_layer = self.get_input_layer(input_index) - psize = self.config.size * input_layer.size - dims = [input_layer.size, self.config.size] - format = self.inputs[input_index].format - sparse = format == "csr" or format == "csc" - if sparse: - psize = self.inputs[input_index].nnz - self.create_input_parameter(input_index, psize, dims, sparse, format) - self.create_bias_parameter(bias, self.config.size) - + def __init__( + self, + name, + size, + inputs, + bias=True, + **xargs): + super(FCLayer, self).__init__(name, 'fc', size, inputs=inputs, **xargs) + for input_index in xrange(len(self.inputs)): + input_layer = self.get_input_layer(input_index) + psize = self.config.size * input_layer.size + dims = [input_layer.size, self.config.size] + format = self.inputs[input_index].format + sparse = format == "csr" or format == "csc" + if sparse: + psize = self.inputs[input_index].nnz + self.create_input_parameter(input_index, psize, dims, sparse, format) + self.create_bias_parameter(bias, self.config.size) In network configuration, the layer can be specifies using the following code snippets. The arguments of this class are: -- `name` is the name identifier of the layer instance. -- `type` is the type of the layer, specified using layer identifier. -- `size` is the output size of the layer. -- `bias` specifies whether this layer instance has bias. -- `inputs` specifies a list of layer instance names as inputs. -The code is listed below:: +- :code:`name` is the name identifier of the layer instance. +- :code:`type` is the type of the layer, specified using layer identifier. +- :code:`size` is the output size of the layer. +- :code:`bias` specifies whether this layer instance has bias. +- :code:`inputs` specifies a list of layer instance names as inputs. + +.. code-block:: python Layer( - name = "fc1", - type = "fc", - size = 64, - bias = True, - inputs = [Input("pool3")] + name = "fc1", + type = "fc", + size = 64, + bias = True, + inputs = [Input("pool3")] ) - -You are also recommended to implement a helper for the Python wrapper, which makes it easier to write models. You can refer to `python/paddle/trainer_config_helpers/layers.py` for examples. +You are also recommended to implement a helper for the Python wrapper, which makes it easier to write models. You can refer to :code:`python/paddle/trainer_config_helpers/layers.py` for examples. diff --git a/doc/demo/text_generation/text_generation.md b/doc/demo/text_generation/text_generation.md index ee97139dd8f..d63f5cb6074 100644 --- a/doc/demo/text_generation/text_generation.md +++ b/doc/demo/text_generation/text_generation.md @@ -287,6 +287,7 @@ paddle train \ 2>&1 | tee 'translation/gen.log' ``` - job: set job mode to test +- save_dir: the path of saved models - num_passes and test_pass: loading model parameters from test_pass to (num_passes - 1), here only loads `data/wmt14_model/pass-00012` You will see messages like this: diff --git a/doc/ui/api/rnn/index.rst b/doc/ui/api/rnn/index.rst index 4f636a431d2..a918f02ab16 100644 --- a/doc/ui/api/rnn/index.rst +++ b/doc/ui/api/rnn/index.rst @@ -1,72 +1,71 @@ Recurrent Neural Network Configuration -===================================== +====================================== + This tutorial will guide you how to configure recurrent neural network in PaddlePaddle. PaddlePaddle supports highly flexible and efficient recurrent neural network configuration. In this tutorial, you will learn how to: + - prepare sequence data for learning recurrent neural networks. - configure recurrent neural network architecture. - generate sequence with learned recurrent neural network models. +We will use vanilla recurrent neural network, and sequence to sequence model to guide you through these steps. The code of sequence to sequence model can be found at :code:`demo/seqToseq`. +===================== +Prepare Sequence Data +===================== +PaddlePaddle does not need any preprocessing to sequence data, such as padding. The only thing that needs to be done is to set the type of the corresponding type to input. For example, the following code snippets defines three input. All of them are sequences, and the size of them are :code:`src_dict`, :code:`trg_dict`, and :code:`trg_dict`: -We will use vanilla recurrent neural network, and sequence to sequence model to guide you through these steps. The code of sequence to sequence model can be found at `/demo/seqToseq`. - - -================= -Prepare Sequence Data -================= -PaddlePaddle does not need any preprocessing to sequence data, such as padding. The only thing that needs to be done is to set the type of the corresponding type to input. For example, the following code snippets defines three input. All of them are sequences, and the size of them are `src_dict`, `trg_dict`, and `trg_dict`:: +.. code-block:: python settings.slots = [ integer_value_sequence(len(settings.src_dict)), integer_value_sequence(len(settings.trg_dict)), - integer_value_sequence(len(settings.trg_dict)) - ] + integer_value_sequence(len(settings.trg_dict))] -Then at the `process` function, each `yield` function will return three integer lists. Each integer list is treated as a sequence of integers:: +Then at the :code:`process` function, each :code:`yield` function will return three integer lists. Each integer list is treated as a sequence of integers: +.. code-block:: python yield src_ids, trg_ids, trg_ids_next -For more details description of how to write a data provider, please refer to :doc:`Python Data Provider <../py_data_provider_wrapper>`. The full data provider file is located at `./demo/seqToseq/dataprovider.py`. +For more details description of how to write a data provider, please refer to :doc:`Python Data Provider <../py_data_provider_wrapper>`. The full data provider file is located at :code:`demo/seqToseq/dataprovider.py`. -================= +=============================================== Configure Recurrent Neural Network Architecture -================= +=============================================== ----------------- +------------------------------------- Simple Gated Recurrent Neural Network ----------------- +------------------------------------- + Recurrent neural network process a sequence at each time step sequentially. An example of the architecture of LSTM is listed below. .. image:: ./bi_lstm.jpg - :align: center - + :align: center -Generally speaking, a recurrent network perform the following operations from t=1 to t=T, or reversely from t=T to t=1. +Generally speaking, a recurrent network perform the following operations from :math:`t=1` to :math:`t=T`, or reversely from :math:`t=T` to :math:`t=1`. .. math:: x_{t+1} = f_x(x_t), y_t = f_y(x_t) -where :math:`f_x(.)` is called *step function*, and :math:`f_y(.)` is called *output function*. In vanilla recurrent neural network, both of the step function and output function are very simple. However, PaddlePaddle supports the configuration of very complex architectures by modifying these two functions. We will use the sequence to sequence model with attention as an example to demonstrate how you can configure complex recurrent neural network models. In this section, we will use a simple vanilla recurrent neural network as an example of configuring simple recurrent neural network using `recurrent_group`. Notice that if you only need to use simple RNN, GRU, or LSTM, then `grumemory` and `lstmemory` is recommended because they are more computationally efficient than `recurrent_group`. - - -For vanilla RNN, at each time step, the *step function* is: +where :math:`f_x(.)` is called **step function**, and :math:`f_y(.)` is called **output function**. In vanilla recurrent neural network, both of the step function and output function are very simple. However, PaddlePaddle supports the configuration of very complex architectures by modifying these two functions. We will use the sequence to sequence model with attention as an example to demonstrate how you can configure complex recurrent neural network models. In this section, we will use a simple vanilla recurrent neural network as an example of configuring simple recurrent neural network using :code:`recurrent_group`. Notice that if you only need to use simple RNN, GRU, or LSTM, then :code:`grumemory` and :code:`lstmemory` is recommended because they are more computationally efficient than :code:`recurrent_group`. +For vanilla RNN, at each time step, the **step function** is: .. math:: x_{t+1} = W_x x_t + W_i I_t + b where :math:`x_t` is the RNN state, and :math:`I_t` is the input, :math:`W_x` and :math:`W_i` are transformation matrices for RNN states and inputs, respectively. :math:`b` is the bias. -Its *output function* simply takes :math:`x_t` as the output. - +Its **output function** simply takes :math:`x_t` as the output. -`recurrent_group` is the most important tools for constructing recurrent neural networks. It defines the *step function*, *output function* and the inputs of the recurrent neural network. Notice that the `step` argument of this function implements both the `step function` and the `output function`:: +:code:`recurrent_group` is the most important tools for constructing recurrent neural networks. It defines the **step function**, **output function** and the inputs of the recurrent neural network. Notice that the :code:`step` argument of this function implements both the :code:`step function` and the :code:`output function`: +.. code-block:: python def simple_rnn(input, size=None, @@ -79,11 +78,11 @@ Its *output function* simply takes :math:`x_t` as the output. out_mem = memory(name=name, size=size) rnn_out = mixed_layer(input = [full_matrix_projection(ipt), full_matrix_projection(out_mem)], - name = name, - bias_attr = rnn_bias_attr, - act = act, - layer_attr = rnn_layer_attr, - size = size) + name = name, + bias_attr = rnn_bias_attr, + act = act, + layer_attr = rnn_layer_attr, + size = size) return rnn_out return recurrent_group(name='%s_recurrent_group' % name, step=__rnn_step__, @@ -91,30 +90,27 @@ Its *output function* simply takes :math:`x_t` as the output. input=input) -PaddlePaddle uses memory to construct step function. *Memory* is the most important concept when constructing recurrent neural networks in PaddlePaddle. A memory is a state that is used recurrently in step functions, such as , :math:`x_{t+1} = f_x(x_t)`. One memory contains an *output* and a *input*. The output of memory at the current time step is utilized as the input of the memory at the next time step. A memory can also has a *boot layer*, whose output is utilized as the initial value of the memory. In our case, the output of the gated recurrent unit is employed as the output memory. Notice that the name of the layer `rnn_out` is the same as the name of `out_mem`. This means the output of the layer `rnn_out` (:math:`x_{t+1}`) is utilized as the *output* of `out_mem` memory. +PaddlePaddle uses memory to construct step function. **Memory** is the most important concept when constructing recurrent neural networks in PaddlePaddle. A memory is a state that is used recurrently in step functions, such as :math:`x_{t+1} = f_x(x_t)`. One memory contains an **output** and a **input**. The output of memory at the current time step is utilized as the input of the memory at the next time step. A memory can also has a **boot layer**, whose output is utilized as the initial value of the memory. In our case, the output of the gated recurrent unit is employed as the output memory. Notice that the name of the layer :code:`rnn_out` is the same as the name of :code:`out_mem`. This means the output of the layer :code:`rnn_out` (:math:`x_{t+1}`) is utilized as the **output** of :code:`out_mem` memory. A memory can also be a sequence. In this case, at each time step, we have a sequence as the state of the recurrent neural network. This can be useful when constructing very complex recurrent neural network. Other advanced functions include defining multiple memories, and defining hierarchical recurrent neural network architecture using sub-sequence. +We return :code:`rnn_out` at the end of the function. It means that the output of the layer :code:`rnn_out` is utilized as the **output** function of the gated recurrent neural network. -We return `rnn_out` at the end of the function. It means that the output of the layer `rnn_out` is utilized as the *output* function of the gated recurrent neural network. - - - ----------------- +----------------------------------------- Sequence to Sequence Model with Attention ----------------- +----------------------------------------- We will use the sequence to sequence model with attention as an example to demonstrate how you can configure complex recurrent neural network models. An illustration of the sequence to sequence model with attention is shown in the following figure. .. image:: ./encoder-decoder-attention-model.png - :align: center - + :align: center -In this model, the source sequence :math:`S = \{s_1, \dots, s_T\}` is encoded with a bidirectional gated recurrent neural networks. The hidden states of the bidirectional gated recurrent neural network :math:`H_S = \{H_S1, \dots, H_sT\}` is called *encoder vector* The decoder is a gated recurrent neural network. When decoding each token :math:`y_t`, the gated recurrent neural network generates a set of weights :math:`W_S^t = \{W_S1^t, \dots, W_sT^t\}`, which are used to compute a weighted sum of the encoder vector. The weighted sum of the encoder vector is utilized to condition the generation of the token :math:`y_t`. +In this model, the source sequence :math:`S = \{s_1, \dots, s_T\}` is encoded with a bidirectional gated recurrent neural networks. The hidden states of the bidirectional gated recurrent neural network :math:`H_S = \{H_1, \dots, H_T\}` is called *encoder vector* The decoder is a gated recurrent neural network. When decoding each token :math:`y_t`, the gated recurrent neural network generates a set of weights :math:`W_S^t = \{W_1^t, \dots, W_T^t\}`, which are used to compute a weighted sum of the encoder vector. The weighted sum of the encoder vector is utilized to condition the generation of the token :math:`y_t`. -The encoder part of the model is listed below. It calls `grumemory` to represent gated recurrent neural network. It is the recommended way of using recurrent neural network if the network architecture is simple, because it is faster than `recurrent_group`. We have implemented most of the commonly used recurrent neural network architectures, you can refer to :doc:`Layers <../trainer_config_helpers/layers>` for more details. +The encoder part of the model is listed below. It calls :code:`grumemory` to represent gated recurrent neural network. It is the recommended way of using recurrent neural network if the network architecture is simple, because it is faster than :code:`recurrent_group`. We have implemented most of the commonly used recurrent neural network architectures, you can refer to :doc:`Layers <../trainer_config_helpers/layers>` for more details. -We also project the encoder vector to `decoder_size` dimensional space, get the first instance of the backward recurrent network, and project it to `decoder_size` dimensional space:: +We also project the encoder vector to :code:`decoder_size` dimensional space, get the first instance of the backward recurrent network, and project it to :code:`decoder_size` dimensional space: +.. code-block:: python # Define the data layer of the source sentence. src_word_id = data_layer(name='source_language_word', size=source_dict_dim) @@ -143,8 +139,9 @@ We also project the encoder vector to `decoder_size` dimensional space, get the decoder_boot = mixed_layer(input=[full_matrix_projection(backward_first)], size=decoder_size, act=TanhActivation()) -The decoder uses `recurrent_group` to define the recurrent neural network. The step and output functions are defined in `gru_decoder_with_attention`:: +The decoder uses :code:`recurrent_group` to define the recurrent neural network. The step and output functions are defined in :code:`gru_decoder_with_attention`: +.. code-block:: python trg_embedding = embedding_layer( input=data_layer(name='target_language_word', @@ -168,8 +165,9 @@ The decoder uses `recurrent_group` to define the recurrent neural network. The s ]) -The implementation of the step function is listed as below. First, it defines the *memory* of the decoder network. Then it defines attention, gated recurrent unit step function, and the output function:: +The implementation of the step function is listed as below. First, it defines the **memory** of the decoder network. Then it defines attention, gated recurrent unit step function, and the output function: +.. code-block:: python def gru_decoder_with_attention(enc_vec, enc_proj, current_word): # Defines the memory of the decoder. @@ -202,21 +200,22 @@ The implementation of the step function is listed as below. First, it defines th ================= Generate Sequence ================= -After training the model, we can use it to generate sequences. A common practice is to use *beam search* to generate sequences. The following code snippets defines a beam search algorithm. Notice that `beam_search` function assumes the output function of the `step` returns a softmax normalized probability vector of the next token. We made the following changes to the model. +After training the model, we can use it to generate sequences. A common practice is to use **beam search** to generate sequences. The following code snippets defines a beam search algorithm. Notice that :code:`beam_search` function assumes the output function of the :code:`step` returns a softmax normalized probability vector of the next token. We made the following changes to the model. -* use `GeneratedInput` for trg_embedding. `GeneratedInput` computes the embedding of the generated token at the last time step for the input at the current time step. -* use `beam_search` function. This function needs to set: +* use :code:`GeneratedInput` for trg_embedding. :code:`GeneratedInput` computes the embedding of the generated token at the last time step for the input at the current time step. +* use :code:`beam_search` function. This function needs to set: - - `id_input`: the integer ID of the data, used to identify the corresponding output in the generated files. - - `dict_file`: the dictionary file for converting word id to word. - - `bos_id`: the start token. Every sentence starts with the start token. - - `eos_id`: the end token. Every sentence ends with the end token. - - `beam_size`: the beam size used in beam search. - - `max_length`: the maximum length of the generated sentences. - - `result_file`: the path of the generation result file. + - :code:`id_input`: the integer ID of the data, used to identify the corresponding output in the generated files. + - :code:`dict_file`: the dictionary file for converting word id to word. + - :code:`bos_id`: the start token. Every sentence starts with the start token. + - :code:`eos_id`: the end token. Every sentence ends with the end token. + - :code:`beam_size`: the beam size used in beam search. + - :code:`max_length`: the maximum length of the generated sentences. + - :code:`result_file`: the path of the generation result file. +The code is listed below: -The code is listed below:: +.. code-block:: python gen_inputs = [StaticInput(input=encoded_vector, is_seq=True), @@ -249,4 +248,4 @@ The code is listed below:: Notice that this generation technique is only useful for decoder like generation process. If you are working on sequence tagging tasks, please refer to :doc:`Semantic Role Labeling Demo <../../../demo/semantic_role_labeling>` for more details. -The full configuration file is located at `./demo/seqToseq/seqToseq_net.py`. +The full configuration file is located at :code:`demo/seqToseq/seqToseq_net.py`. -- GitLab