torchax is a library that serves as a backend for PyTorch, enabling users to run PyTorch programs on JAX-supported hardware like Google Cloud TPUs. It provides seamless graph-level interoperability, allowing the mixing of JAX and PyTorch syntax within the same program, and leveraging JAX features such as `jax.grad`, Optax, and GSPMD for PyTorch model training. The current version is 0.0.11, with development active on GitHub.
pip install torchaxVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to run a standard PyTorch `nn.Module` using torchax. The key steps are to import `torchax`, call `torchax.enable_globally()` *after* model initialization, and then move the model and inputs to the 'jax' device. For improved performance, especially in production, `torchax.interop.JittableModule` (which leverages `jax.jit`) is recommended for compiling the model.
Ensure `torchax.enable_globally()` is called only after your `torch.nn.Module` has been initialized and its weights potentially loaded. For example, `model = MyModel(); torchax.enable_globally(); model.to('jax')`.For performance-critical workloads, always use JAX's Just-In-Time (JIT) compilation. Wrap your model with `torchax.interop.JittableModule` or decorate functions with `torchax.interop.jax_jit` to compile the computation graph for faster execution. The first call will include compilation time, but subsequent calls will be much faster.
For dynamic input shapes, consider using techniques like `StaticCache` (for Hugging Face models) or ensuring that varying dimensions are handled as static arguments (`static_argnums`) if using `jax.jit` directly. Alternatively, refactor the computation to minimize shape changes within JIT-compiled regions.
Utilize `torchax.interop.JittableModule` which handles this by passing weights as explicit arguments, or explicitly convert your PyTorch model to a functional form using `torch.func.functional_call` when interacting with JAX transforms.
Register custom types as JAX pytrees using `jax.tree_util.register_pytree_node`. Refer to JAX documentation and `torchax` examples for correct registration patterns.