Merged
fix(ir): Select merged valid_shape by branch condition #5840
lidongshengAdd on Sep 1
fix(ir): Select merged valid_shape by branch condition #5840
Merged
lidongshengAdd on Sep 1
Total: 25 files changed+496-44
@@ -245,6 +245,11 @@ Pass FlattenSingleStmt();
245 245 
246Pass MergeStmtsIntoIf();246Pass MergeStmtsIntoIf();
247 247 
248+/**
249+ * \brief Simplify symbolic scalars under their enclosing branch condition
250+ */
251+Pass SimplifySymbolicScalar();
252+ 
248Pass CreateRootFunctions();253Pass CreateRootFunctions();
249 254 
250/**255/**
@@ -69,6 +69,7 @@ public:
69 pypto::ir::ExprPtr AsExpr() const;69 pypto::ir::ExprPtr AsExpr() const;
70 void GetVarRefs(std::unordered_set<const pypto::ir::Var*>& out) const;70 void GetVarRefs(std::unordered_set<const pypto::ir::Var*>& out) const;
71 SymbolicScalar SubstituteVars(const std::unordered_map<pypto::ir::VarPtr, pypto::ir::ExprPtr>& vars);71 SymbolicScalar SubstituteVars(const std::unordered_map<pypto::ir::VarPtr, pypto::ir::ExprPtr>& vars);
72+ SymbolicScalar Substitute(const std::vector<std::pair<RawSymbolicScalarPtr, RawSymbolicScalarPtr>>& vals);
72 73 
73 operator int() const74 operator int() const
74 {75 {
@@ -0,0 +1,104 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software; you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See the License in the root of the software repository for the full text of the License.
9+ */
10+#include <functional>
11+#include <utility>
12+#include <vector>
13+ 
14+#include "ir/stmt.h"
15+#include "ir/transforms/base/visitor.h"
16+#include "ir/transforms/passes.h"
17+ 
18+#include "tilefwk/symbolic_scalar.h"
19+#include "interface/tensor/logical_tensor.h"
20+#include "interface/operation/operation.h"
21+ 
22+namespace pypto::ir {
23+ 
24+namespace {
25+ 
26+using npu::tile_fwk::AsLogicalTensor;
27+using npu::tile_fwk::Operation;
28+using npu::tile_fwk::RawSymbolicScalarPtr;
29+using npu::tile_fwk::SymbolicScalar;
30+ 
31+class CondSimplifier : public IRVisitor {
32+ using IRVisitor::VisitExpr_;
33+ using IRVisitor::VisitStmt_;
34+ 
35+public:
36+ void VisitStmt_(const IfStmtPtr& op) override
37+ {
38+ auto cond = SymbolicScalar::FromExpr(op->condition_);
39+ 
40+ conds_.push_back({cond.Raw(), true_.Raw()});
41+ VisitStmt_(op->thenBody_);
42+ conds_.pop_back();
43+ 
44+ if (op->elseBody_) {
45+ conds_.push_back({cond.Raw(), false_.Raw()});
46+ VisitStmt_(*op->elseBody_);
47+ conds_.pop_back();
48+ }
49+ }
50+ 
51+ void VisitExpr_(const VarPtr& var) override
52+ {
53+ if (auto lt = AsLogicalTensor(var)) {
54+ for (auto& s : lt->GetDynValidShape()) {
55+ s = s.Substitute(conds_).Simplify();
56+ }
57+ return;
58+ }
59+ }
60+ 
61+ void VisitStmt_(const TensorOpStmtPtr& op) override
62+ {
63+ for (auto& arg : op->args_) {
64+ VisitExpr(arg);
65+ }
66+ for (auto& res : op->result_) {
67+ VisitExpr(res);
68+ }
69+ auto oper = std::dynamic_pointer_cast<Operation>(std::const_pointer_cast<TensorOpStmt>(op));
70+ if (oper) {
71+ for (auto& attr : oper->GetDynamicAttributeList()) {
72+ auto& s = attr.get();
73+ s = s.Substitute(conds_).Simplify();
74+ }
75+ return;
76+ }
77+ }
78+ 
79+ std::vector<std::pair<RawSymbolicScalarPtr, RawSymbolicScalarPtr>> conds_;
80+ SymbolicScalar true_{1};
81+ SymbolicScalar false_{0};
82+};
83+ 
84+} // namespace
85+ 
86+namespace pass {
87+ 
88+Pass SimplifySymbolicScalar()
89+{
90+ return CreateFunctionPass(
91+ [](const FunctionPtr& func) -> FunctionPtr {
92+ if (!func || !func->body_) {
93+ return func;
94+ }
95+ CondSimplifier rewriter;
96+ rewriter.VisitStmt(func->body_);
97+ return func;
98+ },
99+ "SimplifySymbolicScalar");
100+}
101+ 
102+} // namespace pass
103+ 
104+} // namespace pypto::ir
@@ -22,6 +22,7 @@
22#include "stmt_utils.h"22#include "stmt_utils.h"
23 23 
24#include "interface/tensor/ir.h"24#include "interface/tensor/ir.h"
25+#include "interface/tensor/logical_tensor.h"
25 26 
26namespace pypto {27namespace pypto {
27namespace ir {28namespace ir {
@@ -93,7 +94,15 @@ private:
93 {94 {
94 const auto& returnVars = *rvStack_.back();95 const auto& returnVars = *rvStack_.back();
95 for (size_t k = 0; k < values.size(); ++k) {96 for (size_t k = 0; k < values.size(); ++k) {
96- AddSite({returnVars[k].get()}, CollectVarUses(values[k]));97+ auto uses = CollectVarUses(values[k]);
98+ // A carried tensor's dynvalidshape may reference scalars defined earlier in the
99+ // body (symbolic merge dims); those refs keep the scalar's carry alive.
100+ if (auto lt = npu::tile_fwk::AsLogicalTensor(values[k])) {
101+ for (auto& shape : lt->GetDynValidShape()) {
102+ shape.GetVarRefs(uses);
103+ }
104+ }
105+ AddSite({returnVars[k].get()}, std::move(uses));
97 }106 }
98 }107 }
99 108 
@@ -20,6 +20,7 @@
20#include "ir/transforms/base/visitor.h"20#include "ir/transforms/base/visitor.h"
21 21 
22#include "interface/tensor/ir.h"22#include "interface/tensor/ir.h"
23+#include "interface/tensor/logical_tensor.h"
23 24 
24namespace pypto {25namespace pypto {
25namespace ir {26namespace ir {
@@ -53,18 +54,21 @@ private:
53 {54 {
54 if (!skip_iter_updates_) {55 if (!skip_iter_updates_) {
55 IRVisitor::VisitStmt_(op);56 IRVisitor::VisitStmt_(op);
57+ CollectValueTypeRefs(op->value_);
56 }58 }
57 }59 }
58 void VisitStmt_(const BreakStmtPtr& op) override60 void VisitStmt_(const BreakStmtPtr& op) override
59 {61 {
60 if (!skip_iter_updates_) {62 if (!skip_iter_updates_) {
61 IRVisitor::VisitStmt_(op);63 IRVisitor::VisitStmt_(op);
64+ CollectValueTypeRefs(op->value_);
62 }65 }
63 }66 }
64 void VisitStmt_(const ContinueStmtPtr& op) override67 void VisitStmt_(const ContinueStmtPtr& op) override
65 {68 {
66 if (!skip_iter_updates_) {69 if (!skip_iter_updates_) {
67 IRVisitor::VisitStmt_(op);70 IRVisitor::VisitStmt_(op);
71+ CollectValueTypeRefs(op->value_);
68 }72 }
69 }73 }
70 74 
@@ -74,6 +78,20 @@ private:
74 CollectScalarVarRefs(op, var_uses);78 CollectScalarVarRefs(op, var_uses);
75 }79 }
76 80 
81+ // A terminator forwards carried values, and a carried tensor's dynvalidshape may reference
82+ // scalars (symbolic merge dims) whose defining if lives earlier in the body: those refs are
83+ // uses too, or the scalar's carry gets pruned while the exported tensor type still names it.
84+ void CollectValueTypeRefs(const std::vector<ExprPtr>& values)
85+ {
86+ for (const auto& v : values) {
87+ if (auto lt = npu::tile_fwk::AsLogicalTensor(v)) {
88+ for (auto& shape : lt->GetDynValidShape()) {
89+ shape.GetVarRefs(var_uses);
90+ }
91+ }
92+ }
93+ }
94+ 
77 bool skip_iter_updates_;95 bool skip_iter_updates_;
78};96};
79 97 
@@ -81,6 +81,13 @@ void CollectScalarVarRefs(const TensorOpStmtPtr& op, std::unordered_set<const Va
81 attr.get().GetVarRefs(var_uses);81 attr.get().GetVarRefs(var_uses);
82 }82 }
83 }83 }
84+ for (auto& var : op->result_) {
85+ if (auto lt = std::dynamic_pointer_cast<const LogicalTensor>(var)) {
86+ for (auto& shape : lt->GetDynValidShape()) {
87+ shape.GetVarRefs(var_uses);
88+ }
89+ }
90+ }
84}91}
85 92 
86bool IsSameRawTensor(const VarPtr& v0, const VarPtr& v1)93bool IsSameRawTensor(const VarPtr& v0, const VarPtr& v1)
@@ -33,13 +33,6 @@ using namespace pypto;
33 33 
34namespace npu::tile_fwk {34namespace npu::tile_fwk {
35 35 
36-namespace {
37-inline LogicalTensorPtr AsLogicalTensor(const ir::ExprPtr& expr)
38-{
39- return std::const_pointer_cast<LogicalTensor>(std::dynamic_pointer_cast<const LogicalTensor>(expr));
40-}
41-} // namespace
42- 
43class StmtTransformer : public ir::IRMutator {36class StmtTransformer : public ir::IRMutator {
44public:37public:
45 using IRMutator::VisitExpr_;38 using IRMutator::VisitExpr_;
@@ -228,6 +228,12 @@ enum EmuOpcode : int64_t {
228bool CheckEmuOpcode(const Operation* op, EmuOpcode opcode);228bool CheckEmuOpcode(const Operation* op, EmuOpcode opcode);
229void SetEmuOpcode(Operation* op, EmuOpcode opcode);229void SetEmuOpcode(Operation* op, EmuOpcode opcode);
230 230 
231+// Cast an expression to a mutable LogicalTensor, or nullptr when it is not one.
232+inline LogicalTensorPtr AsLogicalTensor(const ir::ExprPtr& expr)
233+{
234+ return std::const_pointer_cast<LogicalTensor>(std::dynamic_pointer_cast<const LogicalTensor>(expr));
235+}
236+ 
231bool TypeEqual(const LogicalTensorPtr a, const LogicalTensorPtr b);237bool TypeEqual(const LogicalTensorPtr a, const LogicalTensorPtr b);
232 238 
233Tensor TensorExtract(const Tensor& src, const std::vector<SymbolicScalar>& offset);239Tensor TensorExtract(const Tensor& src, const std::vector<SymbolicScalar>& offset);
@@ -973,6 +973,39 @@ SymbolicScalar SymbolicScalar::SubstituteVars(const std::unordered_map<ir::VarPt
973 return SymbolicScalar(substitute(raw_));973 return SymbolicScalar(substitute(raw_));
974}974}
975 975 
976+SymbolicScalar SymbolicScalar::Substitute(
977+ const std::vector<std::pair<RawSymbolicScalarPtr, RawSymbolicScalarPtr>>& vals)
978+{
979+ std::function<RawSymbolicScalarPtr(const RawSymbolicScalarPtr&)> substitute;
980+ substitute = [&](const RawSymbolicScalarPtr& raw) -> RawSymbolicScalarPtr {
981+ if (!raw) {
982+ return raw;
983+ }
984+ for (auto& [key, val] : vals) {
985+ if (key == raw) {
986+ return val;
987+ }
988+ }
989+ if (!raw->IsExpression()) {
990+ return raw;
991+ }
992+ auto expr = std::static_pointer_cast<RawSymbolicExpression>(raw);
993+ std::vector<RawSymbolicScalarPtr> operands;
994+ operands.reserve(expr->OperandList().size());
995+ bool changed = false;
996+ for (auto& operand : expr->OperandList()) {
997+ auto substituted = substitute(operand);
998+ operands.push_back(substituted);
999+ changed = changed || substituted != operand;
1000+ }
1001+ if (!changed) {
1002+ return raw;
1003+ }
1004+ return std::make_shared<RawSymbolicExpression>(expr->Opcode(), operands);
1005+ };
1006+ return SymbolicScalar(substitute(raw_));
1007+}
1008+ 
976SymbolicScalar SymbolicScalar::Min(const SymbolicScalar& sval) const1009SymbolicScalar SymbolicScalar::Min(const SymbolicScalar& sval) const
977{1010{
978 if (ConcreteValid() && sval.ConcreteValid()) {1011 if (ConcreteValid() && sval.ConcreteValid()) {
@@ -43,6 +43,13 @@ static inline std::optional<ScalarImmediateType> GetConstVal(const RawPtr& n)
43 return std::nullopt;43 return std::nullopt;
44}44}
45 45 
46+// Fully-qualified runtime call name of the ternary op, matching SymbolicScalar::Ternary.
47+inline const std::string& TernaryOpCallName()
48+{
49+ static const std::string name = AddRuntimePrefix(SymbolHandler::GetNameByHandlerId(SymbolHandlerId::TernaryOP));
50+ return name;
51+}
52+ 
46// ============================================================================53// ============================================================================
47// CRTP Pattern base54// CRTP Pattern base
48// ============================================================================55// ============================================================================
@@ -448,6 +455,13 @@ private:
448 return MakeConst(Expr::FoldAllImmediate(e->Opcode(), immList));455 return MakeConst(Expr::FoldAllImmediate(e->Opcode(), immList));
449 }456 }
450 457 
458+ // RUNTIME_TernaryOP(c, lhs, rhs) with a decided condition folds to the selected operand
459+ if (newOps.size() == 4 && e->IsExpressionCall(TernaryOpCallName())) {
460+ if (auto condVal = GetConstVal(newOps[1])) {
461+ return condVal.value() != 0 ? newOps[2] : newOps[3];
462+ }
463+ }
464+ 
451 SymbolicOpcode opcode = e->Opcode();465 SymbolicOpcode opcode = e->Opcode();
452 // Unary ops466 // Unary ops
453 if (opcode == SymbolicOpcode::T_UOP_NEG) {467 if (opcode == SymbolicOpcode::T_UOP_NEG) {
@@ -53,7 +53,7 @@ def get_dtensor_type():
53 return _dtensor_type53 return _dtensor_type
54 54 
55 55 
56-def get_npu_tensor_format(tensor):56+def get_tensor_format(tensor):
57 """Return 'NZ' if tensor is in NPU NZ format (format code 29), else 'ND'."""57 """Return 'NZ' if tensor is in NPU NZ format (format code 29), else 'ND'."""
58 torch_npu = get_torch_npu()58 torch_npu = get_torch_npu()
59 if torch_npu is not None and torch_npu.get_npu_format(tensor) == 29:59 if torch_npu is not None and torch_npu.get_npu_format(tensor) == 29:
@@ -61,7 +61,7 @@ def get_npu_tensor_format(tensor):
61 return "ND"61 return "ND"
62 62 
63 63 
64-def get_torch_npu_compute_determinism_level() -> int:64+def get_compute_determinism_level() -> int:
65 """Return torch_npu deterministic level (0/1/2); 0 when torch_npu is unavailable."""65 """Return torch_npu deterministic level (0/1/2); 0 when torch_npu is unavailable."""
66 torch_npu = get_torch_npu()66 torch_npu = get_torch_npu()
67 if torch_npu is None:67 if torch_npu is None:
@@ -26,10 +26,10 @@ import torch
26import pypto26import pypto
27from pypto import pypto_impl27from pypto import pypto_impl
28from pypto._utils import (28from pypto._utils import (
29+ get_compute_determinism_level,
29 get_dtensor_type,30 get_dtensor_type,
30- get_npu_tensor_format,31+ get_tensor_format,
31 get_torch_npu,32 get_torch_npu,
32- get_torch_npu_compute_determinism_level,
33)33)
34from pypto.cost_model import _cost_model_run_once_data_from_host34from pypto.cost_model import _cost_model_run_once_data_from_host
35from pypto.error import FeError, _catch_and_wrap_error35from pypto.error import FeError, _catch_and_wrap_error
@@ -714,7 +714,7 @@ class JitCallableWrapper:
714 """Check if the input tensor definitions match the input tensors."""714 """Check if the input tensor definitions match the input tensors."""
715 715 
716 def get_format(tensor):716 def get_format(tensor):
717- return get_npu_tensor_format(tensor)717+ return get_tensor_format(tensor)
718 718 
719 # Check the number of input tensors and input tensor definitions719 # Check the number of input tensors and input tensor definitions
720 if len(in_tensors) != len(input_tensor_defs):720 if len(in_tensors) != len(input_tensor_defs):
@@ -1024,7 +1024,7 @@ class JitCallableWrapper:
1024 pypto.set_debug_options(**self._debug_options)1024 pypto.set_debug_options(**self._debug_options)
1025 # Follow torch_npu deterministic level 0/1/2 (same idea as TorchAir / aclnn).1025 # Follow torch_npu deterministic level 0/1/2 (same idea as TorchAir / aclnn).
1026 pypto.set_global_config(1026 pypto.set_global_config(
1027- "compute_determinism_level", get_torch_npu_compute_determinism_level()1027+ "compute_determinism_level", get_compute_determinism_level()
1028 )1028 )
1029 1029 
1030 def _run(1030 def _run(
@@ -31,6 +31,7 @@ def _build_default_pipeline():
31 dce = ir.Pass.aggressive_dce()31 dce = ir.Pass.aggressive_dce()
32 canonicalize = ir.Pass.canonicalize()32 canonicalize = ir.Pass.canonicalize()
33 merge_stmts = ir.Pass.merge_stmts_into_if()33 merge_stmts = ir.Pass.merge_stmts_into_if()
34+ simplify_symbolic_scalar = ir.Pass.simplify_symbolic_scalar()
34 remove_redundant_tokens = ir.Pass.remove_redundant_token_pass()35 remove_redundant_tokens = ir.Pass.remove_redundant_token_pass()
35 create_root_functions = ir.Pass.create_root_functions()36 create_root_functions = ir.Pass.create_root_functions()
36 finalize = ir.Pass.finalize_dynamic_function()37 finalize = ir.Pass.finalize_dynamic_function()
@@ -40,6 +41,7 @@ def _build_default_pipeline():
40 ("first_canonicalize_dce", lambda p:dce(canonicalize(p))),41 ("first_canonicalize_dce", lambda p:dce(canonicalize(p))),
41 ("second_canonicalize_dce", lambda p:dce(canonicalize(p))),42 ("second_canonicalize_dce", lambda p:dce(canonicalize(p))),
42 ("canonicalize(merge_stmts)", lambda p:canonicalize(merge_stmts(p))),43 ("canonicalize(merge_stmts)", lambda p:canonicalize(merge_stmts(p))),
44+ ("simplify_symbolic_scalar", simplify_symbolic_scalar),
43 ("remove_redundant_token_pass", remove_redundant_tokens),45 ("remove_redundant_token_pass", remove_redundant_tokens),
44 ("create_root_functions", create_root_functions),46 ("create_root_functions", create_root_functions),
45 ("finalize", finalize),47 ("finalize", finalize),
@@ -392,10 +392,12 @@ def _loop_unroll(body: Block, loop: LoopRange, factor, nstart, nstop, ctx: Build
392 CompileState.bump_atomic_scope_iter()392 CompileState.bump_atomic_scope_iter()
393 dispatch_block(body, False)393 dispatch_block(body, False)
394 else:394 else:
395+ ctx.in_loop_unroll = factor != 1
395 for i in range(factor):396 for i in range(factor):
396 scope.varmap[loop_val.id] = loop_var + i * loop.step397 scope.varmap[loop_val.id] = loop_var + i * loop.step
397 CompileState.bump_atomic_scope_iter()398 CompileState.bump_atomic_scope_iter()
398 dispatch_block(body, False)399 dispatch_block(body, False)
400+ ctx.in_loop_unroll = False
399 if is_positive:401 if is_positive:
400 loop_conds.append(loop_var + (factor - 1) * loop.step < loop.stop)402 loop_conds.append(loop_var + (factor - 1) * loop.step < loop.stop)
401 if is_negative:403 if is_negative:
@@ -452,6 +454,16 @@ def _dyn_for(body: Block, loop: LoopRange, ctx: BuildContext):
452 nstart = nstop454 nstart = nstop
453 455 
454 456 
457+def _merge_valid_shape(var, cond, shape1, shape2):
458+ shape = []
459+ for a, b in zip(shape1, shape2):
460+ if str(a.simplify()) == str(b.simplify()):
461+ shape.append(a)
462+ else:
463+ shape.append(SymbolicScalar.tenary(cond, a, b))
464+ var.valid_shape = shape
465+ 
466+ 
455@impl("pil.loop")467@impl("pil.loop")
456def loop_impl(ctx: BuildContext, body: Block, loop):468def loop_impl(ctx: BuildContext, body: Block, loop):
457 if isinstance(loop, LoopRange):469 if isinstance(loop, LoopRange):
@@ -520,6 +532,8 @@ def _if_else_stmt(cond, then_block: Block, else_block: Block, ctx: BuildContext)
520 for i, name in enumerate(all_names):532 for i, name in enumerate(all_names):
521 if ir.type_equal(then_yield_vars[i], else_yield_vars[i]):533 if ir.type_equal(then_yield_vars[i], else_yield_vars[i]):
522 var = ctx.create_var_like(name, then_yield_vars[i])534 var = ctx.create_var_like(name, then_yield_vars[i])
535+ if isinstance(then_yield_vars[i], ir.LogicalTensor) and not ctx.in_loop_unroll:
536+ _merge_valid_shape(var, cond, then_yield_vars[i].valid_shape, else_yield_vars[i].valid_shape)
523 elif isinstance(then_yield_vars[i].type, ir.NoneType):537 elif isinstance(then_yield_vars[i].type, ir.NoneType):
524 var = ctx.create_var_like(name, else_yield_vars[i])538 var = ctx.create_var_like(name, else_yield_vars[i])
525 elif isinstance(else_yield_vars[i].type, ir.NoneType):539 elif isinstance(else_yield_vars[i].type, ir.NoneType):
@@ -239,6 +239,7 @@ class BuildContext(ir.IRBuilder):
239 self.return_var_names = []239 self.return_var_names = []
240 self.loop_stack = [] # used by legacy is_loop_begin() and is_loop_end()240 self.loop_stack = [] # used by legacy is_loop_begin() and is_loop_end()
241 self.call_stack = []241 self.call_stack = []
242+ self.in_loop_unroll = False
242 243 
243 def __enter__(self):244 def __enter__(self):
244 self.parent = _current.build_context245 self.parent = _current.build_context
@@ -305,6 +305,8 @@ class SymbolicScalar:
305class LogicalTensor(ir.Var):305class LogicalTensor(ir.Var):
306 """Logical tensor"""306 """Logical tensor"""
307 307 
308+ valid_shape: List[SymbolicScalar]
309+ 
308 310 
309class Tensor:311class Tensor:
310 312 
@@ -2426,6 +2426,10 @@ class Pass:
2426 def merge_stmts_into_if() -> Pass:2426 def merge_stmts_into_if() -> Pass:
2427 """Merge statements into if statements."""2427 """Merge statements into if statements."""
2428 2428 
2429+ @staticmethod
2430+ def simplify_symbolic_scalar() -> Pass:
2431+ """Simplify symbolic scalars under their enclosing branch condition."""
2432+ 
2429 @staticmethod2433 @staticmethod
2430 def create_root_functions() -> Pass:2434 def create_root_functions() -> Pass:
2431 """Create root functions."""2435 """Create root functions."""
@@ -96,6 +96,8 @@ void BindPasses(py::module_& m)
96 .def_static("remove_redundant_token_pass", &pass::RemoveRedundantTokenPass,96 .def_static("remove_redundant_token_pass", &pass::RemoveRedundantTokenPass,
97 "Remove redundant token dependencies")97 "Remove redundant token dependencies")
98 .def_static("merge_stmts_into_if", &pass::MergeStmtsIntoIf, "Merge stmts into if branches")98 .def_static("merge_stmts_into_if", &pass::MergeStmtsIntoIf, "Merge stmts into if branches")
99+ .def_static("simplify_symbolic_scalar", &pass::SimplifySymbolicScalar,
100+ "Simplify symbolic scalars under their enclosing branch condition")
99 .def_static("create_root_functions", &pass::CreateRootFunctions, "Create root functions from IR")101 .def_static("create_root_functions", &pass::CreateRootFunctions, "Create root functions from IR")
100 .def_static("finalize_dynamic_function", &pass::FinalizeDynamicFunction,102 .def_static("finalize_dynamic_function", &pass::FinalizeDynamicFunction,
101 "Finalize dynamic functions built from new IR");103 "Finalize dynamic functions built from new IR");
@@ -168,7 +168,10 @@ void BindTensor(py::module_& m)
168 "Get the logical tensor storage.");168 "Get the logical tensor storage.");
169 169 
170 py::class_<LogicalTensor, ir::Var, std::shared_ptr<LogicalTensor>>(m, "LogicalTensor")170 py::class_<LogicalTensor, ir::Var, std::shared_ptr<LogicalTensor>>(m, "LogicalTensor")
171- .def("__str__", [](const LogicalTensor& t) -> std::string { return t.Dump(); });171+ .def("__str__", [](const LogicalTensor& t) -> std::string { return t.Dump(); })
172+ .def_property(
173+ "valid_shape", [](const LogicalTensor& t) -> std::vector<SymbolicScalar> { return t.GetDynValidShape(); },
174+ &LogicalTensor::UpdateDynValidShape, "Dynamic valid shape dims of this logical tensor.");
172 175 
173 m.def(176 m.def(
174 "GetInputShape",177 "GetInputShape",
@@ -18,6 +18,8 @@ import pytest
18import torch18import torch
19 19 
20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21+if not hasattr(torch, "npu"):
22+ pytest.skip("torch_npu not installed", allow_module_level=True)
21from _ops.bsa import bsa_fwd_impl as _bsa_impl # noqa: E40223from _ops.bsa import bsa_fwd_impl as _bsa_impl # noqa: E402
22from _ops.bsa.bsa_common import DEFAULT_CONFIG # noqa: E40224from _ops.bsa.bsa_common import DEFAULT_CONFIG # noqa: E402
23from _ops.bsa.bsa_fwd_golden import BSAForwardInputs, bsa_forward_golden # noqa: E40225from _ops.bsa.bsa_fwd_golden import BSAForwardInputs, bsa_forward_golden # noqa: E402
@@ -19,6 +19,8 @@ import pytest
19import torch19import torch
20 20 
21sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))21sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22+if not hasattr(torch, "npu"):
23+ pytest.skip("torch_npu not installed", allow_module_level=True)
22from _ops.flash_attention_mha_impl import ( # noqa: E40224from _ops.flash_attention_mha_impl import ( # noqa: E402
23 FlashAttentionTileShapeConfig,25 FlashAttentionTileShapeConfig,
24 flash_attention_varlen_forward_kernel,26 flash_attention_varlen_forward_kernel,
@@ -51,8 +51,8 @@ def ssa_verify(func, desc: str = ""):
51 51 
52 52 
53def run_merge_pass(func, *args, create_new_logical_tensor=True):53def run_merge_pass(func, *args, create_new_logical_tensor=True):
54- """Compile a kernel and run canonicalize + dce + merge_stmts_into_if, stopping before lowering54+ """Compile a kernel and run canonicalize + dce + merge_stmts_into_if + symbolic_scalar_simplify_pass, stopping
55- so the resulting if-tree (func.body) is inspectable. Mirrors compile_new_ir's first half.55+ before lowering so the resulting if-tree (func.body) is inspectable. Mirrors compile_new_ir's first half.
56 """56 """
57 b = ir.IRBuilder()57 b = ir.IRBuilder()
58 func = pil.compile(func, *args, create_new_logical_tensor=create_new_logical_tensor)58 func = pil.compile(func, *args, create_new_logical_tensor=create_new_logical_tensor)
@@ -60,6 +60,7 @@ def run_merge_pass(func, *args, create_new_logical_tensor=True):
60 dce = ir.Pass.aggressive_dce()60 dce = ir.Pass.aggressive_dce()
61 canonical = ir.Pass.canonicalize()61 canonical = ir.Pass.canonicalize()
62 merge = ir.Pass.merge_stmts_into_if()62 merge = ir.Pass.merge_stmts_into_if()
63+ simplify_symbolic_scalar = ir.Pass.simplify_symbolic_scalar()
63 verifier = ir.IRVerifier.create_default()64 verifier = ir.IRVerifier.create_default()
64 _ssa_verify(verifier, prog, "original")65 _ssa_verify(verifier, prog, "original")
65 prog = canonical(prog)66 prog = canonical(prog)
@@ -68,6 +69,8 @@ def run_merge_pass(func, *args, create_new_logical_tensor=True):
68 _ssa_verify(verifier, prog, "dce")69 _ssa_verify(verifier, prog, "dce")
69 prog = canonical(merge(prog))70 prog = canonical(merge(prog))
70 _ssa_verify(verifier, prog, "merged")71 _ssa_verify(verifier, prog, "merged")
72+ # only symbolic scalar are simplified, skip ssa_verify
73+ prog = simplify_symbolic_scalar(prog)
71 func = prog.functions[func.name]74 func = prog.functions[func.name]
72 logging.info("\nmerged:\n%s" % func.body)75 logging.info("\nmerged:\n%s" % func.body)
73 return func76 return func
@@ -0,0 +1,217 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+ 
10+import pypto
11+from pypto.pil.compile_pipeline import compile_new_ir
12+ 
13+# ruff: noqa: N806
14+S_TILE = 128
15+ 
16+ 
17+def compute_tile(q_i, k_j, v_j, dy_i, smax_i, ssum_i, d_i,
18+ actual_s1, actual_s2, scale_value, c_tile, v_tile_s, v_tile_d, s_tile_size):
19+ """计算一个 (s1_tile, s2_tile) 块的 P_ij 和 dS_ij。"""
20+ # 计算公式:S_ij = Q_i @ K_j^T * scale
21+ pypto.set_vec_tile_shapes(v_tile_s[0], v_tile_s[1])
22+ pypto.set_cube_tile_shapes(c_tile[0], c_tile[1], c_tile[2])
23+ s_ij = pypto.matmul(q_i, k_j, pypto.DT_FP32, b_trans=True)
24+ s_ij = pypto.view(s_ij, [s_tile_size, s_tile_size], [0, 0],
25+ valid_shape=[actual_s1, actual_s2])
26+ 
27+ pypto.set_vec_tile_shapes(v_tile_s[0], v_tile_s[1])
28+ s_ij = pypto.mul(s_ij, scale_value)
29+ p_ij = pypto.exp(pypto.sub(s_ij, smax_i),
30+ precision_type=pypto.PrecisionType.HIGH_PRECISION)
31+ p_ij = pypto.div(p_ij, ssum_i)
32+ 
33+ # 计算公式:dP_ij = dY_i @ V_j^T
34+ pypto.set_vec_tile_shapes(v_tile_s[0], v_tile_s[1])
35+ pypto.set_cube_tile_shapes(c_tile[0], c_tile[1], c_tile[2])
36+ dp_ij = pypto.matmul(dy_i, v_j, pypto.DT_FP32, b_trans=True)
37+ dp_ij = pypto.view(dp_ij, [s_tile_size, s_tile_size], [0, 0],
38+ valid_shape=[actual_s1, actual_s2])
39+ 
40+ # 计算公式:dS_ij = P_ij * (dP_ij - D_i)
41+ pypto.set_vec_tile_shapes(v_tile_s[0], v_tile_s[1])
42+ ds_ij = pypto.mul(p_ij, pypto.sub(dp_ij, d_i))
43+ 
44+ return p_ij, ds_ij
45+ 
46+ 
47+def flash_attention_score_grad_kernel(
48+ q: pypto.Tensor[[pypto.DYN, ...], pypto.DT_BF16],
49+ k: pypto.Tensor[[pypto.DYN, ...], pypto.DT_BF16],
50+ v: pypto.Tensor[[pypto.DYN, ...], pypto.DT_BF16],
51+ dy: pypto.Tensor[[pypto.DYN, ...], pypto.DT_BF16],
52+ softmax_max: pypto.Tensor[[pypto.DYN, ...], pypto.DT_FP32],
53+ softmax_sum: pypto.Tensor[[pypto.DYN, ...], pypto.DT_FP32],
54+ attention_out: pypto.Tensor[[pypto.DYN, ...], pypto.DT_BF16],
55+ dq: pypto.Tensor[[pypto.DYN, ...], pypto.DT_BF16],
56+ dk: pypto.Tensor[[pypto.DYN, ...], pypto.DT_BF16],
57+ dv: pypto.Tensor[[pypto.DYN, ...], pypto.DT_BF16],
58+ batch_size: pypto.Tensor[[pypto.DYN], pypto.DT_INT32],
59+ scale_value: float,
60+ num_heads: int,
61+):
62+ b = batch_size.shape[0]
63+ total = q.shape[0]
64+ head_dim = q.shape[1]
65+ s = total // b // num_heads
66+ 
67+ q_2d = q
68+ k_2d = k
69+ v_2d = v
70+ dy_2d = dy
71+ ao_2d = attention_out
72+ sm_2d = softmax_max
73+ ss_2d = softmax_sum
74+ dq_2d = dq
75+ dk_2d = dk
76+ dv_2d = dv
77+ 
78+ s_loop = (s + S_TILE - 1) // S_TILE
79+ 
80+ c_tile = [[S_TILE, S_TILE], [head_dim, 256], [S_TILE, S_TILE]]
81+ v_tile_s = [S_TILE, S_TILE]
82+ v_tile_d = [S_TILE, head_dim]
83+ 
84+ for b_idx in pypto.loop(b, name="LOOP_b", idx_name="b_idx"):
85+ for n_idx in pypto.loop(num_heads, name="LOOP_n", idx_name="n_idx"):
86+ bn_base = (b_idx * num_heads + n_idx) * s
87+ 
88+ # ===== 趟1: 计算 dQ =====
89+ for s1_idx in pypto.loop(s_loop, name="LOOP_s1_dq", idx_name="s1_idx"):
90+ s1_off = bn_base + s1_idx * S_TILE
91+ actual_s1 = (s - s1_idx * S_TILE).min(S_TILE)
92+ 
93+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
94+ q_i = pypto.view(q_2d, [S_TILE, head_dim], [s1_off, 0], valid_shape=[actual_s1, head_dim])
95+ dy_i = pypto.view(dy_2d, [S_TILE, head_dim], [s1_off, 0], valid_shape=[actual_s1, head_dim])
96+ ao_i = pypto.view(ao_2d, [S_TILE, head_dim], [s1_off, 0], valid_shape=[actual_s1, head_dim])
97+ 
98+ sm_i_8 = pypto.view(sm_2d, [S_TILE, 8], [s1_off, 0], valid_shape=[actual_s1, 8])
99+ ss_i_8 = pypto.view(ss_2d, [S_TILE, 8], [s1_off, 0], valid_shape=[actual_s1, 8])
100+ pypto.set_vec_tile_shapes(S_TILE, 8)
101+ smax_i = pypto.view(sm_i_8, [S_TILE, 1], [0, 0], valid_shape=[actual_s1, 1])
102+ ssum_i = pypto.view(ss_i_8, [S_TILE, 1], [0, 0], valid_shape=[actual_s1, 1])
103+ 
104+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
105+ dy_ao_fp32 = pypto.cast(pypto.mul(dy_i, ao_i), pypto.DT_FP32)
106+ d_i = pypto.sum(dy_ao_fp32, -1, keepdim=True)
107+ 
108+ dq_acc = pypto.tensor([S_TILE, head_dim], pypto.DT_FP32, "dq_acc")
109+ 
110+ for s2_idx in pypto.loop(s_loop, name="LOOP_s2_dq", idx_name="s2_idx", unroll_list=[2, 1]):
111+ s2_off = bn_base + s2_idx * S_TILE
112+ actual_s2 = (s - s2_idx * S_TILE).min(S_TILE)
113+ 
114+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
115+ k_j = pypto.view(k_2d, [S_TILE, head_dim], [s2_off, 0], valid_shape=[actual_s2, head_dim])
116+ v_j = pypto.view(v_2d, [S_TILE, head_dim], [s2_off, 0], valid_shape=[actual_s2, head_dim])
117+ 
118+ _, ds_ij = compute_tile(q_i, k_j, v_j, dy_i, smax_i, ssum_i, d_i,
119+ actual_s1, actual_s2, scale_value,
120+ c_tile, v_tile_s, v_tile_d, S_TILE)
121+ 
122+ ds_bf16 = pypto.cast(ds_ij, pypto.DT_BF16)
123+ pypto.set_cube_tile_shapes(c_tile[0], c_tile[1], c_tile[2])
124+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
125+ dq_tile = pypto.matmul(ds_bf16, k_j, pypto.DT_FP32)
126+ 
127+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
128+ if pypto.is_loop_begin(s2_idx):
129+ dq_acc[:] = dq_tile
130+ else:
131+ dq_acc[:] = dq_acc + dq_tile
132+ 
133+ if pypto.is_loop_end(s2_idx):
134+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
135+ dq_final = pypto.cast(pypto.mul(dq_acc, scale_value), pypto.DT_BF16)
136+ dq_final_v = pypto.view(dq_final, [S_TILE, head_dim], [0, 0],
137+ valid_shape=[actual_s1, head_dim])
138+ pypto.assemble(dq_final_v, [s1_off, 0], dq_2d)
139+ 
140+ # ===== 趟2: 计算 dK, dV =====
141+ for s2_idx in pypto.loop(s_loop, name="LOOP_s2_dkv", idx_name="s2_idx"):
142+ s2_off = bn_base + s2_idx * S_TILE
143+ actual_s2 = (s - s2_idx * S_TILE).min(S_TILE)
144+ 
145+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
146+ k_j = pypto.view(k_2d, [S_TILE, head_dim], [s2_off, 0], valid_shape=[actual_s2, head_dim])
147+ v_j = pypto.view(v_2d, [S_TILE, head_dim], [s2_off, 0], valid_shape=[actual_s2, head_dim])
148+ 
149+ dk_acc = pypto.tensor([S_TILE, head_dim], pypto.DT_FP32, "dk_acc")
150+ dv_acc = pypto.tensor([S_TILE, head_dim], pypto.DT_FP32, "dv_acc")
151+ 
152+ for s1_idx in pypto.loop(s_loop, name="LOOP_s1_dkv", idx_name="s1_idx", unroll_list=[2, 1]):
153+ s1_off = bn_base + s1_idx * S_TILE
154+ actual_s1 = (s - s1_idx * S_TILE).min(S_TILE)
155+ 
156+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
157+ q_i = pypto.view(q_2d, [S_TILE, head_dim], [s1_off, 0], valid_shape=[actual_s1, head_dim])
158+ dy_i = pypto.view(dy_2d, [S_TILE, head_dim], [s1_off, 0], valid_shape=[actual_s1, head_dim])
159+ ao_i = pypto.view(ao_2d, [S_TILE, head_dim], [s1_off, 0], valid_shape=[actual_s1, head_dim])
160+ 
161+ sm_i_8 = pypto.view(sm_2d, [S_TILE, 8], [s1_off, 0], valid_shape=[actual_s1, 8])
162+ ss_i_8 = pypto.view(ss_2d, [S_TILE, 8], [s1_off, 0], valid_shape=[actual_s1, 8])
163+ pypto.set_vec_tile_shapes(S_TILE, 8)
164+ smax_i = pypto.view(sm_i_8, [S_TILE, 1], [0, 0], valid_shape=[actual_s1, 1])
165+ ssum_i = pypto.view(ss_i_8, [S_TILE, 1], [0, 0], valid_shape=[actual_s1, 1])
166+ 
167+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
168+ dy_ao_fp32 = pypto.cast(pypto.mul(dy_i, ao_i), pypto.DT_FP32)
169+ d_i = pypto.sum(dy_ao_fp32, -1, keepdim=True)
170+ 
171+ p_ij, ds_ij = compute_tile(q_i, k_j, v_j, dy_i, smax_i, ssum_i, d_i,
172+ actual_s1, actual_s2, scale_value,
173+ c_tile, v_tile_s, v_tile_d, S_TILE)
174+ 
175+ ds_bf16 = pypto.cast(ds_ij, pypto.DT_BF16)
176+ p_bf16 = pypto.cast(p_ij, pypto.DT_BF16)
177+ pypto.set_cube_tile_shapes(c_tile[0], c_tile[1], c_tile[2])
178+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
179+ dk_tile = pypto.matmul(ds_bf16, q_i, pypto.DT_FP32, a_trans=True)
180+ dv_tile = pypto.matmul(p_bf16, dy_i, pypto.DT_FP32, a_trans=True)
181+ 
182+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
183+ if pypto.is_loop_begin(s1_idx):
184+ dk_acc[:] = dk_tile
185+ dv_acc[:] = dv_tile
186+ else:
187+ dk_acc[:] = dk_acc + dk_tile
188+ dv_acc[:] = dv_acc + dv_tile
189+ 
190+ if pypto.is_loop_end(s1_idx):
191+ pypto.set_vec_tile_shapes(v_tile_d[0], v_tile_d[1])
192+ dk_final = pypto.cast(pypto.mul(dk_acc, scale_value), pypto.DT_BF16)
193+ dv_final = pypto.cast(dv_acc, pypto.DT_BF16)
194+ dk_final_v = pypto.view(dk_final, [S_TILE, head_dim], [0, 0],
195+ valid_shape=[actual_s2, head_dim])
196+ dv_final_v = pypto.view(dv_final, [S_TILE, head_dim], [0, 0],
197+ valid_shape=[actual_s2, head_dim])
198+ pypto.assemble(dk_final_v, [s2_off, 0], dk_2d)
199+ pypto.assemble(dv_final_v, [s2_off, 0], dv_2d)
200+ 
201+ 
202+def test_fa_score_grad():
203+ B, N, S, D = pypto.SymbolicScalar('B'), 1, pypto.SymbolicScalar('S'), 128
204+ q = pypto.Tensor((B * N * S, D), pypto.DT_BF16)
205+ k = pypto.Tensor((B * N * S, D), pypto.DT_BF16)
206+ v = pypto.Tensor((B * N * S, D), pypto.DT_BF16)
207+ dy = pypto.Tensor((B * N * S, D), pypto.DT_BF16)
208+ smax = pypto.Tensor((B * N * S, 8), pypto.DT_FP32)
209+ ssum = pypto.Tensor((B * N * S, 8), pypto.DT_FP32)
210+ ao = pypto.Tensor((B * N * S, D), pypto.DT_BF16)
211+ dq = pypto.Tensor((B * N * S, D), pypto.DT_BF16)
212+ dk = pypto.Tensor((B * N * S, D), pypto.DT_BF16)
213+ dv = pypto.Tensor((B * N * S, D), pypto.DT_BF16)
214+ batch_size = pypto.Tensor((B,), pypto.DT_INT32)
215+ 
216+ compile_new_ir(flash_attention_score_grad_kernel, q, k, v, dy, smax, ssum, ao, dq, dk, dv,
217+ batch_size, 1.0, N)
Rpython/tests/ut/interface/test_compute_determinism.py→python/tests/ut/ir/test_merge_pass/test_valid_shape.py+20-27
@@ -1,5 +1,4 @@
1-#!/usr/bin/env python31+# -*- coding: utf-8 -*-
2-# coding: utf-8
3# Copyright (c) 2026 Huawei Technologies Co., Ltd.2# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4# This program is free software, you can redistribute it and/or modify it under the terms and conditions of3# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5# CANN Open Software License Agreement Version 2.0 (the "License").4# CANN Open Software License Agreement Version 2.0 (the "License").
@@ -7,37 +6,31 @@
7# 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,
8# 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.
9# 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.
10-# -----------------------------------------------------------------------------------------------------------
11-"""Prove torch_npu deterministic level 0/1/2 is synced to global config."""
12 9 
13-import pytest10+from pathlib import Path
14-import torch_npu
15 11 
16import pypto12import pypto
17-from pypto._utils import get_torch_npu_compute_determinism_level
18-from pypto.frontend.parser.entry import JitCallableWrapper
19 13 
14+from ..test_common import check_snapshot, run_merge_pass
20 15 
21-def _dummy_kernel(x):16+_GOLDEN_DIR = Path(__file__).parent
22- return x
23 17 
18+IR1 = _GOLDEN_DIR / "test_valid_shape1.pypto"
24 19 
25-@pytest.fixture20+def test_valid_shape1():
26-def restore_determinism():
27- prev_level = int(torch_npu.npu._get_deterministic_level())
28- try:
29- yield
30- finally:
31- torch_npu.npu.set_deterministic_level(prev_level)
32- pypto.set_global_config("compute_determinism_level", 0)
33 21 
22+ def foo(a: pypto.Tensor, b: pypto.Tensor,):
23+ tile = 32
24+ n = pypto.ceildiv(a.shape[0], tile)
25+ for x in pypto.loop(n):
26+ if x == n - 1:
27+ t = pypto.view(a, [32, 32], [x*32, 0], valid_shape=[a.shape[0] - x*32, 32])
28+ else:
29+ t = pypto.view(a, [32, 32], [x*32, 0], valid_shape=[32, 32])
30+ t += 1
31+ pypto.assemble(t, [x*32, 0], b)
34 32 
35-def test_torch_npu_determinism_level_synced_to_global_config(restore_determinism):33+ x = pypto.Tensor((-1, 32), pypto.DT_FP32)
36- """torch_npu.set_deterministic_level -> set_global_config -> get_global_config."""34+ y = pypto.Tensor((32, 32), pypto.DT_FP32)
37- wrapper = JitCallableWrapper(None, _dummy_kernel, None)35+ func = run_merge_pass(foo, x, y)
38- 36+ check_snapshot(func, IR1)
39- for level in (0, 1, 2):
40- torch_npu.npu.set_deterministic_level(level)
41- assert get_torch_npu_compute_determinism_level() == level
42- wrapper._set_config_option()
43- assert pypto.get_global_config("compute_determinism_level") == level
@@ -0,0 +1,17 @@
1+function foo incast(v0_logical_tensor %a@0 #dtype(float) #shape([-1, 32]) #offset([0, 0]) #dynvalidshape([v0call(RUNTIME_GetInputShapeDim, ARG_a, 0), 32]), v0_logical_tensor %b@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32])) outcast() #type(Opaque) #entry(false) {
2+ v0_logical_tensor %b_5@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = for %loop_idx_16 inrange 0, v0div(v0sub(v0add(v0call(RUNTIME_GetInputShapeDim, ARG_a, 0), 32), 1), 32), 1 iter { v0_logical_tensor %b_1@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = %b@1; } #parallel(false) #submit_before_loop(false) #_loop_conds(Unsupported) #_config_scope(Unsupported) #unroll_times(1) {
3+ v0_logical_tensor %b_7@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = if v0eq(loop_idx_16, v0sub(v0div(v0add(v0call(RUNTIME_GetInputShapeDim, ARG_a, 0), 31), 32), 1)) then {
4+ v0_logical_tensor %View_a@2 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([v0sub(v0call(RUNTIME_GetInputShapeDim, ARG_a, 0), v0mul(loop_idx_16, 32)), 32]) = !10000 VIEW(%a@0) token() #fromOffset(Unsupported) #toValidShape(Unsupported);
5+ v0_logical_tensor %$0@4 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([v0sub(v0call(RUNTIME_GetInputShapeDim, ARG_a, 0), v0mul(loop_idx_16, 32)), 32]) = !10004 ADDS(%View_a@2) token();
6+ v0_logical_tensor %b_3@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10003 ASSEMBLE(%$0@4) token() #toOffset(Unsupported);
7+ yield %b_3@1;
8+ } else {
9+ v0_logical_tensor %View_a_0@3 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10001 VIEW(%a@0) token() #fromOffset(Unsupported) #toValidShape(Unsupported);
10+ v0_logical_tensor %$0_1@4 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10006 ADDS(%View_a_0@3) token();
11+ v0_logical_tensor %b_9@1 #dtype(float) #shape([32, 32]) #offset([0, 0]) #dynvalidshape([32, 32]) = !10007 ASSEMBLE(%$0_1@4) token() #toOffset(Unsupported);
12+ yield %b_9@1;
13+ }
14+ continue %b_7@1;
15+ }
16+ return %a@0, %b_5@1;
17+}