shuffle_batch_op.cc 6.4 KB
Newer Older
Z
zhoushiyu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 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/shuffle_batch_op.h"
16

Z
zhoushiyu 已提交
17
#include <memory>
18

Z
zhoushiyu 已提交
19 20 21 22 23 24 25 26 27 28 29
#include "paddle/fluid/framework/no_need_buffer_vars_inference.h"
#include "paddle/fluid/framework/var_type_inference.h"

namespace paddle {
namespace operators {
class ShuffleBatchOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE_EQ(
30 31
        ctx->HasInput("X"),
        true,
Z
zhoushiyu 已提交
32 33
        platform::errors::NotFound("Input(X) should not be null."));
    PADDLE_ENFORCE_EQ(
34 35
        ctx->HasInput("Seed"),
        true,
Z
zhoushiyu 已提交
36 37
        platform::errors::NotFound("Input(Seed) should not be null."));
    PADDLE_ENFORCE_EQ(
38 39
        ctx->HasOutput("Out"),
        true,
Z
zhoushiyu 已提交
40 41
        platform::errors::NotFound("Output(Out) should not be null."));
    PADDLE_ENFORCE_EQ(
42 43
        ctx->HasOutput("ShuffleIdx"),
        true,
Z
zhoushiyu 已提交
44 45
        platform::errors::NotFound("Output(ShuffleIdx) should not be null."));
    PADDLE_ENFORCE_EQ(
46 47
        ctx->HasOutput("SeedOut"),
        true,
Z
zhoushiyu 已提交
48 49 50 51 52 53
        platform::errors::NotFound("Output(SeedOut) should not be null."));

    ctx->ShareDim("X", "Out");
    ctx->ShareLoD("X", "Out");
    ctx->ShareDim("Seed", "SeedOut");
    ctx->ShareLoD("Seed", "SeedOut");
54
    ctx->SetOutputDim("ShuffleIdx", phi::make_ddim({-1}));
Z
zhoushiyu 已提交
55 56 57
  }

 protected:
58
  phi::KernelKey GetExpectedKernelType(
Z
zhoushiyu 已提交
59 60
      const framework::ExecutionContext &ctx) const override {
    auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
61
    return phi::KernelKey(data_type, ctx.GetPlace());
Z
zhoushiyu 已提交
62
  }
63

64
  phi::KernelKey GetKernelTypeForVar(
65
      const std::string &var_name,
66
      const phi::DenseTensor &tensor,
67
      const phi::KernelKey &expected_kernel_type) const override {
68
    if (var_name == "Seed") {
69 70 71
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
72 73 74 75
    }
    return framework::OperatorWithKernel::GetKernelTypeForVar(
        var_name, tensor, expected_kernel_type);
  }
Z
zhoushiyu 已提交
76 77 78 79 80
};

class ShuffleBatchOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
81 82
    AddInput("X", "(phi::DenseTensor) The input tensor of shuffle_batch op.");
    AddInput("Seed", "(phi::DenseTensor) The input seed tensor.");
Z
zhoushiyu 已提交
83 84 85 86 87 88
    AddAttr<int>(
        "startup_seed",
        "If input tensor 'Seed' is not initialized, the 'startup_seed' "
        "will be used to replace it. The seed after shuffle batch will "
        "be saved in 'SeedOut'. ")
        .SetDefault(0);
89 90
    AddOutput("Out",
              "(phi::DenseTensor) The output tensor of shuffle_batch op.");
Z
zhoushiyu 已提交
91
    AddOutput("ShuffleIdx", "(Tensor) Record forword shuffle order");
92
    AddOutput("SeedOut", "(phi::DenseTensor) Saved new generated seed.");
Z
zhoushiyu 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    AddComment(R"DOC(
Shuffle Batch Operator.

This operator is used to shuffle input $X$'s elements.

There is 2 input. The product of input dims (except last dim) numbers of elements will be shuffled. $Seed$ is tensor of seed.

There are 3 outputs. $Out$ is shuffled tensor of input. $ShuffleIdx$ is the tensor used to record shuffle order. $SeedOut$ is same tensor of $Seed$.
)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE_EQ(
111 112
        ctx->HasInput("ShuffleIdx"),
        true,
Z
zhoushiyu 已提交
113 114
        platform::errors::NotFound("Input(ShuffleIdx) should not be null"));
    PADDLE_ENFORCE_EQ(
115 116
        ctx->HasInput(framework::GradVarName("Out")),
        true,
Z
zhoushiyu 已提交
117 118
        platform::errors::NotFound("Grad Input(Out) should not be null"));
    PADDLE_ENFORCE_EQ(
119 120
        ctx->HasOutput(framework::GradVarName("X")),
        true,
Z
zhoushiyu 已提交
121 122 123 124 125 126 127
        platform::errors::NotFound("Grad Output(X) should not be null"));

    ctx->ShareDim(framework::GradVarName("Out"), framework::GradVarName("X"));
    ctx->ShareLoD(framework::GradVarName("Out"), framework::GradVarName("X"));
  }

 protected:
128
  phi::KernelKey GetExpectedKernelType(
Z
zhoushiyu 已提交
129 130 131
      const framework::ExecutionContext &ctx) const override {
    auto data_type = OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));
132
    return phi::KernelKey(data_type, ctx.GetPlace());
Z
zhoushiyu 已提交
133 134 135 136 137 138 139 140 141
  }
};

template <typename T>
class ShuffleBatchGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
142
  void Apply(GradOpPtr<T> op) const override {
Z
zhoushiyu 已提交
143 144 145 146 147 148 149 150 151 152 153 154
    op->SetType("shuffle_batch_grad");
    op->SetInput("ShuffleIdx", this->Output("ShuffleIdx"));
    op->SetAttrMap(this->Attrs());
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
155 156 157
REGISTER_OPERATOR(shuffle_batch,
                  ops::ShuffleBatchOp,
                  ops::ShuffleBatchOpMaker,
Z
zhoushiyu 已提交
158 159 160 161
                  ops::ShuffleBatchGradOpMaker<paddle::framework::OpDesc>,
                  ops::ShuffleBatchGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(shuffle_batch_grad, ops::ShuffleBatchOpGrad);

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
PD_REGISTER_STRUCT_KERNEL(shuffle_batch,
                          CPU,
                          ALL_LAYOUT,
                          ops::ShuffleBatchKernel,
                          float,
                          double,
                          int32_t,
                          int64_t) {}
PD_REGISTER_STRUCT_KERNEL(shuffle_batch_grad,
                          CPU,
                          ALL_LAYOUT,
                          ops::ShuffleBatchGradKernel,
                          float,
                          double,
                          int32_t,
                          int64_t) {}