Merged
fix(pypto_pro): use ASC printf for debug output #6385
yzfAdd on Sep 16
fix(pypto_pro): use ASC printf for debug output #6385
Merged
Merged fromfafafafafa/pypto_cann9.2.0intocann/pypto9.2.0
Total: 13 files changed+246-361
| @@ -32,7 +32,7 @@ pypto_pro.language.printf( | |||
| 32 | 32 | ||
| 33 | | 参数 | 输入/输出 | 说明 | | 33 | | 参数 | 输入/输出 | 说明 | |
| 34 | |---|---|---| | 34 | |---|---|---| |
| 35 | -| format_str | 输入 | 格式串,必须是编译时常量字符串,不能是运行时变量。<br>支持的格式说明符:%\[flags\]\[width\]\[.precision\]conversion<br>flags:-、+、 (空格)、#、0<br>conversion:d/i(有符号整数)、u(无符号整数)、x(十六进制)、f(浮点)、p(指针,接受Ptr)<br>不支持的conversion:%%(百分号本身)、%s(字符串)、%c(字符)<br>不支持长度修饰符:如%lld、%ld、%hd等。 | | 35 | +| format_str | 输入 | 格式串,必须是编译时常量字符串,不能是运行时变量。<br>支持%d/%i(有符号整数)、%u(无符号整数)、%x(十六进制)、%f(浮点)和%p(指针)。不支持flags、宽度、精度和长度修饰符。<br>不支持的conversion:%%(百分号本身)、%s(字符串)、%c(字符)。 | |
| 36 | | *args | 输入 | 要打印的标量值或Ptr指针,数量和类型须与格式串中的格式说明符匹配。支持Python int、Python float、Python bool以及Kernel标量表达式;使用%p时还支持Ptr指针。<br>%d/%i:接受有符号整型、BOOL、INDEX,拒绝无符号整型<br>%u:接受无符号整型、BOOL、INDEX,拒绝有符号整型<br>%x:接受无符号整型、INDEX,拒绝有符号整型和BOOL<br>%f:仅接受FP32,拒绝FP16/BF16和整型<br>%p:仅接受Ptr指针。 | | 36 | | *args | 输入 | 要打印的标量值或Ptr指针,数量和类型须与格式串中的格式说明符匹配。支持Python int、Python float、Python bool以及Kernel标量表达式;使用%p时还支持Ptr指针。<br>%d/%i:接受有符号整型、BOOL、INDEX,拒绝无符号整型<br>%u:接受无符号整型、BOOL、INDEX,拒绝有符号整型<br>%x:接受无符号整型、INDEX,拒绝有符号整型和BOOL<br>%f:仅接受FP32,拒绝FP16/BF16和整型<br>%p:仅接受Ptr指针。 | |
| 37 | | loc | 输入 | 可选,是否在输出前打印源文件/行号,取值为True或False(默认)。为True时,在输出前打印调用位置的源文件和行号。 | | 37 | | loc | 输入 | 可选,是否在输出前打印源文件/行号,取值为True或False(默认)。为True时,在输出前打印调用位置的源文件和行号。 | |
| 38 | 38 | ||
| @@ -52,10 +52,10 @@ import pypto_pro.language as pl | |||
| 52 | pl.printf("flag=%d, offset=%d\n", flag, offset) | 52 | pl.printf("flag=%d, offset=%d\n", flag, offset) |
| 53 | 53 | ||
| 54 | # 打印浮点(仅 FP32) | 54 | # 打印浮点(仅 FP32) |
| 55 | -pl.printf("value=%+08.3f\n", value_f32) | 55 | +pl.printf("value=%f\n", value_f32) |
| 56 | 56 | ||
| 57 | # 打印十六进制 | 57 | # 打印十六进制 |
| 58 | -pl.printf("addr=%#08x\n", addr_u32) | 58 | +pl.printf("addr=0x%x\n", addr_u32) |
| 59 | 59 | ||
| 60 | # 纯文本(无参数) | 60 | # 纯文本(无参数) |
| 61 | pl.printf("reached checkpoint A\n") | 61 | pl.printf("reached checkpoint A\n") |
| @@ -69,7 +69,7 @@ pl.printf("debug: i=%d\n", i, loc=True) | |||
| 69 | | 调用 | 输出(假设flag = 1, offset = 32, value_f32 = 3.14, addr_u32 = 0x1234, i = 5) | | 69 | | 调用 | 输出(假设flag = 1, offset = 32, value_f32 = 3.14, addr_u32 = 0x1234, i = 5) | |
| 70 | |---|---| | 70 | |---|---| |
| 71 | | pypto_pro.language.printf("flag=%d, offset=%d\n", flag, offset) | flag=1, offset=32 | | 71 | | pypto_pro.language.printf("flag=%d, offset=%d\n", flag, offset) | flag=1, offset=32 | |
| 72 | -| pypto_pro.language.printf("value=%+08.3f\n", value_f32) | value=+003.140 | | 72 | +| pypto_pro.language.printf("value=%f\n", value_f32) | value=3.140000 | |
| 73 | -| pypto_pro.language.printf("addr=%#08x\n", addr_u32) | addr=0x001234 | | 73 | +| pypto_pro.language.printf("addr=0x%x\n", addr_u32) | addr=0x1234 | |
| 74 | | pypto_pro.language.printf("reached checkpoint A\n") | reached checkpoint A | | 74 | | pypto_pro.language.printf("reached checkpoint A\n") | reached checkpoint A | |
| 75 | | pypto_pro.language.printf("debug: i=%d\n", i, loc=True) | debug: i=5(loc = True时额外附带源码位置) | | 75 | | pypto_pro.language.printf("debug: i=%d\n", i, loc=True) | debug: i=5(loc = True时额外附带源码位置) | |
| @@ -84,19 +84,12 @@ struct PrintfSegment { | |||
| 84 | char conversion; | 84 | char conversion; |
| 85 | }; | 85 | }; |
| 86 | 86 | ||
| 87 | -struct PrintfFormatParts { | ||
| 88 | - std::string prefix; | ||
| 89 | - std::string conversion_spec; | ||
| 90 | - std::string suffix; | ||
| 91 | -}; | ||
| 92 | - | ||
| 93 | std::string EscapeStringLiteral(const std::string& text); | 87 | std::string EscapeStringLiteral(const std::string& text); |
| 94 | std::string QuoteMlirStringLiteral(const std::string& text); | 88 | std::string QuoteMlirStringLiteral(const std::string& text); |
| 95 | std::string FormatDebugLocation(const ir::Span& span); | 89 | std::string FormatDebugLocation(const ir::Span& span); |
| 96 | std::string FormatDebugLocationHeader(const ir::Span& span, const std::string& op_name); | 90 | std::string FormatDebugLocationHeader(const ir::Span& span, const std::string& op_name); |
| 97 | bool IsSupportedPrintfConversion(char conversion); | 91 | bool IsSupportedPrintfConversion(char conversion); |
| 98 | size_t FindPrintfConversionIndex(const std::string& format_segment); | 92 | size_t FindPrintfConversionIndex(const std::string& format_segment); |
| 99 | -PrintfFormatParts SplitPrintfSegment(const std::string& format_segment); | ||
| 100 | std::vector<PrintfSegment> ParsePrintfSegments(const std::string& format); | 93 | std::vector<PrintfSegment> ParsePrintfSegments(const std::string& format); |
| 101 | 94 | ||
| 102 | } // namespace debug_printf | 95 | } // namespace debug_printf |
| @@ -69,44 +69,54 @@ static void EmitDebugLocationHeaderCCE(codegen::CCECodegen& codegen, const ir::S | |||
| 69 | { | 69 | { |
| 70 | std::string header = debug_printf::FormatDebugLocationHeader(span, op_name); | 70 | std::string header = debug_printf::FormatDebugLocationHeader(span, op_name); |
| 71 | if (!header.empty()) { | 71 | if (!header.empty()) { |
| 72 | - codegen.Emit("cce::printf(\"" + debug_printf::EscapeStringLiteral(header + "\n") + "\");"); | 72 | + codegen.Emit("pypto_printf(\"" + debug_printf::EscapeStringLiteral(header + "\n") + "\");"); |
| 73 | } | 73 | } |
| 74 | } | 74 | } |
| 75 | 75 | ||
| 76 | -static bool NeedsCcePrintfSignedLongLong(const DataType& dtype, char conversion) | 76 | +static bool NeedsAscPrintfSignedLongLong(const DataType& dtype, char conversion) |
| 77 | { | 77 | { |
| 78 | return (conversion == 'd' || conversion == 'i') && (dtype == DataType::INT64 || dtype == DataType::INDEX); | 78 | return (conversion == 'd' || conversion == 'i') && (dtype == DataType::INT64 || dtype == DataType::INDEX); |
| 79 | } | 79 | } |
| 80 | 80 | ||
| 81 | -static bool NeedsCcePrintfUnsignedU64Helper(const DataType& dtype, char conversion) | 81 | +static bool NeedsAscPrintfUnsignedLongLong(const DataType& dtype, char conversion) |
| 82 | { | 82 | { |
| 83 | return (conversion == 'u' || conversion == 'x') && (dtype == DataType::UINT64 || dtype == DataType::INDEX); | 83 | return (conversion == 'u' || conversion == 'x') && (dtype == DataType::UINT64 || dtype == DataType::INDEX); |
| 84 | } | 84 | } |
| 85 | 85 | ||
| 86 | -static std::string RewriteCcePrintfFormatForScalarType(const std::string& format_segment, char conversion, | 86 | +static std::string RewriteAscPrintfFormatForScalarType(const std::string& format_segment, char conversion, |
| 87 | const DataType& dtype) | 87 | const DataType& dtype) |
| 88 | { | 88 | { |
| 89 | - if (!NeedsCcePrintfSignedLongLong(dtype, conversion) && conversion != 'p') { | 89 | + const bool signed_long_long = NeedsAscPrintfSignedLongLong(dtype, conversion); |
| 90 | + const bool unsigned_long_long = NeedsAscPrintfUnsignedLongLong(dtype, conversion); | ||
| 91 | + if (!signed_long_long && !unsigned_long_long) { | ||
| 90 | return format_segment; | 92 | return format_segment; |
| 91 | } | 93 | } |
| 92 | 94 | ||
| 93 | size_t conv_idx = debug_printf::FindPrintfConversionIndex(format_segment); | 95 | size_t conv_idx = debug_printf::FindPrintfConversionIndex(format_segment); |
| 94 | std::string rewritten = format_segment; | 96 | std::string rewritten = format_segment; |
| 95 | - rewritten.replace(conv_idx, 1, (conversion == 'd' || conversion == 'p') ? "lld" : "lli"); | 97 | + if (conversion == 'd') { |
| 98 | + rewritten.replace(conv_idx, 1, "lld"); | ||
| 99 | + } else if (conversion == 'i') { | ||
| 100 | + rewritten.replace(conv_idx, 1, "lli"); | ||
| 101 | + } else if (conversion == 'u') { | ||
| 102 | + rewritten.replace(conv_idx, 1, "llu"); | ||
| 103 | + } else { | ||
| 104 | + rewritten.replace(conv_idx, 1, "llx"); | ||
| 105 | + } | ||
| 96 | return rewritten; | 106 | return rewritten; |
| 97 | } | 107 | } |
| 98 | 108 | ||
| 99 | -static std::string CastCcePrintfArgIfNeeded(const std::string& arg, const DataType& dtype, char conversion) | 109 | +static std::string CastAscPrintfArgIfNeeded(const std::string& arg, const DataType& dtype, char conversion) |
| 100 | { | 110 | { |
| 101 | if (conversion == 'f') { | 111 | if (conversion == 'f') { |
| 102 | return arg; | 112 | return arg; |
| 103 | } | 113 | } |
| 104 | - if (conversion == 'p') { | 114 | + if (NeedsAscPrintfSignedLongLong(dtype, conversion)) { |
| 105 | - return "static_cast<long long>((uint64_t)" + arg + ")"; | ||
| 106 | - } | ||
| 107 | - if (NeedsCcePrintfSignedLongLong(dtype, conversion)) { | ||
| 108 | return "static_cast<long long>(" + arg + ")"; | 115 | return "static_cast<long long>(" + arg + ")"; |
| 109 | } | 116 | } |
| 117 | + if (NeedsAscPrintfUnsignedLongLong(dtype, conversion)) { | ||
| 118 | + return "static_cast<unsigned long long>(" + arg + ")"; | ||
| 119 | + } | ||
| 110 | if (dtype == DataType::BOOL) { | 120 | if (dtype == DataType::BOOL) { |
| 111 | return conversion == 'u' ? "static_cast<unsigned int>(" + arg + ")" : "static_cast<int>(" + arg + ")"; | 121 | return conversion == 'u' ? "static_cast<unsigned int>(" + arg + ")" : "static_cast<int>(" + arg + ")"; |
| 112 | } | 122 | } |
| @@ -119,128 +129,32 @@ static std::string CastCcePrintfArgIfNeeded(const std::string& arg, const DataTy | |||
| 119 | return arg; | 129 | return arg; |
| 120 | } | 130 | } |
| 121 | 131 | ||
| 122 | -static void AppendCcePrintfCall(std::vector<std::string>* statements, const std::string& format, | 132 | +static std::string BuildAscPrintfCall(const std::string& format, const std::vector<std::string>& args, |
| 123 | - const std::vector<std::string>& args = {}) | 133 | + const std::vector<DataType>& arg_dtypes) |
| 124 | { | 134 | { |
| 125 | - if (format.empty()) { | 135 | + CHECK(args.size() == arg_dtypes.size()) << "debug.printf ASC argument/type count mismatch"; |
| 126 | - return; | ||
| 127 | - } | ||
| 128 | - std::string statement = "cce::printf(\"" + debug_printf::EscapeStringLiteral(format) + "\""; | ||
| 129 | - for (const auto& arg : args) { | ||
| 130 | - statement += ", " + arg; | ||
| 131 | - } | ||
| 132 | - statement += ");"; | ||
| 133 | - statements->push_back(statement); | ||
| 134 | -} | ||
| 135 | - | ||
| 136 | -static bool CcePrintfSpecHasFlag(const std::string& conversion_spec, char flag) | ||
| 137 | -{ | ||
| 138 | - return conversion_spec.find(flag) != std::string::npos; | ||
| 139 | -} | ||
| 140 | - | ||
| 141 | -static void AppendCcePrintfUnsignedDecimalU64(std::vector<std::string>* statements, const std::string& arg, | ||
| 142 | - int* temp_id) | ||
| 143 | -{ | ||
| 144 | - const std::string suffix = std::to_string((*temp_id)++); | ||
| 145 | - const std::string value = "__pypto_printf_u64_value_" + suffix; | ||
| 146 | - const std::string low = "__pypto_printf_u64_low_" + suffix; | ||
| 147 | - const std::string mid = "__pypto_printf_u64_mid_" + suffix; | ||
| 148 | - const std::string high = "__pypto_printf_u64_high_" + suffix; | ||
| 149 | - const std::string rest = "__pypto_printf_u64_rest_" + suffix; | ||
| 150 | - | ||
| 151 | - statements->push_back("{"); | ||
| 152 | - statements->push_back(" uint64_t " + value + " = static_cast<uint64_t>(" + arg + ");"); | ||
| 153 | - statements->push_back(" unsigned int " + low + " = static_cast<unsigned int>(" + value + " % 1000000000ULL);"); | ||
| 154 | - statements->push_back(" uint64_t " + rest + " = " + value + " / 1000000000ULL;"); | ||
| 155 | - statements->push_back(" unsigned int " + mid + " = static_cast<unsigned int>(" + rest + " % 1000000000ULL);"); | ||
| 156 | - statements->push_back(" unsigned int " + high + " = static_cast<unsigned int>(" + rest + " / 1000000000ULL);"); | ||
| 157 | - statements->push_back(" if (" + high + " != 0U) {"); | ||
| 158 | - statements->push_back(" cce::printf(\"%u%09u%09u\", " + high + ", " + mid + ", " + low + ");"); | ||
| 159 | - statements->push_back(" } else if (" + mid + " != 0U) {"); | ||
| 160 | - statements->push_back(" cce::printf(\"%u%09u\", " + mid + ", " + low + ");"); | ||
| 161 | - statements->push_back(" } else {"); | ||
| 162 | - statements->push_back(" cce::printf(\"%u\", " + low + ");"); | ||
| 163 | - statements->push_back(" }"); | ||
| 164 | - statements->push_back("}"); | ||
| 165 | -} | ||
| 166 | - | ||
| 167 | -static void AppendCcePrintfUnsignedHexU64(std::vector<std::string>* statements, const std::string& arg, | ||
| 168 | - const std::string& conversion_spec, int* temp_id) | ||
| 169 | -{ | ||
| 170 | - const std::string suffix = std::to_string((*temp_id)++); | ||
| 171 | - const std::string value = "__pypto_printf_u64_value_" + suffix; | ||
| 172 | - const std::string high = "__pypto_printf_u64_high_" + suffix; | ||
| 173 | - const std::string low = "__pypto_printf_u64_low_" + suffix; | ||
| 174 | - const bool alternate = CcePrintfSpecHasFlag(conversion_spec, '#'); | ||
| 175 | - | ||
| 176 | - statements->push_back("{"); | ||
| 177 | - statements->push_back(" uint64_t " + value + " = static_cast<uint64_t>(" + arg + ");"); | ||
| 178 | - statements->push_back(" unsigned int " + high + " = static_cast<unsigned int>(" + value + " >> 32);"); | ||
| 179 | - statements->push_back(" unsigned int " + low + " = static_cast<unsigned int>(" + value + " & 0xffffffffULL);"); | ||
| 180 | - statements->push_back(" if (" + high + " != 0U) {"); | ||
| 181 | - if (alternate) { | ||
| 182 | - statements->push_back(" cce::printf(\"0x%x%08x\", " + high + ", " + low + ");"); | ||
| 183 | - } else { | ||
| 184 | - statements->push_back(" cce::printf(\"%x%08x\", " + high + ", " + low + ");"); | ||
| 185 | - } | ||
| 186 | - statements->push_back(" } else {"); | ||
| 187 | - statements->push_back(" cce::printf(\"" + debug_printf::EscapeStringLiteral(conversion_spec) + "\", " + low + | ||
| 188 | - ");"); | ||
| 189 | - statements->push_back(" }"); | ||
| 190 | - statements->push_back("}"); | ||
| 191 | -} | ||
| 192 | - | ||
| 193 | -static std::vector<std::string> MakeCcePrintfStatements(const std::string& format, const std::vector<std::string>& args, | ||
| 194 | - const std::vector<DataType>& arg_dtypes) | ||
| 195 | -{ | ||
| 196 | - CHECK(args.size() == arg_dtypes.size()) << "debug.printf CCE argument/type count mismatch"; | ||
| 197 | 136 | ||
| 198 | auto segments = debug_printf::ParsePrintfSegments(format); | 137 | auto segments = debug_printf::ParsePrintfSegments(format); |
| 199 | CHECK(segments.size() == args.size()) | 138 | CHECK(segments.size() == args.size()) |
| 200 | << "debug.printf format expects " << segments.size() << " scalar arguments, but got " << args.size(); | 139 | << "debug.printf format expects " << segments.size() << " scalar arguments, but got " << args.size(); |
| 201 | 140 | ||
| 202 | - std::vector<std::string> statements; | 141 | + if (format.empty()) { |
| 203 | - int temp_id = 0; | 142 | + return ""; |
| 204 | - if (segments.empty()) { | ||
| 205 | - AppendCcePrintfCall(&statements, format); | ||
| 206 | - return statements; | ||
| 207 | } | 143 | } |
| 208 | 144 | ||
| 209 | - // Merge consecutive non-U64 segments into a single printf call. | 145 | + std::string rewritten_format = segments.empty() ? format : ""; |
| 210 | - // Flush the batch when hitting a U64 segment (which needs multi-statement expansion). | 146 | + std::vector<std::string> rewritten_args; |
| 211 | - std::string batch_format; | ||
| 212 | - std::vector<std::string> batch_args; | ||
| 213 | - | ||
| 214 | - auto flush_batch = [&]() { | ||
| 215 | - if (!batch_format.empty()) { | ||
| 216 | - AppendCcePrintfCall(&statements, batch_format, batch_args); | ||
| 217 | - batch_format.clear(); | ||
| 218 | - batch_args.clear(); | ||
| 219 | - } | ||
| 220 | - }; | ||
| 221 | - | ||
| 222 | for (size_t i = 0; i < segments.size(); ++i) { | 147 | for (size_t i = 0; i < segments.size(); ++i) { |
| 223 | - if (NeedsCcePrintfUnsignedU64Helper(arg_dtypes[i], segments[i].conversion)) { | 148 | + rewritten_format += RewriteAscPrintfFormatForScalarType(segments[i].format_segment, segments[i].conversion, |
| 224 | - flush_batch(); | 149 | + arg_dtypes[i]); |
| 225 | - debug_printf::PrintfFormatParts parts = debug_printf::SplitPrintfSegment(segments[i].format_segment); | 150 | + rewritten_args.push_back(CastAscPrintfArgIfNeeded(args[i], arg_dtypes[i], segments[i].conversion)); |
| 226 | - AppendCcePrintfCall(&statements, parts.prefix); | ||
| 227 | - if (segments[i].conversion == 'u') { | ||
| 228 | - AppendCcePrintfUnsignedDecimalU64(&statements, args[i], &temp_id); | ||
| 229 | - } else { | ||
| 230 | - AppendCcePrintfUnsignedHexU64(&statements, args[i], parts.conversion_spec, &temp_id); | ||
| 231 | - } | ||
| 232 | - AppendCcePrintfCall(&statements, parts.suffix); | ||
| 233 | - } else { | ||
| 234 | - std::string rewritten_format = RewriteCcePrintfFormatForScalarType(segments[i].format_segment, | ||
| 235 | - segments[i].conversion, arg_dtypes[i]); | ||
| 236 | - std::string rewritten_arg = CastCcePrintfArgIfNeeded(args[i], arg_dtypes[i], segments[i].conversion); | ||
| 237 | - batch_format += rewritten_format; | ||
| 238 | - batch_args.push_back(rewritten_arg); | ||
| 239 | - } | ||
| 240 | } | 151 | } |
| 241 | - flush_batch(); | ||
| 242 | 152 | ||
| 243 | - return statements; | 153 | + std::string call = "pypto_printf(\"" + debug_printf::EscapeStringLiteral(rewritten_format) + "\""; |
| 154 | + for (const auto& arg : rewritten_args) { | ||
| 155 | + call += ", " + arg; | ||
| 156 | + } | ||
| 157 | + return call + ");"; | ||
| 244 | } | 158 | } |
| 245 | 159 | ||
| 246 | static bool HasDynamicTensorShape(const ir::TensorTypePtr& tensor_type) | 160 | static bool HasDynamicTensorShape(const ir::TensorTypePtr& tensor_type) |
| @@ -500,7 +414,7 @@ static std::string MakeDebugDumpTensorNZCodegenCCE(codegen::CCECodegen& codegen, | |||
| 500 | view_offset = "(" + offset + " + " + delta + ")"; | 414 | view_offset = "(" + offset + " + " + delta + ")"; |
| 501 | 415 | ||
| 502 | std::ostringstream batch_header; | 416 | std::ostringstream batch_header; |
| 503 | - batch_header << "cce::printf(\"=== [dump_tensor] Batch ["; | 417 | + batch_header << "pypto_printf(\"=== [dump_tensor] Batch ["; |
| 504 | for (size_t axis = 0; axis < row_axis; ++axis) { | 418 | for (size_t axis = 0; axis < row_axis; ++axis) { |
| 505 | if (axis != 0) { | 419 | if (axis != 0) { |
| 506 | batch_header << ", "; | 420 | batch_header << ", "; |
| @@ -531,7 +445,7 @@ static void EmitDumpFlagHeaderCCE(codegen::CCECodegen& codegen, const ir::CallPt | |||
| 531 | if (dump_flag.empty()) { | 445 | if (dump_flag.empty()) { |
| 532 | return; | 446 | return; |
| 533 | } | 447 | } |
| 534 | - codegen.Emit("cce::printf(\"=== [flag] %s ===\\n\", \"" + debug_printf::EscapeStringLiteral(dump_flag) + "\");"); | 448 | + codegen.Emit("pypto_printf(\"=== [flag] %s ===\\n\", \"" + debug_printf::EscapeStringLiteral(dump_flag) + "\");"); |
| 535 | } | 449 | } |
| 536 | 450 | ||
| 537 | static std::string MakeDebugDumpTensorCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) | 451 | static std::string MakeDebugDumpTensorCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) |
| @@ -630,12 +544,10 @@ static std::string MakeDebugPrintfCodegenCCE(const ir::CallPtr& op, codegen::Cod | |||
| 630 | args.reserve(op->args_.size()); | 544 | args.reserve(op->args_.size()); |
| 631 | arg_dtypes.reserve(op->args_.size()); | 545 | arg_dtypes.reserve(op->args_.size()); |
| 632 | 546 | ||
| 633 | - // Parse format to know which args are %p (pointer) vs scalar | ||
| 634 | - auto segments = debug_printf::ParsePrintfSegments(format); | ||
| 635 | for (size_t i = 0; i < op->args_.size(); ++i) { | 547 | for (size_t i = 0; i < op->args_.size(); ++i) { |
| 636 | args.emplace_back(codegen.GetExprAsCode(op->args_[i])); | 548 | args.emplace_back(codegen.GetExprAsCode(op->args_[i])); |
| 637 | - if (i < segments.size() && segments[i].conversion == 'p') { | 549 | + if (ir::As<ir::PtrType>(op->args_[i]->GetType())) { |
| 638 | - // Pointer argument: use INDEX as a dummy dtype; CastCcePrintfArgIfNeeded handles %p specially | 550 | + // Pointer arguments are passed directly to ASC printf. |
| 639 | arg_dtypes.emplace_back(DataType::INDEX); | 551 | arg_dtypes.emplace_back(DataType::INDEX); |
| 640 | } else { | 552 | } else { |
| 641 | auto scalar_type = ir::As<ir::ScalarType>(op->args_[i]->GetType()); | 553 | auto scalar_type = ir::As<ir::ScalarType>(op->args_[i]->GetType()); |
| @@ -644,8 +556,9 @@ static std::string MakeDebugPrintfCodegenCCE(const ir::CallPtr& op, codegen::Cod | |||
| 644 | } | 556 | } |
| 645 | } | 557 | } |
| 646 | 558 | ||
| 647 | - for (const auto& statement : MakeCcePrintfStatements(format, args, arg_dtypes)) { | 559 | + std::string call = BuildAscPrintfCall(format, args, arg_dtypes); |
| 648 | - codegen.Emit(statement); | 560 | + if (!call.empty()) { |
| 561 | + codegen.Emit(call); | ||
| 649 | } | 562 | } |
| 650 | return ""; | 563 | return ""; |
| 651 | } | 564 | } |
| @@ -732,10 +645,12 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 732 | valid_col + " = " + std::to_string(tile_cols->value_) + " - (" + col_off + ");"); | 645 | valid_col + " = " + std::to_string(tile_cols->value_) + " - (" + col_off + ");"); |
| 733 | codegen.Emit("if (" + valid_col + " < 0) " + valid_col + " = 0;"); | 646 | codegen.Emit("if (" + valid_col + " < 0) " + valid_col + " = 0;"); |
| 734 | 647 | ||
| 735 | - codegen.Emit("cce::printf(\"=== [TPRINT Acc Tile Window] Data Type: %s, Layout: NZ, TileType: Acc ===\\n\", " | 648 | + codegen.Emit("pypto_printf(\"=== [TPRINT Acc Tile Window] Data Type: %s, Layout: NZ, TileType: Acc " |
| 649 | + "===\\n\", " | ||
| 736 | "__pypto_dtype_name<" + | 650 | "__pypto_dtype_name<" + |
| 737 | dtype_str + ">());"); | 651 | dtype_str + ">());"); |
| 738 | - codegen.Emit("cce::printf(\" Source Shape: [%d, %d], Window Offsets: [%d, %d], Requested Shape: [%d, %d], " | 652 | + codegen.Emit("pypto_printf(\" Source Shape: [%d, %d], Window Offsets: [%d, %d], Requested Shape: " |
| 653 | + "[%d, %d], " | ||
| 739 | "Valid Shape: [%d, %d]\\n\", " + | 654 | "Valid Shape: [%d, %d]\\n\", " + |
| 740 | std::to_string(tile_rows->value_) + ", " + std::to_string(tile_cols->value_) + | 655 | std::to_string(tile_rows->value_) + ", " + std::to_string(tile_cols->value_) + |
| 741 | ", static_cast<int>(" + row_off + "), static_cast<int>(" + col_off + "), " + requested_row + ", " + | 656 | ", static_cast<int>(" + row_off + "), static_cast<int>(" + col_off + "), " + requested_row + ", " + |
| @@ -750,7 +665,7 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 750 | std::to_string(tile_cols->value_) + " + (" + col_idx + " + (" + col_off + ")));"); | 665 | std::to_string(tile_cols->value_) + " + (" + col_idx + " + (" + col_off + ")));"); |
| 751 | codegen.Emit(" __pypto_print_val(" + debug_val + ");"); | 666 | codegen.Emit(" __pypto_print_val(" + debug_val + ");"); |
| 752 | codegen.Emit(" }"); | 667 | codegen.Emit(" }"); |
| 753 | - codegen.Emit(" cce::printf(\"\\n\");"); | 668 | + codegen.Emit(" pypto_printf(\"\\n\");"); |
| 754 | codegen.Emit(" }"); | 669 | codegen.Emit(" }"); |
| 755 | codegen.Emit("}"); | 670 | codegen.Emit("}"); |
| 756 | return ""; | 671 | return ""; |
| @@ -807,12 +722,13 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 807 | codegen.Emit("if (" + valid_col + " < 0) " + valid_col + " = 0;"); | 722 | codegen.Emit("if (" + valid_col + " < 0) " + valid_col + " = 0;"); |
| 808 | codegen.Emit("if (" + valid_col + " > " + std::to_string(tile_cols->value_) + ") " + valid_col + " = " + | 723 | codegen.Emit("if (" + valid_col + " > " + std::to_string(tile_cols->value_) + ") " + valid_col + " = " + |
| 809 | std::to_string(tile_cols->value_) + ";"); | 724 | std::to_string(tile_cols->value_) + ";"); |
| 810 | - codegen.Emit("cce::printf(\"=== [TPRINT Tile Window] Data Type: %s, Layout: %s, TileType: %s ===\\n\", " | 725 | + codegen.Emit("pypto_printf(\"=== [TPRINT Tile Window] Data Type: %s, Layout: %s, TileType: %s ===\\n\", " |
| 811 | "__pypto_dtype_name<" + | 726 | "__pypto_dtype_name<" + |
| 812 | codegen.GetTypeString(tile_type->dtype_) + | 727 | codegen.GetTypeString(tile_type->dtype_) + |
| 813 | ">(), pto::GetLayoutName(std::remove_reference_t<decltype(" + src + | 728 | ">(), pto::GetLayoutName(std::remove_reference_t<decltype(" + src + |
| 814 | ")>::BFractal, std::remove_reference_t<decltype(" + src + ")>::SFractal), \"Vec\");"); | 729 | ")>::BFractal, std::remove_reference_t<decltype(" + src + ")>::SFractal), \"Vec\");"); |
| 815 | - codegen.Emit("cce::printf(\" Source Shape: [%d, %d], Window Offsets: [%d, %d], Requested Shape: [%d, %d], " | 730 | + codegen.Emit("pypto_printf(\" Source Shape: [%d, %d], Window Offsets: [%d, %d], Requested Shape: " |
| 731 | + "[%d, %d], " | ||
| 816 | "Valid Shape: [%d, %d]\\n\", " + | 732 | "Valid Shape: [%d, %d]\\n\", " + |
| 817 | std::to_string(tile_rows->value_) + ", " + std::to_string(tile_cols->value_) + ", static_cast<int>(" + | 733 | std::to_string(tile_rows->value_) + ", " + std::to_string(tile_cols->value_) + ", static_cast<int>(" + |
| 818 | row_off + "), static_cast<int>(" + col_off + "), " + requested_row + ", " + requested_col + ", " + | 734 | row_off + "), static_cast<int>(" + col_off + "), " + requested_row + ", " + requested_col + ", " + |
| @@ -824,7 +740,7 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 824 | codegen.Emit(" auto " + debug_val + " = " + src + ".data()[__debug_src_offset];"); | 740 | codegen.Emit(" auto " + debug_val + " = " + src + ".data()[__debug_src_offset];"); |
| 825 | codegen.Emit(" __pypto_print_val(" + debug_val + ");"); | 741 | codegen.Emit(" __pypto_print_val(" + debug_val + ");"); |
| 826 | codegen.Emit(" }"); | 742 | codegen.Emit(" }"); |
| 827 | - codegen.Emit(" cce::printf(\"\\n\");"); | 743 | + codegen.Emit(" pypto_printf(\"\\n\");"); |
| 828 | codegen.Emit("}"); | 744 | codegen.Emit("}"); |
| 829 | return ""; | 745 | return ""; |
| 830 | } | 746 | } |
| @@ -1609,19 +1525,19 @@ static std::string MakeDebugAssertCodegenCCE(const ir::CallPtr& op, codegen::Cod | |||
| 1609 | if (op->GetKwarg<bool>("show_location", false)) { | 1525 | if (op->GetKwarg<bool>("show_location", false)) { |
| 1610 | std::string location = debug_printf::FormatDebugLocation(op->span_); | 1526 | std::string location = debug_printf::FormatDebugLocation(op->span_); |
| 1611 | if (!location.empty()) { | 1527 | if (!location.empty()) { |
| 1612 | - codegen.Emit(" cce::printf(\"" + | 1528 | + codegen.Emit(" pypto_printf(\"" + |
| 1613 | debug_printf::EscapeStringLiteral(location + " Assertion failed: " + condition_text + "\n") + | 1529 | debug_printf::EscapeStringLiteral(location + " Assertion failed: " + condition_text + "\n") + |
| 1614 | "\");"); | 1530 | "\");"); |
| 1615 | } else { | 1531 | } else { |
| 1616 | - codegen.Emit(" cce::printf(\"" + | 1532 | + codegen.Emit(" pypto_printf(\"" + |
| 1617 | debug_printf::EscapeStringLiteral("Assertion failed: " + condition_text + "\n") + "\");"); | 1533 | debug_printf::EscapeStringLiteral("Assertion failed: " + condition_text + "\n") + "\");"); |
| 1618 | } | 1534 | } |
| 1619 | } else { | 1535 | } else { |
| 1620 | - codegen.Emit(" cce::printf(\"" + | 1536 | + codegen.Emit(" pypto_printf(\"" + |
| 1621 | debug_printf::EscapeStringLiteral("Assertion failed: " + condition_text + "\n") + "\");"); | 1537 | debug_printf::EscapeStringLiteral("Assertion failed: " + condition_text + "\n") + "\");"); |
| 1622 | } | 1538 | } |
| 1623 | 1539 | ||
| 1624 | - if (!format.empty() && op->args_.size() > 1) { | 1540 | + if (!format.empty()) { |
| 1625 | std::vector<std::string> args; | 1541 | std::vector<std::string> args; |
| 1626 | std::vector<DataType> arg_dtypes; | 1542 | std::vector<DataType> arg_dtypes; |
| 1627 | for (size_t i = 1; i < op->args_.size(); ++i) { | 1543 | for (size_t i = 1; i < op->args_.size(); ++i) { |
| @@ -1630,9 +1546,7 @@ static std::string MakeDebugAssertCodegenCCE(const ir::CallPtr& op, codegen::Cod | |||
| 1630 | CHECK(scalar_type) << "debug.assert argument must be ScalarType"; | 1546 | CHECK(scalar_type) << "debug.assert argument must be ScalarType"; |
| 1631 | arg_dtypes.emplace_back(scalar_type->dtype_); | 1547 | arg_dtypes.emplace_back(scalar_type->dtype_); |
| 1632 | } | 1548 | } |
| 1633 | - for (const auto& statement : MakeCcePrintfStatements(format, args, arg_dtypes)) { | 1549 | + codegen.Emit(" " + BuildAscPrintfCall(format, args, arg_dtypes)); |
| 1634 | - codegen.Emit(" " + statement); | ||
| 1635 | - } | ||
| 1636 | } | 1550 | } |
| 1637 | 1551 | ||
| 1638 | codegen.Emit("}"); | 1552 | codegen.Emit("}"); |
| @@ -258,27 +258,11 @@ size_t FindPrintfConversionIndex(const std::string& format_segment) | |||
| 258 | << "debug.printf does not support literal '%%'"; | 258 | << "debug.printf does not support literal '%%'"; |
| 259 | 259 | ||
| 260 | size_t j = i + 1; | 260 | size_t j = i + 1; |
| 261 | - while (j < format_segment.size()) { | ||
| 262 | - char c = format_segment[j]; | ||
| 263 | - if (c == '-' || c == '+' || c == ' ' || c == '#' || c == '0') { | ||
| 264 | - ++j; | ||
| 265 | - } else { | ||
| 266 | - break; | ||
| 267 | - } | ||
| 268 | - } | ||
| 269 | - while (j < format_segment.size() && std::isdigit(static_cast<unsigned char>(format_segment[j]))) { | ||
| 270 | - ++j; | ||
| 271 | - } | ||
| 272 | - if (j < format_segment.size() && format_segment[j] == '.') { | ||
| 273 | - ++j; | ||
| 274 | - CHECK(j < format_segment.size() && std::isdigit(static_cast<unsigned char>(format_segment[j]))) | ||
| 275 | - << "debug.printf precision must be followed by digits"; | ||
| 276 | - while (j < format_segment.size() && std::isdigit(static_cast<unsigned char>(format_segment[j]))) { | ||
| 277 | - ++j; | ||
| 278 | - } | ||
| 279 | - } | ||
| 280 | - | ||
| 281 | CHECK(j < format_segment.size()) << "debug.printf format ends with an incomplete conversion"; | 261 | CHECK(j < format_segment.size()) << "debug.printf format ends with an incomplete conversion"; |
| 262 | + CHECK(format_segment[j] != '-' && format_segment[j] != '+' && format_segment[j] != ' ' && | ||
| 263 | + format_segment[j] != '#' && format_segment[j] != '0' && format_segment[j] != '.' && | ||
| 264 | + !std::isdigit(static_cast<unsigned char>(format_segment[j]))) | ||
| 265 | + << "debug.printf does not support flags, width, or precision"; | ||
| 282 | CHECK(IsSupportedPrintfConversion(format_segment[j])) | 266 | CHECK(IsSupportedPrintfConversion(format_segment[j])) |
| 283 | << "debug.printf does not support conversion '%" << format_segment[j] << "'"; | 267 | << "debug.printf does not support conversion '%" << format_segment[j] << "'"; |
| 284 | return j; | 268 | return j; |
| @@ -287,16 +271,6 @@ size_t FindPrintfConversionIndex(const std::string& format_segment) | |||
| 287 | return std::string::npos; | 271 | return std::string::npos; |
| 288 | } | 272 | } |
| 289 | 273 | ||
| 290 | -PrintfFormatParts SplitPrintfSegment(const std::string& format_segment) | ||
| 291 | -{ | ||
| 292 | - size_t conv_idx = FindPrintfConversionIndex(format_segment); | ||
| 293 | - size_t percent_idx = format_segment.rfind('%', conv_idx); | ||
| 294 | - INTERNAL_CHECK(percent_idx != std::string::npos) | ||
| 295 | - << "debug.printf failed to locate '%' while splitting format segment"; | ||
| 296 | - return {format_segment.substr(0, percent_idx), format_segment.substr(percent_idx, conv_idx - percent_idx + 1), | ||
| 297 | - format_segment.substr(conv_idx + 1)}; | ||
| 298 | -} | ||
| 299 | - | ||
| 300 | std::vector<PrintfSegment> ParsePrintfSegments(const std::string& format) | 274 | std::vector<PrintfSegment> ParsePrintfSegments(const std::string& format) |
| 301 | { | 275 | { |
| 302 | std::vector<PrintfSegment> segments; | 276 | std::vector<PrintfSegment> segments; |
| @@ -1472,20 +1472,20 @@ TEST(BackendCceOpsTest, DebugDumpAccTileUsesWorkspace) | |||
| 1472 | EXPECT_NE(generated.find("__pypto_print_val"), std::string::npos); | 1472 | EXPECT_NE(generated.find("__pypto_print_val"), std::string::npos); |
| 1473 | } | 1473 | } |
| 1474 | 1474 | ||
| 1475 | -TEST(BackendCceOpsTest, DebugPrintfExpandsUnsigned64BitValues) | 1475 | +TEST(BackendCceOpsTest, DebugPrintfRewritesUnsigned64BitValues) |
| 1476 | { | 1476 | { |
| 1477 | auto u64_type = std::make_shared<const ir::ScalarType>(ir::DataType::UINT64); | 1477 | auto u64_type = std::make_shared<const ir::ScalarType>(ir::DataType::UINT64); |
| 1478 | auto decimal = MakeVar("decimal", u64_type); | 1478 | auto decimal = MakeVar("decimal", u64_type); |
| 1479 | auto hexadecimal = MakeVar("hexadecimal", u64_type); | 1479 | auto hexadecimal = MakeVar("hexadecimal", u64_type); |
| 1480 | - Kwargs kwargs = {{"format", std::string("decimal=%u hex=%#x\n")}}; | 1480 | + Kwargs kwargs = {{"format", std::string("decimal=%u hex=%x\n")}}; |
| 1481 | auto call = std::make_shared<const ir::Call>("debug.printf", std::vector<ir::ExprPtr>{decimal, hexadecimal}, kwargs, | 1481 | auto call = std::make_shared<const ir::Call>("debug.printf", std::vector<ir::ExprPtr>{decimal, hexadecimal}, kwargs, |
| 1482 | ir::Span::Unknown()); | 1482 | ir::Span::Unknown()); |
| 1483 | 1483 | ||
| 1484 | auto generated = RunCodegen("debug.printf", call); | 1484 | auto generated = RunCodegen("debug.printf", call); |
| 1485 | - EXPECT_NE(generated.find("__pypto_printf_u64_rest_"), std::string::npos); | 1485 | + EXPECT_NE(generated.find("decimal=%llu hex=%llx"), std::string::npos); |
| 1486 | - EXPECT_NE(generated.find("%u%09u%09u"), std::string::npos); | 1486 | + EXPECT_NE(generated.find("static_cast<unsigned long long>(decimal)"), std::string::npos); |
| 1487 | - EXPECT_NE(generated.find(">> 32"), std::string::npos); | 1487 | + EXPECT_NE(generated.find("static_cast<unsigned long long>(hexadecimal)"), std::string::npos); |
| 1488 | - EXPECT_NE(generated.find("0x%x%08x"), std::string::npos); | 1488 | + EXPECT_EQ(generated.find("pypto_printf_u64_"), std::string::npos); |
| 1489 | } | 1489 | } |
| 1490 | 1490 | ||
| 1491 | TEST(BackendCceOpsTest, DebugPrintfRewritesPromotedScalarTypes) | 1491 | TEST(BackendCceOpsTest, DebugPrintfRewritesPromotedScalarTypes) |
| @@ -1502,12 +1502,12 @@ TEST(BackendCceOpsTest, DebugPrintfRewritesPromotedScalarTypes) | |||
| 1502 | ir::Span::Unknown()); | 1502 | ir::Span::Unknown()); |
| 1503 | 1503 | ||
| 1504 | auto generated = RunCodegen("debug.printf", call); | 1504 | auto generated = RunCodegen("debug.printf", call); |
| 1505 | - EXPECT_NE(generated.find("signed=%lld small=%d unsigned=%u flag=%u ptr=%lld float=%f"), std::string::npos); | 1505 | + EXPECT_NE(generated.find("signed=%lld small=%d unsigned=%u flag=%u ptr=%p float=%f"), std::string::npos); |
| 1506 | EXPECT_NE(generated.find("static_cast<long long>(signed_value)"), std::string::npos); | 1506 | EXPECT_NE(generated.find("static_cast<long long>(signed_value)"), std::string::npos); |
| 1507 | EXPECT_NE(generated.find("static_cast<int>(small)"), std::string::npos); | 1507 | EXPECT_NE(generated.find("static_cast<int>(small)"), std::string::npos); |
| 1508 | EXPECT_NE(generated.find("static_cast<unsigned int>(unsigned_value)"), std::string::npos); | 1508 | EXPECT_NE(generated.find("static_cast<unsigned int>(unsigned_value)"), std::string::npos); |
| 1509 | EXPECT_NE(generated.find("static_cast<unsigned int>(flag)"), std::string::npos); | 1509 | EXPECT_NE(generated.find("static_cast<unsigned int>(flag)"), std::string::npos); |
| 1510 | - EXPECT_NE(generated.find("static_cast<long long>((uint64_t)ptr)"), std::string::npos); | 1510 | + EXPECT_EQ(generated.find("static_cast<long long>((uint64_t)ptr)"), std::string::npos); |
| 1511 | } | 1511 | } |
| 1512 | 1512 | ||
| 1513 | TEST(BackendCceOpsTest, DebugPrintf) | 1513 | TEST(BackendCceOpsTest, DebugPrintf) |
| @@ -1519,7 +1519,7 @@ TEST(BackendCceOpsTest, DebugPrintf) | |||
| 1519 | 1519 | ||
| 1520 | codegen::CCECodegen codegen(ir::SectionKind::Vector); | 1520 | codegen::CCECodegen codegen(ir::SectionKind::Vector); |
| 1521 | auto generated = codegen.GenerateSingle(MakeProgram(body), "a3"); | 1521 | auto generated = codegen.GenerateSingle(MakeProgram(body), "a3"); |
| 1522 | - EXPECT_NE(generated.find("cce::printf"), std::string::npos); | 1522 | + EXPECT_NE(generated.find("pypto_printf"), std::string::npos); |
| 1523 | } | 1523 | } |
| 1524 | 1524 | ||
| 1525 | TEST(BackendCceOpsTest, DebugAssert) | 1525 | TEST(BackendCceOpsTest, DebugAssert) |
| @@ -1546,7 +1546,19 @@ TEST(BackendCceOpsTest, DebugAssertWithFormatAndArgs) | |||
| 1546 | codegen::CCECodegen codegen(ir::SectionKind::Vector); | 1546 | codegen::CCECodegen codegen(ir::SectionKind::Vector); |
| 1547 | auto generated = codegen.GenerateSingle(MakeProgram(body), "a3"); | 1547 | auto generated = codegen.GenerateSingle(MakeProgram(body), "a3"); |
| 1548 | EXPECT_NE(generated.find("if (!("), std::string::npos); | 1548 | EXPECT_NE(generated.find("if (!("), std::string::npos); |
| 1549 | - EXPECT_NE(generated.find("cce::printf"), std::string::npos); | 1549 | + EXPECT_NE(generated.find("pypto_printf"), std::string::npos); |
| 1550 | +} | ||
| 1551 | + | ||
| 1552 | +TEST(BackendCceOpsTest, DebugAssertWithTextOnlyFormat) | ||
| 1553 | +{ | ||
| 1554 | + Kwargs kwargs = {{"condition_text", std::string("flag")}, {"format", std::string("flag is false\n")}}; | ||
| 1555 | + auto call = std::make_shared<const ir::Call>("debug.assert", std::vector<ir::ExprPtr>{MakeConstInt(1)}, kwargs, | ||
| 1556 | + ir::Span::Unknown()); | ||
| 1557 | + auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown()); | ||
| 1558 | + | ||
| 1559 | + codegen::CCECodegen codegen(ir::SectionKind::Vector); | ||
| 1560 | + auto generated = codegen.GenerateSingle(MakeProgram(body), "a3"); | ||
| 1561 | + EXPECT_NE(generated.find("pypto_printf(\"flag is false\\n\")"), std::string::npos); | ||
| 1550 | } | 1562 | } |
| 1551 | 1563 | ||
| 1552 | // ============================================================================ | 1564 | // ============================================================================ |
| @@ -8,19 +8,41 @@ | |||
| 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 cce::printf (replaces pto-isa's _DEBUG-guarded TPRINT). | 11 | +// Binary-mode TPRINT implementation (replaces pto-isa's _DEBUG-guarded TPRINT). |
| 12 | #pragma once | 12 | #pragma once |
| 13 | #include <cstdint> | 13 | #include <cstdint> |
| 14 | -// cce::printf is only declared by the toolchain when the print mode is enabled (jit emits | 14 | +#if defined(__ENABLE_ASC_PRINTF__) |
| 15 | -// -DPTOAS_ENABLE_CCE_PRINT=1 only for kernels that actually print). Kernels without dump | 15 | +#ifndef __ASCENDC_INCLUDE_INTERNAL_HEADERS__ |
| 16 | -// calls keep a no-op macro so the header compiles in plain mode too. | 16 | +#define __ASCENDC_INCLUDE_INTERNAL_HEADERS__ |
| 17 | -#ifndef __PYPTO_PRINTF | 17 | +#define __PYPTO_TPRINT_DEFINED_INTERNAL_HEADERS__ |
| 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 | 18 | #endif |
| 19 | +#ifndef __NPU_DEVICE__ | ||
| 20 | +#define __NPU_DEVICE__ | ||
| 21 | +#define __PYPTO_TPRINT_DEFINED_NPU_DEVICE__ | ||
| 23 | #endif | 22 | #endif |
| 23 | +#include "impl/utils/debug/asc_aicore_printf_impl.h" | ||
| 24 | +#ifdef __PYPTO_TPRINT_DEFINED_NPU_DEVICE__ | ||
| 25 | +#undef __NPU_DEVICE__ | ||
| 26 | +#undef __PYPTO_TPRINT_DEFINED_NPU_DEVICE__ | ||
| 27 | +#endif | ||
| 28 | +#ifdef __PYPTO_TPRINT_DEFINED_INTERNAL_HEADERS__ | ||
| 29 | +#undef __ASCENDC_INCLUDE_INTERNAL_HEADERS__ | ||
| 30 | +#undef __PYPTO_TPRINT_DEFINED_INTERNAL_HEADERS__ | ||
| 31 | +#endif | ||
| 32 | + | ||
| 33 | +// Use an empty dump header so pl.printf and TPRINT emit only their requested text. | ||
| 34 | +template <class... Args> | ||
| 35 | +__aicore__ static __attribute__((noinline)) void pypto_printf(const __gm__ char* fmt, Args&&... args) | ||
| 36 | +{ | ||
| 37 | +#if !(defined(ASCENDC_DUMP) && ASCENDC_DUMP == 0) | ||
| 38 | + __asc_aicore::enable_asc_diagnostics(); | ||
| 39 | + uint64_t ctrl_value = get_ctrl(); | ||
| 40 | + set_atomic_none(); | ||
| 41 | + __asc_aicore::scalar_printf_impl(DumpType::DUMP_SCALAR, fmt, "", args...); | ||
| 42 | + set_ctrl(ctrl_value); | ||
| 43 | +#endif | ||
| 44 | +} | ||
| 45 | + | ||
| 24 | template <typename V> | 46 | template <typename V> |
| 25 | __aicore__ inline const __gm__ char* __pypto_dtype_name() | 47 | __aicore__ inline const __gm__ char* __pypto_dtype_name() |
| 26 | { | 48 | { |
| @@ -71,22 +93,22 @@ template <typename V> | |||
| 71 | __aicore__ inline void __pypto_print_val(V val) | 93 | __aicore__ inline void __pypto_print_val(V val) |
| 72 | { | 94 | { |
| 73 | if constexpr (std::is_same_v<V, float>) { | 95 | if constexpr (std::is_same_v<V, float>) { |
| 74 | - __PYPTO_PRINTF("%f ", val); | 96 | + pypto_printf("%f ", val); |
| 75 | } else if constexpr (std::is_same_v<V, half>) { | 97 | } else if constexpr (std::is_same_v<V, half>) { |
| 76 | - __PYPTO_PRINTF("%f ", (float)val); | 98 | + pypto_printf("%f ", (float)val); |
| 77 | } else if constexpr (std::is_signed_v<V>) { | 99 | } else if constexpr (std::is_signed_v<V>) { |
| 78 | - __PYPTO_PRINTF("%d ", (int)val); | 100 | + pypto_printf("%d ", (int)val); |
| 79 | } else if constexpr (std::is_unsigned_v<V>) { | 101 | } else if constexpr (std::is_unsigned_v<V>) { |
| 80 | - __PYPTO_PRINTF("%u ", (unsigned int)val); | 102 | + pypto_printf("%u ", (unsigned int)val); |
| 81 | } else if constexpr (sizeof(V) == 2) { | 103 | } else if constexpr (sizeof(V) == 2) { |
| 82 | // bf16: upper 16 bits of float32 | 104 | // bf16: upper 16 bits of float32 |
| 83 | uint32_t fbits = (uint32_t)(*(uint16_t*)&val) << 16; | 105 | uint32_t fbits = (uint32_t)(*(uint16_t*)&val) << 16; |
| 84 | - __PYPTO_PRINTF("%f ", *(float*)&fbits); | 106 | + pypto_printf("%f ", *(float*)&fbits); |
| 85 | } else if constexpr (sizeof(V) == 1) { | 107 | } else if constexpr (sizeof(V) == 1) { |
| 86 | // fp8: print raw byte value | 108 | // fp8: print raw byte value |
| 87 | - __PYPTO_PRINTF("%u ", (unsigned int)(*(uint8_t*)&val)); | 109 | + pypto_printf("%u ", (unsigned int)(*(uint8_t*)&val)); |
| 88 | } else { | 110 | } else { |
| 89 | - __PYPTO_PRINTF("? "); | 111 | + pypto_printf("? "); |
| 90 | } | 112 | } |
| 91 | } | 113 | } |
| 92 | 114 | ||
| @@ -103,26 +125,26 @@ __aicore__ inline void __pypto_tprint(T& src) | |||
| 103 | } | 125 | } |
| 104 | auto* dataPtr = src.data(); | 126 | auto* dataPtr = src.data(); |
| 105 | if constexpr (T::layout == pto::Layout::ND || T::layout == pto::Layout::DN) { | 127 | if constexpr (T::layout == pto::Layout::ND || T::layout == pto::Layout::DN) { |
| 106 | - __PYPTO_PRINTF("=== [dump_tensor] dtype: %s, Layout: %s, shape=[%d,%d,%d,%d,%d] ===\n", | 128 | + pypto_printf("=== [dump_tensor] dtype: %s, Layout: %s, shape=[%d,%d,%d,%d,%d] ===\n", |
| 107 | - __pypto_dtype_name<ElemType>(), T::layout == pto::Layout::ND ? "ND" : "DN", n[0], n[1], n[2], | 129 | + __pypto_dtype_name<ElemType>(), T::layout == pto::Layout::ND ? "ND" : "DN", n[0], n[1], n[2], |
| 108 | - n[3], n[4]); | 130 | + n[3], n[4]); |
| 109 | for (int i0 = 0; i0 < n[0]; ++i0) | 131 | for (int i0 = 0; i0 < n[0]; ++i0) |
| 110 | for (int i1 = 0; i1 < n[1]; ++i1) | 132 | for (int i1 = 0; i1 < n[1]; ++i1) |
| 111 | for (int i2 = 0; i2 < n[2]; ++i2) { | 133 | for (int i2 = 0; i2 < n[2]; ++i2) { |
| 112 | - __PYPTO_PRINTF(" Batch [%d, %d, %d]:\n", i0, i1, i2); | 134 | + pypto_printf(" Batch [%d, %d, %d]:\n", i0, i1, i2); |
| 113 | for (int r = 0; r < n[3]; ++r) { | 135 | for (int r = 0; r < n[3]; ++r) { |
| 114 | for (int c = 0; c < n[4]; ++c) { | 136 | for (int c = 0; c < n[4]; ++c) { |
| 115 | int64_t off = (int64_t)i0 * s[0] + i1 * s[1] + i2 * s[2] + r * s[3] + c * s[4]; | 137 | int64_t off = (int64_t)i0 * s[0] + i1 * s[1] + i2 * s[2] + r * s[3] + c * s[4]; |
| 116 | __pypto_print_val(dataPtr[off]); | 138 | __pypto_print_val(dataPtr[off]); |
| 117 | } | 139 | } |
| 118 | - __PYPTO_PRINTF("\n"); | 140 | + pypto_printf("\n"); |
| 119 | } | 141 | } |
| 120 | } | 142 | } |
| 121 | } else if constexpr (T::layout == pto::Layout::NZ) { | 143 | } else if constexpr (T::layout == pto::Layout::NZ) { |
| 122 | int logical_rows = n[2] * n[3]; | 144 | int logical_rows = n[2] * n[3]; |
| 123 | int logical_cols = n[1] * n[4]; | 145 | int logical_cols = n[1] * n[4]; |
| 124 | - __PYPTO_PRINTF("=== [dump_tensor] dtype: %s, Layout: NZ, logical shape=[%d,%d] ===\n", | 146 | + pypto_printf("=== [dump_tensor] dtype: %s, Layout: NZ, logical shape=[%d,%d] ===\n", |
| 125 | - __pypto_dtype_name<ElemType>(), logical_rows, logical_cols); | 147 | + __pypto_dtype_name<ElemType>(), logical_rows, logical_cols); |
| 126 | for (int r = 0; r < logical_rows; ++r) { | 148 | for (int r = 0; r < logical_rows; ++r) { |
| 127 | for (int c = 0; c < logical_cols; ++c) { | 149 | for (int c = 0; c < logical_cols; ++c) { |
| 128 | int br = r / n[3], ir = r % n[3]; | 150 | int br = r / n[3], ir = r % n[3]; |
| @@ -130,27 +152,30 @@ __aicore__ inline void __pypto_tprint(T& src) | |||
| 130 | int64_t off = (int64_t)br * s[2] + bc * s[1] + ir * s[3] + ic * s[4]; | 152 | int64_t off = (int64_t)br * s[2] + bc * s[1] + ir * s[3] + ic * s[4]; |
| 131 | __pypto_print_val(dataPtr[off]); | 153 | __pypto_print_val(dataPtr[off]); |
| 132 | } | 154 | } |
| 133 | - __PYPTO_PRINTF("\n"); | 155 | + pypto_printf("\n"); |
| 134 | } | 156 | } |
| 135 | } | 157 | } |
| 136 | } else if constexpr (pto::is_tile<T>::value) { | 158 | } else if constexpr (pto::is_tile<T>::value) { |
| 137 | using DType = typename T::DType; | 159 | using DType = typename T::DType; |
| 138 | int validRows = src.GetValidRow(); | 160 | int validRows = src.GetValidRow(); |
| 139 | int validCols = src.GetValidCol(); | 161 | int validCols = src.GetValidCol(); |
| 140 | - __PYPTO_PRINTF("=== [dump_tile] dtype: %s, shape=[%d,%d], valid=[%d,%d], Layout: %s ===\n", | 162 | + pypto_printf("=== [dump_tile] dtype: %s, shape=[%d,%d], valid=[%d,%d], Layout: %s ===\n", |
| 141 | - __pypto_dtype_name<DType>(), T::Rows, T::Cols, validRows, validCols, | 163 | + __pypto_dtype_name<DType>(), T::Rows, T::Cols, validRows, validCols, |
| 142 | - pto::GetLayoutName(T::BFractal, T::SFractal)); | 164 | + pto::GetLayoutName(T::BFractal, T::SFractal)); |
| 143 | for (int r = 0; r < T::Rows; ++r) { | 165 | for (int r = 0; r < T::Rows; ++r) { |
| 144 | for (int c = 0; c < T::Cols; ++c) { | 166 | for (int c = 0; c < T::Cols; ++c) { |
| 145 | auto off = pto::GetTileOffset<T>(r, c); | 167 | auto off = pto::GetTileOffset<T>(r, c); |
| 146 | __pypto_print_val(src.GetValue(off)); | 168 | __pypto_print_val(src.GetValue(off)); |
| 147 | if (c == validCols - 1 && validCols < T::Cols) | 169 | if (c == validCols - 1 && validCols < T::Cols) |
| 148 | - __PYPTO_PRINTF("| "); | 170 | + pypto_printf("| "); |
| 149 | } | 171 | } |
| 150 | - __PYPTO_PRINTF("\n"); | 172 | + pypto_printf("\n"); |
| 151 | if (r == validRows - 1 && validRows < T::Rows) | 173 | if (r == validRows - 1 && validRows < T::Rows) |
| 152 | - __PYPTO_PRINTF("--------\n"); | 174 | + pypto_printf("--------\n"); |
| 153 | } | 175 | } |
| 154 | } | 176 | } |
| 155 | } | 177 | } |
| 156 | #define TPRINT(x) __pypto_tprint(x) | 178 | #define TPRINT(x) __pypto_tprint(x) |
| 179 | +#else | ||
| 180 | +#define TPRINT(x) ((void)0) | ||
| 181 | +#endif | ||
| @@ -23,7 +23,6 @@ from pypto.pypto_impl.ir import Call, ConstBool, ConstInt, DataType, Expr, Scala | |||
| 23 | from .._utils import _get_span_or_capture, _normalize_expr, _to_make_tuple | 23 | from .._utils import _get_span_or_capture, _normalize_expr, _to_make_tuple |
| 24 | from ._op_registry import OpSpec, op_impl, register_table | 24 | from ._op_registry import OpSpec, op_impl, register_table |
| 25 | 25 | ||
| 26 | -_PRINTF_FLAGS = set("-+ #0") | ||
| 27 | _INTEGER_CONVERSIONS = {"d", "i", "u", "x"} | 26 | _INTEGER_CONVERSIONS = {"d", "i", "u", "x"} |
| 28 | _FLOAT_CONVERSIONS = {"f"} | 27 | _FLOAT_CONVERSIONS = {"f"} |
| 29 | _POINTER_CONVERSIONS = {"p"} | 28 | _POINTER_CONVERSIONS = {"p"} |
| @@ -85,21 +84,13 @@ def _scan_printf_format(format_str: str) -> list[str]: | |||
| 85 | raise ValueError("printf does not support literal '%%'") | 84 | raise ValueError("printf does not support literal '%%'") |
| 86 | 85 | ||
| 87 | j = i + 1 | 86 | j = i + 1 |
| 88 | - while j < len(format_str) and format_str[j] in _PRINTF_FLAGS: | ||
| 89 | - j += 1 | ||
| 90 | - while j < len(format_str) and format_str[j].isdigit(): | ||
| 91 | - j += 1 | ||
| 92 | - if j < len(format_str) and format_str[j] == ".": | ||
| 93 | - j += 1 | ||
| 94 | - if j >= len(format_str) or not format_str[j].isdigit(): | ||
| 95 | - raise ValueError("printf precision must be followed by digits") | ||
| 96 | - while j < len(format_str) and format_str[j].isdigit(): | ||
| 97 | - j += 1 | ||
| 98 | if j >= len(format_str): | 87 | if j >= len(format_str): |
| 99 | raise ValueError("printf format string ends with an incomplete conversion") | 88 | raise ValueError("printf format string ends with an incomplete conversion") |
| 100 | 89 | ||
| 101 | conversion = format_str[j] | 90 | conversion = format_str[j] |
| 102 | if conversion not in _SUPPORTED_CONVERSIONS: | 91 | if conversion not in _SUPPORTED_CONVERSIONS: |
| 92 | + if conversion in "-+ #0." or conversion.isdigit(): | ||
| 93 | + raise ValueError("printf does not support flags, width, or precision") | ||
| 103 | raise ValueError(f"printf does not support conversion '%{conversion}'") | 94 | raise ValueError(f"printf does not support conversion '%{conversion}'") |
| 104 | 95 | ||
| 105 | specs.append(format_str[i:j + 1]) | 96 | specs.append(format_str[i:j + 1]) |
| @@ -163,10 +163,10 @@ _DEFAULT_CCE_JIT_COMPILE_CONFIG = JitCompileConfig( | |||
| 163 | "-I{toolkit_home}/include", | 163 | "-I{toolkit_home}/include", |
| 164 | ), | 164 | ), |
| 165 | print_debug_flags=( | 165 | print_debug_flags=( |
| 166 | - "--cce-enable-print", | 166 | + "-isystem", |
| 167 | - "-D_DEBUG", | 167 | + "{toolkit_home}/asc/include", |
| 168 | - "-DCCEBlockMaxSize=1048576", | 168 | + "-isystem", |
| 169 | - "-DPTOAS_ENABLE_CCE_PRINT=1", | 169 | + "{toolkit_home}/asc", |
| 170 | ), | 170 | ), |
| 171 | llvm_common_args=( | 171 | llvm_common_args=( |
| 172 | "-mllvm", | 172 | "-mllvm", |
| @@ -196,7 +196,7 @@ CPP_LITERAL_PATTERN = re.compile( | |||
| 196 | r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'', | 196 | r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'', |
| 197 | ) | 197 | ) |
| 198 | TPRINT_CALL_PATTERN = re.compile(r"\bTPRINT\s*\(") | 198 | TPRINT_CALL_PATTERN = re.compile(r"\bTPRINT\s*\(") |
| 199 | -CCE_PRINTF_CALL_PATTERN = re.compile(r"\bcce::printf\s*\(") | 199 | +PYPTO_PRINTF_CALL_PATTERN = re.compile(r"\bpypto_printf\s*\(") |
| 200 | 200 | ||
| 201 | 201 | ||
| 202 | def _sanitize_artifact_component(value: str) -> str: | 202 | def _sanitize_artifact_component(value: str) -> str: |
| @@ -1064,7 +1064,7 @@ def _generate_caller_cpp( | |||
| 1064 | def _detect_print_debug_from_cpp(content: str) -> bool: | 1064 | def _detect_print_debug_from_cpp(content: str) -> bool: |
| 1065 | """Best-effort detection for device-side debug print usage in generated C++.""" | 1065 | """Best-effort detection for device-side debug print usage in generated C++.""" |
| 1066 | scrubbed = CPP_LITERAL_PATTERN.sub(" ", content) | 1066 | scrubbed = CPP_LITERAL_PATTERN.sub(" ", content) |
| 1067 | - return bool(TPRINT_CALL_PATTERN.search(scrubbed) or CCE_PRINTF_CALL_PATTERN.search(scrubbed)) | 1067 | + return bool(TPRINT_CALL_PATTERN.search(scrubbed) or PYPTO_PRINTF_CALL_PATTERN.search(scrubbed)) |
| 1068 | 1068 | ||
| 1069 | 1069 | ||
| 1070 | def _build_bisheng_flags( | 1070 | def _build_bisheng_flags( |
| @@ -1393,9 +1393,12 @@ def _write_codegen_artifacts(result: CodegenResult) -> None: | |||
| 1393 | 1393 | ||
| 1394 | def _add_kernel_header(result: CodegenResult) -> CodegenResult: | 1394 | def _add_kernel_header(result: CodegenResult) -> CodegenResult: |
| 1395 | """Add the translation-unit header after all target sources are assembled.""" | 1395 | """Add the translation-unit header after all target sources are assembled.""" |
| 1396 | + header = KERNEL_HEADER_SINGLE | ||
| 1397 | + if result.needs_print_debug: | ||
| 1398 | + header += "\n#define __ENABLE_ASC_PRINTF__ 1\n" | ||
| 1396 | return dataclasses.replace( | 1399 | return dataclasses.replace( |
| 1397 | result, | 1400 | result, |
| 1398 | - content=f"{KERNEL_HEADER_SINGLE}\n{result.content.lstrip()}", | 1401 | + content=f"{header}\n{result.content.lstrip()}", |
| 1399 | ) | 1402 | ) |
| 1400 | 1403 | ||
| 1401 | 1404 | ||
| @@ -227,55 +227,6 @@ def _signature_parts(entry_params): | |||
| 227 | return ", ".join(decls), names | 227 | return ", ".join(decls), names |
| 228 | 228 | ||
| 229 | 229 | ||
| 230 | -# Markers of device-side print usage in the generated kernel source. Any hit means the impl | ||
| 231 | -# needs the no-prefix AscendC wrapper: TPRINT/dump helpers live in pypto_tprint.h, and pl.printf | ||
| 232 | -# lowers to plain cce::printf calls that are rewritten to the same wrapper. | ||
| 233 | -_TPRINT_MARKERS = ("TPRINT(", "cce::printf(", "__pypto_dtype_name", "__pypto_print_val") | ||
| 234 | - | ||
| 235 | - | ||
| 236 | -def _needs_tprint_support(content: str) -> bool: | ||
| 237 | - return any(marker in content for marker in _TPRINT_MARKERS) | ||
| 238 | - | ||
| 239 | - | ||
| 240 | -def _write_ascendc_tprint_header(kernel_meta_dir: str) -> None: | ||
| 241 | - """Write a no-prefix AscendC dump copy of pypto_tprint.h next to the impl source. | ||
| 242 | - | ||
| 243 | - The shared header (included by default from codegen) prints via cce::printf | ||
| 244 | - (jit-mode compatible), but the OPC toolchain swallows cce::printf output and | ||
| 245 | - AscendC::printf prepends a "[AIV Block x/y]" dumphead. The local copy remaps | ||
| 246 | - __PYPTO_PRINTF to a wrapper around __asc_aicore::scalar_printf_impl with an | ||
| 247 | - empty dumphead; it is included by a quoted name so the impl resolves it ahead | ||
| 248 | - of the packaged header. | ||
| 249 | - """ | ||
| 250 | - jit_macro_def = ( | ||
| 251 | - "#ifndef __PYPTO_PRINTF\n" | ||
| 252 | - "#if defined(PTOAS_ENABLE_CCE_PRINT) && PTOAS_ENABLE_CCE_PRINT\n" | ||
| 253 | - "#define __PYPTO_PRINTF(...) cce::printf(__VA_ARGS__)\n" | ||
| 254 | - "#else\n" | ||
| 255 | - "#define __PYPTO_PRINTF(...) ((void)0)\n" | ||
| 256 | - "#endif\n" | ||
| 257 | - "#endif\n" | ||
| 258 | - ) | ||
| 259 | - opc_macro_def = ( | ||
| 260 | - "#ifndef __PYPTO_PRINTF\n" | ||
| 261 | - "template <class... Args>\n" | ||
| 262 | - "__aicore__ inline void __pypto_aicore_printf(const __gm__ char* fmt, Args&&... args)\n" | ||
| 263 | - "{\n" | ||
| 264 | - " __asc_aicore::enable_asc_diagnostics();\n" | ||
| 265 | - " __asc_aicore::scalar_printf_impl(__asc_aicore::DumpType::DUMP_SCALAR, fmt, \"\", args...);\n" | ||
| 266 | - "}\n" | ||
| 267 | - "#define __PYPTO_PRINTF(...) __pypto_aicore_printf(__VA_ARGS__)\n" | ||
| 268 | - "#endif\n" | ||
| 269 | - ) | ||
| 270 | - src_header = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "include", "pypto_tprint.h") | ||
| 271 | - tprint_content = open(src_header, "r", encoding="utf-8").read() | ||
| 272 | - tprint_content = tprint_content.replace(jit_macro_def, opc_macro_def) | ||
| 273 | - dst_header = os.path.join(kernel_meta_dir, "pypto_tprint.h") | ||
| 274 | - if not os.path.exists(dst_header) or open(dst_header, "r", encoding="utf-8").read() != tprint_content: | ||
| 275 | - with open(dst_header, "w", encoding="utf-8") as f: | ||
| 276 | - f.write(tprint_content) | ||
| 277 | - | ||
| 278 | - | ||
| 279 | def _gen_infer_cpp(cg, tilingkey_header: str, kernel_cpp: str) -> str: | 230 | def _gen_infer_cpp(cg, tilingkey_header: str, kernel_cpp: str) -> str: |
| 280 | sig, names = _signature_parts(cg.entry_params) | 231 | sig, names = _signature_parts(cg.entry_params) |
| 281 | ws_idx = len(names) - 2 if len(names) >= 2 else None | 232 | ws_idx = len(names) - 2 if len(names) >= 2 else None |
| @@ -287,24 +238,10 @@ def _gen_infer_cpp(cg, tilingkey_header: str, kernel_cpp: str) -> str: | |||
| 287 | f" AscendC::SetSysWorkspaceForce({ws});\n GM_ADDR usrWorkspace = AscendC::GetUserWorkspace({ws});\n" | 238 | f" AscendC::SetSysWorkspaceForce({ws});\n GM_ADDR usrWorkspace = AscendC::GetUserWorkspace({ws});\n" |
| 288 | ) | 239 | ) |
| 289 | inner[ws_idx] = "usrWorkspace" | 240 | inner[ws_idx] = "usrWorkspace" |
| 290 | - # The infer source is only compiled to extract tiling metadata, so the dump | ||
| 291 | - # helpers are replaced with no-op stubs and the header include is dropped. | ||
| 292 | - # This keeps the infer source self-contained (no pypto_tprint.h dependency). | ||
| 293 | - infer_kernel_cpp = kernel_cpp.replace( | ||
| 294 | - "#include <pypto_tprint.h>\n", "" | ||
| 295 | - ) | ||
| 296 | - tprint_stubs = ( | ||
| 297 | - "#define TPRINT(x)\n" | ||
| 298 | - "template <typename T>\n" | ||
| 299 | - "__aicore__ inline const __gm__ char* __pypto_dtype_name() { return \"\"; }\n" | ||
| 300 | - "template <typename V>\n" | ||
| 301 | - "__aicore__ inline void __pypto_print_val(V) {}\n" | ||
| 302 | - ) | ||
| 303 | return ( | 241 | return ( |
| 304 | '#include "kernel_operator.h"\n' | 242 | '#include "kernel_operator.h"\n' |
| 305 | f'#include "{tilingkey_header}"\n' | 243 | f'#include "{tilingkey_header}"\n' |
| 306 | - f"{tprint_stubs}" | 244 | + f"{kernel_cpp}\n" |
| 307 | - f"{infer_kernel_cpp}\n" | ||
| 308 | f'extern "C" __global__ AICORE void {cg.kernel_name}({sig})\n' | 245 | f'extern "C" __global__ AICORE void {cg.kernel_name}({sig})\n' |
| 309 | "{\n" | 246 | "{\n" |
| 310 | f" KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);\n" | 247 | f" KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);\n" |
| @@ -448,6 +385,8 @@ def _setup_options(op_info, compile_options, op_compile_option, extend_options): | |||
| 448 | opt.compile_options = compile_pre_process(op_info, opt.compile_options) | 385 | opt.compile_options = compile_pre_process(op_info, opt.compile_options) |
| 449 | _update_compile_option(_op_info_get(op_info, "kernel_name"), opt.compile_options, extend_options) | 386 | _update_compile_option(_op_info_get(op_info, "kernel_name"), opt.compile_options, extend_options) |
| 450 | opt.compile_options.append("-DASCENDC_TPL_KERNEL") | 387 | opt.compile_options.append("-DASCENDC_TPL_KERNEL") |
| 388 | + pypto_include = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "include") | ||
| 389 | + opt.compile_options.append(f"-I{pypto_include}") | ||
| 451 | return opt | 390 | return opt |
| 452 | 391 | ||
| 453 | 392 | ||
| @@ -747,20 +686,7 @@ def pypto_compile_op( | |||
| 747 | impl_cpp_name = f"{kernel_name}_{packed}_impl.cpp" | 686 | impl_cpp_name = f"{kernel_name}_{packed}_impl.cpp" |
| 748 | impl_src = os.path.join(cg.build_dir, "kernel.cpp") | 687 | impl_src = os.path.join(cg.build_dir, "kernel.cpp") |
| 749 | impl_dst = os.path.join(kernel_meta_dir, impl_cpp_name) | 688 | impl_dst = os.path.join(kernel_meta_dir, impl_cpp_name) |
| 750 | - impl_content = open(impl_src, "r", encoding="utf-8").read() | 689 | + shutil.copyfile(impl_src, impl_dst) |
| 751 | - needs_tprint_support = _needs_tprint_support(impl_content) | ||
| 752 | - impl_content = impl_content.replace("cce::printf", "__pypto_aicore_printf") | ||
| 753 | - if needs_tprint_support: | ||
| 754 | - # Binary-mode TPRINT helpers live in the shared pypto_tprint.h header, which uses | ||
| 755 | - # cce::printf for jit-mode compatibility. The OPC toolchain has no working | ||
| 756 | - # cce::printf output, so drop a no-prefix AscendC dump copy next to the impl and | ||
| 757 | - # resolve it by a quoted local name (the include itself is emitted by codegen). | ||
| 758 | - _write_ascendc_tprint_header(kernel_meta_dir) | ||
| 759 | - impl_content = impl_content.replace( | ||
| 760 | - '#include <pypto_tprint.h>\n', '#include "pypto_tprint.h"\n' | ||
| 761 | - ) | ||
| 762 | - with open(impl_dst, "w", encoding="utf-8") as f: | ||
| 763 | - f.write(impl_content) | ||
| 764 | for hdr in (f for f in os.listdir(cg.build_dir) if f.endswith(".h")): | 690 | for hdr in (f for f in os.listdir(cg.build_dir) if f.endswith(".h")): |
| 765 | shutil.copyfile(os.path.join(cg.build_dir, hdr), os.path.join(kernel_meta_dir, hdr)) | 691 | shutil.copyfile(os.path.join(cg.build_dir, hdr), os.path.join(kernel_meta_dir, hdr)) |
| 766 | 692 | ||
| @@ -774,7 +700,6 @@ def pypto_compile_op( | |||
| 774 | dst_o = os.path.join(kernel_meta_dir, f"{kernel_name}_{channel}_{packed}.o") | 700 | dst_o = os.path.join(kernel_meta_dir, f"{kernel_name}_{channel}_{packed}.o") |
| 775 | sub_arch = _core_arch(core_type) | 701 | sub_arch = _core_arch(core_type) |
| 776 | cmd = gen_compile_cmd_v220(src_path, dst_o, opt, sub_arch, "") # kernel.cpp self-includes its tiling.h | 702 | cmd = gen_compile_cmd_v220(src_path, dst_o, opt, sub_arch, "") # kernel.cpp self-includes its tiling.h |
| 777 | - cmd += [f"-I{os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'include')}"] | ||
| 778 | cmd += [f"-D{TILING_KEY_MACRO}={packed}UL"] | 703 | cmd += [f"-D{TILING_KEY_MACRO}={packed}UL"] |
| 779 | cmd += [f"-D{MIX_CORE_MACRO}=1"] | 704 | cmd += [f"-D{MIX_CORE_MACRO}=1"] |
| 780 | if CommonUtility.is_c310(): | 705 | if CommonUtility.is_c310(): |
| @@ -63,16 +63,10 @@ def printf_di_kernel( | |||
| 63 | @pytest.mark.soc("950") | 63 | @pytest.mark.soc("950") |
| 64 | @pypto.options(pass_options={"enable_slice": False}) | 64 | @pypto.options(pass_options={"enable_slice": False}) |
| 65 | def test_printf_di(): | 65 | def test_printf_di(): |
| 66 | - """测试 pl.printf 的 %d/%i 格式说明符,验证有符号整数(bool、INT8、INT16、INT32、INT64)标量参数的打印功能。 | ||
| 67 | - | ||
| 68 | - 输入:out=全零 INT32 张量[1],flag=True,v_i8=-42,v_i16=-1234,v_i32=-56789,v_i64=-1234567890。 | ||
| 69 | - 预期:kernel 内通过 %d 和 %i 各打印一行含上述参数的格式化字符串, | ||
| 70 | - 最后将 out[0] 置为 1;host 侧通过 assert out[0]==1 验证 kernel 正常执行完毕。 | ||
| 71 | - """ | ||
| 72 | _check_npu() | 66 | _check_npu() |
| 73 | logging.info("------------test_printf_di--------------") | 67 | logging.info("------------test_printf_di--------------") |
| 74 | out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | 68 | out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) |
| 75 | - printf_di_kernel(out, True, -42, -1234, -56789, -1234567890) | 69 | + printf_di_kernel(out, True, -42, -1234, -56789, -1099511627776) |
| 76 | torch.npu.synchronize() | 70 | torch.npu.synchronize() |
| 77 | assert out.tolist()[0] == 1, f"got {out.tolist()}" | 71 | assert out.tolist()[0] == 1, f"got {out.tolist()}" |
| 78 | logging.info("printf_di passed!") | 72 | logging.info("printf_di passed!") |
| @@ -95,6 +89,16 @@ def printf_u_kernel( | |||
| 95 | out[0] = 2 | 89 | out[0] = 2 |
| 96 | 90 | ||
| 97 | 91 | ||
| 92 | +@pytest.mark.soc("950") | ||
| 93 | +@pypto.options(pass_options={"enable_slice": False}) | ||
| 94 | +def test_printf_u(): | ||
| 95 | + _check_npu() | ||
| 96 | + out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | ||
| 97 | + printf_u_kernel(out, True, 250, 60000, 4000000000, 1099511627899) | ||
| 98 | + torch.npu.synchronize() | ||
| 99 | + assert out.tolist()[0] == 2, f"got {out.tolist()}" | ||
| 100 | + | ||
| 101 | + | ||
| 98 | # ============================================================================= | 102 | # ============================================================================= |
| 99 | # Test 3: %f 浮点数 + 精度控制 | 103 | # Test 3: %f 浮点数 + 精度控制 |
| 100 | # ============================================================================= | 104 | # ============================================================================= |
| @@ -104,11 +108,20 @@ def printf_f_kernel( | |||
| 104 | value_f: pl.DT_FP32, | 108 | value_f: pl.DT_FP32, |
| 105 | ): | 109 | ): |
| 106 | with pl.section_vector(): | 110 | with pl.section_vector(): |
| 107 | - pl.printf("printf_f default: val=%f\n", value_f) | 111 | + pl.printf("printf_f: val=%f\n", value_f) |
| 108 | - pl.printf("printf_f signed: val=%+08.3f\n", value_f) | ||
| 109 | out[0] = 3 | 112 | out[0] = 3 |
| 110 | 113 | ||
| 111 | 114 | ||
| 115 | +@pytest.mark.soc("950") | ||
| 116 | +@pypto.options(pass_options={"enable_slice": False}) | ||
| 117 | +def test_printf_f(): | ||
| 118 | + _check_npu() | ||
| 119 | + out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | ||
| 120 | + printf_f_kernel(out, 3.25) | ||
| 121 | + torch.npu.synchronize() | ||
| 122 | + assert out.tolist()[0] == 3, f"got {out.tolist()}" | ||
| 123 | + | ||
| 124 | + | ||
| 112 | # ============================================================================= | 125 | # ============================================================================= |
| 113 | # Test 4: %x 十六进制 | 126 | # Test 4: %x 十六进制 |
| 114 | # ============================================================================= | 127 | # ============================================================================= |
| @@ -121,10 +134,20 @@ def printf_x_kernel( | |||
| 121 | v_u64: pl.DT_UINT64, | 134 | v_u64: pl.DT_UINT64, |
| 122 | ): | 135 | ): |
| 123 | with pl.section_vector(): | 136 | with pl.section_vector(): |
| 124 | - pl.printf("printf_x: u8=%#04x u16=%#06x u32=%#08x u64=%#010x\n", v_u8, v_u16, v_u32, v_u64) | 137 | + pl.printf("printf_x: u8=%x u16=%x u32=%x u64=%x\n", v_u8, v_u16, v_u32, v_u64) |
| 125 | out[0] = 4 | 138 | out[0] = 4 |
| 126 | 139 | ||
| 127 | 140 | ||
| 141 | +@pytest.mark.soc("950") | ||
| 142 | +@pypto.options(pass_options={"enable_slice": False}) | ||
| 143 | +def test_printf_x(): | ||
| 144 | + _check_npu() | ||
| 145 | + out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | ||
| 146 | + printf_x_kernel(out, 0xAB, 0xCDEF, 0x89ABCDEF, 0x123456789ABCDEF0) | ||
| 147 | + torch.npu.synchronize() | ||
| 148 | + assert out.tolist()[0] == 4, f"got {out.tolist()}" | ||
| 149 | + | ||
| 150 | + | ||
| 128 | # ============================================================================= | 151 | # ============================================================================= |
| 129 | # Test 5: %p 指针地址 | 152 | # Test 5: %p 指针地址 |
| 130 | # ============================================================================= | 153 | # ============================================================================= |
| @@ -141,12 +164,6 @@ def printf_ptr_kernel( | |||
| 141 | @pytest.mark.soc("950") | 164 | @pytest.mark.soc("950") |
| 142 | @pypto.options(pass_options={"enable_slice": False}) | 165 | @pypto.options(pass_options={"enable_slice": False}) |
| 143 | def test_printf_ptr(): | 166 | def test_printf_ptr(): |
| 144 | - """测试 pl.printf 的 %p 格式说明符,验证指针地址的打印功能。 | ||
| 145 | - | ||
| 146 | - 输入:out=全零 INT32 张量[1],data=FP16 张量的指针。 | ||
| 147 | - 预期:kernel 内通过 %p 打印 data 指针的十六进制地址值, | ||
| 148 | - 最后将 out[0] 置为 6;host 侧通过 assert out[0]==6 验证 kernel 正常执行完毕。 | ||
| 149 | - """ | ||
| 150 | _check_npu() | 167 | _check_npu() |
| 151 | logging.info("------------test_printf_ptr--------------") | 168 | logging.info("------------test_printf_ptr--------------") |
| 152 | out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | 169 | out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) |
| @@ -169,6 +186,16 @@ def printf_text_loc_kernel( | |||
| 169 | out[0] = 5 | 186 | out[0] = 5 |
| 170 | 187 | ||
| 171 | 188 | ||
| 189 | +@pytest.mark.soc("950") | ||
| 190 | +@pypto.options(pass_options={"enable_slice": False}) | ||
| 191 | +def test_printf_text_loc(): | ||
| 192 | + _check_npu() | ||
| 193 | + out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | ||
| 194 | + printf_text_loc_kernel(out) | ||
| 195 | + torch.npu.synchronize() | ||
| 196 | + assert out.tolist()[0] == 5, f"got {out.tolist()}" | ||
| 197 | + | ||
| 198 | + | ||
| 172 | # ============================================================================= | 199 | # ============================================================================= |
| 173 | # Test 7: for 循环内使用 printf | 200 | # Test 7: for 循环内使用 printf |
| 174 | # ============================================================================= | 201 | # ============================================================================= |
| @@ -187,12 +214,6 @@ def printf_for_loop_kernel( | |||
| 187 | @pytest.mark.soc("950") | 214 | @pytest.mark.soc("950") |
| 188 | @pypto.options(pass_options={"enable_slice": False}) | 215 | @pypto.options(pass_options={"enable_slice": False}) |
| 189 | def test_printf_for_loop(): | 216 | def test_printf_for_loop(): |
| 190 | - """测试 pl.printf 在 for 循环内的使用,验证 printf 在循环控制流中每轮迭代能正确打印格式字符串。 | ||
| 191 | - | ||
| 192 | - 输入:out=全零 INT32 张量[1],无其他参数。kernel 内 for i in range(0,5) 累加 sum_val += i。 | ||
| 193 | - 预期:循环 5 次,每次打印 "for_loop: i=%d sum=%d",最终 sum_val = 0+1+2+3+4 = 10, | ||
| 194 | - out[0] 置为 sum_val;host 侧通过 torch.equal(out, [10]) 验证结果正确。 | ||
| 195 | - """ | ||
| 196 | _check_npu() | 217 | _check_npu() |
| 197 | logging.info("------------test_printf_for_loop--------------") | 218 | logging.info("------------test_printf_for_loop--------------") |
| 198 | out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | 219 | out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) |
| @@ -220,6 +241,20 @@ def printf_if_else_kernel( | |||
| 220 | out[0] = -100 | 241 | out[0] = -100 |
| 221 | 242 | ||
| 222 | 243 | ||
| 244 | +@pytest.mark.parametrize( | ||
| 245 | + "flag,expected_value", | ||
| 246 | + [(True, 100), (False, -100)], | ||
| 247 | +) | ||
| 248 | +@pytest.mark.soc("950") | ||
| 249 | +@pypto.options(pass_options={"enable_slice": False}) | ||
| 250 | +def test_printf_if_else(flag, expected_value): | ||
| 251 | + _check_npu() | ||
| 252 | + out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | ||
| 253 | + printf_if_else_kernel(out, flag) | ||
| 254 | + torch.npu.synchronize() | ||
| 255 | + assert out.tolist()[0] == expected_value, f"got {out.tolist()}" | ||
| 256 | + | ||
| 257 | + | ||
| 223 | # ============================================================================= | 258 | # ============================================================================= |
| 224 | # Test 9: while 循环内使用 printf | 259 | # Test 9: while 循环内使用 printf |
| 225 | # ============================================================================= | 260 | # ============================================================================= |
| @@ -235,6 +270,16 @@ def printf_while_kernel( | |||
| 235 | out[0] = x | 270 | out[0] = x |
| 236 | 271 | ||
| 237 | 272 | ||
| 273 | +@pytest.mark.soc("950") | ||
| 274 | +@pypto.options(pass_options={"enable_slice": False}) | ||
| 275 | +def test_printf_while(): | ||
| 276 | + _check_npu() | ||
| 277 | + out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | ||
| 278 | + printf_while_kernel(out) | ||
| 279 | + torch.npu.synchronize() | ||
| 280 | + assert out.tolist()[0] == 4, f"got {out.tolist()}" | ||
| 281 | + | ||
| 282 | + | ||
| 238 | # ============================================================================= | 283 | # ============================================================================= |
| 239 | # Test 10: 带 loc=True + 多格式组合 | 284 | # Test 10: 带 loc=True + 多格式组合 |
| 240 | # ============================================================================= | 285 | # ============================================================================= |
| @@ -250,14 +295,15 @@ def printf_loc_combo_kernel( | |||
| 250 | pl.printf("loc_combo: post setval out[0]=%d\n", v_i32, loc=True) | 295 | pl.printf("loc_combo: post setval out[0]=%d\n", v_i32, loc=True) |
| 251 | 296 | ||
| 252 | 297 | ||
| 298 | +@pytest.mark.soc("950") | ||
| 299 | +@pypto.options(pass_options={"enable_slice": False}) | ||
| 300 | +def test_printf_loc_combo(): | ||
| 301 | + _check_npu() | ||
| 302 | + out = torch.zeros(1, device=ST_DEVICE, dtype=torch.int32) | ||
| 303 | + printf_loc_combo_kernel(out, 7, 1.5) | ||
| 304 | + torch.npu.synchronize() | ||
| 305 | + assert out.tolist()[0] == 7, f"got {out.tolist()}" | ||
| 306 | + | ||
| 307 | + | ||
| 253 | if __name__ == "__main__": | 308 | if __name__ == "__main__": |
| 254 | - logging.basicConfig(level=logging.INFO, format="%(message)s") | 309 | + raise SystemExit(pytest.main([__file__, "-v"])) |
| 255 | - tests = [ | ||
| 256 | - test_printf_di, | ||
| 257 | - test_printf_ptr, | ||
| 258 | - test_printf_for_loop, | ||
| 259 | - ] | ||
| 260 | - for t in tests: | ||
| 261 | - t() | ||
| 262 | - logging.info(f"{t.__name__} passed!") | ||
| 263 | - logging.info("\nAll pl.printf NPU tests passed!") | ||
| @@ -57,11 +57,11 @@ def printf_doc_examples_kernel( | |||
| 57 | # Example 1: %d integer | 57 | # Example 1: %d integer |
| 58 | pl.printf("flag=%d, offset=%d\n", flag, offset) | 58 | pl.printf("flag=%d, offset=%d\n", flag, offset) |
| 59 | 59 | ||
| 60 | - # Example 2: %+08.3f float | 60 | + # Example 2: %f float |
| 61 | - pl.printf("value=%+08.3f\n", value_f32) | 61 | + pl.printf("value=%f\n", value_f32) |
| 62 | 62 | ||
| 63 | - # Example 3: %#08x hex | 63 | + # Example 3: %x hex |
| 64 | - pl.printf("addr=%#08x\n", addr_u32) | 64 | + pl.printf("addr=0x%x\n", addr_u32) |
| 65 | 65 | ||
| 66 | # Example 4: plain text | 66 | # Example 4: plain text |
| 67 | pl.printf("reached checkpoint A\n") | 67 | pl.printf("reached checkpoint A\n") |
| @@ -102,8 +102,8 @@ def test_printf_doc_examples(): | |||
| 102 | Inputs: flag=True, offset=32, value_f32=3.14, addr_u32=0x1234, i=5 | 102 | Inputs: flag=True, offset=32, value_f32=3.14, addr_u32=0x1234, i=5 |
| 103 | Expected device log: | 103 | Expected device log: |
| 104 | flag=1, offset=32 | 104 | flag=1, offset=32 |
| 105 | - value=+003.140 | 105 | + value=3.140000 |
| 106 | - addr=0x001234 | 106 | + addr=0x1234 |
| 107 | reached checkpoint A | 107 | reached checkpoint A |
| 108 | <source_location> debug: i=5 | 108 | <source_location> debug: i=5 |
| 109 | """ | 109 | """ |
| @@ -125,7 +125,9 @@ def test_shared_library_and_caller_use_the_same_resolved_target(monkeypatch, tmp | |||
| 125 | assert build_arch == arch | 125 | assert build_arch == arch |
| 126 | assert f"--cce-aicore-arch={target.npu_arch}" in flags | 126 | assert f"--cce-aicore-arch={target.npu_arch}" in flags |
| 127 | assert "--cce-fatobj-link" in flags | 127 | assert "--cce-fatobj-link" in flags |
| 128 | - assert "--cce-enable-print" in flags | 128 | + assert "--cce-enable-print" not in flags |
| 129 | + assert "/toolkit/asc/include" in flags | ||
| 130 | + assert "/toolkit/asc" in flags | ||
| 129 | assert f"ResolveLaunchBlockDim<{cores[0]}, {cores[1]}>" in caller | 131 | assert f"ResolveLaunchBlockDim<{cores[0]}, {cores[1]}>" in caller |
| 130 | 132 | ||
| 131 | 133 | ||