svd_kernel.cu 10.4 KB
Newer Older
X
xiongkun 已提交
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
// Copyright (c) 2022 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.

#ifndef PADDLE_WITH_HIP
// HIP not support cusolver

#include "paddle/phi/kernels/svd_kernel.h"

#include "paddle/fluid/memory/memory.h"
#include "paddle/phi/backends/dynload/cusolver.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/kernels/empty_kernel.h"
#include "paddle/phi/kernels/funcs/complex_functors.h"
#include "paddle/phi/kernels/transpose_kernel.h"

namespace phi {

template <class T>
static void GesvdjBatched(const phi::GPUContext& dev_ctx,
                          int batchSize,
                          int m,
                          int n,
                          int k,
                          T* A,
                          T* U,
                          T* V,
                          T* S,
                          int* info,
                          int thin_UV = 1);

template <>
void GesvdjBatched<float>(const phi::GPUContext& dev_ctx,
                          int batchSize,
                          int m,
                          int n,
                          int k,
                          float* A,
                          float* U,
                          float* V,
                          float* S,
                          int* info,
                          int thin_UV) {
  /* compute singular vectors */
  const cusolverEigMode_t jobz =
      CUSOLVER_EIG_MODE_VECTOR; /* compute singular vectors */
  gesvdjInfo_t gesvdj_params = NULL;
  int lda = m;
  int ldu = m;
  int ldt = n;
  int lwork = 0;
  auto handle = dev_ctx.cusolver_dn_handle();
  PADDLE_ENFORCE_GPU_SUCCESS(
      phi::dynload::cusolverDnCreateGesvdjInfo(&gesvdj_params));
  PADDLE_ENFORCE_GPU_SUCCESS(
      phi::dynload::cusolverDnSgesvdj_bufferSize(handle,
                                                 jobz,
                                                 thin_UV,
                                                 m,
                                                 n,
                                                 A,
                                                 lda,
                                                 S,
                                                 U,
                                                 ldu,
                                                 V,
                                                 ldt,
                                                 &lwork,
                                                 gesvdj_params));
  auto workspace = paddle::memory::Alloc(dev_ctx, lwork * sizeof(float));
  float* workspace_ptr = reinterpret_cast<float*>(workspace->ptr());
  int stride_A = lda * n;
  int stride_U = ldu * (thin_UV ? k : m);
  int stride_V = ldt * (thin_UV ? k : n);
  for (int i = 0; i < batchSize; ++i) {
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cusolverDnSgesvdj(handle,
                                                               jobz,
                                                               thin_UV,
                                                               m,
                                                               n,
                                                               A + stride_A * i,
                                                               lda,
                                                               S + k * i,
                                                               U + stride_U * i,
                                                               ldu,
                                                               V + stride_V * i,
                                                               ldt,
                                                               workspace_ptr,
                                                               lwork,
                                                               info,
                                                               gesvdj_params));
    // check the error info
    int error_info;
    paddle::memory::Copy(phi::CPUPlace(),
                         &error_info,
                         dev_ctx.GetPlace(),
                         info,
                         sizeof(int),
                         dev_ctx.stream());
    PADDLE_ENFORCE_EQ(
        error_info,
        0,
        phi::errors::PreconditionNotMet(
            "For batch [%d]: CUSolver SVD is not zero. [%d]", i, error_info));
  }
  PADDLE_ENFORCE_GPU_SUCCESS(
      phi::dynload::cusolverDnDestroyGesvdjInfo(gesvdj_params));
}

template <>
void GesvdjBatched<double>(const phi::GPUContext& dev_ctx,
                           int batchSize,
                           int m,
                           int n,
                           int k,
                           double* A,
                           double* U,
                           double* V,
                           double* S,
                           int* info,
                           int thin_UV) {
  /* compute singular vectors */
  const cusolverEigMode_t jobz =
      CUSOLVER_EIG_MODE_VECTOR; /* compute singular vectors */
  gesvdjInfo_t gesvdj_params = NULL;
  int lda = m;
  int ldu = m;
  int ldt = n;
  int lwork = 0;
  auto handle = dev_ctx.cusolver_dn_handle();
  PADDLE_ENFORCE_GPU_SUCCESS(
      phi::dynload::cusolverDnCreateGesvdjInfo(&gesvdj_params));
  PADDLE_ENFORCE_GPU_SUCCESS(
      phi::dynload::cusolverDnDgesvdj_bufferSize(handle,
                                                 jobz,
                                                 thin_UV,
                                                 m,
                                                 n,
                                                 A,
                                                 lda,
                                                 S,
                                                 U,
                                                 ldu,
                                                 V,
                                                 ldt,
                                                 &lwork,
                                                 gesvdj_params));
  auto workspace = paddle::memory::Alloc(dev_ctx, lwork * sizeof(double));
  double* workspace_ptr = reinterpret_cast<double*>(workspace->ptr());
  int stride_A = lda * n;
  int stride_U = ldu * (thin_UV ? k : m);
  int stride_V = ldt * (thin_UV ? k : n);
  for (int i = 0; i < batchSize; ++i) {
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cusolverDnDgesvdj(handle,
                                                               jobz,
                                                               thin_UV,
                                                               m,
                                                               n,
                                                               A + stride_A * i,
                                                               lda,
                                                               S + k * i,
                                                               U + stride_U * i,
                                                               ldu,
                                                               V + stride_V * i,
                                                               ldt,
                                                               workspace_ptr,
                                                               lwork,
                                                               info,
                                                               gesvdj_params));
    // check the error info
    int error_info;
    paddle::memory::Copy(phi::CPUPlace(),
                         &error_info,
                         dev_ctx.GetPlace(),
                         info,
                         sizeof(int),
                         dev_ctx.stream());
    PADDLE_ENFORCE_EQ(
        error_info,
        0,
        phi::errors::PreconditionNotMet(
            "For batch [%d]: CUSolver SVD is not zero. [%d]", i, error_info));
  }
  PADDLE_ENFORCE_GPU_SUCCESS(
      phi::dynload::cusolverDnDestroyGesvdjInfo(gesvdj_params));
}

template <typename T, typename Context>
void SvdKernel(const Context& dev_ctx,
               const DenseTensor& X,
               bool full_matrices,
               DenseTensor* U,
               DenseTensor* S,
               DenseTensor* VH) {
  auto& dims = X.dims();
  int batch_count = 1;
  for (int i = 0; i < dims.size() - 2; i++) {
    batch_count *= dims[i];
  }
  int rank = dims.size();
  int m = dims[rank - 2];
  int n = dims[rank - 1];

  auto* u_data = dev_ctx.template Alloc<phi::dtype::Real<T>>(U);
  auto* vh_data = dev_ctx.template Alloc<phi::dtype::Real<T>>(VH);
  auto* s_data = dev_ctx.template Alloc<phi::dtype::Real<T>>(S);
  // NOTE:(@xiongkun03)
  // matrices are assumed to be stored in column-major order in cusolver
  // then view A as n x m and do A^T SVD, we can avoid transpose
  // Must Copy X once, because the gesvdj will change the origin input matrix
  DenseTensor x_tmp;
  Copy(dev_ctx, X, dev_ctx.GetPlace(), false, &x_tmp);
  auto info = Empty<int, Context>(dev_ctx, {batch_count});
  int* info_ptr = reinterpret_cast<int*>(info.data());

  GesvdjBatched<T>(dev_ctx,
                   batch_count,
                   n,
                   m,
                   std::min(m, n),
                   dev_ctx.template Alloc<T>(&x_tmp),
                   vh_data,
                   u_data,
                   s_data,
                   info_ptr,
                   !full_matrices);

  auto UT_dim = U->dims();
  std::swap(UT_dim[rank - 1], UT_dim[rank - 2]);  // Get the dim of UT_dim
  U->Resize(UT_dim);                              // U is entirely UT
  auto tmp_U = TransposeLast2Dim<T>(dev_ctx, *U);
  U->ShareDataWith(tmp_U);  // U becomse UT, aka VT;
}
}  // namespace phi

PD_REGISTER_KERNEL(svd,  // cuda_only
                   GPU,
                   ALL_LAYOUT,
                   phi::SvdKernel,
                   float,
                   double) {}

#endif  // not PADDLE_WITH_HIP