id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
151,570
import os import imageio import numpy as np import torch import torchvision from PIL import Image from typing import Union from tqdm import tqdm from einops import rearrange import torch.distributed as dist def ddim_loop(pipeline, ddim_scheduler, latent, num_inv_steps, prompt): context = init_prompt(prompt, pipelin...
null
151,571
import os import imageio import numpy as np import torch import torchvision from PIL import Image from typing import Union from tqdm import tqdm from einops import rearrange import torch.distributed as dist def video2images(path, step=4, length=16, start=0): reader = imageio.get_reader(path) frames = [] fo...
null
151,572
import os import imageio import numpy as np import torch import torchvision from PIL import Image from typing import Union from tqdm import tqdm from einops import rearrange import torch.distributed as dist def images2video(video, path, fps=8): imageio.mimsave(path, video, fps=fps) return
null
151,573
import os import imageio import numpy as np import torch import torchvision from PIL import Image from typing import Union from tqdm import tqdm from einops import rearrange import torch.distributed as dist tensor_interpolation = None def get_tensor_interpolation_method(): return tensor_interpolation
null
151,574
import os import imageio import numpy as np import torch import torchvision from PIL import Image from typing import Union from tqdm import tqdm from einops import rearrange import torch.distributed as dist tensor_interpolation = None def linear(v1, v2, t): def slerp( v0: torch.Tensor, v1: torch.Tensor, t: float, D...
null
151,575
import os import socket import warnings import torch from torch import distributed as dist def get_rank(): if not dist.is_available(): return 0 if not dist.is_nccl_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank() def is_master(): return get_...
null
151,577
from typing import Any, Dict, List, Set, Tuple import sphinx.ext.autodoc import sphinx.ext.autosummary.generate as ag ag.generate_autosummary_content = generate_autosummary_content def generate_autosummary_content( name: str, obj: Any, parent: Any, template: ag.AutosummaryRenderer, template_name: s...
null
151,578
import fiddle as fdl import seqio from t5.data import mixtures from t5.data import tasks from t5x import config_utils from t5x import eval as t5x_eval from t5x import partitioning from t5x import utils from t5x.fiddle_configs.configs import finetune from t5x.fiddle_configs.configs import pretrain from t5x.fiddle_config...
null
151,579
import fiddle as fdl import seqio from t5.data import mixtures from t5.data import tasks from t5x import config_utils from t5x import eval as t5x_eval from t5x import partitioning from t5x import utils from t5x.fiddle_configs.configs import finetune from t5x.fiddle_configs.configs import pretrain from t5x.fiddle_config...
null
151,580
import fiddle as fdl import seqio from t5.data import mixtures from t5.data import tasks from t5x import config_utils from t5x import eval as t5x_eval from t5x import partitioning from t5x import utils from t5x.fiddle_configs.configs import finetune from t5x.fiddle_configs.configs import pretrain from t5x.fiddle_config...
null
151,581
import os from typing import Sequence from absl import logging from t5x import export_lib The provided code snippet includes necessary dependencies for implementing the `_main` function. Write a Python function `def _main(argv: Sequence[str])` to solve the following problem: True main function. Here is the function: ...
True main function.
151,582
import abc import collections import dataclasses import functools import typing from typing import Any, Callable, Optional, Sequence, Set, Tuple, Union from absl import logging import cached_property from flax import traverse_util from flax.linen import partitioning as flax_partitioning import jax from jax import numpy...
Identity function for copying parameters to the devices, sharded.
151,583
import functools import gc import math import os import time from typing import Callable, Dict, Mapping, Optional, Sequence, Tuple, Type from absl import logging from clu import metric_writers import jax from jax import random from jax.experimental import multihost_utils import jax.numpy as jnp import numpy as np impor...
True main function.
151,584
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts class LazyArray...
null
151,585
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts SLOT_MAP = {'_s...
null
151,586
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts SLOT_MAP = {'_s...
null
151,587
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts SLOT_MAP = {'_s...
Process relpos bias assuming that they are not shared across layers.
151,588
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts SLOT_MAP = {'_s...
Process attention layers.
151,589
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts SLOT_MAP = {'_s...
Process MLP blocks.
151,590
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts SLOT_MAP = {'_s...
Process layer norms assuming that they are pre-layernorms.
151,591
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts SLOT_MAP = {'_s...
Process final layer norms.
151,592
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts SLOT_MAP = {'_s...
null
151,593
import abc import asyncio from concurrent.futures import thread import re from typing import Any, Callable, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from flax import traverse_util import jax from jax import numpy as jnp import numpy as np import tensorflow as tf import tensorstore as ts class LazyArray...
Load T5 checkpoint and update Adafactor optimizer and T5 model from it. We require that the final translated checkpoint structure exactly matches that of the Flax Adafactor + Transformer data, up to shape agreement of the leaves. Args: state_dict: Flax Adafactor Optimizer for T5 transformer encoder-decoder. path: a pat...
151,594
import enum import os from typing import Any, BinaryIO, Optional from absl import logging from etils import epath import msgpack from tensorflow.io import gfile def pinned_checkpoint_filepath(ckpt_dir: str) -> str: """Full path of the pinned checkpoint file.""" return os.path.join(ckpt_dir, _PINNED_CHECKPOINT_FILEN...
Pin a checkpoint so it does not get deleted by the normal pruning process. Creates a PINNED file in the checkpoint directory to indicate the checkpoint should be excluded from the deletion of old checkpoints. Args: ckpt_dir: The checkpoint step dir that is to be always kept. txt: Text to be written into the checkpoints...
151,595
import enum import os from typing import Any, BinaryIO, Optional from absl import logging from etils import epath import msgpack from tensorflow.io import gfile def pinned_checkpoint_filepath(ckpt_dir: str) -> str: """Full path of the pinned checkpoint file.""" return os.path.join(ckpt_dir, _PINNED_CHECKPOINT_FILEN...
Removes the pinned status of the checkpoint so it is open for deletion.
151,596
import enum import os from typing import Any, BinaryIO, Optional from absl import logging from etils import epath import msgpack from tensorflow.io import gfile def is_pinned_checkpoint(ckpt_dir: str) -> bool: """Returns whether the checkpoint is pinned, and should NOT be removed.""" pinned_ckpt_file = pinned_check...
Removes the checkpoint dir if it is not pinned.
151,597
import enum import os from typing import Any, BinaryIO, Optional from absl import logging from etils import epath import msgpack from tensorflow.io import gfile def is_pinned_checkpoint(ckpt_dir: str) -> bool: """Returns whether the checkpoint is pinned, and should NOT be removed.""" pinned_ckpt_file = pinned_check...
Removes dataset checkpoints if the checkpoint is not pinned.
151,598
import enum import os from typing import Any, BinaryIO, Optional from absl import logging from etils import epath import msgpack from tensorflow.io import gfile def _read_msgpack_keys(file_like: BinaryIO) -> PyTree: """Returns a tree containing all keys but no values from a msgpack file.""" unpacker = msgpack.Unpac...
Returns the checkpoint type by reading the `.checkpoint` metadata file. Args: checkpoint_path: The path of the `.checkpoint` file. expected: The expected checkpoint type. If the checkpoint type is not as expected, this function will log a warning but will not raise an error. Returns: The checkpoint type.
151,599
import collections import collections.abc from concurrent.futures import thread import contextlib import dataclasses import functools import importlib import inspect import os import re import time import typing from typing import Any, Callable, Iterable, Mapping, Optional, Sequence, Tuple, Type, Union import warnings ...
Create jax.Array from input arrays. Example: Consider a case where the global input array has length 128. The global mesh specifies that the data dimension be sharded into 8 shards. This means we want shards of length 16. The data_layout, defined by the partitioner object, specifies that the data should be divided into...
151,600
import collections import collections.abc from concurrent.futures import thread import contextlib import dataclasses import functools import importlib import inspect import os import re import time import typing from typing import Any, Callable, Iterable, Mapping, Optional, Sequence, Tuple, Type, Union import warnings ...
Random uniform method that uses non-deterministic accelerator hardware.
151,601
import collections import collections.abc from concurrent.futures import thread import contextlib import dataclasses import functools import importlib import inspect import os import re import time import typing from typing import Any, Callable, Iterable, Mapping, Optional, Sequence, Tuple, Type, Union import warnings ...
null
151,602
import collections import collections.abc from concurrent.futures import thread import contextlib import dataclasses import functools import importlib import inspect import os import re import time import typing from typing import Any, Callable, Iterable, Mapping, Optional, Sequence, Tuple, Type, Union import warnings ...
Round up vocabulary size for improved TPU performance.
151,603
import collections import collections.abc from concurrent.futures import thread import contextlib import dataclasses import functools import importlib import inspect import os import re import time import typing from typing import Any, Callable, Iterable, Mapping, Optional, Sequence, Tuple, Type, Union import warnings ...
Flattens a nested dictionary to have string keys and '/' separators.
151,604
import collections import collections.abc from concurrent.futures import thread import contextlib import dataclasses import functools import importlib import inspect import os import re import time import typing from typing import Any, Callable, Iterable, Mapping, Optional, Sequence, Tuple, Type, Union import warnings ...
Applies parameter axis names overrides to axes variables. Args: model_variables: the original model variables containing the 'params_axes' collection. params_axes_names_override: a priority-ordered mapping from regex patterns (fully matching parameter names) to tuples containing string logical axis names to replace mod...
151,605
import functools from typing import Callable, Mapping, Optional, Tuple, Union import flax import jax from jax import lax from jax import random import jax.numpy as jnp from t5x import binary_search from t5x import decoding from t5x.decoding import _is_tracer from t5x.decoding import DecodingState from t5x.decoding impo...
Temperature sampling for language model generation. The temperature sampling is performed `num_decodes` times in a vectorized manner by expanding the batch dimension. This is similar to how beam search expands the batch dimension to process each batch element with multiple beams. This function dynamically updates the `...
151,606
from typing import Any, Callable, Optional, Sequence, Tuple, Union from absl import logging import cached_property from flax import core as flax_core import jax from jax.experimental.pjit import pjit from jax.sharding import Mesh import numpy as np from t5x import adafactor from t5x import optimizers from t5x import pa...
Trivial MoE mesh for CPU Testing.
151,607
from typing import Any, Callable, Optional, Sequence, Tuple, Union from absl import logging import cached_property from flax import core as flax_core import jax from jax.experimental.pjit import pjit from jax.sharding import Mesh import numpy as np from t5x import adafactor from t5x import optimizers from t5x import pa...
Simple MoE mesh for GPUs.
151,608
from typing import Any, Callable, Optional, Sequence, Tuple, Union from absl import logging import cached_property from flax import core as flax_core import jax from jax.experimental.pjit import pjit from jax.sharding import Mesh import numpy as np from t5x import adafactor from t5x import optimizers from t5x import pa...
Construct default xmap/pjit mesh for MoE. Unlike the vanilla T5X mesh, this mesh has three resource axes: - 'expert': 1D submesh with length that divides into `num_expert_partitions`, - 'model': specified by the provided `model_parallel_submesh` shape, and - 'data', which covers the rest of the mesh. Relative to the va...
151,609
from typing import Any, Callable, Optional, Sequence, Tuple, Union from absl import logging import cached_property from flax import core as flax_core import jax from jax.experimental.pjit import pjit from jax.sharding import Mesh import numpy as np from t5x import adafactor from t5x import optimizers from t5x import pa...
Returns partitioning rules for MoE models. MoE params and state are partitioned along the 'expert' axis. Data is partitioned along both of the 'data' AND 'expert' axes. The partitioning rules vary based on whether the expert and data axes need to be decoupled; see also MoePjitPartitioner for details of when expert and ...
151,610
from typing import Any, Callable, Optional, Sequence, Tuple, Union from absl import logging import cached_property from flax import core as flax_core import jax from jax.experimental.pjit import pjit from jax.sharding import Mesh import numpy as np from t5x import adafactor from t5x import optimizers from t5x import pa...
Returns number of model partitions. Args: num_model_partitions: Specifies the size of the model parallel submesh. model_parallel_submesh: 4-tuple that specifies the `(x, y, z, c)` submesh model-parallel device tile Returns: Size of model parallel submesh. Raises: ValueError if neither num_model_partitions nor model_par...
151,611
from typing import Any, Callable, Optional, Sequence, Tuple, Union from absl import logging import cached_property from flax import core as flax_core import jax from jax.experimental.pjit import pjit from jax.sharding import Mesh import numpy as np from t5x import adafactor from t5x import optimizers from t5x import pa...
Override raw axis resources so data is sharded over 'data' & 'expert' axes. Here, we only override any raw partition specs that are hardcoded in T5X libraries: PartitionSpec('data',) -> PartitionSpec(('expert', 'data'),) NOTE: We do not (and there is no need) to override any params or optimizer state (which appear as l...
151,612
from typing import Any, Callable, Optional, Sequence, Tuple, Union from absl import logging import cached_property from flax import core as flax_core import jax from jax.experimental.pjit import pjit from jax.sharding import Mesh import numpy as np from t5x import adafactor from t5x import optimizers from t5x import pa...
Infers relevant regex matching sharded expert model state for train state. The model state generally inherits the correct partitioning specs from the model parameters. In such cases, no state_filter_fn is required. However, T5X's custom Adafactor optimizer, when factored, requires overrides to the `v_col` and `v_row` k...
151,613
from typing import Any, Callable, Dict, Mapping, MutableMapping, Optional, Tuple, Union import clu.metrics as clu_metrics from flax import core as flax_core from flax import linen as nn from flax import traverse_util from flax.core import scope as flax_scope import jax import jax.numpy as jnp import seqio from t5x impo...
Computes combined cross-entropy and MoE auxiliary loss.
151,614
import os from typing import Any, Optional, Union import clu.data import jax from jax.experimental.array_serialization import serialization as array_serialization from jax.experimental.pjit import pjit import jax.numpy as jnp import numpy as np from t5x import checkpoint_importer from t5x import checkpoints from t5x im...
Reads array from tensorstore and handles broadcasting of expert weights. If both `mesh` and `axes` are provided, the method will attempt to restore the array as a GlobalDeviceArray. This method is adapted from _read_ts() in t5x/checkpoints.py. This variant broadcasts dense MLP weights from the checkpoint to the sparse,...
151,615
from flax import core as flax_core from t5x import adafactor FactorDim = adafactor.FactorDim FrozenDict = flax_core.FrozenDict The provided code snippet includes necessary dependencies for implementing the `logical_factor_rules` function. Write a Python function `def logical_factor_rules() -> FrozenDict` to solve the ...
Logical factor rules for Mixture of Experts.
151,616
import dataclasses import re from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union import flax import jax import numpy as np from t5x import train_state Gradients = Union[flax.core.FrozenDict, train_state.TrainState] def _tree_flatten_with_names( tree: ParamTree, ) -> Tuple[Sequence[Tuple[str...
Scales sharded grads, identified by sharded_match_fn, by scale_factor. Args: grads: Parameter gradients. sharded_match_fn: Filter function for distinguishing sharded parameters from replicated parameters. scale_factor: Amount by which to scale sharded parameter gradients. Returns: Gradients matching input, expect with ...
151,617
import dataclasses import re from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union import flax import jax import numpy as np from t5x import train_state def _tree_flatten_with_names( tree: ParamTree, ) -> Tuple[Sequence[Tuple[str, Any]], jax.tree_util.PyTreeDef]: """Like jax.tree_util.tree_...
Like jax.tree_map but with a filter on the leaf path name. Args: f: The function to be applied to each parameter in `param_tree`. param_tree: The tree of parameters `f` should be applied to. match_name_fn: This function is called with each tree leave's path name, which has a path-like format ('a/b/c'), and decides whet...
151,618
import tensorflow_datasets as tfds import tensorflow as tf import io import zstandard import jsonlines import os import time from itertools import chain parser = json.Parser() def json_parser(x): global parser try: line = parser.parse(x).as_dict() return line except ValueError: return x
null
151,624
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn from flax.linen import partitioning as nn_partitioning import jax from jax import lax from jax import random import jax.numpy as jnp import numpy as np Array = jn...
Compute the self-attention mask for a decoder. Decoder mask is formed by combining a causal mask, a padding mask and an optional packing mask. If decoder_causal_attention is passed, it makes the masking non-causal for positions that have value of 1. A prefix LM is applied to a dataset which has a notion of "inputs" and...
151,625
import abc import enum import os import threading import time from typing import Any, Dict, Iterator, Mapping, MutableMapping, Optional, Protocol, Sequence, TYPE_CHECKING, Tuple, Union from absl import logging import cached_property from clu import asynclib from clu import metric_writers import clu.data import clu.metr...
Indirection to `time.time` for mocking.
151,626
import abc import enum import os import threading import time from typing import Any, Dict, Iterator, Mapping, MutableMapping, Optional, Protocol, Sequence, TYPE_CHECKING, Tuple, Union from absl import logging import cached_property from clu import asynclib from clu import metric_writers import clu.data import clu.metr...
Default evaluation step.
151,627
import abc import enum import os import threading import time from typing import Any, Dict, Iterator, Mapping, MutableMapping, Optional, Protocol, Sequence, TYPE_CHECKING, Tuple, Union from absl import logging import cached_property from clu import asynclib from clu import metric_writers import clu.data import clu.metr...
null
151,628
import os from typing import Optional, Sequence, Union from absl import app from absl import logging from clu import metric_writers import gin import jax from t5x import utils import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `sum_fn` function. Write a Python functi...
sum function to use inside gin files.
151,629
import os from typing import Optional, Sequence, Union from absl import app from absl import logging from clu import metric_writers import gin import jax from t5x import utils import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `bool_fn` function. Write a Python funct...
bool function to use inside gin files.
151,630
import os from typing import Optional, Sequence, Union from absl import app from absl import logging from clu import metric_writers import gin import jax from t5x import utils import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `string_split_fn` function. Write a Pyth...
String split function to use inside gin files.
151,631
import abc from collections.abc import Mapping, Sequence import enum import functools import inspect import itertools import logging import os import re from typing import Any, Callable, Iterator, Optional, Tuple, Union import clu.data.dataset_iterator import jax from jax import random from jax.experimental import mult...
Produces a list of batches that is `length` batches long. Given a single batch, repeat the batch `length` times. Given a list of batches, either repeat the batches to get `length` total batches or take the first 'length' batches. Args: batches: either a single batch of examples, or a list of batches. length: the total ...
151,632
import abc from collections.abc import Mapping, Sequence import enum import functools import inspect import itertools import logging import os import re from typing import Any, Callable, Iterator, Optional, Tuple, Union import clu.data.dataset_iterator import jax from jax import random from jax.experimental import mult...
Returns a batch of examples from a provided SeqIO task. Args: task_or_mixture_name: the SeqIO task/mixture to read data from. split: the split of the SeqIO task/mixture to read data from. batch_size: how many examples should be in each batch. num_batches: the total number of batches to return. get_pretokenized_examples...
151,633
import abc from collections.abc import Mapping, Sequence import enum import functools import inspect import itertools import logging import os import re from typing import Any, Callable, Iterator, Optional, Tuple, Union import clu.data.dataset_iterator import jax from jax import random from jax.experimental import mult...
Registers and returns a SeqIO task from the provided inputs. This function will be used to graduate people to the T5X/SeqIO-based train/infer/eval scripts. Args: task_name: the name of the SeqIO task to be created and registered. interactive_model: an instance of the InteractiveModel. examples: a single batch of exampl...
151,634
import abc from collections.abc import Mapping, Sequence import enum import functools import inspect import itertools import logging import os import re from typing import Any, Callable, Iterator, Optional, Tuple, Union import clu.data.dataset_iterator import jax from jax import random from jax.experimental import mult...
Converts an InteractiveModel instance into a Gin config string. This function will be used to graduate people to the T5X/SeqIO-based train/infer/eval scripts. Args: interactive_model: an instance of the InteractiveModel. script_type: which T5X script the Gin config should function with. task_name: the name of the SeqIO...
151,635
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn from flax.linen import partitioning as nn_partitioning import jax from jax import lax from jax import random import jax.numpy as jnp import numpy as np def varian...
Initializer with in_axis, out_axis set at call time.
151,636
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn from flax.linen import partitioning as nn_partitioning import jax from jax import lax from jax import random import jax.numpy as jnp import numpy as np Array = jn...
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. Args: query: queries for calculating attention with shape o...
151,639
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn from flax.linen import partitioning as nn_partitioning import jax from jax import lax from jax import random import jax.numpy as jnp import numpy as np The provi...
Convert a string to an activation function.
151,640
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn from flax.linen import partitioning as nn_partitioning import jax from jax import lax from jax import random import jax.numpy as jnp import numpy as np Array = jn...
Combine attention biases. Args: *masks: set of attention bias arguments to combine, some can be None. Returns: Combined mask, reduced by summation, returns None if no masks given.
151,641
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn from flax.linen import partitioning as nn_partitioning import jax from jax import lax from jax import random import jax.numpy as jnp import numpy as np Array = jn...
Compute the self-attention mask for a decoder. Decoder mask is formed by combining a causal mask, a padding mask and an optional packing mask. If decoder_causal_attention is passed, it makes the masking non-causal for positions that have value of 1. A prefix LM is applied to a dataset which has a notion of "inputs" and...
151,648
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn import flax.core.variables as variables from flax.linen import partitioning as nn_partitioning from flax.training import common_utils import jax from jax import l...
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. Args: query: queries for calculating attention with shape o...
151,649
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn import flax.core.variables as variables from flax.linen import partitioning as nn_partitioning from flax.training import common_utils import jax from jax import l...
null
151,650
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn import flax.core.variables as variables from flax.linen import partitioning as nn_partitioning from flax.training import common_utils import jax from jax import l...
null
151,651
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn import flax.core.variables as variables from flax.linen import partitioning as nn_partitioning from flax.training import common_utils import jax from jax import l...
Convert a string to an activation function.
151,652
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn import flax.core.variables as variables from flax.linen import partitioning as nn_partitioning from flax.training import common_utils import jax from jax import l...
Combine attention biases. Args: *masks: set of attention bias arguments to combine, some can be None. Returns: Combined mask, reduced by summation, returns None if no masks given.
151,653
import dataclasses import functools import operator from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from flax import linen as nn import flax.core.variables as variables from flax.linen import partitioning as nn_partitioning from flax.training import common_utils import jax from jax import l...
Compute the self-attention mask for a decoder. Decoder mask is formed by combining a causal mask, a padding mask and an optional packing mask. If decoder_causal_attention is passed, it makes the masking non-causal for positions that have value of 1. A prefix LM is applied to a dataset which has a notion of "inputs" and...
151,654
import abc import dataclasses import functools import inspect from typing import Any, Callable, Mapping, MutableMapping, Optional, Tuple, Union from absl import logging import clu.metrics as clu_metrics from flax import core as flax_core from flax import linen as nn from flax.core import scope as flax_scope from flax.l...
Remove the prefix portion and shift to the left by the prefix length. The example below uses non-decorated function definition, i.e., arrays do not have batch dimension. `jax.vmap` internally inserts the batch dimension at axis=0. The shape annotations do not include the batch dimension either. Example: ```python seque...
151,655
import abc import dataclasses import functools import inspect from typing import Any, Callable, Mapping, MutableMapping, Optional, Tuple, Union from absl import logging import clu.metrics as clu_metrics from flax import core as flax_core from flax import linen as nn from flax.core import scope as flax_scope from flax.l...
null
151,656
import abc import dataclasses import functools import inspect from typing import Any, Callable, Mapping, MutableMapping, Optional, Tuple, Union from absl import logging import clu.metrics as clu_metrics from flax import core as flax_core from flax import linen as nn from flax.core import scope as flax_scope from flax.l...
null
151,657
import os from typing import Callable, Optional import clu.data import jax from jax import random import numpy as np import t5.data.mixtures from t5x import models from t5x import partitioning from t5x import trainer as trainer_lib from t5x import utils import tensorflow as tf The provided code snippet includes neces...
Compiles and dump the HLO to model dir, with HLO text dumps.
151,658
import re from typing import Any, Mapping, Optional, Sequence, Tuple from absl import logging from flax import traverse_util def flatten_state_dict(state_dict, keep_empty_nodes: bool = False): """Flatten a dictionary until an array or tensorstore is reached. Args: state_dict: Optimizer state as nested dictionar...
Inserts new entries into `state_dict`. Args: state_dict: nested dict of optimizer state from_scratch_state: nested dict of entries to insert overwrite: if True, values present in both state_dict and from_scratch_state will be present in the result with the value taken from `from_scratch_state`. Returns: a nested dict l...
151,659
import re from typing import Any, Mapping, Optional, Sequence, Tuple from absl import logging from flax import traverse_util def flatten_state_dict(state_dict, keep_empty_nodes: bool = False): """Flatten a dictionary until an array or tensorstore is reached. Args: state_dict: Optimizer state as nested dictionar...
Applies an assignment map to a checkpoint optimizer state. In contrast to previous implementations, this has a switch whether to require that all rules match, and has somewhat-custom-but-sensible replacement rules: 1. old keys that are matched are removed. 2. old keys that don't match are retained. 3. if two new keys m...
151,660
import enum from typing import Mapping, Optional, Tuple, Union from flax.training import common_utils import jax import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `_cross_entropy_with_logits_fwd` function. Write a Python function `def _cross_entro...
Forward-mode of `cross_entropy_with_logits`.
151,661
import enum from typing import Mapping, Optional, Tuple, Union from flax.training import common_utils import jax import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `_cross_entropy_with_logits_bwd` function. Write a Python function `def _cross_entro...
Backward-mode of `cross_entropy_with_logits`.
151,662
import functools from typing import Any, Callable, Mapping, Optional, Tuple, Union import flax from flax import traverse_util import jax from jax import lax from jax import random import jax.numpy as jnp import numpy as np from t5x import binary_search class DecodingState: """Holds decoding state data. Used to comm...
Temperature sampling for language model generation. The temperature sampling is performed `num_decodes` times in a vectorized manner by expanding the batch dimension. This is similar to how beam search expands the batch dimension to process each batch element with multiple beams. This function dynamically updates the `...
151,663
import functools from typing import Any, Callable, Mapping, Optional, Tuple, Union import flax from flax import traverse_util import jax from jax import lax from jax import random import jax.numpy as jnp import numpy as np from t5x import binary_search def _pick_last_prompt_token(prompts): # prompts: i32[batch, leng...
null
151,664
import functools from typing import Any, Callable, Mapping, Optional, Tuple, Union import flax from flax import traverse_util import jax from jax import lax from jax import random import jax.numpy as jnp import numpy as np from t5x import binary_search NEG_INF = np.array(-1.0e7) NEG_INF_VALUE = -1.0e7 class DecodingSta...
Beam search for transformer machine translation. If `inputs` has non-zero entries, those values are not modified, i.e., the sampled values for those positions are discarded. This simulates the teacher forcing on the prefix positions. NOTE: While using initial_index with prompts of variable lengths To comply with the ma...
151,665
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Chooses a chunk shape that evenly divides write_shape. The chunk shape is chosen such that the total number of elements is less than or equal to `target_elements`, but is otherwise as large as possible. This uses a greedy algorithm that attempts to split the largest dimensions first. Args: write_shape: Write shape for ...
151,666
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
null
151,667
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Returns available dataset checkpoint step numbers in ascending order.
151,668
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Sync across all hosts/devices.
151,669
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Returns a step number and the parent directory.
151,670
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Get ts.Spec from array and name information.
151,671
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Makes a sharded array from non-sharded array if necessary. Args: arr: array to maybe shard. mesh: jax.sharding.Mesh. axes: mesh_axes. restore_dtype: type to restore as. params_on_devices: If true, the array will be placed on device. Otherwise, it will be stored in the host(s) RAM. Returns: Sharded or unsharded array.
151,672
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Iterate through summary event files and return metrics for `steps`.
151,673
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Applies transformations to the state dict and parameter infos PyTrees.
151,674
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
null
151,675
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Create SaveArgs for Orbax saving.
151,676
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Create RestoreArgs for Orbax restoration.
151,677
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Construct _OrbaxParamInfo tree for TrainState parameters.
151,678
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Construct transformations and restoration arguments for Orbax classes.
151,679
import asyncio import dataclasses import functools import os import re import subprocess import time from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union from absl import logging import clu.data from etils import epath import flax from flax import serialization from fl...
Restore from a TensorFlow-based T5 checkpoint.
151,680
import enum import re import typing from typing import Any, Mapping, Optional, Sequence, Tuple, Union from absl import logging from flax import struct from flax.core import freeze from flax.core import FrozenDict from flax.core import unfreeze from flax.serialization import from_state_dict from flax.serialization impor...
null
151,681
import enum import re import typing from typing import Any, Mapping, Optional, Sequence, Tuple, Union from absl import logging from flax import struct from flax.core import freeze from flax.core import FrozenDict from flax.core import unfreeze from flax.serialization import from_state_dict from flax.serialization impor...
null
151,682
import enum import re import typing from typing import Any, Mapping, Optional, Sequence, Tuple, Union from absl import logging from flax import struct from flax.core import freeze from flax.core import FrozenDict from flax.core import unfreeze from flax.serialization import from_state_dict from flax.serialization impor...
null
151,683
import dataclasses import functools import inspect import itertools import json import os import os.path import typing from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union from absl import logging from flax.core import frozen_dict import flax.traverse_util import jax from jax.ex...
Builds a function based on the config task to tokenize and batch the input text.