Skip to main content

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.

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

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:

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.

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:

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:

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:

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:

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.

Metadata

Release files for jax-ffi-gen 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for jax-ffi-gen 0.7.0
File Size Uploaded Provenance Actions
jax_ffi_gen-0.7.0.tar.gz 19.6 kB Without provenance Details for jax_ffi_gen-0.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for jax-ffi-gen 0.7.0
File Interpreter ABI Platform Actions
jax_ffi_gen-0.7.0-py3-none-any.whl Python 3 none any Details for jax_ffi_gen-0.7.0-py3-none-any.whl

Total release size: 34.2 kB

Release files / jax_ffi_gen-0.7.0.tar.gz

Download URL jax_ffi_gen-0.7.0.tar.gz
Size 19.6 kB
Tags Source
SHA-256 checksum
How to use checksums
6362045558e4d0009c46671d85d73ef81946b7b5a8392680f88dd0e5eb0b9a4f
BLAKE2b-256 checksum
How to use checksums
b1dc3d14ffe5c89cb42708edad2805707e4e6570eb3f7f8a6e084429d682f5e8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.7

Release files / jax_ffi_gen-0.7.0-py3-none-any.whl

Download URL jax_ffi_gen-0.7.0-py3-none-any.whl
Size 14.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fa3ad4e28617c5e1cdc976cc3d90512118c7b99fe9e47963d1864bb3edaf5286
BLAKE2b-256 checksum
How to use checksums
0c686557f42c5a701ff94dada52bb6a9161e8783a5d0e75cd299fecfb28dc522
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.7

Security for jax-ffi-gen 0.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page