aclnnMatmulAbftVerify

Applicable Products

  • Ascend 950PR&950DT products: Not 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: Implements a GEMM fault-tolerance detection operator based on the variance estimation adaptive threshold algorithm (V-ABFT). The operator takes matrices A and B and the pre-computed matrix multiplication result C as inputs, performs block-wise ABFT verification on C, detects silent computation errors, and outputs row-wise detection results.

  • Features

    • Adaptive threshold: The operator automatically determines the threshold for comparison based on the matrix size and value range, ensuring the detection rate while avoiding false detection.

    • The computational cost is significantly lower than that of recomputation-based fault tolerance solutions. When the matrix dimensions are m=n=k=a, this operator requires only 8a^2 floating-point operations, while recomputation requires 2a^3 floating-point operations. The fault tolerance threshold also matches this algorithm.

  • Formula:

    C=A×B,A∈RM×K,  B∈RK×NC = A \times B, \quad A \in \mathbb{R}^{M \times K},\; B \in \mathbb{R}^{K \times N} Cr=C×r,Br=B×rC^r = C\times r, B^r=B\times r

    The threshold ThresholdiThreshold_i is dynamically estimated from the local statistics (mean and standard deviation) of input matrices A and B, without relying on the output of matrix C.

  • Description:

    • Input matrices A and B and the pre-computed C undergo checksum encoding, threshold estimation, and verification comparison, and the compressed row-wise fault detection result tensor comp_row is output, where 1 indicates correctness and 0 indicates a detected error.

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnMatmulAbftVerifyGetWorkspaceSize" API to obtain the input parameters and calculate the workspace size required for the computation, and then call the "aclnnMatmulAbftVerify" API to perform the computation.

aclnnStatus aclnnMatmulAbftVerifyGetWorkspaceSize(
    const aclTensor  *a,
    const aclTensor  *b,
    const aclTensor  *c,
    const aclTensor  *checksumWeight,
    double            eMax,
    const aclTensor  *compRow,
    uint64_t         *workspaceSize,
    aclOpExecutor   **executor);
aclnnStatus aclnnMatmulAbftVerify(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream     stream);

aclnnMatmulAbftVerifyGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    a (aclTensor) Input Matrix multiplication input A.
    • 2 dimensions, shape [M, K].
    FLOAT16, BFLOAT16, FLOAT32 ND [M, K] -
    b (aclTensor) Input Matrix multiplication input B.
    • A 2-dimensional tensor with shape [K, N].
    FLOAT16, BFLOAT16, FLOAT32 ND [K, N] -
    c (aclTensor) Input Pre-computed matrix multiplication result C = A × B, used as the data input for fault tolerance detection.
    • A 2-dimensional tensor with shape [M, N].
    FLOAT32 ND [M, N] -
    checksumWeight (aclTensor) Input Column encoding value vector, corresponding to the row checksum encoding vector $r$ (weighted vector) in ABFT.
    • Dimension: 1, shape: [N].
    FLOAT16, BFLOAT16, FLOAT32 ND [N] -
    eMax (double) Input Error threshold coefficient that controls the sensitivity of fault detection.
    • Default value: 0.001.
    • For BF16 A and B, the recommended value is 0.001.
    • For FP32 A and B, the recommended value is 0.00002.
    • Using an eMax smaller than the recommended value increases the detection rate but may cause false detections.
    • If false positives occur, increase eMax.
    - - - -
    compRow (aclTensor) Output Compressed row-direction fault detection bitstream output.
    • Each bit indicates the detection result of a row segment. 1 indicates correct, and 0 indicates an error is detected.
    UINT8 ND [ceil(M/8) * splitN] -
    workspaceSize (uint64_t) Output Returns the workspace size to be requested on the Device. - - - - -
    executor (aclOpExecutor) Output Returns the op executor, which contains the operator computation process. - - - - -

    where splitN=⌈N/256⌉splitN = \lceil N / 256\rceil.

  • 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 A required input, output, or required attribute is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of a, b, c, weight, eMax, beSplitFactor, or compRow is unsupported.
    The dimensions of a and b are not 2.
    The 1st dimension (K) of a is not equal to the 0th dimension (K) of b.
    eMax is negative.
    reduceCores is less than 0.

aclnnMatmulAbftVerify

  • Parameters:

    ParameterInput/OutputDescription
    workspaceInputMemory address of the workspace allocated on the device.
    workspaceSizeInputSize of the workspace allocated on the device, obtained by calling the first-phase API aclnnMatmulAbftVerifyGetWorkspaceSize.
    executorInputExecutor of the op, containing the operator computation flow.
    streamInputStream used to execute the task.
  • Return value

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

Constraints

  • Deterministic computation:

    • aclnnMatmulAbftVerify defaults to a deterministic implementation.
  • The input matrices a, b, and c must be 2D, with shapes [M, K], [K, N], and [M, N], respectively, and the first dimension (K) of a must be equal to the 0th dimension (K) of b.

  • The shape of the input vector weight must be [N].

  • The supported data type combinations are:

    abcchecksumWeight
    FLOAT16FLOAT16FLOAT32FLOAT16
    BFLOAT16BFLOAT16FLOAT32BFLOAT16
    FLOAT32FLOAT32FLOAT32FLOAT32
  • Unsupported use cases:

    • Data formats other than ND are not supported.
    • Non-contiguous tensors are not supported.
    • Use cases where the dimensions of a, b, and c are not 2 are not supported.

Workspace Usage Design

The workspace consists of two parts:

  1. A fixed 16 MiB system workspace.
  2. The user workspace, which sequentially holds 13 internal intermediate tensors and the FT internal temporary area.

The operator tiling phase calculates the total size based on M, N, K, and the input precision, and returns it through workspaceSize. The caller must allocate contiguous device memory of no less than this size, rather than only the compRow size. The start addresses of all intermediate tensors are aligned up to 32 bytes.

Definition:

splitN      = ceil(N / 256)
rowSplitLen = M * splitN
bStatLen    = ceil(splitN / 8) * 8 + 8
beLen       = K * splitN
align32(x)  = ceil(x / 32) * 32

Let W be the start address of the user workspace. Inside the kernel, W = AscendC::GetUserWorkspace(workspace); for device address calculation outside the operator, the current implementation is equivalent to W = (uint8_t *)workspace + 16 MiB.

The following offsets are all relative to W. Let S0 = 0. The start offset of each tensor is Oi = align32(Si), and its end position is Si+1 = Oi + elementCount × elementSize:

OrderIntermediate ResultStart AddressElement TypeElement Count
0z_rowW + O0FLOAT32rowSplitLen
1d_rowW + O1FLOAT32rowSplitLen
2thresholdW + O2FLOAT32rowSplitLen
3b_mean_absW + O3FLOAT32bStatLen
4b_mean_squareW + O4FLOAT32bStatLen
5b_varW + O5FLOAT32bStatLen
6beW + O6Same as abeLen
7be_for_aivW + O7FLOAT16 if a is FLOAT16, otherwise FLOAT32beLen
8b_max_sliceW + O8FLOAT32beLen
9b_min_sliceW + O9FLOAT32beLen
10a_maxW + O10FLOAT32M
11a_meanW + O11FLOAT32M
12a_minW + O12FLOAT32M
FLOAT16 and BFLOAT16 elements occupy 2 bytes each, and FLOAT32 elements occupy 4 bytes each. After the 13th segment, 32-byte alignment is applied again. The remaining area is the FT internal temporary area, whose logical size is:
M * (splitN + 1) * sizeof(float)

The constant factor 1/K used in the AMean computation does not occupy the workspace. The tiling phase generates this scalar based on the input precision, and the kernel uses it to directly initialize the L1 internal buffer of FT when computing AMean for the first time. Therefore, this factor cannot be copied out as a workspace intermediate result.

If you need to debug and copy out a specific intermediate result, perform a device-to-host copy starting from the corresponding W + Oi in the preceding table after the operator finishes execution and before the workspace is released or reused. The number of bytes to copy is "element count × element byte size". Reading the workspace externally is a debugging capability, not a stable public output interface. If the layout changes, use the address partitioning code under the Workspace ABI comment in matmul_abft_verify.cpp as the authoritative reference; that code also serves as a sample implementation of offset calculation.

Example

The following example uses FLOAT32 inputs. The sample first calls aclnnGemm to compute C = A × B, and then passes the matmul result C to aclnnMatmulAbftVerify for verification.

#include <cstdint>
#include <cstdio>
#include <vector>

#include "acl/acl.h"
#include "aclnnop/aclnn_gemm.h"
#include "aclnnop/aclnn_matmul_abft_verify.h"

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

int64_t GetElementCount(const std::vector<int64_t>& shape)
{
    int64_t count = 1;
    for (int64_t dim : shape) {
        count *= dim;
    }
    return count;
}

template <typename T>
int CreateAclTensor(const std::vector<T>& hostData,
                    const std::vector<int64_t>& shape,
                    aclDataType dataType,
                    void** deviceAddr,
                    aclTensor** tensor)
{
    const uint64_t bytes = static_cast<uint64_t>(hostData.size()) * sizeof(T);
    auto ret = aclrtMalloc(deviceAddr, bytes, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = aclrtMemcpy(*deviceAddr, bytes, hostData.data(), bytes,
                      ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    std::vector<int64_t> strides(shape.size(), 1);
    for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; --i) {
        strides[i] = shape[i + 1] * strides[i + 1];
    }

    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType,
                              strides.data(), 0, ACL_FORMAT_ND,
                              shape.data(), shape.size(), *deviceAddr);
    CHECK_RET(*tensor != nullptr, return ACL_ERROR_FAILURE);
    return ACL_SUCCESS;
}

int main()
{
    constexpr int32_t deviceId = 0;
    constexpr int64_t M = 4096;
    constexpr int64_t N = 4096;
    constexpr int64_t K = 4096;
    constexpr double eMax = 0.00002;

    const int64_t splitN = (N + 255) / 256;
    const std::vector<int64_t> aShape{M, K};
    const std::vector<int64_t> bShape{K, N};
    const std::vector<int64_t> cShape{M, N};
    const std::vector<int64_t> checksumWeightShape{N};
    const std::vector<int64_t> compRowShape{((M + 7) / 8) * splitN};

    // When all checksumWeight values are 1, it corresponds to the ordinary blocked row checksum.
    std::vector<float> hostA(GetElementCount(aShape), 0.5F);
    std::vector<float> hostB(GetElementCount(bShape), 0.25F);
    std::vector<float> hostC(GetElementCount(cShape), 0.0F);
    std::vector<float> hostChecksumWeight(GetElementCount(checksumWeightShape), 1.0F);
    std::vector<uint8_t> hostCompRow(GetElementCount(compRowShape), 0);

    aclrtContext context = nullptr;
    aclrtStream stream = nullptr;
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = aclrtCreateContext(&context, deviceId);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = aclrtSetCurrentContext(context);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = aclrtCreateStream(&stream);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    void* devA = nullptr;
    void* devB = nullptr;
    void* devC = nullptr;
    void* devGemmAddend = nullptr;
    void* devChecksumWeight = nullptr;
    void* devCompRow = nullptr;
    aclTensor* tensorA = nullptr;
    aclTensor* tensorB = nullptr;
    aclTensor* tensorC = nullptr;
    aclTensor* tensorGemmAddend = nullptr;
    aclTensor* tensorChecksumWeight = nullptr;
    aclTensor* tensorCompRow = nullptr;

    ret = CreateAclTensor(hostA, aShape, ACL_FLOAT, &devA, &tensorA);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(hostB, bShape, ACL_FLOAT, &devB, &tensorB);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(hostC, cShape, ACL_FLOAT, &devC, &tensorC);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(hostC, cShape, ACL_FLOAT,
                          &devGemmAddend, &tensorGemmAddend);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(hostChecksumWeight, checksumWeightShape, ACL_FLOAT,
                          &devChecksumWeight, &tensorChecksumWeight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(hostCompRow, compRowShape, ACL_UINT8,
                          &devCompRow, &tensorCompRow);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Preceding matmul: C = 1.0 * A * B + 0.0 * gemmAddend.
    uint64_t gemmWorkspaceSize = 0;
    aclOpExecutor* gemmExecutor = nullptr;
    ret = aclnnGemmGetWorkspaceSize(
        tensorA, tensorB, tensorGemmAddend,
        1.0F, 0.0F, 0, 0, tensorC, 0,
        &gemmWorkspaceSize, &gemmExecutor);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    void* gemmWorkspace = nullptr;
    if (gemmWorkspaceSize > 0) {
        ret = aclrtMalloc(&gemmWorkspace, gemmWorkspaceSize,
                          ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    }
    ret = aclnnGemm(gemmWorkspace, gemmWorkspaceSize, gemmExecutor, stream);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Perform ABFT verification on the result of the preceding GEMM.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor = nullptr;
    ret = aclnnMatmulAbftVerifyGetWorkspaceSize(
        tensorA, tensorB, tensorC, tensorChecksumWeight,
        eMax, tensorCompRow, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    void* workspace = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspace, workspaceSize,
                          ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    }
    ret = aclnnMatmulAbftVerify(workspace, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    aclDestroyTensor(tensorA);
    aclDestroyTensor(tensorB);
    aclDestroyTensor(tensorC);
    aclDestroyTensor(tensorGemmAddend);
    aclDestroyTensor(tensorChecksumWeight);
    aclDestroyTensor(tensorCompRow);
    aclrtFree(devA);
    aclrtFree(devB);
    aclrtFree(devC);
    aclrtFree(devGemmAddend);
    aclrtFree(devChecksumWeight);
    aclrtFree(devCompRow);
    if (gemmWorkspace != nullptr) {
        aclrtFree(gemmWorkspace);
    }
    if (workspace != nullptr) {
        aclrtFree(workspace);
    }
    aclrtDestroyStream(stream);
    aclrtDestroyContext(context);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return ACL_SUCCESS;
}