PrintLayer.cpp 2.1 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

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 "Layer.h"

namespace paddle {

class PrintLayer : public Layer {
W
Wu Yi 已提交
20
 public:
21
  explicit PrintLayer(const LayerConfig& config) : Layer(config) {}
22

23 24
  void forward(PassType passType) override {
    Layer::forward(passType);
25
    std::vector<std::string> vals;
26
    for (size_t i = 0; i != inputLayers_.size(); ++i) {
27 28 29
      std::ostringstream s;
      getInput(i).printValueString(s, "");
      vals.push_back(s.str());
30
    }
31
    size_t pos = 0;
32
    size_t i = 0;
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
    std::ostringstream s;
    const std::string& format = config_.user_arg();
    while (true) {
      size_t pos1 = format.find("%s", pos);
      if (pos1 == std::string::npos) break;
      if (i >= vals.size()) {
        break;
      }
      s << format.substr(pos, pos1 - pos) << vals[i];
      pos = pos1 + 2;
      ++i;
    }
    if (i != inputLayers_.size()) {
      LOG(ERROR) << "Number of value in the format (" << format
                 << ") is not same as the number of inputs ("
                 << inputLayers_.size() << ") at " << getName();
    }
    s << format.substr(pos);
51 52 53 54 55 56 57 58 59 60

    const std::string delimiter("\n");
    std::string content = s.str();
    std::string::size_type foundPos = 0;
    std::string::size_type prevPos = 0;
    while ((foundPos = content.find(delimiter, prevPos)) != std::string::npos) {
      LOG(INFO) << content.substr(prevPos, foundPos - prevPos);
      prevPos = foundPos + delimiter.size();
    }
    LOG(INFO) << content.substr(prevPos);
61
  }
62 63 64

  void backward(const UpdateCallback& callback) override {}
};
65 66 67 68

REGISTER_LAYER(print, PrintLayer);

}  // namespace paddle