戰(zhàn):aclnnLtTensor 與 aclnnInplaceLtTensor 全解析)
算子庫(kù)人工智能CANN【免費(fèi)下載鏈接】ops-math本項(xiàng)目是CANN提供的數(shù)學(xué)類基礎(chǔ)計(jì)算算子庫(kù)實(shí)現(xiàn)網(wǎng)絡(luò)在NPU上加速計(jì)算。項(xiàng)目地址https://gitcode.com/cann/ops-math點(diǎn)擊查看免費(fèi)下載導(dǎo)讀本文以 CANN ops-math 倉(cāng)庫(kù)中 Less小于比較算子的兩個(gè)單算子 API 接口為核心系統(tǒng)講解aclnnLtTensor與aclnnInplaceLtTensor的產(chǎn)品支持情況、功能語(yǔ)義、兩段式調(diào)用范式、完整參數(shù)約束與錯(cuò)誤碼并結(jié)合倉(cāng)庫(kù)源碼剖析其底層計(jì)算流程Contiguous → Cast → Less → ViewCopy、平臺(tái)差異與 kernel 實(shí)現(xiàn)原理。讀完本文你將掌握在 NPU 上通過(guò) aclnn 接口完成逐元素小于比較并輸出 Bool 張量的完整編碼能力并理解普通輸出與原地inplace輸出的工程取舍。產(chǎn)品支持情況根據(jù) math/less/docs/aclnnLtTensoraclnnInplaceLtTensor.md 與 math/less/README.md 的記載Less 算子及配套的兩個(gè) aclnn 接口支持情況如下產(chǎn)品是否支持Ascend 950PR / Ascend 950DT支持Atlas A3 訓(xùn)練系列產(chǎn)品 / Atlas A3 推理系列產(chǎn)品支持Atlas A2 訓(xùn)練系列產(chǎn)品 / Atlas A2 推理系列產(chǎn)品支持Atlas 200I/500 A2 推理產(chǎn)品支持Atlas 推理系列產(chǎn)品不支持Atlas 訓(xùn)練系列產(chǎn)品支持注意在Atlas 200I/500 A2 推理產(chǎn)品與Atlas 訓(xùn)練系列產(chǎn)品上aclnnLtTensor/aclnnInplaceLtTensor不支持BFLOAT16數(shù)據(jù)類型見原文檔約束說(shuō)明中 npu910,310b 標(biāo)記段。功能說(shuō)明aclnnLtTensor與aclnnInplaceLtTensor實(shí)現(xiàn)相同的功能判斷輸入self中的每個(gè)元素是否小于輸入other中的元素返回一個(gè) Bool 類型的 Tensor。計(jì)算公式為$$ out_i (self_i other_i) ? [True] : [False] $$即當(dāng)self_i嚴(yán)格小于other_i時(shí)輸出True否則輸出False。這一語(yǔ)義與 PyTorch 的torch.lt一致常用于掩碼生成、條件篩選、比較統(tǒng)計(jì)等場(chǎng)景。兩個(gè)接口的功能區(qū)別在于結(jié)果的存放位置aclnnLtTensor需新建一個(gè)輸出張量對(duì)象out存儲(chǔ)計(jì)算結(jié)果輸入self保持不變aclnnInplaceLtTensor無(wú)需新建輸出張量對(duì)象直接在輸入張量selfRef的內(nèi)存中原地寫入計(jì)算結(jié)果節(jié)省一份輸出內(nèi)存。在倉(cāng)庫(kù)中該算子的完整實(shí)現(xiàn)分布于 math/less 目錄op_api提供 aclnn 接口層、op_host提供算子定義與 tiling、op_kernel提供 AscendC kernel 實(shí)現(xiàn)、op_kernel_aicpu提供 AICPU 兜底實(shí)現(xiàn)、framework提供 TF 插件適配。兩段式接口與函數(shù)原型aclnnLtTensor和aclnnInplaceLtTensor均為兩段式接口詳細(xì)范式見 兩段式接口必須先調(diào)用xxxGetWorkspaceSize第一段接口獲取計(jì)算所需的workspace 大小與包含算子計(jì)算流程的op 執(zhí)行器executor再依據(jù) workspaceSize 在 Device 側(cè)申請(qǐng)內(nèi)存后調(diào)用第二段接口執(zhí)行計(jì)算。說(shuō)明workspace 是指除輸入/輸出外算子在 NPU 上完成計(jì)算所需的臨時(shí)內(nèi)存。第二段接口如aclnnLtTensor不能重復(fù)調(diào)用否則會(huì)出現(xiàn)異常。四個(gè)接口的原型如下aclnnStatus aclnnLtTensorGetWorkspaceSize( const aclTensor* self, const aclTensor* other, aclTensor* out, uint64_t* workspaceSize, aclOpExecutor** executor)aclnnStatus aclnnLtTensor( void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream)aclnnStatus aclnnInplaceLtTensorGetWorkspaceSize( const aclTensor* selfRef, const aclTensor* other, uint64_t* workspaceSize, aclOpExecutor** executor)aclnnStatus aclnnInplaceLtTensor( void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream)接口聲明位于 math/less/op_api/aclnn_lt_tensor.h實(shí)現(xiàn)位于 math/less/op_api/aclnn_lt_tensor.cpp調(diào)用時(shí)需要包含頭文件aclnnop/aclnn_lt_tensor.h。aclnnLtTensorGetWorkspaceSize 參數(shù)說(shuō)明參數(shù)名輸入/輸出描述使用說(shuō)明數(shù)據(jù)類型數(shù)據(jù)格式維度(shape)非連續(xù)TensorselfaclTensor*輸入輸入張量數(shù)據(jù)類型與 other 需滿足互推導(dǎo)關(guān)系shape 需與 other 滿足 broadcast 關(guān)系FLOAT、FLOAT16、BFLOAT16、INT32、UINT32、INT64、UINT64、INT16、UINT16、INT8、UINT8、DOUBLE、BOOLND0-8√otheraclTensor*輸入輸入張量數(shù)據(jù)類型與 self 需滿足互推導(dǎo)關(guān)系shape 需與 self 滿足 broadcast 關(guān)系FLOAT、FLOAT16、BFLOAT16、INT32、UINT32、INT64、UINT64、INT16、UINT16、INT8、UINT8、DOUBLE、BOOL---outaclTensor*輸出輸出張量shape 與 self、other 廣播之后的 shape 一致數(shù)據(jù)類型要求為 BOOL 可轉(zhuǎn)換的數(shù)據(jù)類型參見互轉(zhuǎn)換關(guān)系FLOAT、FLOAT16、BFLOAT16、INT32、UINT32、INT64、UINT64、INT16、UINT16、INT8、UINT8、DOUBLE、BOOL、COMPLEX64、COMPLEX128ND0-8√workspaceSizeuint64_t*輸出返回需要在 Device 側(cè)申請(qǐng)的 workspace 大小-----executoraclOpExecutor**輸出返回 op 執(zhí)行器包含了算子計(jì)算流程-----約束Atlas 200I/500 A2 推理產(chǎn)品、Atlas 訓(xùn)練系列產(chǎn)品不支持 BFLOAT16 數(shù)據(jù)類型。返回值與錯(cuò)誤碼aclnnLtTensorGetWorkspaceSize返回aclnnStatus狀態(tài)碼完整定義見 aclnn返回碼。第一段接口完成入?yún)⑿r?yàn)出現(xiàn)以下場(chǎng)景時(shí)報(bào)錯(cuò)返回值錯(cuò)誤碼描述ACLNN_ERR_PARAM_NULLPTR161001傳入的 self、other 或 out 是空指針ACLNN_ERR_PARAM_INVALID161002self、other 或 out 的數(shù)據(jù)類型不在支持的范圍之內(nèi)ACLNN_ERR_PARAM_INVALID161002self、other 或 out 的維度大于 8ACLNN_ERR_PARAM_INVALID161002self 和 other 的數(shù)據(jù)類型無(wú)法進(jìn)行推導(dǎo)ACLNN_ERR_PARAM_INVALID161002self 和 other 的 shape 無(wú)法進(jìn)行 broadcastACLNN_ERR_PARAM_INVALID161002out 的 shape 與 broadcast 后的 shape 不一致在 math/less/op_api/aclnn_lt_tensor.cpp 的CheckParams中可以看到校驗(yàn)順序與上述錯(cuò)誤碼一一對(duì)應(yīng)先做空指針檢查CheckNotNull返回ACLNN_ERR_PARAM_NULLPTR再檢查數(shù)據(jù)類型是否在支持列表內(nèi)CheckDtypeValid、類型能否互推導(dǎo)CheckPromoteType、shape 能否 broadcast 且與 out 一致CheckShape其余全部歸入ACLNN_ERR_PARAM_INVALID。aclnnLtTensor 參數(shù)說(shuō)明參數(shù)名輸入/輸出描述workspace輸入在 Device 側(cè)申請(qǐng)的 workspace 內(nèi)存地址workspaceSize輸入在 Device 側(cè)申請(qǐng)的 workspace 大小由第一段接口 aclnnLtTensorGetWorkspaceSize 獲取executor輸入op 執(zhí)行器包含了算子計(jì)算流程stream輸入指定執(zhí)行任務(wù)的 StreamaclnnInplaceLtTensorGetWorkspaceSize 參數(shù)說(shuō)明參數(shù)名輸入/輸出描述使用說(shuō)明數(shù)據(jù)類型數(shù)據(jù)格式維度(shape)非連續(xù)TensorselfRefaclTensor*輸入|輸出輸入|輸出張量數(shù)據(jù)類型與 other 需滿足互推導(dǎo)關(guān)系shape 需與 other 滿足 broadcast 關(guān)系broadcast 后的 shape 需與 selfRef 的 shape 一致FLOAT、FLOAT16、BFLOAT16、INT32、UINT32、INT64、UINT64、INT16、UINT16、INT8、UINT8、DOUBLE、BOOLND0-8√otheraclTensor*輸入輸入張量數(shù)據(jù)類型與 selfRef 需滿足互推導(dǎo)關(guān)系shape 需與 self 滿足 broadcast 關(guān)系broadcast 后的 shape 需與 selfRef 的 shape 一致FLOAT、FLOAT16、BFLOAT16、INT32、UINT32、INT64、UINT64、INT16、UINT16、INT8、UINT8、DOUBLE、BOOL---workspaceSizeuint64_t*輸出返回需要在 Device 側(cè)申請(qǐng)的 workspace 大小-----executoraclOpExecutor**輸出返回 op 執(zhí)行器包含了算子計(jì)算流程-----約束Atlas 200I/500 A2 推理產(chǎn)品、Atlas 訓(xùn)練系列產(chǎn)品不支持 BFLOAT16 數(shù)據(jù)類型。返回值與錯(cuò)誤碼返回值錯(cuò)誤碼描述ACLNN_ERR_PARAM_NULLPTR161001傳入的 selfRef、other 是空指針ACLNN_ERR_PARAM_INVALID161002selfRef 和 other 的數(shù)據(jù)類型不在支持的范圍之內(nèi)ACLNN_ERR_PARAM_INVALID161002selfRef 和 other 的數(shù)據(jù)類型無(wú)法進(jìn)行推導(dǎo)ACLNN_ERR_PARAM_INVALID161002selfRef 和 other 的 shape 無(wú)法做 broadcastACLNN_ERR_PARAM_INVALID161002selfRef 和 other 做 broadcast 后的 shape 不等于 selfRef 的 shapeACLNN_ERR_PARAM_INVALID161002selfRef、other 的維度大于 8注意原地版本的差異點(diǎn)由于結(jié)果寫回selfRef因此要求廣播后的 shape 必須與 selfRef 的 shape 相等否則無(wú)法原地寫回這是與普通版本最核心的語(yǔ)義區(qū)別。aclnnInplaceLtTensor 參數(shù)說(shuō)明參數(shù)名輸入/輸出描述workspace輸入在 Device 側(cè)申請(qǐng)的 workspace 內(nèi)存地址workspaceSize輸入在 Device 側(cè)申請(qǐng)的 workspace 大小由第一段接口 aclnnInplaceLtTensorGetWorkspaceSize 獲取executor輸入op 執(zhí)行器包含了算子計(jì)算流程stream輸入指定執(zhí)行任務(wù)的 Stream約束說(shuō)明確定性計(jì)算aclnnLtTensor與aclnnInplaceLtTensor默認(rèn)確定性實(shí)現(xiàn)。即同一輸入在相同硬件與軟件環(huán)境下多次執(zhí)行結(jié)果完全一致不會(huì)引入并行歸約順序?qū)е碌姆谴_定誤差可放心用于需要復(fù)現(xiàn)結(jié)果的訓(xùn)練與調(diào)試場(chǎng)景更詳細(xì)的背景可參考 確定性計(jì)算說(shuō)明。調(diào)用示例示例代碼僅供參考完整編譯與執(zhí)行流程請(qǐng)參考 編譯與運(yùn)行樣例。兩個(gè)完整可運(yùn)行的示例同樣保存在倉(cāng)庫(kù)中math/less/examples/test_aclnn_lt_tensor.cpp 與 math/less/examples/test_aclnn_inplace_lt_tensor.cpp。aclnnLtTensor 示例代碼#include iostream #include vector #include acl/acl.h #include aclnnop/aclnn_lt_tensor.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::vectorint64_t shape) { int64_t shapeSize 1; for (auto i : shape) { shapeSize * i; } return shapeSize; } int Init(int32_t deviceId, aclrtStream* stream) { // 固定寫法資源初始化 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); aclFinalize(); return ret); ret aclrtCreateStream(stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtCreateStream failed. ERROR: %d\n, ret); aclrtResetDevice(deviceId); aclFinalize(); return ret); return 0; } template typename T int CreateAclTensor(const std::vectorT hostData, const std::vectorint64_t shape, void** deviceAddr, aclDataType dataType, aclTensor** tensor) { auto size GetShapeSize(shape) * sizeof(T); // 調(diào)用aclrtMalloc申請(qǐng)device側(cè)內(nèi)存 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); // 調(diào)用aclrtMemcpy將host側(cè)數(shù)據(jù)拷貝到device側(cè)內(nèi)存上 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); // 計(jì)算連續(xù)tensor的strides std::vectorint64_t strides(shape.size(), 1); for (int64_t i shape.size() - 2; i 0; i--) { strides[i] shape[i 1] * strides[i 1]; } // 調(diào)用aclCreateTensor接口創(chuàng)建aclTensor *tensor aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(), *deviceAddr); return 0; } struct LtTensorData { std::vectorint64_t selfShape {4, 2}; std::vectorint64_t otherShape {4, 2}; std::vectorint64_t outShape {4, 2}; void* selfDeviceAddr nullptr; void* otherDeviceAddr nullptr; void* outDeviceAddr nullptr; aclTensor* self nullptr; aclTensor* other nullptr; aclTensor* out nullptr; std::vectordouble selfHostData {0, 1, 2, 3, 4, 5, 6, 7}; std::vectordouble otherHostData {5, 5, 5, 5, 5, 5, 5, 5}; std::vectordouble outHostData {0, 0, 0, 0, 0, 0, 0, 0}; void* workspaceAddr nullptr; uint64_t workspaceSize 0; }; int CreateInputAndOutputTensors(LtTensorData data) { auto ret 0; // 創(chuàng)建self aclTensor ret CreateAclTensor(data.selfHostData, data.selfShape, data.selfDeviceAddr, aclDataType::ACL_DOUBLE, data.self); CHECK_RET(ret ACL_SUCCESS, return ret); // 創(chuàng)建other aclTensor ret CreateAclTensor(data.otherHostData, data.otherShape, data.otherDeviceAddr, aclDataType::ACL_DOUBLE, data.other); CHECK_RET(ret ACL_SUCCESS, return ret); // 創(chuàng)建out aclTensor ret CreateAclTensor(data.outHostData, data.outShape, data.outDeviceAddr, aclDataType::ACL_DOUBLE, data.out); CHECK_RET(ret ACL_SUCCESS, return ret); return ret; } int ExecuteLtTensorComputation(aclrtStream stream, LtTensorData data) { auto ret 0; aclOpExecutor* executor; // 調(diào)用aclnnLtTensor第一段接口 ret aclnnLtTensorGetWorkspaceSize(data.self, data.other, data.out, data.workspaceSize, executor); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclnnLtTensorGetWorkspaceSize failed. ERROR: %d\n, ret); return ret); // 根據(jù)第一段接口計(jì)算出的workspaceSize申請(qǐng)device內(nèi)存 data.workspaceAddr nullptr; if (data.workspaceSize 0) { ret aclrtMalloc(data.workspaceAddr, data.workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(allocate workspace failed. ERROR: %d\n, ret); return ret); } // 調(diào)用aclnnLtTensor第二段接口 ret aclnnLtTensor(data.workspaceAddr, data.workspaceSize, executor, stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclnnLtTensor failed. ERROR: %d\n, ret); return ret); // 同步等待任務(wù)執(zhí)行結(jié)束 ret aclrtSynchronizeStream(stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtSynchronizeStream failed. ERROR: %d\n, ret); return ret); return ret; } int ProcessAndPrintResults(const LtTensorData data) { auto ret 0; auto size GetShapeSize(data.outShape); std::vectordouble resultData(size, 0); ret aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), data.outDeviceAddr, 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 ret); for (int64_t i 0; i size; i) { LOG_PRINT(result[%ld] is: %lf\n, i, resultData[i]); } return ret; } void ReleaseResources(LtTensorData data) { // 釋放aclTensor和aclScalar aclDestroyTensor(data.self); aclDestroyTensor(data.other); aclDestroyTensor(data.out); // 釋放device資源 aclrtFree(data.selfDeviceAddr); aclrtFree(data.otherDeviceAddr); aclrtFree(data.outDeviceAddr); if (data.workspaceSize 0) { aclrtFree(data.workspaceAddr); } } int ExecuteLtTensorOperator(aclrtStream stream) { LtTensorData data; // 創(chuàng)建輸入和輸出張量 auto ret CreateInputAndOutputTensors(data); CHECK_RET(ret ACL_SUCCESS, return ret); // 執(zhí)行LtTensor算子操作 ret ExecuteLtTensorComputation(stream, data); CHECK_RET(ret ACL_SUCCESS, return ret); // 處理并打印結(jié)果 ret ProcessAndPrintResults(data); CHECK_RET(ret ACL_SUCCESS, return ret); // 釋放資源 ReleaseResources(data); return 0; } int main() { 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); // 執(zhí)行LtTensor操作 ret ExecuteLtTensorOperator(stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(ExecuteLtTensorOperator failed. ERROR: %d\n, ret); return ret); // 重置設(shè)備和終結(jié)ACL aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize(); return 0; }示例中self {0,1,2,3,4,5,6,7}、other {5,5,5,5,5,5,5,5}逐元素執(zhí)行比較后期望輸出前 5 個(gè)元素為True對(duì)應(yīng)數(shù)值 1.0后 3 個(gè)元素為False對(duì)應(yīng)數(shù)值 0.0。結(jié)果通過(guò)aclrtMemcpy(..., ACL_MEMCPY_DEVICE_TO_HOST)拷回 Host 側(cè)打印驗(yàn)證。aclnnInplaceLtTensor 示例代碼#include iostream #include vector #include acl/acl.h #include aclnnop/aclnn_lt_tensor.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::vectorint64_t shape) { int64_t shape_size 1; for (auto i : shape) { shape_size * i; } return shape_size; } int Init(int32_t deviceId, aclrtStream* stream) { // 固定寫法,資源初始化 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); aclFinalize(); return ret); ret aclrtCreateStream(stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtCreateStream failed. ERROR: %d\n, ret); aclrtResetDevice(deviceId); aclFinalize(); return ret); return 0; } templatetypename T int CreateAclTensor(const std::vectorT hostData, const std::vectorint64_t shape, void** deviceAddr, aclDataType dataType, aclTensor** tensor) { auto size GetShapeSize(shape) * sizeof(T); // 調(diào)用aclrtMalloc申請(qǐng)device側(cè)內(nèi)存 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); // 調(diào)用aclrtMemcpy將host側(cè)數(shù)據(jù)拷貝到device側(cè)內(nèi)存上 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); // 計(jì)算連續(xù)tensor的strides std::vectorint64_t strides(shape.size(), 1); for (int64_t i shape.size() - 2; i 0; i--) { strides[i] shape[i 1] * strides[i 1]; } // 調(diào)用aclCreateTensor接口創(chuàng)建aclTensor *tensor aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(), *deviceAddr); return 0; } int ExecuteInplaceLtTensorOperator(aclrtStream stream) { auto ret 0; std::vectorint64_t selfShape {4, 2}; std::vectorint64_t otherShape {4, 2}; void* selfDeviceAddr nullptr; void* otherDeviceAddr nullptr; aclTensor* self nullptr; aclTensor* other nullptr; std::vectordouble selfHostData {0, 1, 2, 3, 4, 5, 6, 7}; std::vectorint otherHostData {1, 1, 1, 1, 0, 0, 0, 0}; ret CreateAclTensor(selfHostData, selfShape, selfDeviceAddr, aclDataType::ACL_DOUBLE, self); CHECK_RET(ret ACL_SUCCESS, return ret); ret CreateAclTensor(otherHostData, otherShape, otherDeviceAddr, aclDataType::ACL_INT32, other); CHECK_RET(ret ACL_SUCCESS, return ret); uint64_t workspaceSize 0; aclOpExecutor* executor; ret aclnnInplaceLtTensorGetWorkspaceSize(self, other, workspaceSize, executor); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclnnInplaceLtTensorGetWorkspaceSize failed. ERROR: %d\n, ret); return ret); 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); } ret aclnnInplaceLtTensor(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclnnInplaceLtTensor failed. ERROR: %d\n, ret); return ret); ret aclrtSynchronizeStream(stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtSynchronizeStream failed. ERROR: %d\n, ret); return ret); auto size GetShapeSize(selfShape); std::vectordouble resultData(size, 0); ret aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), selfDeviceAddr, 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 ret); for (int64_t i 0; i size; i) { LOG_PRINT(result[%ld] is: %lf\n, i, resultData[i]); } aclDestroyTensor(self); aclDestroyTensor(other); aclrtFree(selfDeviceAddr); aclrtFree(otherDeviceAddr); if (workspaceSize 0) { aclrtFree(workspaceAddr); } return 0; } int main() { 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); // 執(zhí)行InplaceLtTensor操作 ret ExecuteInplaceLtTensorOperator(stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(ExecuteInplaceLtTensorOperator failed. ERROR: %d\n, ret); return ret); // 重置設(shè)備和終結(jié)ACL aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize(); return 0; }原地示例展示了兩個(gè)工程要點(diǎn)輸入可以是混合數(shù)據(jù)類型self為ACL_DOUBLE、other為ACL_INT32兩者滿足互推導(dǎo)關(guān)系f64 與 s32 推導(dǎo)為 f64由接口內(nèi)部完成隱式轉(zhuǎn)換無(wú)需用戶手動(dòng) Cast結(jié)果從self的 Device 地址讀取執(zhí)行完aclnnInplaceLtTensor后比較結(jié)果直接寫回self所在內(nèi)存因此只需從selfDeviceAddr拷回結(jié)果即可全程無(wú)需分配輸出張量。源碼級(jí)原理剖析接口層的完整計(jì)算流水線在 math/less/op_api/aclnn_lt_tensor.cpp 的注釋中完整計(jì)算流程被描述為self other | | \ / Contiguous(workspace_0) Contiguous(workspace_2) \ / Cast(workspace_1) Cast(workspace_3) \ / Less(workspace_4) | Cast(workspace_5) | ViewCopy | result對(duì)應(yīng)aclnnLtTensorGetWorkspaceSize的實(shí)現(xiàn)邏輯aclnn_lt_tensor.cpp空 Tensor 快速路徑若self或other為空 Tensor直接返回workspaceSize 0不構(gòu)造計(jì)算圖隱式類型提升先通過(guò)op::PromoteType或 A2 平臺(tái)上的op::BinaryOpTypePromote推導(dǎo)統(tǒng)一計(jì)算類型特別地若推導(dǎo)結(jié)果為DT_BOOL會(huì)提升為DT_UINT8aclnn_lt_tensor.cpp因?yàn)?BOOL 參與向量比較計(jì)算不直接、且 kernel 側(cè)統(tǒng)一按 uint8 語(yǔ)義處理布爾結(jié)果Contiguous Cast分別對(duì)self、other做l0op::Contiguous支持非連續(xù)張量輸入與l0op::Cast轉(zhuǎn)換為統(tǒng)一推導(dǎo)類型Less 核心計(jì)算調(diào)用l0op::Less完成逐元素比較產(chǎn)出 BOOL 結(jié)果Cast ViewCopy將 BOOL 結(jié)果 Cast 成out的目標(biāo)數(shù)據(jù)類型如示例中的 DOUBLE再通過(guò)l0op::ViewCopy拷貝到輸出張量從而兼容out為非連續(xù)張量的情況最后通過(guò)executor-GetWorkspaceSize()匯總整條流水線各階段workspace_0 至 workspace_5所需的臨時(shí)內(nèi)存總大小。Inplace 接口的實(shí)現(xiàn)本質(zhì)從 aclnn_lt_tensor.cpp 可以看出aclnnInplaceLtTensorGetWorkspaceSize的實(shí)現(xiàn)極為簡(jiǎn)潔aclnnStatus aclnnInplaceLtTensorGetWorkspaceSize(const aclTensor* selfRef, const aclTensor* other, uint64_t* workspaceSize, aclOpExecutor** executor) { auto out const_castaclTensor*(selfRef); return aclnnLtTensorGetWorkspaceSize(selfRef, other, out, workspaceSize, executor); }即原地版本只是將selfRef同時(shí)作為輸出out傳給普通版本計(jì)算完成后結(jié)果通過(guò) ViewCopy 寫回selfRef的內(nèi)存。這也解釋了為何原地版本要求broadcast 后的 shape 必須與 selfRef 的 shape 一致——輸出寫回的目標(biāo)地址容量是固定的。平臺(tái)相關(guān)的數(shù)據(jù)類型支持在 aclnn_lt_tensor.cpp 中輸入與輸出的數(shù)據(jù)類型支持列表按平臺(tái)區(qū)分ASCEND910Atlas 訓(xùn)練系列產(chǎn)品等輸入支持 FLOAT、INT32、INT64、FLOAT16、INT16、INT8、UINT8、DOUBLE、UINT32、UINT64、BOOL、UINT16不含 BFLOAT16ASCEND910B 及以上Atlas A2/A3、Ascend 950 等或 RegBase 架構(gòu)在上述基礎(chǔ)上額外支持 BFLOAT16輸出側(cè)還額外支持 COMPLEX64、COMPLEX128作為 BOOL 可轉(zhuǎn)換的目標(biāo)類型。這一差異正是原文檔中Atlas 訓(xùn)練系列產(chǎn)品、Atlas 200I/500 A2 推理產(chǎn)品不支持 BFLOAT16約束的代碼級(jí)來(lái)源由GetCurrentPlatformInfo().GetSocVersion()動(dòng)態(tài)判定。算子定義、InferShape 與 Tiling在算子定義層面math/less/op_host/less_def.cpp算子名為L(zhǎng)ess輸入為x1、x2輸出為y輸入數(shù)據(jù)類型支持 BF16、FLOAT16、FLOAT、INT8、UINT8、INT32、INT64、UINT64、BOOL、DOUBLE輸出固定為 BOOLAICore 配置開啟DynamicCompileStaticFlag、DynamicRankSupportFlag、DynamicShapeSupportFlag即支持動(dòng)態(tài) shape 與動(dòng)態(tài) rank 編譯并指定 kernel 文件為less_apt在 math/less/op_host/less_infershape.cpp 中InferShape 直接復(fù)用廣播基類Ops::Base::InferShape4Broadcast與接口層shape 需滿足 broadcast 關(guān)系的校驗(yàn)保持一致在 math/less/op_host/arch35/less_tiling_arch35.cpp 中tiling 按輸入數(shù)據(jù)類型int64、uint64、int32、float、half、uint8、int8/bool、double實(shí)例化對(duì)應(yīng)的BroadcastBaseTilingLessComputeT::OpDag模板同一時(shí)刻要求x1與x2的數(shù)據(jù)類型一致該文件在接口層完成類型提升后天然滿足。Kernel 層的 DAG 計(jì)算圖在 math/less/op_kernel/arch35/less_dag.h 中kernel 通過(guò) DAG有向無(wú)環(huán)圖描述計(jì)算輸入經(jīng)Vec::CopyInBrcT廣播拷貝進(jìn) Vector 單元Input0/Input1Vec::Compareuint8_t, T, LESS_CMP_MODELESS_CMP_MODE 0執(zhí)行小于比較產(chǎn)出 uint8 掩碼再經(jīng)Vec::SelectLESS_SELECT_MODE 2結(jié)合常量 1/0 把比較結(jié)果映射為布爾值最終Vec::CopyOutuint8_t寫回輸出內(nèi)存配置為MemLevel::LEVEL_2。入口 math/less/op_kernel/less_apt.cpp 中l(wèi)esskernel 使用BroadcastSchschMode, OpDag調(diào)度器統(tǒng)一處理廣播邏輯當(dāng)輸入類型為 BOOL 時(shí)按int8_t模板實(shí)例化其余類型按DTYPE_X1模板實(shí)例化。此外math/less/op_kernel_aicpu/less_aicpu.cpp 提供 AICPU 側(cè)的兜底實(shí)現(xiàn)。二進(jìn)制配置與測(cè)試驗(yàn)證算子的各數(shù)據(jù)類型二進(jìn)制配置位于 math/less/op_host/config/ascend950/less_binary.json如Less_BFLOAT16、Less_FLOAT32、Less_INT64等輸出統(tǒng)一為bool以及 math/less/op_host/config/ascend350/less_binary.json。倉(cāng)庫(kù)同時(shí)提供了多層次的測(cè)試用例用于驗(yàn)證接口行為OP API 單元測(cè)試math/less/tests/ut/op_api/test_lt_tensor.cpp 覆蓋 FLOAT、FLOAT16、INT32、INT64 等多種 dtype 與 ND/NHWC/NCHW 等 format 組合并包含廣播場(chǎng)景如{4,5}與{2,3,4,5}的廣播比較通過(guò)OP_API_UT(aclnnLtTensor, ...)框架自動(dòng)校驗(yàn)GetWorkspaceSize與計(jì)算結(jié)果InferShape 單元測(cè)試math/less/tests/ut/op_host/test_less_infershape.cppAICPU 兜底測(cè)試math/less/tests/ut/op_kernel_aicpu/test_less.cppST 測(cè)試math/less/tests/st/aclnnLtTensor/atk_aclnnLtTensor.json 與 math/less/tests/st/arch35/ttk_kernel_less_st.csv。工程選型建議需要保留原輸入時(shí)使用aclnnLtTensor自行創(chuàng)建out張量接收結(jié)果希望節(jié)省內(nèi)存、原輸入不再需要時(shí)使用aclnnInplaceLtTensor直接將selfRef原地改寫省去一份輸出張量的申請(qǐng)與拷貝注意廣播約束普通版本允許out的 shape 等于廣播后 shape原地版本要求廣播后 shape 與selfRefshape 完全一致平臺(tái)差異在 Atlas 訓(xùn)練系列產(chǎn)品、Atlas 200I/500 A2 推理產(chǎn)品上避免使用 BFLOAT16 輸入否則第一段接口會(huì)返回ACLNN_ERR_PARAM_INVALID。如需了解算子本身的完整語(yǔ)義、參數(shù)總覽與其他調(diào)用方式如 aclnnLtScalar、圖模式調(diào)用可進(jìn)一步閱讀 math/less/README.md 與同目錄下的 aclnnLtScalaraclnnInplaceLtScalar 文檔。贊分享算子庫(kù)人工智能CANN【免費(fèi)下載鏈接】ops-math本項(xiàng)目是CANN提供的數(shù)學(xué)類基礎(chǔ)計(jì)算算子庫(kù)實(shí)現(xiàn)網(wǎng)絡(luò)在NPU上加速計(jì)算。項(xiàng)目地址https://gitcode.com/cann/ops-math點(diǎn)擊查看免費(fèi)下載相關(guān)推薦CANN ops-math Less 算子 aclnnLtTensor 與 aclnnInplaceLtTensor 接口調(diào)用指南CANN ops math Less 算子 aclnnLtTensor 與 aclnnInplaceLtTensor 接口調(diào)用指南 本篇技術(shù)指南以 CANN o算子庫(kù)人工智能CANNCANN ops-math 算子實(shí)戰(zhàn)aclnnDiv 與 aclnnInplaceDiv 除法算子接口全解析CANN ops math 算子實(shí)戰(zhàn)aclnnDiv 與 aclnnInplaceDiv 除法算子接口全解析 本篇技術(shù)指南圍繞 CANN ops math 數(shù)算子庫(kù)人工智能CANNCANN ops-math 除法取模算子 aclnnDivMod / aclnnInplaceDivMod 接口全解析與實(shí)戰(zhàn)CANN ops math 除法取模算子 aclnnDivMod / aclnnInplaceDivMod 接口全解析與實(shí)戰(zhàn) 本文是 CANN ops math算子庫(kù)人工智能CANN創(chuàng)作聲明:本文部分內(nèi)容由AI輔助生成(AIGC),僅供參考