Build and Run Sample
Prerequisites
- Ensure that the basic environment has been set up, including the NPU driver and firmware and the CANN software packages (toolkit + ops). For environment setup, see Environment deployment.
- The
aclsparseSnnzexample in this document applies only to the Ascend 950PR&950DT products: this interface currently has only an arch35 implementation, and arch22 has no corresponding implementation. The fact thatbuild.shsupports a certain--socvalue does not mean that the platform implements all interfaces. - On the Atlas A2 products and Atlas A3 products, refer to the in-repo SpMV tests and run with the target SOC specified at the repository root respectively:
- Atlas A2 products:
bash build.sh --soc=ascend910b --ops=spmv --run - Atlas A3 products:
bash build.sh --soc=ascend910_93 --ops=spmv --run
- Atlas A2 products:
Step 1: Build and install ops-sparse
Before building, complete Environment deployment, including downloading the source code, installing basic dependencies, and configuring the CANN environment variables.
-
Build to generate the run installation package.
Taking the Ascend 950PR&950DT products as an example, run the following in the ops-sparse source root directory:
bash build.sh --pkg --soc=ascend950-
The
--socparameter must match the chip model of the running device. Supported SOC values:ascend910b,ascend910_93,ascend950, andascend310p. -
If unspecified, Release is the default. When debugging kernels, you can switch to Debug through an environment variable:
CMAKE_BUILD_TYPE=Debug bash build.sh --pkg --soc=ascend950Passing
-DCMAKE_BUILD_TYPE=Debugwhen invoking CMake directly has the same effect.
After a successful build, the installation package is generated in the
build_out/directory, with a file name likecann-950-ops-sparse-<cann_version>_linux-<arch>.run.${cann_version}: denotes the version of the ops-sparse run package, taken fromOPS_SPARSE_RUN_VERSIONin cmake/version.cmake.${arch}: denotes the CPU architecture, such asaarch64andx86_64.
-
-
Install the run package.
# Grant execute permission chmod +x build_out/cann-950-ops-sparse-*.run # Install to ${install_path}/cann ./build_out/cann-950-ops-sparse-*.run --install --quiet --install-path="${install_path}"- Before running, set
${install_path}to a non-empty installation root directory without spaces, for exampleinstall_path=/opt/Ascend. - The installer appends
cann/under that root directory: root installs to/usr/local/Ascend/cann/by default, and a regular user installs to${HOME}/Ascend/cann/by default. When--install-pathis omitted, the installer uses the same default root directory.
After installation, the header files and library files of ops-sparse are located at:
${install_path}/cann/ ├── include/ │ ├── cann_ops_sparse.h │ └── cann_ops_sparseLt.h └── lib64/ ├── libops_sparse.so └── libops_sparseLt.so - Before running, set
Step 2: Prepare the example code
This chapter uses the scenario where the development and runtime environments are co-located as an example — that is, code development and execution happen on the same machine. The following aclsparseSnnz example applies only to the Ascend 950PR&950DT products; the libops_sparse.so on the Atlas A2 products and Atlas A3 products does not contain this interface. To invoke other computation interfaces, modify the API invocation script (*.cpp) and the build script (CMakeLists.txt) according to the actual situation.
-
Create the project directory.
mkdir -p ops-sparse-example cd ops-sparse-example -
Create the code file
test_snnz.cppin the project directory.vi test_snnz.cppPaste the following code into the file and save it:
#include <cstdio> #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 aclsparseSnnzTest(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. Set the PointerMode (location of the nnzTotalDevHostPtr memory: HOST mode means host memory) sparseRet = aclsparseSetPointerMode(static_cast<aclsparseHandle_t>(handlePtr.get()), ACL_SPARSE_POINTER_MODE_HOST); CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSetPointerMode failed. ERROR: %d\n", sparseRet); return sparseRet); // 3. Prepare the host data (column-major 3x3 matrix) // Matrix contents: // [1.0 0.0 3.0] // [0.0 0.0 4.0] // [2.0 0.0 0.0] int m = 3, n = 3, lda = 3; std::vector<float> hA(static_cast<size_t>(lda) * n, 0.0f); hA[0 * lda + 0] = 1.0f; // A[0][0] hA[0 * lda + 2] = 2.0f; // A[2][0] hA[2 * lda + 0] = 3.0f; // A[0][2] hA[2 * lda + 1] = 4.0f; // A[1][2] // 4. Allocate device memory and copy the data void* rawMemA = nullptr; auto aclRet = aclrtMalloc(&rawMemA, static_cast<size_t>(lda) * n * sizeof(float), ACL_MEM_MALLOC_HUGE_FIRST); CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtMalloc for A failed. ERROR: %d\n", aclRet); return aclRet); std::unique_ptr<void, aclError (*)(void*)> dA(rawMemA, aclrtFree); aclRet = aclrtMemcpy(dA.get(), static_cast<size_t>(lda) * n * sizeof(float), hA.data(), static_cast<size_t>(lda) * n * sizeof(float), ACL_MEMCPY_HOST_TO_DEVICE); CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy for A failed. ERROR: %d\n", aclRet); return aclRet); void* rawMemNnzPerRow = nullptr; aclRet = aclrtMalloc(&rawMemNnzPerRow, m * sizeof(int), ACL_MEM_MALLOC_HUGE_FIRST); CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtMalloc for nnzPerRow failed. ERROR: %d\n", aclRet); return aclRet); std::unique_ptr<void, aclError (*)(void*)> dNnzPerRow(rawMemNnzPerRow, aclrtFree); int hNnzTotal = 0; // 5. Create the MatDescr aclsparseMatDescr_t matDescr = nullptr; sparseRet = aclsparseCreateMatDescr(&matDescr); CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreateMatDescr failed. ERROR: %d\n", sparseRet); return sparseRet); aclsparseSetMatType(matDescr, ACL_SPARSE_MATRIX_TYPE_GENERAL); aclsparseSetMatIndexBase(matDescr, ACL_SPARSE_INDEX_BASE_ZERO); // 6. Invoke aclsparseSnnz (counting by row) aclsparseDirection_t dirA = ACL_SPARSE_DIRECTION_ROW; sparseRet = aclsparseSnnz( static_cast<aclsparseHandle_t>(handlePtr.get()), dirA, m, n, matDescr, static_cast<const float*>(dA.get()), lda, static_cast<int*>(dNnzPerRow.get()), &hNnzTotal); CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSnnz failed. ERROR: %d\n", sparseRet); aclsparseDestroyMatDescr(matDescr); return sparseRet); // 7. Synchronize and wait for the task to finish aclRet = aclrtSynchronizeStream(stream); CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", aclRet); aclsparseDestroyMatDescr(matDescr); return aclRet); // 8. Copy the results from the device back to the host and print them std::vector<int> hNnzPerRow(m, 0); aclRet = aclrtMemcpy(hNnzPerRow.data(), m * sizeof(int), dNnzPerRow.get(), m * sizeof(int), ACL_MEMCPY_DEVICE_TO_HOST); CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("copy nnzPerRow from device to host failed. ERROR: %d\n", aclRet); aclsparseDestroyMatDescr(matDescr); return aclRet); for (int i = 0; i < m; i++) { LOG_PRINT("nnzPerRow[%d] is: %d\n", i, hNnzPerRow[i]); } LOG_PRINT("nnzTotal is: %d\n", hNnzTotal); // 9. Clean up the MatDescr aclsparseDestroyMatDescr(matDescr); return ACL_SUCCESS; } int main() { AclContext ctx(0); auto ret = ctx.Init(); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = aclsparseSnnzTest(ctx); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclsparseSnnzTest failed. ERROR: %d\n", ret); return ret); return 0; } -
Create the build script
CMakeLists.txtin the project directory.vi CMakeLists.txtPaste the following content into the file and save it (nothing needs to be modified; paths are obtained automatically from environment variables):
cmake_minimum_required(VERSION 3.16) project(ACLSPARSE_EXAMPLE) add_compile_options(-std=c++11) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "./bin") set(CMAKE_CXX_FLAGS_DEBUG "-fPIC -O0 -g -Wall") set(CMAKE_CXX_FLAGS_RELEASE "-fPIC -O2 -Wall") add_executable(opapi_test test_snnz.cpp) # CANN toolkit path; the environment variable is read with priority, and the default path is used if unset if(NOT "$ENV{ASCEND_HOME_PATH}" STREQUAL "") set(ASCEND_PATH $ENV{ASCEND_HOME_PATH}) else() set(ASCEND_PATH "/usr/local/Ascend/cann") endif() # ops-sparse path; if it differs from the CANN installation path, specify it through the OPS_SPARSE_PATH environment variable if(NOT "$ENV{OPS_SPARSE_PATH}" STREQUAL "") set(OPS_SPARSE_PATH $ENV{OPS_SPARSE_PATH}) else() set(OPS_SPARSE_PATH "${ASCEND_PATH}") endif() include_directories( ${OPS_SPARSE_PATH}/include ${ASCEND_PATH}/include ${ASCEND_PATH}/include/aclnn ) target_link_libraries(opapi_test PRIVATE ${ASCEND_PATH}/lib64/libascendcl.so ${OPS_SPARSE_PATH}/lib64/libops_sparse.so) install(TARGETS opapi_test DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) -
Configure the path environment variables.
CMakeLists.txt obtains the paths automatically from environment variables, so no manual editing is needed. Run the following commands in the current terminal to set the environment variables:
# Configure the CANN environment variables (ASCEND_HOME_PATH is set automatically after sourcing set_env.sh) source /usr/local/Ascend/cann/set_env.sh # For a custom-path installation, replace with: # source ${install_path}/cann/set_env.sh # If the ops-sparse installation path differs from CANN, specify the path at build time, and libops_sparse.so must also be findable at runtime # export OPS_SPARSE_PATH=/your/ops-sparse/install/path # export LD_LIBRARY_PATH="${OPS_SPARSE_PATH}/lib64${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"Note:
source set_env.shautomatically sets theASCEND_HOME_PATHenvironment variable, which CMakeLists.txt uses to locate the CANN header and library files.- If the ops-sparse run package has been installed under the CANN directory (see Install the run package),
OPS_SPARSE_PATHdefaults to the same value asASCEND_HOME_PATHand no extra setting is needed. - When customizing
OPS_SPARSE_PATH, also setLD_LIBRARY_PATHabove; this example builds with-DCMAKE_SKIP_RPATH=TRUE, so the executable does not record the custom library directory.
Step 3: Build and run
The following steps are all executed in the project directory created in Step 2.
If the linking reports undefined reference to aclsparseSnnz, check whether the current device belongs to the Ascend 950PR&950DT products and whether OPS_SPARSE_PATH points to the ops-sparse installation directory containing this interface's implementation; arch22 does not support this example.
-
Create the build directory and build.
mkdir -p build cd build cmake ../ -DCMAKE_CXX_COMPILER=g++ -DCMAKE_SKIP_RPATH=TRUE makeAfter a successful build, the executable
opapi_testis generated in thebuild/bin/directory. -
Run.
cd bin ./opapi_testTaking the aclsparseSnnz interface (3x3 matrix, counted by row) as an example, the expected output is as follows:
nnzPerRow[0] is: 2 nnzPerRow[1] is: 1 nnzPerRow[2] is: 1 nnzTotal is: 4 -
If the execution result reports an error or the expected result does not appear, use the
aclGetRecentErrMsginterface to obtain the detailed error information. Example:ret = aclsparseSnnz(handle, dirA, m, n, matDescr, A, lda, nnzPerRow, &nnzTotal); if (ret != ACL_SPARSE_STATUS_SUCCESS) { printf("aclsparseSnnz failed. ERROR: %d\n[ERROR msg]%s\n", ret, aclGetRecentErrMsg()); return ret; }