common_infer_shape_functions.cc 7.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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/operators/common_infer_shape_functions.h"
L
Leo Chen 已提交
16

17 18 19
#include <algorithm>
#include <vector>

W
wanghuancoder 已提交
20 21 22 23 24 25
namespace paddle {
namespace framework {
class InferShapeContext;
}  // namespace framework
}  // namespace paddle

26 27 28 29 30 31
// This file almostly contains all the infershape functions that are used in
// operators.

namespace paddle {
namespace operators {
namespace details {
L
Leo Chen 已提交
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
inline void GetBroadcastDimsArrays(const framework::DDim &x_dims,
                                   const framework::DDim &y_dims,
                                   int *x_dims_array, int *y_dims_array,
                                   int *out_dims_array, const int max_dim,
                                   const int axis) {
  PADDLE_ENFORCE_GE(
      axis, 0,
      platform::errors::InvalidArgument(
          "Axis should be great than or equal to 0, but received axis is %d.",
          axis));
  PADDLE_ENFORCE_LT(axis, max_dim,
                    platform::errors::InvalidArgument(
                        "Axis should be less than %d, but received axis is %d.",
                        max_dim, axis));
  if (x_dims.size() > y_dims.size()) {
    std::fill(y_dims_array, y_dims_array + axis, 1);
    if (axis + y_dims.size() < max_dim) {
      std::fill(y_dims_array + axis + y_dims.size(), y_dims_array + max_dim, 1);
    }
    std::copy(x_dims.Get(), x_dims.Get() + x_dims.size(), x_dims_array);
    std::copy(y_dims.Get(), y_dims.Get() + y_dims.size(), y_dims_array + axis);
  } else {
    std::fill(x_dims_array, x_dims_array + axis, 1);
    if (axis + x_dims.size() < max_dim) {
      std::fill(x_dims_array + axis + x_dims.size(), x_dims_array + max_dim, 1);
    }
    std::copy(x_dims.Get(), x_dims.Get() + x_dims.size(), x_dims_array + axis);
    std::copy(y_dims.Get(), y_dims.Get() + y_dims.size(), y_dims_array);
  }

  for (int i = 0; i < max_dim; i++) {
    PADDLE_ENFORCE_EQ(
        x_dims_array[i] == y_dims_array[i] || x_dims_array[i] <= 1 ||
            y_dims_array[i] <= 1,
        true, platform::errors::InvalidArgument(
                  "Broadcast dimension mismatch. Operands could "
                  "not be broadcast together with the shape of X = [%s] and "
                  "the shape of Y = [%s]. Received [%d] in X is not equal to "
                  "[%d] in Y at i:%d.",
                  x_dims, y_dims, x_dims_array[i], y_dims_array[i], i));
    if ((x_dims_array[i] > 1 || y_dims_array[i] > 1) ||
        (x_dims_array[i] == 1 && y_dims_array[i] == 1)) {
      out_dims_array[i] = std::max(x_dims_array[i], y_dims_array[i]);
    } else {
      out_dims_array[i] = -1;
    }
  }
}
L
Leo Chen 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94

framework::DDim BroadcastTwoDims(const framework::DDim &x_dims,
                                 const framework::DDim &y_dims, int axis) {
  int max_dim = std::max(x_dims.size(), y_dims.size());
  axis = (axis == -1 ? std::abs(x_dims.size() - y_dims.size()) : axis);
  std::vector<int> x_dims_array(max_dim);
  std::vector<int> y_dims_array(max_dim);
  std::vector<int> out_dims_array(max_dim);
  GetBroadcastDimsArrays(x_dims, y_dims, x_dims_array.data(),
                         y_dims_array.data(), out_dims_array.data(), max_dim,
                         axis);
  return framework::make_ddim(out_dims_array);
}

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
}  // namespace details

// shape input(0) -> output(0) without change.
void UnaryOpUnchangedInferShape(framework::InferShapeContext *ctx) {
  auto x_name = ctx->GetInputNameByIdx(0);
  auto out_name = ctx->GetOutputNameByIdx(0);
  ctx->ShareDim(x_name, /*->*/ out_name);
  ctx->ShareLoD(x_name, /*->*/ out_name);
}

// shape input(0) -> output(0) without change, check if axis in range [-Rank(x),
// Rank(x)-1]
void UnaryOpUnchangedInferShapeCheckAxis(framework::InferShapeContext *ctx) {
  auto x_name = ctx->GetInputNameByIdx(0);
  auto out_name = ctx->GetOutputNameByIdx(0);
  auto x_dim = ctx->GetInputDim(x_name);
  auto x_rank = x_dim.size();
  auto axis = ctx->Attrs().Get<int>("axis");
  PADDLE_ENFORCE_GE(
      axis, -x_rank,
      platform::errors::InvalidArgument(
          "Attr(axis) value should be in range [-R, R-1], "
          "R is the rank of Input(X). But received axis: %d, R: %d.",
          axis, x_rank));
  PADDLE_ENFORCE_LT(
      axis, x_rank,
      platform::errors::InvalidArgument(
          "Attr(axis) value should be in range [-R, R-1], "
          "R is the rank of Input(X). But received axis: %d, R: %d.",
          axis, x_rank));
  ctx->ShareDim(x_name, /*->*/ out_name);
  ctx->ShareLoD(x_name, /*->*/ out_name);
}

// broadcast input(0) and input(1) -> output(0)
void BinaryOpBroadcastInferShape(framework::InferShapeContext *ctx) {
  auto x_name = ctx->GetInputNameByIdx(0);
  auto y_name = ctx->GetInputNameByIdx(1);
  auto out_name = ctx->GetOutputNameByIdx(0);
  auto x_dims = ctx->GetInputDim(x_name);
  auto y_dims = ctx->GetInputDim(y_name);
  PADDLE_ENFORCE_EQ(
      ctx->GetInputsVarType(y_name).front(),
      framework::proto::VarType::LOD_TENSOR,
      platform::errors::InvalidArgument(
          "The var type of input %s should be LoDTensor, but got %s.",
          ctx->Inputs(y_name).front(), ctx->GetInputsVarType(y_name).front()));

  if (ctx->GetInputsVarType(x_name).front() ==
      framework::proto::VarType::SELECTED_ROWS) {
    PADDLE_ENFORCE_EQ(y_dims.size(), 1u,
                      platform::errors::InvalidArgument(
                          "For binary broadcastable operator, if X is "
                          "Sparse(VarType.SELECTED_ROWS"
                          "), Y must be scalar, and the size of Y should be 1. "
                          "But reveived the size of Y = %s.",
                          y_dims.size()));
    PADDLE_ENFORCE_EQ(
        y_dims[0], 1,
        platform::errors::InvalidArgument(
            "For binary broadcastable operator, if X is "
            "Sparse(VarType.SELECTED_ROWS"
            "), Y must be scalar, the first dimension of Y should be 1. "
            "But reveived the first dimension of Y = %s.",
            y_dims[0]));
  } else if (ctx->GetInputsVarType(x_name).front() !=
             framework::proto::VarType::LOD_TENSOR) {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "For binary broadcastable operator, the var type of input X should "
        "be LOD_TENSOR, but got %s",
        ctx->GetInputsVarType(x_name).front()));
  }

  if (x_dims == y_dims) {
    ctx->ShareDim(x_name, /*->*/ out_name);
    ctx->ShareLoD(x_name, /*->*/ out_name);
  } else {
    int axis = ctx->Attrs().Get<int>("axis");
L
Leo Chen 已提交
173 174
    auto out_dims = details::BroadcastTwoDims(x_dims, y_dims, axis);
    ctx->SetOutputDim(out_name, out_dims);
175 176 177 178 179 180
    ctx->ShareLoD(x_name, /*->*/ out_name);
  }
}

}  // namespace operators
}  // namespace paddle