aclStft

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

  • API function: computes the Fourier transform of the input within a sliding window.

  • Computation formula:

    • When normalized=False:

      X[w,m]=∑k=0winLength−1window[k]∗self[m∗hopLength+k]∗exp(−j∗2πwknFft)X[w,m]=\sum_{k=0}^{winLength-1}window[k]*self[m*hopLength+k]*exp(-j*\frac{2{\pi}wk}{nFft})

    • When normalized=True:

      X[w,m]=1nFft(∑k=0winLength−1window[k]∗self[m∗hopLength+k]∗exp(−j∗2πwknFft))X[w,m]=\frac{1}{\sqrt{nFft}}(\sum_{k=0}^{winLength-1}window[k]*self[m*hopLength+k]*exp(-j*\frac{2{\pi}wk}{nFft}))

    Here:

    • ww is the frequency point of the FFT.
    • mm is the index of the sliding window.
    • selfself is a 1D or 2D Tensor. If selfself is 1D, it is a time-series sampling sequence. If selfself is 2D, it is multiple time-series sampling sequences.
    • hopLengthhopLength is the sliding window size.
    • windowwindow is a 1D Tensor and the window function of the STFT (for example, hann_window), whose length is winLengthwinLength.
    • exp(−j∗2πwknFft)exp(-j*\frac{2{\pi}wk}{nFft}) is the twiddle factor.

Function Prototype

Each operator uses a two-phase API. Call the "aclStftGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclStft" API to execute 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 Name Input/Output Description Instruction Data Type Data Format Dimensions (shape) Non-contiguous Tensor
    self Input Input to be computed, corresponding to `self` in the formula.
    • Empty tensors are not supported.
    • The shape is [L]/[B, L], where L is the length of the time-series sampling sequence and B is the number of time-series sampling sequences.
    • Inputs Inf, -Inf, and NaN are not supported.
    FLOAT32, DOUBLE, COMPLEX64, COMPLEX128 ND 1-2 ×
    windowOptional Input Must be a 1D Tensor, corresponding to `window` in the formula.
    • Empty tensors are not supported.
    • The data type is the same as that of `self`.
    • The shape is [winLength], where winLength is the length of the STFT window function.
    FLOAT32, DOUBLE, COMPLEX64, COMPLEX128 ND 1 ×
    out Output Result of the Fourier transform of self within the window, corresponding to `X` in the formula.
    • Empty tensors are not supported.
    • If returnComplex=True, `out` is a complex Tensor with the shape [N, T] or [B, N, T].
    • If returnComplex=False, `out` is a real Tensor with the shape [N, T, 2] or [B, N, T, 2].
    Here, N=nFft(onesided=False) or (nFft // 2 + 1)(onesided=True); T is the number of sliding windows, T = (L - nFft) // hopLength + 1.
    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 Denotes the spacing between sliding windows (greater than 0), corresponding to `hopLength` in the formula. - INT64 - - -
    winLength Input Denotes the size of window (greater than 0), corresponding to `winLength` in the formula. - INT64 - - -
    normalized Input Denotes whether to normalize the Fourier transform result. - BOOL - - -
    onesided Input Denotes whether to return the full result or half of the result. If the data type of the input `self` is COMPLEX64 or COMPLEX128, only False is supported. BOOL - - -
    returnComplex Input Denotes whether the return value is a complex Tensor or a Tensor with the real and imaginary parts separated. - BOOL - - -
    workspaceSize Output Returns the size of the workspace to be allocated on the Device side. - - - - -
    executor Output Returns the op executor, which contains 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 Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input 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 range supported by the platform.
    Invalid values are passed in 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 Name Input/Output Description
    workspace Input Memory address of the workspace allocated on the Device side.
    workspaceSize Input Size of the workspace allocated on the Device side, obtained by calling the first-phase API aclStftGetWorkspaceSize.
    executor Input op executor, which contains the operator computation flow.
    stream Input Stream for executing tasks.
  • Return value

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

Constraints

  • The input self differs from that of the PyTorch API: the input self of the PyTorch API is the original input, whereas the input self of aclStftGetWorkspaceSize is the result obtained after the original input is padded by the PyTorch frontend.

  • When the shape of the input self is [B, L], the computation of the current API may time out if the result of the following formula is large.

    B∗((L−nFft)/hopLength+1)∗nFftB * ((L - nFft) / hopLength + 1) * nFft

  • nFft <= L.

  • winLength <= nFft.

  • When normalized=True,

    STFT(w,m)=1NX[w,m]STFT(w,m)=\frac{1}{\sqrt{N}}X[w,m]

  • The mapping between the input and output 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 sample code is for reference only. For details about the compilation and execution process, 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)
{
    // Fixed code 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 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-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 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 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 main()
{
    // 1. (Fixed code) Initialize the device/stream. For details, refer to the list of ACL APIs.
    // Set deviceId based on the 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 the input and output. Customize the construction based on the API definition.
    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 the self aclTensor
    ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the window aclTensor
    ret = CreateAclTensor(windowHostData, windowShape, &windowDeviceAddr, aclDataType::ACL_FLOAT, &window);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the 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. Change it to the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API 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);
    // Allocate device memory based on the workspaceSize computed 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 second-phase API aclStft
    ret = aclStft(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclStft failed. ERROR: %d\n", ret); return ret);
    // 4. (Fixed code) Synchronize and wait for the 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-side memory to the host side. Modify the code 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 the aclTensor. Modify the code based on the specific API definition.
    aclDestroyTensor(self);
    aclDestroyTensor(window);
    aclDestroyTensor(out);
    // 7. Release the device resources. Modify the code based on the specific API definition.
    aclrtFree(selfDeviceAddr);
    aclrtFree(windowDeviceAddr);
    aclrtFree(outDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}