spectral_norm_op.h 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. */

#pragma once
D
dengkaipeng 已提交
13
#include <vector>
D
dengkaipeng 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/blas.h"
#include "paddle/fluid/operators/math/math_function.h"

namespace paddle {
namespace operators {

template <typename T, size_t D, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenTensor = framework::EigenTensor<T, D, MajorType, IndexType>;
using Tensor = framework::Tensor;

using Array1 = Eigen::DSizes<int64_t, 1>;
using Array2 = Eigen::DSizes<int64_t, 2>;
using IndexPair = Eigen::IndexPair<int>;

D
dengkaipeng 已提交
31 32 33 34 35
template <typename DeviceContext, typename T>
static inline void TransCompute(const int rank, const Tensor& in, Tensor* out,
                                const std::vector<int>& perm,
                                const DeviceContext& dev_ctx) {
  if (rank <= 1 || rank > 5) {
36 37 38
    PADDLE_THROW(paddle::platform::errors::Fatal(
        "Weight rank of SpectralNorm should be in range [2, 5], but got %d.",
        rank));
D
dengkaipeng 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
  }

  switch (rank) {
    case 2:
      math::Transpose<DeviceContext, T, 2> trans2;
      trans2(dev_ctx, in, out, perm);
      break;
    case 3:
      math::Transpose<DeviceContext, T, 3> trans3;
      trans3(dev_ctx, in, out, perm);
      break;
    case 4:
      math::Transpose<DeviceContext, T, 4> trans4;
      trans4(dev_ctx, in, out, perm);
      break;
    case 5:
      math::Transpose<DeviceContext, T, 5> trans5;
      trans5(dev_ctx, in, out, perm);
      break;
    default:
      break;
D
dengkaipeng 已提交
60 61 62 63
  }
}

template <typename DeviceContext, typename T>
M
miraiwk 已提交
64 65
static inline void UpdateUandV(
    Tensor* u, Tensor* v, Tensor* weight, const int power_iters,
D
dengkaipeng 已提交
66
    const float eps, const framework::ExecutionContext& ctx) {
M
miraiwk 已提交
67
  if (power_iters <= 0) return;
D
dengkaipeng 已提交
68
  auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
69 70 71
  auto blas = math::GetBlas<DeviceContext, T>(ctx);
  auto u_t = EigenTensor<T, 2>::From(*u);
  auto v_t = EigenTensor<T, 2>::From(*v);
D
dengkaipeng 已提交
72 73 74 75 76

  const int h = weight->dims()[0];
  const int w = weight->dims()[1];

  for (int i = 0; i < power_iters; i++) {
D
dengkaipeng 已提交
77
    // V = W^T * U / ||W^T * U||_2
78
    blas.MatMul(*weight, true, *u, false, T(1), v, T(0));
D
dengkaipeng 已提交
79 80 81 82
    auto v_t_norm =
        v_t.square().sum().sqrt().eval().reshape(Array1(1)).broadcast(
            Array1(w));
    v_t.device(place) = v_t / (v_t_norm + v_t_norm.constant(eps));
D
dengkaipeng 已提交
83
    // U = W^T * V / ||W^T * V||_2
84
    blas.MatMul(*weight, false, *v, false, T(1), u, T(0));
D
dengkaipeng 已提交
85 86 87 88 89
    auto u_t_norm =
        u_t.square().sum().sqrt().eval().reshape(Array1(1)).broadcast(
            Array1(h));
    u_t.device(place) = u_t / (u_t_norm + u_t_norm.constant(eps));
  }
M
miraiwk 已提交
90 91 92 93 94 95
}

// CalcMatrixSigmaAndNormWeight will not update u and v
template <typename DeviceContext, typename T>
static inline void CalcMatrixSigmaAndNormWeight(
    Tensor* sigma, const Tensor* u, const Tensor* v,
M
miraiwk 已提交
96
    Tensor* weight, const framework::ExecutionContext& ctx) {
M
miraiwk 已提交
97 98 99 100 101 102 103 104 105
  auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
  auto blas = math::GetBlas<DeviceContext, T>(ctx);
  auto sigma_t = EigenTensor<T, 2>::From(*sigma);
  auto weight_t = EigenTensor<T, 2>::From(*weight);
  auto u_t = EigenTensor<T, 2>::From(*u);

  const int h = weight->dims()[0];
  const int w = weight->dims()[1];

106 107 108 109 110
  Tensor weight_v;
  weight_v.mutable_data<T>({h, 1}, ctx.GetPlace());
  blas.MatMul(*weight, false, *v, false, T(1), &weight_v, T(0));
  auto weight_v_t = EigenTensor<T, 2>::From(weight_v);
  sigma_t.device(place) = (u_t * weight_v_t)
D
dengkaipeng 已提交
111 112 113 114 115 116 117 118 119 120 121
                              .sum()
                              .eval()
                              .reshape(Array2(1, 1))
                              .broadcast(Array2(h, w));
  weight_t.device(place) = weight_t / sigma_t;
}

template <typename DeviceContext, typename T>
class SpectralNormKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
D
dengkaipeng 已提交
122
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
D
dengkaipeng 已提交
123 124 125 126
    auto weight = ctx.Input<Tensor>("Weight");
    auto u = ctx.Input<Tensor>("U");
    auto v = ctx.Input<Tensor>("V");
    auto out = ctx.Output<Tensor>("Out");
M
miraiwk 已提交
127 128
    auto u_out = ctx.Output<Tensor>("UOut");
    auto v_out = ctx.Output<Tensor>("VOut");
D
dengkaipeng 已提交
129 130 131 132 133

    int dim = ctx.Attr<int>("dim");
    int power_iters = ctx.Attr<int>("power_iters");
    float eps = ctx.Attr<float>("eps");

D
dengkaipeng 已提交
134 135 136
    const int h = u->dims()[0];
    const int w = v->dims()[0];

D
dengkaipeng 已提交
137
    Tensor weight_mat;
D
dengkaipeng 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    auto dims = weight->dims();
    const int rank = dims.size();
    std::vector<int> real_dims;
    if (dim != 0) {
      std::vector<int> perm;
      perm.push_back(dim);
      real_dims.push_back(dims[dim]);
      for (int i = 0; i < rank; i++) {
        if (i != dim) {
          perm.push_back(i);
          real_dims.push_back(dims[i]);
        }
      }
      weight_mat.mutable_data<T>(framework::make_ddim(real_dims),
                                 ctx.GetPlace());
      TransCompute<DeviceContext, T>(rank, *weight, &weight_mat, perm, dev_ctx);
    } else {
      for (int i = 0; i < rank; i++) {
        real_dims.push_back(i);
      }
      TensorCopySync(*weight, ctx.GetPlace(), &weight_mat);
    }
160
    weight_mat = weight_mat.Resize({h, w});
D
dengkaipeng 已提交
161 162

    Tensor sigma;
163
    sigma.mutable_data<T>(weight_mat.dims(), ctx.GetPlace());
M
miraiwk 已提交
164 165 166 167 168
    TensorCopySync(*u, ctx.GetPlace(), u_out);
    TensorCopySync(*v, ctx.GetPlace(), v_out);
    UpdateUandV<DeviceContext, T>(
        &(u_out->Resize({h, 1})), &(v_out->Resize({w, 1})), &weight_mat,
        power_iters, eps, ctx);
D
dengkaipeng 已提交
169
    CalcMatrixSigmaAndNormWeight<DeviceContext, T>(
M
miraiwk 已提交
170
        &sigma, &(u_out->Resize({h, 1})), &(v_out->Resize({w, 1})), &weight_mat,
M
miraiwk 已提交
171
        ctx);
D
dengkaipeng 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

    if (dim != 0) {
      std::vector<int> perm;
      for (int i = 0; i < rank; i++) {
        if (i < dim) {
          perm.push_back(i + 1);
        } else if (i == dim) {
          perm.push_back(0);
        } else {
          perm.push_back(i);
        }
      }
      out->mutable_data<T>(dims, ctx.GetPlace());
      TransCompute<DeviceContext, T>(
          rank, weight_mat.Resize(framework::make_ddim(real_dims)), out, perm,
          dev_ctx);
    } else {
      TensorCopySync(weight_mat.Resize(dims), ctx.GetPlace(), out);
    }
D
dengkaipeng 已提交
191 192 193 194 195 196
  }
};

template <typename DeviceContext, typename T>
class SpectralNormGradKernel : public framework::OpKernel<T> {
 public:
197 198
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
D
dengkaipeng 已提交
199
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
200 201
    auto blas = math::GetBlas<DeviceContext, T>(ctx);
    auto weight = ctx.Input<Tensor>("Weight");
M
miraiwk 已提交
202 203
    auto u_out = ctx.Input<Tensor>("UOut");
    auto v_out = ctx.Input<Tensor>("VOut");
204 205 206 207 208
    auto out_grad = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto weight_grad = ctx.Output<Tensor>(framework::GradVarName("Weight"));

    int dim = ctx.Attr<int>("dim");

M
miraiwk 已提交
209 210 211 212 213 214
    const int h = u_out->dims()[0];
    const int w = v_out->dims()[0];

    Tensor u_mat, v_mat;
    TensorCopySync(*u_out, ctx.GetPlace(), &u_mat);
    TensorCopySync(*v_out, ctx.GetPlace(), &v_mat);
D
dengkaipeng 已提交
215

216
    Tensor weight_mat, out_grad_mat;
D
dengkaipeng 已提交
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
    auto dims = weight->dims();
    const int rank = dims.size();
    std::vector<int> real_dims;
    if (dim != 0) {
      std::vector<int> perm;
      perm.push_back(dim);
      real_dims.push_back(dims[dim]);
      for (int i = 0; i < rank; i++) {
        if (i != dim) {
          perm.push_back(i);
          real_dims.push_back(dims[i]);
        }
      }
      weight_mat.mutable_data<T>(framework::make_ddim(real_dims),
                                 ctx.GetPlace());
      out_grad_mat.mutable_data<T>(framework::make_ddim(real_dims),
                                   ctx.GetPlace());
      TransCompute<DeviceContext, T>(rank, *weight, &weight_mat, perm, dev_ctx);
      TransCompute<DeviceContext, T>(rank, *out_grad, &out_grad_mat, perm,
                                     dev_ctx);
    } else {
      for (int i = 0; i < rank; i++) {
        real_dims.push_back(i);
      }
      TensorCopySync(*weight, ctx.GetPlace(), &weight_mat);
      TensorCopySync(*out_grad, ctx.GetPlace(), &out_grad_mat);
    }
244 245 246 247 248
    weight_mat = weight_mat.Resize({h, w});
    out_grad_mat = out_grad_mat.Resize({h, w});

    Tensor sigma;
    sigma.mutable_data<T>(weight_mat.dims(), ctx.GetPlace());
M
miraiwk 已提交
249

250
    CalcMatrixSigmaAndNormWeight<DeviceContext, T>(
M
miraiwk 已提交
251
        &sigma, &(u_mat.Resize({h, 1})), &(v_mat.Resize({w, 1})), &weight_mat,
M
miraiwk 已提交
252
        ctx);
253 254 255

    Tensor uv;
    uv.mutable_data<T>({h, w}, ctx.GetPlace());
M
miraiwk 已提交
256
    blas.MatMul(u_mat.Resize({h, 1}), false, v_mat.Resize({w, 1}), false, T(1), &uv,
257 258
                T(0));

D
dengkaipeng 已提交
259
    Tensor weight_grad_mat;
260 261 262 263 264 265 266 267 268
    weight_grad_mat.mutable_data<T>({h, w}, ctx.GetPlace());
    auto weight_grad_mat_t = EigenTensor<T, 2>::From(weight_grad_mat);
    auto weight_mat_t = EigenTensor<T, 2>::From(weight_mat);
    auto out_grad_mat_t = EigenTensor<T, 2>::From(out_grad_mat);
    auto sigma_t = EigenTensor<T, 2>::From(sigma);
    auto uv_t = EigenTensor<T, 2>::From(uv);
    weight_mat_t.device(place) =
        weight_mat_t.sum().eval().reshape(Array2(1, 1)).broadcast(Array2(h, w));
    weight_grad_mat_t.device(place) =
D
dengkaipeng 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        out_grad_mat_t * (out_grad_mat_t.constant(1.0) - uv_t * weight_mat_t) /
        sigma_t;

    if (dim != 0) {
      std::vector<int> perm;
      for (int i = 0; i < rank; i++) {
        if (i < dim) {
          perm.push_back(i + 1);
        } else if (i == dim) {
          perm.push_back(0);
        } else {
          perm.push_back(i);
        }
      }
      weight_grad->mutable_data<T>(dims, ctx.GetPlace());
      TransCompute<DeviceContext, T>(
          rank, weight_grad_mat.Resize(framework::make_ddim(real_dims)),
          weight_grad, perm, dev_ctx);
    } else {
      TensorCopySync(weight_grad_mat.Resize(dims), ctx.GetPlace(), weight_grad);
    }
290
  }
D
dengkaipeng 已提交
291 292 293 294
};

}  // namespace operators
}  // namespace paddle