cast_op.cc 5.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yu Yang 已提交
2

L
Luo Tao 已提交
3 4 5
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
Y
Yu Yang 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yu Yang 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
Y
Yu Yang 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/cast_op.h"
T
tensor-tang 已提交
16
#include <memory>
Y
Yi Wang 已提交
17
#include "paddle/fluid/framework/op_registry.h"
K
Kexin Zhao 已提交
18
#include "paddle/fluid/platform/float16.h"
Y
Yu Yang 已提交
19 20 21 22 23 24

namespace paddle {
namespace operators {

class CastOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
25
  void Make() override {
26 27
    AddInput("X", "The input tensor of cast op");
    AddOutput("Out", "The output tensor of cast op");
F
fengjiayi 已提交
28 29
    AddAttr<int>("out_dtype", "output data type");
    AddAttr<int>("in_dtype", "input data type");
30 31 32
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
        .SetDefault(false);
33 34 35 36
    AddComment(R"DOC(
Cast Operator.

This Operator casts the input tensor to another data type and
T
tensor-tang 已提交
37 38
returns the Output Tensor. It's meaningless if the output dtype equals
the input dtype, but it's fine if you do so.
39 40

)DOC");
Y
Yu Yang 已提交
41 42 43
  }
};

H
hong 已提交
44 45
template <typename T>
class CastOpGradMaker : public framework::SingleGradOpMaker<T> {
Y
Yu Yang 已提交
46
 public:
H
hong 已提交
47
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
Y
Yu Yang 已提交
48 49

 protected:
50
  void Apply(GradOpPtr<T> grad) const override {
Y
Yu Yang 已提交
51
    grad->SetType("cast");
H
hong 已提交
52 53 54 55
    grad->SetInput("X", this->OutputGrad("Out"));
    grad->SetOutput("Out", this->InputGrad("X"));
    grad->SetAttr("out_dtype", this->GetAttr("in_dtype"));
    grad->SetAttr("in_dtype", this->GetAttr("out_dtype"));
56
    grad->SetAttr("use_mkldnn", this->GetAttr("use_mkldnn"));
Y
Yu Yang 已提交
57 58 59
  }
};

Q
QI JUN 已提交
60 61 62 63 64
class CastOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
Z
Zeng Jinle 已提交
65
  void InferShape(framework::InferShapeContext *context) const override {
66 67
    OP_INOUT_CHECK(context->HasInput("X"), "Input", "X", "cast");
    OP_INOUT_CHECK(context->HasOutput("Out"), "Output", "Out", "cast");
Z
Zeng Jinle 已提交
68 69 70 71
    context->SetOutputDim("Out", context->GetInputDim("X"));
    context->ShareLoD("X", "Out");
  }

Q
QI JUN 已提交
72 73 74
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    // CastOp kernel's device type is decided by input tensor place
75 76 77 78 79 80 81 82 83
    auto *tensor = ctx.Input<framework::LoDTensor>("X");
    PADDLE_ENFORCE_EQ(tensor->IsInitialized(), true,
                      platform::errors::PreconditionNotMet(
                          "The tensor of Input(X) is not initialized."));
    auto &tensor_place = tensor->place();
    // NOTE: cuda pinned tensor need to copy its data to target place
    if (platform::is_cuda_pinned_place(tensor_place)) {
      return framework::OpKernelType(tensor->type(), ctx.device_context());
    }
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

#ifdef PADDLE_WITH_MKLDNN
    int in_dtype = ctx.Attr<int>("in_dtype");
    int out_dtype = ctx.Attr<int>("out_dtype");

    auto MKLDNNSupportsCast = [&]() -> bool {
      int dtype_fp32 = static_cast<int>(framework::proto::VarType::FP32);
      int dtype_bf16 = static_cast<int>(framework::proto::VarType::BF16);

      if ((in_dtype != dtype_fp32 && in_dtype != dtype_bf16) ||
          (out_dtype != dtype_fp32 && out_dtype != dtype_bf16))
        return false;

      return true;
    };

    if (this->CanMKLDNNBeUsed(ctx, tensor->type()) && MKLDNNSupportsCast()) {
      return framework::OpKernelType(tensor->type(), ctx.GetPlace(),
                                     framework::DataLayout::kMKLDNN,
                                     framework::LibraryType::kMKLDNN);
    }
#endif
106
    return framework::OpKernelType(tensor->type(), tensor_place);
Q
QI JUN 已提交
107
  }
108 109 110 111 112

  framework::KernelSignature GetExpectedPtenKernelArgs(
      const framework::ExecutionContext &ctx) const override {
    return framework::KernelSignature("cast", {"X"}, {"out_dtype"}, {"Out"});
  }
Q
QI JUN 已提交
113 114
};

Y
Yu Yang 已提交
115 116 117 118
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Q
QI JUN 已提交
119
using CPU = paddle::platform::CPUDeviceContext;
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
#define REGISTER_CAST_CPU_BASE(op_name, ...)                                  \
  REGISTER_OPERATOR(op_name, ops::CastOp,                                     \
                    ops::CastOpGradMaker<paddle::framework::OpDesc>,          \
                    ops::CastOpGradMaker<paddle::imperative::OpBase>,         \
                    ops::CastOpProtoMaker);                                   \
  REGISTER_OP_CPU_KERNEL(                                                     \
      op_name, ops::CastOpKernel<CPU, float>, ops::CastOpKernel<CPU, double>, \
      ops::CastOpKernel<CPU, int>, ops::CastOpKernel<CPU, int64_t>,           \
      ops::CastOpKernel<CPU, int>, ops::CastOpKernel<CPU, int16_t>,           \
      ops::CastOpKernel<CPU, bool>, ops::CastOpKernel<CPU, uint8_t>,          \
      ops::CastOpKernel<CPU, paddle::platform::float16>,                      \
      ops::CastOpKernel<CPU, paddle::platform::bfloat16>,                     \
      ops::CastOpKernel<CPU, paddle::platform::complex<float>>,               \
      ops::CastOpKernel<CPU, paddle::platform::complex<double>>);

REGISTER_CAST_CPU_BASE(cast)
// [ why register transfer_dtype_op alias with cast_op? ]
// In case of InterpreterCore, if we reuse cast_op, we cannot distinguish
// which cast_op is inserted by new executor when we do profiling.
REGISTER_CAST_CPU_BASE(transfer_dtype)