code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _compile_to_executable( name: str, fun: Callable[..., Any], in_specs_treedef: tree_util.PyTreeDef, in_specs_leaves: tuple[api.ShapeDtypeStruct, ...], out_specs_treedef: tree_util.PyTreeDef, out_specs_leaves: tuple[api.ShapeDtypeStruct, ...], devices: xc.DeviceList, ) -> Callable[..., Any...
Compiles a Python function into a runtime executable.
_compile_to_executable
python
jax-ml/jax
jax/experimental/colocated_python/func.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/func.py
Apache-2.0
def _make_output_specs_and_push_result_fun( info: FunctionInfo, specialization: Specialization, uid: int ) -> Callable[..., Any]: """Creates a function that computes output specs and pushes the result to the result store.""" assert specialization.in_specs_treedef is not None assert specialization.in_specs_lea...
Creates a function that computes output specs and pushes the result to the result store.
_make_output_specs_and_push_result_fun
python
jax-ml/jax
jax/experimental/colocated_python/func.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/func.py
Apache-2.0
def _make_pop_result_fun( info: FunctionInfo, specialization: Specialization, uid: int ) -> Callable[..., Any]: """Makes a function that pops results from the result store.""" assert specialization.out_specs_treedef is not None assert specialization.out_specs_leaves is not None assert specialization.devices...
Makes a function that pops results from the result store.
_make_pop_result_fun
python
jax-ml/jax
jax/experimental/colocated_python/func.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/func.py
Apache-2.0
def _make_async_execution_fun( info: FunctionInfo, specialization: Specialization ) -> Callable[..., Any]: """Makes a function that asynchronously executes the function.""" assert specialization.in_specs_treedef is not None assert specialization.in_specs_leaves is not None assert specialization.out_specs_tr...
Makes a function that asynchronously executes the function.
_make_async_execution_fun
python
jax-ml/jax
jax/experimental/colocated_python/func.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/func.py
Apache-2.0
def _get_specialized_func( info: FunctionInfo, specialization: Specialization ) -> Callable[..., Any]: """Returns a specialized function for the given specialization.""" util.test_event("colocated_python_func._get_specialized_func") assert specialization.in_specs_treedef is not None assert specialization.in...
Returns a specialized function for the given specialization.
_get_specialized_func
python
jax-ml/jax
jax/experimental/colocated_python/func.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/func.py
Apache-2.0
def specialized_func(*args, **kwargs) -> Any: """Specialized function to be executed with given args and kwargs.""" nonlocal specialization, async_execution_func with mutex: if async_execution_func is None: if specialization.out_specs_treedef is None: if specialization.out_specs_fn i...
Specialized function to be executed with given args and kwargs.
specialized_func
python
jax-ml/jax
jax/experimental/colocated_python/func.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/func.py
Apache-2.0
def specialize( in_specs: ShapeDtypeStructTree | None = None, out_specs_fn: Callable[..., ShapeDtypeStructTree] | None = None, devices: Sequence[jax.Device] | None = None, ) -> Callable[..., Any]: """Returns a colocated Python callable with extra specialization. Args: in_specs: Option...
Returns a colocated Python callable with extra specialization. Args: in_specs: Optionally specifies the expected input specs. Input specs are expressed as a `PyTree[ShapeDtypeStruct]` for `(args, kwargs)` of a function call. out_specs_fn: Optionally specifies a function that computes th...
specialize
python
jax-ml/jax
jax/experimental/colocated_python/func.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/func.py
Apache-2.0
def __call__(*args, **kwargs) -> Any: """Executes the function. If the output specs are not known, the very first execution will be synchronous. """ args_leaves, in_specs_treedef = tree_util.tree_flatten((args, kwargs)) in_specs_leaves = tuple(_get_spec(x) for x in args_leaves) if speciali...
Executes the function. If the output specs are not known, the very first execution will be synchronous.
__call__
python
jax-ml/jax
jax/experimental/colocated_python/func.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/func.py
Apache-2.0
def new_instance(self) -> int: """Returns a new unique identifier for an instance on the controller.""" uid = random.getrandbits(63) with self._lock: assert uid not in self._storage self._storage[uid] = set() return uid
Returns a new unique identifier for an instance on the controller.
new_instance
python
jax-ml/jax
jax/experimental/colocated_python/obj.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/obj.py
Apache-2.0
def update_devices(self, uid: int, device_set: set[jax.Device]) -> None: """Updates the set of devices on which it is live.""" with self._lock: self._storage[uid] |= device_set
Updates the set of devices on which it is live.
update_devices
python
jax-ml/jax
jax/experimental/colocated_python/obj.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/obj.py
Apache-2.0
def get_or_create(self, uid: int, initializer: Callable[[], Any]) -> Any: """Returns the object associated with the given uid, or creates it if it does not exist.""" with self._lock: if uid in self._storage: while True: state = self._storage[uid] if state.is_being_initialized: ...
Returns the object associated with the given uid, or creates it if it does not exist.
get_or_create
python
jax-ml/jax
jax/experimental/colocated_python/obj_backend.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/obj_backend.py
Apache-2.0
def remove(self, uid: int) -> None: """Removes the object associated with the given uid.""" with self._lock: state = self._storage.pop(uid) # The object will be deleted without holding the lock. del state
Removes the object associated with the given uid.
remove
python
jax-ml/jax
jax/experimental/colocated_python/obj_backend.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/obj_backend.py
Apache-2.0
def _get_cpu_device_map() -> dict[int, jax.Device]: """Returns a map from a device id to a matching device.""" cpu_device_map: dict[int, jax.Device] = {} # TODO(hyeontaek): We should look up CPU devices for a specific CPU backend. # When deserializing a device on the controller, the backend should be the one ...
Returns a map from a device id to a matching device.
_get_cpu_device_map
python
jax-ml/jax
jax/experimental/colocated_python/serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/serialization.py
Apache-2.0
def _lookup_cpu_device( cpu_device_map: dict[int, jax.Device], device_id: int ) -> jax.Device: """Returns a CPU device with the given device ID.""" d = cpu_device_map.get(device_id) if d is None: raise ValueError( f"Invalid device ID {device_id}. Device list must contain only CPU" " device...
Returns a CPU device with the given device ID.
_lookup_cpu_device
python
jax-ml/jax
jax/experimental/colocated_python/serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/serialization.py
Apache-2.0
def _serialize(obj: Any) -> bytes: """Serializes callables and input/output spec objects. DO NOT USE THIS FUNCTION EXCEPT FOR THE INTERNAL IMPLEMENTATION OF colocated_python. This module contains utility functions used internally for implementiong `colocated_python` when it ships callables and input/output ...
Serializes callables and input/output spec objects. DO NOT USE THIS FUNCTION EXCEPT FOR THE INTERNAL IMPLEMENTATION OF colocated_python. This module contains utility functions used internally for implementiong `colocated_python` when it ships callables and input/output specs through IFRT. The pickled data i...
_serialize
python
jax-ml/jax
jax/experimental/colocated_python/serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/serialization.py
Apache-2.0
def _deserialize(serialized: bytes) -> Any: """Deserializes callables and input/output spec objects. DO NOT USE THIS FUNCTION EXCEPT FOR THE INTERNAL IMPLEMENTATION OF colocated_python. See serialize() for details. Raises: ModuleNotFoundError: If cloudpickle is not available. """ if cloudpickle is Non...
Deserializes callables and input/output spec objects. DO NOT USE THIS FUNCTION EXCEPT FOR THE INTERNAL IMPLEMENTATION OF colocated_python. See serialize() for details. Raises: ModuleNotFoundError: If cloudpickle is not available.
_deserialize
python
jax-ml/jax
jax/experimental/colocated_python/serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/serialization.py
Apache-2.0
def _make_specs_for_serialized_specs( devices: DeviceList, ) -> api.ShapeDtypeStruct: """Makes output specs for serialized specs.""" mesh = jax.sharding.Mesh(tuple(devices), ("x",)) replicated_sharding = jax.sharding.NamedSharding( mesh, jax.sharding.PartitionSpec() ) return api.ShapeDtypeStruct( ...
Makes output specs for serialized specs.
_make_specs_for_serialized_specs
python
jax-ml/jax
jax/experimental/colocated_python/serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/serialization.py
Apache-2.0
def _serialize_specs( specs_treedef: tree_util.PyTreeDef, specs_leaves: tuple[api.ShapeDtypeStruct, ...], devices: DeviceList, ) -> jax.Array: """Serializes the output specs into a jax.Array of string type. DO NOT USE THIS FUNCTION EXCEPT FOR THE INTERNAL IMPLEMENTATION OF colocated_python. See seria...
Serializes the output specs into a jax.Array of string type. DO NOT USE THIS FUNCTION EXCEPT FOR THE INTERNAL IMPLEMENTATION OF colocated_python. See serialize() for details.
_serialize_specs
python
jax-ml/jax
jax/experimental/colocated_python/serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/serialization.py
Apache-2.0
def _deserialize_specs( serialized_specs: jax.Array, ) -> tuple[tree_util.PyTreeDef, tuple[api.ShapeDtypeStruct, ...]]: """Deserializes the specs from the serialized specs. DO NOT USE THIS FUNCTION EXCEPT FOR THE INTERNAL IMPLEMENTATION OF colocated_python. See serialize() for details. """ data_array = s...
Deserializes the specs from the serialized specs. DO NOT USE THIS FUNCTION EXCEPT FOR THE INTERNAL IMPLEMENTATION OF colocated_python. See serialize() for details.
_deserialize_specs
python
jax-ml/jax
jax/experimental/colocated_python/serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/serialization.py
Apache-2.0
def _mlir_type_to_numpy_dtype(type: ir.Type) -> np.dtype: """Converts an MLIR scalar type to a NumPy dtype.""" if ir.IntegerType.isinstance(type): type = ir.IntegerType(type) width = type.width if width == 1: return np.dtype(np.bool_) elif width == 8: return np.dtype(np.uint8 if type.is...
Converts an MLIR scalar type to a NumPy dtype.
_mlir_type_to_numpy_dtype
python
jax-ml/jax
jax/experimental/jax2tf/call_tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/call_tf.py
Apache-2.0
def _transpose_for_tf_conv(lhs, lhs_shape: core.Shape, rhs, rhs_shape: core.Shape, dimension_numbers): """Transposes lhs and rhs to respectively NHWC and HWIO so they can be passed to TF functions. The shapes passed in and returned may contain polynomials, and thus may be different tha...
Transposes lhs and rhs to respectively NHWC and HWIO so they can be passed to TF functions. The shapes passed in and returned may contain polynomials, and thus may be different than lhs.shape and rhs.shape.
_transpose_for_tf_conv
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _pad_spatial_dims(x, x_shape, padding): """Pads `x` using `padding`, which specifies padding for the spatial dimensions.""" padding = tuple(padding) if len(padding) == len(x_shape) - 2: # If necessary, add empty padding for batch and feature dimensions. no_pad = ((0, 0),) padding = no_pad + paddin...
Pads `x` using `padding`, which specifies padding for the spatial dimensions.
_pad_spatial_dims
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _conv_transpose_pads_to_padtype(kernel_sdims, lhs_dilation, padding): """Finds the padding type for a transpose convolution.""" # This is simply checking agreement with lax._conv_transpose_padding. is_valid = True is_same = True if not len(kernel_sdims) == len(lhs_dilation) == len(padding): raise Valu...
Finds the padding type for a transpose convolution.
_conv_transpose_pads_to_padtype
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _dot_general(lhs, rhs, *, dimension_numbers, precision: tuple[PrecisionType, PrecisionType] | None, preferred_element_type: DType | None, out_sharding=None, _in_avals: Sequence[core.ShapedArray], _out_aval: core.ShapedArray): """...
Implementation of lax.dot_general_p in terms of tf.linalg.einsum.
_dot_general
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _clip(max_indices: Sequence[TfVal], start_indices: Sequence[TfVal], slice_sizes: Sequence[TfVal]): """Simulates XLA clipping behavior with TF ops. Various TF ops have different clipping behavior than XLA: * If `start_indices` is out-of-bounds, then TF fails but XLA clips the indices to [0, ma...
Simulates XLA clipping behavior with TF ops. Various TF ops have different clipping behavior than XLA: * If `start_indices` is out-of-bounds, then TF fails but XLA clips the indices to [0, max_len]. * If `start_indices + slice_size` is out-of-bounds, then TF fails, but XLA adjust `start_indices` so t...
_clip
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def gather_precondition(precondition_fn: Callable[[GatherArgs], None]): """Decorator for specifying a precondition function. This decorator should be put on a function with argument `arg` of type `GatherArgs`. It will first call `precondition_fn` with `arg` (which may throw an exception), and then call the fun...
Decorator for specifying a precondition function. This decorator should be put on a function with argument `arg` of type `GatherArgs`. It will first call `precondition_fn` with `arg` (which may throw an exception), and then call the function it is decorating with `arg` as well.
gather_precondition
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _pre_gather_for_scalar_indexing(args: GatherArgs): """Returns True if this call to gather represents scalar indexing into arrays. E.g., op[2], op[:, :5, :], jnp.take(op, 0, axis=0). """ # TODO(marcvanzee): Add more assumptions here, because this is currently too # permissive. if len(args.start_indices_...
Returns True if this call to gather represents scalar indexing into arrays. E.g., op[2], op[:, :5, :], jnp.take(op, 0, axis=0).
_pre_gather_for_scalar_indexing
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _gather_for_scalar_indexing(args: GatherArgs): """Implements 'scalar indexing into arrays' cases of lax.gather using tf.slice. E.g., op[2], op[:, :5, :], jnp.take(op, 0, axis=0). """ indices = tf.expand_dims(args.dnums.start_index_map, 1) # lax.gather uses an "index map" which maps `start_indices` to the...
Implements 'scalar indexing into arrays' cases of lax.gather using tf.slice. E.g., op[2], op[:, :5, :], jnp.take(op, 0, axis=0).
_gather_for_scalar_indexing
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _pre_gather_for_multidim_indexing(args: GatherArgs): """Returns True if this call to gather represents multi-dimensional indexing. E.g., jnp.take(op, [[0], [1]], axis=0). Note we currently only support multi-dimensional indexing if the last dimension is 1. """ # Handle only the case when tf.gather argu...
Returns True if this call to gather represents multi-dimensional indexing. E.g., jnp.take(op, [[0], [1]], axis=0). Note we currently only support multi-dimensional indexing if the last dimension is 1.
_pre_gather_for_multidim_indexing
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _gather_for_multidim_indexing(args: GatherArgs): """Implements 'multi-dimensional indexing into arrays' cases of lax.gather using tf.gather. E.g., jnp.take(op, [[0], [1]], axis=0). """ # Guess the axis. axis = args.dnums.collapsed_slice_dims[0] squeezed_indices = tf.squeeze(args.start_indices, -1) op...
Implements 'multi-dimensional indexing into arrays' cases of lax.gather using tf.gather. E.g., jnp.take(op, [[0], [1]], axis=0).
_gather_for_multidim_indexing
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _pre_gather_with_batch_dim(args: GatherArgs): """Returns True if this call to gather has non-empty batch dimensions. This is for instance triggered when doing jax.vmap(lax.dynamic_slice). """ # We assume exactly one batch (and one or more non-batch dimensions). if len(args.batch_dims) != 1: raise Val...
Returns True if this call to gather has non-empty batch dimensions. This is for instance triggered when doing jax.vmap(lax.dynamic_slice).
_pre_gather_with_batch_dim
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _pre_gather_with_batch_dims(args: GatherArgs): """Returns True if this call to gather has non-empty 2D batch dimensions. This is for instance triggered when doing jax.vmap(jax.vmap(lax.dynamic_slice)). """ if len(args.dnums.collapsed_slice_dims) != 0: # NOTE: this can be relaxed in _gather_with_batch...
Returns True if this call to gather has non-empty 2D batch dimensions. This is for instance triggered when doing jax.vmap(jax.vmap(lax.dynamic_slice)).
_pre_gather_with_batch_dims
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _gather_with_batch_dim(args: GatherArgs): """Implements call to gather with non-empty batch dimensions. E.g., when doing `jax.vmap(lax.dynamic_slice). """ op_shape = jax2tf._eval_shape(args.op_shape) start_indices = _clip(op_shape, args.start_indices, args.slice_sizes) result = tf.map_fn( lambda id...
Implements call to gather with non-empty batch dimensions. E.g., when doing `jax.vmap(lax.dynamic_slice).
_gather_with_batch_dim
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _gather_generate_indices(shape: tuple[int, ...]): """ Returns the indices of the according to `shape`: each element in the output is the index of an element of an array of the provided shape. The result's shape is (math.prod(shape), len(shape)) For example, given shape (2,2) it returns (0,0),(0,1),(1...
Returns the indices of the according to `shape`: each element in the output is the index of an element of an array of the provided shape. The result's shape is (math.prod(shape), len(shape)) For example, given shape (2,2) it returns (0,0),(0,1),(1,0),(1,1)
_gather_generate_indices
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _gather_with_batch_dims(args: GatherArgs): """Implements call to gather with non-empty 2D batch dimensions.""" op_shape = jax2tf._eval_shape(args.op_shape) output_shape = jax2tf._eval_shape(args.out_aval.shape) # Used to map the start_indices w.r.t start_index_map indices = tf.expand_dims(args.dnums.start...
Implements call to gather with non-empty 2D batch dimensions.
_gather_with_batch_dims
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def get_scatter_indices(indices, batch_indices_size, size_of_index_map): """Generate the start indices of each slice, which index into the operand.""" # Tile indices batch_indices_size times tiled_indices = tf.tile( tf.expand_dims(indices, 0), [batch_indices_size, 1, 1] ) # The above tiles n...
Generate the start indices of each slice, which index into the operand.
get_scatter_indices
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def shift_axes_forward(operand, axes: tuple[int, ...], inverse: bool = False, forward: bool = True): """Shifts the tuple of axes to the front of an array""" other_axes = tuple(i for i in range(len(operand.shape)) if i not in axes) fwd_order = ax...
Shifts the tuple of axes to the front of an array
shift_axes_forward
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def _sparse_scatter(operand, scatter_indices, updates, unique_indices, mode, _in_avals: Sequence[core.ShapedArray], _out_aval: core.ShapedArray): """Implementation of scatter specialised to indexing from the front axes. This covers unique indices and non-unique indic...
Implementation of scatter specialised to indexing from the front axes. This covers unique indices and non-unique indices of single depth. Note on unique indices: `tf.tensor_scatter_nd_update` interprets indices thusly: every axis except the final one encodes a batch dimension, the final axis encoding t...
_sparse_scatter
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def sparse_scatter(operand, scatter_indices, updates, update_jaxpr, update_consts, dimension_numbers, indices_are_sorted: bool, unique_indices: bool, mode, _in_avals: Sequence[core.ShapedArray], _out_aval: core.ShapedArray): """ ...
Wrapper around the scatter function. The underlying tf ops `tf.tensor_scatter_nd_update` and `tf.math.unsorted_segment_*` index from the front dimensions. `tf.math.unsorted_segment_*` indexes to a depth 1 from the front. `tf.tensor_scatter_nd_update` indexes from the front dimensions onwards, w...
sparse_scatter
python
jax-ml/jax
jax/experimental/jax2tf/impl_no_xla.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/impl_no_xla.py
Apache-2.0
def convert(fun_jax: Callable, *, polymorphic_shapes: str | None = None, polymorphic_constraints: Sequence[str] = (), with_gradient: bool = True, enable_xla: bool = True, native_serialization: bool | _DefaultNativeSerialization = DEFAULT_NATIVE_SER...
Allows calling a JAX function from a TensorFlow program. See [README](https://github.com/jax-ml/jax/blob/main/jax/experimental/jax2tf/README.md) for more details about usage and common problems. Args: fun_jax: target JAX function to be called. Its arguments and return value should be JAX arrays, or ...
convert
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def run_fun_tf(self, args_flat_tf: Sequence[TfVal] ) -> tuple[Sequence[TfVal], Sequence[core.ShapedArray], tree_util.PyTreeDef]: """Runs the resulting TF function. Args: args_flat_tf: a flat tuple of tf.Tensor arguments Returns: a tuple with: outs_tfs: a flat ...
Runs the resulting TF function. Args: args_flat_tf: a flat tuple of tf.Tensor arguments Returns: a tuple with: outs_tfs: a flat tuple of tf.Tensor results outs_avals: a flat tuple of JAX abstract values for the underlying JAX function. outs_tree: the PyTreeDef for the outputs ...
run_fun_tf
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def get_vjp_fun(self) -> tuple[Callable, Sequence[core.AbstractValue]]: """Returns the VJP function, and the VJP in_avals.""" raise NotImplementedError
Returns the VJP function, and the VJP in_avals.
get_vjp_fun
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def eval_polymorphic_shape(fun_jax: Callable, *, polymorphic_shapes=None) -> Callable: """Evaluates the output shape in presence of shape polymorphism. This is done without lowering or executing the function, same as for `jax.eval_shape`. Args: fun_jax: target JAX function to...
Evaluates the output shape in presence of shape polymorphism. This is done without lowering or executing the function, same as for `jax.eval_shape`. Args: fun_jax: target JAX function to be called. Its arguments and return value should be JAX arrays, or nested standard Python containers (tuple/l...
eval_polymorphic_shape
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def flatten_fun_jax(fun_jax: Callable, in_tree, ) -> tuple[Callable, Callable]: """Wraps the function to take a (flat) list of positional args. jax2tf works better and is simpler when the JAX function takes and returns just a tuple of values (no pytrees, no kwargs). This i...
Wraps the function to take a (flat) list of positional args. jax2tf works better and is simpler when the JAX function takes and returns just a tuple of values (no pytrees, no kwargs). This is in part because jax.vjp does not support kwargs and we can only set tf.custom_gradient on functions with flat arguments...
flatten_fun_jax
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def preprocess_arg_tf(arg_idx: int, arg_tf: TfVal) -> TfVal: """Pre-processes the TF args. Returns: a tuple with the pre-processed TF arg, the TF shape, and the JAX dtype. """ if not _is_tfval(arg_tf): msg = (f"Argument {arg_tf} of type {type(arg_tf)} of jax2tf.convert(f) should...
Pre-processes the TF args. Returns: a tuple with the pre-processed TF arg, the TF shape, and the JAX dtype.
preprocess_arg_tf
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _make_custom_gradient_fn_tf(fun_jax, *, impl: SerializationImpl, with_gradient: bool, args_specs, kwargs_specs, args_tf: Sequence[TfVal], ...
Prepares the TF function to be used with tf.custom_gradient. Args: impl: the serialization implementation details with_gradient: whether to include a tf.custom_gradient args_specs, kwargs_specs: the jax.ShapeDtypeArrays for the args and kwargs args_tf: the flattened TF arguments of the primal functio...
_make_custom_gradient_fn_tf
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _run_exported_as_tf(args_flat_tf: Sequence[TfVal], exported: export.Exported, ) -> Sequence[TfVal]: """Runs the `exported` as an XlaCallModule TF op. Returns: the flattened tuple of results. """ args_avals = exported.in_avals # TF values may be integer typ...
Runs the `exported` as an XlaCallModule TF op. Returns: the flattened tuple of results.
_run_exported_as_tf
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _interpret_jaxpr(jaxpr: core.ClosedJaxpr, *args_tf: TfVal, extra_name_stack: str | None, fresh_constant_cache: bool = True) -> Sequence[TfVal]: """Evaluates a Jaxpr with tf.Tensor arguments. This is most often used as the body of a tf.function, or tf.switch_case, in ...
Evaluates a Jaxpr with tf.Tensor arguments. This is most often used as the body of a tf.function, or tf.switch_case, in which case it should use a fresh constant cache. The output is a sequence of TfVal, suitable for use with TF.
_interpret_jaxpr
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _jax_physical_aval(aval: core.ShapedArray) -> core.ShapedArray: """Converts JAX avals from logical to physical, if relevant. JAX might have avals whose logical vs physical shape/dtype may differ, and only the physical view is expected to possibly relate to TF. TF impl rules should operate on the physical f...
Converts JAX avals from logical to physical, if relevant. JAX might have avals whose logical vs physical shape/dtype may differ, and only the physical view is expected to possibly relate to TF. TF impl rules should operate on the physical form. A JAX logical aval might even correspond, in principle, to severa...
_jax_physical_aval
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _aval_to_tf_shape(aval: core.ShapedArray) -> tuple[int | None, ...]: """Generate a TF shape, possibly containing None for polymorphic dimensions.""" aval = _jax_physical_aval(aval) return tuple(map(lambda d: None if export.is_symbolic_dim(d) else d, aval.shape))
Generate a TF shape, possibly containing None for polymorphic dimensions.
_aval_to_tf_shape
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _tfval_to_tensor_jax_dtype(val: TfVal, jax_dtype: DType | None = None, memoize_constants=False) -> tuple[TfVal, DType]: """Converts a scalar, ndarray, or tf.Tensor to a tf.Tensor with proper type. If `jax_dtype` is missing, uses JAX typing rules. ...
Converts a scalar, ndarray, or tf.Tensor to a tf.Tensor with proper type. If `jax_dtype` is missing, uses JAX typing rules. See README.md for details regarding 64-bit values. Args: val: a scalar, ndarray, tf.Tensor, or tf.Variable jax_dtype: an optional dtype to use. If missing, uses JAX type inference ...
_tfval_to_tensor_jax_dtype
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _assert_matching_abstract_shape(x: TfVal, shape: Sequence[shape_poly.DimSize]): """Asserts that shape matches x.shape in the known dimensions and has dimension polynomials elsewhere.""" # Ensures that the shape does not contain None; it should contain symbolic expressions. def check_one(xd: int | None, sd: ...
Asserts that shape matches x.shape in the known dimensions and has dimension polynomials elsewhere.
_assert_matching_abstract_shape
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def to_tf_tracer(self, val: TfVal) -> TensorFlowTracer: """Lifts a non-Tracer into the TensorFlowTracer. """ if isinstance(val, TensorFlowTracer): return val if hasattr(val, "__jax_array__"): with core.set_current_trace(self): val = val.__jax_array__() if isinstance(val, Tensor...
Lifts a non-Tracer into the TensorFlowTracer.
to_tf_tracer
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _not(x): """Computes bitwise not with support for booleans. Numpy and JAX support bitwise not for booleans by applying a logical not! This means that applying bitwise_not yields an unexpected result: jnp.bitwise_not(jnp.array([True, False])) >> Array([False, True], dtype=bool) if you assume that ...
Computes bitwise not with support for booleans. Numpy and JAX support bitwise not for booleans by applying a logical not! This means that applying bitwise_not yields an unexpected result: jnp.bitwise_not(jnp.array([True, False])) >> Array([False, True], dtype=bool) if you assume that booleans are simpl...
_not
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def handle_boolean_args(f, argnums: Sequence[int], boolean_f=None): """Computes functions with some bool args and bool results using int8. This is needed because some TF ops do not work for bool args, e.g., inequalities, min/max. Args: f: a TF callable to wrap. It will be called with non-boolean arguments...
Computes functions with some bool args and bool results using int8. This is needed because some TF ops do not work for bool args, e.g., inequalities, min/max. Args: f: a TF callable to wrap. It will be called with non-boolean arguments. argnums: the positional arguments that may be booleans. boolean...
handle_boolean_args
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _conv_general_dimension_numbers_proto(dimension_numbers): """Converts a ConvDimensionNumbers to an XLA ConvolutionDimensionNumbers.""" assert isinstance(dimension_numbers, lax.ConvDimensionNumbers) lhs_spec, rhs_spec, out_spec = dimension_numbers proto = xla_data_pb2.ConvolutionDimensionNumbers() proto.in...
Converts a ConvDimensionNumbers to an XLA ConvolutionDimensionNumbers.
_conv_general_dimension_numbers_proto
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _precision_config_proto(precision: None | (tuple[PrecisionType, PrecisionType])): """Convert an integer to an XLA.PrecisionConfig.""" if precision is None: return None proto = xla_data_pb2.PrecisionConfig() proto.operand_precision.append(precision[0...
Convert an integer to an XLA.PrecisionConfig.
_precision_config_proto
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _reduce_window(*args, jaxpr, consts, window_dimensions, window_strides, padding, base_dilation, window_dilation, _in_avals, _out_aval): """TensorFlow implementation of reduce_window. Args: operands: N dimensional arrays containing elements of type T init_values: st...
TensorFlow implementation of reduce_window. Args: operands: N dimensional arrays containing elements of type T init_values: starting values of the reduction jaxpr: the jaxpr corresponding to the reduction function consts: the constants associated with jaxpr. window_dimensions: array of integers f...
_reduce_window
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _batched_cond_while(*args: TfVal, cond_nconsts: int, cond_jaxpr: core.ClosedJaxpr, body_nconsts: int, body_jaxpr: core.ClosedJaxpr) -> Sequence[TfVal]: """Interprets a while_loop with a batched condition. A batched while has a conditional that returns a tensor of...
Interprets a while_loop with a batched condition. A batched while has a conditional that returns a tensor of booleans, and a body that returns a list of tensors whose leading dimensions match those of the conditional tensor. We need to turn it into a while with scalar boolean conditional. We will expand the...
_batched_cond_while
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def split_to_logical_devices(tensor: TfVal, partition_dimensions: PartitionsOrReplicated): """Like TPUMPStrategy.experimental_split_to_logical_devices. For jax2tf purposes we want to avoid needing to thread the `strategy` object through the generated computation. It seems that the or...
Like TPUMPStrategy.experimental_split_to_logical_devices. For jax2tf purposes we want to avoid needing to thread the `strategy` object through the generated computation. It seems that the original function needs the strategy object only for error checking, which we assume is done upstream by JAX. Args: ...
split_to_logical_devices
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def _register_checkpoint_pytrees(): """Registers TF custom container types as pytrees.""" m = tf.Module() # The types here are automagically changed by TensorFlow's checkpointing # infrastructure. m.a = (tf.Module(), tf.Module()) m.b = [tf.Module(), tf.Module()] m.c = {"a": tf.Module()} tuple_wrapper = ...
Registers TF custom container types as pytrees.
_register_checkpoint_pytrees
python
jax-ml/jax
jax/experimental/jax2tf/jax2tf.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/jax2tf.py
Apache-2.0
def load_mnist(split: tfds.Split, batch_size: int): """Loads either training or test MNIST data. Args: split: either tfds.Split.TRAIN or tfds.Split.TEST. Returns: an iterator with pairs (images, labels). The images have shape (B, 28, 28, 1) and the labels have shape (B, 10), where B is the batch_siz...
Loads either training or test MNIST data. Args: split: either tfds.Split.TRAIN or tfds.Split.TEST. Returns: an iterator with pairs (images, labels). The images have shape (B, 28, 28, 1) and the labels have shape (B, 10), where B is the batch_size.
load_mnist
python
jax-ml/jax
jax/experimental/jax2tf/examples/mnist_lib.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/mnist_lib.py
Apache-2.0
def predict(params: Sequence[tuple[Any, Any]], inputs, with_classifier=True): """The prediction function. Args: params: a list with pairs of weights and biases for each layer. inputs: the batch of images (B, 28, 28, 1) with_classifier: whether to include the classifier layer. Returns: ...
The prediction function. Args: params: a list with pairs of weights and biases for each layer. inputs: the batch of images (B, 28, 28, 1) with_classifier: whether to include the classifier layer. Returns: either the predictions (B, 10) if with_classifier=True, or the final set of...
predict
python
jax-ml/jax
jax/experimental/jax2tf/examples/mnist_lib.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/mnist_lib.py
Apache-2.0
def train(train_ds, test_ds, num_epochs, with_classifier=True): """Trains a pure JAX MNIST predictor. Returns: a tuple with two elements: - a predictor function with signature "(Params, ImagesBatch) -> Predictions". If `with_classifier=False` then the output of the predictor fun...
Trains a pure JAX MNIST predictor. Returns: a tuple with two elements: - a predictor function with signature "(Params, ImagesBatch) -> Predictions". If `with_classifier=False` then the output of the predictor function is the last layer of logits. - the parameters "...
train
python
jax-ml/jax
jax/experimental/jax2tf/examples/mnist_lib.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/mnist_lib.py
Apache-2.0
def train(train_ds, test_ds, num_epochs, with_classifier=True): """Trains a pure JAX MNIST predictor. Returns: a tuple with two elements: - a predictor function with signature "(Params, ImagesBatch) -> Predictions". If `with_classifier=False` then the output of the predictor f...
Trains a pure JAX MNIST predictor. Returns: a tuple with two elements: - a predictor function with signature "(Params, ImagesBatch) -> Predictions". If `with_classifier=False` then the output of the predictor function is the last layer of logits. - the parameters...
train
python
jax-ml/jax
jax/experimental/jax2tf/examples/mnist_lib.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/mnist_lib.py
Apache-2.0
def plot_images(ds, nr_rows: int, nr_cols: int, title: str, inference_fn: Callable | None = None): """Plots a grid of images with their predictions. Params: ds: a tensorflow dataset from where to pick the images and labels. nr_rows, nr_cols: t...
Plots a grid of images with their predictions. Params: ds: a tensorflow dataset from where to pick the images and labels. nr_rows, nr_cols: the size of the grid to plot title: the title of the plot inference_fn: if None then print the existing label, else use this function on the batch of image...
plot_images
python
jax-ml/jax
jax/experimental/jax2tf/examples/mnist_lib.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/mnist_lib.py
Apache-2.0
def __init__(self, tf_graph, param_vars): """Args: tf_graph: a tf.function taking one argument (the inputs), which can be be tuples/lists/dictionaries of np.ndarray or tensors. The function may have references to the tf.Variables in `param_vars`. param_vars: the parameters, as tuples/...
Args: tf_graph: a tf.function taking one argument (the inputs), which can be be tuples/lists/dictionaries of np.ndarray or tensors. The function may have references to the tf.Variables in `param_vars`. param_vars: the parameters, as tuples/lists/dictionaries of tf.Variable, to be...
__init__
python
jax-ml/jax
jax/experimental/jax2tf/examples/saved_model_lib.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/saved_model_lib.py
Apache-2.0
def pick_model_class(): """Picks one of PureJaxMNIST or FlaxMNIST.""" if _MODEL.value == "mnist_pure_jax": return mnist_lib.PureJaxMNIST elif _MODEL.value == "mnist_flax": return mnist_lib.FlaxMNIST else: raise ValueError(f"Unrecognized model: {_MODEL.value}")
Picks one of PureJaxMNIST or FlaxMNIST.
pick_model_class
python
jax-ml/jax
jax/experimental/jax2tf/examples/saved_model_main.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/saved_model_main.py
Apache-2.0
def model_description() -> str: """A short description of the picked model.""" res = pick_model_class().name if not _MODEL_CLASSIFIER_LAYER.value: res += " (features_only)" return res
A short description of the picked model.
model_description
python
jax-ml/jax
jax/experimental/jax2tf/examples/saved_model_main.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/saved_model_main.py
Apache-2.0
def savedmodel_dir(with_version: bool = True) -> str: """The directory where we save the SavedModel.""" model_dir = os.path.join( _MODEL_PATH.value, _MODEL.value + ('' if _MODEL_CLASSIFIER_LAYER.value else '_features') ) if with_version: model_dir = os.path.join(model_dir, str(_MODEL_VERSION.val...
The directory where we save the SavedModel.
savedmodel_dir
python
jax-ml/jax
jax/experimental/jax2tf/examples/saved_model_main.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/saved_model_main.py
Apache-2.0
def tf_accelerator_and_tolerances(): """Picks the TF accelerator to use and the tolerances for numerical checks.""" tf_accelerator = (tf.config.list_logical_devices("TPU") + tf.config.list_logical_devices("GPU") + tf.config.list_logical_devices("CPU"))[0] logging.info("Usin...
Picks the TF accelerator to use and the tolerances for numerical checks.
tf_accelerator_and_tolerances
python
jax-ml/jax
jax/experimental/jax2tf/examples/saved_model_main.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/saved_model_main.py
Apache-2.0
def serving_call_mnist(images): """Send an RPC or REST request to the model server. Args: images: A numpy.ndarray of shape [B, 28, 28, 1] with the batch of images to perform inference on. Returns: A numpy.ndarray of shape [B, 10] with the one-hot inference response. """ if _USE_GRPC.value: ...
Send an RPC or REST request to the model server. Args: images: A numpy.ndarray of shape [B, 28, 28, 1] with the batch of images to perform inference on. Returns: A numpy.ndarray of shape [B, 10] with the one-hot inference response.
serving_call_mnist
python
jax-ml/jax
jax/experimental/jax2tf/examples/serving/model_server_request.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/examples/serving/model_server_request.py
Apache-2.0
def deserialize_directory(serialized_string, output_directory): """Deserialize the string to the directory.""" # Convert the base64-encoded string back to binary data tar_data = base64.b64decode(serialized_string) # Extract the tar archive to the output directory with tarfile.open(fileobj=io.BytesIO(tar_data...
Deserialize the string to the directory.
deserialize_directory
python
jax-ml/jax
jax/experimental/jax2tf/tests/back_compat_tf_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/back_compat_tf_test.py
Apache-2.0
def _walk_stablehlo_operations(cls, op, cb): """walk the stablehlo operation recursive with callback function.""" cb(op) for region in op.operation.regions: for block in region: for op in block: cls._walk_stablehlo_operations(op, cb)
walk the stablehlo operation recursive with callback function.
_walk_stablehlo_operations
python
jax-ml/jax
jax/experimental/jax2tf/tests/call_tf_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/call_tf_test.py
Apache-2.0
def test_b279454591(self): """Test case when tensorflow function returns `StatefulPartitionedCall` op.""" inputs = jnp.ones([10], dtype=jnp.float32) # With one or more outputs, it is okay. def tf_f(x): y = tf.math.sin(3.0) tf.print(y) return x jax_f = jax2tf.call_tf( tf.f...
Test case when tensorflow function returns `StatefulPartitionedCall` op.
test_b279454591
python
jax-ml/jax
jax/experimental/jax2tf/tests/call_tf_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/call_tf_test.py
Apache-2.0
def jax2tfjs(harness: ModelHarness): """Converts the given `test_case` using the TFjs converter.""" with tempfile.TemporaryDirectory() as model_dir: tfjs.converters.convert_jax( apply_fn=harness.apply, params=harness.variables, input_signatures=harness.tf_input_signature, polymor...
Converts the given `test_case` using the TFjs converter.
jax2tfjs
python
jax-ml/jax
jax/experimental/jax2tf/tests/converters.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/converters.py
Apache-2.0
def write_and_check_harness(harness: primitive_harness.Harness, io: Io, save_directory: str, for_platforms: Sequence[str] = ("cpu", "tpu"),) -> Sequence[str]: """Writes and checks HLO for a given harness. Writes the HLOs generated ...
Writes and checks HLO for a given harness. Writes the HLOs generated in the current platform for all platforms. If it finds previously written HLOs generated on other platforms, compares them with the ones generated on this platform. Returns a list of harnesses on which diffs were found.
write_and_check_harness
python
jax-ml/jax
jax/experimental/jax2tf/tests/cross_compilation_check.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/cross_compilation_check.py
Apache-2.0
def test_gradients_with_custom_jvp(self, with_function=True): """Check gradients, for a function with custom JVP.""" @jax.custom_jvp def f(x): return x * x @f.defjvp def f_jvp(primals, tangents): # 3 * x * x_t x, = primals x_dot, = tangents primal_out = f(x) tang...
Check gradients, for a function with custom JVP.
test_gradients_with_custom_jvp
python
jax-ml/jax
jax/experimental/jax2tf/tests/jax2tf_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/jax2tf_test.py
Apache-2.0
def test_gradients_with_custom_vjp(self, with_function=True): """Check gradients, for a function with custom VJP.""" @jax.custom_vjp def f(x): return x * x # f_fwd: a -> (b, residual) def f_fwd(x): return f(x), 3. * x # f_bwd: (residual, CT b) -> [CT a] def f_bwd(residual, ct_b)...
Check gradients, for a function with custom VJP.
test_gradients_with_custom_vjp
python
jax-ml/jax
jax/experimental/jax2tf/tests/jax2tf_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/jax2tf_test.py
Apache-2.0
def test_custom_jvp(self): """Conversion of function with custom JVP""" @jax.custom_jvp def f(x): return x * x @f.defjvp def f_jvp(primals, tangents): x, = primals x_dot, = tangents primal_out = f(x) tangent_out = 3. * x * x_dot return primal_out, tangent_out ...
Conversion of function with custom JVP
test_custom_jvp
python
jax-ml/jax
jax/experimental/jax2tf/tests/jax2tf_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/jax2tf_test.py
Apache-2.0
def test_custom_vjp(self): """Conversion of function with custom VJP""" @jax.custom_vjp def f(x): return x * x # f_fwd: a -> (b, residual) def f_fwd(x): return f(x), 3. * x # f_bwd: (residual, CT b) -> [CT a] def f_bwd(residual, ct_b): return residual * ct_b, f.defv...
Conversion of function with custom VJP
test_custom_vjp
python
jax-ml/jax
jax/experimental/jax2tf/tests/jax2tf_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/jax2tf_test.py
Apache-2.0
def test_nested_convert_error_non_tracer(self): """The inner convert takes non-tracer arguments""" def outer(y): sin_1 = jax2tf.convert(jnp.sin)(1.) # Inner convert takes non-tracer arg return y + sin_1 with self.assertRaisesRegex( ValueError, "convert must be used outside all JAX tran...
The inner convert takes non-tracer arguments
test_nested_convert_error_non_tracer
python
jax-ml/jax
jax/experimental/jax2tf/tests/jax2tf_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/jax2tf_test.py
Apache-2.0
def assertAllOperationStartWith(self, g: tf.Graph, scope_name: str): """Assert all operations name start with ```scope_name```. Also the scope_name only occur one time. """ result = g.get_operations() if not result: self.fail("result is empty.") for op in result: logging.info("tf op...
Assert all operations name start with ```scope_name```. Also the scope_name only occur one time.
assertAllOperationStartWith
python
jax-ml/jax
jax/experimental/jax2tf/tests/jax2tf_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/jax2tf_test.py
Apache-2.0
def test_jax_implemented(self, harness: test_harnesses.Harness): """Runs all harnesses just with JAX to verify the jax_unimplemented field. Runs also harnesses that have jax_unimplemented but ignores their errors. """ jax_unimpl = [l for l in harness.jax_unimplemented if l.filter(devi...
Runs all harnesses just with JAX to verify the jax_unimplemented field. Runs also harnesses that have jax_unimplemented but ignores their errors.
test_jax_implemented
python
jax-ml/jax
jax/experimental/jax2tf/tests/jax_primitives_coverage_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/jax_primitives_coverage_test.py
Apache-2.0
def _write_markdown(results: dict[str, list[tuple[str, str,]]]) -> None: """Writes all results to Markdown file.""" table_lines = [] converters = _CONVERTERS.value table_lines.append("| Example | " + " ".join([f"{c} |" for c in converters])) table_lines.append("|" + (" --- |" * (len(converters) + 1))) err...
Writes all results to Markdown file.
_write_markdown
python
jax-ml/jax
jax/experimental/jax2tf/tests/models_test_main.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/models_test_main.py
Apache-2.0
def test_converters(): """Tests all converters and write output.""" def _exit_if_empty(x, name): if not x: print(f"WARNING: No {name} found to test! Exiting") exit() def _maybe_reraise(e): if _FAIL_ON_ERROR.value: raise e def _format(e): # InvalidArgumentError output is shown dif...
Tests all converters and write output.
test_converters
python
jax-ml/jax
jax/experimental/jax2tf/tests/models_test_main.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/models_test_main.py
Apache-2.0
def _make_harness(harness_fn, name, poly_shapes=None, tensor_specs=None): """Partially apply harness in order to create variables lazily. Note: quotes and commas are stripped from `name` to ensure they can be passed through the command-line. """ if poly_shapes: name += "_" + re.sub(r"(?:'|\"|,)", "...
Partially apply harness in order to create variables lazily. Note: quotes and commas are stripped from `name` to ensure they can be passed through the command-line.
_make_harness
python
jax-ml/jax
jax/experimental/jax2tf/tests/model_harness.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/model_harness.py
Apache-2.0
def test_gradient(self): """Save and restore the custom gradient.""" @jax.custom_jvp def f_jax(x): return x * x @f_jax.defjvp def f_jax_jvp(primals, tangents): # 3 * x * x_t x, = primals x_dot, = tangents primal_out = f_jax(x) tangent_out = x * x_dot * 3. r...
Save and restore the custom gradient.
test_gradient
python
jax-ml/jax
jax/experimental/jax2tf/tests/savedmodel_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/savedmodel_test.py
Apache-2.0
def test_gradient_nested(self): """Save and restore the custom gradient, when combined with other TF code.""" @jax.custom_jvp def f_jax(x): return x * x @f_jax.defjvp def f_jax_jvp(primals, tangents): # 3 * x * x_t x, = primals x_dot, = tangents primal_out = f_jax(x) ...
Save and restore the custom gradient, when combined with other TF code.
test_gradient_nested
python
jax-ml/jax
jax/experimental/jax2tf/tests/savedmodel_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/savedmodel_test.py
Apache-2.0
def test_tf_mix_jax_with_uncompilableble(self): """Show how to combine TF-uncompilableble code with compiled JAX-converted code.""" def tf_fn(x_str, compute_tf_fn=lambda x: x): # Some TF preprocessing code that cannot be compiled with XLA because it # uses strings. numbers_f32 = tf.strings.to_...
Show how to combine TF-uncompilableble code with compiled JAX-converted code.
test_tf_mix_jax_with_uncompilableble
python
jax-ml/jax
jax/experimental/jax2tf/tests/savedmodel_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/savedmodel_test.py
Apache-2.0
def test_simple_unary(self): """Test shape polymorphism for a simple case, unary function.""" def f_jax(x): return x + jnp.sin(x) check_shape_poly(self, f_jax, arg_descriptors=[RandArg((2, 3), _f32)], polymorphic_shapes=[None], ...
Test shape polymorphism for a simple case, unary function.
test_simple_unary
python
jax-ml/jax
jax/experimental/jax2tf/tests/shape_poly_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/shape_poly_test.py
Apache-2.0
def test_simple_binary(self): """Test shape polymorphism for a simple case, binary function.""" def f_jax(x, y): return x + jnp.sin(y) check_shape_poly(self, f_jax, arg_descriptors=[RandArg((2, 3), _f32), RandArg((2, 3), _f32)], polymorp...
Test shape polymorphism for a simple case, binary function.
test_simple_binary
python
jax-ml/jax
jax/experimental/jax2tf/tests/shape_poly_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/shape_poly_test.py
Apache-2.0
def test_kwargs(self): """Test shape polymorphism for a function with kwargs.""" x = np.ones(3, dtype=np.float32) y = np.ones(1, dtype=np.float32) def f_jax(x, *, y): return x + jnp.sin(y) f_tf: Callable[..., Any] = jax2tf.convert(f_jax, polymorphic_shapes=["b, ..."]) self.assertAllClose...
Test shape polymorphism for a function with kwargs.
test_kwargs
python
jax-ml/jax
jax/experimental/jax2tf/tests/shape_poly_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/shape_poly_test.py
Apache-2.0
def test_arg_avals_non_native(self): """Test conversion of actual arguments to abstract values.""" def check_avals(*, arg_shapes: Sequence[Sequence[int | None]], polymorphic_shapes: Sequence[str | None], expected_shapes: Sequence[str] | None = None, e...
Test conversion of actual arguments to abstract values.
test_arg_avals_non_native
python
jax-ml/jax
jax/experimental/jax2tf/tests/shape_poly_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/shape_poly_test.py
Apache-2.0
def test_arg_avals_errors(self): """Test error reporting for shape polymorphism.""" def conv_and_run(*, arg_shape: core.Shape, polymorphic_shape: str): arg = np.arange(math.prod(arg_shape), dtype=np.float32).reshape(arg_shape) check_shape_poly(self, lambda x: x, ...
Test error reporting for shape polymorphism.
test_arg_avals_errors
python
jax-ml/jax
jax/experimental/jax2tf/tests/shape_poly_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/shape_poly_test.py
Apache-2.0
def test_pytree_errors(self, polymorphic_shapes=("b", "b", "b")): """Arguments and polymorphic_shapes are not-matching pytrees.""" # Arguments are of the form [([x00, x01], [x10]), dict(a=ya, b=yb)] x = np.arange(4, dtype=_f32) args = (([x, x], [x]), dict(a=x, b=x)) def add_all_jax(x_pair_of_list, ...
Arguments and polymorphic_shapes are not-matching pytrees.
test_pytree_errors
python
jax-ml/jax
jax/experimental/jax2tf/tests/shape_poly_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/shape_poly_test.py
Apache-2.0
def test_gradients_pytree(self): """Shape polymorphism with gradients and pytrees for inputs and outputs.""" def f(x): # x: dict(x=[b, 3, 4]) # res: dict(res=[b, 3, 4]) return dict(res=x["x"] * 2.) check_shape_poly(self, f, skip_jax_run=True, ...
Shape polymorphism with gradients and pytrees for inputs and outputs.
test_gradients_pytree
python
jax-ml/jax
jax/experimental/jax2tf/tests/shape_poly_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/shape_poly_test.py
Apache-2.0
def test_readme_examples(self): """Some of the examples from the README.""" jax2tf.convert(lambda x: jnp.reshape(x, (x.shape[0] * x.shape[1],)), polymorphic_shapes=["(b, 4)"])(np.ones((3, 4))) jax2tf.convert(lambda x: jnp.reshape(x, (math.prod(x.shape),)), polymorphic...
Some of the examples from the README.
test_readme_examples
python
jax-ml/jax
jax/experimental/jax2tf/tests/shape_poly_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/shape_poly_test.py
Apache-2.0
def _make_vmap_primitive_harnesses() -> Sequence[PolyHarness]: """For each harness group, pick a single dtype. See PolyHarness for documentation. Ignore harnesses that fail in graph mode in jax2tf. """ all_h = test_harnesses.all_harnesses res = [] # Index by group harness_groups: dict[ str, Seque...
For each harness group, pick a single dtype. See PolyHarness for documentation. Ignore harnesses that fail in graph mode in jax2tf.
_make_vmap_primitive_harnesses
python
jax-ml/jax
jax/experimental/jax2tf/tests/shape_poly_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/shape_poly_test.py
Apache-2.0
def log_jax_hlo(self, f_jax, args: Sequence[Any], *, num_replicas=1, num_partitions=2): """Log the HLO generated from JAX before and after optimizations""" jax_comp = f_jax.lower(*args).compiler_ir(dialect="stablehlo") jax_hlo = str(jax_comp) logging.info("[%s] got JAX HLO %s", self._t...
Log the HLO generated from JAX before and after optimizations
log_jax_hlo
python
jax-ml/jax
jax/experimental/jax2tf/tests/sharding_test.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/jax2tf/tests/sharding_test.py
Apache-2.0