NeuralNetwork.cpp 15.7 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. */

#include "paddle/utils/Util.h"

#include "paddle/utils/CustomStackTrace.h"
Y
Yu Yang 已提交
18
#include "paddle/utils/Logging.h"
Z
zhangjinchao01 已提交
19

Y
Yu Yang 已提交
20
#include "MultiNetwork.h"
Z
zhangjinchao01 已提交
21 22
#include "NeuralNetwork.h"
#include "RecurrentGradientMachine.h"
Y
Yu Yang 已提交
23
#include "hl_gpu.h"
Z
zhangjinchao01 已提交
24
#include "paddle/gserver/layers/AgentLayer.h"
Y
Yu Yang 已提交
25
#include "paddle/utils/Stat.h"
Z
zhangjinchao01 已提交
26 27

namespace paddle {
28 29
void parameterInitNN(int paramId,
                     Parameter* para,
Z
zhangjinchao01 已提交
30 31 32 33 34 35 36 37
                     std::vector<ParameterPtr>* sharedParams) {
  // Create parameters values.
  if (!para->useGpu() && sharedParams) {
    para->enableSharedType(PARAMETER_VALUE,
                           (*sharedParams)[paramId]->getBuf(PARAMETER_VALUE),
                           (*sharedParams)[paramId]->getMat(PARAMETER_VALUE));
  } else {
    if (para->isSparseRemoteUpdate()) {
38 39 40 41
      para->enableType(PARAMETER_VALUE,
                       FLAGS_loadsave_parameters_in_pserver
                           ? Parameter::MAT_SPARSE_ROW_PREFETCH
                           : Parameter::MAT_SPARSE_ROW_PREFETCH_FULL_SIZE);
Z
zhangjinchao01 已提交
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
    } else {
      para->enableType(PARAMETER_VALUE);
    }
  }
  // Create parameter gradients.
  if (para->isSparseRemoteUpdate() && !sharedParams) {
    para->enableType(PARAMETER_GRADIENT, Parameter::MAT_SPARSE_ROW);
  } else if (para->isGradSparseUpdate()) {
    para->enableType(PARAMETER_GRADIENT, Parameter::MAT_SPARSE_ROW_AUTO_GROW);
  } else if (!para->isStatic()) {
    para->enableType(PARAMETER_GRADIENT);
  }
}

NeuralNetwork* NeuralNetwork::create(const ModelConfig& config) {
  if (config.type() == "recurrent_nn") {
    return newNeuralNetwork("root");
  } else if (config.type() == "multi_nn") {
    return new MultiNetwork("root");
  } else {
    return newNeuralNetwork();
  }
}

std::map<std::string, bool> NeuralNetwork::dllInitMap;

68 69
void NeuralNetwork::init(const ModelConfig& config,
                         ParamInitCallback callback,
Z
zhangjinchao01 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
                         const std::vector<ParameterType>& parameterTypes,
                         bool useGpu) {
  using std::placeholders::_1;
  using std::placeholders::_2;
  ParamInitCallback paramCallback = nullptr;
  if (callback != nullptr) {
    paramSelfInited_ = false;
    paramCallback = callback;
  } else {
    paramSelfInited_ = true;
    paramCallback = std::bind(parameterInitNN, _1, _2, nullptr);
  }
  config_ = config;

  if (rootNetwork_ != nullptr) {
    // direct use parameters_ and parameterMap_ from base network
    CHECK_EQ((size_t)config.parameters_size(),
             rootNetwork_->getParameters().size());
    parameters_ = rootNetwork_->getParameters();
    parameterMap_ = *(rootNetwork_->getParameterMap());
  } else {
    parameters_.reserve(config.parameters_size());
    for (const auto& para_config : config.parameters()) {
93 94
      auto parameter = std::make_shared<Parameter>(para_config,
                                                   useGpu,
Z
zhangjinchao01 已提交
95 96 97 98
                                                   /*initialize=*/false);
      paramCallback(parameters_.size(), parameter.get());
      if (!callback) {
        for (ParameterType type :
99
             (parameter->isStatic()
Z
zhangjinchao01 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
                  ? std::vector<ParameterType>{PARAMETER_VALUE}
                  : parameterTypes)) {
          if (type != PARAMETER_VALUE && type != PARAMETER_GRADIENT) {
            parameter->enableType(type);
          }
        }
      }
      parameter->setID(parameters_.size());
      parameters_.push_back(parameter);
      CHECK(!parameterMap_.count(parameter->getName()));
      parameterMap_[parameter->getName()] = parameter;
    }
  }

  auto layerCreate = [&](const LayerConfig& layer_config) {
    auto layer = Layer::create(layer_config);
    CHECK(layer) << "Create layer failed. Layer name:" << layer->getName();
    layers_.push_back(layer);
    CHECK(!layerMap_.count(layer->getName()));
    layerMap_[layer->getName()] = layer;
  };

122 123 124 125 126
  auto subModelConfig = std::find_if(config.sub_models().begin(),
                                     config.sub_models().end(),
                                     [=](const SubModelConfig& sub_model) {
                                       return sub_model.name() == subModelName_;
                                     });
Z
zhangjinchao01 已提交
127 128 129 130 131 132
  bool useSubModel = (subModelConfig != config.sub_models().end());
  CHECK_EQ(useSubModel, !subModelName_.empty());
  if (useSubModel) {
    layers_.reserve(subModelConfig->layer_names_size());
    for (const auto& layer_name : subModelConfig->layer_names()) {
      auto layer_config =
133 134
          std::find_if(config.layers().begin(),
                       config.layers().end(),
Z
zhangjinchao01 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
                       [=](const LayerConfig& layer_config) {
                         return layer_config.name() == layer_name;
                       });
      CHECK(layer_config != config.layers().end());
      layerCreate(*layer_config);
    }
  } else {
    layers_.reserve(config.layers_size());
    for (const auto& layer_config : config.layers()) {
      bool useLayer = true;
      if (config.has_external_config()) {
        useLayer = true;
        for (const auto& name : config.external_config().layer_names()) {
          if (layer_config.name() == name) {
            useLayer = false;
            break;
          }
        }
      }
      if (useLayer) {
        layerCreate(layer_config);
      }
    }
  }

  for (const auto& layer : layers_) {
    layer->init(layerMap_, parameterMap_);
    layer->initSubNetwork(this /*root*/, config_, parameterTypes, useGpu);
  }

  for (const auto& layer_name :
       (useSubModel ? subModelConfig->input_layer_names()
                    : config.input_layer_names())) {
    auto it = layerMap_.find(layer_name);
    CHECK(it != layerMap_.end());
    dataLayers_.push_back(std::dynamic_pointer_cast<DataLayer>(it->second));
  }

  for (const auto& layer_name :
       (useSubModel ? subModelConfig->output_layer_names()
                    : config.output_layer_names())) {
    auto it = layerMap_.find(layer_name);
    CHECK(it != layerMap_.end());
    outputLayers_.push_back(it->second);
  }
}

182 183
void NeuralNetwork::connect(LayerPtr agentLayer,
                            LayerPtr realLayer,
Z
zhangjinchao01 已提交
184 185 186 187 188 189
                            int height) {
  AgentLayer* agent = dynamic_cast<AgentLayer*>(agentLayer.get());
  CHECK_NOTNULL(agent);
  agent->setRealLayer(realLayer, height);
}

190 191
void NeuralNetwork::connect(std::string agentLayerName,
                            NeuralNetwork* srcNN,
Z
zhangjinchao01 已提交
192 193 194 195 196 197 198 199 200 201 202
                            std::string realLayerName) {
  connect(this->getLayer(agentLayerName), srcNN->getLayer(realLayerName));
}

void NeuralNetwork::prefetch(const std::vector<Argument>& inArgs) {
  CHECK_EQ(inArgs.size(), dataLayers_.size());

  if (paramSelfInited_) {
    for (auto& para : parameters_) {
      if (para->isSparseRemoteUpdate()) {
        auto mat = dynamic_cast<SparsePrefetchRowCpuMatrix*>(
203
            para->getMat(PARAMETER_VALUE).get());
Z
zhangjinchao01 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
        para->clearGradient();
        mat->clearIndices();
      }
    }
  }

  for (size_t i = 0; i != dataLayers_.size(); ++i) {
    if (FLAGS_parallel_nn) {
      const_cast<Argument&>(inArgs[i]).deviceId = -1;
    }
    dataLayers_[i]->setData(inArgs[i]);
  }

  for (auto& layer : layers_) {
    layer->prefetch();
  }

  if (paramSelfInited_) {
    for (auto& para : parameters_) {
      if (para->isSparseRemoteUpdate()) {
        auto mat = dynamic_cast<SparsePrefetchRowCpuMatrix*>(
225
            para->getMat(PARAMETER_VALUE).get());
Z
zhangjinchao01 已提交
226 227
        mat->setupIndices();
        auto matGrad = dynamic_cast<SparseRowCpuMatrix*>(
228
            para->getMat(PARAMETER_GRADIENT).get());
Z
zhangjinchao01 已提交
229 230 231 232 233 234 235
        matGrad->reserveStore();
      }
    }
  }
}

void NeuralNetwork::forward(const std::vector<Argument>& inArgs,
236 237
                            std::vector<Argument>* outArgs,
                            PassType passType) {
Z
zhangjinchao01 已提交
238 239 240 241 242 243
  CHECK_EQ(inArgs.size(), dataLayers_.size());
  outArgs->resize(outputLayers_.size());
  for (size_t i = 0; i != dataLayers_.size(); ++i) {
    dataLayers_[i]->setData(inArgs[i]);
  }

X
xuwei06 已提交
244 245
  gLayerStackTrace.set_stage(true);

Z
zhangjinchao01 已提交
246 247 248 249 250
  {
    for (auto& layer : layers_) {
      REGISTER_TIMER_INFO("ForwardTimer", layer->getName().c_str());
      gLayerStackTrace.push(layer->getName());
      layer->forward(passType);
X
xuwei06 已提交
251
      gLayerStackTrace.pop(layer->getName());
Z
zhangjinchao01 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    }
  }

  outArgs->clear();
  outArgs->reserve(outputLayers_.size());
  for (auto& layer : outputLayers_) {
    outArgs->push_back(layer->getOutput());
  }
}

void NeuralNetwork::resetState() {
  for (auto& layer : layers_) {
    layer->resetState();
  }
}

void NeuralNetwork::setState(const MachineState& machineState) {
  for (size_t i = 0; i < layers_.size(); i++) {
    if (machineState[i] != nullptr) {
      layers_[i]->setState(machineState[i]);
    }
  }
}

void NeuralNetwork::getState(MachineState& machineState) {
  machineState.clear();
  machineState.reserve(layers_.size());
  for (auto& layer : layers_) {
    LayerStatePtr p = layer->getState();
    machineState.push_back(p);
  }
}

void NeuralNetwork::backward(const UpdateCallback& callback) {
X
xuwei06 已提交
286
  gLayerStackTrace.set_stage(false);
Z
zhangjinchao01 已提交
287 288
  FOR_EACH_R(layer, layers_) {
    REGISTER_TIMER_INFO("BackwardTimer", (*layer)->getName().c_str());
X
xuwei06 已提交
289
    gLayerStackTrace.push((*layer)->getName());
Z
zhangjinchao01 已提交
290 291 292 293 294 295 296
    if ((*layer)->needGradient()) {
      (*layer)->backward(callback);
    }
    gLayerStackTrace.pop((*layer)->getName());
  }
}

L
liaogang 已提交
297
Argument NeuralNetwork::getLayerOutput(const std::string& layerName) {
L
liaogang 已提交
298
  return getLayer(layerName)->getOutput();
Z
zhangjinchao01 已提交
299
}
300

Z
zhangjinchao01 已提交
301 302 303 304 305 306 307 308 309 310 311
void NeuralNetwork::onPassEnd() {
  for (auto& layer : layers_) {
    layer->onPassEnd();
  }
}

class CombinedEvaluator : public Evaluator {
public:
  void addEvaluator(std::unique_ptr<Evaluator>&& evaluator) {
    evaluators_.emplace_back(std::move(evaluator));
  }
Y
Yu Yang 已提交
312
  void start() override {
Z
zhangjinchao01 已提交
313 314 315 316 317
    for (auto& evaluator : evaluators_) {
      evaluator->start();
    }
  }

Y
Yu Yang 已提交
318
  void finish() override {
Z
zhangjinchao01 已提交
319 320 321 322 323
    for (auto& evaluator : evaluators_) {
      evaluator->finish();
    }
  }

Y
Yu Yang 已提交
324
  void eval(const NeuralNetwork& nn) override {
Z
zhangjinchao01 已提交
325 326 327 328
    for (auto& evaluator : evaluators_) {
      evaluator->eval(nn);
    }
  }
Y
Yu Yang 已提交
329
  real evalImp(std::vector<Argument>& arguments) override {
Z
zhangjinchao01 已提交
330 331 332
    (void)arguments;
    return -1;
  }
Y
Yu Yang 已提交
333
  void printStats(std::ostream& os) const override {
Z
zhangjinchao01 已提交
334 335 336 337 338 339
    for (auto& evaluator : evaluators_) {
      evaluator->printStats(os);
      os << ' ';
    }
  }

Y
Yu Yang 已提交
340
  void distributeEval(ParameterClient2* client) override {
Z
zhangjinchao01 已提交
341 342 343 344 345 346 347
    for (auto& evaluator : evaluators_) {
      evaluator->distributeEval(client);
    }
  }

protected:
  std::vector<std::unique_ptr<Evaluator>> evaluators_;
Y
Yu Yang 已提交
348 349 350

  // Evaluator interface
public:
Y
Yu Yang 已提交
351 352 353 354
  /**
   * @brief getNames will return all inside evaluators' names.
   * @param names [out]: return names.
   */
Y
Yu Yang 已提交
355
  void getNames(std::vector<std::string>* names) override {
Y
Yu Yang 已提交
356 357 358 359 360
    for (auto& eval : evaluators_) {
      eval->getNames(names);
    }
  }

Y
Yu Yang 已提交
361 362 363
  /**
   * @brief getValue could get all inside evaluators' value.
   */
Y
Yu Yang 已提交
364
  real getValue(const std::string& name, Error* err) const override {
Y
Yu Yang 已提交
365 366 367 368 369
    return this->getMethodHelper<real>(
        name, err, [&name, err](const std::unique_ptr<Evaluator>& eval) {
          return eval->getValue(name, err);
        });
  }
Y
Yu Yang 已提交
370 371 372 373

  /**
   * @brief getType could get all inside evaluators' type.
   */
Y
Yu Yang 已提交
374
  std::string getType(const std::string& name, Error* err) const override {
Y
Yu Yang 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    return this->getMethodHelper<std::string>(
        name, err, [&name, err](const std::unique_ptr<Evaluator>& eval) {
          return eval->getType(name, err);
        });
  }

private:
  template <typename T>
  T getMethodHelper(const std::string& name,
                    Error* err,
                    const std::function<T(const std::unique_ptr<Evaluator>&)>&
                        callback) const {
    for (auto& eval : evaluators_) {
      std::vector<std::string> names;
      eval->getNames(&names);
      if (std::find(names.begin(), names.end(), name) != names.end()) {
        return callback(eval);
      }
    }
394
    *err = Error("No such key %s", name.c_str());
Y
Yu Yang 已提交
395 396
    return T();
  }
Z
zhangjinchao01 已提交
397 398
};

X
xuwei06 已提交
399 400 401 402 403 404 405
class SubnetEvaluator : public CombinedEvaluator {
public:
  SubnetEvaluator(const std::string& layerName,
                  std::unique_ptr<Evaluator>&& evaluator)
      : layerName_(layerName) {
    addEvaluator(std::move(evaluator));
  }
L
liaogang 已提交
406
  void eval(const NeuralNetwork& nn) override {
X
xuwei06 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    const LayerPtr& layer = nn.getLayer(layerName_);
    CHECK(layer) << "Nonexisted layer: " << layerName_ << " in submodel "
                 << nn.getName();
    bool accessed = false;
    layer->accessSubNetwork([this, &accessed](NeuralNetwork& subnet) {
      subnet.eval(evaluators_[0].get());
      accessed = true;
    });
    CHECK(accessed) << "There is no subnetwork for layer " << layerName_
                    << " in submodel " << nn.getName();
  }

protected:
  std::string layerName_;
};

Y
Yu Yang 已提交
423
Evaluator* NeuralNetwork::makeEvaluator() const {
Z
zhangjinchao01 已提交
424
  CombinedEvaluator* combinedEvaluator = new CombinedEvaluator();
425 426 427 428 429
  auto subModelConfig = std::find_if(config_.sub_models().begin(),
                                     config_.sub_models().end(),
                                     [=](const SubModelConfig& sub_model) {
                                       return sub_model.name() == subModelName_;
                                     });
Z
zhangjinchao01 已提交
430 431 432 433 434 435 436
  bool useSubModel = (subModelConfig != config_.sub_models().end());
  CHECK_EQ(useSubModel, !subModelName_.empty());
  if (useSubModel) {
    // create the evaluators that belong to CURRENT submodel
    for (int i = 0; i < subModelConfig->evaluator_names_size(); ++i) {
      // find evaluator by name
      auto thisEvalConfig = std::find_if(
437 438
          config_.evaluators().begin(),
          config_.evaluators().end(),
Z
zhangjinchao01 已提交
439 440 441 442 443 444 445 446 447 448
          [=](const EvaluatorConfig& ecfg) {
            return ecfg.name() == subModelConfig->evaluator_names(i);
          });
      bool validConfig = (thisEvalConfig != config_.evaluators().end());
      if (validConfig) {
        std::unique_ptr<Evaluator> evaluator(
            Evaluator::create(*thisEvalConfig));
        combinedEvaluator->addEvaluator(std::move(evaluator));
      }
    }
X
xuwei06 已提交
449 450 451 452 453 454 455 456 457
    for (auto& layer : layers_) {
      layer->accessSubNetwork(
          [layer, combinedEvaluator](NeuralNetwork& subnet) {
            std::unique_ptr<Evaluator> subEvaluator(new SubnetEvaluator(
                layer->getName(),
                std::unique_ptr<Evaluator>(subnet.makeEvaluator())));
            combinedEvaluator->addEvaluator(std::move(subEvaluator));
          });
    }
Z
zhangjinchao01 已提交
458 459 460 461 462 463 464 465 466
  } else {
    for (const EvaluatorConfig& evalConfig : config_.evaluators()) {
      std::unique_ptr<Evaluator> evaluator(Evaluator::create(evalConfig));
      combinedEvaluator->addEvaluator(std::move(evaluator));
    }
  }
  return combinedEvaluator;
}

Y
Yu Yang 已提交
467
void NeuralNetwork::eval(Evaluator* evaluator) const { evaluator->eval(*this); }
Z
zhangjinchao01 已提交
468 469 470 471 472 473 474 475

void NeuralNetwork::setOutputGrad(const std::vector<Argument>& args) {
  CHECK_GE(outputLayers_.size(), args.size());
  for (size_t i = 0; i < args.size(); ++i) {
    outputLayers_[i]->getOutput().grad = args[i].grad;
  }
}

476 477 478
extern NeuralNetwork* newCustomNerualNetwork(const std::string& name,
                                             NeuralNetwork* network)
    __attribute__((weak));
L
liaogang 已提交
479

480 481 482 483 484 485 486
NeuralNetwork* NeuralNetwork::newNeuralNetwork(const std::string& name,
                                               NeuralNetwork* rootNetwork) {
  if (newCustomNerualNetwork) {
    return newCustomNerualNetwork(name, rootNetwork);
  } else {
    return new NeuralNetwork(name, rootNetwork);
  }
Z
zhangjinchao01 已提交
487 488 489
}

}  // namespace paddle