aclStft
Applicable Products
| Product | Supported |
|---|---|
| × | |
| √ | |
| √ | |
| × | |
| × | |
| × |
Function
Description: Computes the Fourier transform of the input within a sliding window.
Formula:
When normalized=false:
When normalized=true:
Where:
is the frequency bin of the FFT.
is the index of the sliding window.
is a 1D or 2D tensor. When is 1D, it represents a single time-series sampling sequence. When is 2D, it represents multiple time-series sampling sequences.
is the sliding window size.
is a 1D tensor, serving as the window function for STFT (e.g., hann_window), with a length of .
is the twiddle factor.
Function Prototype
Each operator is divided into a two-phase API. The "aclStftGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclStft" API is called to perform the computation.
aclnnStatus aclStftGetWorkspaceSize(
const aclTensor *self,
const aclTensor *windowOptional,
aclTensor *out,
int64_t nFft,
int64_t hopLength,
int64_t winLength,
bool normalized,
bool onesided,
bool returnComplex,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclStft(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclStftGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor self Input The input to be computed, corresponding to `self` in the formula. - Null Tensor is not supported.
- The shape is [L] or [B, L], where L is the length of the time-domain sampling sequence and B is the number of time-domain sampling sequences.
- Inf, -Inf, or NaN input is not supported.
FLOAT32, DOUBLE, COMPLEX64, COMPLEX128 ND 1-2 × windowOptional Input Must be a 1D tensor, corresponding to `window` in the formula. - Null not supported.
- The data type must be consistent with `self`.
- The shape is [winLength], where winLength is the length of the STFT window function.
FLOAT32, DOUBLE, COMPLEX64, COMPLEX128 ND 1 × out Output Fourier transform result of self within the window, corresponding to `X` in the formula. - Null not supported.
- If returnComplex=True, `out` is a complex tensor of shape [N, T] or [B, N, T].
- If returnComplex=False, `out` is a real tensor of shape [N, T, 2] or [B, N, T, 2].
FLOAT32, DOUBLE, COMPLEX64, COMPLEX128 ND 3-4 × nFft Input Number of FFT points (greater than 0), corresponding to `nFft` in the formula. - INT64 - - - hopLength Input Represents the interval of the sliding window (greater than 0), corresponding to `hopLength` in the formula. - INT64 - - - winLength Input Indicates the window size (greater than 0), corresponding to `winLength` in the formula. - INT64 - - - normalized Input Indicates whether to normalize the Fourier transform result. - BOOL - - - onesided Input Indicates whether to return the full result or half of the result. When the data type of the input `self` is COMPLEX64 or COMPLEX128, only False is supported. BOOL - - - returnComplex Input Indicates whether the return value is a complex tensor or separate real and imaginary tensors. - BOOL - - - workspaceSize Output Returns the workspace size to be allocated 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 Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The passed self or out is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data format of self is not within the supported range. The data types of self and windowOptional are inconsistent. The data types of self, windowOptional, and out are not within the supported range of the platform. Invalid values are input for nFft, hopLength, or winLength. The dimensions of self, windowOptional, and out are not within the supported range. When the data type of the input self is COMPLEX64 or COMPLEX128, the value of onesided is True.
aclStft
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 from the first-phase API aclStftGetWorkspaceSize. executor Input Operator executor, which contains the operator computation flow. stream Input Specifies the stream that executes the task. Return value
aclnnStatus: return code. For details, see aclnn Return Codes.
Constraints
Difference between the input self and the PyTorch API: The input self of the PyTorch API is the original input; the input self of aclStftGetWorkspaceSize is the result obtained after the original input is padded by the frontend PyTorch.
When the shape of the input self is [B, L], the current API call may time out if the result of the following formula is large.
nFft <= L.
winLength <= nFft.
When normalized = True,
The correspondence between the data types of self, windowOptional, returnComplex, and out is as follows:
self windowOptional returnComplex out FLOAT32 FLOAT32 True COMPLEX64 DOUBLE DOUBLE True COMPLEX128 COMPLEX64 COMPLEX64 True COMPLEX64 COMPLEX128 COMPLEX128 True COMPLEX128 FLOAT32 FLOAT32 False FLOAT32 DOUBLE DOUBLE False DOUBLE COMPLEX64 COMPLEX64 False FLOAT32 COMPLEX128 COMPLEX128 False DOUBLE Deterministic computation:
- aclStft 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/acl_stft.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;
}
int Init(int32_t deviceId, aclrtStream* stream)
{
// Boilerplate: 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 memory on the device side.
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 data from the host side to the 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 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 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 main()
{
// 1. (Boilerplate) Initialize device/stream. See the acl external API list.
// Fill in deviceId based on your actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the check as needed.
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct inputs and outputs. Customize the construction based on the API.
std::vector<int64_t> selfShape = {5};
std::vector<int64_t> windowShape = {4};
std::vector<int64_t> outShape = {3, 1, 2};
void* selfDeviceAddr = nullptr;
void* windowDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
aclTensor* self = nullptr;
aclTensor* window = nullptr;
aclTensor* out = nullptr;
std::vector<float> selfHostData = {1, 6, 8, 5, 7};
std::vector<float> windowHostData = {1, 1, 1, 1};
std::vector<float> outHostData = {0, 0, 0, 0, 0, 0};
// Create self aclTensor.
ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
// Create window aclTensor.
ret = CreateAclTensor(windowHostData, windowShape, &windowDeviceAddr, aclDataType::ACL_FLOAT, &window);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
int n_fft = 4;
int hop_length = 2;
int win_length = 4;
bool normalized = false;
bool onesided = true;
bool returnComplex = false;
// 3. Call the CANN operator library API. Replace with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclStft.
ret = aclStftGetWorkspaceSize(
self, window, out, n_fft, hop_length, win_length, normalized, onesided, returnComplex, &workspaceSize,
&executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclStftGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Apply for device memory based on the workspaceSize calculated by the first-phase API.
void* workspaceAddr = nullptr;
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
}
// Call the aclStft second-phase API.
ret = aclStft(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclStft failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronously wait for task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value and copy the result from the device memory to the host side. Modify based on the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<float> resultData(size, 0);
ret = aclrtMemcpy(
resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(resultData[0]),
ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
}
// 6. Release aclTensor. Modify based on the specific API definition.
aclDestroyTensor(self);
aclDestroyTensor(window);
aclDestroyTensor(out);
// 7. Release device resources. Modify based on the specific API definition.
aclrtFree(selfDeviceAddr);
aclrtFree(windowDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}