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 populate_stores(self, stores): """Copy the values from the `stores` into `self.stores`.""" for self_store, other_store in zip(self.stores, stores): if self_store is not None: self_store.store(other_store.val)
Copy the values from the `stores` into `self.stores`.
populate_stores
python
jax-ml/jax
jax/_src/linear_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/linear_util.py
Apache-2.0
def transformation_with_aux2( gen, fun: WrappedFun, *gen_static_args, use_eq_store: bool = False ) -> tuple[WrappedFun, Callable[[], Any]]: """Adds one more transformation with auxiliary output to a WrappedFun.""" out_store = Store() if not use_eq_store else EqualStore() out_thunk = lambda: out_store.val re...
Adds one more transformation with auxiliary output to a WrappedFun.
transformation_with_aux2
python
jax-ml/jax
jax/_src/linear_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/linear_util.py
Apache-2.0
def resolve_result_paths(self) -> DebugInfo: """Return a debug info with resolved result paths.""" assert self.result_paths is not None if callable(self.result_paths): return self._replace(result_paths=tuple(self.result_paths())) return self
Return a debug info with resolved result paths.
resolve_result_paths
python
jax-ml/jax
jax/_src/linear_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/linear_util.py
Apache-2.0
def safe_result_paths(self, expected: int) -> tuple[str, ...]: """Get the result paths with a safety check.""" assert self.result_paths is not None and not callable(self.result_paths), self if self.result_paths is not None and len(self.result_paths) == expected: return self.result_paths else: ...
Get the result paths with a safety check.
safe_result_paths
python
jax-ml/jax
jax/_src/linear_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/linear_util.py
Apache-2.0
def filter_result_paths(self, keep: Sequence[bool]) -> tuple[str, ...]: """Keep only the result_paths for which `keep` is True.""" assert self.result_paths is not None and not callable(self.result_paths), self return tuple(v for v, b in zip(self.safe_result_paths(len(keep)), keep) if b)
Keep only the result_paths for which `keep` is True.
filter_result_paths
python
jax-ml/jax
jax/_src/linear_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/linear_util.py
Apache-2.0
def wrap_init(f: Callable, params=None, *, debug_info: DebugInfo) -> WrappedFun: """Wraps function `f` as a `WrappedFun`, suitable for transformation.""" params_dict = {} if params is None else params params = () if params is None else tuple(sorted(params.items())) fun = WrappedFun(f, partial(f, *...
Wraps function `f` as a `WrappedFun`, suitable for transformation.
wrap_init
python
jax-ml/jax
jax/_src/linear_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/linear_util.py
Apache-2.0
def cache(call: Callable, *, explain: Callable[[WrappedFun, bool, dict, tuple, float], None] | None = None): """Memoization decorator for functions taking a WrappedFun as first argument. Args: call: a Python callable that takes a WrappedFun as its first argument. The underlying transforms and p...
Memoization decorator for functions taking a WrappedFun as first argument. Args: call: a Python callable that takes a WrappedFun as its first argument. The underlying transforms and params on the WrappedFun are used as part of the memoization cache key. explain: a function that is invoked upon c...
cache
python
jax-ml/jax
jax/_src/linear_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/linear_util.py
Apache-2.0
def _enable_debug_logging(logger_name): """Makes the specified logger log everything to stderr. Also adds more useful debug information to the log messages, e.g. the time. Args: logger_name: the name of the logger, e.g. "jax._src.xla_bridge". """ logger = logging.getLogger(logger_name) _debug_enabled_...
Makes the specified logger log everything to stderr. Also adds more useful debug information to the log messages, e.g. the time. Args: logger_name: the name of the logger, e.g. "jax._src.xla_bridge".
_enable_debug_logging
python
jax-ml/jax
jax/_src/logging_config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/logging_config.py
Apache-2.0
def _disable_all_debug_logging(): """Disables all debug logging enabled via `enable_debug_logging`. The default logging behavior will still be in effect, i.e. WARNING and above will be logged to stderr without extra message formatting. """ for logger, prev_level in _debug_enabled_loggers: logger: logging...
Disables all debug logging enabled via `enable_debug_logging`. The default logging behavior will still be in effect, i.e. WARNING and above will be logged to stderr without extra message formatting.
_disable_all_debug_logging
python
jax-ml/jax
jax/_src/logging_config.py
https://github.com/jax-ml/jax/blob/master/jax/_src/logging_config.py
Apache-2.0
def get(self, key: str) -> bytes | None: """Retrieves the cached value for the given key. Args: key: The key for which the cache value is retrieved. Returns: The cached data as bytes if available; ``None`` otherwise. """ if not key: raise ValueError("key cannot be empty") ca...
Retrieves the cached value for the given key. Args: key: The key for which the cache value is retrieved. Returns: The cached data as bytes if available; ``None`` otherwise.
get
python
jax-ml/jax
jax/_src/lru_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lru_cache.py
Apache-2.0
def put(self, key: str, val: bytes) -> None: """Adds a new entry to the cache. If a cache item with the same key already exists, no action will be taken, even if the value is different. Args: key: The key under which the data will be stored. val: The data to be stored. """ if not k...
Adds a new entry to the cache. If a cache item with the same key already exists, no action will be taken, even if the value is different. Args: key: The key under which the data will be stored. val: The data to be stored.
put
python
jax-ml/jax
jax/_src/lru_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lru_cache.py
Apache-2.0
def _evict_if_needed(self, *, additional_size: int = 0) -> None: """Evicts the least recently used items from the cache if necessary to ensure the cache does not exceed its maximum size. Args: additional_size: The size of the new entry being added to the cache. This is included to account for...
Evicts the least recently used items from the cache if necessary to ensure the cache does not exceed its maximum size. Args: additional_size: The size of the new entry being added to the cache. This is included to account for the new entry when checking if eviction is needed.
_evict_if_needed
python
jax-ml/jax
jax/_src/lru_cache.py
https://github.com/jax-ml/jax/blob/master/jax/_src/lru_cache.py
Apache-2.0
def _v5e_create_device_mesh( mesh_shape: Sequence[int], devices: Sequence[Any], **unused_kwargs ) -> np.ndarray | None: """Creates rotated pincer device assignment for selected topologies. Args: mesh_shape: Logical mesh shape used by the model. devices: TPU devices. **unused_kwargs: ... Returns:...
Creates rotated pincer device assignment for selected topologies. Args: mesh_shape: Logical mesh shape used by the model. devices: TPU devices. **unused_kwargs: ... Returns: None or reordered devices reshaped as `mesh_shape`.
_v5e_create_device_mesh
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def _v5p_create_device_mesh( mesh_shape: Sequence[int], devices: Sequence[Any], **unused_kwargs ) -> np.ndarray | None: """Creates device assignment for selected topologies. Args: mesh_shape: Logical mesh shape used by the model. devices: TPU devices. **unused_kwargs: ... Returns: None or re...
Creates device assignment for selected topologies. Args: mesh_shape: Logical mesh shape used by the model. devices: TPU devices. **unused_kwargs: ... Returns: None or reordered devices reshaped as `mesh_shape`.
_v5p_create_device_mesh
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def _create_device_mesh_for_nd_torus( physical_mesh: np.ndarray, mesh_shape: Sequence[int], *, allow_split_physical_axes: bool = False, ) -> tuple[np.ndarray, np.ndarray]: """Assigns logical parallelism axes to physical axes of an N-D torus network. Given logical parallelism axes with sizes in `mes...
Assigns logical parallelism axes to physical axes of an N-D torus network. Given logical parallelism axes with sizes in `mesh_shape` and devices in an N-dimensional torus network represented by `physical_mesh`, maps each logical axis to one or more physical axes. Prefer to map more-performance-sensitive logica...
_create_device_mesh_for_nd_torus
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def _create_device_mesh_for_nd_torus_splitting_axes( physical_mesh: np.ndarray, mesh_shape: Sequence[int], ) -> tuple[np.ndarray, np.ndarray]: """Assigns logical parallelism axes to physical axes of an N-D torus network. This implementation allows creating meshes that requires splitting physical axes, an...
Assigns logical parallelism axes to physical axes of an N-D torus network. This implementation allows creating meshes that requires splitting physical axes, and thus one could produce logical mesh of any shape, as long as the number of devices matches, e.g., - Creating 2x2x4 from 4x4; - Creating 2x2x16 fro...
_create_device_mesh_for_nd_torus_splitting_axes
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def _get_prime_factors(x: int) -> list[int]: """Returns a sorted list of prime factors for the given number.""" assert x > 0 factors = [] for p in range(2, math.isqrt(x) + 2): while x % p == 0: factors.append(p) x //= p if x == 1: return factors else: return [x] # x is a prime n...
Returns a sorted list of prime factors for the given number.
_get_prime_factors
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def _enumerate_feasible_logical_axis_assignments( physical_mesh_shape: Sequence[int], assignment: np.ndarray, logical_axis_size: int, ) -> Generator[np.ndarray, None, None]: """Yields feasible assignments for a single logical axis. For a physical mesh of shape [x_1, ..., x_n], and the product of all pr...
Yields feasible assignments for a single logical axis. For a physical mesh of shape [x_1, ..., x_n], and the product of all previous assignments on each physical axes [y_1, ..., y_n], this function yields all possible assignments for the axis as 1-d arrays [z_1, ..., z_n], so that: - prod(z_1, ..., z_n) = log...
_enumerate_feasible_logical_axis_assignments
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def _prefer_first_logical_axis_assignment( x: np.ndarray, y: np.ndarray, *, physical_mesh_shape: Sequence[int], assignment: np.ndarray, ) -> bool: """Returns True if the first axis assignment is preferred over the second. For now, this is implemented with some very simple heuristics. However, ...
Returns True if the first axis assignment is preferred over the second. For now, this is implemented with some very simple heuristics. However, it is possible to introduce e.g., a value function here based on a more precise model of the underlying hardware. TODO(rosun): Use a proxy of network capacity to sele...
_prefer_first_logical_axis_assignment
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def _generate_logical_mesh( physical_mesh: np.ndarray, logical_mesh_shape: Sequence[int], assignment: np.ndarray, ) -> np.ndarray: """Compute the logical mesh from assignment map. Args: physical_mesh: Physical device mesh. logical_mesh_shape: Logical mesh shape. assignment: 2-d assignment m...
Compute the logical mesh from assignment map. Args: physical_mesh: Physical device mesh. logical_mesh_shape: Logical mesh shape. assignment: 2-d assignment matrix shape [physical_dims, logical_dims]. Returns: Logical mesh reshaped from physical mesh.
_generate_logical_mesh
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def _get_physical_tpu_mesh(jax_devices: Sequence[Any]) -> np.ndarray: r"""Rearrange TPU devices in a slice into a physical mesh. Args: jax_devices: A list of JAX devices in a TPU slice in process-tiled z, y, x, core order, e.g. from jax.devices(). The coordinates of these devices should constitute ...
Rearrange TPU devices in a slice into a physical mesh. Args: jax_devices: A list of JAX devices in a TPU slice in process-tiled z, y, x, core order, e.g. from jax.devices(). The coordinates of these devices should constitute a cuboid with no holes; e.g., the coordinates can be {(1, 0, 0), (1, 0...
_get_physical_tpu_mesh
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def create_device_mesh( mesh_shape: Sequence[int], devices: Sequence[Any] | None = None, *, contiguous_submeshes: bool = False, allow_split_physical_axes: bool = False, ) -> np.ndarray: """Creates a performant device mesh for jax.sharding.Mesh. Args: mesh_shape: shape of logical mesh, order...
Creates a performant device mesh for jax.sharding.Mesh. Args: mesh_shape: shape of logical mesh, ordered by increasing network-intensity e.g. [replica, data, mdl] where mdl has the most network communication requirements. devices: optionally, the devices to construct a mesh for. Defaults to ...
create_device_mesh
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def create_hybrid_device_mesh( mesh_shape: Sequence[int], dcn_mesh_shape: Sequence[int], devices: Sequence[Any] | None = None, *, process_is_granule: bool = False, should_sort_granules_by_key: bool = True, allow_split_physical_axes: bool = False, ) -> np.ndarray: """Creates a device mesh f...
Creates a device mesh for hybrid (e.g., ICI and DCN) parallelism. Args: mesh_shape: shape of the logical mesh for the faster/inner network, ordered by increasing network intensity, e.g. [replica, data, mdl] where mdl has the most network communication requirements. dcn_mesh_shape: shape of the lo...
create_hybrid_device_mesh
python
jax-ml/jax
jax/_src/mesh_utils.py
https://github.com/jax-ml/jax/blob/master/jax/_src/mesh_utils.py
Apache-2.0
def record_event_duration_secs(event: str, duration: float, **kwargs: str | int) -> None: """Record an event duration in seconds (float). If **kwargs are specified, all of the named arguments have to be passed in the same order across all invocations of this method for the same eve...
Record an event duration in seconds (float). If **kwargs are specified, all of the named arguments have to be passed in the same order across all invocations of this method for the same event.
record_event_duration_secs
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def record_event_time_span( event: str, start_time: float, end_time: float, **kwargs: str | int ) -> None: """Record an event start and end time in seconds (float).""" for callback in _event_time_span_listeners: callback(event, start_time, end_time, **kwargs)
Record an event start and end time in seconds (float).
record_event_time_span
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def register_event_listener( callback: EventListenerWithMetadata, ) -> None: """Register a callback to be invoked during record_event().""" _event_listeners.append(callback)
Register a callback to be invoked during record_event().
register_event_listener
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def register_event_time_span_listener( callback: EventTimeSpanListenerWithMetadata, ) -> None: """Register a callback to be invoked during record_event_time_span().""" _event_time_span_listeners.append(callback)
Register a callback to be invoked during record_event_time_span().
register_event_time_span_listener
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def register_event_duration_secs_listener( callback : EventDurationListenerWithMetadata) -> None: """Register a callback to be invoked during record_event_duration_secs().""" _event_duration_secs_listeners.append(callback)
Register a callback to be invoked during record_event_duration_secs().
register_event_duration_secs_listener
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def register_scalar_listener( callback : ScalarListenerWithMetadata, ) -> None: """Register a callback to be invoked during record_scalar().""" _scalar_listeners.append(callback)
Register a callback to be invoked during record_scalar().
register_scalar_listener
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def _unregister_event_duration_listener_by_callback( callback: EventDurationListenerWithMetadata) -> None: """Unregister an event duration listener by callback. This function is supposed to be called for testing only. """ assert callback in _event_duration_secs_listeners _event_duration_secs_listeners.re...
Unregister an event duration listener by callback. This function is supposed to be called for testing only.
_unregister_event_duration_listener_by_callback
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def _unregister_event_duration_listener_by_index(index: int) -> None: """Unregister an event duration listener by index. This function is supposed to be called for testing only. """ size = len(_event_duration_secs_listeners) assert -size <= index < size del _event_duration_secs_listeners[index]
Unregister an event duration listener by index. This function is supposed to be called for testing only.
_unregister_event_duration_listener_by_index
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def _unregister_event_time_span_listener_by_callback( callback: EventTimeSpanListenerWithMetadata, ) -> None: """Unregister an event time span listener by callback. This function is supposed to be called for testing only. """ assert callback in _event_time_span_listeners _event_time_span_listeners.remove...
Unregister an event time span listener by callback. This function is supposed to be called for testing only.
_unregister_event_time_span_listener_by_callback
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def _unregister_event_listener_by_callback( callback: EventListenerWithMetadata) -> None: """Unregister an event listener by callback. This function is supposed to be called for testing only. """ assert callback in _event_listeners _event_listeners.remove(callback)
Unregister an event listener by callback. This function is supposed to be called for testing only.
_unregister_event_listener_by_callback
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def _unregister_scalar_listener_by_callback( callback: ScalarListenerWithMetadata, ) -> None: """Unregister a scalar event listener by callback. This function is supposed to be called for testing only. """ assert callback in _scalar_listeners _scalar_listeners.remove(callback)
Unregister a scalar event listener by callback. This function is supposed to be called for testing only.
_unregister_scalar_listener_by_callback
python
jax-ml/jax
jax/_src/monitoring.py
https://github.com/jax-ml/jax/blob/master/jax/_src/monitoring.py
Apache-2.0
def dumps(obj: Any) -> bytes: """See `pickle.dumps`. Used for serializing host callbacks in jaxlib.""" if cloudpickle is None: raise ModuleNotFoundError('No module named "cloudpickle"') class Pickler(cloudpickle.CloudPickler): """Customizes the behavior of cloudpickle.""" # Make a copy to avoid modi...
See `pickle.dumps`. Used for serializing host callbacks in jaxlib.
dumps
python
jax-ml/jax
jax/_src/pickle_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pickle_util.py
Apache-2.0
def _parse_jit_arguments(fun: Callable, *, in_shardings: Any, out_shardings: Any, static_argnums: int | Sequence[int] | None, static_argnames: str | Iterable[str] | None, donate_argnums: int | Sequence[int] | None, ...
Parses the arguments to jit/pjit. Performs any preprocessing and validation of the arguments that we can do ahead of time before the jit()-ed function is invoked.
_parse_jit_arguments
python
jax-ml/jax
jax/_src/pjit.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pjit.py
Apache-2.0
def make_jit(fun: Callable, *, in_shardings: Any, out_shardings: Any, static_argnums: int | Sequence[int] | None, static_argnames: str | Iterable[str] | None, donate_argnums: int | Sequence[int] | None, donate_argnames: str | Ite...
jit() and pjit() are thin wrappers around this function.
make_jit
python
jax-ml/jax
jax/_src/pjit.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pjit.py
Apache-2.0
def _extract_implicit_args( in_type: Sequence[tuple[core.AbstractValue, bool]], explicit_args: Sequence[Any] ) -> Sequence[core.Tracer]: """ Given an input type and explicitly-passed arguments (per the user-facing API calling convention), extract implicit axis size arguments from shapes of explicit argument...
Given an input type and explicitly-passed arguments (per the user-facing API calling convention), extract implicit axis size arguments from shapes of explicit arguments (for the trace-time / jaxpr-level calling convention).
_extract_implicit_args
python
jax-ml/jax
jax/_src/pjit.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pjit.py
Apache-2.0
def diff_tracing_cache_keys( k: tuple, oldk: tuple, debug_info: lu.DebugInfo) -> tuple[Sequence[str], int]: """Explanations of differences between the cache keys, along with diff sizes. Result: a pair of a list of explanations for differences, and the total size of the differences. The sizes are used to pi...
Explanations of differences between the cache keys, along with diff sizes. Result: a pair of a list of explanations for differences, and the total size of the differences. The sizes are used to pick the old key with the smallest different size for the explanation that is shown to the user.
diff_tracing_cache_keys
python
jax-ml/jax
jax/_src/pjit.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pjit.py
Apache-2.0
def with_sharding_constraint(x, shardings): """Mechanism to constrain the sharding of an Array inside a jitted computation This is a strict constraint for the GSPMD partitioner and not a hint. For examples of how to use this function, see `Distributed arrays and automatic parallelization`_. Inside of a jitted...
Mechanism to constrain the sharding of an Array inside a jitted computation This is a strict constraint for the GSPMD partitioner and not a hint. For examples of how to use this function, see `Distributed arrays and automatic parallelization`_. Inside of a jitted computation, with_sharding_constraint makes it p...
with_sharding_constraint
python
jax-ml/jax
jax/_src/pjit.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pjit.py
Apache-2.0
def format( self, width: int = 80, *, use_color: bool | None = None, annotation_prefix: str = " # ", source_map: list[list[tuple[int, int, Any]]] | None = None ) -> str: """ Formats a pretty-printer document as a string. Args: source_map: for each line in the output, conta...
Formats a pretty-printer document as a string. Args: source_map: for each line in the output, contains a list of (start column, end column, source) tuples. Each tuple associates a region of output text with a source.
format
python
jax-ml/jax
jax/_src/pretty_printer.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pretty_printer.py
Apache-2.0
def color(doc: Doc, *, foreground: Color | None = None, background: Color | None = None, intensity: Intensity | None = None): """ANSI colors. Overrides the foreground/background/intensity of the text for the child doc. Requires use_colors=True to be set when printing and the `colora...
ANSI colors. Overrides the foreground/background/intensity of the text for the child doc. Requires use_colors=True to be set when printing and the `colorama` package to be installed; otherwise does nothing.
color
python
jax-ml/jax
jax/_src/pretty_printer.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pretty_printer.py
Apache-2.0
def _format( self, width: int = 80, *, use_color: bool | None = None, annotation_prefix: str = " # ", source_map: list[list[tuple[int, int, Any]]] | None = None ) -> str: """ Formats a pretty-printer document as a string. Args: source_map: for each line in the output, contains a list of ...
Formats a pretty-printer document as a string. Args: source_map: for each line in the output, contains a list of (start column, end column, source) tuples. Each tuple associates a region of output text with a source.
_format
python
jax-ml/jax
jax/_src/pretty_printer.py
https://github.com/jax-ml/jax/blob/master/jax/_src/pretty_printer.py
Apache-2.0
def _threefry2x32_lowering(key1, key2, x1, x2, use_rolled_loops=True): """Apply the Threefry 2x32 hash. Args: keypair: a pair of 32bit unsigned integers used for the key. count: an array of dtype uint32 used for the counts. Returns: An array of dtype uint32 with the same shape as `count`. """ x ...
Apply the Threefry 2x32 hash. Args: keypair: a pair of 32bit unsigned integers used for the key. count: an array of dtype uint32 used for the counts. Returns: An array of dtype uint32 with the same shape as `count`.
_threefry2x32_lowering
python
jax-ml/jax
jax/_src/prng.py
https://github.com/jax-ml/jax/blob/master/jax/_src/prng.py
Apache-2.0
def iota_2x32_shape(shape): """Reshaped ``uint64`` iota, as two parallel ``uint32`` arrays. Setting aside representation, this function essentially computes the equivalent of:: jax.lax.iota(dtype=np.uint64, size=math.prod(shape)).reshape(shape) However: * It returns two parallel ``uint32`` arrays inst...
Reshaped ``uint64`` iota, as two parallel ``uint32`` arrays. Setting aside representation, this function essentially computes the equivalent of:: jax.lax.iota(dtype=np.uint64, size=math.prod(shape)).reshape(shape) However: * It returns two parallel ``uint32`` arrays instead of one ``uint64`` array. ...
iota_2x32_shape
python
jax-ml/jax
jax/_src/prng.py
https://github.com/jax-ml/jax/blob/master/jax/_src/prng.py
Apache-2.0
def threefry_random_bits(key: typing.Array, bit_width, shape): """Sample uniform random bits of given width and shape using PRNG key.""" if not _is_threefry_prng_key(key): raise TypeError("threefry_random_bits got invalid prng key.") if bit_width not in (8, 16, 32, 64): raise TypeError("requires 8-, 16-, ...
Sample uniform random bits of given width and shape using PRNG key.
threefry_random_bits
python
jax-ml/jax
jax/_src/prng.py
https://github.com/jax-ml/jax/blob/master/jax/_src/prng.py
Apache-2.0
def start_server(port: int) -> _profiler.ProfilerServer: """Starts the profiler server on port `port`. Using the "TensorFlow profiler" feature in `TensorBoard <https://www.tensorflow.org/tensorboard>`_ 2.2 or newer, you can connect to the profiler server and sample execution traces that show CPU, GPU, and/or...
Starts the profiler server on port `port`. Using the "TensorFlow profiler" feature in `TensorBoard <https://www.tensorflow.org/tensorboard>`_ 2.2 or newer, you can connect to the profiler server and sample execution traces that show CPU, GPU, and/or TPU device activity.
start_server
python
jax-ml/jax
jax/_src/profiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/profiler.py
Apache-2.0
def start_trace( log_dir: os.PathLike | str, create_perfetto_link: bool = False, create_perfetto_trace: bool = False, profiler_options: ProfileOptions | None = None, ) -> None: """Starts a profiler trace. The trace will capture CPU, GPU, and/or TPU activity, including Python functions and JAX on-...
Starts a profiler trace. The trace will capture CPU, GPU, and/or TPU activity, including Python functions and JAX on-device operations. Use :func:`stop_trace` to end the trace and save the results to ``log_dir``. The resulting trace can be viewed with TensorBoard. Note that TensorBoard doesn't need to be ...
start_trace
python
jax-ml/jax
jax/_src/profiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/profiler.py
Apache-2.0
def stop_trace(): """Stops the currently-running profiler trace. The trace will be saved to the ``log_dir`` passed to the corresponding :func:`start_trace` call. Raises a RuntimeError if a trace hasn't been started. """ with _profile_state.lock: if _profile_state.profile_session is None: raise Runt...
Stops the currently-running profiler trace. The trace will be saved to the ``log_dir`` passed to the corresponding :func:`start_trace` call. Raises a RuntimeError if a trace hasn't been started.
stop_trace
python
jax-ml/jax
jax/_src/profiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/profiler.py
Apache-2.0
def stop_and_get_fdo_profile() -> bytes | str: """Stops the currently-running profiler trace and export fdo_profile. Currently, this is only supported for GPU. Raises a RuntimeError if a trace hasn't been started. """ with _profile_state.lock: if _profile_state.profile_session is None: raise Runtim...
Stops the currently-running profiler trace and export fdo_profile. Currently, this is only supported for GPU. Raises a RuntimeError if a trace hasn't been started.
stop_and_get_fdo_profile
python
jax-ml/jax
jax/_src/profiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/profiler.py
Apache-2.0
def trace( log_dir: os.PathLike | str, create_perfetto_link=False, create_perfetto_trace=False, profiler_options: ProfileOptions | None = None, ): """Context manager to take a profiler trace. The trace will capture CPU, GPU, and/or TPU activity, including Python functions and JAX on-device operat...
Context manager to take a profiler trace. The trace will capture CPU, GPU, and/or TPU activity, including Python functions and JAX on-device operations. The resulting trace can be viewed with TensorBoard. Note that TensorBoard doesn't need to be running when collecting the trace. Only one trace may be coll...
trace
python
jax-ml/jax
jax/_src/profiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/profiler.py
Apache-2.0
def annotate_function(func: Callable, name: str | None = None, **decorator_kwargs): """Decorator that generates a trace event for the execution of a function. For example: >>> @jax.profiler.annotate_function ... def f(x): ... return jnp.dot(x, x.T).block_until_ready() >>> >>> res...
Decorator that generates a trace event for the execution of a function. For example: >>> @jax.profiler.annotate_function ... def f(x): ... return jnp.dot(x, x.T).block_until_ready() >>> >>> result = f(jnp.ones((1000, 1000))) This will cause an "f" event to show up on the trace timeline if the funct...
annotate_function
python
jax-ml/jax
jax/_src/profiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/profiler.py
Apache-2.0
def save_device_memory_profile(filename, backend: str | None = None) -> None: """Collects a device memory profile and writes it to a file. :func:`save_device_memory_profile` is a convenience wrapper around :func:`device_memory_profile` that saves its output to a ``filename``. See the :func:`device_memory_profi...
Collects a device memory profile and writes it to a file. :func:`save_device_memory_profile` is a convenience wrapper around :func:`device_memory_profile` that saves its output to a ``filename``. See the :func:`device_memory_profile` documentation for more information. Args: filename: the filename to whic...
save_device_memory_profile
python
jax-ml/jax
jax/_src/profiler.py
https://github.com/jax-ml/jax/blob/master/jax/_src/profiler.py
Apache-2.0
def _safe_subtract(x, y, *, dtype): """Subtraction that with `inf - inf == 0` semantics.""" with np.errstate(invalid='ignore'): return np.where(np.equal(x, y), np.array(0, dtype), np.subtract(x, y, dtype=dtype))
Subtraction that with `inf - inf == 0` semantics.
_safe_subtract
python
jax-ml/jax
jax/_src/public_test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/public_test_util.py
Apache-2.0
def check_jvp(f, f_jvp, args, atol=None, rtol=None, eps=EPS, err_msg=''): """Check a JVP from automatic differentiation against finite differences. Gradients are only checked in a single randomly chosen direction, which ensures that the finite difference calculation does not become prohibitively expensive even...
Check a JVP from automatic differentiation against finite differences. Gradients are only checked in a single randomly chosen direction, which ensures that the finite difference calculation does not become prohibitively expensive even for large input/output spaces. Args: f: function to check at ``f(*args)...
check_jvp
python
jax-ml/jax
jax/_src/public_test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/public_test_util.py
Apache-2.0
def check_vjp(f, f_vjp, args, atol=None, rtol=None, eps=EPS, err_msg=''): """Check a VJP from automatic differentiation against finite differences. Gradients are only checked in a single randomly chosen direction, which ensures that the finite difference calculation does not become prohibitively expensive even...
Check a VJP from automatic differentiation against finite differences. Gradients are only checked in a single randomly chosen direction, which ensures that the finite difference calculation does not become prohibitively expensive even for large input/output spaces. Args: f: function to check at ``f(*args)...
check_vjp
python
jax-ml/jax
jax/_src/public_test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/public_test_util.py
Apache-2.0
def check_grads(f, args, order, modes=("fwd", "rev"), atol=None, rtol=None, eps=None): """Check gradients from automatic differentiation against finite differences. Gradients are only checked in a single randomly chosen direction, which ensures that the finite difference calculation does not beco...
Check gradients from automatic differentiation against finite differences. Gradients are only checked in a single randomly chosen direction, which ensures that the finite difference calculation does not become prohibitively expensive even for large input/output spaces. Args: f: function to check at ``f(*a...
check_grads
python
jax-ml/jax
jax/_src/public_test_util.py
https://github.com/jax-ml/jax/blob/master/jax/_src/public_test_util.py
Apache-2.0
def default_prng_impl(): """Get the default PRNG implementation. The default implementation is determined by ``config.jax_default_prng_impl``, which specifies it by name. """ impl_name = config.default_prng_impl.value assert impl_name in prng.prngs, impl_name return prng.prngs[impl_name]
Get the default PRNG implementation. The default implementation is determined by ``config.jax_default_prng_impl``, which specifies it by name.
default_prng_impl
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def key(seed: int | ArrayLike, *, impl: PRNGSpecDesc | None = None) -> Array: """Create a pseudo-random number generator (PRNG) key given an integer seed. The result is a scalar array containing a key, whose dtype indicates the default PRNG implementation, as determined by the optional ``impl`` argumen...
Create a pseudo-random number generator (PRNG) key given an integer seed. The result is a scalar array containing a key, whose dtype indicates the default PRNG implementation, as determined by the optional ``impl`` argument or, otherwise, by the ``jax_default_prng_impl`` config flag at the time when this funct...
key
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def PRNGKey(seed: int | ArrayLike, *, impl: PRNGSpecDesc | None = None) -> Array: """Create a legacy PRNG key given an integer seed. This function produces old-style legacy PRNG keys, which are arrays of dtype ``uint32``. For more, see the note in the `PRNG keys <https://docs.jax.dev/en/latest/jax....
Create a legacy PRNG key given an integer seed. This function produces old-style legacy PRNG keys, which are arrays of dtype ``uint32``. For more, see the note in the `PRNG keys <https://docs.jax.dev/en/latest/jax.random.html#prng-keys>`_ section. When possible, :func:`jax.random.key` is recommended for use ...
PRNGKey
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def fold_in(key: ArrayLike, data: IntegerArray) -> Array: """Folds in data to a PRNG key to form a new PRNG key. Args: key: a PRNG key (from ``key``, ``split``, ``fold_in``). data: a 32-bit integer representing data to be folded into the key. Returns: A new PRNG key that is a deterministic function ...
Folds in data to a PRNG key to form a new PRNG key. Args: key: a PRNG key (from ``key``, ``split``, ``fold_in``). data: a 32-bit integer representing data to be folded into the key. Returns: A new PRNG key that is a deterministic function of the inputs and is statistically safe for producing a str...
fold_in
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def split(key: ArrayLike, num: int | tuple[int, ...] = 2) -> Array: """Splits a PRNG key into `num` new keys by adding a leading axis. Args: key: a PRNG key (from ``key``, ``split``, ``fold_in``). num: optional, a positive integer (or tuple of integers) indicating the number (or shape) of keys to pro...
Splits a PRNG key into `num` new keys by adding a leading axis. Args: key: a PRNG key (from ``key``, ``split``, ``fold_in``). num: optional, a positive integer (or tuple of integers) indicating the number (or shape) of keys to produce. Defaults to 2. Returns: An array-like object of `num` new PR...
split
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def wrap_key_data(key_bits_array: Array, *, impl: PRNGSpecDesc | None = None): """Wrap an array of key data bits into a PRNG key array. Args: key_bits_array: a ``uint32`` array with trailing shape corresponding to the key shape of the PRNG implementation specified by ``impl``. impl:...
Wrap an array of key data bits into a PRNG key array. Args: key_bits_array: a ``uint32`` array with trailing shape corresponding to the key shape of the PRNG implementation specified by ``impl``. impl: optional, specifies a PRNG implementation, as in ``random.key``. Returns: A PRNG key array, wh...
wrap_key_data
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def bits(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeUInt | None = None, *, out_sharding=None) -> Array: """Sample uniform bits in the form of unsigned integers. Args: key: a PRNG key used as the random key. shape: optional, a tuple of nonnegative integers represe...
Sample uniform bits in the form of unsigned integers. Args: key: a PRNG key used as the random key. shape: optional, a tuple of nonnegative integers representing the result shape. Default ``()``. dtype: optional, an unsigned integer dtype for the returned values (default ``uint64`` if ``jax_e...
bits
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def uniform(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeFloat = float, minval: RealArray = 0., maxval: RealArray = 1., *, out_sharding=None) -> Array: """Sample uniform random values in [minval, maxval) with given shape/dtype. Args: ...
Sample uniform random values in [minval, maxval) with given shape/dtype. Args: key: a PRNG key used as the random key. shape: optional, a tuple of nonnegative integers representing the result shape. Default (). dtype: optional, a float dtype for the returned values (default float64 if jax_ena...
uniform
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def randint(key: ArrayLike, shape: Shape, minval: IntegerArray, maxval: IntegerArray, dtype: DTypeLikeInt = int, *, out_sharding=None) -> Array: """Sample uniform random values in [minval, maxval) with given shape/dtype. Args: key: a PRNG ...
Sample uniform random values in [minval, maxval) with given shape/dtype. Args: key: a PRNG key used as the random key. shape: a tuple of nonnegative integers representing the shape. minval: int or array of ints broadcast-compatible with ``shape``, a minimum (inclusive) value for the range. maxv...
randint
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def permutation(key: ArrayLike, x: int | ArrayLike, axis: int = 0, independent: bool = False, *, out_sharding=None) -> Array: """Returns a randomly permuted array or range. Args: key: a PRNG key used as the random key. x: int o...
Returns a randomly permuted array or range. Args: key: a PRNG key used as the random key. x: int or array. If x is an integer, randomly shuffle np.arange(x). If x is an array, randomly shuffle its elements. axis: int, optional. The axis which x is shuffled along. Default is 0. independent: bool...
permutation
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def normal(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeFloat = float, *, out_sharding=None) -> Array: r"""Sample standard normal random values with given shape and float dtype. The values are returned according to the probability density function: .. math:: ...
Sample standard normal random values with given shape and float dtype. The values are returned according to the probability density function: .. math:: f(x) = \frac{1}{\sqrt{2\pi}}e^{-x^2/2} on the domain :math:`-\infty < x < \infty` Args: key: a PRNG key used as the random key. shape: optional...
normal
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def multivariate_normal(key: ArrayLike, mean: RealArray, cov: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat | None = None, method: str = 'cholesky') -> Array: r"""Sample multivariate ...
Sample multivariate normal random values with given mean and covariance. The values are returned according to the probability density function: .. math:: f(x;\mu, \Sigma) = (2\pi)^{-k/2} \det(\Sigma)^{-1}e^{-\frac{1}{2}(x - \mu)^T \Sigma^{-1} (x - \mu)} where :math:`k` is the dimension, :math:`\mu` is the...
multivariate_normal
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def truncated_normal(key: ArrayLike, lower: RealArray, upper: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float, *, out_sharding=None) -> Array: r"""Sample truncated standard normal random value...
Sample truncated standard normal random values with given shape and dtype. The values are returned according to the probability density function: .. math:: f(x) \propto e^{-x^2/2} on the domain :math:`\rm{lower} < x < \rm{upper}`. Args: key: a PRNG key used as the random key. lower: a float or ...
truncated_normal
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def bernoulli(key: ArrayLike, p: RealArray = np.float32(0.5), shape: Shape | None = None, mode: str = 'low') -> Array: r"""Sample Bernoulli random values with given shape and mean. The values are distributed according to the probability mass function: .. math:: f(k...
Sample Bernoulli random values with given shape and mean. The values are distributed according to the probability mass function: .. math:: f(k; p) = p^k(1 - p)^{1 - k} where :math:`k \in \{0, 1\}` and :math:`0 \le p \le 1`. Args: key: a PRNG key used as the random key. p: optional, a float or a...
bernoulli
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def beta(key: ArrayLike, a: RealArray, b: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: r"""Sample Beta random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f...
Sample Beta random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x;a,b) \propto x^{a - 1}(1 - x)^{b - 1} on the domain :math:`0 \le x \le 1`. Args: key: a PRNG key used as the random key. a: a float or array of flo...
beta
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def cauchy(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeFloat = float) -> Array: r"""Sample Cauchy random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) \propto \frac{1}{x^2 + 1} on the domain ...
Sample Cauchy random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) \propto \frac{1}{x^2 + 1} on the domain :math:`-\infty < x < \infty` Args: key: a PRNG key used as the random key. shape: optional, a tuple of n...
cauchy
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def dirichlet(key: ArrayLike, alpha: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: r"""Sample Dirichlet random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: ...
Sample Dirichlet random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(\{x_i\}; \{\alpha_i\}) \propto \prod_{i=1}^k x_i^{\alpha_i - 1} Where :math:`k` is the dimension, and :math:`\{x_i\}` satisfies .. math:: \sum_{i=1...
dirichlet
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def exponential(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeFloat = float) -> Array: r"""Sample Exponential random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) = e^{-x} on the doma...
Sample Exponential random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) = e^{-x} on the domain :math:`0 \le x < \infty`. Args: key: a PRNG key used as the random key. shape: optional, a tuple of nonnegative inte...
exponential
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def gamma(key: ArrayLike, a: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: r"""Sample Gamma random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x;a) \propto x^{a...
Sample Gamma random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x;a) \propto x^{a - 1} e^{-x} on the domain :math:`0 \le x < \infty`, with :math:`a > 0`. This is the standard gamma density, with a unit scale/rate paramet...
gamma
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def loggamma(key: ArrayLike, a: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: """Sample log-gamma random values with given shape and float dtype. This function is implemented such that the following will hold for a dtype-appropriate toleran...
Sample log-gamma random values with given shape and float dtype. This function is implemented such that the following will hold for a dtype-appropriate tolerance:: np.testing.assert_allclose(jnp.exp(loggamma(*args)), gamma(*args), rtol=rtol) The benefit of log-gamma is that for samples very close to zero (...
loggamma
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def poisson(key: ArrayLike, lam: RealArray, shape: Shape | None = None, dtype: DTypeLikeInt = int) -> Array: r"""Sample Poisson random values with given shape and integer dtype. The values are distributed according to the probability mass function: .. math:: f(k; \lambda...
Sample Poisson random values with given shape and integer dtype. The values are distributed according to the probability mass function: .. math:: f(k; \lambda) = \frac{\lambda^k e^{-\lambda}}{k!} Where `k` is a non-negative integer and :math:`\lambda > 0`. Args: key: a PRNG key used as the random k...
poisson
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def gumbel(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeFloat = float, mode: str | None = None) -> Array: """Sample Gumbel random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) = e^{-(x...
Sample Gumbel random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) = e^{-(x + e^{-x})} Args: key: a PRNG key used as the random key. shape: optional, a tuple of nonnegative integers representing the result sh...
gumbel
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def laplace(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeFloat = float) -> Array: r"""Sample Laplace random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) = \frac{1}{2}e^{-|x|} Args: key: ...
Sample Laplace random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) = \frac{1}{2}e^{-|x|} Args: key: a PRNG key used as the random key. shape: optional, a tuple of nonnegative integers representing the result ...
laplace
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def logistic(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeFloat = float) -> Array: r"""Sample logistic random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) = \frac{e^{-x}}{(1 + e^{-x})^2} ...
Sample logistic random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) = \frac{e^{-x}}{(1 + e^{-x})^2} Args: key: a PRNG key used as the random key. shape: optional, a tuple of nonnegative integers representing the r...
logistic
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def pareto(key: ArrayLike, b: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: r"""Sample Pareto random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x; b) = b / ...
Sample Pareto random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x; b) = b / x^{b + 1} on the domain :math:`1 \le x < \infty` with :math:`b > 0` Args: key: a PRNG key used as the random key. b: a float or array o...
pareto
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def t(key: ArrayLike, df: RealArray, shape: Shape = (), dtype: DTypeLikeFloat = float) -> Array: r"""Sample Student's t random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(t; \nu) \propto \left(1 + \frac{t^2...
Sample Student's t random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(t; \nu) \propto \left(1 + \frac{t^2}{\nu}\right)^{-(\nu + 1)/2} Where :math:`\nu > 0` is the degrees of freedom, given by the parameter ``df``. Args: ...
t
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def chisquare(key: ArrayLike, df: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: r"""Sample Chisquare random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: ...
Sample Chisquare random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x; \nu) \propto x^{\nu/2 - 1}e^{-x/2} on the domain :math:`0 < x < \infty`, where :math:`\nu > 0` represents the degrees of freedom, given by the paramet...
chisquare
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def f(key: ArrayLike, dfnum: RealArray, dfden: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: r"""Sample F-distribution random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: ...
Sample F-distribution random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x; \nu_1, \nu_2) \propto x^{\nu_1/2 - 1}\left(1 + \frac{\nu_1}{\nu_2}x\right)^{ -(\nu_1 + \nu_2) / 2} on the domain :math:`0 < x < \infty`. Here...
f
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def rademacher(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeInt = int) -> Array: r"""Sample from a Rademacher distribution. The values are distributed according to the probability mass function: .. math:: f(k) = \frac{1}{2}(\delta(k - 1) + \delta(k + 1)) on the domain...
Sample from a Rademacher distribution. The values are distributed according to the probability mass function: .. math:: f(k) = \frac{1}{2}(\delta(k - 1) + \delta(k + 1)) on the domain :math:`k \in \{-1, 1\}`, where :math:`\delta(x)` is the dirac delta function. Args: key: a PRNG key. shape: The...
rademacher
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def maxwell(key: ArrayLike, shape: Shape = (), dtype: DTypeLikeFloat = float) -> Array: r"""Sample from a one sided Maxwell distribution. The values are distributed according to the probability density function: .. math:: f(x) \propto x^2 e^{-x^2 / 2} on the domain :math:`0 \le x...
Sample from a one sided Maxwell distribution. The values are distributed according to the probability density function: .. math:: f(x) \propto x^2 e^{-x^2 / 2} on the domain :math:`0 \le x < \infty`. Args: key: a PRNG key. shape: The shape of the returned samples. dtype: The type used for s...
maxwell
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def double_sided_maxwell(key: ArrayLike, loc: RealArray, scale: RealArray, shape: Shape = (), dtype: DTypeLikeFloat = float) -> Array: r"""Sample from a double sided Maxwell distribution. The values are distributed ...
Sample from a double sided Maxwell distribution. The values are distributed according to the probability density function: .. math:: f(x;\mu,\sigma) \propto z^2 e^{-z^2 / 2} where :math:`z = (x - \mu) / \sigma`, with the center :math:`\mu` specified by ``loc`` and the scale :math:`\sigma` specified by `...
double_sided_maxwell
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def weibull_min(key: ArrayLike, scale: RealArray, concentration: RealArray, shape: Shape = (), dtype: DTypeLikeFloat = float) -> Array: r"""Sample from a Weibull distribution. The values are distributed according to the probability density function: ...
Sample from a Weibull distribution. The values are distributed according to the probability density function: .. math:: f(x;\sigma,c) \propto x^{c - 1} \exp(-(x / \sigma)^c) on the domain :math:`0 < x < \infty`, where :math:`c > 0` is the concentration parameter, and :math:`\sigma > 0` is the scale para...
weibull_min
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def orthogonal( key: ArrayLike, n: int, shape: Shape = (), dtype: DTypeLikeFloat = float, m: int | None = None, ) -> Array: r"""Sample uniformly from the orthogonal group O(n). If the dtype is complex, sample uniformly from the unitary group U(n). For unequal rows and columns, this samples a semi-orth...
Sample uniformly from the orthogonal group O(n). If the dtype is complex, sample uniformly from the unitary group U(n). For unequal rows and columns, this samples a semi-orthogonal matrix instead. That is, if :math:`A` is the resulting matrix and :math:`A^*` is its conjugate transpose, then: - If :math:`n ...
orthogonal
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def generalized_normal( key: ArrayLike, p: float, shape: Shape = (), dtype: DTypeLikeFloat = float ) -> Array: r"""Sample from the generalized normal distribution. The values are returned according to the probability density function: .. math:: f(x;p) \propto e^{-|x|^p} on the domain :math:`-\in...
Sample from the generalized normal distribution. The values are returned according to the probability density function: .. math:: f(x;p) \propto e^{-|x|^p} on the domain :math:`-\infty < x < \infty`, where :math:`p > 0` is the shape parameter. Args: key: a PRNG key used as the random key. p: ...
generalized_normal
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def ball( key: ArrayLike, d: int, p: float = 2, shape: Shape = (), dtype: DTypeLikeFloat = float ): """Sample uniformly from the unit Lp ball. Reference: https://arxiv.org/abs/math/0503650. Args: key: a PRNG key used as the random key. d: a nonnegative int representing the dimensionality of th...
Sample uniformly from the unit Lp ball. Reference: https://arxiv.org/abs/math/0503650. Args: key: a PRNG key used as the random key. d: a nonnegative int representing the dimensionality of the ball. p: a float representing the p parameter of the Lp norm. shape: optional, the batch dimensions of th...
ball
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def rayleigh(key: ArrayLike, scale: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: r"""Sample Rayleigh random values with given shape and float dtype. The values are returned according to the probability density function: .. math:: f(x...
Sample Rayleigh random values with given shape and float dtype. The values are returned according to the probability density function: .. math:: f(x;\sigma) \propto xe^{-x^2/(2\sigma^2)} on the domain :math:`-\infty < x < \infty`, and where :math:`\sigma > 0` is the scale parameter of the distribution. ...
rayleigh
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def wald(key: ArrayLike, mean: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: r"""Sample Wald random values with given shape and float dtype. The values are returned according to the probability density function: .. math:: f(x;\mu) = \frac{1}{\sqr...
Sample Wald random values with given shape and float dtype. The values are returned according to the probability density function: .. math:: f(x;\mu) = \frac{1}{\sqrt{2\pi x^3}} \exp\left(-\frac{(x - \mu)^2}{2\mu^2 x}\right) on the domain :math:`-\infty < x < \infty`, and where :math:`\mu > 0` is the loca...
wald
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def geometric(key: ArrayLike, p: RealArray, shape: Shape | None = None, dtype: DTypeLikeInt = int) -> Array: r"""Sample Geometric random values with given shape and float dtype. The values are returned according to the probability mass function: .. math:: f(k;p) =...
Sample Geometric random values with given shape and float dtype. The values are returned according to the probability mass function: .. math:: f(k;p) = p(1-p)^{k-1} on the domain :math:`0 < p < 1`. Args: key: a PRNG key used as the random key. p: a float or array of floats broadcast-compatible...
geometric
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def lognormal(key: ArrayLike, sigma: RealArray = np.float32(1), shape: Shape | None = None, dtype: DTypeLikeFloat = float) -> Array: r""" Sample lognormal random values with given shape and float dtype. The values are distributed according to the probability density functi...
Sample lognormal random values with given shape and float dtype. The values are distributed according to the probability density function: .. math:: f(x) = \frac{1}{x\sqrt{2\pi\sigma^2}}\exp\left(-\frac{(\log x)^2}{2\sigma^2}\right) on the domain :math:`x > 0`. Args: key: a PRNG key used as the r...
lognormal
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def binomial( key: Array, n: RealArray, p: RealArray, shape: Shape | None = None, dtype: DTypeLikeFloat = float, ) -> Array: r"""Sample Binomial random values with given shape and float dtype. The values are returned according to the probability mass function: .. math:: f(k;n,p) = \bin...
Sample Binomial random values with given shape and float dtype. The values are returned according to the probability mass function: .. math:: f(k;n,p) = \binom{n}{k}p^k(1-p)^{n-k} on the domain :math:`0 < p < 1`, and where :math:`n` is a nonnegative integer representing the number of trials and :math:`...
binomial
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def multinomial( key: Array, n: RealArray, p: RealArray, *, shape: Shape | None = None, dtype: DTypeLikeFloat = float, unroll: int | bool = 1, ): r"""Sample from a multinomial distribution. The probability mass function is .. math:: f(x;n,p) = \frac{n!}{x_1! \ldots x_k!} p_1^{x...
Sample from a multinomial distribution. The probability mass function is .. math:: f(x;n,p) = \frac{n!}{x_1! \ldots x_k!} p_1^{x_1} \ldots p_k^{x_k} Args: key: PRNG key. n: number of trials. Should have shape broadcastable to ``p.shape[:-1]``. p: probability of each outcome, with outcomes alo...
multinomial
python
jax-ml/jax
jax/_src/random.py
https://github.com/jax-ml/jax/blob/master/jax/_src/random.py
Apache-2.0
def addressable_devices(self) -> set[Device]: """The set of devices in the :class:`Sharding` that are addressable by the current process. """ # Add a fast path for single controller runtimes. if xb.process_count() == 1: return self.device_set return {d for d in self.device_set ...
The set of devices in the :class:`Sharding` that are addressable by the current process.
addressable_devices
python
jax-ml/jax
jax/_src/sharding.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding.py
Apache-2.0
def addressable_devices_indices_map( self, global_shape: Shape) -> Mapping[Device, Index | None]: """A mapping from addressable devices to the slice of array data each contains. ``addressable_devices_indices_map`` contains that part of ``device_indices_map`` that applies to the addressable devices. ...
A mapping from addressable devices to the slice of array data each contains. ``addressable_devices_indices_map`` contains that part of ``device_indices_map`` that applies to the addressable devices.
addressable_devices_indices_map
python
jax-ml/jax
jax/_src/sharding.py
https://github.com/jax-ml/jax/blob/master/jax/_src/sharding.py
Apache-2.0