aclnnSvd
Applicable Products
| Product | Supported |
|---|---|
| × | |
| √ | |
| √ | |
| × | |
| × | |
| × |
Function
Description: Computes the singular value decomposition of one or more matrices.
When the dimension of the input tensor is greater than 2, the high-dimensional tensor is treated as a batch of matrices for processing. For an input tensor of shape (..., M, N), the dimensions preceding the second-to-last dimension (...) are treated as batch dimensions, and singular value decomposition is performed independently on each (M, N) matrix.
Formula:
Function Prototype
Each operator is divided into a two-phase API. The "aclnnSvdGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnSvd" API is called to perform 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 The tensor to undergo singular value decomposition, corresponding to input in the formula. Empty tensors are not supported.
The shape must have at least two dimensions.FLOAT, DOUBLE, COMPLEX64, COMPLEX128 ND 2-8 √ fullMatrices Input An input parameter that specifies whether to compute the output tensors u and v in full. Controls whether to compute the full SVD decomposition.
When set to true, outputs the full u and v.
When set to false, computes only the economy version to save memory and computational resources.
Given input shape [..., M, N], let K = min(M, N).
When set to true, output shapes:
u: [..., M, M], sigma: [..., K], v: [..., N, N].
When set to false, output shapes:
u: [..., M, K], sigma: [..., K], v: [..., N, K].BOOL - - - computeUV Input Input parameter that specifies whether to compute the output tensors u and v. When set to true, the output tensors sigma, u, and v are all computed.
When set to false, only sigma is computed, and the shapes of u and v are no longer validated.BOOL - - - sigma Output Output tensor, corresponding to sigma in the formula. The shape is 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-7 √ u Output Output tensor, corresponding to U in the formula. The shape is derived from the shape of input and the fullMatrices parameter.
The data type must be consistent with that of input.FLOAT, DOUBLE, COMPLEX64, COMPLEX128 ND 2-8 √ v Output Output tensor, corresponding to V in the formula. The shape is derived from the shape of input and the fullMatrices parameter.
The data type must be the same as input.FLOAT, DOUBLE, COMPLEX64, COMPLEX128 ND 2-8 √ workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - - executor Output Returns the operator executor, which contains the operator computation flow. - - - - - Return value
aclnnStatus: return code. For details, see aclnn Return Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The input, sigma, u, or v is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of input, sigma, u, or v is not within the supported range. The data type of input is inconsistent with that of sigma, u, or v. The dimension of input is less than 2 or greater than 8. The shape of sigma, u, or v is inconsistent with the shape derived from input.
aclnnSvd
Parameters:
Parameter Input/Output Description workspace Input Address of the workspace memory applied for on the Device side. workspaceSize Input Size of the workspace applied for on the Device side, obtained through the first-phase API aclnnSvdGetWorkspaceSize. executor Input Operator executor that contains the operator computation flow. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnSvd defaults to a deterministic implementation.
Example
The following provides example code for reference only. For details about compilation and running, 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-side 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-side data to device-side 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);
// Compute the strides of a 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 the aclCreateTensor API 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 the input and output. Custom construction is required 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 the input aclTensor.
ret = CreateAclTensor(inputHostData, inputShape, &tensors.inputDeviceAddr, aclDataType::ACL_FLOAT, &tensors.input);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the u aclTensor.
ret = CreateAclTensor(uHostData, tensors.uShape, &tensors.uDeviceAddr, aclDataType::ACL_FLOAT, &tensors.u);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the sigma aclTensor.
ret = CreateAclTensor(sigmaHostData, tensors.sigmaShape, &tensors.sigmaDeviceAddr, aclDataType::ACL_FLOAT, &tensors.sigma);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the 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. Replace with 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);
// Apply for device memory based on the workspaceSize calculated 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 second-phase API of aclnnSvd.
ret = aclnnSvd(workspace.addr, workspace.size, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSvd failed. ERROR: %d\n", ret); return ret);
// Wait for the task execution to finish synchronously.
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 the device memory to the 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 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() {
// Initialize the device/stream. 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 the device and finalize ACL.
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}