interpolate_mkldnn_op.cc 7.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.

   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/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/operators/interpolate_op.h"
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace operators {

using dnnl::memory;
using dnnl::primitive;
using dnnl::reorder;
using dnnl::resampling_forward;
26 27
using dnnl::stream;
using framework::DataLayout;
28 29 30 31 32
using platform::GetMKLDNNFormat;
using platform::to_void_cast;

template <typename T = float>
class InterpolateMKLDNNHandler
33
    : public platform::MKLDNNHandlerNoCachingT<T, dnnl::resampling_forward> {
34 35
 public:
  InterpolateMKLDNNHandler(const dnnl::algorithm algo,
36 37 38 39
                           const dnnl::engine engine,
                           platform::Place cpu_place,
                           const Tensor* x,
                           Tensor* out)
40 41
      : platform::MKLDNNHandlerNoCachingT<T, dnnl::resampling_forward>(
            engine, cpu_place) {
42
    const auto dst_tz = phi::vectorize(out->dims());
43 44 45 46
    const auto dst_md = memory::desc(
        dst_tz, platform::MKLDNNGetDataType<T>(), MKLDNNMemoryFormat::any);
    this->AcquireForwardPrimitiveDescriptor(
        dnnl::prop_kind::forward_inference, algo, x->mem_desc(), dst_md);
47 48 49 50 51 52 53 54
  }
};

template <typename T = float>
class InterpolateMKLDNNKernel : public framework::OpKernel<T> {
  std::vector<int> ComputeOutputShape(
      const framework::ExecutionContext& ctx) const {
    const auto* x = ctx.Input<Tensor>("X");
55 56 57 58
    const auto& in_dims = x->dims();

    const framework::DDim in_dhw_dims =
        phi::slice_ddim(in_dims, 2, in_dims.size());
59 60

    std::vector<int> out_dims;
61
    out_dims.reserve(5);
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    if (in_dhw_dims.size() == 1) {
      out_dims.push_back(ctx.Attr<int>("out_w"));
    } else if (in_dhw_dims.size() == 2) {
      out_dims.push_back(ctx.Attr<int>("out_h"));
      out_dims.push_back(ctx.Attr<int>("out_w"));
    } else if (in_dhw_dims.size() == 3) {
      out_dims.push_back(ctx.Attr<int>("out_d"));
      out_dims.push_back(ctx.Attr<int>("out_h"));
      out_dims.push_back(ctx.Attr<int>("out_w"));
    }

    auto list_new_size_tensor = ctx.MultiInput<framework::Tensor>("SizeTensor");
    auto out_size = ctx.Input<Tensor>("OutSize");
    if (list_new_size_tensor.size() > 0) {
      auto new_size = get_new_shape(list_new_size_tensor);
      if (new_size.size() == out_dims.size()) {
        out_dims = new_size;
      }
    } else if (out_size != nullptr) {
      auto out_size_data = get_new_data_from_tensor<int>(out_size);
      if (out_size_data.size() == out_dims.size()) {
        out_dims = out_size_data;
      }
    } else {
86 87
      std::vector<float> scale;
      scale.reserve(3);
88 89 90
      auto scale_tensor = ctx.Input<Tensor>("Scale");
      if (scale_tensor != nullptr) {
        auto scale_data = get_new_data_from_tensor<float>(scale_tensor);
91 92
        scale.resize(3, scale_data[0]);
        std::copy(scale_data.begin(), scale_data.end(), scale.begin());
93
      } else {
94 95 96 97 98 99 100 101
        std::string op_type = ctx.Type();

        if (op_type.find("v2") == std::string::npos) {  // v1
          scale.push_back(ctx.Attr<float>("scale"));
          scale.push_back(scale[0]);
          scale.push_back(scale[0]);
        } else {  // v2
          std::vector<float> scale_attr = ctx.Attr<std::vector<float>>("scale");
102 103 104 105
          if (scale_attr.size() > 0) {
            scale.resize(3, scale_attr[0]);
            std::copy(scale_attr.begin(), scale_attr.end(), scale.begin());
          }
106
        }
107
      }
108 109
      if (scale[0] > 0.0f && scale[1] > 0.0f && scale[2] > 0.0f) {
        int j = 0;
110
        std::vector<int64_t> in_dhw_vec = phi::vectorize(in_dhw_dims);
111
        std::transform(
112 113 114
            in_dhw_vec.begin(),
            in_dhw_vec.end(),
            out_dims.begin(),
115
            [&](int64_t i) -> int { return static_cast<int>(i * scale[j++]); });
116 117 118
      }
    }

119 120 121 122 123 124 125
    PADDLE_ENFORCE_GT(
        std::all_of(
            out_dims.begin(), out_dims.end(), [](int i) { return i > 0; }),
        0,
        platform::errors::InvalidArgument(
            "out_d, out_h, out_w of Op(interpolate) "
            "should be greater than 0."));
126

127 128
    const std::vector<int64_t> nc_dims = {in_dims[0], in_dims[1]};
    out_dims.insert(out_dims.begin(), nc_dims.begin(), nc_dims.end());
129 130 131 132 133 134 135 136 137 138
    return out_dims;
  }

 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    const auto& dev_ctx =
        ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();

    const auto* x = ctx.Input<Tensor>("X");
139
    auto* out = ctx.Output<Tensor>("Out");
140

141 142 143 144
    const auto interp_method = ctx.Attr<std::string>("interp_method");
    const dnnl::algorithm algo = (interp_method == "nearest")
                                     ? dnnl::algorithm::resampling_nearest
                                     : dnnl::algorithm::resampling_linear;
145

146
    const auto out_dims_vec = ComputeOutputShape(ctx);
147
    framework::DDim dim_out = phi::make_ddim(out_dims_vec);
148
    out->Resize(dim_out);
149

150 151
    InterpolateMKLDNNHandler<T> handler(
        algo, mkldnn_engine, ctx.GetPlace(), x, out);
152 153

    auto src_memory_p = handler.AcquireSrcMemory(x);
154
    auto dst_memory_p = handler.AcquireDstMemory(out);
155 156 157 158

    auto resampling_prim = handler.AcquireForwardPrimitive();
    const std::unordered_map<int, dnnl::memory> args = {
        {DNNL_ARG_SRC, *src_memory_p}, {DNNL_ARG_DST, *dst_memory_p}};
159
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
160

161 162 163
    resampling_prim->execute(astream, args);
    astream.wait();

164
    out->set_mem_desc(dst_memory_p->get_desc());
165 166 167 168 169 170 171 172
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

173 174 175
REGISTER_OP_KERNEL(nearest_interp,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
176 177 178
                   ops::InterpolateMKLDNNKernel<float>,
                   ops::InterpolateMKLDNNKernel<int8_t>,
                   ops::InterpolateMKLDNNKernel<uint8_t>);
179 180 181
REGISTER_OP_KERNEL(bilinear_interp,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
182
                   ops::InterpolateMKLDNNKernel<float>);
183

184 185 186
REGISTER_OP_KERNEL(nearest_interp_v2,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
187
                   ops::InterpolateMKLDNNKernel<float>,
188
                   ops::InterpolateMKLDNNKernel<paddle::platform::bfloat16>,
189 190
                   ops::InterpolateMKLDNNKernel<int8_t>,
                   ops::InterpolateMKLDNNKernel<uint8_t>);
191 192 193
REGISTER_OP_KERNEL(bilinear_interp_v2,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
194
                   ops::InterpolateMKLDNNKernel<float>);