id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
22,523
from __future__ import annotations import json import multiprocessing import os from copy import copy from logging import getLogger from pathlib import Path import PySimpleGUI as sg import sounddevice as sd import soundfile as sf import torch from pebble import ProcessFuture, ProcessPool from . import __version__ from ...
null
22,524
from __future__ import annotations import json import multiprocessing import os from copy import copy from logging import getLogger from pathlib import Path import PySimpleGUI as sg import sounddevice as sd import soundfile as sf import torch from pebble import ProcessFuture, ProcessPool from . import __version__ from ...
null
22,525
from __future__ import annotations import json import multiprocessing import os from copy import copy from logging import getLogger from pathlib import Path import PySimpleGUI as sg import sounddevice as sd import soundfile as sf import torch from pebble import ProcessFuture, ProcessPool from . import __version__ from ...
null
22,526
import os import sys from logging import DEBUG, INFO, StreamHandler, basicConfig, captureWarnings, getLogger from pathlib import Path from rich.logging import RichHandler LOGGER_INIT = False def is_notebook(): try: from IPython import get_ipython if "IPKernelApp" not in get_ipython().config: # prag...
null
22,527
from typing import List, Tuple import sphinx from docutils import nodes from docutils.parsers.rst import directives from docutils.statemachine import ViewList from sphinx.util.docutils import SphinxDirective class CodeDiffDirective(SphinxDirective): has_content = True option_spec = { 'title_left': directives.un...
null
22,528
import importlib import sphinx import sphinx.ext.autosummary.generate as ag from docutils import nodes from docutils.parsers.rst import directives from docutils.statemachine import ViewList from sphinx.util.docutils import SphinxDirective from docs.conf_sphinx_patch import generate_autosummary_content def generate_aut...
null
22,529
import importlib import sphinx import sphinx.ext.autosummary.generate as ag from docutils import nodes from docutils.parsers.rst import directives from docutils.statemachine import ViewList from sphinx.util.docutils import SphinxDirective from docs.conf_sphinx_patch import generate_autosummary_content class FlaxModuleD...
null
22,530
import collections import os from absl import logging from clu import metric_writers from clu import periodic_actions from flax import linen as nn from flax.training import checkpoints from flax.training import common_utils import jax from jax import random import jax.numpy as jnp from jax.sharding import PartitionSpec...
Execute psum on in_tree"s leaves over one device per host.
22,531
import collections import os from absl import logging from clu import metric_writers from clu import periodic_actions from flax import linen as nn from flax.training import checkpoints from flax.training import common_utils import jax from jax import random import jax.numpy as jnp from jax.sharding import PartitionSpec...
Runs a training and evaluation loop. Args: config: Configuration to use. workdir: Working directory for checkpoints and TF summaries. If this contains checkpoint training will be resumed from the latest checkpoint.
22,532
from typing import Callable, Any, Optional from flax import linen as nn from flax import struct from jax import lax import jax.numpy as jnp import numpy as np def shift_right(x, axis=1): """Shift the input to the right by padding and slicing on axis.""" pad_widths = [(0, 0)] * len(x.shape) pad_widths[axis] = (1, ...
Shift inputs and replace EOS by 0 for packed inputs.
22,533
from typing import Callable, Any, Optional from flax import linen as nn from flax import struct from jax import lax import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `sinusoidal_init` function. Write a Python function `def sinusoidal_init(max_len=...
1D Sinusoidal Position Embedding Initializer. Args: max_len: maximum possible length for the input. min_scale: float: minimum frequency-scale in sine grating. max_scale: float: maximum frequency-scale in sine grating. Returns: output: init function returning `(1, max_len, d_feature)`
22,534
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the default hyperparameter configuration. Here is the function: def get_config(): """Get the default hyperparame...
Get the default hyperparameter configuration.
22,535
import functools from typing import Any, Dict, Tuple from absl import app from absl import flags from absl import logging from clu import metric_writers from flax import linen as nn from flax.training import train_state import jax import jax.numpy as jnp import optax import models from input_pipeline import CharacterTa...
Trains for a fixed number of steps and decode during training.
22,536
import os from typing import Any, Dict, Iterable, Tuple, Optional from absl import logging from clu import checkpoint from clu import metric_writers from clu import metrics from clu import parameter_overview from clu import periodic_actions import flax import flax.core import flax.linen as nn from flax.training import ...
Returns a binary array indicating where predictions match the labels.
22,537
import os from typing import Any, Dict, Iterable, Tuple, Optional from absl import logging from clu import checkpoint from clu import metric_writers from clu import metrics from clu import parameter_overview from clu import periodic_actions import flax import flax.core import flax.linen as nn from flax.training import ...
Execute model training and evaluation loop. Args: config: Hyperparameter configuration for training and evaluation. workdir: Directory where the TensorBoard summaries are written to. Returns: The train state (which includes the `.params`).
22,538
from typing import Callable, Sequence from flax import linen as nn import jax.numpy as jnp import jraph The provided code snippet includes necessary dependencies for implementing the `add_graphs_tuples` function. Write a Python function `def add_graphs_tuples( graphs: jraph.GraphsTuple, other_graphs: jraph.GraphsT...
Adds the nodes, edges and global features from other_graphs to graphs.
22,539
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the default hyperparameter configuration. Here is the function: def get_config(): """Get the default hyperparame...
Get the default hyperparameter configuration.
22,540
import ml_collections def sweep(add): for add_virtual_node in (True, False): for add_undirected_edges in (True, False): for add_self_loops in (True, False): for layer_norm in (True, False): for skip_connections in (True, False): add( add_virtual_node=add_virtua...
null
22,541
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the hyperparameter configuration for the GraphNetwork model. Here is the function: def get_config(): """Get the ...
Get the hyperparameter configuration for the GraphNetwork model.
22,542
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the default hyperparameter configuration. Here is the function: def get_config(): """Get the default hyperparame...
Get the default hyperparameter configuration.
22,543
import collections import gymnasium as gym import numpy as np import seed_rl_atari_preprocessing The provided code snippet includes necessary dependencies for implementing the `get_num_actions` function. Write a Python function `def get_num_actions(game: str)` to solve the following problem: Get the number of possible...
Get the number of possible actions of a given Atari game. This determines the number of outputs in the actor part of the actor-critic model.
22,544
import functools from typing import Any, Callable from absl import logging import flax from flax import linen as nn import agent import models import test_episodes from flax.metrics import tensorboard from flax.training import checkpoints from flax.training import train_state import jax import jax.numpy as jnp import m...
Main training loop. Args: model: the actor-critic model config: object holding hyperparameters and the training information model_dir: path to dictionary where checkpoints and logging info are stored Returns: optimizer: the trained optimizer
22,545
import collections import functools import multiprocessing from typing import Any, Callable import flax import jax import numpy as np import env_utils The provided code snippet includes necessary dependencies for implementing the `rcv_action_send_exp` function. Write a Python function `def rcv_action_send_exp(conn, ga...
Run the remote agents. Receive action from the main learner, perform one step of simulation and send back collected experience.
22,546
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the default configuration. The default hyperparameters originate from PPO paper arXiv:1707.06347 and openAI baseline...
Get the default configuration. The default hyperparameters originate from PPO paper arXiv:1707.06347 and openAI baselines 2:: https://github.com/openai/baselines/blob/master/baselines/ppo2/defaults.py
22,547
import datetime import os import re import subprocess import time from typing import Sequence from absl import app from absl import flags FLAGS = flags.FLAGS timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') def generate_startup_file(vm_name: str) -> str: directory = os.path.dirname(os.path.abspath(__fil...
null
22,548
import datetime import os import re import subprocess import time from typing import Sequence from absl import app from absl import flags FLAGS = flags.FLAGS def launch_gce(*, vm_name: str, startup_script: str): # Note : Use `gcloud compute images list --project ml-images` to get a list # of available VM images. ...
null
22,549
import datetime import os import re import subprocess import time from typing import Sequence from absl import app from absl import flags FLAGS = flags.FLAGS def print_howto(login_args: Sequence[str]): print(f""" ############################################################################### ########################...
null
22,550
from absl import logging from flax import linen as nn from flax.metrics import tensorboard from flax.training import train_state import jax import jax.numpy as jnp import ml_collections import numpy as np import optax import tensorflow_datasets as tfds def apply_model(state, images, labels): """Computes gradients, lo...
Execute model training and evaluation loop. Args: config: Hyperparameter configuration for training and evaluation. workdir: Directory where the tensorboard summaries are written to. Returns: The train state (which includes the `.params`).
22,551
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the default hyperparameter configuration. Here is the function: def get_config(): """Get the default hyperparame...
Get the default hyperparameter configuration.
22,552
import ml_collections def metrics(): return []
null
22,553
from typing import Any, Callable, Dict, Iterable, Optional, Sequence, Tuple, Union from absl import logging from flax import struct from flax.metrics import tensorboard from flax.training import train_state import jax import jax.numpy as jnp import ml_collections import numpy as np import optax import tensorflow as tf ...
Execute model training and evaluation loop. Args: config: Hyperparameter configuration for training and evaluation. workdir: Directory where the tensorboard summaries are written to. Returns: The final train state that includes the trained parameters.
22,554
import time from typing import Iterable, Sequence from absl import logging import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_text as tftext import vocabulary The provided code snippet includes necessary dependencies for implementing the `get_tokenized_sequences` function. Write a Python func...
Returns tokenized sequences for vocabulary building.
22,555
import functools from typing import Any, Callable, Optional from flax import linen as nn import jax from jax import numpy as jnp Array = jnp.ndarray The provided code snippet includes necessary dependencies for implementing the `sequence_mask` function. Write a Python function `def sequence_mask(lengths: Array, max_le...
Computes a boolean mask over sequence positions for each given length. Example: ``` sequence_mask([1, 2], 3) [[True, False, False], [True, True, False]] ``` Args: lengths: The length of each sequence. <int>[batch_size] max_length: The width of the boolean mask. Must be >= max(lengths). Returns: A mask with shape: <bool...
22,556
import functools from typing import Any, Callable, Optional from flax import linen as nn import jax from jax import numpy as jnp Array = jnp.ndarray The provided code snippet includes necessary dependencies for implementing the `flip_sequences` function. Write a Python function `def flip_sequences(inputs: Array, lengt...
Flips a sequence of inputs along the time dimension. 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 padde...
22,557
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the default hyperparameter configuration. Here is the function: def get_config(): """Get the default hyperparame...
Get the default hyperparameter configuration.
22,558
from typing import Any, Dict, Optional from absl import logging import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_text as text import vocabulary The provided code snippet includes necessary dependencies for implementing the `vocab_to_hashtable` function. Write a Python fun...
Returns a TF lookup table (token -> ID) from a vocabulary.
22,559
from typing import Any, Dict, Optional from absl import logging import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_text as text import vocabulary The provided code snippet includes necessary dependencies for implementing the `vocab_to_inverse_hashtable` function. Write a Py...
Returns an inverse TF lookup table (ID -> token) from a vocabulary.
22,560
from typing import Any, Dict, Optional from absl import logging import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_text as text import vocabulary The provided code snippet includes necessary dependencies for implementing the `_is_text_field` function. Write a Python functio...
Identifies a text field when given a feature (name, type) pair.
22,561
from typing import Any, Dict, Optional from absl import logging import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_text as text import vocabulary The provided code snippet includes necessary dependencies for implementing the `_is_class_label` function. Write a Python functi...
Identifies a class label field when given a feature (name, type) pair.
22,562
from absl import logging from flax import linen as nn import input_pipeline import models import utils as vae_utils from flax.training import train_state import jax from jax import random import jax.numpy as jnp import ml_collections import optax import tensorflow_datasets as tfds def train_step(state, batch, z_rng, la...
Train and evaulate pipeline.
22,563
from flax import linen as nn from jax import random import jax.numpy as jnp def reparameterize(rng, mean, logvar): std = jnp.exp(0.5 * logvar) eps = random.normal(rng, logvar.shape) return mean + eps * std
null
22,564
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the default hyperparameter configuration. Here is the function: def get_config(): """Get the default hyperparame...
Get the default hyperparameter configuration.
22,565
import collections import functools import os from absl import logging from clu import metric_writers from clu import periodic_actions from flax import jax_utils from flax import linen as nn from flax.training import checkpoints from flax.training import common_utils from flax.training import dynamic_scale as dynamic_s...
Runs a training and evaluation loop. Args: config: Configuration to use. workdir: Working directory for checkpoints and TF summaries. If this contains checkpoint training will be resumed from the latest checkpoint.
22,566
import collections import math import re import sys import unicodedata import numpy as np def bleu_partial(ref_lines, hyp_lines, case_sensitive=False): """Compute n-gram statistics for two lists of references and translations.""" if len(ref_lines) != len(hyp_lines): raise ValueError( "Reference and tran...
Compute BLEU for two lists of reference and hypothesis translations.
22,567
from typing import Callable, Any, Optional from flax import linen as nn from flax import struct from jax import lax import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `shift_right` function. Write a Python function `def shift_right(x, axis=1)` to s...
Shift the input to the right by padding on axis 1.
22,569
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the default hyperparameter configuration. Here is the function: def get_config(): """Get the default hyperparame...
Get the default hyperparameter configuration.
22,570
import ml_collections def metrics(): return [ 'train_loss', 'eval_loss', 'bleu', 'eval_accuracy', 'train_accuracy', 'uptime', 'steps_per_sec', 'train_learning_rate', ]
null
22,571
import functools import os import time from absl import app from absl import flags from absl import logging from flax import jax_utils from flax import linen as nn from flax.metrics import tensorboard from flax.training import common_utils from flax.training import train_state import jax import jax.numpy as jnp from ja...
creates learning rate schedule. Interprets factors in the factors string which can consist of: * constant: interpreted as the constant value, * linear_warmup: interpreted as linear warmup until warmup_steps, * rsqrt_decay: divide by square root of max(step, warmup_steps) * decay_every: Every k steps decay the learning ...
22,572
import functools import os import time from absl import app from absl import flags from absl import logging from flax import jax_utils from flax import linen as nn from flax.metrics import tensorboard from flax.training import common_utils from flax.training import train_state import jax import jax.numpy as jnp from ja...
Perform a single training step.
22,573
import functools import os import time from absl import app from absl import flags from absl import logging from flax import jax_utils from flax import linen as nn from flax.metrics import tensorboard from flax.training import common_utils from flax.training import train_state import jax import jax.numpy as jnp from ja...
Expand batch to desired size by zeros with the shape of last slice.
22,574
from typing import Callable, Any, Optional from flax import linen as nn from flax import struct import jax.numpy as jnp import numpy as np The provided code snippet includes necessary dependencies for implementing the `sinusoidal_init` function. Write a Python function `def sinusoidal_init(max_len=2048)` to solve the ...
1D Sinusoidal Position Embedding Initializer. Args: max_len: maximum possible length for the input Returns: output: init function returning `(1, max_len, d_feature)`
22,575
import codecs import collections import enum import tensorflow as tf PAD = '<p>' PAD_ID = 0 UNKNOWN = '<u>' UNKNOWN_ID = 1 ROOT = '<r>' ROOT_ID = 2 class CoNLLAttributes(enum.Enum): """CoNLL attributre names and indices. A UD CoNLL file looks like: 1 They they PRON PRP Case=Nom|Number=Plur ...
Loads corpus and create vocabulary lists. Args: filename: file name of a corpus. max_num_forms: maximum number of tokens included. Returns: Dictionary containing named vocab dictionaries.
22,576
import codecs import collections import enum import tensorflow as tf def sentences_from_conll_data( corpus_filename, vocabs, attributes, max_sentence_length=1000 ): """Load and returns conll data in list format. Args: corpus_filename: filename of corpus. vocabs: dictionary of vocabs attributes: lis...
Combines sentences into a dataset of padded batches. Args: filename: file name of a corpus. vocabs: dictionary of dictionaries to map from strings to ids. attributes_input: attributes for the input. attributes_target: target attributes empty targets is not included. batch_size: the size of a batch. bucket_size: the siz...
22,577
import functools import time from typing import Any from absl import logging from clu import metric_writers from clu import periodic_actions from flax import jax_utils from flax.training import checkpoints from flax.training import common_utils from flax.training import dynamic_scale as dynamic_scale_lib from flax.trai...
Execute model training and evaluation loop. Args: config: Hyperparameter configuration for training and evaluation. workdir: Directory where the tensorboard summaries are written to. Returns: Final TrainState.
22,578
from configs import default as default_lib The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the hyperparameter configuration to train on 8 x Nvidia V100 GPUs. Here is the function: def ...
Get the hyperparameter configuration to train on 8 x Nvidia V100 GPUs.
22,579
import ml_collections The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the default hyperparameter configuration. Here is the function: def get_config(): """Get the default hyperparame...
Get the default hyperparameter configuration.
22,580
import ml_collections def metrics(): return [ 'train_loss', 'eval_loss', 'train_accuracy', 'eval_accuracy', 'steps_per_second', 'train_learning_rate', ]
null
22,581
from configs import default as default_lib The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the hyperparameter configuration to train on 8 x Nvidia V100 GPUs. Here is the function: def ...
Get the hyperparameter configuration to train on 8 x Nvidia V100 GPUs.
22,582
from configs import default as default_lib The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the hyperparameter configuration to train on TPUs. Here is the function: def get_config(): ...
Get the hyperparameter configuration to train on TPUs.
22,583
import jax from configs import default as default_lib The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem: Get the hyperparameter configuration for Fake data benchmark. Here is the function: de...
Get the hyperparameter configuration for Fake data benchmark.
22,584
from jax._src import traceback_util as jax_traceback_util from flax import config _flax_filter_tracebacks = config.flax_filter_frames _flax_exclusions = set() The provided code snippet includes necessary dependencies for implementing the `register_exclusion` function. Write a Python function `def register_exclusion(pa...
Marks a Flax source file for exclusion.
22,585
from jax._src import traceback_util as jax_traceback_util from flax import config _flax_filter_tracebacks = config.flax_filter_frames _flax_exclusions = set() The provided code snippet includes necessary dependencies for implementing the `hide_flax_in_tracebacks` function. Write a Python function `def hide_flax_in_tra...
Hides Flax internal stack frames in tracebacks.
22,586
from jax._src import traceback_util as jax_traceback_util from flax import config _flax_filter_tracebacks = config.flax_filter_frames _flax_exclusions = set() The provided code snippet includes necessary dependencies for implementing the `show_flax_in_tracebacks` function. Write a Python function `def show_flax_in_tra...
Shows Flax internal stack frames in tracebacks.
22,587
import contextlib import functools import os import numpy as np import tensorflow as tf from tensorboard.plugins.hparams import api as hparams_api from flax import io The provided code snippet includes necessary dependencies for implementing the `_flatten_dict` function. Write a Python function `def _flatten_dict(inp...
Flattens and simplifies dict such that it can be used by hparams. Args: input_dict: Input dict, e.g., from ConfigDict. parent_key: String used in recursion. sep: String used to separate parent and child keys. Returns: Flattened dict.
22,588
import contextlib import functools import os import numpy as np import tensorflow as tf from tensorboard.plugins.hparams import api as hparams_api from flax import io class SummaryWriter: """Saves data in event and summary protos for tensorboard.""" def __init__(self, log_dir, auto_flush=True): """Create a new...
No-flush variation of summary_writer.as_default().
22,589
import enum import threading from contextlib import contextmanager from typing import Any, Dict, List import jax import msgpack import numpy as np def to_state_dict(target) -> Dict[str, Any]: """Returns a dictionary with the state of the given target.""" if _is_namedtuple(target): ty = _NamedTuple else: t...
null
22,590
import enum import threading from contextlib import contextmanager from typing import Any, Dict, List import jax import msgpack import numpy as np def current_path(): """Current state_dict path during deserialization for error messages.""" return '/'.join(_error_context.path) def from_state_dict(target, state: Dict...
null
22,591
import enum import threading from contextlib import contextmanager from typing import Any, Dict, List import jax import msgpack import numpy as np def to_state_dict(target) -> Dict[str, Any]: """Returns a dictionary with the state of the given target.""" if _is_namedtuple(target): ty = _NamedTuple else: t...
null
22,592
import enum import threading from contextlib import contextmanager from typing import Any, Dict, List import jax import msgpack import numpy as np def current_path(): """Current state_dict path during deserialization for error messages.""" return '/'.join(_error_context.path) def from_state_dict(target, state: Dict...
null
22,593
import enum import threading from contextlib import contextmanager from typing import Any, Dict, List import jax import msgpack import numpy as np def to_state_dict(target) -> Dict[str, Any]: """Returns a dictionary with the state of the given target.""" if _is_namedtuple(target): ty = _NamedTuple else: t...
null
22,594
import enum import threading from contextlib import contextmanager from typing import Any, Dict, List import jax import msgpack import numpy as np def current_path(): """Current state_dict path during deserialization for error messages.""" return '/'.join(_error_context.path) def from_state_dict(target, state: Dict...
Rebuild namedtuple from serialized dict.
22,595
import enum import threading from contextlib import contextmanager from typing import Any, Dict, List import jax import msgpack import numpy as np def from_state_dict(target, state: Dict[str, Any], name: str = '.'): """Restores the state of the given target using a state dict. This function takes the current target...
Restore optimizer or other object from msgpack-serialized state-dict. Args: target: template object with state-dict registrations that matches the structure being deserialized from ``encoded_bytes``. encoded_bytes: msgpack serialized object structurally isomorphic to ``target``. Typically a flax model or optimizer. Ret...
22,596
import functools import re from typing import (Any, Callable, Mapping, Optional, Tuple) import flax from flax import linen as nn from flax import struct from flax.core.frozen_dict import freeze from flax.core.frozen_dict import unfreeze from flax.core.scope import ( CollectionFilter as CollectionFilter, PRNGSequenc...
Declares and returns a variable with logical axes in the current Module. See :mod:`flax.linen.module.variable` for original docstring. Args: collection: The name of the variable collection. name: The variable name. init_fn: The function that will be called to compute the initial value of this variable. This function wi...
22,597
import functools import re from typing import (Any, Callable, Mapping, Optional, Tuple) import flax from flax import linen as nn from flax import struct from flax.core.frozen_dict import freeze from flax.core.frozen_dict import unfreeze from flax.core.scope import ( CollectionFilter as CollectionFilter, PRNGSequenc...
Gets axis names for variables as logical PartitionSpecs. Args: axes_metadata: a single axes-metadata collection from a flax-initialized set of collections. Returns: Collection of Partitionspecs with logical axis names, with the "_axes" suffix on variable names removed to match original variable collection for annotatio...
22,598
import functools import re from typing import (Any, Callable, Mapping, Optional, Tuple) import flax from flax import linen as nn from flax import struct from flax.core.frozen_dict import freeze from flax.core.frozen_dict import unfreeze from flax.core.scope import ( CollectionFilter as CollectionFilter, PRNGSequenc...
Wrapped version of nn.scan that handles logical axis metadata.
22,599
import functools import re from typing import (Any, Callable, Mapping, Optional, Tuple) import flax from flax import linen as nn from flax import struct from flax.core.frozen_dict import freeze from flax.core.frozen_dict import unfreeze from flax.core.scope import ( CollectionFilter as CollectionFilter, PRNGSequenc...
Wrapped version of nn.vmap that handles logical axis metadata.
22,600
import collections import contextlib import dataclasses import enum import functools import threading from typing import Any, Callable, List, Optional, Sequence, Tuple, Union import jax from jax import lax from jax.experimental import maps from flax import struct from flax.core import meta from flax.typing import ( A...
Sets the global logical axis to mesh axis binding.
22,601
import collections import contextlib import dataclasses import enum import functools import threading from typing import Any, Callable, List, Optional, Sequence, Tuple, Union import jax from jax import lax from jax.experimental import maps from flax import struct from flax.core import meta from flax.typing import ( A...
Returns the global logical axis to mesh axis binding.
22,602
import collections import contextlib import dataclasses import enum import functools import threading from typing import Any, Callable, List, Optional, Sequence, Tuple, Union import jax from jax import lax from jax.experimental import maps from flax import struct from flax.core import meta from flax.typing import ( A...
Context manager for setting the logical to mesh axis bindings.
22,603
import collections import contextlib import dataclasses import enum import functools import threading from typing import Any, Callable, List, Optional, Sequence, Tuple, Union import jax from jax import lax from jax.experimental import maps from flax import struct from flax.core import meta from flax.typing import ( A...
Convert pytrees of logical PartitionSpecs to shardings.
22,604
import collections import contextlib import dataclasses import enum import functools import threading from typing import Any, Callable, List, Optional, Sequence, Tuple, Union import jax from jax import lax from jax.experimental import maps from flax import struct from flax.core import meta from flax.typing import ( A...
Version of jit's with_sharding_constraint that uses logical axis names.
22,605
import collections import contextlib import dataclasses import enum import functools import threading from typing import Any, Callable, List, Optional, Sequence, Tuple, Union import jax from jax import lax from jax.experimental import maps from flax import struct from flax.core import meta from flax.typing import ( A...
Wraps a function's return value with LogicallyPartitioned. Example:: >>> import flax.linen as nn >>> kernel_init = nn.with_logical_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 ...
22,606
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
Remove scopes and tracers from children.
22,607
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
null
22,608
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
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 ``Module``. For example we could create a version of ``Dense`` with a batch axis that does not share parameters:: >>> import flax.linen as nn >>> BatchDense = nn.vmap( ... nn.Dense, ...
22,609
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
Lifted version of ``jax.checkpoint``. Checkpointing is a technique for reducing memory usage by recomputing activations during backpropagation. When training large models, it can be helpful to checkpoint parts of the model to trade off memory usage for additional computation. Example:: >>> import jax >>> import jax.num...
22,610
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
Combines remat and 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:: >>> import flax.linen as nn >>> class BigModel(n...
22,611
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
A lifted version of ``jax.lax.scan``. See ``jax.lax.scan`` for the unlifted scan in Jax. To improve consistency with ``vmap``, this version of scan uses ``in_axes`` and ``out_axes`` to determine which arguments are scanned over and along which axis. ``scan`` distinguishes between 3 different types of values inside the ...
22,612
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
A lifted version of ``jax.vjp``. See ``jax.vjp`` for the unlifted vector-Jacobian product (backward gradient). Note that a gradient is returned for all variables in the collections specified by ``vjp_variables``. However, the backward function only expects a cotangent for the return value of ``fn``. If variables requir...
22,613
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
A limited, lifted equivalent of ``jax.grad``. Note that for this convenience function, gradients are only calculated for the function inputs, and not with respect to any module variables. The target function must return a scalar-valued output. For a more general lifted vjp, see ``nn.vjp`` for the lifted vector-Jacobian...
22,614
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
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 ``Module.variables``:: >>> import flax.linen as nn >>> import jax....
22,615
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
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 calli...
22,616
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
Labels a method for labelled traces in profiles. Note that it is better to use the `jax.named_scope` context manager directly to add names to JAX's metadata name stack. Args: class_fn: The class method to label. force: If True, the named_call transform is applied even if it is globally disabled. (e.g.: by calling `flax...
22,617
import dataclasses import functools import inspect from typing import ( Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from flax import core from flax import errors, struct, traceback_util from flax import serialization from flax.core import Scope, lift,...
A helper to manipulate boxed axis metadata. This is a helper to manipulate the *metadata* in boxed variables, similar to how lifted ``vmap`` and ``scan`` will handle the introduction and stripping of the new metadata axis across a transform boundary. Args: target: a ``Module`` or a function taking a ``Module`` as its f...
22,618
import dataclasses import enum import io from abc import ABC, abstractmethod from types import MappingProxyType from typing import ( Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Union, ) import jax import jax.numpy as jnp import numpy as np import rich.console impo...
Returns a function that creates a summary of the Module represented as a table. This function accepts most of the same arguments and internally calls `Module.init`, except that it returns a function of the form `(*args, **kwargs) -> str` where `*args` and `**kwargs` are passed to `method` (e.g. `__call__`) during the f...
22,619
import dataclasses import enum import io from abc import ABC, abstractmethod from types import MappingProxyType from typing import ( Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Union, ) import jax import jax.numpy as jnp import numpy as np import rich.console impo...
null
22,620
import functools import warnings from typing import Any, Callable, Optional, Union, overload import jax import jax.numpy as jnp from jax import lax, random from flax.linen import initializers from flax.linen.dtypes import promote_dtype from flax.linen.linear import ( DenseGeneral, default_kernel_init, ) from flax.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. .. note:: ``query``, ``key``, ``value`` needn't have any ba...
22,621
import functools import warnings from typing import Any, Callable, Optional, Union, overload import jax import jax.numpy as jnp from jax import lax, random from flax.linen import initializers from flax.linen.dtypes import promote_dtype from flax.linen.linear import ( DenseGeneral, default_kernel_init, ) from flax.l...
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 batc...
22,622
import functools import warnings from typing import Any, Callable, Optional, Union, overload import jax import jax.numpy as jnp from jax import lax, random from flax.linen import initializers from flax.linen.dtypes import promote_dtype from flax.linen.linear import ( DenseGeneral, default_kernel_init, ) from flax.l...
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,623
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...
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...