Merged
feat(pypto_pro): auto block_dim for direct calls and explicit over-budget rejection #6584
liulufang_gitcodeAdd on Sep 21
feat(pypto_pro): auto block_dim for direct calls and explicit over-budget rejection #6584
Merged
liulufang_gitcodeAdd on Sep 21
Total: 51 files changed+397-187
@@ -4,7 +4,7 @@
4 * CANN Open Software License Agreement Version 2.0 (the "License").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.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 
@@ -51,6 +51,8 @@ aclError GetStreamResLimitStub(aclrtStream stream, aclrtDevResLimitType resource
51#include "pypto_launch.h"51#include "pypto_launch.h"
52#undef aclrtGetStreamResLimit52#undef aclrtGetStreamResLimit
53 53 
54+inline int64_t RequestError(uint32_t budget) { return pypto::EncodeLaunchError(pypto::LaunchError::Request, budget); }
55+ 
54class PyptoLaunchTest : public testing::Test {56class PyptoLaunchTest : public testing::Test {
55protected:57protected:
56 void SetUp() override58 void SetUp() override
@@ -89,49 +91,63 @@ TEST_F(PyptoLaunchTest, ErrorEncodingPreservesPythonAbiTagsAndAllDetailBits)
89 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::VectorLimit, 0), -0x200000000LL);91 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::VectorLimit, 0), -0x200000000LL);
90 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::CubeQuery, 0), -0x300000000LL);92 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::CubeQuery, 0), -0x300000000LL);
91 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::VectorQuery, 0), -0x400000000LL);93 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::VectorQuery, 0), -0x400000000LL);
94+ EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::Request, 0), -0x500000000LL);
92 constexpr uint32_t maxDetail = std::numeric_limits<uint32_t>::max();95 constexpr uint32_t maxDetail = std::numeric_limits<uint32_t>::max();
93 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::CubeLimit, maxDetail), -0x1FFFFFFFFLL);96 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::CubeLimit, maxDetail), -0x1FFFFFFFFLL);
94 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::VectorLimit, maxDetail), -0x2FFFFFFFFLL);97 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::VectorLimit, maxDetail), -0x2FFFFFFFFLL);
95 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::CubeQuery, maxDetail), -0x3FFFFFFFFLL);98 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::CubeQuery, maxDetail), -0x3FFFFFFFFLL);
96 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::VectorQuery, maxDetail), -0x4FFFFFFFFLL);99 EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::VectorQuery, maxDetail), -0x4FFFFFFFFLL);
100+ EXPECT_EQ(pypto::EncodeLaunchError(pypto::LaunchError::Request, maxDetail), -0x5FFFFFFFFLL);
97}101}
98 102 
99-TEST_F(PyptoLaunchTest, CubeOnlyClampsWithoutQueryingVector)103+TEST_F(PyptoLaunchTest, CubeOnlyAcceptsUpToBudgetWithoutQueryingVector)
100{104{
101 // No vector response is supplied: even a successful extra query is a failure.105 // No vector response is supplied: even a successful extra query is a failure.
102- for (uint32_t request : {1U, 5U, 20U}) {106+ for (uint32_t request : {1U, 5U}) {
103 SCOPED_TRACE(request);107 SCOPED_TRACE(request);
104 ExpectQuery(ACL_RT_DEV_RES_CUBE_CORE, 5);108 ExpectQuery(ACL_RT_DEV_RES_CUBE_CORE, 5);
105- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 0>(request, stream_)), request == 1 ? 1 : 5);109+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 0>(request, stream_)), request);
106 }110 }
107}111}
108 112 
109-TEST_F(PyptoLaunchTest, VectorOnlyClampsWithoutQueryingCube)113+TEST_F(PyptoLaunchTest, CubeOnlyRejectsRequestsAboveBudget)
110{114{
111- for (uint32_t request : {1U, 7U, 20U}) {115+ ExpectQuery(ACL_RT_DEV_RES_CUBE_CORE, 5);
116+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 0>(20, stream_)), RequestError(5));
117+}
118+ 
119+TEST_F(PyptoLaunchTest, VectorOnlyAcceptsUpToBudgetWithoutQueryingCube)
120+{
121+ for (uint32_t request : {1U, 7U}) {
112 SCOPED_TRACE(request);122 SCOPED_TRACE(request);
113 ExpectQuery(ACL_RT_DEV_RES_VECTOR_CORE, 7);123 ExpectQuery(ACL_RT_DEV_RES_VECTOR_CORE, 7);
114- EXPECT_EQ((pypto::ResolveLaunchBlockDim<0, 1>(request, stream_)), request == 1 ? 1 : 7);124+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<0, 1>(request, stream_)), request);
115 }125 }
116}126}
117 127 
118-TEST_F(PyptoLaunchTest, MixedBlocksRespectCubeBottleneck)128+TEST_F(PyptoLaunchTest, VectorOnlyRejectsRequestsAboveBudget)
119{129{
120- ExpectMixedLimits(4, 20);130+ ExpectQuery(ACL_RT_DEV_RES_VECTOR_CORE, 7);
121- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(20, stream_)), 4);131+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<0, 1>(20, stream_)), RequestError(7));
122}132}
123 133 
124-TEST_F(PyptoLaunchTest, MixedBlocksRoundDownOddVectorBudget)134+TEST_F(PyptoLaunchTest, MixedBlocksRejectCubeBottleneckWithBudgetDetail)
135+{
136+ ExpectMixedLimits(4, 20);
137+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(20, stream_)), RequestError(4));
138+}
139+ 
140+TEST_F(PyptoLaunchTest, MixedBlocksRejectOddVectorBudgetWithoutRoundingUp)
125{141{
126 // Nine vectors can complete only four pairs; a fifth cube would deadlock.142 // Nine vectors can complete only four pairs; a fifth cube would deadlock.
127 ExpectMixedLimits(20, 9);143 ExpectMixedLimits(20, 9);
128- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(20, stream_)), 4);144+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(20, stream_)), RequestError(4));
129}145}
130 146 
131-TEST_F(PyptoLaunchTest, MixedBlocksAcceptExactlyOneCompletePair)147+TEST_F(PyptoLaunchTest, MixedBlocksRejectWhenExactlyOneCompletePairFits)
132{148{
133 ExpectMixedLimits(1, 2);149 ExpectMixedLimits(1, 2);
134- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(20, stream_)), 1);150+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(20, stream_)), RequestError(1));
135}151}
136 152 
137TEST_F(PyptoLaunchTest, MixedBlocksPreserveSmallerRequest)153TEST_F(PyptoLaunchTest, MixedBlocksPreserveSmallerRequest)
@@ -144,11 +160,20 @@ TEST_F(PyptoLaunchTest, TopologyUsesConfiguredCoreCounts)
144{160{
145 // A hardcoded 1:2 ratio would fail valid compiler-provided topologies.161 // A hardcoded 1:2 ratio would fail valid compiler-provided topologies.
146 ExpectMixedLimits(8, 5);162 ExpectMixedLimits(8, 5);
147- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 1>(12, stream_)), 5);163+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 1>(12, stream_)), RequestError(5));
148 ExpectMixedLimits(5, 20);164 ExpectMixedLimits(5, 20);
149- EXPECT_EQ((pypto::ResolveLaunchBlockDim<2, 3>(12, stream_)), 2);165+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<2, 3>(12, stream_)), RequestError(2));
150 ExpectMixedLimits(20, 5);166 ExpectMixedLimits(20, 5);
151- EXPECT_EQ((pypto::ResolveLaunchBlockDim<2, 3>(12, stream_)), 1);167+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<2, 3>(12, stream_)), RequestError(1));
168+}
169+ 
170+TEST_F(PyptoLaunchTest, RequestEqualToBudgetIsAccepted)
171+{
172+ // The budget itself must launch; only strictly larger requests are rejected.
173+ ExpectQuery(ACL_RT_DEV_RES_CUBE_CORE, 8);
174+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 0>(8, stream_)), 8);
175+ ExpectMixedLimits(8, 8);
176+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(4, stream_)), 4);
152}177}
153 178 
154TEST_F(PyptoLaunchTest, Uint32MaximumRemainsAPositiveBlockCount)179TEST_F(PyptoLaunchTest, Uint32MaximumRemainsAPositiveBlockCount)
@@ -157,10 +182,33 @@ TEST_F(PyptoLaunchTest, Uint32MaximumRemainsAPositiveBlockCount)
157 constexpr uint32_t maxBlocks = std::numeric_limits<uint32_t>::max();182 constexpr uint32_t maxBlocks = std::numeric_limits<uint32_t>::max();
158 ExpectQuery(ACL_RT_DEV_RES_CUBE_CORE, maxBlocks);183 ExpectQuery(ACL_RT_DEV_RES_CUBE_CORE, maxBlocks);
159 EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 0>(maxBlocks, stream_)), 4294967295LL);184 EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 0>(maxBlocks, stream_)), 4294967295LL);
160- ExpectQuery(ACL_RT_DEV_RES_VECTOR_CORE, 72);185+}
161- EXPECT_EQ((pypto::ResolveLaunchBlockDim<0, 1>(maxBlocks, stream_)), 72);186+ 
187+TEST_F(PyptoLaunchTest, AutoSentinelUsesTheFullStreamBudget)
188+{
189+ // The host's auto sentinel takes the whole budget of every engine the
190+ // kernel uses, mixed blocks still bound by the tighter engine.
191+ ExpectMixedLimits(4, 20);
192+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), 4);
193+ ExpectMixedLimits(20, 9);
194+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), 4);
195+ ExpectMixedLimits(1, 2);
196+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), 1);
197+ ExpectQuery(ACL_RT_DEV_RES_CUBE_CORE, 5);
198+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 0>(pypto::kAutoBlockDim, stream_)), 5);
199+ ExpectQuery(ACL_RT_DEV_RES_VECTOR_CORE, 7);
200+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<0, 1>(pypto::kAutoBlockDim, stream_)), 7);
201+ ExpectMixedLimits(8, 5);
202+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 1>(pypto::kAutoBlockDim, stream_)), 5);
203+ ExpectMixedLimits(5, 20);
204+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<2, 3>(pypto::kAutoBlockDim, stream_)), 2);
205+}
206+ 
207+TEST_F(PyptoLaunchTest, AutoSentinelWithMaxBudgetsStaysPositive)
208+{
209+ constexpr uint32_t maxBlocks = std::numeric_limits<uint32_t>::max();
162 ExpectMixedLimits(maxBlocks, maxBlocks);210 ExpectMixedLimits(maxBlocks, maxBlocks);
163- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(maxBlocks, stream_)), 2147483647LL);211+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), 2147483647LL);
164}212}
165 213 
166TEST_F(PyptoLaunchTest, ZeroCubeBudgetStopsBeforeVectorQuery)214TEST_F(PyptoLaunchTest, ZeroCubeBudgetStopsBeforeVectorQuery)
@@ -211,21 +259,21 @@ TEST_F(PyptoLaunchTest, EveryCallObservesCurrentStreamAndLimitsAfterFailure)
211 // Reuse the same template instantiation while scopes and streams change;259 // Reuse the same template instantiation while scopes and streams change;
212 // caching either a successful budget or an error would keep stale limits.260 // caching either a successful budget or an error would keep stale limits.
213 ExpectMixedLimits(8, 6);261 ExpectMixedLimits(8, 6);
214- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(12, stream_)), 3);262+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), 3);
215 ExpectMixedLimits(8, 2);263 ExpectMixedLimits(8, 2);
216- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(12, stream_)), 1);264+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), 1);
217 uint8_t otherStreamToken = 0;265 uint8_t otherStreamToken = 0;
218 stream_ = &otherStreamToken;266 stream_ = &otherStreamToken;
219 ExpectMixedLimits(8, 1);267 ExpectMixedLimits(8, 1);
220- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(12, stream_)), -0x200000001LL);268+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), -0x200000001LL);
221 ExpectMixedLimits(8, 8);269 ExpectMixedLimits(8, 8);
222- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(12, stream_)), 4);270+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), 4);
223 ExpectQuery(ACL_RT_DEV_RES_CUBE_CORE, 0, 507000);271 ExpectQuery(ACL_RT_DEV_RES_CUBE_CORE, 0, 507000);
224- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(12, stream_)), -(0x300000000LL + 507000));272+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), -(0x300000000LL + 507000));
225 // ACL also accepts the default stream; it must be forwarded without substitution.273 // ACL also accepts the default stream; it must be forwarded without substitution.
226 stream_ = nullptr;274 stream_ = nullptr;
227 ExpectMixedLimits(2, 8);275 ExpectMixedLimits(2, 8);
228- EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(12, stream_)), 2);276+ EXPECT_EQ((pypto::ResolveLaunchBlockDim<1, 2>(pypto::kAutoBlockDim, stream_)), 2);
229}277}
230 278 
231} // namespace279} // namespace
@@ -12,20 +12,28 @@
12 12 
13#include <acl/acl_rt.h>13#include <acl/acl_rt.h>
14#include <cstdint>14#include <cstdint>
15+#include <cstdio>
15 16 
16namespace pypto {17namespace pypto {
17 18 
18// The ctypes boundary cannot propagate C++ exceptions. A positive int64_t is the19// The ctypes boundary cannot propagate C++ exceptions. A positive int64_t is the
19// actual block count; a negative result encodes -(kind << 32 | detail), reported20// actual block count; a negative result encodes -(kind << 32 | detail), reported
20-// unchanged in Python's launch error. The detail holds either the insufficient21+// unchanged in Python's launch error. The detail holds either the budget (cores
21-// budget or all 32 bits of the ACL query's error code.22+// for the Limit kinds, blocks for Request) or the ACL query's error code.
22enum class LaunchError : uint32_t {23enum class LaunchError : uint32_t {
23 CubeLimit = 1,24 CubeLimit = 1,
24 VectorLimit = 2,25 VectorLimit = 2,
25 CubeQuery = 3,26 CubeQuery = 3,
26 VectorQuery = 4,27 VectorQuery = 4,
28+ Request = 5,
27};29};
28 30 
31+// A blockDim of 0 is the host-side "auto" sentinel: the caller did not pick a
32+// block count and the stream's full budget is used. The Python launch boundary
33+// validates user input as positive and saturates oversized requests before the
34+// ABI, so a wrapped or user-supplied 0 cannot reach this protocol.
35+constexpr uint32_t kAutoBlockDim = 0;
36+ 
29inline int64_t EncodeLaunchError(LaunchError kind, uint32_t detail)37inline int64_t EncodeLaunchError(LaunchError kind, uint32_t detail)
30{38{
31 return -static_cast<int64_t>((static_cast<uint64_t>(kind) << 32) | detail);39 return -static_cast<int64_t>((static_cast<uint64_t>(kind) << 32) | detail);
@@ -62,13 +70,26 @@ inline int64_t ResolveLaunchBlockDim(uint32_t blockDim, aclrtStream stream)
62 // Query this launch's stream every time, including capture and cached calls.70 // Query this launch's stream every time, including capture and cached calls.
63 // ACL resolves stream > device > hardware. Caching a budget would retain a71 // ACL resolves stream > device > hardware. Caching a budget would retain a
64 // previous scope's limit; the template arguments cache only the binary's ABI.72 // previous scope's limit; the template arguments cache only the binary's ABI.
65- const int64_t cubeDim = LimitLaunchBlocks<ACL_RT_DEV_RES_CUBE_CORE, CubeCores>(blockDim, stream);73+ // The auto sentinel probes with the largest request, so the clamps return the
74+ // stream's full budget; it self-guards the rejection comparison because a
75+ // budget is never below the sentinel's 0. Negative results are LaunchError
76+ // codes and pass through the final return unchanged, like the original code.
77+ const uint32_t request = blockDim == kAutoBlockDim ? 0xFFFFFFFFu : blockDim;
78+ const int64_t cubeDim = LimitLaunchBlocks<ACL_RT_DEV_RES_CUBE_CORE, CubeCores>(request, stream);
66 if (cubeDim < 0) {79 if (cubeDim < 0) {
67 return cubeDim;80 return cubeDim;
68 }81 }
69 // Both engines of a mixed block must fit together, otherwise cross-core waits82 // Both engines of a mixed block must fit together, otherwise cross-core waits
70 // can lose a participant. Never round a budget up to force a single block.83 // can lose a participant. Never round a budget up to force a single block.
71- return LimitLaunchBlocks<ACL_RT_DEV_RES_VECTOR_CORE, VectorCores>(static_cast<uint32_t>(cubeDim), stream);84+ const int64_t resolved = LimitLaunchBlocks<ACL_RT_DEV_RES_VECTOR_CORE, VectorCores>(static_cast<uint32_t>(cubeDim),
85+ stream);
86+ if (resolved >= 0 && resolved < blockDim) {
87+ // The raw code crosses the ABI; this line is the only human-readable hint.
88+ std::fprintf(stderr, "PyPTO launch rejected: block_dim %u exceeds the stream budget of %u block(s)\n", blockDim,
89+ static_cast<uint32_t>(resolved));
90+ return EncodeLaunchError(LaunchError::Request, static_cast<uint32_t>(resolved));
91+ }
92+ return resolved;
72}93}
73 94 
74} // namespace pypto95} // namespace pypto
@@ -146,7 +146,7 @@ class CompiledKernel:
146 lib_path: str146 lib_path: str
147 param_specs: list[ParamSpec]147 param_specs: list[ParamSpec]
148 # True when the generated kernel uses only vector (AIV) cores (no cube code),148 # True when the generated kernel uses only vector (AIV) cores (no cube code),
149- # so block_dim should be clamped against the vector core count.149+ # so its native block budget comes from the vector core count alone.
150 is_aiv_only: bool = False150 is_aiv_only: bool = False
151 # Identity and artifacts of the generated kernel, forwarded to the exception-dump151 # Identity and artifacts of the generated kernel, forwarded to the exception-dump
152 # bookkeeping on every launch.152 # bookkeeping on every launch.
@@ -834,8 +834,8 @@ def _build_launch_entry(compiled: "CompiledKernel"):
834 if stream is None:834 if stream is None:
835 stream = torch.npu.current_stream()835 stream = torch.npu.current_stream()
836 # Python integers can exceed the uint32_t launch ABI. Saturate the request836 # Python integers can exceed the uint32_t launch ABI. Saturate the request
837- # before ctypes conversion so a large upper bound cannot wrap to zero; the837+ # before ctypes conversion so a large request cannot wrap to zero (0 is the
838- # native query will further reduce it to this stream's actual resources.838+ # native auto sentinel) and is rejected by the native limit check instead.
839 if block_dim > 0xFFFFFFFF:839 if block_dim > 0xFFFFFFFF:
840 block_dim = 0xFFFFFFFF840 block_dim = 0xFFFFFFFF
841 _set_dump_info(compiled, args, block_dim)841 _set_dump_info(compiled, args, block_dim)
@@ -1751,6 +1751,36 @@ def _validate_block_dim(block_dim):
1751 )1751 )
1752 1752 
1753 1753 
1754+# block_dim handed to the native launcher when the caller did not pick a core
1755+# count (direct kernel call); the native side resolves it to the stream's full
1756+# block budget (kAutoBlockDim in pypto_launch.h). Bracket-launch input is
1757+# validated positive by _validate_block_dim and saturated before the ABI, so a
1758+# user-supplied 0 cannot reach this protocol.
1759+_AUTO_BLOCK_DIM = 0
1760+ 
1761+ 
1762+def _auto_block_upper_bound(compiled: "CompiledKernel") -> int:
1763+ """Device-level upper bound on the auto-resolved block count, used to size
1764+ host resources (the sanitizer log buffer) before the native launch resolves
1765+ the sentinel; it can over-estimate, never under-estimate."""
1766+ from pypto_pro.runtime.platform import get_platform_info
1767+ 
1768+ info = get_platform_info()
1769+ target = compiled.target
1770+ if target is not None and info.core_num > 0:
1771+ blocks = []
1772+ if target.aic_per_block:
1773+ blocks.append(info.cube_core_num // target.aic_per_block)
1774+ if target.aiv_per_block:
1775+ blocks.append(info.vector_core_num // target.aiv_per_block)
1776+ if blocks and min(blocks) > 0:
1777+ return min(blocks)
1778+ raise RuntimeError(
1779+ "Cannot size per-block host resources for an auto block_dim launch: "
1780+ "platform core counts are unavailable for this kernel"
1781+ )
1782+ 
1783+ 
1754def _build_sanitizer_entry(compiled: "CompiledKernel", build_dir: str):1784def _build_sanitizer_entry(compiled: "CompiledKernel", build_dir: str):
1755 """Wrap the launch entry of an instrumented kernel with the sanitizer glue.1785 """Wrap the launch entry of an instrumented kernel with the sanitizer glue.
1756 1786 
@@ -1768,18 +1798,21 @@ def _build_sanitizer_entry(compiled: "CompiledKernel", build_dir: str):
1768 base_entry = _build_launch_entry(compiled)1798 base_entry = _build_launch_entry(compiled)
1769 1799 
1770 def entry(args: tuple, block_dim: int, stream):1800 def entry(args: tuple, block_dim: int, stream):
1771- # One region per AIV sub-block, mirroring the device-side buffer layout.1801+ # The sentinel cannot size the buffer (the actual count is resolved
1772- regions = KSANITIZER_SUB_BLOCKS * block_dim1802+ # natively at launch); size by the device-level upper bound instead,
1803+ # while the launch itself still carries the sentinel.
1804+ sized_dim = _auto_block_upper_bound(compiled) if block_dim == _AUTO_BLOCK_DIM else block_dim
1805+ regions = KSANITIZER_SUB_BLOCKS * sized_dim
1773 words_per_region = KSANITIZER_LOG_BUDGET_BYTES // (4 * regions)1806 words_per_region = KSANITIZER_LOG_BUDGET_BYTES // (4 * regions)
1774- capacity_u32 = words_per_region - 1 # one u32 per region is the write counter
1775 nbytes = words_per_region * 4 * regions1807 nbytes = words_per_region * 4 * regions
1776 log_buffer = torch.empty(nbytes, dtype=torch.uint8, device="npu")1808 log_buffer = torch.empty(nbytes, dtype=torch.uint8, device="npu")
1777 # Only the per-region ctr word must start at zero; the record area is1809 # Only the per-region ctr word must start at zero; the record area is
1778 # write-before-read on the device, so zeroing it would be wasted cost.1810 # write-before-read on the device, so zeroing it would be wasted cost.
1779 log_buffer.view(torch.int32)[::words_per_region] = 01811 log_buffer.view(torch.int32)[::words_per_region] = 0
1812+ capacity_u32 = words_per_region - 1
1780 full_args = (*args, log_buffer, capacity_u32)1813 full_args = (*args, log_buffer, capacity_u32)
1781 base_entry(full_args, block_dim, stream)1814 base_entry(full_args, block_dim, stream)
1782- _replay_sanitizer(log_buffer, capacity_u32, block_dim, build_dir, compiled.kernel_name, compiled.source_file)1815+ _replay_sanitizer(log_buffer, capacity_u32, sized_dim, build_dir, compiled.kernel_name, compiled.source_file)
1783 1816 
1784 return entry1817 return entry
1785 1818 
@@ -1957,7 +1990,7 @@ class _TileJitKernel:
1957 Supports:1990 Supports:
1958 kernel[stream, block_dim](x, y, z) — explicit stream and block_dim1991 kernel[stream, block_dim](x, y, z) — explicit stream and block_dim
1959 kernel[block_dim](x, y, z) — default stream, explicit block_dim1992 kernel[block_dim](x, y, z) — default stream, explicit block_dim
1960- kernel(x, y, z) — default stream, block_dim=11993+ kernel(x, y, z) — default stream, full core budget (auto)
1961 """1994 """
1962 1995 
1963 def __init__(1996 def __init__(
@@ -2016,11 +2049,13 @@ class _TileJitKernel:
2016 2049 
2017 Returns a callable launcher that executes the compiled kernel.2050 Returns a callable launcher that executes the compiled kernel.
2018 2051 
2019- ``block_dim`` is an upper bound on worker blocks. Each launch applies the2052+ ``block_dim`` is the exact worker block count and must fit the current
2020- actual stream's torch_npu resource limits, including device defaults and2053+ stream's torch_npu resource limits, including device defaults and
2021- npugraph_ex scopes. Kernels must partition all work using ``get_block_num()``2054+ npugraph_ex scopes; a request above the limit fails the launch instead
2022- (and ``get_subblock_num()`` for mixed vector workers), not a fixed host core2055+ of being silently reduced. Kernels must partition all work using
2023- count. A captured graph retains its launch dimensions until recaptured.2056+ ``get_block_num()`` (and ``get_subblock_num()`` for mixed vector
2057+ workers), not a fixed host core count. A captured graph retains its
2058+ launch dimensions until recaptured.
2024 2059 
2025 For tilingkey kernels the third bracket element is the concrete key dict::2060 For tilingkey kernels the third bracket element is the concrete key dict::
2026 2061 
@@ -2079,7 +2114,7 @@ class _TileJitKernel:
2079 return launcher2114 return launcher
2080 2115 
2081 def __call__(self, *args, **kwargs_):2116 def __call__(self, *args, **kwargs_):
2082- """Direct call with default stream and block_dim=1."""2117+ """Direct call: default stream, block_dim resolved to the stream's full budget."""
2083 if self._tilingkey_schema is not None or self._datatype_schema is not None:2118 if self._tilingkey_schema is not None or self._datatype_schema is not None:
2084 raise NotSupported(2119 raise NotSupported(
2085 f"Kernel '{self.__name__}' has compile-time specialization and cannot be called directly; "2120 f"Kernel '{self.__name__}' has compile-time specialization and cannot be called directly; "
@@ -2089,7 +2124,7 @@ class _TileJitKernel:
2089 if kwargs_ or len(args) != self._positional_arity:2124 if kwargs_ or len(args) != self._positional_arity:
2090 args = self._normalize_launch_args(args, kwargs_)2125 args = self._normalize_launch_args(args, kwargs_)
2091 compiled = self._ensure_compiled(args, spec=_NO_SPEC)2126 compiled = self._ensure_compiled(args, spec=_NO_SPEC)
2092- _launch(compiled, args, 1, None)2127+ _launch(compiled, args, _AUTO_BLOCK_DIM, None)
2093 2128 
2094 def _validate_launch_arch(self) -> None:2129 def _validate_launch_arch(self) -> None:
2095 from pypto_pro.runtime.platform import get_platform_info2130 from pypto_pro.runtime.platform import get_platform_info
@@ -2285,7 +2320,7 @@ class _TileJitKernel:
2285 if cg is None:2320 if cg is None:
2286 raise RuntimeFailure(f"Failed to generate code for kernel '{self.__name__}'")2321 raise RuntimeFailure(f"Failed to generate code for kernel '{self.__name__}'")
2287 2322 
2288- # Resolve once for compiler flags, native resource clamping and debug2323+ # Resolve once for compiler flags, the native block-budget check and debug
2289 # recompilation. Every consumer must use this binary's same core geometry.2324 # recompilation. Every consumer must use this binary's same core geometry.
2290 target = get_jit_compile_config().resolve_kernel_target(2325 target = get_jit_compile_config().resolve_kernel_target(
2291 arch, has_cube=cg.has_cube, has_vector=cg.has_vector,2326 arch, has_cube=cg.has_cube, has_vector=cg.has_vector,
@@ -300,7 +300,11 @@ out = torch.zeros(64, 64, device=dev, dtype=torch.float32)
300out2 = torch.zeros(64, 64, device=dev, dtype=torch.float16)300out2 = torch.zeros(64, 64, device=dev, dtype=torch.float16)
301tiling = SimpleTiling(offset=2, opkind=[1, 0, 0, 0])301tiling = SimpleTiling(offset=2, opkind=[1, 0, 0, 0])
302 302 
303-fused_oob_kernel[None, 32, {"Mode": 2}](a, b, out, out2, tiling)303+# 32 曾被静默钳制到设备预算;显式请求现在必须落在预算内,取当前流的混合块上限。
304+lim = torch.npu.get_stream_limit(torch.npu.current_stream())
305+blocks = min(lim["cube_core_num"], lim["vector_core_num"] // 2)
306+ 
307+fused_oob_kernel[None, blocks, {"Mode": 2}](a, b, out, out2, tiling)
304try:308try:
305 torch.npu.synchronize()309 torch.npu.synchronize()
306 print("ERROR: No AICORE error raised")310 print("ERROR: No AICORE error raised")
@@ -653,7 +653,7 @@ def test_fa_perf():
653 torch.npu.set_device(device)653 torch.npu.set_device(device)
654 torch.manual_seed(42)654 torch.manual_seed(42)
655 for sq, skv, d, num_cores in [655 for sq, skv, d, num_cores in [
656- (8192, 8192, TD, 32),656+ (8192, 8192, TD, 28), # 950 默认流预算 28 cube 核
657 ]:657 ]:
658 logging.info("\nFA-Perf DN (%s,%s,%s) cores=%s", sq, skv, d, num_cores)658 logging.info("\nFA-Perf DN (%s,%s,%s) cores=%s", sq, skv, d, num_cores)
659 q_t = torch.rand((sq, d), device=device, dtype=torch.float16)659 q_t = torch.rand((sq, d), device=device, dtype=torch.float16)
@@ -557,7 +557,7 @@ def test_fa_perf():
557 torch.npu.set_device(device)557 torch.npu.set_device(device)
558 torch.manual_seed(42)558 torch.manual_seed(42)
559 for sq, skv, d, num_cores in [559 for sq, skv, d, num_cores in [
560- (8192, 256, TD, 32),560+ (8192, 256, TD, 28), # 950 默认流预算 28 cube 核
561 ]:561 ]:
562 logging.info("\nFA-Perf DN (%s,%s,%s) cores=%s", sq, skv, d, num_cores)562 logging.info("\nFA-Perf DN (%s,%s,%s) cores=%s", sq, skv, d, num_cores)
563 q_t = torch.rand((sq, d), device=device, dtype=torch.float16)563 q_t = torch.rand((sq, d), device=device, dtype=torch.float16)
@@ -80,7 +80,7 @@ def getval_while_condition_am_kernel(
80def _run_and_measure(a: torch.Tensor):80def _run_and_measure(a: torch.Tensor):
81 """Launch kernel; return (max_abs_diff_vs_golden, details dict)."""81 """Launch kernel; return (max_abs_diff_vs_golden, details dict)."""
82 a_cpu = a.detach().to("cpu", torch.float32)82 a_cpu = a.detach().to("cpu", torch.float32)
83- getval_setval_am_kernel(a)83+ getval_setval_am_kernel[None, 1](a)
84 torch.npu.synchronize()84 torch.npu.synchronize()
85 out = a.detach().to("cpu", torch.float32)85 out = a.detach().to("cpu", torch.float32)
86 86 
@@ -80,7 +80,9 @@ def test_add():
80 80 
81 m_size = 819281 m_size = 8192
82 n_size = 409682 n_size = 4096
83- num_cores = m_size // 12883+ # 请求不得超过流预算;按 M tile 数与 vector 核预算取小。
84+ vector_budget = torch.npu.get_stream_limit(torch.npu.current_stream())["vector_core_num"]
85+ num_cores = min(m_size // 128, vector_budget)
84 86 
85 torch.manual_seed(0)87 torch.manual_seed(0)
86 dtype = torch.float1688 dtype = torch.float16
@@ -135,7 +135,8 @@ def test_float_divmod_defines_static_tile_shape():
135 torch.npu.set_device(ST_DEVICE)135 torch.npu.set_device(ST_DEVICE)
136 src = torch.arange(8, dtype=torch.float32, device=ST_DEVICE).reshape(1, 8)136 src = torch.arange(8, dtype=torch.float32, device=ST_DEVICE).reshape(1, 8)
137 out = torch.empty_like(src)137 out = torch.empty_like(src)
138- scalar_float_static_shape_kernel(src, out)138+ # 单 tile 语义验证:直调现为满核,显式请求 1 块保持单核语义。
139+ scalar_float_static_shape_kernel[None, 1](src, out)
139 torch.npu.synchronize()140 torch.npu.synchronize()
140 torch.testing.assert_close(out, src, rtol=0, atol=0)141 torch.testing.assert_close(out, src, rtol=0, atol=0)
141 142 
@@ -565,7 +565,8 @@ def test_with_cube_then_vector():
565 b = torch.randn(32, 64, device=device, dtype=torch.float16)565 b = torch.randn(32, 64, device=device, dtype=torch.float16)
566 x = torch.randn(64, 64, device=device, dtype=torch.float32)566 x = torch.randn(64, 64, device=device, dtype=torch.float32)
567 out = torch.zeros(64, 64, device=device, dtype=torch.float32)567 out = torch.zeros(64, 64, device=device, dtype=torch.float32)
568- with_cube_then_vector_kernel(a, b, x, out)568+ # 单 tile 读写回 GM:多核会对同一输出互相读到中间结果,显式单块。
569+ with_cube_then_vector_kernel[None, 1](a, b, x, out)
569 torch.npu.synchronize()570 torch.npu.synchronize()
570 z_ref = torch.matmul(a.float(), b.float()) + x.float()571 z_ref = torch.matmul(a.float(), b.float()) + x.float()
571 torch.testing.assert_close(out, z_ref, atol=1e-2, rtol=1e-2)572 torch.testing.assert_close(out, z_ref, atol=1e-2, rtol=1e-2)
@@ -681,7 +682,8 @@ def test_with_cube_then_vf():
681 b = torch.randn(32, 64, device=device, dtype=torch.float16)682 b = torch.randn(32, 64, device=device, dtype=torch.float16)
682 d = torch.randn(1, 64, device=device, dtype=torch.float32)683 d = torch.randn(1, 64, device=device, dtype=torch.float32)
683 out = torch.zeros(64, 64, device=device, dtype=torch.float32)684 out = torch.zeros(64, 64, device=device, dtype=torch.float32)
684- with_cube_then_vf_kernel(a, b, d, out)685+ # 单 tile 读改写 GM:多核会对同一输出互相读到中间结果,显式单块。
686+ with_cube_then_vf_kernel[None, 1](a, b, d, out)
685 torch.npu.synchronize()687 torch.npu.synchronize()
686 mm = torch.matmul(a.float(), b.float())688 mm = torch.matmul(a.float(), b.float())
687 z_ref = mm + d689 z_ref = mm + d
@@ -2,14 +2,14 @@
2# This program is free software, you can redistribute it and/or modify it under the terms and conditions of2# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3# CANN Open Software License Agreement Version 2.0 (the "License").3# CANN Open Software License Agreement Version 2.0 (the "License").
4# Please refer to the License for details. You may not use this file except in compliance with the License.4# Please refer to the License for details. You may not use this file except in compliance with the License.
5-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED.
6-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
7# See LICENSE in the root of the software repository for the full text of the License.7# See LICENSE in the root of the software repository for the full text of the License.
8# -----------------------------------------------------------------------------------------------------------8# -----------------------------------------------------------------------------------------------------------
9"""Boundary and state-transition tests for core limits, using device-written worker counts."""9"""Boundary and state-transition tests for core limits, using device-written worker counts."""
10 10 
11import pytest11import pytest
12-from test_core_limits import DEVICE_ID, KERNELS, REQUESTED, _check, _outputs12+from test_core_limits import DEVICE_ID, KERNELS, _check, _outputs
13import torch13import torch
14 14 
15pytestmark = pytest.mark.soc("950")15pytestmark = pytest.mark.soc("950")
@@ -29,7 +29,7 @@ def stream():
29@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])29@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])
30@pytest.mark.parametrize("requested", [1, 3])30@pytest.mark.parametrize("requested", [1, 3])
31def test_limit_never_increases_requested_blocks(stream, kind, requested):31def test_limit_never_increases_requested_blocks(stream, kind, requested):
32- """Available resources are a ceiling; substituting the limit for the request starts extra workers."""32+ """A request within the budget launches exactly the requested count; available resources are a ceiling."""
33 outputs = _outputs()33 outputs = _outputs()
34 torch.npu.synchronize()34 torch.npu.synchronize()
35 torch.npu.set_stream_limit(stream, 8, 16)35 torch.npu.set_stream_limit(stream, 8, 16)
@@ -40,43 +40,43 @@ def test_limit_never_increases_requested_blocks(stream, kind, requested):
40 40 
41@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])41@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])
42@pytest.mark.parametrize("requested", [1 << 32, (1 << 32) + 1, 1 << 100])42@pytest.mark.parametrize("requested", [1 << 32, (1 << 32) + 1, 1 << 100])
43-def test_large_request_does_not_wrap_at_native_boundary(stream, kind, requested):43+def test_large_request_is_rejected_not_wrapped(stream, kind, requested):
44- """Clamping after ctypes conversion would turn these upper bounds into zero or one block."""44+ """Saturation must keep a huge request positive and rejected, never wrapped onto the auto sentinel."""
45 outputs = _outputs()45 outputs = _outputs()
46 torch.npu.synchronize()46 torch.npu.synchronize()
47 torch.npu.set_stream_limit(stream, 4, 6)47 torch.npu.set_stream_limit(stream, 4, 6)
48- KERNELS[kind][stream, requested](*outputs)48+ with pytest.raises(RuntimeError, match="Kernel launch failed with error code"):
49- stream.synchronize()49+ KERNELS[kind][stream, requested](*outputs)
50- _check(outputs, kind, (4, 6, 3)[kind])
51 50 
52 51 
53@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])52@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])
54-def test_direct_call_keeps_one_block_in_scope(stream, kind):53+def test_direct_call_uses_the_scope_budget(stream, kind):
55- """The direct-call path must use the current stream and preserve its implicit request of one block."""54+ """The direct-call path must use the current stream and resolve to its full budget."""
56 outputs = _outputs()55 outputs = _outputs()
57 torch.npu.synchronize()56 torch.npu.synchronize()
58 with torch.npu.stream(stream), torch.npu.npugraph_ex.scope.limit_core_num(4, 8):57 with torch.npu.stream(stream), torch.npu.npugraph_ex.scope.limit_core_num(4, 8):
59 KERNELS[kind](*outputs)58 KERNELS[kind](*outputs)
60 stream.synchronize()59 stream.synchronize()
61- _check(outputs, kind, 1)60+ _check(outputs, kind, (4, 8, 4)[kind])
62 61 
63 62 
64@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])63@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])
65-@pytest.mark.parametrize("update,expected", [({"cube_num": 3}, (3, 12, 3)), ({"vector_num": 5}, (8, 5, 2))])64+@pytest.mark.parametrize("update,expected", [({"cube_num": 3}, (3, 16, 3)), ({"vector_num": 5}, (8, 5, 2))])
66def test_partial_stream_update(stream, kind, update, expected):65def test_partial_stream_update(stream, kind, update, expected):
67 """Updating only one resource must preserve the other engine's independently configured budget."""66 """Updating only one resource must preserve the other engine's independently configured budget."""
68 outputs = _outputs()67 outputs = _outputs()
69 torch.npu.synchronize()68 torch.npu.synchronize()
70 torch.npu.set_stream_limit(stream, 8, 16)69 torch.npu.set_stream_limit(stream, 8, 16)
71 torch.npu.set_stream_limit(stream, **update)70 torch.npu.set_stream_limit(stream, **update)
72- KERNELS[kind][stream, REQUESTED](*outputs)71+ with torch.npu.stream(stream):
72+ KERNELS[kind](*outputs)
73 stream.synchronize()73 stream.synchronize()
74 _check(outputs, kind, expected[kind])74 _check(outputs, kind, expected[kind])
75 75 
76 76 
77@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])77@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])
78def test_cached_kernel_alternates_streams(stream, kind):78def test_cached_kernel_alternates_streams(stream, kind):
79- """One compiled entry must follow the passed stream rather than the stream used on its first call."""79+ """One compiled kernel must follow the current stream rather than the stream used on its first call."""
80 other = torch.npu.Stream()80 other = torch.npu.Stream()
81 torch.npu.set_stream_limit(stream, 3, 8)81 torch.npu.set_stream_limit(stream, 3, 8)
82 torch.npu.set_stream_limit(other, 6, 4)82 torch.npu.set_stream_limit(other, 6, 4)
@@ -84,7 +84,8 @@ def test_cached_kernel_alternates_streams(stream, kind):
84 for target, blocks in [(stream, (3, 8, 3)), (other, (6, 4, 2)), (stream, (3, 8, 3))]:84 for target, blocks in [(stream, (3, 8, 3)), (other, (6, 4, 2)), (stream, (3, 8, 3))]:
85 outputs = _outputs()85 outputs = _outputs()
86 torch.npu.synchronize()86 torch.npu.synchronize()
87- KERNELS[kind][target, REQUESTED](*outputs)87+ with torch.npu.stream(target):
88+ KERNELS[kind](*outputs)
88 target.synchronize()89 target.synchronize()
89 _check(outputs, kind, blocks[kind])90 _check(outputs, kind, blocks[kind])
90 finally:91 finally:
@@ -98,7 +99,8 @@ def test_unused_engine_does_not_constrain_launch(stream, kind, limits, blocks):
98 outputs = _outputs()99 outputs = _outputs()
99 torch.npu.synchronize()100 torch.npu.synchronize()
100 torch.npu.set_stream_limit(stream, *limits)101 torch.npu.set_stream_limit(stream, *limits)
101- KERNELS[kind][stream, REQUESTED](*outputs)102+ with torch.npu.stream(stream):
103+ KERNELS[kind](*outputs)
102 stream.synchronize()104 stream.synchronize()
103 _check(outputs, kind, blocks)105 _check(outputs, kind, blocks)
104 106 
@@ -107,7 +109,7 @@ def test_insufficient_mixed_budget_rejects_without_device_writes(stream):
107 """Reject before launching any synchronized participants, then allow reuse after the budget is corrected."""109 """Reject before launching any synchronized participants, then allow reuse after the budget is corrected."""
108 outputs = _outputs()110 outputs = _outputs()
109 torch.npu.synchronize()111 torch.npu.synchronize()
110- launcher = KERNELS[2][stream, REQUESTED]112+ launcher = KERNELS[2][stream, 2]
111 torch.npu.set_stream_limit(stream, 4, 1)113 torch.npu.set_stream_limit(stream, 4, 1)
112 with pytest.raises(RuntimeError, match=f"Kernel launch failed with error code {-0x200000001}$"):114 with pytest.raises(RuntimeError, match=f"Kernel launch failed with error code {-0x200000001}$"):
113 launcher(*outputs)115 launcher(*outputs)
@@ -124,7 +126,8 @@ def test_raw_graph_recapture_observes_new_limits(stream, kind):
124 """Raw replay retains the old count, while recapturing the same compiled kernel reads the new stream budget."""126 """Raw replay retains the old count, while recapturing the same compiled kernel reads the new stream budget."""
125 outputs = _outputs()127 outputs = _outputs()
126 torch.npu.synchronize()128 torch.npu.synchronize()
127- KERNELS[kind][stream, REQUESTED](*outputs)129+ with torch.npu.stream(stream):
130+ KERNELS[kind](*outputs)
128 stream.synchronize()131 stream.synchronize()
129 graphs = []132 graphs = []
130 for limits, expected in [((4, 8), (4, 8, 4)), ((2, 6), (2, 6, 2))]:133 for limits, expected in [((4, 8), (4, 8, 4)), ((2, 6), (2, 6, 2))]:
@@ -134,7 +137,8 @@ def test_raw_graph_recapture_observes_new_limits(stream, kind):
134 torch.npu.set_stream_limit(stream, *limits)137 torch.npu.set_stream_limit(stream, *limits)
135 graph = torch.npu.NPUGraph()138 graph = torch.npu.NPUGraph()
136 with torch.npu.graph(graph, stream=stream):139 with torch.npu.graph(graph, stream=stream):
137- KERNELS[kind][stream, REQUESTED](*outputs)140+ with torch.npu.stream(stream):
141+ KERNELS[kind](*outputs)
138 graphs.append(graph)142 graphs.append(graph)
139 graph.replay()143 graph.replay()
140 torch.npu.synchronize()144 torch.npu.synchronize()
@@ -2,8 +2,8 @@
2# This program is free software, you can redistribute it and/or modify it under the terms and conditions of2# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3# CANN Open Software License Agreement Version 2.0 (the "License").3# CANN Open Software License Agreement Version 2.0 (the "License").
4# Please refer to the License for details. You may not use this file except in compliance with the License.4# Please refer to the License for details. You may not use this file except in compliance with the License.
5-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED.
6-# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
7# See LICENSE in the root of the software repository for the full text of the License.7# See LICENSE in the root of the software repository for the full text of the License.
8# -----------------------------------------------------------------------------------------------------------8# -----------------------------------------------------------------------------------------------------------
9"""Observe device block counts and complete work coverage under all torch_npu limit scopes.9"""Observe device block counts and complete work coverage under all torch_npu limit scopes.
@@ -12,6 +12,9 @@ Every worker writes a separate 128-byte cache line, avoiding scalar-store false
12The work array has more tasks than launched workers, so blindly dropping workers from12The work array has more tasks than launched workers, so blindly dropping workers from
13fixed host tiling cannot pass these accuracy checks. Count arrays also distinguish a13fixed host tiling cannot pass these accuracy checks. Count arrays also distinguish a
14correct numerical result produced with too many cores from a compliant launch.14correct numerical result produced with too many cores from a compliant launch.
15+ 
16+An explicit block_dim must fit the stream's budget; a request above it is rejected.
17+A direct call carries the auto sentinel and resolves to the stream's full budget.
15"""18"""
16 19 
17import os20import os
@@ -26,7 +29,6 @@ import torch_npu # noqa: F401 - installs torch.npu
26 29 
27SIZE = 409630SIZE = 4096
28TASKS = 10131TASKS = 101
29-REQUESTED = 12
30DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))32DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
31pytestmark = pytest.mark.soc("950")33pytestmark = pytest.mark.soc("950")
32 34 
@@ -111,32 +113,53 @@ def _check(outputs, kind, blocks):
111 torch.testing.assert_close(actual, reference, rtol=0, atol=0)113 torch.testing.assert_close(actual, reference, rtol=0, atol=0)
112 print(f"kind={kind} blocks={blocks}: count/work max_abs_error=0, exact_match=100%")114 print(f"kind={kind} blocks={blocks}: count/work max_abs_error=0, exact_match=100%")
113 115 
114- 
115@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])116@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])
116@pytest.mark.parametrize("limits", [(4, 10), (8, 5)])117@pytest.mark.parametrize("limits", [(4, 10), (8, 5)])
117-@pytest.mark.parametrize("use_current", [False, True], ids=["explicit_stream", "current_stream"])118+def test_stream_limits(stream, kind, limits):
118-def test_stream_limits(stream, kind, limits, use_current):
119 """Asymmetric limits catch using cube counts for vectors or ignoring mixed vector demand."""119 """Asymmetric limits catch using cube counts for vectors or ignoring mixed vector demand."""
120 outputs = _outputs()120 outputs = _outputs()
121 torch.npu.synchronize()121 torch.npu.synchronize()
122 torch.npu.set_stream_limit(stream, cube_num=limits[0], vector_num=limits[1])122 torch.npu.set_stream_limit(stream, cube_num=limits[0], vector_num=limits[1])
123 blocks = (limits[0], limits[1], min(limits[0], limits[1] // 2))[kind]123 blocks = (limits[0], limits[1], min(limits[0], limits[1] // 2))[kind]
124 with torch.npu.stream(stream):124 with torch.npu.stream(stream):
125- KERNELS[kind][None if use_current else stream, REQUESTED](*outputs)125+ KERNELS[kind](*outputs)
126 stream.synchronize()126 stream.synchronize()
127 _check(outputs, kind, blocks)127 _check(outputs, kind, blocks)
128 128 
129 129 
130@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])130@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])
131-def test_nested_scope_and_cached_launcher(stream, kind):131+@pytest.mark.parametrize("use_current", [False, True], ids=["explicit_stream", "current_stream"])
132- """The same bracket launcher must honor nesting, exception restoration and subsequent resets."""132+def test_bracket_request_within_limits_launches_exactly(stream, kind, use_current):
133- launcher = KERNELS[kind][stream, REQUESTED]133+ """An explicit request that fits the budget launches exactly that many blocks on the named stream."""
134+ outputs = _outputs()
135+ torch.npu.synchronize()
136+ torch.npu.set_stream_limit(stream, cube_num=4, vector_num=10)
137+ with torch.npu.stream(stream):
138+ KERNELS[kind][None if use_current else stream, 4](*outputs)
139+ stream.synchronize()
140+ _check(outputs, kind, 4)
141+ 
142+ 
143+@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])
144+def test_request_above_stream_limit_is_rejected(stream, kind):
145+ """A request the stream cannot host fails the launch."""
146+ outputs = _outputs()
147+ torch.npu.synchronize()
148+ torch.npu.set_stream_limit(stream, 4, 6)
149+ with pytest.raises(RuntimeError, match="Kernel launch failed with error code"):
150+ KERNELS[kind][stream, 12](*outputs)
151+ 
152+ 
153+@pytest.mark.parametrize("kind", range(3), ids=["cube", "vector", "mixed"])
154+def test_nested_scope_and_cached_kernel(stream, kind):
155+ """Direct launches must honor nesting, exception restoration and subsequent resets."""
134 torch.npu.set_stream_limit(stream, 8, 10)156 torch.npu.set_stream_limit(stream, 8, 10)
135 157 
136 def run(blocks):158 def run(blocks):
137 outputs = _outputs()159 outputs = _outputs()
138 torch.npu.synchronize()160 torch.npu.synchronize()
139- launcher(*outputs)161+ with torch.npu.stream(stream):
162+ KERNELS[kind](*outputs)
140 stream.synchronize()163 stream.synchronize()
141 _check(outputs, kind, blocks)164 _check(outputs, kind, blocks)
142 165 
@@ -153,7 +176,7 @@ def test_nested_scope_and_cached_launcher(stream, kind):
153 inherited = torch.npu.get_stream_limit(stream)176 inherited = torch.npu.get_stream_limit(stream)
154 blocks = (inherited["cube_core_num"], inherited["vector_core_num"],177 blocks = (inherited["cube_core_num"], inherited["vector_core_num"],
155 min(inherited["cube_core_num"], inherited["vector_core_num"] // 2))[kind]178 min(inherited["cube_core_num"], inherited["vector_core_num"] // 2))[kind]
156- run(min(REQUESTED, blocks))179+ run(blocks)
157 180 
158 181 
159def test_explicit_scope_does_not_limit_other_stream(stream):182def test_explicit_scope_does_not_limit_other_stream(stream):
@@ -164,7 +187,7 @@ def test_explicit_scope_does_not_limit_other_stream(stream):
164 torch.npu.synchronize()187 torch.npu.synchronize()
165 try:188 try:
166 with torch.npu.stream(other), torch.npu.npugraph_ex.scope.limit_core_num(2, 2, stream=stream):189 with torch.npu.stream(other), torch.npu.npugraph_ex.scope.limit_core_num(2, 2, stream=stream):
167- vector_probe[REQUESTED](*outputs)190+ vector_probe(*outputs)
168 other.synchronize()191 other.synchronize()
169 _check(outputs, 1, 8)192 _check(outputs, 1, 8)
170 finally:193 finally:
@@ -178,7 +201,8 @@ def test_capture_scopes_and_replay(stream, kind):
178 outputs = [_outputs(), _outputs()]201 outputs = [_outputs(), _outputs()]
179 torch.npu.synchronize()202 torch.npu.synchronize()
180 # Compile and bind before capture; warmup results must not mask missing graph writes.203 # Compile and bind before capture; warmup results must not mask missing graph writes.
181- KERNELS[kind][stream, REQUESTED](*outputs[0])204+ with torch.npu.stream(stream):
205+ KERNELS[kind](*outputs[0])
182 stream.synchronize()206 stream.synchronize()
183 for group in outputs:207 for group in outputs:
184 for tensor in group:208 for tensor in group:
@@ -187,9 +211,9 @@ def test_capture_scopes_and_replay(stream, kind):
187 graph = torch.npu.NPUGraph()211 graph = torch.npu.NPUGraph()
188 with torch.npu.graph(graph, stream=stream):212 with torch.npu.graph(graph, stream=stream):
189 with torch.npu.npugraph_ex.scope.limit_core_num(4, 6):213 with torch.npu.npugraph_ex.scope.limit_core_num(4, 6):
190- KERNELS[kind][REQUESTED](*outputs[0])214+ KERNELS[kind](*outputs[0])
191 with torch.npu.npugraph_ex.scope.limit_core_num(2, 2, stream=stream):215 with torch.npu.npugraph_ex.scope.limit_core_num(2, 2, stream=stream):
192- KERNELS[kind][stream, REQUESTED](*outputs[1])216+ KERNELS[kind](*outputs[1])
193 for _ in range(2):217 for _ in range(2):
194 graph.replay()218 graph.replay()
195 torch.npu.synchronize()219 torch.npu.synchronize()
@@ -198,7 +222,7 @@ def test_capture_scopes_and_replay(stream, kind):
198 for group in outputs:222 for group in outputs:
199 for tensor in group:223 for tensor in group:
200 tensor.zero_()224 tensor.zero_()
201- torch.npu.synchronize()225+ torch.npu.synchronize()
202 226 
203 227 
204@pytest.mark.skip_jit_discovery(reason="Device-limit probe compiles and runs in its own process")228@pytest.mark.skip_jit_discovery(reason="Device-limit probe compiles and runs in its own process")
@@ -219,19 +243,22 @@ def _device_probe():
219 for kind in range(3):243 for kind in range(3):
220 outputs = _outputs()244 outputs = _outputs()
221 torch.npu.synchronize()245 torch.npu.synchronize()
222- KERNELS[kind][stream, REQUESTED](*outputs)246+ with torch.npu.stream(stream):
247+ KERNELS[kind](*outputs)
223 stream.synchronize()248 stream.synchronize()
224 _check(outputs, kind, (4, 6, 3)[kind])249 _check(outputs, kind, (4, 6, 3)[kind])
225 torch.npu.set_stream_limit(stream, cube_num=8, vector_num=10)250 torch.npu.set_stream_limit(stream, cube_num=8, vector_num=10)
226 outputs = _outputs()251 outputs = _outputs()
227 torch.npu.synchronize()252 torch.npu.synchronize()
228- mixed_probe[stream, REQUESTED](*outputs)253+ with torch.npu.stream(stream):
254+ mixed_probe(*outputs)
229 stream.synchronize()255 stream.synchronize()
230 _check(outputs, 2, 5)256 _check(outputs, 2, 5)
231 torch.npu.reset_stream_limit(stream)257 torch.npu.reset_stream_limit(stream)
232 outputs = _outputs()258 outputs = _outputs()
233 torch.npu.synchronize()259 torch.npu.synchronize()
234- mixed_probe[stream, REQUESTED](*outputs)260+ with torch.npu.stream(stream):
261+ mixed_probe(*outputs)
235 stream.synchronize()262 stream.synchronize()
236 _check(outputs, 2, 3)263 _check(outputs, 2, 3)
237 264 
@@ -10,7 +10,7 @@
10 10 
11import pypto_pro.language as pl11import pypto_pro.language as pl
12import pytest12import pytest
13-from test_core_limits import DEVICE_ID, REQUESTED13+from test_core_limits import DEVICE_ID
14import torch14import torch
15 15 
16CV_TILE_M = 6416CV_TILE_M = 64
@@ -111,15 +111,17 @@ def test_limited_matmul(limits, capture):
111 out = torch.zeros((CV_M, CV_TILE_N), dtype=torch.float32, device=a.device)111 out = torch.zeros((CV_M, CV_TILE_N), dtype=torch.float32, device=a.device)
112 s = torch.npu.Stream()112 s = torch.npu.Stream()
113 torch.npu.synchronize()113 torch.npu.synchronize()
114- with torch.npu.npugraph_ex.scope.limit_core_num(*limits, stream=s):114+ # A direct call carries the auto sentinel: the launch takes the scope's full
115- limited_matmul[s, REQUESTED](a, b, out)115+ # block budget, the same counts the previous clamped request produced.
116+ with torch.npu.npugraph_ex.scope.limit_core_num(*limits, stream=s), torch.npu.stream(s):
117+ limited_matmul(a, b, out)
116 s.synchronize()118 s.synchronize()
117 if capture:119 if capture:
118 out.zero_()120 out.zero_()
119 torch.npu.synchronize()121 torch.npu.synchronize()
120 graph = torch.npu.NPUGraph()122 graph = torch.npu.NPUGraph()
121 with torch.npu.graph(graph, stream=s):123 with torch.npu.graph(graph, stream=s):
122- limited_matmul[s, REQUESTED](a, b, out)124+ limited_matmul(a, b, out)
123 if capture:125 if capture:
124 graph.replay()126 graph.replay()
125 torch.npu.synchronize()127 torch.npu.synchronize()
@@ -9,7 +9,7 @@
9"""Exercise real npugraph_ex scope lowering around an opaque PyPTO custom operator."""9"""Exercise real npugraph_ex scope lowering around an opaque PyPTO custom operator."""
10 10 
11import pytest11import pytest
12-from test_core_limits import DEVICE_ID, KERNELS, REQUESTED, SIZE, _check12+from test_core_limits import DEVICE_ID, KERNELS, SIZE, _check
13import torch13import torch
14 14 
15 15 
@@ -29,7 +29,8 @@ def _isolated_graph_cache():
29@torch.library.custom_op("pypto_core_limits::probe", mutates_args=())29@torch.library.custom_op("pypto_core_limits::probe", mutates_args=())
30def _probe(x: torch.Tensor, kind: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:30def _probe(x: torch.Tensor, kind: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
31 outputs = tuple(torch.zeros(SIZE, dtype=torch.int32, device=x.device) for _ in range(3))31 outputs = tuple(torch.zeros(SIZE, dtype=torch.int32, device=x.device) for _ in range(3))
32- KERNELS[kind][REQUESTED](*outputs)32+ # Direct call: the auto sentinel resolves to the scope's full budget at capture.
33+ KERNELS[kind](*outputs)
33 return outputs34 return outputs
34 35 
35 36 
@@ -1649,7 +1649,7 @@ def test_store_atomic_add():
1649 a = _inputs(device, [TILE, TILE])1649 a = _inputs(device, [TILE, TILE])
1650 b = torch.eye(TILE, device=device, dtype=torch.float16)1650 b = torch.eye(TILE, device=device, dtype=torch.float16)
1651 out = torch.zeros([TILE, TILE], device=device, dtype=torch.float32)1651 out = torch.zeros([TILE, TILE], device=device, dtype=torch.float32)
1652- call_kernel_store_atomic_add(a, b, out)1652+ call_kernel_store_atomic_add[None, 1](a, b, out)
1653 torch.npu.synchronize()1653 torch.npu.synchronize()
1654 torch.testing.assert_close(out, a.float() * 2, rtol=1e-2, atol=1e-2)1654 torch.testing.assert_close(out, a.float() * 2, rtol=1e-2, atol=1e-2)
1655 1655 
@@ -261,7 +261,7 @@ def test_atomic_add():
261 scale_bits = struct.unpack("!I", struct.pack("!f", scale_value))[0]261 scale_bits = struct.unpack("!I", struct.pack("!f", scale_value))[0]
262 262 
263 # First store (initial values)263 # First store (initial values)
264- scale_atomic_add_kernel(q, k, quant_out, scale_bits)264+ scale_atomic_add_kernel[None, 1](q, k, quant_out, scale_bits)
265 torch.npu.synchronize()265 torch.npu.synchronize()
266 266 
267 raw_ref = torch.matmul(q, k)267 raw_ref = torch.matmul(q, k)
@@ -270,7 +270,7 @@ def test_atomic_add():
270 torch.testing.assert_close(quant_out.to(torch.int32), expected_first.to(torch.int32), rtol=0, atol=1)270 torch.testing.assert_close(quant_out.to(torch.int32), expected_first.to(torch.int32), rtol=0, atol=1)
271 271 
272 # Second store (atomic add)272 # Second store (atomic add)
273- scale_atomic_add_kernel(q, k, quant_out, scale_bits)273+ scale_atomic_add_kernel[None, 1](q, k, quant_out, scale_bits)
274 torch.npu.synchronize()274 torch.npu.synchronize()
275 275 
276 # Expected: first + second (with saturation)276 # Expected: first + second (with saturation)
@@ -73,7 +73,9 @@ def test_add():
73 73 
74 m_size = 819274 m_size = 8192
75 n_size = 409675 n_size = 4096
76- num_cores = m_size // 12876+ # 请求不得超过流预算(vector 核 56);超出会直接报错而非钳制。
77+ vector_budget = torch.npu.get_stream_limit(torch.npu.current_stream())["vector_core_num"]
78+ num_cores = min(m_size // 128, vector_budget)
77 79 
78 torch.manual_seed(0)80 torch.manual_seed(0)
79 dtype = torch.float1681 dtype = torch.float16
@@ -115,7 +115,7 @@ def test_axpy():
115 x = torch.randn(64, 64, device=device, dtype=torch.float32)115 x = torch.randn(64, 64, device=device, dtype=torch.float32)
116 y = torch.randn(64, 64, device=device, dtype=torch.float32)116 y = torch.randn(64, 64, device=device, dtype=torch.float32)
117 y_orig = y.clone()117 y_orig = y.clone()
118- axpy_kernel(x, y)118+ axpy_kernel[None, 1](x, y)
119 torch.npu.synchronize()119 torch.npu.synchronize()
120 y_ref = ALPHA * x + y_orig120 y_ref = ALPHA * x + y_orig
121 torch.testing.assert_close(y, y_ref, rtol=1e-2, atol=1e-2)121 torch.testing.assert_close(y, y_ref, rtol=1e-2, atol=1e-2)
@@ -124,7 +124,7 @@ def test_mul_add_dst():
124 z = torch.randn(M, N, device=ST_DEVICE, dtype=torch.float16)124 z = torch.randn(M, N, device=ST_DEVICE, dtype=torch.float16)
125 z_orig = z.clone()125 z_orig = z.clone()
126 z_ref = z_orig + x * y126 z_ref = z_orig + x * y
127- mul_add_dst_kernel(x, y, z)127+ mul_add_dst_kernel[None, 1](x, y, z)
128 torch.npu.synchronize()128 torch.npu.synchronize()
129 torch.testing.assert_close(z, z_ref, atol=1e-2, rtol=1e-2)129 torch.testing.assert_close(z, z_ref, atol=1e-2, rtol=1e-2)
130 logging.info("test_mul_add_dst passed!")130 logging.info("test_mul_add_dst passed!")
@@ -138,7 +138,7 @@ def test_fused_mul_add_relu():
138 z = torch.randn(M, N, device=ST_DEVICE, dtype=torch.float16)138 z = torch.randn(M, N, device=ST_DEVICE, dtype=torch.float16)
139 z_orig = z.clone()139 z_orig = z.clone()
140 z_ref = torch.relu(z_orig * x + y)140 z_ref = torch.relu(z_orig * x + y)
141- fused_mul_add_relu_kernel(x, y, z)141+ fused_mul_add_relu_kernel[None, 1](x, y, z)
142 torch.npu.synchronize()142 torch.npu.synchronize()
143 torch.testing.assert_close(z, z_ref, atol=1e-2, rtol=1e-2)143 torch.testing.assert_close(z, z_ref, atol=1e-2, rtol=1e-2)
144 logging.info("test_fused_mul_add_relu passed!")144 logging.info("test_fused_mul_add_relu passed!")
@@ -211,7 +211,8 @@ def test_fused_mul_add():
211 b = torch.randn(64, 64, device=device, dtype=torch.float32)211 b = torch.randn(64, 64, device=device, dtype=torch.float32)
212 c = torch.randn(64, 64, device=device, dtype=torch.float32)212 c = torch.randn(64, 64, device=device, dtype=torch.float32)
213 c_ref = c * a + b213 c_ref = c * a + b
214- fused_mul_add_kernel(a, b, c)214+ # 单核验证:kernel 对 c 做原位读改写,直调现在解析为满核(多核回写同一区域会竞态),这里显式请求 1 块。
215+ fused_mul_add_kernel[None, 1](a, b, c)
215 torch.npu.synchronize()216 torch.npu.synchronize()
216 torch.testing.assert_close(c, c_ref, rtol=1e-2, atol=1e-2)217 torch.testing.assert_close(c, c_ref, rtol=1e-2, atol=1e-2)
217 logging.info("fused_mul_add result equal!")218 logging.info("fused_mul_add result equal!")
@@ -686,7 +686,7 @@ def test_fa_perf():
686 torch.npu.set_device(device)686 torch.npu.set_device(device)
687 torch.manual_seed(42)687 torch.manual_seed(42)
688 for sq, skv, d, num_cores in [688 for sq, skv, d, num_cores in [
689- (8192, 8192, TD, 32),689+ (8192, 8192, TD, 28), # 950 默认流预算 28 cube 核
690 ]:690 ]:
691 logging.info("\nFA-Perf DN (%s,%s,%s) cores=%s QK_PRELOAD=%s", sq, skv, d, num_cores, QK_PRELOAD)691 logging.info("\nFA-Perf DN (%s,%s,%s) cores=%s QK_PRELOAD=%s", sq, skv, d, num_cores, QK_PRELOAD)
692 q_t = torch.rand((sq, d), device=device, dtype=torch.float16)692 q_t = torch.rand((sq, d), device=device, dtype=torch.float16)
@@ -730,7 +730,7 @@ def test_fa_perf():
730 torch.manual_seed(42)730 torch.manual_seed(42)
731 attn_mask = make_causal_mask_dn_fixed_u8(device)731 attn_mask = make_causal_mask_dn_fixed_u8(device)
732 for b, sq, n, skv, d, num_cores in [732 for b, sq, n, skv, d, num_cores in [
733- (8, 4096, 8, 4096, TD, 32),733+ (8, 4096, 8, 4096, TD, 28), # 950 默认流预算 28 cube 核
734 ]:734 ]:
735 logging.info(735 logging.info(
736 "\nFA-Perf BSND DN causal (b=%s,sq=%s,n=%s,skv=%s,d=%s) cores=%s QK_PRELOAD=%s",736 "\nFA-Perf BSND DN causal (b=%s,sq=%s,n=%s,skv=%s,d=%s) cores=%s QK_PRELOAD=%s",
@@ -916,7 +916,7 @@ def test_fa_perf(torch_dtype, pl_dtype, rtol, atol):
916 device = f"npu:{device_id}"916 device = f"npu:{device_id}"
917 torch.manual_seed(42)917 torch.manual_seed(42)
918 attn_mask = make_causal_mask_dn_fixed_u8(device)918 attn_mask = make_causal_mask_dn_fixed_u8(device)
919- b, sq, n, skv, d, num_cores = 8, 4096, 8, 4096, TD, 32919+ b, sq, n, skv, d, num_cores = 8, 4096, 8, 4096, TD, 28 # 950 默认流预算 28 cube 核
920 logging.info(920 logging.info(
921 "\nFA-Perf BSND DN dynrank tilingkey dtype=%s (b=%s,sq=%s,n=%s,skv=%s,d=%s) cores=%s QK_PRELOAD=%s",921 "\nFA-Perf BSND DN dynrank tilingkey dtype=%s (b=%s,sq=%s,n=%s,skv=%s,d=%s) cores=%s QK_PRELOAD=%s",
922 torch_dtype,922 torch_dtype,
@@ -873,9 +873,9 @@ def test_fa_perf():
873 (64, 64, TD, 1),873 (64, 64, TD, 1),
874 (34, 62, TD, 1),874 (34, 62, TD, 1),
875 (162, 190, TD, 1),875 (162, 190, TD, 1),
876- (8192, 8192, TD, 32),876+ (8192, 8192, TD, 28), # 950 默认流预算 28 cube 核
877- (8128, 8128, TD, 32),877+ (8128, 8128, TD, 28),
878- (8111, 7777, TD, 32),878+ (8111, 7777, TD, 28),
879 ]:879 ]:
880 logging.info("\nFA-Perf DN tile-group (%s,%s,%s) cores=%s QK_PRELOAD=%s", sq, skv, d, num_cores, QK_PRELOAD)880 logging.info("\nFA-Perf DN tile-group (%s,%s,%s) cores=%s QK_PRELOAD=%s", sq, skv, d, num_cores, QK_PRELOAD)
881 q_t = torch.rand((sq, d), device=device, dtype=torch.float16)881 q_t = torch.rand((sq, d), device=device, dtype=torch.float16)
@@ -736,7 +736,7 @@ def test_fa_tilingkey_attn_mask():
736 736 
737 # Mirror the reference kernel's proven pipeline depth (sq_tiles=32); the QK_PRELOAD737 # Mirror the reference kernel's proven pipeline depth (sq_tiles=32); the QK_PRELOAD
738 # pipeline only drains correctly with enough q tiles.738 # pipeline only drains correctly with enough q tiles.
739- b, sq, n, skv, d, num_cores = 2, 4096, 2, 4096, TD, 32739+ b, sq, n, skv, d, num_cores = 2, 4096, 2, 4096, TD, 28 # 950 默认流预算 28 cube 核
740 q_t = torch.rand((b, sq, n, d), device=device, dtype=torch.float16)740 q_t = torch.rand((b, sq, n, d), device=device, dtype=torch.float16)
741 k_t = torch.rand((b, skv, n, d), device=device, dtype=torch.float16)741 k_t = torch.rand((b, skv, n, d), device=device, dtype=torch.float16)
742 v_t = torch.rand((b, skv, n, d), device=device, dtype=torch.float16)742 v_t = torch.rand((b, skv, n, d), device=device, dtype=torch.float16)
@@ -1106,7 +1106,7 @@ def test_quant_lightning_indexer_vf():
1106 logging.info("\n=== Test QuantLightningIndexer VF ===")1106 logging.info("\n=== Test QuantLightningIndexer VF ===")
1107 1107 
1108 test_cases = [1108 test_cases = [
1109- (1, 64, 1, 8192, 8192, HEAD_DIM, 2048, 32, 0, "fp8"),1109+ (1, 64, 1, 8192, 8192, HEAD_DIM, 2048, 28, 0, "fp8"), # 950 默认流预算 28 cube 核
1110 ]1110 ]
1111 1111 
1112 for b, n1, n2, sq, sk, d, topk, num_cores, sparse_mode, input_dtype in test_cases:1112 for b, n1, n2, sq, sk, d, topk, num_cores, sparse_mode, input_dtype in test_cases:
@@ -106,7 +106,7 @@ def run_perf_test(num_iters: int = 20, warmup: int = 3):
106 a = torch.randn(m_size, k_size, device=device, dtype=torch.float16)106 a = torch.randn(m_size, k_size, device=device, dtype=torch.float16)
107 b = torch.randn(k_size, n_size, device=device, dtype=torch.float16)107 b = torch.randn(k_size, n_size, device=device, dtype=torch.float16)
108 out = torch.zeros(m_size, n_size, device=device, dtype=torch.float16)108 out = torch.zeros(m_size, n_size, device=device, dtype=torch.float16)
109- core_num = 32109+ core_num = 28 # 950 默认流预算 28 cube 核;请求超出预算会直接报错
110 tiling = OpTiling(valid_size=128)110 tiling = OpTiling(valid_size=128)
111 matmul_example[None, core_num](a, b, out, tiling)111 matmul_example[None, core_num](a, b, out, tiling)
112 torch.npu.synchronize()112 torch.npu.synchronize()
@@ -165,7 +165,7 @@ def test_tiled_matmul_add_db_npu():
165 out = torch.zeros(M_SIZE, N_SIZE, device=device, dtype=torch.float32)165 out = torch.zeros(M_SIZE, N_SIZE, device=device, dtype=torch.float32)
166 workspace = torch.zeros(M_SIZE, N_SIZE, device=device, dtype=torch.float32)166 workspace = torch.zeros(M_SIZE, N_SIZE, device=device, dtype=torch.float32)
167 167 
168- tiled_matmul_add_db(a, b, x, out, workspace)168+ tiled_matmul_add_db[None, 1](a, b, x, out, workspace)
169 torch.npu.synchronize()169 torch.npu.synchronize()
170 170 
171 out_ref = torch.matmul(a.float(), b.float()) + x171 out_ref = torch.matmul(a.float(), b.float()) + x
@@ -200,7 +200,7 @@ def test_matmul_bias_fp16():
200 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)200 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)
201 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)201 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
202 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)202 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
203- kernel_bias_fp16[None, 32](a, b, bias, out)203+ kernel_bias_fp16(a, b, bias, out)
204 torch.npu.synchronize()204 torch.npu.synchronize()
205 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)205 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
206 206 
@@ -214,7 +214,7 @@ def test_matmul_bias_bf16():
214 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.bfloat16)214 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.bfloat16)
215 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.bfloat16)215 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.bfloat16)
216 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.bfloat16)216 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.bfloat16)
217- kernel_bias_bf16[None, 32](a, b, bias, out)217+ kernel_bias_bf16(a, b, bias, out)
218 torch.npu.synchronize()218 torch.npu.synchronize()
219 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).to(torch.bfloat16) + bias, rtol=5e-2, atol=5e-2)219 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).to(torch.bfloat16) + bias, rtol=5e-2, atol=5e-2)
220 220 
@@ -227,7 +227,7 @@ def test_matmul_bias_dynamic_m():
227 b = torch.randn(128, 128, device=DEVICE, dtype=torch.float16)227 b = torch.randn(128, 128, device=DEVICE, dtype=torch.float16)
228 bias = torch.randn(1, 128, device=DEVICE, dtype=torch.float16)228 bias = torch.randn(1, 128, device=DEVICE, dtype=torch.float16)
229 out = torch.zeros(256, 128, device=DEVICE, dtype=torch.float16)229 out = torch.zeros(256, 128, device=DEVICE, dtype=torch.float16)
230- kernel_bias_dynamic_m[None, 32](a, b, bias, out)230+ kernel_bias_dynamic_m(a, b, bias, out)
231 torch.npu.synchronize()231 torch.npu.synchronize()
232 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)232 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
233 233 
@@ -294,7 +294,7 @@ def _run_expect_keyword_error(kernel):
294 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)294 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)
295 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)295 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
296 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)296 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
297- kernel[None, 32](a, b, bias, out)297+ kernel(a, b, bias, out)
298 torch.npu.synchronize()298 torch.npu.synchronize()
299 299 
300 300 
@@ -363,11 +363,11 @@ def _run_single(kernel, has_bias):
363 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)363 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
364 if has_bias:364 if has_bias:
365 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)365 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
366- kernel[None, 32](a, b, bias, out)366+ kernel(a, b, bias, out)
367 torch.npu.synchronize()367 torch.npu.synchronize()
368 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)368 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
369 else:369 else:
370- kernel[None, 32](a, b, out)370+ kernel(a, b, out)
371 torch.npu.synchronize()371 torch.npu.synchronize()
372 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half(), rtol=1e-2, atol=1e-2)372 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half(), rtol=1e-2, atol=1e-2)
373 373 
@@ -475,7 +475,7 @@ def test_matmul_bias_n_2tiles():
475 b = torch.randn(TILE, 256, device=DEVICE, dtype=torch.float16)475 b = torch.randn(TILE, 256, device=DEVICE, dtype=torch.float16)
476 bias = torch.randn(1, 256, device=DEVICE, dtype=torch.float16)476 bias = torch.randn(1, 256, device=DEVICE, dtype=torch.float16)
477 out = torch.zeros(TILE, 256, device=DEVICE, dtype=torch.float16)477 out = torch.zeros(TILE, 256, device=DEVICE, dtype=torch.float16)
478- kernel_n_2tiles[None, 32](a, b, bias, out)478+ kernel_n_2tiles(a, b, bias, out)
479 torch.npu.synchronize()479 torch.npu.synchronize()
480 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)480 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
481 481 
@@ -488,7 +488,7 @@ def test_matmul_bias_mn_4tiles():
488 b = torch.randn(TILE, 256, device=DEVICE, dtype=torch.float16)488 b = torch.randn(TILE, 256, device=DEVICE, dtype=torch.float16)
489 bias = torch.randn(1, 256, device=DEVICE, dtype=torch.float16)489 bias = torch.randn(1, 256, device=DEVICE, dtype=torch.float16)
490 out = torch.zeros(256, 256, device=DEVICE, dtype=torch.float16)490 out = torch.zeros(256, 256, device=DEVICE, dtype=torch.float16)
491- kernel_mn_4tiles[None, 32](a, b, bias, out)491+ kernel_mn_4tiles(a, b, bias, out)
492 torch.npu.synchronize()492 torch.npu.synchronize()
493 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)493 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
494 494 
@@ -536,7 +536,7 @@ def test_matmul_bias_m_4tiles():
536 b = torch.randn(128, 128, device=DEVICE, dtype=torch.float16)536 b = torch.randn(128, 128, device=DEVICE, dtype=torch.float16)
537 bias = torch.randn(1, 128, device=DEVICE, dtype=torch.float16)537 bias = torch.randn(1, 128, device=DEVICE, dtype=torch.float16)
538 out = torch.zeros(512, 128, device=DEVICE, dtype=torch.float16)538 out = torch.zeros(512, 128, device=DEVICE, dtype=torch.float16)
539- kernel_m_4tiles[None, 32](a, b, bias, out)539+ kernel_m_4tiles(a, b, bias, out)
540 torch.npu.synchronize()540 torch.npu.synchronize()
541 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)541 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
542 542 
@@ -756,7 +756,7 @@ def test_matmul_bias_k_split():
756 b = torch.randn(K_SPLIT_3, TILE, device=DEVICE, dtype=torch.float16)756 b = torch.randn(K_SPLIT_3, TILE, device=DEVICE, dtype=torch.float16)
757 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)757 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
758 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)758 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
759- kernel_k_split_bias[None, 32](a, b, bias, out)759+ kernel_k_split_bias(a, b, bias, out)
760 torch.npu.synchronize()760 torch.npu.synchronize()
761 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)761 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
762 762 
@@ -769,7 +769,7 @@ def test_matmul_bias_k2_split():
769 b = torch.randn(K_SPLIT_2, TILE, device=DEVICE, dtype=torch.float16)769 b = torch.randn(K_SPLIT_2, TILE, device=DEVICE, dtype=torch.float16)
770 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)770 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
771 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)771 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
772- kernel_k2_split_bias[None, 32](a, b, bias, out)772+ kernel_k2_split_bias(a, b, bias, out)
773 torch.npu.synchronize()773 torch.npu.synchronize()
774 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)774 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
775 775 
@@ -782,7 +782,7 @@ def test_matmul_bias_k4_split():
782 b = torch.randn(K_SPLIT_4, TILE, device=DEVICE, dtype=torch.float16)782 b = torch.randn(K_SPLIT_4, TILE, device=DEVICE, dtype=torch.float16)
783 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)783 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
784 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)784 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
785- kernel_k4_split_bias[None, 32](a, b, bias, out)785+ kernel_k4_split_bias(a, b, bias, out)
786 torch.npu.synchronize()786 torch.npu.synchronize()
787 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)787 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
788 788 
@@ -795,7 +795,7 @@ def test_matmul_bias_mnk_split():
795 b = torch.randn(K_SPLIT_3, N_MNK, device=DEVICE, dtype=torch.float16)795 b = torch.randn(K_SPLIT_3, N_MNK, device=DEVICE, dtype=torch.float16)
796 bias = torch.randn(1, N_MNK, device=DEVICE, dtype=torch.float16)796 bias = torch.randn(1, N_MNK, device=DEVICE, dtype=torch.float16)
797 out = torch.zeros(M_MNK, N_MNK, device=DEVICE, dtype=torch.float16)797 out = torch.zeros(M_MNK, N_MNK, device=DEVICE, dtype=torch.float16)
798- kernel_mnk_split_bias[None, 32](a, b, bias, out)798+ kernel_mnk_split_bias(a, b, bias, out)
799 torch.npu.synchronize()799 torch.npu.synchronize()
800 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)800 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
801 801 
@@ -808,7 +808,7 @@ def test_matmul_bias_mnk_k2_split():
808 b = torch.randn(K_SPLIT_2, N_MNK, device=DEVICE, dtype=torch.float16)808 b = torch.randn(K_SPLIT_2, N_MNK, device=DEVICE, dtype=torch.float16)
809 bias = torch.randn(1, N_MNK, device=DEVICE, dtype=torch.float16)809 bias = torch.randn(1, N_MNK, device=DEVICE, dtype=torch.float16)
810 out = torch.zeros(M_MNK, N_MNK, device=DEVICE, dtype=torch.float16)810 out = torch.zeros(M_MNK, N_MNK, device=DEVICE, dtype=torch.float16)
811- kernel_mnk_k2_split_bias[None, 32](a, b, bias, out)811+ kernel_mnk_k2_split_bias(a, b, bias, out)
812 torch.npu.synchronize()812 torch.npu.synchronize()
813 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)813 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
814 814 
@@ -821,7 +821,7 @@ def test_matmul_bias_phase_final():
821 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)821 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)
822 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)822 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
823 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)823 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
824- kernel_bias_phase_final[None, 32](a, b, bias, out)824+ kernel_bias_phase_final(a, b, bias, out)
825 torch.npu.synchronize()825 torch.npu.synchronize()
826 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)826 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
827 827 
@@ -909,7 +909,7 @@ def test_regress_matmul_no_bias():
909 a = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)909 a = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)
910 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)910 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)
911 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)911 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
912- kernel_regress_no_bias[None, 32](a, b, out)912+ kernel_regress_no_bias(a, b, out)
913 torch.npu.synchronize()913 torch.npu.synchronize()
914 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half(), rtol=1e-2, atol=1e-2)914 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half(), rtol=1e-2, atol=1e-2)
915 915 
@@ -921,7 +921,7 @@ def test_regress_matmul_no_bias_phase():
921 a = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)921 a = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)
922 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)922 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)
923 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)923 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
924- kernel_regress_no_bias_phase[None, 32](a, b, out)924+ kernel_regress_no_bias_phase(a, b, out)
925 torch.npu.synchronize()925 torch.npu.synchronize()
926 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half(), rtol=1e-2, atol=1e-2)926 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half(), rtol=1e-2, atol=1e-2)
927 927 
@@ -933,7 +933,7 @@ def test_regress_matmul_acc():
933 a = torch.randn(TILE, K_SPLIT_2, device=DEVICE, dtype=torch.float16)933 a = torch.randn(TILE, K_SPLIT_2, device=DEVICE, dtype=torch.float16)
934 b = torch.randn(K_SPLIT_2, TILE, device=DEVICE, dtype=torch.float16)934 b = torch.randn(K_SPLIT_2, TILE, device=DEVICE, dtype=torch.float16)
935 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)935 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
936- kernel_regress_matmul_acc[None, 32](a, b, out)936+ kernel_regress_matmul_acc(a, b, out)
937 torch.npu.synchronize()937 torch.npu.synchronize()
938 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half(), rtol=1e-2, atol=1e-2)938 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half(), rtol=1e-2, atol=1e-2)
939 939 
@@ -1048,7 +1048,7 @@ def test_matmul_bias_m_tail():
1048 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)1048 b = torch.randn(TILE, TILE, device=DEVICE, dtype=torch.float16)
1049 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)1049 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
1050 out = torch.zeros(K_TAIL, TILE, device=DEVICE, dtype=torch.float16)1050 out = torch.zeros(K_TAIL, TILE, device=DEVICE, dtype=torch.float16)
1051- kernel_bias_m_tail[None, 32](a, b, bias, out)1051+ kernel_bias_m_tail(a, b, bias, out)
1052 torch.npu.synchronize()1052 torch.npu.synchronize()
1053 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)1053 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
1054 1054 
@@ -1096,7 +1096,7 @@ def test_matmul_bias_n_tail():
1096 b = torch.randn(TILE, K_TAIL, device=DEVICE, dtype=torch.float16)1096 b = torch.randn(TILE, K_TAIL, device=DEVICE, dtype=torch.float16)
1097 bias = torch.randn(1, K_TAIL, device=DEVICE, dtype=torch.float16)1097 bias = torch.randn(1, K_TAIL, device=DEVICE, dtype=torch.float16)
1098 out = torch.zeros(TILE, K_TAIL, device=DEVICE, dtype=torch.float16)1098 out = torch.zeros(TILE, K_TAIL, device=DEVICE, dtype=torch.float16)
1099- kernel_bias_n_tail[None, 32](a, b, bias, out)1099+ kernel_bias_n_tail(a, b, bias, out)
1100 torch.npu.synchronize()1100 torch.npu.synchronize()
1101 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)1101 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
1102 1102 
@@ -1153,7 +1153,7 @@ def test_matmul_bias_k_tail():
1153 b = torch.randn(K_TAIL, TILE, device=DEVICE, dtype=torch.float16)1153 b = torch.randn(K_TAIL, TILE, device=DEVICE, dtype=torch.float16)
1154 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)1154 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
1155 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)1155 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
1156- kernel_bias_k_tail[None, 32](a, b, bias, out)1156+ kernel_bias_k_tail(a, b, bias, out)
1157 torch.npu.synchronize()1157 torch.npu.synchronize()
1158 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)1158 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
1159 1159 
@@ -1220,6 +1220,6 @@ def test_matmul_bias_mnk_tail():
1220 b = torch.randn(K_TAIL, K_TAIL, device=DEVICE, dtype=torch.float16)1220 b = torch.randn(K_TAIL, K_TAIL, device=DEVICE, dtype=torch.float16)
1221 bias = torch.randn(1, K_TAIL, device=DEVICE, dtype=torch.float16)1221 bias = torch.randn(1, K_TAIL, device=DEVICE, dtype=torch.float16)
1222 out = torch.zeros(K_TAIL, K_TAIL, device=DEVICE, dtype=torch.float16)1222 out = torch.zeros(K_TAIL, K_TAIL, device=DEVICE, dtype=torch.float16)
1223- kernel_bias_mnk_tail[None, 32](a, b, bias, out)1223+ kernel_bias_mnk_tail(a, b, bias, out)
1224 torch.npu.synchronize()1224 torch.npu.synchronize()
1225 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)1225 torch.testing.assert_close(out, torch.matmul(a.float(), b.float()).half() + bias, rtol=1e-2, atol=1e-2)
@@ -30,7 +30,7 @@ DEVICE = f"npu:{DEVICE_ID}"
30 30 
31def _run_expect_error(kernel_func, *args):31def _run_expect_error(kernel_func, *args):
32 with pytest.raises((RuntimeError, Exception)):32 with pytest.raises((RuntimeError, Exception)):
33- kernel_func[None, 32](*args)33+ kernel_func(*args)
34 torch.npu.synchronize()34 torch.npu.synchronize()
35 35 
36 36 
@@ -685,7 +685,7 @@ def test_err_matmul_bias_middle_block():
685 b = torch.randn(K_SPLIT, TILE, device=DEVICE, dtype=torch.float16)685 b = torch.randn(K_SPLIT, TILE, device=DEVICE, dtype=torch.float16)
686 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)686 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
687 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)687 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
688- kernel_bias_middle_block[None, 32](a, b, bias, out)688+ kernel_bias_middle_block(a, b, bias, out)
689 torch.npu.synchronize()689 torch.npu.synchronize()
690 golden = torch.matmul(a.float(), b.float()).half() + bias690 golden = torch.matmul(a.float(), b.float()).half() + bias
691 max_diff = (out.float() - golden.float()).abs().max().item()691 max_diff = (out.float() - golden.float()).abs().max().item()
@@ -700,7 +700,7 @@ def test_err_matmul_bias_last_block():
700 b = torch.randn(K_SPLIT, TILE, device=DEVICE, dtype=torch.float16)700 b = torch.randn(K_SPLIT, TILE, device=DEVICE, dtype=torch.float16)
701 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)701 bias = torch.randn(1, TILE, device=DEVICE, dtype=torch.float16)
702 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)702 out = torch.zeros(TILE, TILE, device=DEVICE, dtype=torch.float16)
703- kernel_bias_last_block[None, 32](a, b, bias, out)703+ kernel_bias_last_block(a, b, bias, out)
704 torch.npu.synchronize()704 torch.npu.synchronize()
705 golden = torch.matmul(a.float(), b.float()).half() + bias705 golden = torch.matmul(a.float(), b.float()).half() + bias
706 max_diff = (out.float() - golden.float()).abs().max().item()706 max_diff = (out.float() - golden.float()).abs().max().item()
@@ -1797,7 +1797,8 @@ def test_t03_atomic(in_dtype, mkn, _device):
1797 1797 
1798 FP32 output only: atomic accumulation needs the GM dtype to match the accumulator.1798 FP32 output only: atomic accumulation needs the GM dtype to match the accumulator.
1799 """1799 """
1800- _run(make_matmul_atomic, in_dtype, "fp32", _device, mkn=mkn)1800+ # K 的原子累加按单核语义验证:直调现为满核,显式请求 1 块。
1801+ _run(make_matmul_atomic, in_dtype, "fp32", _device, mkn=mkn, block_dim=1)
1801 1802 
1802 1803 
1803@pytest.mark.soc("950")1804@pytest.mark.soc("950")
@@ -66,7 +66,7 @@ TILE_N = 256
66KL0 = 6466KL0 = 64
67KL1 = 12867KL1 = 128
68STEP_KA = KL1 // KL0 # 268STEP_KA = KL1 // KL0 # 2
69-NUM_CORES = 3269+NUM_CORES = 28 # 950 默认流预算 28 cube 核;请求超出预算会直接报错
70 70 
71M_TILES = M_SIZE // TILE_M # 1671M_TILES = M_SIZE // TILE_M # 16
72N_TILES = N_SIZE // TILE_N # 1672N_TILES = N_SIZE // TILE_N # 16
@@ -245,7 +245,7 @@ def _run_case(m, n, k):
245 out = torch.zeros(m, n, device=device, dtype=torch.float16)245 out = torch.zeros(m, n, device=device, dtype=torch.float16)
246 246 
247 total_cnt = m_tiles * ((n + TILE_N - 1) // TILE_N)247 total_cnt = m_tiles * ((n + TILE_N - 1) // TILE_N)
248- num_cores = min(32, total_cnt)248+ num_cores = min(28, total_cnt) # 950 默认流预算 28 cube 核
249 matmul_perf_asw_4k_dn_move_offset_dynamic_kernel[None, num_cores](a, b, out)249 matmul_perf_asw_4k_dn_move_offset_dynamic_kernel[None, num_cores](a, b, out)
250 torch.npu.synchronize()250 torch.npu.synchronize()
251 251 
@@ -35,7 +35,7 @@ TILE_N = 256
35KL0 = 6435KL0 = 64
36KL1 = 12836KL1 = 128
37STEP_KA = KL1 // KL0 # 237STEP_KA = KL1 // KL0 # 2
38-NUM_CORES = 3238+NUM_CORES = 28 # 950 默认流预算 28 cube 核;请求超出预算会直接报错
39 39 
40M_TILES = M_SIZE // TILE_M # 3240M_TILES = M_SIZE // TILE_M # 32
41N_TILES = N_SIZE // TILE_N # 3241N_TILES = N_SIZE // TILE_N # 32
@@ -222,7 +222,7 @@ def _run_case(m, n, k):
222 out = torch.zeros(m, n, device=device, dtype=torch.float16)222 out = torch.zeros(m, n, device=device, dtype=torch.float16)
223 223 
224 total_cnt = m_tiles * ((n + TILE_N - 1) // TILE_N)224 total_cnt = m_tiles * ((n + TILE_N - 1) // TILE_N)
225- num_cores = min(32, total_cnt)225+ num_cores = min(28, total_cnt) # 950 默认流预算 28 cube 核
226 matmul_perf_asw_8k_k128_dn_move_offset_dynamic_kernel[None, num_cores](a, b, out)226 matmul_perf_asw_8k_k128_dn_move_offset_dynamic_kernel[None, num_cores](a, b, out)
227 torch.npu.synchronize()227 torch.npu.synchronize()
228 228 
@@ -181,7 +181,7 @@ def test_matmul_add_matmul_add():
181 out = torch.zeros(shape, device=device, dtype=dtype)181 out = torch.zeros(shape, device=device, dtype=dtype)
182 workspace = torch.zeros(shape, device=device, dtype=dtype) # bmm1182 workspace = torch.zeros(shape, device=device, dtype=dtype) # bmm1
183 183 
184- matmul_add_matmul_add_cce(q, k, v, x1, x2, out, workspace)184+ matmul_add_matmul_add_cce[None, 1](q, k, v, x1, x2, out, workspace)
185 torch.npu.synchronize()185 torch.npu.synchronize()
186 186 
187 c1 = torch.matmul(q, k)187 c1 = torch.matmul(q, k)
@@ -38,7 +38,7 @@ def _require_a5():
38def _run_kernel(kernel, states):38def _run_kernel(kernel, states):
39 _require_a5()39 _require_a5()
40 device_states = [state.to(ST_DEVICE) for state in states]40 device_states = [state.to(ST_DEVICE) for state in states]
41- kernel(*device_states)41+ kernel[None, 1](*device_states)
42 torch.npu.synchronize()42 torch.npu.synchronize()
43 return [state.cpu() for state in device_states]43 return [state.cpu() for state in device_states]
44 44 
@@ -206,7 +206,7 @@ def simt_atomic_add_multicore(state: pl.Tensor[[1, 1], pl.DT_INT64]):
206 206 
207def _assert_histogram(kernel):207def _assert_histogram(kernel):
208 histogram = torch.zeros((1, ATOMIC_BUCKETS), dtype=torch.int32, device=ST_DEVICE)208 histogram = torch.zeros((1, ATOMIC_BUCKETS), dtype=torch.int32, device=ST_DEVICE)
209- kernel(histogram)209+ kernel[None, 1](histogram)
210 torch.npu.synchronize()210 torch.npu.synchronize()
211 expected = torch.full((1, ATOMIC_BUCKETS), SEMANTIC_THREADS // ATOMIC_BUCKETS, dtype=torch.int32)211 expected = torch.full((1, ATOMIC_BUCKETS), SEMANTIC_THREADS // ATOMIC_BUCKETS, dtype=torch.int32)
212 torch.testing.assert_close(histogram.cpu(), expected, rtol=0, atol=0)212 torch.testing.assert_close(histogram.cpu(), expected, rtol=0, atol=0)
@@ -251,7 +251,7 @@ def test_atomic_add_returns_old_value_and_preserves_other_elements():
251 expected_old[0, 0] = 10251 expected_old[0, 0] = 10
252 state_device = state.to(ST_DEVICE)252 state_device = state.to(ST_DEVICE)
253 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)253 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)
254- simt_atomic_add_return_value_gm(state_device, old_values)254+ simt_atomic_add_return_value_gm[None, 1](state_device, old_values)
255 torch.npu.synchronize()255 torch.npu.synchronize()
256 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)256 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
257 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)257 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -152,7 +152,7 @@ def test_atomic_and_returns_old_value_and_preserves_other_elements():
152 expected_old[0, 0] = 0xFF152 expected_old[0, 0] = 0xFF
153 state_device = state.to(ST_DEVICE)153 state_device = state.to(ST_DEVICE)
154 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)154 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)
155- simt_atomic_and_return_value_gm(state_device, old_values)155+ simt_atomic_and_return_value_gm[None, 1](state_device, old_values)
156 torch.npu.synchronize()156 torch.npu.synchronize()
157 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)157 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
158 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)158 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -185,7 +185,7 @@ def test_atomic_cas_returns_old_value_and_preserves_other_elements():
185 expected_old[0, 0] = 10185 expected_old[0, 0] = 10
186 state_device = state.to(ST_DEVICE)186 state_device = state.to(ST_DEVICE)
187 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)187 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)
188- simt_atomic_cas_return_value_gm(state_device, old_values)188+ simt_atomic_cas_return_value_gm[None, 1](state_device, old_values)
189 torch.npu.synchronize()189 torch.npu.synchronize()
190 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)190 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
191 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)191 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -196,7 +196,7 @@ def test_atomic_cas_contention_has_exactly_one_winner():
196 _require_a5()196 _require_a5()
197 state = torch.zeros((1, 1), dtype=torch.int32, device=ST_DEVICE)197 state = torch.zeros((1, 1), dtype=torch.int32, device=ST_DEVICE)
198 old_values = torch.empty((1, 32), dtype=torch.int32, device=ST_DEVICE)198 old_values = torch.empty((1, 32), dtype=torch.int32, device=ST_DEVICE)
199- simt_atomic_cas_winner_gm(state, old_values)199+ simt_atomic_cas_winner_gm[None, 1](state, old_values)
200 torch.npu.synchronize()200 torch.npu.synchronize()
201 final_value = state.cpu()[0, 0].item()201 final_value = state.cpu()[0, 0].item()
202 old_values = old_values.cpu().reshape(-1)202 old_values = old_values.cpu().reshape(-1)
@@ -35,7 +35,7 @@ def _require_a5():
35def _run_kernel(kernel, states):35def _run_kernel(kernel, states):
36 _require_a5()36 _require_a5()
37 device_states = [state.to(ST_DEVICE) for state in states]37 device_states = [state.to(ST_DEVICE) for state in states]
38- kernel(*device_states)38+ kernel[None, 1](*device_states)
39 torch.npu.synchronize()39 torch.npu.synchronize()
40 return [state.cpu() for state in device_states]40 return [state.cpu() for state in device_states]
41 41 
@@ -128,7 +128,7 @@ def test_atomic_dec_returns_old_value_and_preserves_other_elements():
128 expected_old[0, 0] = 0128 expected_old[0, 0] = 0
129 state_device = state.to(ST_DEVICE)129 state_device = state.to(ST_DEVICE)
130 old_values = torch.full((1, ELEMENTS), 99, dtype=torch.uint32).to(ST_DEVICE)130 old_values = torch.full((1, ELEMENTS), 99, dtype=torch.uint32).to(ST_DEVICE)
131- simt_atomic_dec_return_value_gm(state_device, old_values)131+ simt_atomic_dec_return_value_gm[None, 1](state_device, old_values)
132 torch.npu.synchronize()132 torch.npu.synchronize()
133 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)133 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
134 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)134 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -185,7 +185,7 @@ def test_atomic_exch_returns_old_value_and_preserves_other_elements():
185 expected_old[0, 0] = 10185 expected_old[0, 0] = 10
186 state_device = state.to(ST_DEVICE)186 state_device = state.to(ST_DEVICE)
187 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)187 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)
188- simt_atomic_exch_return_value_gm(state_device, old_values)188+ simt_atomic_exch_return_value_gm[None, 1](state_device, old_values)
189 torch.npu.synchronize()189 torch.npu.synchronize()
190 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)190 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
191 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)191 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -196,7 +196,7 @@ def test_atomic_exch_contention_forms_one_exchange_chain():
196 _require_a5()196 _require_a5()
197 state = torch.tensor([[-1]], dtype=torch.int32, device=ST_DEVICE)197 state = torch.tensor([[-1]], dtype=torch.int32, device=ST_DEVICE)
198 old_values = torch.empty((1, 32), dtype=torch.int32, device=ST_DEVICE)198 old_values = torch.empty((1, 32), dtype=torch.int32, device=ST_DEVICE)
199- simt_atomic_exch_contention_gm(state, old_values)199+ simt_atomic_exch_contention_gm[None, 1](state, old_values)
200 torch.npu.synchronize()200 torch.npu.synchronize()
201 chain = torch.cat((old_values.cpu().reshape(-1), state.cpu().reshape(-1)))201 chain = torch.cat((old_values.cpu().reshape(-1), state.cpu().reshape(-1)))
202 expected = torch.tensor([-1] + list(range(32)), dtype=torch.int32)202 expected = torch.tensor([-1] + list(range(32)), dtype=torch.int32)
@@ -35,7 +35,7 @@ def _require_a5():
35def _run_kernel(kernel, states):35def _run_kernel(kernel, states):
36 _require_a5()36 _require_a5()
37 device_states = [state.to(ST_DEVICE) for state in states]37 device_states = [state.to(ST_DEVICE) for state in states]
38- kernel(*device_states)38+ kernel[None, 1](*device_states)
39 torch.npu.synchronize()39 torch.npu.synchronize()
40 return [state.cpu() for state in device_states]40 return [state.cpu() for state in device_states]
41 41 
@@ -128,7 +128,7 @@ def test_atomic_inc_returns_old_value_and_preserves_other_elements():
128 expected_old[0, 0] = 5128 expected_old[0, 0] = 5
129 state_device = state.to(ST_DEVICE)129 state_device = state.to(ST_DEVICE)
130 old_values = torch.full((1, ELEMENTS), 99, dtype=torch.uint32).to(ST_DEVICE)130 old_values = torch.full((1, ELEMENTS), 99, dtype=torch.uint32).to(ST_DEVICE)
131- simt_atomic_inc_return_value_gm(state_device, old_values)131+ simt_atomic_inc_return_value_gm[None, 1](state_device, old_values)
132 torch.npu.synchronize()132 torch.npu.synchronize()
133 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)133 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
134 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)134 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -197,7 +197,7 @@ def test_atomic_max_returns_old_value_and_preserves_other_elements():
197 expected_old[0, 0] = 10197 expected_old[0, 0] = 10
198 state_device = state.to(ST_DEVICE)198 state_device = state.to(ST_DEVICE)
199 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)199 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)
200- simt_atomic_max_return_value_gm(state_device, old_values)200+ simt_atomic_max_return_value_gm[None, 1](state_device, old_values)
201 torch.npu.synchronize()201 torch.npu.synchronize()
202 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)202 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
203 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)203 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -197,7 +197,7 @@ def test_atomic_min_returns_old_value_and_preserves_other_elements():
197 expected_old[0, 0] = 10197 expected_old[0, 0] = 10
198 state_device = state.to(ST_DEVICE)198 state_device = state.to(ST_DEVICE)
199 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)199 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)
200- simt_atomic_min_return_value_gm(state_device, old_values)200+ simt_atomic_min_return_value_gm[None, 1](state_device, old_values)
201 torch.npu.synchronize()201 torch.npu.synchronize()
202 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)202 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
203 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)203 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -152,7 +152,7 @@ def test_atomic_or_returns_old_value_and_preserves_other_elements():
152 expected_old[0, 0] = 0152 expected_old[0, 0] = 0
153 state_device = state.to(ST_DEVICE)153 state_device = state.to(ST_DEVICE)
154 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)154 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)
155- simt_atomic_or_return_value_gm(state_device, old_values)155+ simt_atomic_or_return_value_gm[None, 1](state_device, old_values)
156 torch.npu.synchronize()156 torch.npu.synchronize()
157 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)157 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
158 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)158 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -35,7 +35,7 @@ def _require_a5():
35def _run_kernel(kernel, states):35def _run_kernel(kernel, states):
36 _require_a5()36 _require_a5()
37 device_states = [state.to(ST_DEVICE) for state in states]37 device_states = [state.to(ST_DEVICE) for state in states]
38- kernel(*device_states)38+ kernel[None, 1](*device_states)
39 torch.npu.synchronize()39 torch.npu.synchronize()
40 return [state.cpu() for state in device_states]40 return [state.cpu() for state in device_states]
41 41 
@@ -167,7 +167,7 @@ def test_atomic_sub_returns_old_value_and_preserves_other_elements():
167 expected_old[0, 0] = 10167 expected_old[0, 0] = 10
168 state_device = state.to(ST_DEVICE)168 state_device = state.to(ST_DEVICE)
169 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)169 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)
170- simt_atomic_sub_return_value_gm(state_device, old_values)170+ simt_atomic_sub_return_value_gm[None, 1](state_device, old_values)
171 torch.npu.synchronize()171 torch.npu.synchronize()
172 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)172 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
173 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)173 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -35,7 +35,7 @@ def _require_a5():
35def _run_kernel(kernel, states):35def _run_kernel(kernel, states):
36 _require_a5()36 _require_a5()
37 device_states = [state.to(ST_DEVICE) for state in states]37 device_states = [state.to(ST_DEVICE) for state in states]
38- kernel(*device_states)38+ kernel[None, 1](*device_states)
39 torch.npu.synchronize()39 torch.npu.synchronize()
40 return [state.cpu() for state in device_states]40 return [state.cpu() for state in device_states]
41 41 
@@ -155,7 +155,7 @@ def test_atomic_xor_returns_old_value_and_preserves_other_elements():
155 expected_old[0, 0] = 0xAA155 expected_old[0, 0] = 0xAA
156 state_device = state.to(ST_DEVICE)156 state_device = state.to(ST_DEVICE)
157 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)157 old_values = torch.full((1, ELEMENTS), 123, dtype=torch.int32).to(ST_DEVICE)
158- simt_atomic_xor_return_value_gm(state_device, old_values)158+ simt_atomic_xor_return_value_gm[None, 1](state_device, old_values)
159 torch.npu.synchronize()159 torch.npu.synchronize()
160 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)160 torch.testing.assert_close(state_device.cpu(), expected_state, rtol=0, atol=0)
161 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)161 torch.testing.assert_close(old_values.cpu(), expected_old, rtol=0, atol=0)
@@ -78,7 +78,7 @@ def test_thread_context():
78 _require_a5()78 _require_a5()
79 79 
80 out = torch.empty((2, THREADS), dtype=torch.int32).to(torch.uint32).to(ST_DEVICE)80 out = torch.empty((2, THREADS), dtype=torch.int32).to(torch.uint32).to(ST_DEVICE)
81- simt_thread_context(out)81+ simt_thread_context[None, 1](out)
82 torch.npu.synchronize()82 torch.npu.synchronize()
83 83 
84 tid = torch.arange(THREADS, dtype=torch.int64)84 tid = torch.arange(THREADS, dtype=torch.int64)
@@ -109,7 +109,7 @@ def test_make_tuple_chain_tile_group_next():
109 _require_a5(ST_DEVICE)109 _require_a5(ST_DEVICE)
110 a = torch.randn(64, 128, device=ST_DEVICE, dtype=torch.float16)110 a = torch.randn(64, 128, device=ST_DEVICE, dtype=torch.float16)
111 expected = a.float().exp().half()111 expected = a.float().exp().half()
112- make_tuple_chain_tile_group_next_kernel(a)112+ make_tuple_chain_tile_group_next_kernel[None, 1](a)
113 torch.npu.synchronize()113 torch.npu.synchronize()
114 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"114 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"
115 115 
@@ -138,7 +138,7 @@ def test_make_tuple_chain_tile_group_current():
138 _require_a5(ST_DEVICE)138 _require_a5(ST_DEVICE)
139 a = torch.randn(64, 128, device=ST_DEVICE, dtype=torch.float16)139 a = torch.randn(64, 128, device=ST_DEVICE, dtype=torch.float16)
140 expected = a.float().exp().half()140 expected = a.float().exp().half()
141- make_tuple_chain_tile_group_current_kernel(a)141+ make_tuple_chain_tile_group_current_kernel[None, 1](a)
142 torch.npu.synchronize()142 torch.npu.synchronize()
143 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"143 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"
144 144 
@@ -241,7 +241,7 @@ def test_make_tuple_chain_tile_group_previous():
241 _require_a5(ST_DEVICE)241 _require_a5(ST_DEVICE)
242 a = torch.randn(64, 128, device=ST_DEVICE, dtype=torch.float16)242 a = torch.randn(64, 128, device=ST_DEVICE, dtype=torch.float16)
243 expected = a.float().exp().half()243 expected = a.float().exp().half()
244- make_tuple_chain_tile_group_previous_kernel(a)244+ make_tuple_chain_tile_group_previous_kernel[None, 1](a)
245 torch.npu.synchronize()245 torch.npu.synchronize()
246 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"246 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"
247 247 
@@ -270,7 +270,7 @@ def test_make_tuple_chain_double_buffer_loop():
270 _require_a5(ST_DEVICE)270 _require_a5(ST_DEVICE)
271 a = torch.randn(128, 128, device=ST_DEVICE, dtype=torch.float16)271 a = torch.randn(128, 128, device=ST_DEVICE, dtype=torch.float16)
272 expected = a.float().exp().half()272 expected = a.float().exp().half()
273- make_tuple_chain_double_buffer_loop_kernel(a)273+ make_tuple_chain_double_buffer_loop_kernel[None, 1](a)
274 torch.npu.synchronize()274 torch.npu.synchronize()
275 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"275 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"
276 276 
@@ -299,7 +299,7 @@ def test_make_tuple_chain_ring_buffer_loop():
299 _require_a5(ST_DEVICE)299 _require_a5(ST_DEVICE)
300 a = torch.randn(256, 128, device=ST_DEVICE, dtype=torch.float16)300 a = torch.randn(256, 128, device=ST_DEVICE, dtype=torch.float16)
301 expected = a.float().exp().half()301 expected = a.float().exp().half()
302- make_tuple_chain_ring_buffer_loop_kernel(a)302+ make_tuple_chain_ring_buffer_loop_kernel[None, 1](a)
303 torch.npu.synchronize()303 torch.npu.synchronize()
304 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"304 assert torch.allclose(a, expected, rtol=1e-3, atol=1e-3), f"max diff: {(a - expected).abs().max().item()}"
305 305 
@@ -647,11 +647,12 @@ def test_large_request_saturates_before_native_abi_conversion(monkeypatch, reque
647 (2, 1),647 (2, 1),
648 (3, 507000),648 (3, 507000),
649 (4, 0xFFFFFFFF),649 (4, 0xFFFFFFFF),
650+ (5, 4),
650 (9, 1),651 (9, 1),
651 ],652 ],
652)653)
653def test_launch_propagates_native_errors(monkeypatch, kind, detail):654def test_launch_propagates_native_errors(monkeypatch, kind, detail):
654- """All native errors retain their full code without querying or interpreting the compiler's core topology."""655+ """All native errors raise without querying or interpreting the compiler's core topology."""
655 lib = _FakeLib()656 lib = _FakeLib()
656 lib.call_kernel.result = -((kind << 32) | detail)657 lib.call_kernel.result = -((kind << 32) | detail)
657 monkeypatch.setattr(_jit, "ctypes", _CtypesProxy(lib))658 monkeypatch.setattr(_jit, "ctypes", _CtypesProxy(lib))
@@ -665,6 +666,20 @@ def test_launch_propagates_native_errors(monkeypatch, kind, detail):
665 config_lookup.assert_not_called()666 config_lookup.assert_not_called()
666 667 
667 668 
669+def test_direct_call_launches_with_auto_sentinel(monkeypatch):
670+ """A direct call must hand the native launcher 0, which resolves to the stream's full budget."""
671+ lib = _FakeLib()
672+ monkeypatch.setattr(_jit, "ctypes", _CtypesProxy(lib))
673+ compiled = CompiledKernel(lib_path="<fake>", param_specs=[])
674+ monkeypatch.setattr(_jit, "_launch", MagicMock())
675+ kernel = _jit._TileJitKernel(lambda: None, arch="a5")
676+ monkeypatch.setattr(kernel, "_validate_launch_arch", lambda: None)
677+ monkeypatch.setattr(kernel, "_ensure_compiled", lambda *_args, **_kwargs: compiled)
678+ kernel()
679+ _jit._launch.assert_called_once()
680+ assert _jit._launch.call_args.args[2] == 0
681+ 
682+ 
668def test_capture_log_uses_native_block_count(monkeypatch, caplog):683def test_capture_log_uses_native_block_count(monkeypatch, caplog):
669 """Logging the host request would misreport captured nodes after the native launcher clamps them."""684 """Logging the host request would misreport captured nodes after the native launcher clamps them."""
670 lib = _FakeLib()685 lib = _FakeLib()
@@ -12,7 +12,8 @@
12 12 
13Only the CCE launch expression becomes a recorder. The emitted host control flow,13Only the CCE launch expression becomes a recorder. The emitted host control flow,
14resource helper, compiler topology and int64_t return ABI are compiled as written,14resource helper, compiler topology and int64_t return ABI are compiled as written,
15-so these tests detect launches after query failure or an incomplete mixed group.15+so these tests detect launches after query failure, an incomplete mixed group,
16+an over-budget request, and the auto sentinel's full-budget resolution.
16"""17"""
17 18 
18import ctypes19import ctypes
@@ -135,19 +136,29 @@ static void RecordLaunch(uint32_t dim, void*, int64_t* = nullptr)
135@pytest.mark.parametrize(136@pytest.mark.parametrize(
136 "mode,cube,vector,requested,expected,queries",137 "mode,cube,vector,requested,expected,queries",
137 [138 [
138- ("cube", 5, 0, 20, 5, (1, 0)),139+ ("cube", 5, 0, 1, 1, (1, 0)),
139- ("vector", 0, 7, 20, 7, (0, 1)),140+ ("cube", 5, 0, 5, 5, (1, 0)),
140- ("mixed", 4, 20, 20, 4, (1, 1)),141+ ("cube", 5, 0, 0, 5, (1, 0)),
141- ("mixed", 20, 9, 20, 4, (1, 1)),142+ ("vector", 0, 7, 7, 7, (0, 1)),
142- ("mixed", 20, 2, 20, 1, (1, 1)),143+ ("vector", 0, 72, 72, 72, (0, 1)),
144+ ("vector", 0, 7, 0, 7, (0, 1)),
143 ("mixed", 20, 40, 3, 3, (1, 1)),145 ("mixed", 20, 40, 3, 3, (1, 1)),
144- ("mixed_1_1", 8, 5, 12, 5, (1, 1)),146+ ("mixed", 8, 8, 4, 4, (1, 1)),
145- ("sync", 8, 5, 12, 2, (1, 1)),147+ ("mixed", 4, 20, 0, 4, (1, 1)),
146- ("vector", 0, 72, 0xFFFFFFFF, 72, (0, 1)),148+ ("mixed", 20, 9, 0, 4, (1, 1)),
149+ ("mixed", 20, 2, 0, 1, (1, 1)),
150+ ("mixed_1_1", 8, 5, 5, 5, (1, 1)),
151+ ("mixed_1_1", 8, 5, 0, 5, (1, 1)),
152+ ("sync", 8, 5, 2, 2, (1, 1)),
153+ ("sync", 8, 5, 0, 2, (1, 1)),
147 ],154 ],
148)155)
149def test_native_launch_counts(native_launchers, mode, cube, vector, requested, expected, queries):156def test_native_launch_counts(native_launchers, mode, cube, vector, requested, expected, queries):
150- """Check the recorded launch as well as the return value; an unclamped launch must never pass."""157+ """Check the recorded launch as well as the return value; an over-budget launch must never pass.
158+ 
159+ A requested 0 is the auto sentinel: the launch takes the stream's full budget,
160+ bounded by the tighter engine for mixed blocks.
161+ """
151 lib = native_launchers162 lib = native_launchers
152 lib.reset(cube, vector, 0, 0)163 lib.reset(cube, vector, 0, 0)
153 assert getattr(lib, f"call_kernel_{mode}")(requested, 0x1234) == expected164 assert getattr(lib, f"call_kernel_{mode}")(requested, 0x1234) == expected
@@ -159,6 +170,28 @@ def test_native_launch_counts(native_launchers, mode, cube, vector, requested, e
159 assert lib.sync_setup_count() == (1 if mode == "sync" else 0)170 assert lib.sync_setup_count() == (1 if mode == "sync" else 0)
160 171 
161 172 
173+@pytest.mark.parametrize(
174+ "mode,cube,vector,requested,expected",
175+ [
176+ ("cube", 5, 0, 20, -0x500000005),
177+ ("vector", 0, 7, 20, -0x500000007),
178+ ("vector", 0, 72, 0xFFFFFFFF, -0x500000048),
179+ ("mixed", 4, 20, 20, -0x500000004),
180+ ("mixed", 20, 9, 20, -0x500000004),
181+ ("mixed", 20, 2, 12, -0x500000001),
182+ ("mixed_1_1", 8, 5, 12, -0x500000005),
183+ ("sync", 8, 5, 12, -0x500000002),
184+ ],
185+)
186+def test_native_requests_above_budget_reject_launch(native_launchers, mode, cube, vector, requested, expected):
187+ """An explicit request the stream cannot host must fail before any device launch or sync setup."""
188+ lib = native_launchers
189+ lib.reset(cube, vector, 0, 0)
190+ assert getattr(lib, f"call_kernel_{mode}")(requested, 0x1234) == expected
191+ assert lib.launch_count() == 0
192+ assert lib.sync_setup_count() == 0
193+ 
194+ 
162@pytest.mark.parametrize(195@pytest.mark.parametrize(
163 "cube,vector,cube_error,vector_error,expected",196 "cube,vector,cube_error,vector_error,expected",
164 [197 [
@@ -191,7 +224,7 @@ def test_unused_engine_query_errors_do_not_block_launch(
191 """Querying both engines would incorrectly fail a valid single-engine kernel on the unused engine."""224 """Querying both engines would incorrectly fail a valid single-engine kernel on the unused engine."""
192 lib = native_launchers225 lib = native_launchers
193 lib.reset(cube, vector, cube_error, vector_error)226 lib.reset(cube, vector, cube_error, vector_error)
194- assert getattr(lib, f"call_kernel_{mode}")(12, 0x1234) == 4227+ assert getattr(lib, f"call_kernel_{mode}")(4, 0x1234) == 4
195 assert lib.launch_count() == 1228 assert lib.launch_count() == 1
196 229 
197 230 
@@ -200,7 +233,7 @@ def test_native_query_observes_budget_and_stream_changes(native_launchers):
200 lib = native_launchers233 lib = native_launchers
201 for vector, stream, expected in [(6, 0x1234, 3), (2, 0x5678, 1), (1, 0x5678, None), (8, 0x1234, 4)]:234 for vector, stream, expected in [(6, 0x1234, 3), (2, 0x5678, 1), (1, 0x5678, None), (8, 0x1234, 4)]:
202 lib.reset(8, vector, 0, 0)235 lib.reset(8, vector, 0, 0)
203- result = lib.call_kernel_mixed(12, stream)236+ result = lib.call_kernel_mixed(0, stream)
204 if expected is None:237 if expected is None:
205 assert result == -0x200000001238 assert result == -0x200000001
206 assert lib.launch_count() == 0239 assert lib.launch_count() == 0
@@ -209,3 +242,14 @@ def test_native_query_observes_budget_and_stream_changes(native_launchers):
209 assert lib.launch_count() == 1242 assert lib.launch_count() == 1
210 assert lib.query_count(0) == lib.query_count(1) == 1243 assert lib.query_count(0) == lib.query_count(1) == 1
211 assert lib.query_stream(0) == lib.query_stream(1) == stream244 assert lib.query_stream(0) == lib.query_stream(1) == stream
245+ 
246+ 
247+def test_native_rejection_does_not_poison_later_launches(native_launchers):
248+ """A request rejected by one budget must not cache anything that alters the next launch."""
249+ lib = native_launchers
250+ lib.reset(8, 6, 0, 0)
251+ assert lib.call_kernel_mixed(12, 0x1234) == -0x500000003
252+ assert lib.launch_count() == 0
253+ lib.reset(20, 40, 0, 0)
254+ assert lib.call_kernel_mixed(12, 0x1234) == 12
255+ assert lib.launched_blocks() == 12