print_op.cc 9.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yan Chunwei 已提交
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 <algorithm>
16
#include "paddle/fluid/framework/data_layout.h"
Y
Yi Wang 已提交
17
#include "paddle/fluid/framework/op_registry.h"
S
sneaxiy 已提交
18
#include "paddle/fluid/framework/var_type.h"
19
#include "paddle/fluid/operators/assign_op.h"
Y
Yan Chunwei 已提交
20 21 22

namespace paddle {
namespace operators {
Y
Yu Yang 已提交
23
using framework::GradVarName;
Y
Yan Chunwei 已提交
24 25 26

#define CLOG std::cout

27 28 29
const char kForward[] = "FORWARD";
const char kBackward[] = "BACKWARD";
const char kBoth[] = "BOTH";
Y
yangyaming 已提交
30

C
chengduo 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43
class LogGuard {
 public:
  inline LogGuard() { LogMutex().lock(); }

  inline ~LogGuard() { LogMutex().unlock(); }

 private:
  static std::mutex &LogMutex() {
    static std::mutex mtx;
    return mtx;
  }
};

Y
Yan Chunwei 已提交
44 45 46
struct Formater {
  std::string message;
  std::string name;
47
  std::string dims;
48
  std::type_index dtype{typeid(const char)};
49
  std::string layout;
Y
Yan Chunwei 已提交
50 51
  framework::LoD lod;
  int summarize;
Y
Yu Yang 已提交
52
  void *data{nullptr};
C
chengduo 已提交
53 54
  platform::Place place;
  std::stringstream logs;
Y
Yan Chunwei 已提交
55 56 57

  void operator()(size_t size) {
    PrintName();
58 59 60
    PrintMessage();
    PrintLod();
    PrintPlace();
Y
Yan Chunwei 已提交
61
    PrintDims();
62
    PrintLayout();
Y
Yan Chunwei 已提交
63 64
    PrintDtype();
    PrintData(size);
C
chengduo 已提交
65 66
    LogGuard guard;
    CLOG << logs.str();
Y
Yan Chunwei 已提交
67 68 69
  }

 private:
70 71 72 73 74 75
  void PrintPlace() { logs << "  - place: " << place << std::endl; }
  void PrintMessage() {
    if (!message.empty()) {
      logs << "  - message: " << message << std::endl;
    }
  }
Y
Yan Chunwei 已提交
76 77
  void PrintName() {
    if (!name.empty()) {
78
      logs << "Variable: " << name << std::endl;
Y
Yan Chunwei 已提交
79 80 81 82
    }
  }
  void PrintDims() {
    if (!dims.empty()) {
83
      logs << "  - shape: " << dims << std::endl;
Y
Yan Chunwei 已提交
84 85 86
    }
  }
  void PrintDtype() {
S
sneaxiy 已提交
87
    if (!framework::IsType<const char>(dtype)) {
88 89 90 91 92 93
      logs << "  - dtype: " << platform::demangle(dtype.name()) << std::endl;
    }
  }
  void PrintLayout() {
    if (!layout.empty()) {
      logs << "  - layout: " << layout << std::endl;
Y
Yan Chunwei 已提交
94 95 96 97
    }
  }
  void PrintLod() {
    if (!lod.empty()) {
98
      logs << "  - lod: {";
Y
Yan Chunwei 已提交
99
      for (auto level : lod) {
100 101
        logs << "{";
        bool is_first = true;
Y
Yan Chunwei 已提交
102
        for (auto i : level) {
103 104 105 106 107 108
          if (is_first) {
            logs << i;
            is_first = false;
          } else {
            logs << ", " << i;
          }
Y
Yan Chunwei 已提交
109
        }
110
        logs << "}";
Y
Yan Chunwei 已提交
111
      }
112
      logs << "}" << std::endl;
Y
Yan Chunwei 已提交
113 114 115 116 117 118
    }
  }

  void PrintData(size_t size) {
    PADDLE_ENFORCE_NOT_NULL(data);
    // print float
S
sneaxiy 已提交
119
    if (framework::IsType<const float>(dtype)) {
Y
Yan Chunwei 已提交
120
      Display<float>(size);
S
sneaxiy 已提交
121
    } else if (framework::IsType<const double>(dtype)) {
Y
Yan Chunwei 已提交
122
      Display<double>(size);
S
sneaxiy 已提交
123
    } else if (framework::IsType<const int>(dtype)) {
Y
Yan Chunwei 已提交
124
      Display<int>(size);
S
sneaxiy 已提交
125
    } else if (framework::IsType<const int64_t>(dtype)) {
Y
Yan Chunwei 已提交
126
      Display<int64_t>(size);
S
sneaxiy 已提交
127
    } else if (framework::IsType<const bool>(dtype)) {
128 129
      Display<bool>(size);
    } else {
130
      logs << "  - data: unprintable type: " << dtype.name() << std::endl;
Y
Yan Chunwei 已提交
131 132 133 134 135
    }
  }

  template <typename T>
  void Display(size_t size) {
Y
Yu Yang 已提交
136
    auto *d = reinterpret_cast<T *>(data);
137
    logs << "  - data: [";
Y
Yan Chunwei 已提交
138 139
    if (summarize != -1) {
      summarize = std::min(size, (size_t)summarize);
140 141 142 143 144
      if (summarize > 0) {
        logs << d[0];
        for (int i = 1; i < summarize; ++i) {
          logs << " " << d[i];
        }
Y
Yan Chunwei 已提交
145 146
      }
    } else {
147 148 149 150 151
      if (size > 0) {
        logs << d[0];
        for (size_t i = 1; i < size; ++i) {
          logs << " " << d[i];
        }
Y
Yan Chunwei 已提交
152 153
      }
    }
154
    logs << "]" << std::endl;
Y
Yan Chunwei 已提交
155 156 157 158
  }
};

// TODO(ChunweiYan) there should be some other printers for TensorArray
159
class PrintOp : public framework::OperatorBase {
Y
Yan Chunwei 已提交
160
 public:
161 162 163
  PrintOp(const std::string &type, const framework::VariableNameMap &inputs,
          const framework::VariableNameMap &outputs,
          const framework::AttributeMap &attrs)
Y
Yan Chunwei 已提交
164 165
      : OperatorBase(type, inputs, outputs, attrs) {}

166
 private:
Y
Yu Yang 已提交
167 168
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
169 170
    const auto in_var = scope.FindVar(Input("In"));
    auto out_var = scope.FindVar(Output("Out"));
171 172 173 174 175 176 177 178

    PADDLE_ENFORCE_NOT_NULL(
        in_var, platform::errors::NotFound("The input:%s not found in scope",
                                           Input("In")));
    PADDLE_ENFORCE_NOT_NULL(
        out_var, platform::errors::NotFound("The output:%s not found in scope",
                                            Output("Out")));

179 180 181 182 183 184 185 186
    auto &in_tensor = in_var->Get<framework::LoDTensor>();
    framework::LoDTensor *out_tensor =
        out_var->GetMutable<framework::LoDTensor>();

    PrintValue(place, Inputs("In").front(), in_tensor);
    framework::TensorCopy(in_tensor, place, out_tensor);
    out_tensor->set_lod(in_tensor.lod());
  }
Y
yangyaming 已提交
187

188 189 190
  void PrintValue(const platform::Place &place,
                  const std::string &printed_var_name,
                  const framework::LoDTensor &in_tensor) const {
Y
yangyaming 已提交
191
    std::string print_phase = Attr<std::string>("print_phase");
Y
Yu Yang 已提交
192 193 194 195
    bool is_forward = Attr<bool>("is_forward");

    if ((is_forward && print_phase == kBackward) ||
        (!is_forward && print_phase == kForward)) {
Y
yangyaming 已提交
196 197 198
      return;
    }

Y
Yan Chunwei 已提交
199 200 201
    int first_n = Attr<int>("first_n");
    if (first_n > 0 && ++times_ > first_n) return;

Y
yangyaming 已提交
202 203 204
    framework::LoDTensor printed_tensor;
    printed_tensor.set_lod(in_tensor.lod());
    printed_tensor.Resize(in_tensor.dims());
Y
Yan Chunwei 已提交
205

206
    if (is_cpu_place(in_tensor.place())) {
Y
yangyaming 已提交
207 208 209 210
      printed_tensor.ShareDataWith(in_tensor);
    } else {
      // copy data to cpu to print
      platform::CPUPlace place;
211
      TensorCopy(in_tensor, place, &printed_tensor);
Y
yangyaming 已提交
212
    }
Y
Yan Chunwei 已提交
213 214

    Formater formater;
C
chengduo 已提交
215
    formater.place = place;
216
    formater.message = Attr<std::string>("message");
Y
Yan Chunwei 已提交
217
    if (Attr<bool>("print_tensor_name")) {
Y
yangyaming 已提交
218
      formater.name = printed_var_name;
Y
Yan Chunwei 已提交
219 220
    }
    if (Attr<bool>("print_tensor_type")) {
Y
Yu Yang 已提交
221
      formater.dtype = framework::ToTypeIndex(printed_tensor.type());
Y
Yan Chunwei 已提交
222 223
    }
    if (Attr<bool>("print_tensor_shape")) {
224
      formater.dims = printed_tensor.dims().to_str();
Y
Yan Chunwei 已提交
225 226
    }
    if (Attr<bool>("print_tensor_lod")) {
Y
yangyaming 已提交
227
      formater.lod = printed_tensor.lod();
Y
Yan Chunwei 已提交
228
    }
229 230 231
    if (Attr<bool>("print_tensor_layout")) {
      formater.layout = framework::DataLayoutToString(printed_tensor.layout());
    }
Y
Yan Chunwei 已提交
232
    formater.summarize = Attr<int>("summarize");
Y
Yu Yang 已提交
233
    formater.data = reinterpret_cast<void *>(printed_tensor.data<void>());
Y
yangyaming 已提交
234
    formater(printed_tensor.numel());
Y
Yan Chunwei 已提交
235 236 237 238 239 240 241 242
  }

 private:
  mutable int times_{0};
};

class PrintOpProtoAndCheckMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
243
  void Make() override {
Y
yangyaming 已提交
244
    AddInput("In", "Input tensor to be displayed.");
245
    AddOutput("Out", "The output tensor.");
Y
Yan Chunwei 已提交
246 247
    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 已提交
248
    AddAttr<int>("summarize", "Number of elements printed.");
249 250 251 252 253 254 255 256 257 258 259
    AddAttr<bool>("print_tensor_name", "Whether to print the tensor name.")
        .SetDefault(true);
    AddAttr<bool>("print_tensor_type", "Whether to print the tensor's dtype.")
        .SetDefault(true);
    AddAttr<bool>("print_tensor_shape", "Whether to print the tensor's shape.")
        .SetDefault(true);
    AddAttr<bool>("print_tensor_layout",
                  "Whether to print the tensor's layout.")
        .SetDefault(true);
    AddAttr<bool>("print_tensor_lod", "Whether to print the tensor's lod.")
        .SetDefault(true);
Y
Yu Yang 已提交
260 261 262 263
    AddAttr<std::string>("print_phase",
                         "(string, default 'FORWARD') Which phase to display "
                         "including 'FORWARD' "
                         "'BACKWARD' and 'BOTH'.")
264 265 266
        .SetDefault(std::string(kBoth))
        .InEnum({std::string(kForward), std::string(kBackward),
                 std::string(kBoth)});
Y
Yu Yang 已提交
267
    AddAttr<bool>("is_forward", "Whether is forward or not").SetDefault(true);
Y
Yan Chunwei 已提交
268
    AddComment(R"DOC(
Y
yangyaming 已提交
269
Creates a print op that will print when a tensor is accessed.
Y
Yan Chunwei 已提交
270

Y
yangyaming 已提交
271 272 273
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 已提交
274 275 276
  }
};

277 278 279 280
class PrintOpInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *ctx) const override {
    VLOG(10) << "PrintOpInferShape";
281 282
    OP_INOUT_CHECK(ctx->HasInput("In"), "Input", "In", "Print");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Print");
283 284 285 286 287 288
    ctx->ShareDim("In", /*->*/ "Out");
    ctx->ShareLoD("In", /*->*/ "Out");
  }
};

class PrintOpVarTypeInference : public framework::VarTypeInference {
Y
Yan Chunwei 已提交
289
 public:
290
  void operator()(framework::InferVarTypeContext *ctx) const override {
291
    ctx->SetOutputType("Out", ctx->GetInputType("In"));
Y
Yan Chunwei 已提交
292 293 294
  }
};

H
hong 已提交
295 296
template <typename T>
class PrintOpGradientMaker : public framework::SingleGradOpMaker<T> {
Y
yangyaming 已提交
297
 public:
H
hong 已提交
298
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
Y
yangyaming 已提交
299

300
  void Apply(GradOpPtr<T> op_desc_ptr) const override {
Y
Yu Yang 已提交
301
    op_desc_ptr->SetType("print");
H
hong 已提交
302 303 304
    op_desc_ptr->SetInput("In", this->OutputGrad("Out"));
    op_desc_ptr->SetOutput("Out", this->InputGrad("In"));
    op_desc_ptr->SetAttrMap(this->Attrs());
Y
Yu Yang 已提交
305
    op_desc_ptr->SetAttr("is_forward", false);
Y
yangyaming 已提交
306 307 308
  }
};

Y
Yan Chunwei 已提交
309 310 311
}  // namespace operators
}  // namespace paddle

Y
yangyaming 已提交
312 313
namespace ops = paddle::operators;

314
REGISTER_OPERATOR(print, ops::PrintOp, ops::PrintOpProtoAndCheckMaker,
H
hong 已提交
315 316 317
                  ops::PrintOpGradientMaker<paddle::framework::OpDesc>,
                  ops::PrintOpGradientMaker<paddle::imperative::OpBase>,
                  ops::PrintOpInferShape, ops::PrintOpVarTypeInference);