torch2jax_without_vjp — forward-only
Use this for keyword arguments (example_kw). For multi-device sharding (out_specs), torch2jax works with
and without gradients, see the multi-device guide.
torch2jax_without_vjp
torch2jax.api._torch2jax(fn, *example_args, example_kw=None, output_shapes=None, out_specs=None, vmap_method='sequential', lock=False, output_sharding_spec=None)
Define a jit-compatible JAX function that calls a PyTorch function. Arbitrary nesting of arguments and outputs is supported.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable
|
PyTorch function to wrap. |
required |
*example_args
|
Any
|
Example arguments as tensors or torch-compatible args. |
()
|
example_kw
|
Any | None
|
Example keyword arguments. Defaults to None. |
None
|
output_shapes
|
Any
|
Output shapes or shapes + dtype struct. Defaults to None. |
None
|
out_specs
|
Any | None
|
Output PartitionSpec(s) (a prefix of the output tree) for inputs sharded along explicit mesh axes.
The torch function is then called per-shard inside |
None
|
vmap_method
|
str
|
batching method, see https://docs.jax.dev/en/latest/ffi.html#batching-with-vmap NOTE: only vmap_method="sequential" is supported non-experimentally NOTE: try "expand_dims", "broadcast_all" if you want to experiment with pytorch-side batching |
'sequential'
|
lock
|
bool | AbstractContextManager
|
Call the torch function under a lock: |
False
|
output_sharding_spec
|
PartitionSpec | None
|
Deprecated alias for |
None
|
Returns: Callable: JIT-compatible JAX function.
Examples:
>>> import torch, jax
>>> from torch2jax import torch2jax_with_vjp, tree_t2j
>>> # let's define the torch function and create some example arguments
>>> torch_fn = lambda x, y: torch.nn.CrossEntropyLoss()(x, y)
>>> xt, yt = torch.randn(10, 5), torch.randint(0, 5, (10,))
>>> # we can now convert the function to jax using the torch fn and example args
>>> jax_fn = torch2jax_with_vjp(torch_fn, xt, yt)
>>> jax_fn = jax.jit(jax_fn) # we can jit it too
>>> # let's convert the arguments to JAX arrays and call the function
>>> x, y = tree_t2j((xt, yt))
>>> jax_fn(x, y)
>>> # it works!
Source code in torch2jax/api.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |