Merged
fix(pypto_pro):delete unuse tensor ops #6613
huanyongbenAdd on Sep 22
fix(pypto_pro):delete unuse tensor ops #6613
Merged
Merged fromhuanyongben/pypto_open9.2.0intocann/pypto9.2.0
Total: 40 files changed+700-2498
| @@ -38,7 +38,7 @@ def stage1(ki, a, b_l1, a_l1_db, left_db, right_db, acc_db, mm1_vec_db): | |||
| 38 | 38 | ||
| 39 | ### 2. 声明跨核共享Buffer | 39 | ### 2. 声明跨核共享Buffer |
| 40 | 40 | ||
| 41 | -跨核共享Buffer使用make_tile_group接口进行声明,tile数目由用户自主分配,通过fwd_ids和bwd_ids参数配置核间正反向同步id,若未配置,则不会插入对应的核间同步。 | 41 | +跨核共享Buffer使用make_tile_group接口进行声明,通过fwd_ids和bwd_ids参数配置核间正反向同步id,若未配置,则不会插入对应的核间同步。 |
| 42 | 42 | ||
| 43 | 其中fwd_ids为正向同步(生产者写完通知消费者),生产者stage之后插入set、消费者stage之前插入wait;bwd_ids为反向同步(消费者用完通知生产者可以覆写),消费者stage之后插入set、生产者stage之前插入wait。只配置fwd_ids时,仅保证消费者读到的是生产者写完的数据,不保证生产者下一轮覆写时消费者已经读完。每次迭代实际使用的id按`ids[迭代序号 % len(ids)]`轮转取用。 | 43 | 其中fwd_ids为正向同步(生产者写完通知消费者),生产者stage之后插入set、消费者stage之前插入wait;bwd_ids为反向同步(消费者用完通知生产者可以覆写),消费者stage之后插入set、生产者stage之前插入wait。只配置fwd_ids时,仅保证消费者读到的是生产者写完的数据,不保证生产者下一轮覆写时消费者已经读完。每次迭代实际使用的id按`ids[迭代序号 % len(ids)]`轮转取用。 |
| 44 | 44 | ||
| @@ -54,7 +54,9 @@ mm1_vec_db = pl.make_tile_group( | |||
| 54 | ) | 54 | ) |
| 55 | ``` | 55 | ``` |
| 56 | 56 | ||
| 57 | -### 3. 编写主循环 | 57 | +Tile数不能随意取,与上游核提前迭代计算的次数相关,且直接影响流水性能,具体规则参见[使用约束](#使用约束)。 |
| 58 | + | ||
| 59 | +### 编写主循环 | ||
| 58 | 60 | ||
| 59 | 主循环内stage函数按照依赖关系顺序进行书写,需要保证stage之间为CV交替。 | 61 | 主循环内stage函数按照依赖关系顺序进行书写,需要保证stage之间为CV交替。 |
| 60 | 62 | ||
| @@ -101,7 +103,7 @@ for kj in pl.range(0, M_ITER): # 第二条流水 | |||
| 101 | | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 103 | | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |
| 102 | | preload | 表示上游核提前迭代计算的次数,类型为int或list[int]。传入单个整数时,kernel内所有流水循环共用该值;传入列表时,按源码顺序为每个流水循环单独配置。取值为0的循环不做流水改写,只在原串行循环中插入核间同步。 | | 104 | | preload | 表示上游核提前迭代计算的次数,类型为int或list[int]。传入单个整数时,kernel内所有流水循环共用该值;传入列表时,按源码顺序为每个流水循环单独配置。取值为0的循环不做流水改写,只在原串行循环中插入核间同步。 | |
| 103 | 105 | ||
| 104 | -**建议流程**:先配置**preload=0**执行,确认串行版本精度正确,再逐步调大preload开启流水。多个流水循环时可以只把其中一条配成0(如preload=[0, 2]),单独验证这条流水的串行精度。 | 106 | +**建议流程**:先配置**preload=0**执行,确认串行版本精度正确,再逐步调大preload开启流水。调大preload的同时,需按[使用约束](#使用约束)检查各跨核Buffer的Tile数是否够用。多个流水循环时可以只把其中一条配成0(如preload=[0, 2]),单独验证这条流水的串行精度。 |
| 105 | 107 | ||
| 106 | ```python | 108 | ```python |
| 107 | import pypto_pro.language as pl | 109 | import pypto_pro.language as pl |
| @@ -153,6 +155,9 @@ def pipeline_demo_kernel(...): | |||
| 153 | - 允许跨核Buffer之间、跨核Buffer与核内Buffer之间进行地址复用,但最多允许两块Buffer复用,且复用双方的Tile数需要一致。 | 155 | - 允许跨核Buffer之间、跨核Buffer与核内Buffer之间进行地址复用,但最多允许两块Buffer复用,且复用双方的Tile数需要一致。 |
| 154 | - 地址复用的Buffer之间必须声明相同的mutex_ids。mutex锁的是地址,不同的id等于没有互斥。 | 156 | - 地址复用的Buffer之间必须声明相同的mutex_ids。mutex锁的是地址,不同的id等于没有互斥。 |
| 155 | - 一个跨核Buffer(通过fwd_ids/bwd_ids标记)需要恰好被两个stage使用,且这两个stage分别在cube和vector上,构成一对一的生产者/消费者关系。 | 157 | - 一个跨核Buffer(通过fwd_ids/bwd_ids标记)需要恰好被两个stage使用,且这两个stage分别在cube和vector上,构成一对一的生产者/消费者关系。 |
| 158 | +- 跨核Buffer的生产者stage与消费者stage必须是主循环中相邻的两个stage,即消费者紧跟在生产者之后,不允许跨过中间的stage直接交接(如stage1写、stage4读)。需要把数据送到更后面的stage时,请逐级交接。 | ||
| 159 | +- 跨核Buffer的Tile数由preload决定,不能随意取:按stage在主循环中的书写顺序编号(1、2、3……,与第一个stage在cube还是vector上无关),写这块Buffer的stage编号为奇数时至少需要2个Tile,为偶数时至少需要preload个Tile。以本文的[调用示例](#调用示例)(stage1 Cube → stage2 Vector → stage3 Cube → stage4 Vector)为例:mm1_vec_db(stage1写)与out_vec_db(stage3写)始终为2个Tile,与preload无关;p_mat_db(stage2写)至少需要preload个Tile,即preload=3时至少3个、preload=4时至少4个。Tile数不足时编译期报错,并给出该Buffer所需的最小Tile数。 | ||
| 160 | +- 上述规则给出的是Tile数的下限。在Buffer空间充足时,可以分配多于该下限的Tile,用于进一步提升性能。增加Tile数时,mutex_ids的长度、fwd_ids/bwd_ids的长度(配成单个共用id的情况除外)以及Buffer占用的地址空间都需要同步调整。 | ||
| 156 | - 跨核Buffer的Tiles必须随迭代顺序轮转。 | 161 | - 跨核Buffer的Tiles必须随迭代顺序轮转。 |
| 157 | - stage函数如果有结构体参数,请使用pypto_pro.language.struct()声明,不支持pypto_pro.language.struct_array()。 | 162 | - stage函数如果有结构体参数,请使用pypto_pro.language.struct()声明,不支持pypto_pro.language.struct_array()。 |
| 158 | - 跨核Buffer仅支持UB和L1 Buffer。 | 163 | - 跨核Buffer仅支持UB和L1 Buffer。 |
| @@ -58,7 +58,7 @@ using CallPtr = std::shared_ptr<const Call>; | |||
| 58 | * Example usage: | 58 | * Example usage: |
| 59 | * @code | 59 | * @code |
| 60 | * OpRegistryEntry entry; | 60 | * OpRegistryEntry entry; |
| 61 | - * entry.set_name("tensor.add") | 61 | + * entry.set_name("block.add") |
| 62 | * .set_description("Element-wise addition of two tensors") | 62 | * .set_description("Element-wise addition of two tensors") |
| 63 | * .add_argument("lhs", "Left-hand side tensor") | 63 | * .add_argument("lhs", "Left-hand side tensor") |
| 64 | * .add_argument("rhs", "Right-hand side tensor") | 64 | * .add_argument("rhs", "Right-hand side tensor") |
| @@ -276,7 +276,7 @@ public: | |||
| 276 | * | 276 | * |
| 277 | * Example usage: | 277 | * Example usage: |
| 278 | * @code | 278 | * @code |
| 279 | - * REGISTER_OP("tensor.matmul") | 279 | + * REGISTER_OP("block.matmul") |
| 280 | * .set_attr<DataType>("out_dtype") // OK: DataType is allowed | 280 | * .set_attr<DataType>("out_dtype") // OK: DataType is allowed |
| 281 | * .set_attr<bool>("a_trans") // OK: bool is allowed | 281 | * .set_attr<bool>("a_trans") // OK: bool is allowed |
| 282 | * .set_attr<MemorySpace>("target_memory") // OK: MemorySpace is allowed | 282 | * .set_attr<MemorySpace>("target_memory") // OK: MemorySpace is allowed |
| @@ -319,9 +319,9 @@ private: | |||
| 319 | * \brief Set the operator name | 319 | * \brief Set the operator name |
| 320 | * | 320 | * |
| 321 | * The name is used as the unique identifier for the operator in the registry. | 321 | * The name is used as the unique identifier for the operator in the registry. |
| 322 | - * Convention: use dotted notation like "tensor.add" or "tile.matmul". | 322 | + * Convention: use dotted notation like "block.add" or "vf.add". |
| 323 | * | 323 | * |
| 324 | - * \param name The operator name (e.g., "tensor.add", "tile.conv2d") | 324 | + * \param name The operator name (e.g., "block.add", "ptr.make_tensor") |
| 325 | * \return Reference to this entry for method chaining | 325 | * \return Reference to this entry for method chaining |
| 326 | */ | 326 | */ |
| 327 | inline OpRegistryEntry& set_name(std::string name) | 327 | inline OpRegistryEntry& set_name(std::string name) |
| @@ -373,7 +373,7 @@ public: | |||
| 373 | * Creates a new operator registry entry that can be configured using | 373 | * Creates a new operator registry entry that can be configured using |
| 374 | * the fluent API (set_description, add_argument, f_deduce_type, etc.). | 374 | * the fluent API (set_description, add_argument, f_deduce_type, etc.). |
| 375 | * | 375 | * |
| 376 | - * \param op_name Name of the operator (e.g., "tensor.add", "block.mul") | 376 | + * \param op_name Name of the operator (e.g., "block.add", "block.mul") |
| 377 | * \throws ValueError if operator is already registered | 377 | * \throws ValueError if operator is already registered |
| 378 | */ | 378 | */ |
| 379 | OpRegistryEntry& Register(const std::string& op_name); | 379 | OpRegistryEntry& Register(const std::string& op_name); |
| @@ -80,7 +80,7 @@ public: | |||
| 80 | * Creates a ConversionFunc that calls OpRegistry::Create with the target name. | 80 | * Creates a ConversionFunc that calls OpRegistry::Create with the target name. |
| 81 | * Re-registering the same from_op replaces the previous rule. | 81 | * Re-registering the same from_op replaces the previous rule. |
| 82 | * | 82 | * |
| 83 | - * \param from_op Source op name (e.g., "tensor.add") | 83 | + * \param from_op Source op name (e.g., "block.add") |
| 84 | * \param to_op Target op name (e.g., "block.add") | 84 | * \param to_op Target op name (e.g., "block.add") |
| 85 | */ | 85 | */ |
| 86 | void RegisterSimple(const std::string& from_op, const std::string& to_op); | 86 | void RegisterSimple(const std::string& from_op, const std::string& to_op); |
| @@ -90,7 +90,7 @@ public: | |||
| 90 | * | 90 | * |
| 91 | * Re-registering the same from_op replaces the previous rule. | 91 | * Re-registering the same from_op replaces the previous rule. |
| 92 | * | 92 | * |
| 93 | - * \param from_op Source op name (e.g., "tensor.matmul") | 93 | + * \param from_op Source op name (e.g., "block.matmul") |
| 94 | * \param func Custom conversion function | 94 | * \param func Custom conversion function |
| 95 | */ | 95 | */ |
| 96 | void RegisterCustom(const std::string& from_op, ConversionFunc func); | 96 | void RegisterCustom(const std::string& from_op, ConversionFunc func); |
| @@ -1,160 +1,207 @@ | |||
| 1 | -# Operator Implementations | 1 | +# 算子实现 |
| 2 | 2 | ||
| 3 | -This directory contains the implementations for all PyPTO IR operators, organized by category. | 3 | +本目录存放所有 PyPTO IR 算子的**前端注册**:算子名、kwarg schema、类型推导。这些算子的 |
| 4 | +CCE 产码是分开的,在 `src/interface/pypto_pro/backend/` 下。 | ||
| 4 | 5 | ||
| 5 | -## Directory Structure | 6 | +## 目录结构 |
| 6 | 7 | ||
| 7 | ```text | 8 | ```text |
| 8 | src/ir/op/ | 9 | src/ir/op/ |
| 9 | -├── README.md # This file | 10 | +├── README.md # 本文件 |
| 10 | -├── type_inference.cpp # Type inference utilities implementation | 11 | +├── README_en.md # 本文件的英文版 |
| 11 | -├── tensor_ops/ # Tensor operator implementations | 12 | +├── type_inference.cpp # 下列文件共用的类型推导工具 |
| 12 | -│ └── elementwise.cpp # Element-wise ops (Add, Sub, Mul, Div) | 13 | +├── ptr_ops.cpp # ptr.* - 指针与张量视图算子 |
| 13 | -└── block_ops/ # Block operator implementations | 14 | +├── simt_ops.cpp # simt.* - SIMT 算子 |
| 14 | - ├── memory.cpp # Memory operations (get_block_idx, load, store) | 15 | +├── vf_ops.cpp # vf.* - VF(vector-function)算子 |
| 15 | - ├── elementwise.cpp # Element-wise ops (Add, Mul, Div) | 16 | +├── debug_ops.cpp # debug.* - 调试算子 |
| 16 | - ├── reduction.cpp # Reduction ops (Sum with keepdim) | 17 | +├── sync_ops/ |
| 17 | - └── unary.cpp # Unary ops (Sqrt) | 18 | +│ └── sync.cpp # system.* - 同步与屏障算子 |
| 19 | +└── block_ops/ | ||
| 20 | + ├── memory.cpp # block 作用域查询与 SPR 访问(无 block. 前缀) | ||
| 21 | + ├── out_memory.cpp # block.* - 数据搬运(load、store、move、insert) | ||
| 22 | + ├── out_elementwise.cpp # block.* - 逐元素与 gather 算子 | ||
| 23 | + ├── out_matmul.cpp # block.* - matmul 系列 | ||
| 24 | + ├── out_reduction.cpp # block.* - 行/列归约与 expand | ||
| 25 | + ├── sort.cpp # block.* - 排序、归并排序、直方图 | ||
| 26 | + └── struct_ops.cpp # struct.* - 结构体创建 / 字段写入 | ||
| 18 | ``` | 27 | ``` |
| 19 | 28 | ||
| 20 | -## Organization Principles | 29 | +`out_` 前缀表示**显式输出**约定:目标 tile 是算子的第一个参数,而不是返回值。 |
| 21 | 30 | ||
| 22 | -### By Operation Type | 31 | +## 组织原则 |
| 23 | 32 | ||
| 24 | -- `tensor_ops/` - Operations on N-dimensional tensors | 33 | +### 按命名空间 |
| 25 | -- `block_ops/` - Block-level operations for hardware-optimized programming | ||
| 26 | 34 | ||
| 27 | -### By Operation Category (within each type) | 35 | +每个文件独占一个算子命名空间,命名空间就是算子名的前缀: |
| 28 | 36 | ||
| 29 | -- `elementwise.cpp` - Element-wise binary operations (Add, Sub, Mul, Div) | 37 | +| 命名空间 | 文件 | 算子数 | |
| 30 | -- `reduction.cpp` - Reduction operations (Sum, Max, Min, etc.) | 38 | +|-------------|-----------------------------------|-------:| |
| 31 | -- `unary.cpp` - Unary operations (Sqrt, etc.) | 39 | +| `vf.` | `vf_ops.cpp` | 83 | |
| 32 | -- `memory.cpp` - Memory operations (load/store, block index) - *block_ops only* | 40 | +| `simt.` | `simt_ops.cpp` | 30 | |
| 33 | -- `matmul.cpp` - Matrix multiplication operations - *to be added* | 41 | +| `system.` | `sync_ops/sync.cpp` | 21 | |
| 34 | -- `transform.cpp` - Shape transformation operations (Reshape, Transpose, etc.) - *to be added* | 42 | +| `block.` | `block_ops/out_*.cpp`、`sort.cpp` | 66 | |
| 43 | +| (顶层) | `block_ops/memory.cpp` | 15 | | ||
| 44 | +| `debug.` | `debug_ops.cpp` | 5 | | ||
| 45 | +| `ptr.` | `ptr_ops.cpp` | 3 | | ||
| 46 | +| `struct.` | `block_ops/struct_ops.cpp` | 2 | | ||
| 35 | 47 | ||
| 36 | -## Adding a New Operator | 48 | +### 按类别(在 `block_ops/` 内部) |
| 37 | 49 | ||
| 38 | -### 1. Choose or create a category file | 50 | +- `out_memory.cpp` —— 张量与 tile 之间的数据搬运 |
| 51 | +- `out_elementwise.cpp` —— 逐元素算术、比较、选择、gather | ||
| 52 | +- `out_matmul.cpp` —— matmul 及其 accumulate / bias / mx 变体 | ||
| 53 | +- `out_reduction.cpp` —— 行列归约,以及配套的 expand | ||
| 54 | +- `sort.cpp` —— 排序与直方图 | ||
| 55 | +- `memory.cpp` —— block 作用域查询(`get_block_idx`、`get_block_num`)与 SPR 访问 | ||
| 56 | +- `struct_ops.cpp` —— 结构体算子 | ||
| 39 | 57 | ||
| 40 | -Select the appropriate category file under `tensor_ops/` or `block_ops/`, or create a new one: | 58 | +## 新增一个算子 |
| 41 | 59 | ||
| 42 | -- Element-wise ops: `elementwise.cpp` | 60 | +### 1. 选择或新建类别文件 |
| 43 | -- Matrix ops: `matmul.cpp` (create if needed) | ||
| 44 | -- Reduction ops: `reduction.cpp` (create if needed) | ||
| 45 | 61 | ||
| 46 | -### 2. Register the operator using the fluent API | 62 | +按算子的命名空间和类别挑文件,或在 `block_ops/` 下新建一个。**新建文件不需要改构建脚本**: |
| 63 | +`framework/src/interface/CMakeLists.txt` 用 `file(GLOB ... ir/op/*.cpp ir/op/*/*.cpp)` 收集源文件, | ||
| 64 | +重跑 CMake 即可。 | ||
| 47 | 65 | ||
| 48 | -Add the operator registration to the category file: | 66 | +### 2. 用流式 API 注册算子 |
| 49 | 67 | ||
| 50 | ```cpp | 68 | ```cpp |
| 51 | -// Example: in tensor_ops/matmul.cpp (new file) | 69 | +// 示例:在 block_ops/out_matmul.cpp 中 |
| 52 | -#include "pypto/core/logging.h" | 70 | +#include "ir/op_registry.h" |
| 53 | -#include "pypto/ir/op_registry.h" | 71 | +#include "ir/type.h" |
| 54 | -#include "pypto/ir/type.h" | 72 | +#include "ir/type_inference.h" |
| 55 | -#include "pypto/ir/type_inference.h" | 73 | +#include "pypto_pro/error.h" |
| 56 | 74 | ||
| 57 | namespace pypto { | 75 | namespace pypto { |
| 58 | namespace ir { | 76 | namespace ir { |
| 77 | +namespace { | ||
| 59 | 78 | ||
| 60 | -// Helper function for type deduction (optional, for code reuse) | 79 | +// 类型推导辅助函数(可选,便于相关算子间复用) |
| 61 | -TypePtr DeduceTensorMatMulType(const std::vector<ExprPtr>& args, const std::string& op_name) { | 80 | +// args 和 kwargs 都会传进来:kwargs 承载算子的属性 |
| 62 | - CHECK(args.size() == 2) << op_name << " requires exactly 2 arguments"; | 81 | +TypePtr DeduceBlockMatMulType(const std::vector<ExprPtr>& args, |
| 63 | - | 82 | + const std::vector<std::pair<std::string, std::any>>& kwargs, |
| 64 | - auto tensor1 = std::dynamic_pointer_cast<const TensorType>(args[0]->GetType()); | 83 | + const std::string& op_name) |
| 65 | - auto tensor2 = std::dynamic_pointer_cast<const TensorType>(args[1]->GetType()); | 84 | +{ |
| 66 | - CHECK(tensor1 && tensor2) << op_name << " requires TensorType arguments"; | 85 | + PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3) |
| 67 | - | 86 | + << op_name << " requires 3 arguments (out, lhs, rhs)"; |
| 68 | - // Matrix multiplication type inference logic | 87 | + // ... 由 args[0] 的类型推导;当某个属性会改变结果时,再看 kwargs ... |
| 69 | - // ... | 88 | + return args[0]->GetType(); |
| 70 | - | ||
| 71 | - return result_type; | ||
| 72 | } | 89 | } |
| 73 | 90 | ||
| 74 | -// Register the operator | 91 | +} // namespace |
| 75 | -REGISTER_OP("tensor.matmul") | 92 | + |
| 76 | - .set_op_category("TensorOp") | 93 | +REGISTER_OP("block.matmul_example") |
| 77 | - .set_description("Matrix multiplication of two tensors") | 94 | + .set_op_category("BlockOp") |
| 78 | - .add_argument("lhs", "Left-hand side tensor") | 95 | + .set_description("Matrix multiplication of two tiles into a pre-allocated output tile") |
| 79 | - .add_argument("rhs", "Right-hand side tensor") | 96 | + .add_argument("out", "Pre-allocated output tile (TileType)") |
| 80 | - .f_deduce_type([](const std::vector<ExprPtr>& args) { | 97 | + .add_argument("lhs", "Left-hand side tile (TileType)") |
| 81 | - return DeduceTensorMatMulType(args, "tensor.matmul"); | 98 | + .add_argument("rhs", "Right-hand side tile (TileType)") |
| 99 | + .set_attr<bool>("a_trans") | ||
| 100 | + .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 101 | + [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 102 | + return DeduceBlockMatMulType(args, kwargs, "block.matmul_example"); | ||
| 82 | }); | 103 | }); |
| 83 | 104 | ||
| 84 | -} // namespace ir | 105 | +} // namespace ir |
| 85 | -} // namespace pypto | 106 | +} // namespace pypto |
| 86 | ``` | 107 | ``` |
| 87 | 108 | ||
| 88 | -The `REGISTER_OP` macro uses static initialization, so the operator is automatically registered when the library loads. No manual registration function calls are needed. | 109 | +`REGISTER_OP` 依赖静态初始化,所以库加载时算子会自行注册,没有需要手动调用的注册函数。 |
| 89 | 110 | ||
| 90 | -### 3. Update CMakeLists.txt | 111 | +关于这几个流式调用,有两点要注意: |
| 91 | 112 | ||
| 92 | -Add the new source file if you created one: | 113 | +- `set_op_category` 用于工具侧分组。取该命名空间已在用的值: |
| 114 | + `BlockOp`、`VFOp`、`SimtOp`、`SyncOp`、`PtrOp`、`StructOp`、`DebugOp`、`LanguageOp`。 | ||
| 115 | +- `set_attr<T>("name")` 声明一个关键字参数。它同时是 `ValidateKwargs` 的**白名单**,所以 | ||
| 116 | + 一个属性都不声明的算子会**不加拦阻地接受任何关键字**。`add_argument` 只是文档—— | ||
| 117 | + 没有任何代码会读回它。 | ||
| 93 | 118 | ||
| 94 | -```cmake | 119 | +### 3. 实现后端 |
| 95 | -set(PYPTO_SOURCES | ||
| 96 | - # ... existing files ... | ||
| 97 | - src/ir/op/tensor_ops/matmul.cpp # Add this | ||
| 98 | - # ... rest of files ... | ||
| 99 | -) | ||
| 100 | -``` | ||
| 101 | 120 | ||
| 102 | -### 4. Write tests | 121 | +只做前端注册的算子能被构造,但不能被编译:kernel 用了没有后端的算子,会在 CCE 产码阶段失败, |
| 122 | +报 `Unknown call '<op>' reached CCE codegen`。产码实现放在 `src/interface/pypto_pro/backend/` 下, | ||
| 123 | +用 `REGISTER_BACKEND_OP(BackendCCE, "<算子名>")` 注册。 | ||
| 103 | 124 | ||
| 104 | -Add tests in `tests/ut/ir/test_op_registry.py` to verify the operator works correctly. | 125 | +### 4. 编写测试 |
| 105 | 126 | ||
| 106 | -## Benefits of This Structure | 127 | +- C++ 注册契约:`framework/tests/ut/interface/src/ir/` |
| 128 | +- Python 侧可见的行为:`python/tests/ut/pypto_pro/ir/op/test_registry.py` | ||
| 129 | +- 后端产出:`framework/tests/ut/interface/src/pypto_pro/backend/` | ||
| 107 | 130 | ||
| 108 | -1. **Modularity**: Each operator category is in its own file | 131 | +## 这种结构的好处 |
| 109 | -2. **Maintainability**: Easy to find and modify specific operator implementations | ||
| 110 | -3. **Scalability**: Adding new operators doesn't bloat existing files | ||
| 111 | -4. **Build Performance**: Changes to one category don't trigger recompilation of others | ||
| 112 | -5. **Clear Organization**: Operators grouped by type (tensor/tile) and category (elementwise/reduction/etc.) | ||
| 113 | 132 | ||
| 114 | -## Current Operators | 133 | +1. **模块化**:每个命名空间、每个类别独占一个文件 |
| 134 | +2. **可维护**:便于定位和修改特定算子 | ||
| 135 | +3. **可扩展**:新增算子不会让已有文件膨胀 | ||
| 136 | +4. **构建性能**:改动一个类别不会触发其他类别重新编译 | ||
| 137 | +5. **组织清晰**:算子该放哪个文件,由它的名字直接决定 | ||
| 115 | 138 | ||
| 116 | -### Tensor Operations | 139 | +## 现有算子 |
| 117 | 140 | ||
| 118 | -- **Element-wise** (`tensor_ops/elementwise.cpp`): | 141 | +共 225 个算子。下面按文件列出代表性的一批,完整清单请看对应文件。 |
| 119 | - - `tensor.add` - Element-wise addition with broadcasting | ||
| 120 | - - `tensor.sub` - Element-wise subtraction with broadcasting | ||
| 121 | - - `tensor.mul` - Element-wise multiplication with broadcasting | ||
| 122 | - - `tensor.div` - Element-wise division with broadcasting | ||
| 123 | 142 | ||
| 124 | -### Block Operations | 143 | +### 指针与张量视图(`ptr_ops.cpp`) |
| 125 | 144 | ||
| 126 | -Block operations are designed for hardware-optimized block-level programming, | 145 | +- `ptr.make_ptr` —— 从张量取出裸指针,或重解释指针的 dtype |
| 127 | -working with tiles and supporting scalar broadcasting. | 146 | +- `ptr.make_tensor` —— 基于指针或已有张量构造张量视图 |
| 147 | +- `ptr.addptr` —— 按元素语义偏移裸指针 | ||
| 128 | 148 | ||
| 129 | -- **Memory** (`block_ops/memory.cpp`): | 149 | +### Block 算子 |
| 130 | - - `block.get_block_idx` - Get the current block index (returns INT32 scalar) | ||
| 131 | - - `block.load` - Copy data from tensor to unified buffer (tile) | ||
| 132 | - - `block.store` - Copy data from unified buffer (tile) to tensor | ||
| 133 | 150 | ||
| 134 | -- **Element-wise** (`block_ops/elementwise.cpp`): | 151 | +Block 算子面向硬件优化的 block 级编程,作用于 tile,并遵循**显式输出**约定:目标 tile 是第一个参数。 |
| 135 | - - Tile-Tile operations (with broadcasting): | ||
| 136 | - - `block.add` - Element-wise addition (tile + tile) | ||
| 137 | - - `block.sub` - Element-wise subtraction (tile - tile) | ||
| 138 | - - `block.mul` - Element-wise multiplication (tile * tile) | ||
| 139 | - - `block.div` - Element-wise division (tile / tile) | ||
| 140 | - - Tile-Scalar operations: | ||
| 141 | - - `block.adds` - Element-wise addition (tile + scalar) | ||
| 142 | - - `block.subs` - Element-wise subtraction (tile - scalar) | ||
| 143 | - - `block.muls` - Element-wise multiplication (tile * scalar) | ||
| 144 | - - `block.divs` - Element-wise division (tile / scalar) | ||
| 145 | 152 | ||
| 146 | -- **Reduction** (`block_ops/reduction.cpp`): | 153 | +- **block 作用域查询与 SPR**(`block_ops/memory.cpp`,无命名空间前缀): |
| 147 | - - `block.sum` - Sum reduction along specified axis | 154 | + `get_block_idx`、`get_block_num`、`get_subblock_idx`、`get_subblock_num`、`get_spr`、 |
| 148 | - - Arguments: `(tile, axis, keepdim?)` | 155 | + `set_saturation_flag` |
| 149 | - - When `keepdim=True`, reduced axis is kept as dimension 1 | 156 | +- **数据搬运**(`block_ops/out_memory.cpp`): |
| 150 | - - When `keepdim=False` (default), reduced axis is removed | 157 | + `block.load`、`block.store`、`block.move`、`block.move_fp`、`block.insert`、`block.ub_copy` |
| 158 | +- **逐元素与 gather**(`block_ops/out_elementwise.cpp`): | ||
| 159 | + `block.add`、`block.sub`、`block.mul`、`block.div`(tile-tile); | ||
| 160 | + `block.adds`、`block.subs`、`block.muls`、`block.divs`(tile-scalar); | ||
| 161 | + `block.cmp`、`block.sel`、`block.gather`、`block.gatherb`、`block.gathermask` | ||
| 162 | +- **Matmul**(`block_ops/out_matmul.cpp`): | ||
| 163 | + `block.matmul`、`block.matmul_acc`、`block.matmul_bias`、`block.matmul_mx`、`block.gemv` | ||
| 164 | +- **归约与 expand**(`block_ops/out_reduction.cpp`): | ||
| 165 | + `block.row_sum`、`block.row_max`、`block.row_min`、`block.col_sum`、`block.col_max`、 | ||
| 166 | + `block.col_min`、`block.row_reduce`、`block.col_reduce`、`block.row_expand`、 | ||
| 167 | + `block.col_expand` | ||
| 168 | +- **排序**(`block_ops/sort.cpp`): | ||
| 169 | + `block.sort32`、`block.mrgsort`、`block.mrgsort2`、`block.histogram` | ||
| 170 | +- **结构体**(`block_ops/struct_ops.cpp`): | ||
| 171 | + `struct.create`、`struct.set` | ||
| 151 | 172 | ||
| 152 | -- **Unary** (`block_ops/unary.cpp`): | 173 | +### VF 算子(`vf_ops.cpp`) |
| 153 | - - `block.sqrt` - Element-wise square root | ||
| 154 | 174 | ||
| 155 | -## See Also | 175 | +vector-function 算子,在 VF section 内发射。寄存器由赋值形式(`dst = vf.xxx(...)`)隐式声明。 |
| 156 | 176 | ||
| 157 | -- [Type Inference Header](../../../../include/ir/type_inference.h) | 177 | +- `vf.reg_tensor`、`vf.mask_reg` —— 寄存器声明(不可直接调用) |
| 158 | -- [Type Inference Implementation](type_inference.cpp) | 178 | +- `vf.create_mask`、`vf.update_mask` —— 谓词寄存器 |
| 159 | -- [Operator Registry Header](../../../../include/ir/op_registry.h) | 179 | +- `vf.load_align`、`vf.store_align` —— 对齐的加载 / 存储 |
| 160 | -- [Operator Registry Implementation](../op_registry.cpp) | 180 | +- `vf.full`、`vf.add`、`vf.max`、`vf.reduce_sum` —— 广播与计算 |
| 181 | + | ||
| 182 | +### SIMT 算子(`simt_ops.cpp`) | ||
| 183 | + | ||
| 184 | +- `simt.thread_idx`、`simt.block_idx`、`simt.block_dim`、`simt.grid_dim`、 | ||
| 185 | + `simt.linear_thread_idx` —— 上下文查询 | ||
| 186 | +- `simt.exp`、`simt.sqrt`、`simt.abs`、`simt.fma` —— 标量数学 | ||
| 187 | +- `simt.atomic_add`、`simt.atomic_cas` —— 原子操作 | ||
| 188 | +- `simt.syncthreads`、`simt.threadfence` —— 同步 | ||
| 189 | + | ||
| 190 | +### 同步(`sync_ops/sync.cpp`) | ||
| 191 | + | ||
| 192 | +- `system.sync_src_dyn`、`system.sync_dst_dyn` —— pipe 事件的 set / wait | ||
| 193 | +- `system.bar_m`、`system.bar_mte1`、`system.bar_mte2`、`system.bar_mte3`、`system.bar_all` —— 屏障 | ||
| 194 | +- `system.set_cross_core`、`system.wait_cross_core` —— 跨核同步 | ||
| 195 | + | ||
| 196 | +### 调试(`debug_ops.cpp`) | ||
| 197 | + | ||
| 198 | +- `debug.dump_tensor`、`debug.dump_tile` —— dump 数据 | ||
| 199 | +- `debug.printf`、`debug.assert`、`debug.trap` | ||
| 200 | + | ||
| 201 | +## 另见 | ||
| 202 | + | ||
| 203 | +- [类型推导头文件](../../../../include/ir/type_inference.h) | ||
| 204 | +- [类型推导实现](type_inference.cpp) | ||
| 205 | +- [算子注册表头文件](../../../../include/ir/op_registry.h) | ||
| 206 | +- [算子注册表实现](../op_registry.cpp) | ||
| 207 | +- [CCE 后端实现](../../pypto_pro/backend/) | ||
| @@ -0,0 +1,215 @@ | |||
| 1 | +# Operator Implementations | ||
| 2 | + | ||
| 3 | +This directory contains the frontend registration for all PyPTO IR operators: each operator's | ||
| 4 | +name, its kwarg schema, and its type deduction. The CCE code generation for these operators | ||
| 5 | +lives separately, under `src/interface/pypto_pro/backend/`. | ||
| 6 | + | ||
| 7 | +## Directory Structure | ||
| 8 | + | ||
| 9 | +```text | ||
| 10 | +src/ir/op/ | ||
| 11 | +├── README.md # Chinese version of this file | ||
| 12 | +├── README_en.md # This file | ||
| 13 | +├── type_inference.cpp # Type inference utilities shared by the files below | ||
| 14 | +├── ptr_ops.cpp # ptr.* - pointer and tensor-view operators | ||
| 15 | +├── simt_ops.cpp # simt.* - SIMT operators | ||
| 16 | +├── vf_ops.cpp # vf.* - VF (vector-function) operators | ||
| 17 | +├── debug_ops.cpp # debug.* - debug operators | ||
| 18 | +├── sync_ops/ | ||
| 19 | +│ └── sync.cpp # system.* - synchronisation and barrier operators | ||
| 20 | +└── block_ops/ | ||
| 21 | + ├── memory.cpp # Block-scope queries and SPR access (no block. prefix) | ||
| 22 | + ├── out_memory.cpp # block.* - data movement (load, store, move, insert) | ||
| 23 | + ├── out_elementwise.cpp # block.* - element-wise and gather operators | ||
| 24 | + ├── out_matmul.cpp # block.* - matmul family | ||
| 25 | + ├── out_reduction.cpp # block.* - row/col reduction and expand | ||
| 26 | + ├── sort.cpp # block.* - sort, merge-sort, histogram | ||
| 27 | + └── struct_ops.cpp # struct.* - struct create / field set | ||
| 28 | +``` | ||
| 29 | + | ||
| 30 | +The `out_` prefix marks the explicit-output convention: the destination tile is the operator's | ||
| 31 | +first argument rather than its return value. | ||
| 32 | + | ||
| 33 | +## Organization Principles | ||
| 34 | + | ||
| 35 | +### By namespace | ||
| 36 | + | ||
| 37 | +Every file owns one operator namespace, and the namespace is the operator-name prefix: | ||
| 38 | + | ||
| 39 | +| Namespace | File | Operators | | ||
| 40 | +|-------------|-------------------------------|----------:| | ||
| 41 | +| `vf.` | `vf_ops.cpp` | 83 | | ||
| 42 | +| `simt.` | `simt_ops.cpp` | 30 | | ||
| 43 | +| `system.` | `sync_ops/sync.cpp` | 21 | | ||
| 44 | +| `block.` | `block_ops/out_*.cpp`, `sort.cpp` | 66 | | ||
| 45 | +| (top level) | `block_ops/memory.cpp` | 15 | | ||
| 46 | +| `debug.` | `debug_ops.cpp` | 5 | | ||
| 47 | +| `ptr.` | `ptr_ops.cpp` | 3 | | ||
| 48 | +| `struct.` | `block_ops/struct_ops.cpp` | 2 | | ||
| 49 | + | ||
| 50 | +### By category (within `block_ops/`) | ||
| 51 | + | ||
| 52 | +- `out_memory.cpp` - data movement between tensor and tile | ||
| 53 | +- `out_elementwise.cpp` - element-wise arithmetic, comparison, selection, gather | ||
| 54 | +- `out_matmul.cpp` - matmul and its accumulate / bias / mx variants | ||
| 55 | +- `out_reduction.cpp` - row and column reduce, and the matching expand | ||
| 56 | +- `sort.cpp` - sort and histogram | ||
| 57 | +- `memory.cpp` - block-scope queries (`get_block_idx`, `get_block_num`) and SPR access | ||
| 58 | +- `struct_ops.cpp` - struct operators | ||
| 59 | + | ||
| 60 | +## Adding a New Operator | ||
| 61 | + | ||
| 62 | +### 1. Choose or create a category file | ||
| 63 | + | ||
| 64 | +Pick the file that owns the operator's namespace and category, or add a new file under | ||
| 65 | +`block_ops/`. A new file needs no build change: `framework/src/interface/CMakeLists.txt` | ||
| 66 | +collects sources with `file(GLOB ... ir/op/*.cpp ir/op/*/*.cpp)`, so re-running CMake picks | ||
| 67 | +it up. | ||
| 68 | + | ||
| 69 | +### 2. Register the operator using the fluent API | ||
| 70 | + | ||
| 71 | +```cpp | ||
| 72 | +// Example: in block_ops/out_matmul.cpp | ||
| 73 | +#include "ir/op_registry.h" | ||
| 74 | +#include "ir/type.h" | ||
| 75 | +#include "ir/type_inference.h" | ||
| 76 | +#include "pypto_pro/error.h" | ||
| 77 | + | ||
| 78 | +namespace pypto { | ||
| 79 | +namespace ir { | ||
| 80 | +namespace { | ||
| 81 | + | ||
| 82 | +// Helper for type deduction (optional, for code reuse across related operators). | ||
| 83 | +// Both args and kwargs are passed in: kwargs carry the operator's attributes. | ||
| 84 | +TypePtr DeduceBlockMatMulType(const std::vector<ExprPtr>& args, | ||
| 85 | + const std::vector<std::pair<std::string, std::any>>& kwargs, | ||
| 86 | + const std::string& op_name) | ||
| 87 | +{ | ||
| 88 | + PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3) | ||
| 89 | + << op_name << " requires 3 arguments (out, lhs, rhs)"; | ||
| 90 | + // ... deduce from args[0]'s type, and from kwargs when an attribute changes the result ... | ||
| 91 | + return args[0]->GetType(); | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +} // namespace | ||
| 95 | + | ||
| 96 | +REGISTER_OP("block.matmul_example") | ||
| 97 | + .set_op_category("BlockOp") | ||
| 98 | + .set_description("Matrix multiplication of two tiles into a pre-allocated output tile") | ||
| 99 | + .add_argument("out", "Pre-allocated output tile (TileType)") | ||
| 100 | + .add_argument("lhs", "Left-hand side tile (TileType)") | ||
| 101 | + .add_argument("rhs", "Right-hand side tile (TileType)") | ||
| 102 | + .set_attr<bool>("a_trans") | ||
| 103 | + .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 104 | + [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 105 | + return DeduceBlockMatMulType(args, kwargs, "block.matmul_example"); | ||
| 106 | + }); | ||
| 107 | + | ||
| 108 | +} // namespace ir | ||
| 109 | +} // namespace pypto | ||
| 110 | +``` | ||
| 111 | + | ||
| 112 | +`REGISTER_OP` uses static initialization, so the operator registers itself when the library | ||
| 113 | +loads; there is no registration function to call. | ||
| 114 | + | ||
| 115 | +Two things about the fluent calls: | ||
| 116 | + | ||
| 117 | +- `set_op_category` groups the operator for tooling. Use the value the namespace already uses: | ||
| 118 | + `BlockOp`, `VFOp`, `SimtOp`, `SyncOp`, `PtrOp`, `StructOp`, `DebugOp`, `LanguageOp`. | ||
| 119 | +- `set_attr<T>("name")` declares one keyword argument. It is also the allow-list that | ||
| 120 | + `ValidateKwargs` checks against, so an operator that declares no attribute accepts any | ||
| 121 | + keyword without complaint. `add_argument` is documentation only - nothing reads it back. | ||
| 122 | + | ||
| 123 | +### 3. Implement the backend | ||
| 124 | + | ||
| 125 | +Frontend registration alone makes an operator constructible but not compilable: a kernel that | ||
| 126 | +uses an operator with no backend fails in CCE codegen with `Unknown call '<op>' reached CCE | ||
| 127 | +codegen`. Add the code generation under `src/interface/pypto_pro/backend/` with | ||
| 128 | +`REGISTER_BACKEND_OP(BackendCCE, "<op name>")`. | ||
| 129 | + | ||
| 130 | +### 4. Write tests | ||
| 131 | + | ||
| 132 | +- C++ registration contract: `framework/tests/ut/interface/src/ir/` | ||
| 133 | +- Python-visible behaviour: `python/tests/ut/pypto_pro/ir/op/test_registry.py` | ||
| 134 | +- Backend output: `framework/tests/ut/interface/src/pypto_pro/backend/` | ||
| 135 | + | ||
| 136 | +## Benefits of This Structure | ||
| 137 | + | ||
| 138 | +1. **Modularity**: each namespace and category is in its own file | ||
| 139 | +2. **Maintainability**: easy to find and modify a specific operator | ||
| 140 | +3. **Scalability**: adding operators does not bloat existing files | ||
| 141 | +4. **Build performance**: changing one category does not recompile the others | ||
| 142 | +5. **Clear organization**: the file an operator lives in follows from its name | ||
| 143 | + | ||
| 144 | +## Current Operators | ||
| 145 | + | ||
| 146 | +225 operators in total. A representative sample per file follows; read the file for the | ||
| 147 | +complete list. | ||
| 148 | + | ||
| 149 | +### Pointer and tensor views (`ptr_ops.cpp`) | ||
| 150 | + | ||
| 151 | +- `ptr.make_ptr` - extract a raw pointer from a tensor, or reinterpret a pointer's dtype | ||
| 152 | +- `ptr.make_tensor` - build a tensor view from a pointer or an existing tensor | ||
| 153 | +- `ptr.addptr` - offset a raw pointer with element semantics | ||
| 154 | + | ||
| 155 | +### Block operators | ||
| 156 | + | ||
| 157 | +Block operators drive hardware-optimized block-level programming. They work on tiles and | ||
| 158 | +follow the explicit-output convention: the destination tile is the first argument. | ||
| 159 | + | ||
| 160 | +- **Block-scope queries and SPR** (`block_ops/memory.cpp`, no namespace prefix): | ||
| 161 | + `get_block_idx`, `get_block_num`, `get_subblock_idx`, `get_subblock_num`, `get_spr`, | ||
| 162 | + `set_saturation_flag` | ||
| 163 | +- **Data movement** (`block_ops/out_memory.cpp`): | ||
| 164 | + `block.load`, `block.store`, `block.move`, `block.move_fp`, `block.insert`, `block.ub_copy` | ||
| 165 | +- **Element-wise and gather** (`block_ops/out_elementwise.cpp`): | ||
| 166 | + `block.add`, `block.sub`, `block.mul`, `block.div` (tile-tile); | ||
| 167 | + `block.adds`, `block.subs`, `block.muls`, `block.divs` (tile-scalar); | ||
| 168 | + `block.cmp`, `block.sel`, `block.gather`, `block.gatherb`, `block.gathermask` | ||
| 169 | +- **Matmul** (`block_ops/out_matmul.cpp`): | ||
| 170 | + `block.matmul`, `block.matmul_acc`, `block.matmul_bias`, `block.matmul_mx`, `block.gemv` | ||
| 171 | +- **Reduction and expand** (`block_ops/out_reduction.cpp`): | ||
| 172 | + `block.row_sum`, `block.row_max`, `block.row_min`, `block.col_sum`, `block.col_max`, | ||
| 173 | + `block.col_min`, `block.row_reduce`, `block.col_reduce`, `block.row_expand`, | ||
| 174 | + `block.col_expand` | ||
| 175 | +- **Sort** (`block_ops/sort.cpp`): | ||
| 176 | + `block.sort32`, `block.mrgsort`, `block.mrgsort2`, `block.histogram` | ||
| 177 | +- **Struct** (`block_ops/struct_ops.cpp`): | ||
| 178 | + `struct.create`, `struct.set` | ||
| 179 | + | ||
| 180 | +### VF operators (`vf_ops.cpp`) | ||
| 181 | + | ||
| 182 | +Vector-function operators, emitted inside a VF section. Registers are declared implicitly by | ||
| 183 | +the assignment form (`dst = vf.xxx(...)`). | ||
| 184 | + | ||
| 185 | +- `vf.reg_tensor`, `vf.mask_reg` - register declarations (not callable directly) | ||
| 186 | +- `vf.create_mask`, `vf.update_mask` - predicate registers | ||
| 187 | +- `vf.load_align`, `vf.store_align` - aligned load / store | ||
| 188 | +- `vf.full`, `vf.add`, `vf.max`, `vf.reduce_sum` - broadcast and compute | ||
| 189 | + | ||
| 190 | +### SIMT operators (`simt_ops.cpp`) | ||
| 191 | + | ||
| 192 | +- `simt.thread_idx`, `simt.block_idx`, `simt.block_dim`, `simt.grid_dim`, | ||
| 193 | + `simt.linear_thread_idx` - context queries | ||
| 194 | +- `simt.exp`, `simt.sqrt`, `simt.abs`, `simt.fma` - scalar math | ||
| 195 | +- `simt.atomic_add`, `simt.atomic_cas` - atomics | ||
| 196 | +- `simt.syncthreads`, `simt.threadfence` - synchronisation | ||
| 197 | + | ||
| 198 | +### Synchronisation (`sync_ops/sync.cpp`) | ||
| 199 | + | ||
| 200 | +- `system.sync_src_dyn`, `system.sync_dst_dyn` - pipe event set / wait | ||
| 201 | +- `system.bar_m`, `system.bar_mte1`, `system.bar_mte2`, `system.bar_mte3`, `system.bar_all` - barriers | ||
| 202 | +- `system.set_cross_core`, `system.wait_cross_core` - cross-core synchronisation | ||
| 203 | + | ||
| 204 | +### Debug (`debug_ops.cpp`) | ||
| 205 | + | ||
| 206 | +- `debug.dump_tensor`, `debug.dump_tile` - dump data | ||
| 207 | +- `debug.printf`, `debug.assert`, `debug.trap` | ||
| 208 | + | ||
| 209 | +## See Also | ||
| 210 | + | ||
| 211 | +- [Type Inference Header](../../../../include/ir/type_inference.h) | ||
| 212 | +- [Type Inference Implementation](type_inference.cpp) | ||
| 213 | +- [Operator Registry Header](../../../../include/ir/op_registry.h) | ||
| 214 | +- [Operator Registry Implementation](../op_registry.cpp) | ||
| 215 | +- [CCE Backend Implementations](../../pypto_pro/backend/) | ||
| @@ -1,188 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -/** | ||
| 12 | - * @file elementwise.cpp | ||
| 13 | - * \brief Element-wise tensor operations (Add, Sub, Mul, Div) | ||
| 14 | - * | ||
| 15 | - * This file implements element-wise tensor operations that support | ||
| 16 | - * N-dimensional tensors with NumPy-style broadcasting. | ||
| 17 | - */ | ||
| 18 | - | ||
| 19 | -#include <any> | ||
| 20 | -#include <memory> | ||
| 21 | -#include <string> | ||
| 22 | -#include <utility> | ||
| 23 | -#include <vector> | ||
| 24 | - | ||
| 25 | -#include "core/logging.h" | ||
| 26 | -#include "ir/kind_traits.h" | ||
| 27 | -#include "ir/op_registry.h" | ||
| 28 | -#include "ir/type.h" | ||
| 29 | -#include "ir/type_inference.h" | ||
| 30 | -#include "pypto_pro/error.h" | ||
| 31 | - | ||
| 32 | -namespace pypto { | ||
| 33 | -namespace ir { | ||
| 34 | -using npu::tile_fwk::ExternalError; | ||
| 35 | - | ||
| 36 | -TypePtr DeduceTensorOpElementwiseBinaryType( | ||
| 37 | - [[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 38 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs, const std::string& op_name) | ||
| 39 | -{ | ||
| 40 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2) | ||
| 41 | - << "The operator " << op_name << " requires exactly 2 arguments, but got " << args.size(); | ||
| 42 | - | ||
| 43 | - // Try TensorType first | ||
| 44 | - auto tensor_type1 = As<TensorType>(args[0]->GetType()); | ||
| 45 | - auto tensor_type2 = As<TensorType>(args[1]->GetType()); | ||
| 46 | - | ||
| 47 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type1) | ||
| 48 | - << "The operator " << op_name << " requires first argument to be a TensorType, but got " | ||
| 49 | - << args[0]->GetType()->TypeName(); | ||
| 50 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type2) | ||
| 51 | - << "The operator " << op_name << " requires second argument to be a TensorType, but got " | ||
| 52 | - << args[1]->GetType()->TypeName(); | ||
| 53 | - | ||
| 54 | - auto result_dtype = PromoteDataTypes(tensor_type1->dtype_, tensor_type2->dtype_); | ||
| 55 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, result_dtype) | ||
| 56 | - << "The operator " << op_name << " requires compatible data types, but got " << args[0]->GetType()->TypeName() | ||
| 57 | - << " and " << args[1]->GetType()->TypeName(); | ||
| 58 | - | ||
| 59 | - auto broadcast_result = BroadcastShapes(tensor_type1->shape_, tensor_type2->shape_); | ||
| 60 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, broadcast_result.success) | ||
| 61 | - << "The operator " << op_name << " requires compatible shapes, but got " << FormatShape(tensor_type1->shape_) | ||
| 62 | - << " and " << FormatShape(tensor_type2->shape_); | ||
| 63 | - | ||
| 64 | - return std::make_shared<TensorType>(broadcast_result.shape, *result_dtype); | ||
| 65 | -} | ||
| 66 | - | ||
| 67 | -TypePtr DeduceTensorOpElementwiseScalarType( | ||
| 68 | - [[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 69 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs, const std::string& op_name) | ||
| 70 | -{ | ||
| 71 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2) | ||
| 72 | - << "The operator " << op_name << " requires exactly 2 arguments, but got " << args.size(); | ||
| 73 | - | ||
| 74 | - auto tensor_type1 = As<TensorType>(args[0]->GetType()); | ||
| 75 | - auto scalar_type2 = As<ScalarType>(args[1]->GetType()); | ||
| 76 | - | ||
| 77 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type1) | ||
| 78 | - << "The operator " << op_name << " requires first argument to be a TensorType, but got " | ||
| 79 | - << args[0]->GetType()->TypeName(); | ||
| 80 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type2) | ||
| 81 | - << "The operator " << op_name << " requires second argument to be a ScalarType, but got " | ||
| 82 | - << args[1]->GetType()->TypeName(); | ||
| 83 | - | ||
| 84 | - // TensorType + ScalarType - result is TensorType with same shape as first argument | ||
| 85 | - auto result_dtype = PromoteDataTypes(tensor_type1->dtype_, scalar_type2->dtype_); | ||
| 86 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, result_dtype) | ||
| 87 | - << "The operator " << op_name << " requires compatible data types, but got " << args[0]->GetType()->TypeName() | ||
| 88 | - << " and " << args[1]->GetType()->TypeName(); | ||
| 89 | - | ||
| 90 | - return std::make_shared<TensorType>(tensor_type1->shape_, *result_dtype); | ||
| 91 | -} | ||
| 92 | - | ||
| 93 | -// ============================================================================ | ||
| 94 | -// Registration Function for Tensor Element-wise Operations | ||
| 95 | -// ============================================================================ | ||
| 96 | - | ||
| 97 | -REGISTER_OP("tensor.add") | ||
| 98 | - .set_op_category("TensorOp") | ||
| 99 | - .set_description("Element-wise addition of two tensors with broadcasting") | ||
| 100 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 101 | - .add_argument("rhs", "Right-hand side tensor (TensorType)") | ||
| 102 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 103 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 104 | - return DeduceTensorOpElementwiseBinaryType(args, kwargs, "tensor.add"); | ||
| 105 | - }); | ||
| 106 | - | ||
| 107 | -REGISTER_OP("tensor.add_scalar") | ||
| 108 | - .set_op_category("TensorOp") | ||
| 109 | - .set_description("Element-wise addition of tensor and scalar") | ||
| 110 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 111 | - .add_argument("rhs", "Right-hand side scalar (ScalarType)") | ||
| 112 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 113 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 114 | - return DeduceTensorOpElementwiseScalarType(args, kwargs, "tensor.add_scalar"); | ||
| 115 | - }); | ||
| 116 | - | ||
| 117 | -REGISTER_OP("tensor.sub") | ||
| 118 | - .set_op_category("TensorOp") | ||
| 119 | - .set_description("Element-wise subtraction of two tensors with broadcasting") | ||
| 120 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 121 | - .add_argument("rhs", "Right-hand side tensor (TensorType)") | ||
| 122 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 123 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 124 | - return DeduceTensorOpElementwiseBinaryType(args, kwargs, "tensor.sub"); | ||
| 125 | - }); | ||
| 126 | - | ||
| 127 | -REGISTER_OP("tensor.sub_scalar") | ||
| 128 | - .set_op_category("TensorOp") | ||
| 129 | - .set_description("Element-wise subtraction of tensor and scalar") | ||
| 130 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 131 | - .add_argument("rhs", "Right-hand side scalar (ScalarType)") | ||
| 132 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 133 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 134 | - return DeduceTensorOpElementwiseScalarType(args, kwargs, "tensor.sub_scalar"); | ||
| 135 | - }); | ||
| 136 | - | ||
| 137 | -REGISTER_OP("tensor.mul") | ||
| 138 | - .set_op_category("TensorOp") | ||
| 139 | - .set_description("Element-wise multiplication of two tensors with broadcasting") | ||
| 140 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 141 | - .add_argument("rhs", "Right-hand side tensor (TensorType)") | ||
| 142 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 143 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 144 | - return DeduceTensorOpElementwiseBinaryType(args, kwargs, "tensor.mul"); | ||
| 145 | - }); | ||
| 146 | - | ||
| 147 | -REGISTER_OP("tensor.mul_scalar") | ||
| 148 | - .set_op_category("TensorOp") | ||
| 149 | - .set_description("Element-wise multiplication of tensor and scalar") | ||
| 150 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 151 | - .add_argument("rhs", "Right-hand side scalar (ScalarType)") | ||
| 152 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 153 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 154 | - return DeduceTensorOpElementwiseScalarType(args, kwargs, "tensor.mul_scalar"); | ||
| 155 | - }); | ||
| 156 | - | ||
| 157 | -REGISTER_OP("tensor.div") | ||
| 158 | - .set_op_category("TensorOp") | ||
| 159 | - .set_description("Element-wise division of two tensors with broadcasting") | ||
| 160 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 161 | - .add_argument("rhs", "Right-hand side tensor (TensorType)") | ||
| 162 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 163 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 164 | - return DeduceTensorOpElementwiseBinaryType(args, kwargs, "tensor.div"); | ||
| 165 | - }); | ||
| 166 | - | ||
| 167 | -REGISTER_OP("tensor.div_scalar") | ||
| 168 | - .set_op_category("TensorOp") | ||
| 169 | - .set_description("Element-wise division of tensor and scalar") | ||
| 170 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 171 | - .add_argument("rhs", "Right-hand side scalar (ScalarType)") | ||
| 172 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 173 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 174 | - return DeduceTensorOpElementwiseScalarType(args, kwargs, "tensor.div_scalar"); | ||
| 175 | - }); | ||
| 176 | - | ||
| 177 | -REGISTER_OP("tensor.maximum") | ||
| 178 | - .set_op_category("TensorOp") | ||
| 179 | - .set_description("Element-wise maximum of two tensors with broadcasting") | ||
| 180 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 181 | - .add_argument("rhs", "Right-hand side tensor (TensorType)") | ||
| 182 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 183 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 184 | - return DeduceTensorOpElementwiseBinaryType(args, kwargs, "tensor.maximum"); | ||
| 185 | - }); | ||
| 186 | - | ||
| 187 | -} // namespace ir | ||
| 188 | -} // namespace pypto | ||
| @@ -1,169 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -/** | ||
| 12 | - * @file matmul.cpp | ||
| 13 | - * \brief Matrix multiplication tensor operations | ||
| 14 | - * | ||
| 15 | - * This file implements matrix multiplication operations for tensors, | ||
| 16 | - * supporting transpose options and output dtype control. | ||
| 17 | - */ | ||
| 18 | - | ||
| 19 | -#include <any> | ||
| 20 | -#include <cstddef> | ||
| 21 | -#include <memory> | ||
| 22 | -#include <optional> | ||
| 23 | -#include <string> | ||
| 24 | -#include <utility> | ||
| 25 | -#include <vector> | ||
| 26 | - | ||
| 27 | -#include "core/any_cast.h" | ||
| 28 | -#include "core/dtype.h" | ||
| 29 | -#include "core/error.h" | ||
| 30 | -#include "core/logging.h" | ||
| 31 | -#include "pypto_pro/error.h" | ||
| 32 | -#include "ir/kind_traits.h" | ||
| 33 | -#include "ir/op_registry.h" | ||
| 34 | -#include "ir/type.h" | ||
| 35 | -#include "ir/type_inference.h" | ||
| 36 | - | ||
| 37 | -namespace pypto { | ||
| 38 | -namespace ir { | ||
| 39 | -using npu::tile_fwk::ExternalError; | ||
| 40 | - | ||
| 41 | -// Helper to get kwargs value with default (uses vector to preserve order) | ||
| 42 | -template <typename T> | ||
| 43 | -T GetKwarg([[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs, const std::string& key, | ||
| 44 | - const std::optional<T>& default_value = std::nullopt) | ||
| 45 | -{ | ||
| 46 | - for (const auto& [k, v] : kwargs) { | ||
| 47 | - if (k == key) { | ||
| 48 | - return AnyCast<T>(v, "kwarg key: " + key); | ||
| 49 | - } | ||
| 50 | - } | ||
| 51 | - if (default_value) { | ||
| 52 | - return *default_value; | ||
| 53 | - } | ||
| 54 | - PRO_IR_THROW(::pypto::ir::ValueError, ExternalError::INVALID_ARGUMENT) << "Missing kwarg: " << key; | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -TypePtr DeduceTensorMatMulType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 58 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 59 | -{ | ||
| 60 | - // tensor.matmul requires exactly 2 Expr arguments (lhs, rhs) | ||
| 61 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2) | ||
| 62 | - << "tensor.matmul requires exactly 2 arguments (lhs, rhs), but got " << args.size(); | ||
| 63 | - | ||
| 64 | - // First two arguments must be TensorType | ||
| 65 | - auto lhs_type = As<TensorType>(args[0]->GetType()); | ||
| 66 | - auto rhs_type = As<TensorType>(args[1]->GetType()); | ||
| 67 | - | ||
| 68 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, lhs_type) | ||
| 69 | - << "tensor.matmul requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName(); | ||
| 70 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, rhs_type) | ||
| 71 | - << "tensor.matmul requires second argument to be a TensorType, but got " << args[1]->GetType()->TypeName(); | ||
| 72 | - | ||
| 73 | - // Extract shapes | ||
| 74 | - const auto& lhs_shape = lhs_type->shape_; | ||
| 75 | - const auto& rhs_shape = rhs_type->shape_; | ||
| 76 | - | ||
| 77 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, lhs_shape.size() >= 1) | ||
| 78 | - << "tensor.matmul requires lhs to have at least 1 dimension"; | ||
| 79 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, rhs_shape.size() >= 1) | ||
| 80 | - << "tensor.matmul requires rhs to have at least 1 dimension"; | ||
| 81 | - | ||
| 82 | - // Read kwargs (with defaults) | ||
| 83 | - DataType out_dtype; | ||
| 84 | - try { | ||
| 85 | - out_dtype = GetKwarg<DataType>(kwargs, "out_dtype"); | ||
| 86 | - } catch (const ValueError& e) { | ||
| 87 | - auto promoted = PromoteDataTypes(lhs_type->dtype_, rhs_type->dtype_); | ||
| 88 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, promoted) << "Cannot promote data types for tensor.matmul"; | ||
| 89 | - out_dtype = *promoted; | ||
| 90 | - } catch (const TypeError& e) { | ||
| 91 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, false) << "Invalid kwarg type for out_dtype: " << e.what(); | ||
| 92 | - out_dtype = lhs_type->dtype_; | ||
| 93 | - } | ||
| 94 | - | ||
| 95 | - bool a_trans = GetKwarg<bool>(kwargs, "a_trans", false); | ||
| 96 | - bool b_trans = GetKwarg<bool>(kwargs, "b_trans", false); | ||
| 97 | - | ||
| 98 | - // Compute output shape based on transpose flags | ||
| 99 | - // For 2D: lhs [M, K] x rhs [K, N] -> [M, N] | ||
| 100 | - // With transpose: lhs [K, M]^T x rhs [N, K]^T -> [M, N] | ||
| 101 | - | ||
| 102 | - std::vector<ExprPtr> output_shape; | ||
| 103 | - | ||
| 104 | - if (lhs_shape.size() == 1 && rhs_shape.size() == 1) { | ||
| 105 | - // Vector x vector (dot product): [K] x [K] -> scalar (0D tensor) | ||
| 106 | - output_shape = {}; | ||
| 107 | - } else if (lhs_shape.size() == 0x2 && rhs_shape.size() == 1) { | ||
| 108 | - // Matrix x vector: [M, K] x [K] -> [M] | ||
| 109 | - output_shape = {lhs_shape[0]}; | ||
| 110 | - } else if (lhs_shape.size() == 1 && rhs_shape.size() == 0x2) { | ||
| 111 | - // Vector x matrix: [K] x [K, N] -> [N] | ||
| 112 | - output_shape = {rhs_shape[1]}; | ||
| 113 | - } else if (lhs_shape.size() == 0x2 && rhs_shape.size() == 0x2) { | ||
| 114 | - // 2D x 2D matrix multiplication | ||
| 115 | - ExprPtr m_dim = a_trans ? lhs_shape[1] : lhs_shape[0]; | ||
| 116 | - ExprPtr n_dim = b_trans ? rhs_shape[0] : rhs_shape[1]; | ||
| 117 | - output_shape = {m_dim, n_dim}; | ||
| 118 | - } else { | ||
| 119 | - // For higher-dimensional tensors (both must have at least 2 dimensions), | ||
| 120 | - // use batched matmul semantics | ||
| 121 | - size_t lhs_ndim = lhs_shape.size(); | ||
| 122 | - size_t rhs_ndim = rhs_shape.size(); | ||
| 123 | - | ||
| 124 | - // Ensure both tensors have at least 2 dimensions for batched matmul | ||
| 125 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, lhs_ndim >= 0x2 && rhs_ndim >= 0x2) | ||
| 126 | - << "tensor.matmul requires both tensors to have at least 2 dimensions " | ||
| 127 | - << "for batched matmul, but got lhs shape size " << lhs_ndim << " and rhs shape size " << rhs_ndim; | ||
| 128 | - | ||
| 129 | - // Extract batch dimensions (all except last 2) | ||
| 130 | - std::vector<ExprPtr> lhs_batch(lhs_shape.begin(), lhs_shape.end() - 0x2); | ||
| 131 | - std::vector<ExprPtr> rhs_batch(rhs_shape.begin(), rhs_shape.end() - 0x2); | ||
| 132 | - | ||
| 133 | - // Broadcast batch dimensions | ||
| 134 | - auto broadcast_result = BroadcastShapes(lhs_batch, rhs_batch); | ||
| 135 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, broadcast_result.success) | ||
| 136 | - << "Cannot broadcast batch dimensions for tensor.matmul"; | ||
| 137 | - | ||
| 138 | - output_shape = broadcast_result.shape; | ||
| 139 | - | ||
| 140 | - // Append matrix dimensions | ||
| 141 | - ExprPtr m_dim = a_trans ? lhs_shape[lhs_ndim - 1] : lhs_shape[lhs_ndim - 2]; | ||
| 142 | - ExprPtr n_dim = b_trans ? rhs_shape[rhs_ndim - 2] : rhs_shape[rhs_ndim - 1]; | ||
| 143 | - output_shape.push_back(m_dim); | ||
| 144 | - output_shape.push_back(n_dim); | ||
| 145 | - } | ||
| 146 | - | ||
| 147 | - return std::make_shared<TensorType>(output_shape, out_dtype); | ||
| 148 | -} | ||
| 149 | - | ||
| 150 | -// ============================================================================ | ||
| 151 | -// Registration Function for Tensor Matrix Multiplication Operations | ||
| 152 | -// ============================================================================ | ||
| 153 | - | ||
| 154 | -REGISTER_OP("tensor.matmul") | ||
| 155 | - .set_op_category("TensorOp") | ||
| 156 | - .set_description("Matrix multiplication of two tensors with optional transpose") | ||
| 157 | - .add_argument("lhs", "Left-hand side tensor (TensorType)") | ||
| 158 | - .add_argument("rhs", "Right-hand side tensor (TensorType)") | ||
| 159 | - .set_attr<DataType>("out_dtype") | ||
| 160 | - .set_attr<bool>("a_trans") | ||
| 161 | - .set_attr<bool>("b_trans") | ||
| 162 | - .set_attr<bool>("c_matrix_nz") | ||
| 163 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 164 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 165 | - return DeduceTensorMatMulType(args, kwargs); | ||
| 166 | - }); | ||
| 167 | - | ||
| 168 | -} // namespace ir | ||
| 169 | -} // namespace pypto | ||
| @@ -1,237 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -/** | ||
| 12 | - * @file memory.cpp | ||
| 13 | - * \brief Memory tensor operations (create, view, assemble) | ||
| 14 | - * | ||
| 15 | - * This file implements memory operations for tensors including allocation, | ||
| 16 | - * view creation, and value assembly/updates. | ||
| 17 | - */ | ||
| 18 | - | ||
| 19 | -#include <any> | ||
| 20 | -#include <cstddef> | ||
| 21 | -#include <cstdint> | ||
| 22 | -#include <memory> | ||
| 23 | -#include <string> | ||
| 24 | -#include <utility> | ||
| 25 | -#include <vector> | ||
| 26 | - | ||
| 27 | -#include "core/any_cast.h" | ||
| 28 | -#include "core/dtype.h" | ||
| 29 | -#include "core/logging.h" | ||
| 30 | -#include "ir/expr.h" | ||
| 31 | -#include "ir/kind_traits.h" | ||
| 32 | -#include "ir/op_registry.h" | ||
| 33 | -#include "ir/scalar_expr.h" | ||
| 34 | -#include "ir/type.h" | ||
| 35 | -#include "pypto_pro/error.h" | ||
| 36 | - | ||
| 37 | -namespace pypto { | ||
| 38 | -namespace ir { | ||
| 39 | -using npu::tile_fwk::ExternalError; | ||
| 40 | - | ||
| 41 | -TypePtr DeduceTensorCreateType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 42 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 43 | -{ | ||
| 44 | - // tensor.create: shape is a single TupleType argument | ||
| 45 | - // dtype comes from kwargs | ||
| 46 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1) | ||
| 47 | - << "tensor.create requires exactly 1 argument (shape tuple), but got " << args.size(); | ||
| 48 | - | ||
| 49 | - // Extract dtype from kwargs | ||
| 50 | - bool found_dtype = false; | ||
| 51 | - DataType dtype; | ||
| 52 | - for (const auto& [key, value] : kwargs) { | ||
| 53 | - if (key == "dtype") { | ||
| 54 | - dtype = AnyCast<DataType>(value, "kwarg key: dtype"); | ||
| 55 | - found_dtype = true; | ||
| 56 | - break; | ||
| 57 | - } | ||
| 58 | - } | ||
| 59 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, found_dtype) << "tensor.create requires 'dtype' kwarg"; | ||
| 60 | - | ||
| 61 | - // First argument must be TupleType (shape) | ||
| 62 | - auto shape_tuple_type = As<TupleType>(args[0]->GetType()); | ||
| 63 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_tuple_type) | ||
| 64 | - << "tensor.create requires shape to be TupleType, but got " << args[0]->GetType()->TypeName(); | ||
| 65 | - | ||
| 66 | - // Validate all shape elements are ScalarType with integer dtype | ||
| 67 | - for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) { | ||
| 68 | - auto scalar_type = As<ScalarType>(shape_tuple_type->types_[i]); | ||
| 69 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type) | ||
| 70 | - << "tensor.create shape tuple element " << i << " must be ScalarType, but got " | ||
| 71 | - << shape_tuple_type->types_[i]->TypeName(); | ||
| 72 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt()) | ||
| 73 | - << "tensor.create shape tuple element " << i << " must have integer dtype, but got " | ||
| 74 | - << scalar_type->dtype_.ToString(); | ||
| 75 | - } | ||
| 76 | - | ||
| 77 | - // Extract shape dimensions | ||
| 78 | - // If args[0] is MakeTuple, extract elements directly to preserve constants | ||
| 79 | - // Otherwise use GetItemExpr for runtime tuples | ||
| 80 | - std::vector<ExprPtr> shape; | ||
| 81 | - shape.reserve(shape_tuple_type->types_.size()); | ||
| 82 | - | ||
| 83 | - if (auto make_tuple = As<MakeTuple>(args[0])) { | ||
| 84 | - // MakeTuple: extract elements directly to preserve ConstInt | ||
| 85 | - shape = make_tuple->elements_; | ||
| 86 | - } else { | ||
| 87 | - // Runtime tuple: use GetItemExpr with ConstInt slice | ||
| 88 | - for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) { | ||
| 89 | - auto idx_const = std::make_shared<ConstInt>(static_cast<int64_t>(i), DataType::INT64, args[0]->span_); | ||
| 90 | - shape.emplace_back(std::make_shared<GetItemExpr>(args[0], idx_const, args[0]->span_)); | ||
| 91 | - } | ||
| 92 | - } | ||
| 93 | - | ||
| 94 | - return std::make_shared<TensorType>(shape, dtype); | ||
| 95 | -} | ||
| 96 | - | ||
| 97 | -TypePtr DeduceTensorViewType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 98 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 99 | -{ | ||
| 100 | - // tensor.view requires exactly 3 arguments: input tensor, shape tuple, and offset tuple | ||
| 101 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3) | ||
| 102 | - << "tensor.view requires exactly 3 arguments (input, shape, offset), but got " << args.size(); | ||
| 103 | - | ||
| 104 | - // First argument must be TensorType | ||
| 105 | - auto tensor_type = As<TensorType>(args[0]->GetType()); | ||
| 106 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type) | ||
| 107 | - << "tensor.view requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName(); | ||
| 108 | - | ||
| 109 | - // Second argument must be TupleType (shape) | ||
| 110 | - auto shape_tuple_type = As<TupleType>(args[1]->GetType()); | ||
| 111 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_tuple_type) | ||
| 112 | - << "tensor.view requires shape to be TupleType, but got " << args[1]->GetType()->TypeName(); | ||
| 113 | - | ||
| 114 | - // Validate all shape elements are ScalarType with integer dtype | ||
| 115 | - for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) { | ||
| 116 | - auto scalar_type = As<ScalarType>(shape_tuple_type->types_[i]); | ||
| 117 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type) | ||
| 118 | - << "tensor.view shape tuple element " << i << " must be ScalarType, but got " | ||
| 119 | - << shape_tuple_type->types_[i]->TypeName(); | ||
| 120 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt()) | ||
| 121 | - << "tensor.view shape tuple element " << i << " must have integer dtype, but got " | ||
| 122 | - << scalar_type->dtype_.ToString(); | ||
| 123 | - } | ||
| 124 | - | ||
| 125 | - // Third argument must be TupleType (offset) | ||
| 126 | - auto offset_tuple_type = As<TupleType>(args[2]->GetType()); | ||
| 127 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_tuple_type) | ||
| 128 | - << "tensor.view requires offset to be TupleType, but got " << args[2]->GetType()->TypeName(); | ||
| 129 | - | ||
| 130 | - // Validate all offset elements are ScalarType with integer dtype | ||
| 131 | - for (size_t i = 0; i < offset_tuple_type->types_.size(); ++i) { | ||
| 132 | - auto scalar_type = As<ScalarType>(offset_tuple_type->types_[i]); | ||
| 133 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type) | ||
| 134 | - << "tensor.view offset tuple element " << i << " must be ScalarType, but got " | ||
| 135 | - << offset_tuple_type->types_[i]->TypeName(); | ||
| 136 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt()) | ||
| 137 | - << "tensor.view offset tuple element " << i << " must have integer dtype, but got " | ||
| 138 | - << scalar_type->dtype_.ToString(); | ||
| 139 | - } | ||
| 140 | - | ||
| 141 | - // Extract shape dimensions | ||
| 142 | - // If args[1] is MakeTuple, extract elements directly to preserve constants | ||
| 143 | - // Otherwise use GetItemExpr for runtime tuples | ||
| 144 | - std::vector<ExprPtr> new_shape; | ||
| 145 | - new_shape.reserve(shape_tuple_type->types_.size()); | ||
| 146 | - | ||
| 147 | - if (auto make_tuple = As<MakeTuple>(args[1])) { | ||
| 148 | - // MakeTuple: extract elements directly to preserve ConstInt | ||
| 149 | - new_shape = make_tuple->elements_; | ||
| 150 | - } else { | ||
| 151 | - // Runtime tuple: use GetItemExpr with ConstInt slice | ||
| 152 | - for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) { | ||
| 153 | - auto idx_const = std::make_shared<ConstInt>(static_cast<int64_t>(i), DataType::INT64, args[1]->span_); | ||
| 154 | - new_shape.emplace_back(std::make_shared<GetItemExpr>(args[1], idx_const, args[1]->span_)); | ||
| 155 | - } | ||
| 156 | - } | ||
| 157 | - | ||
| 158 | - // View preserves dtype but has new shape (which can have different rank than input) | ||
| 159 | - return std::make_shared<TensorType>(new_shape, tensor_type->dtype_); | ||
| 160 | -} | ||
| 161 | - | ||
| 162 | -TypePtr DeduceTensorAssembleType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 163 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 164 | -{ | ||
| 165 | - // tensor.assemble requires exactly 3 arguments: target, source, and offset tuple | ||
| 166 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3) | ||
| 167 | - << "tensor.assemble requires exactly 3 arguments (target, source, offset), but got " << args.size(); | ||
| 168 | - | ||
| 169 | - // First argument (target) must be TensorType | ||
| 170 | - auto target_type = As<TensorType>(args[0]->GetType()); | ||
| 171 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, target_type) | ||
| 172 | - << "tensor.assemble requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName(); | ||
| 173 | - | ||
| 174 | - // Second argument (source) must be TensorType | ||
| 175 | - auto source_type = As<TensorType>(args[1]->GetType()); | ||
| 176 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, source_type) | ||
| 177 | - << "tensor.assemble requires second argument to be a TensorType, but got " << args[1]->GetType()->TypeName(); | ||
| 178 | - | ||
| 179 | - // Third argument must be TupleType (offset) | ||
| 180 | - auto offset_tuple_type = As<TupleType>(args[2]->GetType()); | ||
| 181 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_tuple_type) | ||
| 182 | - << "tensor.assemble requires offset to be TupleType, but got " << args[2]->GetType()->TypeName(); | ||
| 183 | - | ||
| 184 | - // Validate all offset elements are ScalarType with integer dtype | ||
| 185 | - for (size_t i = 0; i < offset_tuple_type->types_.size(); ++i) { | ||
| 186 | - auto scalar_type = As<ScalarType>(offset_tuple_type->types_[i]); | ||
| 187 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type) | ||
| 188 | - << "tensor.assemble offset tuple element " << i << " must be ScalarType, but got " | ||
| 189 | - << offset_tuple_type->types_[i]->TypeName(); | ||
| 190 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt()) | ||
| 191 | - << "tensor.assemble offset tuple element " << i << " must have integer dtype, but got " | ||
| 192 | - << scalar_type->dtype_.ToString(); | ||
| 193 | - } | ||
| 194 | - | ||
| 195 | - // Assemble returns a new TensorType with the same shape and dtype as target | ||
| 196 | - // We need to create a new type object to avoid sharing type instances | ||
| 197 | - return std::make_shared<TensorType>(target_type->shape_, target_type->dtype_); | ||
| 198 | -} | ||
| 199 | - | ||
| 200 | -// ============================================================================ | ||
| 201 | -// Registration Function for Tensor Memory Operations | ||
| 202 | -// ============================================================================ | ||
| 203 | - | ||
| 204 | -REGISTER_OP("tensor.create") | ||
| 205 | - .set_op_category("TensorOp") | ||
| 206 | - .set_description("Create a new tensor with specified shape and dtype") | ||
| 207 | - .add_argument("shape", "Shape dimensions (TupleType of ScalarType(INT64))") | ||
| 208 | - .set_attr<DataType>("dtype") | ||
| 209 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 210 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 211 | - return DeduceTensorCreateType(args, kwargs); | ||
| 212 | - }); | ||
| 213 | - | ||
| 214 | -REGISTER_OP("tensor.view") | ||
| 215 | - .set_op_category("TensorOp") | ||
| 216 | - .set_description("Create a view/slice of a tensor with new shape and offset") | ||
| 217 | - .add_argument("input", "Input tensor (TensorType)") | ||
| 218 | - .add_argument("shape", "New shape dimensions (TupleType of ScalarType(INT64))") | ||
| 219 | - .add_argument("offset", "Offset dimensions (TupleType of ScalarType(INT64))") | ||
| 220 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 221 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 222 | - return DeduceTensorViewType(args, kwargs); | ||
| 223 | - }); | ||
| 224 | - | ||
| 225 | -REGISTER_OP("tensor.assemble") | ||
| 226 | - .set_op_category("TensorOp") | ||
| 227 | - .set_description("Write/update tensor values at specified offset") | ||
| 228 | - .add_argument("target", "Target tensor (TensorType)") | ||
| 229 | - .add_argument("source", "Source tensor to write (TensorType)") | ||
| 230 | - .add_argument("offset", "Offset dimensions (TupleType of ScalarType(INT64))") | ||
| 231 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 232 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 233 | - return DeduceTensorAssembleType(args, kwargs); | ||
| 234 | - }); | ||
| 235 | - | ||
| 236 | -} // namespace ir | ||
| 237 | -} // namespace pypto | ||
| @@ -1,119 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -/** | ||
| 12 | - * @file reduction.cpp | ||
| 13 | - * \brief Reduction tensor operations (row_max, row_sum) | ||
| 14 | - * | ||
| 15 | - * This file implements reduction operations for tensors that reduce along | ||
| 16 | - * specified axes. | ||
| 17 | - */ | ||
| 18 | - | ||
| 19 | -#include <any> | ||
| 20 | -#include <cstdint> | ||
| 21 | -#include <memory> | ||
| 22 | -#include <string> | ||
| 23 | -#include <utility> | ||
| 24 | -#include <vector> | ||
| 25 | - | ||
| 26 | -#include "core/dtype.h" | ||
| 27 | -#include "core/logging.h" | ||
| 28 | -#include "ir/kind_traits.h" | ||
| 29 | -#include "ir/op_registry.h" | ||
| 30 | -#include "ir/scalar_expr.h" | ||
| 31 | -#include "ir/span.h" | ||
| 32 | -#include "ir/type.h" | ||
| 33 | -#include "ir/type_inference.h" | ||
| 34 | -#include "pypto_pro/error.h" | ||
| 35 | - | ||
| 36 | -namespace pypto { | ||
| 37 | -namespace ir { | ||
| 38 | -using npu::tile_fwk::ExternalError; | ||
| 39 | - | ||
| 40 | -TypePtr DeduceTensorReductionType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 41 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs, | ||
| 42 | - const std::string& op_name) | ||
| 43 | -{ | ||
| 44 | - // Reduction operations require exactly 1 argument (input tensor) | ||
| 45 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1) | ||
| 46 | - << "The operator " << op_name << " requires exactly 1 argument, but got " << args.size(); | ||
| 47 | - | ||
| 48 | - // First argument must be TensorType | ||
| 49 | - auto tensor_type = As<TensorType>(args[0]->GetType()); | ||
| 50 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type) | ||
| 51 | - << "The operator " << op_name << " requires first argument to be a TensorType, but got " | ||
| 52 | - << args[0]->GetType()->TypeName(); | ||
| 53 | - | ||
| 54 | - const auto& input_shape = tensor_type->shape_; | ||
| 55 | - int64_t input_ndim = static_cast<int64_t>(input_shape.size()); | ||
| 56 | - | ||
| 57 | - // Extract axis from kwargs (default: -1, meaning last axis) | ||
| 58 | - int axis = GetOpKwarg<int>(kwargs, "axis", -1); | ||
| 59 | - // Normalize negative axis | ||
| 60 | - if (axis < 0) { | ||
| 61 | - axis = static_cast<int>(input_ndim) + axis; | ||
| 62 | - } | ||
| 63 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis >= 0 && static_cast<int64_t>(axis) < input_ndim) | ||
| 64 | - << "The operator " << op_name << " axis " << axis << " is out of range for shape with " << input_ndim | ||
| 65 | - << " dimensions"; | ||
| 66 | - | ||
| 67 | - // Extract keep_dim flag from kwargs (default: true) | ||
| 68 | - bool keep_dim = GetOpKwarg<bool>(kwargs, "keep_dim", true); | ||
| 69 | - | ||
| 70 | - // Build output shape | ||
| 71 | - std::vector<ExprPtr> output_shape; | ||
| 72 | - for (int64_t i = 0; i < input_ndim; ++i) { | ||
| 73 | - if (i == axis) { | ||
| 74 | - if (keep_dim) { | ||
| 75 | - // Keep dimension as 1 | ||
| 76 | - output_shape.push_back(std::make_shared<ConstInt>(1, DataType::INT64, Span::Unknown())); | ||
| 77 | - } | ||
| 78 | - // Otherwise, skip this dimension (reduce it out) | ||
| 79 | - } else { | ||
| 80 | - output_shape.push_back(input_shape[i]); | ||
| 81 | - } | ||
| 82 | - } | ||
| 83 | - | ||
| 84 | - // If output shape is empty (all dimensions reduced and keep_dim=false), return ScalarType | ||
| 85 | - if (output_shape.empty()) { | ||
| 86 | - return std::make_shared<ScalarType>(tensor_type->dtype_); | ||
| 87 | - } | ||
| 88 | - | ||
| 89 | - return std::make_shared<TensorType>(output_shape, tensor_type->dtype_); | ||
| 90 | -} | ||
| 91 | - | ||
| 92 | -// ============================================================================ | ||
| 93 | -// Registration Function for Tensor Reduction Operations | ||
| 94 | -// ============================================================================ | ||
| 95 | - | ||
| 96 | -REGISTER_OP("tensor.row_max") | ||
| 97 | - .set_op_category("TensorOp") | ||
| 98 | - .set_description("Row-wise maximum reduction along specified axis") | ||
| 99 | - .add_argument("input", "Input tensor (TensorType)") | ||
| 100 | - .set_attr<int>("axis") | ||
| 101 | - .set_attr<bool>("keep_dim") | ||
| 102 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 103 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 104 | - return DeduceTensorReductionType(args, kwargs, "tensor.row_max"); | ||
| 105 | - }); | ||
| 106 | - | ||
| 107 | -REGISTER_OP("tensor.row_sum") | ||
| 108 | - .set_op_category("TensorOp") | ||
| 109 | - .set_description("Row-wise sum reduction along specified axis") | ||
| 110 | - .add_argument("input", "Input tensor (TensorType)") | ||
| 111 | - .set_attr<int>("axis") | ||
| 112 | - .set_attr<bool>("keep_dim") | ||
| 113 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 114 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 115 | - return DeduceTensorReductionType(args, kwargs, "tensor.row_sum"); | ||
| 116 | - }); | ||
| 117 | - | ||
| 118 | -} // namespace ir | ||
| 119 | -} // namespace pypto | ||
| @@ -1,195 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -/** | ||
| 12 | - * @file transform.cpp | ||
| 13 | - * \brief Shape transformation tensor operations (reshape, transpose) | ||
| 14 | - * | ||
| 15 | - * This file implements shape transformation operations for tensors including | ||
| 16 | - * reshape and transpose operations. | ||
| 17 | - */ | ||
| 18 | - | ||
| 19 | -#include <any> | ||
| 20 | -#include <cstddef> | ||
| 21 | -#include <cstdint> | ||
| 22 | -#include <memory> | ||
| 23 | -#include <string> | ||
| 24 | -#include <utility> | ||
| 25 | -#include <vector> | ||
| 26 | - | ||
| 27 | -#include "core/dtype.h" | ||
| 28 | -#include "core/logging.h" | ||
| 29 | -#include "ir/expr.h" | ||
| 30 | -#include "ir/kind_traits.h" | ||
| 31 | -#include "ir/op_registry.h" | ||
| 32 | -#include "ir/scalar_expr.h" | ||
| 33 | -#include "ir/type.h" | ||
| 34 | -#include "ir/type_inference.h" | ||
| 35 | -#include "pypto_pro/error.h" | ||
| 36 | - | ||
| 37 | -namespace pypto { | ||
| 38 | -namespace ir { | ||
| 39 | -using npu::tile_fwk::ExternalError; | ||
| 40 | - | ||
| 41 | -namespace { | ||
| 42 | -// ============================================================================ | ||
| 43 | -// Helper Functions (file-local) | ||
| 44 | -// ============================================================================ | ||
| 45 | - | ||
| 46 | -/** | ||
| 47 | - * \brief Normalize axis index to handle negative indexing | ||
| 48 | - * | ||
| 49 | - * \param axis The axis index (can be negative) | ||
| 50 | - * \param ndim The number of dimensions | ||
| 51 | - * \return The normalized axis index | ||
| 52 | - */ | ||
| 53 | -int NormalizeAxis(int axis, size_t ndim) | ||
| 54 | -{ | ||
| 55 | - if (axis < 0) { | ||
| 56 | - axis += static_cast<int>(ndim); | ||
| 57 | - } | ||
| 58 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis >= 0 && axis < static_cast<int>(ndim)) | ||
| 59 | - << "Axis " << axis << " is out of range for " << ndim << "D tensor"; | ||
| 60 | - return axis; | ||
| 61 | -} | ||
| 62 | - | ||
| 63 | -} // anonymous namespace | ||
| 64 | - | ||
| 65 | -// ============================================================================ | ||
| 66 | -// Type Inference Functions | ||
| 67 | -// ============================================================================ | ||
| 68 | - | ||
| 69 | -TypePtr DeduceTensorReshapeType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 70 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 71 | -{ | ||
| 72 | - // tensor.reshape requires exactly 2 arguments: input tensor and shape tuple | ||
| 73 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 2) | ||
| 74 | - << "tensor.reshape requires exactly 2 arguments (input, shape), but got " << args.size(); | ||
| 75 | - | ||
| 76 | - // First argument must be TensorType | ||
| 77 | - auto tensor_type = As<TensorType>(args[0]->GetType()); | ||
| 78 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type) | ||
| 79 | - << "tensor.reshape requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName(); | ||
| 80 | - | ||
| 81 | - // Second argument must be TupleType (shape) | ||
| 82 | - auto shape_tuple_type = As<TupleType>(args[1]->GetType()); | ||
| 83 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_tuple_type) | ||
| 84 | - << "tensor.reshape requires shape to be TupleType, but got " << args[1]->GetType()->TypeName(); | ||
| 85 | - | ||
| 86 | - // Validate all shape elements are ScalarType with integer dtype | ||
| 87 | - for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) { | ||
| 88 | - auto scalar_type = As<ScalarType>(shape_tuple_type->types_[i]); | ||
| 89 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type) | ||
| 90 | - << "tensor.reshape shape tuple element " << i << " must be ScalarType, but got " | ||
| 91 | - << shape_tuple_type->types_[i]->TypeName(); | ||
| 92 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt()) | ||
| 93 | - << "tensor.reshape shape tuple element " << i << " must have integer dtype, but got " | ||
| 94 | - << scalar_type->dtype_.ToString(); | ||
| 95 | - } | ||
| 96 | - | ||
| 97 | - // Extract new shape dimensions | ||
| 98 | - // If args[1] is MakeTuple, extract elements directly to preserve constants | ||
| 99 | - // Otherwise use GetItemExpr for runtime tuples | ||
| 100 | - std::vector<ExprPtr> new_shape; | ||
| 101 | - new_shape.reserve(shape_tuple_type->types_.size()); | ||
| 102 | - | ||
| 103 | - if (auto make_tuple = As<MakeTuple>(args[1])) { | ||
| 104 | - // MakeTuple: extract elements directly to preserve ConstInt | ||
| 105 | - new_shape = make_tuple->elements_; | ||
| 106 | - } else { | ||
| 107 | - // Runtime tuple: use GetItemExpr with ConstInt slice | ||
| 108 | - for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) { | ||
| 109 | - auto idx_const = std::make_shared<ConstInt>(static_cast<int64_t>(i), DataType::INT64, args[1]->span_); | ||
| 110 | - new_shape.emplace_back(std::make_shared<GetItemExpr>(args[1], idx_const, args[1]->span_)); | ||
| 111 | - } | ||
| 112 | - } | ||
| 113 | - | ||
| 114 | - // For static shapes, verify that the total number of elements matches | ||
| 115 | - int64_t old_product = ComputeStaticShapeProduct(tensor_type->shape_); | ||
| 116 | - int64_t new_product = ComputeStaticShapeProduct(new_shape); | ||
| 117 | - if (old_product > 0 && new_product > 0) { | ||
| 118 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, old_product == new_product) | ||
| 119 | - << "tensor.reshape: cannot reshape tensor of size " << old_product << " into shape with size " | ||
| 120 | - << new_product; | ||
| 121 | - } | ||
| 122 | - | ||
| 123 | - // Return new TensorType with reshaped dimensions and same dtype | ||
| 124 | - return std::make_shared<TensorType>(new_shape, tensor_type->dtype_); | ||
| 125 | -} | ||
| 126 | - | ||
| 127 | -TypePtr DeduceTensorTransposeType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 128 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 129 | -{ | ||
| 130 | - // tensor.transpose requires exactly 3 arguments: input tensor, axis1, axis2 | ||
| 131 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3) | ||
| 132 | - << "tensor.transpose requires exactly 3 arguments (input, axis1, axis2), but got " << args.size(); | ||
| 133 | - | ||
| 134 | - // First argument must be TensorType | ||
| 135 | - auto tensor_type = As<TensorType>(args[0]->GetType()); | ||
| 136 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type) | ||
| 137 | - << "tensor.transpose requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName(); | ||
| 138 | - | ||
| 139 | - const auto& input_shape = tensor_type->shape_; | ||
| 140 | - size_t ndim = input_shape.size(); | ||
| 141 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, ndim >= 0x2) | ||
| 142 | - << "tensor.transpose requires at least 2 dimensions, but got " << ndim; | ||
| 143 | - | ||
| 144 | - // Second argument is axis1 (ConstInt) | ||
| 145 | - auto axis1_const = As<ConstInt>(args[1]); | ||
| 146 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis1_const) | ||
| 147 | - << "tensor.transpose requires second argument (axis1) to be a ConstInt"; | ||
| 148 | - | ||
| 149 | - // Third argument is axis2 (ConstInt) | ||
| 150 | - auto axis2_const = As<ConstInt>(args[2]); | ||
| 151 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis2_const) | ||
| 152 | - << "tensor.transpose requires third argument (axis2) to be a ConstInt"; | ||
| 153 | - | ||
| 154 | - // Normalize axes (handle negative indexing) | ||
| 155 | - int axis1 = NormalizeAxis(static_cast<int>(axis1_const->value_), ndim); | ||
| 156 | - int axis2 = NormalizeAxis(static_cast<int>(axis2_const->value_), ndim); | ||
| 157 | - | ||
| 158 | - PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis1 != axis2) | ||
| 159 | - << "tensor.transpose: axis1 and axis2 must be different, but got axis1=" << axis1 << ", axis2=" << axis2; | ||
| 160 | - | ||
| 161 | - // Create new shape by swapping the specified dimensions | ||
| 162 | - std::vector<ExprPtr> new_shape = input_shape; | ||
| 163 | - std::swap(new_shape[axis1], new_shape[axis2]); | ||
| 164 | - | ||
| 165 | - // Return new TensorType with transposed shape and same dtype | ||
| 166 | - return std::make_shared<TensorType>(new_shape, tensor_type->dtype_); | ||
| 167 | -} | ||
| 168 | - | ||
| 169 | -// ============================================================================ | ||
| 170 | -// Registration Function for Tensor Transform Operations | ||
| 171 | -// ============================================================================ | ||
| 172 | - | ||
| 173 | -REGISTER_OP("tensor.reshape") | ||
| 174 | - .set_op_category("TensorOp") | ||
| 175 | - .set_description("Reshape tensor to new shape") | ||
| 176 | - .add_argument("input", "Input tensor (TensorType)") | ||
| 177 | - .add_argument("shape", "New shape dimensions (TupleType of ScalarType(INT64))") | ||
| 178 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 179 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 180 | - return DeduceTensorReshapeType(args, kwargs); | ||
| 181 | - }); | ||
| 182 | - | ||
| 183 | -REGISTER_OP("tensor.transpose") | ||
| 184 | - .set_op_category("TensorOp") | ||
| 185 | - .set_description("Transpose tensor by swapping two axes") | ||
| 186 | - .add_argument("input", "Input tensor (TensorType)") | ||
| 187 | - .add_argument("axis1", "First axis to swap (ConstInt)") | ||
| 188 | - .add_argument("axis2", "Second axis to swap (ConstInt)") | ||
| 189 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 190 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 191 | - return DeduceTensorTransposeType(args, kwargs); | ||
| 192 | - }); | ||
| 193 | - | ||
| 194 | -} // namespace ir | ||
| 195 | -} // namespace pypto | ||
| @@ -1,118 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -/** | ||
| 12 | - * @file unary.cpp | ||
| 13 | - * \brief Unary tensor operations (exp, cast) | ||
| 14 | - * | ||
| 15 | - * This file implements unary operations for tensors that operate element-wise. | ||
| 16 | - */ | ||
| 17 | - | ||
| 18 | -#include <any> | ||
| 19 | -#include <memory> | ||
| 20 | -#include <string> | ||
| 21 | -#include <utility> | ||
| 22 | -#include <vector> | ||
| 23 | - | ||
| 24 | -#include "core/any_cast.h" | ||
| 25 | -#include "core/dtype.h" | ||
| 26 | -#include "core/error.h" | ||
| 27 | -#include "core/logging.h" | ||
| 28 | -#include "ir/kind_traits.h" | ||
| 29 | -#include "ir/op_registry.h" | ||
| 30 | -#include "ir/type.h" | ||
| 31 | -#include "pypto_pro/error.h" | ||
| 32 | -namespace pypto { | ||
| 33 | -namespace ir { | ||
| 34 | -using npu::tile_fwk::ExternalError; | ||
| 35 | - | ||
| 36 | -TypePtr DeduceTensorExpType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 37 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 38 | -{ | ||
| 39 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1) | ||
| 40 | - << "tensor.exp requires exactly 1 argument, but got " << args.size(); | ||
| 41 | - | ||
| 42 | - auto tensor_type = As<TensorType>(args[0]->GetType()); | ||
| 43 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type) | ||
| 44 | - << "tensor.exp requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName(); | ||
| 45 | - | ||
| 46 | - // exp should promote to float type if input is integer | ||
| 47 | - // Exponential always produces floating-point output (e.g., exp(1) = 2.718...) | ||
| 48 | - DataType out_dtype = tensor_type->dtype_; | ||
| 49 | - if (!out_dtype.IsFloat()) { | ||
| 50 | - // Promote to default float type (FP32) | ||
| 51 | - out_dtype = DataType::FP32; | ||
| 52 | - } | ||
| 53 | - | ||
| 54 | - return std::make_shared<TensorType>(tensor_type->shape_, out_dtype); | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -TypePtr DeduceTensorCastType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 58 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 59 | -{ | ||
| 60 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1) | ||
| 61 | - << "tensor.cast requires exactly 1 argument (input), but got " << args.size(); | ||
| 62 | - | ||
| 63 | - auto tensor_type = As<TensorType>(args[0]->GetType()); | ||
| 64 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type) | ||
| 65 | - << "tensor.cast requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName(); | ||
| 66 | - | ||
| 67 | - // Read target_type from kwargs | ||
| 68 | - bool found_target_type = false; | ||
| 69 | - DataType target_dtype; | ||
| 70 | - for (const auto& [key, value] : kwargs) { | ||
| 71 | - if (key == "target_type") { | ||
| 72 | - // Handle both DataType and int for backward compatibility | ||
| 73 | - if (value.type() == typeid(DataType)) { | ||
| 74 | - target_dtype = AnyCast<DataType>(value, "kwarg key: target_type"); | ||
| 75 | - } else if (value.type() == typeid(int)) { | ||
| 76 | - target_dtype = static_cast<DataType>(AnyCast<int>(value, "kwarg key: target_type")); | ||
| 77 | - } else { | ||
| 78 | - PRO_IR_CHECK(ExternalError::INVALID_TYPE, false) | ||
| 79 | - << "target_type must be a DataType or int, but got " << value.type().name(); | ||
| 80 | - } | ||
| 81 | - found_target_type = true; | ||
| 82 | - break; | ||
| 83 | - } | ||
| 84 | - } | ||
| 85 | - PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, found_target_type) << "tensor.cast requires 'target_type' kwarg"; | ||
| 86 | - | ||
| 87 | - // mode kwarg is optional, not used in type deduction | ||
| 88 | - | ||
| 89 | - // Cast preserves shape but changes dtype | ||
| 90 | - return std::make_shared<TensorType>(tensor_type->shape_, target_dtype); | ||
| 91 | -} | ||
| 92 | - | ||
| 93 | -// ============================================================================ | ||
| 94 | -// Registration Function for Tensor Unary Operations | ||
| 95 | -// ============================================================================ | ||
| 96 | - | ||
| 97 | -REGISTER_OP("tensor.exp") | ||
| 98 | - .set_op_category("TensorOp") | ||
| 99 | - .set_description("Element-wise exponential operation") | ||
| 100 | - .add_argument("input", "Input tensor (TensorType)") | ||
| 101 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 102 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 103 | - return DeduceTensorExpType(args, kwargs); | ||
| 104 | - }); | ||
| 105 | - | ||
| 106 | -REGISTER_OP("tensor.cast") | ||
| 107 | - .set_op_category("TensorOp") | ||
| 108 | - .set_description("Type casting operation") | ||
| 109 | - .add_argument("input", "Input tensor (TensorType)") | ||
| 110 | - .set_attr<DataType>("target_type") | ||
| 111 | - .set_attr<int>("mode") | ||
| 112 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 113 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 114 | - return DeduceTensorCastType(args, kwargs); | ||
| 115 | - }); | ||
| 116 | - | ||
| 117 | -} // namespace ir | ||
| 118 | -} // namespace pypto | ||
| @@ -28,31 +28,12 @@ OpConversionRegistry& OpConversionRegistry::GetInstance() | |||
| 28 | return instance; | 28 | return instance; |
| 29 | } | 29 | } |
| 30 | 30 | ||
| 31 | -OpConversionRegistry::OpConversionRegistry() | 31 | +// No default conversions: the tensor.* operators these used to lower from were |
| 32 | -{ | 32 | +// removed (they had no backend implementation, so a kernel using one only failed |
| 33 | - // Register default simple conversions (tensor op -> block op) | 33 | +// once it reached codegen). Conversions are registered by whoever needs them, |
| 34 | - | 34 | +// through RegisterSimple / RegisterCustom or their `register_op_conversion` |
| 35 | - // Elementwise binary ops | 35 | +// bindings. |
| 36 | - RegisterSimple("tensor.add", "block.add"); | 36 | +OpConversionRegistry::OpConversionRegistry() = default; |
| 37 | - RegisterSimple("tensor.sub", "block.sub"); | ||
| 38 | - RegisterSimple("tensor.mul", "block.mul"); | ||
| 39 | - RegisterSimple("tensor.div", "block.div"); | ||
| 40 | - RegisterSimple("tensor.maximum", "block.maximum"); | ||
| 41 | - | ||
| 42 | - // Scalar ops | ||
| 43 | - RegisterSimple("tensor.add_scalar", "block.adds"); | ||
| 44 | - RegisterSimple("tensor.sub_scalar", "block.subs"); | ||
| 45 | - RegisterSimple("tensor.mul_scalar", "block.muls"); | ||
| 46 | - RegisterSimple("tensor.div_scalar", "block.divs"); | ||
| 47 | - | ||
| 48 | - // Unary ops | ||
| 49 | - RegisterSimple("tensor.exp", "block.exp"); | ||
| 50 | - RegisterSimple("tensor.cast", "block.cast"); | ||
| 51 | - | ||
| 52 | - // Transform ops | ||
| 53 | - RegisterSimple("tensor.reshape", "block.reshape"); | ||
| 54 | - RegisterSimple("tensor.transpose", "block.transpose"); | ||
| 55 | -} | ||
| 56 | 37 | ||
| 57 | void OpConversionRegistry::RegisterSimple(const std::string& from_op, const std::string& to_op) | 38 | void OpConversionRegistry::RegisterSimple(const std::string& from_op, const std::string& to_op) |
| 58 | { | 39 | { |
| @@ -15,6 +15,7 @@ | |||
| 15 | 15 | ||
| 16 | #include "pypto_pro/error.h" | 16 | #include "pypto_pro/error.h" |
| 17 | 17 | ||
| 18 | +#include <cstring> | ||
| 18 | #include <iomanip> | 19 | #include <iomanip> |
| 19 | #include <sstream> | 20 | #include <sstream> |
| 20 | 21 | ||
| @@ -32,6 +33,31 @@ thread_local ir::Span g_currentSpan; | |||
| 32 | 33 | ||
| 33 | constexpr unsigned CODE_MASK = 0xFFFFFU; | 34 | constexpr unsigned CODE_MASK = 0xFFFFFU; |
| 34 | constexpr int CODE_WIDTH = 5; | 35 | constexpr int CODE_WIDTH = 5; |
| 36 | +constexpr unsigned CLASS_MASK = 0xF0000U; | ||
| 37 | + | ||
| 38 | +/** | ||
| 39 | + * \brief The enum member name, without the qualification the call site wrote. | ||
| 40 | + * | ||
| 41 | + * PRO_ERR_ stringifies whatever the call site typed, so the depth varies: most | ||
| 42 | + * sites write `ExternalError::X`, the internal checks write | ||
| 43 | + * `npu::tile_fwk::InternalError::X`. Keep only the member so the printed form | ||
| 44 | + * stops depending on how the call site spelled it. | ||
| 45 | + */ | ||
| 46 | +const char* BareEnumName(const char* codeName) | ||
| 47 | +{ | ||
| 48 | + const char* lastColon = std::strrchr(codeName, ':'); | ||
| 49 | + return lastColon != nullptr ? lastColon + 1 : codeName; | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/** | ||
| 53 | + * \brief The enum class a code belongs to, from the code itself. | ||
| 54 | + * | ||
| 55 | + * Every InternalError member sits above the low 16 bits (0x1FFFF and up); every | ||
| 56 | + * ExternalError member stays inside them. The Python side derives the same | ||
| 57 | + * prefix from the same bits (`_errors.py` spec_first_line), so both sides | ||
| 58 | + * render one format. | ||
| 59 | + */ | ||
| 60 | +const char* EnumClassName(unsigned code) { return (code & CLASS_MASK) == 0U ? "ExternalError" : "InternalError"; } | ||
| 35 | 61 | ||
| 36 | } // namespace | 62 | } // namespace |
| 37 | 63 | ||
| @@ -53,7 +79,8 @@ std::string ErrHead(const char* file, int line, const char* module, unsigned cod | |||
| 53 | std::ostringstream oss; | 79 | std::ostringstream oss; |
| 54 | oss << "[" << file << ":" << line << "][" << module << "]:" | 80 | oss << "[" << file << ":" << line << "][" << module << "]:" |
| 55 | << "ErrCode: F" << std::uppercase << std::hex << std::setw(CODE_WIDTH) << std::setfill('0') | 81 | << "ErrCode: F" << std::uppercase << std::hex << std::setw(CODE_WIDTH) << std::setfill('0') |
| 56 | - << (code & CODE_MASK) << std::dec << "! Enum: " << codeName << ". "; | 82 | + << (code & CODE_MASK) << std::dec << "! Enum: " << EnumClassName(code & CODE_MASK) |
| 83 | + << "::" << BareEnumName(codeName) << ". "; | ||
| 57 | return oss.str(); | 84 | return oss.str(); |
| 58 | } | 85 | } |
| 59 | 86 | ||
| @@ -1,484 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -/*! | ||
| 12 | - * \file test_tensor_ops.cpp | ||
| 13 | - * \brief Coverage tests for tensor_ops type deduction via OpRegistry::Create | ||
| 14 | - */ | ||
| 15 | - | ||
| 16 | -#include "gtest/gtest.h" | ||
| 17 | - | ||
| 18 | -#include <any> | ||
| 19 | -#include <cstdint> | ||
| 20 | -#include <memory> | ||
| 21 | -#include <string> | ||
| 22 | -#include <utility> | ||
| 23 | -#include <vector> | ||
| 24 | - | ||
| 25 | -#include "core/dtype.h" | ||
| 26 | -#include "core/error.h" | ||
| 27 | -#include "ir/expr.h" | ||
| 28 | -#include "ir/kind_traits.h" | ||
| 29 | -#include "ir/op_registry.h" | ||
| 30 | -#include "ir/scalar_expr.h" | ||
| 31 | -#include "ir/type.h" | ||
| 32 | -#include "test_op_helpers.h" | ||
| 33 | -#include "tilefwk/error.h" | ||
| 34 | - | ||
| 35 | -namespace pypto { | ||
| 36 | -namespace ir { | ||
| 37 | - | ||
| 38 | -using namespace test_helpers; | ||
| 39 | - | ||
| 40 | -// MakeShapeTuple is just an alias for MakeOffsetsTuple in this context | ||
| 41 | -static ExprPtr MakeShapeTuple(std::vector<int64_t> dims) { return MakeOffsetsTuple(dims); } | ||
| 42 | - | ||
| 43 | -// ============================================================================ | ||
| 44 | -// elementwise.cpp: tensor.add (binary), tensor.add_scalar (tensor+scalar) | ||
| 45 | -// ============================================================================ | ||
| 46 | - | ||
| 47 | -class TensorOpsElemwiseTest : public testing::Test {}; | ||
| 48 | - | ||
| 49 | -TEST_F(TensorOpsElemwiseTest, TensorAdd_TwoTensors_ReturnsBroadcastedType) | ||
| 50 | -{ | ||
| 51 | - auto& reg = OpRegistry::GetInstance(); | ||
| 52 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP16); | ||
| 53 | - auto rhs = MakeTensorVar("b", {4, 8}, DataType::FP16); | ||
| 54 | - auto call = reg.Create("tensor.add", {lhs, rhs}, Sp()); | ||
| 55 | - auto rt = As<TensorType>(call->GetType()); | ||
| 56 | - ASSERT_NE(rt, nullptr); | ||
| 57 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 58 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 59 | -} | ||
| 60 | - | ||
| 61 | -TEST_F(TensorOpsElemwiseTest, TensorAdd_Broadcasting_ReturnsLargerShape) | ||
| 62 | -{ | ||
| 63 | - auto& reg = OpRegistry::GetInstance(); | ||
| 64 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP32); | ||
| 65 | - auto rhs = MakeTensorVar("b", {8}, DataType::FP32); | ||
| 66 | - auto call = reg.Create("tensor.add", {lhs, rhs}, Sp()); | ||
| 67 | - auto rt = As<TensorType>(call->GetType()); | ||
| 68 | - ASSERT_NE(rt, nullptr); | ||
| 69 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 70 | -} | ||
| 71 | - | ||
| 72 | -TEST_F(TensorOpsElemwiseTest, TensorAdd_DtypePromotion) | ||
| 73 | -{ | ||
| 74 | - auto& reg = OpRegistry::GetInstance(); | ||
| 75 | - auto lhs = MakeTensorVar("a", {16}, DataType::INT32); | ||
| 76 | - auto rhs = MakeTensorVar("b", {16}, DataType::FP32); | ||
| 77 | - auto call = reg.Create("tensor.add", {lhs, rhs}, Sp()); | ||
| 78 | - auto rt = As<TensorType>(call->GetType()); | ||
| 79 | - ASSERT_NE(rt, nullptr); | ||
| 80 | - EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 81 | -} | ||
| 82 | - | ||
| 83 | -TEST_F(TensorOpsElemwiseTest, TensorAdd_WrongArgCount_Throws) | ||
| 84 | -{ | ||
| 85 | - auto& reg = OpRegistry::GetInstance(); | ||
| 86 | - EXPECT_THROW((void)reg.Create("tensor.add", {MakeTensorVar("a", {16}, DataType::FP32)}, Sp()), | ||
| 87 | - npu::tile_fwk::Error); | ||
| 88 | -} | ||
| 89 | - | ||
| 90 | -TEST_F(TensorOpsElemwiseTest, TensorAdd_NonTensorArg_Throws) | ||
| 91 | -{ | ||
| 92 | - auto& reg = OpRegistry::GetInstance(); | ||
| 93 | - EXPECT_THROW((void)reg.Create("tensor.add", | ||
| 94 | - {MakeScalarVar("s", DataType::FP32), MakeTensorVar("b", {16}, DataType::FP32)}, Sp()), | ||
| 95 | - npu::tile_fwk::Error); | ||
| 96 | -} | ||
| 97 | - | ||
| 98 | -TEST_F(TensorOpsElemwiseTest, TensorAddScalar_ReturnsTensorType) | ||
| 99 | -{ | ||
| 100 | - auto& reg = OpRegistry::GetInstance(); | ||
| 101 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP16); | ||
| 102 | - auto rhs = MakeScalarVar("s", DataType::FP16); | ||
| 103 | - auto call = reg.Create("tensor.add_scalar", {lhs, rhs}, Sp()); | ||
| 104 | - auto rt = As<TensorType>(call->GetType()); | ||
| 105 | - ASSERT_NE(rt, nullptr); | ||
| 106 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 107 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 108 | -} | ||
| 109 | - | ||
| 110 | -TEST_F(TensorOpsElemwiseTest, TensorAddScalar_NonScalarSecond_Throws) | ||
| 111 | -{ | ||
| 112 | - auto& reg = OpRegistry::GetInstance(); | ||
| 113 | - EXPECT_THROW( | ||
| 114 | - (void)reg.Create("tensor.add_scalar", | ||
| 115 | - {MakeTensorVar("a", {16}, DataType::FP32), MakeTensorVar("b", {16}, DataType::FP32)}, Sp()), | ||
| 116 | - npu::tile_fwk::Error); | ||
| 117 | -} | ||
| 118 | - | ||
| 119 | -// Representative coverage for other elementwise binary ops (sub, mul, div, maximum). | ||
| 120 | -// All use DeduceTensorOpElementwiseBinaryType: validate 2 tensor args, broadcast shapes, promote dtypes. | ||
| 121 | - | ||
| 122 | -TEST_F(TensorOpsElemwiseTest, TensorSub_ReturnsTensorType) | ||
| 123 | -{ | ||
| 124 | - auto& reg = OpRegistry::GetInstance(); | ||
| 125 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP16); | ||
| 126 | - auto rhs = MakeTensorVar("b", {4, 8}, DataType::FP16); | ||
| 127 | - auto call = reg.Create("tensor.sub", {lhs, rhs}, Sp()); | ||
| 128 | - auto rt = As<TensorType>(call->GetType()); | ||
| 129 | - ASSERT_NE(rt, nullptr); | ||
| 130 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 131 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 132 | -} | ||
| 133 | - | ||
| 134 | -TEST_F(TensorOpsElemwiseTest, TensorMul_ReturnsTensorType) | ||
| 135 | -{ | ||
| 136 | - auto& reg = OpRegistry::GetInstance(); | ||
| 137 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP32); | ||
| 138 | - auto rhs = MakeTensorVar("b", {4, 8}, DataType::FP32); | ||
| 139 | - auto call = reg.Create("tensor.mul", {lhs, rhs}, Sp()); | ||
| 140 | - auto rt = As<TensorType>(call->GetType()); | ||
| 141 | - ASSERT_NE(rt, nullptr); | ||
| 142 | - EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 143 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 144 | -} | ||
| 145 | - | ||
| 146 | -TEST_F(TensorOpsElemwiseTest, TensorDiv_ReturnsTensorType) | ||
| 147 | -{ | ||
| 148 | - auto& reg = OpRegistry::GetInstance(); | ||
| 149 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP32); | ||
| 150 | - auto rhs = MakeTensorVar("b", {4, 8}, DataType::FP32); | ||
| 151 | - auto call = reg.Create("tensor.div", {lhs, rhs}, Sp()); | ||
| 152 | - auto rt = As<TensorType>(call->GetType()); | ||
| 153 | - ASSERT_NE(rt, nullptr); | ||
| 154 | - EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 155 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 156 | -} | ||
| 157 | - | ||
| 158 | -TEST_F(TensorOpsElemwiseTest, TensorMaximum_ReturnsTensorType) | ||
| 159 | -{ | ||
| 160 | - auto& reg = OpRegistry::GetInstance(); | ||
| 161 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP16); | ||
| 162 | - auto rhs = MakeTensorVar("b", {4, 8}, DataType::FP16); | ||
| 163 | - auto call = reg.Create("tensor.maximum", {lhs, rhs}, Sp()); | ||
| 164 | - auto rt = As<TensorType>(call->GetType()); | ||
| 165 | - ASSERT_NE(rt, nullptr); | ||
| 166 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 167 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 168 | -} | ||
| 169 | - | ||
| 170 | -// Representative coverage for elementwise scalar ops (sub_scalar, mul_scalar, div_scalar). | ||
| 171 | -// All use DeduceTensorOpElementwiseScalarType: validate tensor+scalar args, preserve tensor shape. | ||
| 172 | - | ||
| 173 | -TEST_F(TensorOpsElemwiseTest, TensorSubScalar_ReturnsTensorType) | ||
| 174 | -{ | ||
| 175 | - auto& reg = OpRegistry::GetInstance(); | ||
| 176 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP16); | ||
| 177 | - auto rhs = MakeScalarVar("s", DataType::FP16); | ||
| 178 | - auto call = reg.Create("tensor.sub_scalar", {lhs, rhs}, Sp()); | ||
| 179 | - auto rt = As<TensorType>(call->GetType()); | ||
| 180 | - ASSERT_NE(rt, nullptr); | ||
| 181 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 182 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 183 | -} | ||
| 184 | - | ||
| 185 | -TEST_F(TensorOpsElemwiseTest, TensorMulScalar_ReturnsTensorType) | ||
| 186 | -{ | ||
| 187 | - auto& reg = OpRegistry::GetInstance(); | ||
| 188 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP32); | ||
| 189 | - auto rhs = MakeScalarVar("s", DataType::FP32); | ||
| 190 | - auto call = reg.Create("tensor.mul_scalar", {lhs, rhs}, Sp()); | ||
| 191 | - auto rt = As<TensorType>(call->GetType()); | ||
| 192 | - ASSERT_NE(rt, nullptr); | ||
| 193 | - EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 194 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 195 | -} | ||
| 196 | - | ||
| 197 | -TEST_F(TensorOpsElemwiseTest, TensorDivScalar_ReturnsTensorType) | ||
| 198 | -{ | ||
| 199 | - auto& reg = OpRegistry::GetInstance(); | ||
| 200 | - auto lhs = MakeTensorVar("a", {4, 8}, DataType::FP32); | ||
| 201 | - auto rhs = MakeScalarVar("s", DataType::FP32); | ||
| 202 | - auto call = reg.Create("tensor.div_scalar", {lhs, rhs}, Sp()); | ||
| 203 | - auto rt = As<TensorType>(call->GetType()); | ||
| 204 | - ASSERT_NE(rt, nullptr); | ||
| 205 | - EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 206 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 207 | -} | ||
| 208 | - | ||
| 209 | -// ============================================================================ | ||
| 210 | -// unary.cpp: tensor.exp, tensor.cast | ||
| 211 | -// ============================================================================ | ||
| 212 | - | ||
| 213 | -class TensorOpsUnaryTest : public testing::Test {}; | ||
| 214 | - | ||
| 215 | -TEST_F(TensorOpsUnaryTest, TensorExp_FloatInput_PreservesDtype) | ||
| 216 | -{ | ||
| 217 | - auto& reg = OpRegistry::GetInstance(); | ||
| 218 | - auto call = reg.Create("tensor.exp", {MakeTensorVar("t", {16, 32}, DataType::FP16)}, Sp()); | ||
| 219 | - auto rt = As<TensorType>(call->GetType()); | ||
| 220 | - ASSERT_NE(rt, nullptr); | ||
| 221 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 222 | -} | ||
| 223 | - | ||
| 224 | -TEST_F(TensorOpsUnaryTest, TensorExp_IntInput_PromotesToFP32) | ||
| 225 | -{ | ||
| 226 | - auto& reg = OpRegistry::GetInstance(); | ||
| 227 | - auto call = reg.Create("tensor.exp", {MakeTensorVar("t", {16}, DataType::INT32)}, Sp()); | ||
| 228 | - auto rt = As<TensorType>(call->GetType()); | ||
| 229 | - ASSERT_NE(rt, nullptr); | ||
| 230 | - EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 231 | -} | ||
| 232 | - | ||
| 233 | -TEST_F(TensorOpsUnaryTest, TensorExp_NonTensor_Throws) | ||
| 234 | -{ | ||
| 235 | - auto& reg = OpRegistry::GetInstance(); | ||
| 236 | - EXPECT_THROW((void)reg.Create("tensor.exp", {MakeScalarVar("s", DataType::FP32)}, Sp()), npu::tile_fwk::Error); | ||
| 237 | -} | ||
| 238 | - | ||
| 239 | -TEST_F(TensorOpsUnaryTest, TensorCast_ChangesDtype) | ||
| 240 | -{ | ||
| 241 | - auto& reg = OpRegistry::GetInstance(); | ||
| 242 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"target_type", DataType::FP16}}; | ||
| 243 | - auto call = reg.Create("tensor.cast", {MakeTensorVar("t", {8, 16}, DataType::FP32)}, kwargs, Sp()); | ||
| 244 | - auto rt = As<TensorType>(call->GetType()); | ||
| 245 | - ASSERT_NE(rt, nullptr); | ||
| 246 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 247 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 248 | -} | ||
| 249 | - | ||
| 250 | -TEST_F(TensorOpsUnaryTest, TensorCast_MissingTargetType_Throws) | ||
| 251 | -{ | ||
| 252 | - auto& reg = OpRegistry::GetInstance(); | ||
| 253 | - EXPECT_THROW((void)reg.Create("tensor.cast", {MakeTensorVar("t", {8}, DataType::FP32)}, Sp()), | ||
| 254 | - npu::tile_fwk::Error); | ||
| 255 | -} | ||
| 256 | - | ||
| 257 | -// ============================================================================ | ||
| 258 | -// matmul.cpp: tensor.matmul | ||
| 259 | -// ============================================================================ | ||
| 260 | - | ||
| 261 | -class TensorOpsMatmulTest : public testing::Test {}; | ||
| 262 | - | ||
| 263 | -TEST_F(TensorOpsMatmulTest, Matmul_2Dx2D_ReturnsCorrectShape) | ||
| 264 | -{ | ||
| 265 | - auto& reg = OpRegistry::GetInstance(); | ||
| 266 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"a_trans", false}, {"b_trans", false}}; | ||
| 267 | - auto call = reg.Create("tensor.matmul", | ||
| 268 | - {MakeTensorVar("a", {16, 32}, DataType::FP16), MakeTensorVar("b", {32, 64}, DataType::FP16)}, | ||
| 269 | - kwargs, Sp()); | ||
| 270 | - auto rt = As<TensorType>(call->GetType()); | ||
| 271 | - ASSERT_NE(rt, nullptr); | ||
| 272 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 273 | -} | ||
| 274 | - | ||
| 275 | -TEST_F(TensorOpsMatmulTest, Matmul_WithTranspose_ReturnsCorrectShape) | ||
| 276 | -{ | ||
| 277 | - auto& reg = OpRegistry::GetInstance(); | ||
| 278 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"a_trans", true}, {"b_trans", false}}; | ||
| 279 | - auto call = reg.Create("tensor.matmul", | ||
| 280 | - {MakeTensorVar("a", {32, 16}, DataType::FP16), MakeTensorVar("b", {32, 64}, DataType::FP16)}, | ||
| 281 | - kwargs, Sp()); | ||
| 282 | - auto rt = As<TensorType>(call->GetType()); | ||
| 283 | - ASSERT_NE(rt, nullptr); | ||
| 284 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 285 | -} | ||
| 286 | - | ||
| 287 | -TEST_F(TensorOpsMatmulTest, Matmul_VectorDot_ReturnsScalarTensor) | ||
| 288 | -{ | ||
| 289 | - auto& reg = OpRegistry::GetInstance(); | ||
| 290 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"a_trans", false}, {"b_trans", false}}; | ||
| 291 | - auto call = reg.Create("tensor.matmul", | ||
| 292 | - {MakeTensorVar("a", {32}, DataType::FP32), MakeTensorVar("b", {32}, DataType::FP32)}, kwargs, | ||
| 293 | - Sp()); | ||
| 294 | - auto rt = As<TensorType>(call->GetType()); | ||
| 295 | - ASSERT_NE(rt, nullptr); | ||
| 296 | - EXPECT_EQ(rt->shape_.size(), 0u); | ||
| 297 | -} | ||
| 298 | - | ||
| 299 | -TEST_F(TensorOpsMatmulTest, Matmul_Batched3D_ReturnsBatchedShape) | ||
| 300 | -{ | ||
| 301 | - auto& reg = OpRegistry::GetInstance(); | ||
| 302 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"a_trans", false}, {"b_trans", false}}; | ||
| 303 | - auto call = reg.Create( | ||
| 304 | - "tensor.matmul", | ||
| 305 | - {MakeTensorVar("a", {4, 16, 32}, DataType::FP16), MakeTensorVar("b", {4, 32, 64}, DataType::FP16)}, kwargs, | ||
| 306 | - Sp()); | ||
| 307 | - auto rt = As<TensorType>(call->GetType()); | ||
| 308 | - ASSERT_NE(rt, nullptr); | ||
| 309 | - EXPECT_EQ(rt->shape_.size(), 3u); | ||
| 310 | -} | ||
| 311 | - | ||
| 312 | -TEST_F(TensorOpsMatmulTest, Matmul_WrongArgCount_Throws) | ||
| 313 | -{ | ||
| 314 | - auto& reg = OpRegistry::GetInstance(); | ||
| 315 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"a_trans", false}, {"b_trans", false}}; | ||
| 316 | - EXPECT_THROW((void)reg.Create("tensor.matmul", {MakeTensorVar("a", {16, 32}, DataType::FP16)}, kwargs, Sp()), | ||
| 317 | - npu::tile_fwk::Error); | ||
| 318 | -} | ||
| 319 | - | ||
| 320 | -// ============================================================================ | ||
| 321 | -// tensor.create, tensor.view, tensor.assemble | ||
| 322 | -// ============================================================================ | ||
| 323 | - | ||
| 324 | -class TensorOpsMemoryTest : public testing::Test {}; | ||
| 325 | - | ||
| 326 | -TEST_F(TensorOpsMemoryTest, TensorCreate_ReturnsTensorWithShape) | ||
| 327 | -{ | ||
| 328 | - auto& reg = OpRegistry::GetInstance(); | ||
| 329 | - auto shape = MakeShapeTuple({16, 32}); | ||
| 330 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"dtype", DataType::FP16}}; | ||
| 331 | - auto call = reg.Create("tensor.create", {shape}, kwargs, Sp()); | ||
| 332 | - auto rt = As<TensorType>(call->GetType()); | ||
| 333 | - ASSERT_NE(rt, nullptr); | ||
| 334 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 335 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 336 | -} | ||
| 337 | - | ||
| 338 | -TEST_F(TensorOpsMemoryTest, TensorCreate_MissingDtype_Throws) | ||
| 339 | -{ | ||
| 340 | - auto& reg = OpRegistry::GetInstance(); | ||
| 341 | - auto shape = MakeShapeTuple({16}); | ||
| 342 | - EXPECT_THROW((void)reg.Create("tensor.create", {shape}, Sp()), npu::tile_fwk::Error); | ||
| 343 | -} | ||
| 344 | - | ||
| 345 | -TEST_F(TensorOpsMemoryTest, TensorView_ReturnsTensorWithNewShape) | ||
| 346 | -{ | ||
| 347 | - auto& reg = OpRegistry::GetInstance(); | ||
| 348 | - auto tensor = MakeTensorVar("t", {64, 128}, DataType::FP32); | ||
| 349 | - auto shape = MakeShapeTuple({32, 64}); | ||
| 350 | - auto offset = MakeShapeTuple({0, 0}); | ||
| 351 | - auto call = reg.Create("tensor.view", {tensor, shape, offset}, Sp()); | ||
| 352 | - auto rt = As<TensorType>(call->GetType()); | ||
| 353 | - ASSERT_NE(rt, nullptr); | ||
| 354 | - EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 355 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 356 | -} | ||
| 357 | - | ||
| 358 | -TEST_F(TensorOpsMemoryTest, TensorView_WrongArgCount_Throws) | ||
| 359 | -{ | ||
| 360 | - auto& reg = OpRegistry::GetInstance(); | ||
| 361 | - EXPECT_THROW( | ||
| 362 | - (void)reg.Create("tensor.view", {MakeTensorVar("t", {64}, DataType::FP32), MakeShapeTuple({32})}, Sp()), | ||
| 363 | - npu::tile_fwk::Error); | ||
| 364 | -} | ||
| 365 | - | ||
| 366 | -TEST_F(TensorOpsMemoryTest, TensorAssemble_ReturnsTargetType) | ||
| 367 | -{ | ||
| 368 | - auto& reg = OpRegistry::GetInstance(); | ||
| 369 | - auto target = MakeTensorVar("target", {64, 128}, DataType::FP16); | ||
| 370 | - auto source = MakeTensorVar("source", {16, 32}, DataType::FP16); | ||
| 371 | - auto offset = MakeShapeTuple({0, 0}); | ||
| 372 | - auto call = reg.Create("tensor.assemble", {target, source, offset}, Sp()); | ||
| 373 | - auto rt = As<TensorType>(call->GetType()); | ||
| 374 | - ASSERT_NE(rt, nullptr); | ||
| 375 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 376 | -} | ||
| 377 | - | ||
| 378 | -// ============================================================================ | ||
| 379 | -// reduction.cpp: tensor.row_max, tensor.row_sum | ||
| 380 | -// ============================================================================ | ||
| 381 | - | ||
| 382 | -class TensorOpsReductionTest : public testing::Test {}; | ||
| 383 | - | ||
| 384 | -TEST_F(TensorOpsReductionTest, TensorRowMax_KeepDim_ReturnsReducedShape) | ||
| 385 | -{ | ||
| 386 | - auto& reg = OpRegistry::GetInstance(); | ||
| 387 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"axis", int(-1)}, {"keep_dim", true}}; | ||
| 388 | - auto call = reg.Create("tensor.row_max", {MakeTensorVar("t", {16, 32}, DataType::FP16)}, kwargs, Sp()); | ||
| 389 | - auto rt = As<TensorType>(call->GetType()); | ||
| 390 | - ASSERT_NE(rt, nullptr); | ||
| 391 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 392 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 393 | -} | ||
| 394 | - | ||
| 395 | -TEST_F(TensorOpsReductionTest, TensorRowSum_NoKeepDim_RemovesDim) | ||
| 396 | -{ | ||
| 397 | - auto& reg = OpRegistry::GetInstance(); | ||
| 398 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"axis", int(1)}, {"keep_dim", false}}; | ||
| 399 | - auto call = reg.Create("tensor.row_sum", {MakeTensorVar("t", {16, 32}, DataType::FP32)}, kwargs, Sp()); | ||
| 400 | - auto rt = As<TensorType>(call->GetType()); | ||
| 401 | - ASSERT_NE(rt, nullptr); | ||
| 402 | - EXPECT_EQ(rt->shape_.size(), 1u); | ||
| 403 | -} | ||
| 404 | - | ||
| 405 | -TEST_F(TensorOpsReductionTest, TensorRowMax_1D_NoKeepDim_ReturnsScalar) | ||
| 406 | -{ | ||
| 407 | - auto& reg = OpRegistry::GetInstance(); | ||
| 408 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"axis", int(0)}, {"keep_dim", false}}; | ||
| 409 | - auto call = reg.Create("tensor.row_max", {MakeTensorVar("t", {64}, DataType::FP32)}, kwargs, Sp()); | ||
| 410 | - auto rt = As<ScalarType>(call->GetType()); | ||
| 411 | - ASSERT_NE(rt, nullptr); | ||
| 412 | - EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 413 | -} | ||
| 414 | - | ||
| 415 | -TEST_F(TensorOpsReductionTest, TensorRowMax_NonTensor_Throws) | ||
| 416 | -{ | ||
| 417 | - auto& reg = OpRegistry::GetInstance(); | ||
| 418 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"axis", int(0)}, {"keep_dim", true}}; | ||
| 419 | - EXPECT_THROW((void)reg.Create("tensor.row_max", {MakeScalarVar("s", DataType::FP32)}, kwargs, Sp()), | ||
| 420 | - npu::tile_fwk::Error); | ||
| 421 | -} | ||
| 422 | - | ||
| 423 | -// ============================================================================ | ||
| 424 | -// transform.cpp: tensor.reshape, tensor.transpose | ||
| 425 | -// ============================================================================ | ||
| 426 | - | ||
| 427 | -class TensorOpsTransformTest : public testing::Test {}; | ||
| 428 | - | ||
| 429 | -TEST_F(TensorOpsTransformTest, TensorReshape_ReturnsNewShape) | ||
| 430 | -{ | ||
| 431 | - auto& reg = OpRegistry::GetInstance(); | ||
| 432 | - auto tensor = MakeTensorVar("t", {16, 32}, DataType::FP16); | ||
| 433 | - auto shape = MakeShapeTuple({8, 64}); | ||
| 434 | - auto call = reg.Create("tensor.reshape", {tensor, shape}, Sp()); | ||
| 435 | - auto rt = As<TensorType>(call->GetType()); | ||
| 436 | - ASSERT_NE(rt, nullptr); | ||
| 437 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 438 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 439 | -} | ||
| 440 | - | ||
| 441 | -TEST_F(TensorOpsTransformTest, TensorReshape_IncompatibleSize_Throws) | ||
| 442 | -{ | ||
| 443 | - auto& reg = OpRegistry::GetInstance(); | ||
| 444 | - auto tensor = MakeTensorVar("t", {16, 32}, DataType::FP16); | ||
| 445 | - auto shape = MakeShapeTuple({7, 7}); | ||
| 446 | - EXPECT_THROW((void)reg.Create("tensor.reshape", {tensor, shape}, Sp()), npu::tile_fwk::Error); | ||
| 447 | -} | ||
| 448 | - | ||
| 449 | -TEST_F(TensorOpsTransformTest, TensorTranspose_SwapsAxes) | ||
| 450 | -{ | ||
| 451 | - auto& reg = OpRegistry::GetInstance(); | ||
| 452 | - auto tensor = MakeTensorVar("t", {16, 32}, DataType::FP16); | ||
| 453 | - auto axis1 = std::make_shared<ConstInt>(int64_t(0), DataType::INT64, Sp()); | ||
| 454 | - auto axis2 = std::make_shared<ConstInt>(int64_t(1), DataType::INT64, Sp()); | ||
| 455 | - auto call = reg.Create("tensor.transpose", {tensor, axis1, axis2}, Sp()); | ||
| 456 | - auto rt = As<TensorType>(call->GetType()); | ||
| 457 | - ASSERT_NE(rt, nullptr); | ||
| 458 | - EXPECT_EQ(rt->dtype_, DataType::FP16); | ||
| 459 | - EXPECT_EQ(rt->shape_.size(), 2u); | ||
| 460 | -} | ||
| 461 | - | ||
| 462 | -TEST_F(TensorOpsTransformTest, TensorTranspose_NegativeAxis) | ||
| 463 | -{ | ||
| 464 | - auto& reg = OpRegistry::GetInstance(); | ||
| 465 | - auto tensor = MakeTensorVar("t", {4, 16, 32}, DataType::FP32); | ||
| 466 | - auto axis1 = std::make_shared<ConstInt>(int64_t(0), DataType::INT64, Sp()); | ||
| 467 | - auto axis2 = std::make_shared<ConstInt>(int64_t(-1), DataType::INT64, Sp()); | ||
| 468 | - auto call = reg.Create("tensor.transpose", {tensor, axis1, axis2}, Sp()); | ||
| 469 | - auto rt = As<TensorType>(call->GetType()); | ||
| 470 | - ASSERT_NE(rt, nullptr); | ||
| 471 | - EXPECT_EQ(rt->shape_.size(), 3u); | ||
| 472 | -} | ||
| 473 | - | ||
| 474 | -TEST_F(TensorOpsTransformTest, TensorTranspose_SameAxis_Throws) | ||
| 475 | -{ | ||
| 476 | - auto& reg = OpRegistry::GetInstance(); | ||
| 477 | - auto tensor = MakeTensorVar("t", {16, 32}, DataType::FP16); | ||
| 478 | - auto axis1 = std::make_shared<ConstInt>(int64_t(0), DataType::INT64, Sp()); | ||
| 479 | - auto axis2 = std::make_shared<ConstInt>(int64_t(0), DataType::INT64, Sp()); | ||
| 480 | - EXPECT_THROW((void)reg.Create("tensor.transpose", {tensor, axis1, axis2}, Sp()), npu::tile_fwk::Error); | ||
| 481 | -} | ||
| 482 | - | ||
| 483 | -} // namespace ir | ||
| 484 | -} // namespace pypto | ||
| @@ -38,18 +38,6 @@ protected: | |||
| 38 | ExprPtr Int(int64_t value) { return std::make_shared<ConstInt>(value, DataType::INT32, Sp()); } | 38 | ExprPtr Int(int64_t value) { return std::make_shared<ConstInt>(value, DataType::INT32, Sp()); } |
| 39 | }; | 39 | }; |
| 40 | 40 | ||
| 41 | -TEST_F(OpConversionRegistryTest, TestDefaultConversionsContainRepresentativeOps) | ||
| 42 | -{ | ||
| 43 | - const std::vector<std::string> ops{ | ||
| 44 | - "tensor.add", "tensor.add_scalar", "tensor.exp", "tensor.reshape", "tensor.transpose", | ||
| 45 | - }; | ||
| 46 | - | ||
| 47 | - for (const auto& op : ops) { | ||
| 48 | - EXPECT_TRUE(Registry().HasConversion(op)) << op; | ||
| 49 | - EXPECT_NE(Registry().Lookup(op), nullptr) << op; | ||
| 50 | - } | ||
| 51 | -} | ||
| 52 | - | ||
| 53 | TEST_F(OpConversionRegistryTest, TestLookupUnknownReturnsNull) | 41 | TEST_F(OpConversionRegistryTest, TestLookupUnknownReturnsNull) |
| 54 | { | 42 | { |
| 55 | const std::string unknown = "nonexistent.op"; | 43 | const std::string unknown = "nonexistent.op"; |
| @@ -345,7 +345,13 @@ def _first_line(code: ErrorCode, module: str, origin: str, message: str) -> str: | |||
| 345 | if carries_spec_head(message): | 345 | if carries_spec_head(message): |
| 346 | return message | 346 | return message |
| 347 | head = f"[{origin}][{module}]" if origin else f"[{module}]" | 347 | head = f"[{origin}][{module}]" if origin else f"[{module}]" |
| 348 | - return f"{head}:ErrCode: F{int(code) & 0xFFFFF:05X}! Enum: {code.name}. {message}" | 348 | + masked = int(code) & 0xFFFFF |
| 349 | + # Every InternalError member sits above the low 16 bits (0x1FFFF and up); | ||
| 350 | + # every ExternalError member stays inside them. The C++ side derives the same | ||
| 351 | + # prefix from the same bits (error.cpp EnumClassName), so both sides render | ||
| 352 | + # one format. | ||
| 353 | + enum_class = "ExternalError" if masked & 0xF0000 == 0 else "InternalError" | ||
| 354 | + return f"{head}:ErrCode: F{masked:05X}! Enum: {enum_class}::{code.name}. {message}" | ||
| 349 | 355 | ||
| 350 | 356 | ||
| 351 | # Lines of context shown around a span. pypto's diagnostics show 2 and 4; the | 357 | # Lines of context shown around a span. pypto's diagnostics show 2 and 4; the |
| @@ -12,7 +12,7 @@ PyPTO IR module with tensor operations. | |||
| 12 | 12 | ||
| 13 | This module provides: | 13 | This module provides: |
| 14 | - Re-exports of all core IR types from pypto_pro.ir | 14 | - Re-exports of all core IR types from pypto_pro.ir |
| 15 | -- Organized operation namespaces (e.g., op.tensor.create) | 15 | +- Organized operation namespaces (e.g., op.block.load) |
| 16 | - IR Builder for incremental IR construction | 16 | - IR Builder for incremental IR construction |
| 17 | - Helper utilities | 17 | - Helper utilities |
| 18 | - Enhanced type constructors (e.g., TensorType with integer shape support) | 18 | - Enhanced type constructors (e.g., TensorType with integer shape support) |
| @@ -19,7 +19,6 @@ __all__ = [ | |||
| 19 | "block", | 19 | "block", |
| 20 | "debug", | 20 | "debug", |
| 21 | "system", | 21 | "system", |
| 22 | - "tensor", | ||
| 23 | "ptr", | 22 | "ptr", |
| 24 | "scalar", | 23 | "scalar", |
| 25 | "simt", | 24 | "simt", |
| @@ -32,4 +31,3 @@ from . import ptr_ops as ptr | |||
| 32 | from . import scalar_ops as scalar | 31 | from . import scalar_ops as scalar |
| 33 | from . import simt_ops as simt | 32 | from . import simt_ops as simt |
| 34 | from . import system_ops as system | 33 | from . import system_ops as system |
| 35 | -from . import tensor_ops as tensor | ||
| @@ -13,7 +13,7 @@ | |||
| 13 | 13 | ||
| 14 | Kept in ir/op/ so that ir/op/*.py can use relative imports, avoiding the | 14 | Kept in ir/op/ so that ir/op/*.py can use relative imports, avoiding the |
| 15 | circular-import cycle: | 15 | circular-import cycle: |
| 16 | - ir/op/__init__.py -> tensor_ops.py -> language/parser/op_registry.py | 16 | + ir/op/__init__.py -> block_ops.py -> language/parser/op_registry.py |
| 17 | -> language/__init__.py -> pypto_pro.ir (partially initialized) | 17 | -> language/__init__.py -> pypto_pro.ir (partially initialized) |
| 18 | """ | 18 | """ |
| 19 | 19 | ||
| @@ -1,477 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | - | ||
| 10 | -"""Tensor operations for PyPTO IR.""" | ||
| 11 | - | ||
| 12 | -from __future__ import annotations | ||
| 13 | - | ||
| 14 | -from collections.abc import Sequence | ||
| 15 | -from typing import Any | ||
| 16 | - | ||
| 17 | -from pypto.pypto_impl import ir as _ir_core | ||
| 18 | -from pypto.pypto_impl.ir import Call, ConstInt, DataType, Expr, RoundMode, ScalarType, Span | ||
| 19 | - | ||
| 20 | -from .._utils import _get_span_or_capture, _normalize_expr, _to_make_tuple | ||
| 21 | -from ._op_registry import OpSpec, register_table | ||
| 22 | - | ||
| 23 | - | ||
| 24 | -def create(shape: Sequence[int | Expr] | _ir_core.MakeTuple, dtype: DataType, span: Span | None = None) -> Call: | ||
| 25 | - """Create a new tensor with specified shape and dtype. | ||
| 26 | - | ||
| 27 | - Args: | ||
| 28 | - shape: List of dimension sizes (int or Expr), or a MakeTuple | ||
| 29 | - dtype: Data type of tensor elements | ||
| 30 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 31 | - | ||
| 32 | - Returns: | ||
| 33 | - Call expression creating a new tensor | ||
| 34 | - """ | ||
| 35 | - actual_span = _get_span_or_capture(span) | ||
| 36 | - | ||
| 37 | - shape_tuple = _to_make_tuple(shape, actual_span) | ||
| 38 | - | ||
| 39 | - args = [shape_tuple] | ||
| 40 | - kwargs: dict[str, Any] = {"dtype": dtype} | ||
| 41 | - | ||
| 42 | - return _ir_core.create_op_call("tensor.create", args, kwargs, actual_span) | ||
| 43 | - | ||
| 44 | - | ||
| 45 | -def view( | ||
| 46 | - tensor: Expr, | ||
| 47 | - shape: list[int | Expr] | _ir_core.MakeTuple, | ||
| 48 | - offset: list[int | Expr] | _ir_core.MakeTuple, | ||
| 49 | - span: Span | None = None, | ||
| 50 | -) -> Call: | ||
| 51 | - """Create a view/slice of a tensor with new shape and offset. | ||
| 52 | - | ||
| 53 | - Args: | ||
| 54 | - tensor: Input tensor expression | ||
| 55 | - shape: New shape dimensions, or a MakeTuple | ||
| 56 | - offset: Offset dimensions for the view, or a MakeTuple | ||
| 57 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 58 | - | ||
| 59 | - Returns: | ||
| 60 | - Call expression creating a tensor view | ||
| 61 | - """ | ||
| 62 | - actual_span = _get_span_or_capture(span) | ||
| 63 | - | ||
| 64 | - shape_tuple = _to_make_tuple(shape, actual_span) | ||
| 65 | - offset_tuple = _to_make_tuple(offset, actual_span) | ||
| 66 | - | ||
| 67 | - args = [tensor, shape_tuple, offset_tuple] | ||
| 68 | - return _ir_core.create_op_call("tensor.view", args, {}, actual_span) | ||
| 69 | - | ||
| 70 | - | ||
| 71 | -def matmul( | ||
| 72 | - lhs: Expr, | ||
| 73 | - rhs: Expr, | ||
| 74 | - out_dtype: int | DataType | None = None, | ||
| 75 | - a_trans: bool = False, | ||
| 76 | - b_trans: bool = False, | ||
| 77 | - c_matrix_nz: bool = False, | ||
| 78 | - span: Span | None = None, | ||
| 79 | -) -> Call: | ||
| 80 | - """Matrix multiplication with optional transpose. | ||
| 81 | - | ||
| 82 | - Args: | ||
| 83 | - lhs: Left-hand side tensor | ||
| 84 | - rhs: Right-hand side tensor | ||
| 85 | - out_dtype: Output data type (optional, inferred if not provided) | ||
| 86 | - a_trans: Whether to transpose lhs | ||
| 87 | - b_trans: Whether to transpose rhs | ||
| 88 | - c_matrix_nz: C matrix non-zero flag | ||
| 89 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 90 | - | ||
| 91 | - Returns: | ||
| 92 | - Call expression for matrix multiplication | ||
| 93 | - """ | ||
| 94 | - actual_span = _get_span_or_capture(span) | ||
| 95 | - args = [lhs, rhs] | ||
| 96 | - | ||
| 97 | - kwargs: dict[str, Any] = { | ||
| 98 | - "a_trans": a_trans, | ||
| 99 | - "b_trans": b_trans, | ||
| 100 | - "c_matrix_nz": c_matrix_nz, | ||
| 101 | - } | ||
| 102 | - if out_dtype is not None: | ||
| 103 | - kwargs["out_dtype"] = out_dtype | ||
| 104 | - | ||
| 105 | - return _ir_core.create_op_call("tensor.matmul", args, kwargs, actual_span) | ||
| 106 | - | ||
| 107 | - | ||
| 108 | -def mul(lhs: Expr, rhs: int | float | Expr, span: Span | None = None) -> Call: | ||
| 109 | - """Element-wise multiplication of tensor and tensor or scalar. | ||
| 110 | - | ||
| 111 | - Automatically selects between tensor.mul (tensor x tensor) and | ||
| 112 | - tensor.mul_scalar (tensor x scalar) based on the rhs type. | ||
| 113 | - | ||
| 114 | - Args: | ||
| 115 | - lhs: Left-hand side tensor | ||
| 116 | - rhs: Right-hand side tensor or scalar (int/float/Expr) | ||
| 117 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 118 | - | ||
| 119 | - Returns: | ||
| 120 | - Call expression for element-wise multiplication | ||
| 121 | - """ | ||
| 122 | - actual_span = _get_span_or_capture(span) | ||
| 123 | - rhs_expr = ( | ||
| 124 | - _normalize_expr(rhs, actual_span, int_dtype=DataType.FP32, float_dtype=DataType.FP32) | ||
| 125 | - if not isinstance(rhs, Expr) | ||
| 126 | - else rhs | ||
| 127 | - ) | ||
| 128 | - | ||
| 129 | - rhs_type = rhs_expr.type | ||
| 130 | - if isinstance(rhs_type, ScalarType): | ||
| 131 | - return _ir_core.create_op_call("tensor.mul_scalar", [lhs, rhs_expr], {}, actual_span) | ||
| 132 | - else: | ||
| 133 | - return _ir_core.create_op_call("tensor.mul", [lhs, rhs_expr], {}, actual_span) | ||
| 134 | - | ||
| 135 | - | ||
| 136 | -def mul_scalar(lhs: Expr, rhs: int | float | Expr, span: Span | None = None) -> Call: | ||
| 137 | - """Element-wise multiplication of tensor and scalar. | ||
| 138 | - | ||
| 139 | - Args: | ||
| 140 | - lhs: Left-hand side tensor | ||
| 141 | - rhs: Right-hand side scalar (int/float/Expr with ScalarType) | ||
| 142 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 143 | - | ||
| 144 | - Returns: | ||
| 145 | - Call expression for element-wise multiplication with scalar | ||
| 146 | - """ | ||
| 147 | - actual_span = _get_span_or_capture(span) | ||
| 148 | - rhs_expr = ( | ||
| 149 | - _normalize_expr(rhs, actual_span, int_dtype=DataType.FP32, float_dtype=DataType.FP32) | ||
| 150 | - if not isinstance(rhs, Expr) | ||
| 151 | - else rhs | ||
| 152 | - ) | ||
| 153 | - return _ir_core.create_op_call("tensor.mul_scalar", [lhs, rhs_expr], {}, actual_span) | ||
| 154 | - | ||
| 155 | - | ||
| 156 | -def add(lhs: Expr, rhs: int | float | Expr, span: Span | None = None) -> Call: | ||
| 157 | - """Element-wise addition of tensor and tensor or scalar. | ||
| 158 | - | ||
| 159 | - Automatically selects between tensor.add (tensor + tensor) and | ||
| 160 | - tensor.add_scalar (tensor + scalar) based on the rhs type. | ||
| 161 | - | ||
| 162 | - Args: | ||
| 163 | - lhs: Left-hand side tensor | ||
| 164 | - rhs: Right-hand side tensor or scalar (int/float/Expr) | ||
| 165 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 166 | - | ||
| 167 | - Returns: | ||
| 168 | - Call expression for element-wise addition | ||
| 169 | - """ | ||
| 170 | - actual_span = _get_span_or_capture(span) | ||
| 171 | - rhs_expr = ( | ||
| 172 | - _normalize_expr(rhs, actual_span, int_dtype=DataType.FP32, float_dtype=DataType.FP32) | ||
| 173 | - if not isinstance(rhs, Expr) | ||
| 174 | - else rhs | ||
| 175 | - ) | ||
| 176 | - | ||
| 177 | - rhs_type = rhs_expr.type | ||
| 178 | - if isinstance(rhs_type, ScalarType): | ||
| 179 | - return _ir_core.create_op_call("tensor.add_scalar", [lhs, rhs_expr], {}, actual_span) | ||
| 180 | - else: | ||
| 181 | - return _ir_core.create_op_call("tensor.add", [lhs, rhs_expr], {}, actual_span) | ||
| 182 | - | ||
| 183 | - | ||
| 184 | -def add_scalar(lhs: Expr, rhs: int | float | Expr, span: Span | None = None) -> Call: | ||
| 185 | - """Element-wise addition of tensor and scalar. | ||
| 186 | - | ||
| 187 | - Args: | ||
| 188 | - lhs: Left-hand side tensor | ||
| 189 | - rhs: Right-hand side scalar (int/float/Expr with ScalarType) | ||
| 190 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 191 | - | ||
| 192 | - Returns: | ||
| 193 | - Call expression for element-wise addition with scalar | ||
| 194 | - """ | ||
| 195 | - actual_span = _get_span_or_capture(span) | ||
| 196 | - rhs_expr = ( | ||
| 197 | - _normalize_expr(rhs, actual_span, int_dtype=DataType.FP32, float_dtype=DataType.FP32) | ||
| 198 | - if not isinstance(rhs, Expr) | ||
| 199 | - else rhs | ||
| 200 | - ) | ||
| 201 | - return _ir_core.create_op_call("tensor.add_scalar", [lhs, rhs_expr], {}, actual_span) | ||
| 202 | - | ||
| 203 | - | ||
| 204 | -def sub(lhs: Expr, rhs: int | float | Expr, span: Span | None = None) -> Call: | ||
| 205 | - """Element-wise subtraction of tensor and tensor or scalar. | ||
| 206 | - | ||
| 207 | - Automatically selects between tensor.sub (tensor - tensor) and | ||
| 208 | - tensor.sub_scalar (tensor - scalar) based on the rhs type. | ||
| 209 | - | ||
| 210 | - Args: | ||
| 211 | - lhs: Left-hand side tensor | ||
| 212 | - rhs: Right-hand side tensor or scalar (int/float/Expr) | ||
| 213 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 214 | - | ||
| 215 | - Returns: | ||
| 216 | - Call expression for element-wise subtraction | ||
| 217 | - """ | ||
| 218 | - actual_span = _get_span_or_capture(span) | ||
| 219 | - rhs_expr = ( | ||
| 220 | - _normalize_expr(rhs, actual_span, int_dtype=DataType.FP32, float_dtype=DataType.FP32) | ||
| 221 | - if not isinstance(rhs, Expr) | ||
| 222 | - else rhs | ||
| 223 | - ) | ||
| 224 | - | ||
| 225 | - rhs_type = rhs_expr.type | ||
| 226 | - if isinstance(rhs_type, ScalarType): | ||
| 227 | - return _ir_core.create_op_call("tensor.sub_scalar", [lhs, rhs_expr], {}, actual_span) | ||
| 228 | - else: | ||
| 229 | - return _ir_core.create_op_call("tensor.sub", [lhs, rhs_expr], {}, actual_span) | ||
| 230 | - | ||
| 231 | - | ||
| 232 | -def sub_scalar(lhs: Expr, rhs: int | float | Expr, span: Span | None = None) -> Call: | ||
| 233 | - """Element-wise subtraction of tensor and scalar. | ||
| 234 | - | ||
| 235 | - Args: | ||
| 236 | - lhs: Left-hand side tensor | ||
| 237 | - rhs: Right-hand side scalar (int/float/Expr with ScalarType) | ||
| 238 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 239 | - | ||
| 240 | - Returns: | ||
| 241 | - Call expression for element-wise subtraction with scalar | ||
| 242 | - """ | ||
| 243 | - actual_span = _get_span_or_capture(span) | ||
| 244 | - rhs_expr = ( | ||
| 245 | - _normalize_expr(rhs, actual_span, int_dtype=DataType.FP32, float_dtype=DataType.FP32) | ||
| 246 | - if not isinstance(rhs, Expr) | ||
| 247 | - else rhs | ||
| 248 | - ) | ||
| 249 | - return _ir_core.create_op_call("tensor.sub_scalar", [lhs, rhs_expr], {}, actual_span) | ||
| 250 | - | ||
| 251 | - | ||
| 252 | -def div(lhs: Expr, rhs: int | float | Expr, span: Span | None = None) -> Call: | ||
| 253 | - """Element-wise division of tensor and tensor or scalar. | ||
| 254 | - | ||
| 255 | - Automatically selects between tensor.div (tensor / tensor) and | ||
| 256 | - tensor.div_scalar (tensor / scalar) based on the rhs type. | ||
| 257 | - | ||
| 258 | - Args: | ||
| 259 | - lhs: Left-hand side tensor | ||
| 260 | - rhs: Right-hand side tensor or scalar (int/float/Expr) | ||
| 261 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 262 | - | ||
| 263 | - Returns: | ||
| 264 | - Call expression for element-wise division | ||
| 265 | - """ | ||
| 266 | - actual_span = _get_span_or_capture(span) | ||
| 267 | - rhs_expr = ( | ||
| 268 | - _normalize_expr(rhs, actual_span, int_dtype=DataType.FP32, float_dtype=DataType.FP32) | ||
| 269 | - if not isinstance(rhs, Expr) | ||
| 270 | - else rhs | ||
| 271 | - ) | ||
| 272 | - | ||
| 273 | - rhs_type = rhs_expr.type | ||
| 274 | - if isinstance(rhs_type, ScalarType): | ||
| 275 | - return _ir_core.create_op_call("tensor.div_scalar", [lhs, rhs_expr], {}, actual_span) | ||
| 276 | - else: | ||
| 277 | - return _ir_core.create_op_call("tensor.div", [lhs, rhs_expr], {}, actual_span) | ||
| 278 | - | ||
| 279 | - | ||
| 280 | -def div_scalar(lhs: Expr, rhs: int | float | Expr, span: Span | None = None) -> Call: | ||
| 281 | - """Element-wise division of tensor and scalar. | ||
| 282 | - | ||
| 283 | - Args: | ||
| 284 | - lhs: Left-hand side tensor | ||
| 285 | - rhs: Right-hand side scalar (int/float/Expr with ScalarType) | ||
| 286 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 287 | - | ||
| 288 | - Returns: | ||
| 289 | - Call expression for element-wise division with scalar | ||
| 290 | - """ | ||
| 291 | - actual_span = _get_span_or_capture(span) | ||
| 292 | - rhs_expr = ( | ||
| 293 | - _normalize_expr(rhs, actual_span, int_dtype=DataType.FP32, float_dtype=DataType.FP32) | ||
| 294 | - if not isinstance(rhs, Expr) | ||
| 295 | - else rhs | ||
| 296 | - ) | ||
| 297 | - return _ir_core.create_op_call("tensor.div_scalar", [lhs, rhs_expr], {}, actual_span) | ||
| 298 | - | ||
| 299 | - | ||
| 300 | -def maximum(lhs: Expr, rhs: Expr, span: Span | None = None) -> Call: | ||
| 301 | - """Element-wise maximum of two tensors. | ||
| 302 | - | ||
| 303 | - Args: | ||
| 304 | - lhs: Left-hand side tensor | ||
| 305 | - rhs: Right-hand side tensor | ||
| 306 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 307 | - | ||
| 308 | - Returns: | ||
| 309 | - Call expression for element-wise maximum | ||
| 310 | - """ | ||
| 311 | - actual_span = _get_span_or_capture(span) | ||
| 312 | - return _ir_core.create_op_call("tensor.maximum", [lhs, rhs], {}, actual_span) | ||
| 313 | - | ||
| 314 | - | ||
| 315 | -def row_max(inp: Expr, span: Span | None = None) -> Call: | ||
| 316 | - """Row-wise max reduction (reduces along last axis, keeps dim). | ||
| 317 | - | ||
| 318 | - Args: | ||
| 319 | - inp: Input tensor | ||
| 320 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 321 | - | ||
| 322 | - Returns: | ||
| 323 | - Call expression for row-wise max reduction | ||
| 324 | - """ | ||
| 325 | - actual_span = _get_span_or_capture(span) | ||
| 326 | - return _ir_core.create_op_call("tensor.row_max", [inp], {}, actual_span) | ||
| 327 | - | ||
| 328 | - | ||
| 329 | -def row_sum(inp: Expr, span: Span | None = None) -> Call: | ||
| 330 | - """Row-wise sum reduction (reduces along last axis, keeps dim). | ||
| 331 | - | ||
| 332 | - Args: | ||
| 333 | - inp: Input tensor | ||
| 334 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 335 | - | ||
| 336 | - Returns: | ||
| 337 | - Call expression for row-wise sum reduction | ||
| 338 | - """ | ||
| 339 | - actual_span = _get_span_or_capture(span) | ||
| 340 | - return _ir_core.create_op_call("tensor.row_sum", [inp], {}, actual_span) | ||
| 341 | - | ||
| 342 | - | ||
| 343 | -def exp(inp: Expr, span: Span | None = None) -> Call: | ||
| 344 | - """Element-wise exponential operation. | ||
| 345 | - | ||
| 346 | - Args: | ||
| 347 | - inp: Input tensor | ||
| 348 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 349 | - | ||
| 350 | - Returns: | ||
| 351 | - Call expression for element-wise exponential | ||
| 352 | - """ | ||
| 353 | - actual_span = _get_span_or_capture(span) | ||
| 354 | - return _ir_core.create_op_call("tensor.exp", [inp], {}, actual_span) | ||
| 355 | - | ||
| 356 | - | ||
| 357 | -def cast( | ||
| 358 | - inp: Expr, | ||
| 359 | - target_type: int | DataType, | ||
| 360 | - mode: RoundMode = RoundMode.CAST_ROUND, | ||
| 361 | - span: Span | None = None, | ||
| 362 | -) -> Call: | ||
| 363 | - """Type casting operation. | ||
| 364 | - | ||
| 365 | - Args: | ||
| 366 | - inp: Input tensor | ||
| 367 | - target_type: Target data type | ||
| 368 | - mode: Rounding mode — ``pl.RoundMode.CAST_NONE``, ``pl.RoundMode.CAST_RINT``, | ||
| 369 | - ``pl.RoundMode.CAST_ROUND``, ``pl.RoundMode.CAST_FLOOR``, ``pl.RoundMode.CAST_CEIL``, | ||
| 370 | - ``pl.RoundMode.CAST_TRUNC``, ``pl.RoundMode.CAST_ODD`` | ||
| 371 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 372 | - | ||
| 373 | - Returns: | ||
| 374 | - Call expression for type casting | ||
| 375 | - """ | ||
| 376 | - actual_span = _get_span_or_capture(span) | ||
| 377 | - | ||
| 378 | - args = [inp] | ||
| 379 | - kwargs: dict[str, Any] = { | ||
| 380 | - "target_type": target_type, | ||
| 381 | - "mode": mode, | ||
| 382 | - } | ||
| 383 | - | ||
| 384 | - return _ir_core.create_op_call("tensor.cast", args, kwargs, actual_span) | ||
| 385 | - | ||
| 386 | - | ||
| 387 | -def assemble( | ||
| 388 | - target: Expr, source: Expr, offset: list[int | Expr] | _ir_core.MakeTuple, span: Span | None = None | ||
| 389 | -) -> Call: | ||
| 390 | - """Write/update tensor values at specified offset. | ||
| 391 | - | ||
| 392 | - Args: | ||
| 393 | - target: Target tensor to update | ||
| 394 | - source: Source tensor to write | ||
| 395 | - offset: Offset dimensions for where to write, or a MakeTuple | ||
| 396 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 397 | - | ||
| 398 | - Returns: | ||
| 399 | - Call expression for tensor assembly | ||
| 400 | - """ | ||
| 401 | - actual_span = _get_span_or_capture(span) | ||
| 402 | - | ||
| 403 | - offset_tuple = _to_make_tuple(offset, actual_span) | ||
| 404 | - | ||
| 405 | - args = [target, source, offset_tuple] | ||
| 406 | - return _ir_core.create_op_call("tensor.assemble", args, {}, actual_span) | ||
| 407 | - | ||
| 408 | - | ||
| 409 | -def reshape(tensor: Expr, shape: list[int | Expr] | _ir_core.MakeTuple, span: Span | None = None) -> Call: | ||
| 410 | - """Reshape tensor to new shape. | ||
| 411 | - | ||
| 412 | - Args: | ||
| 413 | - tensor: Input tensor expression | ||
| 414 | - shape: New shape dimensions, or a MakeTuple | ||
| 415 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 416 | - | ||
| 417 | - Returns: | ||
| 418 | - Call expression for tensor reshape | ||
| 419 | - """ | ||
| 420 | - actual_span = _get_span_or_capture(span) | ||
| 421 | - | ||
| 422 | - shape_tuple = _to_make_tuple(shape, actual_span) | ||
| 423 | - | ||
| 424 | - args = [tensor, shape_tuple] | ||
| 425 | - return _ir_core.create_op_call("tensor.reshape", args, {}, actual_span) | ||
| 426 | - | ||
| 427 | - | ||
| 428 | -def transpose(tensor: Expr, axis1: int, axis2: int, span: Span | None = None) -> Call: | ||
| 429 | - """Transpose tensor by swapping two axes. | ||
| 430 | - | ||
| 431 | - Args: | ||
| 432 | - tensor: Input tensor expression | ||
| 433 | - axis1: First axis to swap (supports negative indexing) | ||
| 434 | - axis2: Second axis to swap (supports negative indexing) | ||
| 435 | - span: Optional source span for debugging (auto-captured if not provided) | ||
| 436 | - | ||
| 437 | - Returns: | ||
| 438 | - Call expression for tensor transpose | ||
| 439 | - """ | ||
| 440 | - actual_span = _get_span_or_capture(span) | ||
| 441 | - axis1_expr = ConstInt(axis1, DataType.INT64, actual_span) | ||
| 442 | - axis2_expr = ConstInt(axis2, DataType.INT64, actual_span) | ||
| 443 | - | ||
| 444 | - args = [tensor, axis1_expr, axis2_expr] | ||
| 445 | - | ||
| 446 | - return _ir_core.create_op_call("tensor.transpose", args, {}, actual_span) | ||
| 447 | - | ||
| 448 | - | ||
| 449 | -# --------------------------------------------------------------------------- | ||
| 450 | -# Declarative op registration | ||
| 451 | -# --------------------------------------------------------------------------- | ||
| 452 | - | ||
| 453 | -register_table( | ||
| 454 | - { | ||
| 455 | - # args + kwargs -> builder | ||
| 456 | - "tensor.cast": OpSpec(builder=cast), | ||
| 457 | - "tensor.create_tensor": OpSpec(builder=create), | ||
| 458 | - "tensor.view": OpSpec(builder=view), | ||
| 459 | - "tensor.assemble": OpSpec(builder=assemble), | ||
| 460 | - "tensor.reshape": OpSpec(builder=reshape), | ||
| 461 | - "tensor.transpose": OpSpec(builder=transpose), | ||
| 462 | - "tensor.matmul": OpSpec(builder=matmul), | ||
| 463 | - # fixed positional args, no kwargs | ||
| 464 | - "tensor.add": OpSpec(builder=add, parse_kwargs=False), | ||
| 465 | - "tensor.add_scalar": OpSpec(builder=add_scalar, parse_kwargs=False), | ||
| 466 | - "tensor.mul": OpSpec(builder=mul, parse_kwargs=False), | ||
| 467 | - "tensor.mul_scalar": OpSpec(builder=mul_scalar, parse_kwargs=False), | ||
| 468 | - "tensor.sub": OpSpec(builder=sub, parse_kwargs=False), | ||
| 469 | - "tensor.sub_scalar": OpSpec(builder=sub_scalar, parse_kwargs=False), | ||
| 470 | - "tensor.div": OpSpec(builder=div, parse_kwargs=False), | ||
| 471 | - "tensor.div_scalar": OpSpec(builder=div_scalar, parse_kwargs=False), | ||
| 472 | - "tensor.maximum": OpSpec(builder=maximum, parse_kwargs=False), | ||
| 473 | - "tensor.row_max": OpSpec(builder=row_max, parse_kwargs=False), | ||
| 474 | - "tensor.row_sum": OpSpec(builder=row_sum, parse_kwargs=False), | ||
| 475 | - "tensor.exp": OpSpec(builder=exp, parse_kwargs=False), | ||
| 476 | - } | ||
| 477 | -) | ||
| @@ -63,7 +63,7 @@ def register_op_conversion(from_op: str, to_op: str) -> None: | |||
| 63 | """Register a simple op name mapping. | 63 | """Register a simple op name mapping. |
| 64 | 64 | ||
| 65 | Args: | 65 | Args: |
| 66 | - from_op: Source op name (e.g., 'tensor.add') | 66 | + from_op: Source op name (e.g., 'block.add') |
| 67 | to_op: Target op name (e.g., 'block.add') | 67 | to_op: Target op name (e.g., 'block.add') |
| 68 | """ | 68 | """ |
| 69 | _register_simple(from_op, to_op) | 69 | _register_simple(from_op, to_op) |
| @@ -82,7 +82,7 @@ def op_conversion(from_op: str) -> Callable: | |||
| 82 | 82 | ||
| 83 | Example:: | 83 | Example:: |
| 84 | 84 | ||
| 85 | - @op_conversion("tensor.add") | 85 | + @op_conversion("block.adds") |
| 86 | def convert_add(ctx, args, kwargs, span): | 86 | def convert_add(ctx, args, kwargs, span): |
| 87 | return ir.create_op_call("block.add", args, kwargs, span) | 87 | return ir.create_op_call("block.add", args, kwargs, span) |
| 88 | """ | 88 | """ |
| @@ -1043,7 +1043,7 @@ class CallParserMixin: | |||
| 1043 | ) | 1043 | ) |
| 1044 | 1044 | ||
| 1045 | def parse_op_call(self, call: ast.Call) -> Any: | 1045 | def parse_op_call(self, call: ast.Call) -> Any: |
| 1046 | - """Parse operation call like pl.tensor.create_tensor() or pl.add(). | 1046 | + """Parse operation call like pl.add() or pl.simt.abs(). |
| 1047 | 1047 | ||
| 1048 | Args: | 1048 | Args: |
| 1049 | call: Call AST node | 1049 | call: Call AST node |
| @@ -1068,7 +1068,7 @@ class CallParserMixin: | |||
| 1068 | raise NotSupported( | 1068 | raise NotSupported( |
| 1069 | f"Unsupported operation call: {ast.unparse(call)}", | 1069 | f"Unsupported operation call: {ast.unparse(call)}", |
| 1070 | span=span, | 1070 | span=span, |
| 1071 | - hint="Use pl.*, pl.tensor.*, or pl.system.* operations", | 1071 | + hint="Use pl.*, pl.simt.*, or pl.system.* operations", |
| 1072 | parser_retry=True, | 1072 | parser_retry=True, |
| 1073 | ) | 1073 | ) |
| 1074 | 1074 | ||
| @@ -36,7 +36,7 @@ class Tensor: | |||
| 36 | y: pl.Tensor[[64, 128], pl.DT_FP16, pl.NZ] | 36 | y: pl.Tensor[[64, 128], pl.DT_FP16, pl.NZ] |
| 37 | 37 | ||
| 38 | Runtime mode (wraps IR expressions): | 38 | Runtime mode (wraps IR expressions): |
| 39 | - tensor = pl.tensor.create_tensor([64, 128], dtype=pl.DT_FP32) | 39 | + tensor = pl.make_tensor(src, [64, 128], [128, 1], dtype=pl.DT_FP32) |
| 40 | # Returns Tensor wrapping the Call expression | 40 | # Returns Tensor wrapping the Call expression |
| 41 | 41 | ||
| 42 | Examples: | 42 | Examples: |
| @@ -309,7 +309,7 @@ def build_graph(info, schedule: list) -> SyncGraph: | |||
| 309 | # One gate for every check that needs the graph (see _validate), run here so the checks | 309 | # One gate for every check that needs the graph (see _validate), run here so the checks |
| 310 | # see exactly what the emission will. The cycle walk is graph work and is done here; the | 310 | # see exactly what the emission will. The cycle walk is graph work and is done here; the |
| 311 | # verdict on what a cycle's total distance means is a check. | 311 | # verdict on what a cycle's total distance means is a check. |
| 312 | - validate_sync(graph, info, find_cycles(graph)) | 312 | + validate_sync(graph, info, find_cycles(graph), schedule) |
| 313 | return graph | 313 | return graph |
| 314 | 314 | ||
| 315 | 315 | ||
| @@ -72,21 +72,60 @@ def validate_kernel_buffers(sync, used: set) -> None: | |||
| 72 | ) | 72 | ) |
| 73 | 73 | ||
| 74 | 74 | ||
| 75 | -def validate_sync(graph, info, cycles) -> None: | 75 | +def validate_sync(graph, info, cycles, schedule) -> None: |
| 76 | """Checks that need the sync graph: regions, op-level accesses, users, edges. | 76 | """Checks that need the sync graph: regions, op-level accesses, users, edges. |
| 77 | 77 | ||
| 78 | Called from _sync_graph once the graph is built. ``cycles`` is what ``find_cycles(graph)`` | 78 | Called from _sync_graph once the graph is built. ``cycles`` is what ``find_cycles(graph)`` |
| 79 | returned, passed in because walking the graph is the graph's job while deciding what a | 79 | returned, passed in because walking the graph is the graph's job while deciding what a |
| 80 | cycle's total distance MEANS is a check. | 80 | cycle's total distance MEANS is a check. |
| 81 | + | ||
| 82 | + ``_check_slot_counts`` runs before the two edge checks on purpose: too few tiles shows up | ||
| 83 | + there as an unstable distance or a non-positive cycle, and those messages describe the | ||
| 84 | + symptom rather than the tile count that caused it. | ||
| 81 | """ | 85 | """ |
| 82 | users = buffer_users(graph) | 86 | users = buffer_users(graph) |
| 83 | _check_cross_core_users(info, users) | 87 | _check_cross_core_users(info, users) |
| 84 | _check_event_id_counts(graph, info) | 88 | _check_event_id_counts(graph, info) |
| 85 | _check_reuse_mutex_ids(graph, info) | 89 | _check_reuse_mutex_ids(graph, info) |
| 90 | + _check_slot_counts(graph, info, users, schedule) | ||
| 86 | _check_stable_distances(graph) | 91 | _check_stable_distances(graph) |
| 87 | _check_no_deadlock_cycle(cycles) | 92 | _check_no_deadlock_cycle(cycles) |
| 88 | 93 | ||
| 89 | 94 | ||
| 95 | +def _check_slot_counts(graph, info, users: dict, schedule: list) -> None: | ||
| 96 | + """A cross-core buffer needs one tile per beat its two stages sit apart, plus one. | ||
| 97 | + | ||
| 98 | + While the producer works on task t its consumer is still on task ``t - dist``, so tasks | ||
| 99 | + ``t - dist .. t`` are all live at once: the one being written, the one being read, and | ||
| 100 | + every one in between that is written but not yet read. One tile short and the producer | ||
| 101 | + lands on the tile the consumer is reading. | ||
| 102 | + | ||
| 103 | + ``dist`` is read from the schedule rather than from the graph's edges: once the tiles run | ||
| 104 | + out the edges themselves are distorted (the producer laps the consumer, and the lane scan | ||
| 105 | + then pairs a read with a write from a later task), so the edge no longer states the | ||
| 106 | + distance the schedule asked for. | ||
| 107 | + """ | ||
| 108 | + for buf_name, buf in info.sync.buffers.items(): | ||
| 109 | + if buf.fwd_ids_node is None and buf.bwd_ids_node is None: | ||
| 110 | + continue # not a cross-core buffer: a local group's rotation is the user's own | ||
| 111 | + region = graph.regions.get(buf_name) | ||
| 112 | + entries = users.get(buf_name, []) | ||
| 113 | + if region is None or len(entries) != 2: | ||
| 114 | + continue # unused here, or already reported by _check_cross_core_users | ||
| 115 | + producer, consumer = entries[0], entries[1] | ||
| 116 | + needed = schedule[consumer[0]] - schedule[producer[0]] + 1 | ||
| 117 | + have = graph.slots[region] | ||
| 118 | + if have >= needed: | ||
| 119 | + continue | ||
| 120 | + raise InvalidArgument( | ||
| 121 | + f"pipeline: cross-core buffer '{buf_name}' has {have} tile(s), but at this " | ||
| 122 | + f"preload its producer '{producer[1]}' runs {needed - 1} iteration(s) ahead of " | ||
| 123 | + f"its consumer '{consumer[1]}', so {needed} tiles are live at once. Give it " | ||
| 124 | + f"{needed} tiles (the length of mutex_ids, and of fwd_ids/bwd_ids unless those " | ||
| 125 | + f"are a single shared id), or lower `preload`." | ||
| 126 | + ) | ||
| 127 | + | ||
| 128 | + | ||
| 90 | def _check_stable_distances(graph) -> None: | 129 | def _check_stable_distances(graph) -> None: |
| 91 | """Every edge must sit at the same distance on every task. | 130 | """Every edge must sit at the same distance on every task. |
| 92 | 131 | ||
| @@ -158,6 +197,9 @@ def _check_cross_core_users(info, users: dict) -> None: | |||
| 158 | and the hardware faults once an id is set more than 15 times unmatched. | 197 | and the hardware faults once an id is set more than 15 times unmatched. |
| 159 | A handover reaching across two loops has this shape and is not supported. | 198 | A handover reaching across two loops has this shape and is not supported. |
| 160 | same core both users on cube, or both on vector — no core boundary is crossed. | 199 | same core both users on cube, or both on vector — no core boundary is crossed. |
| 200 | + not adjacent the two stages have others between them. The handover then has to | ||
| 201 | + survive those stages' whole span, which costs one more tile per stage | ||
| 202 | + crossed and is not a shape any kernel needs. | ||
| 161 | 3+ users one variable standing in for several producer/consumer pairs IN ONE LOOP. | 203 | 3+ users one variable standing in for several producer/consumer pairs IN ONE LOOP. |
| 162 | Ids are resolved per buffer, so two pairs would share one id group and | 204 | Ids are resolved per buffer, so two pairs would share one id group and |
| 163 | their differently-skewed edges would interleave. Declare a separate | 205 | their differently-skewed edges would interleave. Declare a separate |
| @@ -192,6 +234,16 @@ def _check_cross_core_users(info, users: dict) -> None: | |||
| 192 | f"'{sections.pop()}' stages {names}. Cross-core sync orders work across the " | 234 | f"'{sections.pop()}' stages {names}. Cross-core sync orders work across the " |
| 193 | f"cube/vector boundary; same-core ordering comes from auto_mutex instead." | 235 | f"cube/vector boundary; same-core ordering comes from auto_mutex instead." |
| 194 | ) | 236 | ) |
| 237 | + producer, consumer = entries[0], entries[1] | ||
| 238 | + if consumer[0] != producer[0] + 1: | ||
| 239 | + between = consumer[0] - producer[0] - 1 | ||
| 240 | + raise InvalidOperation( | ||
| 241 | + f"pipeline: cross-core buffer '{buf_name}' is handed from stage " | ||
| 242 | + f"'{producer[1]}' to stage '{consumer[1]}', with {between} stage(s) in " | ||
| 243 | + f"between. A cross-core buffer must be handed to the stage that follows " | ||
| 244 | + f"its producer directly. Hand the data over through the stages in between, " | ||
| 245 | + f"or move the two stages next to each other." | ||
| 246 | + ) | ||
| 195 | 247 | ||
| 196 | 248 | ||
| 197 | def _check_event_id_counts(graph, info) -> None: | 249 | def _check_event_id_counts(graph, info) -> None: |
| @@ -22,7 +22,7 @@ def _tensor_var(name: str, dtype=DataType.FP16): | |||
| 22 | 22 | ||
| 23 | @pytest.mark.parametrize( | 23 | @pytest.mark.parametrize( |
| 24 | "op_name", | 24 | "op_name", |
| 25 | - ["tensor.add", "tensor.matmul", "tensor.cast", "tensor.row_max", "block.load", "block.store"], | 25 | + ["block.add", "block.cast", "block.move", "block.quant", "block.load", "block.store"], |
| 26 | ) | 26 | ) |
| 27 | def test_block_visible_ops_are_registered(op_name): | 27 | def test_block_visible_ops_are_registered(op_name): |
| 28 | assert ir.is_op_registered(op_name) | 28 | assert ir.is_op_registered(op_name) |
| @@ -32,10 +32,10 @@ def test_block_visible_ops_are_registered(op_name): | |||
| 32 | @pytest.mark.parametrize( | 32 | @pytest.mark.parametrize( |
| 33 | "op_name, attrs", | 33 | "op_name, attrs", |
| 34 | [ | 34 | [ |
| 35 | - ("tensor.matmul", {"out_dtype", "a_trans", "b_trans", "c_matrix_nz"}), | 35 | + ("block.cast", {"target_type", "mode"}), |
| 36 | - ("tensor.cast", {"target_type", "mode"}), | 36 | + ("block.load", {"is_transpose", "tile_dims"}), |
| 37 | - ("tensor.row_max", {"axis", "keep_dim"}), | 37 | + ("block.store", {"atomic", "phase", "relu_pre_mode"}), |
| 38 | - ("tensor.row_sum", {"axis", "keep_dim"}), | 38 | + ("block.move", {"acc_to_vec_mode", "phase", "relu_pre_mode"}), |
| 39 | ], | 39 | ], |
| 40 | ) | 40 | ) |
| 41 | def test_block_op_kwarg_schema_is_exposed(op_name, attrs): | 41 | def test_block_op_kwarg_schema_is_exposed(op_name, attrs): |
| @@ -46,13 +46,15 @@ def test_block_op_kwarg_schema_is_exposed(op_name, attrs): | |||
| 46 | 46 | ||
| 47 | 47 | ||
| 48 | def test_create_op_call_accepts_registered_kwargs(): | 48 | def test_create_op_call_accepts_registered_kwargs(): |
| 49 | - lhs = _tensor_var("lhs") | 49 | + src = _tensor_var("src") |
| 50 | - rhs = _tensor_var("rhs") | 50 | + span = ir.Span.unknown() |
| 51 | + shape = ir.MakeTuple([ir.ConstInt(64, DataType.INDEX, span)], span) | ||
| 52 | + stride = ir.MakeTuple([ir.ConstInt(1, DataType.INDEX, span)], span) | ||
| 51 | call = ir.create_op_call( | 53 | call = ir.create_op_call( |
| 52 | - "tensor.matmul", | 54 | + "ptr.make_tensor", |
| 53 | - [lhs, rhs], | 55 | + [src, shape, stride], |
| 54 | - {"out_dtype": DataType.FP32, "a_trans": False, "b_trans": False}, | 56 | + {"dtype": DataType.FP32}, |
| 55 | - ir.Span.unknown(), | 57 | + span, |
| 56 | ) | 58 | ) |
| 57 | 59 | ||
| 58 | assert isinstance(call.type, ir.TensorType) | 60 | assert isinstance(call.type, ir.TensorType) |
| @@ -63,15 +65,17 @@ def test_create_op_call_accepts_registered_kwargs(): | |||
| 63 | "kwargs", | 65 | "kwargs", |
| 64 | [ | 66 | [ |
| 65 | {"unknown_param": 123}, | 67 | {"unknown_param": 123}, |
| 66 | - {"a_trans": "true"}, | 68 | + {"atomic": "true"}, |
| 67 | ], | 69 | ], |
| 68 | ) | 70 | ) |
| 69 | def test_create_op_call_rejects_invalid_kwargs(kwargs): | 71 | def test_create_op_call_rejects_invalid_kwargs(kwargs): |
| 70 | - lhs = _tensor_var("lhs") | 72 | + dst = _tensor_var("dst") |
| 71 | - rhs = _tensor_var("rhs") | 73 | + src = _tensor_var("src") |
| 74 | + span = ir.Span.unknown() | ||
| 75 | + offsets = ir.MakeTuple([ir.ConstInt(0, DataType.INDEX, span)], span) | ||
| 72 | 76 | ||
| 73 | with pytest.raises(Exception): | 77 | with pytest.raises(Exception): |
| 74 | - ir.create_op_call("tensor.matmul", [lhs, rhs], kwargs, ir.Span.unknown()) | 78 | + ir.create_op_call("block.store", [dst, src, offsets], kwargs, span) |
| 75 | 79 | ||
| 76 | 80 | ||
| 77 | # =================================================================== | 81 | # =================================================================== |
| @@ -1,144 +0,0 @@ | |||
| 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 | -"""Block-facing smoke tests for pypto_pro.ir.op.tensor helpers.""" | ||
| 12 | - | ||
| 13 | -from pypto_pro import DataType, ir | ||
| 14 | -import pytest | ||
| 15 | - | ||
| 16 | - | ||
| 17 | -def _tensor_var(name: str, shape=None, dtype=DataType.FP32): | ||
| 18 | - span = ir.Span.unknown() | ||
| 19 | - dims = [ir.ConstInt(dim, DataType.INDEX, span) for dim in (shape or [64, 128])] | ||
| 20 | - return ir.Var(name, ir.TensorType(dims, dtype), span) | ||
| 21 | - | ||
| 22 | - | ||
| 23 | -@pytest.mark.parametrize( | ||
| 24 | - "factory, expected_name", | ||
| 25 | - [ | ||
| 26 | - (lambda:ir.op.tensor.create([4, 8], DataType.FP32), "tensor.create"), | ||
| 27 | - (lambda:ir.op.tensor.view(_tensor_var("t"), [8, 16], [0, 0]), "tensor.view"), | ||
| 28 | - (lambda:ir.op.tensor.assemble(_tensor_var("dst"), _tensor_var("src"), [0, 0]), "tensor.assemble"), | ||
| 29 | - ], | ||
| 30 | -) | ||
| 31 | -def test_tensor_memory_helpers_create_calls(factory, expected_name): | ||
| 32 | - call = factory() | ||
| 33 | - | ||
| 34 | - assert isinstance(call, ir.Call) | ||
| 35 | - assert call.name == expected_name | ||
| 36 | - assert isinstance(call.type, ir.TensorType) | ||
| 37 | - | ||
| 38 | - | ||
| 39 | -@pytest.mark.parametrize( | ||
| 40 | - "factory, expected_name", | ||
| 41 | - [ | ||
| 42 | - (lambda x, y:ir.op.tensor.add(x, y), "tensor.add"), | ||
| 43 | - (lambda x, y:ir.op.tensor.sub(x, y), "tensor.sub"), | ||
| 44 | - (lambda x, y:ir.op.tensor.mul(x, y), "tensor.mul"), | ||
| 45 | - (lambda x, y:ir.op.tensor.div(x, y), "tensor.div"), | ||
| 46 | - (lambda x, y:ir.op.tensor.maximum(x, y), "tensor.maximum"), | ||
| 47 | - ], | ||
| 48 | -) | ||
| 49 | -def test_tensor_binary_helpers_create_calls(factory, expected_name): | ||
| 50 | - x = _tensor_var("x") | ||
| 51 | - y = _tensor_var("y") | ||
| 52 | - call = factory(x, y) | ||
| 53 | - | ||
| 54 | - assert isinstance(call, ir.Call) | ||
| 55 | - assert call.name == expected_name | ||
| 56 | - assert isinstance(call.type, ir.TensorType) | ||
| 57 | - | ||
| 58 | - | ||
| 59 | -@pytest.mark.parametrize( | ||
| 60 | - "factory, expected_name", | ||
| 61 | - [ | ||
| 62 | - (lambda x:ir.op.tensor.exp(x), "tensor.exp"), | ||
| 63 | - (lambda x:ir.op.tensor.cast(x, DataType.FP32), "tensor.cast"), | ||
| 64 | - (lambda x:ir.op.tensor.row_max(x), "tensor.row_max"), | ||
| 65 | - (lambda x:ir.op.tensor.row_sum(x), "tensor.row_sum"), | ||
| 66 | - ], | ||
| 67 | -) | ||
| 68 | -def test_tensor_unary_and_reduction_helpers_create_calls(factory, expected_name): | ||
| 69 | - x = _tensor_var("x", dtype=DataType.FP16) | ||
| 70 | - call = factory(x) | ||
| 71 | - | ||
| 72 | - assert isinstance(call, ir.Call) | ||
| 73 | - assert call.name == expected_name | ||
| 74 | - assert isinstance(call.type, ir.TensorType) | ||
| 75 | - | ||
| 76 | - | ||
| 77 | -@pytest.mark.parametrize( | ||
| 78 | - "factory, expected_name", | ||
| 79 | - [ | ||
| 80 | - (lambda x:ir.op.tensor.reshape(x, [32]), "tensor.reshape"), | ||
| 81 | - ( | ||
| 82 | - lambda x:ir.op.tensor.reshape( | ||
| 83 | - x, [ir.Var('n', ir.ScalarType(DataType.INT64), ir.Span.unknown())] | ||
| 84 | - ), | ||
| 85 | - "tensor.reshape", | ||
| 86 | - ), | ||
| 87 | - (lambda x:ir.op.tensor.transpose(x, 0, 1), "tensor.transpose"), | ||
| 88 | - (lambda x:ir.op.tensor.transpose(x, -2, -1), "tensor.transpose"), | ||
| 89 | - ], | ||
| 90 | -) | ||
| 91 | -def test_tensor_shape_transform_helpers_create_calls(factory, expected_name): | ||
| 92 | - x = _tensor_var("x", shape=[4, 8]) | ||
| 93 | - call = factory(x) | ||
| 94 | - | ||
| 95 | - assert isinstance(call, ir.Call) | ||
| 96 | - assert call.name == expected_name | ||
| 97 | - assert isinstance(call.type, ir.TensorType) | ||
| 98 | - | ||
| 99 | - | ||
| 100 | -def test_tensor_transpose_integer_axes_use_int64(): | ||
| 101 | - call = ir.op.tensor.transpose(_tensor_var("x", shape=[4, 8]), 0, 1) | ||
| 102 | - | ||
| 103 | - assert call.args[1].type.dtype == DataType.INT64 | ||
| 104 | - assert call.args[2].type.dtype == DataType.INT64 | ||
| 105 | - | ||
| 106 | - | ||
| 107 | -def test_tensor_matmul_helper_accepts_kwargs(): | ||
| 108 | - lhs = _tensor_var("lhs", [4, 8], DataType.FP16) | ||
| 109 | - rhs = _tensor_var("rhs", [8, 16], DataType.FP16) | ||
| 110 | - | ||
| 111 | - call = ir.op.tensor.matmul(lhs, rhs, out_dtype=DataType.FP32, a_trans=False, b_trans=False) | ||
| 112 | - | ||
| 113 | - assert isinstance(call, ir.Call) | ||
| 114 | - assert call.name == "tensor.matmul" | ||
| 115 | - assert isinstance(call.type, ir.TensorType) | ||
| 116 | - assert call.type.dtype == DataType.FP32 | ||
| 117 | - | ||
| 118 | - | ||
| 119 | -def test_const_float_is_available_for_tensor_helpers(): | ||
| 120 | - value = ir.ConstFloat(3.14, DataType.FP32, ir.Span.unknown()) | ||
| 121 | - | ||
| 122 | - assert isinstance(value, ir.ConstFloat) | ||
| 123 | - assert value.value == 3.14 | ||
| 124 | - assert value.dtype == DataType.FP32 | ||
| 125 | - | ||
| 126 | - | ||
| 127 | -def test_tensor_ops_are_registered_without_removed_dim_helper(): | ||
| 128 | - expected = { | ||
| 129 | - "tensor.create", | ||
| 130 | - "tensor.view", | ||
| 131 | - "tensor.matmul", | ||
| 132 | - "tensor.row_max", | ||
| 133 | - "tensor.row_sum", | ||
| 134 | - "tensor.exp", | ||
| 135 | - "tensor.cast", | ||
| 136 | - "tensor.assemble", | ||
| 137 | - "tensor.maximum", | ||
| 138 | - "tensor.reshape", | ||
| 139 | - "tensor.transpose", | ||
| 140 | - } | ||
| 141 | - | ||
| 142 | - assert all(ir.is_op_registered(name) for name in expected) | ||
| 143 | - assert not hasattr(ir.op.tensor, "dim") | ||
| 144 | - assert not ir.is_op_registered("tensor.dim") | ||
| @@ -299,11 +299,12 @@ def test_let_with_tensor_expr(): | |||
| 299 | with ib.function("tensor_test") as f: | 299 | with ib.function("tensor_test") as f: |
| 300 | f.return_type(ir.ScalarType(DataType.INT64)) | 300 | f.return_type(ir.ScalarType(DataType.INT64)) |
| 301 | 301 | ||
| 302 | - # Create a tensor operation | 302 | + # Create an op whose result carries a TensorType |
| 303 | - tensor_create = ir.op.tensor.create([4, 8], DataType.FP32) | 303 | + src = ir.Var("src", ir.TensorType([4, 8], DataType.FP32), ir.Span.unknown()) |
| 304 | + tensor_view = ir.op.ptr.make_tensor(src, [4, 8], [8, 1], dtype=DataType.FP32) | ||
| 304 | 305 | ||
| 305 | - # let() should infer TensorType from the create operation | 306 | + # let() should infer TensorType from the op's result type |
| 306 | - t = ib.let("t", tensor_create) | 307 | + t = ib.let("t", tensor_view) |
| 307 | 308 | ||
| 308 | assert t.name == "t_0" | 309 | assert t.name == "t_0" |
| 309 | assert isinstance(t.type, ir.TensorType) | 310 | assert isinstance(t.type, ir.TensorType) |
| @@ -14,7 +14,7 @@ import inspect | |||
| 14 | 14 | ||
| 15 | from pypto_pro import DataType, ir | 15 | from pypto_pro import DataType, ir |
| 16 | from pypto_pro.ir._utils import _get_span_or_capture | 16 | from pypto_pro.ir._utils import _get_span_or_capture |
| 17 | -from pypto_pro.ir.op import tensor as tensor_ops | 17 | +from pypto_pro.ir.op import ptr as ptr_ops |
| 18 | 18 | ||
| 19 | 19 | ||
| 20 | def _current_line(): | 20 | def _current_line(): |
| @@ -30,10 +30,9 @@ def _tensor_var(name: str): | |||
| 30 | 30 | ||
| 31 | def test_tensor_op_helper_captures_caller_span(): | 31 | def test_tensor_op_helper_captures_caller_span(): |
| 32 | x = _tensor_var("x") | 32 | x = _tensor_var("x") |
| 33 | - y = _tensor_var("y") | ||
| 34 | 33 | ||
| 35 | line_before = _current_line() | 34 | line_before = _current_line() |
| 36 | - result = tensor_ops.add(x, y) | 35 | + result = ptr_ops.make_tensor(x, [64], [1]) |
| 37 | 36 | ||
| 38 | assert result.span.filename.endswith("test_operation_span_capture.py") | 37 | assert result.span.filename.endswith("test_operation_span_capture.py") |
| 39 | assert result.span.is_valid() | 38 | assert result.span.is_valid() |
| @@ -42,10 +41,9 @@ def test_tensor_op_helper_captures_caller_span(): | |||
| 42 | 41 | ||
| 43 | def test_explicit_span_overrides_auto_capture(): | 42 | def test_explicit_span_overrides_auto_capture(): |
| 44 | x = _tensor_var("x") | 43 | x = _tensor_var("x") |
| 45 | - y = _tensor_var("y") | ||
| 46 | explicit = ir.Span("custom.py", 100, 20) | 44 | explicit = ir.Span("custom.py", 100, 20) |
| 47 | 45 | ||
| 48 | - result = tensor_ops.add(x, y, span=explicit) | 46 | + result = ptr_ops.make_tensor(x, [64], [1], span=explicit) |
| 49 | 47 | ||
| 50 | assert result.span.filename == "custom.py" | 48 | assert result.span.filename == "custom.py" |
| 51 | assert result.span.begin_line == 100 | 49 | assert result.span.begin_line == 100 |
| @@ -43,11 +43,12 @@ def test_list_closure_var_as_positional_arg(): | |||
| 43 | 43 | ||
| 44 | def test_int_closure_var_as_positional_arg(): | 44 | def test_int_closure_var_as_positional_arg(): |
| 45 | """Int closure variable resolves to ConstInt in function body.""" | 45 | """Int closure variable resolves to ConstInt in function body.""" |
| 46 | - axis_value = 1 | 46 | + addr_value = 512 |
| 47 | 47 | ||
| 48 | @pl.jit(auto_mutex=False) | 48 | @pl.jit(auto_mutex=False) |
| 49 | - def func(x: pl.Tensor[[64, 128], pl.DT_FP32]): | 49 | + def func(x: pl.Tensor[[1, 64], pl.DT_FP32]): |
| 50 | - result: pl.Tensor[[128, 64], pl.DT_FP32] = pl.tensor.transpose(x, axis1=0, axis2=axis_value) | 50 | + tile_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) |
| 51 | + result = pl.make_tile(tile_type, addr=addr_value) | ||
| 51 | _test_result = result | 52 | _test_result = result |
| 52 | 53 | ||
| 53 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 54 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| @@ -61,9 +62,12 @@ def test_float_closure_var_as_positional_arg(): | |||
| 61 | scale_value = 2.0 | 62 | scale_value = 2.0 |
| 62 | 63 | ||
| 63 | @pl.jit(auto_mutex=False) | 64 | @pl.jit(auto_mutex=False) |
| 64 | - def func(x: pl.Tensor[[64], pl.DT_FP32]): | 65 | + def func(x: pl.Tensor[[1, 64], pl.DT_FP32]): |
| 65 | - result: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.mul(x, scale_value) | 66 | + tile_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) |
| 66 | - _test_result = result | 67 | + o = pl.make_tile(tile_type, addr=0) |
| 68 | + s = pl.make_tile(tile_type, addr=512) | ||
| 69 | + pl.axpy(o, s, scale_value) | ||
| 70 | + _test_result = o | ||
| 67 | 71 | ||
| 68 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 72 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| 69 | func = func_program.get_function(func.__name__) | 73 | func = func_program.get_function(func.__name__) |
| @@ -76,9 +80,9 @@ def test_bool_closure_var_as_positional_arg(): | |||
| 76 | flag_value = True | 80 | flag_value = True |
| 77 | 81 | ||
| 78 | @pl.jit(auto_mutex=False) | 82 | @pl.jit(auto_mutex=False) |
| 79 | - def func(x: pl.Tensor[[64], pl.DT_FP32]): | 83 | + def func(x: pl.Tensor[[1, 64], pl.DT_FP32]): |
| 80 | - result: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.mul(x, flag_value) | 84 | + pl.printf("closure bool", loc=flag_value) |
| 81 | - _test_result = result | 85 | + _test_result = x |
| 82 | 86 | ||
| 83 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 87 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| 84 | func = func_program.get_function(func.__name__) | 88 | func = func_program.get_function(func.__name__) |
| @@ -149,10 +153,13 @@ def test_dynamic_tensor_shape_value(): | |||
| 149 | """A DYNAMIC parameter dimension is read through tensor.shape.""" | 153 | """A DYNAMIC parameter dimension is read through tensor.shape.""" |
| 150 | @pl.jit(auto_mutex=False) | 154 | @pl.jit(auto_mutex=False) |
| 151 | def func( | 155 | def func( |
| 152 | - x: pl.Tensor[[pl.DYNAMIC], pl.DT_FP32], | 156 | + x: pl.Tensor[[pl.DYNAMIC, 64], pl.DT_FP32], |
| 153 | ): | 157 | ): |
| 154 | - result = pl.tensor.mul(x, x.shape[0]) | 158 | + tile_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) |
| 155 | - _test_result = result | 159 | + o = pl.make_tile(tile_type, addr=0) |
| 160 | + s = pl.make_tile(tile_type, addr=512) | ||
| 161 | + pl.axpy(o, s, x.shape[0]) | ||
| 162 | + _test_result = o | ||
| 156 | 163 | ||
| 157 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 164 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| 158 | func = func_program.get_function(func.__name__) | 165 | func = func_program.get_function(func.__name__) |
| @@ -165,9 +172,11 @@ def test_dsl_scope_shadows_closure(): | |||
| 165 | x_scale = 999.0 # noqa: F841 -deliberately shadowed by DSL assignment | 172 | x_scale = 999.0 # noqa: F841 -deliberately shadowed by DSL assignment |
| 166 | 173 | ||
| 167 | @pl.jit(auto_mutex=False) | 174 | @pl.jit(auto_mutex=False) |
| 168 | - def func(x: pl.Tensor[[64], pl.DT_FP32]): | 175 | + def func(x: pl.Tensor[[1, 64], pl.DT_FP32]): |
| 169 | - x_scale: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.add(x, x) | 176 | + tile_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) |
| 170 | - result: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.mul(x_scale, x) | 177 | + x_scale = pl.make_tile(tile_type, addr=0) |
| 178 | + result = pl.make_tile(tile_type, addr=512) | ||
| 179 | + pl.add(result, x_scale, x_scale) | ||
| 171 | _test_result = result | 180 | _test_result = result |
| 172 | 181 | ||
| 173 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 182 | func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| @@ -181,9 +190,11 @@ def test_undefined_variable_still_raises(): | |||
| 181 | with pytest.raises(NameNotFound, match="Use of potentially undefined variable"): | 190 | with pytest.raises(NameNotFound, match="Use of potentially undefined variable"): |
| 182 | 191 | ||
| 183 | @pl.jit(auto_mutex=False) | 192 | @pl.jit(auto_mutex=False) |
| 184 | - def func(x: pl.Tensor[[64], pl.DT_FP32]): | 193 | + def func(x: pl.Tensor[[1, 64], pl.DT_FP32]): |
| 185 | - result: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.add(x, totally_undefined) # noqa: F821 # type: ignore | 194 | + tile_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) |
| 186 | - _test_result = result | 195 | + o = pl.make_tile(tile_type, addr=0) |
| 196 | + s = pl.make_tile(tile_type, addr=512) | ||
| 197 | + pl.axpy(o, s, totally_undefined) # noqa: F821 # type: ignore | ||
| 187 | 198 | ||
| 188 | func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 199 | func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| 189 | 200 | ||
| @@ -195,8 +206,10 @@ def test_unsupported_closure_type_raises(): | |||
| 195 | with pytest.raises(InvalidType, match="Unsupported closure variable type: str"): | 206 | with pytest.raises(InvalidType, match="Unsupported closure variable type: str"): |
| 196 | 207 | ||
| 197 | @pl.jit(auto_mutex=False) | 208 | @pl.jit(auto_mutex=False) |
| 198 | - def func(x: pl.Tensor[[64], pl.DT_FP32]): | 209 | + def func(x: pl.Tensor[[1, 64], pl.DT_FP32]): |
| 199 | - result: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.add(x, bad_value) # type: ignore[arg-type] | 210 | + tile_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) |
| 200 | - _test_result = result | 211 | + o = pl.make_tile(tile_type, addr=0) |
| 212 | + s = pl.make_tile(tile_type, addr=512) | ||
| 213 | + pl.axpy(o, s, bad_value) # type: ignore[arg-type] | ||
| 201 | 214 | ||
| 202 | func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 215 | func.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| @@ -20,14 +20,15 @@ def test_loop_without_iter_args(): | |||
| 20 | """Test loop without iter_args.""" | 20 | """Test loop without iter_args.""" |
| 21 | 21 | ||
| 22 | @pl.jit(auto_mutex=False) | 22 | @pl.jit(auto_mutex=False) |
| 23 | - def loop_without_iter_args(x: pl.Tensor[[64], pl.DT_FP32]): | 23 | + def loop_without_iter_args(x: pl.Tensor[[1, 64], pl.DT_FP32]): |
| 24 | - result: pl.Tensor[[64], pl.DT_FP32] = x | 24 | + tile_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) |
| 25 | + result = pl.make_tile(tile_type, addr=0) | ||
| 25 | for i in pl.range(3): | 26 | for i in pl.range(3): |
| 26 | if i > 0: | 27 | if i > 0: |
| 27 | - temp = pl.tensor.mul(result, 2.0) | 28 | + temp = pl.make_tile(tile_type, addr=512) |
| 28 | result = temp | 29 | result = temp |
| 29 | else: | 30 | else: |
| 30 | - temp = pl.tensor.add(result, 1.0) | 31 | + temp = pl.make_tile(tile_type, addr=1024) |
| 31 | result = temp | 32 | result = temp |
| 32 | _test_result = result | 33 | _test_result = result |
| 33 | 34 | ||
| @@ -868,7 +869,7 @@ def test_scalar_param_as_stop(): | |||
| 868 | def scalar_stop(n: pl.DT_INT64, x: pl.Tensor[[64], pl.DT_FP32]): | 869 | def scalar_stop(n: pl.DT_INT64, x: pl.Tensor[[64], pl.DT_FP32]): |
| 869 | y = x | 870 | y = x |
| 870 | for _ in pl.range(n): | 871 | for _ in pl.range(n): |
| 871 | - y: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.add(x, 1.0) | 872 | + pl.system.bar_all() |
| 872 | _test_result = y | 873 | _test_result = y |
| 873 | 874 | ||
| 874 | scalar_stop_program, _ = scalar_stop.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 875 | scalar_stop_program, _ = scalar_stop.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| @@ -891,7 +892,7 @@ def test_scalar_param_as_start_stop(): | |||
| 891 | ): | 892 | ): |
| 892 | y = x | 893 | y = x |
| 893 | for _ in pl.range(0, n): | 894 | for _ in pl.range(0, n): |
| 894 | - y: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.add(x, 1.0) | 895 | + pl.system.bar_all() |
| 895 | _test_result = y | 896 | _test_result = y |
| 896 | 897 | ||
| 897 | scalar_start_stop_program, _ = scalar_start_stop.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 898 | scalar_start_stop_program, _ = scalar_start_stop.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| @@ -936,7 +937,7 @@ def test_scalar_expression_as_stop(): | |||
| 936 | def scalar_expr_stop(n: pl.DT_INT64, x: pl.Tensor[[64], pl.DT_FP32]): | 937 | def scalar_expr_stop(n: pl.DT_INT64, x: pl.Tensor[[64], pl.DT_FP32]): |
| 937 | y = x | 938 | y = x |
| 938 | for _ in pl.range(n * 2): # type: ignore[operator] | 939 | for _ in pl.range(n * 2): # type: ignore[operator] |
| 939 | - y: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.add(x, 1.0) | 940 | + pl.system.bar_all() |
| 940 | _test_result = y | 941 | _test_result = y |
| 941 | 942 | ||
| 942 | scalar_expr_stop_program, _ = scalar_expr_stop.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 943 | scalar_expr_stop_program, _ = scalar_expr_stop.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| @@ -955,7 +956,7 @@ def test_scalar_complex_expression_as_stop(): | |||
| 955 | ): | 956 | ): |
| 956 | y = x | 957 | y = x |
| 957 | for _ in pl.range(n * 2 + 1): # type: ignore[operator] | 958 | for _ in pl.range(n * 2 + 1): # type: ignore[operator] |
| 958 | - y: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.add(x, 1.0) | 959 | + pl.system.bar_all() |
| 959 | _test_result = y | 960 | _test_result = y |
| 960 | 961 | ||
| 961 | scalar_complex_expr_program, _ = scalar_complex_expr.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 962 | scalar_complex_expr_program, _ = scalar_complex_expr.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| @@ -974,7 +975,7 @@ def test_scalar_floordiv_expression_as_stop(): | |||
| 974 | ): | 975 | ): |
| 975 | y = x | 976 | y = x |
| 976 | for _ in pl.range(n // 4): # type: ignore[operator] | 977 | for _ in pl.range(n // 4): # type: ignore[operator] |
| 977 | - y: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.add(x, 1.0) | 978 | + pl.system.bar_all() |
| 978 | _test_result = y | 979 | _test_result = y |
| 979 | 980 | ||
| 980 | scalar_floordiv_expr_program, _ = scalar_floordiv_expr.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 981 | scalar_floordiv_expr_program, _ = scalar_floordiv_expr.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |
| @@ -1152,12 +1153,13 @@ def test_while_loop_with_tensors(): | |||
| 1152 | """Test while loop with tensor operations.""" | 1153 | """Test while loop with tensor operations.""" |
| 1153 | 1154 | ||
| 1154 | @pl.jit(auto_mutex=False) | 1155 | @pl.jit(auto_mutex=False) |
| 1155 | - def while_tensors(n: pl.DT_INT64, x: pl.Tensor[[64], pl.DT_FP32]): | 1156 | + def while_tensors(n: pl.DT_INT64, x: pl.Tensor[[1, 64], pl.DT_FP32]): |
| 1156 | i: pl.DT_INT64 = 0 | 1157 | i: pl.DT_INT64 = 0 |
| 1157 | - acc: pl.Tensor[[64], pl.DT_FP32] = pl.tensor.create_tensor([64], dtype=pl.DT_FP32) | 1158 | + tile_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec) |
| 1159 | + acc = pl.make_tile(tile_type, addr=0) | ||
| 1158 | while i < n: | 1160 | while i < n: |
| 1159 | i = i + 1 | 1161 | i = i + 1 |
| 1160 | - acc = pl.tensor.add(acc, x) | 1162 | + pl.add(acc, acc, acc) |
| 1161 | _test_result = acc | 1163 | _test_result = acc |
| 1162 | 1164 | ||
| 1163 | while_tensors_program, _ = while_tensors.to_kernel_def().parse_target_program(ir.SectionKind.Vector) | 1165 | while_tensors_program, _ = while_tensors.to_kernel_def().parse_target_program(ir.SectionKind.Vector) |