| Files | Last commit | Last update |
|---|---|---|
Complex Tridiagonal Linear System Solver Operator
Operator Overview
aclsparseCgtsv2 solves a single complex tridiagonal system A·X=B and supports multiple right-hand sides (RHS).
The matrix is represented by the subdiagonal dl, main diagonal d, and superdiagonal du. The solution overwrites the column-major B in place, the coefficients are read-only, and padding remains unchanged.
The generic path uses adjacent partial pivoting, shares the factorization, and retains the second superdiagonal produced by row swaps.
This operator does not change the existing real-valued aclsparseSgtsv2 interface.
The invocation sequence is: query the workspace capacity → allocate and align the workspace → perform the solve → read the result after synchronizing the stream.
Mathematical expression:
dl[i] * X[i-1,j] + d[i] * X[i,j] + du[i] * X[i+1,j] = B[i,j]
0 <= i < m, 0 <= j < n; out-of-range terms are 0, dl[0] = du[m-1] = 0.
This operator provides the following interfaces:
| Interface name | Function brief |
|---|---|
| aclsparseCgtsv2_bufferSizeExt | Queries the number of bytes of Device workspace that the caller should provide |
| aclsparseCgtsv2 | Solves the complex tridiagonal system with pivoting and writes the solution back to B in place |
Interface contract source
This implementation is based on the official task book of Atlas A2 products and Atlas A3 products.
Section 2.2 of the task book explicitly requires the Kernel direct-call mode of the Legacy C API, and section 2.3 specifies
aclsparseCgtsv2_bufferSizeExt and aclsparseCgtsv2. This document confirms the interface system according to the task requirements and adds no Generic descriptor interfaces.
Following the review suggestion, this implementation reuses the existing repository struct aclsparseComplex { float x; float y; }, and aclsparseComplex_t is only a type alias of it,
where x denotes the real part and y denotes the imaginary part. The two names are the same C/C++ type, you can assign directly or pass pointers,
and no second complex64 struct is maintained. Compared with the original real/imag representation in the task book, the order of the two FLOAT32 components,
the 8-byte size, and the public C symbol remain unchanged; source-code member access is unified as the existing x/y of the repository.
For the design description, see the design document PR.
Operator Execution Interfaces
aclsparseCgtsv2
Product support
| Product | Support status |
|---|---|
| Atlas A2 products | Supported, arch22 / DAV_2201 |
| Atlas A3 products | Supported, arch22 / DAV_2201 |
| Ascend 950PR&950DT products | Supported, arch35 / DAV_3510 |
Function prototype
aclsparseStatus_t aclsparseCgtsv2(aclsparseHandle_t handle, int m, int n,
const aclsparseComplex_t *dl, const aclsparseComplex_t *d,
const aclsparseComplex_t *du, aclsparseComplex_t *B, int ldb, void *pBuffer)
Parameter description
| Parameter | Input/Output | Parameter type | Description |
|---|---|---|---|
| handle | Input | aclsparseHandle_t | Valid library handle that carries the execution stream, Host memory |
| m | Input | int | Number of rows of the system, m>=3, Host memory |
| n | Input | int | Number of RHS columns, n>=0, Host memory |
| dl | Input | const aclsparseComplex_t* | Subdiagonal, m complex64 values, dl[0]=0, Device memory |
| d | Input | const aclsparseComplex_t* | Main diagonal, m complex64 values, Device memory |
| du | Input | const aclsparseComplex_t* | Superdiagonal, m complex64 values, du[m-1]=0, Device memory |
| B | Input/Output | aclsparseComplex_t* | [ldb,n] column-major; the first m rows are overwritten in place with the solution, Device memory |
| ldb | Input | int | Physical column stride, ldb>=m, Host memory |
| pBuffer | Input/workspace | void* | At least the queried capacity, with the base address 128-byte aligned, Device memory |
Constraints
- The complex type is contiguous
float x/y, with a size of 8 bytes and an alignment ofalignof(float). dl/d/dumust be read-only; the rows[m,ldb)of B retain the original bytes. There are no separate X, batch, broadcast, or arbitrary stride parameters.n=0still validates handle andm/ldb, returns success, and launches no kernel; empty data/workspace pointers are allowed.- A non-empty call must provide a valid device allocation. A bare-pointer API cannot know the real capacity, dtype, or stride of the allocation, and the caller is responsible for this.
- Concurrent calls must use separate writable workspaces. The inputs, B, and workspace must not be released before the stream completes.
- A successful return only indicates that validation and asynchronous dispatch succeed; device errors must still be checked when the caller synchronizes the stream.
- A null handle returns
ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR; an invalid size, pointer, alignment, or address span returnsACL_SPARSE_STATUS_INVALID_VALUE. A platform discovery failure returnsACL_SPARSE_STATUS_INTERNAL_ERRORand logs an error; when the backend for the corresponding architecture is not compiled,ACL_SPARSE_STATUS_NOT_SUPPORTEDis returned. - Singular and non-finite inputs use bounded execution and separate diagnostic semantics, and they do not serve as evidence of accuracy pass for ordinary finite values.
Invocation example
The example uses m=3,n=1,ldb=3. The main diagonal of the matrix is 4, the two off-diagonals are 1, the right-hand side is [6,12,14],
the analytical solution is [1,2,3], and the imaginary parts are all 0. The interface does not use MatDescr and has no scalar pointer parameter that requires PointerMode.
The example uses AclContext and std::unique_ptr to manage ACL, the handle, Device inputs, and the workspace, and it contains complete querying, execution, and result checking.
For the build and run method, see Build and Run Example. Select the target SoC according to the actual Atlas A2 products, Atlas A3 products, or Ascend 950PR&950DT products device.
#include <array>
#include <cmath>
#include <cstdio>
#include <cstdint>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include "acl/acl.h"
#include "cann_ops_sparse.h"
void CheckAcl(aclError status, const char *operation)
{
if (status != ACL_SUCCESS) {
throw std::runtime_error(std::string(operation) + ": " + std::to_string(status));
}
}
void CheckSparse(aclsparseStatus_t status, const char *operation)
{
if (status != ACL_SPARSE_STATUS_SUCCESS) {
throw std::runtime_error(std::string(operation) + ": " + std::to_string(status));
}
}
class AclContext {
public:
explicit AclContext(int32_t deviceId) : deviceId_(deviceId) {}
AclContext(const AclContext &) = delete;
AclContext &operator=(const AclContext &) = delete;
~AclContext()
{
if (stream_ != nullptr) { aclrtDestroyStream(stream_); }
if (deviceSet_) { aclrtResetDevice(deviceId_); }
if (initialized_) { aclFinalize(); }
}
void Init()
{
CheckAcl(aclInit(nullptr), "aclInit");
initialized_ = true;
CheckAcl(aclrtSetDevice(deviceId_), "aclrtSetDevice");
deviceSet_ = true;
CheckAcl(aclrtCreateStream(&stream_), "aclrtCreateStream");
}
aclrtStream Stream() const { return stream_; }
private:
int32_t deviceId_;
aclrtStream stream_ = nullptr;
bool initialized_ = false;
bool deviceSet_ = false;
};
struct DeviceDeleter {
aclrtStream stream;
void operator()(void *address) const
{
// Error paths also wait before releasing data used by an async launch.
aclrtSynchronizeStream(stream);
aclrtFree(address);
}
};
using DevicePtr = std::unique_ptr<void, DeviceDeleter>;
DevicePtr Allocate(size_t bytes, aclrtStream stream)
{
void *address = nullptr;
CheckAcl(aclrtMalloc(&address, bytes, ACL_MEM_MALLOC_HUGE_FIRST), "aclrtMalloc");
return DevicePtr(address, DeviceDeleter{stream});
}
void RunExample(AclContext &ctx)
{
using Complex = aclsparseComplex;
const std::array<Complex, 3> lower{{{0, 0}, {1, 0}, {1, 0}}};
const std::array<Complex, 3> diagonal{{{4, 0}, {4, 0}, {4, 0}}};
const std::array<Complex, 3> upper{{{1, 0}, {1, 0}, {0, 0}}};
const std::array<Complex, 3> rhs{{{6, 0}, {12, 0}, {14, 0}}};
constexpr size_t dataBytes = sizeof(Complex) * 3;
aclsparseHandle_t rawHandle = nullptr;
CheckSparse(aclsparseCreate(&rawHandle), "aclsparseCreate");
std::unique_ptr<aclsparseContext, decltype(&aclsparseDestroy)> handle(rawHandle, aclsparseDestroy);
CheckSparse(aclsparseSetStream(handle.get(), ctx.Stream()), "aclsparseSetStream");
auto dl = Allocate(dataBytes, ctx.Stream());
auto d = Allocate(dataBytes, ctx.Stream());
auto du = Allocate(dataBytes, ctx.Stream());
auto b = Allocate(dataBytes, ctx.Stream());
CheckAcl(aclrtMemcpy(dl.get(), dataBytes, lower.data(), dataBytes, ACL_MEMCPY_HOST_TO_DEVICE), "copy dl");
CheckAcl(aclrtMemcpy(d.get(), dataBytes, diagonal.data(), dataBytes, ACL_MEMCPY_HOST_TO_DEVICE), "copy d");
CheckAcl(aclrtMemcpy(du.get(), dataBytes, upper.data(), dataBytes, ACL_MEMCPY_HOST_TO_DEVICE), "copy du");
CheckAcl(aclrtMemcpy(b.get(), dataBytes, rhs.data(), dataBytes, ACL_MEMCPY_HOST_TO_DEVICE), "copy B");
size_t bytes = 0;
CheckSparse(aclsparseCgtsv2_bufferSizeExt(handle.get(), 3, 1,
static_cast<const Complex *>(dl.get()), static_cast<const Complex *>(d.get()),
static_cast<const Complex *>(du.get()), static_cast<const Complex *>(b.get()), 3, &bytes), "bufferSizeExt");
if (bytes == 0 || bytes > std::numeric_limits<size_t>::max() - 127U) {
throw std::runtime_error("invalid workspace size");
}
auto backing = Allocate(bytes + 127U, ctx.Stream());
const auto base = reinterpret_cast<uintptr_t>(backing.get());
void *workspace = reinterpret_cast<void *>((base + 127U) & ~uintptr_t(127U));
CheckSparse(aclsparseCgtsv2(handle.get(), 3, 1,
static_cast<const Complex *>(dl.get()), static_cast<const Complex *>(d.get()),
static_cast<const Complex *>(du.get()), static_cast<Complex *>(b.get()), 3, workspace), "aclsparseCgtsv2");
CheckAcl(aclrtSynchronizeStream(ctx.Stream()), "aclrtSynchronizeStream");
std::array<Complex, 3> result{};
CheckAcl(aclrtMemcpy(result.data(), dataBytes, b.get(), dataBytes, ACL_MEMCPY_DEVICE_TO_HOST), "copy result");
for (size_t i = 0; i < result.size(); ++i) {
if (!std::isfinite(result[i].x) || !std::isfinite(result[i].y) ||
std::abs(result[i].x - static_cast<float>(i + 1)) > 1e-5f || std::abs(result[i].y) > 1e-5f) {
throw std::runtime_error("unexpected solution");
}
std::printf("result[%zu] = (%.6f, %.6f)\n", i, result[i].x, result[i].y == 0 ? 0.0f : result[i].y);
}
}
int main()
{
try {
AclContext ctx(0);
ctx.Init();
RunExample(ctx);
return 0;
} catch (const std::exception &error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
}
The expected output is as follows:
result[0] = (1.000000, 0.000000)
result[1] = (2.000000, 0.000000)
result[2] = (3.000000, 0.000000)
aclsparseCgtsv2_bufferSizeExt
Product support
The support is the same as that of the execution interface; Atlas A2 products and Atlas A3 products are supported.
Function prototype
aclsparseStatus_t aclsparseCgtsv2_bufferSizeExt(aclsparseHandle_t handle,
int m, int n, const aclsparseComplex_t *dl, const aclsparseComplex_t *d,
const aclsparseComplex_t *du, const aclsparseComplex_t *B, int ldb,
size_t *pBufferSizeInBytes)
Parameter description
| Parameter | Input/Output | Parameter type | Description |
|---|---|---|---|
| handle | Input | aclsparseHandle_t | Valid library handle, Host memory |
| m | Input | int | Number of rows of the system, m>=3, Host memory |
| n | Input | int | Number of RHS columns, n>=0, Host memory |
| dl | Input | const aclsparseComplex_t* | m subdiagonal values, Device memory |
| d | Input | const aclsparseComplex_t* | m main diagonal values, Device memory |
| du | Input | const aclsparseComplex_t* | m superdiagonal values, Device memory |
| B | Input | const aclsparseComplex_t* | Column-major RHS, Device memory |
| ldb | Input | int | Physical column stride, ldb>=m, Host memory |
| pBufferSizeInBytes | Output | size_t* | Non-null output pointer for the number of bytes, Host memory |
Constraints
The input constraints are the same as those of the execution interface; pBufferSizeInBytes cannot be null.
A valid n=0 returns 0; a non-empty call retains the checks that dl/d/du/B are non-null and that the address span is representable according to section 2.4 of the task book.
The query does not read device inputs, does not allocate device memory, and does not launch a kernel.
aclsparseGetStream only validates the handle signature, allows a null stream value (default stream), and neither creates nor synchronizes a stream.
The caller must re-query the capacity according to the current library and cannot hard-code a historical capacity.
Invocation example
The complete example of the preceding interface first calls this interface to obtain bytes, then allocates and aligns the workspace, and finally performs the solve.
The two interfaces share this example and its expected output, and no second set of ACL resources needs to be initialized separately; the returned workspace capacity is determined by the current implementation and cannot be hard-coded.
Implementation notes
Common entry and architecture backends
cgtsv2_api.cpp unifies the two public C entry points and the checks of size, handle, pointer, address span, and workspace alignment.
cgtsv2_backend.h declares the internal Cgtsv2WorkspaceBytes and Cgtsv2Dispatch hooks.
arch22/cgtsv2_host.cpp is only responsible for the workspace of this architecture, UB admission, and kernel dispatch.
arch35/cgtsv2_host.cpp connects to the same set of internal hooks, independently queries the bounded RHS slot workspace, and dispatches arch35 kernels.
The two architectures reuse the upstream aclsparseComplex_t (the x/y alias of aclsparseComplex) and keep the common layout of FP32, 8 bytes, and float alignment for both groups.
arch22 numerical and memory paths
The generic finite-input path represents intermediate values with high and low FP32 mantissas and separate int64 exponents for the real and imaginary parts, reducing intermediate overflow.
The original B is retained until the final conversion; the per-column working arrays are reused by the solve and the residual correction on the original equations, and the workspace is O(m).
For fewer than 1024 rows, the UB factorization consists of four groups of complex factors plus a uint32 pivot, 36 bytes per row;
after the solve adds a group of RHS, it is 44 bytes, and the arrays are aligned to 32-byte boundaries.
Host and Device share the constants in arch22/cgtsv2_tiling_data.h; admission additionally reserves 16 KiB for TPipe/compiler use.
This reservation is a conservative scheduling budget, not the hardware capacity. The unreachable tiled direct-solve branch has been removed.
Misaligned physical write boundaries use conservative single-writer scheduling; the scalar GM fallback is written by one core.
The fast path depends only on the actual sizes, matrix properties, and input ranges, and does not depend on case numbers or seeds.
Jacobi certification and residual correction
Large systems require 1<=maxComp(d)<=8, RHS components that are finite with an absolute value not exceeding 16, and row-wise
maxComp(d)>1.351352*offBound. offBound conservatively estimates the sum of complex moduli using a four-segment linear chord of sqrt(1+t*t), round-up constants,
and an FP32 safety margin, and the certified contraction rate is less than 0.74.
The algorithm first performs 40 iterations with zero initial values, computes the compensated residual using the original FP32 A/B, and then performs 40 iterations to obtain the correction and adds it back to the initial solution.
The truncation bound under exact arithmetic is 0.74^80*16*sqrt(2)/(1-0.74)<3.01e-9; FP32 rounding is separately checked by the compensated residual and boundary regression checks.
The dependency radius covers at most 39+1+39=79 rows, and an 80-row original-B halo is retained.
For aligned large single RHS, the prepare kernel publishes a snapshot of the original B, and each core exclusively owns a 512-row center tile; other qualified calls are scheduled by whole RHS columns.
On certification failure (including non-finite RHS), the algorithm falls back to expanded; small-size direct retains independent admission conditions.
Testing notes
The in-repo tests reside in test/cgtsv2/ and reuse the GTest/CSV, ACL RAII, and memory check facilities;
for the differences in build, coverage, and task-specific comparators, see Testing notes.
Official acceptance uses the original task package and its original comparators, independent of the in-repo regression; this document does not list the out-of-repo acceptance counts as in-repo cases.
arch35 numerical and memory paths
Ascend 950PR&950DT products use twofold FP32 complex solving with adjacent partial pivoting, and the real and imaginary parts keep independent exponents. Inputs that satisfy the device-side strong diagonal dominance and numerical range thresholds use shared-coefficient PCR, and other inputs use the extended-range generic path. Internal computation still uses the real/imag representation, and the x/y components of public data are read and written in the same byte order.
The workspace for non-empty RHS is 128 + align_up(96*m*min(n,128),128) bytes, defined in
arch35/cgtsv2_workspace.h; when there are more than 128 columns, bounded slots are reused. The capacity follows the value queried from the current dynamic library.
The input coefficients are read-only, B is updated in place, padding is retained, and a valid n=0 dispatches no kernel.
The dispatch chain entry clears stale thread errors, and the thread Runtime error is checked immediately after each kernel dispatch; on failure,
subsequent dispatches stop and ACL_SPARSE_STATUS_EXECUTION_FAILED is returned, and the log records the stage, error code, dimensions, and stream.
The interface remains asynchronous, and Device execution errors are checked when the caller synchronizes the stream. Tasks already submitted before a mid-way failure may still execute,
and you must still synchronize before releasing or reusing data and the workspace.
The arch35 implementation is based on the official task book of Ascend 950PR&950DT products.
Build and run example: bash build.sh --soc=ascend950 --ops=cgtsv2 --run --device=0.