Merged
feat(cake): 导入 AscendDSL·CV 轨三个技能 #60
feat(cake): 导入 AscendDSL·CV 轨三个技能 #60
Merged
JunyiAdd on Sep 28
Total: 97 files changed+10741-12
@@ -0,0 +1,211 @@
1+---
2+name: ascend-call-generation-cv
3+disable-model-invocation: true
4+description: Generate AscendC CV project scaffold (workspace alloc, AIC+AIV dispatch, Catlass headers) from functional PyTorch for Cube+Vector fused operators (matmul+activation, norm+matmul+scale). Use after functional-conversion when operator_type is "cv".
5+---
6+ 
7+## What I do
8+ 
9+Generate Ascend operator invocation code and project JSON configuration for **Cube+Vector (CV) fused operators**, then create the initial AscendC project. CV operators differ from pure Vector operators in that they require workspace allocation, use AIC+AIV dispatch, and include Catlass headers.
10+ 
11+## Prerequisite: env.json
12+ 
13+Read `output/{op_name}/env.json` before selecting Catlass SoC targets and AIC/AIV dispatch counts. Use `soc_version`, `cube_core_cnt`, and `vector_core_cnt`; do not hardcode `Ascend910B2`, AIC=24, or AIV=48 when the fields are available.
14+ 
15+## Workflow
16+ 
17+1. Read input functional PyTorch code `output/{op_name}/{op_name}_functional.py`
18+2. Read reference examples by operator pattern:
19+ - For matmul + activation: `references/matmul_gelu/`
20+ - For norm + matmul + scale: `references/rms_matmul_scale/`
21+ - For int8 quantized matmul with dequant: `references/quant_matmul/`
22+ - For matmul + bias + activation: `references/matmul_bias_relu/`
23+ - For matmul + add (residual): `references/matmul_add/`
24+ - For matmul + GLU (SwiGLU/GeGLU): `references/matmul_swiglu/`
25+ - For matmul + add + normalization (multi-output): `references/matmul_add_rmsnorm/`
26+ - For FFN (dual matmul): `references/ffn_silu/`
27+ - For flash attention: `references/flash_attn_basic/`
28+3. Generate code and save files:
29+ - project JSON code for msopgen to create the custom AscendC operator project
30+ - pybind11 C++ binding code (workspace is framework-managed, NOT allocated in pybind)
31+ - Python code to call the custom AscendC operator
32+4. Save all files in `output/{op_name}/` directory
33+5. Create AscendC project (run gen_project_cv.py)
34+6. Continue to the next step in agent workflow
35+ 
36+### Generation Task
37+ 
38+Construct operator name as `{op_name}_custom` and convert to PascalCase for operator definition.
39+ 
40+#### 1. project_json code
41+ 
42+JSON schema defining the custom AscendC operator:
43+- **inputs**: ND tensors mapping to [module_fn] tensor arguments
44+- **outputs**: ND tensors mapping to [module_fn] return values
45+- **attributes**: scalar/config parameters from [module_fn]
46+ 
47+**CV-Specific Notes**:
48+- **⚠️ Workspace is NOT listed as an input/output in project.json**. It is allocated implicitly by the framework via tiling's `GetWorkspaceSizes`. Never add workspace to the JSON schema.
49+- Input/output data types for CV operators are typically `float16` (half precision), since cube units work with fp16.
50+- Output tensor shape must match the fused operation's final output shape.
51+- The `attr` array should only contain attributes that appear in [module_fn] signature. For pure matmul with no extra parameters, `attr` is empty.
52+ 
53+**Fixpipe (Cube-Only) Note**:
54+When the Vector scope only performs fp32→fp16 cast (no GELU, normalization, or other operations), the operator uses fixpipe mode and does **not** need workspace at all:
55+- The tiling function does NOT call `GetWorkspaceSizes`
56+- The pybind code remains unchanged (it never passes workspace regardless)
57+- Input/output data types stay `float16` as usual
58+ 
59+Save json code in `{op_name}_project.json`
60+ 
61+#### 2. python_bind code
62+ 
63+C++ pybind11 code connecting AscendC operator to PyTorch:
64+- Include headers: `torch/library.h`, `pytorch_npu_helper.hpp`
65+- Implement `*_impl_npu` function calling `EXEC_NPU_CMD`
66+- Register with `TORCH_LIBRARY_IMPL`
67+- Export via `PYBIND11_MODULE`
68+ 
69+**CV-Specific Requirements**:
70+- **⚠️ CRITICAL: Workspace is NOT allocated in pybind code**. Workspace is managed entirely by the framework through the tiling function's `GetWorkspaceSizes()`. Do NOT allocate workspace in the impl function or pass it to `EXEC_NPU_CMD`. Only pass input tensors and output tensors.
71+ ```cpp
72+ // WRONG — Do NOT do this:
73+ // at::Tensor workspace = at::empty({...}, input.options().dtype(at::kFloat));
74+ // EXEC_NPU_CMD(aclnnOpCustom, input, weight, output, workspace);
75+ 
76+ // CORRECT — Only pass inputs and outputs:
77+ at::Tensor result = at::empty({M, N}, a.options());
78+ EXEC_NPU_CMD(aclnnMatmulCustom, a, b, result);
79+ ```
80+ The workspace (e.g., M*N floats for fp32 matmul accumulation) is allocated by the framework based on `context->GetWorkspaceSizes()` in the host-side tiling function. The kernel receives it as a `GM_ADDR workspace` parameter automatically.
81+- Output tensor shape is derived from the fused operation (e.g., for matmul: `[M, N]` from `[M,K] @ [K,N]`; for matmul+gelu: same `[M, N]`).
82+- Use `a.options()` to propagate dtype/device from input to output tensor.
83+ 
84+**Mixed-Type Operators (e.g., int8 input → fp16 output)**:
85+- When input and output dtypes differ, do NOT use `a.options()` to create output tensors — it inherits the input dtype (e.g., int8).
86+- Instead, use explicit TensorOptions: `at::TensorOptions().dtype(at::kHalf).device(a.device())`
87+- project.json `type` must match the actual dtype (use `"int8"` for int8 inputs, `"float16"` for fp16 outputs).
88+- When B is stored as [N, K] (transposed weight), use `N = b.size(0)` (not `b.size(1)`).
89+- See `references/quant_matmul/` for a complete int8 quantized matmul example.
90+ 
91+Save C code in `{op_name}.cpp`
92+ 
93+#### 3. model code
94+ 
95+`ModelNew(nn.Module)` class that:
96+- Replicates original `Model` functionality
97+- Calls custom AscendC operator via `custom_ops_lib.{op_name}_custom`
98+- Maintains same `__init__` and `forward` signatures
99+- Imports: `torch`, `torch.nn`, `torch_npu`, `custom_ops_lib`
100+ 
101+**Note**: Weight initialization in `ModelNew` must exactly match `Model` (same seed, same tensor creation).
102+ 
103+Save python code in `{op_name}_custom.py`
104+ 
105+### Create AscendC Project
106+ 
107+Use `gen_project_cv.py` to create the AscendC project with Catlass support.
108+ 
109+**⚠️ CRITICAL: 必须使用 `--output-dir` 指定输出目录为 `output/{op_name}`**,否则项目会生成到 `output/` 根目录下,需要手动搬移。
110+ 
111+```shell
112+python3 ${CLAUDE_SKILL_DIR}/scripts/gen_project_cv.py <op_name> <json_file_path> --output-dir output/<op_name>
113+```
114+ 
115+Example:
116+```shell
117+python3 ${CLAUDE_SKILL_DIR}/scripts/gen_project_cv.py MatmulGelu output/MatmulGelu/MatmulGelu_project.json --output-dir output/MatmulGelu
118+```
119+ 
120+This generates the project at `output/{op_name}/{OpNameCustom}/` and additionally:
121+- Adds Catlass include paths to CMakeLists.txt
122+- Generates kernel template with `ASCEND_IS_AIC` / `ASCEND_IS_AIV` dispatch structure
123+ 
124+Check if the project was generated successfully. If not, analyze the error and retry.
125+ 
126+### Extended Pattern Support
127+ 
128+#### Multi-Input Operators
129+ 
130+For operators with 3+ input tensors (e.g., FFN with X, W1, W2; Flash Attention with Q, K, V):
131+ 
132+**project.json**: List all input tensors in `inputs` array. Each gets its own ND tensor entry.
133+```json
134+{
135+ "inputs": [
136+ {"name": "q", "dtype": "float16", "format": "ND"},
137+ {"name": "k", "dtype": "float16", "format": "ND"},
138+ {"name": "v", "dtype": "float16", "format": "ND"}
139+ ]
140+}
141+```
142+ 
143+**pybind**: Pass all input tensors to `EXEC_NPU_CMD` in same order as project.json.
144+```cpp
145+at::Tensor result = at::empty({M, D}, q.options());
146+EXEC_NPU_CMD(aclnnFlashAttnCustom, q, k, v, result);
147+```
148+ 
149+#### Optional Input (Bias)
150+ 
151+When bias is optional (may or may not be present in [module_fn]):
152+ 
153+**project.json**: Include bias as a regular input. The pybind code handles the optional logic.
154+ 
155+**pybind**: Check if bias is provided, create zero tensor if not:
156+```cpp
157+void op_impl_npu(const at::Tensor& a, const at::Tensor& b,
158+ const c10::optional<at::Tensor>& bias, at::Tensor& result) {
159+ at::Tensor bias_tensor = bias.has_value() ? bias.value()
160+ : at::zeros({b.size(1)}, a.options());
161+ EXEC_NPU_CMD(aclnnOpCustom, a, b, bias_tensor, result);
162+}
163+```
164+ 
165+#### Multi-Output Operators
166+ 
167+For operators that return multiple tensors (e.g., MatMul + Add + RmsNorm returning both normalized output and pre-norm sum):
168+ 
169+**project.json**: List all output tensors in `outputs` array:
170+```json
171+{
172+ "outputs": [
173+ {"name": "y", "dtype": "float16", "format": "ND"},
174+ {"name": "x_add", "dtype": "float16", "format": "ND"}
175+ ]
176+}
177+```
178+ 
179+**pybind**: Allocate and return all output tensors:
180+```cpp
181+at::Tensor y = at::empty({M, N}, x.options());
182+at::Tensor x_add = at::empty({M, N}, x.options());
183+EXEC_NPU_CMD(aclnnOpCustom, x, weight, residual, gamma, y, x_add);
184+return std::make_tuple(y, x_add);
185+```
186+ 
187+**model code**: Unpack multiple returns:
188+```python
189+def forward(self, x, residual):
190+ y, x_add = custom_ops_lib.op_custom(x, self.weight, residual, self.gamma)
191+ return y, x_add
192+```
193+ 
194+#### Attribute Types
195+ 
196+Beyond simple `float` (eps), CV operators may need:
197+ 
198+| Attribute Type | Example | project.json |
199+|---|---|---|
200+| `float` | eps=1e-6 | `{"name": "eps", "type": "float", "defaultValue": "1e-6"}` |
201+| `int` | num_heads=32 | `{"name": "num_heads", "type": "int"}` |
202+| `int` | head_dim=128 | `{"name": "head_dim", "type": "int"}` |
203+| `string` | activation_type="silu" | `{"name": "activation_type", "type": "string"}` |
204+ 
205+#### FFN / Multi-MatMul Workspace
206+ 
207+For FFN-type operators with multiple matmul stages:
208+- Workspace is still **NOT** listed in project.json (framework-managed)
209+- Workspace allocation happens in tiling function, not pybind
210+- Multiple workspace segments are allocated as one contiguous block
211+- Tiling function computes: `ws_total = ws1_size + ws2_size + ws3_size + sysWorkspaceSize`
@@ -0,0 +1,14 @@
1+# ascend-call-generation-cv 参考示例
2+ 
3+本目录收录 Cube+Vector(CV)融合算子的 AscendC 工程脚手架样例,供本 skill 生成
4+pybind / CMake / host 代码时对照。CV 工程与纯 Vector 工程的差别在于需要 workspace
5+分配、AIC+AIV 双核派发,以及 Catlass 头文件引用。
6+ 
7+每个算子子目录包含一组样例文件:
8+ 
9+- `<op>_custom.py` — 算子的 Python 调用封装
10+- `<op>.cpp` — pybind 桥接代码
11+- `<op>_project.json` — `gen_project_cv.py` 使用的工程配置
12+ 
13+已收录算子:`matmul_gelu/`(matmul + 激活)、`rms_matmul_scale/`(归一化 + matmul + 缩放)、
14+`quant_matmul/`(int8 量化 matmul 含反量化)。
@@ -0,0 +1,39 @@
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+#include <torch/library.h>
12+#include <torch/csrc/autograd/custom_function.h>
13+#include "pytorch_npu_helper.hpp"
14+#include <torch/extension.h>
15+ 
16+at::Tensor matmul_gelu_custom_impl_npu(const at::Tensor& a, const at::Tensor& b) {
17+ // a: [M, K], b: [K, N] → output: [M, N] in float16
18+ // CV operator: cube does matmul into fp32 workspace, vector does GELU + cast to fp16
19+ int64_t M = a.size(0);
20+ int64_t K = a.size(1);
21+ int64_t N = b.size(1);
22+ 
23+ at::Tensor result = at::empty({M, N}, a.options());
24+ 
25+ // Workspace for fp32 matmul accumulation (M * N floats)
26+ int64_t workspace_elems = M * N;
27+ at::Tensor workspace = at::empty({workspace_elems}, a.options().dtype(at::kFloat));
28+ 
29+ EXEC_NPU_CMD(aclnnMatmulGeluCustom, a, b, result, workspace);
30+ return result;
31+}
32+ 
33+TORCH_LIBRARY_IMPL(myops, PrivateUse1, m) {
34+ m.impl("matmul_gelu_custom", &matmul_gelu_custom_impl_npu);
35+}
36+ 
37+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
38+ m.def("matmul_gelu_custom", &matmul_gelu_custom_impl_npu, "MatMul + GELU Fused Custom");
39+}
@@ -0,0 +1,26 @@
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+import torch
12+import torch.nn as nn
13+import torch_npu
14+import custom_ops_lib
15+ 
16+ 
17+def module_fn(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
18+ return custom_ops_lib.matmul_gelu_custom(A, B)
19+ 
20+ 
21+class ModelNew(nn.Module):
22+ def __init__(self):
23+ super(ModelNew, self).__init__()
24+ 
25+ def forward(self, A: torch.Tensor, B: torch.Tensor, fn=module_fn) -> torch.Tensor:
26+ return fn(A, B)
@@ -0,0 +1,41 @@
1+[
2+ {
3+ "op": "MatmulGeluCustom",
4+ "language": "cpp",
5+ "input_desc": [
6+ {
7+ "name": "a",
8+ "param_type": "required",
9+ "format": [
10+ "ND"
11+ ],
12+ "type": [
13+ "float16"
14+ ]
15+ },
16+ {
17+ "name": "b",
18+ "param_type": "required",
19+ "format": [
20+ "ND"
21+ ],
22+ "type": [
23+ "float16"
24+ ]
25+ }
26+ ],
27+ "output_desc": [
28+ {
29+ "name": "y",
30+ "param_type": "required",
31+ "format": [
32+ "ND"
33+ ],
34+ "type": [
35+ "float16"
36+ ]
37+ }
38+ ],
39+ "attr": []
40+ }
41+]
@@ -0,0 +1,35 @@
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+#include <torch/library.h>
12+#include <torch/csrc/autograd/custom_function.h>
13+#include "pytorch_npu_helper.hpp"
14+#include <torch/extension.h>
15+ 
16+at::Tensor quant_matmul_custom_impl_npu(const at::Tensor& a, const at::Tensor& b,
17+ const at::Tensor& scale, const at::Tensor& per_token_scale) {
18+ // a: [M, K] int8, b: [N, K] int8 -> output: [M, N] in float16
19+ // B is stored as [N, K] (ColumnMajor(K, N)), so N = b.size(0)
20+ int64_t M = a.size(0);
21+ int64_t N = b.size(0);
22+ 
23+ at::Tensor result = at::empty({M, N}, at::TensorOptions().dtype(at::kHalf).device(a.device()));
24+ 
25+ EXEC_NPU_CMD(aclnnQuantMatmulCustom, a, b, scale, per_token_scale, result);
26+ return result;
27+}
28+ 
29+TORCH_LIBRARY_IMPL(myops, PrivateUse1, m) {
30+ m.impl("quant_matmul_custom", &quant_matmul_custom_impl_npu);
31+}
32+ 
33+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
34+ m.def("quant_matmul_custom", &quant_matmul_custom_impl_npu, "Quantized Matrix Multiplication Custom (CV)");
35+}
@@ -0,0 +1,27 @@
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+import torch
12+import torch.nn as nn
13+import torch_npu
14+import custom_ops_lib
15+ 
16+ 
17+def module_fn(A: torch.Tensor, B: torch.Tensor, Scale: torch.Tensor, PerTokenScale: torch.Tensor) -> torch.Tensor:
18+ return custom_ops_lib.quant_matmul_custom(A, B, Scale, PerTokenScale)
19+ 
20+ 
21+class ModelNew(nn.Module):
22+ def __init__(self):
23+ super(ModelNew, self).__init__()
24+ 
25+ def forward(self, A: torch.Tensor, B: torch.Tensor, Scale: torch.Tensor,
26+ PerTokenScale: torch.Tensor, fn=module_fn) -> torch.Tensor:
27+ return fn(A, B, Scale, PerTokenScale)
@@ -0,0 +1,14 @@
1+[{
2+ "op": "QuantMatmulCustom",
3+ "language": "cpp",
4+ "input_desc": [
5+ {"name": "a", "param_type": "required", "format": ["ND"], "type": ["int8"]},
6+ {"name": "b", "param_type": "required", "format": ["ND"], "type": ["int8"]},
7+ {"name": "scale", "param_type": "required", "format": ["ND"], "type": ["float16"]},
8+ {"name": "per_token_scale", "param_type": "required", "format": ["ND"], "type": ["float16"]}
9+ ],
10+ "output_desc": [
11+ {"name": "y", "param_type": "required", "format": ["ND"], "type": ["float16"]}
12+ ],
13+ "attr": []
14+}]
@@ -0,0 +1,42 @@
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+#include <torch/library.h>
12+#include <torch/csrc/autograd/custom_function.h>
13+#include "pytorch_npu_helper.hpp"
14+#include <torch/extension.h>
15+ 
16+at::Tensor rms_matmul_scale_custom_impl_npu(const at::Tensor& x, const at::Tensor& weight, double norm_eps) {
17+ // x: [B, S, N, D] → viewed as [M, K] where M=B*S, K=N*D
18+ // weight: [K, O]
19+ // output: [M, O] in float16
20+ int64_t B = x.size(0);
21+ int64_t S = x.size(1);
22+ int64_t M = B * S;
23+ int64_t K = x.size(2) * x.size(3);
24+ int64_t O = weight.size(1);
25+ 
26+ at::Tensor result = at::empty({M, O}, x.options());
27+ 
28+ // Workspace: matmul accumulation (M*O floats) + inv_rms per row (M floats)
29+ int64_t workspace_elems = M * O + M;
30+ at::Tensor workspace = at::empty({workspace_elems}, x.options().dtype(at::kFloat));
31+ 
32+ EXEC_NPU_CMD(aclnnRmsMatmulScaleCustom, x, weight, result, workspace);
33+ return result;
34+}
35+ 
36+TORCH_LIBRARY_IMPL(myops, PrivateUse1, m) {
37+ m.impl("rms_matmul_scale_custom", &rms_matmul_scale_custom_impl_npu);
38+}
39+ 
40+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
41+ m.def("rms_matmul_scale_custom", &rms_matmul_scale_custom_impl_npu, "RMSNorm + MatMul + Scale Fused Custom");
42+}
@@ -0,0 +1,26 @@
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+import torch
12+import torch.nn as nn
13+import torch_npu
14+import custom_ops_lib
15+ 
16+ 
17+def module_fn(x: torch.Tensor, weight: torch.Tensor, norm_eps: float = 1e-6) -> torch.Tensor:
18+ return custom_ops_lib.rms_matmul_scale_custom(x, weight, norm_eps)
19+ 
20+ 
21+class ModelNew(nn.Module):
22+ def __init__(self):
23+ super(ModelNew, self).__init__()
24+ 
25+ def forward(self, x: torch.Tensor, weight: torch.Tensor, norm_eps: float = 1e-6, fn=module_fn) -> torch.Tensor:
26+ return fn(x, weight, norm_eps)
@@ -0,0 +1,48 @@
1+[
2+ {
3+ "op": "RmsMatmulScaleCustom",
4+ "language": "cpp",
5+ "input_desc": [
6+ {
7+ "name": "x",
8+ "param_type": "required",
9+ "format": [
10+ "ND"
11+ ],
12+ "type": [
13+ "float16"
14+ ]
15+ },
16+ {
17+ "name": "weight",
18+ "param_type": "required",
19+ "format": [
20+ "ND"
21+ ],
22+ "type": [
23+ "float16"
24+ ]
25+ }
26+ ],
27+ "output_desc": [
28+ {
29+ "name": "y",
30+ "param_type": "required",
31+ "format": [
32+ "ND"
33+ ],
34+ "type": [
35+ "float16"
36+ ]
37+ }
38+ ],
39+ "attr": [
40+ {
41+ "name": "norm_eps",
42+ "type": "float",
43+ "paramType": "optional",
44+ "defaultValue": "0.000001"
45+ }
46+ ]
47+ }
48+]
@@ -0,0 +1,178 @@
1+#!/usr/bin/env python3
2+# ----------------------------------------------------------------------------------------------------------
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# ----------------------------------------------------------------------------------------------------------
11+ 
12+ 
13+"""
14+Use msopgen to create AscendC project for Cube+Vector (CV) fused operators.
15+Extends the standard gen_project.py with Catlass include paths and AIC/AIV dispatch template.
16+ 
17+Usage:
18+ python3 gen_project_cv.py <op_name> <json_file_path>
19+ 
20+Examples:
21+ python3 gen_project_cv.py matmul_gelu output/matmul_gelu/matmul_gelu_project.json
22+"""
23+ 
24+from pathlib import Path
25+import logging
26+import argparse
27+import sys
28+ 
29+# Add parent skill's scripts to path for reuse
30+sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent / "ascend-call-generation" / "scripts"))
31+from gen_project import prepare_ascend_project
32+ 
33+ 
34+# Catlass include path for CANN 8.x on Ascend 910B
35+# The kernel compiler (TBE/opc) does NOT use CMake's include_directories.
36+# Must use add_ops_compile_options(-I...) in op_kernel/CMakeLists.txt.
37+CATLASS_INCLUDE_CANDIDATES = [
38+ # CANN 8.5.0+ (new path structure with ops_legacy)
39+ "/usr/local/Ascend/cann-8.5.0/opp/built-in/op_impl/ai_core/tbe/impl/ops_legacy/ascendc/common/catlass/include",
40+ "/usr/local/Ascend/ascend-toolkit/latest/opp/built-in/op_impl/ai_core/tbe/impl"
41+ "/ops_legacy/ascendc/common/catlass/include",
42+ # CANN 8.3.x (old path structure)
43+ "/usr/local/Ascend/ascend-toolkit/8.3.RC1/opp/built-in/op_impl/ai_core/tbe/impl/ascendc/common/catlass/include",
44+ "/usr/local/Ascend/ascend-toolkit/8.3.RC2/opp/built-in/op_impl/ai_core/tbe/impl/ascendc/common/catlass/include",
45+ "/usr/local/Ascend/ascend-toolkit/latest/opp/built-in/op_impl/ai_core/tbe/impl/ascendc/common/catlass/include",
46+]
47+ 
48+ 
49+def find_catlass_include() -> str:
50+ """Find the actual catlass include path on this system."""
51+ for path in CATLASS_INCLUDE_CANDIDATES:
52+ if Path(path).exists():
53+ return path
54+ # Fallback: search filesystem (both old and new structures)
55+ import glob
56+ patterns = [
57+ "/usr/local/Ascend/*/opp/built-in/op_impl/ai_core/tbe/impl/ops_legacy/ascendc/common/catlass/include",
58+ "/usr/local/Ascend/ascend-toolkit/*/opp/built-in/op_impl/ai_core/tbe/impl"
59+ "/ops_legacy/ascendc/common/catlass/include",
60+ "/usr/local/Ascend/ascend-toolkit/*/opp/built-in/op_impl/ai_core/tbe/impl/ascendc/common/catlass/include",
61+ ]
62+ for pat in patterns:
63+ matches = glob.glob(pat)
64+ if matches:
65+ return sorted(matches)[-1]
66+ raise FileNotFoundError(
67+ "Cannot find catlass include directory. "
68+ "Searched both CANN 8.5+ (ops_legacy/ascendc) and CANN 8.3 (ascendc) paths."
69+ )
70+ 
71+ 
72+def patch_cmake_for_catlass(project_dir: Path):
73+ """
74+ Patch op_kernel/CMakeLists.txt to add Catlass include paths for CV operators.
75+ 
76+ NOTE: The kernel compiler (TBE/opc) does NOT honor CMake's include_directories().
77+ We must use add_ops_compile_options(ALL OPTIONS -I<path>) in op_kernel/CMakeLists.txt
78+ to pass the include path to the kernel compiler.
79+ """
80+ kernel_cmake = project_dir / "op_kernel" / "CMakeLists.txt"
81+ if not kernel_cmake.exists():
82+ logging.warning(f"op_kernel/CMakeLists.txt not found at {kernel_cmake}, skipping Catlass patch")
83+ return
84+ 
85+ content = kernel_cmake.read_text()
86+ 
87+ # Skip if already patched
88+ if "CATLASS_INCLUDE_PATH" in content:
89+ logging.info("op_kernel/CMakeLists.txt already has Catlass include, skipping")
90+ return
91+ 
92+ catlass_path = find_catlass_include()
93+ 
94+ # Insert before add_kernels_compile()
95+ catlass_snippet = f"""
96+# Catlass include path for CV (Cube+Vector) fused operators
97+# NOTE: Must use add_ops_compile_options, not include_directories (TBE compiler ignores CMake includes)
98+set(CATLASS_INCLUDE_PATH "{catlass_path}")
99+add_ops_compile_options(ALL OPTIONS -I${{CATLASS_INCLUDE_PATH}})
100+"""
101+ 
102+ if "add_kernels_compile()" in content:
103+ content = content.replace(
104+ "add_kernels_compile()",
105+ catlass_snippet.strip() + "\n\nadd_kernels_compile()"
106+ )
107+ else:
108+ content += "\n" + catlass_snippet
109+ 
110+ kernel_cmake.write_text(content)
111+ logging.info(f"Patched op_kernel/CMakeLists.txt with Catlass include: {catlass_path}")
112+ 
113+ 
114+def patch_kernel_for_cv_dispatch(project_dir: Path, op_name: str):
115+ """
116+ Patch the kernel source to use ASCEND_IS_AIC / ASCEND_IS_AIV dispatch structure.
117+ """
118+ op_custom = op_name + "_custom"
119+ 
120+ kernel_dir = project_dir / "op_kernel"
121+ if not kernel_dir.exists():
122+ logging.warning(f"op_kernel directory not found at {kernel_dir}")
123+ return
124+ 
125+ # Find the kernel .cpp file
126+ kernel_files = list(kernel_dir.glob("*.cpp"))
127+ if not kernel_files:
128+ logging.warning("No kernel .cpp files found in op_kernel/")
129+ return
130+ 
131+ kernel_file = kernel_files[0]
132+ snake_name = op_custom # e.g., matmul_gelu_custom
133+ 
134+ cv_kernel_template = f'''#include "kernel_operator.h"
135+ 
136+// CV (Cube+Vector) fused kernel entry point
137+// KernelCube and KernelVector classes will be implemented during DSL lowering
138+ 
139+extern "C" __global__ __aicore__
140+void {snake_name}(GM_ADDR a, GM_ADDR b, GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling) {{
141+ // GET_TILING_DATA(t, tiling);
142+ // if ASCEND_IS_AIC {{
143+ // KernelCube opCube;
144+ // opCube.Init(...);
145+ // opCube.Process();
146+ // }} else if ASCEND_IS_AIV {{
147+ // KernelVector opVector;
148+ // opVector.Init(...);
149+ // opVector.Process();
150+ // }}
151+}}
152+'''
153+ kernel_file.write_text(cv_kernel_template)
154+ logging.info(f"Patched kernel file with CV dispatch template: {kernel_file}")
155+ 
156+ 
157+if __name__ == "__main__":
158+ logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
159+ parser = argparse.ArgumentParser(description="AscendC CV operator project generator")
160+ parser.add_argument("op_name", type=str, help="Operator name (e.g., 'matmul_gelu')")
161+ parser.add_argument("project_json", type=Path, help="Project JSON file path")
162+ parser.add_argument("--output-dir", type=Path, default=None,
163+ help="Base directory for CMake project output (default: output/). "
164+ "The project is created at <output-dir>/{OpNameCustom}/.")
165+ 
166+ args = parser.parse_args()
167+ try:
168+ # Step 1: Create standard project
169+ project_path = prepare_ascend_project(args.op_name, args.project_json, args.output_dir)
170+ logging.info(f"Created base AscendC project at: {project_path}")
171+ 
172+ # Step 2: Patch for CV support
173+ patch_cmake_for_catlass(project_path)
174+ patch_kernel_for_cv_dispatch(project_path, args.op_name)
175+ 
176+ logging.info(f"CV project setup complete: {project_path}")
177+ except Exception as e:
178+ logging.error(e)
@@ -14,7 +14,9 @@
14at::Tensor average_pooling_2d_custom_impl_npu(const at::Tensor& input, int64_t kernel_size) {14at::Tensor average_pooling_2d_custom_impl_npu(const at::Tensor& input, int64_t kernel_size) {
15 // bf16 variant: input/output tensors are bfloat1615 // bf16 variant: input/output tensors are bfloat16
16 // The kernel handles bf16↔f32 casting internally16 // The kernel handles bf16↔f32 casting internally
17- int64_t actual_stride = kernel_size ;17+ TORCH_CHECK(kernel_size > 0,
18+ "average_pooling_2d_custom: kernel_size must be positive, got ", kernel_size);
19+ int64_t actual_stride = kernel_size;
18 20
19 // --------------------------------------------------21 // --------------------------------------------------
20 // Input tensor layout (NHWC):22 // Input tensor layout (NHWC):
@@ -246,7 +246,7 @@ def load_test_cases(work_dir: Path) -> Tuple[Dict, Any]:
246 if not hasattr(module, "TEST_CASES"):246 if not hasattr(module, "TEST_CASES"):
247 raise AttributeError(f"test_cases.py must define TEST_CASES dict")247 raise AttributeError(f"test_cases.py must define TEST_CASES dict")
248 248 
249- return module.loaded_cases, module249+ return module.TEST_CASES, module
250 250 
251 251 
252def setup_environment(work_dir: Path):252def setup_environment(work_dir: Path):
@@ -370,6 +370,43 @@ def _compare_one_output(c_out, r_out, g_out, out_name: str, out_tolerances):
370 )370 )
371 371 
372 372 
373+def normalize_output_triple(
374+ custom_output: Any,
375+ ref_output: Any,
376+ golden_output: Any,
377+) -> Tuple[List[Any], List[Any], List[Any], Optional[str]]:
378+ """Normalize one case's three outputs to lists and check their counts agree.
379+ 
380+ Each output is normalized on its own: a tuple/list becomes a list of its
381+ elements, anything else (a single tensor) becomes a one-element list.
382+ Normalizing the three together off the custom output's type would turn a
383+ single reference tensor into `list(tensor)`, i.e. a split along dim 0, and
384+ report a count that never existed.
385+ 
386+ Returns (custom_outputs, ref_outputs, golden_outputs, mismatch_reason).
387+ mismatch_reason is None when the three counts agree; otherwise it names the
388+ three counts and the case must fail, because zip() would stop at the
389+ shortest list and leave the surplus outputs unchecked.
390+ """
391+ def _to_list(output: Any) -> List[Any]:
392+ if isinstance(output, (tuple, list)):
393+ return list(output)
394+ return [output]
395+ 
396+ custom_outputs = _to_list(custom_output)
397+ ref_outputs = _to_list(ref_output)
398+ golden_outputs = _to_list(golden_output)
399+ 
400+ if len(custom_outputs) == len(ref_outputs) == len(golden_outputs):
401+ return custom_outputs, ref_outputs, golden_outputs, None
402+ 
403+ reason = (
404+ f"Output count mismatch: custom={len(custom_outputs)}, "
405+ f"ref={len(ref_outputs)}, golden={len(golden_outputs)}"
406+ )
407+ return custom_outputs, ref_outputs, golden_outputs, reason
408+ 
409+ 
373def _evaluate_case_precision(ctx: "_EvalCtx", ref_model, custom_model, inputs) -> tuple:410def _evaluate_case_precision(ctx: "_EvalCtx", ref_model, custom_model, inputs) -> tuple:
374 """返回 (是否通过, 诊断串, 首个精度结果)。"""411 """返回 (是否通过, 诊断串, 首个精度结果)。"""
375 logging.info(" Running precision evaluation...")412 logging.info(" Running precision evaluation...")
@@ -377,15 +414,11 @@ def _evaluate_case_precision(ctx: "_EvalCtx", ref_model, custom_model, inputs) -
377 ctx, ref_model, custom_model, inputs)414 ctx, ref_model, custom_model, inputs)
378 415 
379 # Move all outputs to CPU for comparison416 # Move all outputs to CPU for comparison
380- # Normalize outputs to list for uniform handling (single tensor or tuple)417+ custom_outputs, ref_outputs, golden_outputs, count_mismatch = normalize_output_triple(
381- if isinstance(custom_output, (tuple, list)):418+ custom_output, ref_output, golden_output)
382- custom_outputs = list(custom_output)419+ if count_mismatch is not None:
383- ref_outputs = list(ref_output)420+ # 调用方据 passed=False 记 warning、quiet 模式打印并写出 FAIL 结果。
384- golden_outputs = list(golden_output)421+ return False, count_mismatch, None
385- else:
386- custom_outputs = [custom_output]
387- ref_outputs = [ref_output]
388- golden_outputs = [golden_output]
389 422 
390 precision_passed = True423 precision_passed = True
391 precision_diagnosis = []424 precision_diagnosis = []
@@ -607,7 +640,7 @@ def evaluate_multi_case(
607 operator_type = loaded_cases.get("operator_type", "unary")640 operator_type = loaded_cases.get("operator_type", "unary")
608 cases = loaded_cases["cases"]641 cases = loaded_cases["cases"]
609 642 
610- logging.info(f"Operator: {TEST_CASES['operator']}")643+ logging.info(f"Operator: {loaded_cases['operator']}")
611 logging.info(f"Type: {operator_type}")644 logging.info(f"Type: {operator_type}")
612 logging.info(f"Test cases: {len(cases)}")645 logging.info(f"Test cases: {len(cases)}")
613 646 
@@ -409,3 +409,73 @@ class TestSuites:
409 result = smoke_test("multi", MultiOut, (inp,))409 result = smoke_test("multi", MultiOut, (inp,))
410 assert result["passed"]410 assert result["passed"]
411 assert result["n_outputs"] == 2411 assert result["n_outputs"] == 2
412+ 
413+ 
414+# ---------------------------------------------------------------------------
415+# Multi-output count check (evaluate.normalize_output_triple)
416+# ---------------------------------------------------------------------------
417+ 
418+class TestNormalizeOutputTriple:
419+ """Custom / reference / golden output counts must agree before comparison."""
420+ 
421+ @staticmethod
422+ def test_single_tensor_outputs_agree():
423+ import torch
424+ from evaluate import normalize_output_triple
425+ 
426+ t = torch.tensor([1.0])
427+ custom, ref, golden, reason = normalize_output_triple(t, t, t)
428+ assert reason is None
429+ assert len(custom) == len(ref) == len(golden) == 1
430+ 
431+ @staticmethod
432+ def test_matching_tuple_outputs_agree():
433+ import torch
434+ from evaluate import normalize_output_triple
435+ 
436+ triple = (torch.tensor([1.0]), torch.tensor([2.0]))
437+ custom, ref, golden, reason = normalize_output_triple(triple, triple, triple)
438+ assert reason is None
439+ assert len(custom) == len(ref) == len(golden) == 2
440+ 
441+ @staticmethod
442+ def test_custom_returns_extra_output():
443+ """Surplus custom output must fail instead of being dropped by zip()."""
444+ import torch
445+ from evaluate import normalize_output_triple
446+ 
447+ custom_output = (torch.tensor([1.0]), torch.tensor([999.0]))
448+ ref_output = (torch.tensor([1.0]),)
449+ _, _, _, reason = normalize_output_triple(custom_output, ref_output, ref_output)
450+ assert reason is not None
451+ assert "custom=2" in reason
452+ assert "ref=1" in reason
453+ assert "golden=1" in reason
454+ 
455+ @staticmethod
456+ def test_custom_returns_missing_output():
457+ """Missing custom output must fail instead of being dropped by zip()."""
458+ import torch
459+ from evaluate import normalize_output_triple
460+ 
461+ custom_output = (torch.tensor([1.0]),)
462+ ref_output = (torch.tensor([1.0]), torch.tensor([2.0]))
463+ _, _, _, reason = normalize_output_triple(custom_output, ref_output, ref_output)
464+ assert reason is not None
465+ assert "custom=1" in reason
466+ assert "ref=2" in reason
467+ assert "golden=2" in reason
468+ 
469+ @staticmethod
470+ def test_single_reference_tensor_is_not_split_along_dim0():
471+ """A bare reference tensor counts as one output, not one per row."""
472+ import torch
473+ from evaluate import normalize_output_triple
474+ 
475+ custom_output = (torch.tensor([1.0]), torch.tensor([2.0]))
476+ ref_output = torch.tensor([[1.0], [2.0]])
477+ _, ref, _, reason = normalize_output_triple(custom_output, ref_output, ref_output)
478+ assert len(ref) == 1
479+ assert reason is not None
480+ assert "custom=2" in reason
481+ assert "ref=1" in reason
@@ -0,0 +1,275 @@
1+---
2+name: dsl-baseline-generation-cv
3+disable-model-invocation: true
4+description: Generate initial AscendDSL code with scope('cube')/scope('vector') structure for CV fused operators. Use after ascend-call-generation-cv creates the CV project scaffold.
5+---
6+ 
7+## What I do
8+ 
9+Generate initial AscendDSL code for **Cube+Vector (CV) fused operators** — kernels that combine matrix multiplication (cube) with element-wise or reduction operations (vector). The generated DSL uses `tl.scope('cube')` and `tl.scope('vector')` to separate compute phases, with cross-core synchronization.
10+ 
11+## Prerequisite: env.json
12+ 
13+Read `output/{op_name}/env.json` before generating cube/vector DSL. Use `soc_version`, `cube_core_cnt`, `vector_core_cnt`, and memory-size fields for hardware budgets. Treat `null` fields as unknown rather than falling back silently.
14+ 
15+## Workflow
16+ 
17+1. Read input functional PyTorch code `output/{op_name}/{op_name}_functional.py`
18+2. Read CV DSL knowledge: @references/ascend_dsl_cv.py
19+3. **Match examples** — find the best reference for each sub-pattern in the operator:
20+ 
21+ **Direct match** (operator maps to a single example):
22+ 
23+ | Operator pattern | Example pair (`references/input_example/` + `references/output_example/`) |
24+ |---|---|
25+ | matmul + activation (GELU, ReLU, etc.) | `matmul_gelu.py` |
26+ | norm + matmul + scale | `rms_matmul_scale.py` |
27+ | matmul + bias + activation | `matmul_bias_relu.py` |
28+ | matmul + add (residual) | `matmul_add.py` |
29+ | matmul + GLU (SwiGLU/GeGLU/ReGLU) | `matmul_swiglu.py` |
30+ | matmul + add + normalization (multi-output) | `matmul_add_rmsnorm.py` |
31+ | FFN (dual matmul) | `ffn_silu.py` |
32+ | flash attention (Q@K→softmax→S@V) | `flash_attn_basic.py` |
33+ | conv2d (1x1 pointwise, kH=kW=1, stride=1, pad=0) | `conv2d_1x1.py` |
34+ | conv2d + bias (general kH×kW) | `conv2d_bias.py` |
35+ 
36+ **No direct match** (complex/multi-stage operators like MLA, custom fusions):
37+ 
38+ When no single example covers the full operator, use **decompose → match → compose**:
39+ 1. **Decompose**: Run Step 0 (DAG analysis) to break the operator into individual stages (each stage = one Cube or Vector scope)
40+ 2. **Match each stage**: Map each stage to the closest existing example's corresponding scope:
41+ - Cube stage doing matmul → any example's `scope('cube')` (e.g., from `matmul_gelu.py`)
42+ - Vector stage doing RMSNorm → `rms_matmul_scale.py`'s vector scope
43+ - Vector stage doing RoPE → `ascend_dsl_cv.py` §3.6
44+ - Vector stage doing activation → `matmul_gelu.py`'s vector scope
45+ - Vector stage doing cast only → Fixpipe pattern or simple `vcast` loop
46+ 3. **Compose**: Chain the matched scopes in DAG order, adding workspace segments and cross-core events at each Cube↔Vector boundary. Use `ascend_dsl_cv.py` §3.1 for multi-scope layout patterns.
47+ 
48+ **Example**: MLAPre (4C+4V) decomposes into:
49+ - C1 (matmul) → match `matmul_gelu.py` cube scope
50+ - V1 (RMSNorm) → match `rms_matmul_scale.py` vector scope
51+ - C2 (matmul) → match cube scope
52+ - V2 (split + RoPE) → match `ascend_dsl_cv.py` §3.6 for RoPE, simple cast loop for split
53+ - C3 (per-head matmul) → match cube scope + head-major layout rule (§0.2.1)
54+ - C4 (matmul) → match cube scope
55+ - V3 (cast) → simple `vcast` loop
56+ - V4 (RMSNorm + RoPE) → combine `rms_matmul_scale.py` vector scope + §3.6
57+ 
58+4. Generate Ascend DSL code
59+5. Save to `output/{op_name}/{op_name}_dsl.py`
60+6. Continue to the next step in agent workflow
61+ 
62+### Input Explain
63+- **[module_fn]**: a pure PyTorch functional implementation that contains matrix multiplication fused with other operations
64+- **[Model Definition]**: a `Model(nn.Module)` calling [module_fn]
65+- **[Configurations]**: hyper-parameters and input helper functions
66+ 
67+### Fixpipe Optimization (Cube-Only Pattern)
68+ 
69+When the Vector scope **only** performs `tl.vcast(dst, src)` for fp32→fp16 type conversion and no other computation (no GELU, RMSNorm, reduction, etc.), the NPU fixpipe hardware can perform this cast automatically as part of the Cube output path. In this case, generate a **Cube-only** DSL without any Vector scope.
70+ 
71+#### Detection Criteria
72+- The functional PyTorch code's post-matmul processing is limited to `.half()` / `.to(torch.float16)` type cast
73+- No activation functions, normalization, or other element-wise operations after matmul
74+ 
75+#### DSL Generation Rules for Fixpipe
76+1. **No `tl.scope('vector')` block** — omit entirely
77+2. **No `tl.cross_core_set` / `tl.cross_core_wait`** — no cross-core synchronization needed
78+3. **`DTYPE_C = tl.half`** — Cube output type is fp16 directly (not fp32)
79+4. **Cube writes to output tensor directly** — `tl.dot(...)` writes to the final output `D`, not a workspace
80+5. **Host does not allocate workspace** — no `torch.empty(...)` for intermediate buffers
81+ 
82+> **Note**: Fixpipe is a conditional optimization. If the Vector scope contains any computation beyond a simple fp32→fp16 cast, use the standard CV dual-scope pattern described below.
83+ 
84+---
85+ 
86+### Step 0: Data Dependency Analysis (MANDATORY before DSL generation)
87+ 
88+Before writing any DSL code, you MUST analyze the functional PyTorch code and construct a data dependency graph. This determines the scope layout, workspace allocation, synchronization, and UB buffer strategy.
89+ 
90+#### 0.1 Construct the Data Flow DAG
91+ 
92+Classify each operation in [module_fn] by execution unit:
93+ 
94+| Operation Type | Execution Unit | Memory Level |
95+|---|---|---|
96+| MatMul / GEMM / Linear | **Cube** (AIC) | L0C accumulation |
97+| Conv2d (1x1, stride=1, pad=0) | **Cube** (AIC) | L0C accumulation (reshape to MatMul) |
98+| Conv2d (general kH×kW) | **Cube** (AIC) | L0C accumulation (im2col via Load3D + Mmad, use `tl.conv2d_dot()`) |
99+| Element-wise (Add/Mul/Exp/Sigmoid/ReLU/GELU/SiLU/Cast) | **Vector** (AIV) | UB |
100+| Reduction (ReduceSum/ReduceMax/Mean/Variance) | **Vector** (AIV) | UB |
101+| RoPE (rotary position embedding) | **Vector** (AIV) | UB (see `ascend_dsl_cv.py` §3.6) |
102+| Softmax (= ReduceMax + Sub + Exp + ReduceSum + Div) | **Vector** (AIV) | UB |
103+| Data movement (GM↔UB) | **Vector MTE** | UB↔GM |
104+ 
105+For each operation node, annotate:
106+- Input tensor source (GM / workspace / UB)
107+- Output tensor destination (GM / workspace / UB)
108+- Data type (fp16 / fp32 / bf16 / int8 / int32)
109+ 
110+Edge rules:
111+- If output crosses Cube↔Vector boundary → mark as **"needs workspace in GM"**
112+- If within same execution unit → data can stay in **UB or L0** (no workspace needed)
113+ 
114+#### 0.2 Determine Scope Layout from DAG
115+ 
116+From the DAG, determine how many `tl.scope('cube')` and `tl.scope('vector')` blocks are needed and their ordering:
117+ 
118+| Fusion Pattern | DAG Structure | Scope Layout |
119+|---|---|---|
120+| MatMul + Activation | `[C] MM → ws → [V] Act → GM` | 1C + 1V |
121+| MatMul + Bias + Activation | `[C] MM → ws → [V] (bias + Act) → GM` | 1C + 1V |
122+| MatMul + Add (residual) | `[C] MM → ws → [V] (residual + Add) → GM` | 1C + 1V |
123+| MatMul + SwiGLU | `[C] MM → ws → [V] (split + gate) → GM` | 1C + 1V |
124+| MatMul + Add + RmsNorm | `[C] MM → ws → [V] (Add + Norm) → GM` | 1C + 1V, multi-output |
125+| Norm + MatMul + Scale | `[V] Norm → ws; [C] MM → ws; [V] Scale → GM` | 1V + 1C + 1V |
126+| FFN (MM1→Act→MM2) | `[C]→ws→[V]→ws→[C]→ws→[V]→GM` | 2C + 2V alternating |
127+| Flash Attention | `[C] Q@K→[V] softmax→[C] P@V→[V] rescale` per KV block | 2C + 2V per iteration |
128+| Conv2d (1x1, bias-only) | `[C] dot (reshape) → GM` (Fixpipe) | Cube-only |
129+| Conv2d (general, bias-only) | `[C] conv2d_dot → GM` (ConvBias, Fixpipe) | Cube-only |
130+| Conv2d + Activation | `[C] conv2d_dot → ws → [V] (bias + Act) → GM` | 1C + 1V |
131+| MLA Preprocess | See §0.2.1 below | 4C + 4V multi-stage |
132+ 
133+##### 0.2.1 MLA Multi-Stage Scope Layout
134+ 
135+For MLA-class operators (4+ Cube stages with interleaved Vector processing):
136+ 
137+```
138+Data flow:
139+ [C1] token_x @ W_DQ → ws_cq_raw (fp32)
140+ [V1] RMSNorm(ws_cq_raw) → ws_cq (bf16)
141+ [C2] ws_cq @ W_UQ_QR → ws_qr (fp32)
142+ [C4] token_x @ W_DKV_KR → ws_dkv (fp32) ← parallel with C2
143+ [V2] split(ws_qr) → ws_qc (bf16, head-major) + RoPE(q_r) → out_query_rope
144+ [C3] ws_qc @ W_UK → ws_qn (fp32, per-head) ← depends on V2
145+ [V3] cast(ws_qn) → out_query
146+ [V4] RMSNorm(ckv) + RoPE(kr) → out_c_kv, out_k_rope
147+```
148+ 
149+**Key layout rule for per-head matmul**: When V2 writes intermediate data (ws_qc) consumed by C3's per-head matmul, use **head-major layout** — head h's M rows are stored contiguously at `[h*M, (h+1)*M)`. This allows C3 to do standard `(M,D) @ (D,Hckv)` GEMM per head without strided access.
150+ 
151+#### 0.3 Derive Workspace from DAG
152+ 
153+For each edge that crosses Cube↔Vector boundary:
154+- **One workspace segment** per cross-boundary data transfer
155+- Size = output shape × sizeof(output_dtype)
156+ 
157+Workspace mode selection:
158+- **Full mode**: `size = M × N × sizeof(dtype)` — default for most operators
159+- **Streaming double-buffer**: `size = L1_M × L1_N × cores × 2 × sizeof(dtype)` — when full is too large or pipeline overlap needed
160+- **Multi-segment**: concatenate separate segments — when multiple different-shaped intermediates needed
161+ 
162+#### 0.4 Derive Cross-Core Events from DAG
163+ 
164+Count the number of Cube↔Vector boundary crossings in the DAG:
165+- **1 crossing** → 1 event (e.g., matmul_gelu: `matmul_ready_id = 0`)
166+- **2 crossings** → 2 events (e.g., FFN: `mm1_done`, `act_done`)
167+- **N crossings** → N events for multi-stage operators (e.g., MLA: 6 events)
168+ 
169+Event placement rule:
170+- **Set**: after producer's last write operation
171+- **Wait**: before consumer's first read operation
172+ 
173+**Critical for multi-core**: `SetBlockDim` must equal `min(tileCountM, aic_core_num)`. Cores with no work must NOT be scheduled, otherwise they skip the matmul loop without firing CrossCoreSetFlag, causing paired AIV cores to deadlock.
174+ 
175+#### 0.5 UB Buffer Planning (192KB constraint)
176+ 
177+**Critical: UB total is only 192KB (196,608 bytes).**
178+ 
179+For simple operators (total buffer need < 192KB):
180+- Allocate each buffer independently with `tl.alloc_ub()`
181+ 
182+For complex operators (multiple stages exceed 192KB):
183+- **Stage-sequential reuse**: buffers from completed stages are reused by later stages
184+- **Peak UB = max(peak_stage_1, peak_stage_2, ..., peak_stage_n)** must fit in 176KB (192KB - 16KB system)
185+ 
186+---
187+ 
188+### Complexity Levels and Generation Strategy
189+ 
190+#### Level 1: Simple CV (1 Cube + 1 Vector)
191+ 
192+Single MatMul followed by single Vector post-processing. Use existing examples directly.
193+- **Examples**: matmul_gelu, matmul_relu, matmul_bias_relu, matmul_add
194+- **Workspace**: 1 segment (M×N×sizeof(fp32))
195+- **Events**: 1
196+ 
197+**Code pattern**: see examples in `references/output_example/matmul_gelu.py` etc.
198+ 
199+#### Level 1-Conv: Conv2d (Cube-only or 1 Cube + 1 Vector)
200+ 
201+Conv2d operators. Two sub-patterns:
202+ 
203+**1x1 Conv (kH=1, kW=1, stride=1, pad=0)**: Equivalent to matmul after reshape.
204+- Use `tl.dot()` with Fixpipe (Cube-only, no Vector scope).
205+- Host reshapes input `[N,Cin,H,W]` → `[N*H*W,Cin]`, weight `[Cout,Cin,1,1]` → `[Cin,Cout]`.
206+- **Example**: `conv2d_1x1.py`
207+ 
208+**General Conv (kH>1 or kW>1 or stride>1 or pad>0)**: Use `tl.conv2d_dot()`.
209+- Maps to Catlass `BlockConv` (im2col via Load3D handled internally).
210+- If post-processing is bias-only: Cube-only via ConvBias (bias fused in Cube via BT buffer).
211+- If post-processing includes activation: Cube→workspace→Vector pattern (same as matmul+activation).
212+- Input format: NC1HWC0 (C0=16 for fp16). Weight format: FracZ (KDC1KHKWN1N0C0).
213+- **Example**: `conv2d_bias.py`
214+ 
215+#### Level 2: CV with Complex Vector (1 Cube + 1 Vector, more complex)
216+ 
217+Single MatMul, but Vector does more (split, reduction, multi-output, gate).
218+- **Examples**: matmul_swiglu, matmul_add_rmsnorm, rms_matmul_scale
219+- **Workspace**: 1-2 segments
220+- **Events**: 1
221+ 
222+Specific patterns for SwiGLU, RmsNorm, bias+activation: see `references/output_example/` and `ascend_dsl_cv.py` §3.5.
223+ 
224+#### Level 3: Multi-Cube CV (2+ Cube stages)
225+ 
226+Multiple MatMul operations with Vector processing between them. **MUST draw DAG first (Step 0).**
227+ 
228+- **FFN (MM1→Act→MM2)**: 2C + 2V. See `references/output_example/ffn_silu.py`.
229+ - Workspace: 3 segments. Events: 3.
230+ 
231+- **Flash Attention (Q@K→softmax→P@V)**: 2C + 2V per KV block. See `references/output_example/flash_attn_basic.py`.
232+ - Iterative scope pattern with running max/sum.
233+ 
234+- **MLA Preprocess (4C + 4V)**: See §0.2.1 above for DAG and layout rules.
235+ - Workspace: 6 segments. Events: 6.
236+ - RoPE implementation: see `ascend_dsl_cv.py` §3.6 (uses `tl.ub_copy` for swap halves + `tl.vmul_scalar` for partial negate).
237+ - Per-head matmul: use head-major workspace layout.
238+ 
239+---
240+ 
241+### Generation Requirements
242+ 
243+Your task is to generate an **Ascend DSL (CV)** that replicates the computation in [module_fn], optimized for the input shape specified in Configurations.
244+ 
245+#### Key Rules
246+ 
247+1. **Dual Scope Structure**: Use `tl.scope('cube')` for matrix ops and `tl.scope('vector')` for element-wise/reduction ops.
248+ 
249+2. **Layouts**: Define 2D layouts for all global tensors using `tl.make_layout(tl.make_shape(...), tl.make_stride(...))`.
250+ 
251+3. **Matrix Compute**: Use `tl.dot(A_ptr, A_layout, B_ptr, B_layout, C_ptr, C_layout, actual_block_shape)` within `tl.scope('cube')`.
252+ 
253+4. **Cross-Core Sync**: Use `tl.cross_core_set(event_id)` / `tl.cross_core_wait(event_id)` at each Cube↔Vector boundary.
254+ 
255+5. **Workspace**: Host allocates workspace tensors for intermediates that cross Cube↔Vector boundaries.
256+ 
257+6. **Tiling in Kernel**: Tiling constants (L1_M, L1_N, etc.) defined inside kernel. Host only passes problem sizes.
258+ 
259+7. **Subcore Partitioning**: Vector scope may use `tl.get_num_sub_blocks()` / `tl.get_sub_block_id()` for parallel row processing.
260+ 
261+8. **Vector compute patterns**: See `ascend_dsl_cv.py` §3.5 (activations) and §3.6 (RoPE) for standard implementations.
262+ 
263+#### Host Function Requirements
264+- Read input tensor shapes and pass problem sizes into the kernel
265+- Allocate workspace tensors as needed
266+- Launch kernel with `kernel_name[core_num](args...)`
267+ 
268+#### Kernel Function Requirements
269+- Define tiling constants at the top
270+- Define global layouts for all tensors
271+- Include a task partition comment block explaining core assignment
272+- Use one outer task loop: `for task in range(aicore_id, total, aicore_num)`
273+- Place `tl.scope('cube')` and `tl.scope('vector')` inside the task loop
274+ 
275+Natural-language comments are mandatory and are part of the DSL.
@@ -0,0 +1,15 @@
1+# dsl-baseline-generation-cv 参考示例
2+ 
3+本目录收录 Cube+Vector(CV)融合算子的 AscendDSL baseline 样例,供本 skill 由
4+functional PyTorch 生成含 `tl.scope('cube')` / `tl.scope('vector')` 结构的 DSL 时对照。
5+ 
6+目录构成:
7+ 
8+- `ascend_dsl_cv.py` — CV DSL 知识库(常量 `ASCEND_DSL_CV_KNOWLEDGE`),按章节组织
9+ 多 scope 布局、workspace 分段、跨核事件、激活与 RoPE 等实现模式
10+- `input_example/<op>.py` — 输入侧:算子的 functional PyTorch 实现
11+- `output_example/<op>.py` — 输出侧:对应的 CV DSL baseline
12+ 
13+已收录算子:`matmul_add`、`matmul_gelu`、`matmul_swiglu`、`matmul_bias_relu`、
14+`matmul_add_rmsnorm`、`rms_matmul_scale`、`ffn_silu`、`conv2d_1x1`、`conv2d_bias`、
15+`flash_attn_basic`。
@@ -0,0 +1,38 @@
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+import torch
12+import torch.nn as nn
13+import torch.nn.functional as F
14+ 
15+ 
16+class Model(nn.Module):
17+ def __init__(self):
18+ super(Model, self).__init__()
19+ 
20+ def forward(self, x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
21+ return F.conv2d(x, weight, bias=None, stride=1, padding=0)
22+ 
23+ 
24+N = 2
25+CIN = 64
26+H = 16
27+W = 16
28+COUT = 128
29+ 
30+ 
31+def get_inputs():
32+ x = torch.randn(N, CIN, H, W, dtype=torch.float16)
33+ weight = torch.randn(COUT, CIN, 1, 1, dtype=torch.float16)
34+ return [x, weight]
35+ 
36+ 
37+def get_init_inputs():
38+ return []
@@ -0,0 +1,41 @@
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+import torch
12+import torch.nn as nn
13+import torch.nn.functional as F
14+ 
15+ 
16+class Model(nn.Module):
17+ def __init__(self):
18+ super(Model, self).__init__()
19+ 
20+ def forward(self, x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:
21+ return F.conv2d(x, weight, bias=bias, stride=1, padding=1)
22+ 
23+ 
24+N = 2
25+CIN = 3
26+H = 32
27+W = 32
28+COUT = 16
29+K_H = 3
30+K_W = 3
31+ 
32+ 
33+def get_inputs():
34+ x = torch.randn(N, CIN, H, W, dtype=torch.float16)
35+ weight = torch.randn(COUT, CIN, K_H, K_W, dtype=torch.float16)
36+ bias = torch.randn(COUT, dtype=torch.float16)
37+ return [x, weight, bias]
38+ 
39+ 
40+def get_init_inputs():
41+ return []
@@ -0,0 +1,39 @@
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+import torch
12+import torch.nn as nn
13+import torch.nn.functional as F
14+ 
15+ 
16+class Model(nn.Module):
17+ def __init__(self):
18+ super(Model, self).__init__()
19+ 
20+ def forward(self, X: torch.Tensor, W1: torch.Tensor, W2: torch.Tensor) -> torch.Tensor:
21+ hidden = F.silu(torch.matmul(X, W1))
22+ return torch.matmul(hidden, W2)
23+ 
24+ 
25+M = 1024
26+K = 1024
27+N1 = 2048
28+N2 = 1024
29+ 
30+ 
31+def get_inputs():
32+ X = torch.randn(M, K, dtype=torch.float16)
33+ W1 = torch.randn(K, N1, dtype=torch.float16)
34+ W2 = torch.randn(N1, N2, dtype=torch.float16)
35+ return [X, W1, W2]
36+ 
37+ 
38+def get_init_inputs():
39+ return []
@@ -0,0 +1,44 @@
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+import math
12+ 
13+import torch
14+import torch.nn as nn
15+import torch.nn.functional as F
16+ 
17+ 
18+class Model(nn.Module):
19+ def __init__(self):
20+ super(Model, self).__init__()
21+ 
22+ def forward(self, Q: torch.Tensor, K: torch.Tensor, V: torch.Tensor) -> torch.Tensor:
23+ # Standard scaled dot-product attention
24+ # Q: (M, D), K: (N, D), V: (N, D), output: (M, D)
25+ scale = 1.0 / math.sqrt(Q.shape[-1])
26+ scores = torch.matmul(Q, K.transpose(-2, -1)) * scale # (M, N)
27+ probs = F.softmax(scores, dim=-1) # (M, N)
28+ return torch.matmul(probs, V) # (M, D)
29+ 
30+ 
31+M = 1024
32+N = 1024
33+D = 128
34+ 
35+ 
36+def get_inputs():
37+ Q = torch.randn(M, D, dtype=torch.float16)
38+ K = torch.randn(N, D, dtype=torch.float16)
39+ V = torch.randn(N, D, dtype=torch.float16)
40+ return [Q, K, V]
41+ 
42+ 
43+def get_init_inputs():
44+ return []
@@ -0,0 +1,36 @@
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+import torch
12+import torch.nn as nn
13+ 
14+ 
15+class Model(nn.Module):
16+ def __init__(self):
17+ super(Model, self).__init__()
18+ 
19+ def forward(self, A: torch.Tensor, B: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
20+ return torch.matmul(A, B) + residual
21+ 
22+ 
23+M = 1024
24+K = 1024
25+N = 1024
26+ 
27+ 
28+def get_inputs():
29+ A = torch.randn(M, K, dtype=torch.float16)
30+ B = torch.randn(K, N, dtype=torch.float16)
31+ residual = torch.randn(M, N, dtype=torch.float16)
32+ return [A, B, residual]
33+ 
34+ 
35+def get_init_inputs():
36+ return []
@@ -0,0 +1,44 @@
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+import torch
12+import torch.nn as nn
13+import torch.nn.functional as F
14+ 
15+ 
16+class Model(nn.Module):
17+ def __init__(self):
18+ super(Model, self).__init__()
19+ 
20+ def forward(self, A: torch.Tensor, B: torch.Tensor, residual: torch.Tensor,
21+ gamma: torch.Tensor, eps: float = 1e-6) -> tuple:
22+ mm = torch.matmul(A, B)
23+ x_add = mm + residual
24+ # RmsNorm
25+ rms = torch.sqrt(torch.mean(x_add ** 2, dim=-1, keepdim=True) + eps)
26+ y = x_add / rms * gamma
27+ return y, x_add
28+ 
29+ 
30+M = 1024
31+K = 1024
32+N = 1024
33+ 
34+ 
35+def get_inputs():
36+ A = torch.randn(M, K, dtype=torch.float16)
37+ B = torch.randn(K, N, dtype=torch.float16)
38+ residual = torch.randn(M, N, dtype=torch.float16)
39+ gamma = torch.randn(N, dtype=torch.float16)
40+ return [A, B, residual, gamma]
41+ 
42+ 
43+def get_init_inputs():
44+ return []
@@ -0,0 +1,37 @@
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+import torch
12+import torch.nn as nn
13+import torch.nn.functional as F
14+ 
15+ 
16+class Model(nn.Module):
17+ def __init__(self):
18+ super(Model, self).__init__()
19+ 
20+ def forward(self, A: torch.Tensor, B: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:
21+ return F.relu(torch.matmul(A, B) + bias)
22+ 
23+ 
24+M = 1024
25+K = 1024
26+N = 1024
27+ 
28+ 
29+def get_inputs():
30+ A = torch.randn(M, K, dtype=torch.float16)
31+ B = torch.randn(K, N, dtype=torch.float16)
32+ bias = torch.randn(N, dtype=torch.float16)
33+ return [A, B, bias]
34+ 
35+ 
36+def get_init_inputs():
37+ return []
@@ -0,0 +1,36 @@
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+import torch
12+import torch.nn as nn
13+import torch.nn.functional as F
14+ 
15+ 
16+class Model(nn.Module):
17+ def __init__(self):
18+ super(Model, self).__init__()
19+ 
20+ def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
21+ return F.gelu(torch.matmul(A, B))
22+ 
23+ 
24+M = 1024
25+K = 1024
26+N = 1024
27+ 
28+ 
29+def get_inputs():
30+ A = torch.randn(M, K, dtype=torch.float16)
31+ B = torch.randn(K, N, dtype=torch.float16)
32+ return [A, B]
33+ 
34+ 
35+def get_init_inputs():
36+ return []
@@ -0,0 +1,39 @@
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+import torch
12+import torch.nn as nn
13+import torch.nn.functional as F
14+ 
15+ 
16+class Model(nn.Module):
17+ def __init__(self):
18+ super(Model, self).__init__()
19+ 
20+ def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
21+ mm = A @ B # (M, 2*N)
22+ left, right = mm.chunk(2, dim=-1)
23+ Y = F.silu(left) * right # (M, N)
24+ return Y
25+ 
26+ 
27+M = 1024
28+K = 1024
29+N = 512
30+ 
31+ 
32+def get_inputs():
33+ A = torch.randn(M, K, dtype=torch.float16)
34+ B = torch.randn(K, 2 * N, dtype=torch.float16)
35+ return [A, B]
36+ 
37+ 
38+def get_init_inputs():
39+ return []
@@ -0,0 +1,37 @@
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+import torch
12+import torch.nn as nn
13+import torch.nn.functional as F
14+ 
15+ 
16+class Model(nn.Module):
17+ def __init__(self):
18+ super(Model, self).__init__()
19+ 
20+ def forward(self, x: torch.Tensor, weight: torch.Tensor, norm_eps: float = 1e-6) -> torch.Tensor:
21+ B, S, N, D = x.shape
22+ x_rs = x.reshape(B, S, N * D)
23+ inv_rms = torch.rsqrt(x_rs.square().mean(-1, keepdim=True) + norm_eps)
24+ return inv_rms * torch.matmul(x_rs, weight)
25+ 
26+BATCH, SEQ, NUM_HEADS, HEAD_DIM = 16, 256, 4, 512
27+TOTAL = 2 * NUM_HEADS + NUM_HEADS * NUM_HEADS
28+ 
29+ 
30+def get_inputs():
31+ x = torch.rand(BATCH, SEQ, NUM_HEADS, HEAD_DIM).half()
32+ weight = torch.rand(NUM_HEADS * HEAD_DIM, TOTAL).half()
33+ return [x, weight]
34+ 
35+ 
36+def get_init_inputs():
37+ return [] # No special initialization inputs needed
@@ -0,0 +1,89 @@
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+import tile.language as tl
12+import torch
13+ 
14+ 
15+@ascend_kernel
16+def conv2d_1x1_kernel(A, B, D, M, N, K):
17+ # ----------------------------------------------------------------------
18+ # 1. Tiling & Layout Configuration
19+ # ----------------------------------------------------------------------
20+ # 1x1 conv is equivalent to matmul:
21+ # A = input reshaped to [N*H*W, Cin] (M x K)
22+ # B = weight reshaped to [Cin, Cout] (K x N)
23+ # D = output [N*H*W, Cout] (M x N)
24+ L1_M, L1_N = 128, 256
25+ DTYPE_C = tl.half # Fixpipe: Cube outputs fp16 directly, no Vector scope needed
26+ 
27+ # Global Layouts (row-major 2D after reshape)
28+ layout_a = tl.make_layout(tl.make_shape(M, K), tl.make_stride(K, 1))
29+ layout_b = tl.make_layout(tl.make_shape(K, N), tl.make_stride(N, 1))
30+ layout_d = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
31+ 
32+ # ----------------------------------------------------------------------
33+ # 任务核间划分说明
34+ # ----------------------------------------------------------------------
35+ # 1) 将输出矩阵按 (M, N) 两个轴切分为 grid:
36+ # block_m in [0, tile_count_m), block_n in [0, tile_count_n)
37+ # 2) 每个任务对应一个 L1_M * L1_N 的 tile。
38+ # 3) 任务按一维 task_id 分配给 AICore。
39+ # 4) Fixpipe 模式:Cube 直接输出 fp16,无 Vector scope。
40+ tile_count_m = tl.cdiv(M, L1_M)
41+ tile_count_n = tl.cdiv(N, L1_N)
42+ total_tasks = tile_count_m * tile_count_n
43+ 
44+ aicore_id = tl.program_id()
45+ aicore_num = tl.num_programs()
46+ 
47+ # ----------------------------------------------------------------------
48+ # 2. Per-task Fixpipe scheduling (Cube-only, no Vector)
49+ # ----------------------------------------------------------------------
50+ for task_id in range(aicore_id, total_tasks, aicore_num):
51+ block_m = task_id // tile_count_n
52+ block_n = task_id % tile_count_n
53+ actual_m = tl.min(L1_M, M - block_m * L1_M)
54+ actual_n = tl.min(L1_N, N - block_n * L1_N)
55+ 
56+ with tl.scope('cube'):
57+ actual_block_shape = tl.make_shape(actual_m, actual_n, K)
58+ 
59+ coord_a = (block_m * L1_M, 0)
60+ coord_b = (0, block_n * L1_N)
61+ coord_d = (block_m * L1_M, block_n * L1_N)
62+ 
63+ with tl.compute():
64+ tl.dot(A[layout_a.get_offset(coord=coord_a)], layout_a,
65+ B[layout_b.get_offset(coord=coord_b)], layout_b,
66+ D[layout_d.get_offset(coord=coord_d)], layout_d,
67+ actual_block_shape)
68+ 
69+ 
70+# --- Host 调用 ---
71+def host_main(x: torch.Tensor, weight: torch.Tensor, D: torch.Tensor):
72+ N_batch, Cin, H, W = x.shape
73+ Cout = weight.shape[0]
74+ 
75+ # 1x1 conv reshape: fmap [N,Cin,H,W] → A [N*H*W, Cin]
76+ M = N_batch * H * W
77+ K = Cin
78+ N_out = Cout
79+ A = x.permute(0, 2, 3, 1).reshape(M, K).contiguous()
80+ # weight [Cout, Cin, 1, 1] → B [Cin, Cout]
81+ B = weight.squeeze(-1).squeeze(-1).t().contiguous()
82+ 
83+ core_num = tl.get_core_num()
84+ 
85+ conv2d_1x1_kernel[core_num](
86+ A, B, D,
87+ M, N_out, K
88+ )
89+ # Output D is [M, Cout], reshape back to [N, Cout, H, W] by caller
@@ -0,0 +1,102 @@
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+import tile.language as tl
12+import torch
13+ 
14+ 
15+@ascend_kernel
16+def conv2d_bias_kernel(fmap, weight, bias, output,
17+ batch, Cin, H, W, Cout, kH, kW, sH, sW, pH, pW):
18+ # ----------------------------------------------------------------------
19+ # 1. Convolution Parameters
20+ # ----------------------------------------------------------------------
21+ # General Conv2d uses tl.conv2d_dot() which maps to Catlass BlockConv.
22+ # BlockConv internally handles:
23+ # - im2col via Load3Dv2 (L1 → L0A)
24+ # - Matrix multiply via Mmad (L0A × L0B → L0C)
25+ # - Bias addition via BT buffer
26+ # - Output via Fixpipe (L0C → GM)
27+ # No Vector scope needed for conv + bias only (ConvBias pattern).
28+ 
29+ DTYPE_OUT = tl.half
30+ 
31+ conv_params = tl.make_conv_params(
32+ H=H, W=W, kH=kH, kW=kW,
33+ strideH=sH, strideW=sW,
34+ padH=pH, padW=pW,
35+ Cin=Cin, Cout=Cout,
36+ bias_ptr=bias
37+ )
38+ 
39+ Ho = (H + 2 * pH - kH) // sH + 1
40+ Wo = (W + 2 * pW - kW) // sW + 1
41+ 
42+ # ----------------------------------------------------------------------
43+ # 2. Layouts (hardware-specific formats)
44+ # ----------------------------------------------------------------------
45+ # Feature map: NC1HWC0 format (C0=16 for fp16)
46+ # shape: [batch, D=1, Cin1, H*W, C0]
47+ # Weight: FracZ format (KDC1KHKWN1N0C0)
48+ # shape: [Kd*Cin1*kH*kW, Cout1, N0=16, C0=16]
49+ # Output: NC1HWC0 format
50+ # shape: [batch, D=1, Cout1, Ho*Wo, C0]
51+ C0 = 16
52+ Cin1 = tl.cdiv(Cin, C0)
53+ Cout1 = tl.cdiv(Cout, C0)
54+ layout_fmap = tl.make_ndc1hwc0_layout(batch, 1, Cin1, H * W, C0)
55+ layout_weight = tl.make_fracz_layout(Cin1 * kH * kW, Cout1, C0)
56+ layout_out = tl.make_ndc1hwc0_layout(batch, 1, Cout1, Ho * Wo, C0)
57+ 
58+ # ----------------------------------------------------------------------
59+ # 任务核间划分说明
60+ # ----------------------------------------------------------------------
61+ # BlockConv + ConvBias handles task partitioning internally via
62+ # Conv3dIdentityBlockSwizzle. The block scheduler divides the output
63+ # tensor along (batch, Cout1, Ho*Wo) dimensions and assigns tiles
64+ # to AICore units. Each core processes one or more output tiles.
65+ # No manual scheduling loop needed — BlockConv manages everything.
66+ 
67+ aicore_id = tl.program_id()
68+ aicore_num = tl.num_programs()
69+ 
70+ # ----------------------------------------------------------------------
71+ # 3. Cube-only Conv2d + Bias (ConvBias pattern)
72+ # ----------------------------------------------------------------------
73+ # tl.conv2d_dot() encapsulates the full convolution pipeline:
74+ # GM→L1 (fmap + weight + bias)
75+ # L1→L0A (im2col via Load3Dv2)
76+ # L1→L0B (weight load)
77+ # L0A×L0B→L0C (Mmad)
78+ # L0C + bias → GM (Fixpipe)
79+ with tl.scope('cube'):
80+ conv_shape = tl.make_conv_shape(batch, Ho, Wo, Cout)
81+ tl.conv2d_dot(
82+ fmap, layout_fmap,
83+ weight, layout_weight,
84+ output, layout_out,
85+ conv_shape, conv_params
86+ )
87+ 
88+ 
89+# --- Host 调用 ---
90+def host_main(fmap: torch.Tensor, weight: torch.Tensor,
91+ bias: torch.Tensor, output: torch.Tensor):
92+ batch, Cin, H, W = fmap.shape
93+ Cout, _, kH, kW = weight.shape
94+ sH, sW = 1, 1
95+ pH, pW = 1, 1
96+ 
97+ core_num = tl.get_core_num()
98+ 
99+ conv2d_bias_kernel[core_num](
100+ fmap, weight, bias, output,
101+ batch, Cin, H, W, Cout, kH, kW, sH, sW, pH, pW
102+ )
@@ -0,0 +1,210 @@
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+import tile.language as tl
12+import torch
13+ 
14+ 
15+@ascend_kernel
16+def ffn_silu_kernel(X, W1, W2, Y, workspace_mm1, workspace_act, workspace_mm2, M, N1, N2, K):
17+ # ----------------------------------------------------------------------
18+ # 1. Tiling & Layout Configuration
19+ # ----------------------------------------------------------------------
20+ # FFN: X @ W1 → SiLU → @ W2 → Y
21+ # Stage 1 (Cube): MM1: X(M,K) @ W1(K,N1) → workspace_mm1(M,N1) fp32
22+ # Stage 2 (Vector): SiLU(workspace_mm1) → workspace_act(M,N1) fp16
23+ # Stage 3 (Cube): MM2: workspace_act(M,N1) @ W2(N1,N2) → workspace_mm2(M,N2) fp32
24+ # Stage 4 (Vector): Cast(workspace_mm2) → Y(M,N2) fp16
25+ 
26+ L1_M, L1_N = 128, 256
27+ DTYPE_MM = tl.float32
28+ DTYPE_ACT = tl.half
29+ DTYPE_OUT = tl.half
30+ 
31+ layout_x = tl.make_layout(tl.make_shape(M, K), tl.make_stride(K, 1))
32+ layout_w1 = tl.make_layout(tl.make_shape(K, N1), tl.make_stride(N1, 1))
33+ layout_mm1 = tl.make_layout(tl.make_shape(M, N1), tl.make_stride(N1, 1))
34+ layout_act = tl.make_layout(tl.make_shape(M, N1), tl.make_stride(N1, 1))
35+ layout_w2 = tl.make_layout(tl.make_shape(N1, N2), tl.make_stride(N2, 1))
36+ layout_mm2 = tl.make_layout(tl.make_shape(M, N2), tl.make_stride(N2, 1))
37+ layout_y = tl.make_layout(tl.make_shape(M, N2), tl.make_stride(N2, 1))
38+ 
39+ # ----------------------------------------------------------------------
40+ # 数据依赖图(Data Dependency DAG)
41+ # ----------------------------------------------------------------------
42+ # [Cube] MM1(X, W1) → ws_mm1 ──sync(mm1_done)──→ [Vector] SiLU(ws_mm1) → ws_act
43+ # ──sync(act_done)──→
44+ # [Cube] MM2(ws_act, W2) → ws_mm2 ──sync(mm2_done)──→ [Vector] Cast(ws_mm2) → Y
45+ #
46+ # 同步事件:3 个 cross-core events
47+ # Workspace:3 段(ws_mm1: M×N1×4, ws_act: M×N1×2, ws_mm2: M×N2×4)
48+ # UB 复用:Stage 2 和 Stage 4 的 UB 可顺序复用(阶段间不重叠)
49+ 
50+ tile_count_m = tl.cdiv(M, L1_M)
51+ tile_count_n1 = tl.cdiv(N1, L1_N)
52+ tile_count_n2 = tl.cdiv(N2, L1_N)
53+ 
54+ mm1_done_id = 0
55+ act_done_id = 1
56+ mm2_done_id = 2
57+ 
58+ aicore_id = tl.program_id()
59+ aicore_num = tl.num_programs()
60+ num_sub = tl.get_num_sub_blocks()
61+ subcore_id = tl.get_sub_block_id()
62+ 
63+ # UB buffers (reused across stages, peak ~64KB per stage within 192KB)
64+ compute_length = (L1_M // num_sub) * L1_N
65+ ub_in = tl.alloc_ub(compute_length, dtype=DTYPE_MM)
66+ ub_compute = tl.alloc_ub(compute_length, dtype=DTYPE_MM)
67+ ub_out = tl.alloc_ub(compute_length, dtype=DTYPE_ACT)
68+ 
69+ # ----------------------------------------------------------------------
70+ # 2. Per-block_m fused 4-stage scheduling
71+ # ----------------------------------------------------------------------
72+ for block_m in range(aicore_id, tile_count_m, aicore_num):
73+ actual_m = tl.min(L1_M, M - block_m * L1_M)
74+ 
75+ # ============ Stage 1: Cube MM1 (X @ W1 → workspace_mm1) ============
76+ with tl.scope('cube'):
77+ for block_n in range(tile_count_n1):
78+ actual_n1 = tl.min(L1_N, N1 - block_n * L1_N)
79+ actual_shape = tl.make_shape(actual_m, actual_n1, K)
80+ 
81+ coord_x = (block_m * L1_M, 0)
82+ coord_w1 = (0, block_n * L1_N)
83+ coord_mm1 = (block_m * L1_M, block_n * L1_N)
84+ 
85+ with tl.compute():
86+ tl.dot(
87+ X[layout_x.get_offset(coord=coord_x)], layout_x,
88+ W1[layout_w1.get_offset(coord=coord_w1)], layout_w1,
89+ workspace_mm1[layout_mm1.get_offset(coord=coord_mm1)], layout_mm1,
90+ actual_shape,
91+ )
92+ 
93+ tl.cross_core_set(mm1_done_id)
94+ 
95+ # ============ Stage 2: Vector SiLU (workspace_mm1 → workspace_act) ============
96+ with tl.scope('vector'):
97+ tl.cross_core_wait(mm1_done_id)
98+ 
99+ sub_m = tl.cdiv(actual_m, num_sub)
100+ sub_offset_m = subcore_id * sub_m
101+ curr_sub_m = tl.min(sub_m, actual_m - sub_offset_m)
102+ 
103+ if curr_sub_m > 0:
104+ curr_gm_row = (block_m * L1_M) + sub_offset_m
105+ 
106+ for block_n in range(tile_count_n1):
107+ col_start = block_n * L1_N
108+ curr_n1 = tl.min(L1_N, N1 - col_start)
109+ 
110+ ub_shape = tl.make_shape(curr_sub_m, curr_n1)
111+ ub_layout = tl.make_layout(ub_shape, tl.make_stride(L1_N, 1))
112+ 
113+ gm_mm1_offset = layout_mm1.get_offset(coord=(curr_gm_row, col_start))
114+ gm_act_offset = layout_act.get_offset(coord=(curr_gm_row, col_start))
115+ 
116+ with tl.copyin():
117+ tl.load_2d(workspace_mm1[gm_mm1_offset],
118+ tl.make_layout(ub_shape, layout_mm1.stride()),
119+ ub_in, ub_layout)
120+ 
121+ with tl.compute():
122+ sub_length = curr_sub_m * curr_n1
123+ # SiLU(x) = x / (1 + exp(-x))
124+ tl.vmul_scalar(ub_compute, ub_in, scalar_value=-1.0, count=sub_length)
125+ tl.vexp(ub_compute, ub_compute, count=sub_length)
126+ tl.vadd_scalar(ub_compute, ub_compute, scalar_value=1.0, count=sub_length)
127+ tl.vdiv(ub_compute, ub_in, ub_compute, count=sub_length)
128+ # Cast fp32 → fp16
129+ tl.vcast(ub_out, ub_compute, count=sub_length)
130+ 
131+ with tl.copyout():
132+ tl.store_2d(workspace_act[gm_act_offset],
133+ tl.make_layout(ub_shape, layout_act.stride()),
134+ ub_out, ub_layout)
135+ 
136+ tl.cross_core_set(act_done_id)
137+ 
138+ # ============ Stage 3: Cube MM2 (workspace_act @ W2 → workspace_mm2) ============
139+ with tl.scope('cube'):
140+ tl.cross_core_wait(act_done_id)
141+ 
142+ for block_n in range(tile_count_n2):
143+ actual_n2 = tl.min(L1_N, N2 - block_n * L1_N)
144+ actual_shape2 = tl.make_shape(actual_m, actual_n2, N1)
145+ 
146+ coord_act = (block_m * L1_M, 0)
147+ coord_w2 = (0, block_n * L1_N)
148+ coord_mm2 = (block_m * L1_M, block_n * L1_N)
149+ 
150+ with tl.compute():
151+ tl.dot(
152+ workspace_act[layout_act.get_offset(coord=coord_act)], layout_act,
153+ W2[layout_w2.get_offset(coord=coord_w2)], layout_w2,
154+ workspace_mm2[layout_mm2.get_offset(coord=coord_mm2)], layout_mm2,
155+ actual_shape2,
156+ )
157+ 
158+ tl.cross_core_set(mm2_done_id)
159+ 
160+ # ============ Stage 4: Vector Cast (workspace_mm2 → Y) ============
161+ with tl.scope('vector'):
162+ tl.cross_core_wait(mm2_done_id)
163+ 
164+ # Reuse UB buffers from Stage 2 (stage-sequential reuse)
165+ if curr_sub_m > 0:
166+ for block_n in range(tile_count_n2):
167+ col_start = block_n * L1_N
168+ curr_n2 = tl.min(L1_N, N2 - col_start)
169+ 
170+ ub_shape2 = tl.make_shape(curr_sub_m, curr_n2)
171+ ub_layout2 = tl.make_layout(ub_shape2, tl.make_stride(L1_N, 1))
172+ 
173+ gm_mm2_offset = layout_mm2.get_offset(coord=(curr_gm_row, col_start))
174+ gm_y_offset = layout_y.get_offset(coord=(curr_gm_row, col_start))
175+ 
176+ with tl.copyin():
177+ tl.load_2d(workspace_mm2[gm_mm2_offset],
178+ tl.make_layout(ub_shape2, layout_mm2.stride()),
179+ ub_in, ub_layout2)
180+ 
181+ with tl.compute():
182+ sub_length2 = curr_sub_m * curr_n2
183+ tl.vcast(ub_out, ub_in, count=sub_length2)
184+ 
185+ with tl.copyout():
186+ tl.store_2d(Y[gm_y_offset],
187+ tl.make_layout(ub_shape2, layout_y.stride()),
188+ ub_out, ub_layout2)
189+ 
190+ 
191+# --- Host 调用 ---
192+def host_main(X: torch.Tensor, W1: torch.Tensor, W2: torch.Tensor, Y: torch.Tensor):
193+ M, K = X.shape
194+ K, N1 = W1.shape
195+ N1, N2 = W2.shape
196+ 
197+ # 3 workspace segments:
198+ # ws_mm1: M × N1 × sizeof(fp32) — matmul1 output accumulator
199+ # ws_act: M × N1 × sizeof(fp16) — activation output (Cube input for MM2)
200+ # ws_mm2: M × N2 × sizeof(fp32) — matmul2 output accumulator
201+ workspace_mm1 = torch.empty(M * N1, dtype=torch.float32, device=X.device)
202+ workspace_act = torch.empty(M * N1, dtype=torch.float16, device=X.device)
203+ workspace_mm2 = torch.empty(M * N2, dtype=torch.float32, device=X.device)
204+ core_num = tl.get_core_num()
205+ 
206+ ffn_silu_kernel[core_num](
207+ X, W1, W2, Y,
208+ workspace_mm1, workspace_act, workspace_mm2,
209+ M, N1, N2, K
210+ )
@@ -0,0 +1,294 @@
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+import math
12+ 
13+import tile.language as tl
14+import torch
15+ 
16+ 
17+@ascend_kernel
18+def flash_attn_basic_kernel(Q, K, V, O, workspace_score, workspace_prob,
19+ workspace_out, workspace_max, workspace_sum,
20+ M, N, D, Bk, scale):
21+ # ----------------------------------------------------------------------
22+ # 1. Tiling & Layout Configuration
23+ # ----------------------------------------------------------------------
24+ # Flash Attention (basic, single-head, no causal mask):
25+ # Per KV block b:
26+ # [Cube] S_b = Q @ K_b^T (M, Bk) fp32
27+ # [Vector] P_b = online_softmax(S_b, running_max, running_sum) (M, Bk) fp16
28+ # [Cube] O_b = P_b @ V_b (M, D) fp32
29+ # [Vector] O += scale * O_b (accumulate with rescaling)
30+ # After all KV blocks:
31+ # [Vector] O = O / running_sum (final normalize)
32+ 
33+ L1_M = 128
34+ DTYPE_SCORE = tl.float32
35+ DTYPE_PROB = tl.half
36+ DTYPE_OUT = tl.float32
37+ DTYPE_FINAL = tl.half
38+ 
39+ layout_q = tl.make_layout(tl.make_shape(M, D), tl.make_stride(D, 1))
40+ layout_k = tl.make_layout(tl.make_shape(N, D), tl.make_stride(D, 1)) # K stored as (N, D)
41+ layout_v = tl.make_layout(tl.make_shape(N, D), tl.make_stride(D, 1))
42+ layout_score = tl.make_layout(tl.make_shape(M, Bk), tl.make_stride(Bk, 1))
43+ layout_prob = tl.make_layout(tl.make_shape(M, Bk), tl.make_stride(Bk, 1))
44+ layout_out = tl.make_layout(tl.make_shape(M, D), tl.make_stride(D, 1))
45+ layout_o = tl.make_layout(tl.make_shape(M, D), tl.make_stride(D, 1))
46+ 
47+ # ----------------------------------------------------------------------
48+ # 数据依赖图(Data Dependency DAG)—— 每个 KV block 内
49+ # ----------------------------------------------------------------------
50+ # [Cube] Q(M,D) @ K_b(Bk,D)^T → ws_score(M,Bk) fp32
51+ # ──sync(score_ready)──→
52+ # [Vector] online_softmax(ws_score, max, sum) → ws_prob(M,Bk) fp16
53+ # ──sync(prob_ready)──→
54+ # [Cube] ws_prob(M,Bk) @ V_b(Bk,D) → ws_out(M,D) fp32
55+ # ──sync(out_ready)──→
56+ # [Vector] O = O * rescale + ws_out, update max/sum
57+ # ──sync(update_done)──→ [next KV block]
58+ #
59+ # 同步事件:4 per KV block iteration (score_ready, prob_ready, out_ready, update_done)
60+ # Workspace:ws_score(M×Bk×4), ws_prob(M×Bk×2), ws_out(M×D×4), max(M×4), sum(M×4)
61+ 
62+ kv_blocks = tl.cdiv(N, Bk)
63+ 
64+ score_ready_id = 0
65+ prob_ready_id = 1
66+ out_ready_id = 2
67+ update_done_id = 3
68+ 
69+ aicore_id = tl.program_id()
70+ aicore_num = tl.num_programs()
71+ num_sub = tl.get_num_sub_blocks()
72+ subcore_id = tl.get_sub_block_id()
73+ 
74+ # UB buffers for vector processing (reused across KV block iterations)
75+ # Peak UB: score_tile + prob_tile + reduce_temps ≈ 128KB (within 192KB)
76+ ub_score_row = tl.alloc_ub(Bk, dtype=DTYPE_SCORE)
77+ ub_prob_row = tl.alloc_ub(Bk, dtype=DTYPE_PROB)
78+ ub_reduce = tl.alloc_ub(Bk, dtype=DTYPE_SCORE)
79+ ub_out_row = tl.alloc_ub(D, dtype=DTYPE_OUT)
80+ ub_acc_row = tl.alloc_ub(D, dtype=DTYPE_OUT)
81+ ub_final = tl.alloc_ub(D, dtype=DTYPE_FINAL)
82+ ub_scalar = tl.alloc_ub(1, dtype=DTYPE_SCORE)
83+ 
84+ # ----------------------------------------------------------------------
85+ # 2. Per-block_m scheduling (core-parallel over M dimension)
86+ # ----------------------------------------------------------------------
87+ tile_count_m = tl.cdiv(M, L1_M)
88+ 
89+ for block_m in range(aicore_id, tile_count_m, aicore_num):
90+ actual_m = tl.min(L1_M, M - block_m * L1_M)
91+ row_start = block_m * L1_M
92+ 
93+ # Initialize running max to -inf, running sum to 0
94+ sub_m = tl.cdiv(actual_m, num_sub)
95+ sub_offset_m = subcore_id * sub_m
96+ curr_sub_m = tl.min(sub_m, actual_m - sub_offset_m)
97+ 
98+ # --- KV block iteration (core computation loop) ---
99+ for kv_b in range(kv_blocks):
100+ kv_start = kv_b * Bk
101+ actual_bk = tl.min(Bk, N - kv_start)
102+ 
103+ # ============ Cube: Q @ K_b^T → workspace_score ============
104+ with tl.scope('cube'):
105+ if kv_b > 0:
106+ tl.cross_core_wait(update_done_id)
107+ 
108+ actual_shape_bmm1 = tl.make_shape(actual_m, actual_bk, D)
109+ 
110+ coord_q = (row_start, 0)
111+ coord_k = (kv_start, 0) # K is (N, D), we need K_b rows [kv_start:kv_start+Bk]
112+ coord_s = (row_start, 0)
113+ 
114+ with tl.compute():
115+ # Q(M,D) @ K_b^T(D,Bk) → S(M,Bk)
116+ # Note: K is stored as (N,D), transpose gives (D,Bk)
117+ tl.dot(
118+ Q[layout_q.get_offset(coord=coord_q)], layout_q,
119+ K[layout_k.get_offset(coord=coord_k)], layout_k,
120+ workspace_score[layout_score.get_offset(coord=coord_s)], layout_score,
121+ actual_shape_bmm1,
122+ )
123+ 
124+ tl.cross_core_set(score_ready_id)
125+ 
126+ # ============ Vector: online softmax ============
127+ with tl.scope('vector'):
128+ tl.cross_core_wait(score_ready_id)
129+ 
130+ if curr_sub_m > 0:
131+ gm_row_base = row_start + sub_offset_m
132+ 
133+ for r in range(curr_sub_m):
134+ row_id = gm_row_base + r
135+ gm_score_offset = layout_score.get_offset(coord=(row_id, 0))
136+ 
137+ with tl.copyin():
138+ tl.load(workspace_score[gm_score_offset + tl.arange(0, actual_bk)], ub_score_row)
139+ 
140+ with tl.compute():
141+ # Scale: S = S * scale
142+ tl.vmul_scalar(ub_score_row, ub_score_row, scalar_value=scale, count=actual_bk)
143+ 
144+ # Row max
145+ tl.reduce_max(ub_reduce, ub_score_row, ub_reduce)
146+ new_max = tl.extract_scalar(ub_reduce, 0)
147+ 
148+ # Load running max
149+ with tl.copyin():
150+ tl.load(workspace_max[row_id + tl.arange(0, 1)], ub_scalar)
151+ old_max = tl.extract_scalar(ub_scalar, 0)
152+ 
153+ if kv_b == 0:
154+ running_max = new_max
155+ else:
156+ running_max = max(old_max, new_max)
157+ 
158+ # exp(score - running_max)
159+ tl.vadd_scalar(ub_score_row, ub_score_row, scalar_value=-running_max, count=actual_bk)
160+ tl.vexp(ub_score_row, ub_score_row, count=actual_bk)
161+ 
162+ # Row sum of exp
163+ tl.reduce_sum(ub_reduce, ub_score_row, ub_reduce)
164+ new_sum = tl.extract_scalar(ub_reduce, 0)
165+ 
166+ # Rescale factor for previous accumulator
167+ if kv_b > 0:
168+ rescale = math.exp(old_max - running_max)
169+ # Load running sum, rescale
170+ with tl.copyin():
171+ tl.load(workspace_sum[row_id + tl.arange(0, 1)], ub_scalar)
172+ old_sum = tl.extract_scalar(ub_scalar, 0)
173+ running_sum = old_sum * rescale + new_sum
174+ 
175+ # Rescale output accumulator: O[row] *= rescale
176+ with tl.copyin():
177+ tl.load(O[layout_o.get_offset(coord=(row_id, 0)) + tl.arange(0, D)], ub_acc_row)
178+ tl.vmul_scalar(ub_acc_row, ub_acc_row, scalar_value=rescale, count=D)
179+ with tl.copyout():
180+ tl.store(O[layout_o.get_offset(coord=(row_id, 0)) + tl.arange(0, D)], ub_acc_row)
181+ else:
182+ running_sum = new_sum
183+ 
184+ # Store updated max and sum
185+ tl.set_scalar(ub_scalar, 0, running_max)
186+ with tl.copyout():
187+ tl.store(workspace_max[row_id + tl.arange(0, 1)], ub_scalar)
188+ tl.set_scalar(ub_scalar, 0, running_sum)
189+ with tl.copyout():
190+ tl.store(workspace_sum[row_id + tl.arange(0, 1)], ub_scalar)
191+ 
192+ # Cast prob to fp16 for next matmul
193+ tl.vcast(ub_prob_row, ub_score_row, count=actual_bk)
194+ 
195+ gm_prob_offset = layout_prob.get_offset(coord=(row_id, 0))
196+ with tl.copyout():
197+ tl.store(workspace_prob[gm_prob_offset + tl.arange(0, actual_bk)], ub_prob_row)
198+ 
199+ tl.cross_core_set(prob_ready_id)
200+ 
201+ # ============ Cube: P_b @ V_b → workspace_out ============
202+ with tl.scope('cube'):
203+ tl.cross_core_wait(prob_ready_id)
204+ 
205+ actual_shape_bmm2 = tl.make_shape(actual_m, D, actual_bk)
206+ 
207+ coord_p = (row_start, 0)
208+ coord_v = (kv_start, 0)
209+ coord_o = (row_start, 0)
210+ 
211+ with tl.compute():
212+ # P(M,Bk) @ V_b(Bk,D) → O_partial(M,D)
213+ tl.dot(
214+ workspace_prob[layout_prob.get_offset(coord=coord_p)], layout_prob,
215+ V[layout_v.get_offset(coord=coord_v)], layout_v,
216+ workspace_out[layout_out.get_offset(coord=coord_o)], layout_out,
217+ actual_shape_bmm2,
218+ )
219+ 
220+ tl.cross_core_set(out_ready_id)
221+ 
222+ # ============ Vector: O += O_partial ============
223+ with tl.scope('vector'):
224+ tl.cross_core_wait(out_ready_id)
225+ 
226+ if curr_sub_m > 0:
227+ for r in range(curr_sub_m):
228+ row_id = gm_row_base + r
229+ gm_out_offset = layout_out.get_offset(coord=(row_id, 0))
230+ gm_o_offset = layout_o.get_offset(coord=(row_id, 0))
231+ 
232+ with tl.copyin():
233+ tl.load(workspace_out[gm_out_offset + tl.arange(0, D)], ub_out_row)
234+ tl.load(O[gm_o_offset + tl.arange(0, D)], ub_acc_row)
235+ 
236+ with tl.compute():
237+ # O = O + O_partial (O was already rescaled in softmax stage)
238+ tl.vadd(ub_acc_row, ub_acc_row, ub_out_row, count=D)
239+ 
240+ with tl.copyout():
241+ tl.store(O[gm_o_offset + tl.arange(0, D)], ub_acc_row)
242+ 
243+ tl.cross_core_set(update_done_id)
244+ 
245+ # --- After all KV blocks: final normalize O = O / running_sum ---
246+ with tl.scope('vector'):
247+ if curr_sub_m > 0:
248+ for r in range(curr_sub_m):
249+ row_id = (row_start + sub_offset_m) + r
250+ gm_o_offset = layout_o.get_offset(coord=(row_id, 0))
251+ 
252+ with tl.copyin():
253+ tl.load(workspace_sum[row_id + tl.arange(0, 1)], ub_scalar)
254+ tl.load(O[gm_o_offset + tl.arange(0, D)], ub_acc_row)
255+ 
256+ with tl.compute():
257+ inv_sum = 1.0 / tl.extract_scalar(ub_scalar, 0)
258+ tl.vmul_scalar(ub_acc_row, ub_acc_row, scalar_value=inv_sum, count=D)
259+ tl.vcast(ub_final, ub_acc_row, count=D)
260+ 
261+ with tl.copyout():
262+ tl.store(O[gm_o_offset + tl.arange(0, D)], ub_final)
263+ 
264+ 
265+# --- Host 调用 ---
266+def host_main(Q: torch.Tensor, K: torch.Tensor, V: torch.Tensor, O: torch.Tensor):
267+ M, D = Q.shape
268+ N, D = K.shape
269+ Bk = 256 # KV block size
270+ 
271+ scale = 1.0 / math.sqrt(D)
272+ 
273+ # Workspace segments:
274+ # ws_score: M × Bk × sizeof(fp32) — attention score buffer
275+ # ws_prob: M × Bk × sizeof(fp16) — probability buffer
276+ # ws_out: M × D × sizeof(fp32) — partial output buffer
277+ # ws_max: M × sizeof(fp32) — running max per row
278+ # ws_sum: M × sizeof(fp32) — running sum per row
279+ workspace_score = torch.empty(M * Bk, dtype=torch.float32, device=Q.device)
280+ workspace_prob = torch.empty(M * Bk, dtype=torch.float16, device=Q.device)
281+ workspace_out = torch.empty(M * D, dtype=torch.float32, device=Q.device)
282+ workspace_max = torch.full((M,), float('-inf'), dtype=torch.float32, device=Q.device)
283+ workspace_sum = torch.zeros(M, dtype=torch.float32, device=Q.device)
284+ 
285+ # Initialize O to zero for accumulation
286+ O.zero_()
287+ 
288+ core_num = tl.get_core_num()
289+ 
290+ flash_attn_basic_kernel[core_num](
291+ Q, K, V, O,
292+ workspace_score, workspace_prob, workspace_out, workspace_max, workspace_sum,
293+ M, N, D, Bk, scale
294+ )
@@ -0,0 +1,144 @@
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+import tile.language as tl
12+import torch
13+ 
14+ 
15+@ascend_kernel
16+def matmul_add_kernel(A, B, residual, D, workspace, M, N, K):
17+ # ----------------------------------------------------------------------
18+ # 1. Tiling & Layout Configuration
19+ # ----------------------------------------------------------------------
20+ L1_M, L1_N = 128, 256
21+ DTYPE_C, DTYPE_D = tl.float32, tl.half
22+ 
23+ # Global Layouts
24+ layout_a = tl.make_layout(tl.make_shape(M, K), tl.make_stride(K, 1))
25+ layout_b = tl.make_layout(tl.make_shape(K, N), tl.make_stride(N, 1))
26+ layout_c = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
27+ layout_res = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
28+ layout_d = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
29+ 
30+ # c = a@b
31+ # d = c + residual
32+ 
33+ # ----------------------------------------------------------------------
34+ # 任务核间划分说明
35+ # ----------------------------------------------------------------------
36+ # 1) 将输出矩阵按 (M, N) 两个轴同时切分为 grid:
37+ # block_m in [0, tile_count_m), block_n in [0, tile_count_n)
38+ # 2) 每个任务对应一个 L1_M * L1_N 的 tile(边界 tile 为实际尺寸)。
39+ # 3) 任务按一维 task_id 分配给 AICore:
40+ # task_id = aicore_id + t * aicore_num
41+ # block_m = task_id // tile_count_n, block_n = task_id % tile_count_n
42+ # 4) 每个任务内先 cube 做 matmul,再 vector 做 add。
43+ tile_count_m = tl.cdiv(M, L1_M)
44+ tile_count_n = tl.cdiv(N, L1_N)
45+ total_tasks = tile_count_m * tile_count_n
46+ 
47+ matmul_ready_id = 0
48+ 
49+ aicore_id = tl.program_id()
50+ aicore_num = tl.num_programs()
51+ num_sub = tl.get_num_sub_blocks()
52+ subcore_id = tl.get_sub_block_id()
53+ compute_length = (L1_M // num_sub) * L1_N
54+ 
55+ ub_c = tl.alloc_ub(compute_length, dtype=DTYPE_C)
56+ ub_res = tl.alloc_ub(compute_length, dtype=DTYPE_D)
57+ ub_res_fp32 = tl.alloc_ub(compute_length, dtype=DTYPE_C)
58+ ub_d = tl.alloc_ub(compute_length, dtype=DTYPE_D)
59+ 
60+ # ----------------------------------------------------------------------
61+ # 2. Per-task fused scheduling
62+ # One outer loop drives cube and vector phases for one (block_m, block_n) tile.
63+ # ----------------------------------------------------------------------
64+ for task_id in range(aicore_id, total_tasks, aicore_num):
65+ block_m = task_id // tile_count_n
66+ block_n = task_id % tile_count_n
67+ actual_m = tl.min(L1_M, M - block_m * L1_M)
68+ actual_n = tl.min(L1_N, N - block_n * L1_N)
69+ 
70+ with tl.scope('cube'):
71+ actual_block_shape = tl.make_shape(actual_m, actual_n, K)
72+ 
73+ coord_a = (block_m * L1_M, 0)
74+ coord_b = (0, block_n * L1_N)
75+ coord_c = (block_m * L1_M, block_n * L1_N)
76+ 
77+ with tl.compute():
78+ tl.dot(A[layout_a.get_offset(coord=coord_a)], layout_a,
79+ B[layout_b.get_offset(coord=coord_b)], layout_b,
80+ workspace[layout_c.get_offset(coord=coord_c)], layout_c,
81+ actual_block_shape)
82+ 
83+ tl.cross_core_set(matmul_ready_id)
84+ 
85+ with tl.scope('vector'):
86+ tl.cross_core_wait(matmul_ready_id)
87+ 
88+ sub_m = tl.cdiv(actual_m, num_sub)
89+ sub_offset_m = subcore_id * sub_m
90+ curr_actual_sub_m = tl.min(sub_m, actual_m - sub_offset_m)
91+ if curr_actual_sub_m <= 0:
92+ continue
93+ 
94+ curr_gm_row = (block_m * L1_M) + sub_offset_m
95+ curr_gm_col = (block_n * L1_N)
96+ 
97+ # UB tile view uses a fixed stride of L1_N in the M dimension (RowMajor tile).
98+ ub_shape = tl.make_shape(curr_actual_sub_m, actual_n)
99+ ub_layout = tl.make_layout(ub_shape, tl.make_stride(L1_N, 1))
100+ 
101+ gm_c_offset = layout_c.get_offset(coord=(curr_gm_row, curr_gm_col))
102+ gm_res_offset = layout_res.get_offset(coord=(curr_gm_row, curr_gm_col))
103+ gm_d_offset = layout_d.get_offset(coord=(curr_gm_row, curr_gm_col))
104+ 
105+ # --- A. Copy-In (workspace -> ub_c, residual -> ub_res) ---
106+ with tl.copyin():
107+ tl.load_2d(workspace[gm_c_offset], tl.make_layout(ub_shape, layout_c.stride()),
108+ ub_c, ub_layout
109+ )
110+ tl.load_2d(residual[gm_res_offset], tl.make_layout(ub_shape, layout_res.stride()),
111+ ub_res, ub_layout
112+ )
113+ 
114+ # --- B. Compute (ub_c + residual -> ub_d) ---
115+ with tl.compute():
116+ # Cast residual FP16 -> FP32
117+ tl.vcast(ub_res_fp32, ub_res, count=compute_length)
118+ 
119+ # ub_c = matmul_result(fp32) + residual(fp32)
120+ tl.vadd(ub_c, ub_c, ub_res_fp32, count=compute_length)
121+ 
122+ # Cast FP32 -> FP16 (output)
123+ tl.vcast(ub_d, ub_c, count=compute_length)
124+ 
125+ # --- C. Copy-Out (ub_d -> D) ---
126+ with tl.copyout():
127+ tl.store_2d(
128+ D[gm_d_offset], tl.make_layout(ub_shape, layout_d.stride()),
129+ ub_d, ub_layout
130+ )
131+ 
132+ 
133+# --- Host 调用 ---
134+def host_main(A: torch.Tensor, B: torch.Tensor, residual: torch.Tensor, D: torch.Tensor):
135+ M, K = A.shape
136+ K, N = B.shape
137+ 
138+ workspace = torch.empty(M * N, dtype=torch.float32, device=A.device)
139+ core_num = tl.get_core_num()
140+ 
141+ matmul_add_kernel[core_num](
142+ A, B, residual, D, workspace,
143+ M, N, K
144+ )
@@ -0,0 +1,174 @@
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+import tile.language as tl
12+import torch
13+ 
14+ 
15+@ascend_kernel
16+def matmul_add_rmsnorm_kernel(A, B, residual, gamma, Y, X_add, workspace, M, N, K, norm_eps):
17+ # ----------------------------------------------------------------------
18+ # 1. Tiling & Layout Configuration
19+ # ----------------------------------------------------------------------
20+ L1_M, L1_N = 128, 256
21+ K_TILE = 1024
22+ DTYPE_C, DTYPE_D = tl.float32, tl.half
23+ 
24+ layout_a = tl.make_layout(tl.make_shape(M, K), tl.make_stride(K, 1))
25+ layout_b = tl.make_layout(tl.make_shape(K, N), tl.make_stride(N, 1))
26+ layout_c = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
27+ layout_res = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
28+ layout_y = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
29+ layout_xadd = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
30+ 
31+ # c = a @ b
32+ # x_add = c + residual
33+ # y = rmsnorm(x_add) * gamma
34+ 
35+ # ----------------------------------------------------------------------
36+ # 任务核间划分说明
37+ # ----------------------------------------------------------------------
38+ # 1) 将 M 轴按 L1_M 切成 tile_count_m 个 block_m 任务。
39+ # 2) 每个 block_m 内 Cube 负责所有 N 方向的 matmul。
40+ # 3) Vector 负责 residual add + RmsNorm,逐行处理(需要 reduction)。
41+ # 4) 输出两个 tensor:Y(归一化后)和 X_add(归一化前的 add 结果)。
42+ tile_count_m = tl.cdiv(M, L1_M)
43+ tile_count_n = tl.cdiv(N, L1_N)
44+ 
45+ matmul_done_id = 0
46+ 
47+ aicore_id = tl.program_id()
48+ aicore_num = tl.num_programs()
49+ 
50+ # UB buffers for vector processing
51+ ub_mm_row = tl.alloc_ub(L1_N, dtype=DTYPE_C)
52+ ub_res_row = tl.alloc_ub(L1_N, dtype=DTYPE_D)
53+ ub_res_fp32 = tl.alloc_ub(L1_N, dtype=DTYPE_C)
54+ ub_add_row = tl.alloc_ub(L1_N, dtype=DTYPE_C)
55+ ub_gamma = tl.alloc_ub(L1_N, dtype=DTYPE_D)
56+ ub_gamma_fp32 = tl.alloc_ub(L1_N, dtype=DTYPE_C)
57+ ub_sq = tl.alloc_ub(L1_N, dtype=DTYPE_C)
58+ ub_reduce = tl.alloc_ub(L1_N, dtype=DTYPE_C)
59+ ub_y = tl.alloc_ub(L1_N, dtype=DTYPE_D)
60+ ub_xadd_out = tl.alloc_ub(L1_N, dtype=DTYPE_D)
61+ 
62+ # ----------------------------------------------------------------------
63+ # 2. Per-block_m fused scheduling
64+ # ----------------------------------------------------------------------
65+ for block_m in range(aicore_id, tile_count_m, aicore_num):
66+ actual_m = tl.min(L1_M, M - block_m * L1_M)
67+ 
68+ # --- Cube: matmul for all N tiles in this block_m ---
69+ with tl.scope('cube'):
70+ for block_n in range(tile_count_n):
71+ actual_n = tl.min(L1_N, N - block_n * L1_N)
72+ actual_shape = tl.make_shape(actual_m, actual_n, K)
73+ 
74+ coord_a = (block_m * L1_M, 0)
75+ coord_b = (0, block_n * L1_N)
76+ coord_c = (block_m * L1_M, block_n * L1_N)
77+ 
78+ with tl.compute():
79+ tl.dot(
80+ A[layout_a.get_offset(coord=coord_a)], layout_a,
81+ B[layout_b.get_offset(coord=coord_b)], layout_b,
82+ workspace[layout_c.get_offset(coord=coord_c)], layout_c,
83+ actual_shape,
84+ )
85+ 
86+ tl.cross_core_set(matmul_done_id)
87+ 
88+ # --- Vector: residual add + RmsNorm (per-row processing) ---
89+ with tl.scope('vector'):
90+ tl.cross_core_wait(matmul_done_id)
91+ 
92+ num_sub = tl.get_num_sub_blocks()
93+ subcore_id = tl.get_sub_block_id()
94+ sub_m = tl.cdiv(actual_m, num_sub)
95+ sub_offset_m = subcore_id * sub_m
96+ curr_m = tl.min(sub_m, actual_m - sub_offset_m)
97+ 
98+ if curr_m > 0:
99+ row_start = block_m * L1_M + sub_offset_m
100+ 
101+ for r in range(curr_m):
102+ row_id = row_start + r
103+ 
104+ # Step 1: Load matmul result row-by-row, add residual, compute sum_sq
105+ row_sum_sq = 0.0
106+ 
107+ for block_n in range(tile_count_n):
108+ col_start = block_n * L1_N
109+ curr_n = tl.min(L1_N, N - col_start)
110+ 
111+ gm_mm_offset = layout_c.get_offset(coord=(row_id, col_start))
112+ gm_res_offset = layout_res.get_offset(coord=(row_id, col_start))
113+ 
114+ with tl.copyin():
115+ tl.load(workspace[gm_mm_offset + tl.arange(0, curr_n)], ub_mm_row)
116+ tl.load(residual[gm_res_offset + tl.arange(0, curr_n)], ub_res_row)
117+ 
118+ with tl.compute():
119+ # Cast residual to fp32 and add
120+ tl.vcast(ub_res_fp32, ub_res_row, count=curr_n)
121+ tl.vadd(ub_add_row, ub_mm_row, ub_res_fp32, count=curr_n)
122+ 
123+ # Store x_add (fp16) for output
124+ tl.vcast(ub_xadd_out, ub_add_row, count=curr_n)
125+ 
126+ # Accumulate sum of squares for RmsNorm
127+ tl.vmul(ub_sq, ub_add_row, ub_add_row, count=curr_n)
128+ tl.reduce_sum(ub_reduce, ub_sq, ub_reduce)
129+ row_sum_sq = row_sum_sq + tl.extract_scalar(ub_reduce, 0)
130+ 
131+ with tl.copyout():
132+ gm_xadd_offset = layout_xadd.get_offset(coord=(row_id, col_start))
133+ tl.store(X_add[gm_xadd_offset + tl.arange(0, curr_n)], ub_xadd_out)
134+ 
135+ # Step 2: Compute inv_rms for this row
136+ row_mean_sq = row_sum_sq / float(N)
137+ inv_rms = (row_mean_sq + norm_eps) ** (-0.5)
138+ 
139+ # Step 3: Normalize and apply gamma, store Y
140+ for block_n in range(tile_count_n):
141+ col_start = block_n * L1_N
142+ curr_n = tl.min(L1_N, N - col_start)
143+ 
144+ gm_xadd_offset = layout_xadd.get_offset(coord=(row_id, col_start))
145+ gm_y_offset = layout_y.get_offset(coord=(row_id, col_start))
146+ 
147+ with tl.copyin():
148+ tl.load(X_add[gm_xadd_offset + tl.arange(0, curr_n)], ub_xadd_out)
149+ tl.load(gamma[col_start + tl.arange(0, curr_n)], ub_gamma)
150+ 
151+ with tl.compute():
152+ tl.vcast(ub_add_row, ub_xadd_out, count=curr_n) # fp16→fp32
153+ tl.vmul_scalar(ub_add_row, ub_add_row, scalar_value=inv_rms, count=curr_n)
154+ tl.vcast(ub_gamma_fp32, ub_gamma, count=curr_n)
155+ tl.vmul(ub_add_row, ub_add_row, ub_gamma_fp32, count=curr_n)
156+ tl.vcast(ub_y, ub_add_row, count=curr_n)
157+ 
158+ with tl.copyout():
159+ tl.store(Y[gm_y_offset + tl.arange(0, curr_n)], ub_y)
160+ 
161+ 
162+# --- Host 调用 ---
163+def host_main(A: torch.Tensor, B: torch.Tensor, residual: torch.Tensor,
164+ gamma: torch.Tensor, Y: torch.Tensor, X_add: torch.Tensor, norm_eps: float = 1e-6):
165+ M, K = A.shape
166+ K, N = B.shape
167+ 
168+ workspace = torch.empty(M * N, dtype=torch.float32, device=A.device)
169+ core_num = tl.get_core_num()
170+ 
171+ matmul_add_rmsnorm_kernel[core_num](
172+ A, B, residual, gamma, Y, X_add, workspace,
173+ M, N, K, norm_eps
174+ )
@@ -0,0 +1,149 @@
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+import tile.language as tl
12+import torch
13+ 
14+ 
15+@ascend_kernel
16+def matmul_bias_relu_kernel(A, B, bias, D, workspace, M, N, K):
17+ # ----------------------------------------------------------------------
18+ # 1. Tiling & Layout Configuration
19+ # ----------------------------------------------------------------------
20+ L1_M, L1_N = 128, 256
21+ DTYPE_C, DTYPE_D = tl.float32, tl.half
22+ 
23+ # Global Layouts
24+ layout_a = tl.make_layout(tl.make_shape(M, K), tl.make_stride(K, 1))
25+ layout_b = tl.make_layout(tl.make_shape(K, N), tl.make_stride(N, 1))
26+ layout_c = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
27+ layout_d = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
28+ 
29+ # c = a@b
30+ # c = c + bias (broadcast along M)
31+ # d = relu(c)
32+ 
33+ # ----------------------------------------------------------------------
34+ # 任务核间划分说明
35+ # ----------------------------------------------------------------------
36+ # 1) 将输出矩阵按 (M, N) 两个轴同时切分为 grid:
37+ # block_m in [0, tile_count_m), block_n in [0, tile_count_n)
38+ # 2) 每个任务对应一个 L1_M * L1_N 的 tile(边界 tile 为实际尺寸)。
39+ # 3) 任务按一维 task_id 分配给 AICore:
40+ # task_id = aicore_id + t * aicore_num
41+ # block_m = task_id // tile_count_n, block_n = task_id % tile_count_n
42+ # 4) 每个任务内先 cube 做 matmul,再 vector 做 bias-add + ReLU。
43+ tile_count_m = tl.cdiv(M, L1_M)
44+ tile_count_n = tl.cdiv(N, L1_N)
45+ total_tasks = tile_count_m * tile_count_n
46+ 
47+ matmul_ready_id = 0
48+ 
49+ aicore_id = tl.program_id()
50+ aicore_num = tl.num_programs()
51+ num_sub = tl.get_num_sub_blocks()
52+ subcore_id = tl.get_sub_block_id()
53+ compute_length = (L1_M // num_sub) * L1_N
54+ 
55+ ub_c = tl.alloc_ub(compute_length, dtype=DTYPE_C)
56+ ub_compute = tl.alloc_ub(compute_length, dtype=DTYPE_C)
57+ ub_d = tl.alloc_ub(compute_length, dtype=DTYPE_D)
58+ ub_bias = tl.alloc_ub(L1_N, dtype=DTYPE_D)
59+ ub_bias_fp32 = tl.alloc_ub(L1_N, dtype=DTYPE_C)
60+ 
61+ # ----------------------------------------------------------------------
62+ # 2. Per-task fused scheduling
63+ # One outer loop drives cube and vector phases for one (block_m, block_n) tile.
64+ # ----------------------------------------------------------------------
65+ for task_id in range(aicore_id, total_tasks, aicore_num):
66+ block_m = task_id // tile_count_n
67+ block_n = task_id % tile_count_n
68+ actual_m = tl.min(L1_M, M - block_m * L1_M)
69+ actual_n = tl.min(L1_N, N - block_n * L1_N)
70+ 
71+ with tl.scope('cube'):
72+ actual_block_shape = tl.make_shape(actual_m, actual_n, K)
73+ 
74+ coord_a = (block_m * L1_M, 0)
75+ coord_b = (0, block_n * L1_N)
76+ coord_c = (block_m * L1_M, block_n * L1_N)
77+ 
78+ with tl.compute():
79+ tl.dot(A[layout_a.get_offset(coord=coord_a)], layout_a,
80+ B[layout_b.get_offset(coord=coord_b)], layout_b,
81+ workspace[layout_c.get_offset(coord=coord_c)], layout_c,
82+ actual_block_shape)
83+ 
84+ tl.cross_core_set(matmul_ready_id)
85+ 
86+ with tl.scope('vector'):
87+ tl.cross_core_wait(matmul_ready_id)
88+ 
89+ sub_m = tl.cdiv(actual_m, num_sub)
90+ sub_offset_m = subcore_id * sub_m
91+ curr_actual_sub_m = tl.min(sub_m, actual_m - sub_offset_m)
92+ if curr_actual_sub_m <= 0:
93+ continue
94+ 
95+ curr_gm_row = (block_m * L1_M) + sub_offset_m
96+ curr_gm_col = (block_n * L1_N)
97+ 
98+ # UB tile view uses a fixed stride of L1_N in the M dimension (RowMajor tile).
99+ ub_shape = tl.make_shape(curr_actual_sub_m, actual_n)
100+ ub_layout = tl.make_layout(ub_shape, tl.make_stride(L1_N, 1))
101+ 
102+ gm_c_offset = layout_c.get_offset(coord=(curr_gm_row, curr_gm_col))
103+ gm_d_offset = layout_d.get_offset(coord=(curr_gm_row, curr_gm_col))
104+ 
105+ col_start = block_n * L1_N
106+ 
107+ # --- A. Copy-In (workspace -> ub_c, bias -> ub_bias) ---
108+ with tl.copyin():
109+ tl.load_2d(workspace[gm_c_offset], tl.make_layout(ub_shape, layout_c.stride()),
110+ ub_c, ub_layout
111+ )
112+ tl.load(bias[col_start:col_start + actual_n], ub_bias)
113+ 
114+ # --- B. Compute (ub_c + bias -> ReLU -> ub_d) ---
115+ with tl.compute():
116+ # Cast bias FP16 -> FP32
117+ tl.vcast(ub_bias_fp32, ub_bias, count=actual_n)
118+ 
119+ # Broadcast-add bias to each row: ub_c[row, :] += bias[:]
120+ for row in range(curr_actual_sub_m):
121+ row_offset = row * L1_N
122+ tl.vadd(ub_c[row_offset:], ub_c[row_offset:], ub_bias_fp32, count=actual_n)
123+ 
124+ # ReLU: clamp to min 0
125+ tl.vclamp_min(ub_compute, ub_c, scalar_value=0.0, count=compute_length)
126+ 
127+ # Cast FP32 -> FP16 (output)
128+ tl.vcast(ub_d, ub_compute, count=compute_length)
129+ 
130+ # --- C. Copy-Out (ub_d -> D) ---
131+ with tl.copyout():
132+ tl.store_2d(
133+ D[gm_d_offset], tl.make_layout(ub_shape, layout_d.stride()),
134+ ub_d, ub_layout
135+ )
136+ 
137+ 
138+# --- Host 调用 ---
139+def host_main(A: torch.Tensor, B: torch.Tensor, bias: torch.Tensor, D: torch.Tensor):
140+ M, K = A.shape
141+ K, N = B.shape
142+ 
143+ workspace = torch.empty(M * N, dtype=torch.float32, device=A.device)
144+ core_num = tl.get_core_num()
145+ 
146+ matmul_bias_relu_kernel[core_num](
147+ A, B, bias, D, workspace,
148+ M, N, K
149+ )
@@ -0,0 +1,151 @@
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+import tile.language as tl
12+import torch
13+ 
14+ 
15+@ascend_kernel
16+def matmul_gelu_kernel(A, B, D, workspace, M, N, K):
17+ # ----------------------------------------------------------------------
18+ # 1. Tiling & Layout Configuration
19+ # ----------------------------------------------------------------------
20+ L1_M, L1_N = 128, 256
21+ DTYPE_C, DTYPE_D = tl.float32, tl.half
22+ 
23+ # Global Layouts
24+ layout_a = tl.make_layout(tl.make_shape(M, K), tl.make_stride(K, 1))
25+ layout_b = tl.make_layout(tl.make_shape(K, N), tl.make_stride(N, 1))
26+ layout_c = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
27+ layout_d = tl.make_layout(tl.make_shape(M, N), tl.make_stride(N, 1))
28+ 
29+ # c = a@b
30+ # d = gelu(c)
31+ 
32+ # ----------------------------------------------------------------------
33+ # 任务核间划分说明
34+ # ----------------------------------------------------------------------
35+ # 1) 将输出矩阵按 (M, N) 两个轴同时切分为 grid:
36+ # block_m in [0, tile_count_m), block_n in [0, tile_count_n)
37+ # 2) 每个任务对应一个 L1_M * L1_N 的 tile(边界 tile 为实际尺寸)。
38+ # 3) 任务按一维 task_id 分配给 AICore:
39+ # task_id = aicore_id + t * aicore_num
40+ # block_m = task_id // tile_count_n, block_n = task_id % tile_count_n
41+ # 4) 每个任务内先 cube 做 matmul,再 vector 做 GELU。
42+ tile_count_m = tl.cdiv(M, L1_M)
43+ tile_count_n = tl.cdiv(N, L1_N)
44+ total_tasks = tile_count_m * tile_count_n
45+ 
46+ matmul_ready_id = 0
47+ 
48+ aicore_id = tl.program_id()
49+ aicore_num = tl.num_programs()
50+ num_sub = tl.get_num_sub_blocks()
51+ subcore_id = tl.get_sub_block_id()
52+ compute_length = (L1_M // num_sub) * L1_N
53+ 
54+ ub_c = tl.alloc_ub(compute_length, dtype=DTYPE_C)
55+ ub_compute = tl.alloc_ub(compute_length, dtype=DTYPE_C)
56+ ub_d = tl.alloc_ub(compute_length, dtype=DTYPE_D)
57+ 
58+ # y = x / (1 + exp(NEG_SQRT_EIGHT_OVER_PI * (x^3 + TANH_APPROX_FACTOR * x)))
59+ NEG_SQRT_EIGHT_OVER_PI = -1.595769121 * 0.044715
60+ TANH_APPROX_FACTOR = 1.0 / 0.044715
61+ 
62+ # ----------------------------------------------------------------------
63+ # 2. Per-task fused scheduling
64+ # One outer loop drives cube and vector phases for one (block_m, block_n) tile.
65+ # ----------------------------------------------------------------------
66+ for task_id in range(aicore_id, total_tasks, aicore_num):
67+ block_m = task_id // tile_count_n
68+ block_n = task_id % tile_count_n
69+ actual_m = tl.min(L1_M, M - block_m * L1_M)
70+ actual_n = tl.min(L1_N, N - block_n * L1_N)
71+ 
72+ with tl.scope('cube'):
73+ actual_block_shape = tl.make_shape(actual_m, actual_n, K)
74+ 
75+ coord_a = (block_m * L1_M, 0)
76+ coord_b = (0, block_n * L1_N)
77+ coord_c = (block_m * L1_M, block_n * L1_N)
78+ 
79+ with tl.compute():
80+ tl.dot(A[layout_a.get_offset(coord=coord_a)], layout_a,
81+ B[layout_b.get_offset(coord=coord_b)], layout_b,
82+ workspace[layout_c.get_offset(coord=coord_c)], layout_c,
83+ actual_block_shape)
84+ 
85+ tl.cross_core_set(matmul_ready_id)
86+ 
87+ with tl.scope('vector'):
88+ tl.cross_core_wait(matmul_ready_id)
89+ 
90+ sub_m = tl.cdiv(actual_m, num_sub)
91+ sub_offset_m = subcore_id * sub_m
92+ curr_actual_sub_m = tl.min(sub_m, actual_m - sub_offset_m)
93+ if curr_actual_sub_m <= 0:
94+ continue
95+ 
96+ curr_gm_row = (block_m * L1_M) + sub_offset_m
97+ curr_gm_col = (block_n * L1_N)
98+ 
99+ # UB tile view uses a fixed stride of L1_N in the M dimension (RowMajor tile).
100+ ub_shape = tl.make_shape(curr_actual_sub_m, actual_n)
101+ ub_layout = tl.make_layout(ub_shape, tl.make_stride(L1_N, 1))
102+ 
103+ gm_c_offset = layout_c.get_offset(coord=(curr_gm_row, curr_gm_col))
104+ gm_d_offset = layout_d.get_offset(coord=(curr_gm_row, curr_gm_col))
105+ 
106+ # --- A. Copy-In (workspace -> ub_c) ---
107+ with tl.copyin():
108+ tl.load_2d(workspace[gm_c_offset], tl.make_layout(ub_shape, layout_c.stride()),
109+ ub_c, ub_layout
110+ )
111+ 
112+ # --- B. Compute (ub_c -> ub_d via ub_compute) ---
113+ with tl.compute():
114+ # ub_compute = x^3
115+ tl.vmul(ub_compute, ub_c, ub_c, count=compute_length)
116+ tl.vmul(ub_compute, ub_compute, ub_c, count=compute_length)
117+ 
118+ # ub_compute = x^3 + (TANH_APPROX_FACTOR * x)
119+ tl.vaxpy(ub_compute, ub_c, alpha=TANH_APPROX_FACTOR, count=compute_length)
120+ 
121+ # ub_compute = NEG_SQRT_EIGHT_OVER_PI * ub_compute
122+ tl.vmul_scalar(ub_compute, ub_compute, scalar_value=NEG_SQRT_EIGHT_OVER_PI, count=compute_length)
123+ 
124+ # ub_compute = exp(ub_compute); ub_compute = ub_compute + 1; ub_compute = x / ub_compute
125+ tl.vexp(ub_compute, ub_compute, count=compute_length)
126+ tl.vadd_scalar(ub_compute, ub_compute, scalar_value=1.0, count=compute_length)
127+ tl.vdiv(ub_compute, ub_c, ub_compute, count=compute_length)
128+ 
129+ # Cast FP32 -> FP16 (output)
130+ tl.vcast(ub_d, ub_compute, count=compute_length)
131+ 
132+ # --- C. Copy-Out (ub_d -> D) ---
133+ with tl.copyout():
134+ tl.store_2d(
135+ D[gm_d_offset], tl.make_layout(ub_shape, layout_d.stride()),
136+ ub_d, ub_layout
137+ )
138+ 
139+ 
140+# --- Host 调用 ---
141+def host_main(A: torch.Tensor, B: torch.Tensor, D: torch.Tensor):
142+ M, K = A.shape
143+ K, N = B.shape
144+ 
145+ workspace = torch.empty(M * N, dtype=torch.float32, device=A.device)
146+ core_num = tl.get_core_num()
147+ 
148+ matmul_gelu_kernel[core_num](
149+ A, B, D, workspace,
150+ M, N, K
151+ )