Argument.h 11.6 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 17
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 "hl_gpu.h"

#include "paddle/math/Matrix.h"
#include "paddle/math/Vector.h"
Y
Yu Yang 已提交
18
#include "paddle/parameter/Parameter.h"
Z
zhangjinchao01 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include "paddle/utils/Locks.h"
#include "paddle/utils/Util.h"

namespace paddle {

typedef std::shared_ptr<std::vector<std::string>> SVectorPtr;

struct Argument {
  Argument()
      : in(nullptr),
        value(nullptr),
        ids(nullptr),
        grad(nullptr),
        strs(nullptr),
        frameHeight(0),
        frameWidth(0),
35
        frameDepth(0),
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
        sequenceStartPositions(nullptr),
        subSequenceStartPositions(nullptr),
        cpuSequenceDims(nullptr),
        deviceId(-1),
        allCount(0),
        valueCount(0),
        gradCount(0),
        dataId(0) {}
  Argument(const Argument& argument) {
    *this = argument;
    valueCount = 0;
    gradCount = 0;
    dataId = argument.dataId;
  }
  ~Argument() {}

  void operator=(const Argument& argument) {
    in = argument.in;
    value = argument.value;
    ids = argument.ids;
    grad = argument.grad;
    strs = argument.strs;
    sequenceStartPositions = argument.sequenceStartPositions;
    subSequenceStartPositions = argument.subSequenceStartPositions;
    cpuSequenceDims = argument.cpuSequenceDims;
    deviceId = argument.deviceId;
    allCount = argument.allCount;
    frameHeight = argument.frameHeight;
    frameWidth = argument.frameWidth;
65
    frameDepth = argument.frameDepth;
Z
zhangjinchao01 已提交
66 67 68 69 70 71 72 73 74 75 76 77
    dataId = argument.dataId;
  }

  MatrixPtr in;  // used if needed
  MatrixPtr value;
  IVectorPtr ids;  // a sequence of ids. Can be use for class id for costLayer
  MatrixPtr grad;  // If empty, gradient is not needed.
  SVectorPtr strs;

  // A dataBatch includes batchSize frames, one frame maybe not only vector
  size_t frameHeight;
  size_t frameWidth;
78
  size_t frameDepth;
Z
zhangjinchao01 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

  // If NULL, each position is treated independently.
  // Otherwise, its size should be #NumberOfSequences + 1.
  // The first position is always 0 and
  // the last position should be equal to batchSize.
  ICpuGpuVectorPtr sequenceStartPositions;

  // If NULL, each sequence has no subsequence.
  // Otherwise, its size should be #NumberOfSubSequences + 1.
  // The first position is always 0 and
  // the last position should be equal to batchSize.
  ICpuGpuVectorPtr subSequenceStartPositions;

  // dimension of sequence, stored only in CPU
  IVectorPtr cpuSequenceDims;

  int deviceId;            // the GPU device id which the argument in
  int allCount;            // the number of output layers using this argument
  mutable int valueCount;  // waiting this member when layer do forward
  mutable int gradCount;   // waiting this member when layer do backward
  mutable LockedCondition valueReadyCond;
  mutable LockedCondition gradReadyCond;

  int dataId;  // dataProvider id

  /* Increase the reference count of the argument. */
  void countIncrement() { allCount++; }

  int getAllCount() const { return allCount; }

  void waitValueReady() const {
    valueReadyCond.wait([this] { return (valueCount != 0); });

    std::lock_guard<std::mutex> guard(*valueReadyCond.mutex());
    valueCount--;
  }

  void notifyValueReady() const {
    valueReadyCond.notify_all([this] { valueCount = allCount; });
  }

  void waitGradReady() const {
    gradReadyCond.wait([this] { return (gradCount == allCount); });
    gradCount = 0;
  }

  void notifyGradReady() const {
    gradReadyCond.notify_all([this] { gradCount++; });
  }

  int64_t getBatchSize() const {
    if (value) return value->getHeight();
    if (ids) return ids->getSize();
    if (grad) return grad->getHeight();
    if (in) return in->getHeight();
    if (strs) return strs->size();
    return 0;
  }
  size_t getFrameHeight() const { return frameHeight; }
  size_t getFrameWidth() const { return frameWidth; }
139
  size_t getFrameDepth() const { return frameDepth; }
Z
zhangjinchao01 已提交
140 141
  void setFrameHeight(size_t h) { frameHeight = h; }
  void setFrameWidth(size_t w) { frameWidth = w; }
142
  void setFrameDepth(size_t d) { frameDepth = d; }
Z
zhangjinchao01 已提交
143 144 145 146 147 148 149

  int64_t getNumSequences() const {
    return sequenceStartPositions ? sequenceStartPositions->getSize() - 1
                                  : getBatchSize();
  }

  int64_t getNumSubSequences() const {
150 151
    return subSequenceStartPositions ? subSequenceStartPositions->getSize() - 1
                                     : getBatchSize();
Z
zhangjinchao01 已提交
152 153
  }

154
  bool hasSeq() const { return sequenceStartPositions != nullptr; }
Z
zhangjinchao01 已提交
155 156 157 158 159 160 161
  bool hasSubseq() const { return subSequenceStartPositions != nullptr; }

  const int* getCpuStartPositions() const {
    return hasSubseq() ? subSequenceStartPositions->getData(false)
                       : sequenceStartPositions->getData(false);
  }

162
  static inline real sum(const std::vector<Argument>& arguments) {
Z
zhangjinchao01 已提交
163 164 165 166 167 168 169 170 171 172 173
    real cost = 0;
    for (auto& arg : arguments) {
      if (arg.value) {
        SetDevice device(arg.deviceId);
        cost += arg.value->getSum();
      }
    }
    return cost;
  }

  /**
174
   * @brief (value, ids, grad, sequenceStartPositions) of output are subset of
Z
zhangjinchao01 已提交
175 176 177
   *        input. Note that, output share the same memory of input.
   *
   * @param input[in]       input
178
   * @param offset[in]      offset in terms of rows
Z
zhangjinchao01 已提交
179 180 181 182 183 184 185 186
   * @param height[in]      height of output.value
   * @param width[in]       width of output.value
   * @param useGpu[in]
   * @param trans[in]       whether input.value is transform
   * @param seqFlag[in]     whether input has sequenceStartPositions
   * @param seqStart[in]    offset of input.sequenceStartPositions
   * @param seqSize[in]     lenght of output.sequenceStartPositions
   */
187 188 189 190 191 192 193 194
  void subArgFrom(const Argument& input,
                  size_t offset,
                  size_t height,
                  size_t width,
                  bool useGpu,
                  bool trans = false,
                  bool seqFlag = false,
                  size_t seqStart = 0,
Z
zhangjinchao01 已提交
195 196 197 198 199 200 201 202 203 204
                  size_t seqSize = 0);
  /*
   * for sequence input:
   *   startSeq: the sequence id of start
   *   copySize: how many sequences need to copy
   *   return value: how many samples are copied
   * for non-sequence input:
   *   startSeq: the sample id of start
   *   copySize: how many samples need to copy
   *   return value: how many samples are copied
205 206
   * Note that when specifying the stream explicitly in this case,
   * synchronize should also be called somewhere after this function
Z
zhangjinchao01 已提交
207
   */
208 209 210 211 212
  int32_t resizeAndCopyFrom(const Argument& src,
                            int32_t startSeq,
                            int32_t copySize,
                            bool useGpu,
                            hl_stream_t stream);
Z
zhangjinchao01 已提交
213

214 215 216 217 218
  /*
   * same with the above function, except that the stream is
   * HPPL_STREAM_DEFAULT and synchronize is automatically called
   * inside it
   */
219 220 221 222
  int32_t resizeAndCopyFrom(const Argument& src,
                            int32_t startSeq,
                            int32_t copySize,
                            bool useGpu = FLAGS_use_gpu);
223 224 225

  void resizeAndCopyFrom(const Argument& src, bool useGpu, hl_stream_t stream);

226 227 228 229 230
  /*
   * same with the above function, except that the stream is
   * HPPL_STREAM_DEFAULT and synchronize is automatically called
   * inside it
   */
231
  void resizeAndCopyFrom(const Argument& src, bool useGpu = FLAGS_use_gpu);
Z
zhangjinchao01 已提交
232 233 234 235 236 237 238 239 240 241 242 243

  /*
    @brief Concatenate several arguments into one and put the result into it.
    @param args : a vector of argument, each element of which is a frame in a
    batch of sequences.
    @param selectRows : select several row of args to concatenate
    @param seqStartPos : sequence start positions in the final Argument
    @param hl_stream_t : cuda stream
    @param passTyoe : type of task, training or testing
   */
  void concat(const std::vector<Argument>& args,
              const std::vector<int>& selectRows,
244
              const std::vector<int>& seqStartPos,
245
              const std::vector<int>& copySize,
246 247 248
              bool useGpu,
              hl_stream_t stream,
              PassType passType);
Z
zhangjinchao01 已提交
249 250 251 252

  /*
    Concatenate several args into one and put the result into this.
   */
253 254
  void concat(const std::vector<Argument>& src,
              bool useGpu = FLAGS_use_gpu,
Z
zhangjinchao01 已提交
255 256 257 258 259 260 261 262 263
              hl_stream_t stream = HPPL_STREAM_DEFAULT,
              PassType passType = PASS_TEST);

  /*
   * split vector<Argument> to several vectors according to dataId
   */
  static void splitByDataId(const std::vector<Argument>& argus,
                            std::vector<std::vector<Argument>>* arguGroups);

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
  struct SeqInfo {
    // Equal to sequence length for sequence data
    // Equal to number of subsequences for subsequence data
    int topLevelLength;

    int seqStart;
    int seqId;

    // Equal to topLevelLength for sequence data
    // Equal to sum of the length of subsequences for subsequence data
    int subLevelLength;

    // Only used for subsequence data, start position of this sequence
    // is subSequenceStartPositions, i.e.
    // subSequenceStartPositions[subSeqStart] == seqStart
    int subSeqStart;
  };
Z
zhangjinchao01 已提交
281
  /*
282 283 284 285 286
    Get SeqInfo for each sequence of this argument
    Elements in *seqInfo are sorted by topLevelLength in descending order
  */
  void getSeqInfo(std::vector<SeqInfo>* segInfo) const;

Z
zhangjinchao01 已提交
287 288 289 290 291 292 293 294 295
  /*
   Check Whether sequenceStartPositions is subset of
   subSequenceStartPositions.
   */
  void checkSubset() const;

  /*
   sequence has sub-sequence degrades to a sequence.
   */
296
  void degradeSequence(const Argument& input);
297

298 299 300
  /*
   After pooling with stride n (n is smaller than sequence length),
   a long sequence will be shorten.
L
Luo Tao 已提交
301
   This function is invalid for sequence having sub-sequence.
302 303 304
   */
  void poolSequenceWithStride(const Argument& input,
                              size_t stride,
305
                              ICpuGpuVectorPtr* stridePositions,
L
Luo Tao 已提交
306
                              bool reversed = false);
307 308 309 310 311 312 313
  /**
   * @brief getValueString will return the argument's output in string. There
   * are several kinds of output. The keys of output dictionary are 'value',
   * 'id', 'sequence pos', 'sub-sequence pos'.
   * @param out [out]: the return values.
   */
  void getValueString(std::unordered_map<std::string, std::string>* out) const;
314

Y
Yu Yang 已提交
315 316 317 318 319 320
  /**
   * @brief printValueString will print the argument's output in order of
   * 'value', 'id', 'sequence pos', 'sub-sequence pos'.
   * @param stream: Output stream
   * @param prefix: line prefix for printing.
   */
321 322
  void printValueString(std::ostream& stream,
                        const std::string& prefix = "") const;
C
caoying03 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

  /**
   * @brief reorganizeSeqInfo will reorganize sequenceStartPositions and
   * subSequenceStartPositions into a 2 dimensional arrary: reorganizedSeqInfo.
   *
   * @param seqStartPos: sequenceStartPositions of an Argument.
   * @param subSeqStartPos: subSequenceStartPositions of an Argument.
   * @param the reorganized sequence start position information.
   *
   * Examples:
   * seqStartPos: [0, 4, 15, 20, 28]
   * subSeqStartPos: [0, 3, 4, 5, 7, 10, 15, 20, 22, 23, 25, 28]
   * reorganizedSeqInfo:
   *   [
   *     [0,3,4],
   *     [4,5,7,10,15],
   *     [15,20],
   *     [20,22,23,25,28]
   *   ]
   */
  static void reorganizeSeqInfo(
      const ICpuGpuVectorPtr seqStartPos,
      const ICpuGpuVectorPtr subSeqStartPos,
      std::vector<std::vector<int>>& reorganizedSeqInfo);
Z
zhangjinchao01 已提交
347 348 349
};

}  // namespace paddle