pad2d_op.cc 26.0 KB
Newer Older
W
whs 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 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 <algorithm>
16 17 18
#include <memory>
#include <string>
#include <vector>
W
whs 已提交
19 20 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 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 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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 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 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/math_function.h"

namespace paddle {
namespace operators {

using framework::Tensor;

template <typename T>
void Pad2DConstNCHW(const T* in_data, const int num, const int channels,
                    const int in_height, const int in_width,
                    const int out_height, const int out_width,
                    const int pad_top, const int pad_left, T value,
                    T* out_data) {
  for (int n = 0; n < num; ++n) {
    for (int c = 0; c < channels; ++c) {
      for (int out_h = 0; out_h < out_height; ++out_h) {
        for (int out_w = 0; out_w < out_width; ++out_w) {
          int in_h = out_h - pad_top;
          int in_w = out_w - pad_left;
          out_data[out_h * out_width + out_w] =
              (in_h < 0 || in_w < 0 || in_h >= in_height || in_w >= in_width)
                  ? value
                  : in_data[in_h * in_width + in_w];
        }
      }
      in_data += in_height * in_width;
      out_data += out_height * out_width;
    }
  }
}

template <typename T>
void Pad2DConstNHWC(const T* in_data, const int num, const int channels,
                    const int in_height, const int in_width,
                    const int out_height, const int out_width,
                    const int pad_top, const int pad_left, T value,
                    T* out_data) {
  for (int n = 0; n < num; ++n) {
    for (int out_h = 0; out_h < out_height; ++out_h) {
      for (int out_w = 0; out_w < out_width; ++out_w) {
        int in_h = out_h - pad_top;
        int in_w = out_w - pad_left;
        const int out_index = (out_h * out_width + out_w) * channels;
        if (in_h < 0 || in_w < 0 || in_h >= in_height || in_w >= in_width) {
          for (int c = 0; c < channels; ++c) {
            out_data[out_index + c] = value;
          }
        } else {
          const int in_index = (in_h * in_width + in_w) * channels;
          for (int c = 0; c < channels; ++c) {
            out_data[out_index + c] = in_data[in_index + c];
          }
        }
      }
    }
    in_data += in_height * in_width * channels;
    out_data += out_height * out_width * channels;
  }
}

template <typename T>
void Pad2DReflectNCHW(const T* in_data, const int num, const int channels,
                      const int in_height, const int in_width,
                      const int out_height, const int out_width,
                      const int pad_top, const int pad_left, T* out_data) {
  for (int n = 0; n < num; ++n) {
    for (int c = 0; c < channels; ++c) {
      for (int out_h = 0; out_h < out_height; ++out_h) {
        for (int out_w = 0; out_w < out_width; ++out_w) {
          int in_h = out_h - pad_top;
          int in_w = out_w - pad_left;
          in_h = std::max(in_h, -in_h);  // reflect by 0
          in_h =
              std::min(in_h, 2 * in_height - in_h - 2);  // reflect by in_height
          in_w = std::max(in_w, -in_w);                  // reflect by 0
          in_w =
              std::min(in_w, 2 * in_width - in_w - 2);  // reflect by in_width
          out_data[out_h * out_width + out_w] = in_data[in_h * in_width + in_w];
        }
      }
      in_data += in_height * in_width;
      out_data += out_height * out_width;
    }
  }
}

template <typename T>
void Pad2DReflectNHWC(const T* in_data, const int num, const int channels,
                      const int in_height, const int in_width,
                      const int out_height, const int out_width,
                      const int pad_top, const int pad_left, T* out_data) {
  for (int n = 0; n < num; ++n) {
    for (int out_h = 0; out_h < out_height; ++out_h) {
      for (int out_w = 0; out_w < out_width; ++out_w) {
        const int out_index = (out_h * out_width + out_w) * channels;
        int in_h = out_h - pad_top;
        int in_w = out_w - pad_left;
        in_h = std::max(in_h, -in_h);
        in_h = std::min(in_h, 2 * in_height - in_h - 2);
        in_w = std::max(in_w, -in_w);
        in_w = std::min(in_w, 2 * in_width - in_w - 2);
        const int in_index = (in_h * in_width + in_w) * channels;

        for (int c = 0; c < channels; ++c) {
          out_data[out_index + c] = in_data[in_index + c];
        }
      }
    }
    in_data += in_height * in_width * channels;
    out_data += out_height * out_width * channels;
  }
}

template <typename T>
void Pad2DEdgeNCHW(const T* in_data, const int num, const int channels,
                   const int in_height, const int in_width,
                   const int out_height, const int out_width, const int pad_top,
                   const int pad_left, T* out_data) {
  for (int n = 0; n < num; ++n) {
    for (int c = 0; c < channels; ++c) {
      for (int out_h = 0; out_h < out_height; ++out_h) {
        for (int out_w = 0; out_w < out_width; ++out_w) {
          int in_h = std::min(in_height - 1, std::max(out_h - pad_top, 0));
          int in_w = std::min(in_width - 1, std::max(out_w - pad_left, 0));
          out_data[out_h * out_width + out_w] = in_data[in_h * in_width + in_w];
        }
      }
      in_data += in_height * in_width;
      out_data += out_height * out_width;
    }
  }
}

template <typename T>
void Pad2DEdgeNHWC(const T* in_data, const int num, const int channels,
                   const int in_height, const int in_width,
                   const int out_height, const int out_width, const int pad_top,
                   const int pad_left, T* out_data) {
  for (int n = 0; n < num; ++n) {
    for (int out_h = 0; out_h < out_height; ++out_h) {
      for (int out_w = 0; out_w < out_width; ++out_w) {
        const int out_index = (out_h * out_width + out_w) * channels;
        int in_h = std::min(in_height - 1, std::max(out_h - pad_top, 0));
        int in_w = std::min(in_width - 1, std::max(out_w - pad_left, 0));
        const int in_index = (in_h * in_width + in_w) * channels;
        for (int c = 0; c < channels; ++c) {
          out_data[out_index + c] = in_data[in_index + c];
        }
      }
    }
    in_data += in_height * in_width * channels;
    out_data += out_height * out_width * channels;
  }
}

template <typename T>
void Pad2DGradConstNCHW(T* d_in_data, const int num, const int channels,
                        const int in_height, const int in_width,
                        const int out_height, const int out_width,
                        const int pad_top, const int pad_left,
                        const T* d_out_data) {
  for (int n = 0; n < num; ++n) {
    for (int c = 0; c < channels; ++c) {
      for (int out_h = 0; out_h < out_height; ++out_h) {
        for (int out_w = 0; out_w < out_width; ++out_w) {
          int in_h = out_h - pad_top;
          int in_w = out_w - pad_left;
          if (!(in_h < 0 || in_w < 0 || in_h >= in_height ||
                in_w >= in_width)) {
            d_in_data[in_h * in_width + in_w] =
                d_out_data[out_h * out_width + out_w];
          }
        }
      }
      d_in_data += in_height * in_width;
      d_out_data += out_height * out_width;
    }
  }
}

template <typename T>
void Pad2DGradConstNHWC(T* d_in_data, const int num, const int channels,
                        const int in_height, const int in_width,
                        const int out_height, const int out_width,
                        const int pad_top, const int pad_left,
                        const T* d_out_data) {
  for (int n = 0; n < num; ++n) {
    for (int out_h = 0; out_h < out_height; ++out_h) {
      for (int out_w = 0; out_w < out_width; ++out_w) {
        int in_h = out_h - pad_top;
        int in_w = out_w - pad_left;
        const int out_index = (out_h * out_width + out_w) * channels;
        if (!(in_h < 0 || in_w < 0 || in_h >= in_height || in_w >= in_width)) {
          const int in_index = (in_h * in_width + in_w) * channels;
          for (int c = 0; c < channels; ++c) {
            d_in_data[in_index + c] = d_out_data[out_index + c];
          }
        }
      }
    }
    d_in_data += in_height * in_width * channels;
    d_out_data += out_height * out_width * channels;
  }
}

template <typename T>
void Pad2DGradReflectNCHW(T* d_in_data, const int num, const int channels,
                          const int in_height, const int in_width,
                          const int out_height, const int out_width,
                          const int pad_top, const int pad_left,
                          const T* d_out_data) {
  for (int n = 0; n < num; ++n) {
    for (int c = 0; c < channels; ++c) {
      for (int out_h = 0; out_h < out_height; ++out_h) {
        for (int out_w = 0; out_w < out_width; ++out_w) {
          int in_h = out_h - pad_top;
          int in_w = out_w - pad_left;
          in_h = std::max(in_h, -in_h);  // reflect over 0
          in_h = std::min(in_h,
                          2 * in_height - in_h - 2);  // reflect over in_height
          in_w = std::max(in_w, -in_w);               // reflect over 0
          in_w =
              std::min(in_w, 2 * in_width - in_w - 2);  // reflect over in_width
          d_in_data[in_h * in_width + in_w] +=
              d_out_data[out_h * out_width + out_w];
        }
      }
      d_in_data += in_height * in_width;
      d_out_data += out_height * out_width;
    }
  }
}

template <typename T>
void Pad2DGradReflectNHWC(T* d_in_data, const int num, const int channels,
                          const int in_height, const int in_width,
                          const int out_height, const int out_width,
                          const int pad_top, const int pad_left,
                          const T* d_out_data) {
  for (int n = 0; n < num; ++n) {
    for (int out_h = 0; out_h < out_height; ++out_h) {
      for (int out_w = 0; out_w < out_width; ++out_w) {
        const int out_index = (out_h * out_width + out_w) * channels;
        int in_h = out_h - pad_top;
        int in_w = out_w - pad_left;
        in_h = std::max(in_h, -in_h);
        in_h = std::min(in_h, 2 * in_height - in_h - 2);
        in_w = std::max(in_w, -in_w);
        in_w = std::min(in_w, 2 * in_width - in_w - 2);
        const int in_index = (in_h * in_width + in_w) * channels;
        for (int c = 0; c < channels; ++c) {
          d_in_data[in_index + c] += d_out_data[out_index + c];
        }
      }
    }
    d_in_data += in_height * in_width * channels;
    d_out_data += out_height * out_width * channels;
  }
}

template <typename T>
void Pad2DGradEdgeNCHW(T* d_in_data, const int num, const int channels,
                       const int in_height, const int in_width,
                       const int out_height, const int out_width,
                       const int pad_top, const int pad_left,
                       const T* d_out_data) {
  for (int n = 0; n < num; ++n) {
    for (int c = 0; c < channels; ++c) {
      for (int out_h = 0; out_h < out_height; ++out_h) {
        for (int out_w = 0; out_w < out_width; ++out_w) {
          int in_h = std::min(in_height - 1, std::max(out_h - pad_top, 0));
          int in_w = std::min(in_width - 1, std::max(out_w - pad_left, 0));
          d_in_data[in_h * in_width + in_w] +=
              d_out_data[out_h * out_width + out_w];
        }
      }
      d_in_data += in_height * in_width;
      d_out_data += out_height * out_width;
    }
  }
}

template <typename T>
void Pad2DGradEdgeNHWC(T* d_in_data, const int num, const int channels,
                       const int in_height, const int in_width,
                       const int out_height, const int out_width,
                       const int pad_top, const int pad_left,
                       const T* d_out_data) {
  for (int n = 0; n < num; ++n) {
    for (int out_h = 0; out_h < out_height; ++out_h) {
      for (int out_w = 0; out_w < out_width; ++out_w) {
        const int out_index = (out_h * out_width + out_w) * channels;
        int in_h = std::min(in_height - 1, std::max(out_h - pad_top, 0));
        int in_w = std::min(in_width - 1, std::max(out_w - pad_left, 0));
        const int in_index = (in_h * in_width + in_w) * channels;
        for (int c = 0; c < channels; ++c) {
          d_in_data[in_index + c] += d_out_data[out_index + c];
        }
      }
    }
    d_in_data += in_height * in_width * channels;
    d_out_data += out_height * out_width * channels;
  }
}

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
static inline void GetPaddings(int* paddings,
                               const framework::ExecutionContext& context) {
  auto* paddings_t = context.Input<Tensor>("Paddings");
  if (paddings_t) {
    auto paddings_data = paddings_t->data<int>();
    paddings[0] = paddings_data[0];
    paddings[1] = paddings_data[1];
    paddings[2] = paddings_data[2];
    paddings[3] = paddings_data[3];
  } else {
    auto pads = context.Attr<std::vector<int>>("paddings");
    std::copy(pads.begin(), pads.end(), paddings);
  }
}

W
whs 已提交
340 341 342 343
template <typename T>
class Pad2dCPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
344 345
    int pads[4];
    GetPaddings(pads, context);
W
whs 已提交
346 347
    auto mode = context.Attr<std::string>("mode");
    auto data_format = context.Attr<std::string>("data_format");
348
    T value = static_cast<T>(context.Attr<float>("pad_value"));
349

W
whs 已提交
350 351 352
    auto* x = context.Input<Tensor>("X");
    auto in_dims = x->dims();
    const T* in_data = x->data<T>();
353 354 355 356 357 358 359 360 361 362

    auto* out = context.Output<Tensor>("Out");
    if (data_format == "NCHW") {
      out->Resize({in_dims[0], in_dims[1], in_dims[2] + pads[0] + pads[1],
                   in_dims[3] + pads[2] + pads[3]});
    } else {
      out->Resize({in_dims[0], in_dims[1] + pads[0] + pads[1],
                   in_dims[2] + pads[2] + pads[3], in_dims[3]});
    }
    auto out_dims = out->dims();
W
whs 已提交
363
    T* out_data = out->mutable_data<T>(context.GetPlace());
364

W
whs 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    const int pad_top = pads[0];
    const int pad_left = pads[2];
    const int num = in_dims[0];
    if (data_format == "NCHW") {
      const int channels = in_dims[1];
      const int in_height = in_dims[2];
      const int in_width = in_dims[3];
      const int out_height = out_dims[2];
      const int out_width = out_dims[3];
      if (mode == "reflect") {
        Pad2DReflectNCHW(in_data, num, channels, in_height, in_width,
                         out_height, out_width, pad_top, pad_left, out_data);
      } else if (mode == "edge") {
        Pad2DEdgeNCHW(in_data, num, channels, in_height, in_width, out_height,
                      out_width, pad_top, pad_left, out_data);
      } else {
        Pad2DConstNCHW(in_data, num, channels, in_height, in_width, out_height,
                       out_width, pad_top, pad_left, value, out_data);
      }
    } else {
      const int channels = in_dims[3];
      const int in_height = in_dims[1];
      const int in_width = in_dims[2];
      const int out_height = out_dims[1];
      const int out_width = out_dims[2];
      if (mode == "reflect") {
        Pad2DReflectNHWC(in_data, num, channels, in_height, in_width,
                         out_height, out_width, pad_top, pad_left, out_data);
      } else if (mode == "edge") {
        Pad2DEdgeNHWC(in_data, num, channels, in_height, in_width, out_height,
                      out_width, pad_top, pad_left, out_data);
      } else {
        Pad2DConstNHWC(in_data, num, channels, in_height, in_width, out_height,
                       out_width, pad_top, pad_left, value, out_data);
      }
    }
  }
};

template <typename T>
class Pad2dGradCPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
408 409
    int pads[4];
    GetPaddings(pads, context);
W
whs 已提交
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 463 464 465 466 467 468
    auto mode = context.Attr<std::string>("mode");
    auto data_format = context.Attr<std::string>("data_format");
    auto* d_out = context.Input<Tensor>(framework::GradVarName("Out"));
    auto* d_in = context.Output<Tensor>(framework::GradVarName("X"));
    auto d_in_dims = d_in->dims();
    auto d_out_dims = d_out->dims();
    const T* d_out_data = d_out->data<T>();
    T* d_in_data = d_in->mutable_data<T>(context.GetPlace());
    math::SetConstant<platform::CPUDeviceContext, T> set_zero;
    set_zero(context.template device_context<platform::CPUDeviceContext>(),
             d_in, static_cast<T>(0));
    const int pad_top = pads[0];
    const int pad_left = pads[2];
    const int num = d_in_dims[0];
    if (data_format == "NCHW") {
      const int channels = d_in_dims[1];
      const int in_height = d_in_dims[2];
      const int in_width = d_in_dims[3];
      const int out_height = d_out_dims[2];
      const int out_width = d_out_dims[3];
      if (mode == "reflect") {
        Pad2DGradReflectNCHW(d_in_data, num, channels, in_height, in_width,
                             out_height, out_width, pad_top, pad_left,
                             d_out_data);
      } else if (mode == "edge") {
        Pad2DGradEdgeNCHW(d_in_data, num, channels, in_height, in_width,
                          out_height, out_width, pad_top, pad_left, d_out_data);
      } else {
        Pad2DGradConstNCHW(d_in_data, num, channels, in_height, in_width,
                           out_height, out_width, pad_top, pad_left,
                           d_out_data);
      }
    } else {
      const int channels = d_in_dims[3];
      const int in_height = d_in_dims[1];
      const int in_width = d_in_dims[2];
      const int out_height = d_out_dims[1];
      const int out_width = d_out_dims[2];
      if (mode == "reflect") {
        Pad2DGradReflectNHWC(d_in_data, num, channels, in_height, in_width,
                             out_height, out_width, pad_top, pad_left,
                             d_out_data);
      } else if (mode == "edge") {
        Pad2DGradEdgeNHWC(d_in_data, num, channels, in_height, in_width,
                          out_height, out_width, pad_top, pad_left, d_out_data);
      } else {
        Pad2DGradConstNHWC(d_in_data, num, channels, in_height, in_width,
                           out_height, out_width, pad_top, pad_left,
                           d_out_data);
      }
    }
  }
};

class Pad2dOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
469 470
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Pad2d");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "Pad2d");
W
whs 已提交
471 472 473

    auto x_dim = ctx->GetInputDim("X");
    PADDLE_ENFORCE_EQ(x_dim.size(), 4,
474 475 476 477
                      platform::errors::InvalidArgument(
                          "The size of Input(X)'s dimension should be equal to "
                          "4, but received %d. ",
                          x_dim.size()));
W
whs 已提交
478

479
    std::vector<int64_t> out_dims(x_dim.size());
W
whs 已提交
480 481
    auto data_format = ctx->Attrs().Get<std::string>("data_format");
    out_dims[0] = x_dim[0];
482 483
    if (ctx->HasInput("Paddings")) {
      auto paddings_dim = ctx->GetInputDim("Paddings");
484 485 486 487 488
      PADDLE_ENFORCE_EQ(paddings_dim.size(), 1,
                        platform::errors::InvalidArgument(
                            "Size of Input(Paddings)'s dimension should be "
                            "equal to 1, but received %d.",
                            paddings_dim.size()));
W
wanghaoshuang 已提交
489 490
      if (ctx->IsRuntime()) {
        PADDLE_ENFORCE_EQ(paddings_dim[0], 4,
491 492 493 494
                          platform::errors::InvalidArgument(
                              "Shape of Input(Paddings) should be equal to "
                              "[4], but received [%d].",
                              paddings_dim[0]));
W
wanghaoshuang 已提交
495
      }
W
whs 已提交
496
      out_dims[1] = x_dim[1];
497
      out_dims[2] = x_dim[2];
W
whs 已提交
498
      out_dims[3] = x_dim[3];
499 500
    } else {
      auto paddings = ctx->Attrs().Get<std::vector<int>>("paddings");
501 502 503 504 505
      PADDLE_ENFORCE_EQ(
          paddings.size(), 4,
          platform::errors::InvalidArgument(
              "Size of paddings should be equal to 4, but received %d.",
              static_cast<int>(paddings.size())));
506
      if (data_format == "NCHW") {
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        out_dims[1] = x_dim[1];  // channel
        out_dims[2] = ((!ctx->IsRuntime()) && (x_dim[2] < 0))
                          ? x_dim[2]
                          : (x_dim[2] + paddings[0] + paddings[1]);  // height
        out_dims[3] = ((!ctx->IsRuntime()) && (x_dim[3] < 0))
                          ? x_dim[3]
                          : (x_dim[3] + paddings[2] + paddings[3]);  // width
      } else {                                                       // NHWC
        out_dims[3] = x_dim[3];                                      // channel
        out_dims[1] = ((!ctx->IsRuntime()) && (x_dim[1] < 0))
                          ? x_dim[1]
                          : (x_dim[1] + paddings[0] + paddings[1]);  // height
        out_dims[2] = ((!ctx->IsRuntime()) && (x_dim[2] < 0))
                          ? x_dim[2]
                          : (x_dim[2] + paddings[2] + paddings[3]);  // width
522
      }
W
whs 已提交
523 524 525
    }

    ctx->SetOutputDim("Out", framework::make_ddim(out_dims));
W
wanghaoshuang 已提交
526
    ctx->ShareLoD("X", /*->*/ "Out");
W
whs 已提交
527
  }
528 529 530 531

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
532 533
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
534
  }
W
whs 已提交
535 536 537 538 539 540 541 542 543 544 545
};

class Pad2dOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "The input of pad2d op. "
             "The input should be a 4-D tensor with formate NCHW or NHWC.");
    AddOutput("Out",
              "The output of pad2d op. "
              "A tensor with the same shape as X.");
546 547 548 549 550 551
    AddInput("Paddings",
             "A 1-D tensor to describe the padding rules."
             "paddings=[0, 1, 2, 3] means "
             "padding 0 row to top, 1 row to bottom, 2 columns to left "
             "and 3 columns to right. Size of paddings must be 4.")
        .AsDispensable();
W
whs 已提交
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    AddAttr<std::vector<int>>(
        "paddings",
        "(vector<int>) "
        "A list<int> to describe the padding rules."
        "paddings=[0, 1, 2, 3] means "
        "padding 0 row to top, 1 row to bottom, 2 columns to left "
        "and 3 columns to right. Size of paddings must be 4.");
    AddAttr<float>("pad_value",
                   "(float, default 0.0) "
                   "The value to fill the padded areas in constant mode.")
        .SetDefault(0.0f);
    AddAttr<std::string>("mode",
                         "(float, default constant) "
                         "Three modes: constant(default), reflect, edge.")
        .SetDefault("constant");
    AddAttr<std::string>(
        "data_format",
        "(string, default NCHW) Only used in "
        "An optional string from: \"NHWC\", \"NCHW\". "
        "Defaults to \"NHWC\". Specify the data format of the input data.")
        .SetDefault("NCHW");
    AddComment(R"DOC(
Pad2d Operator.
T
tianshuo78520a 已提交
575
Pad 2-d images according to 'paddings' and 'mode'. 
W
whs 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
If mode is 'reflect', paddings[0] and paddings[1] must be no greater
than height-1. And the width dimension has the same condition.

Given that X is a channel of image from input:

X = [[1, 2, 3],
     [4, 5, 6]]

Case 0:

paddings = [0, 1, 2, 3],
mode = 'constant'
pad_value = 0

Out = [[0, 0, 1, 2, 3, 0, 0, 0]
       [0, 0, 4, 5, 6, 0, 0, 0]
       [0, 0, 0, 0, 0, 0, 0, 0]]

Case 1:

paddings = [0, 1, 2, 1],
mode = 'reflect'

Out = [[3, 2, 1, 2, 3, 2]
       [6, 5, 4, 5, 6, 5]
       [3, 2, 1, 2, 3, 2]]

Case 2:

paddings = [0, 1, 2, 1],
mode = 'edge'

Out = [[1, 1, 1, 2, 3, 3]
       [4, 4, 4, 5, 6, 6]
       [4, 4, 4, 5, 6, 6]]
)DOC");
  }
};

class Pad2dOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
620 621 622 623
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Pad2d@Grad");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input",
                   framework::GradVarName("Out"), "Pad2d@Grad");

W
whs 已提交
624 625 626 627 628 629
    auto x_dims = ctx->GetInputDim("X");
    auto x_grad_name = framework::GradVarName("X");
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
    }
  }
630 631 632 633

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
634 635 636
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.GetPlace());
637
  }
W
whs 已提交
638 639
};

H
hong 已提交
640 641
template <typename T>
class Pad2dOpGradMaker : public framework::SingleGradOpMaker<T> {
W
whs 已提交
642
 public:
H
hong 已提交
643
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
W
whs 已提交
644 645

 protected:
646
  void Apply(GradOpPtr<T> bind) const override {
H
hong 已提交
647 648 649
    bind->SetInput("X", this->Input("X"));
    if (this->HasInput("Paddings")) {
      bind->SetInput("Paddings", this->Input("Paddings"));
650
    }
H
hong 已提交
651 652 653
    bind->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    bind->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    bind->SetAttrMap(this->Attrs());
W
whs 已提交
654 655 656 657
    bind->SetType("pad2d_grad");
  }
};

658
// TODO(zjl): Paddings can also be skipped!
Z
Zeng Jinle 已提交
659
DECLARE_NO_NEED_BUFFER_VARS_INFERER(Pad2dOpGradNoNeedBufferVarsInference, "X");
660

W
whs 已提交
661 662 663 664 665 666
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(pad2d, ops::Pad2dOp, ops::Pad2dOpMaker,
H
hong 已提交
667 668
                  ops::Pad2dOpGradMaker<paddle::framework::OpDesc>,
                  ops::Pad2dOpGradMaker<paddle::imperative::OpBase>);
669 670
REGISTER_OPERATOR(pad2d_grad, ops::Pad2dOpGrad,
                  ops::Pad2dOpGradNoNeedBufferVarsInference);
671 672 673 674 675
REGISTER_OP_CPU_KERNEL(pad2d, ops::Pad2dCPUKernel<float>,
                       ops::Pad2dCPUKernel<double>, ops::Pad2dCPUKernel<int>,
                       ops::Pad2dCPUKernel<int64_t>);
REGISTER_OP_CPU_KERNEL(pad2d_grad, ops::Pad2dGradCPUKernel<float>,
                       ops::Pad2dGradCPUKernel<double>);