id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
29,033
import dataclasses from typing import Callable, Optional from acme.jax import networks as networks_lib from acme.jax import types from typing_extensions import Protocol The provided code snippet includes necessary dependencies for implementing the `identity_sample` function. Write a Python function `def identity_sampl...
Placeholder sampling function for non-distributional networks.
29,034
import dataclasses from typing import Callable, Optional from acme.jax import networks as networks_lib from acme.jax import types from typing_extensions import Protocol class BCPolicyNetwork: """Holds a pair of pure functions defining a policy network for BC. This is a feed-forward network taking params, obs, is_tr...
Converts a policy network from SAC/TD3/D4PG/.. into a BC policy network. Args: policy_network: FeedForwardNetwork taking the observation as input and returning action representation compatible with one of the BC losses. Returns: The BC policy network taking observation, is_training, key as input.
29,035
import dataclasses from typing import Callable, Optional from acme.jax import networks as networks_lib from acme.jax import types from typing_extensions import Protocol class BCPolicyNetwork: """Holds a pair of pure functions defining a policy network for BC. This is a feed-forward network taking params, obs, is_tr...
Converts a policy-value network (e.g. from PPO) into a BC policy network. Args: policy_value_network: FeedForwardNetwork taking the observation as input. Returns: The BC policy network taking observation, is_training, key as input.
29,036
from typing import Callable, Iterator from acme import types from acme.agents.jax.bc import learning from acme.agents.jax.bc import losses from acme.agents.jax.bc import networks as bc_networks from acme.jax import networks as networks_lib from acme.jax import utils import jax import optax The provided code snippet in...
Trains the given network with BC and returns the params. Args: make_demonstrations: A function (batch_size) -> iterator with demonstrations to be imitated. networks: Network taking (params, obs, is_training, key) as input loss: BC loss to use. num_steps: number of training steps Returns: The trained network params.
29,037
import time from typing import Dict, List, NamedTuple, Optional, Tuple, Union, Iterator import acme from acme import types from acme.agents.jax.bc import losses from acme.agents.jax.bc import networks as bc_networks from acme.jax import networks as networks_lib from acme.jax import utils from acme.utils import counting...
Creates loss metrics for logging.
29,038
import dataclasses from typing import Any, Callable, Optional, Tuple, Union from acme import types from acme.agents.jax.mbop import dataset from acme.jax import networks import jax import jax.numpy as jnp def mse(a: jnp.ndarray, b: jnp.ndarray) -> jnp.ndarray: """MSE distance.""" return jnp.mean(jnp.square(a - b)) ...
Returns the loss for the world model. Args: apply_fn: applies a transition model (o_t, a_t) -> (o_t+1, r), expects the leading axis to index the batch and the second axis to index the transition triplet (t-1, t, t+1). steps: RLDS dictionary of transition triplets as prepared by `rlds_loader.episode_to_timestep_batch`. ...
29,039
import dataclasses from typing import Any, Callable, Optional, Tuple, Union from acme import types from acme.agents.jax.mbop import dataset from acme.jax import networks import jax import jax.numpy as jnp def mse(a: jnp.ndarray, b: jnp.ndarray) -> jnp.ndarray: """MSE distance.""" return jnp.mean(jnp.square(a - b)) ...
Returns the loss for the policy prior. Args: apply_fn: applies a policy prior (o_t, a_t) -> a_t+1, expects the leading axis to index the batch and the second axis to index the transition triplet (t-1, t, t+1). steps: RLDS dictionary of transition triplets as prepared by `rlds_loader.episode_to_timestep_batch`. Returns:...
29,040
import dataclasses from typing import Any, Callable, Optional, Tuple, Union from acme import types from acme.agents.jax.mbop import dataset from acme.jax import networks import jax import jax.numpy as jnp def mse(a: jnp.ndarray, b: jnp.ndarray) -> jnp.ndarray: """MSE distance.""" return jnp.mean(jnp.square(a - b)) ...
Returns the loss for the n-step return model. Args: apply_fn: applies an n-step return model (o_t, a_t) -> r, expects the leading axis to index the batch and the second axis to index the transition triplet (t-1, t, t+1). steps: RLDS dictionary of transition triplets as prepared by `rlds_loader.episode_to_timestep_batch...
29,041
import dataclasses from typing import Any, Tuple from acme import specs from acme.jax import networks from acme.jax import utils import haiku as hk import jax.numpy as jnp import numpy as np class MBOPNetworks: """Container class to hold MBOP networks.""" world_model_network: WorldModelNetwork policy_prior_networ...
Creates networks used by the agent.
29,042
import functools import itertools from typing import Iterator, Optional from acme import types from acme.jax import running_statistics import jax import jax.numpy as jnp import rlds import tensorflow as tf import tree EPISODE_RETURN: str = 'episode_return' def episode_to_timestep_batch( episode: rlds.BatchedStep, ...
Process an existing dataset converting it to episode to 3-transitions. A 3-transition is an Transition with each attribute having an extra dimension of size 3, representing 3 consecutive timesteps. Each 3-step object will be in random order relative to each other. See `episode_to_timestep_batch` for more information. A...
29,043
import functools import itertools from typing import Iterator, Optional from acme import types from acme.jax import running_statistics import jax import jax.numpy as jnp import rlds import tensorflow as tf import tree PREVIOUS: int = 0 The provided code snippet includes necessary dependencies for implementing the `get...
Precomputes normalization statistics over a fixed number of batches. The iterator should contain batches of 3-transitions, i.e. with two leading dimensions, the first one denoting the batch dimension and the second one the previous, current and next timesteps. The statistics are calculated using the data of the previou...
29,044
import dataclasses import functools import itertools import time from typing import Any, Callable, Iterator, List, Optional from acme import core from acme import types from acme.agents.jax import bc from acme.agents.jax.mbop import ensemble from acme.agents.jax.mbop import losses as mbop_losses from acme.agents.jax.mb...
Creates an ensemble regressor learner from the base network. Args: name: Name of the learner used for logging and counters. num_networks: Number of networks in the ensemble. logger_fn: Constructs a logger for a label. counter: Parent counter object. rng_key: Random key. iterator: An iterator of time-batched transitions...
29,045
import dataclasses import functools from typing import Callable, Optional from acme import specs from acme.agents.jax.mbop import models from acme.jax import networks import jax from jax import random import jax.numpy as jnp The provided code snippet includes necessary dependencies for implementing the `return_weighte...
r"""Calculates return-weighted average over all trajectories. This will calculate the return-weighted average over a set of trajectories as defined on l.17 of Alg. 2 in the MBOP paper: [https://arxiv.org/abs/2008.05556]. Note: Clipping will be performed for `cum_reward` values > 80 to avoid NaNs. Args: action_trajector...
29,046
import dataclasses import functools from typing import Callable, Optional from acme import specs from acme.agents.jax.mbop import models from acme.jax import networks import jax from jax import random import jax.numpy as jnp The provided code snippet includes necessary dependencies for implementing the `return_top_k_a...
r"""Calculates the top-k average over all trajectories. This will calculate the top-k average over a set of trajectories as defined in the POIR Paper: Note: top-k average is more numerically stable than the weighted average. Args: action_trajectories: (n_trajectories, horizon, action_dim) tensor of action trajectories....
29,047
from typing import List, Mapping, Optional, Tuple from acme import adders from acme import core from acme import specs from acme.agents.jax import actor_core as actor_core_lib from acme.agents.jax import actors from acme.agents.jax.mbop import models from acme.agents.jax.mbop import mppi from acme.agents.jax.mbop impor...
Creates an actor core that uses ensemble models. Args: networks: MBOP networks. mppi_config: Planner hyperparameters. environment_spec: Used to initialize the initial trajectory data structure. mean_std: Used to undo normalization if the networks trained normalized. use_round_robin: Whether to use round robin or mean t...
29,048
from typing import List, Mapping, Optional, Tuple from acme import adders from acme import core from acme import specs from acme.agents.jax import actor_core as actor_core_lib from acme.agents.jax import actors from acme.agents.jax.mbop import models from acme.agents.jax.mbop import mppi from acme.agents.jax.mbop impor...
Creates an MBOP actor from an actor core. Args: actor_core: An MBOP actor core. random_key: JAX Random key. variable_source: The source to get networks parameters from. adder: An adder to add experiences to. The `extras` of the adder holds the state of the recurrent policy. If `has_extras=True` then the `extras` part r...
29,049
from typing import Callable from acme import types from acme.agents.jax.crr.networks import CRRNetworks from acme.jax import networks as networks_lib import jax.numpy as jnp def _compute_advantage(networks: CRRNetworks, policy_params: networks_lib.Params, critic_params: net...
Exponential advantage weigting; see equation (4) in CRR paper.
29,050
from typing import Callable from acme import types from acme.agents.jax.crr.networks import CRRNetworks from acme.jax import networks as networks_lib import jax.numpy as jnp def _compute_advantage(networks: CRRNetworks, policy_params: networks_lib.Params, critic_params: net...
Indicator advantage weighting; see equation (3) in CRR paper.
29,051
from typing import Callable from acme import types from acme.agents.jax.crr.networks import CRRNetworks from acme.jax import networks as networks_lib import jax.numpy as jnp class CRRNetworks: """Network and pure functions for the CRR agent..""" policy_network: networks_lib.FeedForwardNetwork critic_network: net...
Constant weights.
29,052
import dataclasses from typing import Callable, Tuple from acme import specs from acme.jax import networks as networks_lib from acme.jax import utils import haiku as hk import jax import jax.numpy as jnp import numpy as np class CRRNetworks: """Network and pure functions for the CRR agent..""" policy_network: netwo...
Creates networks used by the agent.
29,053
import dataclasses from typing import Callable, Optional, Tuple from acme import specs from acme.agents.jax import actor_core as actor_core_lib from acme.jax import networks as networks_lib from acme.jax import utils import haiku as hk import jax import jax.numpy as jnp import numpy as np class ValueDiceNetworks: """...
Returns a function that computes actions.
29,054
import dataclasses from typing import Callable, Optional, Tuple from acme import specs from acme.agents.jax import actor_core as actor_core_lib from acme.jax import networks as networks_lib from acme.jax import utils import haiku as hk import jax import jax.numpy as jnp import numpy as np class ValueDiceNetworks: """...
Creates networks used by the agent.
29,055
import functools import time from typing import Any, Dict, Iterator, List, Mapping, NamedTuple, Optional, Tuple import acme from acme import types from acme.agents.jax.value_dice import networks as value_dice_networks from acme.jax import networks as networks_lib from acme.jax import utils from acme.utils import counti...
Orthogonal regularization. See equation (3) in https://arxiv.org/abs/1809.11096. Args: params: Dictionary of parameters to apply regualization for. Returns: A regularization loss term.
29,056
import threading from typing import Callable, Generic, Iterator, List, Optional, Sequence from acme import adders from acme import core from acme import specs from acme import types from acme.agents.jax import builders from acme.agents.jax.pwil import adder as pwil_adder from acme.agents.jax.pwil import config as pwil_...
Fill the adder's replay buffer with expert transitions. Assumes that the demonstrations dataset stores transitions in order. Args: adder: the agent which adds the demonstrations. demonstrations: the expert demonstrations to iterate over. reward: if non-None, populates the environment reward entry of transitions. min_nu...
29,057
from typing import Callable, Generic, Iterator, List, Optional from acme import adders from acme import core from acme import specs from acme import types from acme.agents.jax import builders from acme.jax import networks as networks_lib from acme.jax import utils from acme.jax.imitation_learning_types import DirectPol...
Generator which creates the sample iterator for SQIL. Args: demonstration_iterator: Iterator of demonstrations. replay_iterator: Replay buffer sample iterator. Yields: Samples having a mix of demonstrations with reward 1 and replay samples with reward 0.
29,058
from acme import specs from acme.jax import networks as networks_lib IMPALANetworks = networks_lib.UnrollableNetwork The provided code snippet includes necessary dependencies for implementing the `make_atari_networks` function. Write a Python function `def make_atari_networks(env_spec: specs.EnvironmentSpec) -> IMPALA...
Builds default IMPALA networks for Atari games.
29,059
from typing import Generic, Mapping, Tuple from acme import specs from acme.agents.jax import actor_core as actor_core_lib from acme.agents.jax.impala import networks as impala_networks from acme.jax import networks as networks_lib from acme.jax import types as jax_types import chex import jax import jax.numpy as jnp I...
Creates an Impala ActorCore.
29,060
from typing import Dict, Iterator, List, Optional, Tuple import acme from acme import adders from acme import core from acme import specs from acme.adders import reverb as adders_reverb from acme.agents.jax import actor_core as actor_core_lib from acme.agents.jax import actors from acme.agents.jax import builders from ...
Returns a function that computes actions.
29,061
from typing import Tuple from acme import specs from acme.jax import networks as networks_lib import jax.numpy as jnp The provided code snippet includes necessary dependencies for implementing the `make_networks` function. Write a Python function `def make_networks( spec: specs.EnvironmentSpec) -> networks_lib.Fee...
Creates networks used by the agent. The model used by the ARS paper is a simple clipped linear model. Args: spec: an environment spec Returns: A FeedForwardNetwork network.
29,062
from typing import Tuple from acme import specs from acme.jax import networks as networks_lib import jax.numpy as jnp BEHAVIOR_PARAMS_NAME = 'policy' EVAL_PARAMS_NAME = 'eval' def make_policy_network( network: networks_lib.FeedForwardNetwork, eval_mode: bool = True) -> Tuple[str, networks_lib.FeedForwardNetwor...
null
29,063
import math from typing import List, Optional, Sequence from acme import core from acme import types import dm_env import numpy as np import reverb The provided code snippet includes necessary dependencies for implementing the `_calculate_num_learner_steps` function. Write a Python function `def _calculate_num_learner...
Calculates the number of learner steps to do at step=num_observations.
29,064
import copy import dataclasses import functools from typing import Iterator, List, Optional, Tuple, Union, Sequence from acme import adders from acme import core from acme import datasets from acme import specs from acme import types from acme.adders import reverb as reverb_adders from acme.agents import agent from acm...
Returns a replicator instance appropriate for the given accelerator. This caches the instance using functools.cache, so that only one replicator is instantiated per process and argument value. Args: accelerator: None, 'TPU', 'GPU', or 'CPU'. If None, the first available accelerator type will be chosen from ('TPU', 'GPU...
29,065
from typing import Mapping, Sequence from acme import specs from acme import types from acme.tf import networks from acme.tf import utils as tf2_utils import numpy as np import sonnet as snt The provided code snippet includes necessary dependencies for implementing the `make_default_networks` function. Write a Python ...
Creates networks used by the agent.
29,066
import time from typing import Dict, Iterator, List, Optional, Union, Sequence import acme from acme import types from acme.tf import losses from acme.tf import networks as acme_nets from acme.tf import savers as tf2_savers from acme.tf import utils as tf2_utils from acme.utils import counting from acme.utils import lo...
Computes the average gradient across replicas. This computes the gradient locally on this device, then copies over the gradients computed on the other replicas, and takes the average across replicas. This is faster than copying the gradients from TPU to CPU, and averaging them on the CPU (which is what we do for the lo...
29,067
import functools import time from typing import Dict, Iterator, List, Mapping, Union, Optional import acme from acme import specs from acme.adders import reverb as adders from acme.tf import losses from acme.tf import networks from acme.tf import savers as tf2_savers from acme.tf import utils as tf2_utils from acme.uti...
Compute priority as mixture of max and mean sequence errors.
29,068
import dataclasses import time from typing import Callable, List, Optional, Sequence import acme from acme import types from acme.tf import losses from acme.tf import networks from acme.tf import savers as tf2_savers from acme.tf import utils as tf2_utils from acme.utils import counting from acme.utils import loggers i...
Compute loss and sampled Q-values for distributional critics.
29,069
import dataclasses import time from typing import Callable, List, Optional, Sequence import acme from acme import types from acme.tf import losses from acme.tf import networks from acme.tf import savers as tf2_savers from acme.tf import utils as tf2_utils from acme.utils import counting from acme.utils import loggers i...
Compute loss and sampled Q-values for (non-distributional) critics.
29,070
import dataclasses from typing import Callable, Dict from acme.agents.tf.mcts import models from acme.agents.tf.mcts import types import numpy as np class Node: """A MCTS node.""" reward: float = 0. visit_count: int = 0 terminal: bool = False prior: float = 1. total_value: float = 0. children: Dict[types....
Does Monte Carlo tree search (MCTS), AlphaZero style.
29,071
import dataclasses from typing import Callable, Dict from acme.agents.tf.mcts import models from acme.agents.tf.mcts import types import numpy as np class Node: """A MCTS node.""" reward: float = 0. visit_count: int = 0 terminal: bool = False prior: float = 1. total_value: float = 0. children: Dict[types....
Breadth-first search policy.
29,072
import dataclasses from typing import Callable, Dict from acme.agents.tf.mcts import models from acme.agents.tf.mcts import types import numpy as np class Node: """A MCTS node.""" reward: float = 0. visit_count: int = 0 terminal: bool = False prior: float = 1. total_value: float = 0. children: Dict[types....
PUCT search policy, i.e. UCT with 'prior' policy.
29,073
import dataclasses from typing import Callable, Dict from acme.agents.tf.mcts import models from acme.agents.tf.mcts import types import numpy as np class Node: """A MCTS node.""" reward: float = 0. visit_count: int = 0 terminal: bool = False prior: float = 1. total_value: float = 0. children: Dict[types....
Probability weighted by visit^{1/temp} of children nodes.
29,074
import functools from typing import Optional from acme import datasets from acme import specs from acme import types as acme_types from acme.adders import reverb as adders from acme.agents import agent from acme.agents.tf import actors from acme.agents.tf.r2d2 import learning from acme.tf import savers as tf2_savers fr...
Produce Reverb-like sequence from a full episode. Observations, actions, rewards and discounts have the same length. This function will ignore the first reward and discount and the last action. This function generates fake (all-zero) extras. See docs for reverb.SequenceAdder() for more details. Args: observations: [L, ...
29,075
from typing import Dict, List, Optional, Tuple from acme import core from acme import types from acme.adders import reverb as adders from acme.tf import losses from acme.tf import networks from acme.tf import savers as tf2_savers from acme.tf import utils as tf2_utils from acme.utils import counting from acme.utils imp...
Slice an embedding Tensor with action indices. Take embeddings of the form [batch_size, num_actions, embed_dim] and actions of the form [batch_size], and return the sliced embeddings like embeddings[:, actions, :]. Doing this my way because the comments in the official op are scary. Args: embeddings: Tensor of embeddin...
29,076
import collections from typing import Tuple, Optional, Dict, Iterable from acme import types from acme.tf import utils as tf2_utils import sonnet as snt import tensorflow as tf import tree def _nest_stack(list_of_nests, axis=0): """Convert a list of nests to a nest of stacked lists.""" return tree.map_structure(lam...
Unroll core along inputs for unroll_length steps. Note: for time-major input tensors whose leading dimension is less than unroll_length, `None` would be provided instead. Args: core: an instance of snt.Module. inputs: a `nest` of time-major input tensors. unroll_length: number of time steps to unroll. Returns: step_out...
29,077
import collections from typing import Tuple, Optional, Dict, Iterable from acme import types from acme.tf import utils as tf2_utils import sonnet as snt import tensorflow as tf import tree The provided code snippet includes necessary dependencies for implementing the `mask_out_restarting` function. Write a Python func...
Mask out `tensor` taken on the step that resets the environment. Args: tensor: a time-major 2-D `Tensor` of shape [T, B]. start_of_episode: a 2-D `Tensor` of shape [T, B] that contains the points where the episode restarts. Returns: tensor of shape [T, B] with elements are masked out according to step_types, restarting...
29,078
import functools from typing import Mapping, Sequence, Optional from acme import specs from acme import types from acme.agents.tf.svg0_prior import utils as svg0_utils from acme.tf import networks from acme.tf import utils as tf2_utils import numpy as np import sonnet as snt The provided code snippet includes necessar...
Creates networks used by the agent.
29,079
import functools from typing import Mapping, Sequence, Optional from acme import specs from acme import types from acme.agents.tf.svg0_prior import utils as svg0_utils from acme.tf import networks from acme.tf import utils as tf2_utils import numpy as np import sonnet as snt The provided code snippet includes necessar...
Creates networks used by the agent.
29,080
from typing import Mapping, Sequence from acme import specs from acme.tf import networks from acme.tf import utils as tf2_utils import numpy as np import sonnet as snt The provided code snippet includes necessary dependencies for implementing the `make_default_networks` function. Write a Python function `def make_defa...
Creates networks used by the agent.
29,081
from typing import Any, List from absl import flags from bsuite.environments import deep_sea import dm_env import numpy as np import tensorflow as tf import tree The provided code snippet includes necessary dependencies for implementing the `_nested_stack` function. Write a Python function `def _nested_stack(sequence:...
Stack nested elements in a sequence.
29,082
import copy import functools import operator from typing import Optional from acme import datasets from acme import specs from acme import types as acme_types from acme.adders import reverb as adders from acme.agents import agent from acme.agents.tf import actors from acme.agents.tf import dqn from acme.tf import utils...
Produce Reverb-like N-step transition from a full episode. Observations, actions, rewards and discounts have the same length. This function will ignore the first reward and discount and the last action. Args: observations: [L, ...] Tensor. actions: [L, ...] Tensor. rewards: [L] Tensor. discounts: [L] Tensor. n_step: nu...
29,083
import dataclasses from typing import Any, Callable, Dict, Iterator, Optional from acme import adders as adders_lib from acme import datasets from acme import specs from acme import types from acme.adders import reverb as adders import reverb class ReverbReplay: server: reverb.Server adder: adders_lib.Adder data_...
Creates a single-process replay infrastructure from an environment spec.
29,084
import dataclasses from typing import Any, Callable, Dict, Iterator, Optional from acme import adders as adders_lib from acme import datasets from acme import specs from acme import types from acme.adders import reverb as adders import reverb class ReverbReplay: server: reverb.Server adder: adders_lib.Adder data_...
Creates a single process queue from an environment spec and extra_spec.
29,085
import dataclasses from typing import Any, Callable, Dict, Iterator, Optional from acme import adders as adders_lib from acme import datasets from acme import specs from acme import types from acme.adders import reverb as adders import reverb class ReverbReplay: server: reverb.Server adder: adders_lib.Adder data_...
Single-process replay for sequence data from an environment spec.
29,086
from acme import specs from acme import types from acme.wrappers import base import dm_env import numpy as np import tree The provided code snippet includes necessary dependencies for implementing the `_convert_spec` function. Write a Python function `def _convert_spec(nested_spec: types.NestedSpec) -> types.NestedSpe...
Convert a nested spec.
29,087
from acme import specs from acme import types from acme.wrappers import base import dm_env import numpy as np import tree The provided code snippet includes necessary dependencies for implementing the `_convert_value` function. Write a Python function `def _convert_value(nested_value: types.Nest) -> types.Nest` to sol...
Convert a nested value given a desired nested spec.
29,088
import os.path import tempfile from typing import Callable, Optional, Sequence, Tuple, Union from acme.utils import paths from acme.wrappers import base import dm_env import matplotlib import matplotlib.animation as anim import matplotlib.pyplot as plt import numpy as np The provided code snippet includes necessary ...
Generates a matplotlib animation from a stack of frames.
29,089
from typing import Any from acme.wrappers import base import dm_env from dm_env import specs import numpy as np import tree def _expand_scalar_spec_shape(spec: specs.Array) -> specs.Array: if not spec.shape: # NOTE: This line upcasts the spec to an Array to avoid edge cases (as in # DiscreteSpec) where we ca...
null
29,090
from typing import Any from acme.wrappers import base import dm_env from dm_env import specs import numpy as np import tree def _expand_scalar_array_shape(array: np.ndarray) -> np.ndarray: return array if array.shape else np.expand_dims(array, axis=-1)
null
29,091
from typing import Any, Dict, List, Optional from acme import specs from acme import types import dm_env import gym from gym import spaces import numpy as np import tree The provided code snippet includes necessary dependencies for implementing the `_convert_to_spec` function. Write a Python function `def _convert_to_...
Converts an OpenAI Gym space to a dm_env spec or nested structure of specs. Box, MultiBinary and MultiDiscrete Gym spaces are converted to BoundedArray specs. Discrete OpenAI spaces are converted to DiscreteArray specs. Tuple and Dict spaces are recursively converted to tuples and dictionaries of specs. Args: space: Th...
29,092
from typing import Callable, Sequence import dm_env The provided code snippet includes necessary dependencies for implementing the `wrap_all` function. Write a Python function `def wrap_all( environment: dm_env.Environment, wrappers: Sequence[Callable[[dm_env.Environment], dm_env.Environment]], ) -> dm_env.Env...
Given an environment, wrap it in a list of wrappers.
29,093
from typing import Sequence, Optional from acme import types from acme.wrappers import base import dm_env import numpy as np import tree The provided code snippet includes necessary dependencies for implementing the `_concat` function. Write a Python function `def _concat(values: types.NestedArray) -> np.ndarray` to s...
Concatenates the leaves of `values` along the leading dimension. Treats scalars as 1d arrays and expects that the shapes of all leaves are the same except for the leading dimension. Args: values: the nested arrays to concatenate. Returns: The concatenated array.
29,094
from typing import Sequence, Optional from acme import types from acme.wrappers import base import dm_env import numpy as np import tree The provided code snippet includes necessary dependencies for implementing the `_zeros_like` function. Write a Python function `def _zeros_like(nest, dtype=None)` to solve the follow...
Generate a nested NumPy array according to spec.
29,095
from typing import Any, Dict, List, Optional import warnings from acme import specs from acme import types from acme import wrappers from acme.multiagent import types as ma_types from acme.wrappers import multiagent_dict_key_wrapper import dm_env import gym from gym import spaces import jax import numpy as np import tr...
Converts multigrid Gym space to an Acme multiagent spec. Args: space: The Gym space to convert. num_agents: the number of agents. name: Optional name to apply to all return spec(s). Returns: A dm_env spec or nested structure of specs, corresponding to the input space.
29,096
from typing import Any, Dict, List, Optional import warnings from acme import specs from acme import types from acme import wrappers from acme.multiagent import types as ma_types from acme.wrappers import multiagent_dict_key_wrapper import dm_env import gym from gym import spaces import jax import numpy as np import tr...
Returns multigrid observations converted to agent-index-first format. By default, multigrid observations are structured as: observation['image'][agent_index] observation['direction'][agent_index] ... However, multiagent Acme expects observations with agent indices first: observation[agent_index]['image'] observation[ag...
29,097
from acme import specs from acme import types from acme.wrappers import base import dm_env import numpy as np import tree The provided code snippet includes necessary dependencies for implementing the `_convert_spec` function. Write a Python function `def _convert_spec(nested_spec: types.NestedSpec) -> types.NestedSpe...
Converts all bounded specs in nested spec to the canonical scale.
29,098
from acme import specs from acme import types from acme.wrappers import base import dm_env import numpy as np import tree The provided code snippet includes necessary dependencies for implementing the `_scale_nested_action` function. Write a Python function `def _scale_nested_action( nested_action: types.NestedArr...
Converts a canonical nested action back to the given nested action spec.
29,099
import dataclasses from typing import Dict, Sequence, Tuple, Union from acme.tf.losses import mpo import sonnet as snt import tensorflow as tf import tensorflow_probability as tfp The provided code snippet includes necessary dependencies for implementing the `compute_weights_and_temperature_loss` function. Write a Pyt...
Computes normalized importance weights for the policy optimization. Args: q_values: Q-values associated with the actions sampled from the target policy; expected shape [N, B, K]. epsilons: Desired per-objective constraints on the KL between the target and non-parametric policies; expected shape [K]. temperature: Per-ob...
29,100
from typing import Dict, Tuple, Union import sonnet as snt import tensorflow as tf import tensorflow_probability as tfp The provided code snippet includes necessary dependencies for implementing the `compute_weights_and_temperature_loss` function. Write a Python function `def compute_weights_and_temperature_loss( ...
Computes normalized importance weights for the policy optimization. Args: q_values: Q-values associated with the actions sampled from the target policy; expected shape [N, B]. epsilon: Desired constraint on the KL between the target and non-parametric policies. temperature: Scalar used to temper the Q-values before com...
29,101
from typing import Dict, Tuple, Union import sonnet as snt import tensorflow as tf import tensorflow_probability as tfp The provided code snippet includes necessary dependencies for implementing the `compute_nonparametric_kl_from_normalized_weights` function. Write a Python function `def compute_nonparametric_kl_from_...
Estimate the actualized KL between the non-parametric and target policies.
29,102
from typing import Dict, Tuple, Union import sonnet as snt import tensorflow as tf import tensorflow_probability as tfp The provided code snippet includes necessary dependencies for implementing the `compute_cross_entropy_loss` function. Write a Python function `def compute_cross_entropy_loss( sampled_actions: tf....
Compute cross-entropy online and the reweighted target policy. Args: sampled_actions: samples used in the Monte Carlo integration in the policy loss. Expected shape is [N, B, ...], where N is the number of sampled actions and B is the number of sampled states. normalized_weights: target policy multiplied by the exponen...
29,103
from typing import Dict, Tuple, Union import sonnet as snt import tensorflow as tf import tensorflow_probability as tfp The provided code snippet includes necessary dependencies for implementing the `compute_parametric_kl_penalty_and_dual_loss` function. Write a Python function `def compute_parametric_kl_penalty_and_d...
Computes the KL cost to be added to the Lagragian and its dual loss. The KL cost is simply the alpha-weighted KL divergence and it is added as a regularizer to the policy loss. The dual variable alpha itself has a loss that can be minimized to adapt the strength of the regularizer to keep the KL between consecutive upd...
29,104
from acme.tf import networks import tensorflow as tf def l2_project( # pylint: disable=invalid-name Zp: tf.Tensor, P: tf.Tensor, Zq: tf.Tensor, ) -> tf.Tensor: """Project distribution (Zp, P) onto support Zq under the L2-metric over CDFs. This projection works for any support Zq. Let Kq be len(Zq) an...
Implements the Categorical Distributional TD(0)-learning loss.
29,105
from acme.tf import networks import tensorflow as tf def multiaxis_l2_project( # pylint: disable=invalid-name Zp: tf.Tensor, P: tf.Tensor, Zq: tf.Tensor, ) -> tf.Tensor: """Project distribution (Zp, P) onto support Zq under the L2-metric over CDFs. Let source support Zp's shape be described as (B, *C, ...
Implements a multi-axis categorical distributional TD(0)-learning loss. All arguments may have a leading batch axis, but q_tm1.logits, and one of r_t or d_t *must* have a leading batch axis. Args: q_tm1: Previous timestep's value distribution. r_t: Reward. d_t: Discount. q_t: Current timestep's value distribution. Retu...
29,106
from typing import Iterable, NamedTuple, Sequence import tensorflow as tf import trfl class LossCoreExtra(NamedTuple): targets: tf.Tensor errors: tf.Tensor def _compute_n_step_sequence_targets( r_t: tf.Tensor, pcont_t: tf.Tensor, bootstrap_value: tf.Tensor, n: int, ) -> tf.Tensor: """Computes n-st...
Helper function for computing transformed loss on sequences. Args: qs: 3-D tensor corresponding to the Q-values to be learned. Shape is [T+1, B, A]. targnet_qs: Like `qs`, but in the target network setting, these values should be computed by the target network. Shape is [T+1, B, A]. actions: 2-D tensor holding the indi...
29,107
import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `huber` function. Write a Python function `def huber(inputs: tf.Tensor, quadratic_linear_boundary: float) -> tf.Tensor` to solve the following problem: Calculates huber loss of `inputs`. For each value x in `inputs`,...
Calculates huber loss of `inputs`. For each value x in `inputs`, the following is calculated: ``` 0.5 * x^2 if |x| <= d 0.5 * d^2 + d * (|x| - d) if |x| > d ``` where d is `quadratic_linear_boundary`. Args: inputs: Input Tensor to calculate the huber loss on. quadratic_linear_boundary: The point where the huber loss fu...
29,108
from typing import Optional import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `dpg` function. Write a Python function `def dpg( q_max: tf.Tensor, a_max: tf.Tensor, tape: tf.GradientTape, dqda_clipping: Optional[float] = None, clip_norm: bool = Fa...
Deterministic policy gradient loss, similar to trfl.dpg.
29,109
import functools from typing import List, Optional, Union from acme import types from acme.utils import tree_utils import sonnet as snt import tensorflow as tf import tree The provided code snippet includes necessary dependencies for implementing the `batch_to_sequence` function. Write a Python function `def batch_to_...
Converts data between sequence-major and batch-major format.
29,110
import functools from typing import List, Optional, Union from acme import types from acme.utils import tree_utils import sonnet as snt import tensorflow as tf import tree def tile_tensor(tensor: tf.Tensor, multiple: int) -> tf.Tensor: """Tiles `multiple` copies of `tensor` along a new leading axis.""" rank = len(t...
Tiles tensors in a nested structure along a new leading axis.
29,111
import functools from typing import List, Optional, Union from acme import types from acme.utils import tree_utils import sonnet as snt import tensorflow as tf import tree The provided code snippet includes necessary dependencies for implementing the `to_numpy` function. Write a Python function `def to_numpy(nest: typ...
Converts a nest of Tensors to a nest of numpy arrays.
29,112
import functools from typing import List, Optional, Union from acme import types from acme.utils import tree_utils import sonnet as snt import tensorflow as tf import tree The provided code snippet includes necessary dependencies for implementing the `to_numpy_squeeze` function. Write a Python function `def to_numpy_s...
Converts a nest of Tensors to a nest of numpy arrays and squeeze axis.
29,113
import abc import datetime import os import pickle import time from typing import Mapping, Optional, Union from absl import logging from acme import core from acme.utils import signals from acme.utils import paths import sonnet as snt import tensorflow as tf import tree from tensorflow.python.saved_model import revived...
Create a thin wrapper around a module to make it snapshottable.
29,114
from typing import Callable, Optional, Sequence, Union import sonnet as snt import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `_preprocess_inputs` function. Write a Python function `def _preprocess_inputs(inputs: tf.Tensor, output_dtype: tf.DType) -> tf.Tensor` to s...
Returns the `Tensor` corresponding to the preprocessed inputs.
29,115
from typing import Callable, Optional, Sequence from acme import types from acme.tf import utils as tf2_utils from acme.tf.networks import base import sonnet as snt import tensorflow as tf def _uniform_initializer(): return tf.initializers.VarianceScaling( distribution='uniform', mode='fan_out', scale=0.333)
null
29,116
from typing import Dict, Union from acme import types from acme.adders.reverb import base import jax import jax.numpy as jnp import numpy as np import tree def zeros_like(x: Union[np.ndarray, int, float, np.number]): """Returns a zero-filled object of the same (d)type and shape as the input. The difference between ...
Return a list of steps with the final step zero-filled.
29,117
from typing import Dict, Union from acme import types from acme.adders.reverb import base import jax import jax.numpy as jnp import numpy as np import tree The provided code snippet includes necessary dependencies for implementing the `calculate_priorities` function. Write a Python function `def calculate_priorities( ...
Helper used to calculate the priority of a Trajectory or Transition. This helper converts the leaves of the Trajectory or Transition from `reverb.TrajectoryColumn` objects into numpy arrays. The converted Trajectory or Transition is then passed into each of the functions in `priority_fns`. Args: priority_fns: a mapping...
29,118
import itertools import time from typing import Callable, List, Optional, Sequence, Sized from absl import logging from acme import specs from acme import types from acme.adders import base as adders_base from acme.adders.reverb import base as reverb_base from acme.adders.reverb import sequence as sequence_adder from a...
null
29,119
import itertools import time from typing import Callable, List, Optional, Sequence, Sized from absl import logging from acme import specs from acme import types from acme.adders import base as adders_base from acme.adders.reverb import base as reverb_base from acme.adders.reverb import sequence as sequence_adder from a...
Generates configs that replicates the behaviour of NStepTransitionAdder. Please see the docstring of NStepTransitionAdder for more details. NOTE! In contrast to NStepTransitionAdder, the trajectories written by the `StructuredWriter` does not include the precomputed cumulative reward and discounts. Instead the trajecto...
29,120
import itertools import time from typing import Callable, List, Optional, Sequence, Sized from absl import logging from acme import specs from acme import types from acme.adders import base as adders_base from acme.adders.reverb import base as reverb_base from acme.adders.reverb import sequence as sequence_adder from a...
Converts an (n+1)-step trajectory into an n-step transition.
29,121
import abc import time from typing import Callable, Iterable, Mapping, NamedTuple, Optional, Sized, Union, Tuple from absl import logging from acme import specs from acme import types from acme.adders import base import dm_env import numpy as np import reverb import tensorflow as tf import tree def spec_like_to_tensor...
null
29,122
import copy from typing import Optional, Tuple from acme import specs from acme import types from acme.adders.reverb import base from acme.adders.reverb import utils from acme.utils import tree_utils import numpy as np import reverb import tree The provided code snippet includes necessary dependencies for implementing...
Like np.broadcast, but for specs.Array. Args: *args: one or more specs.Array instances. Returns: A specs.Array with the broadcasted shape and dtype of the specs in *args.
29,123
import enum from acme import types from acme.datasets import reverb as reverb_dataset import reverb import tensorflow as tf class CropType(enum.Enum): """Types of cropping supported by the image aumentation transforms. BILINEAR: Continuously randomly located then bilinearly interpolated. ALIGNED: Aligned with inp...
Pad and crop image to mimic a random translation with mirroring at edges. This implements the image augmentation from section 3.1 in (Kostrikov et al.) https://arxiv.org/abs/2004.13649. Args: img: The image to pad and crop. Its dimensions are [..., H, W, C] where ... are batch dimensions (if it has any). pad_size: The ...
29,124
import enum from acme import types from acme.datasets import reverb as reverb_dataset import reverb import tensorflow as tf import reverb The provided code snippet includes necessary dependencies for implementing the `make_transform` function. Write a Python function `def make_transform( observation_transform: ty...
Creates the appropriate dataset transform for the given signature.
29,125
import logging from typing import Any, Iterator, Optional, Tuple, Sequence from acme import specs from acme import types from flax import jax_utils import jax import jax.numpy as jnp import numpy as np import rlds import tensorflow as tf import tensorflow_datasets as tfds def _dataset_size_upperbound(dataset: tf.data....
null
29,126
import logging from typing import Any, Iterator, Optional, Tuple, Sequence from acme import specs from acme import types from flax import jax_utils import jax import jax.numpy as jnp import numpy as np import rlds import tensorflow as tf import tensorflow_datasets as tfds _BEST_DIVISOR = 128 def _pad(x: jnp.ndarray) -...
null
29,127
import logging from typing import Any, Iterator, Optional, Tuple, Sequence from acme import specs from acme import types from flax import jax_utils import jax import jax.numpy as jnp import numpy as np import rlds import tensorflow as tf import tensorflow_datasets as tfds def _unpad(x: jnp.ndarray, shape: Sequence[int...
null
29,128
import time from typing import Sequence from absl import app from absl import logging from acme import adders from acme import specs from acme.adders import reverb as adders_reverb from acme.datasets import reverb as datasets from acme.testing import fakes import numpy as np import reverb from reverb import rate_limite...
Create tables to insert data into.
29,129
import time from typing import Sequence from absl import app from absl import logging from acme import adders from acme import specs from acme.adders import reverb as adders_reverb from acme.datasets import reverb as datasets from acme.testing import fakes import numpy as np import reverb from reverb import rate_limite...
null
29,130
import collections import os from typing import Callable, Mapping, Optional, Union from acme import specs from acme import types from acme.adders import reverb as adders import reverb import tensorflow as tf Transform = Callable[[reverb.ReplaySample], reverb.ReplaySample] import reverb The provided code snippet inclu...
Make a TensorFlow dataset backed by a Reverb trajectory replay service. Arguments: server_address: Address of the Reverb server. batch_size: Batch size of the returned dataset. prefetch_size: The number of elements to prefetch from the original dataset. Note that Reverb may do some internal prefetching in addition to t...
29,131
import operator import time from typing import Optional, Sequence from acme import core from acme.utils import counting from acme.utils import loggers from acme.wrappers import open_spiel_wrapper import dm_env from dm_env import specs import numpy as np import tree import pyspiel def _generate_zeros_from_spec(spec: sp...
null
29,132
from acme import types import jax import numpy as np import reverb from reverb import item_selectors from reverb import rate_limiters from reverb import reverb_types import tensorflow as tf import tree def _make_selector_from_key_distribution_options( options) -> reverb_types.SelectorType: """Returns a Selector f...
Build a replay table out of its specs in a TableInfo. Args: table_info: A TableInfo containing the Table specs. Returns: A reverb replay table matching the info specs.