FilesLast commitLast update
README

Tridiagonal Linear System Solver Operator with Pivoting (Multiple RHS)

Operator Overview

The gtsv2 operator solves a single tridiagonal linear system and supports multiple right-hand sides (Multiple Right-Hand Sides). Given an m × m tridiagonal matrix A and an m × n dense right-hand side matrix B, the operator solves:

A · X = B

The tridiagonal matrix A is represented by three diagonals:

  • dl: sub-diagonal, dl[0] must be 0
  • d: main diagonal
  • du: super-diagonal, du[m-1] must be 0

B is a dense matrix (ldb × n) in column-major layout, and the solution X overwrites B in place.

The operator uses the Thomas algorithm with partial pivoting, and the flow consists of two steps:

  1. Forward Elimination: eliminate sub-diagonal elements row by row, and compare |d'[i-1]| with |dl[i]| to select the pivot at each step. If |dl[i]| > |d'[i-1]|, swap the tridiagonal coefficients of rows i-1 and i and the corresponding row of B. After elimination, both du and du2 produce fill-in
  2. Backward Substitution: solve x step by step upward from the last row, using the modified du' and du2' that contain fill-in

Compared with gtsv2_nopivot (the pivot-free version), the Thomas algorithm with pivoting is more numerically stable and more precise. Different architectures use different implementations: arch35 independently saves 3 groups of factors for each RHS; arch22 factors the common matrix only once and provides 4 groups of FP32 factors and 1 group of per-row pivot marks for all RHS to reuse.

Multi-core parallelism is distributed along the RHS column count n: each SIMT thread of arch35 processes one RHS column; the fast path of arch22 is handled by each AIV core in grid-stride mode, processing one or more RHS columns.

arch22 provides an FP32 vector Jacobi fast path for matrices with sufficient row diagonal dominance margin (each row satisfies abs(d) > 2*(abs(dl)+abs(du))). Each RHS must also satisfy that all inputs are finite, the sum of absolute values does not overflow, and the conservative normalization bound max(abs(B_column))/min(abs(d)) <= 4 holds. The contraction factor is less than 1/2, and 40 fixed iterations eliminate the truncation error. The RHS range limit controls the rounding error and does not relax the external precision standard. For 128<=m<=6144, the operator uses UB double buffering with explicit boundary areas. For 6144<m<=8192, the multi-RHS path uses six groups of aligned FP32 arrays, occupying at most 192 KiB UB, temporarily writes the normalized RHS into B in place, reloads it at each iteration, and finally writes the solution back in place, without increasing the workspace. The UB in-kernel vector fast path and direct solve of a single RHS are located in the same AIV kernel. Systems that do not satisfy the preceding conditions, smaller systems, or systems larger than UB retain the direct path with pivoting. All selections depend only on sizes, matrix properties, and the input dynamic range, and do not depend on test seeds or case numbers. Inf/NaN and large dynamic range RHS fall back before B is overwritten.

The direct/vector fast paths of arch22 also require 2^-24 <= min(abs(d)), max(abs(d)) <= 2^24, and max(abs(B)) <= 2^24, reserving FP32 dynamic range margin for elimination and backward substitution under the sufficient row diagonal dominance condition. The factorization kernel checks all RHS before B is overwritten.

Other finite systems are handled by core 0 using LU with pivoting and extended exponents: each intermediate value separately stores two groups of FP32 mantissas and one int64 exponent, avoiding intermediate overflow in the Schur complement, RHS forward elimination, and backward substitution. Each row is balanced by an exact power of two, adjusting only the independent exponent. Coefficients with vastly different magnitudes in the same row or in different rows are independently preserved. When the component-wise backward error of the initial output exceeds 1e-6, the operator compares the unbalanced factorization and keeps the one with the smaller error. Five intermediate arrays of length m and one original FP32 RHS are reused by all columns. Finite outputs always attempt two rounds of extended-exponent residual correction: compute b−Ax in the original equations, reuse the selected LU to solve the correction, and write back after confirming that the updated values of the entire column are finite. An ill-conditioned system may still have a large solution error even if the residual is small, so the correction cannot be skipped merely because the residual is small. This method does not guarantee the forward precision of all ill-conditioned systems. The computation still runs on the NPU, without hardware FP64 instructions or CPU fallback. The critical sums/products of mantissas use rounding barriers to maintain the compensated operation order, are finally rounded to FP32, and keep subnormal outputs. Non-finite inputs and exact zero pivots fall back to the original FP32 operation order to preserve the Inf/NaN propagation semantics.

The workspace query returns align_up(align_up(17*m,128)+85*m,128) when n>0, and returns 0 when n=0. The caller must query again the capacity required by the current library and must not hardcode historical capacities. You must still provide a sufficiently large, 128-byte aligned workspace, and the public API and stream asynchronous semantics remain unchanged.

This operator includes the following APIs:

API Brief Description
aclsparseSgtsv2 Solves tridiagonal linear systems (FP32), Thomas algorithm with partial pivoting
aclsparseSgtsv2_bufferSizeExt Queries the workspace size required by aclsparseSgtsv2

Operator Execution APIs

aclsparseSgtsv2

Product support

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Supported (arch22 / DAV_2201)
  • Atlas A2 products: Supported (arch22 / DAV_2201)

Function prototype

aclsparseStatus_t aclsparseSgtsv2(
    aclsparseHandle_t handle,
    int m, int n,
    const float *dl, const float *d, const float *du,
    float *B, int ldb, void *pBuffer);

Parameter description

Parameter Input/Output Type Description Memory Location
handle Input aclsparseHandle_t Context handle of the ops-sparse library, carrying the stream Host memory
m Input int Size of the linear system (number of rows = number of columns); must be ≥ 3 Host memory
n Input int Number of RHS columns; must be ≥ 0. When n=0, the API returns SUCCESS early without computation Host memory
dl Input const float* Sub-diagonal array [m]; dl[0] must be set to 0 before the call Device memory
d Input const float* Main diagonal array [m] Device memory
du Input const float* Super-diagonal array [m]; du[m-1] must be set to 0 before the call Device memory
B Input/Output float* Right-hand side b (input) / solution X (output), of size ldb × n (column-major). On input, it is the right-hand side matrix B, and after the computation, it is overwritten in place with the solution matrix X Device memory
ldb Input int Leading dimension of B; must be ≥ max(1, m) Host memory
pBuffer Input void* Workspace buffer whose address must be 128-byte aligned. When n > 0, it must be a valid pointer whose size is no less than the bytes returned by bufferSizeExt Device memory

Constraints

  • m ≥ 3
  • n ≥ 0 (when n = 0, the API returns SUCCESS early without computation)
  • ldb ≥ max(1, m)
  • When n > 0, none of dl, d, du, or B can be nullptr
  • When n > 0, pBuffer cannot be nullptr, and the address must be a multiple of 128 bytes
  • The size of pBuffer must be ≥ the value returned by aclsparseSgtsv2_bufferSizeExt
  • dl[0] must be set to 0 before the call
  • du[m-1] must be set to 0 before the call
  • Zero pivots may produce Inf/NaN, following the propagation behavior of the Legacy API. Finite ill-conditioned inputs must still be verified against the FP64 golden result and the task precision thresholds, and cannot be exempted from precision failure merely with an "ill-conditioned" label. The extended exponents and two-component mantissas are also not an unlimited precision guarantee for matrices with any condition number.

arch22 implementation notes:

  • The workspace is align_up(align_up(17*m,128)+85*m,128) bytes, independent of the RHS count n. It includes the original four groups of FP32 factors/pivot marks, the extended-exponent factors, the single-column RHS, the original FP32 RHS, and the independent pivot scratch. When m=8192, it is 835584 bytes.
  • When m <= 8192, multi-core parallelism runs along the RHS columns. The vector Jacobi protected by numerical conditions and the direct solve with pivoting coexist. When m > 8192, the operator uses the single-core GM scalar fallback path and does not use CPU fallback.
  • When ldb × sizeof(float) is not 32-byte aligned, to avoid adjacent-column boundary conflicts of unaligned DMA, arch22 uses single-core solving, and the padding rows of B are not overwritten.

aclsparseSgtsv2_bufferSizeExt

Product support

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Supported (arch22 / DAV_2201)
  • Atlas A2 products: Supported (arch22 / DAV_2201)

Function prototype

aclsparseStatus_t aclsparseSgtsv2_bufferSizeExt(
    aclsparseHandle_t handle,
    int m, int n,
    const float *dl, const float *d, const float *du,
    const float *B, int ldb,
    size_t *pBufferSizeInBytes);

Parameter description

Parameter Input/Output Type Description Memory Location
handle Input aclsparseHandle_t Context handle of the ops-sparse library Host memory
m Input int Size of the linear system (number of rows = number of columns); must be ≥ 3 Host memory
n Input int Number of RHS columns; must be ≥ 0. Returns 0 when n=0 Host memory
dl Input const float* Sub-diagonal array [m]; dl[0] must be 0 Device memory
d Input const float* Main diagonal array [m] Device memory
du Input const float* Super-diagonal array [m]; du[m-1] must be 0 Device memory
B Input const float* Right-hand side matrix [ldb × n] (column-major); the query API does not use its values, and it can be nullptr Device memory
ldb Input int Leading dimension of B; must be ≥ max(1, m) Host memory
pBufferSizeInBytes Output size_t* Outputs the workspace size (bytes) required by aclsparseSgtsv2; cannot be nullptr Host memory

Constraints

  • m ≥ 3
  • n ≥ 0 (returns 0 when n = 0, no workspace needed)
  • ldb ≥ max(1, m)
  • None of dl, d, du, or pBufferSizeInBytes can be nullptr
  • B can be nullptr (the query API does not use the values of B)
  • The returned workspace size already includes 128-byte alignment

Returns / Error Codes

The following table distinguishes the aclsparseSgtsv2_bufferSizeExt query API and the aclsparseSgtsv2 solve API.

Return Value Applicable APIs and Scenarios
ACL_SPARSE_STATUS_SUCCESS The query or solve succeeds
ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR The handle of the two APIs is nullptr
ACL_SPARSE_STATUS_INVALID_VALUE The parameters do not satisfy the constraints of the corresponding API, including that pBuffer of the solve API is empty or is not 128-byte aligned when n > 0
ACL_SPARSE_STATUS_INTERNAL_ERROR The solve API fails to obtain the AIV core count or the result is 0 (Atlas A2/A3, Ascend 950)
ACL_SPARSE_STATUS_EXECUTION_FAILED The Ascend 950 solve API detects that kernel enqueue fails

The workspace size query API writes back the query result synchronously. The solve API returns asynchronously, and the caller checks the device asynchronous execution result through stream synchronization.

Supported sparse formats

Format Supported Description
CSR No Not applicable (this operator is a tridiagonal solver and does not use the CSR format)
COO No Not applicable (this operator is a tridiagonal solver and does not use the COO format)
CSC No Not applicable (this operator is a tridiagonal solver and does not use the CSC format)
Tridiagonal Yes Dense array representation using three diagonals (dl, d, du)

Multi-Precision Version List

Precision Prefix Data Type Support
S float (FP32) Supported
D double (FP64) Not supported
C Complex64 (FP32 real part + FP32 imaginary part) Not supported
Z Complex128 (FP64 real part + FP64 imaginary part) Not supported

Currently, only the S prefix (FP32) version is implemented.

Precision Standard

dtype rtol atol Description
FP32 2^-10 2^-16 Mixed per-element tolerance; the overall match rate is ≥ 0.99, and the upper limit of the absolute error is max(1e-2, 32 × ULP(golden))

Invocation example

The example code is for reference only. For details about compilation and running, see Compiling and Running a Sample.

#include <cstdio>
#include <cstdlib>
#include <memory>
#include <vector>

#include "acl/acl.h"
#include "cann_ops_sparse.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)

class AclContext {
public:
    explicit AclContext(int32_t deviceId) : deviceId_(deviceId) {}

    ~AclContext()
    {
        if (stream_ != nullptr) {
            aclrtDestroyStream(stream_);
            stream_ = nullptr;
        }
        if (deviceSet_) {
            aclrtResetDevice(deviceId_);
            deviceSet_ = false;
        }
        if (aclInited_) {
            aclFinalize();
            aclInited_ = false;
        }
    }

    int Init()
    {
        auto ret = aclInit(nullptr);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
        aclInited_ = true;

        ret = aclrtSetDevice(deviceId_);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
        deviceSet_ = true;

        ret = aclrtCreateStream(&stream_);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
        return ACL_SUCCESS;
    }

    aclrtStream Stream() const { return stream_; }

private:
    int32_t deviceId_;
    aclrtStream stream_ = nullptr;
    bool aclInited_ = false;
    bool deviceSet_ = false;
};

int aclsparseSgtsv2Test(AclContext& ctx)
{
    aclrtStream stream = ctx.Stream();

    // 1. Create the ops-sparse handle
    aclsparseHandle_t rawHandle = nullptr;
    auto sparseRet = aclsparseCreate(&rawHandle);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS,
              LOG_PRINT("aclsparseCreate failed. ERROR: %d\n", sparseRet); return sparseRet);
    std::unique_ptr<aclsparseContext, aclsparseStatus_t (*)(aclsparseHandle_t)>
        handlePtr(rawHandle, aclsparseDestroy);

    sparseRet = aclsparseSetStream(static_cast<aclsparseHandle_t>(handlePtr.get()), stream);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS,
              LOG_PRINT("aclsparseSetStream failed. ERROR: %d\n", sparseRet); return sparseRet);

    // 2. Prepare host data
    //    Example: m=4, n=2, solving a 4x4 tridiagonal system (2 RHS columns)
    //    Use a non-diagonally dominant matrix to demonstrate the effect of partial pivoting
    //
    //    Tridiagonal matrix A:
    //    [ 1  1  0  0]
    //    [ 2  2  1  0]
    //    [ 0  3  2  1]
    //    [ 0  0  4  2]
    //
    //    RHS matrix B (column-major, ldb=4):
    //    Column 1: [2, 5, 6, 6]^T
    //    Column 2: [1, 0, 0, 0]^T

    const int m = 4;
    const int n = 2;
    const int ldb = 4;

    // dl: sub-diagonal [m], dl[0] must be 0
    std::vector<float> hDl = {0.0f, 2.0f, 3.0f, 4.0f};

    // d: main diagonal [m]
    std::vector<float> hD = {1.0f, 2.0f, 2.0f, 2.0f};

    // du: super-diagonal [m], du[m-1] must be 0
    std::vector<float> hDu = {1.0f, 1.0f, 1.0f, 0.0f};

    // B: right-hand side [ldb * n] column-major
    //    Column 0: [2, 5, 6, 6], Column 1: [1, 0, 0, 0]
    std::vector<float> hB(ldb * n, 0.0f);
    hB[0] = 2.0f;  hB[4] = 1.0f;
    hB[1] = 5.0f;  hB[5] = 0.0f;
    hB[2] = 6.0f;  hB[6] = 0.0f;
    hB[3] = 6.0f;  hB[7] = 0.0f;

    // 3. Allocate device memory and copy data
    const size_t diagSize = static_cast<size_t>(m) * sizeof(float);
    const size_t bSize = static_cast<size_t>(ldb) * n * sizeof(float);

    void *dDl = nullptr, *dD = nullptr, *dDu = nullptr, *dB = nullptr;
    aclrtMalloc(&dDl, diagSize, ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMalloc(&dD,  diagSize, ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMalloc(&dDu, diagSize, ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMalloc(&dB,  bSize,    ACL_MEM_MALLOC_HUGE_FIRST);

    aclrtMemcpy(dDl, diagSize, hDl.data(), diagSize, ACL_MEMCPY_HOST_TO_DEVICE);
    aclrtMemcpy(dD,  diagSize, hD.data(),  diagSize, ACL_MEMCPY_HOST_TO_DEVICE);
    aclrtMemcpy(dDu, diagSize, hDu.data(), diagSize, ACL_MEMCPY_HOST_TO_DEVICE);
    aclrtMemcpy(dB,  bSize,    hB.data(),  bSize,    ACL_MEMCPY_HOST_TO_DEVICE);

    // 4. Query the required buffer size
    size_t bufferSize = 0;
    sparseRet = aclsparseSgtsv2_bufferSizeExt(
        static_cast<aclsparseHandle_t>(handlePtr.get()),
        m, n,
        static_cast<const float*>(dDl),
        static_cast<const float*>(dD),
        static_cast<const float*>(dDu),
        static_cast<const float*>(dB),
        ldb, &bufferSize);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS,
              LOG_PRINT("bufferSizeExt failed. ERROR: %d\n", sparseRet); return sparseRet);

    // 5. Allocate and initialize the workspace buffer
    void *pBuffer = nullptr;
    if (bufferSize > 0) {
        aclrtMalloc(&pBuffer, bufferSize, ACL_MEM_MALLOC_HUGE_FIRST);
    }

    // 6. Call the operator to solve (B is overwritten in place with the solution X)
    sparseRet = aclsparseSgtsv2(
        static_cast<aclsparseHandle_t>(handlePtr.get()),
        m, n,
        static_cast<const float*>(dDl),
        static_cast<const float*>(dD),
        static_cast<const float*>(dDu),
        static_cast<float*>(dB),
        ldb, pBuffer);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS,
              LOG_PRINT("aclsparseSgtsv2 failed. ERROR: %d\n", sparseRet);
              if (pBuffer) aclrtFree(pBuffer); return sparseRet);

    // 7. Synchronize and read the result
    aclrtSynchronizeStream(stream);

    std::vector<float> hResult(ldb * n, 0.0f);
    aclrtMemcpy(hResult.data(), bSize, dB, bSize, ACL_MEMCPY_DEVICE_TO_HOST);

    // Print the solution vector (column-major: m elements per column)
    for (int j = 0; j < n; j++) {
        LOG_PRINT("RHS column %d solution:\n", j);
        for (int i = 0; i < m; i++) {
            LOG_PRINT("  X[%d][%d] = %f\n", i, j, hResult[i + j * ldb]);
        }
    }

    // 8. Clean up
    if (pBuffer) aclrtFree(pBuffer);
    aclrtFree(dDl);
    aclrtFree(dD);
    aclrtFree(dDu);
    aclrtFree(dB);

    return ACL_SPARSE_STATUS_SUCCESS;
}

int main()
{
    AclContext ctx(0);
    auto ret = ctx.Init();
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = aclsparseSgtsv2Test(ctx);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS,
              LOG_PRINT("aclsparseSgtsv2Test failed. ERROR: %d\n", ret); return ret);
    return 0;
}

The expected output is as follows:

RHS column 0 solution:
  X[0][0] = 1.000000
  X[1][0] = 1.000000
  X[2][0] = 1.000000
  X[3][0] = 1.000000
RHS column 1 solution:
  X[0][1] = 1.000000
  X[1][1] = 0.000000
  X[2][1] = -2.000000
  X[3][1] = 4.000000