spectral_norm_op.cc 10.3 KB
Newer Older
1
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
D
dengkaipeng 已提交
2 3 4 5 6 7 8 9 10 11 12
   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/spectral_norm_op.h"
Z
zhhsplendid 已提交
13 14 15

#include <memory>

D
dengkaipeng 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28
#include "paddle/fluid/framework/op_registry.h"

namespace paddle {
namespace operators {

using framework::Tensor;

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

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
K
Kaipeng Deng 已提交
29 30 31 32
    OP_INOUT_CHECK(ctx->HasInput("Weight"), "Input", "Weight", "SpectralNorm");
    OP_INOUT_CHECK(ctx->HasInput("U"), "Input", "U", "SpectralNorm");
    OP_INOUT_CHECK(ctx->HasInput("V"), "Input", "V", "SpectralNorm");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "SpectralNorm");
M
miraiwk 已提交
33 34
    OP_INOUT_CHECK(ctx->HasOutput("UOut"), "Output", "UOut", "SpectralNorm");
    OP_INOUT_CHECK(ctx->HasOutput("VOut"), "Output", "VOut", "SpectralNorm");
D
dengkaipeng 已提交
35 36

    auto dim_weight = ctx->GetInputDim("Weight");
D
dengkaipeng 已提交
37
    auto rank_weight = dim_weight.size();
38 39 40 41 42 43 44 45 46 47
    PADDLE_ENFORCE_GE(rank_weight, 2,
                      platform::errors::InvalidArgument(
                          "The rank of Input(Weights) should be greater equal "
                          "than 2, but received Weight rank(%d)",
                          rank_weight));
    PADDLE_ENFORCE_LE(rank_weight, 5,
                      platform::errors::InvalidArgument(
                          "The rank of Input(Weights) should be less equal "
                          "than 5, but received Weight rank(%d)",
                          rank_weight));
D
dengkaipeng 已提交
48 49 50

    int dim = ctx->Attrs().Get<int>("dim");
    int power_iters = ctx->Attrs().Get<int>("power_iters");
51 52 53 54 55 56 57 58 59 60
    auto dim_valid = dim == 0 || dim == 1;
    PADDLE_ENFORCE_EQ(
        dim_valid, true,
        platform::errors::InvalidArgument(
            "Attr(dim) can only be 0 or 1, but received %d", dim));
    PADDLE_ENFORCE_GE(
        power_iters, 0,
        platform::errors::InvalidArgument(
            "Attr(power_iters) should be greater equal then 0, but received %d",
            power_iters));
D
dengkaipeng 已提交
61

D
dengkaipeng 已提交
62 63 64 65 66 67 68 69 70
    int h = dim_weight[dim];
    int w = 1;
    for (int i = 0; i < rank_weight; i++) {
      if (i != dim) {
        w *= dim_weight[i];
      }
    }
    auto dim_u = ctx->GetInputDim("U");
    auto dim_v = ctx->GetInputDim("V");
71 72 73

    if (ctx->IsRuntime() || (dim_u[0] > 0 && h > 0)) {
      PADDLE_ENFORCE_EQ(dim_u[0], h,
74 75 76 77 78
                        platform::errors::InvalidArgument(
                            "Input(U) dimension[0] should be equal to "
                            "Input(Weight) dimension[Attr(dim)], but received "
                            "U dimension[0](%d) != Weight dimension[%d](%d)",
                            dim_u[0], dim, h));
79 80 81 82 83
    }

    if (ctx->IsRuntime() || (dim_v[0] > 0 && w > 0)) {
      PADDLE_ENFORCE_EQ(
          dim_v[0], w,
84 85 86 87 88 89
          platform::errors::InvalidArgument(
              "Input(V) dimension[0] should be equal to the product of "
              "Input(Weight) dimension except dimension[Attr(dim)], but "
              "received V dimension[0](%d) != product of Input(Weight) "
              "dimension(%d)",
              dim_v[0], w));
90
    }
D
dengkaipeng 已提交
91

D
dengkaipeng 已提交
92
    ctx->SetOutputDim("Out", dim_weight);
M
miraiwk 已提交
93 94
    ctx->SetOutputDim("UOut", dim_u);
    ctx->SetOutputDim("VOut", dim_v);
D
dengkaipeng 已提交
95 96 97 98 99 100
    ctx->ShareLoD("Weight", /*->*/ "Out");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
101 102
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Weight"), ctx.GetPlace());
D
dengkaipeng 已提交
103 104 105 106 107 108 109 110
  }
};

class SpectralNormOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("Weight",
             "The input weight tensor of spectral_norm operator, "
D
dengkaipeng 已提交
111
             "This can be a 2-D, 3-D, 4-D, 5-D tensor which is the "
K
Kaipeng Deng 已提交
112 113
             "weights of fc, conv1d, conv2d, conv3d layer. "
             "The data type is float32 or float64.");
D
dengkaipeng 已提交
114 115 116
    AddInput("U",
             "The weight_u tensor of spectral_norm operator, "
             "This can be a 1-D tensor in shape [H, 1],"
T
tianshuo78520a 已提交
117
             "H is the 1st dimensions of Weight after reshape"
118 119
             "corresponding by Attr(dim). As for Attr(dim) = 1"
             "in conv2d layer with weight shape [M, C, K1, K2]"
D
dengkaipeng 已提交
120
             "Weight will be reshape to [C, M*K1*K2], U will"
121
             "be in shape [C, 1].");
D
dengkaipeng 已提交
122
    AddInput("V",
123
             "The weight_v tensor of spectral_norm operator, "
D
dengkaipeng 已提交
124
             "This can be a 1-D tensor in shape [W, 1], "
T
tianshuo78520a 已提交
125
             "W is the 2nd dimensions of Weight after reshape "
D
dengkaipeng 已提交
126 127 128
             "corresponding by Attr(dim). As for Attr(dim) = 1 "
             "in conv2d layer with weight shape [M, C, K1, K2] "
             "Weight will be reshape to [C, M*K1*K2], V will "
129
             "be in shape [M*K1*K2, 1].");
D
dengkaipeng 已提交
130 131 132
    AddOutput("Out",
              "The output weight tensor of spectral_norm operator, "
              "This tensor is in same shape with Input(Weight).");
M
miraiwk 已提交
133 134 135 136
    AddOutput("UOut",
              "The updated value of `U`");
    AddOutput("VOut",
              "The updated value of `V`");
D
dengkaipeng 已提交
137 138

    AddAttr<int>("dim",
D
dengkaipeng 已提交
139 140
                 "The index of dimension which should be permuted "
                 "to the first before reshaping Input(Weight) to "
D
dengkaipeng 已提交
141 142
                 "matrix, it should be set as 0 if Input(Weight) is "
                 "the weight of fc layer, and should be set as 1 if "
D
dengkaipeng 已提交
143 144
                 "Input(Weight) is the weight of conv layer, "
                 "default 0.")
D
dengkaipeng 已提交
145 146
        .SetDefault(0);
    AddAttr<int>("power_iters",
D
dengkaipeng 已提交
147 148
                 "number of power iterations to calculate "
                 "spectral norm, default 1.")
D
dengkaipeng 已提交
149 150
        .SetDefault(1);
    AddAttr<float>("eps",
D
dengkaipeng 已提交
151
                   "epsilon for numerical stability in "
K
Kaipeng Deng 已提交
152 153 154
                   "calculating norms, it will be added to "
                   "the denominator to aviod divide zero. "
                   "Default 1e-12.")
D
dengkaipeng 已提交
155 156
        .SetDefault(1e-12);
    AddComment(R"DOC(
D
dengkaipeng 已提交
157
          This layer calculates the spectral normalization value of weight of
158 159
          fc, conv1d, conv2d, conv3d layers which should be 2-D, 3-D, 4-D, 5-D
          tensor.
D
dengkaipeng 已提交
160

161 162 163
          Spectral normalization stabilizes the training of critic in GANs
          (Generative Adversarial Networks). This layer rescaling weight tensor
          with spectral normalize value.
D
dengkaipeng 已提交
164

165
          For spectral normalization calculations, we rescaling weight
D
dengkaipeng 已提交
166
          tensor with :math:`\sigma`, while :math:`\sigma{\mathbf{W}}` is
167

D
dengkaipeng 已提交
168
            $$\sigma(\mathbf{W}) = \max_{\mathbf{h}: \mathbf{h} \ne 0} \\frac{\|\mathbf{W} \mathbf{h}\|_2}{\|\mathbf{h}\|_2}$$
169

D
dengkaipeng 已提交
170
          We calculate :math:`\sigma{\mathbf{W}}` through power iterations as
171

D
dengkaipeng 已提交
172
            $$
173
            \mathbf{v} = \mathbf{W}^{T} \mathbf{u}
D
dengkaipeng 已提交
174 175 176 177 178
            $$
            $$
            \mathbf{v} = \\frac{\mathbf{v}}{\|\mathbf{v}\|_2}
            $$
            $$
179
            \mathbf{u} = \mathbf{W}^{T} \mathbf{v}
D
dengkaipeng 已提交
180 181 182 183
            $$
            $$
            \mathbf{u} = \\frac{\mathbf{u}}{\|\mathbf{u}\|_2}
            $$
184

D
dengkaipeng 已提交
185
          And :math:`\sigma` should be
186

D
dengkaipeng 已提交
187
            $$\sigma{\mathbf{W}} = \mathbf{u}^{T} \mathbf{W} \mathbf{v}$$
188 189 190

          For details of spectral normalization, please refer to paper: 
          `Spectral Normalization <https://arxiv.org/abs/1802.05957>`_ .
D
dengkaipeng 已提交
191 192 193 194
         )DOC");
  }
};

H
hong 已提交
195 196
template <typename T>
class SpectralNormGradOpMaker : public framework::SingleGradOpMaker<T> {
Z
zhhsplendid 已提交
197
 public:
H
hong 已提交
198
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
Z
zhhsplendid 已提交
199 200

 protected:
201
  void Apply(GradOpPtr<T> op) const override {
Z
zhhsplendid 已提交
202 203
    op->SetType("spectral_norm_grad");

H
hong 已提交
204 205 206 207
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetInput("Weight", this->Input("Weight"));
    op->SetInput("U", this->Input("U"));
    op->SetInput("V", this->Input("V"));
M
miraiwk 已提交
208 209
    op->SetInput("UOut", this->Output("UOut"));
    op->SetInput("VOut", this->Output("VOut"));
Z
zhhsplendid 已提交
210

H
hong 已提交
211
    op->SetOutput(framework::GradVarName("Weight"), this->InputGrad("Weight"));
Z
zhhsplendid 已提交
212

H
hong 已提交
213
    op->SetAttrMap(this->Attrs());
Z
zhhsplendid 已提交
214 215 216
  }
};

D
dengkaipeng 已提交
217 218 219 220 221 222
class SpectralNormOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
K
Kaipeng Deng 已提交
223 224 225 226 227 228 229
    OP_INOUT_CHECK(ctx->HasInput("Weight"), "Input", "Weight",
                   "SpectralNormGrad");
    OP_INOUT_CHECK(ctx->HasInput("U"), "Input", "U", "SpectralNormGrad");
    OP_INOUT_CHECK(ctx->HasInput("V"), "Input", "V", "SpectralNormGrad");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input",
                   "Out@GRAD", "SpectralNormGrad");

230 231 232
    PADDLE_ENFORCE_EQ(
        ctx->HasInput(framework::GradVarName("Out")), true,
        platform::errors::NotFound("Input(Out@GRAD) should not be null"));
D
dengkaipeng 已提交
233 234 235 236 237 238 239 240
    auto dim_x = ctx->GetInputDim("Weight");
    if (ctx->HasOutput(framework::GradVarName("Weight"))) {
      ctx->SetOutputDim(framework::GradVarName("Weight"), dim_x);
    }
  }

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
241 242
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Weight"), ctx.GetPlace());
D
dengkaipeng 已提交
243 244 245 246 247 248 249 250
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(spectral_norm, ops::SpectralNormOp, ops::SpectralNormOpMaker,
H
hong 已提交
251 252
                  ops::SpectralNormGradOpMaker<paddle::framework::OpDesc>,
                  ops::SpectralNormGradOpMaker<paddle::imperative::OpBase>);
D
dengkaipeng 已提交
253 254 255 256 257 258 259 260 261
REGISTER_OPERATOR(spectral_norm_grad, ops::SpectralNormOpGrad);
REGISTER_OP_CPU_KERNEL(
    spectral_norm,
    ops::SpectralNormKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SpectralNormKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
    spectral_norm_grad,
    ops::SpectralNormGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SpectralNormGradKernel<paddle::platform::CPUDeviceContext, double>);