torch2jax_without_vjp — forward-only with sharding support
Use this for multi-GPU sharding (output_sharding_spec) and keyword arguments (example_kw).
torch2jax_without_vjp
torch2jax.api._torch2jax(fn, *example_args, example_kw=None, output_shapes=None, output_sharding_spec=None, vmap_method='sequential')
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
|
output_sharding_spec
|
PartitionSpec | None
|
jax.sharding.PartitionSpec specifying the sharding spec of the output, uses input mesh. |
None
|
vmap_method
|
str
|
batching method, see https://docs.jax.dev/en/latest/ffi.html#batching-with-vmap NOTE: only vmap_method="sequntial" is supported non-experimentally NOTE: try "expand_dims", "broadcast_all" if you want to experiment with pytorch-side batching |
'sequential'
|
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
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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | |