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

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 <stddef.h>
#include <stdint.h>
19
#include <stdexcept>
Y
Yu Yang 已提交
20
#include <string>
Z
zhangjinchao01 已提交
21
#include <vector>
X
Xin Pan 已提交
22
#include "paddle/legacy/gserver/gradientmachines/GradientMachine.h"
L
liaogang 已提交
23
#include "paddle/utils/Common.h"
Z
zhangjinchao01 已提交
24 25
#include "paddle/utils/GlobalConstants.h"

L
lipeng17 已提交
26
/// Import PaddlePaddle's enumeration into global namespace.
Z
zhangjinchao01 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
using namespace paddle::enumeration_wrapper;  // NOLINT

/**
 * @brief Initialize paddle.
 *
 * In python, this method should be invoked as
 * @code
 *  import sys
 *  import paddle
 *  paddle.initPaddle(sys.argv)
 *  or you can change arguments as any list of str.
 * @endcode
 */
void initPaddle(int argc, char** argv);

42
/// Return FLAGS_use_gpu
43
bool isUsingGpu();
44

45 46 47
/// Set the Flags_use_gpu to the given parameter
void setUseGpu(bool useGpu);

Z
zhangjinchao01 已提交
48 49 50
/// Return true if this py_paddle is compiled in GPU Version
bool isGpuVersion();

D
dangqingqing 已提交
51
/// Return FLAGS_trainer_count
52 53
int getTrainerCount();

Z
zhangjinchao01 已提交
54 55 56 57 58 59 60
/// The Error of IO Operation. Such as file not found, etc.
class IOError {};

/// Out of range error
class RangeError {};

/// Not support Error, such as access GPU memory directly, etc.
61
class UnsupportError : public std::runtime_error {
W
Wu Yi 已提交
62 63 64 65
 public:
  UnsupportError() : std::runtime_error(" ") {}
  explicit UnsupportError(const std::string& message)
      : std::runtime_error(message) {}
66
};
Z
zhangjinchao01 已提交
67 68 69

/// This type will map to python's list of float.
struct FloatArray {
L
liaogang 已提交
70
  const float* buf;
Z
zhangjinchao01 已提交
71 72
  const size_t length;
  bool needFree;  // true if the buf is dynamic alloced.
L
liaogang 已提交
73
  FloatArray(const float* b, const size_t l);
Z
zhangjinchao01 已提交
74 75 76 77 78 79 80 81 82 83 84 85
};

/// This type will map to python's list of int
struct IntArray {
  const int* buf;
  const size_t length;
  bool needFree;
  IntArray(const int* b, const size_t l, bool f = false);
};

/// This type will map to python's list of (int, float)
struct IntWithFloatArray {
L
liaogang 已提交
86
  const float* valBuf;
Z
zhangjinchao01 已提交
87 88 89
  const int* idxBuf;
  const size_t length;
  bool needFree;
L
liaogang 已提交
90
  IntWithFloatArray(const float* v, const int* i, size_t l, bool f = false);
Z
zhangjinchao01 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
};

enum SparseValueType { SPARSE_NON_VALUE = 0, SPARSE_VALUE = 1 };

enum SparseFormatType { SPARSE_CSR = 0, SPARSE_CSC = 1 };

/**
 * In Python, -1UL is hard to write. So define a const value used by python
 * side.
 */
const size_t NO_SPARSE_ID = -1UL;

struct MatrixPrivate;
class Matrix {
  Matrix();  // User Cannot Create Matrix.
106
  DISABLE_COPY(Matrix);
Z
zhangjinchao01 已提交
107 108
  static Matrix* createByPaddleMatrixPtr(void* sharedPtr);

W
Wu Yi 已提交
109
 public:
Z
zhangjinchao01 已提交
110 111 112 113 114
  virtual ~Matrix();

  /**
   * Create A Matrix with height,width, which is filled by zero.
   */
115 116
  static Matrix* createZero(size_t height,
                            size_t width,
117
                            bool useGpu = isUsingGpu());
Z
zhangjinchao01 已提交
118 119 120 121 122 123 124 125 126 127

  /**
   * Create Sparse Matrix.
   *
   * After create sparse, sparseCopyFrom can be used to fill matrix.
   *
   * @param nnz  Number of non zero values.
   *
   * @note the default sparse type is SPARSE_CSR.
   */
128 129 130 131 132
  static Matrix* createSparse(size_t height,
                              size_t width,
                              size_t nnz,
                              bool isNonVal = true,
                              bool trans = false,
133
                              bool useGpu = isUsingGpu());
Z
zhangjinchao01 已提交
134 135 136 137 138 139 140

  /**
   * Create Dense Matrix.
   *
   * @param data  list of float should be passed in python.
   * @note        the value will be copy into a new matrix.
   */
141 142 143 144 145 146 147 148 149 150 151
  static Matrix* createDense(const std::vector<float>& data,
                             size_t height,
                             size_t width,
                             bool useGpu = isUsingGpu());

  static Matrix* createDenseFromNumpy(
      float* data,
      int dim1,
      int dim2,
      bool copy = true,
      bool useGpu = isUsingGpu()) throw(UnsupportError);
Z
zhangjinchao01 已提交
152 153 154 155 156 157 158 159

  /**
   *  Create Cpu Dense Matrix from numpy matrix, dtype=float32
   *
   *  @param data  a numpy matrix.
   *  @param dim1  dimension of data.
   *  @param dim2  dimension of data.
   *  @param copy  true if copy into a new matrix, false will create
X
xuwei06 已提交
160 161 162 163
   *               matrix inplace. copy = false should be used with extreme
   *               care because Matrix will share the memory with the given
   *               numpy array. If the numpy array object is no longer valid,
   *               the memory space will not be usable.
Z
zhangjinchao01 已提交
164
   */
165 166 167
  static Matrix* createCpuDenseFromNumpy(float* data,
                                         int dim1,
                                         int dim2,
X
xuwei06 已提交
168
                                         bool copy = true);
Z
zhangjinchao01 已提交
169 170

  /// Create Gpu Dense Matrix from numpy matrix, dtype=float32
L
liaogang 已提交
171
  static Matrix* createGpuDenseFromNumpy(float* data, int dim1, int dim2);
Z
zhangjinchao01 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

  /**
   * Cast to numpy matrix.
   *
   * @note    This method take no parameter in python.
   * @note    This method in python will return a numpy matrix, not void.
   * @note    Only CpuDenseMatrix is supported.
   *
   * Example:
   * @code
   * import paddle
   * m = paddle.Matrix.createZero(10,2)
   * numpy_mat = m.toNumpyMat()
   * @endcode
   */
187 188
  void toNumpyMatInplace(float** view_data,
                         int* dim1,
Z
zhangjinchao01 已提交
189 190 191
                         int* dim2) throw(UnsupportError);

  /// Copy To numpy mat.
192 193
  void copyToNumpyMat(float** view_m_data,
                      int* dim1,
Z
zhangjinchao01 已提交
194 195 196
                      int* dim2) throw(UnsupportError);

  /// Copy From Numpy Mat
L
liaogang 已提交
197
  void copyFromNumpyMat(float* data, int dim1, int dim2) throw(UnsupportError,
Z
zhangjinchao01 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
                                                               RangeError);

  /// return true if this matrix is sparse.
  bool isSparse() const;

  SparseValueType getSparseValueType() const throw(UnsupportError);

  SparseFormatType getSparseFormat() const throw(UnsupportError);

  IntArray getSparseRowCols(size_t i) const throw(UnsupportError, RangeError);

  IntWithFloatArray getSparseRowColsVal(size_t i) const
      throw(UnsupportError, RangeError);

  size_t getHeight() const;

  size_t getWidth() const;

L
liaogang 已提交
216
  float get(size_t x, size_t y) const throw(RangeError);
Z
zhangjinchao01 已提交
217

L
liaogang 已提交
218
  void set(size_t x, size_t y, float val) throw(RangeError, UnsupportError);
Z
zhangjinchao01 已提交
219 220 221 222 223 224 225 226 227 228 229

  /// return type is list of float
  FloatArray getData() const;

  /**
   * Copy from rows, cols, values.
   *
   * if sparse_nonvalue, the values should be []
   */
  void sparseCopyFrom(const std::vector<int>& rows,
                      const std::vector<int>& cols,
L
liaogang 已提交
230 231
                      const std::vector<float>& values =
                          std::vector<float>()) throw(UnsupportError);
Z
zhangjinchao01 已提交
232 233 234

  bool isGpu() const;

W
Wu Yi 已提交
235
 private:
Z
zhangjinchao01 已提交
236 237 238 239 240 241 242 243 244 245
  void* getSharedPtr() const;

  MatrixPrivate* m;
  friend class Trainer;
  friend class GradientMachine;
  friend class Arguments;
};

struct VectorPrivate;
class Vector {
246
  DISABLE_COPY(Vector);
Z
zhangjinchao01 已提交
247 248 249 250 251
  Vector();
  static Vector* createByPaddleVectorPtr(void* ptr);

  void* getSharedPtr();

W
Wu Yi 已提交
252
 public:
Z
zhangjinchao01 已提交
253 254 255
  ~Vector();

  /// Create Vector filled with zero.
256
  static Vector* createZero(size_t sz, bool useGpu = isUsingGpu());
Z
zhangjinchao01 已提交
257 258 259 260 261 262

  /**
   * Create Vector from list of float.
   *
   * It will create a new vector, and copy data into it.
   */
263
  static Vector* create(const std::vector<float>& data,
264
                        bool useGpu = isUsingGpu());
Z
zhangjinchao01 已提交
265

266 267 268 269 270
  static Vector* createVectorFromNumpy(
      float* data,
      int dim,
      bool copy = true,
      bool useGpu = isUsingGpu()) throw(UnsupportError);
Z
zhangjinchao01 已提交
271 272 273 274 275
  /**
   * Create Cpu Vector from numpy array, which dtype=float32
   *
   * If copy is false, it will create vector inplace.
   */
276 277
  static Vector* createCpuVectorFromNumpy(float* data,
                                          int dim,
X
xuwei06 已提交
278
                                          bool copy = true);
Z
zhangjinchao01 已提交
279 280

  /// Create Gpu Vector from numpy array, which dtype=float32
L
liaogang 已提交
281
  static Vector* createGpuVectorFromNumpy(float* data, int dim);
Z
zhangjinchao01 已提交
282

X
xuwei06 已提交
283 284 285 286 287 288 289
  /**
   * copy from another vector
   * throw(RangeError) if size of src vector is different from size of this
   * vector
   */
  void copyFrom(Vector* src) throw(RangeError);

Z
zhangjinchao01 已提交
290
  /// Cast to numpy array inplace.
L
liaogang 已提交
291
  void toNumpyArrayInplace(float** view_data, int* dim1) throw(UnsupportError);
Z
zhangjinchao01 已提交
292 293

  /// Copy to numpy array.
L
liaogang 已提交
294
  void copyToNumpyArray(float** view_m_data, int* dim1);
Z
zhangjinchao01 已提交
295 296

  /// Copy from numpy array.
L
liaogang 已提交
297
  void copyFromNumpyArray(float* data, int dim);
Z
zhangjinchao01 已提交
298 299

  /// __getitem__ in python
L
liaogang 已提交
300
  float get(const size_t idx) const throw(RangeError, UnsupportError);
Z
zhangjinchao01 已提交
301 302

  /// __setitem__ in python
L
liaogang 已提交
303
  void set(const size_t idx, float val) throw(RangeError, UnsupportError);
Z
zhangjinchao01 已提交
304 305 306 307

  /// Return is GPU vector or not.
  bool isGpu() const;

308 309 310
  /// Return a list of float, the memory is alloced and copied.
  FloatArray getData() const;

Z
zhangjinchao01 已提交
311 312 313
  /// __len__ in python
  size_t getSize() const;

W
Wu Yi 已提交
314
 private:
Z
zhangjinchao01 已提交
315 316
  VectorPrivate* m;

W
Wu Yi 已提交
317
 private:
Z
zhangjinchao01 已提交
318 319 320 321 322 323 324 325
  friend class Parameter;
  friend class ParameterOptimizer;
  friend struct ParameterTraverseCallbackPrivate;
};

struct IVectorPrivate;
class IVector {
  IVector();
326
  DISABLE_COPY(IVector);
Z
zhangjinchao01 已提交
327 328
  static IVector* createByPaddleVectorPtr(void* ptr);

W
Wu Yi 已提交
329
 public:
Z
zhangjinchao01 已提交
330
  /// Create IVector filled with zero
331
  static IVector* createZero(size_t sz, bool useGpu = isUsingGpu());
Z
zhangjinchao01 已提交
332 333 334 335 336

  /**
   * Create IVector from list of int.
   * It will create a new vector, and copy data into it.
   */
337
  static IVector* create(const std::vector<int>& data,
338
                         bool useGpu = isUsingGpu());
339

340 341 342 343 344
  static IVector* createVectorFromNumpy(
      int* data,
      int dim,
      bool copy = true,
      bool useGpu = isUsingGpu()) throw(UnsupportError);
Z
zhangjinchao01 已提交
345 346 347 348 349 350

  /**
   * Create Cpu IVector from numpy array, which dtype=int32
   *
   * If copy is false, it will create vector inplace
   */
351 352
  static IVector* createCpuVectorFromNumpy(int* data,
                                           int dim,
X
xuwei06 已提交
353
                                           bool copy = true);
Z
zhangjinchao01 已提交
354 355 356
  /**
   * Create Gpu IVector from numpy array, which dtype=int32
   */
357
  static IVector* createGpuVectorFromNumpy(int* data, int dim);
Z
zhangjinchao01 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

  /// Cast to numpy array inplace.
  void toNumpyArrayInplace(int** view_data, int* dim1) throw(UnsupportError);

  /// Copy to numpy array.
  void copyToNumpyArray(int** view_m_data, int* dim1);

  /// Copy from numpy array.
  void copyFromNumpyArray(int* data, int dim);

  virtual ~IVector();

  /// Return a list of int, the memory is alloced and copied.
  IntArray getData() const;

  /// This method will map to python [] method.
  int& operator[](const size_t idx) throw(RangeError, UnsupportError);

  const int& operator[](const size_t idx) const
      throw(RangeError, UnsupportError);

  inline int get(const size_t idx) const throw(RangeError, UnsupportError) {
    return (*this)[idx];
  }

  inline void set(const size_t idx, int val) throw(RangeError, UnsupportError) {
    (*this)[idx] = val;
  }

  /// Return true if it is gpu vector.
  bool isGpu() const;

  /// This method will map to python __len__();
  size_t getSize() const;

W
Wu Yi 已提交
393
 private:
Z
zhangjinchao01 已提交
394 395 396 397 398 399 400 401 402 403
  void* getSharedPtr() const;

  friend class Arguments;
  IVectorPrivate* m;
};

struct ArgumentsPrivate;

/// The Arguments is actual a std::vector<paddle::Argument> in paddle.
class Arguments {
W
Wu Yi 已提交
404
 private:
Z
zhangjinchao01 已提交
405
  Arguments();  // Internal Create.
406
  DISABLE_COPY(Arguments);
Z
zhangjinchao01 已提交
407

W
Wu Yi 已提交
408
 public:
Z
zhangjinchao01 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
  /**
   * Create a arguments with size.
   * Note that it can be zero.
   */
  static Arguments* createArguments(size_t slotNum);

  void resize(size_t slotNum);

  virtual ~Arguments();

  /**
   * Return the slot number that aguments contains.
   *
   * It is actually the vector's size
   */
  size_t getSlotNum() const;

  /**
   * The get functions of Arguments
   *
   * the param idx is the slot id
   */
  Matrix* getSlotValue(size_t idx) const throw(RangeError);
X
xuwei06 已提交
432
  Matrix* getSlotGrad(size_t idx) const throw(RangeError);
Z
zhangjinchao01 已提交
433 434 435
  IVector* getSlotIds(size_t idx) const throw(RangeError);
  Matrix* getSlotIn(size_t idx) const throw(RangeError);
  IVector* getSlotSequenceStartPositions(size_t idx) const throw(RangeError);
436
  IVector* getSlotSubSequenceStartPositions(size_t idx) const throw(RangeError);
Z
zhangjinchao01 已提交
437 438 439 440 441 442 443 444 445 446 447 448
  IVector* getSlotSequenceDim(size_t idx) const throw(RangeError);
  // End Of get functions of Arguments

  int64_t getBatchSize(size_t idx = 0) const throw(RangeError);

  /**
   * The set functions of Arguments.
   *
   * The param idx is the slot id.
   * The other param is the input Matrix or vector.
   */
  void setSlotValue(size_t idx, Matrix* mat) throw(RangeError);
X
xuwei06 已提交
449
  void setSlotGrad(size_t idx, Matrix* mat) throw(RangeError);
Z
zhangjinchao01 已提交
450 451 452 453
  void setSlotIn(size_t idx, Matrix* mat) throw(RangeError);
  void setSlotIds(size_t idx, IVector* vec) throw(RangeError);
  void setSlotSequenceStartPositions(size_t idx,
                                     IVector* vec) throw(RangeError);
454
  void setSlotSubSequenceStartPositions(size_t idx,
Y
yuyang18 已提交
455
                                        IVector* vec) throw(RangeError);
Z
zhangjinchao01 已提交
456 457
  void setSlotSequenceDim(size_t idx, IVector* vec) throw(RangeError);

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  /**
   * Set the frame height of the idx-th Argument.
   *
   * @param ids The index of which Argument.
   * @param h The height value.
   */
  void setSlotFrameHeight(size_t idx, size_t h) throw(RangeError);

  /**
   * Set the frame height of the idx-th Argument.
   *
   * @param ids The index of which Argument.
   * @param h The height value.
   */
  void setSlotFrameWidth(size_t idx, size_t w) throw(RangeError);

  size_t getSlotFrameHeight(size_t idx = 0) const throw(RangeError);
  size_t getSlotFrameWidth(size_t idx = 0) const throw(RangeError);

477
  float sum() const;
Y
Yu Yang 已提交
478

W
Wu Yi 已提交
479
 private:
Z
zhangjinchao01 已提交
480
  static Arguments* createByPaddleArgumentVector(void* ptr);
L
liaogang 已提交
481
  static Arguments* createByPaddleArgument(const void* ptr);
Z
zhangjinchao01 已提交
482 483
  void* getInternalArgumentsPtr() const;

W
Wu Yi 已提交
484
 private:
Z
zhangjinchao01 已提交
485 486 487 488 489 490 491
  ArgumentsPrivate* m;
  friend class Trainer;
  friend class GradientMachine;
  friend class SequenceGenerator;
};

enum GradientMatchineCreateMode {
Q
qiaolongfei 已提交
492
  CREATE_MODE_NORMAL = paddle::GradientMachine::kNormal,
Q
qiaolongfei 已提交
493 494
  CREATE_MODE_SGD_SPARSE_CPU_TRAINING =
      paddle::GradientMachine::kSgdSparseCpuTraining,
Q
qiaolongfei 已提交
495
  CREATE_MODE_TESTING = paddle::GradientMachine::kTesting
Z
zhangjinchao01 已提交
496 497 498 499
};

struct ParameterConfigPrivate;
class ParameterConfig {
500
  DISABLE_COPY(ParameterConfig);
Z
zhangjinchao01 已提交
501 502 503 504 505 506 507 508 509 510
  ParameterConfig();

  /**
   * Internal methods
   */
  static ParameterConfig* createParameterConfigFromParameterSharedPtr(
      void* ptr);
  static ParameterConfig* createParameterConfigFromParameterPtr(void* ptr);
  void* getRawPtr();

W
Wu Yi 已提交
511
 public:
Z
zhangjinchao01 已提交
512 513 514 515 516 517 518
  ~ParameterConfig();

  /**
   * return proto buf string.
   */
  std::string toProtoString() const;

W
Wu Yi 已提交
519
 private:
Z
zhangjinchao01 已提交
520 521
  ParameterConfigPrivate* m;

W
Wu Yi 已提交
522
 private:
Z
zhangjinchao01 已提交
523 524 525 526 527 528 529
  friend class Parameter;
  friend class ParameterOptimizer;
  friend struct ParameterTraverseCallbackPrivate;
};

struct OptimizationConfigPrivate;
class OptimizationConfig {
530
  DISABLE_COPY(OptimizationConfig);
Z
zhangjinchao01 已提交
531 532
  OptimizationConfig();

W
Wu Yi 已提交
533
 public:
Z
zhangjinchao01 已提交
534 535 536 537 538 539 540 541
  static OptimizationConfig* createFromProtoString(const std::string& str);
  ~OptimizationConfig();

  /**
   * return protobuf string.
   */
  std::string toProtoString();

W
Wu Yi 已提交
542
 private:
Z
zhangjinchao01 已提交
543 544 545 546
  OptimizationConfigPrivate* m;

  friend class TrainerConfig;
  friend class ParameterOptimizer;
Y
Yu Yang 已提交
547
  friend class ParameterUpdater;
E
emailweixu 已提交
548
  friend class Trainer;
Z
zhangjinchao01 已提交
549 550 551 552
};

struct ParameterPrivate;
class Parameter {
W
Wu Yi 已提交
553
 private:
Z
zhangjinchao01 已提交
554
  Parameter();
555
  DISABLE_COPY(Parameter);
Z
zhangjinchao01 已提交
556

W
Wu Yi 已提交
557
 public:
Z
zhangjinchao01 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
  virtual ~Parameter();

  /**
   * get parameter name
   */
  std::string getName() const;

  /**
   * get buf in Parameter
   */
  Vector* getBuf(ParameterType type);

  /**
   * get id
   */
  size_t getID() const;

  ParameterConfig* getConfig();
X
xuwei06 已提交
576
  void setValueUpdated();
Z
zhangjinchao01 已提交
577

Y
Yu Yang 已提交
578 579 580 581
  bool save(const std::string& filename) const;

  bool load(const std::string& filename) const;

Y
Yu Yang 已提交
582 583
  size_t getSize() const;

W
Wu Yi 已提交
584
 private:
Z
zhangjinchao01 已提交
585 586 587
  static Parameter* createFromRawPtr(void* ptr);
  static Parameter* createFromSharedPtr(void* ptr);

W
Wu Yi 已提交
588
 private:
Z
zhangjinchao01 已提交
589 590 591
  ParameterPrivate* m;
  friend class UpdateCallbackWrapper;
  friend class GradientMachine;
Y
Yu Yang 已提交
592
  friend class ParameterUpdater;
Z
zhangjinchao01 已提交
593 594 595 596 597 598 599 600 601
};

struct ModelConfigPrivate;
/**
 * You can only get model config from TrainerConfig.
 *
 * It is used by GradientMachine.
 */
class ModelConfig {
W
Wu Yi 已提交
602
 private:
Z
zhangjinchao01 已提交
603
  ModelConfig();
604
  DISABLE_COPY(ModelConfig);
Z
zhangjinchao01 已提交
605

W
Wu Yi 已提交
606
 public:
Z
zhangjinchao01 已提交
607 608
  virtual ~ModelConfig();

W
Wu Yi 已提交
609
 private:
Z
zhangjinchao01 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622
  ModelConfigPrivate* m;
  friend class TrainerConfig;
  friend struct TrainerConfigPrivate;
  friend class GradientMachine;
};

struct TrainerConfigPrivate;
/**
 * To get TrainerConfig from file.
 *
 * It is used by GradientMachine.
 */
class TrainerConfig {
W
Wu Yi 已提交
623
 private:
Z
zhangjinchao01 已提交
624
  TrainerConfig();
625
  DISABLE_COPY(TrainerConfig);
Z
zhangjinchao01 已提交
626

W
Wu Yi 已提交
627
 public:
Z
zhangjinchao01 已提交
628 629 630 631
  virtual ~TrainerConfig();

  static TrainerConfig* createFromTrainerConfigFile(
      const std::string& configPath);
E
emailweixu 已提交
632
  static TrainerConfig* createFromProtoString(const std::string& str);
Z
zhangjinchao01 已提交
633 634 635 636 637

  ModelConfig* getModelConfig() const;

  OptimizationConfig* getOptimizationConfig() const;

W
Wu Yi 已提交
638
 private:
Z
zhangjinchao01 已提交
639
  TrainerConfigPrivate* m;
E
emailweixu 已提交
640
  friend class Trainer;
Z
zhangjinchao01 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
};

/**
 * The callback in backword.
 *
 * You can inherit this class in python.
 *
 * @code
 * class UpdateCallbackInPython(paddle.UpdateCallback):
 *   def __init__(self):
 *     paddle.UpdateCallback.__init__(self)
 *
 *   def apply(self, param):
 *     assert isinstance(param, paddle.Parameter)
 * @endcode
 */
class UpdateCallback {
W
Wu Yi 已提交
658
 public:
Z
zhangjinchao01 已提交
659 660 661 662 663 664
  virtual ~UpdateCallback();
  virtual void apply(Parameter* p);
};

struct ParameterTraverseCallbackPrivate;
class ParameterTraverseCallback {
665
  DISABLE_COPY(ParameterTraverseCallback);
Z
zhangjinchao01 已提交
666 667
  ParameterTraverseCallback();

W
Wu Yi 已提交
668
 public:
Z
zhangjinchao01 已提交
669 670
  ~ParameterTraverseCallback();

671 672
  void apply(const std::vector<Vector*>& vecs,
             const ParameterConfig& config,
Z
zhangjinchao01 已提交
673 674
             size_t sparseId);

W
Wu Yi 已提交
675
 private:
Z
zhangjinchao01 已提交
676 677 678 679 680 681 682 683 684 685 686
  ParameterTraverseCallbackPrivate* m;
  friend class ParameterOptimizer;
};

/**
 * The ParameterOptimizer Wrapper Class.
 *
 * Basically same as common/ParameterOptimizer.h
 */
struct ParameterOptimizerPrivate;
class ParameterOptimizer {
687
  DISABLE_COPY(ParameterOptimizer);
Z
zhangjinchao01 已提交
688 689
  ParameterOptimizer();

W
Wu Yi 已提交
690
 public:
Z
zhangjinchao01 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704
  static ParameterOptimizer* create(OptimizationConfig* config);

  ~ParameterOptimizer();

  void init(size_t numRows, const ParameterConfig* config);

  void startPass();

  void finishPass();

  void startBatch(size_t numSamplesProcessed);

  void finishBatch();

705 706
  void update(const std::vector<Vector*>& vecs,
              const ParameterConfig& conf,
Z
zhangjinchao01 已提交
707 708 709 710 711 712 713
              size_t sparseId = NO_SPARSE_ID);

  std::vector<int> getParameterTypes() const;

  ParameterTraverseCallback* needSpecialTraversal(
      const ParameterConfig& config) const;

W
Wu Yi 已提交
714
 private:
Z
zhangjinchao01 已提交
715 716 717 718
  ParameterOptimizerPrivate* m;
};

class SequenceGenerator;
Y
Yu Yang 已提交
719
class Evaluator;
Z
zhangjinchao01 已提交
720 721
struct GradientMachinePrivate;
class GradientMachine {
W
Wu Yi 已提交
722
 private:
Z
zhangjinchao01 已提交
723
  GradientMachine();
724
  DISABLE_COPY(GradientMachine);
Z
zhangjinchao01 已提交
725

W
Wu Yi 已提交
726
 public:
Z
zhangjinchao01 已提交
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
  virtual ~GradientMachine();

  /**
   * Create By ProtoStr.
   *
   * The ProtoStr can be generate by python's protobuf code.
   */
  static GradientMachine* createByConfigProtoStr(
      const std::string& protoStr,
      GradientMatchineCreateMode mode = CREATE_MODE_NORMAL,
      const std::vector<int>& parameterTypes = defaultParamTypes);

  /**
   * Create by ModelConfig object.
   *
   * To get ModelConfig, you can get TrainerConfig from config file, then get
   * model config by TrainerConfig
   */
  static GradientMachine* createByModelConfig(
746 747
      ModelConfig* conf,
      GradientMatchineCreateMode mode = CREATE_MODE_NORMAL,
Z
zhangjinchao01 已提交
748 749
      const std::vector<int>& parameterTypes = defaultParamTypes);

Y
Yu Yang 已提交
750 751 752 753 754 755 756
  /**
   * @brief finish
   */
  void finish();

  void start();

757 758 759 760 761 762 763 764 765 766
  /**
   * Prefetch row ids of sparse parameter.
   */
  void prefetch(const Arguments& inArgs);

  /**
   * Do some thing when train pass ended.
   */
  void onPassEnd();

Z
zhangjinchao01 已提交
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
  /**
   * The forward stage of GradientMachine.
   *
   * @note  the outArgs could be zero length arguemnts.
   * @note  THIS METHOD IS VERY USEFULL FOR PREDICT FROM TRAINED MODEL.
   */
  void forward(const Arguments& inArgs, Arguments* outArgs, PassType passType);

  /**
   * The backward stage of GradientMachine.
   *
   * @note  Currently the ParameterUpdater is not wrapped in SWIG, so backward
   * cannot actually train a network. But you can write a update callback to
   * change the parameter or implement a ParameterUpdater in python side.
   */
  void backward(const UpdateCallback& callback = UpdateCallback());

  /**
   * Combine forward/backward
   */
787 788
  void forwardBackward(const Arguments& inArgs,
                       Arguments* outArgs,
Z
zhangjinchao01 已提交
789 790 791 792 793 794 795 796
                       PassType passType,
                       const UpdateCallback& callback = UpdateCallback());

  void loadParameters(const std::string& path);

  size_t getParameterSize() const;
  Parameter* getParameter(size_t i) throw(RangeError);

L
liaogang 已提交
797 798 799
  size_t getNonStaticParameterSize() const;
  Parameter* getNonStaticParameter(size_t i) throw(RangeError);

Z
zhangjinchao01 已提交
800 801
  void randParameters();

L
liaogang 已提交
802
  Arguments* getLayerOutput(const std::string& layerName) const
Z
zhangjinchao01 已提交
803 804 805 806 807 808 809 810 811
      throw(UnsupportError);

  /**
   * Create a sequence generator.
   *
   * @note  It just like a paddle_gen_sequence.
   */
  SequenceGenerator* asSequenceGenerator(
      const std::vector<std::string>& dict = std::vector<std::string>(),
812 813 814
      size_t begin_id = 0UL,
      size_t end_id = 0UL,
      size_t max_length = 100UL,
Z
zhangjinchao01 已提交
815 816
      size_t beam_size = -1UL);

Y
Yu Yang 已提交
817 818 819 820
  Evaluator* makeEvaluator();

  void eval(Evaluator* evaluator);

W
Wu Yi 已提交
821
 private:
Z
zhangjinchao01 已提交
822 823 824
  GradientMachinePrivate* m;

  static GradientMachine* createFromPaddleModelPtr(
825 826
      const void* confPtr,
      GradientMatchineCreateMode mode,
Z
zhangjinchao01 已提交
827 828 829 830
      const std::vector<int>& types);

  // Not to use c++ 11 init-list, so we use static var as function default arg.
  static std::vector<int> defaultParamTypes;
E
emailweixu 已提交
831
  friend class Trainer;
Y
Yu Yang 已提交
832 833 834 835 836
  friend class ParameterUpdater;
};

struct ParameterUpdaterPrivate;
class ParameterUpdater {
W
Wu Yi 已提交
837
 private:
Y
Yu Yang 已提交
838 839
  ParameterUpdater();

W
Wu Yi 已提交
840
 public:
Y
Yu Yang 已提交
841
  static ParameterUpdater* createLocalUpdater(OptimizationConfig* config);
Q
qiaolongfei 已提交
842
  static ParameterUpdater* createRemoteUpdater(OptimizationConfig* config,
Q
qiaolongfei 已提交
843
                                               int passCount,
844
                                               bool useSparseUpdater);
845
  static ParameterUpdater* createNewRemoteUpdater(
Q
qiaolongfei 已提交
846
      OptimizationConfig* config,
847 848
      const std::string pserverSpec,
      const bool useEtcd) throw(UnsupportError);
Y
Yu Yang 已提交
849 850
  ~ParameterUpdater();

Y
Yu Yang 已提交
851 852 853 854
  /**
   * @brief initialize Parameter Updater by GradientMachine.
   * @param gm
   */
Y
Yu Yang 已提交
855 856
  void init(const GradientMachine& gm);

Y
Yu Yang 已提交
857 858 859
  /**
   * @brief begin of a training/testing of one pass.
   */
Y
Yu Yang 已提交
860 861
  void startPass();

Y
Yu Yang 已提交
862 863 864
  /**
   * @brief end of a traning/testing of one pass.
   */
Y
Yu Yang 已提交
865 866
  void finishPass();

Y
Yu Yang 已提交
867 868 869 870 871
  /**
   * @brief begin of a training/testing of one batch.
   * @param data batch's size
   * @return PassType, mostly will be training.
   */
Y
Yu Yang 已提交
872
  PassType startBatch(size_t batchSize);
Y
Yu Yang 已提交
873

Y
Yu Yang 已提交
874 875 876 877
  /**
   * @brief end of a traning/testing of one batch
   * @param cost current batch cost.
   */
Y
Yu Yang 已提交
878 879
  void finishBatch(float cost);

Y
Yu Yang 已提交
880 881 882 883
  /**
   * @brief update a parameter (by local optimizer or by cluster pserver)
   * @param param
   */
Y
Yu Yang 已提交
884 885
  void update(Parameter* param);

886 887 888 889 890 891 892
  /**
   * @breif only get required sparse rows by default.
   * @param fullSize: get full matrix parameter if *fullSize* set
   * @param apply: get PARAMETER_APPLY on pserver if *apply* set
   */
  void getParametersRemote(bool fullSize = false, bool apply = false);

Y
Yu Yang 已提交
893 894 895 896 897
  /**
   * @brief restore the average parameter.
   * @note It is only used in AverageOptimizer. Restore will get the current
   * PARAMETER_VALUE back.
   */
Y
Yu Yang 已提交
898 899
  void restore();

Y
Yu Yang 已提交
900 901 902 903 904 905
  /**
   * @brief apply. Store the average parameter.
   * @note It is only used in AverageOptimizer. Apply will store the current
   * PARAMETER_VALUE to buffer, calcaualte current Average Parameter, and save
   * it to PARAMETER_VALUE.
   */
Y
Yu Yang 已提交
906 907
  void apply();

Y
Yu Yang 已提交
908 909 910 911 912
  /**
   * @brief catchUpWith The Regularization will be delayed in many situations(
   * pserver, local sparse). Catch Up means catch the regularization up, apply
   * regularization to all params.
   */
Y
Yu Yang 已提交
913 914
  void catchUpWith();

W
Wu Yi 已提交
915
 private:
Y
Yu Yang 已提交
916
  ParameterUpdaterPrivate* m;
Z
zhangjinchao01 已提交
917 918
};

Y
Yu Yang 已提交
919 920
struct EvaluatorPrivate;
class Evaluator {
W
Wu Yi 已提交
921
 private:
Y
Yu Yang 已提交
922
  Evaluator();
Y
Yu Yang 已提交
923
  DISABLE_COPY(Evaluator);
Y
Yu Yang 已提交
924

W
Wu Yi 已提交
925
 public:
Y
Yu Yang 已提交
926 927
  ~Evaluator();

Y
Yu Yang 已提交
928 929 930
  /**
   * @brief begin an evaluate stage.
   */
Y
Yu Yang 已提交
931 932
  void start();

Y
Yu Yang 已提交
933 934 935
  /**
   * @brief end an evaluate stage.
   */
Y
Yu Yang 已提交
936 937
  void finish();

Y
Yu Yang 已提交
938 939 940 941 942
  /**
   * @brief toString will get a evaluate result.
   *
   * __repr__ method in python
   */
Y
Yu Yang 已提交
943 944
  std::string toString();

Y
Yu Yang 已提交
945 946
  std::vector<std::string> getNames() const;

947 948
  double getValue(const std::string name) const;

W
Wu Yi 已提交
949
 private:
Y
Yu Yang 已提交
950 951 952
  EvaluatorPrivate* m;

  friend class GradientMachine;
Z
zhangjinchao01 已提交
953 954 955 956
};

struct TrainerPrivate;
class Trainer {
W
Wu Yi 已提交
957
 private:
Z
zhangjinchao01 已提交
958 959
  TrainerPrivate* m;
  Trainer();
E
emailweixu 已提交
960
  Trainer(TrainerConfig* optConfig, GradientMachine* gm);
961
  DISABLE_COPY(Trainer);
Z
zhangjinchao01 已提交
962

W
Wu Yi 已提交
963
 public:
Z
zhangjinchao01 已提交
964 965 966 967 968
  virtual ~Trainer();

  /// Create A Trainer By TrainerConfig. using paddle command line.
  static Trainer* createByCommandLine() throw(IOError);

969 970
  static Trainer* create(TrainerConfig* optConfig,
                         GradientMachine* gm) throw(IOError);
E
emailweixu 已提交
971 972

  /// Start training
Z
zhangjinchao01 已提交
973
  void startTrain();
E
emailweixu 已提交
974 975

  /// Finish training
Z
zhangjinchao01 已提交
976 977
  void finishTrain();

E
emailweixu 已提交
978
  /// Start a pass.
Z
zhangjinchao01 已提交
979 980
  void startTrainPass();

E
emailweixu 已提交
981 982
  /// Finish a pass
  void finishTrainPass();
Z
zhangjinchao01 已提交
983 984 985 986 987 988

  /**
   * Train one batch,
   *
   * @return true if all batch finished.
   */
E
emailweixu 已提交
989
  bool trainOneBatch(size_t batchSize);
Z
zhangjinchao01 已提交
990

E
emailweixu 已提交
991
  void trainOneDataBatch(size_t batchSize, const Arguments& args);
Z
zhangjinchao01 已提交
992

E
emailweixu 已提交
993 994 995
  void startTestPeriod();
  void testOneDataBatch(size_t batchSize, const Arguments& args);
  void finishTestPeriod();
Z
zhangjinchao01 已提交
996

E
emailweixu 已提交
997
  void forwardOneBatch(size_t batchSize);
Z
zhangjinchao01 已提交
998

E
emailweixu 已提交
999
  Arguments* getForwardOutput();
Z
zhangjinchao01 已提交
1000

L
liaogang 已提交
1001
  Arguments* getLayerOutput(const std::string& layerName) const;
Z
zhangjinchao01 已提交
1002 1003
};

E
emailweixu 已提交
1004
/// the N-Best results generated from one input sequence.
Z
zhangjinchao01 已提交
1005
class ISequenceResults {
W
Wu Yi 已提交
1006
 public:
Z
zhangjinchao01 已提交
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
  virtual ~ISequenceResults();

  /// Number of result.
  virtual size_t getSize() const = 0;

  /**
   * Get sentence from dictionary.
   *
   * @param id  the index of result.
   * @param split  if true, the return sentence will be splited with ' ' by
   *               each word. Default is false.
   */
  virtual std::string getSentence(size_t id, bool split = false) const
      throw(RangeError) = 0;
  virtual std::vector<int> getSequence(size_t id) const throw(RangeError) = 0;
  virtual float getScore(size_t id) const throw(RangeError) = 0;
};

struct SequenceGeneratorPrivate;
class SequenceGenerator {
1027
  DISABLE_COPY(SequenceGenerator);
Z
zhangjinchao01 已提交
1028 1029
  SequenceGenerator();

W
Wu Yi 已提交
1030
 public:
Z
zhangjinchao01 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
  virtual ~SequenceGenerator();

  /**
   * Generate Sequence by input.
   *
   * @note  The inArgs is just one sequence of data.
   * @note  The return will get a N-best generate result by inArgs.
   *        Sort by score.
   */
  ISequenceResults* generateSequence(const Arguments& inArgs) const;

  void setDict(const std::vector<std::string>& dict);
  void setBos(size_t bos);
  void setEos(size_t eos);
  void setMaxLength(size_t maxlength);
  void setBeamSize(size_t beamSize);

W
Wu Yi 已提交
1048
 private:
Z
zhangjinchao01 已提交
1049 1050 1051
  static SequenceGenerator* createByGradientMachineSharedPtr(void* ptr);
  friend class GradientMachine;

W
Wu Yi 已提交
1052
 private:
Z
zhangjinchao01 已提交
1053 1054
  SequenceGeneratorPrivate* m;
};