ninetoothed 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,11 @@
1
+ name: Ruff
2
+ on: [push, pull_request]
3
+ jobs:
4
+ ruff:
5
+ runs-on: ubuntu-latest
6
+ steps:
7
+ - uses: actions/checkout@v4
8
+ - uses: chartboost/ruff-action@v1
9
+ - uses: chartboost/ruff-action@v1
10
+ with:
11
+ args: format --check
@@ -0,0 +1,162 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
@@ -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,19 @@
1
+ Metadata-Version: 2.3
2
+ Name: ninetoothed
3
+ Version: 0.1.0
4
+ Summary: A domain-specific language based on Triton but providing higher-level abstraction.
5
+ Project-URL: Homepage, https://github.com/InfiniTensor/ninetoothed
6
+ Project-URL: Issues, https://github.com/InfiniTensor/ninetoothed/issues
7
+ Author-email: Jiacheng Huang <huangjiacheng0709@outlook.com>
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Nine-Toothed
16
+
17
+ A domain-specific language based on Triton but providing higher-level abstraction.
18
+
19
+ **Read this in other languages: [English](README.md), [简体中文](docs/README.zh.md).**
@@ -0,0 +1,5 @@
1
+ # Nine-Toothed
2
+
3
+ A domain-specific language based on Triton but providing higher-level abstraction.
4
+
5
+ **Read this in other languages: [English](README.md), [简体中文](docs/README.zh.md).**
@@ -0,0 +1,72 @@
1
+ # 九齿
2
+
3
+ 一种基于 Triton 但提供更高层抽象的领域特定语言(DSL)。
4
+
5
+ **其他语言版本: [English](../README.md)、[简体中文](README.zh.md)。**
6
+
7
+ ## 安装
8
+
9
+ 由于现在 `ninetoothed` 还没有进入到 PyPI,我们需要手动 `git clone` 本仓库,再 `pip install`。
10
+
11
+ ```shell
12
+ git clone https://github.com/InfiniTensor/ninetoothed.git
13
+ pip install ./ninetoothed
14
+ ```
15
+
16
+ 成功运行完以上两个命令之后,`ninetoothed` 就被安装好了。需要注意的是,我们目前还没有加入任何的依赖管理,所以如果想要运行 Triton 核函数,那么最起码应该再安装 Triton。
17
+
18
+ ```shell
19
+ pip install triton
20
+ ```
21
+
22
+ 其余包可以根据需要自行安装,如 `torch`、`matplotlib`、`pandas` 等。
23
+
24
+ ## 使用
25
+
26
+ 目前,我们可以通过 `ninetoothed` 包当中的 `Tensor` 和 `Symbol` 类,进行 `tile` 和 `expand` 等元操作,从而简单地构建核函数。下面,我们将使用这些内容构建出向量加法和矩阵乘法核函数。
27
+
28
+ ### 向量加法
29
+
30
+ ```python
31
+ BLOCK_SIZE = Symbol("BLOCK_SIZE", meta=True)
32
+
33
+ @ninetoothed.jit
34
+ def add_kernel(
35
+ x: Tensor(1).tile((BLOCK_SIZE,)),
36
+ y: Tensor(1).tile((BLOCK_SIZE,)),
37
+ z: Tensor(1).tile((BLOCK_SIZE,)),
38
+ ):
39
+ z = x + y
40
+ ```
41
+
42
+ 在这段代码当中,我们首先定义了 `BLOCK_SIZE`,它是一个 `Symbol`,我们可以把 `"BLOCK_SIZE"` 理解成它的名字。我们可以看到 `meta` 被设成了 `True`,这是在告诉编译器,它是一个元参数,可以由编译器决定它的取值。之后出现的 `Tensor(1)` 则是在构造一个一维的张量(向量),`Tensor(1).tile((BLOCK_SIZE,))` 的意思就是说,我们想要构造一个向量,并且把它分成大小为 `BLOCK_SIZE` 的块。假设这个向量的大小为 `8192`,而 `BLOCK_SIZE` 是 `1024`,那么这个向量就会被分成 `8` 块,每一块的大小都是 `1024`。
43
+
44
+ 我们通过类型标注的方式,告诉了编译器,我们将会有三个参数张量,并且每个参数张量,都会被按照这样的方式分块,而 `x`、`y`、`z` 就是被分成的块。这一点很重要,我们要意识到,`x`、`y`、`z` 是被分成的块,而不是被分块的张量本身,并且函数体当中的 `x`、`y`、`z` 也都是被分成的块。剩下的就很好理解了(也就剩下 `z = x + y` 一行了,哈哈哈),我们把每一块 `x` 和 `y` 相加,放到了 `z` 中,由于参数张量被分成的每一块都被执行了这样的操作,因此即便对于整体而言,加法也被完成了。
45
+
46
+ ### 矩阵乘法
47
+
48
+ ```python
49
+ BLOCK_SIZE_M = Symbol("BLOCK_SIZE_M", meta=True)
50
+ BLOCK_SIZE_N = Symbol("BLOCK_SIZE_N", meta=True)
51
+ BLOCK_SIZE_K = Symbol("BLOCK_SIZE_K", meta=True)
52
+
53
+ a_tiled = Tensor(2).tile((BLOCK_SIZE_M, BLOCK_SIZE_K)).tile((1, -1))
54
+ b_tiled = Tensor(2).tile((BLOCK_SIZE_K, BLOCK_SIZE_N)).tile((-1, 1))
55
+ c_tiled = Tensor(2).tile((BLOCK_SIZE_M, BLOCK_SIZE_N))
56
+
57
+ a_tiled = a_tiled.expand((-1, c_tiled.shape[1]))
58
+ b_tiled = b_tiled.expand((c_tiled.shape[0], -1))
59
+
60
+ @ninetoothed.jit
61
+ def matmul_kernel(a: a_tiled, b: b_tiled, c: c_tiled):
62
+ accumulator = ninetoothed.language.zeros(
63
+ c.shape, dtype=ninetoothed.language.float32
64
+ )
65
+ for k in range(a.shape[1]):
66
+ accumulator = ninetoothed.language.dot(a[0, k], b[k, 0], accumulator)
67
+ c = accumulator.to(ninetoothed.language.float16)
68
+ ```
69
+
70
+ 对于矩阵乘法来说,我们也有三个参数张量,但是分块的方式肯定比向量加法要复杂一些。我们将三个矩阵分别记作 A、B、C,其中 A 和 B 为输入,C 为输出。其中 C 的分块操作很简单,我们只需要按照行和列,将其分成大小为 `(BLOCK_SIZE_M, BLOCK_SIZE_N)` 的块即可,这样只要每个这样的块都算出了结果,整个 C 也就都算出了结果。那么该如何分 A 和 B 呢?答案是再引入一个元参数 `BLOCK_SIZE_K`,这样我们就可以把 A 分成 `(BLOCK_SIZE_M, BLOCK_SIZE_K)` 大小的块,把 B 分成 `(BLOCK_SIZE_K, BLOCK_SIZE_N)` 的块。但是对于矩阵乘法,A 和 B 并不是块块对应,而是需要对应 A 的每一行和 B 的每一列,所以我们还需要继续 `tile`,把 A 和 B 进一步分成以行为单位和以列为单位的块。到目前为止,我们有了一堆 A 的行块和 B 的列块,但是对于每一个 A 的行块,我们都要对应 B 的每一个列块。这个时候,我们就需要进行 `expand` 了,我们把 A 的行块沿着列 `expand` 成 C 的列数那么多列,把 B 的列块沿着行 `expand` 成 C 的行数那么多行。这样,我们就成功地将 A、B、C 三者都分好了块,并且对于每一个 C 的块,我们都有对应好的 A 的行块和 B 的列块。
71
+
72
+ 对应好了分块,后续的部分就简单多了。在函数体当中,我们定义了一个 `accumulator`,用于累加中间结果,之后就遍历了对应好的 A 的行块和 B 的列块,并且把他们相乘的结果累加到了 `accumulator` 当中,最后再将 `accumulator` 放到了对应的 C 的分块当中。由于参数张量被分成的每一块都被执行了这样的操作,因此即便对于整体而言,乘法也被完成了。
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ninetoothed"
7
+ version = "0.1.0"
8
+ authors = [{ name = "Jiacheng Huang", email = "huangjiacheng0709@outlook.com" }]
9
+ description = "A domain-specific language based on Triton but providing higher-level abstraction."
10
+ readme = "README.md"
11
+ requires-python = ">=3.10"
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "License :: OSI Approved :: Apache Software License",
15
+ "Operating System :: OS Independent",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/InfiniTensor/ninetoothed"
20
+ Issues = "https://github.com/InfiniTensor/ninetoothed/issues"
@@ -0,0 +1,5 @@
1
+ from ninetoothed.jit import jit
2
+ from ninetoothed.symbol import Symbol
3
+ from ninetoothed.tensor import Tensor
4
+
5
+ __all__ = ["Symbol", "Tensor", "jit"]
@@ -0,0 +1,319 @@
1
+ import ast
2
+ import functools
3
+ import inspect
4
+ import itertools
5
+ import math
6
+ import tempfile
7
+ import textwrap
8
+
9
+ from ninetoothed.language import attribute, call
10
+ from ninetoothed.symbol import Symbol
11
+ from ninetoothed.tensor import Tensor
12
+ from ninetoothed.torchifier import Torchifier
13
+
14
+
15
+ class CodeGenerator(ast.NodeTransformer):
16
+ def __init__(self, context):
17
+ super().__init__()
18
+
19
+ self._context = context
20
+
21
+ self._args = list(self._context.values())
22
+
23
+ self._POWER_OF_TWOS = tuple(2**n for n in range(5, 11))
24
+
25
+ self._MIN_PRODUCT = 2**10
26
+
27
+ self._MAX_PRODUCT = 2**20
28
+
29
+ def visit_Module(self, node):
30
+ self.generic_visit(node)
31
+
32
+ node.body.append(self._launch)
33
+
34
+ return node
35
+
36
+ def visit_FunctionDef(self, node):
37
+ self._func_def = node
38
+
39
+ self.generic_visit(node)
40
+
41
+ return node
42
+
43
+ def visit_arguments(self, node):
44
+ self.generic_visit(node)
45
+
46
+ names_of_args = [arg.names() - {"ninetoothed"} for arg in self._args]
47
+ names = functools.reduce(lambda x, y: x | y, names_of_args)
48
+ meta_names = {name for name in names if Symbol.is_meta(name)}
49
+ non_meta_names = {name for name in names if name not in meta_names}
50
+
51
+ node.args = [
52
+ ast.arg(arg=name)
53
+ if not Symbol.is_constexpr(name)
54
+ else ast.arg(arg=name, annotation=attribute("constexpr"))
55
+ for name in non_meta_names
56
+ ] + [
57
+ ast.arg(arg=name, annotation=attribute("constexpr").node)
58
+ for name in meta_names
59
+ ]
60
+
61
+ autotune = self._generate_autotune(non_meta_names, meta_names)
62
+ self._func_def.decorator_list.insert(0, autotune)
63
+
64
+ self._launch = self._generate_launch(non_meta_names, meta_names)
65
+
66
+ return node
67
+
68
+ def visit_Subscript(self, node):
69
+ if (
70
+ isinstance(node.value, ast.Name)
71
+ and node.value.id in self._context
72
+ and isinstance(node.ctx, ast.Load)
73
+ ):
74
+ value = self._context[node.value.id]
75
+
76
+ if isinstance(value, Tensor):
77
+ if isinstance(node.slice, ast.Tuple):
78
+ indices = value.indices() + tuple(node.slice.elts)
79
+ else:
80
+ indices = value.indices() + (node.slice,)
81
+ offsets = value.offsets(indices)
82
+ pointers = value.pointers(offsets)
83
+
84
+ return call("load", pointers).node
85
+
86
+ self.generic_visit(node)
87
+
88
+ return node
89
+
90
+ def visit_Attribute(self, node):
91
+ if isinstance(node.value, ast.Name) and node.value.id in self._context:
92
+ value = self._context[node.value.id]
93
+
94
+ if isinstance(value, Tensor):
95
+ inner = value.dtype
96
+
97
+ return Symbol(inner.__dict__[node.attr]).node
98
+
99
+ self.generic_visit(node)
100
+
101
+ return node
102
+
103
+ def visit_Name(self, node):
104
+ self.generic_visit(node)
105
+
106
+ if node.id in self._context and isinstance(node.ctx, ast.Load):
107
+ return call("load", self._context[node.id].pointers().node).node
108
+
109
+ return node
110
+
111
+ def visit_Assign(self, node):
112
+ if len(node.targets) == 1:
113
+ target = node.targets[0]
114
+
115
+ if isinstance(target, ast.Name) and target.id in self._context:
116
+ self.generic_visit(node)
117
+
118
+ return ast.Expr(
119
+ call(
120
+ "store",
121
+ self._context[target.id].pointers().node,
122
+ node.value,
123
+ ).node
124
+ )
125
+ elif (
126
+ isinstance(target, ast.Subscript)
127
+ and isinstance(target.value, ast.Name)
128
+ and target.value.id in self._context
129
+ and isinstance(target.ctx, ast.Store)
130
+ ):
131
+ value = self._context[target.value.id]
132
+
133
+ if isinstance(value, Tensor):
134
+ self.generic_visit(node)
135
+
136
+ indices = value.indices() + tuple(
137
+ target.slice.elts
138
+ if isinstance(target.slice, ast.Tuple)
139
+ else target.slice
140
+ )
141
+ offsets = value.offsets(indices)
142
+ pointers = value.pointers(offsets)
143
+
144
+ return ast.Expr(
145
+ call(
146
+ "store",
147
+ pointers.node,
148
+ node.value,
149
+ ).node
150
+ )
151
+
152
+ self.generic_visit(node)
153
+
154
+ return node
155
+
156
+ def _generate_autotune(self, params, meta):
157
+ configs = [
158
+ ast.Call(
159
+ func=ast.Attribute(
160
+ value=ast.Name(id="ninetoothed", ctx=ast.Load()),
161
+ attr="Config",
162
+ ctx=ast.Load(),
163
+ ),
164
+ args=[
165
+ ast.Dict(
166
+ keys=[ast.Constant(value=param) for param in meta],
167
+ values=[ast.Constant(value=value) for value in values],
168
+ )
169
+ ],
170
+ keywords=[],
171
+ )
172
+ for values in itertools.product(self._POWER_OF_TWOS, repeat=len(meta))
173
+ if self._MIN_PRODUCT <= math.prod(values) <= self._MAX_PRODUCT
174
+ ]
175
+
176
+ return ast.Call(
177
+ func=ast.Attribute(
178
+ value=ast.Name(id="ninetoothed", ctx=ast.Load()),
179
+ attr="autotune",
180
+ ctx=ast.Load(),
181
+ ),
182
+ args=[],
183
+ keywords=[
184
+ ast.keyword(
185
+ arg="configs",
186
+ value=ast.List(
187
+ elts=configs,
188
+ ctx=ast.Load(),
189
+ ),
190
+ ),
191
+ ast.keyword(
192
+ arg="key",
193
+ value=ast.List(
194
+ elts=[
195
+ ast.Constant(value=param)
196
+ for param in params
197
+ if not Tensor.is_pointer(param)
198
+ ],
199
+ ctx=ast.Load(),
200
+ ),
201
+ ),
202
+ ],
203
+ )
204
+
205
+ def _generate_launch(self, params, meta):
206
+ launch = ast.FunctionDef(
207
+ name=f"launch_{self._func_def.name}",
208
+ args=ast.arguments(
209
+ posonlyargs=[],
210
+ args=[ast.arg(arg.name) for arg in self._args],
211
+ kwonlyargs=[],
212
+ defaults=[],
213
+ ),
214
+ body=[
215
+ ast.Expr(
216
+ ast.Call(
217
+ func=ast.Subscript(
218
+ value=ast.Name(id=self._func_def.name, ctx=ast.Load()),
219
+ slice=self._generate_grid(),
220
+ ctx=ast.Load(),
221
+ ),
222
+ args=[ast.Name(id=param, ctx=ast.Load()) for param in params],
223
+ keywords=[],
224
+ )
225
+ )
226
+ ],
227
+ decorator_list=[],
228
+ )
229
+
230
+ class MetaEncloser(ast.NodeTransformer):
231
+ def __init__(self, meta):
232
+ self._meta = meta
233
+
234
+ def visit_Name(self, node):
235
+ self.generic_visit(node)
236
+
237
+ if node.id in self._meta:
238
+ return ast.Subscript(
239
+ value=ast.Name(id="meta", ctx=ast.Load()),
240
+ slice=ast.Constant(value=node.id),
241
+ ctx=ast.Load(),
242
+ )
243
+
244
+ return node
245
+
246
+ MetaEncloser(meta).visit(launch)
247
+
248
+ Torchifier().visit(launch)
249
+
250
+ return launch
251
+
252
+ def _generate_grid(self):
253
+ num_elements = functools.reduce(lambda x, y: x * y, self._args[0].shape)
254
+
255
+ return ast.parse(f"lambda meta: ({num_elements},)", mode="eval").body
256
+
257
+
258
+ class Tritonizer(ast.NodeTransformer):
259
+ def visit_Module(self, node):
260
+ self.generic_visit(node)
261
+
262
+ node.body.insert(0, ast.Import(names=[ast.alias(name="triton.language")]))
263
+ node.body.insert(0, ast.Import(names=[ast.alias(name="triton")]))
264
+
265
+ return node
266
+
267
+ def visit_Name(self, node):
268
+ self.generic_visit(node)
269
+
270
+ if node.id == "ninetoothed":
271
+ node.id = "triton"
272
+
273
+ return node
274
+
275
+ def visit_Call(self, node):
276
+ self.generic_visit(node)
277
+
278
+ if (
279
+ isinstance(node.func, ast.Attribute)
280
+ and isinstance(node.func.value, ast.Name)
281
+ and node.func.value.id == "triton"
282
+ and node.func.attr == "jit"
283
+ ):
284
+ return ast.Attribute(
285
+ value=ast.Name(id="triton", ctx=ast.Load()), attr="jit", ctx=ast.Load()
286
+ )
287
+
288
+ return node
289
+
290
+
291
+ def jit(func):
292
+ source = textwrap.dedent(inspect.getsource(func))
293
+ tree = ast.parse(source)
294
+
295
+ CodeGenerator(func.__annotations__).visit(tree)
296
+ Tritonizer().visit(tree)
297
+ ast.fix_missing_locations(tree)
298
+
299
+ unparsed = ast.unparse(tree).replace("None:", ":").replace(":None", ":")
300
+
301
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".py") as temp_file:
302
+ temp_file.write(unparsed.encode("utf-8"))
303
+ temp_file_name = temp_file.name
304
+
305
+ with open(temp_file_name, "r") as temp_file:
306
+ code = compile(source=temp_file.read(), filename=temp_file_name, mode="exec")
307
+
308
+ namespace = {}
309
+ exec(code, namespace)
310
+
311
+ class Handle:
312
+ def __init__(self, kernel, launch):
313
+ self._kernel = kernel
314
+ self._launch = launch
315
+
316
+ def __call__(self, *args, **kwargs):
317
+ return self._launch(*args, **kwargs)
318
+
319
+ return Handle(namespace[func.__name__], namespace[f"launch_{func.__name__}"])
@@ -0,0 +1,19 @@
1
+ import ast
2
+
3
+ from ninetoothed.symbol import Symbol
4
+
5
+ LANGUAGE = "ninetoothed.language"
6
+
7
+
8
+ def call(func, *args, **kwargs):
9
+ return Symbol(
10
+ ast.Call(
11
+ func=attribute(func).node,
12
+ args=[Symbol(arg).node for arg in args],
13
+ keywords=[(kwarg, Symbol(kwargs[kwarg]).node) for kwarg in kwargs],
14
+ )
15
+ )
16
+
17
+
18
+ def attribute(attr):
19
+ return Symbol(ast.parse(f"{LANGUAGE}.{attr}", mode="eval").body)
@@ -0,0 +1,109 @@
1
+ import ast
2
+ import inspect
3
+ import types
4
+
5
+
6
+ class Symbol:
7
+ def __init__(self, expr, constexpr=None, meta=None):
8
+ if isinstance(expr, type(self)):
9
+ self._node = expr._node
10
+ return
11
+
12
+ if isinstance(expr, ast.AST):
13
+ self._node = expr
14
+ return
15
+
16
+ if isinstance(expr, types.CodeType):
17
+ expr = inspect.getsource(expr)
18
+
19
+ if not isinstance(expr, str):
20
+ expr = str(expr)
21
+
22
+ self._node = ast.parse(expr, mode="eval").body
23
+
24
+ if (constexpr or meta) and not isinstance(self._node, ast.Name):
25
+ raise ValueError("`constexpr` and `meta` are properties of name symbols.")
26
+
27
+ if meta:
28
+ if constexpr is False:
29
+ raise ValueError("Non-constexpr meta symbol is not supported.")
30
+
31
+ self._node.id = type(self)._create_meta(self._node.id)
32
+
33
+ if constexpr:
34
+ self._node.id = type(self)._create_constexpr(self._node.id)
35
+
36
+ def __add__(self, other):
37
+ return type(self)(
38
+ ast.BinOp(left=self._node, op=ast.Add(), right=type(self)(other)._node)
39
+ )
40
+
41
+ def __radd__(self, other):
42
+ return self.__add__(other)
43
+
44
+ def __mul__(self, other):
45
+ return type(self)(
46
+ ast.BinOp(left=self._node, op=ast.Mult(), right=type(self)(other)._node)
47
+ )
48
+
49
+ def __rmul__(self, other):
50
+ return self.__mul__(other)
51
+
52
+ def __floordiv__(self, other):
53
+ return type(self)(
54
+ ast.BinOp(left=self._node, op=ast.FloorDiv(), right=type(self)(other)._node)
55
+ )
56
+
57
+ def __mod__(self, other):
58
+ return type(self)(
59
+ ast.BinOp(left=self._node, op=ast.Mod(), right=type(self)(other)._node)
60
+ )
61
+
62
+ def __getitem__(self, key):
63
+ return type(self)(ast.Subscript(value=self._node, slice=type(self)(key)._node))
64
+
65
+ def __repr__(self):
66
+ return ast.unparse(self._node)
67
+
68
+ def names(self):
69
+ class NameCollector(ast.NodeVisitor):
70
+ def __init__(self):
71
+ self.names = set()
72
+
73
+ def visit_Name(self, node):
74
+ self.generic_visit(node)
75
+
76
+ self.names.add(node.id)
77
+
78
+ name_collector = NameCollector()
79
+
80
+ name_collector.visit(self._node)
81
+
82
+ return name_collector.names
83
+
84
+ @property
85
+ def node(self):
86
+ class SliceSimplifier(ast.NodeTransformer):
87
+ def visit_Call(self, node):
88
+ if isinstance(node.func, ast.Name) and node.func.id == "slice":
89
+ return ast.Slice(*node.args)
90
+
91
+ return node
92
+
93
+ return SliceSimplifier().visit(self._node)
94
+
95
+ @staticmethod
96
+ def is_constexpr(name):
97
+ return name.startswith("_ninetoothed_constexpr_") or Symbol.is_meta(name)
98
+
99
+ @staticmethod
100
+ def is_meta(name):
101
+ return name.startswith("_ninetoothed_meta_")
102
+
103
+ @staticmethod
104
+ def _create_constexpr(name):
105
+ return f"_ninetoothed_constexpr_{name}"
106
+
107
+ @staticmethod
108
+ def _create_meta(name):
109
+ return f"_ninetoothed_meta_{name}"
@@ -0,0 +1,165 @@
1
+ import itertools
2
+
3
+ from ninetoothed.language import call
4
+ from ninetoothed.symbol import Symbol
5
+
6
+
7
+ class Tensor:
8
+ num_instances = 0
9
+
10
+ def __init__(self, ndim=None, shape=None, dtype=None, strides=None, name=None):
11
+ type(self).num_instances += 1
12
+
13
+ self.dtype = dtype
14
+
15
+ if name is not None:
16
+ self.name = name
17
+ else:
18
+ self.name = f"tensor_{type(self).num_instances}"
19
+
20
+ if ndim is not None:
21
+ self.shape = [Symbol(f"{self.name}_size_{i}") for i in range(ndim)]
22
+ self.strides = [Symbol(f"{self.name}_stride_{i}") for i in range(ndim)]
23
+ else:
24
+ self.shape = shape
25
+
26
+ if strides is not None:
27
+ self.strides = strides
28
+ else:
29
+ self.strides = self._calculate_default_strides(shape)
30
+
31
+ def tile(self, tile_shape, tile_strides=None):
32
+ if tile_strides is None:
33
+ tile_strides = [1 for _ in tile_shape]
34
+
35
+ outer_shape = []
36
+ outer_strides = []
37
+ inner_shape = []
38
+ inner_strides = []
39
+
40
+ for size, stride, tile_size, tile_stride in zip(
41
+ self.shape, self.strides, tile_shape, tile_strides
42
+ ):
43
+ if tile_size == -1:
44
+ tile_size = size
45
+
46
+ new_size = call("cdiv", size, tile_size)
47
+ outer_shape.append(new_size)
48
+
49
+ new_stride = call("cdiv", stride * size, (new_size * tile_stride))
50
+ outer_strides.append(new_stride)
51
+
52
+ inner_shape.append(tile_size)
53
+ next_stride = stride * tile_stride
54
+ inner_strides.append(next_stride)
55
+
56
+ return type(self)(
57
+ shape=outer_shape,
58
+ dtype=type(self)(
59
+ shape=inner_shape,
60
+ dtype=self.dtype,
61
+ strides=inner_strides,
62
+ name=self.name,
63
+ ),
64
+ strides=outer_strides,
65
+ name=self.name,
66
+ )
67
+
68
+ def expand(self, shape):
69
+ # TODO: Add error handling.
70
+ return type(self)(
71
+ shape=[
72
+ new_size if new_size != -1 else size
73
+ for size, new_size in zip(self.shape, shape)
74
+ ],
75
+ dtype=self.dtype,
76
+ strides=[
77
+ stride if new_size == -1 else 0
78
+ for new_size, stride in zip(shape, self.strides)
79
+ ],
80
+ name=self.name,
81
+ )
82
+
83
+ def names(self):
84
+ return (
85
+ {self._pointer()}
86
+ | {
87
+ name
88
+ for value in itertools.chain(self.shape, self.strides)
89
+ if isinstance(value, Symbol)
90
+ for name in value.names()
91
+ }
92
+ | (self.dtype.names() if isinstance(self.dtype, type(self)) else set())
93
+ )
94
+
95
+ def pointers(self, offsets=None):
96
+ if offsets is None:
97
+ offsets = self.offsets()
98
+
99
+ return self._pointer() + offsets
100
+
101
+ def offsets(self, indices=None):
102
+ if indices is None:
103
+ indices = self.indices()
104
+
105
+ if not isinstance(self.dtype, type(self)):
106
+ if indices:
107
+ raise IndexError("Incorrect number of indices.")
108
+
109
+ return sum(
110
+ self.stride(idx)
111
+ * call("arange", 0, self.size(idx))[
112
+ tuple(slice(None) if i == idx else None for i in range(self.ndim()))
113
+ ]
114
+ for idx in range(self.ndim())
115
+ )
116
+
117
+ outer_indices = indices[: self.ndim()]
118
+ inner_indices = indices[self.ndim() :]
119
+
120
+ return sum(
121
+ index * stride for index, stride in zip(outer_indices, self.strides)
122
+ ) + self.dtype.offsets(inner_indices)
123
+
124
+ def indices(self, index=None):
125
+ if index is None:
126
+ index = call("program_id", 0)
127
+
128
+ indices = []
129
+
130
+ for stride in type(self)(shape=self.shape, name=self.name).strides:
131
+ indices.append(index // stride)
132
+ index %= stride
133
+
134
+ return tuple(indices)
135
+
136
+ def ndim(self):
137
+ return len(self.shape)
138
+
139
+ def size(self, dim=None):
140
+ if dim is None:
141
+ return self.shape
142
+
143
+ return self.shape[dim]
144
+
145
+ def stride(self, dim=None):
146
+ if dim is None:
147
+ return self.strides
148
+
149
+ return self.strides[dim]
150
+
151
+ @staticmethod
152
+ def is_pointer(name):
153
+ return name.endswith("_ptr")
154
+
155
+ def _pointer(self):
156
+ return f"{self.name}_ptr"
157
+
158
+ @staticmethod
159
+ def _calculate_default_strides(shape):
160
+ strides = [1]
161
+
162
+ for size in shape[1:]:
163
+ strides.append(size * strides[-1])
164
+
165
+ return reversed(strides)
@@ -0,0 +1,34 @@
1
+ import ast
2
+ import re
3
+
4
+
5
+ class Torchifier(ast.NodeTransformer):
6
+ def visit_Name(self, node):
7
+ self.generic_visit(node)
8
+
9
+ pattern = re.compile(r"([a-zA-Z_][a-zA-Z0-9_]*)_(size|stride)_(.+)")
10
+
11
+ node.id = node.id.replace("_ptr", "")
12
+
13
+ if re.fullmatch(pattern, node.id):
14
+ return ast.parse(
15
+ pattern.sub(
16
+ lambda match: f"{match.group(1)}.{match.group(2)}({match.group(3)})",
17
+ node.id,
18
+ ),
19
+ mode="eval",
20
+ ).body
21
+
22
+ return node
23
+
24
+ def visit_Attribute(self, node):
25
+ self.generic_visit(node)
26
+
27
+ if (
28
+ isinstance(node.value, ast.Name)
29
+ and node.value.id == "ninetoothed"
30
+ and node.attr == "language"
31
+ ):
32
+ return node.value
33
+
34
+ return node