code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def compute_feasibility_probability( observation: types.NestedTensor, constraints: Iterable[BaseConstraint], batch_size: types.Int, num_actions: int, action_mask: Optional[types.Tensor] = None, ) -> types.Float: """Helper function to compute the action feasibility probability.""" feasibility_pro...
Helper function to compute the action feasibility probability.
compute_feasibility_probability
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def construct_mask_from_multiple_sources( observation: types.NestedTensor, observation_and_action_constraint_splitter: types.Splitter, constraints: Iterable[BaseConstraint], max_num_actions: int, ) -> Optional[types.Tensor]: """Constructs an action mask from multiple sources. The sources include: ...
Constructs an action mask from multiple sources. The sources include: -- The action mask encoded in the observation, -- the `num_actions` feature restricting the number of actions per sample, -- the feasibility mask implied by constraints. The resulting mask disables all actions that are masked out in any o...
construct_mask_from_multiple_sources
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def __call__(self, observation, actions=None): """Returns the probability of input actions being feasible.""" batch_size = tf.shape(observation)[0] num_actions = self._action_spec.maximum - self._action_spec.minimum + 1 feasibility_prob = 0.5 * tf.ones([batch_size, num_actions], tf.float32) return f...
Returns the probability of input actions being feasible.
__call__
python
tensorflow/agents
tf_agents/bandits/policies/constraints_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints_test.py
Apache-2.0
def __call__(self, observation, actions=None): """Returns the probability of input actions being feasible.""" if actions is None: actions = tf.range(self._action_spec.minimum, self._action_spec.maximum) feasibility_prob = tf.cast(tf.greater(actions, 2), tf.float32) return feasibility_prob
Returns the probability of input actions being feasible.
__call__
python
tensorflow/agents
tf_agents/bandits/policies/constraints_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints_test.py
Apache-2.0
def get_number_of_trainable_elements(network: types.Network) -> types.Float: """Gets the total # of elements in the network's trainable variables. Args: network: A `types.Network`. Returns: The total number of elements in the network's trainable variables. """ num_elements_list = [] for var in net...
Gets the total # of elements in the network's trainable variables. Args: network: A `types.Network`. Returns: The total number of elements in the network's trainable variables.
get_number_of_trainable_elements
python
tensorflow/agents
tf_agents/bandits/policies/falcon_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/falcon_reward_prediction_policy.py
Apache-2.0
def _find_action_probabilities( greedy_action_prob: types.Tensor, other_actions_probs: types.Tensor, max_exploration_prob: float, ): """Finds action probabilities satisfying `max_exploration_prob`. Given action probabilities calculated by different values of the gamma parameter, this function attempt...
Finds action probabilities satisfying `max_exploration_prob`. Given action probabilities calculated by different values of the gamma parameter, this function attempts to find action probabilities at a specific gamma value such that non-greedy actions are chosen with at most `max_exploration_prob` probability. ...
_find_action_probabilities
python
tensorflow/agents
tf_agents/bandits/policies/falcon_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/falcon_reward_prediction_policy.py
Apache-2.0
def _get_number_of_allowed_actions( self, mask: Optional[types.Tensor] ) -> types.Float: """Gets the number of allowed actions. Args: mask: An optional mask represented by a tensor shaped as [batch_size, num_actions]. Returns: The number of allowed actions. It can be either a s...
Gets the number of allowed actions. Args: mask: An optional mask represented by a tensor shaped as [batch_size, num_actions]. Returns: The number of allowed actions. It can be either a scalar (when `mask` is None), or a tensor shaped as [batch_size].
_get_number_of_allowed_actions
python
tensorflow/agents
tf_agents/bandits/policies/falcon_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/falcon_reward_prediction_policy.py
Apache-2.0
def _compute_gamma( self, mask: Optional[types.Tensor], dtype: tf.DType, batch_size: int ) -> types.Float: """Computes the gamma parameter(s) in the sampling probability. This helper method implements a simple heuristic for computing the the gamma parameter in Step 2 of Algorithm 1 in the paper ...
Computes the gamma parameter(s) in the sampling probability. This helper method implements a simple heuristic for computing the the gamma parameter in Step 2 of Algorithm 1 in the paper https://arxiv.org/pdf/2003.12699.pdf. A higher gamma makes the action sampling distribution concentrate more on the g...
_compute_gamma
python
tensorflow/agents
tf_agents/bandits/policies/falcon_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/falcon_reward_prediction_policy.py
Apache-2.0
def scalarize_objectives( objectives_tensor: tf.Tensor, scalarizer: multi_objective_scalarizer.Scalarizer, ): """Scalarize a rank-3 objectives tensor into a rank-2 tensor. Scalarize an objective values tensor shaped as [batch_size, num_of_objectives, num_of_actions] along the second dimension into a ra...
Scalarize a rank-3 objectives tensor into a rank-2 tensor. Scalarize an objective values tensor shaped as [batch_size, num_of_objectives, num_of_actions] along the second dimension into a rank-2 tensor shaped as [batch_size, num_of_actions] Args: objectives_tensor: An objectives tensor to be scalarized. ...
scalarize_objectives
python
tensorflow/agents
tf_agents/bandits/policies/greedy_multi_objective_neural_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/greedy_multi_objective_neural_policy.py
Apache-2.0
def _predict( self, observation: types.NestedSpecTensorOrArray, step_type: types.SpecTensorOrArray, policy_state: Sequence[types.TensorSpec], ) -> Tuple[tf.Tensor, List[types.TensorSpec]]: """Predict the objectives using the policy's objective networks. Args: observation: The ob...
Predict the objectives using the policy's objective networks. Args: observation: The observation whose objectives are to be predicted. step_type: The `tf_agents.trajectories.time_step.StepType` for the input observation. policy_state: The states for the policy's objective networks. R...
_predict
python
tensorflow/agents
tf_agents/bandits/policies/greedy_multi_objective_neural_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/greedy_multi_objective_neural_policy.py
Apache-2.0
def __init__( self, observation_spec: types.NestedTensorSpec, kernel_weights: np.ndarray, bias: np.ndarray, ): """A simple linear network. Args: observation_spec: The observation specification. kernel_weights: A 2-d numpy array of shape [input_size, output_size]. bia...
A simple linear network. Args: observation_spec: The observation specification. kernel_weights: A 2-d numpy array of shape [input_size, output_size]. bias: A 1-d numpy array of shape [output_size].
__init__
python
tensorflow/agents
tf_agents/bandits/policies/greedy_multi_objective_neural_policy_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/greedy_multi_objective_neural_policy_test.py
Apache-2.0
def __init__(self, kernel_weights: np.ndarray, bias: np.ndarray): """A simple linear heteroscedastic network. Args: kernel_weights: A 2-d numpy array of shape [input_size, output_size]. bias: A 1-d numpy array of shape [output_size]. """ assert len(kernel_weights.shape) == 2 assert len(...
A simple linear heteroscedastic network. Args: kernel_weights: A 2-d numpy array of shape [input_size, output_size]. bias: A 1-d numpy array of shape [output_size].
__init__
python
tensorflow/agents
tf_agents/bandits/policies/greedy_multi_objective_neural_policy_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/greedy_multi_objective_neural_policy_test.py
Apache-2.0
def _action_distribution(self, mask, predicted_rewards): """Returns the action with largest predicted reward.""" # Argmax. batch_size = tf.shape(predicted_rewards)[0] if mask is not None: actions = policy_utilities.masked_argmax( predicted_rewards, mask, output_type=self.action_spec.dtyp...
Returns the action with largest predicted reward.
_action_distribution
python
tensorflow/agents
tf_agents/bandits/policies/greedy_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/greedy_reward_prediction_policy.py
Apache-2.0
def conjugate_gradient( a_mat: types.Tensor, b_mat: types.Tensor, tol: float = 1e-10 ) -> types.Float: """Returns `X` such that `A * X = B`. Implements the Conjugate Gradient method. https://en.wikipedia.org/wiki/Conjugate_gradient_method Args: a_mat: a Symmetric Positive Definite matrix, represented ...
Returns `X` such that `A * X = B`. Implements the Conjugate Gradient method. https://en.wikipedia.org/wiki/Conjugate_gradient_method Args: a_mat: a Symmetric Positive Definite matrix, represented as a `Tensor` of shape `[n, n]`. b_mat: a `Tensor` of shape `[n, k]`. tol: (float) desired toleran...
conjugate_gradient
python
tensorflow/agents
tf_agents/bandits/policies/linalg.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linalg.py
Apache-2.0
def while_exit_cond(i, x, p, r, rs_old, rs_new): """Exit the loop when n is reached or when the residual becomes small.""" del x # unused del p # unused del r # unused del rs_old # unused i_cond = tf.less(i, n) residual_cond = tf.greater(tf.reduce_max(tf.sqrt(rs_new)), tol) return tf...
Exit the loop when n is reached or when the residual becomes small.
while_exit_cond
python
tensorflow/agents
tf_agents/bandits/policies/linalg.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linalg.py
Apache-2.0
def simplified_woodbury_update( a_inv: types.Float, u: types.Float ) -> types.Float: """Returns `w` such that `inverse(a + u.T.dot(u)) = a_inv + w`. Makes use of the Woodbury matrix identity. See https://en.wikipedia.org/wiki/Woodbury_matrix_identity. **NOTE**: This implementation assumes that a_inv is sy...
Returns `w` such that `inverse(a + u.T.dot(u)) = a_inv + w`. Makes use of the Woodbury matrix identity. See https://en.wikipedia.org/wiki/Woodbury_matrix_identity. **NOTE**: This implementation assumes that a_inv is symmetric. Since it's too expensive to check symmetricity, the function silently outputs a wro...
simplified_woodbury_update
python
tensorflow/agents
tf_agents/bandits/policies/linalg.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linalg.py
Apache-2.0
def update_inverse(a_inv: types.Float, x: types.Float) -> types.Float: """Updates the inverse using the Woodbury matrix identity. Given a matrix `A` of size d-by-d and a matrix `X` of size k-by-d, this function computes the inverse of B = A + X^T X, assuming that the inverse of A is available. Reference: ...
Updates the inverse using the Woodbury matrix identity. Given a matrix `A` of size d-by-d and a matrix `X` of size k-by-d, this function computes the inverse of B = A + X^T X, assuming that the inverse of A is available. Reference: https://en.wikipedia.org/wiki/Woodbury_matrix_identity Args: a_inv: a...
update_inverse
python
tensorflow/agents
tf_agents/bandits/policies/linalg.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linalg.py
Apache-2.0
def _predict_mean_reward( self, theta: tf.Tensor, global_observation: tf.Tensor, arm_observations: Optional[tf.Tensor], ) -> tf.Tensor: """Predicts the mean reward using the theta vectors. Args: theta: A `tf.Tensor` of theta vectors, shaped as [num_models, overall_contex...
Predicts the mean reward using the theta vectors. Args: theta: A `tf.Tensor` of theta vectors, shaped as [num_models, overall_context_dim]. global_observation: A `tf.Tensor` shaped as [batch_size, self._global_context_dim]. arm_observations: An optional `tf.Tensor` shaped as [batc...
_predict_mean_reward
python
tensorflow/agents
tf_agents/bandits/policies/linear_bandit_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linear_bandit_policy.py
Apache-2.0
def _predict_mean_reward_and_variance( self, global_observation: tf.Tensor, arm_observations: Optional[tf.Tensor] ) -> Tuple[tf.Tensor, tf.Tensor]: """Predicts mean reward and variance. Args: global_observation: A `tf.Tensor` shaped as [batch_size, self._global_context_dim]. arm_obs...
Predicts mean reward and variance. Args: global_observation: A `tf.Tensor` shaped as [batch_size, self._global_context_dim]. arm_observations: An optional `tf.Tensor` shaped as [batch_size, self._num_actions, self._arm_context_dim]. Expected to be supplied only when self._accept...
_predict_mean_reward_and_variance
python
tensorflow/agents
tf_agents/bandits/policies/linear_bandit_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linear_bandit_policy.py
Apache-2.0
def _get_current_observation( self, global_observation, arm_observations, arm_index ): """Helper function to construct the observation for a specific arm. This function constructs the observation depending if the policy accepts per-arm features or not. If not, it simply returns the original observa...
Helper function to construct the observation for a specific arm. This function constructs the observation depending if the policy accepts per-arm features or not. If not, it simply returns the original observation. If yes, it concatenates the global observation with the observation of the arm indexed b...
_get_current_observation
python
tensorflow/agents
tf_agents/bandits/policies/linear_bandit_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linear_bandit_policy.py
Apache-2.0
def _split_observation(self, observation): """Splits the observation into global and arm observations.""" if self._accepts_per_arm_features: global_observation = observation[bandit_spec_utils.GLOBAL_FEATURE_KEY] arm_observations = observation[bandit_spec_utils.PER_ARM_FEATURE_KEY] if not arm_o...
Splits the observation into global and arm observations.
_split_observation
python
tensorflow/agents
tf_agents/bandits/policies/linear_bandit_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linear_bandit_policy.py
Apache-2.0
def pinball_loss( y_true: types.Tensor, y_pred: types.Tensor, weights: types.Float = 1.0, scope: Optional[Text] = None, loss_collection: tf.compat.v1.GraphKeys = tf.compat.v1.GraphKeys.LOSSES, reduction: tf.compat.v1.losses.Reduction = tf.compat.v1.losses.Reduction.SUM_BY_NONZERO_WEIGHTS, qu...
Adds a Pinball loss for quantile regression. ``` loss = quantile * (y_true - y_pred) if y_true > y_pred loss = (quantile - 1) * (y_true - y_pred) otherwise ``` See: https://en.wikipedia.org/wiki/Quantile_regression#Quantiles `weights` acts as a coefficient for the loss. If a scalar is provid...
pinball_loss
python
tensorflow/agents
tf_agents/bandits/policies/loss_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/loss_utils.py
Apache-2.0
def __init__( self, mixture_distribution: types.Distribution, policies: Sequence[tf_policy.TFPolicy], name: Optional[Text] = None, ): """Initializes an instance of `MixturePolicy`. Args: mixture_distribution: A `tfd.Categorical` distribution on the domain `[0, len(polici...
Initializes an instance of `MixturePolicy`. Args: mixture_distribution: A `tfd.Categorical` distribution on the domain `[0, len(policies) -1]`. This distribution is used by the mixture policy to choose which policy to listen to. policies: List of TF Policies. These are the policies that...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/mixture_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/mixture_policy.py
Apache-2.0
def _get_predicted_rewards_from_linucb(self, observation_numpy, batch_size): """Runs one step of LinUCB using numpy arrays.""" observation_numpy.reshape([batch_size, self._encoding_dim]) predicted_rewards = [] for k in range(self._num_actions): a_inv = np.linalg.inv(self._a_numpy[k] + np.eye(self...
Runs one step of LinUCB using numpy arrays.
_get_predicted_rewards_from_linucb
python
tensorflow/agents
tf_agents/bandits/policies/neural_linucb_policy_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/neural_linucb_policy_test.py
Apache-2.0
def _get_predicted_rewards_from_per_arm_linucb( self, observation_numpy, batch_size ): """Runs one step of LinUCB using numpy arrays.""" observation_numpy.reshape( [batch_size, self._num_actions, self._encoding_dim] ) predicted_rewards = [] for k in range(self._num_actions): a...
Runs one step of LinUCB using numpy arrays.
_get_predicted_rewards_from_per_arm_linucb
python
tensorflow/agents
tf_agents/bandits/policies/neural_linucb_policy_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/neural_linucb_policy_test.py
Apache-2.0
def __init__( self, features: types.Tensor, num_slots: int, logits: types.Tensor, penalty_mixture_coefficient: float = 1.0, ): """Initializes an instance of PenalizedPlackettLuce. Args: features: Item features based on which similarity is calculated. num_slots: The n...
Initializes an instance of PenalizedPlackettLuce. Args: features: Item features based on which similarity is calculated. num_slots: The number of slots to fill: this many items will be sampled. logits: Unnormalized log probabilities for the PlackettLuce distribution. Shape is `[num_items]...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def _penalizer_fn( self, logits: types.Float, slots: tf.Tensor, num_slotted: tf.Tensor, ): """Downscores items by their similarity to already selected items. Args: logits: The current logits of all items, shaped as [batch_size, num_items]. slots: A tensor of indice...
Downscores items by their similarity to already selected items. Args: logits: The current logits of all items, shaped as [batch_size, num_items]. slots: A tensor of indices of the selected items, shaped as [batch_size, num_slots]. Only the first `num_slotted` columns correspond to valid...
_penalizer_fn
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def __init__( self, features: types.Tensor, num_slots: int, logits: types.Tensor, penalty_mixture_coefficient: float = 1.0, ): """Initializes an instance of CosinePenalizedPlackettLuce. Args: features: Item features based on which similarity is calculated. num_slots:...
Initializes an instance of CosinePenalizedPlackettLuce. Args: features: Item features based on which similarity is calculated. num_slots: The number of slots to fill: this many items will be sampled. logits: Unnormalized log probabilities for the PlackettLuce distribution. Shape is `[num_...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def __init__( self, features: types.Tensor, num_slots: int, logits: types.Tensor, penalty_mixture_coefficient: float = 1.0, ): """Initializes an instance of NoPenaltyPlackettLuce. Args: features: Unused for this distribution. num_slots: The number of slots to fill: t...
Initializes an instance of NoPenaltyPlackettLuce. Args: features: Unused for this distribution. num_slots: The number of slots to fill: this many items will be sampled. logits: Unnormalized log probabilities for the PlackettLuce distribution. Shape is `[num_items]`. penalty_mixture_...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def __init__( self, num_items: int, num_slots: int, time_step_spec: types.TimeStep, network: types.Network, item_sampler: tfd.Distribution, penalty_mixture_coefficient: float = 1.0, logits_temperature: float = 1.0, name: Optional[Text] = None, ): """Initialize...
Initializes an instance of `RankingPolicy`. Args: num_items: The number of items the policy can choose from, to be slotted. num_slots: The number of recommendation slots presented to the user, i.e., chosen by the policy. time_step_spec: The time step spec. network: The network that ...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def _action_distribution( self, mask: Optional[types.Tensor], predicted_rewards: types.Tensor ) -> Tuple[tfp.distributions.Distribution, types.Tensor]: """Returns an action distribution based on predicted rewards. Sub-classes are expected to implement this method. Args: mask: A 2-D tensor of...
Returns an action distribution based on predicted rewards. Sub-classes are expected to implement this method. Args: mask: A 2-D tensor of binary masks shaped as [batch_size, num_of_arms]. predicted_rewards: A 2-D tensor of predicted rewards shaped as [batch_size, num_of_arms]. Returns...
_action_distribution
python
tensorflow/agents
tf_agents/bandits/policies/reward_prediction_base_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/reward_prediction_base_policy.py
Apache-2.0
def _maybe_save_chosen_arm_features( self, time_step: ts.TimeStep, action: types.Tensor, step: policy_step.PolicyStep, ) -> policy_step.PolicyStep: """Extracts and saves the chosen arm features in the policy info. If the policy accepts arm features, this method extracts the arm featur...
Extracts and saves the chosen arm features in the policy info. If the policy accepts arm features, this method extracts the arm features from `time_step.observation` corresponding to the input `action` tensor, saves it in the policy info of the input `step` and returns the modified step. Otherwise, the...
_maybe_save_chosen_arm_features
python
tensorflow/agents
tf_agents/bandits/policies/reward_prediction_base_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/reward_prediction_base_policy.py
Apache-2.0
def _action( self, time_step: ts.TimeStep, policy_state: types.NestedTensor, seed: Optional[types.Seed] = None, ) -> policy_step.PolicyStep: """Implementation of `action`. Args: time_step: A `TimeStep` tuple corresponding to `time_step_spec()`. policy_state: A Tensor, or a...
Implementation of `action`. Args: time_step: A `TimeStep` tuple corresponding to `time_step_spec()`. policy_state: A Tensor, or a nested dict, list or tuple of Tensors representing the previous policy_state. seed: Seed to use if action performs sampling (optional). Returns: A `...
_action
python
tensorflow/agents
tf_agents/bandits/policies/reward_prediction_base_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/reward_prediction_base_policy.py
Apache-2.0
def get_distribution_strategy( distribution_strategy="default", num_gpus=0, num_packs=-1 ): """Return a DistributionStrategy for running the model. Args: distribution_strategy: a string specifying which distribution strategy to use. Accepted values are 'off', 'default', 'one_device', and 'mirrored' ...
Return a DistributionStrategy for running the model. Args: distribution_strategy: a string specifying which distribution strategy to use. Accepted values are 'off', 'default', 'one_device', and 'mirrored' case insensitive. 'off' means not to use Distribution Strategy; 'default' means to choose ...
get_distribution_strategy
python
tensorflow/agents
tf_agents/benchmark/distribution_strategy_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/distribution_strategy_utils.py
Apache-2.0
def benchmark_pong_v0_at_3M(self): """Benchmarks to 3M Env steps. This is below the 12.5M train steps (50M frames) run by the paper to converge. Running 12.5M at the current throughput would take more than a week. 1-2 days is the max duration for a remotely usable test. 3M only confirms we have not...
Benchmarks to 3M Env steps. This is below the 12.5M train steps (50M frames) run by the paper to converge. Running 12.5M at the current throughput would take more than a week. 1-2 days is the max duration for a remotely usable test. 3M only confirms we have not regressed at 3M and does not gurantee con...
benchmark_pong_v0_at_3M
python
tensorflow/agents
tf_agents/benchmark/dqn_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/dqn_benchmark.py
Apache-2.0
def _run( self, strategy, batch_size=64, tf_function=True, replay_buffer_max_length=1000, train_steps=110, log_steps=10, ): """Runs Dqn CartPole environment. Args: strategy: Strategy to use, None is a valid value. batch_size: Total batch size to use for t...
Runs Dqn CartPole environment. Args: strategy: Strategy to use, None is a valid value. batch_size: Total batch size to use for the run. tf_function: If True tf.function is used. replay_buffer_max_length: Max length of the replay buffer. train_steps: Number of steps to run. log_s...
_run
python
tensorflow/agents
tf_agents/benchmark/dqn_benchmark_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/dqn_benchmark_test.py
Apache-2.0
def run_and_report( self, train_step, strategy, batch_size, train_steps=110, log_steps=10, iterator=None, ): """Run function provided and report results per `tf.test.Benchmark`. Args: train_step: Function to execute on each step. strategy: Strategy to use...
Run function provided and report results per `tf.test.Benchmark`. Args: train_step: Function to execute on each step. strategy: Strategy to use, None is a valid value. batch_size: Total batch_size. train_steps: Number of steps to run. log_steps: How often to log step statistics, e.g. ...
run_and_report
python
tensorflow/agents
tf_agents/benchmark/dqn_benchmark_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/dqn_benchmark_test.py
Apache-2.0
def __init__(self, output_dir=None): """Initialize class. Args: output_dir: Base directory to store all output for the test. """ # MLCompass sets this value, but PerfZero OSS passes it as an arg. if os.getenv('BENCHMARK_OUTPUT_DIR'): self.output_dir = os.getenv('BENCHMARK_OUTPUT_DIR') ...
Initialize class. Args: output_dir: Base directory to store all output for the test.
__init__
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark.py
Apache-2.0
def setUp(self): """Sets up and resets flags before each test.""" logging.set_verbosity(logging.INFO) if PerfZeroBenchmark.local_flags is None: # Loads flags to get defaults to then override. List cannot be empty. flags.FLAGS(['foo']) saved_flag_values = flagsaver.save_flag_values() ...
Sets up and resets flags before each test.
setUp
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark.py
Apache-2.0
def build_metric( self, name: str, value: Number, min_value: Optional[Number] = None, max_value: Optional[Number] = None, ): """Builds a dictionary representing the metric to record. Args: name: Name of the metric. value: Value of the metric. min_value: Lowest ...
Builds a dictionary representing the metric to record. Args: name: Name of the metric. value: Value of the metric. min_value: Lowest acceptable value. max_value: Highest acceptable value. Returns: Dictionary representing the metric.
build_metric
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark.py
Apache-2.0
def test_build_metric(self): """Tests building metric with only required values.""" bench = perfzero_benchmark.PerfZeroBenchmark() metric_name = 'metric_name' value = 25.93 expected_metric = {'name': metric_name, 'value': value} metric = bench.build_metric(metric_name, value) self.assertEqu...
Tests building metric with only required values.
test_build_metric
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark_test.py
Apache-2.0
def test_build_metric_min_max(self): """Tests building metric with min and max values.""" bench = perfzero_benchmark.PerfZeroBenchmark() metric_name = 'metric_name' value = 25.93 min_value = 0.004 max_value = 59783 expected_metric = { 'name': metric_name, 'value': value, ...
Tests building metric with min and max values.
test_build_metric_min_max
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark_test.py
Apache-2.0
def run_benchmark(self, training_env, expected_min, expected_max): """Run benchmark for a given environment. In order to execute ~1M environment steps to match the paper, we run 489 iterations (num_iterations=489) which results in 1,001,472 environment steps. Each iteration results in 320 training step...
Run benchmark for a given environment. In order to execute ~1M environment steps to match the paper, we run 489 iterations (num_iterations=489) which results in 1,001,472 environment steps. Each iteration results in 320 training steps and 2,048 environment steps. Thus 489 * 2,048 = 1,001,472 environmen...
run_benchmark
python
tensorflow/agents
tf_agents/benchmark/ppo_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/ppo_benchmark.py
Apache-2.0
def run_test( target_call, num_steps, strategy, batch_size=None, log_steps=100, num_steps_per_batch=1, iterator=None, ): """Run benchmark and return TimeHistory object with stats. Args: target_call: Call to execute for each step. num_steps: Number of steps to run. strategy: ...
Run benchmark and return TimeHistory object with stats. Args: target_call: Call to execute for each step. num_steps: Number of steps to run. strategy: None or tf.distribute.DistibutionStrategy object. batch_size: Total batch size. log_steps: Interval of steps between logging of stats. num_ste...
run_test
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def __init__(self, batch_size, log_steps, num_steps_per_batch=1): """Callback for logging performance. Args: batch_size: Total batch size. log_steps: Interval of steps between logging of stats. num_steps_per_batch: Number of steps per batch. """ self.batch_size = batch_size super(...
Callback for logging performance. Args: batch_size: Total batch size. log_steps: Interval of steps between logging of stats. num_steps_per_batch: Number of steps per batch.
__init__
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def on_batch_end(self): """Records elapse time of the batch and calculates examples per second.""" if self.global_steps % self.log_steps == 0: timestamp = time.time() elapsed_time = timestamp - self.start_time steps_per_second = self.log_steps / elapsed_time examples_per_second = steps_p...
Records elapse time of the batch and calculates examples per second.
on_batch_end
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def get_average_examples_per_second(self, warmup=True): """Returns average examples per second so far. Examples per second are defined by `batch_size` * `num_steps_per_batch` Args: warmup: If true ignore first set of steps executed as determined by `log_steps`. Returns: Average ex...
Returns average examples per second so far. Examples per second are defined by `batch_size` * `num_steps_per_batch` Args: warmup: If true ignore first set of steps executed as determined by `log_steps`. Returns: Average examples per second.
get_average_examples_per_second
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def get_average_step_time(self, warmup=True): """Returns average step time (seconds) so far. Args: warmup: If true ignore first set of steps executed as determined by `log_steps`. Returns: Average step time in seconds. """ if warmup: if len(self.timestamp_log) < 3: ...
Returns average step time (seconds) so far. Args: warmup: If true ignore first set of steps executed as determined by `log_steps`. Returns: Average step time in seconds.
get_average_step_time
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def get_variable_value(agent, name): """Returns the value of the trainable variable with the given name.""" policy_vars = agent.policy.variables() tf_vars = [v for v in policy_vars if name in v.name] assert tf_vars, 'Variable "{}" does not exist. Found: {}'.format( name, policy_vars ) if tf.executing_...
Returns the value of the trainable variable with the given name.
get_variable_value
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def find_event_log( eventlog_dir: str, log_file_pattern: str = 'events.out.tfevents.*' ) -> str: """Find the event log in a given folder. Expects to find a single log file matching the pattern provided. Args: eventlog_dir: Event log directory to search. log_file_pattern: Pattern to use to find the e...
Find the event log in a given folder. Expects to find a single log file matching the pattern provided. Args: eventlog_dir: Event log directory to search. log_file_pattern: Pattern to use to find the event log. Returns: Path to the event log file that was found. Raises: FileNotFoundError: If ...
find_event_log
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def extract_event_log_values( event_file: str, event_tag: str, end_step: Optional[int] = None, start_step: Optional[int] = 0, ) -> Tuple[Dict[int, np.generic], float]: """Extracts the event values for the `event_tag` and total wall time. Args: event_file: Path to the event log. event_tag: E...
Extracts the event values for the `event_tag` and total wall time. Args: event_file: Path to the event log. event_tag: Event to extract from the logs. end_step: If set, processing of the event log ends on this step. start_step: First step to look for in event log, defaults to 0. Returns: Tuple...
extract_event_log_values
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def test_extract_value(self): """Tests extracting data from all steps in the event log.""" values, walltime = utils.extract_event_log_values( os.path.join(TEST_DATA, 'event_log_3m/events.out.tfevents.1599310762'), 'AverageReturn', ) # Verifies all (3M) records were examined 0-3M = 301. ...
Tests extracting data from all steps in the event log.
test_extract_value
python
tensorflow/agents
tf_agents/benchmark/utils_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils_test.py
Apache-2.0
def test_extract_value_1m_only(self): """Tests extracting data from the first 1M steps in the event log.""" values, walltime = utils.extract_event_log_values( os.path.join(TEST_DATA, 'event_log_3m/events.out.tfevents.1599310762'), 'AverageReturn', 1000000, ) # Verifies only 1M re...
Tests extracting data from the first 1M steps in the event log.
test_extract_value_1m_only
python
tensorflow/agents
tf_agents/benchmark/utils_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils_test.py
Apache-2.0
def test_extract_value_1m_only_start_at_1k(self): """Tests extracting data starting at step 1k.""" values, walltime = utils.extract_event_log_values( os.path.join(TEST_DATA, 'event_log_3m/events.out.tfevents.1599310762'), 'AverageReturn', 1000000, start_step=10000, ) # Ve...
Tests extracting data starting at step 1k.
test_extract_value_1m_only_start_at_1k
python
tensorflow/agents
tf_agents/benchmark/utils_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils_test.py
Apache-2.0
def __init__( self, temperature, logits=None, probs=None, dtype=tf.int32, validate_args=False, allow_nan_stats=True, name='GumbelSoftmax', ): """Initialize GumbelSoftmax using class log-probabilities. Args: temperature: A `Tensor`, representing the temper...
Initialize GumbelSoftmax using class log-probabilities. Args: temperature: A `Tensor`, representing the temperature of one or more distributions. The temperature values must be positive, and the shape must broadcast against `(logits or probs)[..., 0]`. logits: An N-D `Tensor`, `N >= 1`,...
__init__
python
tensorflow/agents
tf_agents/distributions/gumbel_softmax.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/gumbel_softmax.py
Apache-2.0
def __init__( self, logits, mask, probs=None, dtype=tf.int32, validate_args=False, allow_nan_stats=True, neg_inf=-1e10, name='MaskedCategorical', ): """Initialize Categorical distributions using class log-probabilities. Args: logits: An N-D `Tensor`...
Initialize Categorical distributions using class log-probabilities. Args: logits: An N-D `Tensor`, `N >= 1`, representing the log probabilities of a set of Categorical distributions. The first `N - 1` dimensions index into a batch of independent distributions and the last dimension re...
__init__
python
tensorflow/agents
tf_agents/distributions/masked.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/masked.py
Apache-2.0
def testCopy(self): """Confirm we can copy the distribution.""" distribution = masked.MaskedCategorical( [100.0, 100.0, 100.0], mask=[True, False, True] ) copy = distribution.copy() with self.cached_session() as s: probs_np = s.run(copy.probs_parameter()) logits_np = s.run(copy.l...
Confirm we can copy the distribution.
testCopy
python
tensorflow/agents
tf_agents/distributions/masked_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/masked_test.py
Apache-2.0
def sample(distribution, reparam=False, **kwargs): """Sample from distribution either with reparameterized sampling or regular sampling. Args: distribution: A `tfp.distributions.Distribution` instance. reparam: Whether to use reparameterized sampling. **kwargs: Parameters to be passed to distribution's...
Sample from distribution either with reparameterized sampling or regular sampling. Args: distribution: A `tfp.distributions.Distribution` instance. reparam: Whether to use reparameterized sampling. **kwargs: Parameters to be passed to distribution's sample() fucntion. Returns:
sample
python
tensorflow/agents
tf_agents/distributions/reparameterized_sampling.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/reparameterized_sampling.py
Apache-2.0
def __init__( self, logits=None, probs=None, dtype=tf.int32, force_probs_to_zero_outside_support=False, validate_args=False, allow_nan_stats=True, shift=None, name="ShiftedCategorical", ): """Initialize Categorical distributions using class log-probabilities. ...
Initialize Categorical distributions using class log-probabilities. Args: logits: An N-D `Tensor`, `N >= 1`, representing the log probabilities of a set of Categorical distributions. The first `N - 1` dimensions index into a batch of independent distributions and the last dimension re...
__init__
python
tensorflow/agents
tf_agents/distributions/shifted_categorical.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/shifted_categorical.py
Apache-2.0
def sample(self, sample_shape=(), seed=None, name="sample", **kwargs): """Generate samples of the specified shape.""" sample = super(ShiftedCategorical, self).sample( sample_shape=sample_shape, seed=seed, name=name, **kwargs ) return sample + self._shift
Generate samples of the specified shape.
sample
python
tensorflow/agents
tf_agents/distributions/shifted_categorical.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/shifted_categorical.py
Apache-2.0
def testCopy(self): """Confirm we can copy the distribution.""" distribution = shifted_categorical.ShiftedCategorical( logits=[100.0, 100.0, 100.0], shift=2 ) copy = distribution.copy() with self.cached_session() as s: probs_np = s.run(copy.probs_parameter()) logits_np = s.run(co...
Confirm we can copy the distribution.
testCopy
python
tensorflow/agents
tf_agents/distributions/shifted_categorical_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/shifted_categorical_test.py
Apache-2.0
def __init__( self, distribution, spec, validate_args=False, name="SquashToSpecNormal" ): """Constructs a SquashToSpecNormal distribution. Args: distribution: input normal distribution with normalized mean and std dev spec: bounded action spec from which to compute action ranges valid...
Constructs a SquashToSpecNormal distribution. Args: distribution: input normal distribution with normalized mean and std dev spec: bounded action spec from which to compute action ranges validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for val...
__init__
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def kl_divergence(self, other, name="kl_divergence"): """Computes the KL Divergence between two SquashToSpecNormal distributions.""" if not isinstance(other, SquashToSpecNormal): raise ValueError( "other distribution should be of type " "SquashToSpecNormal, got {}".format(other) ...
Computes the KL Divergence between two SquashToSpecNormal distributions.
kl_divergence
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def mode(self, name="mode"): """Compute mean of the SquashToSpecNormal distribution.""" mean = ( self.action_magnitudes * tf.tanh(self.input_distribution.mode()) + self.action_means ) return mean
Compute mean of the SquashToSpecNormal distribution.
mode
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def get_parameters(value: Any) -> Params: """Creates a recursive `Params` object from `value`. The `Params` object can be converted back to an object of type `type(value)` with `make_from_parameters`. For more details, see the docstring of `Params`. Args: value: Typically a user provides `tfp.Distribut...
Creates a recursive `Params` object from `value`. The `Params` object can be converted back to an object of type `type(value)` with `make_from_parameters`. For more details, see the docstring of `Params`. Args: value: Typically a user provides `tfp.Distribution`, `tfp.Bijector`, or `tf.linalg.Linea...
get_parameters
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def make_from_parameters(value: Params) -> Any: """Creates an instance of type `value.type_` with the parameters in `value`. For more details, see the docstrings for `get_parameters` and `Params`. This function may raise strange errors if `value` is a `Params` created from a badly constructed object (one whic...
Creates an instance of type `value.type_` with the parameters in `value`. For more details, see the docstrings for `get_parameters` and `Params`. This function may raise strange errors if `value` is a `Params` created from a badly constructed object (one which does not set `self._parameters` properly). For e...
make_from_parameters
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def merge_to_parameters_from_dict( value: Params, params_dict: Mapping[Text, Any] ) -> Params: """Merges dict matching data of `parameters_to_dict(value)` to a new `Params`. For more details, see the example below and the documentation of `parameters_to_dict`. Example: ```python scale_matrix = tf.Var...
Merges dict matching data of `parameters_to_dict(value)` to a new `Params`. For more details, see the example below and the documentation of `parameters_to_dict`. Example: ```python scale_matrix = tf.Variable([[1.0, 2.0], [-1.0, 0.0]]) d = tfp.distributions.MultivariateNormalDiag( loc=[1.0, 1.0], s...
merge_to_parameters_from_dict
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def __init__( self, event_shape: tf.TensorShape, dtype: tf.DType, parameters: Params ): """Construct a `DistributionSpecV2` from a Distribution's properties. Note that the `parameters` used to create the spec should contain `tf.TypeSpec` objects instead of tensors. We check for this. Args: ...
Construct a `DistributionSpecV2` from a Distribution's properties. Note that the `parameters` used to create the spec should contain `tf.TypeSpec` objects instead of tensors. We check for this. Args: event_shape: The distribution's `event_shape`. This is the shape that `distribution.sample...
__init__
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def assert_specs_are_compatible( network_output_spec: types.NestedTensorSpec, spec: types.NestedTensorSpec, message_prefix: str, ): """Checks that the output of `network.create_variables` matches a spec. Args: network_output_spec: The output of `network.create_variables`. spec: The spec we are ...
Checks that the output of `network.create_variables` matches a spec. Args: network_output_spec: The output of `network.create_variables`. spec: The spec we are matching to. message_prefix: The message prefix for error messages, used when the specs don't match. Raises: ValueError: If the spec...
assert_specs_are_compatible
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def __init__( self, env, policy, observers=None, transition_observers=None, info_observers=None, ): """Creates a Driver. Args: env: An environment.Base environment. policy: A policy.Base policy. observers: A list of observers that are updated after the dr...
Creates a Driver. Args: env: An environment.Base environment. policy: A policy.Base policy. observers: A list of observers that are updated after the driver is run. Each observer is a callable(Trajectory) that returns the input. Trajectory.time_step is a stacked batch [N+1, batch_...
__init__
python
tensorflow/agents
tf_agents/drivers/driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/driver.py
Apache-2.0
def __init__( self, env, policy, observers=None, transition_observers=None, num_episodes=1, ): """Creates a DynamicEpisodeDriver. **Note** about bias when using batched environments with `num_episodes`: When using `num_episodes != None`, a `run` step "finishes" when ...
Creates a DynamicEpisodeDriver. **Note** about bias when using batched environments with `num_episodes`: When using `num_episodes != None`, a `run` step "finishes" when `num_episodes` have been completely collected (hit a boundary). When used in conjunction with environments that have variable-length ...
__init__
python
tensorflow/agents
tf_agents/drivers/dynamic_episode_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_episode_driver.py
Apache-2.0
def _loop_condition_fn(self, num_episodes): """Returns a function with the condition needed for tf.while_loop.""" def loop_cond(counter, *_): """Determines when to stop the loop, based on episode counter. Args: counter: Episode counters per batch index. Shape [batch_size] when ba...
Returns a function with the condition needed for tf.while_loop.
_loop_condition_fn
python
tensorflow/agents
tf_agents/drivers/dynamic_episode_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_episode_driver.py
Apache-2.0
def _loop_body_fn(self): """Returns a function with the driver's loop body ops.""" def loop_body(counter, time_step, policy_state): """Runs a step in environment. While loop will call multiple times. Args: counter: Episode counters per batch index. Shape [batch_size]. time_s...
Returns a function with the driver's loop body ops.
_loop_body_fn
python
tensorflow/agents
tf_agents/drivers/dynamic_episode_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_episode_driver.py
Apache-2.0
def loop_body(counter, time_step, policy_state): """Runs a step in environment. While loop will call multiple times. Args: counter: Episode counters per batch index. Shape [batch_size]. time_step: TimeStep tuple with elements shape [batch_size, ...]. policy_state: Poicy state...
Runs a step in environment. While loop will call multiple times. Args: counter: Episode counters per batch index. Shape [batch_size]. time_step: TimeStep tuple with elements shape [batch_size, ...]. policy_state: Poicy state tensor shape [batch_size, policy_state_dim]. Pa...
loop_body
python
tensorflow/agents
tf_agents/drivers/dynamic_episode_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_episode_driver.py
Apache-2.0
def run( self, time_step=None, policy_state=None, num_episodes=None, maximum_iterations=None, ): """Takes episodes in the environment using the policy and update observers. If `time_step` and `policy_state` are not provided, `run` will reset the environment and request an in...
Takes episodes in the environment using the policy and update observers. If `time_step` and `policy_state` are not provided, `run` will reset the environment and request an initial state from the policy. **Note** about bias when using batched environments with `num_episodes`: When using `num_episodes ...
run
python
tensorflow/agents
tf_agents/drivers/dynamic_episode_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_episode_driver.py
Apache-2.0
def __init__( self, env, policy, observers=None, transition_observers=None, num_steps=1, ): """Creates a DynamicStepDriver. Args: env: A tf_environment.Base environment. policy: A tf_policy.TFPolicy policy. observers: A list of observers that are updated ...
Creates a DynamicStepDriver. Args: env: A tf_environment.Base environment. policy: A tf_policy.TFPolicy policy. observers: A list of observers that are updated after every step in the environment. Each observer is a callable(time_step.Trajectory). transition_observers: A list of obs...
__init__
python
tensorflow/agents
tf_agents/drivers/dynamic_step_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_step_driver.py
Apache-2.0
def _loop_condition_fn(self): """Returns a function with the condition needed for tf.while_loop.""" def loop_cond(counter, *_): """Determines when to stop the loop, based on step counter. Args: counter: Step counters per batch index. Shape [batch_size] when batch_size > 1, else s...
Returns a function with the condition needed for tf.while_loop.
_loop_condition_fn
python
tensorflow/agents
tf_agents/drivers/dynamic_step_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_step_driver.py
Apache-2.0
def _loop_body_fn(self): """Returns a function with the driver's loop body ops.""" def loop_body(counter, time_step, policy_state): """Runs a step in environment. While loop will call multiple times. Args: counter: Step counters per batch index. Shape [batch_size]. time_step...
Returns a function with the driver's loop body ops.
_loop_body_fn
python
tensorflow/agents
tf_agents/drivers/dynamic_step_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_step_driver.py
Apache-2.0
def loop_body(counter, time_step, policy_state): """Runs a step in environment. While loop will call multiple times. Args: counter: Step counters per batch index. Shape [batch_size]. time_step: TimeStep tuple with elements shape [batch_size, ...]. policy_state: Policy state t...
Runs a step in environment. While loop will call multiple times. Args: counter: Step counters per batch index. Shape [batch_size]. time_step: TimeStep tuple with elements shape [batch_size, ...]. policy_state: Policy state tensor shape [batch_size, policy_state_dim]. Pass...
loop_body
python
tensorflow/agents
tf_agents/drivers/dynamic_step_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_step_driver.py
Apache-2.0
def run(self, time_step=None, policy_state=None, maximum_iterations=None): """Takes steps in the environment using the policy while updating observers. Args: time_step: optional initial time_step. If None, it will use the current_time_step of the environment. Elements should be shape [bat...
Takes steps in the environment using the policy while updating observers. Args: time_step: optional initial time_step. If None, it will use the current_time_step of the environment. Elements should be shape [batch_size, ...]. policy_state: optional initial state for the policy. ma...
run
python
tensorflow/agents
tf_agents/drivers/dynamic_step_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/dynamic_step_driver.py
Apache-2.0
def __init__( self, env: py_environment.PyEnvironment, policy: py_policy.PyPolicy, observers: Sequence[Callable[[trajectory.Trajectory], Any]], transition_observers: Optional[ Sequence[Callable[[trajectory.Transition], Any]] ] = None, info_observers: Optional[Sequence...
A driver that runs a python policy in a python environment. **Note** about bias when using batched environments with `max_episodes`: When using `max_episodes != None`, a `run` step "finishes" when `max_episodes` have been completely collected (hit a boundary). When used in conjunction with environments...
__init__
python
tensorflow/agents
tf_agents/drivers/py_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/py_driver.py
Apache-2.0
def run( # pytype: disable=signature-mismatch # overriding-parameter-count-checks self, time_step: ts.TimeStep, policy_state: types.NestedArray = () ) -> Tuple[ts.TimeStep, types.NestedArray]: """Run policy in environment given initial time_step and policy_state. Args: time_step: The initial ti...
Run policy in environment given initial time_step and policy_state. Args: time_step: The initial time_step. policy_state: The initial policy_state. Returns: A tuple (final time_step, final policy_state).
run
python
tensorflow/agents
tf_agents/drivers/py_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/py_driver.py
Apache-2.0
def make_random_trajectory(): """Creates a random trajectory. This trajectory contains Tensors shaped `[1, 6, ...]` where `1` is the batch and `6` is the number of time steps. Observations are unbounded but actions are bounded to take values within `[1, 2]`. Policy info is also provided, and is equal to ...
Creates a random trajectory. This trajectory contains Tensors shaped `[1, 6, ...]` where `1` is the batch and `6` is the number of time steps. Observations are unbounded but actions are bounded to take values within `[1, 2]`. Policy info is also provided, and is equal to the actions. It can be removed v...
make_random_trajectory
python
tensorflow/agents
tf_agents/drivers/test_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/test_utils.py
Apache-2.0
def __init__( self, env: tf_environment.TFEnvironment, policy: tf_policy.TFPolicy, observers: Sequence[Callable[[trajectory.Trajectory], Any]], transition_observers: Optional[ Sequence[Callable[[trajectory.Transition], Any]] ] = None, max_steps: Optional[types.Int] = ...
A driver that runs a TF policy in a TF environment. **Note** about bias when using batched environments with `max_episodes`: When using `max_episodes != None`, a `run` step "finishes" when `max_episodes` have been completely collected (hit a boundary). When used in conjunction with environments that ha...
__init__
python
tensorflow/agents
tf_agents/drivers/tf_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/tf_driver.py
Apache-2.0
def run( # pytype: disable=signature-mismatch # overriding-parameter-count-checks self, time_step: ts.TimeStep, policy_state: types.NestedTensor = () ) -> Tuple[ts.TimeStep, types.NestedTensor]: """Run policy in environment given initial time_step and policy_state. Args: time_step: The initial ...
Run policy in environment given initial time_step and policy_state. Args: time_step: The initial time_step. policy_state: The initial policy_state. Returns: A tuple (final time_step, final policy_state).
run
python
tensorflow/agents
tf_agents/drivers/tf_driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/tf_driver.py
Apache-2.0
def __init__( self, env: gym.Env, frame_skip: int = 4, terminal_on_life_loss: bool = False, screen_size: int = 84, ): """Constructor for an Atari 2600 preprocessor. Args: env: Gym environment whose observations are preprocessed. frame_skip: int, the frequency at whic...
Constructor for an Atari 2600 preprocessor. Args: env: Gym environment whose observations are preprocessed. frame_skip: int, the frequency at which the agent experiences the game. terminal_on_life_loss: bool, If True, the step() method returns is_terminal=True whenever a life is lost. See...
__init__
python
tensorflow/agents
tf_agents/environments/atari_preprocessing.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/atari_preprocessing.py
Apache-2.0
def step(self, action: np.ndarray) -> np.ndarray: """Applies the given action in the environment. Remarks: * If a terminal state (from life loss or episode end) is reached, this may execute fewer than self.frame_skip steps in the environment. * Furthermore, in this case the returned observ...
Applies the given action in the environment. Remarks: * If a terminal state (from life loss or episode end) is reached, this may execute fewer than self.frame_skip steps in the environment. * Furthermore, in this case the returned observation may not contain valid image data and should...
step
python
tensorflow/agents
tf_agents/environments/atari_preprocessing.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/atari_preprocessing.py
Apache-2.0
def _pool_and_resize(self): """Transforms two frames into a Nature DQN observation. For efficiency, the transformation is done in-place in self.screen_buffer. Returns: transformed_screen: numpy array, pooled, resized screen. """ # Pool if there are enough screens to do so. if self.frame_...
Transforms two frames into a Nature DQN observation. For efficiency, the transformation is done in-place in self.screen_buffer. Returns: transformed_screen: numpy array, pooled, resized screen.
_pool_and_resize
python
tensorflow/agents
tf_agents/environments/atari_preprocessing.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/atari_preprocessing.py
Apache-2.0
def __init__( self, envs: Sequence[py_environment.PyEnvironment], multithreading: bool = True, ): """Batch together multiple (non-batched) py environments. The environments can be different but must use the same action and observation specs. Args: envs: List python environmen...
Batch together multiple (non-batched) py environments. The environments can be different but must use the same action and observation specs. Args: envs: List python environments (must be non-batched). multithreading: Python bool describing whether interactions with the given environmen...
__init__
python
tensorflow/agents
tf_agents/environments/batched_py_environment.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/batched_py_environment.py
Apache-2.0
def _reset(self): """Reset all environments and combine the resulting observation. Returns: Time step with batch dimension. """ if self._num_envs == 1: return nest_utils.batch_nested_array(self._envs[0].reset()) else: time_steps = self._execute(lambda env: env.reset(), self._envs)...
Reset all environments and combine the resulting observation. Returns: Time step with batch dimension.
_reset
python
tensorflow/agents
tf_agents/environments/batched_py_environment.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/batched_py_environment.py
Apache-2.0
def _step(self, actions): """Forward a batch of actions to the wrapped environments. Args: actions: Batched action, possibly nested, to apply to the environment. Raises: ValueError: Invalid actions. Returns: Batch of observations, rewards, and done flags. """ if self._num_e...
Forward a batch of actions to the wrapped environments. Args: actions: Batched action, possibly nested, to apply to the environment. Raises: ValueError: Invalid actions. Returns: Batch of observations, rewards, and done flags.
_step
python
tensorflow/agents
tf_agents/environments/batched_py_environment.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/batched_py_environment.py
Apache-2.0
def set_state(self, state: Sequence[Any]) -> None: """Restores the environment to a given `state`.""" self._execute( lambda env_state: env_state[0].set_state(env_state[1]), zip(self._envs, state) )
Restores the environment to a given `state`.
set_state
python
tensorflow/agents
tf_agents/environments/batched_py_environment.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/batched_py_environment.py
Apache-2.0
def close(self) -> None: """Send close messages to the external process and join them.""" self._execute(lambda env: env.close(), self._envs) if self._parallel_execution: self._pool.close() self._pool.join()
Send close messages to the external process and join them.
close
python
tensorflow/agents
tf_agents/environments/batched_py_environment.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/batched_py_environment.py
Apache-2.0
def unstack_actions(batched_actions: types.NestedArray) -> types.NestedArray: """Returns a list of actions from potentially nested batch of actions.""" flattened_actions = tf.nest.flatten(batched_actions) unstacked_actions = [ tf.nest.pack_sequence_as(batched_actions, actions) for actions in zip(*flat...
Returns a list of actions from potentially nested batch of actions.
unstack_actions
python
tensorflow/agents
tf_agents/environments/batched_py_environment.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/batched_py_environment.py
Apache-2.0
def convert_time_step(time_step): """Convert to agents time_step type as the __hash__ method is different.""" reward = time_step.reward if reward is None: reward = 0.0 discount = time_step.discount if discount is None: discount = 1.0 observation = tf.nest.map_structure(_maybe_float32, time_step.obs...
Convert to agents time_step type as the __hash__ method is different.
convert_time_step
python
tensorflow/agents
tf_agents/environments/dm_control_wrapper.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/dm_control_wrapper.py
Apache-2.0
def spec_from_gym_space( space: gym.Space, simplify_box_bounds: bool = True, name: Optional[Text] = None, ) -> Union[ specs.BoundedArraySpec, specs.ArraySpec, tuple[specs.ArraySpec, ...], list[specs.ArraySpec], collections.OrderedDict[str, specs.ArraySpec], ]: """Converts gymnasium spa...
Converts gymnasium spaces into array specs, or a collection thereof. Please note: Unlike OpenAI's gym, Farama's gymnasium provides a dtype for each current implementation of spaces. dtype should be defined in all specific subclasses of gymnasium.Space even if it is still optional in the superclass. ...
spec_from_gym_space
python
tensorflow/agents
tf_agents/environments/gymnasium_wrapper.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/gymnasium_wrapper.py
Apache-2.0
def try_simplify_array_to_value(np_array): """If given numpy array has all the same values, returns that value.""" first_value = np_array.item(0) if np.all(np_array == first_value): return np.array(first_value, dtype=np_array.dtype) else: return np_array
If given numpy array has all the same values, returns that value.
try_simplify_array_to_value
python
tensorflow/agents
tf_agents/environments/gymnasium_wrapper.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/gymnasium_wrapper.py
Apache-2.0
def nested_spec(spec, child_name): """Returns the nested spec with a unique name.""" nested_name = name + '/' + child_name if name else child_name return spec_from_gym_space(spec, simplify_box_bounds, nested_name)
Returns the nested spec with a unique name.
nested_spec
python
tensorflow/agents
tf_agents/environments/gymnasium_wrapper.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/gymnasium_wrapper.py
Apache-2.0
def __getattr__(self, name: Text) -> Any: """Forward all other calls to the base environment.""" gym_env = super(GymnasiumWrapper, self).__getattribute__('_gym_env') return getattr(gym_env, name)
Forward all other calls to the base environment.
__getattr__
python
tensorflow/agents
tf_agents/environments/gymnasium_wrapper.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/gymnasium_wrapper.py
Apache-2.0
def spec_from_gym_space( space: gym.Space, dtype_map: Optional[Dict[gym.Space, np.dtype]] = None, simplify_box_bounds: bool = True, name: Optional[Text] = None, ) -> specs.BoundedArraySpec: """Converts gym spaces into array specs. Gym does not properly define dtypes for spaces. By default all space...
Converts gym spaces into array specs. Gym does not properly define dtypes for spaces. By default all spaces set their type to float64 even though observations do not always return this type. See: https://github.com/openai/gym/issues/527 To handle this we allow a dtype_map for setting default types for mappi...
spec_from_gym_space
python
tensorflow/agents
tf_agents/environments/gym_wrapper.py
https://github.com/tensorflow/agents/blob/master/tf_agents/environments/gym_wrapper.py
Apache-2.0