Merged
refactor(operator): Remove tile_fwk_operator library and associated tests. #5704
chaizhengtongAdd on Aug 26
refactor(operator): Remove tile_fwk_operator library and associated tests. #5704
Merged
chaizhengtongAdd on Aug 26
Total: 38 files changed+61-5403
@@ -8,10 +8,6 @@
8# See LICENSE in the root of the software repository for the full text of the License.8# See LICENSE in the root of the software repository for the full text of the License.
9# -----------------------------------------------------------------------------------------------------------9# -----------------------------------------------------------------------------------------------------------
10 10 
11-if (NOT ENABLE_FEATURE_PYTHON_FRONT_END)
12- add_subdirectory(operator)
13-endif ()
14- 
15add_subdirectory(utils)11add_subdirectory(utils)
16add_subdirectory(adapter)12add_subdirectory(adapter)
17add_subdirectory(interface)13add_subdirectory(interface)
@@ -1,27 +0,0 @@
1-# -----------------------------------------------------------------------------------------------------------
2-# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
3-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4-# CANN Open Software License Agreement Version 2.0 (the "License").
5-# Please refer to the License for details. You may not use this file except in compliance with the License.
6-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8-# See LICENSE in the root of the software repository for the full text of the License.
9-# -----------------------------------------------------------------------------------------------------------
10- 
11-file(GLOB_RECURSE _Operator_Srcs *.cpp)
12- 
13-#PTO_Fwk_Debug_Source_List(NAME "_Operator_Srcs" LIST ${_Operator_Srcs} DETAIL OFF)
14- 
15-add_library(tile_fwk_operator SHARED)
16-target_sources(tile_fwk_operator PRIVATE ${_Operator_Srcs})
17-target_link_libraries(tile_fwk_operator
18- PUBLIC
19- json
20- c_sec
21- PRIVATE
22- tile_fwk_intf_pub
23- $<$<BOOL:${ENABLE_COMPILE_DEPENDENCY_CHECK}>:tile_fwk_interface>
24- $<$<BOOL:${ENABLE_COMPILE_DEPENDENCY_CHECK}>:tile_fwk_utils>
25-)
26-PTO_Fwk_AnalysisTargetHeaderFiles(TARGET tile_fwk_operator)
27-PTO_Fwk_AnalysisTargetSymbols(TARGET tile_fwk_operator)
@@ -1,42 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file sigmoid.cpp
13- * \brief
14- */
15- 
16-#include "tilefwk/tilefwk.h"
17-#include "interface/inner/tilefwk.h"
18-using namespace npu::tile_fwk;
19- 
20-namespace npu::tile_fwk {
21-constexpr float F_1 = 1.0;
22-constexpr float F_NEGA_1 = -1.0;
23- 
24-Tensor Sigmoid(Tensor& input)
25-{
26- // 1/(1+exp(-x))
27- auto dtype = input.GetStorage()->Datatype();
28- if (dtype != DT_FP32) {
29- input = Cast(input, DataType::DT_FP32);
30- }
31- auto expRes = Exp(Mul(input, Element(DataType::DT_FP32, F_NEGA_1)));
32- auto res = Add(expRes, Element(DataType::DT_FP32, F_1));
33- Element src(DataType::DT_FP32, 1.0f);
34- auto ones = Full(src, DataType::DT_FP32, res.GetShape());
35- res = Div(ones, res);
36- if (dtype != DT_FP32) {
37- res = Cast(res, dtype);
38- }
39- return res;
40-}
41- 
42-} // namespace npu::tile_fwk
@@ -1,129 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file fa_def.cpp
13- * \brief
14- */
15- 
16-#include "operator/models/llama/llama_def.h"
17- 
18-namespace npu::tile_fwk {
19- 
20-static constexpr int NUM_64 = 64;
21-static constexpr int NUM_128 = 128;
22- 
23-Tensor FlashAttentionNew(const Tensor& q, const Tensor& k, const Tensor& v, const Tensor& m, const Tensor& l,
24- const AttentionDims& atDims)
25-{
26- (void)m;
27- (void)l;
28- int dim0 = q.GetShape()[0];
29- int dim1 = q.GetShape()[1];
30- int b = atDims.b;
31- int n = atDims.n;
32- int s = dim0 / b;
33- int d = dim1 / n;
34- int singleM = atDims.singleM; // 128
35- int singleN = atDims.singleN; // 1024
36- int s1Loop = s / singleM;
37- int s2Loop = s / singleN;
38- 
39- std::cout << "FlashAttention, B, N, S, D --------" << b << "," << n << "," << s << "," << d << std::endl;
40- std::cout << "s1Loop, s2Loop -------" << s1Loop << "," << s2Loop << "," << std::endl;
41- 
42- auto bns = atDims.b * atDims.n * atDims.s;
43- std::vector<int64_t> shapeReduce = {bns, 1};
44- std::vector<float> max(bns, 0);
45- std::vector<float> sum(bns, 0);
46- 
47- std::map<std::vector<int64_t>, Tensor> lastOi;
48- std::map<std::vector<int64_t>, Tensor> lastMi;
49- std::map<std::vector<int64_t>, Tensor> lastLi;
50- Tensor result;
51- 
52- for (int bIdx = 0; bIdx < b; bIdx++) {
53- for (int nIdx = 0; nIdx < n; nIdx++) {
54- for (int s2Idx = 0; s2Idx < s2Loop; s2Idx++) {
55- auto kj = View(k, {singleN, d}, {bIdx * s + s2Idx * singleN, nIdx * d});
56- auto vj = View(v, {singleN, d}, {bIdx * s + s2Idx * singleN, nIdx * d});
57- 
58- for (int s1Idx = 0; s1Idx < s1Loop; s1Idx++) {
59- auto qi = View(q, {singleM, d}, {bIdx * s + s1Idx * singleM, nIdx * d});
60- std::vector<int64_t> oiOffset = {bIdx * s + s1Idx * singleM, nIdx * d};
61- std::vector<int64_t> liOffset = {(bIdx * n + nIdx) * s + s1Idx * singleM, 0};
62- std::vector<int64_t> miOffset = {(bIdx * n + nIdx) * s + s1Idx * singleM, 0};
63- // [128, 128], [128, 1024] => [128, 1024]
64- auto sij = Matrix::Matmul(DataType::DT_FP32, qi, kj, false, true);
65- 
66- auto tildaMij = Amax(sij, -1, true);
67- auto tsub = Sub(sij, tildaMij);
68- auto tildaPij = Exp(tsub);
69- auto tildaPijF16 = Cast(tildaPij, DataType::DT_FP16);
70- auto tildaLij = Sum(tildaPij, -1, true);
71- 
72- if (!s2Idx) {
73- auto oiTmp = Matrix::Matmul(DataType::DT_FP32, tildaPijF16, vj, false, false);
74- if (s2Loop == 1) {
75- auto liExpand = Reciprocal(tildaLij);
76- lastOi[oiOffset] = Mul(oiTmp, liExpand);
77- } else {
78- lastOi[oiOffset] = oiTmp;
79- }
80- lastLi[liOffset] = tildaLij;
81- lastMi[miOffset] = tildaMij;
82- continue;
83- }
84- 
85- ASSERT(lastOi.count(oiOffset) > 0);
86- ASSERT(lastLi.count(liOffset) > 0);
87- ASSERT(lastMi.count(miOffset) > 0);
88- auto oi = lastOi[oiOffset];
89- auto li = lastLi[liOffset];
90- auto mi = lastMi[miOffset];
91- 
92- auto miNew = Maximum(mi, tildaMij); // [128, 1], [128, 1] => [128, 1]
93- auto t1 = Sub(mi, miNew); // [128, 1], [128, 1] => [128, 1]
94- auto t2 = Exp(t1); // [128, 1]
95- auto t3 = Sub(tildaMij, miNew); // [128, 1], [128, 1] => [128, 1]
96- auto t4 = Exp(t3); // [128, 1]
97- auto t5 = Mul(t4, tildaLij); // [128, 1], [128, 1] => [128, 1]
98- auto t6 = Mul(t2, li); // [128, 1], [128, 1] => [128, 1]
99- auto liNew = Add(t6, t5); // [128, 1], [128, 1] => [128, 1]
100- 
101- auto q3 = Mul(oi, t2);
102- auto q1 = Matrix::Matmul(DataType::DT_FP32, tildaPijF16, vj, false, false);
103- auto q2 = Mul(q1, t4);
104- auto oiTmp = Add(q3, q2); // [128, 128]
105- if (s2Idx == s2Loop - 1) {
106- lastOi[oiOffset] = Mul(oiTmp, Reciprocal(liNew));
107- } else {
108- lastOi[oiOffset] = oiTmp;
109- }
110- lastLi[liOffset] = liNew;
111- lastMi[miOffset] = miNew;
112- }
113- }
114- }
115- }
116- 
117- std::vector<std::pair<Tensor, std::vector<int64_t>>> aggregation;
118- for (auto& [offset, tensor] : lastOi) {
119- aggregation.emplace_back(tensor, offset);
120- }
121- 
122- result = Assemble(aggregation);
123- assert(result.GetShape()[0] == b * s);
124- assert(result.GetShape()[1] == n * d);
125- 
126- return result;
127-}
128- 
129-} // namespace npu::tile_fwk
@@ -1,231 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file llama_def.cpp
13- * \brief
14- */
15- 
16-#include "operator/models/llama/llama_def.h"
17- 
18-#include "interface/function/function.h"
19-#include "tilefwk/tensor.h"
20-#include "interface/tensor/logical_tensor.h"
21- 
22-#ifndef LLAMA_FUNCTION
23-#define LLAMA_FUNCTION(n, ...)
24-#endif
25- 
26-#ifndef LLAMA_PROGRAM
27-#define LLAMA_PROGRAM(n, ...)
28-#endif
29- 
30-constexpr int T_SHAPE = 128;
31-constexpr int NUM_64 = 64;
32-constexpr int NUM_128 = 128;
33-constexpr float F_1 = 1.0;
34-constexpr float F_NEGA_1 = -1.0;
35-namespace npu::tile_fwk {
36- 
37-void SetDefaultL0CubeConfig()
38-{
39- TileShape::Current().SetCubeTile({T_SHAPE, T_SHAPE}, {T_SHAPE, T_SHAPE}, {T_SHAPE, T_SHAPE});
40-}
41- 
42-Tensor FlashAttention(const Tensor& q, const Tensor& k, const Tensor& v, const Tensor& m, const Tensor& l,
43- const AttentionDims& atDims, const AttentionVecTileConfig& vecCfg,
44- const AttentionCubeTileConfig& cubeCfg)
45-{
46- (void)m;
47- (void)l;
48- // q, k, v, result shape: [b*s, n*d]
49- int dim0 = q.GetShape()[0];
50- int dim1 = q.GetShape()[1];
51- int b = atDims.b;
52- int n = atDims.n;
53- int s = dim0 / b;
54- int d = dim1 / n;
55- int singleM = atDims.singleM; // 128
56- assert(singleM == 128);
57- int singleN = atDims.singleN; // 1024
58- int s1Loop = s / singleM;
59- int s2Loop = s / singleN;
60- 
61- std::cout << "FlashAttention, B, N, S, D --------" << b << "," << n << "," << s << "," << d << std::endl;
62- std::cout << "s1Loop, s2Loop -------" << s1Loop << "," << s2Loop << "," << std::endl;
63- 
64- auto bns = atDims.b * atDims.n * atDims.s;
65- std::vector<int64_t> shapeReduce = {bns, 1};
66- std::vector<float> max(bns, 0);
67- std::vector<float> sum(bns, 0);
68- 
69- std::map<std::vector<int64_t>, Tensor> lastOi;
70- std::map<std::vector<int64_t>, Tensor> lastMi;
71- std::map<std::vector<int64_t>, Tensor> lastLi;
72- Tensor result;
73- 
74- // LLAMA_FUNCTION(FlashAttention_L4) {
75- for (int bIdx = 0; bIdx < b; bIdx++) {
76- // LLAMA_FUNCTION(FlashAttention_L3) {
77- for (int nIdx = 0; nIdx < n; nIdx++) {
78- // LLAMA_FUNCTION(FlashAttention_L2) {
79- for (int s2Idx = 0; s2Idx < s2Loop; s2Idx++) {
80- // LLAMA_FUNCTION(FlashAttention_L1) {
81- auto kj = View(k, {singleN, d}, {bIdx * s + s2Idx * singleN, nIdx * d});
82- auto vj = View(v, {singleN, d}, {bIdx * s + s2Idx * singleN, nIdx * d});
83- 
84- for (int s1Idx = 0; s1Idx < s1Loop; s1Idx++) {
85- // LLAMA_FUNCTION(FlashAttention_L0) {
86- auto qi = View(q, {singleM, d}, {bIdx * s + s1Idx * singleM, nIdx * d});
87- std::vector<int64_t> oiOffset = {bIdx * s + s1Idx * singleM, nIdx * d};
88- std::vector<int64_t> liOffset = {(bIdx * n + nIdx) * s + s1Idx * singleM, 0};
89- std::vector<int64_t> miOffset = {(bIdx * n + nIdx) * s + s1Idx * singleM, 0};
90- SetC1CubeConfig(cubeCfg);
91- auto sij = Matrix::Matmul(DataType::DT_FP32, qi, kj, false,
92- true); // [128, 128], [128, 1024] => [128, 1024]
93- 
94- TileShape::Current().SetVecTile(vecCfg.softmaxTileX, vecCfg.softmaxTileY);
95- 
96- auto tildaMij = Amax(sij, -1, true);
97- auto tsub = Sub(sij, tildaMij);
98- auto tildaPij = Exp(tsub);
99- auto tildaPijF16 = Cast(tildaPij, DataType::DT_FP16);
100- auto tildaLij = Sum(tildaPij, -1, true);
101- 
102- SetC2CubeConfig(cubeCfg);
103- 
104- if (!s2Idx) {
105- auto oiTmp = Matrix::Matmul(DataType::DT_FP32, tildaPijF16, vj, false, false);
106- if (s2Loop == 1) {
107- auto liExpand = Reciprocal(tildaLij);
108- lastOi[oiOffset] = Mul(oiTmp, liExpand);
109- } else {
110- lastOi[oiOffset] = oiTmp;
111- }
112- lastLi[liOffset] = tildaLij;
113- lastMi[miOffset] = tildaMij;
114- continue;
115- }
116- 
117- ASSERT(lastOi.count(oiOffset) > 0);
118- ASSERT(lastLi.count(liOffset) > 0);
119- ASSERT(lastMi.count(miOffset) > 0);
120- auto oi = lastOi[oiOffset];
121- auto li = lastLi[liOffset];
122- auto mi = lastMi[miOffset];
123- 
124- auto miNew = Maximum(mi, tildaMij); // [128, 1], [128, 1] => [128, 1]
125- auto t1 = Sub(mi, miNew); // [128, 1], [128, 1] => [128, 1]
126- auto t2 = Exp(t1); // [128, 1]
127- auto t3 = Sub(tildaMij, miNew); // [128, 1], [128, 1] => [128, 1]
128- auto t4 = Exp(t3); // [128, 1]
129- auto t5 = Mul(t4, tildaLij); // [128, 1], [128, 1] => [128, 1]
130- auto t6 = Mul(t2, li); // [128, 1], [128, 1] => [128, 1]
131- auto liNew = Add(t6, t5); // [128, 1], [128, 1] => [128, 1]
132- 
133- auto q3 = Mul(oi, t2);
134- auto q1 = Matrix::Matmul(DataType::DT_FP32, tildaPijF16, vj, false, false);
135- auto q2 = Mul(q1, t4);
136- auto oiTmp = Add(q3, q2); // [128, 128]
137- if (s2Idx == s2Loop - 1) {
138- lastOi[oiOffset] = Mul(oiTmp, Reciprocal(liNew));
139- } else {
140- lastOi[oiOffset] = oiTmp;
141- }
142- lastLi[liOffset] = liNew;
143- lastMi[miOffset] = miNew;
144- }
145- }
146- }
147- 
148- std::vector<std::pair<Tensor, std::vector<int64_t>>> aggregation;
149- for (auto& [offset, tensor] : lastOi) {
150- aggregation.emplace_back(tensor, offset);
151- }
152- result = Assemble(aggregation);
153- assert(result.GetShape()[0] == b * s);
154- assert(result.GetShape()[1] == n * d);
155- }
156- return result;
157-}
158- 
159-Tensor MultiAttention(const Tensor& hiddenStates, const Tensor& weight, const Tensor& m, const Tensor& l,
160- const AttentionDims& atDims, const AttentionVecTileConfig& vecCfg,
161- const AttentionCubeTileConfig& cubeCfg)
162-{
163- Tensor result;
164- LLAMA_FUNCTION(MultiAttention)
165- {
166- auto x = Cast(hiddenStates, DataType::DT_FP16);
167- 
168- auto qkv = Matrix::Matmul(DataType::DT_FP16, x, weight, false, false);
169- auto q = View(qkv, hiddenStates.GetShape(), {0, 0});
170- auto k = View(qkv, hiddenStates.GetShape(), {0, hiddenStates.GetShape()[1]});
171- auto v = View(qkv, hiddenStates.GetShape(), {0, hiddenStates.GetShape()[1] * 2});
172- 
173- result = FlashAttention(q, k, v, m, l, atDims, vecCfg, cubeCfg);
174- }
175- return result;
176-}
177- 
178-Tensor LlamaLayer(Tensor hiddenStates, const Tensor& attnWight, const Tensor& denseWeight, const Tensor& ffnWeight,
179- const AttentionDims& atDims, const AttentionVecTileConfig& vecCfg,
180- const AttentionCubeTileConfig& cubeCfg)
181-{
182- TileShape::Current().SetVecTile(vecCfg.defaultVecTileX, vecCfg.defaultVecTileY);
183- SetDefaultL0CubeConfig();
184- auto shape = hiddenStates.GetShape();
185- auto residual = hiddenStates;
186- hiddenStates = RmsNorm(hiddenStates);
187- 
188- auto bns = atDims.b * atDims.n * atDims.s;
189- std::vector<int64_t> shapeReduce = {bns, 1};
190- std::vector<float> max(bns, 0);
191- std::vector<float> sum(bns, 0);
192- 
193- Tensor m(DataType::DT_FP32, shapeReduce);
194- Tensor l(DataType::DT_FP32, shapeReduce);
195- auto attentionOut = MultiAttention(hiddenStates, attnWight, m, l, atDims, vecCfg, cubeCfg);
196- 
197- auto attentionOutFp16 = Cast(attentionOut, DataType::DT_FP16);
198- // Dense
199- SetDefaultL0CubeConfig();
200- auto denseOut = Matrix::Matmul(DataType::DT_FP32, attentionOutFp16, denseWeight, false, false);
201- TileShape::Current().SetVecTile(vecCfg.defaultVecTileX, vecCfg.defaultVecTileY);
202- hiddenStates = Add(residual, denseOut);
203- 
204- // Fully Connected
205- residual = hiddenStates;
206- hiddenStates = RmsNorm(hiddenStates);
207- 
208- Tensor mlpRes(DataType::DT_FP32, shape);
209- 
210- auto a = Cast(hiddenStates, DataType::DT_FP16);
211- auto gate = Matrix::Matmul(DataType::DT_FP32, a, ffnWeight, false,
212- false); // [b*s, n*d] [n*d, n*d*3] => [b*s, n*d*3]
213- 
214- // swish: x / (1 + e^(-x))
215- auto swish = Mul(gate, Element(DataType::DT_FP32, F_NEGA_1));
216- swish = Exp(swish);
217- swish = Add(swish, Element(DataType::DT_FP32, F_1));
218- swish = Div(gate, swish);
219- 
220- // up_proj
221- // [b*s, n*d] [n*d, n*d*3] => [b*s, n*d*3]
222- auto up = Matrix::Matmul(DataType::DT_FP32, a, ffnWeight, false, false);
223- swish = Mul(swish, up);
224- auto swishFp16 = Cast(swish, DataType::DT_FP16);
225- 
226- // down_proj
227- // [b*s, n*d*3] [n*d, n*d*3]^T => [b*s, n*d]
228- mlpRes = Matrix::Matmul(DataType::DT_FP32, swishFp16, ffnWeight, false, true);
229- return Add(residual, mlpRes);
230-}
231-} // namespace npu::tile_fwk
@@ -1,106 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file llama_def.h
13- * \brief
14- */
15- 
16-#pragma once
17-#ifndef LLAMA_DEF_H
18-#define LLAMA_DEF_H
19- 
20-#include "interface/inner/pre_def.h"
21-#include "tilefwk/tilefwk.h"
22-#include "interface/inner/tilefwk.h"
23- 
24-#define LLAMA_FUNCTION(n, ...) FUNCTION(#n, ##__VA_ARGS__)
25-#define LLAMA_PROGRAM(n, ...) PROGRAM(#n, ##__VA_ARGS__)
26- 
27-namespace npu::tile_fwk {
28- 
29-struct AttentionDims {
30- int b;
31- int n;
32- int s;
33- int d;
34- int singleM;
35- int singleN;
36-};
37- 
38-struct AttentionVecTileConfig {
39- int defaultVecTileX;
40- int defaultVecTileY;
41- int softmaxTileX;
42- int softmaxTileY;
43- int updateTileX;
44- int updateTileY;
45- int castTileX;
46- int castTileY;
47-};
48- 
49-struct AttentionCubeTileConfig {
50- int c1L1M;
51- int c1L1K;
52- int c1L1N;
53- int c2L1M;
54- int c2L1K;
55- int c2L1N;
56- int c1L0 = 128;
57- int c2L0 = 128;
58-};
59- 
60-struct KeyConfig {
61- int max;
62- int min;
63- int dbType;
64- int nBuffer;
65- int isPartitionCv;
66- int cTileX;
67- int cTileY;
68-};
69- 
70-constexpr AttentionVecTileConfig DFS_VEC_CFG = {128, 128, 16, 128, 16, 128, 32, 128};
71-constexpr AttentionVecTileConfig SMALL_DFS_VEC_CFG = {64, 128, 16, 128, 16, 128, 32, 128};
72-constexpr AttentionCubeTileConfig DFS_CUBE_CFG = {128, 128, 128, 128, 128, 128};
73- 
74-constexpr AttentionVecTileConfig OOO_VEC_CFG = {64, 128, 16, 512, 32, 128, 32, 128};
75-constexpr AttentionCubeTileConfig OOO_CUBE_CFG = {128, 128, 512, 64, 256, 64, 128, 64};
76- 
77-constexpr KeyConfig DFT_BASIC_CFG = {8192, 1024, 1, 1, 0, 128, 128};
78-constexpr int DFT_SINGLE_M = 128;
79-constexpr int DFT_SINGLE_N = 128;
80- 
81-Tensor LlamaLayer(Tensor hiddenStates, const Tensor& attnWight, const Tensor& denseWeight, const Tensor& ffnWeight,
82- const AttentionDims& atDims, const AttentionVecTileConfig& vecCfg,
83- const AttentionCubeTileConfig& cubeCfg);
84- 
85-Tensor FlashAttention(const Tensor& q, const Tensor& k, const Tensor& v, const Tensor& m, const Tensor& l,
86- const AttentionDims& atDims, const AttentionVecTileConfig& vecCfg,
87- const AttentionCubeTileConfig& cubeCfg);
88- 
89-Tensor FlashAttentionNew(const Tensor& q, const Tensor& k, const Tensor& v, const Tensor& m, const Tensor& l,
90- const AttentionDims& atDims);
91- 
92-static inline void SetC1CubeConfig(const AttentionCubeTileConfig& cubeCfg)
93-{
94- TileShape::Current().SetCubeTile({cubeCfg.c1L0, cubeCfg.c1L1M}, {cubeCfg.c1L0, cubeCfg.c1L1K},
95- {cubeCfg.c1L0, cubeCfg.c1L1N});
96-}
97- 
98-static inline void SetC2CubeConfig(const AttentionCubeTileConfig& cubeCfg)
99-{
100- TileShape::Current().SetCubeTile({cubeCfg.c2L0, cubeCfg.c2L1M}, {cubeCfg.c2L0, cubeCfg.c2L1K},
101- {cubeCfg.c2L0, cubeCfg.c2L1N});
102-}
103- 
104-} // namespace npu::tile_fwk
105- 
106-#endif
@@ -1,152 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file view_type.cpp
13- * \brief
14- */
15- 
16-#include "view_type.h"
17- 
18-using namespace npu::tile_fwk;
19- 
20-namespace npu::tile_fwk {
21- 
22-void ViewTypeFunc(const Tensor& x, Tensor& result, DataType dstDtype)
23-{
24- FUNCTION("ViewTypeFunc", {x}, {result})
25- {
26- int m = x.GetShape()[0];
27- int k = x.GetShape()[1];
28- int n = x.GetShape()[2];
29- int tileM = m / 4;
30- SymbolicScalar mLoop = m / tileM;
31- 
32- LOOP("LOOP_L0_nIdx_view_type", FunctionType::DYNAMIC_LOOP, mIdx, LoopRange(0, mLoop, 1))
33- {
34- SymbolicScalar mOffset = mIdx * tileM;
35- TileShape::Current().SetVecTile({tileM, k, n});
36- auto xView = View(x, {tileM, k, n}, {mOffset, 0, 0});
37- TileShape::Current().SetVecTile({tileM, k, n});
38- auto resultView = View(xView, dstDtype);
39- auto resultRes = resultView;
40- 
41- if (dstDtype == DT_FP32) {
42- resultRes = Add(resultView, Element(dstDtype, float(0)));
43- }
44- Assemble(resultRes, {mOffset, 0, 0}, result);
45- }
46- }
47-}
48- 
49-std::tuple<Tensor, Tensor> MyPrologQuant(const Tensor& input)
50-{
51- config::SetSemanticLabel("Prolog-Quant");
52- constexpr const float s8_max_value = 127.0f;
53- constexpr const float s8_one_value = 1.0f;
54- auto inputFp32 = Cast(input, DataType::DT_FP32, CAST_NONE);
55- 
56- auto absRes = Abs(inputFp32);
57- auto maxValue = Amax(absRes, -1, true);
58- auto temp127 = Full(Element(DT_FP32, s8_max_value), DT_FP32, maxValue.GetShape());
59- 
60- auto scaleQuant = Div(temp127, maxValue);
61- auto outFp32 = Mul(inputFp32, scaleQuant);
62- auto outInt32 = Cast(outFp32, DataType::DT_INT32, CAST_RINT);
63- auto outHalf = Cast(outInt32, DataType::DT_FP16, CAST_ROUND);
64- auto outInt8 = Cast(outHalf, DataType::DT_INT8, CAST_TRUNC);
65- auto temp1 = Full(Element(DT_FP32, s8_one_value), DT_FP32, scaleQuant.GetShape());
66- auto scaleDeQuant = Div(temp1, scaleQuant);
67- return std::tie(outInt8, scaleDeQuant);
68-}
69- 
70-void ViewTypeQuantTestFunc(const Tensor& x, Tensor& result)
71-{
72- FUNCTION("ViewTypeQuantTestFunc", {x}, {result})
73- {
74- int m = x.GetShape()[0];
75- int k = x.GetShape()[1];
76- int n = x.GetShape()[2];
77- int tileM = m / 2;
78- SymbolicScalar mLoop = m / tileM;
79- LOOP("LOOP_L0_mIdx_view_type_quant", FunctionType::DYNAMIC_LOOP, mIdx, LoopRange(0, mLoop, 1))
80- {
81- SymbolicScalar mOffset = mIdx * tileM;
82- TileShape::Current().SetVecTile({tileM, k, n});
83- auto xView = View(x, {tileM, k, n}, {mOffset, 0, 0});
84- TileShape::Current().SetVecTile({tileM, k, n});
85- auto xReshape = Reshape(xView, {tileM, k, 4, n / 4});
86- TileShape::Current().SetVecTile({tileM, k, 4, n / 4});
87- std::tuple<Tensor, Tensor> xQuant = MyPrologQuant(xReshape);
88- auto outInt8 = std::get<0>(xQuant);
89- auto scaleDeQuant = std::get<1>(xQuant);
90- 
91- TileShape::Current().SetVecTile({tileM, k, 4, n / 4});
92- auto outInt8Reshape = Reshape(outInt8, {tileM, k, n});
93- TileShape::Current().SetVecTile({tileM, k, 8});
94- auto scaleDeQuantReshape = Reshape(scaleDeQuant, {tileM, k, 4});
95- TileShape::Current().SetVecTile({tileM, k, 8});
96- auto scaleQuantView = View(scaleDeQuantReshape, DT_INT8);
97- TileShape::Current().SetVecTile({tileM, k, 32});
98- auto scaleQuantViewRes = Reshape(scaleQuantView, {tileM, k, 16});
99- TileShape::Current().SetVecTile({tileM, k, n});
100- auto combinedRes = Cat({outInt8Reshape, scaleQuantViewRes}, -1);
101- Assemble(combinedRes, {mOffset, 0, 0}, result);
102- }
103- }
104-}
105- 
106-void ViewTypeDequantTestFunc(const Tensor& x, Tensor& result)
107-{
108- FUNCTION("ViewTypeDequantTestFunc", {x}, {result})
109- {
110- int m = x.GetShape()[0];
111- int k = x.GetShape()[1];
112- 
113- int tileM = m / 8;
114- SymbolicScalar mLoop = m / tileM;
115- 
116- LOOP("LOOP_L0_nIdx_view_type_dequant", FunctionType::DYNAMIC_LOOP, mIdx, LoopRange(0, mLoop, 1))
117- {
118- SymbolicScalar mOffset = mIdx * tileM;
119- 
120- TileShape::Current().SetVecTile({tileM, k, 128});
121- auto ropeView = View(x, {tileM, k, 128}, {mOffset, 0, 512});
122- TileShape::Current().SetVecTile({tileM, k, 64});
123- auto ropeRes = View(ropeView, DT_BF16);
124- 
125- TileShape::Current().SetVecTile({tileM, k, 32});
126- auto nopeView = View(x, {tileM, k, 512}, {mOffset, 0, 0});
127- auto nopeCast = Cast(nopeView, DT_FP16);
128- auto nopeCastCast = Cast(nopeCast, DT_FP32);
129- auto nopeRehape = Reshape(nopeCastCast, {tileM, k, 4, 128});
130- 
131- TileShape::Current().SetVecTile({tileM, k, 32});
132- auto scaleView = View(x, {tileM, k, 16}, {mOffset, 0, 640});
133- TileShape::Current().SetVecTile({tileM, k, 32});
134- auto scaleRes = View(scaleView, DT_FP32);
135- TileShape::Current().SetVecTile({tileM, k, 8});
136- auto scaleReshape = Reshape(scaleRes, {tileM, k, 4, 1});
137- 
138- TileShape::Current().SetVecTile({tileM, k, 4, 16});
139- auto cacheNope = Mul(nopeRehape, scaleReshape);
140- TileShape::Current().SetVecTile({tileM, k, 4, 16});
141- auto cacheNopeBf16 = Cast(cacheNope, DT_BF16);
142- TileShape::Current().SetVecTile({tileM, k, 4, 16});
143- auto cacheNopeReshape = Reshape(cacheNopeBf16, {tileM, k, 512});
144- TileShape::Current().SetVecTile({tileM, k, 64});
145- auto cache = Cat({cacheNopeReshape, ropeRes}, -1);
146- 
147- Assemble(cache, {mOffset, 0, 0}, result);
148- }
149- }
150-}
151- 
152-} // namespace npu::tile_fwk
@@ -1,32 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file view_type.h
13- * \brief
14- */
15- 
16-#pragma once
17-#ifndef GEN_GATED_SCORE
18-#define GEN_GATED_SCORE
19- 
20-#include "tilefwk/tilefwk_op.h"
21-#include "interface/inner/pre_def.h"
22-#include "tilefwk/tilefwk.h"
23-#include "interface/inner/tilefwk.h"
24- 
25-namespace npu::tile_fwk {
26-void ViewTypeFunc(const Tensor& x, Tensor& result, DataType dstDtype);
27-std::tuple<Tensor, Tensor> MyPrologQuant(const Tensor& input);
28-void ViewTypeQuantTestFunc(const Tensor& x, Tensor& result);
29-void ViewTypeDequantTestFunc(const Tensor& x, Tensor& result);
30-} // namespace npu::tile_fwk
31- 
32-#endif
@@ -1,70 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file rms_norm.cpp
13- * \brief
14- */
15- 
16-#include "tilefwk/tilefwk.h"
17-#include "interface/inner/tilefwk.h"
18-using namespace npu::tile_fwk;
19- 
20-namespace npu::tile_fwk {
21-Tensor RmsNorm(const Tensor& operand)
22-{
23- constexpr float epsilon = 1e-6f;
24- 
25- auto fp32Operand = Cast(operand, DataType::DT_FP32);
26- // y = x^2 / n
27- auto y = Mul(fp32Operand, fp32Operand);
28- y = Mul(y, Element(DataType::DT_FP32, 1.0f / operand.GetShape()[operand.GetShape().size() - 1]));
29- 
30- // ReduceSum(x^2 / n) + Eps
31- y = Sum(y, -1, true);
32- y = Add(y, Element(DataType::DT_FP32, epsilon));
33- 
34- // sqrt rstd
35- y = Sqrt(y);
36- Element src(DataType::DT_FP32, 1.0f);
37- auto ones = Full(src, DT_FP32, y.GetShape());
38- y = Div(ones, y);
39- return Cast(Mul(fp32Operand, y), operand.GetStorage()->Datatype());
40-}
41- 
42-Tensor RmsNorm(const Tensor& operand, const Tensor& gamma, float epsilon)
43-{
44- auto fp32Operand = Cast(operand, DataType::DT_FP32);
45- int size = operand.GetShape().size();
46- std::vector<int64_t> shape(size, 1);
47- shape[size - 1] = gamma.GetShape()[0];
48- auto gammaCast = Reshape(gamma, shape);
49- auto gammaOperand = Cast(gammaCast, DataType::DT_FP32);
50- // y = x^2 / n
51- auto y = Mul(fp32Operand, fp32Operand);
52- y = Mul(y, Element(DataType::DT_FP32, 1.0f / operand.GetShape()[operand.GetShape().size() - 1]));
53- 
54- // ReduceSum(x^2 / n) + Eps
55- y = Sum(y, -1, true);
56- y = Add(y, Element(DataType::DT_FP32, epsilon));
57- 
58- // sqrt rstd
59- y = Sqrt(y);
60- Element src(DataType::DT_FP32, 1.0f);
61- auto ones = Full(src, DT_FP32, y.GetShape());
62- y = Div(ones, y);
63- y = Mul(fp32Operand, y);
64- y = Mul(gammaOperand, y);
65- y = Cast(y, operand.GetStorage()->Datatype());
66- 
67- return y;
68-}
69- 
70-} // namespace npu::tile_fwk
@@ -1,88 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file soft_max.cpp
13- * \brief
14- */
15- 
16-#include "tilefwk/tilefwk.h"
17-#include "interface/inner/tilefwk.h"
18-using namespace npu::tile_fwk;
19- 
20-namespace npu::tile_fwk {
21-Tensor Softmax(const Tensor& operand)
22-{
23- auto tRowmax = RowMaxExpand(operand);
24- auto tSub = Sub(operand, tRowmax);
25- auto tExp = Exp(tSub);
26- auto tEsum = RowSumExpand(tExp);
27- auto tSoftmax = Div(tExp, tEsum);
28- 
29- return tSoftmax;
30-}
31- 
32-Tensor SoftmaxNew(const Tensor& operand)
33-{
34- // 获取输入数据类型
35- auto inputDtype = operand.GetStorage()->Datatype();
36- Tensor castOperand = operand;
37- // 如果输入数据类型不是FP32,则将其转换为FP32
38- if (inputDtype != DataType::DT_FP32) {
39- castOperand = Cast(operand, DataType::DT_FP32);
40- }
41- // 描述计算逻辑
42- // M=rowMax(xi)
43- auto rowmax = Amax(castOperand, -1, true);
44- // S=rowSum(exp(xi-M))
45- auto sub = Sub(castOperand, rowmax);
46- auto exp = Exp(sub);
47- auto esum = Sum(exp, -1, true);
48- // softmax(zi)=exp(xi-M)/S
49- auto softmax = Div(exp, esum);
50- // 如果输出数据类型与输入不同,则进行类型转换
51- if (inputDtype != softmax.GetStorage()->Datatype()) {
52- softmax = Cast(softmax, inputDtype);
53- }
54- return softmax;
55-}
56- 
57-void SoftmaxDynamicCompute(Tensor& input, Tensor& output)
58-{
59- // 获取输入形状信息[b, n1, n2, dim], batch轴动态
60- SymbolicScalar b = GetInputShape(input, 0);
61- int n1 = input.GetShape()[1];
62- int n2 = input.GetShape()[2];
63- int dim = input.GetShape()[3];
64- // 设置Loop处理的batch大小及循环次数
65- int tileB = 1;
66- SymbolicScalar bLoop = b / tileB;
67- // 定义循环,用于处理每个batch块,每个batch块为(1, 32, 1, 256)
68- LOOP("SOFTMAX_LOOP_L0_bIdx", FunctionType::DYNAMIC_LOOP, bIdx, LoopRange(0, bLoop, 1), {}, true)
69- {
70- // 计算偏移量
71- SymbolicScalar bOffset = bIdx * tileB;
72- std::vector<SymbolicScalar> outOffset = {bOffset, 0, 0, 0};
73- // 对每个batch块进行tile切分,切分大小为(1, 4, 1, 64)
74- TileShape::Current().SetVecTile({1, 4, 1, 64});
75- // 创建输入视图
76- auto inputView = View(input, {tileB, n1, n2, dim}, {bOffset, 0, 0, 0});
77- // 调用Softmax算子函数
78- auto outputView = SoftmaxNew(inputView);
79- // 将输出结果组装到输出Tensor中
80- Assemble(outputView, outOffset, output);
81- }
82-}
83- 
84-void SoftmaxDynamic(Tensor& input, Tensor& output)
85-{
86- FUNCTION("SOFTMAX_DYNAMIC_EXAMPLE", {input}, {output}) { SoftmaxDynamicCompute(input, output); }
87-}
88-} // namespace npu::tile_fwk
@@ -212,7 +212,6 @@ function(PTO_Fwk_STest_AddExe_RunExe)
212 tile_fwk_compiler212 tile_fwk_compiler
213 tile_fwk_runtime213 tile_fwk_runtime
214 tile_fwk_simulation214 tile_fwk_simulation
215- tile_fwk_operator
216 )215 )
217 PTO_Fwk_GTest_AddExe(216 PTO_Fwk_GTest_AddExe(
218 TARGET ${ARG_TARGET}217 TARGET ${ARG_TARGET}
@@ -135,6 +135,7 @@ function(PTO_Fwk_UTest_AddExe_RunExe)
135 )135 )
136 set(_Sources ${CMAKE_CURRENT_BINARY_DIR}/${PTO_Fwk_UTestNamePrefix}_main_stub.cpp)136 set(_Sources ${CMAKE_CURRENT_BINARY_DIR}/${PTO_Fwk_UTestNamePrefix}_main_stub.cpp)
137 execute_process(COMMAND touch ${_Sources})137 execute_process(COMMAND touch ${_Sources})
138+ list(APPEND _Sources ${CMAKE_CURRENT_SOURCE_DIR}/utils/operator_stubs.cpp)
138 139 
139 # 默认全部执行140 # 默认全部执行
140 set(GTestFilterList "*")141 set(GTestFilterList "*")
@@ -72,11 +72,6 @@ stest:
72 - DynamicReshapeUnalignImplaceTest.test_exchange_dim72 - DynamicReshapeUnalignImplaceTest.test_exchange_dim
73 - DynamicReshapeUnalignImplaceTest.test_reshape_special73 - DynamicReshapeUnalignImplaceTest.test_reshape_special
74 - DynamicReshapeUnalignImplaceTest.test_src_op_dst_op74 - DynamicReshapeUnalignImplaceTest.test_src_op_dst_op
75- #===========================================================================
76- # ViewType功能用例
77- #===========================================================================
78- - ViewType.quant_test_bf16_2_int8
79- - ViewType.dequant_test_bf16_2_int8
80 75 
81 machine_host:76 machine_host:
82 cases:77 cases:
@@ -1,138 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_dynamic_bin.cpp
13- * \brief
14- */
15-#include <gtest/gtest.h>
16-#include "test_suite_stest_ops.h"
17-#include "interface/interpreter/raw_tensor_data.h"
18-#include "machine/utils/dynamic/dev_encode.h"
19-#include "test_dev_func_runner.h"
20- 
21-using namespace npu::tile_fwk;
22-using namespace npu::tile_fwk::dynamic;
23-class DynamicBinTest : public npu::tile_fwk::stest::TestSuite_STest_Ops_Aihac {};
24- 
25-TEST_F(DynamicBinTest, TestDynamicAddUnalign)
26-{
27- SetInterpreterConfig();
28- TileShape::Current().SetVecTile(64, 64);
29- 
30- int b = 1;
31- int sq = 128;
32- int d = 64;
33- std::vector<int64_t> inputShape = {b * sq, d};
34- std::vector<int64_t> outShape = {b * sq, d};
35- 
36- Tensor input1(DT_FP32, inputShape, "intput1");
37- Tensor input2(DT_FP32, inputShape, "intput2");
38- Tensor curSeq(DT_INT32, {b, 1}, "curSeq");
39- Tensor out(DT_FP32, outShape, "out");
40- 
41- std::vector<int> actSeqsData(b, 100);
42- std::vector<float> golden(b * sq * d, 0.001f);
43- for (int i = 0; i < b; i++) {
44- int offset = i * sq * d;
45- std::fill(golden.begin() + offset, golden.begin() + offset + actSeqsData[i] * d, 2.0);
46- }
47- 
48- ProgramData::GetInstance().AppendInputs({
49- RawTensorData::CreateConstantTensor<float>(input1, 1.0),
50- RawTensorData::CreateConstantTensor<float>(input2, 1.0),
51- RawTensorData::CreateTensor<int32_t>(curSeq, actSeqsData),
52- });
53- 
54- ProgramData::GetInstance().AppendOutputs({
55- RawTensorData::CreateConstantTensor<float>(out, 0.001f),
56- });
57- 
58- ProgramData::GetInstance().AppendGoldens({
59- RawTensorData::CreateTensor<float>(out, golden),
60- });
61- 
62- FUNCTION("main", {input1, input2, curSeq}, {out})
63- {
64- LOOP("L0", FunctionType::DYNAMIC_LOOP, batchId, LoopRange(b))
65- {
66- auto seq = GetTensorData(curSeq, {batchId, 0});
67- Tensor intput11 = View(input1, {sq, d}, {seq, d}, {batchId, 0});
68- Tensor intput22 = View(input2, {sq, d}, {seq, d}, {batchId, 0});
69- auto tmp = Add(intput11, intput22);
70- Assemble(tmp, {batchId * sq, 0}, out);
71- }
72- }
73- 
74- // excute
75- DevFuncRunner::Run(Program::GetInstance().GetLastFunction());
76- 
77- auto outs = npu::tile_fwk::ProgramData::GetInstance().GetOutputData(0);
78- EXPECT_TRUE(resultCmp(golden, (float*)outs->data(), 0.001f));
79-}
80- 
81-TEST_F(DynamicBinTest, testDynMulsUnalign)
82-{
83- SetInterpreterConfig();
84- TileShape::Current().SetVecTile(64, 64);
85- 
86- std::vector<uint8_t> devProgBinary;
87- 
88- int b = 4;
89- int sq = 128;
90- int d = 64;
91- std::vector<int64_t> qShape = {b * sq, d}; // input_src0 shape: {512, 64}
92- std::vector<int64_t> outShape = {b * sq, d}; // output shape: {4*128, 64}
93- 
94- Tensor q(DT_FP32, qShape, "q");
95- Tensor actSeqs(DT_INT32, {b, 1}, "actual_seq");
96- Tensor out(DT_FP32, outShape, "out");
97- 
98- std::vector<int> actSeqsData(b, 100);
99- std::vector<float> golden(b * sq * d, 0.001f);
100- for (int bidx = 0; bidx < b; ++bidx) {
101- for (int seq = 0; seq < actSeqsData[bidx]; ++seq) {
102- for (int dim = 0; dim < d; ++dim) {
103- int idx = bidx * sq * d + seq * d + dim;
104- golden[idx] = 1.0f;
105- }
106- }
107- }
108- ProgramData::GetInstance().AppendInputs({
109- RawTensorData::CreateConstantTensor<float>(q, 1.0),
110- RawTensorData::CreateTensor<int>(actSeqs, actSeqsData),
111- });
112- 
113- ProgramData::GetInstance().AppendOutputs({
114- RawTensorData::CreateConstantTensor<float>(out, 0.001f),
115- });
116- 
117- ProgramData::GetInstance().AppendGoldens({
118- RawTensorData::CreateTensor<float>(out, golden),
119- });
120- 
121- FUNCTION("main", {q, actSeqs}, {out})
122- {
123- LOOP("L0", FunctionType::DYNAMIC_LOOP, batchId, LoopRange(GetInputShape(q, 0) / (sq)))
124- {
125- SymbolicScalar curSeq = GetTensorData(actSeqs, {batchId, 0});
126- Element value(DataType::DT_FP32, 1.0);
127- Tensor q0 = View(q, {sq, d}, {curSeq, d}, {batchId * sq, 0});
128- auto tmp = Mul(q0, value);
129- 
130- Assemble(tmp, {batchId * sq, 0}, out);
131- }
132- }
133- 
134- DevFuncRunner::Run(Program::GetInstance().GetLastFunction());
135- 
136- auto outs = npu::tile_fwk::ProgramData::GetInstance().GetOutputData(0);
137- EXPECT_TRUE(resultCmp(golden, (float*)outs->data(), 0.001f));
138-}
@@ -1,81 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_dynamic_binry_brc.cpp
13- * \brief
14- */
15-#include <gtest/gtest.h>
16-#include "test_suite_stest_ops.h"
17-#include "interface/interpreter/raw_tensor_data.h"
18-#include "machine/utils/dynamic/dev_encode.h"
19-#include "test_dev_func_runner.h"
20- 
21-using namespace npu::tile_fwk;
22-using namespace npu::tile_fwk::dynamic;
23-class DynamicBrcTest : public npu::tile_fwk::stest::TestSuite_STest_Ops_Aihac {};
24- 
25-TEST_F(DynamicBrcTest, TestDynamicMulBrcUnalign)
26-{
27- SetInterpreterConfig();
28- config::SetOperationOption(KEY_COMBINE_AXIS, true);
29- TileShape::Current().SetVecTile(32, 128);
30- 
31- int b = 2;
32- int sq = 32;
33- int d = 72;
34- std::vector<int64_t> inputShape_a = {b * sq, d};
35- std::vector<int64_t> inputShape_b = {b * sq, 8};
36- std::vector<int64_t> outShape = {b * sq, d};
37- 
38- Tensor input_a(DT_FP32, inputShape_a, "intput_a");
39- Tensor input_b(DT_FP32, inputShape_b, "intput_b");
40- Tensor curSeq(DT_INT32, {b, 1}, "curSeq");
41- Tensor out(DT_FP32, outShape, "out");
42- 
43- std::vector<int> actSeqsData(b, 24); // 有效值应该是block对齐的
44- std::vector<float> golden(b * sq * d, 0.001f);
45- for (int i = 0; i < b; i++) {
46- int offset = i * sq * d;
47- std::fill(golden.begin() + offset, golden.begin() + offset + actSeqsData[i] * d, 48.0);
48- }
49- 
50- ProgramData::GetInstance().AppendInputs({
51- RawTensorData::CreateConstantTensor<float>(input_a, 2.0),
52- RawTensorData::CreateConstantTensor<float>(input_b, 3.0),
53- RawTensorData::CreateTensor<int32_t>(curSeq, actSeqsData),
54- });
55- 
56- ProgramData::GetInstance().AppendOutputs({
57- RawTensorData::CreateConstantTensor<float>(out, 0.001f),
58- });
59- 
60- ProgramData::GetInstance().AppendGoldens({
61- RawTensorData::CreateTensor<float>(out, golden),
62- });
63- FUNCTION("main", {input_a, input_b, curSeq}, {out})
64- {
65- LOOP("L0", FunctionType::DYNAMIC_LOOP, batchId, LoopRange(b))
66- {
67- auto seq = GetTensorData(curSeq, {batchId, 0});
68- Tensor input_a0 = View(input_a, {sq, d}, {seq, d}, {batchId * sq, 0});
69- Tensor input_b0 = View(input_b, {sq, 8}, {seq, 8}, {batchId * sq, 0});
70- auto input_c = Sum(input_b0, -1, true);
71- auto tmp = Mul(input_a0, input_c);
72- Assemble(tmp, {batchId * sq, 0}, out);
73- }
74- }
75- 
76- // excute
77- DevFuncRunner::Run(Program::GetInstance().GetLastFunction());
78- 
79- auto outs = npu::tile_fwk::ProgramData::GetInstance().GetOutputData(0);
80- EXPECT_TRUE(resultCmp(golden, (float*)outs->data(), 0.001f));
81-}
@@ -1,215 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_view_type.cpp
13- * \brief
14- */
15-#include "interface/interpreter/raw_tensor_data.h"
16-#include "interface/tensor/float.h"
17-#include "test_dev_func_runner.h"
18-#include "test_suite_stest_ops.h"
19-#include "tilefwk/tensor.h"
20-#include "operator/models/nsa/view_type.h"
21- 
22-using namespace npu::tile_fwk;
23- 
24-class ViewType : public npu::tile_fwk::stest::TestSuite_STest_Ops_Aihac {};
25- 
26-template <typename T>
27-static std::shared_ptr<RawTensorData> CreateTensorData(Tensor tensor, std::string fileName)
28-{
29- auto shape = tensor.GetShape();
30- int capacity = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<>());
31- std::vector<T> values(capacity, 0);
32- readInput<T>(GetGoldenDir() + fileName, values);
33- return RawTensorData::CreateTensor<T>(tensor, values);
34-}
35- 
36-template <typename T>
37-static std::vector<T> GetGoldenVec(std::vector<int64_t> shape, std::string fileName)
38-{
39- uint64_t capacity = std::accumulate(shape.begin(), shape.end(), uint64_t{1}, std::multiplies<uint64_t>());
40- std::vector<T> golden(capacity, 0);
41- readInput<T>(GetGoldenDir() + fileName, golden);
42- return golden;
43-}
44- 
45-template <typename InputT, typename OutputT>
46-void ViewTypeEntry(const std::vector<int64_t>& mkn)
47-{
48- int64_t m = mkn[0];
49- int64_t k = mkn[1];
50- int64_t n = mkn[2];
51- 
52- DataType originDtype = GetAstDtype<InputT>();
53- DataType dstDtype = GetAstDtype<OutputT>();
54- float factor = (float)BytesOf(originDtype) / (float)BytesOf(dstDtype);
55- 
56- std::vector<int64_t> xShape = {m, k, n};
57- std::vector<int64_t> resultShape = {m, k, int(n * factor)};
58- 
59- Tensor x(originDtype, xShape, "x");
60- Tensor result(dstDtype, resultShape, "result");
61- 
62- auto goldenData = GetGoldenVec<OutputT>(resultShape, "/result.bin");
63- auto xData = CreateTensorData<InputT>(x, "/x.bin");
64- 
65- auto resultData = RawTensorData::CreateConstantTensor<OutputT>(result, 0.0);
66- 
67- std::vector<RawTensorDataPtr> inputDataList = {xData};
68- std::vector<RawTensorDataPtr> outputDataList = {resultData};
69- 
70- ViewTypeFunc(x, result, dstDtype);
71- 
72-#ifdef BUILD_WITH_CANN
73- DevFuncRunner::Run(Program::GetInstance().GetLastFunction(), inputDataList, outputDataList);
74- std::cout << "====== result ======" << std::endl;
75- EXPECT_TRUE(resultCmp<OutputT>(goldenData, (OutputT*)resultData->data(), 0.005f));
76-#endif
77-}
78- 
79-template <typename InputT, typename OutputT>
80-void ViewTypeQuantTestEntry(const std::vector<int64_t>& mkn)
81-{
82- int64_t m = mkn[0];
83- int64_t k = mkn[1];
84- int64_t n = mkn[2];
85- 
86- DataType originDtype = GetAstDtype<InputT>();
87- DataType dstDtype = GetAstDtype<OutputT>();
88- 
89- std::vector<int64_t> xShape = {m, k, n};
90- std::vector<int64_t> resultShape = {m, k, n + 16};
91- 
92- Tensor x(originDtype, xShape, "x");
93- Tensor result(dstDtype, resultShape, "result");
94- 
95- auto goldenData = GetGoldenVec<OutputT>(resultShape, "/result.bin");
96- auto xData = CreateTensorData<InputT>(x, "/x.bin");
97- 
98- auto resultData = RawTensorData::CreateConstantTensor<OutputT>(result, 0.0);
99- 
100- std::vector<RawTensorDataPtr> inputDataList = {xData};
101- std::vector<RawTensorDataPtr> outputDataList = {resultData};
102- 
103- ViewTypeQuantTestFunc(x, result);
104- 
105-#ifdef BUILD_WITH_CANN
106- DevFuncRunner::Run(Program::GetInstance().GetLastFunction(), inputDataList, outputDataList);
107- std::cout << "====== result ======" << std::endl;
108- EXPECT_TRUE(resultCmp<OutputT>(goldenData, (OutputT*)resultData->data(), 0.005f));
109-#endif
110-}
111- 
112-template <typename InputT, typename OutputT>
113-void ViewTypeDequantTestEntry(const std::vector<int64_t>& mkn)
114-{
115- int64_t m = mkn[0];
116- int64_t k = mkn[1];
117- int64_t n = mkn[2];
118- 
119- DataType originDtype = GetAstDtype<InputT>();
120- DataType dstDtype = GetAstDtype<OutputT>();
121- 
122- std::vector<int64_t> xShape = {m, k, n};
123- std::vector<int64_t> resultShape = {m, k, 512 + 64};
124- 
125- Tensor x(originDtype, xShape, "x");
126- Tensor result(dstDtype, resultShape, "result");
127- 
128- auto goldenData = GetGoldenVec<OutputT>(resultShape, "/result.bin");
129- auto xData = CreateTensorData<InputT>(x, "/x.bin");
130- 
131- auto resultData = RawTensorData::CreateConstantTensor<OutputT>(result, 0.0);
132- 
133- std::vector<RawTensorDataPtr> inputDataList = {xData};
134- std::vector<RawTensorDataPtr> outputDataList = {resultData};
135- 
136- ViewTypeDequantTestFunc(x, result);
137- 
138-#ifdef BUILD_WITH_CANN
139- DevFuncRunner::Run(Program::GetInstance().GetLastFunction(), inputDataList, outputDataList);
140- std::cout << "====== result ======" << std::endl;
141- EXPECT_TRUE(resultCmp<OutputT>(goldenData, (OutputT*)resultData->data(), 0.005f));
142-#endif
143-}
144- 
145-TEST_F(ViewType, int8_2_float32)
146-{
147- std::vector<int64_t> mkn = {4, 32, 1024};
148- ViewTypeEntry<int8_t, float>(mkn);
149-}
150- 
151-TEST_F(ViewType, int8_2_bfloat16)
152-{
153- std::vector<int64_t> mkn = {4, 32, 1024};
154- ViewTypeEntry<int8_t, bfloat16>(mkn);
155-}
156- 
157-TEST_F(ViewType, int8_2_float16)
158-{
159- std::vector<int64_t> mkn = {4, 32, 1024};
160- ViewTypeEntry<int8_t, float16>(mkn);
161-}
162- 
163-TEST_F(ViewType, float32_2_int8)
164-{
165- std::vector<int64_t> mkn = {4, 32, 1024};
166- ViewTypeEntry<float, int8_t>(mkn);
167-}
168- 
169-TEST_F(ViewType, bfloat16_2_int8)
170-{
171- std::vector<int64_t> mkn = {4, 32, 1024};
172- ViewTypeEntry<bfloat16, int8_t>(mkn);
173-}
174- 
175-TEST_F(ViewType, float16_2_int8)
176-{
177- std::vector<int64_t> mkn = {4, 32, 1024};
178- ViewTypeEntry<float16, int8_t>(mkn);
179-}
180- 
181-TEST_F(ViewType, float16_2_float32)
182-{
183- std::vector<int64_t> mkn = {4, 32, 1024};
184- ViewTypeEntry<float16, float>(mkn);
185-}
186- 
187-TEST_F(ViewType, float32_2_float16)
188-{
189- std::vector<int64_t> mkn = {4, 32, 1024};
190- ViewTypeEntry<float, float16>(mkn);
191-}
192- 
193-TEST_F(ViewType, bfloat16_2_float32)
194-{
195- std::vector<int64_t> mkn = {4, 32, 1024};
196- ViewTypeEntry<bfloat16, float>(mkn);
197-}
198- 
199-TEST_F(ViewType, float32_2_bfloat16)
200-{
201- std::vector<int64_t> mkn = {4, 32, 1024};
202- ViewTypeEntry<float, bfloat16>(mkn);
203-}
204- 
205-TEST_F(ViewType, quant_test_bf16_2_int8)
206-{
207- std::vector<int64_t> mkn = {64, 1, 512};
208- ViewTypeQuantTestEntry<bfloat16, int8_t>(mkn);
209-}
210- 
211-TEST_F(ViewType, dequant_test_bf16_2_int8)
212-{
213- std::vector<int64_t> mkn = {2048, 1, 656};
214- ViewTypeDequantTestEntry<int8_t, bfloat16>(mkn);
215-}
@@ -1,231 +0,0 @@
1-#!/usr/bin/env python3
2-# coding: utf-8
3-# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5-# CANN Open Software License Agreement Version 2.0 (the "License").
6-# Please refer to the License for details. You may not use this file except in compliance with the License.
7-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9-# See LICENSE in the root of the software repository for the full text of the License.
10-# -----------------------------------------------------------------------------------------------------------
11-"""
12- 
13-本脚本有 2 种执行模式:
14-1. CI批跑时, 由 cmake/scripts/golden_ctrl.py 调用, 为避免日志过多, 此时 logging 级别为 logging.INFO;
15-2. 单独调试时, 本脚本单独被调用, 此时 logging 级别为 logging.DEBUG;
16-"""
17- 
18-import logging
19-import os
20-from pathlib import Path
21-import sys
22-from typing import List
23- 
24-import torch
25- 
26-project_root = os.path.dirname(os.path.abspath(__file__)) # 当前脚本目录
27-golden_parent = os.path.join(project_root, "../../../../") # 假设 golden 在上级目录
28-sys.path.insert(0, golden_parent)
29- 
30- 
31-if __name__ == "__main__":
32- """单独调试时配置"""
33- # 日志级别
34- logging.basicConfig(
35- format="%(asctime)s - %(filename)s:%(lineno)d - %(levelname)s: %(message)s",
36- level=logging.DEBUG,
37- )
38- # 系统 import 路径
39- g_src_root: Path = Path(Path(__file__).parent, "../../../../../").resolve()
40- logging.debug("SrcRoot: %s", g_src_root)
41- g_ctrl_path: Path = Path(g_src_root, "scripts")
42- if str(g_ctrl_path) not in sys.path:
43- sys.path.append(str(g_ctrl_path))
44- from golden_register import (
45- GoldenRegister,
46- ) # 单独调试 import 失败, 需确认上文中 '系统 import 路径' 配置正确
47-else:
48- from golden_register import GoldenRegister
49- 
50- 
51-def tensor_tofile(t: torch.Tensor, output: Path):
52- input_file_bin = open(str(output), "wb")
53- for each in t:
54- if t.dtype == torch.bfloat16:
55- input_file_bin.write(each.view(torch.int16).numpy().tobytes())
56- elif t.dtype == torch.float16:
57- input_file_bin.write(each.view(torch.int16).numpy().tobytes())
58- elif t.dtype == torch.float32:
59- input_file_bin.write(each.view(torch.int32).numpy().tobytes())
60- elif t.dtype == torch.int32:
61- input_file_bin.write(each.numpy().tobytes())
62- elif t.dtype == torch.int8:
63- input_file_bin.write(each.numpy().tobytes())
64- else:
65- raise ValueError(
66- f"Unsupported dtype: {t.dtype}, please add in framework/tests/st/operator/src/test_view_type.py"
67- )
68- input_file_bin.close()
69- 
70- 
71-def view_type_entry(mkn, origin_dtype, dst_dtype, output_dir: Path):
72- x_path = Path(output_dir, 'x.bin')
73- result_path = Path(output_dir, 'result.bin')
74- 
75- m, k, n = mkn
76- x_shape = [m, k, n]
77- 
78- x = torch.randint(-128, 127, x_shape, dtype=origin_dtype)
79- result = x.view(dst_dtype)
80- 
81- tensor_tofile(x, x_path)
82- tensor_tofile(result, result_path)
83- 
84- 
85-def view_type_cast_entry(mkn, origin_dtype, dst_dtype, output_dir: Path, cast_dtype):
86- x_path = Path(output_dir, 'x.bin')
87- result_path = Path(output_dir, 'result.bin')
88- 
89- m, k, n = mkn
90- x_shape = [m, k, n]
91- 
92- x = torch.randint(-128, 127, x_shape, dtype=origin_dtype)
93- result = x.view(dst_dtype).to(cast_dtype)
94- 
95- tensor_tofile(x, x_path)
96- tensor_tofile(result, result_path)
97- 
98- 
99-def view_type_quant_test_entry(output_dir: Path):
100- x_path = Path(output_dir, 'x.bin')
101- result_path = Path(output_dir, 'result.bin')
102- 
103- t, d_kv = 64, 512
104- n_kv = 1
105- 
106- def dynamic_quant(x):
107- x_dtype = x.dtype
108- x_fp32 = x.to(torch.float32)
109- max_value = torch.amax(torch.abs(x_fp32), dim=-1, keepdim=True)
110- scale_quant = 127.0 / max_value
111- y_fp32 = x_fp32 * scale_quant
112- y_fp32 = y_fp32.view(x.shape)
113- y_int32 = torch.round(y_fp32).to(torch.int32)
114- y_int8 = torch.trunc(y_int32.to(x_dtype)).to(torch.int8)
115- scale_dequant = 1.0 / scale_quant
116- return y_int8, scale_dequant
117- 
118- k_nope = torch.ones((t, n_kv, d_kv), dtype=torch.bfloat16)
119- x = k_nope
120- tensor_tofile(x, x_path)
121- 
122- k_nope = k_nope.reshape((t, n_kv, 4, d_kv // 4))
123- k_nope_int8, k_scale = dynamic_quant(k_nope)
124- 
125- k_nope_int8 = k_nope_int8.reshape((t, n_kv, d_kv))
126- k_scale = k_scale.reshape((t, n_kv, 4))
127- k_scale_view_int8 = k_scale.view(torch.int8)
128- k_combined = torch.cat((k_nope_int8, k_scale_view_int8), dim=-1)
129- 
130- result = k_combined
131- tensor_tofile(result, result_path)
132- 
133- 
134-def view_type_dequant_test_entry(output_dir: Path):
135- x_path = Path(output_dir, 'x.bin')
136- result_path = Path(output_dir, 'result.bin')
137- 
138- d_kv, d_r = 512, 64
139- n_kv = 1
140- selected_count = 2048
141- cache_combined = torch.ones((selected_count, n_kv, d_kv + 2 * d_r + 4 * 4), dtype=torch.int8)
142- cache_nope_int8 = cache_combined[:, :, :d_kv]
143- cache_rope_int8 = cache_combined[:, :, d_kv:d_kv + 2 * d_r]
144- cache_scale_int8 = cache_combined[:, :, d_kv + 2 * d_r:]
145- 
146- cache_nope_fp16 = cache_nope_int8.to(torch.float16)
147- cache_nope_fp32 = cache_nope_fp16.to(torch.float32)
148- cache_rope_bf16 = cache_rope_int8.view(torch.bfloat16)
149- cache_scale_fp32 = cache_scale_int8.view(torch.float32).reshape((selected_count, n_kv, 4, 1))
150- 
151- cache_nope_fp32 = cache_nope_fp32.reshape((selected_count, n_kv, 4, 128))
152- cache_nope = cache_nope_fp32 * cache_scale_fp32
153- cache_nope_bf16 = cache_nope.to(torch.bfloat16)
154- cache_nope_bf16_res = cache_nope_bf16.reshape((selected_count, n_kv, 512))
155- cache = torch.cat((cache_nope_bf16_res, cache_rope_bf16), dim=-1)
156- 
157- x = cache_combined
158- result = cache
159- tensor_tofile(x, x_path)
160- tensor_tofile(result, result_path)
161- 
162- 
163-@GoldenRegister.reg_golden_func(
164- case_names=[
165- "ViewType.int8_2_float32",
166- "ViewType.int8_2_bfloat16",
167- "ViewType.int8_2_float16",
168- "ViewType.float32_2_int8",
169- "ViewType.bfloat16_2_int8",
170- "ViewType.float16_2_int8",
171- "ViewType.float16_2_float32",
172- "ViewType.float32_2_float16",
173- "ViewType.bfloat16_2_float32",
174- "ViewType.float32_2_bfloat16",
175- "ViewType.int8_2_bfloat16_cast_fp32",
176- "ViewType.int8_2_float16_cast_fp32",
177- "ViewType.quant_test_bf16_2_int8",
178- "ViewType.dequant_test_bf16_2_int8",
179- ]
180-)
181-def view_type_func(case_name: str, output: Path) -> bool:
182- if case_name == "ViewType.int8_2_float32":
183- view_type_entry((4, 32, 1024), torch.int8, torch.float32, output)
184- elif case_name == "ViewType.int8_2_bfloat16":
185- view_type_entry((4, 32, 1024), torch.int8, torch.bfloat16, output)
186- elif case_name == "ViewType.int8_2_float16":
187- view_type_entry((4, 32, 1024), torch.int8, torch.float16, output)
188- elif case_name == "ViewType.float32_2_int8":
189- view_type_entry((4, 32, 1024), torch.float32, torch.int8, output)
190- elif case_name == "ViewType.bfloat16_2_int8":
191- view_type_entry((4, 32, 1024), torch.bfloat16, torch.int8, output)
192- elif case_name == "ViewType.float16_2_int8":
193- view_type_entry((4, 32, 1024), torch.float16, torch.int8, output)
194- elif case_name == "ViewType.float16_2_float32":
195- view_type_entry((4, 32, 1024), torch.float16, torch.float32, output)
196- elif case_name == "ViewType.float32_2_float16":
197- view_type_entry((4, 32, 1024), torch.float32, torch.float16, output)
198- elif case_name == "ViewType.bfloat16_2_float32":
199- view_type_entry((4, 32, 1024), torch.bfloat16, torch.float32, output)
200- elif case_name == "ViewType.float32_2_bfloat16":
201- view_type_entry((4, 32, 1024), torch.float32, torch.bfloat16, output)
202- elif case_name == "ViewType.int8_2_bfloat16_cast_fp32":
203- view_type_cast_entry((4, 32, 1024), torch.int8, torch.bfloat16, output, torch.float32)
204- elif case_name == "ViewType.int8_2_float16_cast_fp32":
205- view_type_cast_entry((4, 32, 1024), torch.int8, torch.float16, output, torch.float32)
206- elif case_name == "ViewType.quant_test_bf16_2_int8":
207- view_type_quant_test_entry(output)
208- elif case_name == "ViewType.dequant_test_bf16_2_int8":
209- view_type_dequant_test_entry(output)
210- else:
211- logging.error("Can't get func to gen golden, Case(%s)", case_name)
212- return False
213- return True
214- 
215- 
216-def main() -> bool:
217- """
218- 单独调试 入口函数
219- """
220- case_name_list: List[str] = []
221- 
222- for cs in case_name_list:
223- output = Path(g_src_root, "build/tests/st/golden", cs).resolve()
224- output.mkdir(parents=True, exist_ok=True)
225- ret = view_type_func(case_name=cs, output=output)
226- 
227- return ret
228- 
229- 
230-if __name__ == "__main__":
231- exit(0 if main() else 1)
@@ -10,7 +10,6 @@
10 10 
11if (ENABLE_UTEST)11if (ENABLE_UTEST)
12 add_subdirectory(utils)12 add_subdirectory(utils)
13- PTO_Fwk_UTest_AddModuleDir(DIR operator)
14 PTO_Fwk_UTest_AddModuleDir(DIR interface)13 PTO_Fwk_UTest_AddModuleDir(DIR interface)
15 PTO_Fwk_UTest_AddModuleDir(DIR passes)14 PTO_Fwk_UTest_AddModuleDir(DIR passes)
16 if (NOT ENABLE_ASAN)15 if (NOT ENABLE_ASAN)
@@ -17,5 +17,5 @@ PTO_Fwk_UTest_AddCaseLib(
17 TARGET ${_Target}17 TARGET ${_Target}
18 SOURCES ${_Sources}18 SOURCES ${_Sources}
19 PRIVATE_INCLUDE_DIRECTORIES ${_Include}19 PRIVATE_INCLUDE_DIRECTORIES ${_Include}
20- LINK_LIBRARIES tile_fwk_operator20+ LINK_LIBRARIES
21)21)
@@ -20,7 +20,7 @@ PTO_Fwk_UTest_AddCaseLib(
20 TARGET ${_Target}20 TARGET ${_Target}
21 SOURCES ${_Sources}21 SOURCES ${_Sources}
22 PRIVATE_INCLUDE_DIRECTORIES ${_Include}22 PRIVATE_INCLUDE_DIRECTORIES ${_Include}
23- LINK_LIBRARIES tile_fwk_runtime tile_fwk_operator dl23+ LINK_LIBRARIES tile_fwk_runtime dl
24)24)
25target_compile_definitions(${_Target}25target_compile_definitions(${_Target}
26 PRIVATE26 PRIVATE
@@ -1,24 +0,0 @@
1-# -----------------------------------------------------------------------------------------------------------
2-# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
3-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4-# CANN Open Software License Agreement Version 2.0 (the "License").
5-# Please refer to the License for details. You may not use this file except in compliance with the License.
6-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8-# See LICENSE in the root of the software repository for the full text of the License.
9-# -----------------------------------------------------------------------------------------------------------
10- 
11-set(_Target ${PTO_Fwk_UTestNamePrefix}_operator)
12- 
13-file(GLOB_RECURSE _Sources src/*.cpp)
14- 
15-set(LinkLibraries tile_fwk_operator)
16-if (TARGET tile_fwk_calculator)
17- list(APPEND LinkLibraries tile_fwk_calculator)
18-endif ()
19- 
20-PTO_Fwk_UTest_AddCaseLib(
21- TARGET ${_Target}
22- SOURCES ${_Sources}
23- LINK_LIBRARIES ${LinkLibraries}
24-)
@@ -1,49 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_dynamic_softmax.cpp
13- * \brief
14- */
15- 
16-#include "gtest/gtest.h"
17-#include "tilefwk/tilefwk_op.h"
18- 
19-#include "tilefwk/tilefwk.h"
20-#include "interface/inner/tilefwk.h"
21-#include "interface/tensor/logical_tensor.h"
22-#include "interface/tensor/raw_tensor.h"
23-#include "interface/interpreter/raw_tensor_data.h"
24-#include "interface/configs/config_manager.h"
25-#include "interface/tensor/float.h"
26- 
27-using namespace npu::tile_fwk;
28- 
29-class DynamicSoftmaxUtest : public testing::Test {
30-public:
31- static void SetUpTestCase() {}
32- 
33- static void TearDownTestCase() {}
34- 
35- void SetUp() override { Program::GetInstance().Reset(); }
36- 
37- void TearDown() override {}
38-};
39- 
40-TEST_F(DynamicSoftmaxUtest, utest_softmax_dyn)
41-{
42- TileShape::Current().SetVecTile({4, 4, 1, 64});
43- std::vector<int64_t> shape = {32, 32, 1, 256};
44- DataType dtype = DataType::DT_FP32;
45- Tensor input(dtype, shape, "input");
46- Tensor output(dtype, shape, "output");
47- 
48- SoftmaxDynamic(input, output);
49-}
@@ -1,170 +0,0 @@
1-// /**
2-// * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3-// * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4-// * CANN Open Software License Agreement Version 2.0 (the "License").
5-// * Please refer to the License for details. You may not use this file except in compliance with the License.
6-// * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7-// * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8-// * See LICENSE in the root of the software repository for the full text of the License.
9-// */
10- 
11-// /*!
12-// * \file test_graph_only.cpp
13-// * \brief
14-// */
15- 
16-// #include "gtest/gtest.h"
17- 
18-// #include "interface/tensor/logical_tensor.h"
19-// #include "interface/configs/config_manager.h"
20-// #include "tilefwk/tilefwk.h"
21-// #include "interface/inner/tilefwk.h"
22-// #include "operator/models/llama/llama_def.h"
23-// #include "tilefwk/data_type.h"
24- 
25-// using namespace npu::tile_fwk;
26- 
27-// constexpr int NUM_2 = 2;
28-// constexpr int NUM_8 = 8;
29-// constexpr int NUM_128 = 128;
30- 
31-// class GraphTest : public testing::Test {
32-// public:
33-// static void SetUpTestCase() {}
34- 
35-// static void TearDownTestCase() {}
36- 
37-// void SetUp() override
38-// {
39-// Program::GetInstance().Reset();
40-// config::Reset();
41-// config::SetHostOption(COMPILE_STAGE, CS_EXECUTE_GRAPH);
42-// config::SetHostConfig(KEY_STRATEGY, "PVC2_OOO");
43-// config::SetPlatformConfig(KEY_ENABLE_COST_MODEL, false);
44-// config::SetSimConfig(KEY_BUILD_TASK_BASED_TOPO, false);
45-// }
46- 
47-// void TearDown() override {}
48-// };
49- 
50-// void RunLLamaLayerGraph(const AttentionDims& dimsCfg)
51-// {
52-// int b = dimsCfg.b;
53-// int n = dimsCfg.n;
54-// int s = dimsCfg.s;
55-// int d = dimsCfg.d;
56-// PROGRAM("LLAMALAYER")
57-// {
58-// Tensor H(DataType::DT_FP32, {b * s, n * d}, "H");
59-// Tensor AW(DataType::DT_FP16, {n * d, n * d * 3}, "AW");
60-// Tensor DW(DataType::DT_FP16, {n * d, n * d}, "DW");
61-// Tensor FW(DataType::DT_FP16, {n * d, n * d * 3}, "FW");
62-// Tensor Res(DT_FP32, {b * s, n * d}, "Res");
63-// FUNCTION("LLAMA") { Res = LlamaLayer(H, AW, DW, FW, dimsCfg, SMALL_DFS_VEC_CFG, DFS_CUBE_CFG); }
64-// }
65-// }
66- 
67-// TEST_F(GraphTest, llama_1_1_128_128)
68-// {
69-// AttentionDims dimsCfg = {1, 1, 128, 128, DFT_SINGLE_M, DFT_SINGLE_N};
70-// RunLLamaLayerGraph(dimsCfg);
71-// }
72- 
73-// TEST_F(GraphTest, llama_1_1_256_128)
74-// {
75-// AttentionDims dimsCfg = {1, 1, 256, 128, DFT_SINGLE_M, DFT_SINGLE_N};
76-// RunLLamaLayerGraph(dimsCfg);
77-// }
78- 
79-// // TEST_F(GraphTest, llama_1_1_512_128)
80-// // {
81-// // AttentionDims dimsCfg = {1, 1, 512, 128, DFT_SINGLE_M, DFT_SINGLE_N};
82-// // RunLLamaLayerGraph(dimsCfg);
83-// // }
84- 
85-// TEST_F(GraphTest, llama_1_1_256_128_mix)
86-// {
87-// config::SetPassConfig("PVC2_OOO", "PreGraphProcess", KEY_PRE_CHECK, false);
88-// config::SetPassConfig("PVC2_OOO", "PreGraphProcess", KEY_POST_CHECK, false);
89-// AttentionDims dimsCfg = {1, 1, 256, 128, DFT_SINGLE_M, DFT_SINGLE_N};
90-// RunLLamaLayerGraph(dimsCfg);
91-// }
92- 
93-// void TestLoopTailBlock(const Tensor& t0, const Tensor& blockTable, Tensor& out, int s)
94-// {
95-// int blockSize = 64;
96- 
97-// FUNCTION("main", {t0, blockTable}, {out})
98-// {
99-// LOOP("L0", FunctionType::DYNAMIC_LOOP, i, LoopRange(GetInputShape(t0, 0) / s))
100-// {
101-// SymbolicScalar size = GetTensorData(blockTable, {i, 0});
102-// Tensor t0s = View(t0, {s, s}, {size, s}, {blockSize * i, 0});
103-// Tensor t1s = View(t0, {s / 2, s}, {size, s}, {blockSize * i, 0});
104-// Tensor t1 = Add(t1s, t1s);
105-// Assemble(t1, {blockSize * i, 0}, out);
106-// }
107-// }
108-// }
109- 
110-// TEST_F(GraphTest, TestTailBlock)
111-// {
112-// TileShape::Current().SetVecTile(32, 32);
113-// TileShape::Current().SetCubeTile({32, 32}, {32, 32}, {32, 32});
114-// int s = 64;
115-// int n = 8;
116-// Tensor t0(DT_FP32, {n * s, s}, "t0"); // [32*8, 32]
117-// Tensor blockTable{DT_INT32, {n, 1}, "blockTable"};
118-// Tensor out(DT_FP32, {n * s, s}, "out");
119-// TestLoopTailBlock(t0, blockTable, out, s);
120-// }
121- 
122-// TEST_F(GraphTest, TestTranspose_MLA_3D_2_add)
123-// {
124-// int bs = 8;
125-// int n = 32;
126-// int d = 128;
127-// std::vector<int64_t> shape{bs, n, d};
128-// std::vector<int64_t> resShape{n, bs, d};
129-// PROGRAM("Transpose")
130-// {
131-// Tensor input(DataType::DT_FP32, shape, "input");
132-// Tensor output(DataType::DT_FP32, resShape, "res");
133-// config::SetBuildStatic(true);
134-// FUNCTION("MLA_3D_2", {input, output})
135-// {
136-// TileShape::Current().SetVecTile(NUM_2, NUM_2, NUM_128);
137-// auto tmp = Transpose(input, {0, 1});
138-// TileShape::Current().SetVecTile(NUM_8, NUM_8, NUM_128);
139-// output = Add(tmp, Element(DataType::DT_FP32, 0.0));
140-// }
141-// }
142-// }
143- 
144-// TEST_F(GraphTest, TestTranspose_MLA_3D_2_reshape)
145-// {
146-// int bs = 8;
147-// int n = 32;
148-// int d = 128;
149-// std::vector<int64_t> shape{bs, n, d};
150-// std::vector<int64_t> transposeShape{n, bs, d};
151-// std::vector<int64_t> resShape{n, bs * d};
152-// std::vector<int64_t> flattenShape{n * bs * d};
153- 
154-// PROGRAM("Transpose")
155-// {
156-// Tensor input(DataType::DT_FP32, shape, "input");
157-// Tensor output1(DataType::DT_FP32, transposeShape, "res1");
158-// Tensor output2(DataType::DT_FP32, resShape, "res2");
159-// Tensor output3(DataType::DT_FP32, flattenShape, "res3");
160-// config::SetBuildStatic(true);
161-// FUNCTION("MLA_3D_2", {input, output1, output2})
162-// {
163-// TileShape::Current().SetVecTile(NUM_2, NUM_2, NUM_128);
164-// output1 = Transpose(input, {0, 1}); // [8, 32, 128] --> [32, 8, 128]
165-// TileShape::Current().SetVecTile(NUM_8, NUM_8, NUM_128);
166-// output2 = Reshape(output1, resShape); // [32, 8, 128] --> [32, 1024]
167-// output3 = Reshape(output1, {-1}); // [32, 8, 128] --> [32 * 8 * 128]
168-// }
169-// }
170-// }
@@ -1,95 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_parallel_sort.cpp
13- * \brief
14- */
15-#include "gtest/gtest.h"
16-#include "tilefwk/tilefwk_op.h"
17-#include "interface/inner/tilefwk.h"
18- 
19-using namespace npu::tile_fwk;
20- 
21-class ParallelSortUTest : public testing::Test {
22-public:
23- static void SetUpTestCase() {}
24- 
25- static void TearDownTestCase() {}
26- 
27- void SetUp() override { Program::GetInstance().Reset(); }
28- 
29- void TearDown() override {}
30-};
31- 
32-struct SortParams {
33- int length;
34- int tileSize;
35- int descending;
36-};
37- 
38-template <typename T = float, typename idxT = int>
39-void SortTest(const SortParams& params)
40-{
41- int length = params.length;
42- int tileSize = params.tileSize;
43- int descending = params.descending;
44- 
45- DataType dType = DT_FP32;
46- DataType idxDType = DT_INT32;
47- std::vector<int64_t> shape = {1, length};
48- 
49- Tensor x(dType, shape, "x");
50- Tensor y(dType, shape, "y");
51- Tensor yIdx(idxDType, shape, "yIdx");
52- 
53- config::SetBuildStatic(true);
54- FUNCTION("Sort", {x, y, yIdx})
55- {
56- TileShape::Current().SetVecTile({1, tileSize});
57- std::tie(y, yIdx) = Sort(x, descending);
58- }
59-}
60- 
61-template <typename T = float, typename idxT = int>
62-void SortWithIndexTest(const SortParams& params)
63-{
64- int length = params.length;
65- int tileSize = params.tileSize;
66- int descending = params.descending;
67- 
68- DataType dType = DT_FP32;
69- DataType idxDType = DT_INT32;
70- std::vector<int64_t> shape = {1, length};
71- 
72- Tensor x(dType, shape, "x");
73- Tensor idx(idxDType, shape, "idx");
74- Tensor y(dType, shape, "y");
75- Tensor yIdx(idxDType, shape, "yIdx");
76- 
77- config::SetBuildStatic(true);
78- FUNCTION("Sort", {x, idx, y, yIdx})
79- {
80- TileShape::Current().SetVecTile({1, tileSize});
81- std::tie(y, yIdx) = SortWithIndex(x, idx, descending);
82- }
83-}
84- 
85-TEST_F(ParallelSortUTest, fp32_64k_8k)
86-{
87- SortParams params = {1024 * 64, 1024 * 8, true};
88- SortTest(params);
89-}
90- 
91-TEST_F(ParallelSortUTest, withindex_fp32_64k_8k)
92-{
93- SortParams params = {1024 * 64, 1024 * 8, true};
94- SortWithIndexTest(params);
95-}
@@ -1,139 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_quant.cpp
13- * \brief UT for Quant and Matrix::QuantMM operators
14- */
15- 
16-#include "gtest/gtest.h"
17-#include "tilefwk/tilefwk_op.h"
18- 
19-#include "tilefwk/tilefwk.h"
20-#include "interface/inner/tilefwk.h"
21-#include "interface/tensor/logical_tensor.h"
22-#include "interface/configs/config_manager.h"
23- 
24-using namespace npu::tile_fwk;
25- 
26-class QuantUtest : public testing::Test {
27-public:
28- static void SetUpTestCase() {}
29- 
30- static void TearDownTestCase() {}
31- 
32- void SetUp() override { Program::GetInstance().Reset(); }
33- 
34- void TearDown() override {}
35-};
36- 
37-TEST_F(QuantUtest, quant_symmetric_no_smooth_fp32)
38-{
39- TileShape::Current().SetVecTile({4, 128});
40- std::vector<int64_t> shape = {4, 128};
41- Tensor input(DT_FP32, shape, "input");
42- 
43- FUNCTION("QuantSymNoSmooth_fp32") { auto result = Quant(input); }
44-}
45- 
46-TEST_F(QuantUtest, quant_symmetric_no_smooth_bf16)
47-{
48- TileShape::Current().SetVecTile({4, 128});
49- std::vector<int64_t> shape = {8, 128};
50- Tensor input(DT_BF16, shape, "input");
51- 
52- FUNCTION("QuantSymNoSmooth_bf16") { auto result = Quant(input, true, false, Tensor()); }
53-}
54- 
55-TEST_F(QuantUtest, quant_symmetric_with_smooth)
56-{
57- TileShape::Current().SetVecTile({4, 128});
58- std::vector<int64_t> shape = {4, 128};
59- Tensor input(DT_FP32, shape, "input");
60- Tensor smoothFactor(DT_FP32, shape, "smoothFactor");
61- 
62- FUNCTION("QuantSymWithSmooth") { auto result = Quant(input, true, true, smoothFactor); }
63-}
64- 
65-TEST_F(QuantUtest, quant_asymmetric_no_smooth)
66-{
67- TileShape::Current().SetVecTile({4, 128});
68- std::vector<int64_t> shape = {4, 128};
69- Tensor input(DT_FP32, shape, "input");
70- 
71- FUNCTION("QuantAsymNoSmooth") { auto result = Quant(input, false, false, Tensor()); }
72-}
73- 
74-TEST_F(QuantUtest, quant_asymmetric_with_smooth)
75-{
76- TileShape::Current().SetVecTile({4, 128});
77- std::vector<int64_t> shape = {4, 128};
78- Tensor input(DT_FP32, shape, "input");
79- Tensor smoothFactor(DT_FP32, shape, "smoothFactor");
80- 
81- FUNCTION("QuantAsymWithSmooth") { auto result = Quant(input, false, true, smoothFactor); }
82-}
83- 
84-class QuantMMUtest : public testing::Test {
85-public:
86- static void SetUpTestCase() {}
87- 
88- static void TearDownTestCase() {}
89- 
90- void SetUp() override { Program::GetInstance().Reset(); }
91- 
92- void TearDown() override {}
93-};
94- 
95-TEST_F(QuantMMUtest, quant_mm_2d)
96-{
97- TileShape::Current().SetVecTile({4, 64});
98- TileShape::Current().SetCubeTile({16, 16}, {32, 32, 32}, {32, 32});
99- int64_t m = 32;
100- int64_t k = 128;
101- int64_t n = 64;
102- 
103- Tensor operand1(DT_BF16, {m, k}, "operand1");
104- Tensor operand2(DT_INT8, {k, n}, "operand2");
105- Tensor dequantScaleW(DT_FP32, {1, n}, "dequantScaleW");
106- 
107- FUNCTION("QuantMM_2d") { auto output = Matrix::QuantMM(operand1, operand2, dequantScaleW); }
108-}
109- 
110-TEST_F(QuantMMUtest, quant_mm_3d)
111-{
112- TileShape::Current().SetVecTile({1, 4, 64});
113- TileShape::Current().SetCubeTile({16, 16}, {32, 32, 32}, {32, 32});
114- int64_t b = 2;
115- int64_t m = 32;
116- int64_t k = 128;
117- int64_t n = 64;
118- 
119- Tensor operand1(DT_BF16, {b, m, k}, "operand1");
120- Tensor operand2(DT_INT8, {b, k, n}, "operand2");
121- Tensor dequantScaleW(DT_FP32, {1, n}, "dequantScaleW");
122- 
123- FUNCTION("QuantMM_3d") { auto output = Matrix::QuantMM(operand1, operand2, dequantScaleW); }
124-}
125- 
126-TEST_F(QuantMMUtest, quant_mm_4d_invalid_asserts)
127-{
128- TileShape::Current().SetVecTile({1, 1, 4, 64});
129- TileShape::Current().SetCubeTile({16, 16}, {32, 32, 32}, {32, 32});
130- 
131- Tensor operand1(DT_BF16, {2, 32, 128, 4}, "operand1");
132- Tensor operand2(DT_INT8, {128, 64}, "operand2");
133- Tensor dequantScaleW(DT_FP32, {1, 64}, "dequantScaleW");
134- 
135- EXPECT_ANY_THROW({
136- FUNCTION("QuantMM_4d_invalid") { auto output = Matrix::QuantMM(operand1, operand2, dequantScaleW);
137-}
138-});
139-}
@@ -1,85 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_rms_norm.cpp
13- * \brief UT for RmsNorm operator (both overloads)
14- */
15- 
16-#include "gtest/gtest.h"
17-#include "tilefwk/tilefwk_op.h"
18- 
19-#include "tilefwk/tilefwk.h"
20-#include "interface/inner/tilefwk.h"
21-#include "interface/tensor/logical_tensor.h"
22-#include "interface/configs/config_manager.h"
23- 
24-using namespace npu::tile_fwk;
25- 
26-class RmsNormUtest : public testing::Test {
27-public:
28- static void SetUpTestCase() {}
29- 
30- static void TearDownTestCase() {}
31- 
32- void SetUp() override { Program::GetInstance().Reset(); }
33- 
34- void TearDown() override {}
35-};
36- 
37-TEST_F(RmsNormUtest, rms_norm_without_gamma_fp32)
38-{
39- TileShape::Current().SetVecTile({1, 128});
40- std::vector<int64_t> shape = {4, 128};
41- Tensor input(DT_FP32, shape, "input");
42- 
43- FUNCTION("RmsNormNoGamma_fp32") { auto output = RmsNorm(input); }
44-}
45- 
46-TEST_F(RmsNormUtest, rms_norm_without_gamma_bf16)
47-{
48- TileShape::Current().SetVecTile({1, 128});
49- std::vector<int64_t> shape = {2, 128};
50- Tensor input(DT_BF16, shape, "input");
51- 
52- FUNCTION("RmsNormNoGamma_bf16") { auto output = RmsNorm(input); }
53-}
54- 
55-TEST_F(RmsNormUtest, rms_norm_with_gamma_fp32)
56-{
57- TileShape::Current().SetVecTile({1, 128});
58- std::vector<int64_t> shape = {4, 128};
59- Tensor input(DT_FP32, shape, "input");
60- Tensor gamma(DT_FP32, {128}, "gamma");
61- float epsilon = 1e-6f;
62- 
63- FUNCTION("RmsNormWithGamma_fp32") { auto output = RmsNorm(input, gamma, epsilon); }
64-}
65- 
66-TEST_F(RmsNormUtest, rms_norm_with_gamma_bf16)
67-{
68- TileShape::Current().SetVecTile({1, 128});
69- std::vector<int64_t> shape = {2, 128};
70- Tensor input(DT_BF16, shape, "input");
71- Tensor gamma(DT_BF16, {128}, "gamma");
72- float epsilon = 1e-5f;
73- 
74- FUNCTION("RmsNormWithGamma_bf16") { auto output = RmsNorm(input, gamma, epsilon); }
75-}
76- 
77-TEST_F(RmsNormUtest, rms_norm_with_gamma_custom_epsilon)
78-{
79- TileShape::Current().SetVecTile({1, 64});
80- std::vector<int64_t> shape = {8, 64};
81- Tensor input(DT_FP32, shape, "input");
82- Tensor gamma(DT_FP32, {64}, "gamma");
83- 
84- FUNCTION("RmsNormWithGamma_customEps") { auto output = RmsNorm(input, gamma, 1e-3f); }
85-}
@@ -1,80 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_softmax.cpp
13- * \brief UT for Softmax and SoftmaxNew operators
14- */
15- 
16-#include "gtest/gtest.h"
17-#include "tilefwk/tilefwk_op.h"
18- 
19-#include "tilefwk/tilefwk.h"
20-#include "interface/inner/tilefwk.h"
21-#include "interface/tensor/logical_tensor.h"
22-#include "interface/configs/config_manager.h"
23- 
24-using namespace npu::tile_fwk;
25- 
26-class SoftmaxUtest : public testing::Test {
27-public:
28- static void SetUpTestCase() {}
29- 
30- static void TearDownTestCase() {}
31- 
32- void SetUp() override { Program::GetInstance().Reset(); }
33- 
34- void TearDown() override {}
35-};
36- 
37-TEST_F(SoftmaxUtest, softmax_fp32)
38-{
39- TileShape::Current().SetVecTile({4, 64});
40- std::vector<int64_t> shape = {4, 64};
41- Tensor input(DT_FP32, shape, "input");
42- 
43- FUNCTION("Softmax_fp32") { auto output = Softmax(input); }
44-}
45- 
46-TEST_F(SoftmaxUtest, softmax_bf16)
47-{
48- TileShape::Current().SetVecTile({4, 64});
49- std::vector<int64_t> shape = {4, 64};
50- Tensor input(DT_BF16, shape, "input");
51- 
52- FUNCTION("Softmax_bf16") { auto output = Softmax(input); }
53-}
54- 
55-TEST_F(SoftmaxUtest, softmax_new_fp32_no_cast)
56-{
57- TileShape::Current().SetVecTile({4, 1, 1, 64});
58- std::vector<int64_t> shape = {4, 4, 1, 64};
59- Tensor input(DT_FP32, shape, "input");
60- 
61- FUNCTION("SoftmaxNew_fp32") { auto output = SoftmaxNew(input); }
62-}
63- 
64-TEST_F(SoftmaxUtest, softmax_new_bf16_triggers_cast)
65-{
66- TileShape::Current().SetVecTile({4, 1, 1, 64});
67- std::vector<int64_t> shape = {2, 4, 1, 64};
68- Tensor input(DT_BF16, shape, "input");
69- 
70- FUNCTION("SoftmaxNew_bf16") { auto output = SoftmaxNew(input); }
71-}
72- 
73-TEST_F(SoftmaxUtest, softmax_new_fp16_triggers_cast)
74-{
75- TileShape::Current().SetVecTile({4, 1, 1, 64});
76- std::vector<int64_t> shape = {2, 4, 1, 64};
77- Tensor input(DT_FP16, shape, "input");
78- 
79- FUNCTION("SoftmaxNew_fp16") { auto output = SoftmaxNew(input); }
80-}
@@ -1,92 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file test_view_type.cpp
13- * \brief
14- */
15- 
16-#include "gtest/gtest.h"
17-#include "tilefwk/tilefwk_op.h"
18- 
19-#include "tilefwk/tilefwk.h"
20-#include "interface/inner/tilefwk.h"
21-#include "interface/tensor/logical_tensor.h"
22-#include "interface/tensor/raw_tensor.h"
23-#include "interface/interpreter/raw_tensor_data.h"
24-#include "interface/configs/config_manager.h"
25-#include "interface/tensor/float.h"
26-#include "operator/models/nsa/view_type.h"
27- 
28-using namespace npu::tile_fwk;
29- 
30-class ViewTypeUtest : public testing::Test {
31-public:
32- static void SetUpTestCase() { config::SetCodeGenConfig(KEY_CODEGEN_SUPPORT_TILE_TENSOR, false); }
33- 
34- static void TearDownTestCase() { config::SetCodeGenConfig(KEY_CODEGEN_SUPPORT_TILE_TENSOR, true); }
35- 
36- void SetUp() override { Program::GetInstance().Reset(); }
37- 
38- void TearDown() override {}
39-};
40- 
41-TEST_F(ViewTypeUtest, add0_test)
42-{
43- int64_t m = 4;
44- int64_t k = 32;
45- int64_t n = 1024;
46- 
47- DataType originDtype = DT_INT8;
48- DataType dstDtype = DT_FP32;
49- float factor = (float)BytesOf(originDtype) / (float)BytesOf(dstDtype);
50- 
51- std::vector<int64_t> xShape = {m, k, n};
52- std::vector<int64_t> resultShape = {m, k, int(n * factor)};
53- 
54- Tensor x(originDtype, xShape, "x");
55- Tensor result(dstDtype, resultShape, "result");
56- 
57- ViewTypeFunc(x, result, dstDtype);
58-}
59- 
60-TEST_F(ViewTypeUtest, quant_test)
61-{
62- int64_t m = 64;
63- int64_t k = 1;
64- int64_t n = 512;
65- 
66- DataType originDtype = DT_BF16;
67- DataType dstDtype = DT_INT8;
68- std::vector<int64_t> xShape = {m, k, n};
69- std::vector<int64_t> resultShape = {m, k, n + 16};
70- 
71- Tensor x(originDtype, xShape, "x");
72- Tensor result(dstDtype, resultShape, "result");
73- 
74- ViewTypeQuantTestFunc(x, result);
75-}
76- 
77-TEST_F(ViewTypeUtest, dequant_test)
78-{
79- int64_t m = 2048;
80- int64_t k = 1;
81- int64_t n = 656;
82- 
83- DataType originDtype = DT_INT8;
84- DataType dstDtype = DT_BF16;
85- std::vector<int64_t> xShape = {m, k, n};
86- std::vector<int64_t> resultShape = {m, k, 512 + 64};
87- 
88- Tensor x(originDtype, xShape, "x");
89- Tensor result(dstDtype, resultShape, "result");
90- 
91- ViewTypeDequantTestFunc(x, result);
92-}
@@ -15,7 +15,7 @@ file(GLOB_RECURSE _Sources src/*.cpp)
15PTO_Fwk_UTest_AddCaseLib(15PTO_Fwk_UTest_AddCaseLib(
16 TARGET ${_Target}16 TARGET ${_Target}
17 SOURCES ${_Sources}17 SOURCES ${_Sources}
18- LINK_LIBRARIES tile_fwk_operator18+ LINK_LIBRARIES
19)19)
20add_custom_command(20add_custom_command(
21 TARGET ${_Target} PRE_BUILD21 TARGET ${_Target} PRE_BUILD
@@ -16,7 +16,7 @@ PTO_Fwk_UTest_AddCaseLib(
16 TARGET ${_Target}16 TARGET ${_Target}
17 SOURCES ${_Sources}17 SOURCES ${_Sources}
18 PRIVATE_INCLUDE_DIRECTORIES ${PTO_FWK_SRC_ROOT}/framework/src/cost_model18 PRIVATE_INCLUDE_DIRECTORIES ${PTO_FWK_SRC_ROOT}/framework/src/cost_model
19- LINK_LIBRARIES tile_fwk_operator tile_fwk_simulation dl19+ LINK_LIBRARIES tile_fwk_simulation dl
20)20)
21add_dependencies(${_Target} tile_fwk_simulation_pv)21add_dependencies(${_Target} tile_fwk_simulation_pv)
22 22 
@@ -17,7 +17,7 @@
17#include <dlfcn.h>17#include <dlfcn.h>
18 18 
19#include "cost_model/simulation/backend.h"19#include "cost_model/simulation/backend.h"
20-#include "operator/models/llama/llama_def.h"20+ 
21#include "cost_model/simulation/common/CommonType.h"21#include "cost_model/simulation/common/CommonType.h"
22#include "tilefwk/tilefwk.h"22#include "tilefwk/tilefwk.h"
23#include "interface/inner/tilefwk.h"23#include "interface/inner/tilefwk.h"
@@ -52,30 +52,6 @@ public:
52 void TearDown() override {}52 void TearDown() override {}
53};53};
54 54 
55-void RunLLamaLayerCostModel(const AttentionDims& dimsCfg, float threadhold = 0.001f)
56-{
57- (void)threadhold;
58- int b = dimsCfg.b;
59- int n = dimsCfg.n;
60- int s = dimsCfg.s;
61- int d = dimsCfg.d;
62- 
63- PROGRAM("LLAMALAYER")
64- {
65- Tensor H(DataType::DT_FP32, {b * s, n * d}, "H");
66- Tensor AW(DataType::DT_FP16, {n * d, n * d * 3}, "AW");
67- Tensor DW(DataType::DT_FP16, {n * d, n * d}, "DW");
68- Tensor FW(DataType::DT_FP16, {n * d, n * d * 3}, "FW");
69- Tensor Res(DT_FP32, {b * s, n * d}, "Res");
70- config::SetBuildStatic(true);
71- FUNCTION("LLAMA", {H, AW, DW, FW, Res})
72- {
73- Res = LlamaLayer(H, AW, DW, FW, dimsCfg, SMALL_DFS_VEC_CFG, DFS_CUBE_CFG);
74- }
75- config::SetPassStrategy("OOO");
76- }
77-}
78- 
79void RunMatrixCostModel()55void RunMatrixCostModel()
80{56{
81 int bs = 1;57 int bs = 1;
Rframework/src/operator/quantize/quant.cpp→framework/tests/ut/utils/operator_stubs.cpp+51-43
@@ -1,27 +1,58 @@
1/**1/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.2+ * Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
3 * This program is free software, you can redistribute it and/or modify it under the terms and conditions of3 * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").4+ * CANN Open Software License Version 2.0 (the "License").
5 * Please refer to the License for details. You may not use this file except in compliance with the License.5 * Please refer to the License for details. You may not use this file except in compliance with the License.
6 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,6 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.7 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 * See LICENSE in the root of the software repository for the full text of the License.8 * See LICENSE in the root of the software repository for the full text of the License.
9 */9 */
10 10 
11-/*!
12- * \file quant.cpp
13- * \brief
14- */
15- 
16#include "tilefwk/tilefwk.h"11#include "tilefwk/tilefwk.h"
17#include "interface/inner/tilefwk.h"12#include "interface/inner/tilefwk.h"
18-using namespace npu::tile_fwk;
19 13 
20namespace npu::tile_fwk {14namespace npu::tile_fwk {
21-constexpr float F_1 = 1.0;15+ 
22-constexpr float F_127 = 127.0;16+constexpr float STUB_F_1 = 1.0;
23-constexpr float F_255 = 255.0;17+constexpr float STUB_F_NEGA_1 = -1.0;
24-constexpr float F_1E_12 = 1e-12f;18+constexpr float STUB_F_127 = 127.0;
19+constexpr float STUB_F_255 = 255.0;
20+constexpr float STUB_F_1E_12 = 1e-12f;
21+ 
22+Tensor Sigmoid(Tensor& input)
23+{
24+ auto dtype = input.GetStorage()->Datatype();
25+ if (dtype != DT_FP32) {
26+ input = Cast(input, DataType::DT_FP32);
27+ }
28+ auto expRes = Exp(Mul(input, Element(DataType::DT_FP32, STUB_F_NEGA_1)));
29+ auto res = Add(expRes, Element(DataType::DT_FP32, STUB_F_1));
30+ Element src(DataType::DT_FP32, 1.0f);
31+ auto ones = Full(src, DataType::DT_FP32, res.GetShape());
32+ res = Div(ones, res);
33+ if (dtype != DT_FP32) {
34+ res = Cast(res, dtype);
35+ }
36+ return res;
37+}
38+ 
39+Tensor SoftmaxNew(const Tensor& operand)
40+{
41+ auto inputDtype = operand.GetStorage()->Datatype();
42+ Tensor castOperand = operand;
43+ if (inputDtype != DataType::DT_FP32) {
44+ castOperand = Cast(operand, DataType::DT_FP32);
45+ }
46+ auto rowmax = Amax(castOperand, -1, true);
47+ auto sub = Sub(castOperand, rowmax);
48+ auto exp = Exp(sub);
49+ auto esum = Sum(exp, -1, true);
50+ auto softmax = Div(exp, esum);
51+ if (inputDtype != softmax.GetStorage()->Datatype()) {
52+ softmax = Cast(softmax, inputDtype);
53+ }
54+ return softmax;
55+}
25 56 
26std::tuple<Tensor, Tensor> Quant(const Tensor& input, bool isSymmetry, bool hasSmoothFactor, const Tensor& smoothFactor)57std::tuple<Tensor, Tensor> Quant(const Tensor& input, bool isSymmetry, bool hasSmoothFactor, const Tensor& smoothFactor)
27{58{
@@ -29,25 +60,24 @@ std::tuple<Tensor, Tensor> Quant(const Tensor& input, bool isSymmetry, bool hasS
29 if (hasSmoothFactor) {60 if (hasSmoothFactor) {
30 inputFp32 = Mul(inputFp32, smoothFactor);61 inputFp32 = Mul(inputFp32, smoothFactor);
31 }62 }
32- // perToken
33 if (isSymmetry) {63 if (isSymmetry) {
34 auto absRes = Abs(inputFp32);64 auto absRes = Abs(inputFp32);
35 auto maxValue = Amax(absRes, -1, true);65 auto maxValue = Amax(absRes, -1, true);
36- auto scaleQuant = ScalarDivS(maxValue, Element(DataType::DT_FP32, F_127), true);66+ auto scaleQuant = ScalarDivS(maxValue, Element(DataType::DT_FP32, STUB_F_127), true);
37 auto outFp32 = Mul(inputFp32, scaleQuant);67 auto outFp32 = Mul(inputFp32, scaleQuant);
38 auto outInt32 = Cast(outFp32, DataType::DT_INT32, CAST_RINT);68 auto outInt32 = Cast(outFp32, DataType::DT_INT32, CAST_RINT);
39 auto outHalf = Cast(outInt32, DataType::DT_FP16, CAST_ROUND);69 auto outHalf = Cast(outInt32, DataType::DT_FP16, CAST_ROUND);
40 auto outInt8 = Cast(outHalf, DataType::DT_INT8, CAST_TRUNC, SaturationMode::ON);70 auto outInt8 = Cast(outHalf, DataType::DT_INT8, CAST_TRUNC, SaturationMode::ON);
41- auto scaleDeQuant = ScalarDivS(scaleQuant, Element(DataType::DT_FP32, F_1), true);71+ auto scaleDeQuant = ScalarDivS(scaleQuant, Element(DataType::DT_FP32, STUB_F_1), true);
42 return std::tie(outInt8, scaleDeQuant);72 return std::tie(outInt8, scaleDeQuant);
43 } else {73 } else {
44- // 优先级低
45 auto maxValue = Amax(inputFp32, -1, true);74 auto maxValue = Amax(inputFp32, -1, true);
46 auto minValue = Amin(inputFp32, -1, true);75 auto minValue = Amin(inputFp32, -1, true);
47- auto scaleDeQuant = ScalarMaxS(ScalarDivS(ScalarSub(maxValue, minValue), Element(DataType::DT_FP32, F_255)),76+ auto scaleDeQuant = ScalarMaxS(
48- Element(DataType::DT_FP32, F_1E_12));77+ ScalarDivS(ScalarSub(maxValue, minValue), Element(DataType::DT_FP32, STUB_F_255)),
49- auto offset = ScalarSubS(ScalarDiv(maxValue, scaleDeQuant), Element(DataType::DT_FP32, F_127), true);78+ Element(DataType::DT_FP32, STUB_F_1E_12));
50- auto scaleQuant = ScalarDivS(scaleDeQuant, Element(DataType::DT_FP32, F_1), true);79+ auto offset = ScalarSubS(ScalarDiv(maxValue, scaleDeQuant), Element(DataType::DT_FP32, STUB_F_127), true);
80+ auto scaleQuant = ScalarDivS(scaleDeQuant, Element(DataType::DT_FP32, STUB_F_1), true);
51 auto outFp32 = Mul(inputFp32, scaleQuant);81 auto outFp32 = Mul(inputFp32, scaleQuant);
52 auto outInt32 = Cast(outFp32, DataType::DT_INT32, CAST_RINT);82 auto outInt32 = Cast(outFp32, DataType::DT_INT32, CAST_RINT);
53 auto outHalf = Cast(outInt32, DataType::DT_FP16, CAST_ROUND);83 auto outHalf = Cast(outInt32, DataType::DT_FP16, CAST_ROUND);
@@ -55,27 +85,5 @@ std::tuple<Tensor, Tensor> Quant(const Tensor& input, bool isSymmetry, bool hasS
55 return std::tie(outInt8, scaleDeQuant);85 return std::tie(outInt8, scaleDeQuant);
56 }86 }
57}87}
58-} // namespace npu::tile_fwk
59 88 
60-namespace npu::tile_fwk::Matrix {89+} // namespace npu::tile_fwk
61-Tensor QuantMM(const Tensor& operand1, const Tensor& operand2, const Tensor& dequantScaleW)
62-{
63- auto quantA = Quant(operand1);
64- auto quantizedA = std::get<0>(quantA);
65- auto dequantScaleA = std::get<1>(quantA);
66- Tensor res;
67- if (operand1.GetShape().size() == NUM_VALUE_2) {
68- res = Matmul(DataType::DT_INT32, quantizedA, operand2, false, false);
69- } else if (operand1.GetShape().size() == NUM_VALUE_3) {
70- res = BatchMatmul(DataType::DT_INT32, quantizedA, operand2);
71- } else {
72- ASSERT(VectorErrorCode::ERR_PARAM_INVALID, operand1.GetShape().size() <= NUM_VALUE_3)
73- << "QuantMM only supports 2D or 3D tensors.";
74- }
75- res = Cast(res, DataType::DT_FP32);
76- res = Mul(res, dequantScaleA);
77- res = Mul(res, dequantScaleW);
78- res = Cast(res, DataType::DT_BF16, CAST_RINT);
79- return res;
80-}
81-} // namespace npu::tile_fwk::Matrix
@@ -20,12 +20,10 @@ has ``libtile_fwk_bundle.so`` + a ``.pyptokb`` -- no compiler front end, no reco
20Cases:20Cases:
21 static_add non-value-dependent, static workspace (0 B); packed through the emulation hook, so the21 static_add non-value-dependent, static workspace (0 B); packed through the emulation hook, so the
22 bundle carries a NON-EMPTY CtrlFlowCache snapshot.22 bundle carries a NON-EMPTY CtrlFlowCache snapshot.
23- dyn_cellmatch non-value-dependent but dynamically shaped: SymbolMeta carries real symbolic trees plus23+ dyn_cellmatch non-value-dependent but dynamically shaped: SymbolMeta carries real symbolic trees plus
24 the dynamic cell-match launch metas, so workspace is re-evaluated per launch shape.24 the dynamic cell-match launch metas, so workspace is re-evaluated per launch shape.
25- value_depend_pa value-dependent control flow (loop bounds read from act_seqs tensor VALUES). Packed
26- through the value-depend hook, so the CtrlFlowCache segment is EMPTY and the on-device
27- interpreter resolves the trip counts at launch.
28"""25"""
26+ 
29import argparse27import argparse
30import ctypes28import ctypes
31import os29import os
@@ -42,12 +40,6 @@ import torch_npu # noqa: E402, F401 -- registers the npu backend
42 40 
43import pypto # noqa: E40241import pypto # noqa: E402
44from st.bundle.bundle_abi import BundleClient, make_desc_array # noqa: E40242from st.bundle.bundle_abi import BundleClient, make_desc_array # noqa: E402
45-from st.operator.test_page_attention import ( # noqa: E402
46- TileConfig,
47- op_page_attention,
48- op_page_attention_golden,
49-)
50-from st.pypto_test import TestBuilder # noqa: E402
51from st.test_cellmatch_case import B_STATIC, D_STATIC, H_STATIC, k_tmp_to_d_emb # noqa: E40243from st.test_cellmatch_case import B_STATIC, D_STATIC, H_STATIC, k_tmp_to_d_emb # noqa: E402
52 44 
53 45 
@@ -200,150 +192,12 @@ def consume_dyn_cellmatch(bundle_path: str, api: str):
200 _check(f"cellmatch L={CM_PACK_L} ({api} API)", d_emb, _cm_golden(dy, weight), 1e-3)192 _check(f"cellmatch L={CM_PACK_L} ({api} API)", d_emb, _cm_golden(dy, weight), 1e-3)
201 193 
202 194 
203-# ---------------------------------------------------------------------------------------------------
204-# case: value_depend_pa -- value-dependent control flow (page attention)
205-# ---------------------------------------------------------------------------------------------------
206-# Loop trip counts come from act_seqs tensor VALUES (`cur_seq = act_seqs[b_idx]` -> GetTensorData ->
207-# bn_per_batch), which sets devProg->disableCtrlFlowCache. Every shape below is held constant across the
208-# two value sets -- the cache size is pinned by PA_MAX_BLOCKS, not by max(act_seqs) -- so the only thing
209-# that differs between the two consume launches is the tensor CONTENT.
210-PA_BLOCK_SIZE = 128
211-PA_MAX_BLOCKS = 4 # blocks reserved per batch; pins block_table / kv-cache shapes
212-PA_BATCH = 4
213-PA_N_TILE = 32
214- 
215-PA_ACT_SEQS_PACKED = [512, 512, 512, 512] # bn_per_batch = [4, 4, 4, 4]
216-PA_ACT_SEQS_ALT = [128, 512, 256, 384] # bn_per_batch = [1, 4, 2, 3] -- same shapes, different values
217- 
218-PA_TOL = 5e-4
219- 
220- 
221-def _pa_params():
222- return {
223- "block_size": PA_BLOCK_SIZE,
224- "tile_config": TileConfig(
225- head_num_q_tile=PA_N_TILE,
226- c1_tile_shape=(32, 32, 64, 64, 128, 128),
227- v1_tile_shape=(32, 64),
228- c2_tile_shape=(32, 32, 64, 64, 128, 128),
229- v2_tile_shape=(32, 64),
230- ),
231- "max_unroll_times": 1,
232- "is_nz_format": False,
233- "b": PA_BATCH,
234- "n_q": 32,
235- "block_num": PA_BATCH * PA_MAX_BLOCKS,
236- "dtype": torch.float32,
237- "s_q": 1,
238- "n_kv": 1,
239- "kv_lora_rank": 512,
240- "qk_rope_dim": 64,
241- "n_tile": PA_N_TILE,
242- }
243- 
244- 
245-def _pa_make_inputs(params, act_seqs, device: str, seed: int = 11):
246- """Build the 7-operand input list on CPU or device. Shapes depend only on params, never on act_seqs."""
247- b = params["b"]
248- n_q = params["n_q"]
249- s_q = params["s_q"]
250- n_kv = params["n_kv"]
251- kv_lora_rank = params["kv_lora_rank"]
252- qk_rope_dim = params["qk_rope_dim"]
253- block_size = params["block_size"]
254- block_num = params["block_num"]
255- dtype = params["dtype"]
256- d_q = kv_lora_rank + qk_rope_dim
257- 
258- max_seq = max(act_seqs)
259- assert max_seq <= PA_MAX_BLOCKS * block_size, (
260- f"act_seqs {act_seqs} exceeds the {PA_MAX_BLOCKS * block_size}-token reservation")
261- 
262- torch.manual_seed(seed)
263- q_bnsd = (torch.rand([b * n_q * s_q, d_q], dtype=dtype) * 2 - 1).to(device)
264- k_cache = (torch.rand([block_num, block_size, n_kv * d_q], dtype=dtype) * 2 - 1).to(device)
265- v_cache = (torch.rand([block_num, block_size, n_kv * kv_lora_rank], dtype=dtype) * 2 - 1).to(device)
266- 
267- # Identity block mapping: batch bi owns physical blocks [bi*PA_MAX_BLOCKS, (bi+1)*PA_MAX_BLOCKS).
268- block_table = torch.arange(0, block_num, dtype=torch.int32).reshape(b, PA_MAX_BLOCKS).to(device)
269- act = torch.tensor(act_seqs, dtype=torch.int32).to(device)
270- 
271- nope_h = n_kv * kv_lora_rank
272- q_nope = q_bnsd[:, :kv_lora_rank].contiguous()
273- q_rope = q_bnsd[:, kv_lora_rank:].contiguous()
274- k_cache_nope = k_cache[:, :, :nope_h].reshape(block_num * block_size, nope_h).contiguous()
275- k_cache_rope = k_cache[:, :, nope_h:].reshape(block_num * block_size, n_kv * qk_rope_dim).contiguous()
276- v_cache_2d = v_cache.reshape(block_num * block_size, nope_h).contiguous()
277- return [q_nope, k_cache_nope, v_cache_2d, q_rope, k_cache_rope, block_table, act]
278- 
279- 
280-def _pa_golden(params, inputs):
281- cpu_inputs = [t.cpu() for t in inputs]
282- out, = op_page_attention_golden(params, *cpu_inputs, None)
283- return out
284- 
285- 
286-def pack_value_depend_pa():
287- class _PABundlePack(TestBuilder):
288- def get_input_from_param(self):
289- # TestBuilder feeds the host-side run-once path, which wants CPU tensors.
290- inputs = _pa_make_inputs(self.params, self.params["act_seqs"], "cpu")
291- self.setup_inputs(*inputs)
292- self.set_tol(rtol=PA_TOL, atol=PA_TOL)
293- # Mirrors PATest: the golden's trailing attention_out slot is unused, params rides along.
294- return inputs + [self.params]
295- 
296- params = _pa_params()
297- params["act_seqs"] = PA_ACT_SEQS_PACKED
298- _PABundlePack(params, op_page_attention, op_page_attention_golden, tiling=PA_N_TILE)()
299- 
300- 
301-def consume_value_depend_pa(bundle_path: str, api: str):
302- _, device = _device()
303- client = BundleClient(bundle_path, api)
304- params = _pa_params()
305- 
306- # Both launches reuse the one loaded bundle. Identical shapes, different act_seqs VALUES: if the device
307- # were replaying a host-baked control-flow cache instead of resolving trip counts from the tensor, the
308- # second case would read the wrong number of KV blocks and miss the golden.
309- goldens = {}
310- for label, act_seqs in (("packed", PA_ACT_SEQS_PACKED), ("alt", PA_ACT_SEQS_ALT)):
311- inputs = _pa_make_inputs(params, act_seqs, device)
312- out = torch.zeros(
313- params["b"] * params["n_q"] * params["s_q"], params["kv_lora_rank"],
314- dtype=params["dtype"], device=device)
315- descs = make_desc_array(inputs + [out])
316- 
317- ws_size = client.workspace(descs)
318- print(f"[ST] {label} act_seqs={act_seqs}: workspace = {ws_size}")
319- ws_keep, ws_ptr = _alloc_workspace(ws_size, device)
320- rc = client.launch(descs, ws_ptr, None, 1)
321- assert rc == 0, f"{label}: PyptoLaunch rc={rc}"
322- torch.npu.synchronize()
323- del ws_keep
324- 
325- golden = _pa_golden(params, inputs)
326- goldens[label] = golden
327- _check(f"page-attention {label} ({api} API)", out.reshape(golden.shape), golden, PA_TOL)
328- 
329- # Guard the guard: the two value sets share a seed, so they differ only through act_seqs. If they no
330- # longer drive the output apart, the pair of launches above would pass even on a device that ignored
331- # the tensor values entirely, and this case would stop testing value dependency at all.
332- spread = _max_diff(goldens["packed"], goldens["alt"])
333- print(f"[ST] golden spread between the two act_seqs value sets = {spread:.6f}")
334- assert spread > PA_TOL * 10, (
335- f"act_seqs {PA_ACT_SEQS_PACKED} vs {PA_ACT_SEQS_ALT} barely move the result (spread={spread}); "
336- f"pick value sets whose per-batch block counts differ more"
337- )
338- 
339- 
340# ---------------------------------------------------------------------------------------------------195# ---------------------------------------------------------------------------------------------------
341# registry + CLI196# registry + CLI
342# ---------------------------------------------------------------------------------------------------197# ---------------------------------------------------------------------------------------------------
343CASES = {198CASES = {
344 "static_add": (pack_static_add, consume_static_add),199 "static_add": (pack_static_add, consume_static_add),
345 "dyn_cellmatch": (pack_dyn_cellmatch, consume_dyn_cellmatch),200 "dyn_cellmatch": (pack_dyn_cellmatch, consume_dyn_cellmatch),
346- "value_depend_pa": (pack_value_depend_pa, consume_value_depend_pa),
347}201}
348 202 
349 203 
@@ -359,8 +213,9 @@ def main():
359 if args.phase == "pack":213 if args.phase == "pack":
360 # Packing is gated by these two env vars; the driver sets them, assert rather than silently no-op.214 # Packing is gated by these two env vars; the driver sets them, assert rather than silently no-op.
361 assert os.environ.get("PYPTO_ENABLE_KERNEL_BUNDLE") == "1", "PYPTO_ENABLE_KERNEL_BUNDLE must be 1"215 assert os.environ.get("PYPTO_ENABLE_KERNEL_BUNDLE") == "1", "PYPTO_ENABLE_KERNEL_BUNDLE must be 1"
362- assert os.environ.get("PYPTO_KERNEL_BUNDLE_PATH") == args.bundle_path, \216+ assert os.environ.get("PYPTO_KERNEL_BUNDLE_PATH") == args.bundle_path, (
363 "PYPTO_KERNEL_BUNDLE_PATH must match the requested bundle path"217 "PYPTO_KERNEL_BUNDLE_PATH must match the requested bundle path"
218+ )
364 pack_fn()219 pack_fn()
365 assert os.path.exists(args.bundle_path), f"no bundle produced at {args.bundle_path}"220 assert os.path.exists(args.bundle_path), f"no bundle produced at {args.bundle_path}"
366 print(f"[ST] packed {args.case} -> {args.bundle_path} ({os.path.getsize(args.bundle_path)} B)")221 print(f"[ST] packed {args.case} -> {args.bundle_path} ({os.path.getsize(args.bundle_path)} B)")
@@ -30,8 +30,6 @@ Scenario coverage:
30 in-memory ABI variants; CtrlFlowCache non-empty30 in-memory ABI variants; CtrlFlowCache non-empty
31 dyn_cellmatch not value-dep dynamic (symbolic) SymbolMeta symbol trees + dynamic cell-match31 dyn_cellmatch not value-dep dynamic (symbolic) SymbolMeta symbol trees + dynamic cell-match
32 metas: workspace re-evaluated per launch shape32 metas: workspace re-evaluated per launch shape
33- value_depend value-dependent dynamic CtrlFlowCache segment EMPTY; the same bundle
34- launched twice with different tensor VALUES
35 standalone not value-dep static, 0 B the self-contained delivery form: one .so + one33 standalone not value-dep static, 0 B the self-contained delivery form: one .so + one
36 .pyptokb + configs/, no pypto in the process.34 .pyptokb + configs/, no pypto in the process.
37 SKIPPED unless the artifact was built35 SKIPPED unless the artifact was built
@@ -62,7 +60,6 @@ from st.bundle.bundle_abi import ( # noqa: E402
62 TLV_AICPU_SO,60 TLV_AICPU_SO,
63 TLV_CTRL_FLOW_CACHE,61 TLV_CTRL_FLOW_CACHE,
64 TLV_DEV_PROGRAM,62 TLV_DEV_PROGRAM,
65- TLV_SYMBOL_META,
66 read_bundle_tlvs,63 read_bundle_tlvs,
67 read_symbol_meta,64 read_symbol_meta,
68)65)
@@ -187,31 +184,6 @@ def test_bundle_dynamic_cellmatch(bundle_path):
187 _consume("dyn_cellmatch", bundle_path)184 _consume("dyn_cellmatch", bundle_path)
188 185 
189 186 
190-@duration_estimate(34)
191-@pypto.options(pass_options={"enable_slice": True})
192-def test_bundle_value_depend_page_attention(bundle_path):
193- """Value-dependent control flow: loop bounds come from tensor VALUES, so there is no cache to bake.
194- 
195- Such ops set devProg->disableCtrlFlowCache, skip the emulation pack hook entirely and are packed from
196- the launch path instead; the bundle must therefore carry an EMPTY CtrlFlowCache segment. The consume
197- step launches the one bundle twice with identical shapes but different act_seqs values -- that only
198- works if the on-device interpreter resolves the trip counts at launch.
199- """
200- _pack("value_depend_pa", bundle_path)
201- 
202- tlvs = _assert_common_segments(bundle_path)
203- cache = tlvs.get(TLV_CTRL_FLOW_CACHE)
204- assert cache is not None, "expected a present-but-empty CtrlFlowCache segment, not an absent one"
205- assert cache.length == 0, (
206- f"a value-dependent op must not carry a control-flow cache snapshot (got {cache.length} B); "
207- f"either the op stopped being value-dependent or the value-depend pack hook regressed"
208- )
209- assert TLV_SYMBOL_META in tlvs, "expected a SymbolMeta segment"
210- 
211- out = _consume("value_depend_pa", bundle_path)
212- assert "page-attention packed" in out and "page-attention alt" in out
213- 
214- 
215@duration_estimate(28)187@duration_estimate(28)
216@pypto.options(pass_options={"enable_slice": True})188@pypto.options(pass_options={"enable_slice": True})
217def test_bundle_standalone_delivery(bundle_path, tmp_path):189def test_bundle_standalone_delivery(bundle_path, tmp_path):
@@ -1,33 +0,0 @@
1-#!/usr/bin/env python3
2-# coding: utf-8
3-# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5-# CANN Open Software License Agreement Version 2.0 (the "License").
6-# Please refer to the License for details. You may not use this file except in compliance with the License.
7-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9-# See LICENSE in the root of the software repository for the full text of the License.
10-# -----------------------------------------------------------------------------------------------------------
11-import enum
12- 
13-import torch
14- 
15- 
16-class TileOpFormat(enum.Enum):
17- ND = "ND"
18- NZ = "NZ"
19- 
20- 
21-def get_format(tensor):
22- if not isinstance(tensor, torch.Tensor):
23- raise TypeError("input type error")
24- if not tensor.is_contiguous():
25- raise TypeError("input type error")
26- 
27- tile_op_format = TileOpFormat.ND.value
28- if tensor.device.type == "npu":
29- import torch_npu
30- 
31- if torch_npu.get_npu_format(tensor) == 29:
32- tile_op_format = TileOpFormat.NZ.value
33- return tile_op_format
@@ -1,151 +0,0 @@
1-#!/usr/bin/env python3
2-# coding: utf-8
3-# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5-# CANN Open Software License Agreement Version 2.0 (the "License").
6-# Please refer to the License for details. You may not use this file except in compliance with the License.
7-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9-# See LICENSE in the root of the software repository for the full text of the License.
10-# -----------------------------------------------------------------------------------------------------------
11-import numpy as np
12-from numpy.testing import assert_allclose
13- 
14- 
15-class Colors:
16- reset = '\033[0m'
17- BOLD = '\033[1m'
18- UNDERLINE = '\033[4m'
19- RED = '\033[91m'
20- GREEN = '\033[92m'
21- yellow = '\033[93m'
22- BLUE = '\033[94m'
23- PURPLE = '\033[95m'
24- CYAN = '\033[96m'
25- 
26- 
27-def detailed_allclose_manual(cpu, npu, name, rtol=1e-3, atol=1e-3, max_prints=50, force_print_first_n=5):
28- """
29- 手动实现 np.allclose 的详细比较,打印超出容差和 NaN 的值
30- 
31- 参数:
32- cpu: CPU端的数组
33- npu: NPU端的数组
34- rtol: 相对容差
35- atol: 绝对容差
36- max_prints: 最大打印数量
37- force_print_first_n: 强制打印前n个元素的值,无论是否异常
38- """
39- # 检查形状是否一致
40- if cpu.shape != npu.shape:
41- print(f"错误: 形状不一致 - cpu {cpu.shape} vs npu {npu.shape}")
42- return False
43- 
44- total_elements = cpu.size
45- abnormal_count = 0
46- nan_count = 0
47- exceed_tolerance_count = 0
48- 
49- print(f"开始比较数组,形状: {cpu.shape}, 总元素数: {total_elements}")
50- print(f"容差条件: rtol={rtol}, atol={atol}")
51- print("=" * 80)
52- 
53- # 定义颜色代码
54- yellow = '\033[93m'
55- reset = '\033[0m'
56- 
57- # 将数组展平以便遍历,但记录原始索引
58- cpu_flat = cpu.reshape(-1)
59- npu_flat = npu.reshape(-1)
60- 
61- # 获取多维索引的函数
62- def get_multi_index(flat_index, shape):
63- indices = []
64- remaining = flat_index
65- for dim in reversed(shape):
66- indices.append(remaining % dim)
67- remaining = remaining // dim
68- return tuple(reversed(indices))
69- 
70- # 强制打印前n个元素
71- if force_print_first_n > 0:
72- print(f"{yellow}强制打印前 {force_print_first_n} 个元素:{reset}")
73- for flat_idx in range(min(force_print_first_n, total_elements)):
74- cpu_val = cpu_flat[flat_idx]
75- npu_val = npu_flat[flat_idx]
76- multi_idx = get_multi_index(flat_idx, cpu.shape)
77- 
78- # 计算差值
79- if np.isnan(cpu_val) or np.isnan(npu_val):
80- diff_str = "NaN"
81- else:
82- diff_val = np.abs(cpu_val - npu_val)
83- diff_str = f"{diff_val:.6e}"
84- 
85- # 格式化值
86- cpu_str = "NaN" if np.isnan(cpu_val) else f"{cpu_val:.6e}"
87- npu_str = "NaN" if np.isnan(npu_val) else f"{npu_val:.6e}"
88- 
89- print(f"{yellow}索引 {multi_idx}: cpu={cpu_str}, npu={npu_str}, 差值={diff_str}{reset}")
90- 
91- print("-" * 80)
92- 
93- # 遍历所有元素查找异常
94- for flat_idx in range(total_elements):
95- cpu_val = cpu_flat[flat_idx]
96- npu_val = npu_flat[flat_idx]
97- 
98- # 获取多维索引
99- multi_idx = get_multi_index(flat_idx, cpu.shape)
100- 
101- # 检查是否为 NaN (npu 中有 NaN 就认为是异常)
102- if np.isnan(npu_val):
103- abnormal_count += 1
104- nan_count += 1
105- 
106- if abnormal_count <= max_prints:
107- cpu_str = "NaN" if np.isnan(cpu_val) else f"{cpu_val:.6e}"
108- print(f"索引 {multi_idx}: cpu={cpu_str}, npu=NaN, 差值=NaN (NPU包含NaN)")
109- 
110- # 检查是否超出容差
111- elif np.isnan(cpu_val):
112- # CPU 有 NaN 但 NPU 没有,也是异常
113- abnormal_count += 1
114- exceed_tolerance_count += 1
115- 
116- if abnormal_count <= max_prints:
117- print(f"索引 {multi_idx}: cpu=NaN, npu={npu_val:.6e}, 差值=NaN (CPU包含NaN)")
118- 
119- else:
120- # 计算绝对差值和允许的容差
121- abs_diff = np.abs(cpu_val - npu_val)
122- allowed_diff = atol + rtol * np.abs(npu_val)
123- 
124- # 检查是否超出容差
125- if abs_diff > allowed_diff:
126- abnormal_count += 1
127- exceed_tolerance_count += 1
128- 
129- if abnormal_count <= max_prints:
130- print(
131- f"索引 {multi_idx}: cpu={cpu_val:.6e}, npu={npu_val:.6e}, "
132- f"差值={abs_diff:.6e} (超过容差 {allowed_diff:.6e})"
133- )
134- 
135- # 统计信息
136- print("=" * 80)
137- print(f"{Colors.BOLD}{Colors.PURPLE}{name} 比较结果统计:{Colors.reset}")
138- print(f"总元素数量: {total_elements}")
139- print(f"异常元素数量: {abnormal_count}")
140- print(f" - NaN 数量: {nan_count}")
141- print(f" - 超出容差数量: {exceed_tolerance_count}")
142- print(f"异常比例: {abnormal_count / total_elements * 100:.4f}%")
143- 
144- # 检查是否通过 allclose 条件
145- is_allclose = abnormal_count == 0
146- print(f"\nnp.allclose 等价结果: {is_allclose}")
147- 
148- if abnormal_count > max_prints:
149- print(f"\n注意: 只显示了前 {max_prints} 个异常,共有 {abnormal_count} 个异常元素")
150- assert_allclose(cpu, npu, rtol, atol)
151- return is_allclose