transpose_kernel.cc 7.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright (c) 2022 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/phi/kernels/transpose_kernel.h"
#include "paddle/phi/backends/onednn/onednn_reuse.h"
#include "paddle/phi/core/kernel_registry.h"

namespace phi {

21 22 23 24 25 26 27 28 29 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
void SetOutMemDescWithLogicalLayoutFusesSupport(
    const OneDNNContext& dev_ctx,
    phi::DenseTensor* out,
    const dnnl::memory::desc& out_md) {
  const auto fused_unsqueeze2_axes =
      dev_ctx.HasDnnAttr("fused_unsqueeze2_axes")
          ? PADDLE_GET_CONST(std::vector<int>,
                             dev_ctx.GetDnnAttr("fused_unsqueeze2_axes"))
          : std::vector<int>();
  const auto fused_reshape2_shape =
      dev_ctx.HasDnnAttr("fused_reshape2_shape")
          ? PADDLE_GET_CONST(std::vector<int>,
                             dev_ctx.GetDnnAttr("fused_reshape2_shape"))
          : std::vector<int>();
  const auto fused_squeeze2_axes =
      dev_ctx.HasDnnAttr("fused_squeeze2_axes")
          ? PADDLE_GET_CONST(std::vector<int>,
                             dev_ctx.GetDnnAttr("fused_squeeze2_axes"))
          : std::vector<int>();

  if (!fused_unsqueeze2_axes.empty()) {
    funcs::SetOutMemDescWithUnsqueeze2FuseSupport(
        fused_unsqueeze2_axes, out, out_md);
  } else if (!fused_reshape2_shape.empty()) {
    funcs::SetOutMemDescWithReshape2FuseSupport(
        fused_reshape2_shape, out, out_md);
  } else if (!fused_squeeze2_axes.empty()) {
    out->set_mem_desc(out_md);
    out->Resize(make_ddim(out_md.dims()));
  } else {
    out->set_mem_desc(out_md);
  }
}

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
void SetInMemDescWithSqueeze2FuseSupport(
    const std::vector<int> fused_squeeze2_axes,
    DenseTensor* in,
    const dnnl::memory::desc& in_md) {
  const std::set<int64_t> squeeze2_axes_set(fused_squeeze2_axes.begin(),
                                            fused_squeeze2_axes.end());
  const std::vector<int64_t>& x_vec_dims = in_md.dims();
  std::vector<int64_t> squeezed_op_tz(
      x_vec_dims.size() - fused_squeeze2_axes.size(), 0);

  int j = 0;
  for (size_t i = 0; i < x_vec_dims.size(); ++i) {
    if (squeeze2_axes_set.count(i) ||
        squeeze2_axes_set.count(i - x_vec_dims.size())) {
      PADDLE_ENFORCE_EQ(
          x_vec_dims[i],
          1,
          errors::InvalidArgument(
              "Squeeze2 input dim %d should be equal to one, but get %d.",
              i,
              x_vec_dims[i]));
      continue;
    }
    squeezed_op_tz[j++] = x_vec_dims[i];
  }

  in->set_mem_desc(in_md.reshape(squeezed_op_tz));
  in->Resize(make_ddim(squeezed_op_tz));
}

void SetInMemDescWithLogicalLayoutFusesSupport(
    const OneDNNContext& dev_ctx,
    DenseTensor* in,
    const dnnl::memory::desc& in_md) {
  const auto fused_squeeze2_axes =
      dev_ctx.HasDnnAttr("fused_squeeze2_axes")
          ? PADDLE_GET_CONST(std::vector<int>,
                             dev_ctx.GetDnnAttr("fused_squeeze2_axes"))
          : std::vector<int>();
  if (fused_squeeze2_axes.empty()) {
    in->set_mem_desc(in_md);
    in->Resize(make_ddim(in_md.dims()));
  } else {
    SetInMemDescWithSqueeze2FuseSupport(fused_squeeze2_axes, in, in_md);
  }
}

template <typename T, typename Context>
void TransposeKernel(const Context& dev_ctx,
                     const DenseTensor& x,
                     const std::vector<int>& axis,
                     DenseTensor* out) {
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  // Here we need to match dims to paddle layout
  // as we are producing non-oneDNN result
  auto x_dims = x.dims();
  if ((x_dims.size() >= 3) &&
      (phi::OneDNNContext::tls().get_cur_paddle_data_layout() ==
       phi::DataLayout::kNHWC)) {
    int axis_size = axis.size();
    std::vector<int> formated_axis = axis;
    std::vector<int> count(axis_size, 0);
    for (int i = 0; i < axis_size; i++) {
      if (axis[i] < 0) {
        formated_axis[i] = axis[i] + axis_size;
      }
    }
    auto dims = phi::vectorize<int>(x_dims);

    std::rotate(dims.begin() + 1, dims.begin() + 2, dims.end());
    x_dims = x_dims.reshape(dims);
    VLOG(3)
        << "Rotating Shape in Transpose from: kMKLDNN to: kNHWC output_shape";

    phi::DDim out_dims(x_dims);
    for (size_t i = 0; i < axis.size(); i++) {
      out_dims[i] = x_dims[formated_axis[i]];
    }
    out->Resize(out_dims);
  }

135
  PADDLE_ENFORCE_EQ(
136 137
      dev_ctx.GetPlace().GetType(),
      AllocationType::CPU,
138 139 140 141 142
      errors::PreconditionNotMet("oneDNN Transpose kernel must use CPUPlace"));

  SetInMemDescWithLogicalLayoutFusesSupport(
      dev_ctx, const_cast<DenseTensor*>(&x), x.mem_desc());

143
  if (axis.size() == 1 || axis.size() == 0) {
144
    Copy<Context>(dev_ctx, x, x.place(), false, out);
145 146 147 148 149 150
    out->set_mem_desc(x.mem_desc());
    return;
  }

  auto x_vec_dims = vectorize(x.dims());
  auto x_type = funcs::ToOneDNNDataType(x.dtype());
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

  dnnl::primitive_attr attrs;
  const int32_t mask = 0;
  const auto quantization_scale =
      dev_ctx.HasDnnAttr("scale")
          ? PADDLE_GET_CONST(float, dev_ctx.GetDnnAttr("scale"))
          : 1.0f;
  const auto quantization_shift =
      dev_ctx.HasDnnAttr("shift")
          ? PADDLE_GET_CONST(float, dev_ctx.GetDnnAttr("shift"))
          : 0.0f;
  const auto output_data_type =
      dev_ctx.HasDnnAttr("output_data_type")
          ? PADDLE_GET_CONST(std::string,
                             dev_ctx.GetDnnAttr("output_data_type"))
          : "";
  const bool with_scale = quantization_scale != 1.0f;
  const bool with_shift = quantization_shift != 0.0f;

  if (with_scale) {
    attrs.set_output_scales(mask, {quantization_scale});
  }

  if (with_shift) {
    auto dst = output_data_type == "fp32" ? DNNL_ARG_SRC : DNNL_ARG_DST;
    attrs.set_zero_points(
        dst, mask, {static_cast<int32_t>(quantization_shift)});
  }

  DataType out_dtype;
  if (output_data_type == "bf16") {
    out_dtype = DataType::BFLOAT16;
  } else if (output_data_type == "int8") {
    out_dtype = DataType::INT8;
  } else if (output_data_type == "uint8") {
    out_dtype = DataType::UINT8;
  } else if (output_data_type == "fp32") {
    out_dtype = DataType::FLOAT32;
  } else {
    out_dtype = x.dtype();
  }
  auto out_type = phi::funcs::ToOneDNNDataType(out_dtype);

194
  funcs::ReorderOneDNNHandler reorder_handler(
195 196
      x_vec_dims, x.dtype(), x_type, out_dtype, out_type, dev_ctx.GetEngine());

197 198 199
  auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
      x.mem_desc(), funcs::to_void_cast(x.data<T>()));

200
  auto fake_strides = funcs::FakeTransposeStrides(x_vec_dims, axis);
201
  auto dst_md = dnnl::memory::desc(x_vec_dims, out_type, fake_strides);
202
  auto reorder_dst_memory_p =
203 204 205 206
      reorder_handler.AcquireDstMemory(out, dst_md, dev_ctx.GetPlace());

  auto reorder_p = reorder_handler.AcquireReorder(
      reorder_dst_memory_p, reorder_src_memory_p, attrs);
207 208 209 210 211 212 213 214 215 216 217

  auto& astream = OneDNNContext::tls().get_stream();
  reorder_p->execute(astream, *reorder_src_memory_p, *reorder_dst_memory_p);
  astream.wait();

  // it is needed because oneDNN's permute axis understand axes order in
  // different way PaddlePaddle's transpose
  std::vector<int> permute_axis(axis.size());
  for (size_t i = 0; i < axis.size(); ++i) {
    permute_axis[axis[i]] = i;
  }
218

219
  SetOutMemDescWithLogicalLayoutFusesSupport(
220 221
      dev_ctx,
      out,
222 223
      reorder_dst_memory_p->get_desc().permute_axes(
          funcs::TransposeToPermuteAxes(axis)));
224 225 226 227 228 229 230 231 232 233 234
}
}  // namespace phi

PD_REGISTER_KERNEL(transpose,
                   OneDNN,
                   ONEDNN,
                   phi::TransposeKernel,
                   float,
                   uint8_t,
                   int8_t,
                   phi::dtype::bfloat16) {}