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 scale_and_translate(image, shape: core.Shape,
spatial_dims: Sequence[int],
scale, translation,
method: str | ResizeMethod,
antialias: bool = True,
precision=lax.Precision.HIGHEST):
"""Apply a sc... | Apply a scale and translation to an image.
Generates a new image of shape 'shape' by resampling from the input image
using the sampling method corresponding to method. For 2D images, this
operation transforms a location in the input images, (x, y), to a location
in the output image according to::
(x * sca... | scale_and_translate | python | jax-ml/jax | jax/_src/image/scale.py | https://github.com/jax-ml/jax/blob/master/jax/_src/image/scale.py | Apache-2.0 |
def resize(image, shape: core.Shape, method: str | ResizeMethod,
antialias: bool = True,
precision = lax.Precision.HIGHEST):
"""Image resize.
The ``method`` argument expects one of the following resize methods:
``ResizeMethod.NEAREST``, ``"nearest"``
`Nearest neighbor interpolation`_. ... | Image resize.
The ``method`` argument expects one of the following resize methods:
``ResizeMethod.NEAREST``, ``"nearest"``
`Nearest neighbor interpolation`_. The values of ``antialias`` and
``precision`` are ignored.
``ResizeMethod.LINEAR``, ``"linear"``, ``"bilinear"``, ``"trilinear"``, ``"triangle"``... | resize | python | jax-ml/jax | jax/_src/image/scale.py | https://github.com/jax-ml/jax/blob/master/jax/_src/image/scale.py | Apache-2.0 |
def run_one_test(self,
func: Callable[..., jax.Array] | stages.Wrapped,
data: CompatTestData,
polymorphic_shapes: Sequence[str] | None = None,
rtol: float | None = None,
atol: float | None = None,
allow_uns... | Run one compatibility test.
Args:
func: the JAX function to serialize and run, either as a Python Callable
or as a `jax.jit(callable)`.
data: the test data
polymorphic_shapes: when using shape polymorphism, the specification for
each argument of `func`.
rtol: relative tolera... | run_one_test | python | jax-ml/jax | jax/_src/internal_test_util/export_back_compat_test_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/internal_test_util/export_back_compat_test_util.py | Apache-2.0 |
def run_current(self,
func: Callable | stages.Wrapped,
data: CompatTestData):
"""Lowers and runs the test function at the current JAX version."""
jit_func = func if isinstance(func, stages.Wrapped) else jax.jit(func)
return jit_func(*data.inputs) | Lowers and runs the test function at the current JAX version. | run_current | python | jax-ml/jax | jax/_src/internal_test_util/export_back_compat_test_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/internal_test_util/export_back_compat_test_util.py | Apache-2.0 |
def serialize(self,
func: Callable | stages.Wrapped, data: CompatTestData, *,
polymorphic_shapes: Sequence[str] | None = None,
allow_unstable_custom_call_targets: Sequence[str] = ()
) -> tuple[bytes, str, int, int]:
"""Serializes the test function.
... | Serializes the test function.
Args:
func: the function to serialize.
polymorphic_shapes: the polymorphic_shapes to use for serialization
allow_unstable_custom_call_targets: whether to allow additional
custom call targets besides those known as stable.
Returns: a tuple with the (a) se... | serialize | python | jax-ml/jax | jax/_src/internal_test_util/export_back_compat_test_util.py | https://github.com/jax-ml/jax/blob/master/jax/_src/internal_test_util/export_back_compat_test_util.py | Apache-2.0 |
def dyn_args_maker(self, rng: Rng) -> Sequence:
"""A dynamic-argument maker, for use with `dyn_fun`."""
return [
self._arg_maker(ad, rng)
for ad in self.arg_descriptors
if not isinstance(ad, StaticArg)
] | A dynamic-argument maker, for use with `dyn_fun`. | dyn_args_maker | python | jax-ml/jax | jax/_src/internal_test_util/test_harnesses.py | https://github.com/jax-ml/jax/blob/master/jax/_src/internal_test_util/test_harnesses.py | Apache-2.0 |
def _args_from_dynargs(self, dyn_args: Sequence) -> Sequence:
"""All arguments, including the static ones."""
next_dynamic_argnum = 0
all_args = []
for ad in self.arg_descriptors:
if isinstance(ad, StaticArg):
all_args.append(ad.value)
else:
all_args.append(dyn_args[next_dyna... | All arguments, including the static ones. | _args_from_dynargs | python | jax-ml/jax | jax/_src/internal_test_util/test_harnesses.py | https://github.com/jax-ml/jax/blob/master/jax/_src/internal_test_util/test_harnesses.py | Apache-2.0 |
def dtypes_to_str(dtype_list: Sequence[DType], empty_means_all=False) -> str:
"""User-friendly description of a set of dtypes"""
if not dtype_list and empty_means_all:
return "all"
names = {np.dtype(dt).name for dt in dtype_list}
signed = {"int8", "int16", "int32", "int64"}
if signed <= names:
names ... | User-friendly description of a set of dtypes | dtypes_to_str | python | jax-ml/jax | jax/_src/internal_test_util/test_harnesses.py | https://github.com/jax-ml/jax/blob/master/jax/_src/internal_test_util/test_harnesses.py | Apache-2.0 |
def define(
group_name,
name,
fun,
arg_descriptors,
*,
dtype,
rng_factory=jtu.rand_default,
jax_unimplemented: Sequence[Limitation] = (),
**params):
"""Defines a harness and stores it in `all_harnesses`. See Harness."""
group_name = str(group_name)
h = Harness(
group_name... | Defines a harness and stores it in `all_harnesses`. See Harness. | define | python | jax-ml/jax | jax/_src/internal_test_util/test_harnesses.py | https://github.com/jax-ml/jax/blob/master/jax/_src/internal_test_util/test_harnesses.py | Apache-2.0 |
def parameterized(harnesses: Iterable[Harness],
*,
one_containing: str | None = None,
include_jax_unimpl: bool = False):
"""Decorator for tests.
The tests receive a `harness` argument.
The `JAX_TEST_HARNESS_ONE_CONTAINING` environment variable is useful for
... | Decorator for tests.
The tests receive a `harness` argument.
The `JAX_TEST_HARNESS_ONE_CONTAINING` environment variable is useful for
debugging. If given, then picks only one harness whose name contains the
string. The whole set of parameterized tests is reduced to one test,
whose name is not decorated to m... | parameterized | python | jax-ml/jax | jax/_src/internal_test_util/test_harnesses.py | https://github.com/jax-ml/jax/blob/master/jax/_src/internal_test_util/test_harnesses.py | Apache-2.0 |
def _is_ir_values(x: IrValues) -> bool:
"""Returns true if `x` is an ir.Value or tuple of ir.Values"""
if isinstance(x, ir.Value):
return True
return (isinstance(x, tuple) and len(x) != 1
and all(isinstance(v, ir.Value) for v in x)) | Returns true if `x` is an ir.Value or tuple of ir.Values | _is_ir_values | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def aval_to_ir_type(aval: core.AbstractValue) -> IrTypes:
"""Converts a JAX aval to zero or more MLIR IR types.
In general, a JAX value may be represented by multiple IR values, so this
function may return a tuple of types."""
try:
return ir_type_handlers[type(aval)](aval)
except KeyError as err:
rai... | Converts a JAX aval to zero or more MLIR IR types.
In general, a JAX value may be represented by multiple IR values, so this
function may return a tuple of types. | aval_to_ir_type | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def __call__(self, val: Any) -> IrValues:
"""Builds an IR representation for a constant `val`.
A JAX value is represented by zero or more IR values.""" | Builds an IR representation for a constant `val`.
A JAX value is represented by zero or more IR values. | __call__ | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def ir_constant(val: Any) -> IrValues:
"""Translate a Python `val` to an IR constant, canonicalizing its dtype.
Args:
val: a Python value to be translated to a constant.
Returns:
A representation of the constant as an IR value or sequence of IR values.
"""
for t in type(val).__mro__:
handler = _... | Translate a Python `val` to an IR constant, canonicalizing its dtype.
Args:
val: a Python value to be translated to a constant.
Returns:
A representation of the constant as an IR value or sequence of IR values.
| ir_constant | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def _ndarray_constant_handler(val: np.ndarray | np.generic) -> IrValues:
"""Constant handler for ndarray literals, handling zero-size strides.
In most cases this function calls _numpy_array_constant(val) except it has
special handling of arrays with any strides of size zero: for those, it
generates appropriate... | Constant handler for ndarray literals, handling zero-size strides.
In most cases this function calls _numpy_array_constant(val) except it has
special handling of arrays with any strides of size zero: for those, it
generates appropriate calls to NumpyArrayConstant, Broadcast, and Transpose
to avoid staging in l... | _ndarray_constant_handler | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def ir_attribute(val: Any) -> ir.Attribute:
"""Convert a Python value to an MLIR attribute."""
for t in type(val).__mro__:
handler = _attribute_handlers.get(t)
if handler:
out = handler(val)
assert isinstance(out, ir.Attribute), (type(val), out)
return out
if hasattr(val, '__jax_array__'... | Convert a Python value to an MLIR attribute. | ir_attribute | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def _traceback_to_location(ctx: ModuleContext, tb: xc.Traceback) -> ir.Location:
"""Converts a full traceback to a callsite() MLIR location."""
loc = ctx.traceback_caches.traceback_cache.get(tb, None)
if loc is not None:
return loc
frame_locs = []
frames_limit = config.traceback_in_locations_limit.value
... | Converts a full traceback to a callsite() MLIR location. | _traceback_to_location | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def dump_module_to_file(module: ir.Module, stage_name: str) -> str | None:
"""Dumps the `module` IR to a file.
Dumps the module if JAX_DUMP_IR_TO is defined.
Args:
module: The module to dump
stage_name: A name to distinguish different stages of a module, will be
appended to the `module.name`.
R... | Dumps the `module` IR to a file.
Dumps the module if JAX_DUMP_IR_TO is defined.
Args:
module: The module to dump
stage_name: A name to distinguish different stages of a module, will be
appended to the `module.name`.
Returns:
The name of the file containing the dump if JAX_DUMP_IR_TO is define... | dump_module_to_file | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def make_ir_context() -> ir.Context:
"""Creates an MLIR context suitable for JAX IR."""
context = JaxIrContext()
context.append_dialect_registry(upstream_dialects)
context.load_all_available_dialects()
context.set_thread_pool(global_thread_pool)
dialects.sdy.register_dialect(context)
dialects.mhlo.regist... | Creates an MLIR context suitable for JAX IR. | make_ir_context | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def is_forward_compat(self) -> bool:
"""Returns true if the lowering parameters are in forward compatibility mode.
"""
lowering_parameters = self.module_context.lowering_parameters
check_platforms: Sequence[str] = (
self.platforms or self.module_context.platforms
)
force_forward_compat ... | Returns true if the lowering parameters are in forward compatibility mode.
| is_forward_compat | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def flatten_ir_values(xs: Iterable[IrValues]) -> list[ir.Value]:
"""Concatenates/flattens a list of ir.Values or ir.Value sequences."""
out = []
for x in xs:
if isinstance(x, ir.Value):
out.append(x)
else:
out.extend(x)
return out | Concatenates/flattens a list of ir.Values or ir.Value sequences. | flatten_ir_values | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def flatten_ir_types(xs: Iterable[IrTypes]) -> list[ir.Type]:
"""Concatenates/flattens a list of ir.Types or ir.Type sequences."""
out = []
for x in xs:
if isinstance(x, ir.Type):
out.append(x)
else:
out.extend(x)
return out | Concatenates/flattens a list of ir.Types or ir.Type sequences. | flatten_ir_types | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def unflatten_ir_types(xs: Iterable[ir.Type], ns: Sequence[int]) -> list[IrTypes]:
"""Splits `xs` into subsequences of lengths `ns`.
Unlike `split_list`, the `sum(ns)` must be equal to `len(xs)`, and if n == 1
then types are not wrapped in a singleton list."""
xs_iter = iter(xs)
unflattened: list[IrTypes]
... | Splits `xs` into subsequences of lengths `ns`.
Unlike `split_list`, the `sum(ns)` must be equal to `len(xs)`, and if n == 1
then types are not wrapped in a singleton list. | unflatten_ir_types | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def unflatten_ir_values_like_types(xs: Iterable[ir.Value],
ys: Sequence[IrTypes]) -> list[IrValues]:
"""Splits `xs` into subsequences of lengths `ns`.
Unlike `split_list`, the `sum(ns)` must be equal to `len(xs)`, and if n == 1
then values are not wrapped in a singleton list.""... | Splits `xs` into subsequences of lengths `ns`.
Unlike `split_list`, the `sum(ns)` must be equal to `len(xs)`, and if n == 1
then values are not wrapped in a singleton list. | unflatten_ir_values_like_types | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def sharded_aval(aval: core.AbstractValue,
sharding: JSharding | AUTO | None) -> core.AbstractValue:
"""Returns the new aval sharded based on sharding proto."""
if sharding is None:
return aval
if isinstance(sharding, AUTO):
return aval
if isinstance(aval, core.AbstractToken):
retur... | Returns the new aval sharded based on sharding proto. | sharded_aval | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def eval_dynamic_shape_as_vals(ctx: LoweringRuleContext,
shape: core.Shape) -> tuple[Value, ...]:
"""Evaluates the dynamic shapes as int32 values."""
def convert_dim(d: int | Value):
if type(d) is int:
return ir_constant(np.array(d, dtype=np.int32))
else:
i32_type ... | Evaluates the dynamic shapes as int32 values. | eval_dynamic_shape_as_vals | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def eval_dynamic_shape_as_ivals(
ctx: LoweringRuleContext, shape: core.Shape
) -> tuple[int | Value, ...]:
"""Evaluates the dynamic shapes as int or ir.int32 values."""
def convert_dim(d: int | Value) -> int | ir.Value:
if type(d) is int:
return d
else:
i32_type = aval_to_ir_type(core.Sh... | Evaluates the dynamic shapes as int or ir.int32 values. | eval_dynamic_shape_as_ivals | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def eval_dynamic_shape_as_tensor(ctx: LoweringRuleContext,
shape: core.Shape) -> Value:
"""Evaluates the dynamic shapes as one 1d int32 tensor."""
return shape_tensor(eval_dynamic_shape(ctx, shape)) | Evaluates the dynamic shapes as one 1d int32 tensor. | eval_dynamic_shape_as_tensor | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def check_jaxpr_constants(closed_jaxpr: core.ClosedJaxpr):
"""Check if a JAXPR contains an excessive amount of constants, if so, report where they were captured"""
if (threshold := config.captured_constants_warn_bytes.value) == -1:
return
# need the unaesthetic getter here as some of the consts in the test s... | Check if a JAXPR contains an excessive amount of constants, if so, report where they were captured | check_jaxpr_constants | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def lower_jaxpr_to_module(
module_name: str,
jaxpr: core.ClosedJaxpr,
*,
ordered_effects: list[core.Effect],
# See ModuleContext.get_backend() for backend and platforms usage.
platforms: Sequence[str],
backend: xb.XlaBackend | None,
axis_context: AxisContext,
name_stack: source_info_... | Lowers a top-level jaxpr to an MLIR module.
Handles the quirks of the argument/return value passing conventions of the
runtime.
| lower_jaxpr_to_module | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def create(cls, effects: Sequence[core.Effect]) -> TokenSet:
"""Creates a `TokenSet` corresponding to a list of `core.Effect`s."""
tokens = [create_token() for _ in effects]
return TokenSet(zip(effects, tokens)) | Creates a `TokenSet` corresponding to a list of `core.Effect`s. | create | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def update_tokens(self, tokens: TokenSet) -> TokenSet:
"""Returns a new `TokenSet` with tokens replaced with ones from the input `TokenSet`."""
new_tokens = []
for eff in self.effects():
if eff in tokens._tokens:
new_tokens.append((eff, tokens._tokens[eff]))
else:
new_tokens.appe... | Returns a new `TokenSet` with tokens replaced with ones from the input `TokenSet`. | update_tokens | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def jaxpr_subcomp(ctx: ModuleContext, jaxpr: core.Jaxpr,
name_stack: source_info_util.NameStack,
tokens: TokenSet,
consts: Sequence[IrValues],
*args: IrValues,
dim_var_values: Sequence[ir.Value]
) -> tuple[Sequen... | Lowers a jaxpr into MLIR, inlined into an existing function.
Assumes that an MLIR context, location, and insertion point are set.
dim_var_values: the list of dimension variables values in the current
IR function, in the order of ctx.shape_poly_state.dim_vars.
| jaxpr_subcomp | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def _platforms_for_eqn_ctx(eqn_ctx: core.JaxprEqnContext | None
) -> tuple[str, ...]:
"""Returns platforms to override based on compute type of jaxpr equation."""
if eqn_ctx is None:
return ()
if eqn_ctx.compute_type == 'device_host':
return ('cpu',)
if eqn_ctx.compute_type ==... | Returns platforms to override based on compute type of jaxpr equation. | _platforms_for_eqn_ctx | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def _platforms_for_eqn(ctx: LoweringRuleContext) -> tuple[str, ...]:
"""The lowering platforms for the current eqn"""
return tuple((_platforms_for_eqn_ctx(ctx.jaxpr_eqn_ctx) or
ctx.platforms or ctx.module_context.platforms)) | The lowering platforms for the current eqn | _platforms_for_eqn | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def lower_fun(fun: Callable, multiple_results: bool = True) -> Callable:
"""Converts a traceable JAX function `fun` into a lowering rule.
The returned function does not use `avals_out`, so callers may pass any value
as `avals_out`."""
def f_lowered(ctx: LoweringRuleContext, *args, **params):
f = fun if mul... | Converts a traceable JAX function `fun` into a lowering rule.
The returned function does not use `avals_out`, so callers may pass any value
as `avals_out`. | lower_fun | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def full_like_aval(ctx: LoweringRuleContext, value, aval: core.ShapedArray) -> ir.Value:
"""Returns an IR constant shaped full of `value` shaped like `aval`."""
zero = ir_constant(np.array(value, dtypes.canonicalize_dtype(aval.dtype)))
return broadcast_in_dim(ctx, zero, aval, broadcast_dimensions=()) | Returns an IR constant shaped full of `value` shaped like `aval`. | full_like_aval | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def _minmax_hlo(op, cmp, x, y):
"""Min/max that compares complex values lexicographically as pairs."""
tensor_type = ir.RankedTensorType(x.type)
if ir.ComplexType.isinstance(tensor_type.element_type):
rx = hlo.real(x)
ry = hlo.real(y)
real_eq = compare_hlo(rx, ry, "EQ", "FLOAT")
real_cmp = compare... | Min/max that compares complex values lexicographically as pairs. | _minmax_hlo | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def convert_hlo(ctx: LoweringRuleContext, x, aval_in, aval_out):
"""Variant of convert that has HLO semantics.
In particular, treat casts to boolean as x != 0, rather than truncating
integer values (b/209440332)."""
if (not dtypes.issubdtype(aval_out.dtype, dtypes.extended) and
aval_out.dtype == np.dtype... | Variant of convert that has HLO semantics.
In particular, treat casts to boolean as x != 0, rather than truncating
integer values (b/209440332). | convert_hlo | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def merge_mlir_modules(dst_module: ir.Module,
sym_name: str,
src_module: ir.Module,
dst_symtab: ir.SymbolTable | None = None) -> str:
"""
Args:
dst_module: the module into which the contents of src_module should be
moved. Nothing in dst_... |
Args:
dst_module: the module into which the contents of src_module should be
moved. Nothing in dst_module will be renamed.
sym_name: the desired name for the "main" function of src_module after
merging. This is a hint: the true name may be different because of symbol
uniquification, and the... | merge_mlir_modules | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def build_mlir_module_helper(
closed_jaxpr: core.ClosedJaxpr, *, name: str,
platforms: Sequence[str],
backend: xb.XlaBackend | None,
axis_context: AxisContext) -> ir.Module:
"""Helper to generate pmap-style XLA computations for custom partitioners."""
unlowerable_effects = lowerable_effects.filter_n... | Helper to generate pmap-style XLA computations for custom partitioners. | build_mlir_module_helper | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def custom_call(
call_target_name: str,
*,
result_types: Sequence[ir.Type],
operands: Sequence[ir.Value],
backend_config: str | bytes | dict[str, ir.Attribute] = "",
has_side_effect: bool = False,
result_shapes: Sequence[ir.Value] | None = None,
called_computations: Sequence[str] = (),
... | Helper function for building an hlo.CustomCall.
Args:
call_target_name: the name of the custom call target
result_types: the MLIR types of the results of the custom call
operands: the MLIR IR values that are arguments to the custom call
backend_config: an opaque string passed to the custom call kerne... | custom_call | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def reduce_window(
ctx: LoweringRuleContext,
*,
# Base name to be used for the reducer function
reducer_name: str,
# Compute the reducer body given the reducer.
reducer_body: Callable[[ir.Block], Sequence[ir.Value]],
operands: Sequence[ir.Value],
init_values: Sequence[ir.Value],
init... | Builds a ReduceWindowOp, with support for dynamic shapes. | reduce_window | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def refine_polymorphic_shapes(module: ir.Module) -> ir.Module:
"""Refines the polymorphic shapes inside a module.
Given a module with static input shapes, but using dynamic shapes due to
shape polymorphism, runs shape refinement to resolve all the dynamic shapes.
Then verifies that there are no more dynamic sh... | Refines the polymorphic shapes inside a module.
Given a module with static input shapes, but using dynamic shapes due to
shape polymorphism, runs shape refinement to resolve all the dynamic shapes.
Then verifies that there are no more dynamic shapes in the module.
| refine_polymorphic_shapes | python | jax-ml/jax | jax/_src/interpreters/mlir.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/mlir.py | Apache-2.0 |
def get_aval(self) -> AbstractValue:
"""Get AbstractValue directly (if unknown) or from the constant (known)."""
known = self.get_known()
if known is not None:
return get_aval(known)
else:
return self[0] | Get AbstractValue directly (if unknown) or from the constant (known). | get_aval | python | jax-ml/jax | jax/_src/interpreters/partial_eval.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/partial_eval.py | Apache-2.0 |
def tracers_to_jaxpr(
in_tracers: Sequence[JaxprTracer],
out_tracers: Sequence[JaxprTracer],
effect_handles: Sequence[Any],
debug_info: core.DebugInfo,
) -> tuple[Jaxpr, tuple[Any, ...], tuple[Any, ...]]:
"""Constructs Jaxpr given tracers for inputs and outputs.
Params:
in_tracers: the tracers that w... | Constructs Jaxpr given tracers for inputs and outputs.
Params:
in_tracers: the tracers that were created for the function inputs
out_tracers: the tracers that were output by the function.
debug_info: the debug info for the function.
Returns: a triple of a `Jaxpr`, a list of constant values correspondi... | tracers_to_jaxpr | python | jax-ml/jax | jax/_src/interpreters/partial_eval.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/partial_eval.py | Apache-2.0 |
def convert_constvars_jaxpr(jaxpr: Jaxpr) -> Jaxpr:
"""Moves the constvars to the start of invars."""
config.enable_checks.value and core.check_jaxpr(jaxpr)
dbg = jaxpr.debug_info._replace(
arg_names=("",) * len(jaxpr.constvars) + jaxpr.debug_info.arg_names)
lifted_jaxpr = jaxpr.replace(
constvars=(... | Moves the constvars to the start of invars. | convert_constvars_jaxpr | python | jax-ml/jax | jax/_src/interpreters/partial_eval.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/partial_eval.py | Apache-2.0 |
def convert_invars_to_constvars(jaxpr: Jaxpr, n: int) -> Jaxpr:
"""Move n invars to constvars. Like an inverse of convert_constvars_jaxpr."""
if n == 0:
return jaxpr.replace() # 'return jaxpr' would create cache reference cycle
config.enable_checks.value and core.check_jaxpr(jaxpr)
constvars, invars = spli... | Move n invars to constvars. Like an inverse of convert_constvars_jaxpr. | convert_invars_to_constvars | python | jax-ml/jax | jax/_src/interpreters/partial_eval.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/partial_eval.py | Apache-2.0 |
def dce_jaxpr(jaxpr: Jaxpr, used_outputs: Sequence[bool],
instantiate: bool | Sequence[bool] = False,
) -> tuple[Jaxpr, list[bool]]:
"""Runs dead-code elementation on a given jaxpr.
Args:
jaxpr: The jaxpr to DCE.
used_outputs: A list of bools indicating which outputs are used.
... | Runs dead-code elementation on a given jaxpr.
Args:
jaxpr: The jaxpr to DCE.
used_outputs: A list of bools indicating which outputs are used.
instantiate: A bool or a list of bools indicating which inputs should be
considered used, regardless of whether they are actually used in a jaxpr.
If a... | dce_jaxpr | python | jax-ml/jax | jax/_src/interpreters/partial_eval.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/partial_eval.py | Apache-2.0 |
def move_binders_to_front(closed_jaxpr: ClosedJaxpr, to_move: Sequence[bool]
) -> ClosedJaxpr:
"""Reorder `invars` by moving those indicated in `to_move` to the front."""
return _move_binders_to_front(closed_jaxpr, tuple(to_move)) | Reorder `invars` by moving those indicated in `to_move` to the front. | move_binders_to_front | python | jax-ml/jax | jax/_src/interpreters/partial_eval.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/partial_eval.py | Apache-2.0 |
def move_binders_to_back(closed_jaxpr: ClosedJaxpr, to_move: Sequence[bool]
) -> ClosedJaxpr:
"""Reorder `invars` by moving those indicated in `to_move` to the back."""
return move_binders_to_front(closed_jaxpr, map(op.not_, to_move)) | Reorder `invars` by moving those indicated in `to_move` to the back. | move_binders_to_back | python | jax-ml/jax | jax/_src/interpreters/partial_eval.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/partial_eval.py | Apache-2.0 |
def local_aval_to_result_handler(
aval: core.AbstractValue,
sharding: JSharding,
indices: tuple[Index, ...] | None,
) -> Callable[[list[xc.ArrayImpl]], Any]:
"""Returns a function for handling the raw buffers of a single output aval.
Args:
aval: The local output AbstractValue.
sharding_spec: In... | Returns a function for handling the raw buffers of a single output aval.
Args:
aval: The local output AbstractValue.
sharding_spec: Indicates how the output is sharded across devices, or None
for non-array avals.
indices: The pre-computed result of spec_to_indices, or None for non-array
avals... | local_aval_to_result_handler | python | jax-ml/jax | jax/_src/interpreters/pxla.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/pxla.py | Apache-2.0 |
def global_aval_to_result_handler(
aval: core.AbstractValue, out_sharding, committed: bool
) -> Callable[[Sequence[xc.ArrayImpl]], Any]:
"""Returns a function for handling the raw buffers of a single output aval.
Args:
aval: The global output AbstractValue.
out_axis_resources: A PartitionSpec specifyin... | Returns a function for handling the raw buffers of a single output aval.
Args:
aval: The global output AbstractValue.
out_axis_resources: A PartitionSpec specifying the sharding of outputs.
Used for creating GSDAs.
global_mesh: The global device mesh that generated this output. Used
for creat... | global_aval_to_result_handler | python | jax-ml/jax | jax/_src/interpreters/pxla.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/pxla.py | Apache-2.0 |
def _axis_groups(mesh_spec, mesh_axes):
"""Computes replica group ids for a collective performed over a subset of the mesh.
Args:
mesh_spec: A sequence of integers representing the mesh shape.
mesh_axes: A sequence of integers between 0 and `len(mesh_spec)` (exclusive)
indicating over which axes the ... | Computes replica group ids for a collective performed over a subset of the mesh.
Args:
mesh_spec: A sequence of integers representing the mesh shape.
mesh_axes: A sequence of integers between 0 and `len(mesh_spec)` (exclusive)
indicating over which axes the collective is performed.
Returns:
A tup... | _axis_groups | python | jax-ml/jax | jax/_src/interpreters/pxla.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/pxla.py | Apache-2.0 |
def manual_proto(
aval: core.ShapedArray,
manual_axes_set: frozenset[sharding_impls.MeshAxisName], mesh: Mesh):
"""Create an OpSharding proto that declares all mesh axes from `axes` as manual
and all others as replicated.
"""
named_mesh_shape = mesh.shape
mesh_shape = list(named_mesh_shape.values())
... | Create an OpSharding proto that declares all mesh axes from `axes` as manual
and all others as replicated.
| manual_proto | python | jax-ml/jax | jax/_src/interpreters/pxla.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/pxla.py | Apache-2.0 |
def _get_num_devices(
shardings, device_assignment
) -> tuple[int, tuple[xc.Device, ...] | None]:
"""Number of lowering devices, and the device_assignment to use.
If all the specified shardings have an abstract mesh, then we are compiling
with abstract devices, and the returned device_assignment is None.
... | Number of lowering devices, and the device_assignment to use.
If all the specified shardings have an abstract mesh, then we are compiling
with abstract devices, and the returned device_assignment is None.
| _get_num_devices | python | jax-ml/jax | jax/_src/interpreters/pxla.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/pxla.py | Apache-2.0 |
def lower_sharding_computation(
closed_jaxpr: core.ClosedJaxpr,
api_name: str,
fun_name: str,
in_shardings: Sequence[MaybeSharding],
out_shardings: Sequence[MaybeSharding],
in_layouts: MaybeLayout,
out_layouts: MaybeLayout,
donated_invars: Sequence[bool],
*,
keep_unused: bool,
... | Lowers a computation to XLA. It can take arbitrary shardings as input.
The caller of this code can pass in a singleton UNSPECIFIED because the
number of out_avals might not be known at that time and
lower_sharding_computation calculates the number of out_avals so it can apply
the singleton UNSPECIFIED to all o... | lower_sharding_computation | python | jax-ml/jax | jax/_src/interpreters/pxla.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/pxla.py | Apache-2.0 |
def _maybe_get_and_check_in_shardings(
xla_executable, in_shardings, device_assignment,
global_in_avals, num_ordered_effects):
"""Returns in_shardings extracted from XLA or checks and returns original
shardings.
If in_shardings exist on `jit` or on `jax.Array`, then this function will
check that shardi... | Returns in_shardings extracted from XLA or checks and returns original
shardings.
If in_shardings exist on `jit` or on `jax.Array`, then this function will
check that sharding against what XLA returns as in_shardings. If they don't
match, an error is raised.
If in_sharding is unspecified, then the sharding ... | _maybe_get_and_check_in_shardings | python | jax-ml/jax | jax/_src/interpreters/pxla.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/pxla.py | Apache-2.0 |
def sharding_to_proto(sharding: SpatialSharding):
"""Converts a SpatialSharding to an OpSharding.
See
https://github.com/tensorflow/tensorflow/blob/main/tensorflow/compiler/xla/xla_data.proto#L601
for details on the OpSharding proto.
"""
proto = xc.OpSharding()
if isinstance(sharding, tuple) and not isin... | Converts a SpatialSharding to an OpSharding.
See
https://github.com/tensorflow/tensorflow/blob/main/tensorflow/compiler/xla/xla_data.proto#L601
for details on the OpSharding proto.
| sharding_to_proto | python | jax-ml/jax | jax/_src/interpreters/xla.py | https://github.com/jax-ml/jax/blob/master/jax/_src/interpreters/xla.py | Apache-2.0 |
def approx_max_k(operand: Array,
k: int,
reduction_dimension: int = -1,
recall_target: float = 0.95,
reduction_input_size_override: int = -1,
aggregate_to_topk: bool = True) -> tuple[Array, Array]:
"""Returns max ``k`` values and the... | Returns max ``k`` values and their indices of the ``operand`` in an approximate manner.
See https://arxiv.org/abs/2206.14286 for the algorithm details.
Args:
operand : Array to search for max-k. Must be a floating number type.
k : Specifies the number of max-k.
reduction_dimension : Integer dimension ... | approx_max_k | python | jax-ml/jax | jax/_src/lax/ann.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/ann.py | Apache-2.0 |
def approx_min_k(operand: Array,
k: int,
reduction_dimension: int = -1,
recall_target: float = 0.95,
reduction_input_size_override: int = -1,
aggregate_to_topk: bool = True) -> tuple[Array, Array]:
"""Returns min ``k`` values and the... | Returns min ``k`` values and their indices of the ``operand`` in an approximate manner.
See https://arxiv.org/abs/2206.14286 for the algorithm details.
Args:
operand : Array to search for min-k. Must be a floating number type.
k : Specifies the number of min-k.
reduction_dimension: Integer dimension a... | approx_min_k | python | jax-ml/jax | jax/_src/lax/ann.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/ann.py | Apache-2.0 |
def conv_general_dilated(
lhs: Array, rhs: Array, window_strides: Sequence[int],
padding: str | Sequence[tuple[int, int]],
lhs_dilation: Sequence[int] | None = None,
rhs_dilation: Sequence[int] | None = None,
dimension_numbers: ConvGeneralDilatedDimensionNumbers = None,
feature_group_count: int = 1, batch_... | General n-dimensional convolution operator, with optional dilation.
Wraps XLA's `Conv
<https://www.tensorflow.org/xla/operation_semantics#conv_convolution>`_
operator.
Args:
lhs: a rank `n+2` dimensional input array.
rhs: a rank `n+2` dimensional array of kernel weights.
window_strides: a sequence... | conv_general_dilated | python | jax-ml/jax | jax/_src/lax/convolution.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/convolution.py | Apache-2.0 |
def conv(lhs: Array, rhs: Array, window_strides: Sequence[int],
padding: str, precision: lax.PrecisionLike = None,
preferred_element_type: DTypeLike | None = None) -> Array:
"""Convenience wrapper around `conv_general_dilated`.
Args:
lhs: a rank `n+2` dimensional input array.
rhs: a rank ... | Convenience wrapper around `conv_general_dilated`.
Args:
lhs: a rank `n+2` dimensional input array.
rhs: a rank `n+2` dimensional array of kernel weights.
window_strides: a sequence of `n` integers, representing the inter-window
strides.
padding: either the string `'SAME'`, the string `'VALID'`... | conv | python | jax-ml/jax | jax/_src/lax/convolution.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/convolution.py | Apache-2.0 |
def conv_with_general_padding(lhs: Array, rhs: Array,
window_strides: Sequence[int],
padding: str | Sequence[tuple[int, int]],
lhs_dilation: Sequence[int] | None,
rhs_dilation: Sequence[int] | None,
... | Convenience wrapper around `conv_general_dilated`.
Args:
lhs: a rank `n+2` dimensional input array.
rhs: a rank `n+2` dimensional array of kernel weights.
window_strides: a sequence of `n` integers, representing the inter-window
strides.
padding: either the string `'SAME'`, the string `'VALID'`... | conv_with_general_padding | python | jax-ml/jax | jax/_src/lax/convolution.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/convolution.py | Apache-2.0 |
def _conv_transpose_padding(k, s, padding):
"""Calculate before and after padding for a dim of transposed convolution.
Args:
k: int: kernel dimension.
s: int: dimension stride value.
padding: 'same' or 'valid' padding mode for original forward conv.
Returns:
2-tuple: ints: before and after paddi... | Calculate before and after padding for a dim of transposed convolution.
Args:
k: int: kernel dimension.
s: int: dimension stride value.
padding: 'same' or 'valid' padding mode for original forward conv.
Returns:
2-tuple: ints: before and after padding for transposed convolution.
| _conv_transpose_padding | python | jax-ml/jax | jax/_src/lax/convolution.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/convolution.py | Apache-2.0 |
def _flip_axes(x, axes):
"""Flip ndarray 'x' along each axis specified in axes tuple."""
for axis in axes:
x = np.flip(x, axis)
return x | Flip ndarray 'x' along each axis specified in axes tuple. | _flip_axes | python | jax-ml/jax | jax/_src/lax/convolution.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/convolution.py | Apache-2.0 |
def conv_transpose(lhs: Array, rhs: Array, strides: Sequence[int],
padding: str | Sequence[tuple[int, int]],
rhs_dilation: Sequence[int] | None = None,
dimension_numbers: ConvGeneralDilatedDimensionNumbers = None,
transpose_kernel: bool = False... | Convenience wrapper for calculating the N-d convolution "transpose".
This function directly calculates a fractionally strided conv rather than
indirectly calculating the gradient (transpose) of a forward convolution.
Args:
lhs: a rank `n+2` dimensional input array.
rhs: a rank `n+2` dimensional array of... | conv_transpose | python | jax-ml/jax | jax/_src/lax/convolution.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/convolution.py | Apache-2.0 |
def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1):
"""Compute the shape tuple of a conv given input shapes in canonical order."""
if isinstance(pads, str):
pads = lax.padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
if len(pads) != len(lhs_shape) - 2:
msg = "Wrong ... | Compute the shape tuple of a conv given input shapes in canonical order. | conv_shape_tuple | python | jax-ml/jax | jax/_src/lax/convolution.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/convolution.py | Apache-2.0 |
def conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers
) -> ConvDimensionNumbers:
"""Converts convolution `dimension_numbers` to a `ConvDimensionNumbers`.
Args:
lhs_shape: tuple of nonnegative integers, shape of the convolution input.
rhs_shape: tuple of nonnegative i... | Converts convolution `dimension_numbers` to a `ConvDimensionNumbers`.
Args:
lhs_shape: tuple of nonnegative integers, shape of the convolution input.
rhs_shape: tuple of nonnegative integers, shape of the convolution kernel.
dimension_numbers: None or a tuple/list of strings or a ConvDimensionNumbers
... | conv_dimension_numbers | python | jax-ml/jax | jax/_src/lax/convolution.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/convolution.py | Apache-2.0 |
def conv_general_permutations(dimension_numbers):
"""Utility for convolution dimension permutations relative to Conv HLO."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
lhs_char, rhs_char, out_char = charpairs = ("N", "C"), ("O", "I"), ("N", "C")
for i, (a, b) in enumerate(charpairs):
if not dimension_... | Utility for convolution dimension permutations relative to Conv HLO. | conv_general_permutations | python | jax-ml/jax | jax/_src/lax/convolution.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/convolution.py | Apache-2.0 |
def _mask(x, dims, alternative=0):
"""Masks `x` up to the dynamic shape `dims`.
Replaces values outside those dimensions with `alternative`. `alternative` is
broadcast with `x`.
"""
assert np.ndim(x) == len(dims)
mask = None
for i, d in enumerate(dims):
if d is not None:
mask_dim_i = lax.broadc... | Masks `x` up to the dynamic shape `dims`.
Replaces values outside those dimensions with `alternative`. `alternative` is
broadcast with `x`.
| _mask | python | jax-ml/jax | jax/_src/lax/eigh.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/eigh.py | Apache-2.0 |
def _slice(operand, start_indices, dynamic_slice_sizes, static_slice_sizes,
fill_value=0):
"""Similar to lax.dynamic_slice, but handles arrays with dynamic sizes.
Returns fill_value instead of clamping start_indices for those elements that
would overflow the side of the array.
Args:
operand: th... | Similar to lax.dynamic_slice, but handles arrays with dynamic sizes.
Returns fill_value instead of clamping start_indices for those elements that
would overflow the side of the array.
Args:
operand: the array to slice
start_indices: the offset of the start of the slice
dynamic_slice_sizes: the true ... | _slice | python | jax-ml/jax | jax/_src/lax/eigh.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/eigh.py | Apache-2.0 |
def _update_slice(operand, update, start_indices, update_dims):
"""
Similar to lax.dynamic_update_slice, but handles padded updates where padding
values should not overwrite existing values in the array.
Args:
operand: the array to update
update: the padded array to write
start_indices: the offset at whi... |
Similar to lax.dynamic_update_slice, but handles padded updates where padding
values should not overwrite existing values in the array.
Args:
operand: the array to update
update: the padded array to write
start_indices: the offset at which to write `update`.
update_dims: the true dimensions of the padde... | _update_slice | python | jax-ml/jax | jax/_src/lax/eigh.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/eigh.py | Apache-2.0 |
def _try_broadcast_shapes(*shapes: tuple[int, ...], name: str) -> tuple[int, ...]:
"""
Attempt to broadcast shapes, raising a TypeError if broadcasting fails.
"""
if not shapes:
raise TypeError(f"{name}: At least one shape is required.")
ranks = {len(shape) for shape in shapes}
if len(ranks) != 1:
r... |
Attempt to broadcast shapes, raising a TypeError if broadcasting fails.
| _try_broadcast_shapes | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def asarray(x: ArrayLike) -> Array:
"""Lightweight conversion of ArrayLike input to Array output."""
if isinstance(x, Array):
return x
elif isinstance(x, (bool, np.ndarray, np.generic)):
return _convert_element_type(x, weak_type=False) # pytype: disable=bad-return-type
elif isinstance(x, (int, float, b... | Lightweight conversion of ArrayLike input to Array output. | asarray | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def broadcast_shapes(*shapes):
"""Returns the shape that results from NumPy broadcasting of `shapes`.
This follows the rules of `NumPy broadcasting`_.
Args:
shapes: one or more tuples of integers containing the shapes of arrays
to be broadcast.
Returns:
A tuple of integers representing the broa... | Returns the shape that results from NumPy broadcasting of `shapes`.
This follows the rules of `NumPy broadcasting`_.
Args:
shapes: one or more tuples of integers containing the shapes of arrays
to be broadcast.
Returns:
A tuple of integers representing the broadcasted shape.
Raises:
ValueE... | broadcast_shapes | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def nextafter(x1: ArrayLike, x2: ArrayLike) -> Array:
"""Returns the next representable value after ``x1`` in the direction of ``x2``.
This function lowers directly to the ``chlo.next_after`` operation.
Args:
x1, x2: input arrays. Must have a matching floating-point dtypes. If neither is
a scalar, mus... | Returns the next representable value after ``x1`` in the direction of ``x2``.
This function lowers directly to the ``chlo.next_after`` operation.
Args:
x1, x2: input arrays. Must have a matching floating-point dtypes. If neither is
a scalar, must have the same number of dimensions and be broadcast-compa... | nextafter | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def round(x: ArrayLike,
rounding_method: RoundingMethod = RoundingMethod.AWAY_FROM_ZERO
) -> Array:
r"""Elementwise round.
Rounds values to the nearest integer. This function lowers directly to the
`stablehlo.round`_ operation.
Args:
x: an array or scalar value to round. Must have floa... | Elementwise round.
Rounds values to the nearest integer. This function lowers directly to the
`stablehlo.round`_ operation.
Args:
x: an array or scalar value to round. Must have floating-point type.
rounding_method: the method to use when rounding halfway values
(e.g., ``0.5``). See :class:`jax.la... | round | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def atan2(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise two-term arc tangent: :math:`\mathrm{atan}({x \over y})`.
This function lowers directly to the `stablehlo.atan2`_ operation.
Args:
x, y: input arrays. Must have a matching floating-point or complex dtypes. If
neither is a scalar, the two ... | Elementwise two-term arc tangent: :math:`\mathrm{atan}({x \over y})`.
This function lowers directly to the `stablehlo.atan2`_ operation.
Args:
x, y: input arrays. Must have a matching floating-point or complex dtypes. If
neither is a scalar, the two arrays must have the same number of dimensions
a... | atan2 | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def complex(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise make complex number: :math:`x + jy`.
This function lowers directly to the `stablehlo.complex`_ operation.
Args:
x, y: input arrays. Must have matching floating-point dtypes. If
neither is a scalar, the two arrays must have the same numb... | Elementwise make complex number: :math:`x + jy`.
This function lowers directly to the `stablehlo.complex`_ operation.
Args:
x, y: input arrays. Must have matching floating-point dtypes. If
neither is a scalar, the two arrays must have the same number
of dimensions and be broadcast-compatible.
R... | complex | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def conj(x: ArrayLike) -> Array:
r"""Elementwise complex conjugate function: :math:`\overline{x}`.
This function lowers to a combination of `stablehlo.real`_, `stablehlo.imag`_,
and `stablehlo.complex`_.
Args:
x: input array. Must have complex dtype.
Returns:
Array of the same shape and dtype as `... | Elementwise complex conjugate function: :math:`\overline{x}`.
This function lowers to a combination of `stablehlo.real`_, `stablehlo.imag`_,
and `stablehlo.complex`_.
Args:
x: input array. Must have complex dtype.
Returns:
Array of the same shape and dtype as ``x`` containing its complex conjugate.
... | conj | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def pow(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise power: :math:`x^y`.
This function lowers directly to the `stablehlo.pow`_ operation, along with
a `stablehlo.convert`_ when the argument dtypes do not match.
Args:
x: Input array giving the base value. Must have floating or complex type.
y:... | Elementwise power: :math:`x^y`.
This function lowers directly to the `stablehlo.pow`_ operation, along with
a `stablehlo.convert`_ when the argument dtypes do not match.
Args:
x: Input array giving the base value. Must have floating or complex type.
y: Input array giving the exponent value. Must have in... | pow | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def bitwise_and(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise AND: :math:`x \wedge y`.
This function lowers directly to the `stablehlo.and`_ operation.
Args:
x, y: Input arrays. Must have matching boolean or integer dtypes.
If neither is a scalar, ``x`` and ``y`` must have the same number
... | Elementwise AND: :math:`x \wedge y`.
This function lowers directly to the `stablehlo.and`_ operation.
Args:
x, y: Input arrays. Must have matching boolean or integer dtypes.
If neither is a scalar, ``x`` and ``y`` must have the same number
of dimensions and be broadcast compatible.
Returns:
... | bitwise_and | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def bitwise_or(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise OR: :math:`x \vee y`.
This function lowers directly to the `stablehlo.or`_ operation.
Args:
x, y: Input arrays. Must have matching boolean or integer dtypes.
If neither is a scalar, ``x`` and ``y`` must have the same number
of ... | Elementwise OR: :math:`x \vee y`.
This function lowers directly to the `stablehlo.or`_ operation.
Args:
x, y: Input arrays. Must have matching boolean or integer dtypes.
If neither is a scalar, ``x`` and ``y`` must have the same number
of dimensions and be broadcast compatible.
Returns:
An ... | bitwise_or | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def bitwise_xor(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise exclusive OR: :math:`x \oplus y`.
This function lowers directly to the `stablehlo.xor`_ operation.
Args:
x, y: Input arrays. Must have matching boolean or integer dtypes.
If neither is a scalar, ``x`` and ``y`` must have the same nu... | Elementwise exclusive OR: :math:`x \oplus y`.
This function lowers directly to the `stablehlo.xor`_ operation.
Args:
x, y: Input arrays. Must have matching boolean or integer dtypes.
If neither is a scalar, ``x`` and ``y`` must have the same number
of dimensions and be broadcast compatible.
Ret... | bitwise_xor | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def add(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise addition: :math:`x + y`.
This function lowers directly to the `stablehlo.add`_ operation.
Args:
x, y: Input arrays. Must have matching numerical dtypes. If neither
is a scalar, ``x`` and ``y`` must have the same number of dimensions
a... | Elementwise addition: :math:`x + y`.
This function lowers directly to the `stablehlo.add`_ operation.
Args:
x, y: Input arrays. Must have matching numerical dtypes. If neither
is a scalar, ``x`` and ``y`` must have the same number of dimensions
and be broadcast compatible.
Returns:
An array... | add | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def sub(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise subtraction: :math:`x - y`.
This function lowers directly to the `stablehlo.subtract`_ operation.
Args:
x, y: Input arrays. Must have matching numerical dtypes. If neither
is a scalar, ``x`` and ``y`` must have the same number of dimensions... | Elementwise subtraction: :math:`x - y`.
This function lowers directly to the `stablehlo.subtract`_ operation.
Args:
x, y: Input arrays. Must have matching numerical dtypes. If neither
is a scalar, ``x`` and ``y`` must have the same number of dimensions
and be broadcast compatible.
Returns:
... | sub | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def mul(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise multiplication: :math:`x \times y`.
This function lowers directly to the `stablehlo.multiply`_ operation.
Args:
x, y: Input arrays. Must have matching numerical dtypes. If neither
is a scalar, ``x`` and ``y`` must have the same number of di... | Elementwise multiplication: :math:`x \times y`.
This function lowers directly to the `stablehlo.multiply`_ operation.
Args:
x, y: Input arrays. Must have matching numerical dtypes. If neither
is a scalar, ``x`` and ``y`` must have the same number of dimensions
and be broadcast compatible.
Retur... | mul | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def div(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise division: :math:`x \over y`.
This function lowers directly to the `stablehlo.divide`_ operation.
Integer division overflow (division by zero or signed division of
INT_SMIN with -1) produces an implementation defined value.
Args:
x, y: Input ... | Elementwise division: :math:`x \over y`.
This function lowers directly to the `stablehlo.divide`_ operation.
Integer division overflow (division by zero or signed division of
INT_SMIN with -1) produces an implementation defined value.
Args:
x, y: Input arrays. Must have matching numerical dtypes. If neit... | div | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def rem(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise remainder: :math:`x \bmod y`.
This function lowers directly to the `stablehlo.remainder`_ operation.
The sign of the result is taken from the dividend, and the absolute value
of the result is always less than the divisor's absolute value.
Integer... | Elementwise remainder: :math:`x \bmod y`.
This function lowers directly to the `stablehlo.remainder`_ operation.
The sign of the result is taken from the dividend, and the absolute value
of the result is always less than the divisor's absolute value.
Integer division overflow (remainder by zero or remainder o... | rem | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def max(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise maximum: :math:`\mathrm{max}(x, y)`.
This function lowers directly to the `stablehlo.maximum`_ operation for
non-complex inputs. For complex numbers, this uses a lexicographic
comparison on the `(real, imaginary)` pairs.
Args:
x, y: Input arr... | Elementwise maximum: :math:`\mathrm{max}(x, y)`.
This function lowers directly to the `stablehlo.maximum`_ operation for
non-complex inputs. For complex numbers, this uses a lexicographic
comparison on the `(real, imaginary)` pairs.
Args:
x, y: Input arrays. Must have matching dtypes. If neither is a scal... | max | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def min(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise minimum: :math:`\mathrm{min}(x, y)`
This function lowers directly to the `stablehlo.minimum`_ operation for
non-complex inputs. For complex numbers, this uses a lexicographic
comparison on the `(real, imaginary)` pairs.
Args:
x, y: Input arra... | Elementwise minimum: :math:`\mathrm{min}(x, y)`
This function lowers directly to the `stablehlo.minimum`_ operation for
non-complex inputs. For complex numbers, this uses a lexicographic
comparison on the `(real, imaginary)` pairs.
Args:
x, y: Input arrays. Must have matching dtypes. If neither is a scala... | min | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def shift_left(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise left shift: :math:`x \ll y`.
This function lowers directly to the `stablehlo.shift_left`_ operation.
Args:
x, y: Input arrays. Must have matching integer dtypes. If neither is a
scalar, ``x`` and ``y`` must have the same number of di... | Elementwise left shift: :math:`x \ll y`.
This function lowers directly to the `stablehlo.shift_left`_ operation.
Args:
x, y: Input arrays. Must have matching integer dtypes. If neither is a
scalar, ``x`` and ``y`` must have the same number of dimensions and
be broadcast compatible.
Returns:
... | shift_left | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def shift_right_arithmetic(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise arithmetic right shift: :math:`x \gg y`.
This function lowers directly to the `stablehlo.shift_right_arithmetic`_ operation.
Args:
x, y: Input arrays. Must have matching integer dtypes. If neither is a
scalar, ``x`` and `... | Elementwise arithmetic right shift: :math:`x \gg y`.
This function lowers directly to the `stablehlo.shift_right_arithmetic`_ operation.
Args:
x, y: Input arrays. Must have matching integer dtypes. If neither is a
scalar, ``x`` and ``y`` must have the same number of dimensions and
be broadcast com... | shift_right_arithmetic | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def shift_right_logical(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise logical right shift: :math:`x \gg y`.
This function lowers directly to the `stablehlo.shift_right_logical`_ operation.
Args:
x, y: Input arrays. Must have matching integer dtypes. If neither is a
scalar, ``x`` and ``y`` must... | Elementwise logical right shift: :math:`x \gg y`.
This function lowers directly to the `stablehlo.shift_right_logical`_ operation.
Args:
x, y: Input arrays. Must have matching integer dtypes. If neither is a
scalar, ``x`` and ``y`` must have the same number of dimensions and
be broadcast compatibl... | shift_right_logical | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def eq(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise equals: :math:`x = y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=EQ`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching dtypes. If neither ... | Elementwise equals: :math:`x = y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=EQ`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching dtypes. If neither is a
scalar, ``x`` and ``y`` must have the sa... | eq | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def ne(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise not-equals: :math:`x \neq y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=NE`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching dtypes. If n... | Elementwise not-equals: :math:`x \neq y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=NE`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching dtypes. If neither is a
scalar, ``x`` and ``y`` must have... | ne | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def ge(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise greater-than-or-equals: :math:`x \geq y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=GE`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching ... | Elementwise greater-than-or-equals: :math:`x \geq y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=GE`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching non-complex dtypes. If neither is
a scalar, `... | ge | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def gt(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise greater-than: :math:`x > y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=GT`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching non-complex d... | Elementwise greater-than: :math:`x > y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=GT`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching non-complex dtypes. If neither is
a scalar, ``x`` and ``y`... | gt | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
def le(x: ArrayLike, y: ArrayLike) -> Array:
r"""Elementwise less-than-or-equals: :math:`x \leq y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=LE`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching non... | Elementwise less-than-or-equals: :math:`x \leq y`.
This function lowers directly to the `stablehlo.compare`_ operation
with ``comparison_direction=LE`` and ``compare_type`` set according
to the input dtype.
Args:
x, y: Input arrays. Must have matching non-complex dtypes. If neither is
a scalar, ``x`... | le | python | jax-ml/jax | jax/_src/lax/lax.py | https://github.com/jax-ml/jax/blob/master/jax/_src/lax/lax.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.