pool_grad_kernel.cc 15.9 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 26
// 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/pool_grad_kernel.h"

#include "paddle/phi/backends/xpu/enforce_xpu.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/kernels/funcs/pooling.h"

namespace phi {
template <typename T, typename Context>
void Pool2dGradKernel(const Context& ctx,
                      const DenseTensor& x,
                      const DenseTensor& out,
                      const DenseTensor& dout,
27
                      const IntArray& kernel_size_t,
28 29 30 31 32 33 34 35 36 37 38 39 40
                      const std::vector<int>& strides_t,
                      const std::vector<int>& paddings_t,
                      bool ceil_mode,
                      bool exclusive,
                      const std::string& data_format,
                      const std::string& pooling_type,
                      bool global_pooling,
                      bool adaptive,
                      const std::string& padding_algorithm,
                      DenseTensor* dx) {
  using XPUType = typename XPUTypeTrait<T>::Type;

  std::vector<int> paddings(paddings_t);
41 42
  std::vector<int> kernel_size(kernel_size_t.GetData().begin(),
                               kernel_size_t.GetData().end());
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
  std::vector<int> strides(strides_t);

  PADDLE_ENFORCE_EQ(
      data_format,
      "NCHW",
      phi::errors::InvalidArgument("The Pool2d_grad XPU OP only support"
                                   "data_format is 'NCHW', but received %s",
                                   data_format));

  PADDLE_ENFORCE_EQ(
      kernel_size.size(),
      2,
      phi::errors::InvalidArgument("The Pool2d XPU OP only support 2 "
                                   "dimension pooling!, but received "
                                   "%d-dimension pool kernel size",
                                   kernel_size.size()));
  if (global_pooling) {
    for (size_t i = 0; i < kernel_size.size(); ++i) {
      paddings[i] = 0;
      kernel_size[i] = static_cast<int>(x.dims()[i + 2]);
    }
  }
  if (!dx) {
    return;
  }
  const int n = x.dims()[0];
  const int c = x.dims()[1];
  const int in_h = x.dims()[2];
  const int in_w = x.dims()[3];

  const int out_h = out.dims()[2];
  const int out_w = out.dims()[3];

  DDim data_dims;

  data_dims = slice_ddim(x.dims(), 2, x.dims().size());
  funcs::UpdatePadding(&paddings,
                       global_pooling,
                       adaptive,
                       padding_algorithm,
                       data_dims,
                       strides,
                       kernel_size);
  if (ceil_mode) {
    int in_h_ceil = (out_h - 1) * strides[0] + kernel_size[0] - 2 * paddings[0];
    int in_w_ceil = (out_w - 1) * strides[1] + kernel_size[1] - 2 * paddings[2];

    paddings[1] += (in_h_ceil - in_h);
    paddings[3] += (in_w_ceil - in_w);
  }

  ctx.template Alloc<T>(dx);
  const int* index_data = nullptr;
  int r = xpu::Error_t::SUCCESS;
  if (adaptive) {
Y
ykkk2333 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    if (pooling_type == "max") {
      r = xpu::adaptive_max_pool2d_grad<XPUType>(
          ctx.x_context(),
          reinterpret_cast<const XPUType*>(x.data<T>()),
          reinterpret_cast<const XPUType*>(out.data<T>()),
          index_data,
          reinterpret_cast<const XPUType*>(dout.data<T>()),
          reinterpret_cast<XPUType*>(dx->data<T>()),
          n,
          c,
          in_h,
          in_w,
          out_h,
          out_w,
          true);

    } else if (pooling_type == "avg") {
115 116
      // When output dim is 1 * 1 (1 * 1 * 1 in pool_3d), use scale
      // and broadcast kernels to get same output, but better performance.
117
      if (out_h == 1 && out_w == 1 && std::is_same<T, float>::value) {
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        xpu::ctx_guard RAII_GUARD(ctx.x_context());
        float scale = 1.0 / (in_h * in_w);
        float* scaled_dy = RAII_GUARD.alloc_l3_or_gm<float>(n * c);
        r = xpu::scale(ctx.x_context(),
                       dout.data<float>(),
                       scaled_dy,
                       n * c,
                       true,
                       scale,
                       0.0);
        PADDLE_ENFORCE_XDNN_SUCCESS(r, "scale");

        r = xpu::broadcast(ctx.x_context(),
                           scaled_dy,
                           dx->data<float>(),
                           {n, c, 1, 1},
                           {n, c, in_h, in_w});
        PADDLE_ENFORCE_XDNN_SUCCESS(r, "broadcast");

        return;
      }
Y
ykkk2333 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
      r = xpu::adaptive_avg_pool2d_grad<XPUType>(
          ctx.x_context(),
          reinterpret_cast<const XPUType*>(dout.data<T>()),
          reinterpret_cast<XPUType*>(dx->data<T>()),
          n,
          c,
          in_h,
          in_w,
          out_h,
          out_w,
          true);
    } else {
      PADDLE_THROW(phi::errors::InvalidArgument(
          "Unsupported pooling type for kunlun ", pooling_type));
    }

    PADDLE_ENFORCE_XDNN_SUCCESS(r, "adaptive_pool2d_grad");
  } else {
157 158 159 160 161 162
    if (kernel_size[0] > in_h) {
      kernel_size[0] = in_h;
    }
    if (kernel_size[1] > in_w) {
      kernel_size[1] = in_w;
    }
Y
ykkk2333 已提交
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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    if (pooling_type == "max") {
      // TODO(zhanghuan05) to bind max_pool2d_grad_indices xpu api
      r = xpu::max_pool2d_grad<XPUType>(
          ctx.x_context(),
          reinterpret_cast<const XPUType*>(x.data<T>()),
          reinterpret_cast<const XPUType*>(out.data<T>()),
          index_data,
          reinterpret_cast<const XPUType*>(dout.data<T>()),
          reinterpret_cast<XPUType*>(dx->data<T>()),
          n,
          c,
          in_h,
          in_w,
          kernel_size,
          strides,
          paddings,
          true);
    } else if (pooling_type == "avg") {
      r = xpu::avg_pool2d_grad<XPUType>(
          ctx.x_context(),
          reinterpret_cast<const XPUType*>(x.data<T>()),
          reinterpret_cast<const XPUType*>(out.data<T>()),
          reinterpret_cast<const XPUType*>(dout.data<T>()),
          reinterpret_cast<XPUType*>(dx->data<T>()),
          n,
          c,
          in_h,
          in_w,
          kernel_size,
          strides,
          paddings,
          !exclusive,
          true);
    } else {
      PADDLE_THROW(phi::errors::InvalidArgument(
          "Unsupported pooling type for kunlun ", pooling_type));
    }
    PADDLE_ENFORCE_XDNN_SUCCESS(r, "pool2dgrad");
  }
}

template <typename T, typename Context>
void Pool3dGradKernel(const Context& ctx,
                      const DenseTensor& x,
                      const DenseTensor& out,
                      const DenseTensor& dout,
                      const std::vector<int>& kernel_size_t,
                      const std::vector<int>& strides_t,
                      const std::vector<int>& paddings_t,
                      bool ceil_mode,
                      bool exclusive,
                      const std::string& data_format,
                      const std::string& pooling_type,
                      bool global_pooling,
                      bool adaptive,
                      const std::string& padding_algorithm,
                      DenseTensor* dx) {
  using XPUType = typename XPUTypeTrait<T>::Type;
  auto x_dims = x.dims();
  const bool channel_last = data_format == "NDHWC";

  std::vector<int> paddings(paddings_t);
  std::vector<int> kernel_size(kernel_size_t);
  std::vector<int> strides(strides_t);

  PADDLE_ENFORCE_EQ(
      data_format,
      "NCDHW",
      phi::errors::InvalidArgument("The Pool3d_grad XPU OP only support"
                                   "data_format is 'NCDHW', but received %s",
                                   data_format));
  if (!dx) {
    return;
236
  }
Y
ykkk2333 已提交
237 238 239 240 241
  int n = x.dims()[0];
  int c = x.dims()[1];
  int in_d = x.dims()[2];
  int in_h = x.dims()[3];
  int in_w = x.dims()[4];
242

Y
ykkk2333 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
  int out_d = out.dims()[2];
  int out_h = out.dims()[3];
  int out_w = out.dims()[4];

  if (channel_last) {
    c = x.dims()[4];
    in_d = x.dims()[1];
    in_h = x.dims()[2];
    in_w = x.dims()[3];

    out_d = out.dims()[1];
    out_h = out.dims()[2];
    out_w = out.dims()[3];
  }

  DDim data_dims;
  if (channel_last) {
    data_dims = slice_ddim(x_dims, 1, x_dims.size() - 1);
261
  } else {
Y
ykkk2333 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    data_dims = slice_ddim(x_dims, 2, x_dims.size());
  }
  funcs::UpdatePadding(&paddings,
                       global_pooling,
                       adaptive,
                       padding_algorithm,
                       data_dims,
                       strides,
                       kernel_size);

  if (global_pooling) {
    funcs::UpdateKernelSize(&kernel_size, data_dims);
  }

  ctx.template Alloc<T>(dx);
  const int* index_data = nullptr;
  int r = xpu::Error_t::SUCCESS;

  if (adaptive) {
    if (pooling_type == "max") {
      r = xpu::adaptive_max_pool3d_grad<XPUType>(
          ctx.x_context(),
          reinterpret_cast<const XPUType*>(x.data<T>()),
          reinterpret_cast<const XPUType*>(out.data<T>()),
          index_data,
          reinterpret_cast<const XPUType*>(dout.data<T>()),
          reinterpret_cast<XPUType*>(dx->data<T>()),
          n,
          c,
          in_d,
          in_h,
          in_w,
          out_d,
          out_h,
          out_w,
          !channel_last);

    } else if (pooling_type == "avg") {
300
      if (out_d == 1 && out_h == 1 && out_w == 1 &&
301
          std::is_same<T, float>::value) {
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        xpu::ctx_guard RAII_GUARD(ctx.x_context());
        float scale = 1.0 / (in_d * in_h * in_w);
        float* scaled_dy = RAII_GUARD.alloc_l3_or_gm<float>(n * c);
        r = xpu::scale(ctx.x_context(),
                       dout.data<float>(),
                       scaled_dy,
                       n * c,
                       true,
                       scale,
                       0.0);
        PADDLE_ENFORCE_XDNN_SUCCESS(r, "scale");

        r = xpu::broadcast(ctx.x_context(),
                           scaled_dy,
                           dx->data<float>(),
                           {n, c, 1, 1, 1},
                           {n, c, in_d, in_h, in_w});
        PADDLE_ENFORCE_XDNN_SUCCESS(r, "broadcast");

        return;
      }

Y
ykkk2333 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
      r = xpu::adaptive_avg_pool3d_grad<XPUType>(
          ctx.x_context(),
          reinterpret_cast<const XPUType*>(dout.data<T>()),
          reinterpret_cast<XPUType*>(dx->data<T>()),
          n,
          c,
          in_d,
          in_h,
          in_w,
          out_d,
          out_h,
          out_w,
          !channel_last);
    } else {
      PADDLE_THROW(phi::errors::InvalidArgument(
          "Unsupported pooling type for kunlun ", pooling_type));
    }

    PADDLE_ENFORCE_XDNN_SUCCESS(r, "adaptive_pool3d_grad");
  } else {
    if (pooling_type == "max") {
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
      if (kernel_size[0] == 1 && kernel_size.size() == 3 &&
          strides.size() == 3 && paddings.size() == 6) {
        r = xpu::max_pool2d_grad<XPUType>(
            ctx.x_context(),
            reinterpret_cast<const XPUType*>(x.data<T>()),
            reinterpret_cast<const XPUType*>(out.data<T>()),
            index_data,
            reinterpret_cast<const XPUType*>(dout.data<T>()),
            reinterpret_cast<XPUType*>(dx->data<T>()),
            n,
            c * in_d,
            in_h,
            in_w,
            {kernel_size[1], kernel_size[2]},
            {strides[1], strides[2]},
            {paddings[2], paddings[3], paddings[4], paddings[5]},
            !channel_last);
      } else {
        r = xpu::max_pool3d_grad<XPUType>(
            ctx.x_context(),
            reinterpret_cast<const XPUType*>(x.data<T>()),
            reinterpret_cast<const XPUType*>(out.data<T>()),
            index_data,
            reinterpret_cast<const XPUType*>(dout.data<T>()),
            reinterpret_cast<XPUType*>(dx->data<T>()),
            n,
            c,
            in_d,
            in_h,
            in_w,
            kernel_size,
            strides,
            paddings,
            !channel_last);
      }
Y
ykkk2333 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    } else if (pooling_type == "avg") {
      r = xpu::avg_pool3d_grad<XPUType>(
          ctx.x_context(),
          reinterpret_cast<const XPUType*>(dout.data<T>()),
          reinterpret_cast<XPUType*>(dx->data<T>()),
          n,
          c,
          in_d,
          in_h,
          in_w,
          kernel_size,
          strides,
          paddings,
          !exclusive,
          !channel_last);
    } else {
      PADDLE_THROW(phi::errors::InvalidArgument(
          "Unsupported pooling type for kunlun ", pooling_type));
    }
    PADDLE_ENFORCE_XDNN_SUCCESS(r, "pool3dgrad");
400 401
  }
}
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

template <typename T, typename Context>
void MaxPool2dWithIndexGradKernel(const Context& ctx,
                                  const DenseTensor& x,
                                  const DenseTensor& mask,
                                  const DenseTensor& dout,
                                  const std::vector<int>& kernel_size,
                                  const std::vector<int>& strides_t,
                                  const std::vector<int>& paddings_t,
                                  bool global_pooling,
                                  bool adaptive,
                                  DenseTensor* dx) {
  using XPUType = typename XPUTypeTrait<T>::Type;

  ctx.template Alloc<T>(dx);
  auto input_grad = reinterpret_cast<XPUType*>(dx->data<T>());
  std::vector<int> ksize(kernel_size);
  std::vector<int> strides(strides_t);
  std::vector<int> paddings(paddings_t);
  const auto* index_data = mask.data<int>();

  PADDLE_ENFORCE_NOT_NULL(index_data,
                          errors::NotFound("index data should not be nullptr"));
  PADDLE_ENFORCE_EQ(
      ksize.size(),
      2,
      phi::errors::InvalidArgument("The Pool2d XPU OP only support 2 "
                                   "dimension pooling!, but received "
                                   "%d-dimension pool kernel size",
                                   ksize.size()));
  global_pooling = global_pooling || (adaptive && (ksize[0] * ksize[1] == 1));
  if (global_pooling) {
    for (size_t i = 0; i < ksize.size(); ++i) {
      paddings[i] = 0;
      ksize[i] = static_cast<int>(dx->dims()[i + 2]);
    }
  }
  const int n = dx->dims()[0];
  const int c = dx->dims()[1];
  const int in_h = dx->dims()[2];
  const int in_w = dx->dims()[3];
  auto output_grad = reinterpret_cast<const XPUType*>(dout.data<T>());

  int r = xpu::Error_t::SUCCESS;
  // pass a nullptr as input to XDNN is fine as long as index_data exists
  r = xpu::max_pool2d_grad<XPUType>(ctx.x_context(),
                                    /*input*/ nullptr,
                                    /*output*/ nullptr,
                                    index_data,
                                    output_grad,
                                    input_grad,
                                    n,
                                    c,
                                    in_h,
                                    in_w,
                                    ksize,
                                    strides,
                                    paddings,
                                    true);
  PADDLE_ENFORCE_XDNN_SUCCESS(r, "max_pool2d_with_index_grad");
}
463 464 465 466 467 468 469 470
}  // namespace phi

PD_REGISTER_KERNEL(pool2d_grad,
                   XPU,
                   ALL_LAYOUT,
                   phi::Pool2dGradKernel,
                   float,
                   phi::dtype::float16) {}
Y
ykkk2333 已提交
471 472 473 474 475 476
PD_REGISTER_KERNEL(pool3d_grad,
                   XPU,
                   ALL_LAYOUT,
                   phi::Pool3dGradKernel,
                   float,
                   phi::dtype::float16) {}
477 478 479 480 481 482
PD_REGISTER_KERNEL(max_pool2d_with_index_grad,
                   XPU,
                   ALL_LAYOUT,
                   phi::MaxPool2dWithIndexGradKernel,
                   float,
                   phi::dtype::float16) {}