print_op.cc 8.9 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   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 <algorithm>
#include <ctime>

Y
Yi Wang 已提交
18 19
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/variable.h"
Y
Yan Chunwei 已提交
20 21 22 23 24 25

namespace paddle {
namespace operators {

#define CLOG std::cout

Y
yangyaming 已提交
26 27 28 29
const std::string kForward = "FORWARD";
const std::string kBackward = "BACKWARD";
const std::string kBoth = "BOTH";

Y
Yan Chunwei 已提交
30 31 32 33 34 35 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 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
struct Formater {
  std::string message;
  std::string name;
  std::vector<int> dims;
  std::type_index dtype{typeid(char)};
  framework::LoD lod;
  int summarize;
  void* data{nullptr};

  void operator()(size_t size) {
    PrintMessage();
    PrintName();
    PrintDims();
    PrintDtype();
    PrintLod();
    PrintData(size);
  }

 private:
  void PrintMessage() { CLOG << std::time(nullptr) << "\t" << message; }
  void PrintName() {
    if (!name.empty()) {
      CLOG << "Tensor[" << name << "]" << std::endl;
    }
  }
  void PrintDims() {
    if (!dims.empty()) {
      CLOG << "\tshape: [";
      for (auto i : dims) {
        CLOG << i << ",";
      }
      CLOG << "]" << std::endl;
    }
  }
  void PrintDtype() {
    if (dtype.hash_code() != typeid(char).hash_code()) {
      CLOG << "\tdtype: " << dtype.name() << std::endl;
    }
  }
  void PrintLod() {
    if (!lod.empty()) {
      CLOG << "\tLoD: [";
      for (auto level : lod) {
        CLOG << "[ ";
        for (auto i : level) {
          CLOG << i << ",";
        }
        CLOG << " ]";
      }
      CLOG << "]" << std::endl;
    }
  }

  void PrintData(size_t size) {
    PADDLE_ENFORCE_NOT_NULL(data);
    // print float
    if (dtype.hash_code() == typeid(float).hash_code()) {
      Display<float>(size);
    }
    if (dtype.hash_code() == typeid(double).hash_code()) {
      Display<double>(size);
    }
    if (dtype.hash_code() == typeid(int).hash_code()) {
      Display<int>(size);
    }
    if (dtype.hash_code() == typeid(int64_t).hash_code()) {
      Display<int64_t>(size);
    }
  }

  template <typename T>
  void Display(size_t size) {
    auto* d = (T*)data;
    CLOG << "\tdata: ";
    if (summarize != -1) {
      summarize = std::min(size, (size_t)summarize);
      for (int i = 0; i < summarize; i++) {
        CLOG << d[i] << ",";
      }
    } else {
      for (size_t i = 0; i < size; i++) {
        CLOG << d[i] << ",";
      }
    }
    CLOG << std::endl;
  }
};

// TODO(ChunweiYan) there should be some other printers for TensorArray
class TensorPrintOp : public framework::OperatorBase {
 public:
  TensorPrintOp(const std::string& type,
                const framework::VariableNameMap& inputs,
                const framework::VariableNameMap& outputs,
                const framework::AttributeMap& attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

  TensorPrintOp(const TensorPrintOp& o)
      : framework::OperatorBase(
            static_cast<const framework::OperatorBase&>(o)) {
Y
yangyaming 已提交
130
    PADDLE_THROW("Not implemented.");
Y
Yan Chunwei 已提交
131 132
  }

133 134 135
 private:
  void RunImpl(const framework::Scope& scope,
               const platform::Place& place) const override {
Y
yangyaming 已提交
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
    const framework::Variable* in_var_ptr = nullptr;
    std::string phase = kForward;
    std::string printed_var_name = "";

    auto& inputs = Inputs();
    if (inputs.find("In") != inputs.end() && !Inputs("In").empty()) {
      in_var_ptr = scope.FindVar(Input("In"));
      printed_var_name = Inputs("In").front();
    } else if (inputs.find("In@GRAD") != inputs.end() &&
               !Inputs("In@GRAD").empty()) {
      in_var_ptr = scope.FindVar(Input("In@GRAD"));
      printed_var_name = Inputs("In@GRAD").front();
      phase = kBackward;
    } else {
      PADDLE_THROW("Unknown phase, should be forward or backward.");
    }

    PADDLE_ENFORCE_NOT_NULL(in_var_ptr);

    auto& in_tensor = in_var_ptr->Get<framework::LoDTensor>();
    auto* out_var_ptr = scope.FindVar(Output("Out"));
    auto& out_tensor = *out_var_ptr->GetMutable<framework::LoDTensor>();

    // Just copy data from input tensor to output tensor
    // output tensor share same memory with input tensor
    out_tensor.ShareDataWith(in_tensor);
    out_tensor.set_lod(in_tensor.lod());

    std::string print_phase = Attr<std::string>("print_phase");
    if (print_phase != phase && print_phase != kBoth) {
      return;
    }

Y
Yan Chunwei 已提交
169 170 171
    int first_n = Attr<int>("first_n");
    if (first_n > 0 && ++times_ > first_n) return;

Y
yangyaming 已提交
172 173 174
    framework::LoDTensor printed_tensor;
    printed_tensor.set_lod(in_tensor.lod());
    printed_tensor.Resize(in_tensor.dims());
Y
Yan Chunwei 已提交
175

Y
yangyaming 已提交
176 177 178 179 180 181 182
    if (platform::is_cpu_place(in_tensor.place())) {
      printed_tensor.ShareDataWith(in_tensor);
    } else {
      // copy data to cpu to print
      platform::CPUPlace place;
      framework::Copy(in_tensor, place, &printed_tensor);
    }
Y
Yan Chunwei 已提交
183 184 185

    Formater formater;
    if (Attr<bool>("print_tensor_name")) {
Y
yangyaming 已提交
186
      formater.name = printed_var_name;
Y
Yan Chunwei 已提交
187 188
    }
    if (Attr<bool>("print_tensor_type")) {
Y
yangyaming 已提交
189
      formater.dtype = printed_tensor.type();
Y
Yan Chunwei 已提交
190 191
    }
    if (Attr<bool>("print_tensor_shape")) {
Y
yangyaming 已提交
192 193 194
      auto& dims = printed_tensor.dims();
      formater.dims.resize(dims.size());
      for (int i = 0; i < dims.size(); ++i) formater.dims[i] = dims[i];
Y
Yan Chunwei 已提交
195 196
    }
    if (Attr<bool>("print_tensor_lod")) {
Y
yangyaming 已提交
197
      formater.lod = printed_tensor.lod();
Y
Yan Chunwei 已提交
198 199
    }
    formater.summarize = Attr<int>("summarize");
Y
yangyaming 已提交
200 201
    formater.data = (void*)printed_tensor.data<void>();
    formater(printed_tensor.numel());
Y
Yan Chunwei 已提交
202 203 204 205 206 207 208 209 210 211
  }

 private:
  mutable int times_{0};
};

class PrintOpProtoAndCheckMaker : public framework::OpProtoAndCheckerMaker {
 public:
  PrintOpProtoAndCheckMaker(OpProto* proto, OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
Y
yangyaming 已提交
212
    AddInput("In", "Input tensor to be displayed.");
Y
Yan Chunwei 已提交
213 214
    AddAttr<int>("first_n", "Only log `first_n` number of times.");
    AddAttr<std::string>("message", "A string message to print as a prefix.");
Y
yangyaming 已提交
215
    AddAttr<int>("summarize", "Number of elements printed.");
Y
Yan Chunwei 已提交
216 217 218 219
    AddAttr<bool>("print_tensor_name", "Whether to print the tensor name.");
    AddAttr<bool>("print_tensor_type", "Whether to print the tensor's dtype.");
    AddAttr<bool>("print_tensor_shape", "Whether to print the tensor's shape.");
    AddAttr<bool>("print_tensor_lod", "Whether to print the tensor's lod.");
Y
yangyaming 已提交
220 221 222 223 224 225 226
    AddAttr<std::string>(
        "print_phase",
        "(string, default 'BOTH') Which phase to display including 'FORWARD' "
        "'BACKWARD' and 'BOTH'.")
        .SetDefault(kBoth)
        .InEnum({kForward, kBackward, kBoth});
    AddOutput("Out", "Output tensor with same data as input tensor.");
Y
Yan Chunwei 已提交
227
    AddComment(R"DOC(
Y
yangyaming 已提交
228
Creates a print op that will print when a tensor is accessed.
Y
Yan Chunwei 已提交
229

Y
yangyaming 已提交
230 231 232
Wraps the tensor passed in so that whenever that a tensor is accessed,
the message `message` is printed, along with the current value of the
tensor `t`.)DOC");
Y
Yan Chunwei 已提交
233 234 235
  }
};

Y
yangyaming 已提交
236
class InferShapeForward : public framework::InferShapeBase {
Y
Yan Chunwei 已提交
237 238
 public:
  void operator()(framework::InferShapeContext* context) const override {
Y
yangyaming 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251
    PADDLE_ENFORCE(context->HasInput("In"), "Input(In) should not be null.");
    context->ShareLoD("In", /*->*/ "Out");
    context->SetOutputDim("Out", context->GetInputDim("In"));
  }
};

class InferShapeBackward : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext* context) const override {
    PADDLE_ENFORCE(context->HasInput("In@GRAD"),
                   "Input(In@GRAD) should not be null.");
    context->ShareLoD("In@GRAD", /*->*/ "Out");
    context->SetOutputDim("Out", context->GetInputDim("In@GRAD"));
Y
Yan Chunwei 已提交
252 253 254 255 256 257 258 259 260
  }
};

class InferVarType : public framework::VarTypeInference {
 public:
  void operator()(const framework::OpDesc& op_desc,
                  framework::BlockDesc* block) const override {}
};

Y
yangyaming 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
class PrintOpProtoAndCheckGradOpMaker
    : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto* op_desc_ptr = new framework::OpDesc();
    op_desc_ptr->SetType("print_grad");
    op_desc_ptr->SetInput("In@GRAD", OutputGrad("Out"));
    op_desc_ptr->SetOutput("Out", InputGrad("In"));
    op_desc_ptr->SetAttrMap(Attrs());
    return std::unique_ptr<framework::OpDesc>(op_desc_ptr);
  }
};

Y
Yan Chunwei 已提交
276 277 278
}  // namespace operators
}  // namespace paddle

Y
yangyaming 已提交
279 280 281 282 283 284
namespace ops = paddle::operators;

REGISTER_OPERATOR(print, ops::TensorPrintOp, ops::PrintOpProtoAndCheckMaker,
                  ops::PrintOpProtoAndCheckGradOpMaker, ops::InferShapeForward,
                  ops::InferVarType);
REGISTER_OPERATOR(print_grad, ops::TensorPrintOp, ops::InferShapeBackward);