pad2d_op.cc 24.4 KB
Newer Older
W
whs 已提交
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 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
/* 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>
#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;
  }
}

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
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 已提交
337 338 339 340
template <typename T>
class Pad2dCPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
341 342
    int pads[4];
    GetPaddings(pads, context);
W
whs 已提交
343 344 345
    auto mode = context.Attr<std::string>("mode");
    auto data_format = context.Attr<std::string>("data_format");
    T value = context.Attr<T>("pad_value");
346

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

    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 已提交
360
    T* out_data = out->mutable_data<T>(context.GetPlace());
361

W
whs 已提交
362 363 364 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
    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 {
405 406
    int pads[4];
    GetPaddings(pads, context);
W
whs 已提交
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 463 464 465 466 467 468 469 470 471 472
    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 {
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of Pad2dOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of Pad2dOp should not be null.");

    auto x_dim = ctx->GetInputDim("X");
    PADDLE_ENFORCE_EQ(x_dim.size(), 4,
473
                      "The size of input(X)'s dimension should be equal to 4.");
W
whs 已提交
474

475
    std::vector<int64_t> out_dims(x_dim.size());
W
whs 已提交
476 477
    auto data_format = ctx->Attrs().Get<std::string>("data_format");
    out_dims[0] = x_dim[0];
478 479 480 481 482 483 484
    if (ctx->HasInput("Paddings")) {
      auto paddings_dim = ctx->GetInputDim("Paddings");
      PADDLE_ENFORCE_EQ(
          paddings_dim.size(), 1,
          "Size of Input(Paddings)'s dimension should be equal to 1.");
      PADDLE_ENFORCE_EQ(paddings_dim[0], 4,
                        "Shape of Input(Paddings) should be equal to [4].");
W
whs 已提交
485
      out_dims[1] = x_dim[1];
486
      out_dims[2] = x_dim[2];
W
whs 已提交
487
      out_dims[3] = x_dim[3];
488 489 490 491 492 493 494 495 496 497 498 499 500
    } else {
      auto paddings = ctx->Attrs().Get<std::vector<int>>("paddings");
      PADDLE_ENFORCE_EQ(paddings.size(), 4,
                        "Size of paddings should be equal to 4.");
      if (data_format == "NCHW") {
        out_dims[1] = x_dim[1];
        out_dims[2] = x_dim[2] + paddings[0] + paddings[1];  // height
        out_dims[3] = x_dim[3] + paddings[2] + paddings[3];  // width
      } else {                                               // NHWC
        out_dims[3] = x_dim[3];
        out_dims[1] = x_dim[1] + paddings[0] + paddings[1];
        out_dims[2] = x_dim[2] + paddings[2] + paddings[3];
      }
W
whs 已提交
501 502 503 504 505 506 507 508 509
    }

    ctx->SetOutputDim("Out", framework::make_ddim(out_dims));
    if (out_dims[0] == x_dim[0]) {
      // Only pass LoD when the first dimension is equal between
      // output and input.
      ctx->ShareLoD("X", /*->*/ "Out");
    }
  }
510 511 512 513 514 515 516

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        framework::ToDataType(ctx.Input<Tensor>("X")->type()), ctx.GetPlace());
  }
W
whs 已提交
517 518 519 520 521 522 523 524 525 526 527
};

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.");
528 529 530 531 532 533
    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 已提交
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 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
    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.
Pad 2-d images accordding to 'paddings' and 'mode'. 
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 {
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) should not be null");
    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);
    }
  }
611 612 613 614 615 616 617

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        framework::ToDataType(ctx.Input<Tensor>("X")->type()), ctx.GetPlace());
  }
W
whs 已提交
618 619 620 621 622 623 624 625 626 627
};

class Pad2dOpGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto* bind = new framework::OpDesc();
    bind->SetInput("X", Input("X"));
628
    bind->SetInput("Paddings", Input("Paddings"));
W
whs 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    bind->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
    bind->SetOutput(framework::GradVarName("X"), InputGrad("X"));
    bind->SetAttrMap(Attrs());
    bind->SetType("pad2d_grad");
    return std::unique_ptr<framework::OpDesc>(bind);
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(pad2d, ops::Pad2dOp, ops::Pad2dOpMaker,
                  ops::Pad2dOpGradMaker);
REGISTER_OPERATOR(pad2d_grad, ops::Pad2dOpGrad);
REGISTER_OP_CPU_KERNEL(pad2d, ops::Pad2dCPUKernel<float>);
REGISTER_OP_CPU_KERNEL(pad2d_grad, ops::Pad2dGradCPUKernel<float>);