jax-ffi-gen 0.5.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.
- jax_ffi_gen-0.5.0/LICENSE +21 -0
- jax_ffi_gen-0.5.0/PKG-INFO +65 -0
- jax_ffi_gen-0.5.0/README.md +47 -0
- jax_ffi_gen-0.5.0/pyproject.toml +28 -0
- jax_ffi_gen-0.5.0/setup.cfg +4 -0
- jax_ffi_gen-0.5.0/src/jax_ffi_gen/generator.py +71 -0
- jax_ffi_gen-0.5.0/src/jax_ffi_gen/parse.py +218 -0
- jax_ffi_gen-0.5.0/src/jax_ffi_gen.egg-info/PKG-INFO +65 -0
- jax_ffi_gen-0.5.0/src/jax_ffi_gen.egg-info/SOURCES.txt +10 -0
- jax_ffi_gen-0.5.0/src/jax_ffi_gen.egg-info/dependency_links.txt +1 -0
- jax_ffi_gen-0.5.0/src/jax_ffi_gen.egg-info/requires.txt +3 -0
- jax_ffi_gen-0.5.0/src/jax_ffi_gen.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jens Stücker
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jax-ffi-gen
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Scripts to auto-generate jax's foreign function interface from CUDA kernels
|
|
5
|
+
Author-email: Jens Stücker <jens.stuecker@univie.ac.at>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jstuecker/jax_ffi_gen
|
|
8
|
+
Project-URL: Issues, https://github.com/jstuecker/jax_ffi_gen/issues
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: jinja2
|
|
15
|
+
Requires-Dist: tree_sitter
|
|
16
|
+
Requires-Dist: tree_sitter_cuda
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# JAX-FFI-GEN
|
|
20
|
+
|
|
21
|
+
A few scripts that help with auto-generating jax's foreign function interface (FFI) binding for CUDA kernels
|
|
22
|
+
This code uses `tree_sitter` to parse CUDA code and `jinja2` to auto-generate the corresponding FFI. This is useful for establishing a workflow where one "almost" directly calls CUDA kernels rather than worrying too much about the large amount of boiler plate code that comes with jax's FFI.
|
|
23
|
+
|
|
24
|
+
It is recommended to put a little python script next to the CUDA source files and execute it every time one needs to regenerate some source file, because the corresponding kernel interface changed.
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from jax_ffi_gen import parse, generator
|
|
29
|
+
|
|
30
|
+
HERE = Path(__file__).resolve().parent
|
|
31
|
+
|
|
32
|
+
kernels = parse.get_functions_from_file(str(HERE / "my_kernels.cuh"), only_kernels=True)
|
|
33
|
+
|
|
34
|
+
generator.generate_ffi_module_file(
|
|
35
|
+
output_file = str(HERE / "generated/ffi_my_kernels.cu"),
|
|
36
|
+
functions = kernels
|
|
37
|
+
)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The parser will interprete each argument of your kernel as follows:
|
|
41
|
+
* `const *` pointer type as an input jax array
|
|
42
|
+
* `*` modifiable pointer type as an output jax array
|
|
43
|
+
* `const` as a static parameter that needs to be known at jit-compile time
|
|
44
|
+
|
|
45
|
+
Some useful customization options
|
|
46
|
+
```python
|
|
47
|
+
kernels = parse.get_functions_from_file(
|
|
48
|
+
str(HERE / "my_kernels.cuh"),
|
|
49
|
+
names = ["MyKernelA", "MyKernelB"] # only select some kernels by name
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Examples of a few useful features that you may need to define per kenrel
|
|
53
|
+
kernels["MyKernelA"].init_outputs_zero = True
|
|
54
|
+
kernels["MyKernelA"].grid_size_expression = "x.element_count()"
|
|
55
|
+
kernels["MyKernelA"].block_size_expression = "64"
|
|
56
|
+
kernels["MyKernelA"].smem_size_expression = "blockDim.x * sizeof(float4)" # dynamic shared memory
|
|
57
|
+
kernels["MyKernelA"].par["num_particles"].expression = "x.element_count()/3"
|
|
58
|
+
kernels["MyKernelA"].template_par["p"].instances = (0,1,2)
|
|
59
|
+
|
|
60
|
+
generator.generate_ffi_module_file(
|
|
61
|
+
output_file = str(HERE / "generated/ffi_new_kernels.cu"),
|
|
62
|
+
functions = kernels,
|
|
63
|
+
includes = ["../math.cuh"] # set includes
|
|
64
|
+
)
|
|
65
|
+
```
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# JAX-FFI-GEN
|
|
2
|
+
|
|
3
|
+
A few scripts that help with auto-generating jax's foreign function interface (FFI) binding for CUDA kernels
|
|
4
|
+
This code uses `tree_sitter` to parse CUDA code and `jinja2` to auto-generate the corresponding FFI. This is useful for establishing a workflow where one "almost" directly calls CUDA kernels rather than worrying too much about the large amount of boiler plate code that comes with jax's FFI.
|
|
5
|
+
|
|
6
|
+
It is recommended to put a little python script next to the CUDA source files and execute it every time one needs to regenerate some source file, because the corresponding kernel interface changed.
|
|
7
|
+
|
|
8
|
+
```python
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from jax_ffi_gen import parse, generator
|
|
11
|
+
|
|
12
|
+
HERE = Path(__file__).resolve().parent
|
|
13
|
+
|
|
14
|
+
kernels = parse.get_functions_from_file(str(HERE / "my_kernels.cuh"), only_kernels=True)
|
|
15
|
+
|
|
16
|
+
generator.generate_ffi_module_file(
|
|
17
|
+
output_file = str(HERE / "generated/ffi_my_kernels.cu"),
|
|
18
|
+
functions = kernels
|
|
19
|
+
)
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The parser will interprete each argument of your kernel as follows:
|
|
23
|
+
* `const *` pointer type as an input jax array
|
|
24
|
+
* `*` modifiable pointer type as an output jax array
|
|
25
|
+
* `const` as a static parameter that needs to be known at jit-compile time
|
|
26
|
+
|
|
27
|
+
Some useful customization options
|
|
28
|
+
```python
|
|
29
|
+
kernels = parse.get_functions_from_file(
|
|
30
|
+
str(HERE / "my_kernels.cuh"),
|
|
31
|
+
names = ["MyKernelA", "MyKernelB"] # only select some kernels by name
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# Examples of a few useful features that you may need to define per kenrel
|
|
35
|
+
kernels["MyKernelA"].init_outputs_zero = True
|
|
36
|
+
kernels["MyKernelA"].grid_size_expression = "x.element_count()"
|
|
37
|
+
kernels["MyKernelA"].block_size_expression = "64"
|
|
38
|
+
kernels["MyKernelA"].smem_size_expression = "blockDim.x * sizeof(float4)" # dynamic shared memory
|
|
39
|
+
kernels["MyKernelA"].par["num_particles"].expression = "x.element_count()/3"
|
|
40
|
+
kernels["MyKernelA"].template_par["p"].instances = (0,1,2)
|
|
41
|
+
|
|
42
|
+
generator.generate_ffi_module_file(
|
|
43
|
+
output_file = str(HERE / "generated/ffi_new_kernels.cu"),
|
|
44
|
+
functions = kernels,
|
|
45
|
+
includes = ["../math.cuh"] # set includes
|
|
46
|
+
)
|
|
47
|
+
```
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "jax-ffi-gen"
|
|
3
|
+
version = "0.5.0"
|
|
4
|
+
requires-python = ">=3.10"
|
|
5
|
+
dependencies = [
|
|
6
|
+
"jinja2",
|
|
7
|
+
"tree_sitter",
|
|
8
|
+
"tree_sitter_cuda"
|
|
9
|
+
]
|
|
10
|
+
description = "Scripts to auto-generate jax's foreign function interface from CUDA kernels"
|
|
11
|
+
authors = [
|
|
12
|
+
{ name="Jens Stücker", email="jens.stuecker@univie.ac.at" }
|
|
13
|
+
]
|
|
14
|
+
readme = "README.md"
|
|
15
|
+
license = "MIT"
|
|
16
|
+
license-files = ["LICEN[CS]E*"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://github.com/jstuecker/jax_ffi_gen"
|
|
24
|
+
Issues = "https://github.com/jstuecker/jax_ffi_gen/issues"
|
|
25
|
+
|
|
26
|
+
[build-system]
|
|
27
|
+
requires = ["setuptools>=68", "wheel"]
|
|
28
|
+
build-backend = "setuptools.build_meta"
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from .parse import FunctionInfo
|
|
2
|
+
from jinja2 import Environment, PackageLoader, select_autoescape
|
|
3
|
+
from dataclasses import dataclass, replace
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
env = Environment(
|
|
7
|
+
loader=PackageLoader("jax_ffi_gen", "templates"),
|
|
8
|
+
autoescape=select_autoescape()
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
def simplify_and_validate(func: FunctionInfo) -> FunctionInfo:
|
|
12
|
+
if not func.is_kernel:
|
|
13
|
+
assert tuple(func.par.keys())[0] == "stream", "All Host functions must use stream as first parameter"
|
|
14
|
+
del func.par["stream"] # will be added automatically
|
|
15
|
+
|
|
16
|
+
# convert pars to lists for easier templating
|
|
17
|
+
func = replace(
|
|
18
|
+
func,
|
|
19
|
+
par = list(func.par.values())
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
for name,p in func.template_par.items():
|
|
23
|
+
if (len(p.instances) == 0) and (p.type == "bool"):
|
|
24
|
+
p.instances = ("true", "false")
|
|
25
|
+
elif len(p.instances) == 0:
|
|
26
|
+
raise ValueError(f"Please define instances for template parameter {p.name} "
|
|
27
|
+
f"in function {func.name}.")
|
|
28
|
+
|
|
29
|
+
return func
|
|
30
|
+
|
|
31
|
+
def create_ffi_call(func: FunctionInfo) -> str:
|
|
32
|
+
func = simplify_and_validate(func)
|
|
33
|
+
|
|
34
|
+
template = env.get_template("template_ffi_call.j2")
|
|
35
|
+
return template.render(f=func)
|
|
36
|
+
|
|
37
|
+
def create_ffi_module_code(funcs: list[FunctionInfo],
|
|
38
|
+
includes: tuple[str] = (),
|
|
39
|
+
module_name: str = "ffi_module") -> str:
|
|
40
|
+
if type(funcs) is dict:
|
|
41
|
+
funcs = list(funcs.values())
|
|
42
|
+
|
|
43
|
+
new_funcs = []
|
|
44
|
+
for f in funcs:
|
|
45
|
+
new_funcs.append(simplify_and_validate(f))
|
|
46
|
+
|
|
47
|
+
template = env.get_template("template_ffi_module.j2")
|
|
48
|
+
return template.render(functions=new_funcs, includes=includes, module_name=module_name)
|
|
49
|
+
|
|
50
|
+
def generate_ffi_module_file(output_file: str,
|
|
51
|
+
functions: list[FunctionInfo],
|
|
52
|
+
includes: tuple[str] = (),
|
|
53
|
+
module_name: str | None = None) -> None:
|
|
54
|
+
if module_name is None:
|
|
55
|
+
module_name = output_file.split("/")[-1].split(".")[0]
|
|
56
|
+
|
|
57
|
+
code = create_ffi_module_code(functions, includes, module_name)
|
|
58
|
+
|
|
59
|
+
if os.path.exists(output_file):
|
|
60
|
+
with open(output_file, 'r') as f:
|
|
61
|
+
txt = f.read()
|
|
62
|
+
if txt == code:
|
|
63
|
+
print(f"No changes to generated file at {output_file}")
|
|
64
|
+
return
|
|
65
|
+
else:
|
|
66
|
+
print(f"Updating generated file at {output_file}")
|
|
67
|
+
else:
|
|
68
|
+
print(f"Generating new file file at {output_file}")
|
|
69
|
+
|
|
70
|
+
with open(output_file, 'w') as f:
|
|
71
|
+
f.write(code)
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
import tree_sitter_cuda
|
|
5
|
+
from tree_sitter import Language, Parser, Query, QueryCursor, Node, Tree
|
|
6
|
+
except ImportError as e:
|
|
7
|
+
raise ImportError("Please install tree-sitter and tree-sitter-cuda packages to use this module.") from e
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
def std_dtype_to_ffi_enum(typename):
|
|
12
|
+
dtype_map = {
|
|
13
|
+
"float": "F32",
|
|
14
|
+
"double": "F64",
|
|
15
|
+
"int": "S32",
|
|
16
|
+
"int32_t": "S32",
|
|
17
|
+
"int64_t": "S64",
|
|
18
|
+
"long long": "S64",
|
|
19
|
+
"int16_t": "S16",
|
|
20
|
+
"short": "S16",
|
|
21
|
+
"int8_t": "S8",
|
|
22
|
+
"uint32_t": "U32",
|
|
23
|
+
"unsigned int": "U32",
|
|
24
|
+
"uint64_t": "U64",
|
|
25
|
+
"unsigned long long": "U64",
|
|
26
|
+
"uint16_t": "U16",
|
|
27
|
+
"unsigned short": "U16",
|
|
28
|
+
"uint8_t": "U8",
|
|
29
|
+
"half": "F16",
|
|
30
|
+
"__half": "F16",
|
|
31
|
+
"bool": "PRED"
|
|
32
|
+
}
|
|
33
|
+
if typename in dtype_map:
|
|
34
|
+
return "DT::" + dtype_map[typename]
|
|
35
|
+
else:
|
|
36
|
+
raise ValueError(f"Unknown datatype {typename}, cannot map to FFI type...")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class ParamInfo():
|
|
41
|
+
type : str = ""
|
|
42
|
+
name : str = ""
|
|
43
|
+
is_ptr : bool = False
|
|
44
|
+
is_const : bool = False
|
|
45
|
+
expression : str = ""
|
|
46
|
+
init_zero : bool = False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class TemplateParamInfo():
|
|
51
|
+
type : str = ""
|
|
52
|
+
name : str = ""
|
|
53
|
+
instances : list[str] = ()
|
|
54
|
+
expression : str = ""
|
|
55
|
+
dtype_from_buffer : str = "" # Buffer parameter name to extract dtype from
|
|
56
|
+
|
|
57
|
+
def ctype(self):
|
|
58
|
+
"""Return the C type for dispatch tuples (DT for typename, type otherwise)"""
|
|
59
|
+
return "DT" if self.type == "typename" else self.type
|
|
60
|
+
|
|
61
|
+
def dispatch_values(self):
|
|
62
|
+
if self.type != "typename":
|
|
63
|
+
return self.instances
|
|
64
|
+
|
|
65
|
+
return tuple(map(std_dtype_to_ffi_enum, self.instances))
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class FunctionInfo():
|
|
69
|
+
name : str
|
|
70
|
+
par : dict[str, ParamInfo]
|
|
71
|
+
type : str = "void"
|
|
72
|
+
is_kernel : bool = False
|
|
73
|
+
template_par : list[str, ParamInfo] = field(default_factory=dict)
|
|
74
|
+
block_size_expression : str = ""
|
|
75
|
+
grid_size_expression : str = ""
|
|
76
|
+
smem_size_expression : str = ""
|
|
77
|
+
init_outputs_zero : bool = False
|
|
78
|
+
|
|
79
|
+
def template_values_flat(self):
|
|
80
|
+
all_perm = np.meshgrid(*[p.instances for p in self.template_par.values()], indexing='ij')
|
|
81
|
+
return np.stack(all_perm, axis=-1).reshape(-1, len(self.template_par))
|
|
82
|
+
|
|
83
|
+
def dispatch_values_flat(self):
|
|
84
|
+
"""Returns dispatch key values derived from instances."""
|
|
85
|
+
values_list = [p.dispatch_values() for p in self.template_par.values()]
|
|
86
|
+
|
|
87
|
+
all_perm = np.meshgrid(*values_list, indexing='ij')
|
|
88
|
+
return np.stack(all_perm, axis=-1).reshape(-1, len(self.template_par))
|
|
89
|
+
|
|
90
|
+
def dispatch_values_str(self):
|
|
91
|
+
return [", ".join([str(v) for v in vals]) for vals in self.dispatch_values_flat()]
|
|
92
|
+
|
|
93
|
+
def template_values_str(self):
|
|
94
|
+
return [", ".join([str(v) for v in vals]) for vals in self.template_values_flat()]
|
|
95
|
+
|
|
96
|
+
CUDA = Language(tree_sitter_cuda.language())
|
|
97
|
+
parser = Parser(CUDA)
|
|
98
|
+
|
|
99
|
+
def node_text(node: Node, txt: str) -> str:
|
|
100
|
+
return txt[node.start_byte:node.end_byte]
|
|
101
|
+
|
|
102
|
+
def query(node: Node, query_src: str) -> dict:
|
|
103
|
+
q = QueryCursor(Query(CUDA, query_src))
|
|
104
|
+
caps = q.captures(node)
|
|
105
|
+
|
|
106
|
+
return caps
|
|
107
|
+
|
|
108
|
+
def interprete_parameter_list(node_param: Node, txt: str) -> dict[str, ParamInfo]:
|
|
109
|
+
assert node_param.type == "parameter_list"
|
|
110
|
+
|
|
111
|
+
res = {}
|
|
112
|
+
for c in node_param.named_children:
|
|
113
|
+
if c.type == "comment": continue
|
|
114
|
+
|
|
115
|
+
assert (c.type == "parameter_declaration") or (c.type == "optional_parameter_declaration")
|
|
116
|
+
|
|
117
|
+
pinfo = ParamInfo()
|
|
118
|
+
|
|
119
|
+
tq = query(c, '(type_qualifier)? @tq')
|
|
120
|
+
pinfo.is_const = any(node_text(cap, txt) == "const" for cap in tq.get("tq", []))
|
|
121
|
+
|
|
122
|
+
pinfo.type = node_text(c.child_by_field_name("type"), txt)
|
|
123
|
+
|
|
124
|
+
decl = c.child_by_field_name("declarator")
|
|
125
|
+
if decl.type == "identifier":
|
|
126
|
+
pinfo.name = node_text(decl, txt)
|
|
127
|
+
elif decl.type == "pointer_declarator":
|
|
128
|
+
pinfo.is_ptr = True
|
|
129
|
+
pinfo.name = node_text(decl.child_by_field_name("declarator"), txt)
|
|
130
|
+
else:
|
|
131
|
+
raise ValueError("Unknown type %s" % decl.type)
|
|
132
|
+
|
|
133
|
+
res[pinfo.name] = pinfo
|
|
134
|
+
|
|
135
|
+
return res
|
|
136
|
+
|
|
137
|
+
def interprete_template_list(node_param: Node, txt: str) -> dict[str, TemplateParamInfo]:
|
|
138
|
+
assert node_param.type == "template_parameter_list"
|
|
139
|
+
|
|
140
|
+
res = {}
|
|
141
|
+
for c in node_param.named_children:
|
|
142
|
+
assert c.type in ("parameter_declaration", "type_parameter_declaration", "optional_parameter_declaration")
|
|
143
|
+
|
|
144
|
+
pinfo = TemplateParamInfo()
|
|
145
|
+
if c.type == "parameter_declaration":
|
|
146
|
+
pinfo.type = node_text(c.child_by_field_name("type"), txt)
|
|
147
|
+
pinfo.name = node_text(c.child_by_field_name("declarator"), txt)
|
|
148
|
+
elif c.type == "type_parameter_declaration":
|
|
149
|
+
# Handle typename/class template parameters (e.g., "typename T" or "class T")
|
|
150
|
+
pinfo.type = "typename"
|
|
151
|
+
# The type identifier is typically the last named child
|
|
152
|
+
pinfo.name = node_text(c.named_children[-1], txt)
|
|
153
|
+
elif c.type == "optional_parameter_declaration":
|
|
154
|
+
pinfo.type = node_text(c.child_by_field_name("type"), txt)
|
|
155
|
+
pinfo.name = node_text(c.child_by_field_name("declarator"), txt)
|
|
156
|
+
pinfo.instances = []
|
|
157
|
+
|
|
158
|
+
res[pinfo.name] = pinfo
|
|
159
|
+
|
|
160
|
+
return res
|
|
161
|
+
|
|
162
|
+
def get_functions(node: Node, txt: str, skip_device=True) -> dict[str, FunctionInfo]:
|
|
163
|
+
query_func = f"""
|
|
164
|
+
(function_definition
|
|
165
|
+
("__device__")? @fdevice
|
|
166
|
+
("__global__")? @fglobal
|
|
167
|
+
type: (_) @ftype
|
|
168
|
+
declarator: (function_declarator
|
|
169
|
+
declarator: (identifier) @fname
|
|
170
|
+
parameters: (parameter_list) @fparam
|
|
171
|
+
)
|
|
172
|
+
) @node
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
cursor = QueryCursor(Query(CUDA, query_func))
|
|
176
|
+
res = {}
|
|
177
|
+
for i,match in cursor.matches(node):
|
|
178
|
+
if skip_device and (match.get("fdevice") is not None):
|
|
179
|
+
continue
|
|
180
|
+
|
|
181
|
+
if (not "ftemp" in match) and () :
|
|
182
|
+
print("template function")
|
|
183
|
+
new_func = FunctionInfo(
|
|
184
|
+
name = node_text(match["fname"][0], txt),
|
|
185
|
+
par = interprete_parameter_list(match["fparam"][0], txt),
|
|
186
|
+
type = node_text(match["ftype"][0], txt),
|
|
187
|
+
is_kernel = match.get("fglobal") is not None
|
|
188
|
+
)
|
|
189
|
+
parent = match["node"][0].parent
|
|
190
|
+
if parent.type == "template_declaration":
|
|
191
|
+
tpar_list = parent.child_by_field_name("parameters")
|
|
192
|
+
new_func.template_par = interprete_template_list(tpar_list, txt)
|
|
193
|
+
|
|
194
|
+
res[new_func.name] = new_func
|
|
195
|
+
|
|
196
|
+
return res
|
|
197
|
+
|
|
198
|
+
def build_tree_sitter(file_path: str) -> tuple[Tree, str]:
|
|
199
|
+
with open(file_path, 'r') as f:
|
|
200
|
+
txt = f.read()
|
|
201
|
+
tree = parser.parse(txt.encode())
|
|
202
|
+
return tree, txt
|
|
203
|
+
|
|
204
|
+
def get_functions_from_file(file_path: str, only_kernels: bool = True, names: tuple[str] = None
|
|
205
|
+
) -> dict[str, FunctionInfo]:
|
|
206
|
+
tree, txt = build_tree_sitter(file_path)
|
|
207
|
+
funcs = get_functions(tree.root_node, txt)
|
|
208
|
+
|
|
209
|
+
if only_kernels:
|
|
210
|
+
funcs = {k:v for k,v in funcs.items() if v.is_kernel}
|
|
211
|
+
|
|
212
|
+
if names is not None:
|
|
213
|
+
funcs = {k:v for k,v in funcs.items() if k in names}
|
|
214
|
+
for name in names:
|
|
215
|
+
if name not in funcs:
|
|
216
|
+
raise ValueError(f"Function {name} not found in file {file_path}")
|
|
217
|
+
|
|
218
|
+
return funcs
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jax-ffi-gen
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Scripts to auto-generate jax's foreign function interface from CUDA kernels
|
|
5
|
+
Author-email: Jens Stücker <jens.stuecker@univie.ac.at>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jstuecker/jax_ffi_gen
|
|
8
|
+
Project-URL: Issues, https://github.com/jstuecker/jax_ffi_gen/issues
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: jinja2
|
|
15
|
+
Requires-Dist: tree_sitter
|
|
16
|
+
Requires-Dist: tree_sitter_cuda
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# JAX-FFI-GEN
|
|
20
|
+
|
|
21
|
+
A few scripts that help with auto-generating jax's foreign function interface (FFI) binding for CUDA kernels
|
|
22
|
+
This code uses `tree_sitter` to parse CUDA code and `jinja2` to auto-generate the corresponding FFI. This is useful for establishing a workflow where one "almost" directly calls CUDA kernels rather than worrying too much about the large amount of boiler plate code that comes with jax's FFI.
|
|
23
|
+
|
|
24
|
+
It is recommended to put a little python script next to the CUDA source files and execute it every time one needs to regenerate some source file, because the corresponding kernel interface changed.
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from jax_ffi_gen import parse, generator
|
|
29
|
+
|
|
30
|
+
HERE = Path(__file__).resolve().parent
|
|
31
|
+
|
|
32
|
+
kernels = parse.get_functions_from_file(str(HERE / "my_kernels.cuh"), only_kernels=True)
|
|
33
|
+
|
|
34
|
+
generator.generate_ffi_module_file(
|
|
35
|
+
output_file = str(HERE / "generated/ffi_my_kernels.cu"),
|
|
36
|
+
functions = kernels
|
|
37
|
+
)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The parser will interprete each argument of your kernel as follows:
|
|
41
|
+
* `const *` pointer type as an input jax array
|
|
42
|
+
* `*` modifiable pointer type as an output jax array
|
|
43
|
+
* `const` as a static parameter that needs to be known at jit-compile time
|
|
44
|
+
|
|
45
|
+
Some useful customization options
|
|
46
|
+
```python
|
|
47
|
+
kernels = parse.get_functions_from_file(
|
|
48
|
+
str(HERE / "my_kernels.cuh"),
|
|
49
|
+
names = ["MyKernelA", "MyKernelB"] # only select some kernels by name
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Examples of a few useful features that you may need to define per kenrel
|
|
53
|
+
kernels["MyKernelA"].init_outputs_zero = True
|
|
54
|
+
kernels["MyKernelA"].grid_size_expression = "x.element_count()"
|
|
55
|
+
kernels["MyKernelA"].block_size_expression = "64"
|
|
56
|
+
kernels["MyKernelA"].smem_size_expression = "blockDim.x * sizeof(float4)" # dynamic shared memory
|
|
57
|
+
kernels["MyKernelA"].par["num_particles"].expression = "x.element_count()/3"
|
|
58
|
+
kernels["MyKernelA"].template_par["p"].instances = (0,1,2)
|
|
59
|
+
|
|
60
|
+
generator.generate_ffi_module_file(
|
|
61
|
+
output_file = str(HERE / "generated/ffi_new_kernels.cu"),
|
|
62
|
+
functions = kernels,
|
|
63
|
+
includes = ["../math.cuh"] # set includes
|
|
64
|
+
)
|
|
65
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/jax_ffi_gen/generator.py
|
|
5
|
+
src/jax_ffi_gen/parse.py
|
|
6
|
+
src/jax_ffi_gen.egg-info/PKG-INFO
|
|
7
|
+
src/jax_ffi_gen.egg-info/SOURCES.txt
|
|
8
|
+
src/jax_ffi_gen.egg-info/dependency_links.txt
|
|
9
|
+
src/jax_ffi_gen.egg-info/requires.txt
|
|
10
|
+
src/jax_ffi_gen.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
jax_ffi_gen
|