aclnnMaskedCausalConv1d

📄 View Source Code

Applicable Products

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

Function

  • Description: Performs masked causal 1D grouped convolution between tokens of the hidden layer.

  • Formula:

    Assume that the shapes of input x and output y are [S, B, H], and the shape of the convolution weight weight is [W, H], where i and j denote the indexes of the S and B axes respectively. The output is calculated as follows:

    $$ out[i,j] = mask[j,i] * \sum_{k=0}^{W-1} x[i-k,j] * weight[W-1-k] $$

    where invalid positions are padded with 0; currently only 3 is supported for W; the operation on the H axis is elementwise and is not reflected in the preceding formulas.

Function Prototype

Each operator uses a two-phase API. Call the aclnnMaskedCausalConv1dGetWorkspaceSize API first to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call the aclnnMaskedCausalConv1d API to perform the computation.

aclnnStatus aclnnMaskedCausalConv1dGetWorkspaceSize(
  const aclTensor   *x,
  const aclTensor   *weight,
  const aclTensor   *maskOptional,
  const aclTensor   *out,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnMaskedCausalConv1d(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  aclrtStream       stream)

aclnnMaskedCausalConv1dGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Represents the data to be computed, corresponding to x in the formula.
    • Does not support empty tensors.
    • The shape is [S, B, H].
    BFLOAT16, FLOAT16 ND 3 √
    weight (aclTensor*) Input Represents convolution weight, corresponding to weight in the formula.
    • Does not support empty tensor.
    • Shape is [W, H].
    Same data type as x ND 2 √
    maskOptional (aclTensor*) Optional input Represents the output mask of the convolution operation, corresponding to mask in the formula.
    • Does not support empty tensor.
    • Shape is [B, S].
    • Default value is nullptr.
    BOOL ND 2 √
    out (aclTensor*) Output Represents the output result of convolution, corresponding to out in the formula.
    • Does not support empty tensor.
    • shape is [S, B, H].
    Data type same as x ND 3 x
    workspaceSize Output Returns the workspace size to be applied by the Device side. - - - - -
    executor Output Returns the op executor that contains the operator computing process. - - - - -
  • Return value

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

    Error Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input parameter is a required input, output, or required attribute, and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types or data formats of x, weight, maskOptional, and out are not within the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shapes of the input and output tensors are not within the supported range.

aclnnMaskedCausalConv1d

  • Parameters:

    Parameter Input/Output Description
    workspace Input Address of the workspace memory applied by the Device side.
    workspaceSize Input Size of the workspace applied by the Device side, obtained by the first-phase API aclnnMaskedCausalConv1dGetWorkspaceSize.
    executor Input Op executor, containing the operator computation flow.
    stream Input Stream for executing tasks.
  • Return value

    Returns an aclnnStatus return code. For details, see aclnn return codes.

Constraints

  • When using this API with PyTorch, ensure that the versions of CANN-related packages and PyTorch-related packages are compatible.
  • Deterministic computation:
    • aclnnMaskedCausalConv1d defaults to a deterministic implementation.
  • Input shape constraints:
    • B * S: range 1-512K.
    • H (hiddenSize): value range 384-24576 (an integer multiple of 64).
    • W: only 3 is supported currently.
  • The operator input parameters and intermediate computation results do not exceed the value range of the corresponding runtime data types (float16/bfloat16).
  • Operator inputs containing ±inf or nan are not supported.

Example

The following sample code shows how to call the single-operator API through aclnn, 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 "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_masked_causal_conv1d.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;
}

void PrintOutResult(std::vector<int64_t> &shape, void **deviceAddr)
{
    auto size = GetShapeSize(shape);
    std::vector<int8_t> resultData(size, 0);
    auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
                           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);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]);
    }
}

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 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);

    // 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 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. Boilerplate for device/stream initialization. For details, see the acl API.
    // 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);

    // 2. Construct the input and output according to the API definition.
    int64_t S = 1;
    int64_t B = 2;
    int64_t H = 192 * 2;
    int64_t W = 3;

    std::vector<int64_t> xShape = {S, B, H};
    std::vector<int64_t> weightShape = {W, H};
    std::vector<int64_t> maskShape = {B, S};
    std::vector<int64_t> yShape = {S, B, H};

    std::vector<op::fp16_t> xHostData(S * B * H, 1.0f);
    std::vector<op::fp16_t> weightHostData(W * H, 1.0f);
    std::vector<uint8_t> maskHostData(B * S, 1);
    std::vector<op::fp16_t> yHostData(S * B * H, 0.5f);


    void *xDeviceAddr = nullptr;
    void *weightDeviceAddr = nullptr;
    void *maskDeviceAddr = nullptr;
    void *yDeviceAddr = nullptr;

    aclTensor *x = nullptr;
    aclTensor *weight = nullptr;
    aclTensor *mask = nullptr;
    aclTensor *y = nullptr;

    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT16, &weight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(maskHostData, maskShape, &maskDeviceAddr, aclDataType::ACL_BOOL, &mask);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT16, &y);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Change it to the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor;

    // Call the first-phase API of aclnnMaskedCausalConv1d.
    ret = aclnnMaskedCausalConv1dGetWorkspaceSize(x, weight, mask, y, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMaskedCausalConv1dGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);

    // Allocate 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 second-phase API aclnnMaskedCausalConv1d.
    ret = aclnnMaskedCausalConv1d(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMaskedCausalConv1d failed. ERROR: %d\n", ret); return ret);

    // 4. Boilerplate: synchronously 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 to the host side. Modify the code based on the actual API definition.
    PrintOutResult(yShape, &yDeviceAddr);

    // 6. Release aclTensor and aclScalar. Modify the code based on the actual API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(weight);
    aclDestroyTensor(mask);
    aclDestroyTensor(y);

    // 7. Release device resources.
    aclrtFree(xDeviceAddr);
    aclrtFree(weightDeviceAddr);
    aclrtFree(maskDeviceAddr);
    aclrtFree(yDeviceAddr);

    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}