LayerGradUtil.h 10.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#pragma once
#include "ModelConfig.pb.h"
Y
Yu Yang 已提交
17 18
#include "paddle/gserver/layers/DataLayer.h"
#include "paddle/trainer/Trainer.h"
Z
zhangjinchao01 已提交
19

20
#include "paddle/testing/TestUtil.h"
Z
zhangjinchao01 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33
using namespace std;  // NOLINT

namespace paddle {
enum InputType {
  INPUT_DATA,         // dense vector
  INPUT_LABEL,        // id
  INPUT_DATA_TARGET,  // dense vector, but no gradient
  INPUT_SEQUENCE_DATA,
  INPUT_HASSUB_SEQUENCE_DATA,  // sequence has sub-sequence
  INPUT_SEQUENCE_MDIM_DATA,
  INPUT_SEQUENCE_LABEL,
  INPUT_SPARSE_NON_VALUE_DATA,
  INPUT_SPARSE_FLOAT_VALUE_DATA,
34 35
  INPUT_DENSE_DIM_DATA,    // using sequence length to init dense data
  INPUT_SELF_DEFINE_DATA,  // support customizing for input value
Z
zhangjinchao01 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
};

struct ParaSparse {
  bool sparse;
  string format;
  // if equalNnzPerSample is set true,
  // every row of the sparse matrix in a format of CSR has a same
  // number of nnz values. Currently, this flag is only used for
  // selective_fc layer
  bool equalNnzPerSample;
  ParaSparse(const string& formatIn = "") {  // NOLINT
    if (formatIn == "") {
      sparse = false;
    } else {
      sparse = true;
    }
    equalNnzPerSample = false;
  }
  ParaSparse(const string& formatIn, bool equalNnz) {
    format = formatIn;
    sparse = true;
    equalNnzPerSample = equalNnz;
  }
};

struct InputDef {
  InputType inputType;
  string name;
  size_t dim;
  size_t paraSize;
  ParaSparse sparse;
  bool isStatic;
68 69
  std::vector<int> labelInitValue;
  std::vector<int> labelSeqStartPositions;
70
  std::vector<int> labelSubSeqStartPositions;
C
caoying03 已提交
71
  std::vector<int> ids;
72
  MatrixPtr selfDefinedData;
73

Z
zhangjinchao01 已提交
74 75 76 77 78 79 80 81
  InputDef(InputType type, string nameIn, size_t dimIn, size_t sizeIn) {
    inputType = type;
    name = nameIn;
    dim = dimIn;
    paraSize = sizeIn;
    sparse = {""};
    isStatic = false;
  }
82

83 84 85
  InputDef(InputType type,
           string nameIn,
           MatrixPtr selfDefinedData,
86 87
           std::vector<int> selfDefinedSeqStartPos = {},
           std::vector<int> selfDefinedSubSeqStartPos = {})
88
      : labelSeqStartPositions(selfDefinedSeqStartPos),
89
        labelSubSeqStartPositions(selfDefinedSubSeqStartPos),
90 91 92 93 94 95 96 97
        selfDefinedData(selfDefinedData) {
    inputType = type;
    name = nameIn;
    dim = 0;
    sparse = {""};
    paraSize = 0;
    isStatic = false;
  }
C
caoying03 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

  InputDef(InputType type,
           string nameIn,
           std::vector<int> ids,
           std::vector<int> selfDefinedSeqStartPos = {},
           std::vector<int> selfDefinedSubSeqStartPos = {})
      : labelSeqStartPositions(selfDefinedSeqStartPos),
        labelSubSeqStartPositions(selfDefinedSubSeqStartPos),
        ids(ids) {
    selfDefinedData = nullptr;
    inputType = type;
    name = nameIn;
    dim = 0;
    sparse = {""};
    paraSize = 0;
    isStatic = false;
  }
115

116 117 118 119
  InputDef(InputType type,
           string nameIn,
           size_t dimIn,
           size_t sizeIn,
120 121
           const std::vector<int>& labelInitValue,
           const std::vector<int>& labelSeqStartPositions)
122 123 124 125 126 127 128 129 130 131
      : labelInitValue(labelInitValue),
        labelSeqStartPositions(labelSeqStartPositions) {
    inputType = type;
    name = nameIn;
    dim = dimIn;
    paraSize = sizeIn;
    sparse = {""};
    isStatic = false;
  }

132 133 134 135
  InputDef(InputType type,
           string nameIn,
           size_t dimIn,
           size_t sizeIn,
Z
zhangjinchao01 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148
           ParaSparse sparseIn) {
    inputType = type;
    name = nameIn;
    dim = dimIn;
    paraSize = sizeIn;
    sparse = sparseIn;
  }
};

struct TestConfig {
  LayerConfig layerConfig;
  std::vector<InputDef> inputDefs;
  size_t biasSize;
Y
yangyaming 已提交
149 150
  real paramInitialMean;
  real paramInitialStd;
Z
zhangjinchao01 已提交
151 152 153 154 155 156
  bool testAccumulate;
  bool testState;
  bool staticBias;
  bool testBatchState;
  TestConfig()
      : biasSize(0),
Y
yangyaming 已提交
157 158
        paramInitialMean(0.0),
        paramInitialStd(1.0),
Z
zhangjinchao01 已提交
159 160 161 162 163 164
        testAccumulate(true),
        testState(false),
        staticBias(false),
        testBatchState(false) {}
};

165 166 167 168
real getCostSum(ParameterPtr& parameter,
                CpuVector& cpuPara,
                LayerPtr& testLayer,
                MatrixPtr weights = nullptr);
Z
zhangjinchao01 已提交
169

170 171 172 173 174 175 176
real getDiffAndPrint(real newCost1,
                     real newCost2,
                     real callbackCount,
                     char fill,
                     string testLayerName,
                     string name,
                     real step,
Z
zhangjinchao01 已提交
177 178 179 180 181 182 183 184 185 186
                     real delta);

/**
 * @brief verify that sequentially running forward() one timestamp at one time
 *        has same result as running forward() with one whole sequence
 *
 * @param testLayer[in/out]    testLayer
 * @param dataLayers[in/out]   dataLayers
 * @param datas[in/out]        data of dataLayers
 */
187 188
void testState(LayerPtr testLayer,
               vector<DataLayerPtr>& dataLayers,
Z
zhangjinchao01 已提交
189 190 191 192 193 194 195 196 197 198
               vector<Argument>& datas);

/**
 * @brief verify that sequentially running forward() with short sequences one
 *        time has same result as running forward() with long sequences.
 *
 * @param testLayer[in/out]    testLayer
 * @param dataLayers[in/out]   dataLayers
 * @param datas[in/out]        data of dataLayers
 */
199 200
void testBatchState(LayerPtr testLayer,
                    vector<DataLayerPtr>& dataLayers,
Z
zhangjinchao01 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
                    vector<Argument>& datas);

/**
 * @brief Generate a perturbation so that it is roughly aligned with the
 *        gradient direction. This is to make sure that change along this
 *        direction will make cost increase (or decrease) in a meaningful
 *        way so that the finite difference can be used to approximate the
 *        directional dirivative well.
 *
 * @param oldGrad[in]  input gradient
 *        newGrad[out] output gradient
 *        dim          dimension of oldGrad/newGrad
 *
 * @return sum_i(oldGrad[i] * newGrad[i])
 */
double genPerturbation(const real* oldGrad, real* newGrad, size_t dim);

void initWeight(MatrixPtr& weights);

220 221 222 223
void initBatchState(LayerPtr dataLayer,
                    LayerPtr testLayer,
                    LayerStatePtr state,
                    bool useGpu);
Z
zhangjinchao01 已提交
224 225 226 227 228 229 230 231 232

/**
 * @brief initialize the dataLayer by its inputType
 *
 * @param testConf[in]        test config
 *        dataLayers[out]     dataLayers
 *        datas[out]          initialized data of dataLayers
 *        layerMap[out]       layerMap
 */
233 234 235 236 237 238 239
void initDataLayer(TestConfig testConf,
                   std::vector<DataLayerPtr>* dataLayers,
                   vector<Argument>* datas,
                   LayerMap* layerMap,
                   string testLayerName,
                   size_t batchSize,
                   bool trans,
Z
zhangjinchao01 已提交
240 241 242 243 244 245 246 247 248 249
                   bool useGpu);

/**
 * @brief initialize the parameter of testLayer
 *
 * @param testConf[in/out]    test config
 *        layerMap[out]       layerMap
 *        parameters[out]     parameters of testLayer
 *        testLayer[out]      testLayer
 */
250 251 252 253
void initTestLayer(TestConfig testConf,
                   LayerMap* layerMap,
                   std::vector<ParameterPtr>* parameters,
                   LayerPtr* testLayer);
Z
zhangjinchao01 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267

/**
 * @brief Test whether the layer's forward calculation is stable by adding
 *        perturbation to its parameters
 *
 * @param testConf[in]         test config
 *        weights[in]          weights of testLayer
 *        state[in]            state of testLayer
 *        cost[in]             input cost
 *        callbackCount[in]    number of done callback
 *        maxDiff[in/out]      max of all previous diff
 *        testLayer[in/out]    testLayer
 *        parameters[in/out]   parameters of testLayer
 */
268 269 270 271 272 273 274
void testPerturbParameter(TestConfig testConf,
                          const MatrixPtr weights,
                          const LayerStatePtr state,
                          real cost,
                          real callbackCount,
                          real* maxDiff,
                          LayerPtr testLayer,
Z
zhangjinchao01 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
                          std::vector<ParameterPtr>* parameters);

/**
 * @brief Test whether the layer's forward calculation is stable by adding
 *        perturbation to its input layers
 *
 * @param testConf[in]         test config
 *        weights[in]          weights of testLayer
 *        state[in]            state of testLayer
 *        cost[in]             input cost
 *        callbackCount[in]    number of done callback
 *        maxDiff[in/out]      max of all previous diff
 *        testLayer[in/out]    testLayer
 *        dataLayers[in/out]   dataLayers
 */
290 291 292 293 294 295 296
void testPerturbInput(TestConfig testConf,
                      const MatrixPtr weights,
                      const LayerStatePtr state,
                      real cost,
                      real callbackCount,
                      real* maxDiff,
                      LayerPtr testLayer,
Z
zhangjinchao01 已提交
297 298
                      std::vector<DataLayerPtr> dataLayers);

299 300 301 302 303 304 305
void testLayerGradKernel(TestConfig testConf,
                         string testLayerName,
                         size_t batchSize,
                         bool trans,
                         bool useGpu,
                         bool useWeight = false,
                         float epsilon = 0.02);
Z
zhangjinchao01 已提交
306

307 308 309 310 311 312
void testLayerGrad(TestConfig testConf,
                   string testLayerName,
                   size_t batchSize,
                   bool trans,
                   bool useGpu,
                   bool useWeight = false,
Z
zhangjinchao01 已提交
313 314
                   float epsilon = 0.02);

315 316 317 318 319 320 321
void testProjectionGrad(ProjectionConfig conf,
                        InputType inputType,
                        size_t parameterSize,
                        size_t batchSize,
                        bool useGpu,
                        bool testState = false,
                        int biasSize = 0,
322
                        bool sharedBias = false);
Z
zhangjinchao01 已提交
323

324 325 326 327 328
void testOperatorGrad(TestConfig& config,
                      OperatorConfig& operatorConf,
                      size_t batchSize,
                      bool useGpu,
                      bool testState = false);
Z
zhangjinchao01 已提交
329 330

}  //  namespace paddle