aclnnSvd

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Supported
  • Atlas A2 products: Supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: Computes the singular value decomposition of one or more matrices.

    When the input tensor has more than two dimensions, the high-dimension tensor is treated as a batch of matrices. For an input tensor with shape (..., M, N), the dimensions (...) before the second-to-last dimension are batch dimensions, and singular value decomposition is performed independently for each (M, N) matrix.

  • Formula:

input=U×diag(sigma)×VT\mathbf{input} = \mathbf{U} \times \mathrm{diag}(\boldsymbol{sigma}) \times \mathbf{V}^T

Function Prototype

Each operator uses a two-phase API. First call the "aclnnSvdGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process. Then call the "aclnnSvd" API to execute the computation.

aclnnStatus aclnnSvdGetWorkspaceSize(
    const aclTensor *input,
    const bool       fullMatrices,
    const bool       computeUV,
    aclTensor       *sigma,
    aclTensor       *u,
    aclTensor       *v,
    uint64_t        *workspaceSize,
    aclOpExecutor   **executor)
aclnnStatus aclnnSvd(
    void            *workspace,
    uint64_t         workspaceSize,
    aclOpExecutor   *executor,
    aclrtStream      stream)

aclnnSvdGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension Non-contiguous Tensor
    Input Input Tensor on which singular value decomposition is performed, corresponding to input in the corresponding formula. Empty tensors are not supported.
    The shape must have at least 2 dimensions.
    FLOAT, DOUBLE, COMPLEX64, COMPLEX128 ND 2-8 √
    fullMatrices Input Input parameter indicating whether to compute the full output tensors u and v. Controls whether to compute the full SVD decomposition.
    If true, the full u and v are output.
    If false, only the economy version is computed to save memory and computing resources.
    If the shape of input is [..., M, N], K=min(M, N).
    If true, the output shapes are:
    u: [..., M, M], sigma: [..., K], v: [..., N, N].
    If false, the output shapes are:
    u: [..., M, K], sigma: [..., K], v: [..., N, K].
    BOOL - - -
    computeUV Input Input parameter. Specifies whether to compute the output tensors u and v. If true, output tensors sigma, u, and v are all computed.
    If false, only sigma is computed, and the shapes of u and v are not validated.
    BOOL - - -
    sigma Output Output tensor, which is sigma in the corresponding formula. The shape must be derived based on the shape of input and the fullMatrices parameter.
    The data type must be consistent with that of input.
    FLOAT, DOUBLE, COMPLEX64, COMPLEX128 ND 2-7 √
    u Output Output tensor, U in the corresponding formula. The shape must be derived from the shape of input and the fullMatrices parameter.
    The data type must be the same as that of input.
    FLOAT, DOUBLE, COMPLEX64, COMPLEX128 ND 2-8 √
    v Output Output tensor, corresponding to V in the formula. The shape must be derived from the shape of input and the fullMatrices parameter.
    The data type must be the same as that of input.
    FLOAT, DOUBLE, COMPLEX64, COMPLEX128 ND 2-8 √
    workspaceSize Output Returns the workspace size to be requested on the Device. - - - - -
    executor Output Returns the op executor, containing the operator computation flow. - - - - -
  • Return value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Values Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 input, sigma, u, or v contains a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of input, sigma, u, and v are not within the supported range.
    The data type of input is inconsistent with those of sigma, u, and v.
    The dimension of input is less than 2 or greater than 8.
    The shapes of sigma, u, and v are inconsistent with the shapes derived from input.

aclnnSvd

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Size of the workspace allocated on the device, obtained by calling the first-phase API aclnnSvdGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Specifies the Stream for executing tasks.
  • Return value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • deterministic computation:
    • aclnnSvd defaults to a deterministic implementation.

Example

The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_svd.h"

#define CHECK_RET(cond, return_expr) \
  do {                               \
    if (!(cond)) {                   \
      return_expr;                   \
    }                                \
  } while (0)

#define LOG_PRINT(message, ...)     \
  do {                              \
    printf(message, ##__VA_ARGS__); \
  } while (0)

int64_t GetShapeSize(const std::vector<int64_t>& shape) {
  int64_t shapeSize = 1;
  for (auto i : shape) {
    shapeSize *= i;
  }
  return shapeSize;
}

struct SVDTensors {
  void* inputDeviceAddr = nullptr;
  void* uDeviceAddr = nullptr;
  void* sigmaDeviceAddr = nullptr;
  void* vDeviceAddr = nullptr;
  aclTensor* input = nullptr;
  aclTensor* u = nullptr;
  aclTensor* sigma = nullptr;
  aclTensor* v = nullptr;
  std::vector<int64_t> uShape = {2, 2};
  std::vector<int64_t> sigmaShape = {2};
  std::vector<int64_t> vShape = {3, 3};
};

struct SVDWorkspace {
  void* addr = nullptr;
  uint64_t size = 0;
};


int Init(int32_t deviceId, aclrtStream* stream) {
  // Boilerplate for resource initialization.
  auto ret = aclInit(nullptr);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSetDevice(deviceId);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
  return 0;
}

template <typename T>
int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                    aclDataType dataType, aclTensor** tensor) {
  auto size = GetShapeSize(shape) * sizeof(T);
  // Call aclrtMalloc to allocate device memory.
  auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
  // Call aclrtMemcpy to copy host data to device memory.
  ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

  // Calculate the strides of the contiguous tensor.
  std::vector<int64_t> strides(shape.size(), 1);
  for (int64_t i = shape.size() - 2; i >= 0; i--) {
    strides[i] = shape[i + 1] * strides[i + 1];
  }

  // Call aclCreateTensor to create an aclTensor.
  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}



int SetupAndExecuteSVD(aclrtStream stream, SVDTensors& tensors, SVDWorkspace& workspace) {
  auto ret = 0;

  //Construct inputs and outputs. Customize the construction based on the API.
  std::vector<int64_t> inputShape = {2, 3};
  std::vector<float> inputHostData = {1, 2, 3, 4, 5, 6};
  std::vector<float> uHostData = {0, 0, 0, 0};
  std::vector<float> sigmaHostData = {0, 0};
  std::vector<float> vHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0};
  bool fullMatrices = true;
  bool computeUV = true;


  // Create input aclTensor.
  ret = CreateAclTensor(inputHostData, inputShape, &tensors.inputDeviceAddr, aclDataType::ACL_FLOAT, &tensors.input);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create u aclTensor.
  ret = CreateAclTensor(uHostData, tensors.uShape, &tensors.uDeviceAddr, aclDataType::ACL_FLOAT, &tensors.u);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create sigma aclTensor.
  ret = CreateAclTensor(sigmaHostData, tensors.sigmaShape, &tensors.sigmaDeviceAddr, aclDataType::ACL_FLOAT, &tensors.sigma);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create v aclTensor.
  ret = CreateAclTensor(vHostData, tensors.vShape, &tensors.vDeviceAddr, aclDataType::ACL_FLOAT, &tensors.v);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Call the CANN operator library API. Change it to the specific API name.
  aclOpExecutor* executor;
  // Call the aclnnSvdGetWorkspaceSize first-phase API.
  ret = aclnnSvdGetWorkspaceSize(tensors.input, fullMatrices, computeUV, tensors.sigma, tensors.u, tensors.v,
                                 &workspace.size, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSvdGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

  // Allocate device memory based on the workspaceSize computed by the first-phase API.
  workspace.addr = nullptr;
  if (workspace.size > 0) {
    ret = aclrtMalloc(&workspace.addr, workspace.size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
  }

  // Call the aclnnSvd second-phase API.
  ret = aclnnSvd(workspace.addr, workspace.size, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSvd failed. ERROR: %d\n", ret); return ret);

  // Synchronize and wait for the task to complete.
  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

  return 0;
}

int ProcessAndCleanupSVD(SVDTensors& tensors, SVDWorkspace& workspace) {
  auto ret = 0;

  // Obtain the output values and copy the results from device memory to host memory. Modify based on the specific API definition.
  auto uSize = GetShapeSize(tensors.uShape);
  std::vector<float> uData(uSize, 0);
  ret = aclrtMemcpy(uData.data(), uData.size() * sizeof(uData[0]), tensors.uDeviceAddr,
                    uSize * sizeof(uData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy outTensor U from device to host failed. ERROR: %d\n", ret); return ret);

  for (int64_t i = 0; i < uSize; i++) {
    LOG_PRINT("u[%ld] is: %f\n", i, uData[i]);
  }

  auto sigmaSize = GetShapeSize(tensors.sigmaShape);
  std::vector<float> sigmaData(sigmaSize, 0);
  ret = aclrtMemcpy(sigmaData.data(), sigmaData.size() * sizeof(sigmaData[0]), tensors.sigmaDeviceAddr,
                    sigmaSize * sizeof(sigmaData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy outTensor sigma from device to host failed. ERROR: %d\n", ret); return ret);

  for (int64_t i = 0; i < sigmaSize; i++) {
    LOG_PRINT("sigma[%ld] is: %f\n", i, sigmaData[i]);
  }

  auto vSize = GetShapeSize(tensors.vShape);
  std::vector<float> vData(vSize, 0);
  ret = aclrtMemcpy(vData.data(), vData.size() * sizeof(vData[0]), tensors.vDeviceAddr,
                    vSize * sizeof(vData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy outTensor V from device to host failed. ERROR: %d\n", ret); return ret);

  for (int64_t i = 0; i < vSize; i++) {
    LOG_PRINT("v[%ld] is: %f\n", i, vData[i]);
  }

  // Release the aclTensor and aclScalar. Modify based on the specific API definition.
  aclDestroyTensor(tensors.input);
  aclDestroyTensor(tensors.u);
  aclDestroyTensor(tensors.sigma);
  aclDestroyTensor(tensors.v);

  // Release device resources.
  aclrtFree(tensors.inputDeviceAddr);
  aclrtFree(tensors.uDeviceAddr);
  aclrtFree(tensors.sigmaDeviceAddr);
  aclrtFree(tensors.vDeviceAddr);
  if (workspace.size > 0) {
    aclrtFree(workspace.addr);
  }

  return 0;
}

int ExecuteSVDOperator(aclrtStream stream) {
  SVDTensors tensors;
  SVDWorkspace workspace;

  auto ret = SetupAndExecuteSVD(stream, tensors, workspace);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  ret = ProcessAndCleanupSVD(tensors, workspace);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  return 0;
}


int main() {
  // Device/stream initialization. For details, see the acl API manual.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // Perform the GtScalar operation.
  ret = ExecuteSVDOperator(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("ExecuteGtScalarOperator failed. ERROR: %d\n", ret); return ret);

  // Reset device and finalize ACL.
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}