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 jit_trivial_dispatch(state): """Benchmarks only the duration for jitted_f to return the future.""" f = jax.jit(swap) a, b = f(1, 2) x = f(a, b) while state: x = f(a, b) x[0].block_until_ready()
Benchmarks only the duration for jitted_f to return the future.
jit_trivial_dispatch
python
jax-ml/jax
benchmarks/api_benchmark.py
https://github.com/jax-ml/jax/blob/master/benchmarks/api_benchmark.py
Apache-2.0
def add_global_arguments(parser: argparse.ArgumentParser): """Adds all the global arguments that applies to all the CLI subcommands.""" parser.add_argument( "--python_version", type=str, default=f"{sys.version_info.major}.{sys.version_info.minor}", help= """ Hermetic Python v...
Adds all the global arguments that applies to all the CLI subcommands.
add_global_arguments
python
jax-ml/jax
build/build.py
https://github.com/jax-ml/jax/blob/master/build/build.py
Apache-2.0
def add_artifact_subcommand_arguments(parser: argparse.ArgumentParser): """Adds all the arguments that applies to the artifact subcommands.""" parser.add_argument( "--wheels", type=str, default="jaxlib", help= """ A comma separated list of JAX wheels to build. E.g: --wheels="...
Adds all the arguments that applies to the artifact subcommands.
add_artifact_subcommand_arguments
python
jax-ml/jax
build/build.py
https://github.com/jax-ml/jax/blob/master/build/build.py
Apache-2.0
def parse_test_log(log_file): """Parses the test module log file to extract test modules and functions.""" test_files = set() with open(log_file, "r") as f: for line in f: report = json.loads(line) if "nodeid" in report: module = report["nodeid"].split("::")[0...
Parses the test module log file to extract test modules and functions.
parse_test_log
python
jax-ml/jax
build/rocm/run_single_gpu.py
https://github.com/jax-ml/jax/blob/master/build/rocm/run_single_gpu.py
Apache-2.0
def install_amdgpu_installer_internal(rocm_version): """ Download and install the "amdgpu-installer" package from internal builds on the current system. """ md = os_release_meta() url, fn = _build_installer_url(rocm_version, md) try: # download installer LOG.info("Downloadin...
Download and install the "amdgpu-installer" package from internal builds on the current system.
install_amdgpu_installer_internal
python
jax-ml/jax
build/rocm/tools/get_rocm.py
https://github.com/jax-ml/jax/blob/master/build/rocm/tools/get_rocm.py
Apache-2.0
def get_libc_version(): """ Detect and return glibc version that the current Python is linked against. This mimics the detection behavior of the 'wheel' and 'auditwheel' projects, but without any PyPy or libmusl support. """ try: version_str = os.confstr("CS_GNU_LIBC_VERSION") ...
Detect and return glibc version that the current Python is linked against. This mimics the detection behavior of the 'wheel' and 'auditwheel' projects, but without any PyPy or libmusl support.
get_libc_version
python
jax-ml/jax
build/rocm/tools/libc.py
https://github.com/jax-ml/jax/blob/master/build/rocm/tools/libc.py
Apache-2.0
async def _process_log_stream(stream, result: CommandResult): """Logs the output of a subprocess stream.""" while True: line_bytes = await stream.readline() if not line_bytes: break line = line_bytes.decode().rstrip() result.logs += line logger.info("%s", line)
Logs the output of a subprocess stream.
_process_log_stream
python
jax-ml/jax
build/tools/command.py
https://github.com/jax-ml/jax/blob/master/build/tools/command.py
Apache-2.0
async def run(self, cmd: str, dry_run: bool = False, detailed_timestamped_log: bool = False) -> CommandResult: """ Executes a subprocess command. Args: cmd: The command to execute. dry_run: If True, prints the command instead of executing it. Returns: A CommandResult instance. ...
Executes a subprocess command. Args: cmd: The command to execute. dry_run: If True, prints the command instead of executing it. Returns: A CommandResult instance.
run
python
jax-ml/jax
build/tools/command.py
https://github.com/jax-ml/jax/blob/master/build/tools/command.py
Apache-2.0
def download_and_verify_bazel(): """Downloads a bazel binary from GitHub, verifying its SHA256 hash.""" package = bazel_packages.get((platform.system(), platform.machine())) if package is None: return None if not os.access(package.file, os.X_OK): uri = (package.base_uri or BAZEL_BASE_URI) + package.fil...
Downloads a bazel binary from GitHub, verifying its SHA256 hash.
download_and_verify_bazel
python
jax-ml/jax
build/tools/utils.py
https://github.com/jax-ml/jax/blob/master/build/tools/utils.py
Apache-2.0
def get_bazel_paths(bazel_path_flag): """Yields a sequence of guesses about bazel path. Some of sequence elements can be None. The resulting iterator is lazy and potentially has a side effects. """ yield bazel_path_flag yield shutil.which("bazel") yield download_and_verify_bazel()
Yields a sequence of guesses about bazel path. Some of sequence elements can be None. The resulting iterator is lazy and potentially has a side effects.
get_bazel_paths
python
jax-ml/jax
build/tools/utils.py
https://github.com/jax-ml/jax/blob/master/build/tools/utils.py
Apache-2.0
def get_bazel_path(bazel_path_flag): """Returns the path to a Bazel binary, downloading Bazel if not found. Also, checks Bazel's version is at least newer than 7.4.1 A manual version check is needed only for really old bazel versions. Newer bazel releases perform their own version check against .bazelversion ...
Returns the path to a Bazel binary, downloading Bazel if not found. Also, checks Bazel's version is at least newer than 7.4.1 A manual version check is needed only for really old bazel versions. Newer bazel releases perform their own version check against .bazelversion (see for details https://blog.bazel.bu...
get_bazel_path
python
jax-ml/jax
build/tools/utils.py
https://github.com/jax-ml/jax/blob/master/build/tools/utils.py
Apache-2.0
def get_jax_configure_bazel_options(bazel_command: list[str], use_new_wheel_build_rule: bool): """Returns the bazel options to be written to .jax_configure.bazelrc.""" # Get the index of the "run" parameter. Build options will come after "run" so # we find the index of "run" and filter everything after it. If we ...
Returns the bazel options to be written to .jax_configure.bazelrc.
get_jax_configure_bazel_options
python
jax-ml/jax
build/tools/utils.py
https://github.com/jax-ml/jax/blob/master/build/tools/utils.py
Apache-2.0
def msys_to_windows_path(msys_path): """Converts an MSYS path to a Windows path using cygpath. Args: msys_path: The MSYS path to convert. Returns: The corresponding Windows path. """ try: # Use cygpath with the -w flag to convert to Windows format process = subprocess.run(['cygpath', '-w', m...
Converts an MSYS path to a Windows path using cygpath. Args: msys_path: The MSYS path to convert. Returns: The corresponding Windows path.
msys_to_windows_path
python
jax-ml/jax
ci/utilities/convert_msys_paths_to_win_paths.py
https://github.com/jax-ml/jax/blob/master/ci/utilities/convert_msys_paths_to_win_paths.py
Apache-2.0
def should_convert(var: str, convert: list[str] | None): """Check the variable name against convert list""" if var in convert: return True else: return False
Check the variable name against convert list
should_convert
python
jax-ml/jax
ci/utilities/convert_msys_paths_to_win_paths.py
https://github.com/jax-ml/jax/blob/master/ci/utilities/convert_msys_paths_to_win_paths.py
Apache-2.0
def jax_issue_role(name, rawtext, text, lineno, inliner, options=None, content=()): """Generate links to jax issues or PRs in sphinx. Usage:: :jax-issue:`1234` This will output a hyperlink of the form `#1234 <http://github.com/jax-ml/jax/issues/1234>`_. These links work even for PR...
Generate links to jax issues or PRs in sphinx. Usage:: :jax-issue:`1234` This will output a hyperlink of the form `#1234 <http://github.com/jax-ml/jax/issues/1234>`_. These links work even for PR numbers.
jax_issue_role
python
jax-ml/jax
docs/sphinxext/jax_extensions.py
https://github.com/jax-ml/jax/blob/master/docs/sphinxext/jax_extensions.py
Apache-2.0
def create_field_item(label, content): """Create a field list item with a label and content side by side. Args: label: The label text for the field name content: The content to add (a node or text) Returns: A field list item with the label and content side by side. """ # Create a field list item...
Create a field list item with a label and content side by side. Args: label: The label text for the field name content: The content to add (a node or text) Returns: A field list item with the label and content side by side.
create_field_item
python
jax-ml/jax
docs/sphinxext/jax_list_config_options.py
https://github.com/jax-ml/jax/blob/master/docs/sphinxext/jax_list_config_options.py
Apache-2.0
def clipped_grad(params, l2_norm_clip, single_example_batch): """Evaluate gradient for a single-example batch and clip its grad norm.""" grads = grad(loss)(params, single_example_batch) nonempty_grads, tree_def = tree_flatten(grads) total_grad_norm = jnp.linalg.norm( jnp.array([jnp.linalg.norm(neg.ravel()...
Evaluate gradient for a single-example batch and clip its grad norm.
clipped_grad
python
jax-ml/jax
examples/differentially_private_sgd.py
https://github.com/jax-ml/jax/blob/master/examples/differentially_private_sgd.py
Apache-2.0
def private_grad(params, batch, rng, l2_norm_clip, noise_multiplier, batch_size): """Return differentially private gradients for params, evaluated on batch.""" clipped_grads = vmap(clipped_grad, (None, None, 0))(params, l2_norm_clip, batch) clipped_grads_flat, grads_treedef = tree_flatten(clipped...
Return differentially private gradients for params, evaluated on batch.
private_grad
python
jax-ml/jax
examples/differentially_private_sgd.py
https://github.com/jax-ml/jax/blob/master/examples/differentially_private_sgd.py
Apache-2.0
def cov_map(cov_func, xs, xs2=None): """Compute a covariance matrix from a covariance function and data points. Args: cov_func: callable function, maps pairs of data points to scalars. xs: array of data points, stacked along the leading dimension. Returns: A 2d array `a` such that `a[i, j...
Compute a covariance matrix from a covariance function and data points. Args: cov_func: callable function, maps pairs of data points to scalars. xs: array of data points, stacked along the leading dimension. Returns: A 2d array `a` such that `a[i, j] = cov_func(xs[i], xs[j])`.
cov_map
python
jax-ml/jax
examples/gaussian_process_regression.py
https://github.com/jax-ml/jax/blob/master/examples/gaussian_process_regression.py
Apache-2.0
def elbo(rng, params, images): """Monte Carlo estimate of the negative evidence lower bound.""" enc_params, dec_params = params mu_z, sigmasq_z = encode(enc_params, images) logits_x = decode(dec_params, gaussian_sample(rng, mu_z, sigmasq_z)) return bernoulli_logpdf(logits_x, images) - gaussian_kl(mu_z, sigmas...
Monte Carlo estimate of the negative evidence lower bound.
elbo
python
jax-ml/jax
examples/mnist_vae.py
https://github.com/jax-ml/jax/blob/master/examples/mnist_vae.py
Apache-2.0
def image_sample(rng, params, nrow, ncol): """Sample images from the generative model.""" _, dec_params = params code_rng, img_rng = random.split(rng) logits = decode(dec_params, random.normal(code_rng, (nrow * ncol, 10))) sampled_images = random.bernoulli(img_rng, jnp.logaddexp(0., logits)) return image_gr...
Sample images from the generative model.
image_sample
python
jax-ml/jax
examples/mnist_vae.py
https://github.com/jax-ml/jax/blob/master/examples/mnist_vae.py
Apache-2.0
def image_grid(nrow, ncol, imagevecs, imshape): """Reshape a stack of image vectors into an image grid for plotting.""" images = iter(imagevecs.reshape((-1,) + imshape)) return jnp.vstack([jnp.hstack([next(images).T for _ in range(ncol)][::-1]) for _ in range(nrow)]).T
Reshape a stack of image vectors into an image grid for plotting.
image_grid
python
jax-ml/jax
examples/mnist_vae.py
https://github.com/jax-ml/jax/blob/master/examples/mnist_vae.py
Apache-2.0
def onnx_maxpool(x, kernel_shape, pads=None, strides=None): """Numpy-backed implementation of ONNX MaxPool op.""" prefix = (1,) * (x.ndim - len(kernel_shape)) dims = prefix + tuple(kernel_shape) pads = tuple(pads) if pads else [0] * len(kernel_shape) strides = (prefix + tuple(strides)) if strides else [1] * l...
Numpy-backed implementation of ONNX MaxPool op.
onnx_maxpool
python
jax-ml/jax
examples/onnx2xla.py
https://github.com/jax-ml/jax/blob/master/examples/onnx2xla.py
Apache-2.0
def onnx_conv(x, w, b=0, group=1, kernel_shape=None, pads=None, strides=None, dilations=None, auto_pad=None): """Numpy-backed implementation of ONNX Conv op.""" assert group == 1 kernel_shape = kernel_shape or w.shape strides = strides or [1] * (w.ndim - 2) if auto_pad: auto_pad = 'SAME' if ...
Numpy-backed implementation of ONNX Conv op.
onnx_conv
python
jax-ml/jax
examples/onnx2xla.py
https://github.com/jax-ml/jax/blob/master/examples/onnx2xla.py
Apache-2.0
def onnx_add(a, b, axis=None, broadcast=True): """Numpy-backed implementation of ONNX Add op.""" if broadcast: axis = (a.dim - b.ndim) if axis is None else axis % a.ndim assert a.shape[axis:][:b.ndim] == b.shape b_shape = np.ones(a.ndim, dtype='int64') b_shape[axis:axis + b.ndim] = b.shape b = j...
Numpy-backed implementation of ONNX Add op.
onnx_add
python
jax-ml/jax
examples/onnx2xla.py
https://github.com/jax-ml/jax/blob/master/examples/onnx2xla.py
Apache-2.0
def _get_version_for_build() -> str: """Determine the version at build time. The returned version string depends on which environment variables are set: - if WHEEL_VERSION_SUFFIX is set: version looks like "0.5.1.dev20230906+ge58560fdc" Here the WHEEL_VERSION_SUFFIX value is ".dev20230906+ge58560fdc". Pl...
Determine the version at build time. The returned version string depends on which environment variables are set: - if WHEEL_VERSION_SUFFIX is set: version looks like "0.5.1.dev20230906+ge58560fdc" Here the WHEEL_VERSION_SUFFIX value is ".dev20230906+ge58560fdc". Please note that the WHEEL_VERSION_SUFFIX va...
_get_version_for_build
python
jax-ml/jax
jax/version.py
https://github.com/jax-ml/jax/blob/master/jax/version.py
Apache-2.0
def _is_prerelease() -> bool: """Determine if this is a pre-release ("rc" wheels) build.""" rc_version = os.getenv("WHEEL_VERSION_SUFFIX", "") return True if rc_version.startswith("rc") else False
Determine if this is a pre-release ("rc" wheels) build.
_is_prerelease
python
jax-ml/jax
jax/version.py
https://github.com/jax-ml/jax/blob/master/jax/version.py
Apache-2.0
def _write_version(fname: str) -> None: """Used by setup.py to write the specified version info into the source tree.""" release_version = _get_version_for_build() old_version_string = "_release_version: str | None = None" new_version_string = f"_release_version: str = {release_version!r}" fhandle = pathlib.P...
Used by setup.py to write the specified version info into the source tree.
_write_version
python
jax-ml/jax
jax/version.py
https://github.com/jax-ml/jax/blob/master/jax/version.py
Apache-2.0
def optimizer(opt_maker: Callable[..., tuple[Callable[[Params], State], Callable[[Step, Updates, Params], Params], Callable[[State], Params]]]) -> Callable[..., Optimizer]: """Decorator to make an optimizer defined for arrays generalize to containers. With this decorator, you can write init, upda...
Decorator to make an optimizer defined for arrays generalize to containers. With this decorator, you can write init, update, and get_params functions that each operate only on single arrays, and convert them to corresponding functions that operate on pytrees of parameters. See the optimizers defined in optimiz...
optimizer
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def sgd(step_size): """Construct optimizer triple for stochastic gradient descent. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. Returns: An (init_fun, update_fun, get_params) triple. """ step_size = make_s...
Construct optimizer triple for stochastic gradient descent. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. Returns: An (init_fun, update_fun, get_params) triple.
sgd
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def momentum(step_size: Schedule, mass: float): """Construct optimizer triple for SGD with momentum. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. mass: positive scalar representing the momentum coefficient. Re...
Construct optimizer triple for SGD with momentum. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. mass: positive scalar representing the momentum coefficient. Returns: An (init_fun, update_fun, get_params) trip...
momentum
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def nesterov(step_size: Schedule, mass: float): """Construct optimizer triple for SGD with Nesterov momentum. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. mass: positive scalar representing the momentum coefficie...
Construct optimizer triple for SGD with Nesterov momentum. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. mass: positive scalar representing the momentum coefficient. Returns: An (init_fun, update_fun, get_par...
nesterov
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def adagrad(step_size, momentum=0.9): """Construct optimizer triple for Adagrad. Adaptive Subgradient Methods for Online Learning and Stochastic Optimization: http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf Args: step_size: positive scalar, or a callable representing a step size schedule t...
Construct optimizer triple for Adagrad. Adaptive Subgradient Methods for Online Learning and Stochastic Optimization: http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive ...
adagrad
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def rmsprop(step_size, gamma=0.9, eps=1e-8): """Construct optimizer triple for RMSProp. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. gamma: Decay parameter. eps: Epsilon parameter. Returns: An (ini...
Construct optimizer triple for RMSProp. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. gamma: Decay parameter. eps: Epsilon parameter. Returns: An (init_fun, update_fun, get_params) triple.
rmsprop
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def rmsprop_momentum(step_size, gamma=0.9, eps=1e-8, momentum=0.9): """Construct optimizer triple for RMSProp with momentum. This optimizer is separate from the rmsprop optimizer because it needs to keep track of additional parameters. Args: step_size: positive scalar, or a callable representing a step si...
Construct optimizer triple for RMSProp with momentum. This optimizer is separate from the rmsprop optimizer because it needs to keep track of additional parameters. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. ...
rmsprop_momentum
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def adam(step_size, b1=0.9, b2=0.999, eps=1e-8): """Construct optimizer triple for Adam. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. b1: optional, a positive scalar value for beta_1, the exponential decay rate ...
Construct optimizer triple for Adam. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. b1: optional, a positive scalar value for beta_1, the exponential decay rate for the first moment estimates (default 0.9). ...
adam
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def adamax(step_size, b1=0.9, b2=0.999, eps=1e-8): """Construct optimizer triple for AdaMax (a variant of Adam based on infinity norm). Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. b1: optional, a positive scalar...
Construct optimizer triple for AdaMax (a variant of Adam based on infinity norm). Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. b1: optional, a positive scalar value for beta_1, the exponential decay rate for ...
adamax
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def sm3(step_size, momentum=0.9): """Construct optimizer triple for SM3. Memory-Efficient Adaptive Optimization for Large-Scale Learning. https://arxiv.org/abs/1901.11150 Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive sca...
Construct optimizer triple for SM3. Memory-Efficient Adaptive Optimization for Large-Scale Learning. https://arxiv.org/abs/1901.11150 Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to a positive scalar. momentum: optional, a positive...
sm3
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def l2_norm(tree): """Compute the l2 norm of a pytree of arrays. Useful for weight decay.""" leaves, _ = jax.tree.flatten(tree) return jnp.sqrt(sum(jnp.vdot(x, x) for x in leaves))
Compute the l2 norm of a pytree of arrays. Useful for weight decay.
l2_norm
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def unpack_optimizer_state(opt_state): """Converts an OptimizerState to a marked pytree. Converts an OptimizerState to a marked pytree with the leaves of the outer pytree represented as JoinPoints to avoid losing information. This function is intended to be useful when serializing optimizer states. Args: ...
Converts an OptimizerState to a marked pytree. Converts an OptimizerState to a marked pytree with the leaves of the outer pytree represented as JoinPoints to avoid losing information. This function is intended to be useful when serializing optimizer states. Args: opt_state: An OptimizerState Returns: ...
unpack_optimizer_state
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def pack_optimizer_state(marked_pytree): """Converts a marked pytree to an OptimizerState. The inverse of unpack_optimizer_state. Converts a marked pytree with the leaves of the outer pytree represented as JoinPoints back into an OptimizerState. This function is intended to be useful when deserializing optim...
Converts a marked pytree to an OptimizerState. The inverse of unpack_optimizer_state. Converts a marked pytree with the leaves of the outer pytree represented as JoinPoints back into an OptimizerState. This function is intended to be useful when deserializing optimizer states. Args: marked_pytree: A pyt...
pack_optimizer_state
python
jax-ml/jax
jax/example_libraries/optimizers.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/optimizers.py
Apache-2.0
def Dense(out_dim, W_init=glorot_normal(), b_init=normal()): """Layer constructor function for a dense (fully-connected) layer.""" def init_fun(rng, input_shape): output_shape = input_shape[:-1] + (out_dim,) k1, k2 = random.split(rng) W, b = W_init(k1, (input_shape[-1], out_dim)), b_init(k2, (out_dim,))...
Layer constructor function for a dense (fully-connected) layer.
Dense
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def GeneralConv(dimension_numbers, out_chan, filter_shape, strides=None, padding='VALID', W_init=None, b_init=normal(1e-6)): """Layer construction function for a general convolution layer.""" lhs_spec, rhs_spec, out_spec = dimension_numbers one = (1,) * len(filter_shape) strides ...
Layer construction function for a general convolution layer.
GeneralConv
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def GeneralConvTranspose(dimension_numbers, out_chan, filter_shape, strides=None, padding='VALID', W_init=None, b_init=normal(1e-6)): """Layer construction function for a general transposed-convolution layer.""" lhs_spec, rhs_spec, out_spec = dimension_numbers one...
Layer construction function for a general transposed-convolution layer.
GeneralConvTranspose
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def BatchNorm(axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True, beta_init=zeros, gamma_init=ones): """Layer construction function for a batch normalization layer.""" _beta_init = lambda rng, shape: beta_init(rng, shape) if center else () _gamma_init = lambda rng, shape: gamma_init(rng, shape) i...
Layer construction function for a batch normalization layer.
BatchNorm
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def elementwise(fun, **fun_kwargs): """Layer that applies a scalar function elementwise on its inputs.""" init_fun = lambda rng, input_shape: (input_shape, ()) apply_fun = lambda params, inputs, **kwargs: fun(inputs, **fun_kwargs) return init_fun, apply_fun
Layer that applies a scalar function elementwise on its inputs.
elementwise
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def PoolingLayer(window_shape, strides=None, padding='VALID', spec=None): """Layer construction function for a pooling layer.""" strides = strides or (1,) * len(window_shape) rescale = rescaler(window_shape, strides, padding) if rescaler else None if spec is None: non_spatial_axes = 0, len(window...
Layer construction function for a pooling layer.
PoolingLayer
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def Flatten(): """Layer construction function for flattening all but the leading dim.""" def init_fun(rng, input_shape): output_shape = input_shape[0], functools.reduce(op.mul, input_shape[1:], 1) return output_shape, () def apply_fun(params, inputs, **kwargs): return jnp.reshape(inputs, (inputs.shape...
Layer construction function for flattening all but the leading dim.
Flatten
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def Identity(): """Layer construction function for an identity layer.""" init_fun = lambda rng, input_shape: (input_shape, ()) apply_fun = lambda params, inputs, **kwargs: inputs return init_fun, apply_fun
Layer construction function for an identity layer.
Identity
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def FanOut(num): """Layer construction function for a fan-out layer.""" init_fun = lambda rng, input_shape: ([input_shape] * num, ()) apply_fun = lambda params, inputs, **kwargs: [inputs] * num return init_fun, apply_fun
Layer construction function for a fan-out layer.
FanOut
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def FanInSum(): """Layer construction function for a fan-in sum layer.""" init_fun = lambda rng, input_shape: (input_shape[0], ()) apply_fun = lambda params, inputs, **kwargs: sum(inputs) return init_fun, apply_fun
Layer construction function for a fan-in sum layer.
FanInSum
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def FanInConcat(axis=-1): """Layer construction function for a fan-in concatenation layer.""" def init_fun(rng, input_shape): ax = axis % len(input_shape[0]) concat_size = sum(shape[ax] for shape in input_shape) out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:] return out_shap...
Layer construction function for a fan-in concatenation layer.
FanInConcat
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def Dropout(rate, mode='train'): """Layer construction function for a dropout layer with given rate.""" def init_fun(rng, input_shape): return input_shape, () def apply_fun(params, inputs, **kwargs): rng = kwargs.get('rng', None) if rng is None: msg = ("Dropout layer requires apply_fun to be cal...
Layer construction function for a dropout layer with given rate.
Dropout
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def serial(*layers): """Combinator for composing layers in serial. Args: *layers: a sequence of layers, each an (init_fun, apply_fun) pair. Returns: A new layer, meaning an (init_fun, apply_fun) pair, representing the serial composition of the given sequence of layers. """ nlayers = len(layers) ...
Combinator for composing layers in serial. Args: *layers: a sequence of layers, each an (init_fun, apply_fun) pair. Returns: A new layer, meaning an (init_fun, apply_fun) pair, representing the serial composition of the given sequence of layers.
serial
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def parallel(*layers): """Combinator for composing layers in parallel. The layer resulting from this combinator is often used with the FanOut and FanInSum layers. Args: *layers: a sequence of layers, each an (init_fun, apply_fun) pair. Returns: A new layer, meaning an (init_fun, apply_fun) pair, re...
Combinator for composing layers in parallel. The layer resulting from this combinator is often used with the FanOut and FanInSum layers. Args: *layers: a sequence of layers, each an (init_fun, apply_fun) pair. Returns: A new layer, meaning an (init_fun, apply_fun) pair, representing the parallel ...
parallel
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def shape_dependent(make_layer): """Combinator to delay layer constructor pair until input shapes are known. Args: make_layer: a one-argument function that takes an input shape as an argument (a tuple of positive integers) and returns an (init_fun, apply_fun) pair. Returns: A new layer, meaning an...
Combinator to delay layer constructor pair until input shapes are known. Args: make_layer: a one-argument function that takes an input shape as an argument (a tuple of positive integers) and returns an (init_fun, apply_fun) pair. Returns: A new layer, meaning an (init_fun, apply_fun) pair, represent...
shape_dependent
python
jax-ml/jax
jax/example_libraries/stax.py
https://github.com/jax-ml/jax/blob/master/jax/example_libraries/stax.py
Apache-2.0
def broadcast_one_to_all(in_tree: Any, is_source: bool | None = None) -> Any: """Broadcast data from a source host (host 0 by default) to all other hosts. Args: in_tree: pytree of arrays - each array *must* have the same shape across the hosts. is_source: optional bool denoting whether the caller is ...
Broadcast data from a source host (host 0 by default) to all other hosts. Args: in_tree: pytree of arrays - each array *must* have the same shape across the hosts. is_source: optional bool denoting whether the caller is the source. Only 'source host' will contribute the data for the broadcast. If...
broadcast_one_to_all
python
jax-ml/jax
jax/experimental/multihost_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/multihost_utils.py
Apache-2.0
def sync_global_devices(name: str): """Creates a barrier across all hosts/devices.""" h = np.uint32(zlib.crc32(name.encode())) assert_equal(h, f"sync_global_devices name mismatch ('{name}')")
Creates a barrier across all hosts/devices.
sync_global_devices
python
jax-ml/jax
jax/experimental/multihost_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/multihost_utils.py
Apache-2.0
def process_allgather(in_tree: Any, tiled: bool = False) -> Any: """Gather data from across processes. Args: in_tree: pytree of arrays - each array _must_ have the same shape across the hosts. tiled: Whether to stack or concat the output. Defaults to False i.e. stack into a new positional axis ...
Gather data from across processes. Args: in_tree: pytree of arrays - each array _must_ have the same shape across the hosts. tiled: Whether to stack or concat the output. Defaults to False i.e. stack into a new positional axis at index 0. Returns: Pytrees of numpy arrays. * If the in...
process_allgather
python
jax-ml/jax
jax/experimental/multihost_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/multihost_utils.py
Apache-2.0
def assert_equal(in_tree, fail_message: str = ''): """Verifies that all the hosts have the same tree of values.""" expected = broadcast_one_to_all(in_tree) if not jax.tree_util.tree_all( jax.tree_util.tree_map(lambda *x: np.all(np.equal(*x)), in_tree, expected)): raise AssertionError( f'{fail_me...
Verifies that all the hosts have the same tree of values.
assert_equal
python
jax-ml/jax
jax/experimental/multihost_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/multihost_utils.py
Apache-2.0
def reached_preemption_sync_point(step_id: int) -> bool: """Determine whether all hosts have reached a preemption sync step. When any host receives a preemption notice, the notice is propagated to all hosts and triggers a synchronization protocol in the background. The synchronization protocol calculates the m...
Determine whether all hosts have reached a preemption sync step. When any host receives a preemption notice, the notice is propagated to all hosts and triggers a synchronization protocol in the background. The synchronization protocol calculates the maximum step ids from all hosts, and uses the next step id (i...
reached_preemption_sync_point
python
jax-ml/jax
jax/experimental/multihost_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/multihost_utils.py
Apache-2.0
def host_local_array_to_global_array( local_inputs: Any, global_mesh: jax.sharding.Mesh, pspecs: Any): r"""Converts a host local value to a globally sharded jax.Array. This function takes host-local data (which might be different across hosts), and populates a global array with this data, where each device...
Converts a host local value to a globally sharded jax.Array. This function takes host-local data (which might be different across hosts), and populates a global array with this data, where each device on each host, get the appropriate slice of the data according to sharding defined by the global_mesh/pspects. ...
host_local_array_to_global_array
python
jax-ml/jax
jax/experimental/multihost_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/multihost_utils.py
Apache-2.0
def global_array_to_host_local_array( global_inputs: Any, global_mesh: jax.sharding.Mesh, pspecs: Any): r"""Converts a global `jax.Array` to a host local `jax.Array`. You can use this function to transition to `jax.Array`. Using `jax.Array` with pjit has the same semantics of using GDA with pjit i.e. all `ja...
Converts a global `jax.Array` to a host local `jax.Array`. You can use this function to transition to `jax.Array`. Using `jax.Array` with pjit has the same semantics of using GDA with pjit i.e. all `jax.Array` inputs to pjit should be globally shaped and the output from pjit will also be globally shaped jax.Ar...
global_array_to_host_local_array
python
jax-ml/jax
jax/experimental/multihost_utils.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/multihost_utils.py
Apache-2.0
def odeint(func, y0, t, *args, rtol=1.4e-8, atol=1.4e-8, mxstep=jnp.inf, hmax=jnp.inf): """Adaptive stepsize (Dormand-Prince) Runge-Kutta odeint implementation. Args: func: function to evaluate the time derivative of the solution `y` at time `t` as `func(y, t, *args)`, producing the same shape/structure ...
Adaptive stepsize (Dormand-Prince) Runge-Kutta odeint implementation. Args: func: function to evaluate the time derivative of the solution `y` at time `t` as `func(y, t, *args)`, producing the same shape/structure as `y0`. y0: array or pytree of arrays representing the initial value for the state. ...
odeint
python
jax-ml/jax
jax/experimental/ode.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/ode.py
Apache-2.0
def _W_ih_l(layer_i: int, input_size: int, hidden_size: int, bidirectional: bool) -> Shape: """Shape of W_ii|W_if|W_ig|W_io. Note that layer_i is an index of pseudo-layers. """ if layer_i == 0 or (layer_i == 1 and bidirectional): return (4 * hidden_size, input_size) else: num_directions =...
Shape of W_ii|W_if|W_ig|W_io. Note that layer_i is an index of pseudo-layers.
_W_ih_l
python
jax-ml/jax
jax/experimental/rnn.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/rnn.py
Apache-2.0
def _get_params_shapes_in_lstm(input_size: int, hidden_size: int, num_layers: int, bidirectional: bool) -> list[Shape]: """Get flat param shapes in LSTM. See module docstring for layout.""" layer_shapes = [] num_directions = 2 if bidirectional else 1 ...
Get flat param shapes in LSTM. See module docstring for layout.
_get_params_shapes_in_lstm
python
jax-ml/jax
jax/experimental/rnn.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/rnn.py
Apache-2.0
def init_lstm_weight(rng: PRNGKeyArray, input_size: int, hidden_size: int, num_layers: int, bidirectional: bool): """Random initialize LSTM weights from U(-k, k), k=sqrt(1/hidden_size).""" param_count = get_num_params_in_lstm(input_size, hidden_size, num_layers, ...
Random initialize LSTM weights from U(-k, k), k=sqrt(1/hidden_size).
init_lstm_weight
python
jax-ml/jax
jax/experimental/rnn.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/rnn.py
Apache-2.0
def swap_lstm_gates(weights, input_size, hidden_size, num_layers, bidirectional): """Swaps the weights for the input and output gates for an LSTM model.""" weights = jnp.asarray(weights) # Ensure weights are JAX arrays flat_shapes = _get_params_shapes_in_lstm(input_size, hidden_size, num_layers, bidirectional) ...
Swaps the weights for the input and output gates for an LSTM model.
swap_lstm_gates
python
jax-ml/jax
jax/experimental/rnn.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/rnn.py
Apache-2.0
def unpack_lstm_weights( weights: Array, input_size: int, hidden_size: int, num_layers: int, bidirectional: bool ) -> tuple[dict[int, Array], dict[int, Array], dict[int, Array], dict[int, Array]]: """Unpack cudnn LSTM weights into individua...
Unpack cudnn LSTM weights into individual weights. CUDNN LSTM weight layout: (num_layers, num_directions, W_ih, W_hh, b_ih, b_hh) Returns W_ih, W_hh, b_ih, b_hh. e.g. W_ih[2][1] is the concat weights of 4 weights (W_ii, W_if, W_ig, W_io), each of shape (hidden_size, input_size) at 2nd layer for the reverse dir...
unpack_lstm_weights
python
jax-ml/jax
jax/experimental/rnn.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/rnn.py
Apache-2.0
def lstm(x: Array, h_0: Array, c_0: Array, weights: Array, seq_lengths: Array, input_size: int, hidden_size: int, num_layers: int, dropout: float, bidirectional: bool, precision: lax.PrecisionLike = None) -> tuple[Array, Array, Array]: """LSTM via CuDNN or HIPDNN (not-yet-supported). Assume batch...
LSTM via CuDNN or HIPDNN (not-yet-supported). Assume batch-first inputs. Arguments: x: (batch_size, max_seq_length, input_size) h_0: (num_directions * num_layers, batch_size, hidden_size) c_0: (num_directions * num_layers, batch_size, hidden_size) weights: (num_params,) where num_params = get_num_...
lstm
python
jax-ml/jax
jax/experimental/rnn.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/rnn.py
Apache-2.0
def lstm_ref(x: Array, h_0: Array, c_0: Array, W_ih: dict[int, Array], W_hh: dict[int, Array], b_ih: dict[int, Array], b_hh: dict[int, Array], seq_lengths: Array, input_size: int, hidden_size: int, num_layers: int, dropout: float, bidirectional: bool) -> tuple[Array, ...
Reference implementation of LSTM. See https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html#lstm https://docs.nvidia.com/deeplearning/cudnn/api/index.html#cudnnRNNMode_t
lstm_ref
python
jax-ml/jax
jax/experimental/rnn.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/rnn.py
Apache-2.0
def serialize(compiled: jax.stages.Compiled): """Serializes a compiled binary. Because pytrees are not serializable, they are returned so that the user can handle them properly. """ unloaded_executable = getattr(compiled._executable, '_unloaded_executable', None) if unloaded...
Serializes a compiled binary. Because pytrees are not serializable, they are returned so that the user can handle them properly.
serialize
python
jax-ml/jax
jax/experimental/serialize_executable.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/serialize_executable.py
Apache-2.0
def deserialize_and_load(serialized, in_tree, out_tree, backend: str | xc.Client | None = None, execution_devices: Sequence[xc.Device] | None = None): """Constructs a jax.stages.Compiled from a serialized executable.""...
Constructs a jax.stages.Compiled from a serialized executable.
deserialize_and_load
python
jax-ml/jax
jax/experimental/serialize_executable.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/serialize_executable.py
Apache-2.0
def shard_map( f: Callable, mesh: Mesh | AbstractMesh, in_specs: Specs, out_specs: Specs, check_rep: bool = True, auto: frozenset[AxisName] = frozenset()): """Map a function over shards of data. Note: ``shard_map`` is an experimental API, and still subject to change. For an introduction to sharded ...
Map a function over shards of data. Note: ``shard_map`` is an experimental API, and still subject to change. For an introduction to sharded data, refer to :ref:`sharded-computation`. For a more in-depth look at using ``shard_map``, refer to `SPMD multi-device parallelism with shard_map`_. Args: f:...
shard_map
python
jax-ml/jax
jax/experimental/shard_map.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/shard_map.py
Apache-2.0
def pull(self, uuid: int, xs: Any) -> Any: """Fetches a pytree of arrays from a remote device. Args: uuid: identifier for the request xs: A pytree of ShapeDtypeStruct. Returns: A pytree of arrays. """ xs_flat, tree = jax.tree.flatten(xs) if not xs_flat: return xs ...
Fetches a pytree of arrays from a remote device. Args: uuid: identifier for the request xs: A pytree of ShapeDtypeStruct. Returns: A pytree of arrays.
pull
python
jax-ml/jax
jax/experimental/transfer.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/transfer.py
Apache-2.0
def _get_unique_sync_key() -> str | None: """Generate a thread-local key for ensuring all host finish (de)serializing""" if jax.process_count() == 1: return None # broadcast a thread-local unique barrier name sync_key_unique = multihost_utils.broadcast_one_to_all( np.frombuffer(uuid4().bytes, dtype=np...
Generate a thread-local key for ensuring all host finish (de)serializing
_get_unique_sync_key
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def _is_str_same_on_all_hosts(path: str | PathLike[str]) -> bool: """All-gather the location of the checkpoint and check if it's the same.""" if jax.process_count() <= 1: return False path_b = str(path).encode("utf-8") if len(path_b) > _MAX_PATH_LENGTH: raise ValueError(f"Path exceeds maximum length of ...
All-gather the location of the checkpoint and check if it's the same.
_is_str_same_on_all_hosts
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def _is_remote_path(path: str | PathLike[str]): """Check whether a path is remote by examining the prefix.""" # we need to truncate e.g., gs:// to gs:/ because pathlib.Path collapses // return any(str(path).startswith(prefix[:-1]) for prefix in _REMOTE_URL_PREFIXES)
Check whether a path is remote by examining the prefix.
_is_remote_path
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def _set_up_destination(root: str | PathLike[str], overwrite: bool, pytree_repr: dict[str, Any], distinct_locations: bool, sync_key: str | None) -> dict[str, Any]: """Inspect the destination, set it up for writing, potentially read existing data.""" root = _norm_path(...
Inspect the destination, set it up for writing, potentially read existing data.
_set_up_destination
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def _prepare_directory(root: str | PathLike[str], overwrite: bool, pytreedef_repr: dict[str, Any], distinct_locations: bool, sync_key: str | None): """Prepare the directory: check destination, potentially read existing data and overwrite. Raises: RuntimeError: If...
Prepare the directory: check destination, potentially read existing data and overwrite. Raises: RuntimeError: If the destination directory cannot be created.
_prepare_directory
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def _finalize_array_store(kvstore_path, distinct_locations: bool): """When multiple processes are writing, they must write to a per-process location followed by combining them via no-copy links to the final location. """ # only in multiprocess case and only process 0 if distinct_locations or jax.process_count...
When multiple processes are writing, they must write to a per-process location followed by combining them via no-copy links to the final location.
_finalize_array_store
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def _write_pytreedef(directory: Any, pytree_repr: dict[str, Any], distinct_locations: bool): """Write the pytreedef to the destination directory and aux data to the archive.""" if not (jax.process_index() == 0 or distinct_locations): return root = _norm_path(directory) (root / _PYTREEDE...
Write the pytreedef to the destination directory and aux data to the archive.
_write_pytreedef
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def _tree_broadcast(a, b, is_leaf=lambda x: x is None): """Broadcast the prefix tree `a` to the full tree `b` Uses `flatten_axes` for better error messages on mismatched arity but allowing for custom is_leaf in the `a` and `b` trees. """ a_leaves, a_struct = jax.tree.flatten(a, is_leaf=is_leaf) a_idx2leaf_...
Broadcast the prefix tree `a` to the full tree `b` Uses `flatten_axes` for better error messages on mismatched arity but allowing for custom is_leaf in the `a` and `b` trees.
_tree_broadcast
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def save(data: PyTreeT, directory: str | PathLike[str], *, overwrite: bool = True, ts_specs: PyTreeT | None = None) -> None: """Saves the given data structure to the provided directory path. This function provides functionality to serialize and save a data structure comprising JAX arrays, along with its...
Saves the given data structure to the provided directory path. This function provides functionality to serialize and save a data structure comprising JAX arrays, along with its structure to a given directory. It leverages `PyTree` for flattening and reconstructing the data structure. This is a simple experime...
save
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def load_pytreedef(directory: str | PathLike[str]) -> PyTreeT: """Loads a pytree from the given directory. This is a simple experimental array serialization API, for anything more complex and for all checkpointing prefer: https://github.com/google/orbax Args: directory: Directory path to load from. Retu...
Loads a pytree from the given directory. This is a simple experimental array serialization API, for anything more complex and for all checkpointing prefer: https://github.com/google/orbax Args: directory: Directory path to load from. Returns: The loaded pytree with arrays represented as jax.ShapeDtype...
load_pytreedef
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def load(directory: str | PathLike[str], shardings: PyTreeT, *, mask: PyTreeT | None = None, ts_specs: PyTreeT | None = None ) -> PyTreeT: """Loads and reconstructs a data structure from a directory. This is a simple experimental array serialization API, for anything more complex and for all ch...
Loads and reconstructs a data structure from a directory. This is a simple experimental array serialization API, for anything more complex and for all checkpointing prefer: https://github.com/google/orbax Args: directory: Directory path where the data is stored. shardings: Sharding strategy for array ob...
load
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def nonblocking_save(data: PyTreeT, directory: str | PathLike[str], *, overwrite: bool = True, ts_specs: PyTreeT | None = None ) -> utils.PyTreeFuture: """Nonblocking alias of save, return an awaitable future with a pytree stub. This is a simple experimental array serializ...
Nonblocking alias of save, return an awaitable future with a pytree stub. This is a simple experimental array serialization API, for anything more complex and for all checkpointing prefer: https://github.com/google/orbax Examples: >>> fut = nonblocking_save(data, directory) >>> print(fut.pytree) # a py...
nonblocking_save
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def nonblocking_load(directory: str | PathLike[str], shardings: PyTreeT, *, mask: PyTreeT | None = None, ts_specs: PyTreeT | None = None) -> utils.PyTreeFuture: """Nonblocking alias of load, return an awaitable future with a pytree stub. This is a simple experimental array...
Nonblocking alias of load, return an awaitable future with a pytree stub. This is a simple experimental array serialization API, for anything more complex and for all checkpointing prefer: https://github.com/google/orbax Examples: >>> fut = nonblocking_load(directory) >>> print(fut.pytree) # a pytree o...
nonblocking_load
python
jax-ml/jax
jax/experimental/array_serialization/pytree_serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/pytree_serialization.py
Apache-2.0
def is_remote_storage(tspec: dict[str, Any] | str) -> bool: """Detect if user is using cloud storages. This can detect common defines and unable to detect some corner cases such as using gcsfuse. """ if isinstance(tspec, str): # KvStoreUrl if re.match(rf'^({"|".join(_REMOTE_URL_PREFIXES)})', tspec): ...
Detect if user is using cloud storages. This can detect common defines and unable to detect some corner cases such as using gcsfuse.
is_remote_storage
python
jax-ml/jax
jax/experimental/array_serialization/serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/serialization.py
Apache-2.0
def check_for_errors(self): """Checks if any errors have been raised in the child thread. This is a non-blocking call that can be called in the main thread. """
Checks if any errors have been raised in the child thread. This is a non-blocking call that can be called in the main thread.
check_for_errors
python
jax-ml/jax
jax/experimental/array_serialization/serialization.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/serialization.py
Apache-2.0
def merge_nested_ts_specs(dict1: dict[Any, Any], dict2: dict[Any, Any] | None): """Merge two ts specs, dict2 takes precedence.""" if dict2 is None: # nothing to do return dict1 # TODO(rdyro): this is an opinionated merge, we should get user feedback # merge kvstore explicitly kvstore = dict1.get("kvstore...
Merge two ts specs, dict2 takes precedence.
merge_nested_ts_specs
python
jax-ml/jax
jax/experimental/array_serialization/tensorstore_impl.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/tensorstore_impl.py
Apache-2.0
def verify_tensorstore_spec(spec: dict[str, Any], arr: jax.Array | None, path: str | os.PathLike[str], ocdbt: bool, check_metadata: bool = True) -> None: """Verify the minimum requirements for a tensorstore spec.""" if ocdbt: if spec.get("kvstore", {}).get...
Verify the minimum requirements for a tensorstore spec.
verify_tensorstore_spec
python
jax-ml/jax
jax/experimental/array_serialization/tensorstore_impl.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/tensorstore_impl.py
Apache-2.0
async def combine_kvstores(combined_kvstore: dict[str, Any], kvstores: list[dict[str, Any]], context: ts.Context | dict[str, Any] = _TS_CONTEXT ) -> None: """Merge a list of kvstores into a single kvstore. NOT multi-process safe.""" co...
Merge a list of kvstores into a single kvstore. NOT multi-process safe.
combine_kvstores
python
jax-ml/jax
jax/experimental/array_serialization/tensorstore_impl.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/tensorstore_impl.py
Apache-2.0
def _run_serialization(arrays, tensorstore_specs): """Legacy serialization of a list of arrays.""" async def _run_serializer(): future_writer = jax.tree_util.tree_map(async_serialize, arrays, tensorstore_specs) return await asyncio.gather(*future_writer) asyncio.run(_run_serializer())
Legacy serialization of a list of arrays.
_run_serialization
python
jax-ml/jax
jax/experimental/array_serialization/tensorstore_impl.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/tensorstore_impl.py
Apache-2.0
async def async_deserialize( user_in_sharding: jax.sharding.Sharding | Format, tensorstore_spec: ts.Spec | dict[str, Any], global_shape: Sequence[int] | None = None, dtype=None, byte_limiter: _LimitInFlightBytes | None = None, context=_TS_CONTEXT, chunk_layout=_TS_CHUNK_LAYOUT, assume_me...
Main performant deserialization routine for arrays using tensorstore.
async_deserialize
python
jax-ml/jax
jax/experimental/array_serialization/tensorstore_impl.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/tensorstore_impl.py
Apache-2.0
def _run_deserialization(shardings: Sequence[jax.sharding.Sharding | Format], tensorstore_specs: Sequence[dict[str, Any]], global_shapes: Sequence[array.Shape] | None = None, dtypes: Sequence[typing.DTypeLike] | None = None, ...
Legacy deserialization of a list of arrays. Optionally pass global_shapes and dtypes for type-checking.
_run_deserialization
python
jax-ml/jax
jax/experimental/array_serialization/tensorstore_impl.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/array_serialization/tensorstore_impl.py
Apache-2.0
def colocated_cpu_devices( devices: Sequence[jax.Device], ) -> Sequence[jax.Device]: """Finds CPU devices colocated with the given devices.""" if not isinstance(devices, tuple): devices = tuple(devices) try: return _colocated_cpu_devices_cached(devices) except (ValueError, AttributeError): retur...
Finds CPU devices colocated with the given devices.
colocated_cpu_devices
python
jax-ml/jax
jax/experimental/colocated_python/api.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/api.py
Apache-2.0
def colocated_python(fun: Callable[..., Any]) -> Callable[..., Any]: """Executes the given Python function on the same devices as the arguments.""" return make_callable( fun, api_util.fun_sourceinfo(fun), api_util.fun_signature(fun) )
Executes the given Python function on the same devices as the arguments.
colocated_python
python
jax-ml/jax
jax/experimental/colocated_python/api.py
https://github.com/jax-ml/jax/blob/master/jax/experimental/colocated_python/api.py
Apache-2.0
def _get_spec(x: Any) -> api.ShapeDtypeStruct: """Extracts a spec for a value, which must be a JAX Array.""" # TODO(hyeontaek): Allow Python values and automatically apply `shard_arg` # with a suitable sharding and layout. if not isinstance(x, jax.Array): raise ValueError( "colocated_python only sup...
Extracts a spec for a value, which must be a JAX Array.
_get_spec
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 _infer_devices_from_args(args: Sequence[Any]) -> xc.DeviceList | None: """Returns a representative device list from function call arguments.""" device_list_set: set[xc.DeviceList] = set() for x in args: sharding = getattr(x, "sharding", None) if sharding is not None: device_list_set.add(x.shardi...
Returns a representative device list from function call arguments.
_infer_devices_from_args
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