ninetoothed 0.1.0__tar.gz → 0.2.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,18 @@
1
+ name: pytest
2
+ on: [push, pull_request]
3
+ jobs:
4
+ pytest:
5
+ runs-on: ubuntu-latest
6
+ steps:
7
+ - uses: actions/checkout@v4
8
+ - name: Set up Python
9
+ uses: actions/setup-python@v5
10
+ with:
11
+ python-version: "3.10"
12
+ - name: Install dependencies
13
+ run: |
14
+ python -m pip install --upgrade pip
15
+ pip install -r requirements.txt
16
+ - name: Test with pytest
17
+ run: |
18
+ pytest --doctest-modules --junitxml=junit/test-results.xml --cov=ninetoothed --cov-report=xml --cov-report=html
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.3
2
+ Name: ninetoothed
3
+ Version: 0.2.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
+ # NineToothed
16
+
17
+ A domain-specific language (DSL) based on Triton but providing higher-level abstractions.
18
+
19
+ **Other language versions: [English](README.md), [简体中文](docs/README.zh.md).**
20
+
21
+ ## Installation
22
+
23
+ We can use `pip` to install `ninetoothed`.
24
+
25
+ ```shell
26
+ pip install ninetoothed
27
+ ```
28
+
29
+ After successfully running the above command, `ninetoothed` will be installed. However, to fully utilize its capabilities, you also need to install `triton` and a deep learning framework supported by `ninetoothed`. For trial purposes, we recommend installing `triton` and `torch`.
30
+
31
+ ## Usage
32
+
33
+ Currently, we can use the `Tensor` and `Symbol` classes in the `ninetoothed` package to perform meta-operations like `tile` and `expand` to easily construct kernel functions. Below, we will use these features to create vector addition and matrix multiplication kernel functions.
34
+
35
+ ### Vector Addition
36
+
37
+ ```python
38
+ BLOCK_SIZE = Symbol("BLOCK_SIZE", meta=True)
39
+
40
+ @ninetoothed.jit
41
+ def add_kernel(
42
+ x: Tensor(1).tile((BLOCK_SIZE,)),
43
+ y: Tensor(1).tile((BLOCK_SIZE,)),
44
+ z: Tensor(1).tile((BLOCK_SIZE,)),
45
+ ):
46
+ z = x + y
47
+ ```
48
+
49
+ In this code, we first define `BLOCK_SIZE`, which is a `Symbol`. You can think of `"BLOCK_SIZE"` as its name. We see that `meta` is set to `True`, indicating to the compiler that it is a meta-parameter and its value can be determined by the compiler. The `Tensor(1)` constructs a one-dimensional tensor (vector), and `Tensor(1).tile((BLOCK_SIZE,))` means we want to create a vector and divide it into blocks of size `BLOCK_SIZE`. Suppose the size of this vector is `8192` and `BLOCK_SIZE` is `1024`, then the vector will be divided into `8` blocks, each of size `1024`.
50
+
51
+ By using type annotations, we tell the compiler that we will have three tensor parameters, which will be divided into blocks, and `x`, `y`, and `z` are these blocks. It's important to understand that `x`, `y`, and `z` are the blocks, not the tensors themselves. In the function body, `x`, `y`, and `z` are also the blocks. The rest is straightforward (only one line `z = x + y` left, haha), we add each block of `x` and `y` and store it in `z`. Since each block of the parameter tensors undergoes this operation, the addition is completed for the whole tensors as well.
52
+
53
+ ### Matrix Multiplication
54
+
55
+ ```python
56
+ BLOCK_SIZE_M = Symbol("BLOCK_SIZE_M", meta=True)
57
+ BLOCK_SIZE_N = Symbol("BLOCK_SIZE_N", meta=True)
58
+ BLOCK_SIZE_K = Symbol("BLOCK_SIZE_K", meta=True)
59
+
60
+ a_tiled = Tensor(2).tile((BLOCK_SIZE_M, BLOCK_SIZE_K)).tile((1, -1))
61
+ b_tiled = Tensor(2).tile((BLOCK_SIZE_K, BLOCK_SIZE_N)).tile((-1, 1))
62
+ c_tiled = Tensor(2).tile((BLOCK_SIZE_M, BLOCK_SIZE_N))
63
+
64
+ a_tiled = a_tiled.expand((-1, c_tiled.shape[1]))
65
+ b_tiled = b_tiled.expand((c_tiled.shape[0], -1))
66
+
67
+ @ninetoothed.jit
68
+ def matmul_kernel(a: a_tiled, b: b_tiled, c: c_tiled):
69
+ accumulator = ninetoothed.language.zeros(
70
+ c.shape, dtype=ninetoothed.language.float32
71
+ )
72
+ for k in range(a.shape[1]):
73
+ accumulator = ninetoothed.language.dot(a[0, k], b[k, 0], accumulator)
74
+ c = accumulator.to(ninetoothed.language.float16)
75
+ ```
76
+
77
+ For matrix multiplication, we also have three tensor parameters, but the tiling method is more complex than vector addition. We denote the three matrices as $A$, $B$, and $C$, where $A$ and $B$ are inputs, and $C$ is the output. Tiling $C$ is simple; we just need to divide it into blocks of size `(BLOCK_SIZE_M, BLOCK_SIZE_N)` by rows and columns. Once each block computes its result, the entire $C$ is computed. However, how should we tile $A$ and $B$? The answer is to introduce another meta-parameter `BLOCK_SIZE_K`. This way, we can divide $A$ into blocks of size `(BLOCK_SIZE_M, BLOCK_SIZE_K)` and $B$ into blocks of size `(BLOCK_SIZE_K, BLOCK_SIZE_N)`. However, for matrix multiplication, $A$ and $B$ do not correspond block by block; each row of $A$ needs to correspond to each column of $B$. Therefore, we need to further `tile` $A$ and $B$ by rows and columns, respectively. Up to this point, we have a set of row blocks of $A$ and column blocks of $B$. However, each row block of $A$ must correspond to every column block of $B$. This is where `expand` comes in. We `expand` the row blocks of $A$ along the columns to the number of columns of $C$ and the column blocks of $B$ along the rows to the number of rows of $C$. This way, we successfully tile $A$, $B$, and $C$.
78
+
79
+ With tiling done, the rest is simple. In the function body, we define an `accumulator` to accumulate intermediate results. We then iterate through the corresponding row blocks of $A$ and column blocks of B, multiplying them and accumulating the results in `accumulator`. Finally, we place the `accumulator` in the corresponding block of $C$. Since each block of the parameter tensors undergoes this operation, the multiplication is completed for the whole tensors as well.
@@ -0,0 +1,65 @@
1
+ # NineToothed
2
+
3
+ A domain-specific language (DSL) based on Triton but providing higher-level abstractions.
4
+
5
+ **Other language versions: [English](README.md), [简体中文](docs/README.zh.md).**
6
+
7
+ ## Installation
8
+
9
+ We can use `pip` to install `ninetoothed`.
10
+
11
+ ```shell
12
+ pip install ninetoothed
13
+ ```
14
+
15
+ After successfully running the above command, `ninetoothed` will be installed. However, to fully utilize its capabilities, you also need to install `triton` and a deep learning framework supported by `ninetoothed`. For trial purposes, we recommend installing `triton` and `torch`.
16
+
17
+ ## Usage
18
+
19
+ Currently, we can use the `Tensor` and `Symbol` classes in the `ninetoothed` package to perform meta-operations like `tile` and `expand` to easily construct kernel functions. Below, we will use these features to create vector addition and matrix multiplication kernel functions.
20
+
21
+ ### Vector Addition
22
+
23
+ ```python
24
+ BLOCK_SIZE = Symbol("BLOCK_SIZE", meta=True)
25
+
26
+ @ninetoothed.jit
27
+ def add_kernel(
28
+ x: Tensor(1).tile((BLOCK_SIZE,)),
29
+ y: Tensor(1).tile((BLOCK_SIZE,)),
30
+ z: Tensor(1).tile((BLOCK_SIZE,)),
31
+ ):
32
+ z = x + y
33
+ ```
34
+
35
+ In this code, we first define `BLOCK_SIZE`, which is a `Symbol`. You can think of `"BLOCK_SIZE"` as its name. We see that `meta` is set to `True`, indicating to the compiler that it is a meta-parameter and its value can be determined by the compiler. The `Tensor(1)` constructs a one-dimensional tensor (vector), and `Tensor(1).tile((BLOCK_SIZE,))` means we want to create a vector and divide it into blocks of size `BLOCK_SIZE`. Suppose the size of this vector is `8192` and `BLOCK_SIZE` is `1024`, then the vector will be divided into `8` blocks, each of size `1024`.
36
+
37
+ By using type annotations, we tell the compiler that we will have three tensor parameters, which will be divided into blocks, and `x`, `y`, and `z` are these blocks. It's important to understand that `x`, `y`, and `z` are the blocks, not the tensors themselves. In the function body, `x`, `y`, and `z` are also the blocks. The rest is straightforward (only one line `z = x + y` left, haha), we add each block of `x` and `y` and store it in `z`. Since each block of the parameter tensors undergoes this operation, the addition is completed for the whole tensors as well.
38
+
39
+ ### Matrix Multiplication
40
+
41
+ ```python
42
+ BLOCK_SIZE_M = Symbol("BLOCK_SIZE_M", meta=True)
43
+ BLOCK_SIZE_N = Symbol("BLOCK_SIZE_N", meta=True)
44
+ BLOCK_SIZE_K = Symbol("BLOCK_SIZE_K", meta=True)
45
+
46
+ a_tiled = Tensor(2).tile((BLOCK_SIZE_M, BLOCK_SIZE_K)).tile((1, -1))
47
+ b_tiled = Tensor(2).tile((BLOCK_SIZE_K, BLOCK_SIZE_N)).tile((-1, 1))
48
+ c_tiled = Tensor(2).tile((BLOCK_SIZE_M, BLOCK_SIZE_N))
49
+
50
+ a_tiled = a_tiled.expand((-1, c_tiled.shape[1]))
51
+ b_tiled = b_tiled.expand((c_tiled.shape[0], -1))
52
+
53
+ @ninetoothed.jit
54
+ def matmul_kernel(a: a_tiled, b: b_tiled, c: c_tiled):
55
+ accumulator = ninetoothed.language.zeros(
56
+ c.shape, dtype=ninetoothed.language.float32
57
+ )
58
+ for k in range(a.shape[1]):
59
+ accumulator = ninetoothed.language.dot(a[0, k], b[k, 0], accumulator)
60
+ c = accumulator.to(ninetoothed.language.float16)
61
+ ```
62
+
63
+ For matrix multiplication, we also have three tensor parameters, but the tiling method is more complex than vector addition. We denote the three matrices as $A$, $B$, and $C$, where $A$ and $B$ are inputs, and $C$ is the output. Tiling $C$ is simple; we just need to divide it into blocks of size `(BLOCK_SIZE_M, BLOCK_SIZE_N)` by rows and columns. Once each block computes its result, the entire $C$ is computed. However, how should we tile $A$ and $B$? The answer is to introduce another meta-parameter `BLOCK_SIZE_K`. This way, we can divide $A$ into blocks of size `(BLOCK_SIZE_M, BLOCK_SIZE_K)` and $B$ into blocks of size `(BLOCK_SIZE_K, BLOCK_SIZE_N)`. However, for matrix multiplication, $A$ and $B$ do not correspond block by block; each row of $A$ needs to correspond to each column of $B$. Therefore, we need to further `tile` $A$ and $B$ by rows and columns, respectively. Up to this point, we have a set of row blocks of $A$ and column blocks of $B$. However, each row block of $A$ must correspond to every column block of $B$. This is where `expand` comes in. We `expand` the row blocks of $A$ along the columns to the number of columns of $C$ and the column blocks of $B$ along the rows to the number of rows of $C$. This way, we successfully tile $A$, $B$, and $C$.
64
+
65
+ With tiling done, the rest is simple. In the function body, we define an `accumulator` to accumulate intermediate results. We then iterate through the corresponding row blocks of $A$ and column blocks of B, multiplying them and accumulating the results in `accumulator`. Finally, we place the `accumulator` in the corresponding block of $C$. Since each block of the parameter tensors undergoes this operation, the multiplication is completed for the whole tensors as well.
@@ -6,20 +6,13 @@
6
6
 
7
7
  ## 安装
8
8
 
9
- 由于现在 `ninetoothed` 还没有进入到 PyPI,我们需要手动 `git clone` 本仓库,再 `pip install`。
9
+ 我们可以使用 `pip` 安装 `ninetoothed`。
10
10
 
11
11
  ```shell
12
- git clone https://github.com/InfiniTensor/ninetoothed.git
13
- pip install ./ninetoothed
12
+ pip install ninetoothed
14
13
  ```
15
14
 
16
- 成功运行完以上两个命令之后,`ninetoothed` 就被安装好了。需要注意的是,我们目前还没有加入任何的依赖管理,所以如果想要运行 Triton 核函数,那么最起码应该再安装 Triton。
17
-
18
- ```shell
19
- pip install triton
20
- ```
21
-
22
- 其余包可以根据需要自行安装,如 `torch`、`matplotlib`、`pandas` 等。
15
+ 成功运行完以上两个命令之后,`ninetoothed` 就被安装好了。但是除了 `ninetoothed` 的本体之外,如果我们想要真正发挥它的作用,至少还需要安装 `triton` 和一个 `ninetoothed` 所支持的深度学习框架。以尝试为目的的话,我们推荐安装 `triton` 和 `torch`。
23
16
 
24
17
  ## 使用
25
18
 
@@ -67,6 +60,6 @@ def matmul_kernel(a: a_tiled, b: b_tiled, c: c_tiled):
67
60
  c = accumulator.to(ninetoothed.language.float16)
68
61
  ```
69
62
 
70
- 对于矩阵乘法来说,我们也有三个参数张量,但是分块的方式肯定比向量加法要复杂一些。我们将三个矩阵分别记作 ABC,其中 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 的行数那么多行。这样,我们就成功地将 ABC 三者都分好了块,并且对于每一个 C 的块,我们都有对应好的 A 的行块和 B 的列块。
63
+ 对于矩阵乘法来说,我们也有三个参数张量,但是分块的方式肯定比向量加法要复杂一些。我们将三个矩阵分别记作 $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
64
 
72
- 对应好了分块,后续的部分就简单多了。在函数体当中,我们定义了一个 `accumulator`,用于累加中间结果,之后就遍历了对应好的 A 的行块和 B 的列块,并且把他们相乘的结果累加到了 `accumulator` 当中,最后再将 `accumulator` 放到了对应的 C 的分块当中。由于参数张量被分成的每一块都被执行了这样的操作,因此即便对于整体而言,乘法也被完成了。
65
+ 对应好了分块,后续的部分就简单多了。在函数体当中,我们定义了一个 `accumulator`,用于累加中间结果,之后就遍历了对应好的 $A$ 的行块和 $B$ 的列块,并且把他们相乘的结果累加到了 `accumulator` 当中,最后再将 `accumulator` 放到了对应的 $C$ 的分块当中。由于参数张量被分成的每一块都被执行了这样的操作,因此即便对于整体而言,乘法也被完成了。
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "ninetoothed"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  authors = [{ name = "Jiacheng Huang", email = "huangjiacheng0709@outlook.com" }]
9
9
  description = "A domain-specific language based on Triton but providing higher-level abstraction."
10
10
  readme = "README.md"
@@ -18,3 +18,9 @@ classifiers = [
18
18
  [project.urls]
19
19
  Homepage = "https://github.com/InfiniTensor/ninetoothed"
20
20
  Issues = "https://github.com/InfiniTensor/ninetoothed/issues"
21
+
22
+ [tool.ruff]
23
+ src = [".", "src", "tests"]
24
+
25
+ [tool.ruff.lint]
26
+ select = ["E4", "E7", "E9", "F", "I"]
@@ -0,0 +1,7 @@
1
+ matplotlib
2
+ pandas
3
+ pytest
4
+ pytest-cov
5
+ ruff
6
+ torch
7
+ triton
@@ -1,10 +1,10 @@
1
1
  import ast
2
+ import collections
2
3
  import functools
3
4
  import inspect
4
5
  import itertools
5
6
  import math
6
7
  import tempfile
7
- import textwrap
8
8
 
9
9
  from ninetoothed.language import attribute, call
10
10
  from ninetoothed.symbol import Symbol
@@ -12,6 +12,67 @@ from ninetoothed.tensor import Tensor
12
12
  from ninetoothed.torchifier import Torchifier
13
13
 
14
14
 
15
+ def jit(func):
16
+ return JIT(func)()
17
+
18
+
19
+ class JIT:
20
+ handles = collections.defaultdict(dict)
21
+
22
+ def __init__(self, func):
23
+ self.func = func
24
+
25
+ def __call__(self):
26
+ source_file = inspect.getsourcefile(self.func)
27
+ source_line = inspect.getsourcelines(self.func)[1]
28
+
29
+ if (
30
+ source_file in type(self).handles
31
+ and source_line in type(self).handles[source_file]
32
+ ):
33
+ return type(self).handles[source_file][source_line]
34
+
35
+ tree = self._get_tree()
36
+
37
+ CodeGenerator(inspect.get_annotations(self.func)).visit(tree)
38
+ Tritonizer().visit(tree)
39
+ ast.fix_missing_locations(tree)
40
+
41
+ unparsed = ast.unparse(tree).replace("None:", ":").replace(":None", ":")
42
+
43
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".py") as temp_file:
44
+ temp_file.write(unparsed.encode("utf-8"))
45
+ temp_file_name = temp_file.name
46
+
47
+ with open(temp_file_name, "r") as temp_file:
48
+ code = compile(
49
+ source=temp_file.read(),
50
+ filename=temp_file_name,
51
+ mode="exec",
52
+ )
53
+
54
+ namespace = {}
55
+ exec(code, namespace)
56
+
57
+ handle = _Handle(
58
+ namespace[self.func.__name__],
59
+ namespace[f"launch_{self.func.__name__}"],
60
+ )
61
+
62
+ type(self).handles[source_file][source_line] = handle
63
+
64
+ return handle
65
+
66
+ def _get_tree(self):
67
+ module = ast.parse(inspect.getsource(inspect.getmodule(self.func)))
68
+
69
+ _AliasRestorer().visit(module)
70
+ finder = _FunctionDefFinder(self.func.__name__)
71
+ finder.visit(module)
72
+
73
+ return ast.Module(body=[finder.result], type_ignores=[])
74
+
75
+
15
76
  class CodeGenerator(ast.NodeTransformer):
16
77
  def __init__(self, context):
17
78
  super().__init__()
@@ -38,6 +99,18 @@ class CodeGenerator(ast.NodeTransformer):
38
99
 
39
100
  self.generic_visit(node)
40
101
 
102
+ for arg in self._args:
103
+ if not isinstance(arg, Tensor):
104
+ continue
105
+
106
+ node.body.insert(
107
+ 0,
108
+ ast.Assign(
109
+ targets=[Symbol(f"{arg.name}_ptrs").node],
110
+ value=arg.pointers().node,
111
+ ),
112
+ )
113
+
41
114
  return node
42
115
 
43
116
  def visit_arguments(self, node):
@@ -74,12 +147,12 @@ class CodeGenerator(ast.NodeTransformer):
74
147
  value = self._context[node.value.id]
75
148
 
76
149
  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)
150
+ pointers = type(self)._create_pointers(
151
+ value,
152
+ node.slice.elts
153
+ if isinstance(node.slice, ast.Tuple)
154
+ else (node.slice,),
155
+ )
83
156
 
84
157
  return call("load", pointers).node
85
158
 
@@ -104,7 +177,9 @@ class CodeGenerator(ast.NodeTransformer):
104
177
  self.generic_visit(node)
105
178
 
106
179
  if node.id in self._context and isinstance(node.ctx, ast.Load):
107
- return call("load", self._context[node.id].pointers().node).node
180
+ return call(
181
+ "load", type(self)._create_pointers(self._context[node.id], ()).node
182
+ ).node
108
183
 
109
184
  return node
110
185
 
@@ -118,7 +193,7 @@ class CodeGenerator(ast.NodeTransformer):
118
193
  return ast.Expr(
119
194
  call(
120
195
  "store",
121
- self._context[target.id].pointers().node,
196
+ type(self)._create_pointers(self._context[target.id], ()).node,
122
197
  node.value,
123
198
  ).node
124
199
  )
@@ -133,13 +208,12 @@ class CodeGenerator(ast.NodeTransformer):
133
208
  if isinstance(value, Tensor):
134
209
  self.generic_visit(node)
135
210
 
136
- indices = value.indices() + tuple(
211
+ pointers = type(self)._create_pointers(
212
+ value,
137
213
  target.slice.elts
138
214
  if isinstance(target.slice, ast.Tuple)
139
- else target.slice
215
+ else (target.slice,),
140
216
  )
141
- offsets = value.offsets(indices)
142
- pointers = value.pointers(offsets)
143
217
 
144
218
  return ast.Expr(
145
219
  call(
@@ -254,6 +328,14 @@ class CodeGenerator(ast.NodeTransformer):
254
328
 
255
329
  return ast.parse(f"lambda meta: ({num_elements},)", mode="eval").body
256
330
 
331
+ @staticmethod
332
+ def _create_pointers(tensor, indices):
333
+ return Symbol(f"{tensor.name}_ptrs") + tensor.offsets(
334
+ [0 for _ in range(tensor.ndim())]
335
+ + list(indices)
336
+ + [0 for _ in range(tensor.inmost().ndim())]
337
+ )
338
+
257
339
 
258
340
  class Tritonizer(ast.NodeTransformer):
259
341
  def visit_Module(self, node):
@@ -267,8 +349,8 @@ class Tritonizer(ast.NodeTransformer):
267
349
  def visit_Name(self, node):
268
350
  self.generic_visit(node)
269
351
 
270
- if node.id == "ninetoothed":
271
- node.id = "triton"
352
+ if node.id == "ninetoothed" or "ninetoothed." in node.id:
353
+ node.id = node.id.replace("ninetoothed", "triton")
272
354
 
273
355
  return node
274
356
 
@@ -288,32 +370,71 @@ class Tritonizer(ast.NodeTransformer):
288
370
  return node
289
371
 
290
372
 
291
- def jit(func):
292
- source = textwrap.dedent(inspect.getsource(func))
293
- tree = ast.parse(source)
373
+ class _Handle:
374
+ def __init__(self, kernel, launch):
375
+ self._kernel = kernel
376
+ self._launch = launch
377
+
378
+ def __call__(self, *args, **kwargs):
379
+ return self._launch(*args, **kwargs)
380
+
381
+
382
+ class _AliasRestorer(ast.NodeTransformer):
383
+ def __init__(self):
384
+ super().__init__()
385
+
386
+ self._aliases = {}
387
+ self._redefined = set()
388
+
389
+ def visit_Import(self, node):
390
+ for alias in node.names:
391
+ if alias.asname:
392
+ self._aliases[alias.asname] = alias.name
393
+
394
+ return node
395
+
396
+ def visit_ImportFrom(self, node):
397
+ for alias in node.names:
398
+ full_name = f"{node.module}.{alias.name}"
399
+ if alias.asname:
400
+ self._aliases[alias.asname] = full_name
401
+
402
+ return node
294
403
 
295
- CodeGenerator(func.__annotations__).visit(tree)
296
- Tritonizer().visit(tree)
297
- ast.fix_missing_locations(tree)
404
+ def visit_Assign(self, node):
405
+ for target in node.targets:
406
+ if isinstance(target, ast.Name):
407
+ self._redefined.add(target.id)
408
+
409
+ return self.generic_visit(node)
410
+
411
+ def visit_FunctionDef(self, node):
412
+ original_redefined = self._redefined.copy()
413
+
414
+ self.generic_visit(node)
415
+
416
+ self._redefined = original_redefined
298
417
 
299
- unparsed = ast.unparse(tree).replace("None:", ":").replace(":None", ":")
418
+ return node
419
+
420
+ def visit_Name(self, node):
421
+ if node.id in self._redefined:
422
+ return node
300
423
 
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
424
+ if node.id in self._aliases:
425
+ return ast.Name(id=self._aliases[node.id], ctx=node.ctx)
304
426
 
305
- with open(temp_file_name, "r") as temp_file:
306
- code = compile(source=temp_file.read(), filename=temp_file_name, mode="exec")
427
+ return node
307
428
 
308
- namespace = {}
309
- exec(code, namespace)
310
429
 
311
- class Handle:
312
- def __init__(self, kernel, launch):
313
- self._kernel = kernel
314
- self._launch = launch
430
+ class _FunctionDefFinder(ast.NodeVisitor):
431
+ def __init__(self, name):
432
+ self._name = name
315
433
 
316
- def __call__(self, *args, **kwargs):
317
- return self._launch(*args, **kwargs)
434
+ self.result = None
318
435
 
319
- return Handle(namespace[func.__name__], namespace[f"launch_{func.__name__}"])
436
+ def visit_FunctionDef(self, node):
437
+ if node.name == self._name:
438
+ self.result = node
439
+
440
+ self.generic_visit(node)
@@ -34,24 +34,47 @@ class Symbol:
34
34
  self._node.id = type(self)._create_constexpr(self._node.id)
35
35
 
36
36
  def __add__(self, other):
37
- return type(self)(
38
- ast.BinOp(left=self._node, op=ast.Add(), right=type(self)(other)._node)
39
- )
37
+ other = type(self)(other)
38
+
39
+ if isinstance(self._node, ast.Constant) and self._node.value == 0:
40
+ return other
41
+
42
+ if isinstance(other._node, ast.Constant) and other._node.value == 0:
43
+ return self
44
+
45
+ return type(self)(ast.BinOp(left=self._node, op=ast.Add(), right=other._node))
40
46
 
41
47
  def __radd__(self, other):
42
48
  return self.__add__(other)
43
49
 
44
50
  def __mul__(self, other):
45
- return type(self)(
46
- ast.BinOp(left=self._node, op=ast.Mult(), right=type(self)(other)._node)
47
- )
51
+ other = type(self)(other)
52
+
53
+ if isinstance(self._node, ast.Constant) and self._node.value == 0:
54
+ return type(self)(0)
55
+
56
+ if isinstance(other._node, ast.Constant) and other._node.value == 0:
57
+ return type(self)(0)
58
+
59
+ if isinstance(self._node, ast.Constant) and self._node.value == 1:
60
+ return other
61
+
62
+ if isinstance(other._node, ast.Constant) and other._node.value == 1:
63
+ return self
64
+
65
+ return type(self)(ast.BinOp(left=self._node, op=ast.Mult(), right=other._node))
48
66
 
49
67
  def __rmul__(self, other):
50
68
  return self.__mul__(other)
51
69
 
52
70
  def __floordiv__(self, other):
71
+ other = type(self)(other)
72
+
73
+ if isinstance(other._node, ast.Constant) and other._node.value == 1:
74
+ return self
75
+
53
76
  return type(self)(
54
- ast.BinOp(left=self._node, op=ast.FloorDiv(), right=type(self)(other)._node)
77
+ ast.BinOp(left=self._node, op=ast.FloorDiv(), right=other._node)
55
78
  )
56
79
 
57
80
  def __mod__(self, other):
@@ -46,7 +46,7 @@ class Tensor:
46
46
  new_size = call("cdiv", size, tile_size)
47
47
  outer_shape.append(new_size)
48
48
 
49
- new_stride = call("cdiv", stride * size, (new_size * tile_stride))
49
+ new_stride = stride * tile_size // tile_stride
50
50
  outer_strides.append(new_stride)
51
51
 
52
52
  inner_shape.append(tile_size)
@@ -103,11 +103,12 @@ class Tensor:
103
103
  indices = self.indices()
104
104
 
105
105
  if not isinstance(self.dtype, type(self)):
106
- if indices:
106
+ if len(indices) != self.ndim():
107
107
  raise IndexError("Incorrect number of indices.")
108
108
 
109
109
  return sum(
110
- self.stride(idx)
110
+ indices[idx]
111
+ * self.stride(idx)
111
112
  * call("arange", 0, self.size(idx))[
112
113
  tuple(slice(None) if i == idx else None for i in range(self.ndim()))
113
114
  ]
@@ -131,8 +132,21 @@ class Tensor:
131
132
  indices.append(index // stride)
132
133
  index %= stride
133
134
 
135
+ curr = self.dtype
136
+ while isinstance(curr, type(self)):
137
+ indices.extend(
138
+ 0 if curr is not self.inmost() else 1 for _ in range(curr.ndim())
139
+ )
140
+ curr = curr.dtype
141
+
134
142
  return tuple(indices)
135
143
 
144
+ def inmost(self):
145
+ if not isinstance(self.dtype, type(self)):
146
+ return self
147
+
148
+ return self.dtype.inmost()
149
+
136
150
  def ndim(self):
137
151
  return len(self.shape)
138
152
 
File without changes
@@ -0,0 +1,16 @@
1
+ import pytest
2
+ import torch
3
+
4
+
5
+ def skip_if_cuda_not_available(func):
6
+ return pytest.mark.skipif(
7
+ not torch.cuda.is_available(),
8
+ reason="CUDA not available",
9
+ )(func)
10
+
11
+
12
+ def skip_if_float8_e5m2_not_supported(func):
13
+ return pytest.mark.skipif(
14
+ not hasattr(torch, "float8_e5m2"),
15
+ reason="`float8_e5m2` not supported",
16
+ )(func)
@@ -0,0 +1,41 @@
1
+ import torch
2
+
3
+ import ninetoothed
4
+ from ninetoothed import Symbol, Tensor
5
+ from tests.skippers import skip_if_cuda_not_available
6
+
7
+
8
+ def add(lhs, rhs):
9
+ BLOCK_SIZE = Symbol("BLOCK_SIZE", meta=True)
10
+
11
+ @ninetoothed.jit
12
+ def add_kernel(
13
+ lhs: Tensor(1).tile((BLOCK_SIZE,)),
14
+ rhs: Tensor(1).tile((BLOCK_SIZE,)),
15
+ output: Tensor(1).tile((BLOCK_SIZE,)),
16
+ ):
17
+ output = lhs + rhs # noqa: F841
18
+
19
+ output = torch.empty_like(lhs)
20
+
21
+ add_kernel(lhs, rhs, output)
22
+
23
+ return output
24
+
25
+
26
+ @skip_if_cuda_not_available
27
+ class TestCUDA:
28
+ @classmethod
29
+ def setup_class(cls):
30
+ torch.manual_seed(0)
31
+
32
+ size = 98432
33
+
34
+ cls.lhs = torch.rand(size, device="cuda")
35
+ cls.rhs = torch.rand(size, device="cuda")
36
+
37
+ def test_fp32(self):
38
+ lhs = type(self).lhs.to(torch.float32)
39
+ rhs = type(self).rhs.to(torch.float32)
40
+
41
+ assert torch.allclose(add(lhs, rhs), lhs + rhs)
@@ -0,0 +1,71 @@
1
+ import torch
2
+
3
+ import ninetoothed
4
+ import ninetoothed.language as ntl
5
+ from ninetoothed import Symbol, Tensor
6
+ from tests.skippers import skip_if_cuda_not_available, skip_if_float8_e5m2_not_supported
7
+
8
+
9
+ def matmul(lhs, rhs):
10
+ BLOCK_SIZE_M = Symbol("BLOCK_SIZE_M", meta=True)
11
+ BLOCK_SIZE_N = Symbol("BLOCK_SIZE_N", meta=True)
12
+ BLOCK_SIZE_K = Symbol("BLOCK_SIZE_K", meta=True)
13
+
14
+ output_tiled = Tensor(2).tile((BLOCK_SIZE_M, BLOCK_SIZE_N))
15
+
16
+ lhs_tiled = (
17
+ Tensor(2)
18
+ .tile((BLOCK_SIZE_M, BLOCK_SIZE_K))
19
+ .tile((1, -1))
20
+ .expand((-1, output_tiled.shape[1]))
21
+ )
22
+ rhs_tiled = (
23
+ Tensor(2)
24
+ .tile((BLOCK_SIZE_K, BLOCK_SIZE_N))
25
+ .tile((-1, 1))
26
+ .expand((output_tiled.shape[0], -1))
27
+ )
28
+
29
+ @ninetoothed.jit
30
+ def matmul_kernel(lhs: lhs_tiled, rhs: rhs_tiled, output: output_tiled):
31
+ accumulator = ntl.zeros(output.shape, dtype=ntl.float32)
32
+ for k in range(lhs.shape[1]):
33
+ accumulator = ntl.dot(lhs[0, k], rhs[k, 0], accumulator)
34
+ output = accumulator.to(ntl.float16)
35
+
36
+ output = torch.empty(
37
+ (lhs.shape[0], rhs.shape[1]), device=lhs.device, dtype=torch.float16
38
+ )
39
+
40
+ matmul_kernel(lhs, rhs, output)
41
+
42
+ return output
43
+
44
+
45
+ @skip_if_cuda_not_available
46
+ class TestCUDA:
47
+ @classmethod
48
+ def setup_class(cls):
49
+ torch.manual_seed(0)
50
+
51
+ shape = (512, 512)
52
+
53
+ cls.lhs = torch.randn(shape, device="cuda")
54
+ cls.rhs = torch.randn(shape, device="cuda")
55
+
56
+ def test_fp16(self):
57
+ lhs = type(self).lhs.to(torch.float16)
58
+ rhs = type(self).rhs.to(torch.float16)
59
+
60
+ assert torch.allclose(matmul(lhs, rhs), torch.matmul(lhs, rhs))
61
+
62
+ @skip_if_float8_e5m2_not_supported
63
+ def test_fp8(self):
64
+ lhs = type(self).lhs.to(torch.float8_e5m2)
65
+ rhs = type(self).rhs.T.to(torch.float8_e5m2)
66
+
67
+ assert torch.allclose(
68
+ matmul(lhs, rhs),
69
+ torch.matmul(lhs.to(torch.float16), rhs.to(torch.float16)),
70
+ atol=0.125,
71
+ )
@@ -1,19 +0,0 @@
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).**
@@ -1,5 +0,0 @@
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).**
File without changes
File without changes