Metadata-Version: 2.4
Name: jax-ffi-gen
Version: 0.7.0
Summary: Scripts to auto-generate jax's foreign function interface from CUDA kernels
Author-email: Jens Stücker <jens.stuecker@univie.ac.at>
License-Expression: MIT
Project-URL: Homepage, https://github.com/jstuecker/jax_ffi_gen
Project-URL: Issues, https://github.com/jstuecker/jax_ffi_gen/issues
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: jinja2
Requires-Dist: tree_sitter
Requires-Dist: tree_sitter_cuda
Dynamic: license-file

# JAX-FFI-GEN

A few scripts that help with auto-generating jax's foreign function interface (FFI) binding for CUDA kernels
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.

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.

```python
from pathlib import Path
from jax_ffi_gen import parse, generator

HERE = Path(__file__).resolve().parent

kernels = parse.get_functions_from_file(str(HERE / "my_kernels.cuh"), only_kernels=True)

generator.generate_ffi_module_file(
    output_file = str(HERE / "generated/ffi_my_kernels.cu"), 
    functions = kernels
)
```

The parser will interprete each argument of your kernel as follows:
* `const *` pointer type as an input jax array
* `*` modifiable pointer type as an output jax array
* `const` as a static parameter that needs to be known at jit-compile time

Some useful customization options
```python
kernels = parse.get_functions_from_file(
    str(HERE / "my_kernels.cuh"), 
    names = ["MyKernelA", "MyKernelB"] # only select some kernels by name
)

# Examples of a few useful features that you may need to define per kenrel
kernels["MyKernelA"].init_outputs_zero = True
kernels["MyKernelA"].grid_size_expression = "x.element_count()"
kernels["MyKernelA"].block_size_expression = "64"
kernels["MyKernelA"].smem_size_expression = "blockDim.x * sizeof(float4)" # dynamic shared memory
kernels["MyKernelA"].par["num_particles"].expression = "x.element_count()/3"
kernels["MyKernelA"].template_par["p"].instances = (0,1,2)

# Optionally retain only selected combinations of template parameters. The
# filter receives the original Python instance values by keyword.
kernels["MyKernelA"].template_filter = lambda *, p, **_: p != 1

generator.generate_ffi_module_file(
    output_file = str(HERE / "generated/ffi_new_kernels.cu"), 
    functions = kernels,
    includes = ["../math.cuh"] # set includes
)
```

Other functions of the included sources (e.g. host-only helpers that should share the
module's template instantiations) can be exported with the same module:

```python
generator.generate_ffi_module_file(
    output_file = str(HERE / "generated/ffi_new_kernels.cu"),
    functions = kernels,
    includes = ["../my_kernels.cuh"],
    extra_defs = {"scratch_bytes": "&ScratchBytes"} # m.def("scratch_bytes", &ScratchBytes)
)
```

Template filtering requires **jax-ffi-gen 0.6.1 or newer** when installing from PyPI (the 0.6.0 archives omitted the required templates). The filter receives each combination of template parameter values as keyword arguments and must return a Python `bool`. Only retained combinations are instantiated and included in the generated dispatch; at least one combination must remain. This can reduce CUDA compilation time and binary size when only part of the template matrix is needed.

CPU host functions are supported by setting `function.platform = "cpu"` after
parsing. They have no CUDA stream parameter; generation omits stream binding,
CUDA launch/error handling, and otherwise uses the same template dispatch and
buffer expressions. CUDA remains the default. Generated CPU files need only the
XLA FFI headers and the application's ordinary C++ includes.

```python
functions = parse.get_functions_from_file("host.cc", only_kernels=False)
for function in functions.values():
    function.platform = "cpu"
generator.generate_ffi_module_file("generated_cpu.cc", functions, includes=("host.cc",))
```

The same parsed function description can be generated repeatedly; generation
leaves its native CUDA stream parameter available for subsequent calls.

### Registration for optional backends

For handlers compiled in separate translation units, generate a nanobind
registration table from the same function descriptions:

```python
code = generator.create_ffi_registration_code(
    [(cpu_function, "my_operation"), (cuda_function, "my_operation")],
    platform_guards={"cuda": "ENABLE_CUDA"},
)
```

Include the resulting code in the module and export
`m.def("registrations", &FFIRegistrations)`. Python can register every available
implementation once:

```python
for platform, targets in extension.registrations().items():
    for name, capsule in targets.items():
        jax.ffi.register_ffi_target(name, capsule, platform=platform)
```

One `jax.ffi.ffi_call("my_operation", ...)` then works on either platform.
The guard excludes CUDA declarations and references from CPU-only builds; the
registration header itself requires no CUDA headers. Guards must be defined
only for enabled platforms. Duplicate names within one platform are rejected.

Optional `FunctionInfo.checks` keep input validation in the generated adapter,
so the wrapped implementation need not depend on JAX error types:

```python
function.checks = (("n > 0", "Expected a positive size"),)
```

Each pair contains a C++ boolean expression and a failure message. Checks run
after inferred parameters are computed, before dispatch and execution; failure
returns `ffi::Error::InvalidArgument`. Expressions may reference FFI buffers,
attributes and inferred parameters, but not the later dispatch constants.

A template parameter can receive an FFI attribute directly, without adding a
redundant runtime argument to the native function. Set
`TemplateParamInfo.attribute_name="order"` to keep a Python attribute named
`order` while the C++ template parameter is named `Order`. With no override,
the attribute uses the template parameter's name as before.

Generated C++/CUDA layout is emitted directly by the Jinja templates, using
four-space indentation and a 100-column target. No external formatter is
required. Caller-supplied C++ expressions may contain newlines for readability;
they are indented in the generated body without rewriting their contents.
Long diagnostic strings may exceed the column target.

### Function selection and references

`get_functions_from_file(...)` selects CUDA `__global__` kernels by default.
Use `only_kernels=False` to include host entry points, and `names=("Entry",)`
to request specific functions. Device-only functions are excluded by default.
These selections happen before parameter parsing, so unrelated helpers do not
need supported FFI signatures.

C++ reference parameters (`T&`, `const T&`, `T&&`) are not supported.
Automatic discovery skips functions containing them. Explicitly requesting such
a function raises an error naming the function and reference parameter, rather
than reporting that the function was not found.

### Handler traits and CUDA graphs

Generated handlers declare `xla::ffi::Traits::kCmdBufferCompatible` by default,
preserving the existing behavior. This tells XLA that a handler is safe to capture
into a CUDA graph; it does not make an incompatible implementation capture-safe.
Set `FunctionInfo.traits = ()` for handlers that must execute outside capture:

```python
function.traits = ()
```

Examples include handlers that allocate device memory or create library plans
during execution, synchronize the stream to inspect GPU values on the host, or
perform host-side checks that must run on every invocation rather than only when
the graph is captured. Such handlers can still use generated FFI bindings.

`traits` is a tuple of unqualified `xla::ffi::Traits` enumerator names supported
by the target XLA headers. Multiple entries are emitted as a comma-separated
initializer list, parenthesized to keep it a single macro argument. The caller is
responsible for choosing traits that accurately
describe the handler; see the [XLA FFI trait contract](https://github.com/openxla/xla/blob/main/xla/ffi/api/api.h).
