GradientMachine.cpp 5.5 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

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. */

#include "PaddleAPI.h"
E
emailweixu 已提交
16 17
#include "PaddleAPIPrivate.h"

Z
zhangjinchao01 已提交
18
#include "Internal.h"
Y
Yu Yang 已提交
19
#include "paddle/gserver/gradientmachines/NeuralNetwork.h"
Z
zhangjinchao01 已提交
20 21 22 23 24 25 26 27 28

std::vector<int> GradientMachine::defaultParamTypes = {
    PARAMETER_VALUE, PARAMETER_GRADIENT, PARAMETER_MOMENTUM};

GradientMachine::GradientMachine() : m(new GradientMachinePrivate()) {}

GradientMachine::~GradientMachine() { delete m; }

GradientMachine* GradientMachine::createFromPaddleModelPtr(
29 30
    const void* confPtr,
    GradientMatchineCreateMode mode,
Z
zhangjinchao01 已提交
31
    const std::vector<int>& types) {
E
emailweixu 已提交
32
  auto& conf = *(const paddle::ModelConfig*)(confPtr);
Z
zhangjinchao01 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46
  std::vector<ParameterType> realTypes;
  staticCastVector(&realTypes, types);
  auto machineRawPtr = paddle::GradientMachine::create(conf, mode, realTypes);
  auto machinePtr = std::shared_ptr<paddle::GradientMachine>(machineRawPtr);
  if (machinePtr != nullptr) {
    auto machine = new GradientMachine();
    machine->m->machine = machinePtr;
    return machine;
  } else {
    return nullptr;
  }
}

GradientMachine* GradientMachine::createByConfigProtoStr(
47 48
    const std::string& protoStr,
    GradientMatchineCreateMode mode,
Z
zhangjinchao01 已提交
49 50 51 52 53 54 55 56 57 58 59
    const std::vector<int>& types) {
  paddle::ModelConfig conf;
  conf.ParseFromString(protoStr);
  if (conf.IsInitialized()) {
    return GradientMachine::createFromPaddleModelPtr(&conf, mode, types);
  } else {
    return nullptr;
  }
}

GradientMachine* GradientMachine::createByModelConfig(
60 61
    ModelConfig* conf,
    GradientMatchineCreateMode mode,
Z
zhangjinchao01 已提交
62
    const std::vector<int>& types) {
E
emailweixu 已提交
63
  auto confPtr = &conf->m->conf->getModelConfig();
Z
zhangjinchao01 已提交
64 65 66
  return GradientMachine::createFromPaddleModelPtr(confPtr, mode, types);
}

Y
Yu Yang 已提交
67 68 69 70
void GradientMachine::start() { m->machine->start(); }

void GradientMachine::finish() { m->machine->finish(); }

71 72 73 74 75 76 77 78
void GradientMachine::onPassEnd() { m->machine->onPassEnd(); }

void GradientMachine::prefetch(const Arguments& inArgs) {
  auto& in =
      m->cast<std::vector<paddle::Argument>>(inArgs.getInternalArgumentsPtr());
  m->machine->prefetch(in);
}

79 80
void GradientMachine::forward(const Arguments& inArgs,
                              Arguments* outArgs,
Z
zhangjinchao01 已提交
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
                              PassType passType) {
  auto& in =
      m->cast<std::vector<paddle::Argument>>(inArgs.getInternalArgumentsPtr());
  auto& out = m->cast<std::vector<paddle::Argument>>(
      outArgs->getInternalArgumentsPtr());
  paddle::PassType pt = (paddle::PassType)(passType);
  m->machine->forward(in, &out, pt);
}

UpdateCallback::~UpdateCallback() {}

void UpdateCallback::apply(Parameter* p) {
  // UNUSED(p);
}

class UpdateCallbackWrapper {
public:
  explicit UpdateCallbackWrapper(const UpdateCallback& callback)
      : callback(const_cast<UpdateCallback&>(callback)) {}

  void operator()(paddle::Parameter* param) {
    auto p = Parameter::createFromRawPtr(&param);
    // @TODO Use Stack variable instead.
    callback.apply(p);
    delete p;
  }

private:
  UpdateCallback& callback;
};

void GradientMachine::backward(const UpdateCallback& callback) {
  m->machine->backward(UpdateCallbackWrapper(callback));
}

void GradientMachine::forwardBackward(const Arguments& inArgs,
117 118
                                      Arguments* outArgs,
                                      PassType passType,
Z
zhangjinchao01 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
                                      const UpdateCallback& callback) {
  auto& in =
      m->cast<std::vector<paddle::Argument>>(inArgs.getInternalArgumentsPtr());
  auto& out = m->cast<std::vector<paddle::Argument>>(
      outArgs->getInternalArgumentsPtr());
  paddle::PassType pt = (paddle::PassType)(passType);
  m->machine->forwardBackward(in, &out, pt, UpdateCallbackWrapper(callback));
}

void GradientMachine::loadParameters(const std::string& path) {
  m->machine->loadParameters(path);
}

size_t GradientMachine::getParameterSize() const {
  return m->machine->getParameters().size();
}

Parameter* GradientMachine::getParameter(size_t i) throw(RangeError) {
  auto params = m->machine->getParameters();
  if (i < params.size()) {
    return Parameter::createFromSharedPtr(&m->machine->getParameters()[i]);
  } else {
    throw RangeError();
  }
}

void GradientMachine::randParameters() { m->machine->randParameters(); }

L
liaogang 已提交
147
Arguments* GradientMachine::getLayerOutput(const std::string& layerName) const
148
    throw(UnsupportError) {
L
liaogang 已提交
149
  auto nn = m->machine;
Z
zhangjinchao01 已提交
150
  if (nn) {
L
liaogang 已提交
151
    return Arguments::createByPaddleArgument(&nn->getLayerOutput(layerName));
Z
zhangjinchao01 已提交
152 153 154 155 156 157
  } else {
    throw UnsupportError();
  }
}

SequenceGenerator* GradientMachine::asSequenceGenerator(
158 159 160 161 162
    const std::vector<std::string>& dict,
    size_t begin_id,
    size_t end_id,
    size_t max_length,
    size_t beam_size) {
Z
zhangjinchao01 已提交
163 164 165 166 167 168 169 170 171
  SequenceGenerator* r =
      SequenceGenerator::createByGradientMachineSharedPtr(&m->machine);
  r->setDict(dict);
  r->setBos(begin_id);
  r->setEos(end_id);
  r->setMaxLength(max_length);
  r->setBeamSize(beam_size);
  return r;
}
Y
Yu Yang 已提交
172 173 174 175 176 177 178 179 180 181

Evaluator* GradientMachine::makeEvaluator() {
  auto ev = new Evaluator();
  ev->m->rawPtr = m->machine->makeEvaluator();
  return ev;
}

void GradientMachine::eval(Evaluator* evaluator) {
  m->machine->eval(evaluator->m->rawPtr);
}