tilelang-attnres 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: tilelang-attnres
3
+ Version: 0.1.0
4
+ Summary: Attention Residual architecture from Kimi K3 using TileLang, with fused forward and backward kernels.
5
+ Author: Index4NekoMeteor
6
+ License-Expression: Apache-2.0
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Provides-Extra: all
11
+ Requires-Dist: torch>=2.0; extra == "all"
12
+ Requires-Dist: tilelang>=0.1.15; extra == "all"
13
+ Dynamic: license-file
14
+
15
+ # TileLang-AttnRes
16
+
17
+ This repository implements the **Attention Residual** architecture from **Kimi K3** using [TileLang](https://github.com/tile-ai/tilelang), including both **forward** and **backward** kernels. The operators are benchmarked against native PyTorch and `torch.compile`.
18
+
19
+ ## Repository Structure
20
+
21
+ ```text
22
+ Tilelang-AttnRes/
23
+ ├── assets/ # Images / resources
24
+ ├── benchmark/ # Benchmark scripts
25
+ │ ├── benchmark_fwd.py
26
+ │ └── benchmark_bwd.py
27
+ ├── tilelang_attnres/ # Python package
28
+ │ ├── __init__.py # Autograd & nn.Module wrappers
29
+ │ └── kernels/
30
+ │ ├── attn_res_fwd.py # Forward kernel
31
+ │ └── attn_res_bwd.py # Backward kernel
32
+ ├── test.py # Correctness verification script
33
+ ├── requirements.txt
34
+ └── README.md
35
+ ```
36
+
37
+ ## Benchmark
38
+
39
+ ### Testing environment
40
+
41
+ - OS: Windows 11
42
+ - CPU: AMD Ryzen 7 9800X3D
43
+ - GPU: NVIDIA RTX 5080 (16 GB VRAM)
44
+ - Dependencies: see [requirements.txt](requirements.txt)
45
+
46
+ ### Forward
47
+
48
+ **bfloat16:**
49
+
50
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
51
+ | --- | --- | --- | --- | --- | --- | --- | --- |
52
+ | 1280×8×7168 | 0.258 | 5.699 | 1.104 | **22.12×** | 5.16× | 2.34e-05 | 1.90e-05 |
53
+ | 2560×4×7168 | 0.243 | 5.711 | 1.854 | **23.53×** | 3.08× | 2.37e-05 | 2.02e-05 |
54
+ | 5120×2×7168 | 0.398 | 8.079 | 2.666 | **20.29×** | 3.03× | 1.94e-05 | 1.69e-05 |
55
+ | 10240×1×7168 | 0.570 | 11.232| 3.447 | **19.70×** | 3.26× | 1.68e-05 | 1.35e-05 |
56
+ | 7680×8×768 | 0.142 | 3.163 | 1.231 | **22.26×** | 2.57× | 2.55e-05 | 2.38e-05 |
57
+ | 768×1×4096 | 0.032 | 0.223 | 0.101 | **7.06×** | 2.21× | 1.22e-05 | 1.43e-05 |
58
+
59
+ **float32:**
60
+
61
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
62
+ | --- | --- | --- | --- | --- | --- | --- | --- |
63
+ | 1280×8×7168 | 0.432 | 5.121 | 2.152 | **11.84×** | 2.38× | 1.04e-06 | 8.80e-07 |
64
+ | 2560×4×7168 | 0.540 | 5.555 | 2.301 | **10.28×** | 2.41× | 1.13e-06 | 8.18e-07 |
65
+ | 5120×2×7168 | 0.761 | 8.021 | 2.806 | **10.54×** | 2.86× | 9.85e-07 | 7.60e-07 |
66
+ | 10240×1×7168 | 1.298 | 10.252| 3.258 | **7.90×** | 3.15× | 8.55e-07 | 6.57e-07 |
67
+ | 7680×8×768 | 0.280 | 2.966 | 1.680 | **10.61×** | 1.77× | 5.67e-07 | 5.37e-07 |
68
+ | 768×1×4096 | 0.048 | 0.211 | 0.104 | **4.38×** | 2.03× | 6.97e-07 | 4.93e-07 |
69
+
70
+ ### Backward
71
+
72
+ **`rel_err` is the maximum global L2 relative error across all four gradients**
73
+
74
+ **bfloat16:**
75
+
76
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
77
+ | --- | --- | --- | --- | --- | --- | --- | --- |
78
+ | 1280×8×7168 | 0.916 | 16.155 | 4.040 | **17.64×** | 4.00× | 2.41e-04 | 2.22e-04 |
79
+ | 2560×4×7168 | 0.861 | 18.376 | 5.302 | **21.33×** | 3.47× | 3.21e-04 | 2.43e-04 |
80
+ | 5120×2×7168 | 1.021 | 26.337 | 7.984 | **25.80×** | 3.30× | 2.49e-04 | 2.18e-04 |
81
+ | 10240×1×7168| 1.406 | 32.962 | 11.492| **23.45×** | 2.87× | 3.07e-04 | 2.31e-04 |
82
+ | 7680×8×768 | 0.611 | 10.257 | 5.539 | **16.80×** | 1.85× | 1.15e-04 | 1.12e-04 |
83
+ | 768×1×4096 | 0.083 | 0.921 | 0.409 | **11.16×** | 2.25× | 2.90e-04 | 1.52e-04 |
84
+
85
+ **float32:**
86
+
87
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
88
+ | --- | --- | --- | --- | --- | --- | --- | --- |
89
+ | 1280×8×7168 | 1.658 | 14.967 | 5.566 | **9.03×** | 2.69× | 3.15e-05 | 1.57e-05 |
90
+ | 2560×4×7168 | 2.427 | 17.111 | 6.642 | **7.05×** | 2.58× | 2.13e-05 | 1.68e-05 |
91
+ | 5120×2×7168 | 2.347 | 21.645 | 10.614| **9.22×** | 2.04× | 2.13e-05 | 1.48e-05 |
92
+ | 10240×1×7168| 3.316 | 33.348 | 10.281| **10.06×**| 3.24× | 1.94e-05 | 1.86e-05 |
93
+ | 7680×8×768 | 0.943 | 11.038 | 4.543 | **11.71×**| 2.43× | 6.04e-06 | 5.77e-06 |
94
+ | 768×1×4096 | 0.112 | 0.901 | 0.375 | **8.07×** | 2.40× | 1.59e-05 | 1.41e-05 |
95
+
96
+ > **Note**
97
+ > - `rel_err = ‖TileLang − baseline‖₂ / ‖baseline‖₂`, computed in `float32` to avoid bf16 accumulation artifacts in the metric itself.
98
+ > - Timing uses `tilelang.profiler.bench.do_bench` with `warmup=100`.
99
+ > - bf16 backward results are also verified; expected `rel_err` is around `1e-4`.
100
+
101
+ ## Future
102
+
103
+ - [x] Implement backward
104
+
105
+ ## Citation
106
+
107
+ ```bibtex
108
+ @misc{chen2026attnres,
109
+ title = {Attention Residuals},
110
+ author = {Kimi Team and Chen, Guangyu and Zhang, Yu and Su, Jianlin and Xu, Weixin and Pan, Siyuan and Wang, Yaoyu and Wang, Yucheng and Chen, Guanduo and Yin, Bohong and Chen, Yutian and Yan, Junjie and Wei, Ming and Zhang, Y. and Meng, Fanqing and Hong, Chao and Xie, Xiaotong and Liu, Shaowei and Lu, Enzhe and Tai, Yunpeng and Chen, Yanru and Men, Xin and Guo, Haiqing and Charles, Y. and Lu, Haoyu and Sui, Lin and Zhu, Jinguo and Zhou, Zaida and He, Weiran and Huang, Weixiao and Xu, Xinran and Wang, Yuzhi and Lai, Guokun and Du, Yulun and Wu, Yuxin and Yang, Zhilin and Zhou, Xinyu},
111
+ year = {2026},
112
+ archiveprefix = {arXiv},
113
+ eprint = {2603.15031},
114
+ primaryclass = {cs.CL}
115
+ }
116
+ ```
117
+
118
+ ## License
119
+
120
+ This project is licensed under the terms in the [LICENSE](LICENSE) file.
@@ -0,0 +1,106 @@
1
+ # TileLang-AttnRes
2
+
3
+ This repository implements the **Attention Residual** architecture from **Kimi K3** using [TileLang](https://github.com/tile-ai/tilelang), including both **forward** and **backward** kernels. The operators are benchmarked against native PyTorch and `torch.compile`.
4
+
5
+ ## Repository Structure
6
+
7
+ ```text
8
+ Tilelang-AttnRes/
9
+ ├── assets/ # Images / resources
10
+ ├── benchmark/ # Benchmark scripts
11
+ │ ├── benchmark_fwd.py
12
+ │ └── benchmark_bwd.py
13
+ ├── tilelang_attnres/ # Python package
14
+ │ ├── __init__.py # Autograd & nn.Module wrappers
15
+ │ └── kernels/
16
+ │ ├── attn_res_fwd.py # Forward kernel
17
+ │ └── attn_res_bwd.py # Backward kernel
18
+ ├── test.py # Correctness verification script
19
+ ├── requirements.txt
20
+ └── README.md
21
+ ```
22
+
23
+ ## Benchmark
24
+
25
+ ### Testing environment
26
+
27
+ - OS: Windows 11
28
+ - CPU: AMD Ryzen 7 9800X3D
29
+ - GPU: NVIDIA RTX 5080 (16 GB VRAM)
30
+ - Dependencies: see [requirements.txt](requirements.txt)
31
+
32
+ ### Forward
33
+
34
+ **bfloat16:**
35
+
36
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
37
+ | --- | --- | --- | --- | --- | --- | --- | --- |
38
+ | 1280×8×7168 | 0.258 | 5.699 | 1.104 | **22.12×** | 5.16× | 2.34e-05 | 1.90e-05 |
39
+ | 2560×4×7168 | 0.243 | 5.711 | 1.854 | **23.53×** | 3.08× | 2.37e-05 | 2.02e-05 |
40
+ | 5120×2×7168 | 0.398 | 8.079 | 2.666 | **20.29×** | 3.03× | 1.94e-05 | 1.69e-05 |
41
+ | 10240×1×7168 | 0.570 | 11.232| 3.447 | **19.70×** | 3.26× | 1.68e-05 | 1.35e-05 |
42
+ | 7680×8×768 | 0.142 | 3.163 | 1.231 | **22.26×** | 2.57× | 2.55e-05 | 2.38e-05 |
43
+ | 768×1×4096 | 0.032 | 0.223 | 0.101 | **7.06×** | 2.21× | 1.22e-05 | 1.43e-05 |
44
+
45
+ **float32:**
46
+
47
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
48
+ | --- | --- | --- | --- | --- | --- | --- | --- |
49
+ | 1280×8×7168 | 0.432 | 5.121 | 2.152 | **11.84×** | 2.38× | 1.04e-06 | 8.80e-07 |
50
+ | 2560×4×7168 | 0.540 | 5.555 | 2.301 | **10.28×** | 2.41× | 1.13e-06 | 8.18e-07 |
51
+ | 5120×2×7168 | 0.761 | 8.021 | 2.806 | **10.54×** | 2.86× | 9.85e-07 | 7.60e-07 |
52
+ | 10240×1×7168 | 1.298 | 10.252| 3.258 | **7.90×** | 3.15× | 8.55e-07 | 6.57e-07 |
53
+ | 7680×8×768 | 0.280 | 2.966 | 1.680 | **10.61×** | 1.77× | 5.67e-07 | 5.37e-07 |
54
+ | 768×1×4096 | 0.048 | 0.211 | 0.104 | **4.38×** | 2.03× | 6.97e-07 | 4.93e-07 |
55
+
56
+ ### Backward
57
+
58
+ **`rel_err` is the maximum global L2 relative error across all four gradients**
59
+
60
+ **bfloat16:**
61
+
62
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
63
+ | --- | --- | --- | --- | --- | --- | --- | --- |
64
+ | 1280×8×7168 | 0.916 | 16.155 | 4.040 | **17.64×** | 4.00× | 2.41e-04 | 2.22e-04 |
65
+ | 2560×4×7168 | 0.861 | 18.376 | 5.302 | **21.33×** | 3.47× | 3.21e-04 | 2.43e-04 |
66
+ | 5120×2×7168 | 1.021 | 26.337 | 7.984 | **25.80×** | 3.30× | 2.49e-04 | 2.18e-04 |
67
+ | 10240×1×7168| 1.406 | 32.962 | 11.492| **23.45×** | 2.87× | 3.07e-04 | 2.31e-04 |
68
+ | 7680×8×768 | 0.611 | 10.257 | 5.539 | **16.80×** | 1.85× | 1.15e-04 | 1.12e-04 |
69
+ | 768×1×4096 | 0.083 | 0.921 | 0.409 | **11.16×** | 2.25× | 2.90e-04 | 1.52e-04 |
70
+
71
+ **float32:**
72
+
73
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
74
+ | --- | --- | --- | --- | --- | --- | --- | --- |
75
+ | 1280×8×7168 | 1.658 | 14.967 | 5.566 | **9.03×** | 2.69× | 3.15e-05 | 1.57e-05 |
76
+ | 2560×4×7168 | 2.427 | 17.111 | 6.642 | **7.05×** | 2.58× | 2.13e-05 | 1.68e-05 |
77
+ | 5120×2×7168 | 2.347 | 21.645 | 10.614| **9.22×** | 2.04× | 2.13e-05 | 1.48e-05 |
78
+ | 10240×1×7168| 3.316 | 33.348 | 10.281| **10.06×**| 3.24× | 1.94e-05 | 1.86e-05 |
79
+ | 7680×8×768 | 0.943 | 11.038 | 4.543 | **11.71×**| 2.43× | 6.04e-06 | 5.77e-06 |
80
+ | 768×1×4096 | 0.112 | 0.901 | 0.375 | **8.07×** | 2.40× | 1.59e-05 | 1.41e-05 |
81
+
82
+ > **Note**
83
+ > - `rel_err = ‖TileLang − baseline‖₂ / ‖baseline‖₂`, computed in `float32` to avoid bf16 accumulation artifacts in the metric itself.
84
+ > - Timing uses `tilelang.profiler.bench.do_bench` with `warmup=100`.
85
+ > - bf16 backward results are also verified; expected `rel_err` is around `1e-4`.
86
+
87
+ ## Future
88
+
89
+ - [x] Implement backward
90
+
91
+ ## Citation
92
+
93
+ ```bibtex
94
+ @misc{chen2026attnres,
95
+ title = {Attention Residuals},
96
+ author = {Kimi Team and Chen, Guangyu and Zhang, Yu and Su, Jianlin and Xu, Weixin and Pan, Siyuan and Wang, Yaoyu and Wang, Yucheng and Chen, Guanduo and Yin, Bohong and Chen, Yutian and Yan, Junjie and Wei, Ming and Zhang, Y. and Meng, Fanqing and Hong, Chao and Xie, Xiaotong and Liu, Shaowei and Lu, Enzhe and Tai, Yunpeng and Chen, Yanru and Men, Xin and Guo, Haiqing and Charles, Y. and Lu, Haoyu and Sui, Lin and Zhu, Jinguo and Zhou, Zaida and He, Weiran and Huang, Weixiao and Xu, Xinran and Wang, Yuzhi and Lai, Guokun and Du, Yulun and Wu, Yuxin and Yang, Zhilin and Zhou, Xinyu},
97
+ year = {2026},
98
+ archiveprefix = {arXiv},
99
+ eprint = {2603.15031},
100
+ primaryclass = {cs.CL}
101
+ }
102
+ ```
103
+
104
+ ## License
105
+
106
+ This project is licensed under the terms in the [LICENSE](LICENSE) file.
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 77.0.3", ]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tilelang-attnres"
7
+ version = "0.1.0"
8
+ description = "Attention Residual architecture from Kimi K3 using TileLang, with fused forward and backward kernels."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Index4NekoMeteor"}]
14
+
15
+ [project.optional-dependencies]
16
+ all = [
17
+ "torch>=2.0",
18
+ "tilelang>=0.1.15"
19
+ ]
20
+
21
+ [tool.setuptools.packages.find]
22
+ include = ["tilelang_attnres*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,83 @@
1
+ import torch
2
+ from torch import nn
3
+ from torch.autograd import Function
4
+ from .kernels import block_residual_fwd, block_residual_bwd
5
+
6
+
7
+ class AttnResFunction(Function):
8
+ @staticmethod
9
+ def forward(
10
+ ctx,
11
+ prefix_sum,
12
+ block_residual,
13
+ proj_weight,
14
+ norm_weight,
15
+ eps: float = 1e-6,
16
+ ):
17
+ output, rsqrt_output, max_output, exp_output, div_output, softmax_output = block_residual_fwd(
18
+ prefix_sum, block_residual, proj_weight, norm_weight, eps=eps
19
+ )
20
+ ctx.save_for_backward(
21
+ prefix_sum,
22
+ block_residual,
23
+ proj_weight,
24
+ norm_weight,
25
+ rsqrt_output,
26
+ max_output,
27
+ exp_output,
28
+ div_output,
29
+ softmax_output,
30
+ )
31
+ return output
32
+
33
+ @staticmethod
34
+ def backward(ctx, grad):
35
+ (
36
+ prefix_sum,
37
+ block_residual,
38
+ proj_weight,
39
+ norm_weight,
40
+ rsqrt_output,
41
+ max_output,
42
+ exp_output,
43
+ div_output,
44
+ softmax_output,
45
+ ) = ctx.saved_tensors
46
+
47
+ dprefix_sum, dblock_residual, dproj_weight, dnorm_weight = block_residual_bwd(
48
+ grad,
49
+ prefix_sum,
50
+ block_residual,
51
+ proj_weight,
52
+ norm_weight,
53
+ rsqrt_output,
54
+ max_output,
55
+ exp_output,
56
+ div_output,
57
+ softmax_output,
58
+ )
59
+ return dprefix_sum, dblock_residual, dnorm_weight, dproj_weight, None
60
+
61
+
62
+ def attn_res_tilelang(prefix_sum, block_residual, proj_weight, norm_weight, eps=1e-6):
63
+ return AttnResFunction.apply(prefix_sum, block_residual, proj_weight, norm_weight, eps)
64
+
65
+
66
+ class AttnRes(nn.Module):
67
+ def __init__(self, hidden_size, eps=1e-6):
68
+ super().__init__()
69
+ self.eps = eps
70
+ self.proj_weight = nn.Parameter(torch.ones(hidden_size))
71
+ self.norm_weight = nn.Parameter(torch.ones(hidden_size))
72
+
73
+ def forward(self, prefix_sum, block_residual):
74
+ return AttnResFunction.apply(prefix_sum, block_residual, self.proj_weight, self.norm_weight, self.eps)
75
+
76
+
77
+ __all__ = [
78
+ "AttnResFunction",
79
+ "AttnRes",
80
+ "block_residual_fwd",
81
+ "block_residual_bwd",
82
+ "attn_res_tilelang",
83
+ ]
@@ -0,0 +1,2 @@
1
+ from .attn_res_fwd import block_residual_fwd
2
+ from .attn_res_bwd import block_residual_bwd
@@ -0,0 +1,314 @@
1
+ import os
2
+ import sys
3
+ import torch
4
+ import tilelang
5
+ from itertools import product
6
+ from tilelang import language as T
7
+ from tilelang.autotuner.capture import set_autotune_inputs
8
+ from tilelang.layout.swizzle import make_linear_layout, make_swizzled_layout
9
+
10
+
11
+ # NOTE: disable autotuner
12
+ # def block_residual_bwd_configs(**kwargs):
13
+ # dtype = kwargs.get("dtype")
14
+ # keys = ("threads", "threads_2", "block_size", "block_size_2")
15
+
16
+ # if dtype != "float32":
17
+ # values = product(
18
+ # [256, 512],
19
+ # [32, 64, 128],
20
+ # [256, 512, 1024],
21
+ # [64, 128],
22
+ # )
23
+ # else:
24
+ # values = product(
25
+ # [256, 512],
26
+ # [32, 64, 128],
27
+ # [256, 512, 1024],
28
+ # [64],
29
+ # )
30
+
31
+ # return [dict(zip(keys, value)) for value in values]
32
+
33
+
34
+ # @tilelang.autotune(
35
+ # configs=block_residual_bwd_configs,
36
+ # do_not_specialize=["threads", "threads_2", "block_size", "block_size_2"],
37
+ # warmup=3,
38
+ # rep=5,
39
+ # )
40
+ @tilelang.jit(
41
+ pass_configs={
42
+ tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
43
+ tilelang.PassConfigKey.TL_DISABLE_DATA_RACE_CHECK: True,
44
+ tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
45
+ },
46
+ )
47
+ def block_residual_bwd_kernel(
48
+ num_blocks,
49
+ hidden_size,
50
+ dtype,
51
+ weight_dtype,
52
+ threads=128,
53
+ threads_2=64,
54
+ token_size=32,
55
+ block_size=256,
56
+ block_size_2=64,
57
+ num_stages: int = 1,
58
+ accum_dtype=T.float32,
59
+ ):
60
+ num_token = T.dynamic("num_token")
61
+ total_block = num_blocks + 1
62
+
63
+ @T.prim_func
64
+ def bwd_kernel(
65
+ grad: T.Tensor((num_token, hidden_size), dtype),
66
+ prefix_sum: T.Tensor((num_token, hidden_size), dtype),
67
+ block_residual: T.Tensor((num_token, num_blocks, hidden_size), dtype),
68
+ norm_weight: T.Tensor((hidden_size,), weight_dtype),
69
+ proj_weight: T.Tensor((hidden_size,), weight_dtype),
70
+ # fwd cache values
71
+ rsqrt_output: T.Tensor((num_token, total_block), accum_dtype),
72
+ max_output: T.Tensor((num_token, 1), T.int32),
73
+ exp_output: T.Tensor((num_token, total_block), accum_dtype),
74
+ div_output: T.Tensor((num_token, 1), accum_dtype),
75
+ softmax_output: T.Tensor((num_token, total_block), accum_dtype),
76
+ # output value
77
+ doutput: T.Tensor((num_token, total_block, hidden_size), dtype),
78
+ dproj_weight: T.Tensor((hidden_size), accum_dtype),
79
+ dnorm_weight: T.Tensor((hidden_size), accum_dtype),
80
+ add_workspace: T.Tensor((num_token, total_block), accum_dtype),
81
+ ):
82
+ with T.Kernel(num_token, threads=threads) as token:
83
+ T.annotate_min_blocks_per_sm(2)
84
+ T.assume(num_token > 0) # ty: ignore
85
+ T.assume(num_blocks > 0)
86
+ T.assume(total_block > 0)
87
+ T.assume(hidden_size > 0)
88
+
89
+ T.pdl_sync()
90
+ # ======= stage 1 =======
91
+ idx_local = T.alloc_fragment((1), T.int32)
92
+ divisor_local = T.alloc_fragment((1), accum_dtype)
93
+ grad_share_ptx = T.alloc_shared((block_size), dtype)
94
+ norm_share_ptx = T.alloc_shared((block_size), accum_dtype)
95
+ proj_share_ptx = T.alloc_shared((block_size), accum_dtype)
96
+ hidden_share_ptx = T.alloc_shared((total_block, block_size), dtype)
97
+
98
+ weight_local_ptx = T.alloc_fragment((block_size), accum_dtype)
99
+ exp_output_local_ptx = T.alloc_fragment((total_block), accum_dtype)
100
+ rsqrt_output_local_ptx = T.alloc_fragment((total_block), accum_dtype)
101
+ softmax_output_local_ptx = T.alloc_fragment((total_block), accum_dtype)
102
+ add_workspace_local_ptx = T.alloc_fragment((total_block), accum_dtype)
103
+
104
+ div_3 = T.alloc_fragment((total_block), accum_dtype)
105
+ mul_12 = T.alloc_fragment((total_block), accum_dtype)
106
+ bmm_2 = T.alloc_fragment((total_block), accum_dtype)
107
+ bmm_weight = T.alloc_fragment((total_block), accum_dtype)
108
+
109
+ mul_3_sum = T.alloc_fragment((1), accum_dtype)
110
+ div_3_sum = T.alloc_fragment((1), accum_dtype)
111
+ tile_sum_1 = T.alloc_fragment((total_block, block_size), accum_dtype)
112
+ tile_sum_2 = T.alloc_fragment((total_block, block_size), accum_dtype)
113
+
114
+ T.copy(max_output[token, :], idx_local)
115
+ T.copy(div_output[token, :], divisor_local)
116
+ T.copy(exp_output[token, :], exp_output_local_ptx)
117
+ T.copy(rsqrt_output[token, :], rsqrt_output_local_ptx)
118
+ T.copy(softmax_output[token, :], softmax_output_local_ptx)
119
+
120
+ T.clear(mul_3_sum)
121
+ T.clear(tile_sum_1)
122
+ T.clear(tile_sum_2)
123
+
124
+ inv_1 = T.float32(1.0) / divisor_local[0] # ty: ignore
125
+ inv_2 = T.float32(1.0) / hidden_size # ty: ignore
126
+
127
+ for block in T.Pipelined(
128
+ T.ceildiv(hidden_size, block_size),
129
+ num_stages=num_stages,
130
+ ):
131
+ ptx_start = block * block_size
132
+ ptx_end = ptx_start + block_size
133
+
134
+ T.copy(grad[token, ptx_start:ptx_end], grad_share_ptx)
135
+ T.copy(norm_weight[ptx_start:ptx_end], norm_share_ptx)
136
+ T.copy(proj_weight[ptx_start:ptx_end], proj_share_ptx)
137
+ T.copy(block_residual[token, :, ptx_start:ptx_end], hidden_share_ptx[0:num_blocks, :])
138
+ T.copy(prefix_sum[token, ptx_start:ptx_end], hidden_share_ptx[num_blocks:total_block, :])
139
+
140
+ for j in T.Parallel(block_size):
141
+ weight_local_ptx[j] = norm_share_ptx[j] * proj_share_ptx[j]
142
+
143
+ for i, j in T.Parallel(total_block, block_size):
144
+ grad_fp32 = T.cast(grad_share_ptx[j], accum_dtype)
145
+ hidden_fp32 = T.cast(hidden_share_ptx[i, j], accum_dtype)
146
+ tile_sum_1[i, j] += hidden_fp32 * grad_fp32
147
+ tile_sum_2[i, j] += hidden_fp32 * weight_local_ptx[j]
148
+
149
+ T.reduce_sum(tile_sum_1, bmm_2, batch=total_block)
150
+ T.reduce_sum(tile_sum_2, bmm_weight, batch=total_block)
151
+
152
+ for i in T.unroll(total_block):
153
+ div_3[i] = bmm_2[i] * inv_1
154
+
155
+ for i in T.unroll(total_block):
156
+ mul_3_sum[0] += -div_3[i] * softmax_output_local_ptx[i]
157
+
158
+ for i in T.unroll(total_block):
159
+ div_3[i] = (div_3[i] + mul_3_sum[0]) * exp_output_local_ptx[i]
160
+
161
+ T.reduce_sum(div_3, div_3_sum, dim=-1)
162
+
163
+ for i in T.Parallel(total_block):
164
+ div_3[i] = div_3[i] - T.if_then_else(i == idx_local[0], div_3_sum[0], T.float32(0.0)) # ty:ignore
165
+ add_workspace_local_ptx[i] = div_3[i] * rsqrt_output_local_ptx[i]
166
+
167
+ T.copy(add_workspace_local_ptx, add_workspace[token, :total_block])
168
+
169
+ for i in T.unroll(total_block):
170
+ pow_2 = rsqrt_output_local_ptx[i] * rsqrt_output_local_ptx[i] * rsqrt_output_local_ptx[i]
171
+ mul_12[i] = (div_3[i] * bmm_weight[i] * -0.5) * pow_2 * inv_2
172
+
173
+ # ======= stage 2 =======
174
+ for block in T.Pipelined(
175
+ T.ceildiv(hidden_size, block_size),
176
+ num_stages=num_stages,
177
+ ):
178
+ ptx_start = block * block_size
179
+ ptx_end = ptx_start + block_size
180
+
181
+ T.copy(grad[token, ptx_start:ptx_end], grad_share_ptx)
182
+ T.copy(norm_weight[ptx_start:ptx_end], norm_share_ptx)
183
+ T.copy(proj_weight[ptx_start:ptx_end], proj_share_ptx)
184
+ T.copy(block_residual[token, :, ptx_start:ptx_end], hidden_share_ptx[0:num_blocks, :])
185
+ T.copy(prefix_sum[token, ptx_start:ptx_end], hidden_share_ptx[num_blocks:total_block, :])
186
+
187
+ for j in T.Parallel(block_size):
188
+ weight_local_ptx[j] = norm_share_ptx[j] * proj_share_ptx[j]
189
+
190
+ for j in T.Parallel(block_size):
191
+ for i in T.unroll(total_block):
192
+ grad_fp32 = T.cast(grad_share_ptx[j], accum_dtype)
193
+ hidden_fp32 = T.cast(hidden_share_ptx[i, j], accum_dtype)
194
+
195
+ bmm_1 = grad_fp32 * softmax_output_local_ptx[i]
196
+ mul_6 = div_3[i] * weight_local_ptx[j] * rsqrt_output_local_ptx[i]
197
+
198
+ doutput[token, i, ptx_start + j] = T.cast(
199
+ mul_6 + bmm_1 + mul_12[i] * (hidden_fp32 * 2.0), weight_dtype
200
+ )
201
+
202
+ with T.Kernel(T.ceildiv(hidden_size, block_size_2), threads=threads_2) as hidden_block:
203
+ ptx_start = hidden_block * block_size_2
204
+ ptx_end = ptx_start + block_size_2
205
+
206
+ mul_5 = T.alloc_fragment((token_size, block_size_2), accum_dtype)
207
+ mul_5_sum = T.alloc_fragment((block_size_2), accum_dtype)
208
+ add_local_ptx = T.alloc_shared((token_size, total_block), accum_dtype)
209
+
210
+ proj_weight_ptx = T.alloc_fragment((block_size_2), weight_dtype)
211
+ norm_weight_ptx = T.alloc_fragment((block_size_2), weight_dtype)
212
+ hidden_share_ptx = T.alloc_shared((token_size, total_block, block_size_2), dtype)
213
+
214
+ dproj_weight_local_ptx = T.alloc_fragment((block_size_2), weight_dtype)
215
+ dnorm_weight_local_ptx = T.alloc_fragment((block_size_2), weight_dtype)
216
+
217
+ T.copy(proj_weight[ptx_start:ptx_end], proj_weight_ptx)
218
+ T.copy(norm_weight[ptx_start:ptx_end], norm_weight_ptx)
219
+
220
+ T.clear(mul_5_sum)
221
+
222
+ T.pdl_sync()
223
+ for token in T.Pipelined(T.ceildiv(num_token, token_size), num_stages=num_stages):
224
+ token_ptx_start = token * token_size
225
+ token_ptx_end = token_ptx_start + token_size
226
+
227
+ T.copy(add_workspace[token_ptx_start:token_ptx_end, :], add_local_ptx)
228
+ T.copy(
229
+ block_residual[token_ptx_start:token_ptx_end, :, ptx_start:ptx_end],
230
+ hidden_share_ptx[:, 0:num_blocks, :],
231
+ )
232
+ T.copy(
233
+ prefix_sum[token_ptx_start:token_ptx_end, ptx_start:ptx_end],
234
+ hidden_share_ptx[:, num_blocks:total_block, :],
235
+ )
236
+
237
+ for t, j in T.Parallel(token_size, block_size_2):
238
+ tile_acc = T.alloc_local((1), accum_dtype)
239
+ tile_acc[0] = 0
240
+ for i in T.unroll(total_block):
241
+ hidden_fp32 = T.cast(hidden_share_ptx[t, i, j], accum_dtype)
242
+ tile_acc[0] += add_local_ptx[t, i] * hidden_fp32
243
+ mul_5[t, j] = tile_acc[0]
244
+
245
+ T.reduce_sum(mul_5, mul_5_sum, dim=0, clear=False)
246
+
247
+ for j in T.Parallel(block_size_2):
248
+ dproj_weight_local_ptx[j] = T.cast(mul_5_sum[j] * norm_weight_ptx[j], weight_dtype)
249
+ dnorm_weight_local_ptx[j] = T.cast(mul_5_sum[j] * proj_weight_ptx[j], weight_dtype)
250
+
251
+ T.copy(dproj_weight_local_ptx, dproj_weight[ptx_start:ptx_end])
252
+ T.copy(dnorm_weight_local_ptx, dnorm_weight[ptx_start:ptx_end])
253
+
254
+ return bwd_kernel
255
+
256
+
257
+ def block_residual_bwd(
258
+ grad,
259
+ prefix_sum,
260
+ block_residual,
261
+ proj_weight,
262
+ norm_weight,
263
+ # fwd cache values
264
+ rsqrt_output,
265
+ max_output,
266
+ exp_output,
267
+ div_output,
268
+ softmax_output,
269
+ ):
270
+ device = block_residual.device
271
+ num_token, num_blocks, hidden_size = block_residual.shape
272
+ total_block = num_blocks + 1
273
+
274
+ dtype = str(block_residual.dtype).replace("torch.", "")
275
+ weight_dtype = str(norm_weight.dtype).replace("torch.", "")
276
+
277
+ doutput = torch.empty((num_token, total_block, hidden_size), device=device, dtype=block_residual.dtype)
278
+ dproj_weight = torch.empty((hidden_size), device=device, dtype=norm_weight.dtype)
279
+ dnorm_weight = torch.empty((hidden_size), device=device, dtype=norm_weight.dtype)
280
+ add_workspace = torch.empty((num_token, total_block), device=device, dtype=torch.float32)
281
+
282
+
283
+ kernel = block_residual_bwd_kernel(
284
+ block_residual.shape[1],
285
+ block_residual.shape[2],
286
+ dtype, weight_dtype
287
+ )
288
+
289
+ kernel(
290
+ grad,
291
+ prefix_sum,
292
+ block_residual,
293
+ norm_weight,
294
+ proj_weight,
295
+ rsqrt_output,
296
+ max_output,
297
+ exp_output,
298
+ div_output,
299
+ softmax_output,
300
+ doutput,
301
+ dproj_weight,
302
+ dnorm_weight,
303
+ add_workspace,
304
+ )
305
+
306
+ return (
307
+ doutput[:, num_blocks, :].view(num_token, hidden_size),
308
+ doutput[:, 0:num_blocks, :],
309
+ dproj_weight,
310
+ dnorm_weight,
311
+ )
312
+
313
+
314
+
@@ -0,0 +1,188 @@
1
+ import torch
2
+ import tilelang
3
+ import itertools
4
+ from tilelang import language as T
5
+ from tilelang.autotuner import set_autotune_inputs
6
+
7
+
8
+ # @tilelang.autotune(
9
+ # configs=[
10
+ # {"block_size": bs, "threads": th, "num_stages": ns}
11
+ # for bs in [256, 512, 1024]
12
+ # for th in [64]
13
+ # for ns in [1, 2, 3]
14
+ # ],
15
+ # warmup=3,
16
+ # rep=5,
17
+ # do_not_specialize=["block_size", "threads", "num_stages"],
18
+ # )
19
+ @tilelang.jit(
20
+ pass_configs={
21
+ tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
22
+ },
23
+ )
24
+ def block_residual_fwd_kernel(
25
+ num_block,
26
+ hidden_size,
27
+ dtype,
28
+ weight_dtype,
29
+ eps=1e-6,
30
+ block_size=1024,
31
+ threads=64,
32
+ num_stages: int = 2,
33
+ accum_dtype=T.float32,
34
+ ):
35
+ num_token = T.dynamic("num_token")
36
+ total_block = num_block + 1
37
+
38
+ @T.prim_func
39
+ def fwd_kernel(
40
+ prefix_sum: T.Tensor((num_token, hidden_size), dtype),
41
+ block_residual: T.Tensor((num_token, num_block, hidden_size), dtype),
42
+ norm_weight: T.Tensor((hidden_size,), weight_dtype),
43
+ proj_weight: T.Tensor((hidden_size,), weight_dtype),
44
+ # output value
45
+ output: T.Tensor((num_token, hidden_size), dtype),
46
+ rsqrt_output: T.Tensor((num_token, total_block), accum_dtype),
47
+ max_output: T.Tensor((num_token, 1), T.int32),
48
+ exp_output: T.Tensor((num_token, total_block), accum_dtype),
49
+ div_output: T.Tensor((num_token, 1), accum_dtype),
50
+ softmax_output: T.Tensor((num_token, total_block), accum_dtype),
51
+ ):
52
+ with T.Kernel(num_token, threads=threads) as token:
53
+ inv = T.float32(1.0) / hidden_size # ty: ignore
54
+
55
+ rsqrt = T.alloc_shared((total_block,), accum_dtype)
56
+
57
+ hidden_weight_max = T.alloc_fragment((1,), accum_dtype)
58
+ hidden_dot_sum_ptx = T.alloc_fragment((total_block,), accum_dtype)
59
+ hidden_square_sum_ptx = T.alloc_fragment((total_block,), accum_dtype)
60
+
61
+ divisor = T.alloc_fragment((1,), accum_dtype)
62
+ result_ptx = T.alloc_fragment((block_size,), accum_dtype)
63
+
64
+ T.clear(hidden_dot_sum_ptx)
65
+ T.clear(hidden_square_sum_ptx)
66
+
67
+ hidden_share_ptx = T.alloc_shared((total_block, block_size), dtype)
68
+
69
+ for block in T.Pipelined(T.ceildiv(hidden_size, block_size), num_stages=num_stages):
70
+ ptx = block * block_size
71
+
72
+ tile_sum = T.alloc_fragment((total_block,), accum_dtype)
73
+ tile_dot = T.alloc_fragment((total_block,), accum_dtype)
74
+
75
+ weight = T.alloc_fragment((block_size,), accum_dtype)
76
+ hidden_dot_ptx = T.alloc_fragment((total_block, block_size), accum_dtype)
77
+ hidden_square_ptx = T.alloc_fragment((total_block, block_size), accum_dtype)
78
+
79
+ norm_weight_share_ptx = T.alloc_fragment((block_size,), accum_dtype)
80
+ proj_weight_share_ptx = T.alloc_fragment((block_size,), accum_dtype)
81
+
82
+ T.copy(block_residual[token, :, ptx : ptx + block_size], hidden_share_ptx[0:num_block, :])
83
+ T.copy(prefix_sum[token, ptx : ptx + block_size], hidden_share_ptx[num_block:total_block, :])
84
+ T.copy(norm_weight[ptx : ptx + block_size], norm_weight_share_ptx)
85
+ T.copy(proj_weight[ptx : ptx + block_size], proj_weight_share_ptx)
86
+
87
+ for j in T.Parallel(block_size):
88
+ weight[j] = norm_weight_share_ptx[j] * proj_weight_share_ptx[j]
89
+
90
+ for i, j in T.Parallel(total_block, block_size):
91
+ hidden_fp32 = T.cast(hidden_share_ptx[i, j], accum_dtype)
92
+ hidden_dot_ptx[i, j] = hidden_fp32 * weight[j]
93
+ hidden_square_ptx[i, j] = hidden_fp32 * hidden_fp32
94
+
95
+ T.reduce_sum(hidden_dot_ptx, tile_dot, dim=-1)
96
+ T.reduce_sum(hidden_square_ptx, tile_sum, dim=-1)
97
+ for i in T.Parallel(total_block):
98
+ hidden_dot_sum_ptx[i] += tile_dot[i]
99
+ hidden_square_sum_ptx[i] += tile_sum[i]
100
+
101
+ for i in T.Parallel(total_block):
102
+ rsqrt[i] = T.rsqrt(hidden_square_sum_ptx[i] * inv + eps)
103
+
104
+ for i in T.Parallel(total_block):
105
+ hidden_dot_sum_ptx[i] = hidden_dot_sum_ptx[i] * rsqrt[i]
106
+
107
+ T.copy(rsqrt, rsqrt_output[token, :])
108
+
109
+ T.reduce_max(hidden_dot_sum_ptx, hidden_weight_max, dim=-1)
110
+
111
+ idx_ptx = T.alloc_fragment((total_block,), T.int32)
112
+ idx_sum = T.alloc_fragment((1,), T.int32)
113
+
114
+ for i in T.Parallel(total_block):
115
+ idx_ptx[i] = T.if_then_else(
116
+ hidden_dot_sum_ptx[i] == hidden_weight_max[0],
117
+ T.cast(i, T.int32),
118
+ T.int32(total_block), # ty: ignore
119
+ )
120
+ T.reduce_min(idx_ptx, idx_sum, dim=-1)
121
+ T.copy(idx_sum, max_output[token, :])
122
+
123
+ for i in T.Parallel(total_block):
124
+ hidden_dot_sum_ptx[i] = T.exp(hidden_dot_sum_ptx[i] - hidden_weight_max[0])
125
+
126
+ T.copy(hidden_dot_sum_ptx, exp_output[token, :])
127
+
128
+ T.reduce_sum(hidden_dot_sum_ptx, divisor, dim=-1)
129
+
130
+ inv_2 = T.float32(1.0) / divisor[0] # ty: ignore
131
+ T.copy(divisor, div_output[token, :])
132
+
133
+ for i in T.Parallel(total_block):
134
+ hidden_dot_sum_ptx[i] = hidden_dot_sum_ptx[i] * inv_2
135
+
136
+ T.copy(hidden_dot_sum_ptx, softmax_output[token, :])
137
+
138
+ for block in T.Pipelined(T.ceildiv(hidden_size, block_size), num_stages=num_stages):
139
+ T.clear(result_ptx)
140
+
141
+ ptx = block * block_size
142
+ T.copy(block_residual[token, :, ptx : ptx + block_size], hidden_share_ptx[0:num_block, :])
143
+ T.copy(prefix_sum[token, ptx : ptx + block_size], hidden_share_ptx[num_block:total_block, :])
144
+
145
+ for k, j in T.Parallel(total_block, block_size):
146
+ result_ptx[j] += hidden_dot_sum_ptx[k] * T.cast(hidden_share_ptx[k, j], accum_dtype)
147
+
148
+ T.copy(result_ptx, output[token, ptx : ptx + block_size])
149
+
150
+ return fwd_kernel
151
+
152
+
153
+ def block_residual_fwd(prefix_sum, block_residual, proj_weight, norm_weight, eps=1e-6):
154
+ num_token, num_block, hidden_size = block_residual.shape
155
+ total_block = num_block + 1
156
+
157
+ device = block_residual.device
158
+ max_output = torch.empty(num_token, 1, dtype=torch.int32, device=device)
159
+ div_output = torch.empty(num_token, 1, dtype=torch.float32, device=device)
160
+ output = torch.empty(num_token, hidden_size, dtype=block_residual.dtype, device=device)
161
+ exp_output = torch.empty(num_token, total_block, dtype=torch.float32, device=device)
162
+ rsqrt_output = torch.empty(num_token, total_block, dtype=torch.float32, device=device)
163
+ softmax_output = torch.empty(num_token, total_block, dtype=torch.float32, device=device)
164
+
165
+ weight_dtype = str(norm_weight.dtype).replace("torch.", "")
166
+ dtype = str(block_residual.dtype).replace("torch.", "")
167
+
168
+
169
+ kernel = block_residual_fwd_kernel(
170
+ block_residual.shape[1],
171
+ block_residual.shape[2],
172
+ dtype, weight_dtype, eps=eps
173
+ )
174
+
175
+ kernel(
176
+ prefix_sum,
177
+ block_residual,
178
+ proj_weight,
179
+ norm_weight,
180
+ output,
181
+ rsqrt_output,
182
+ max_output,
183
+ exp_output,
184
+ div_output,
185
+ softmax_output,
186
+ )
187
+
188
+ return output, rsqrt_output, max_output, exp_output, div_output, softmax_output
@@ -0,0 +1,18 @@
1
+ import torch
2
+
3
+
4
+ # from https://huggingface.co/moonshotai/Kimi-K3/blob/main/modeling_kimi_linear.py
5
+ def apply_attn_res(prefix_sum, block_residual, proj, norm):
6
+ """
7
+ prefix_sum: (num_tokens, hidden_size)
8
+ block_residual: (num_tokens, num_blocks, hidden_size)
9
+ """
10
+ v = torch.cat((block_residual, prefix_sum.unsqueeze(1)), dim=1)
11
+ v_float = v.float()
12
+ variance = v_float.pow(2).mean(-1, keepdim=True)
13
+ k = v_float * torch.rsqrt(variance + 1e-6)
14
+ score_weight = norm.float() * proj.squeeze(0).float()
15
+ scores = (k * score_weight).sum(-1)
16
+ probs = scores.softmax(-1).unsqueeze(1)
17
+ hidden_states = torch.matmul(probs, v_float).squeeze(1)
18
+ return hidden_states.to(v.dtype)
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: tilelang-attnres
3
+ Version: 0.1.0
4
+ Summary: Attention Residual architecture from Kimi K3 using TileLang, with fused forward and backward kernels.
5
+ Author: Index4NekoMeteor
6
+ License-Expression: Apache-2.0
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Provides-Extra: all
11
+ Requires-Dist: torch>=2.0; extra == "all"
12
+ Requires-Dist: tilelang>=0.1.15; extra == "all"
13
+ Dynamic: license-file
14
+
15
+ # TileLang-AttnRes
16
+
17
+ This repository implements the **Attention Residual** architecture from **Kimi K3** using [TileLang](https://github.com/tile-ai/tilelang), including both **forward** and **backward** kernels. The operators are benchmarked against native PyTorch and `torch.compile`.
18
+
19
+ ## Repository Structure
20
+
21
+ ```text
22
+ Tilelang-AttnRes/
23
+ ├── assets/ # Images / resources
24
+ ├── benchmark/ # Benchmark scripts
25
+ │ ├── benchmark_fwd.py
26
+ │ └── benchmark_bwd.py
27
+ ├── tilelang_attnres/ # Python package
28
+ │ ├── __init__.py # Autograd & nn.Module wrappers
29
+ │ └── kernels/
30
+ │ ├── attn_res_fwd.py # Forward kernel
31
+ │ └── attn_res_bwd.py # Backward kernel
32
+ ├── test.py # Correctness verification script
33
+ ├── requirements.txt
34
+ └── README.md
35
+ ```
36
+
37
+ ## Benchmark
38
+
39
+ ### Testing environment
40
+
41
+ - OS: Windows 11
42
+ - CPU: AMD Ryzen 7 9800X3D
43
+ - GPU: NVIDIA RTX 5080 (16 GB VRAM)
44
+ - Dependencies: see [requirements.txt](requirements.txt)
45
+
46
+ ### Forward
47
+
48
+ **bfloat16:**
49
+
50
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
51
+ | --- | --- | --- | --- | --- | --- | --- | --- |
52
+ | 1280×8×7168 | 0.258 | 5.699 | 1.104 | **22.12×** | 5.16× | 2.34e-05 | 1.90e-05 |
53
+ | 2560×4×7168 | 0.243 | 5.711 | 1.854 | **23.53×** | 3.08× | 2.37e-05 | 2.02e-05 |
54
+ | 5120×2×7168 | 0.398 | 8.079 | 2.666 | **20.29×** | 3.03× | 1.94e-05 | 1.69e-05 |
55
+ | 10240×1×7168 | 0.570 | 11.232| 3.447 | **19.70×** | 3.26× | 1.68e-05 | 1.35e-05 |
56
+ | 7680×8×768 | 0.142 | 3.163 | 1.231 | **22.26×** | 2.57× | 2.55e-05 | 2.38e-05 |
57
+ | 768×1×4096 | 0.032 | 0.223 | 0.101 | **7.06×** | 2.21× | 1.22e-05 | 1.43e-05 |
58
+
59
+ **float32:**
60
+
61
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
62
+ | --- | --- | --- | --- | --- | --- | --- | --- |
63
+ | 1280×8×7168 | 0.432 | 5.121 | 2.152 | **11.84×** | 2.38× | 1.04e-06 | 8.80e-07 |
64
+ | 2560×4×7168 | 0.540 | 5.555 | 2.301 | **10.28×** | 2.41× | 1.13e-06 | 8.18e-07 |
65
+ | 5120×2×7168 | 0.761 | 8.021 | 2.806 | **10.54×** | 2.86× | 9.85e-07 | 7.60e-07 |
66
+ | 10240×1×7168 | 1.298 | 10.252| 3.258 | **7.90×** | 3.15× | 8.55e-07 | 6.57e-07 |
67
+ | 7680×8×768 | 0.280 | 2.966 | 1.680 | **10.61×** | 1.77× | 5.67e-07 | 5.37e-07 |
68
+ | 768×1×4096 | 0.048 | 0.211 | 0.104 | **4.38×** | 2.03× | 6.97e-07 | 4.93e-07 |
69
+
70
+ ### Backward
71
+
72
+ **`rel_err` is the maximum global L2 relative error across all four gradients**
73
+
74
+ **bfloat16:**
75
+
76
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
77
+ | --- | --- | --- | --- | --- | --- | --- | --- |
78
+ | 1280×8×7168 | 0.916 | 16.155 | 4.040 | **17.64×** | 4.00× | 2.41e-04 | 2.22e-04 |
79
+ | 2560×4×7168 | 0.861 | 18.376 | 5.302 | **21.33×** | 3.47× | 3.21e-04 | 2.43e-04 |
80
+ | 5120×2×7168 | 1.021 | 26.337 | 7.984 | **25.80×** | 3.30× | 2.49e-04 | 2.18e-04 |
81
+ | 10240×1×7168| 1.406 | 32.962 | 11.492| **23.45×** | 2.87× | 3.07e-04 | 2.31e-04 |
82
+ | 7680×8×768 | 0.611 | 10.257 | 5.539 | **16.80×** | 1.85× | 1.15e-04 | 1.12e-04 |
83
+ | 768×1×4096 | 0.083 | 0.921 | 0.409 | **11.16×** | 2.25× | 2.90e-04 | 1.52e-04 |
84
+
85
+ **float32:**
86
+
87
+ | Shape | TileLang (ms) | Torch (ms) | Torch Compile (ms) | Speedup (TileLang) | Speedup (Compile) | rel_err TileLang/Torch | rel_err TileLang/Compile |
88
+ | --- | --- | --- | --- | --- | --- | --- | --- |
89
+ | 1280×8×7168 | 1.658 | 14.967 | 5.566 | **9.03×** | 2.69× | 3.15e-05 | 1.57e-05 |
90
+ | 2560×4×7168 | 2.427 | 17.111 | 6.642 | **7.05×** | 2.58× | 2.13e-05 | 1.68e-05 |
91
+ | 5120×2×7168 | 2.347 | 21.645 | 10.614| **9.22×** | 2.04× | 2.13e-05 | 1.48e-05 |
92
+ | 10240×1×7168| 3.316 | 33.348 | 10.281| **10.06×**| 3.24× | 1.94e-05 | 1.86e-05 |
93
+ | 7680×8×768 | 0.943 | 11.038 | 4.543 | **11.71×**| 2.43× | 6.04e-06 | 5.77e-06 |
94
+ | 768×1×4096 | 0.112 | 0.901 | 0.375 | **8.07×** | 2.40× | 1.59e-05 | 1.41e-05 |
95
+
96
+ > **Note**
97
+ > - `rel_err = ‖TileLang − baseline‖₂ / ‖baseline‖₂`, computed in `float32` to avoid bf16 accumulation artifacts in the metric itself.
98
+ > - Timing uses `tilelang.profiler.bench.do_bench` with `warmup=100`.
99
+ > - bf16 backward results are also verified; expected `rel_err` is around `1e-4`.
100
+
101
+ ## Future
102
+
103
+ - [x] Implement backward
104
+
105
+ ## Citation
106
+
107
+ ```bibtex
108
+ @misc{chen2026attnres,
109
+ title = {Attention Residuals},
110
+ author = {Kimi Team and Chen, Guangyu and Zhang, Yu and Su, Jianlin and Xu, Weixin and Pan, Siyuan and Wang, Yaoyu and Wang, Yucheng and Chen, Guanduo and Yin, Bohong and Chen, Yutian and Yan, Junjie and Wei, Ming and Zhang, Y. and Meng, Fanqing and Hong, Chao and Xie, Xiaotong and Liu, Shaowei and Lu, Enzhe and Tai, Yunpeng and Chen, Yanru and Men, Xin and Guo, Haiqing and Charles, Y. and Lu, Haoyu and Sui, Lin and Zhu, Jinguo and Zhou, Zaida and He, Weiran and Huang, Weixiao and Xu, Xinran and Wang, Yuzhi and Lai, Guokun and Du, Yulun and Wu, Yuxin and Yang, Zhilin and Zhou, Xinyu},
111
+ year = {2026},
112
+ archiveprefix = {arXiv},
113
+ eprint = {2603.15031},
114
+ primaryclass = {cs.CL}
115
+ }
116
+ ```
117
+
118
+ ## License
119
+
120
+ This project is licensed under the terms in the [LICENSE](LICENSE) file.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ tilelang_attnres/__init__.py
5
+ tilelang_attnres.egg-info/PKG-INFO
6
+ tilelang_attnres.egg-info/SOURCES.txt
7
+ tilelang_attnres.egg-info/dependency_links.txt
8
+ tilelang_attnres.egg-info/requires.txt
9
+ tilelang_attnres.egg-info/top_level.txt
10
+ tilelang_attnres/kernels/__init__.py
11
+ tilelang_attnres/kernels/attn_res_bwd.py
12
+ tilelang_attnres/kernels/attn_res_fwd.py
13
+ tilelang_attnres/kernels/baseline.py
@@ -0,0 +1,4 @@
1
+
2
+ [all]
3
+ torch>=2.0
4
+ tilelang>=0.1.15
@@ -0,0 +1 @@
1
+ tilelang_attnres