Merged
修复dump 数据bug #5436
Inspiron_stAdd on Aug 13
修复dump 数据bug #5436
Merged
Merged fromu010986451/pyptobug/dumpdataintocann/pyptomaster
Total: 12 files changed+281-40
| @@ -35,6 +35,7 @@ recursive-include framework/src/platform * | |||
| 35 | recursive-include python/pypto *.py | 35 | recursive-include python/pypto *.py |
| 36 | recursive-include python/pypto *.pyi | 36 | recursive-include python/pypto *.pyi |
| 37 | recursive-include python/pypto *.md | 37 | recursive-include python/pypto *.md |
| 38 | +recursive-include python/pypto_pro *.h | ||
| 38 | recursive-include python/src *.cpp | 39 | recursive-include python/src *.cpp |
| 39 | recursive-include python/src *.h | 40 | recursive-include python/src *.h |
| 40 | include python/CMakeLists.txt | 41 | include python/CMakeLists.txt |
| @@ -357,6 +357,7 @@ REGISTER_OP("debug.dump_tensor") | |||
| 357 | .add_argument("offsets", "Offsets per dimension (MakeTuple of integer scalars)") | 357 | .add_argument("offsets", "Offsets per dimension (MakeTuple of integer scalars)") |
| 358 | .add_argument("shapes", "Shape per dimension (MakeTuple of integer scalars)") | 358 | .add_argument("shapes", "Shape per dimension (MakeTuple of integer scalars)") |
| 359 | .set_attr<bool>("show_location") | 359 | .set_attr<bool>("show_location") |
| 360 | + .set_attr<std::string>("dump_flag") | ||
| 360 | .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 361 | .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, |
| 361 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | 362 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { |
| 362 | return DeduceDebugDumpTensorType(args, kwargs); | 363 | return DeduceDebugDumpTensorType(args, kwargs); |
| @@ -373,6 +374,7 @@ REGISTER_OP("debug.dump_tile") | |||
| 373 | .add_argument("shapes", "Optional shape per dimension (MakeTuple of integer scalars; dynamic only on CCE)") | 374 | .add_argument("shapes", "Optional shape per dimension (MakeTuple of integer scalars; dynamic only on CCE)") |
| 374 | .add_argument("workspace", "Optional GM Tensor for Acc tile temporary space (required for Acc tiles)") | 375 | .add_argument("workspace", "Optional GM Tensor for Acc tile temporary space (required for Acc tiles)") |
| 375 | .set_attr<bool>("show_location") | 376 | .set_attr<bool>("show_location") |
| 377 | + .set_attr<std::string>("dump_flag") | ||
| 376 | .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 378 | .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, |
| 377 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | 379 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { |
| 378 | return DeduceDebugDumpTileType(args, kwargs); | 380 | return DeduceDebugDumpTileType(args, kwargs); |
| @@ -645,6 +645,15 @@ static std::string MakeDebugDumpTensorNZDynamicCodegenCCE(codegen::CCECodegen& c | |||
| 645 | return ""; | 645 | return ""; |
| 646 | } | 646 | } |
| 647 | 647 | ||
| 648 | +static void EmitDumpFlagHeaderCCE(codegen::CCECodegen& codegen, const ir::CallPtr& op) | ||
| 649 | +{ | ||
| 650 | + std::string dump_flag = op->HasKwarg("dump_flag") ? op->GetKwarg<std::string>("dump_flag") : ""; | ||
| 651 | + if (dump_flag.empty()) { | ||
| 652 | + return; | ||
| 653 | + } | ||
| 654 | + codegen.Emit("cce::printf(\"=== [flag] %s ===\\n\", \"" + debug_printf::EscapeStringLiteral(dump_flag) + "\");"); | ||
| 655 | +} | ||
| 656 | + | ||
| 648 | static std::string MakeDebugDumpTensorCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) | 657 | static std::string MakeDebugDumpTensorCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) |
| 649 | { | 658 | { |
| 650 | auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base); | 659 | auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base); |
| @@ -652,6 +661,7 @@ static std::string MakeDebugDumpTensorCodegenCCE(const ir::CallPtr& op, codegen: | |||
| 652 | if (op->GetKwarg<bool>("show_location", false)) { | 661 | if (op->GetKwarg<bool>("show_location", false)) { |
| 653 | EmitDebugLocationHeaderCCE(codegen, op->span_, "dump_tensor"); | 662 | EmitDebugLocationHeaderCCE(codegen, op->span_, "dump_tensor"); |
| 654 | } | 663 | } |
| 664 | + EmitDumpFlagHeaderCCE(codegen, op); | ||
| 655 | 665 | ||
| 656 | auto tensor_var = ir::As<ir::Var>(op->args_[0]); | 666 | auto tensor_var = ir::As<ir::Var>(op->args_[0]); |
| 657 | CHECK(tensor_var) << "debug.dump_tensor first argument must be a Var"; | 667 | CHECK(tensor_var) << "debug.dump_tensor first argument must be a Var"; |
| @@ -773,6 +783,7 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 773 | if (op->GetKwarg<bool>("show_location", false)) { | 783 | if (op->GetKwarg<bool>("show_location", false)) { |
| 774 | EmitDebugLocationHeaderCCE(codegen, op->span_, "dump_tile"); | 784 | EmitDebugLocationHeaderCCE(codegen, op->span_, "dump_tile"); |
| 775 | } | 785 | } |
| 786 | + EmitDumpFlagHeaderCCE(codegen, op); | ||
| 776 | 787 | ||
| 777 | std::string src = codegen.GetExprAsCode(op->args_[0]); | 788 | std::string src = codegen.GetExprAsCode(op->args_[0]); |
| 778 | 789 | ||
| @@ -846,7 +857,7 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 846 | codegen.Emit("if (" + valid_col + " < 0) " + valid_col + " = 0;"); | 857 | codegen.Emit("if (" + valid_col + " < 0) " + valid_col + " = 0;"); |
| 847 | 858 | ||
| 848 | codegen.Emit("cce::printf(\"=== [TPRINT Acc Tile Window] Data Type: %s, Layout: NZ, TileType: Acc ===\\n\", " | 859 | codegen.Emit("cce::printf(\"=== [TPRINT Acc Tile Window] Data Type: %s, Layout: NZ, TileType: Acc ===\\n\", " |
| 849 | - "pto::GetDTypeName<" + | 860 | + "__pypto_dtype_name<" + |
| 850 | dtype_str + ">());"); | 861 | dtype_str + ">());"); |
| 851 | codegen.Emit("cce::printf(\" Source Shape: [%d, %d], Window Offsets: [%d, %d], Requested Shape: [%d, %d], " | 862 | codegen.Emit("cce::printf(\" Source Shape: [%d, %d], Window Offsets: [%d, %d], Requested Shape: [%d, %d], " |
| 852 | "Valid Shape: [%d, %d]\\n\", " + | 863 | "Valid Shape: [%d, %d]\\n\", " + |
| @@ -861,7 +872,7 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 861 | codegen.Emit(" for (int " + col_idx + " = 0; " + col_idx + " < " + valid_col + "; ++" + col_idx + ") {"); | 872 | codegen.Emit(" for (int " + col_idx + " = 0; " + col_idx + " < " + valid_col + "; ++" + col_idx + ") {"); |
| 862 | codegen.Emit(" " + dtype_str + " " + debug_val + " = *(__ws + (" + row_idx + " + (" + row_off + ")) * " + | 873 | codegen.Emit(" " + dtype_str + " " + debug_val + " = *(__ws + (" + row_idx + " + (" + row_off + ")) * " + |
| 863 | std::to_string(tile_cols->value_) + " + (" + col_idx + " + (" + col_off + ")));"); | 874 | std::to_string(tile_cols->value_) + " + (" + col_idx + " + (" + col_off + ")));"); |
| 864 | - codegen.Emit(" pto::PrintValue<pto::PrintFormat::Width8_Precision4>(" + debug_val + ", " + col_idx + ");"); | 875 | + codegen.Emit(" __pypto_print_val(" + debug_val + ");"); |
| 865 | codegen.Emit(" }"); | 876 | codegen.Emit(" }"); |
| 866 | codegen.Emit(" cce::printf(\"\\n\");"); | 877 | codegen.Emit(" cce::printf(\"\\n\");"); |
| 867 | codegen.Emit(" }"); | 878 | codegen.Emit(" }"); |
| @@ -921,7 +932,7 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 921 | codegen.Emit("if (" + valid_col + " > " + std::to_string(tile_cols->value_) + ") " + valid_col + " = " + | 932 | codegen.Emit("if (" + valid_col + " > " + std::to_string(tile_cols->value_) + ") " + valid_col + " = " + |
| 922 | std::to_string(tile_cols->value_) + ";"); | 933 | std::to_string(tile_cols->value_) + ";"); |
| 923 | codegen.Emit("cce::printf(\"=== [TPRINT Tile Window] Data Type: %s, Layout: %s, TileType: %s ===\\n\", " | 934 | codegen.Emit("cce::printf(\"=== [TPRINT Tile Window] Data Type: %s, Layout: %s, TileType: %s ===\\n\", " |
| 924 | - "pto::GetDTypeName<" + | 935 | + "__pypto_dtype_name<" + |
| 925 | codegen.GetTypeString(tile_type->dtype_) + | 936 | codegen.GetTypeString(tile_type->dtype_) + |
| 926 | ">(), pto::GetLayoutName(std::remove_reference_t<decltype(" + src + | 937 | ">(), pto::GetLayoutName(std::remove_reference_t<decltype(" + src + |
| 927 | ")>::BFractal, std::remove_reference_t<decltype(" + src + ")>::SFractal), \"Vec\");"); | 938 | ")>::BFractal, std::remove_reference_t<decltype(" + src + ")>::SFractal), \"Vec\");"); |
| @@ -935,7 +946,7 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 935 | codegen.Emit(" auto __debug_src_offset = pto::GetTileOffset<std::remove_reference_t<decltype(" + src + ")>>(" + | 946 | codegen.Emit(" auto __debug_src_offset = pto::GetTileOffset<std::remove_reference_t<decltype(" + src + ")>>(" + |
| 936 | row_idx + " + (" + row_off + "), " + col_idx + " + (" + col_off + "));"); | 947 | row_idx + " + (" + row_off + "), " + col_idx + " + (" + col_off + "));"); |
| 937 | codegen.Emit(" auto " + debug_val + " = " + src + ".data()[__debug_src_offset];"); | 948 | codegen.Emit(" auto " + debug_val + " = " + src + ".data()[__debug_src_offset];"); |
| 938 | - codegen.Emit(" pto::PrintValue<pto::PrintFormat::Width8_Precision4>(" + debug_val + ", " + col_idx + ");"); | 949 | + codegen.Emit(" __pypto_print_val(" + debug_val + ");"); |
| 939 | codegen.Emit(" }"); | 950 | codegen.Emit(" }"); |
| 940 | codegen.Emit(" cce::printf(\"\\n\");"); | 951 | codegen.Emit(" cce::printf(\"\\n\");"); |
| 941 | codegen.Emit("}"); | 952 | codegen.Emit("}"); |
| @@ -530,6 +530,7 @@ std::string CCECodegen::GenerateSingle(const ir::ProgramPtr& program, const std: | |||
| 530 | emitter_.EmitLine("#if defined(__DAV_VEC__)"); | 530 | emitter_.EmitLine("#if defined(__DAV_VEC__)"); |
| 531 | } | 531 | } |
| 532 | EmitStructTypes(); | 532 | EmitStructTypes(); |
| 533 | + emitter_.EmitLine("#include <pypto_tprint.h>"); | ||
| 533 | emitter_.EmitRaw(function_code); | 534 | emitter_.EmitRaw(function_code); |
| 534 | emitter_.EmitLine("#endif"); | 535 | emitter_.EmitLine("#endif"); |
| 535 | 536 | ||
| @@ -1255,7 +1255,8 @@ TEST(BackendCceOpsTest, DebugDumpTileFullAndWindow) | |||
| 1255 | EXPECT_NE(generated.find("[TPRINT Tile Window]"), std::string::npos); | 1255 | EXPECT_NE(generated.find("[TPRINT Tile Window]"), std::string::npos); |
| 1256 | EXPECT_NE(generated.find("tile.GetValidRow() - (2)"), std::string::npos); | 1256 | EXPECT_NE(generated.find("tile.GetValidRow() - (2)"), std::string::npos); |
| 1257 | EXPECT_NE(generated.find("pto::GetTileOffset<std::remove_reference_t<decltype(tile)>>"), std::string::npos); | 1257 | EXPECT_NE(generated.find("pto::GetTileOffset<std::remove_reference_t<decltype(tile)>>"), std::string::npos); |
| 1258 | - EXPECT_NE(generated.find("pto::PrintValue<pto::PrintFormat::Width8_Precision4>"), std::string::npos); | 1258 | + EXPECT_NE(generated.find("__pypto_dtype_name"), std::string::npos); |
| 1259 | + EXPECT_NE(generated.find("__pypto_print_val"), std::string::npos); | ||
| 1259 | } | 1260 | } |
| 1260 | 1261 | ||
| 1261 | TEST(BackendCceOpsTest, DebugDumpAccTileUsesWorkspace) | 1262 | TEST(BackendCceOpsTest, DebugDumpAccTileUsesWorkspace) |
| @@ -1275,7 +1276,8 @@ TEST(BackendCceOpsTest, DebugDumpAccTileUsesWorkspace) | |||
| 1275 | EXPECT_NE(generated.find("reinterpret_cast<__gm__"), std::string::npos); | 1276 | EXPECT_NE(generated.find("reinterpret_cast<__gm__"), std::string::npos); |
| 1276 | EXPECT_NE(generated.find("workspace_ptr"), std::string::npos); | 1277 | EXPECT_NE(generated.find("workspace_ptr"), std::string::npos); |
| 1277 | EXPECT_NE(generated.find("[TPRINT Acc Tile Window]"), std::string::npos); | 1278 | EXPECT_NE(generated.find("[TPRINT Acc Tile Window]"), std::string::npos); |
| 1278 | - EXPECT_NE(generated.find("pto::PrintValue<pto::PrintFormat::Width8_Precision4>"), std::string::npos); | 1279 | + EXPECT_NE(generated.find("__pypto_dtype_name"), std::string::npos); |
| 1280 | + EXPECT_NE(generated.find("__pypto_print_val"), std::string::npos); | ||
| 1279 | } | 1281 | } |
| 1280 | 1282 | ||
| 1281 | TEST(BackendCceOpsTest, DebugPrintfExpandsUnsigned64BitValues) | 1283 | TEST(BackendCceOpsTest, DebugPrintfExpandsUnsigned64BitValues) |
| @@ -95,7 +95,7 @@ packages.find.include = [ | |||
| 95 | 95 | ||
| 96 | # 保留 package-data,确保目录下的 .so/.h 等文件被包含 | 96 | # 保留 package-data,确保目录下的 .so/.h 等文件被包含 |
| 97 | include-package-data = true | 97 | include-package-data = true |
| 98 | -package-data = { "pypto" = ["lib/**/*", "include/**/*"] } | 98 | +package-data = { "pypto" = ["lib/**/*", "include/**/*"], "pypto_pro" = ["include/*"] } |
| 99 | zip-safe = false | 99 | zip-safe = false |
| 100 | 100 | ||
| 101 | [tool.ruff] | 101 | [tool.ruff] |
| @@ -8,8 +8,19 @@ | |||
| 8 | * See LICENSE in the root of the software repository for the full text of the License. | 8 | * See LICENSE in the root of the software repository for the full text of the License. |
| 9 | */ | 9 | */ |
| 10 | 10 | ||
| 11 | -// Binary-mode TPRINT implementation using AscendC::printf (replaces pto-isa's _DEBUG-guarded TPRINT). | 11 | +// Binary-mode TPRINT implementation using cce::printf (replaces pto-isa's _DEBUG-guarded TPRINT). |
| 12 | #pragma once | 12 | #pragma once |
| 13 | +#include <cstdint> | ||
| 14 | +// cce::printf is only declared by the toolchain when the print mode is enabled (jit emits | ||
| 15 | +// -DPTOAS_ENABLE_CCE_PRINT=1 only for kernels that actually print). Kernels without dump | ||
| 16 | +// calls keep a no-op macro so the header compiles in plain mode too. | ||
| 17 | +#ifndef __PYPTO_PRINTF | ||
| 18 | +#if defined(PTOAS_ENABLE_CCE_PRINT) && PTOAS_ENABLE_CCE_PRINT | ||
| 19 | +#define __PYPTO_PRINTF(...) cce::printf(__VA_ARGS__) | ||
| 20 | +#else | ||
| 21 | +#define __PYPTO_PRINTF(...) ((void)0) | ||
| 22 | +#endif | ||
| 23 | +#endif | ||
| 13 | template <typename V> | 24 | template <typename V> |
| 14 | __aicore__ inline const __gm__ char* __pypto_dtype_name() | 25 | __aicore__ inline const __gm__ char* __pypto_dtype_name() |
| 15 | { | 26 | { |
| @@ -60,22 +71,22 @@ template <typename V> | |||
| 60 | __aicore__ inline void __pypto_print_val(V val) | 71 | __aicore__ inline void __pypto_print_val(V val) |
| 61 | { | 72 | { |
| 62 | if constexpr (std::is_same_v<V, float>) { | 73 | if constexpr (std::is_same_v<V, float>) { |
| 63 | - AscendC::printf("%f ", val); | 74 | + __PYPTO_PRINTF("%f ", val); |
| 64 | } else if constexpr (std::is_same_v<V, half>) { | 75 | } else if constexpr (std::is_same_v<V, half>) { |
| 65 | - AscendC::printf("%f ", (float)val); | 76 | + __PYPTO_PRINTF("%f ", (float)val); |
| 66 | } else if constexpr (std::is_signed_v<V>) { | 77 | } else if constexpr (std::is_signed_v<V>) { |
| 67 | - AscendC::printf("%d ", (int)val); | 78 | + __PYPTO_PRINTF("%d ", (int)val); |
| 68 | } else if constexpr (std::is_unsigned_v<V>) { | 79 | } else if constexpr (std::is_unsigned_v<V>) { |
| 69 | - AscendC::printf("%u ", (unsigned int)val); | 80 | + __PYPTO_PRINTF("%u ", (unsigned int)val); |
| 70 | } else if constexpr (sizeof(V) == 2) { | 81 | } else if constexpr (sizeof(V) == 2) { |
| 71 | // bf16: upper 16 bits of float32 | 82 | // bf16: upper 16 bits of float32 |
| 72 | uint32_t fbits = (uint32_t)(*(uint16_t*)&val) << 16; | 83 | uint32_t fbits = (uint32_t)(*(uint16_t*)&val) << 16; |
| 73 | - AscendC::printf("%f ", *(float*)&fbits); | 84 | + __PYPTO_PRINTF("%f ", *(float*)&fbits); |
| 74 | } else if constexpr (sizeof(V) == 1) { | 85 | } else if constexpr (sizeof(V) == 1) { |
| 75 | // fp8: print raw byte value | 86 | // fp8: print raw byte value |
| 76 | - AscendC::printf("%u ", (unsigned int)(*(uint8_t*)&val)); | 87 | + __PYPTO_PRINTF("%u ", (unsigned int)(*(uint8_t*)&val)); |
| 77 | } else { | 88 | } else { |
| 78 | - AscendC::printf("? "); | 89 | + __PYPTO_PRINTF("? "); |
| 79 | } | 90 | } |
| 80 | } | 91 | } |
| 81 | 92 | ||
| @@ -92,25 +103,25 @@ __aicore__ inline void __pypto_tprint(T& src) | |||
| 92 | } | 103 | } |
| 93 | auto* dataPtr = src.data(); | 104 | auto* dataPtr = src.data(); |
| 94 | if constexpr (T::layout == pto::Layout::ND || T::layout == pto::Layout::DN) { | 105 | if constexpr (T::layout == pto::Layout::ND || T::layout == pto::Layout::DN) { |
| 95 | - AscendC::printf("=== [dump_tensor] dtype: %s, Layout: %s, shape=[%d,%d,%d,%d,%d] ===\n", | 106 | + __PYPTO_PRINTF("=== [dump_tensor] dtype: %s, Layout: %s, shape=[%d,%d,%d,%d,%d] ===\n", |
| 96 | __pypto_dtype_name<ElemType>(), T::layout == pto::Layout::ND ? "ND" : "DN", n[0], n[1], | 107 | __pypto_dtype_name<ElemType>(), T::layout == pto::Layout::ND ? "ND" : "DN", n[0], n[1], |
| 97 | n[2], n[3], n[4]); | 108 | n[2], n[3], n[4]); |
| 98 | for (int i0 = 0; i0 < n[0]; ++i0) | 109 | for (int i0 = 0; i0 < n[0]; ++i0) |
| 99 | for (int i1 = 0; i1 < n[1]; ++i1) | 110 | for (int i1 = 0; i1 < n[1]; ++i1) |
| 100 | for (int i2 = 0; i2 < n[2]; ++i2) { | 111 | for (int i2 = 0; i2 < n[2]; ++i2) { |
| 101 | - AscendC::printf(" Batch [%d, %d, %d]:\n", i0, i1, i2); | 112 | + __PYPTO_PRINTF(" Batch [%d, %d, %d]:\n", i0, i1, i2); |
| 102 | for (int r = 0; r < n[3]; ++r) { | 113 | for (int r = 0; r < n[3]; ++r) { |
| 103 | for (int c = 0; c < n[4]; ++c) { | 114 | for (int c = 0; c < n[4]; ++c) { |
| 104 | int64_t off = (int64_t)i0 * s[0] + i1 * s[1] + i2 * s[2] + r * s[3] + c * s[4]; | 115 | int64_t off = (int64_t)i0 * s[0] + i1 * s[1] + i2 * s[2] + r * s[3] + c * s[4]; |
| 105 | __pypto_print_val(dataPtr[off]); | 116 | __pypto_print_val(dataPtr[off]); |
| 106 | } | 117 | } |
| 107 | - AscendC::printf("\n"); | 118 | + __PYPTO_PRINTF("\n"); |
| 108 | } | 119 | } |
| 109 | } | 120 | } |
| 110 | } else if constexpr (T::layout == pto::Layout::NZ) { | 121 | } else if constexpr (T::layout == pto::Layout::NZ) { |
| 111 | int logical_rows = n[2] * n[3]; | 122 | int logical_rows = n[2] * n[3]; |
| 112 | int logical_cols = n[1] * n[4]; | 123 | int logical_cols = n[1] * n[4]; |
| 113 | - AscendC::printf("=== [dump_tensor] dtype: %s, Layout: NZ, logical shape=[%d,%d] ===\n", | 124 | + __PYPTO_PRINTF("=== [dump_tensor] dtype: %s, Layout: NZ, logical shape=[%d,%d] ===\n", |
| 114 | __pypto_dtype_name<ElemType>(), logical_rows, logical_cols); | 125 | __pypto_dtype_name<ElemType>(), logical_rows, logical_cols); |
| 115 | for (int r = 0; r < logical_rows; ++r) { | 126 | for (int r = 0; r < logical_rows; ++r) { |
| 116 | for (int c = 0; c < logical_cols; ++c) { | 127 | for (int c = 0; c < logical_cols; ++c) { |
| @@ -119,14 +130,14 @@ __aicore__ inline void __pypto_tprint(T& src) | |||
| 119 | int64_t off = (int64_t)br * s[2] + bc * s[1] + ir * s[3] + ic * s[4]; | 130 | int64_t off = (int64_t)br * s[2] + bc * s[1] + ir * s[3] + ic * s[4]; |
| 120 | __pypto_print_val(dataPtr[off]); | 131 | __pypto_print_val(dataPtr[off]); |
| 121 | } | 132 | } |
| 122 | - AscendC::printf("\n"); | 133 | + __PYPTO_PRINTF("\n"); |
| 123 | } | 134 | } |
| 124 | } | 135 | } |
| 125 | } else if constexpr (pto::is_tile<T>::value) { | 136 | } else if constexpr (pto::is_tile<T>::value) { |
| 126 | using DType = typename T::DType; | 137 | using DType = typename T::DType; |
| 127 | int validRows = src.GetValidRow(); | 138 | int validRows = src.GetValidRow(); |
| 128 | int validCols = src.GetValidCol(); | 139 | int validCols = src.GetValidCol(); |
| 129 | - AscendC::printf("=== [dump_tile] dtype: %s, shape=[%d,%d], valid=[%d,%d], Layout: %s ===\n", | 140 | + __PYPTO_PRINTF("=== [dump_tile] dtype: %s, shape=[%d,%d], valid=[%d,%d], Layout: %s ===\n", |
| 130 | __pypto_dtype_name<DType>(), T::Rows, T::Cols, validRows, validCols, | 141 | __pypto_dtype_name<DType>(), T::Rows, T::Cols, validRows, validCols, |
| 131 | pto::GetLayoutName(T::BFractal, T::SFractal)); | 142 | pto::GetLayoutName(T::BFractal, T::SFractal)); |
| 132 | for (int r = 0; r < T::Rows; ++r) { | 143 | for (int r = 0; r < T::Rows; ++r) { |
| @@ -134,11 +145,11 @@ __aicore__ inline void __pypto_tprint(T& src) | |||
| 134 | int off = (T::BFractal == pto::BLayout::RowMajor) ? r * T::Cols + c : c * T::Rows + r; | 145 | int off = (T::BFractal == pto::BLayout::RowMajor) ? r * T::Cols + c : c * T::Rows + r; |
| 135 | __pypto_print_val(src.GetValue(off)); | 146 | __pypto_print_val(src.GetValue(off)); |
| 136 | if (c == validCols - 1 && validCols < T::Cols) | 147 | if (c == validCols - 1 && validCols < T::Cols) |
| 137 | - AscendC::printf("| "); | 148 | + __PYPTO_PRINTF("| "); |
| 138 | } | 149 | } |
| 139 | - AscendC::printf("\n"); | 150 | + __PYPTO_PRINTF("\n"); |
| 140 | if (r == validRows - 1 && validRows < T::Rows) | 151 | if (r == validRows - 1 && validRows < T::Rows) |
| 141 | - AscendC::printf("--------\n"); | 152 | + __PYPTO_PRINTF("--------\n"); |
| 142 | } | 153 | } |
| 143 | } | 154 | } |
| 144 | } | 155 | } |
| @@ -192,6 +192,7 @@ def dump_tensor( | |||
| 192 | shapes: Sequence[int | Expr] | _ir_core.MakeTuple | None = None, | 192 | shapes: Sequence[int | Expr] | _ir_core.MakeTuple | None = None, |
| 193 | loc: bool = False, | 193 | loc: bool = False, |
| 194 | span: Span | None = None, | 194 | span: Span | None = None, |
| 195 | + flag: str | None = None, | ||
| 195 | ) -> Call: | 196 | ) -> Call: |
| 196 | """Print a tensor or tensor window for debugging. | 197 | """Print a tensor or tensor window for debugging. |
| 197 | 198 | ||
| @@ -209,6 +210,8 @@ def dump_tensor( | |||
| 209 | """ | 210 | """ |
| 210 | actual_span = _get_span_or_capture(span) | 211 | actual_span = _get_span_or_capture(span) |
| 211 | show_location = _normalize_location_flag(loc, "dump_tensor") | 212 | show_location = _normalize_location_flag(loc, "dump_tensor") |
| 213 | + if flag is not None and not isinstance(flag, str): | ||
| 214 | + raise TypeError(f"debug.dump_tensor requires str flag, but got {type(flag).__name__}") | ||
| 212 | tensor_type = tensor.type | 215 | tensor_type = tensor.type |
| 213 | if not isinstance(tensor_type, TensorType): | 216 | if not isinstance(tensor_type, TensorType): |
| 214 | raise TypeError(f"debug.dump_tensor requires TensorType input, but got {type(tensor_type).__name__}") | 217 | raise TypeError(f"debug.dump_tensor requires TensorType input, but got {type(tensor_type).__name__}") |
| @@ -244,10 +247,13 @@ def dump_tensor( | |||
| 244 | if isinstance(shape_expr, ConstInt) and shape_expr.value <= 0: | 247 | if isinstance(shape_expr, ConstInt) and shape_expr.value <= 0: |
| 245 | raise ValueError(f"debug.dump_tensor shape at axis {idx} must be positive, got {shape_expr.value}") | 248 | raise ValueError(f"debug.dump_tensor shape at axis {idx} must be positive, got {shape_expr.value}") |
| 246 | 249 | ||
| 250 | + dump_kwargs: dict[str, Any] = {"show_location": show_location} | ||
| 251 | + if flag: | ||
| 252 | + dump_kwargs["dump_flag"] = flag | ||
| 247 | return _ir_core.create_op_call( | 253 | return _ir_core.create_op_call( |
| 248 | "debug.dump_tensor", | 254 | "debug.dump_tensor", |
| 249 | [tensor, offsets_tuple, shapes_tuple], | 255 | [tensor, offsets_tuple, shapes_tuple], |
| 250 | - {"show_location": show_location}, | 256 | + dump_kwargs, |
| 251 | actual_span, | 257 | actual_span, |
| 252 | ) | 258 | ) |
| 253 | 259 | ||
| @@ -275,6 +281,8 @@ def dump_tile( | |||
| 275 | workspace: Expr | None = None, | 281 | workspace: Expr | None = None, |
| 276 | loc: bool = False, | 282 | loc: bool = False, |
| 277 | span: Span | None = None, | 283 | span: Span | None = None, |
| 284 | + section: _ir_core.SectionKind | None = None, | ||
| 285 | + flag: str | None = None, | ||
| 278 | ) -> Call: | 286 | ) -> Call: |
| 279 | """Print a tile or tile window for debugging. | 287 | """Print a tile or tile window for debugging. |
| 280 | 288 | ||
| @@ -297,9 +305,13 @@ def dump_tile( | |||
| 297 | """ | 305 | """ |
| 298 | actual_span = _get_span_or_capture(span) | 306 | actual_span = _get_span_or_capture(span) |
| 299 | show_location = _normalize_location_flag(loc, "dump_tile") | 307 | show_location = _normalize_location_flag(loc, "dump_tile") |
| 308 | + if flag is not None and not isinstance(flag, str): | ||
| 309 | + raise TypeError(f"debug.dump_tile requires str flag, but got {type(flag).__name__}") | ||
| 300 | tile_type = tile.type | 310 | tile_type = tile.type |
| 301 | if not isinstance(tile_type, TileType): | 311 | if not isinstance(tile_type, TileType): |
| 302 | raise TypeError(f"debug.dump_tile requires TileType input, but got {type(tile_type).__name__}") | 312 | raise TypeError(f"debug.dump_tile requires TileType input, but got {type(tile_type).__name__}") |
| 313 | + if section is not None: | ||
| 314 | + _validate_dump_memory_section(tile_type, section, actual_span) | ||
| 303 | if (offsets is None) != (shapes is None): | 315 | if (offsets is None) != (shapes is None): |
| 304 | raise ValueError("debug.dump_tile offsets and shapes must be provided together") | 316 | raise ValueError("debug.dump_tile offsets and shapes must be provided together") |
| 305 | 317 | ||
| @@ -309,6 +321,9 @@ def dump_tile( | |||
| 309 | raise TypeError(f"debug.dump_tile workspace must be TensorType, but got {type(ws_type).__name__}") | 321 | raise TypeError(f"debug.dump_tile workspace must be TensorType, but got {type(ws_type).__name__}") |
| 310 | 322 | ||
| 311 | rank = len(tile_type.shape) | 323 | rank = len(tile_type.shape) |
| 324 | + dump_kwargs: dict[str, Any] = {"show_location": show_location} | ||
| 325 | + if flag: | ||
| 326 | + dump_kwargs["dump_flag"] = flag | ||
| 312 | if workspace is not None: | 327 | if workspace is not None: |
| 313 | if offsets is None and shapes is None: | 328 | if offsets is None and shapes is None: |
| 314 | offsets_tuple = _to_make_tuple([0] * rank, actual_span) | 329 | offsets_tuple = _to_make_tuple([0] * rank, actual_span) |
| @@ -320,12 +335,12 @@ def dump_tile( | |||
| 320 | return _ir_core.create_op_call( | 335 | return _ir_core.create_op_call( |
| 321 | "debug.dump_tile", | 336 | "debug.dump_tile", |
| 322 | [tile, offsets_tuple, shapes_tuple, workspace], | 337 | [tile, offsets_tuple, shapes_tuple, workspace], |
| 323 | - {"show_location": show_location}, | 338 | + dump_kwargs, |
| 324 | actual_span, | 339 | actual_span, |
| 325 | ) | 340 | ) |
| 326 | 341 | ||
| 327 | if offsets is None and shapes is None: | 342 | if offsets is None and shapes is None: |
| 328 | - return _ir_core.create_op_call("debug.dump_tile", [tile], {"show_location": show_location}, actual_span) | 343 | + return _ir_core.create_op_call("debug.dump_tile", [tile], dict(dump_kwargs), actual_span) |
| 329 | 344 | ||
| 330 | offsets_tuple = _to_make_tuple(offsets, actual_span) | 345 | offsets_tuple = _to_make_tuple(offsets, actual_span) |
| 331 | shapes_tuple = _to_make_tuple(shapes, actual_span) | 346 | shapes_tuple = _to_make_tuple(shapes, actual_span) |
| @@ -334,11 +349,50 @@ def dump_tile( | |||
| 334 | return _ir_core.create_op_call( | 349 | return _ir_core.create_op_call( |
| 335 | "debug.dump_tile", | 350 | "debug.dump_tile", |
| 336 | [tile, offsets_tuple, shapes_tuple], | 351 | [tile, offsets_tuple, shapes_tuple], |
| 337 | - {"show_location": show_location}, | 352 | + dict(dump_kwargs), |
| 338 | actual_span, | 353 | actual_span, |
| 339 | ) | 354 | ) |
| 340 | 355 | ||
| 341 | 356 | ||
| 357 | +def _validate_dump_memory_section(data_type, section, span: Span | None = None) -> None: | ||
| 358 | + """Validate that dumping ``data_type`` is legal in ``section``. | ||
| 359 | + | ||
| 360 | + GM tensors may be dumped from either section; on-chip tiles must live in | ||
| 361 | + Vec (UB) inside a Vector section and Acc (L0C) inside a Cube section. | ||
| 362 | + """ | ||
| 363 | + if isinstance(data_type, TensorType): | ||
| 364 | + return | ||
| 365 | + if not isinstance(data_type, TileType): | ||
| 366 | + return | ||
| 367 | + mem = getattr(data_type, "target_memory", None) | ||
| 368 | + if mem is None and data_type.memref is not None: | ||
| 369 | + mem = data_type.memref.memory_space_ | ||
| 370 | + if mem is None: | ||
| 371 | + return | ||
| 372 | + if section == _ir_core.SectionKind.Vector: | ||
| 373 | + if mem == _ir_core.MemorySpace.Vec: | ||
| 374 | + return | ||
| 375 | + from pypto_pro.language.parser.diagnostics import ParserSyntaxError | ||
| 376 | + | ||
| 377 | + raise ParserSyntaxError( | ||
| 378 | + f"pl.dump_data of a {mem.name} tile is not allowed in a Vector section; " | ||
| 379 | + "only Vec (UB) tiles (and GM tensors) can be dumped there", | ||
| 380 | + span=span, | ||
| 381 | + hint="Move pl.dump_data into a 'with pl.section_cube():' block, or dump a Vec/UB tile.", | ||
| 382 | + ) | ||
| 383 | + if section == _ir_core.SectionKind.Cube: | ||
| 384 | + if mem == _ir_core.MemorySpace.Acc: | ||
| 385 | + return | ||
| 386 | + from pypto_pro.language.parser.diagnostics import ParserSyntaxError | ||
| 387 | + | ||
| 388 | + raise ParserSyntaxError( | ||
| 389 | + f"pl.dump_data of a {mem.name} tile is not allowed in a Cube section; " | ||
| 390 | + "only Acc (L0C) tiles (and GM tensors) can be dumped there", | ||
| 391 | + span=span, | ||
| 392 | + hint="Move pl.dump_data into a 'with pl.section_vector():' block, or dump an Acc/L0C tile.", | ||
| 393 | + ) | ||
| 394 | + | ||
| 395 | + | ||
| 342 | def dump_data( | 396 | def dump_data( |
| 343 | data: Expr, | 397 | data: Expr, |
| 344 | offsets: Sequence[int | Expr] | _ir_core.MakeTuple | None = None, | 398 | offsets: Sequence[int | Expr] | _ir_core.MakeTuple | None = None, |
| @@ -346,6 +400,8 @@ def dump_data( | |||
| 346 | workspace: Expr | None = None, | 400 | workspace: Expr | None = None, |
| 347 | loc: bool = False, | 401 | loc: bool = False, |
| 348 | span: Span | None = None, | 402 | span: Span | None = None, |
| 403 | + section: _ir_core.SectionKind | None = None, | ||
| 404 | + flag: str | None = None, | ||
| 349 | ) -> Call: | 405 | ) -> Call: |
| 350 | """Unified debug dump entry — dispatches to dump_tensor or dump_tile based on input type. | 406 | """Unified debug dump entry — dispatches to dump_tensor or dump_tile based on input type. |
| 351 | 407 | ||
| @@ -355,12 +411,14 @@ def dump_data( | |||
| 355 | All parameters are forwarded to the underlying function unchanged. | 411 | All parameters are forwarded to the underlying function unchanged. |
| 356 | """ | 412 | """ |
| 357 | data_type = data.type | 413 | data_type = data.type |
| 414 | + if flag is not None and not isinstance(flag, str): | ||
| 415 | + raise TypeError(f"debug.dump_data requires str flag, but got {type(flag).__name__}") | ||
| 358 | if isinstance(data_type, TensorType): | 416 | if isinstance(data_type, TensorType): |
| 359 | if workspace is not None: | 417 | if workspace is not None: |
| 360 | raise ValueError("debug.dump_data: workspace is only valid for Tile inputs, not Tensor") | 418 | raise ValueError("debug.dump_data: workspace is only valid for Tile inputs, not Tensor") |
| 361 | - return dump_tensor(data, offsets, shapes, loc=loc, span=span) | 419 | + return dump_tensor(data, offsets, shapes, loc=loc, span=span, flag=flag) |
| 362 | elif isinstance(data_type, TileType): | 420 | elif isinstance(data_type, TileType): |
| 363 | - return dump_tile(data, offsets, shapes, workspace=workspace, loc=loc, span=span) | 421 | + return dump_tile(data, offsets, shapes, workspace=workspace, loc=loc, span=span, section=section, flag=flag) |
| 364 | else: | 422 | else: |
| 365 | raise TypeError(f"debug.dump_data requires Tensor or Tile input, but got {type(data_type).__name__}") | 423 | raise TypeError(f"debug.dump_data requires Tensor or Tile input, but got {type(data_type).__name__}") |
| 366 | 424 | ||
| @@ -442,12 +500,19 @@ def trap(*, span: Span | None = None) -> Call: | |||
| 442 | register_table( | 500 | register_table( |
| 443 | { | 501 | { |
| 444 | "printf": OpSpec(builder=printf), | 502 | "printf": OpSpec(builder=printf), |
| 445 | - "dump_data": OpSpec(builder=dump_data), | ||
| 446 | "trap": OpSpec(builder=trap), | 503 | "trap": OpSpec(builder=trap), |
| 447 | } | 504 | } |
| 448 | ) | 505 | ) |
| 449 | 506 | ||
| 450 | 507 | ||
| 508 | +@op_impl("dump_data") | ||
| 509 | +def _parse_dump_data(self, call: ast.Call): | ||
| 510 | + span = self.span_tracker.get_span(call) | ||
| 511 | + args = [self.parse_expression(a) for a in call.args] | ||
| 512 | + kwargs = self.parse_op_kwargs(call) | ||
| 513 | + return dump_data(*args, section=self.target, **kwargs, span=span) | ||
| 514 | + | ||
| 515 | + | ||
| 451 | @op_impl("pto_assert") | 516 | @op_impl("pto_assert") |
| 452 | def _parse_pto_assert(self, call: ast.Call): | 517 | def _parse_pto_assert(self, call: ast.Call): |
| 453 | span = self.span_tracker.get_span(call) | 518 | span = self.span_tracker.get_span(call) |
| @@ -939,6 +939,7 @@ def dump_data( | |||
| 939 | *, | 939 | *, |
| 940 | workspace: Optional[Tensor] = None, | 940 | workspace: Optional[Tensor] = None, |
| 941 | loc: bool = False, | 941 | loc: bool = False, |
| 942 | + flag: Optional[str] = None, | ||
| 942 | ) -> None: | 943 | ) -> None: |
| 943 | """Print Tensor or Tile contents for debugging. | 944 | """Print Tensor or Tile contents for debugging. |
| 944 | 945 | ||
| @@ -953,6 +954,8 @@ def dump_data( | |||
| 953 | workspace: GM Tensor used as temporary space (only valid for Acc Tile inputs, | 954 | workspace: GM Tensor used as temporary space (only valid for Acc Tile inputs, |
| 954 | size >= tile_numel * sizeof(element_type)) | 955 | size >= tile_numel * sizeof(element_type)) |
| 955 | loc: Show source location | 956 | loc: Show source location |
| 957 | + flag: Optional compile-time string label printed as a standalone marker line | ||
| 958 | + before the dump output, to distinguish multiple dump sites | ||
| 956 | """ | 959 | """ |
| 957 | 960 | ||
| 958 | 961 | ||
| @@ -15,6 +15,7 @@ from __future__ import annotations | |||
| 15 | 15 | ||
| 16 | from collections.abc import Mapping | 16 | from collections.abc import Mapping |
| 17 | from dataclasses import dataclass | 17 | from dataclasses import dataclass |
| 18 | +import os | ||
| 18 | 19 | ||
| 19 | CCE_BACKEND = "cce" | 20 | CCE_BACKEND = "cce" |
| 20 | 21 | ||
| @@ -77,7 +78,12 @@ class JitCompileConfig: | |||
| 77 | 78 | ||
| 78 | def runtime_include_flags(self, ascend_home_path: str) -> list[str]: | 79 | def runtime_include_flags(self, ascend_home_path: str) -> list[str]: |
| 79 | variables = {"ascend_home": ascend_home_path} | 80 | variables = {"ascend_home": ascend_home_path} |
| 80 | - return [f"-I{include_dir}" for include_dir in self._format_values(self.runtime_include_dirs, variables)] | 81 | + flags = [f"-I{include_dir}" for include_dir in self._format_values(self.runtime_include_dirs, variables)] |
| 82 | + import pypto_pro | ||
| 83 | + | ||
| 84 | + pypto_include = os.path.join(os.path.dirname(pypto_pro.__file__), "include") | ||
| 85 | + flags.append(f"-I{pypto_include}") | ||
| 86 | + return flags | ||
| 81 | 87 | ||
| 82 | def runtime_link_args(self, ascend_home_path: str) -> list[str]: | 88 | def runtime_link_args(self, ascend_home_path: str) -> list[str]: |
| 83 | variables = {"ascend_home": ascend_home_path} | 89 | variables = {"ascend_home": ascend_home_path} |
| @@ -196,6 +196,45 @@ def _signature_parts(entry_params): | |||
| 196 | return ", ".join(decls), names | 196 | return ", ".join(decls), names |
| 197 | 197 | ||
| 198 | 198 | ||
| 199 | +def _write_ascendc_tprint_header(kernel_meta_dir: str) -> None: | ||
| 200 | + """Write a no-prefix AscendC dump copy of pypto_tprint.h next to the impl source. | ||
| 201 | + | ||
| 202 | + The shared header (included by default from codegen) prints via cce::printf | ||
| 203 | + (jit-mode compatible), but the OPC toolchain swallows cce::printf output and | ||
| 204 | + AscendC::printf prepends a "[AIV Block x/y]" dumphead. The local copy remaps | ||
| 205 | + __PYPTO_PRINTF to a wrapper around __asc_aicore::scalar_printf_impl with an | ||
| 206 | + empty dumphead; it is included by a quoted name so the impl resolves it ahead | ||
| 207 | + of the packaged header. | ||
| 208 | + """ | ||
| 209 | + jit_macro_def = ( | ||
| 210 | + "#ifndef __PYPTO_PRINTF\n" | ||
| 211 | + "#if defined(PTOAS_ENABLE_CCE_PRINT) && PTOAS_ENABLE_CCE_PRINT\n" | ||
| 212 | + "#define __PYPTO_PRINTF(...) cce::printf(__VA_ARGS__)\n" | ||
| 213 | + "#else\n" | ||
| 214 | + "#define __PYPTO_PRINTF(...) ((void)0)\n" | ||
| 215 | + "#endif\n" | ||
| 216 | + "#endif\n" | ||
| 217 | + ) | ||
| 218 | + opc_macro_def = ( | ||
| 219 | + "#ifndef __PYPTO_PRINTF\n" | ||
| 220 | + "template <class... Args>\n" | ||
| 221 | + "__aicore__ inline void __pypto_aicore_printf(const __gm__ char* fmt, Args&&... args)\n" | ||
| 222 | + "{\n" | ||
| 223 | + " __asc_aicore::enable_asc_diagnostics();\n" | ||
| 224 | + " __asc_aicore::scalar_printf_impl(__asc_aicore::DumpType::DUMP_SCALAR, fmt, \"\", args...);\n" | ||
| 225 | + "}\n" | ||
| 226 | + "#define __PYPTO_PRINTF(...) __pypto_aicore_printf(__VA_ARGS__)\n" | ||
| 227 | + "#endif\n" | ||
| 228 | + ) | ||
| 229 | + src_header = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "include", "pypto_tprint.h") | ||
| 230 | + tprint_content = open(src_header, "r", encoding="utf-8").read() | ||
| 231 | + tprint_content = tprint_content.replace(jit_macro_def, opc_macro_def) | ||
| 232 | + dst_header = os.path.join(kernel_meta_dir, "pypto_tprint.h") | ||
| 233 | + if not os.path.exists(dst_header) or open(dst_header, "r", encoding="utf-8").read() != tprint_content: | ||
| 234 | + with open(dst_header, "w", encoding="utf-8") as f: | ||
| 235 | + f.write(tprint_content) | ||
| 236 | + | ||
| 237 | + | ||
| 199 | def _gen_infer_cpp(cg, tilingkey_header: str, kernel_cpp: str) -> str: | 238 | def _gen_infer_cpp(cg, tilingkey_header: str, kernel_cpp: str) -> str: |
| 200 | sig, names = _signature_parts(cg.entry_params) | 239 | sig, names = _signature_parts(cg.entry_params) |
| 201 | ws_idx = len(names) - 2 if len(names) >= 2 else None | 240 | ws_idx = len(names) - 2 if len(names) >= 2 else None |
| @@ -207,10 +246,24 @@ def _gen_infer_cpp(cg, tilingkey_header: str, kernel_cpp: str) -> str: | |||
| 207 | f" AscendC::SetSysWorkspaceForce({ws});\n GM_ADDR usrWorkspace = AscendC::GetUserWorkspace({ws});\n" | 246 | f" AscendC::SetSysWorkspaceForce({ws});\n GM_ADDR usrWorkspace = AscendC::GetUserWorkspace({ws});\n" |
| 208 | ) | 247 | ) |
| 209 | inner[ws_idx] = "usrWorkspace" | 248 | inner[ws_idx] = "usrWorkspace" |
| 249 | + # The infer source is only compiled to extract tiling metadata, so the dump | ||
| 250 | + # helpers are replaced with no-op stubs and the header include is dropped. | ||
| 251 | + # This keeps the infer source self-contained (no pypto_tprint.h dependency). | ||
| 252 | + infer_kernel_cpp = kernel_cpp.replace( | ||
| 253 | + "#include <pypto_tprint.h>\n", "" | ||
| 254 | + ) | ||
| 255 | + tprint_stubs = ( | ||
| 256 | + "#define TPRINT(x)\n" | ||
| 257 | + "template <typename T>\n" | ||
| 258 | + "__aicore__ inline const __gm__ char* __pypto_dtype_name() { return \"\"; }\n" | ||
| 259 | + "template <typename V>\n" | ||
| 260 | + "__aicore__ inline void __pypto_print_val(V) {}\n" | ||
| 261 | + ) | ||
| 210 | return ( | 262 | return ( |
| 211 | '#include "kernel_operator.h"\n' | 263 | '#include "kernel_operator.h"\n' |
| 212 | f'#include "{tilingkey_header}"\n' | 264 | f'#include "{tilingkey_header}"\n' |
| 213 | - f"{kernel_cpp}\n" | 265 | + f"{tprint_stubs}" |
| 266 | + f"{infer_kernel_cpp}\n" | ||
| 214 | f'extern "C" __global__ AICORE void {cg.kernel_name}({sig})\n' | 267 | f'extern "C" __global__ AICORE void {cg.kernel_name}({sig})\n' |
| 215 | "{\n" | 268 | "{\n" |
| 216 | f" KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);\n" | 269 | f" KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);\n" |
| @@ -622,14 +675,19 @@ def pypto_compile_op( | |||
| 622 | impl_src = os.path.join(cg.build_dir, "kernel.cpp") | 675 | impl_src = os.path.join(cg.build_dir, "kernel.cpp") |
| 623 | impl_dst = os.path.join(kernel_meta_dir, impl_cpp_name) | 676 | impl_dst = os.path.join(kernel_meta_dir, impl_cpp_name) |
| 624 | impl_content = open(impl_src, "r", encoding="utf-8").read() | 677 | impl_content = open(impl_src, "r", encoding="utf-8").read() |
| 625 | - impl_content = impl_content.replace("cce::printf", "AscendC::printf") | 678 | + impl_content = impl_content.replace("cce::printf", "__pypto_aicore_printf") |
| 626 | - if "TPRINT(" in impl_content: | 679 | + if ( |
| 627 | - # Copy custom TPRINT implementation header to kernel_meta_dir | 680 | + "TPRINT(" in impl_content |
| 628 | - tprint_dst = os.path.join(kernel_meta_dir, "_pypto_tprint.h") | 681 | + or "__pypto_dtype_name" in impl_content |
| 629 | - if not os.path.exists(tprint_dst): | 682 | + or "__pypto_print_val" in impl_content |
| 630 | - shutil.copyfile(os.path.join(os.path.dirname(__file__), "_pypto_tprint.h"), tprint_dst) | 683 | + ): |
| 684 | + # Binary-mode TPRINT helpers live in the shared pypto_tprint.h header, which uses | ||
| 685 | + # cce::printf for jit-mode compatibility. The OPC toolchain has no working | ||
| 686 | + # cce::printf output, so drop a no-prefix AscendC dump copy next to the impl and | ||
| 687 | + # resolve it by a quoted local name (the include itself is emitted by codegen). | ||
| 688 | + _write_ascendc_tprint_header(kernel_meta_dir) | ||
| 631 | impl_content = impl_content.replace( | 689 | impl_content = impl_content.replace( |
| 632 | - '#include <pto/pto-inst.hpp>\n', '#include <pto/pto-inst.hpp>\n#include "_pypto_tprint.h"\n' | 690 | + '#include <pypto_tprint.h>\n', '#include "pypto_tprint.h"\n' |
| 633 | ) | 691 | ) |
| 634 | with open(impl_dst, "w", encoding="utf-8") as f: | 692 | with open(impl_dst, "w", encoding="utf-8") as f: |
| 635 | f.write(impl_content) | 693 | f.write(impl_content) |
| @@ -646,6 +704,7 @@ def pypto_compile_op( | |||
| 646 | dst_o = os.path.join(kernel_meta_dir, f"{kernel_name}_{channel}_{packed}.o") | 704 | dst_o = os.path.join(kernel_meta_dir, f"{kernel_name}_{channel}_{packed}.o") |
| 647 | sub_arch = _core_arch(core_type) | 705 | sub_arch = _core_arch(core_type) |
| 648 | cmd = gen_compile_cmd_v220(src_path, dst_o, opt, sub_arch, "") # kernel.cpp self-includes its tiling.h | 706 | cmd = gen_compile_cmd_v220(src_path, dst_o, opt, sub_arch, "") # kernel.cpp self-includes its tiling.h |
| 707 | + cmd += [f"-I{os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'include')}"] | ||
| 649 | cmd += [f"-D{TILING_KEY_MACRO}={packed}UL"] | 708 | cmd += [f"-D{TILING_KEY_MACRO}={packed}UL"] |
| 650 | cmd += [f"-D{MIX_CORE_MACRO}=1"] | 709 | cmd += [f"-D{MIX_CORE_MACRO}=1"] |
| 651 | if CommonUtility.is_c310(): | 710 | if CommonUtility.is_c310(): |
| @@ -0,0 +1,80 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# 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 of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | + | ||
| 12 | +"""pl.dump_data flag 参数测试 — 简单 dump / 窗口 dump / tensor dump 的标记行输出。""" | ||
| 13 | + | ||
| 14 | +import logging | ||
| 15 | +import os | ||
| 16 | + | ||
| 17 | +import pypto_pro.language as pl | ||
| 18 | +import pytest | ||
| 19 | +import torch | ||
| 20 | + | ||
| 21 | +ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 22 | +ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def _check_npu(): | ||
| 26 | + try: | ||
| 27 | + torch.npu.set_device(ST_DEVICE) | ||
| 28 | + name = torch.npu.get_device_name() | ||
| 29 | + if "Ascend950" not in name: | ||
| 30 | + pytest.skip(f"Device {name} is not A5 (Ascend950). Skip.") | ||
| 31 | + return True | ||
| 32 | + except RuntimeError as exc: | ||
| 33 | + pytest.skip(f"NPU unavailable: {exc}") | ||
| 34 | + return False | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +@pl.jit() | ||
| 38 | +def dump_data_flag_simple_kernel(out: pl.Tensor[[16], pl.DT_INT32]): | ||
| 39 | + with pl.section_vector(): | ||
| 40 | + for i in pl.range(0, 16): | ||
| 41 | + out[i] = i | ||
| 42 | + pl.dump_data(out, flag="checkpoint_A") | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +@pytest.mark.soc("950") | ||
| 46 | +def test_dump_data_flag_tensor_simple(): | ||
| 47 | + _check_npu() | ||
| 48 | + logging.info("------------test_dump_data_flag_tensor_simple--------------") | ||
| 49 | + out = torch.zeros(16, device=ST_DEVICE, dtype=torch.int32) | ||
| 50 | + dump_data_flag_simple_kernel(out) | ||
| 51 | + torch.npu.synchronize() | ||
| 52 | + torch.testing.assert_close(out, torch.arange(16, device=ST_DEVICE, dtype=torch.int32)) | ||
| 53 | + logging.info("dump_data_flag_tensor_simple passed!") | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +@pl.jit(auto_mutex=True) | ||
| 57 | +def dump_data_flag_window_kernel( | ||
| 58 | + a: pl.Tensor[[32, 32], pl.DT_INT32], | ||
| 59 | + out: pl.Tensor[[32, 32], pl.DT_INT32], | ||
| 60 | +): | ||
| 61 | + tt = pl.TileType(shape=[32, 32], dtype=pl.DT_INT32, target_memory=pl.MemorySpace.Vec) | ||
| 62 | + tc_group = pl.make_tile_group(type=tt, addrs=0x2000, mutex_ids=[2]) | ||
| 63 | + with pl.section_vector(): | ||
| 64 | + tc = tc_group.current() | ||
| 65 | + pl.load(tc, a, [0, 0]) | ||
| 66 | + pl.add(tc, tc, tc) | ||
| 67 | + pl.dump_data(tc, offsets=[4, 4], shapes=[8, 8], flag="checkpoint_B") | ||
| 68 | + pl.store(out, tc, [0, 0]) | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +@pytest.mark.soc("950") | ||
| 72 | +def test_dump_data_flag_tile_window(): | ||
| 73 | + _check_npu() | ||
| 74 | + logging.info("------------test_dump_data_flag_tile_window--------------") | ||
| 75 | + a = torch.arange(32 * 32, device=ST_DEVICE, dtype=torch.int32).reshape(32, 32) | ||
| 76 | + out = torch.empty_like(a) | ||
| 77 | + dump_data_flag_window_kernel(a, out) | ||
| 78 | + torch.npu.synchronize() | ||
| 79 | + torch.testing.assert_close(out, a + a) | ||
| 80 | + logging.info("dump_data_flag_tile_window passed!") | ||
这个为啥也要替换,这个接口看着很普通,二进制场景有啥特殊问题不能直接调用么