id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
22,624 | import dataclasses
import functools
from typing import Any, Iterable, Optional, Tuple
import jax
import jax.numpy as jnp
from jax import lax
from jax.nn import initializers
from flax.linen import dtypes, module, transforms
from flax.typing import (
Array,
PRNGKey as PRNGKey,
Dtype,
Shape as Shape,
Initializer... | Normalizes the input of a normalization layer and optionally applies a learned scale and bias. Arguments: mdl: Module to apply the normalization in (normalization params will reside in this module). x: The input. mean: Mean to use for normalization. var: Variance to use for normalization. reduction_axes: The axes in ``... |
22,625 | import dataclasses
import functools
from typing import Any, Iterable, Optional, Tuple
import jax
import jax.numpy as jnp
from jax import lax
from jax.nn import initializers
from flax.linen import dtypes, module, transforms
from flax.typing import (
Array,
PRNGKey as PRNGKey,
Dtype,
Shape as Shape,
Initializer... | Normalizes along dimension `axis` using an L2 norm. This specialized function exists for numerical stability reasons. Args: x: An input ndarray. axis: Dimension along which to normalize, e.g. `1` to separately normalize vectors in a batch. Passing `None` views `t` as a flattened vector when calculating the norm (equiva... |
22,626 | import jax, jax.numpy as jnp
import numpy as np
def ndim_at_least(x, num_dims):
if not (isinstance(x, jax.Array) or isinstance(x, np.ndarray)):
x = jnp.asarray(x)
return x.ndim >= num_dims
def arbitrary_mergeable_leaf(min_num_dims, args, kwargs):
for a in jax.tree_util.tree_leaves(args):
if ndim_at_least... | null |
22,627 | import jax, jax.numpy as jnp
import numpy as np
def ndim_at_least(x, num_dims):
if not (isinstance(x, jax.Array) or isinstance(x, np.ndarray)):
x = jnp.asarray(x)
return x.ndim >= num_dims
The provided code snippet includes necessary dependencies for implementing the `merge_leading_dims` function. Write a Pyth... | Merge leading dimensions. |
22,628 | import jax, jax.numpy as jnp
import numpy as np
def split_leading_dim(x, to_dim):
new_shape = to_dim + x.shape[1:]
return x.reshape(new_shape) | null |
22,629 | import jax.numpy as jnp
import numpy as np
from jax import lax
def pool(inputs, init, reduce_fn, window_shape, strides, padding):
"""Helper function to define pooling functions.
Pooling functions are implemented using the ReduceWindow XLA op.
.. note::
Be aware that pooling is not generally differentiable.
... | Pools the input by taking the average over a window. Args: inputs: input data with dimensions (batch, window dims..., features). window_shape: a shape tuple defining the window to reduce over. strides: a sequence of ``n`` integers, representing the inter-window strides (default: ``(1, ..., 1)``). padding: either the st... |
22,630 | import jax.numpy as jnp
import numpy as np
from jax import lax
def pool(inputs, init, reduce_fn, window_shape, strides, padding):
"""Helper function to define pooling functions.
Pooling functions are implemented using the ReduceWindow XLA op.
.. note::
Be aware that pooling is not generally differentiable.
... | Pools the input by taking the maximum of a window slice. Args: inputs: input data with dimensions (batch, window dims..., features). window_shape: a shape tuple defining the window to reduce over. strides: a sequence of ``n`` integers, representing the inter-window strides (default: ``(1, ..., 1)``). padding: either th... |
22,631 | import jax.numpy as jnp
import numpy as np
from jax import lax
def pool(inputs, init, reduce_fn, window_shape, strides, padding):
"""Helper function to define pooling functions.
Pooling functions are implemented using the ReduceWindow XLA op.
.. note::
Be aware that pooling is not generally differentiable.
... | Pools the input by taking the minimum of a window slice. Args: inputs: Input data with dimensions (batch, window dims..., features). window_shape: A shape tuple defining the window to reduce over. strides: A sequence of ``n`` integers, representing the inter-window strides (default: ``(1, ..., 1)``). padding: Either th... |
22,632 | import dataclasses
import numpy as np
import warnings
from functools import partial
from jax import custom_jvp, custom_vjp, lax, random
from jax import numpy as jnp
from jax._src import core
from jax._src import dtypes
from flax.linen import initializers, module
def qdq_and_return(x, q_dtype, scale, amax_history, compu... | null |
22,633 | import dataclasses
import numpy as np
import warnings
from functools import partial
from jax import custom_jvp, custom_vjp, lax, random
from jax import numpy as jnp
from jax._src import core
from jax._src import dtypes
from flax.linen import initializers, module
def qdq_and_return(x, q_dtype, scale, amax_history, compu... | null |
22,634 | import dataclasses
import numpy as np
import warnings
from functools import partial
from jax import custom_jvp, custom_vjp, lax, random
from jax import numpy as jnp
from jax._src import core
from jax._src import dtypes
from flax.linen import initializers, module
def in_qdq_bwd(compute_dtype, res, g):
new_scale, new_... | null |
22,635 | import dataclasses
import numpy as np
import warnings
from functools import partial
from jax import custom_jvp, custom_vjp, lax, random
from jax import numpy as jnp
from jax._src import core
from jax._src import dtypes
from flax.linen import initializers, module
def out_qdq(compute_dtype, out, scale, amax_history):
... | null |
22,636 | import dataclasses
import numpy as np
import warnings
from functools import partial
from jax import custom_jvp, custom_vjp, lax, random
from jax import numpy as jnp
from jax._src import core
from jax._src import dtypes
from flax.linen import initializers, module
def out_qdq_fwd(compute_dtype, out, scale, amax_history)... | null |
22,637 | import dataclasses
import numpy as np
import warnings
from functools import partial
from jax import custom_jvp, custom_vjp, lax, random
from jax import numpy as jnp
from jax._src import core
from jax._src import dtypes
from flax.linen import initializers, module
def qdq_and_return(x, q_dtype, scale, amax_history, compu... | null |
22,638 | import dataclasses
import numpy as np
import warnings
from functools import partial
from jax import custom_jvp, custom_vjp, lax, random
from jax import numpy as jnp
from jax._src import core
from jax._src import dtypes
from flax.linen import initializers, module
def dot_general_with_precision(
lhs, rhs, dimension_nu... | null |
22,639 | import dataclasses
import numpy as np
import warnings
from functools import partial
from jax import custom_jvp, custom_vjp, lax, random
from jax import numpy as jnp
from jax._src import core
from jax._src import dtypes
from flax.linen import initializers, module
def dot_general_with_precision_jvp(
dimension_numbers,... | null |
22,640 | from functools import partial
from typing import (
Any,
Callable,
Dict,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import jax
import numpy as np
from absl import logging
from jax import numpy as jnp
from jax import random
from typing_extensions import Protocol
from flax.core.frozen_dict im... | null |
22,641 | from functools import partial
from typing import (
Any,
Callable,
Dict,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import jax
import numpy as np
from absl import logging
from jax import numpy as jnp
from jax import random
from typing_extensions import Protocol
from flax.core.frozen_dict im... | Flips a sequence of inputs along the time axis. This function can be used to prepare inputs for the reverse direction of a bidirectional LSTM. It solves the issue that, when naively flipping multiple padded sequences stored in a matrix, the first elements would be padding values for those sequences that were padded. Th... |
22,642 | from functools import partial
from typing import (
Any,
Callable,
Dict,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import jax
import numpy as np
from absl import logging
from jax import numpy as jnp
from jax import random
from typing_extensions import Protocol
from flax.core.frozen_dict im... | Concatenates two arrays along the last dimension. |
22,643 | import dataclasses
from typing import Any, Callable, Iterable, Optional, Tuple, Sequence
import jax.numpy as jnp
from jax import lax
from flax import linen as nn
from flax.linen import initializers
from flax.linen.partitioning import param_with_axes, with_sharding_constraint
from flax.typing import (
Array,
Dtype,
... | Computes mean and variance statistics. This implementation takes care of a few important details: - Computes in float32 precision for half precision inputs - mean and variance is computable in a single XLA fusion, by using Var = E[|x|^2] - |E[x]|^2 instead of Var = E[|x - E[x]|^2]). - Clips negative variances to zero w... |
22,644 | import dataclasses
from typing import Any, Callable, Iterable, Optional, Tuple, Sequence
import jax.numpy as jnp
from jax import lax
from flax import linen as nn
from flax.linen import initializers
from flax.linen.partitioning import param_with_axes, with_sharding_constraint
from flax.typing import (
Array,
Dtype,
... | "Normalizes the input of a normalization layer and optionally applies a learned scale and bias. A seperate bias and scale is learned for each feature as specified by feature_axes. |
22,645 | import dataclasses
from typing import (
Any,
Iterable,
List,
Optional,
Sequence,
Tuple,
Union,
)
import jax
import jax.numpy as jnp
import numpy as np
from jax import eval_shape, lax
from jax.core import ShapedArray
import opt_einsum
from flax.core import meta
from flax.linen import initializers
from flax... | null |
22,646 | import dataclasses
from typing import (
Any,
Iterable,
List,
Optional,
Sequence,
Tuple,
Union,
)
import jax
import jax.numpy as jnp
import numpy as np
from jax import eval_shape, lax
from jax.core import ShapedArray
import opt_einsum
from flax.core import meta
from flax.linen import initializers
from flax... | null |
22,647 | import dataclasses
from typing import (
Any,
Iterable,
List,
Optional,
Sequence,
Tuple,
Union,
)
import jax
import jax.numpy as jnp
import numpy as np
from jax import eval_shape, lax
from jax.core import ShapedArray
import opt_einsum
from flax.core import meta
from flax.linen import initializers
from flax... | Computes the dimension numbers based on the input shape. |
22,648 | import dataclasses
from typing import (
Any,
Iterable,
List,
Optional,
Sequence,
Tuple,
Union,
)
import jax
import jax.numpy as jnp
import numpy as np
from jax import eval_shape, lax
from jax.core import ShapedArray
import opt_einsum
from flax.core import meta
from flax.linen import initializers
from flax... | "Canonicalizes conv padding to a jax.lax supported format. |
22,649 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Returns a pretty printed representation of the module. |
22,650 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Enables named call wrapping for labelling profile traces. When named call wrapping is enabled all JAX ops executed in a Module will be run under ``jax.named_scope``. The ``Module`` class name will show up around the operations belonging to that Module in the Tensorboard profiling UI, simplifying the profiling process. ... |
22,651 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Disables named call wrapping. See ``enable_named_call`` |
22,652 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Returns a context manager that enables/disables named call wrapping. Args: enable: If true, enables named call wrapping for labelling profile traces. (see ``enabled_named_call``). |
22,653 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | r"""Registers a new method interceptor. Method interceptors allow you to (at a distance) intercept method calls to modules. It works similarly to decorators. You could modify args/kwargs before calling the underlying method and/or modify the result returning from calling the underlying method. Or you could completely s... |
22,654 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Runs method interceptors. |
22,655 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Helper for naming pytrees of submodules. |
22,656 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Marks the given module method allowing inlined submodules. Methods wrapped in @compact can define submodules directly within the method. For instance:: >>> import flax.linen as nn >>> class Foo(nn.Module): ... @nn.compact ... def __call__(self, x, features): ... x = nn.Dense(features)(x) ... ... ... return x At most on... |
22,657 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Creates compact submodules from a method. This is a decorator that allows you to define compact submodules from a method. It's intention is to make it easier to port code Haiku code to Flax by providing the same functionality. Example:: >>> import flax.linen as nn >>> import jax >>> import jax.numpy as jnp >>> from fla... |
22,658 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Gets method names of a class, excluding class and static methods. Args: cls: The class to get method names for. exclude: Names to exclude from output. Returns: A list of method names. |
22,659 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Gets descriptor names of a class. Args: cls: The class to get property names for. exclude: Names to exclude from output. Returns: A list of property names. |
22,660 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Wraps a descriptor to give better error messages. Args: descriptor: User-defined Module attribute descriptor. Returns: Wrapped descriptor. |
22,661 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Wraps a hash function with some check for Flax Modules. |
22,662 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Map a function over all submodules in a tree. |
22,663 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | null |
22,664 | import contextlib
import dataclasses
import enum
import functools
import inspect
import sys
import threading
import typing
import weakref
from types import MappingProxyType
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Uni... | Merges construction- and call-time argument. This is a utility for supporting a pattern where a Module hyperparameter can be passed either to ``__init__`` or ``__call__``, and the value that is not ``None`` will be used. Example:: >>> import flax.linen as nn >>> from typing import Optional >>> class Foo(nn.Module): ...... |
22,665 | import functools
from collections.abc import Iterable
from typing import Any, Callable, Union
import jax
import jax.numpy as jnp
import numpy as np
from jax import lax, random
from flax import struct
from flax.core import Scope
from flax.linen import initializers
from .linear import default_kernel_init, dense_general
... | Applies multi-head dot product attention on the input data. Projects the inputs into multi-headed query, key, and value vectors, applies dot-product attention and project the results to an output vector. This can be used for encoder-decoder attention by specifying both `inputs_q` and `inputs_kv` orfor self-attention by... |
22,666 | import jax.numpy as jnp
from jax import lax
from flax.core import Scope
from flax.linen import initializers
def _absolute_dims(ndim, dims):
def batch_norm(
scope: Scope,
x,
use_running_average=False,
axis=-1,
momentum=0.99,
epsilon=1e-5,
dtype=jnp.float32,
bias=True,
scale=True,
bias_init=initializ... | null |
22,667 | import jax.numpy as jnp
from jax import lax
from flax.core import Scope
from flax.linen import initializers
The provided code snippet includes necessary dependencies for implementing the `layer_norm` function. Write a Python function `def layer_norm( scope: Scope, x, epsilon=1e-6, dtype=jnp.float32, bias=Tru... | Applies layer normalization on the input. It normalizes the activations of the layer for each given example in a batch independently, rather than across a batch like Batch Normalization. i.e. applies a transformation that maintains the mean activation within each example close to 0 and the activation standard deviation... |
22,668 | import jax.numpy as jnp
from jax import lax
from flax.core import Scope
from flax.linen import initializers
The provided code snippet includes necessary dependencies for implementing the `group_norm` function. Write a Python function `def group_norm( scope, x, num_groups=32, group_size=None, epsilon=1e-6, ... | Applies group normalization to the input (arxiv.org/abs/1803.08494). This op is similar to batch normalization, but statistics are shared across equally-sized groups of channels and not shared across batch dimension. Thus, group normalization does not depend on the batch composition and does not require maintaining int... |
22,669 | import jax.numpy as jnp
from jax import lax, random
The provided code snippet includes necessary dependencies for implementing the `dropout` function. Write a Python function `def dropout(scope, inputs, rate, deterministic=False, rng=None)` to solve the following problem:
Applies a random dropout mask to the input. Ar... | Applies a random dropout mask to the input. Args: inputs: the inputs that should be randomly masked. rate: the probablity of masking out a value. deterministic: if false the inputs are scaled by `1 / (1 - rate)` and masked, whereas if true, no mask is applied and the inputs are returned as is. rng: an optional `jax.ran... |
22,670 | from collections.abc import Iterable
import jax.numpy as jnp
import numpy as np
from jax import lax
from flax import struct
from flax.core import Scope
from flax.linen import initializers
default_kernel_init = initializers.lecun_normal()
def _conv_dimension_numbers(input_shape):
"""Computes the dimension numbers bas... | Applies a convolution to the inputs. Args: inputs: input data with dimensions (batch, spatial_dims..., features). features: number of convolution filters. kernel_size: shape of the convolutional kernel. strides: a sequence of `n` integers, representing the inter-window strides. padding: either the string `'SAME'`, the ... |
22,671 | from collections.abc import Iterable
import jax.numpy as jnp
import numpy as np
from jax import lax
from flax import struct
from flax.core import Scope
from flax.linen import initializers
default_kernel_init = initializers.lecun_normal()
The provided code snippet includes necessary dependencies for implementing the `... | Applies a transposed convolution to the inputs. Behaviour mirrors that of `jax.lax.conv_transpose`. Args: scope: functional scope. inputs: input data with dimensions (batch, spatial_dims..., features). features: number of convolution filters. kernel_size: shape of the convolutional kernel. strides: a sequence of `n` in... |
22,672 | from collections.abc import Iterable
import jax.numpy as jnp
import numpy as np
from jax import lax
from flax import struct
from flax.core import Scope
from flax.linen import initializers
default_embed_init = initializers.variance_scaling(
1.0, 'fan_in', 'normal', out_axis=0
)
class Embedding:
table: np.ndarray
... | Creates embedding dataclass. Args: num_embeddings: number of embeddings. features: Number of feature dimensions for each embedding. embedding_init: embedding initializer. Returns: Embedding dataclass with lookup and attend methods. |
22,673 | import collections
import functools
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import warnings
from flax import traceback_util
from flax.typing import (
In,
Out,
InOutAxis,
InOutScanAxis,
)
import ja... | Swap two collections. |
22,674 | import collections
import functools
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import warnings
from flax import traceback_util
from flax.typing import (
In,
Out,
InOutAxis,
InOutScanAxis,
)
import ja... | A lifted version of ``jax.jvp``. See ``jax.jvp`` for the unlifted Jacobian-vector product (forward gradient). Note that no tangents are returned for variables. When variable tangents are required their value should be returned explicitly by `fn` using `scope.variables()`. Example:: def learn_scale(scope, x): p = scope.... |
22,675 | import collections
import functools
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import warnings
from flax import traceback_util
from flax.typing import (
In,
Out,
InOutAxis,
InOutScanAxis,
)
import ja... | A lifted version of ``jax.vmap``. See ``jax.vmap`` for the unlifted batch transform in Jax. ``vmap`` can be used to add a batch axis to a scope function. For example we could create a version of ``dense`` with a batch axis that does not share parameters:: batch_dense = lift.vmap( nn.dense, in_axes=(0, None), variable_a... |
22,676 | import collections
import functools
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import warnings
from flax import traceback_util
from flax.typing import (
In,
Out,
InOutAxis,
InOutScanAxis,
)
import ja... | Lifted version of jax.lax.while_loop. The lifted scope is passed to `cond_fn` and `body_fn`. Broadcasted variables are immutable. The carry variable are mutable but cannot change shape and dtype. This also means you cannot initialize variables inside the body. Consider calling `body_fn` once manually before calling `wh... |
22,677 | import collections
import functools
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import warnings
from flax import traceback_util
from flax.typing import (
In,
Out,
InOutAxis,
InOutScanAxis,
)
import ja... | Lifted version of ``jax.checkpoint``. This function is aliased to ``lift.remat`` just like ``jax.remat``. Args: fn: scope function for which intermediate computations should be re-computed when computing gradients. variables: The variable collections that are lifted. By default all collections are lifted. rngs: The PRN... |
22,678 | import collections
import functools
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
import warnings
from flax import traceback_util
from flax.typing import (
In,
Out,
InOutAxis,
InOutScanAxis,
)
import ja... | Combines `lift.remat` and `lift.scan` for memory efficiency and constant time compilation. ``remat_scan`` allows for constant compile times and sublinear memory usage with respect to model depth. At a small constant penalty. This is typically beneficial for very deep models. Example:: def body_fn(scope, x): return nn.d... |
22,679 | import collections
import contextlib
import dataclasses
import functools
import hashlib
import typing
from typing import (
Any,
Callable,
Dict,
Generic,
Iterable,
Literal,
Mapping,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import jax
import numpy as np
from jax impo... | Legacy RNG folding. |
22,680 | import collections
import contextlib
import dataclasses
import functools
import hashlib
import typing
from typing import (
Any,
Callable,
Dict,
Generic,
Iterable,
Literal,
Mapping,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import jax
import numpy as np
from jax impo... | Folds static data (strings & ints) into a jax.random.PRNGKey using its SHA-1 hash. This is faster than splitting an PRNGKey because it allows generating new PRNG keys in parallel that are independent of each other. Args: rng: the rng to fold the string into. data: the string to be folded in. Returns: The newly generate... |
22,681 | import collections
import contextlib
import dataclasses
import functools
import hashlib
import typing
from typing import (
Any,
Callable,
Dict,
Generic,
Iterable,
Literal,
Mapping,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import jax
import numpy as np
from jax impo... | Functionalizes a `Scope` function for lazy initialization. Similair to ``init`` except that the init function now accepts ``jax.ShapeDtypeStruct`` instances for arguments that do not affect the variable initialization (typically this is all the input data). Example:: def f(scope, x): # the kernel init only uses the sha... |
22,682 | import jax
from .. import errors
def current_trace():
def trace_level(main):
def check_trace_level(base_level):
level = trace_level(current_trace())
if level != base_level:
raise errors.JaxTransformError() | null |
22,683 | import collections
from types import MappingProxyType
from typing import Any, Dict, Hashable, Mapping, Tuple, TypeVar, Union
import jax
from flax import serialization
class FrozenDict(Mapping[K, V]):
"""An immutable variant of the Python dict."""
__slots__ = ('_dict', '_hash')
def __init__(self, *args, __unsafe_s... | Deep copy unfrozen dicts to make the dictionary FrozenDict safe. |
22,684 | import collections
from types import MappingProxyType
from typing import Any, Dict, Hashable, Mapping, Tuple, TypeVar, Union
import jax
from flax import serialization
class FrozenDict(Mapping[K, V]):
"""An immutable variant of the Python dict."""
__slots__ = ('_dict', '_hash')
def __init__(self, *args, __unsafe_s... | Create a new dict with additional and/or replaced entries. This is a utility function that can act on either a FrozenDict or regular dict and mimics the behavior of ``FrozenDict.copy``. Example:: >>> from flax.core import FrozenDict, copy >>> variables = FrozenDict({'params': {...}, 'batch_stats': {...}}) >>> new_varia... |
22,685 | import collections
from types import MappingProxyType
from typing import Any, Dict, Hashable, Mapping, Tuple, TypeVar, Union
import jax
from flax import serialization
def _indent(x, num_spaces):
indent_str = ' ' * num_spaces
lines = x.split('\n')
assert not lines[-1]
# skip the final line because it's empty and... | Returns an indented representation of the nested dictionary. This is a utility function that can act on either a FrozenDict or regular dict and mimics the behavior of ``FrozenDict.pretty_repr``. If x is any other dtype, this function will return ``repr(x)``. Args: x: the dictionary to be represented num_spaces: the num... |
22,686 | import collections
from types import MappingProxyType
from typing import Any, Dict, Hashable, Mapping, Tuple, TypeVar, Union
import jax
from flax import serialization
serialization.register_serialization_state(
FrozenDict, _frozen_dict_state_dict, _restore_frozen_dict
)
def _frozen_dict_state_dict(xs):
return {key... | null |
22,687 | import collections
from types import MappingProxyType
from typing import Any, Dict, Hashable, Mapping, Tuple, TypeVar, Union
import jax
from flax import serialization
class FrozenDict(Mapping[K, V]):
"""An immutable variant of the Python dict."""
__slots__ = ('_dict', '_hash')
def __init__(self, *args, __unsafe_s... | null |
22,688 | import abc
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
from flax import errors, struct
from flax.typing import LogicalNames
import jax
from jax.experimental import maps
class AxisMetadata(Generic[A], metaclass=abc.ABCMeta):
"""Abstract base class for boxed Metadata.
``AxisMet... | Updates all AxisMetadata boxes with the values in updates. |
22,689 | import abc
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
from flax import errors, struct
from flax.typing import LogicalNames
import jax
from jax.experimental import maps
class Partitioned(struct.PyTreeNode, AxisMetadata[A]):
"""Wrapper for partitioning metadata.
``Partitioned`... | Wraps a function's return value with Partitioned. Example:: >>> import flax.linen as nn >>> kernel_init = nn.with_partitioning( ... nn.initializers.lecun_normal(), (None, "data")) >>> partitioned_dense = nn.Dense(features=3, kernel_init=kernel_init) Args: fn: The function to be wrapped. Typically this is an initializer... |
22,690 | import abc
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
from flax import errors, struct
from flax.typing import LogicalNames
import jax
from jax.experimental import maps
def get_partition_spec(tree: Any) -> Any:
"""Extracts a PartitionSpec tree from a PyTree containing ``Partiti... | Extracts a jax.sharding tree from a PyTree containing ``Partitioned`` values and a mesh. |
22,691 | import functools
from typing import Any
import jax
from jax import core
from jax.extend import linear_util as lu
from jax.interpreters import partial_eval as pe
from flax import errors
def _maybe_unknown(x: Any) -> pe.PartialVal:
if isinstance(x, jax.ShapeDtypeStruct):
return pe.PartialVal.unknown(core.ShapedArra... | Lazily evaluates a function by using the shapes of the inputs. The returned function accepts a combination of JAX values and ``jax.ShapeDtypeStruct`` instances for the inputs for which we don't need concrete values (only the shape and dtype). This API is used by ``core.lazy_init`` or ``Module.lazy_init`` to initialize ... |
22,692 | import collections
import itertools
import warnings
from collections.abc import Iterable
import jax
import jax.numpy as jnp
import numpy as np
from jax import core, lax
from jax.extend import linear_util as lu
from jax.interpreters import partial_eval as pe
def _parse_spec(spec):
"""Parse an input spec of the form (... | Lazily evaluate a function by using the shapes of the inputs. This function is similar to ``jax.eval_shape`` with the key difference that function outputs that can be computed without a concrete value of the inputs are returned as is instead of only the shape. See for example ``module.init_by_shape`` where this functio... |
22,693 | import collections
import itertools
import warnings
from collections.abc import Iterable
import jax
import jax.numpy as jnp
import numpy as np
from jax import core, lax
from jax.extend import linear_util as lu
from jax.interpreters import partial_eval as pe
def _scan_nd(body_fn, init, xs, n=1, unroll=(1,)):
"""Utili... | utility for doing a scan along arbitrary dimensions. See `lax.scan` for details on how the scan operation works. Note on `unroll`: This argument gets left padded with ones to match the size of `axis`. Doing so allows unrolls to performed from the innermost loop first. For example, `scan_in_dim(..., axis=(1, 2, 3), unro... |
22,694 | import collections
import itertools
import warnings
from collections.abc import Iterable
import jax
import jax.numpy as jnp
import numpy as np
from jax import core, lax
from jax.extend import linear_util as lu
from jax.interpreters import partial_eval as pe
The provided code snippet includes necessary dependencies fo... | Wraps a function with code that pads, shards, then un-shards, un-pads. Args: wrapped: the function to be wrapped. Signature is ``params, *args, *kwargs``. static_argnums: indices of arguments to ``wrapped`` that should _not_ be padded and sharded, but instead be forwarded as-is. The default is (0,) because by far the m... |
22,695 | import jax
import jax.numpy as jnp
import numpy as np
from jax import lax
The provided code snippet includes necessary dependencies for implementing the `shard_prng_key` function. Write a Python function `def shard_prng_key(prng_key)` to solve the following problem:
Helper to shard (aka split) a PRNGKey for use with p... | Helper to shard (aka split) a PRNGKey for use with pmap'd functions. PRNG keys can be used at train time to drive stochastic modules e.g. Dropout. We would like a different PRNG key for each local device so that we end up with different random numbers on each one, hence we split our PRNG key. Args: prng_key: JAX PRNGKe... |
22,696 | import functools
import os
import pathlib
import re
import time
import warnings
from concurrent.futures import thread
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import jax
import orbax.checkpoint as ocp
from absl import logging
from jax import monitoring,... | Return step numbers of available checkpoints in a directory. Args: ckpt_dir: str: directory of checkpoints to restore from. prefix: str: name prefix of checkpoint files. step_type: type: type for steps, int (default) or float. Returns: Sorted list of available steps or empty list if no checkpoints were found. |
22,697 | import functools
import os
import pathlib
import re
import time
import warnings
from concurrent.futures import thread
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import jax
import orbax.checkpoint as ocp
from absl import logging
from jax import monitoring,... | Converts a pre-Linen parameter pytree. In pre-Linen API submodules were numbered incrementally, independent of the submodule class. With Linen this behavior has changed to keep separate submodule counts per module class. Consider the following module:: class Model(nn.Module): @nn.compact def __call__(self, x): x = nn.C... |
22,698 | import jax.numpy as jnp
import numpy as np
from absl import logging
The provided code snippet includes necessary dependencies for implementing the `create_constant_learning_rate_schedule` function. Write a Python function `def create_constant_learning_rate_schedule( base_learning_rate, steps_per_epoch, warmup_length... | Create a constant learning rate schedule with optional warmup. Note that with `FLIP #1009`_ learning rate schedules in ``flax.training`` are **effectively deprecated** in favor of Optax_ schedules. Please refer to `Optimizer Schedules`_ for more information. .. _FLIP #1009: https://github.com/google/flax/blob/main/docs... |
22,699 | import jax.numpy as jnp
import numpy as np
from absl import logging
def _piecewise_constant(boundaries, values, t):
index = jnp.sum(boundaries < t)
return jnp.take(values, index)
The provided code snippet includes necessary dependencies for implementing the `create_stepped_learning_rate_schedule` function. Write a... | Create a stepped learning rate schedule with optional warmup. Note that with `FLIP #1009`_ learning rate schedules in ``flax.training`` are **effectively deprecated** in favor of Optax_ schedules. Please refer to `Optimizer Schedules`_ for more information. .. _FLIP #1009: https://github.com/google/flax/blob/main/docs/... |
22,700 | import jax.numpy as jnp
import numpy as np
from absl import logging
The provided code snippet includes necessary dependencies for implementing the `create_cosine_learning_rate_schedule` function. Write a Python function `def create_cosine_learning_rate_schedule( base_learning_rate, steps_per_epoch, halfcos_epochs, w... | Create a cosine learning rate schedule with optional warmup. Note that with `FLIP #1009`_ learning rate schedules in ``flax.training`` are **effectively deprecated** in favor of Optax_ schedules. Please refer to `Optimizer Schedules`_ for more information. .. _FLIP #1009: https://github.com/google/flax/blob/main/docs/f... |
22,701 | import dataclasses
import enum
from typing import (
Any,
Callable,
Dict,
Generator,
Generic,
Mapping,
Optional,
Protocol,
TypeVar,
runtime_checkable,
)
from flax.core import FrozenDict
from flax.errors import CursorFindError, TraverseTreeError
class AccessType(enum.Enum):
ITEM = enum.auto()
ATTR... | Helper function for ``Cursor.apply_update`` and ``Cursor.find_all``. Exactly one of ``update_fn`` and ``cond_fn`` must be not None. - If ``update_fn`` is not None, then ``Cursor.apply_update`` is calling this function and ``_traverse_tree`` will return a generator where each generated element is of type Tuple[Tuple[Uni... |
22,702 | import dataclasses
import enum
from typing import (
Any,
Callable,
Dict,
Generator,
Generic,
Mapping,
Optional,
Protocol,
TypeVar,
runtime_checkable,
)
from flax.core import FrozenDict
from flax.errors import CursorFindError, TraverseTreeError
A = TypeVar('A')
class Cursor(Generic[A]):
_obj: A
_... | Wrap :class:`Cursor <flax.cursor.Cursor>` over ``obj`` and return it. Changes can then be applied to the Cursor object in the following ways: - single-line change via the ``.set`` method - multiple changes, and then calling the ``.build`` method - multiple changes conditioned on the pytree path and node value via the `... |
22,703 | import os
from contextlib import contextmanager
from typing import Any, Generic, NoReturn, TypeVar, overload
class Config:
# See https://google.github.io/pytype/faq.html.
_HAS_DYNAMIC_ATTRIBUTES = True
def __init__(self):
self._values = {}
def _add_option(self, name, default):
if name in self._values:
... | Set up a boolean flag. Example:: enable_foo = bool_flag( name='flax_enable_foo', default=False, help='Enable foo.', ) Now the ``FLAX_ENABLE_FOO`` shell environment variable can be used to control the process-level value of the flag, in addition to using e.g. ``config.update("flax_enable_foo", True)`` directly. Args: na... |
22,704 | import os
from contextlib import contextmanager
from typing import Any, Generic, NoReturn, TypeVar, overload
config = Config()
The provided code snippet includes necessary dependencies for implementing the `temp_flip_flag` function. Write a Python function `def temp_flip_flag(var_name: str, var_value: bool)` to solve ... | Context manager to temporarily flip feature flags for test functions. Args: var_name: the config variable name (without the 'flax_' prefix) var_value: the boolean value to set var_name to temporarily |
22,705 | import dataclasses
from typing import TypeVar
import jax
from typing_extensions import (
dataclass_transform, # pytype: disable=not-supported-yet
)
from . import serialization
_T = TypeVar('_T')
The provided code snippet includes necessary dependencies for implementing the `dataclass` function. Write a Python funct... | Create a class which can be passed to functional transformations. .. note:: Inherit from ``PyTreeNode`` instead to avoid type checking issues when using PyType. Jax transformations such as ``jax.jit`` and ``jax.grad`` require objects that are immutable and can be mapped over using the ``jax.tree_util`` methods. The ``d... |
22,706 | import contextlib
import glob as glob_module
import importlib
import os
import shutil
from enum import Enum
from absl import logging
from . import errors
class BackendMode(Enum):
DEFAULT = 0
TF = 1
io_mode = None
if io_mode == BackendMode.TF:
from tensorflow import errors as tf_errors # type: ignore
NotFoundEr... | Returns a context manager that changes backend IO mode. Args: override: BackendMode enum value to set IO mode inside context. |
22,707 | import contextlib
import glob as glob_module
import importlib
import os
import shutil
from enum import Enum
from absl import logging
from . import errors
class BackendMode(Enum):
DEFAULT = 0
TF = 1
io_mode = None
if io_mode == BackendMode.TF:
from tensorflow import errors as tf_errors # type: ignore
NotFoundEr... | Sets global io mode. Args: override: BackendMode enum value to set for IO mode. |
22,708 | import contextlib
import glob as glob_module
import importlib
import os
import shutil
from enum import Enum
from absl import logging
from . import errors
class BackendMode(Enum):
DEFAULT = 0
TF = 1
io_mode = None
gfile = None
if io_mode == BackendMode.TF:
from tensorflow import errors as tf_errors # type: ignore... | null |
22,709 | import contextlib
import glob as glob_module
import importlib
import os
import shutil
from enum import Enum
from absl import logging
from . import errors
class BackendMode(Enum):
DEFAULT = 0
TF = 1
io_mode = None
gfile = None
if io_mode == BackendMode.TF:
from tensorflow import errors as tf_errors # type: ignore... | null |
22,710 | from __future__ import annotations
import functools
from typing import Any, Callable, Optional, overload
import jax
import jax.numpy as jnp
from jax import lax, random
from flax.experimental import nnx
from flax.experimental.nnx.nnx import rnglib
from flax.experimental.nnx.nnx.module import Module, first_from
from flax... | Computes dot-product attention given query, key, and value. This is the core function for applying attention based on https://arxiv.org/abs/1706.03762. It calculates the attention weights given query and key and combines the values using the attention weights. .. note:: ``query``, ``key``, ``value`` needn't have any ba... |
22,711 | from __future__ import annotations
import functools
from typing import Any, Callable, Optional, overload
import jax
import jax.numpy as jnp
from jax import lax, random
from flax.experimental import nnx
from flax.experimental.nnx.nnx import rnglib
from flax.experimental.nnx.nnx.module import Module, first_from
from flax... | Make a causal mask for self-attention. In case of 1d inputs (i.e., `[batch..., len]`, the self-attention weights will be `[batch..., heads, len, len]` and this function will produce a causal mask of shape `[batch..., 1, len, len]`. Args: x: input array of shape `[batch..., len]` extra_batch_dims: number of batch dims t... |
22,712 | from __future__ import annotations
import functools
from typing import Any, Callable, Optional, overload
import jax
import jax.numpy as jnp
from jax import lax, random
from flax.experimental import nnx
from flax.experimental.nnx.nnx import rnglib
from flax.experimental.nnx.nnx.module import Module, first_from
from flax... | Combine attention masks. Args: *masks: set of attention mask arguments to combine, some can be None. dtype: dtype for the returned mask. Returns: Combined mask, reduced by logical and, returns None if no masks given. |
22,713 | import typing as tp
import jax
import jax.numpy as jnp
from jax import lax
from flax.experimental import nnx
from flax.experimental.nnx.nnx import rnglib
from flax.experimental.nnx.nnx.module import Module, first_from
from flax.experimental.nnx.nnx.nn import dtypes, initializers
from flax.typing import (
Array,
Dty... | Computes mean and variance statistics. This implementation takes care of a few important details: - Computes in float32 precision for stability in half precision training. - If `use_fast_variance` is `True`, mean and variance are computed using Var = E[|x|^2] - |E[x]|^2, instead of Var = E[|x - E[x]|^2]), in a single X... |
22,714 | import typing as tp
import jax
import jax.numpy as jnp
from jax import lax
from flax.experimental import nnx
from flax.experimental.nnx.nnx import rnglib
from flax.experimental.nnx.nnx.module import Module, first_from
from flax.experimental.nnx.nnx.nn import dtypes, initializers
from flax.typing import (
Array,
Dty... | "Normalizes the input of a normalization layer and optionally applies a learned scale and bias. Arguments: x: The input. mean: Mean to use for normalization. var: Variance to use for normalization. reduction_axes: The axes in ``x`` to reduce. feature_axes: Axes containing features. A separate bias and scale is learned ... |
22,715 | import typing as tp
from jax.nn.initializers import constant as constant
from jax.nn.initializers import delta_orthogonal as delta_orthogonal
from jax.nn.initializers import glorot_normal as glorot_normal
from jax.nn.initializers import glorot_uniform as glorot_uniform
from jax.nn.initializers import he_normal as he_no... | Builds an initializer that returns a constant array full of zeros. >>> import jax, jax.numpy as jnp >>> from flax.experimental.nnx import initializers >>> zeros_initializer = initializers.zeros_init() >>> zeros_initializer(jax.random.key(42), (2, 3), jnp.float32) Array([[0., 0., 0.], [0., 0., 0.]], dtype=float32) |
22,716 | import typing as tp
from jax.nn.initializers import constant as constant
from jax.nn.initializers import delta_orthogonal as delta_orthogonal
from jax.nn.initializers import glorot_normal as glorot_normal
from jax.nn.initializers import glorot_uniform as glorot_uniform
from jax.nn.initializers import he_normal as he_no... | Builds an initializer that returns a constant array full of ones. >>> import jax, jax.numpy as jnp >>> from flax.experimental.nnx import initializers >>> ones_initializer = initializers.ones_init() >>> ones_initializer(jax.random.key(42), (3, 2), jnp.float32) Array([[1., 1.], [1., 1.], [1., 1.]], dtype=float32) |
22,717 | from __future__ import annotations
import typing as tp
from types import MappingProxyType
import jax
import jax.numpy as jnp
import numpy as np
from jax import lax
import opt_einsum
from flax.experimental import nnx
from flax.experimental.nnx.nnx import rnglib, variables
from flax.experimental.nnx.nnx.module import Mod... | "Canonicalizes conv padding to a jax.lax supported format. |
22,718 | from __future__ import annotations
import typing as tp
from types import MappingProxyType
import jax
import jax.numpy as jnp
import numpy as np
from jax import lax
import opt_einsum
from flax.experimental import nnx
from flax.experimental.nnx.nnx import rnglib, variables
from flax.experimental.nnx.nnx.module import Mod... | Computes the dimension numbers based on the input shape. |
22,719 | from __future__ import annotations
import typing as tp
from types import MappingProxyType
import jax
import jax.numpy as jnp
import numpy as np
from jax import lax
import opt_einsum
from flax.experimental import nnx
from flax.experimental.nnx.nnx import rnglib, variables
from flax.experimental.nnx.nnx.module import Mod... | null |
22,720 | from __future__ import annotations
import typing as tp
from types import MappingProxyType
import jax
import jax.numpy as jnp
import numpy as np
from jax import lax
import opt_einsum
from flax.experimental import nnx
from flax.experimental.nnx.nnx import rnglib, variables
from flax.experimental.nnx.nnx.module import Mod... | null |
22,721 | import functools
import typing as tp
import jax
from jax.experimental import maps
from jax.sharding import Mesh, PartitionSpec
from flax.experimental.nnx.nnx import variables
from flax.experimental.nnx.nnx.pytreelib import TreeNode
from flax.experimental.nnx.nnx.state import State
from flax.typing import (
Array,
A... | null |
22,722 | import functools
import typing as tp
import jax
from jax.experimental import maps
from jax.sharding import Mesh, PartitionSpec
from flax.experimental.nnx.nnx import variables
from flax.experimental.nnx.nnx.pytreelib import TreeNode
from flax.experimental.nnx.nnx.state import State
from flax.typing import (
Array,
A... | null |
22,723 | from __future__ import annotations
import dataclasses
import functools
import typing as tp
from abc import abstractmethod
from types import MappingProxyType
from typing import Any
import jax
import jax.numpy as jnp
import jax.stages
from flax.experimental.nnx.nnx import (
filterlib,
rnglib,
spmd,
variables,
)
f... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.