cholesky_op.h 13.9 KB
Newer Older
G
Guo Sheng 已提交
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 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
/* 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. */

#pragma once

#include <numeric>
#include <vector>
#include "Eigen/Cholesky"
#include "Eigen/Core"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/blas.h"
#include "paddle/fluid/operators/transpose_op.h"
#include "paddle/fluid/platform/for_range.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

template <typename T>
class CholeskyCPUKernel : public framework::OpKernel<T> {
 public:
  // different with EigenMatrix in framework/eigen.h
  using EigenMatrix =
      Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
  using InputMatrixMap = Eigen::Map<const EigenMatrix>;
  using OutputMatrixMap = Eigen::Map<EigenMatrix>;
  void Compute(const framework::ExecutionContext& context) const override {
    const Tensor* x = context.Input<Tensor>("X");
    Tensor* out = context.Output<Tensor>("Out");

    bool upper = context.Attr<bool>("upper");
    auto& dims = x->dims();
    int batch_count = 1;
    for (int i = 0; i < dims.size() - 2; i++) {
      batch_count *= dims[i];
    }
    auto m = dims[dims.size() - 1];

    const auto* x_data = x->data<T>();
    auto* out_data = out->mutable_data<T>(context.GetPlace());
    // Cholesky decomposition for each matrix, maybe can use multi threads
    for (int i = 0; i < batch_count; i++) {
      auto input = InputMatrixMap(x_data + i * m * m, m, m);
      auto output = OutputMatrixMap(out_data + i * m * m, m, m);
      if (upper) {
        Eigen::LLT<
            Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,
            Eigen::UpLoType::Upper>
            llt_decomposition(input);
        PADDLE_ENFORCE_EQ(
            llt_decomposition.info(), Eigen::Success,
            platform::errors::InvalidArgument(
                "Cholesky decomposition was not successful. The input matrice "
                "might not be not be positive definite."));
        output = llt_decomposition.matrixU();
      } else {
        Eigen::LLT<
            Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,
            Eigen::UpLoType::Lower>
            llt_decomposition(input);
        PADDLE_ENFORCE_EQ(
            llt_decomposition.info(), Eigen::Success,
            platform::errors::InvalidArgument(
                "Cholesky decomposition was not successful. The input matrice "
                "might not be not be positive definite."));
        output = llt_decomposition.matrixL();
      }
    }
  }
};

/*! Use these functors to implement tril, triu, diagonal and other operators */
template <typename T>
struct EyeFunctor {
  EyeFunctor(const int m, const int n, T* output)
      : m_(m), n_(n), output_(output) {}

  HOSTDEVICE void operator()(size_t index) const {
    const int global_row = index / n_;
    const int col = index - global_row * n_;
    const int batch = global_row / m_;
    const int row = global_row - batch * m_;
    output_[index] = col == row ? static_cast<T>(1) : static_cast<T>(0);
  }

  const int m_, n_;
  T* output_;
};

template <typename T>
struct MatrixBandPartFunctor {
  /*! Set output as input value outside a central band and 0 inside that band.
   * That is: output[i, j, ..., m, n] = in_band(m, n) * input[i, j, ..., m, n]
   * where: in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)) && (num_upper
   * < 0 || (n-m) <= num_upper)
   */
  MatrixBandPartFunctor(const int m, const int n, const int num_lower_diags,
                        const int num_upper_diags, const T* input, T* output)
      : m_(m),
        n_(n),
        num_lower_diags_(num_lower_diags),
        num_upper_diags_(num_upper_diags),
        input_(input),
        output_(output) {}

  HOSTDEVICE void operator()(size_t index) const {
    const int col = index % n_;
    const int row = (index / n_) % m_;
    const int band_start = (num_lower_diags_ < 0 ? 0 : row - num_lower_diags_);
    const int band_end =
        (num_upper_diags_ < 0 ? n_ : row + num_upper_diags_ + 1);
    if (col < band_start || col >= band_end) {
      output_[index] = static_cast<T>(0);
    } else {
      output_[index] = input_[index];
    }
  }

  const int m_, n_, num_lower_diags_, num_upper_diags_;
  const T* input_;
  T* output_;
};

template <typename T>
struct MatrixSetDiagFunctor {
  /*! Overwrite specified diagonals of output by the values in diagonal.
   * diagonals can be a central band specified by num_diags and
   * upper_diag_index, where upper_diag_index=0 refers to the main diagonal,
   * positive value means superdiagonal and negative value means subdiagonal.
   * When it is a band, `diag` has a shape [i, j, ..., num_diags, max_diag_len]
   * and the num_diags diagonals has a up to down layout. Otherwise it has a
   * shape [i, j, ..., max_diag_len].
   */
  MatrixSetDiagFunctor(const int m, const int n, const int num_diags,
                       const int max_diag_len, const int upper_diag_index,
                       const T* diag, T* output)
      : m_(m),
        n_(n),
        num_diags_(num_diags),
        max_diag_len_(max_diag_len),
        upper_diag_index_(upper_diag_index),
        diag_(diag),
        output_(output) {}

  HOSTDEVICE void operator()(size_t index) const {
    const int batch_and_diag_index = index / max_diag_len_;
    const int index_in_the_diagonal =
        index - batch_and_diag_index * max_diag_len_;
    const int batch = batch_and_diag_index / num_diags_;
    const int diag_index_in_input = batch_and_diag_index - batch * num_diags_;
    // diag_index=0 refers to the main diagonal
    const int diag_index = upper_diag_index_ - diag_index_in_input;
    // shift down for subdiagonal if diag_index < 0
    const int y_index =
        index_in_the_diagonal + (0 > -diag_index ? 0 : -diag_index);
    // shift right for superdiagonal if diag_index > 0
    const int x_index =
        index_in_the_diagonal + (0 > diag_index ? 0 : diag_index);

    // Upper-bound checks for diagonals shorter than max_diag_len.
    // y_index and x_index are nonnegative by construction.
    if (y_index < m_ && x_index < n_) {
      const int out_index = batch * m_ * n_ + y_index * n_ + x_index;
      output_[out_index] = diag_[index];
    }
  }

  const int m_, n_, num_diags_, max_diag_len_, upper_diag_index_;
  const T* diag_;
  T* output_;
};

template <typename T>
struct MatrixDiagPartFunctor {
  /*! Similar to MatrixSetDiagFunctor but return the diagonals. diag_index=0
   * refers to the main diagonal, positive value means superdiagonal and
   * negative value means subdiagonal */
  MatrixDiagPartFunctor(const int m, const int n, const int num_diags,
                        const int max_diag_len, const int upper_diag_index,
                        const T padding, const T* input, T* output)
      : m_(m),
        n_(n),
        num_diags_(num_diags),
        max_diag_len_(max_diag_len),
        upper_diag_index_(upper_diag_index),
        input_(input),
        output_(output) {}

  HOSTDEVICE void operator()(size_t index) const {
    const int batch_and_mapped_diag_index = index / max_diag_len_;
    const int index_in_the_diagonal =
        index - batch_and_mapped_diag_index * max_diag_len_;
    const int batch = batch_and_mapped_diag_index / num_diags_;
    const int mapped_diag_index =
        batch_and_mapped_diag_index - batch * num_diags_;
    // diag_index=0 refers to the main diagonal
    const int diag_index = upper_diag_index_ - mapped_diag_index;
    // shift down for subdiagonal if diag_index < 0
    const int y_index =
        index_in_the_diagonal + (0 > -diag_index ? 0 : -diag_index);
    // shift right for superdiagonal if diag_index > 0
    const int x_index =
        index_in_the_diagonal + (0 > diag_index ? 0 : diag_index);
    if (y_index < m_ && x_index < n_) {
      output_[index] = input_[batch * m_ * n_ + y_index * m_ + x_index];
    } else {
      output_[index] = padding_;
    }
  }

  const int m_, n_, num_diags_, max_diag_len_, upper_diag_index_;
  const T padding_;
  const T* input_;
  T* output_;
};

template <typename T>
struct MatrixBandPartScaleEndFunctor {
  /*! Compared with MatrixBandPartFunctor, it scale up values at the end of
   * band. It can be used to fuse the following operations, which actually
   * output triangular with diagonal scaled up:
   * 1. dig = matrix_diag_part(middle)
   * 2. middle = matrix_set_diag(middle, diag * scalar)
   * 3. middle = matrix_band_part(middle, -1, 0)
   */
  MatrixBandPartScaleEndFunctor(const int m, const int n,
                                const int num_lower_diags,
                                const int num_upper_diags, const T scale,
                                const T* input, T* output)
      : m_(m),
        n_(n),
        num_lower_diags_(num_lower_diags),
        num_upper_diags_(num_upper_diags),
        scale_(scale),
        input_(input),
        output_(output) {}

  HOSTDEVICE void operator()(size_t index) const {
    const int col = index % n_;
    const int row = (index / n_) % m_;
    const int band_start = (num_lower_diags_ < 0 ? 0 : row - num_lower_diags_);
    const int band_end =
        (num_upper_diags_ < 0 ? n_ : row + num_upper_diags_ + 1);
    if (col < band_start || col >= band_end) {
      output_[index] = 0;
    } else if (col == band_end - 1) {
      output_[index] = scale_ * input_[index];
    } else {
      output_[index] = input_[index];
    }
  }

  const int m_, n_, num_lower_diags_, num_upper_diags_;
  const T scale_;
  const T* input_;
  T* output_;
};

template <typename T>
struct AddtoScaleFunctor {
  AddtoScaleFunctor(const T scale, const T* input, T* output)
      : scale_(scale), input_(input), output_(output) {}
  HOSTDEVICE void operator()(size_t index) const {
    output_[index] += input_[index];
    output_[index] *= scale_;
  }
  const T scale_;
  const T* input_;
  T* output_;
};

template <typename DeviceContext, typename T>
class CholeskyGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* out = context.Input<Tensor>("Out");
    auto* out_grad = context.Input<Tensor>(framework::GradVarName("Out"));
    auto* x_grad = context.Output<Tensor>(framework::GradVarName("X"));
    auto* x_grad_data = x_grad->mutable_data<T>(context.GetPlace());

    bool upper = context.Attr<bool>("upper");
    auto& dims = out->dims();
    int batch_count = 1;
    for (int i = 0; i < dims.size() - 2; i++) {
      batch_count *= dims[i];
    }
    auto m = dims[dims.size() - 1];
    int tensor_size = batch_count * m * m;

    auto& dev_ctx = context.template device_context<DeviceContext>();

    std::vector<int> axis(dims.size() - 2);
    std::iota(axis.begin(), axis.end(), 0);
    axis.insert(axis.end(), {dims.size() - 1, dims.size() - 2});
    Tensor l, l_grad;
    if (upper) {
      l.mutable_data<T>(dims, context.GetPlace());
      l_grad.mutable_data<T>(dims, context.GetPlace());
      TransCompute<DeviceContext, T>(dims.size(), dev_ctx, *out, &l, axis);
      TransCompute<DeviceContext, T>(dims.size(), dev_ctx, *out_grad, &l_grad,
                                     axis);
    } else {
      l = *out;
      l_grad = *out_grad;
    }
    auto* l_data = l.data<T>();

    /*! refer to Iain Murray (2016); arXiv 1602.07527 */
    /*! phi = matmul(L.transpose(-1, -2), grad) */
    Tensor middle;
    auto* middle_data = middle.mutable_data<T>(dims, context.GetPlace());
    auto trans_desc = math::CreateMatrixDescriptor(dims, 0, true);
    auto no_trans_desc = math::CreateMatrixDescriptor(dims, 0, false);
    auto blas = math::GetBlas<DeviceContext, T>(context);
    blas.MatMul(l, trans_desc, l_grad, no_trans_desc, T(1), &middle, T(0));

    /*! phi.tril_().diagonal(0, -2, -1).mul_(0.5) */
    platform::ForRange<DeviceContext> for_range(dev_ctx, tensor_size);
    MatrixBandPartScaleEndFunctor<T> matrix_band_part_scale_end_functor(
        m, m, /* num_lower_diags */ m, /* num_upper_diags */ 0,
        /* scale */ 0.5, middle_data, middle_data);
    for_range(matrix_band_part_scale_end_functor);

    // Compute inverse by solving the triangular linear system AX = B, where B
    // is the identity matrix. The matrix X would be overwritten on B
    Tensor identity;
    auto* identity_data = identity.mutable_data<T>(dims, context.GetPlace());
    EyeFunctor<T> eye_functor(m, m, identity_data);
    for_range(eye_functor);
    // TODO(guosheng): use trsmBatched for GPU
    for (int i = 0; i < batch_count; i++) {
      blas.TRSM(/*side*/ CblasLeft, /*uplo*/ CblasLower,
                /*trans*/ CblasNoTrans, /*diag*/ CblasNonUnit, /*m*/ m, /*n*/ m,
                /*alpha*/ T(1), l_data + i * m * m, /*lda*/ m,
                identity_data + i * m * m, /*ldb*/ m);
    }
    Tensor& l_inverse = identity;

    /*! x_grad = matmul(matmul(L_inverse.transpose(-1, -2), phi), L_inverse) */
    Tensor middle1;
    middle1.mutable_data<T>(dims, context.GetPlace());
    blas.MatMul(l_inverse, trans_desc, middle, no_trans_desc, T(1), &middle1,
                T(0));
    blas.MatMul(middle1, no_trans_desc, l_inverse, no_trans_desc, T(1), x_grad,
                T(0));

    /*! x_grad.add(x_grad.transpose(-1, -2)).mul_(0.5) */
    Tensor x_grad_trans;
    auto* x_grad_trans_data =
        x_grad_trans.mutable_data<T>(dims, context.GetPlace());
    TransCompute<DeviceContext, T>(dims.size(), dev_ctx, *x_grad, &x_grad_trans,
                                   axis);
    AddtoScaleFunctor<T> addto_scale_functor(0.5, x_grad_trans_data,
                                             x_grad_data);
    for_range(addto_scale_functor);
  }
};

}  // namespace operators
}  // namespace paddle