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 _critic_loss_with_optional_entropy_term( self, time_steps: ts.TimeStep, actions: types.Tensor, next_time_steps: ts.TimeStep, td_errors_loss_fn: types.LossFn, gamma: types.Float = 1.0, reward_scale_factor: types.Float = 1.0, weights: Optional[types.Tensor] = None, ...
Computes the critic loss for CQL-SAC training. The original SAC critic loss is: ``` (q(s, a) - (r(s, a) + \gamma q(s', a') - \gamma \alpha \log \pi(a'|s')))^2 ``` The CQL-SAC critic loss makes the entropy term optional. CQL may value unseen actions higher since it lower-bounds the value of ...
_critic_loss_with_optional_entropy_term
python
tensorflow/agents
tf_agents/agents/cql/cql_sac_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/cql/cql_sac_agent.py
Apache-2.0
def __init__( self, input_tensor_spec, output_tensor_spec, fc_layer_params=None, dropout_layer_params=None, conv_layer_params=None, activation_fn=tf.keras.activations.relu, kernel_initializer=None, last_kernel_initializer=None, name='ActorNetwork', ): ""...
Creates an instance of `ActorNetwork`. Args: input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the inputs. output_tensor_spec: A nest of `tensor_spec.BoundedTensorSpec` representing the outputs. fc_layer_params: Optional list of fully_connected parameters, where e...
__init__
python
tensorflow/agents
tf_agents/agents/ddpg/actor_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/actor_network.py
Apache-2.0
def __init__( self, input_tensor_spec, output_tensor_spec, conv_layer_params=None, input_fc_layer_params=(200, 100), lstm_size=(40,), output_fc_layer_params=(200, 100), activation_fn=tf.keras.activations.relu, name='ActorRnnNetwork', ): """Creates an instance ...
Creates an instance of `ActorRnnNetwork`. Args: input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the input observations. output_tensor_spec: A nest of `tensor_spec.BoundedTensorSpec` representing the actions. conv_layer_params: Optional list of convolution layers...
__init__
python
tensorflow/agents
tf_agents/agents/ddpg/actor_rnn_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/actor_rnn_network.py
Apache-2.0
def __init__( self, input_tensor_spec, observation_conv_layer_params=None, observation_fc_layer_params=None, observation_dropout_layer_params=None, action_fc_layer_params=None, action_dropout_layer_params=None, joint_fc_layer_params=None, joint_dropout_layer_params=...
Creates an instance of `CriticNetwork`. Args: input_tensor_spec: A tuple of (observation, action) each a nest of `tensor_spec.TensorSpec` representing the inputs. observation_conv_layer_params: Optional list of convolution layer parameters for observations, where each item is a length-t...
__init__
python
tensorflow/agents
tf_agents/agents/ddpg/critic_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/critic_network.py
Apache-2.0
def __init__( self, input_tensor_spec, observation_conv_layer_params=None, observation_fc_layer_params=(200,), action_fc_layer_params=(200,), joint_fc_layer_params=(100,), lstm_size=None, output_fc_layer_params=(200, 100), activation_fn=tf.keras.activations.relu, ...
Creates an instance of `CriticRnnNetwork`. Args: input_tensor_spec: A tuple of (observation, action) each of type `tensor_spec.TensorSpec` representing the inputs. observation_conv_layer_params: Optional list of convolution layers parameters to apply to the observations, where each item...
__init__
python
tensorflow/agents
tf_agents/agents/ddpg/critic_rnn_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/critic_rnn_network.py
Apache-2.0
def __init__( self, time_step_spec: ts.TimeStep, action_spec: types.NestedTensorSpec, actor_network: network.Network, critic_network: network.Network, actor_optimizer: Optional[types.Optimizer] = None, critic_optimizer: Optional[types.Optimizer] = None, ou_stddev: types.F...
Creates a DDPG Agent. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of BoundedTensorSpec representing the actions. actor_network: A tf_agents.network.Network to be used by the agent. The network will be called with call(observation, step_type[, po...
__init__
python
tensorflow/agents
tf_agents/agents/ddpg/ddpg_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/ddpg_agent.py
Apache-2.0
def _get_target_updater(self, tau=1.0, period=1): """Performs a soft update of the target network parameters. For each weight w_s in the original network, and its corresponding weight w_t in the target network, a soft update is: w_t = (1- tau) x w_t + tau x ws Args: tau: A float scalar in [0...
Performs a soft update of the target network parameters. For each weight w_s in the original network, and its corresponding weight w_t in the target network, a soft update is: w_t = (1- tau) x w_t + tau x ws Args: tau: A float scalar in [0, 1]. Default `tau=1.0` means hard update. period: ...
_get_target_updater
python
tensorflow/agents
tf_agents/agents/ddpg/ddpg_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/ddpg_agent.py
Apache-2.0
def critic_loss( self, time_steps: ts.TimeStep, actions: types.NestedTensor, next_time_steps: ts.TimeStep, weights: Optional[types.Tensor] = None, training: bool = False, ) -> types.Tensor: """Computes the critic loss for DDPG training. Args: time_steps: A batch of t...
Computes the critic loss for DDPG training. Args: time_steps: A batch of timesteps. actions: A batch of actions. next_time_steps: A batch of next timesteps. weights: Optional scalar or element-wise (per-batch-entry) importance weights. training: Whether this loss is being used...
critic_loss
python
tensorflow/agents
tf_agents/agents/ddpg/ddpg_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/ddpg_agent.py
Apache-2.0
def actor_loss( self, time_steps: ts.TimeStep, weights: Optional[types.Tensor] = None, training: bool = False, ) -> types.Tensor: """Computes the actor_loss for DDPG training. Args: time_steps: A batch of timesteps. weights: Optional scalar or element-wise (per-batch-entry...
Computes the actor_loss for DDPG training. Args: time_steps: A batch of timesteps. weights: Optional scalar or element-wise (per-batch-entry) importance weights. training: Whether this loss is being used for training. Returns: actor_loss: A scalar actor loss.
actor_loss
python
tensorflow/agents
tf_agents/agents/ddpg/ddpg_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/ddpg_agent.py
Apache-2.0
def train_eval( root_dir, env_name='HalfCheetah-v2', eval_env_name=None, env_load_fn=suite_mujoco.load, num_iterations=2000000, actor_fc_layers=(400, 300), critic_obs_fc_layers=(400,), critic_action_fc_layers=None, critic_joint_fc_layers=(300,), # Params for collect initial_c...
A simple train and eval for DDPG.
train_eval
python
tensorflow/agents
tf_agents/agents/ddpg/examples/v2/train_eval.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/examples/v2/train_eval.py
Apache-2.0
def create_actor_network(fc_layer_units, action_spec): """Create an actor network for DDPG.""" flat_action_spec = tf.nest.flatten(action_spec) if len(flat_action_spec) > 1: raise ValueError('Only a single action tensor is supported by this network') flat_action_spec = flat_action_spec[0] fc_layers = [den...
Create an actor network for DDPG.
create_actor_network
python
tensorflow/agents
tf_agents/agents/ddpg/examples/v2/train_eval.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ddpg/examples/v2/train_eval.py
Apache-2.0
def _check_network_output(self, net, label): """Check outputs of q_net and target_q_net against expected shape. Subclasses that require different q_network outputs should override this function. Args: net: A `Network`. label: A label to print in case of a mismatch. """ outputs = ne...
Check outputs of q_net and target_q_net against expected shape. Subclasses that require different q_network outputs should override this function. Args: net: A `Network`. label: A label to print in case of a mismatch.
_check_network_output
python
tensorflow/agents
tf_agents/agents/dqn/dqn_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/dqn/dqn_agent.py
Apache-2.0
def _get_target_updater(self, tau=1.0, period=1): """Performs a soft update of the target network parameters. For each weight w_s in the q network, and its corresponding weight w_t in the target_q_network, a soft update is: w_t = (1 - tau) * w_t + tau * w_s Args: tau: A float scalar in [0, 1...
Performs a soft update of the target network parameters. For each weight w_s in the q network, and its corresponding weight w_t in the target_q_network, a soft update is: w_t = (1 - tau) * w_t + tau * w_s Args: tau: A float scalar in [0, 1]. Default `tau=1.0` means hard update. period: Ste...
_get_target_updater
python
tensorflow/agents
tf_agents/agents/dqn/dqn_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/dqn/dqn_agent.py
Apache-2.0
def _loss( self, experience, td_errors_loss_fn=None, gamma=1.0, reward_scale_factor=1.0, weights=None, training=False, ): """Computes loss for DQN training. Args: experience: A batch of experience data in the form of a `Trajectory` or `Transition`. The ...
Computes loss for DQN training. Args: experience: A batch of experience data in the form of a `Trajectory` or `Transition`. The structure of `experience` must match that of `self.collect_policy.step_spec`. If a `Trajectory`, all tensors in `experience` must be shaped `[B, T, ...]` wh...
_loss
python
tensorflow/agents
tf_agents/agents/dqn/dqn_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/dqn/dqn_agent.py
Apache-2.0
def _compute_next_q_values(self, next_time_steps, info): """Compute the q value of the next state for TD error computation. Args: next_time_steps: A batch of next timesteps info: PolicyStep.info that may be used by other agents inherited from dqn_agent. Returns: A tensor of Q val...
Compute the q value of the next state for TD error computation. Args: next_time_steps: A batch of next timesteps info: PolicyStep.info that may be used by other agents inherited from dqn_agent. Returns: A tensor of Q values for the given next state.
_compute_next_q_values
python
tensorflow/agents
tf_agents/agents/dqn/dqn_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/dqn/dqn_agent.py
Apache-2.0
def testLossNStepMidMidLastFirst(self, agent_class): """Tests that n-step loss handles LAST time steps properly.""" q_net = DummyNet(self._observation_spec, self._action_spec) agent = agent_class( self._time_step_spec, self._action_spec, q_network=q_net, optimizer=None, ...
Tests that n-step loss handles LAST time steps properly.
testLossNStepMidMidLastFirst
python
tensorflow/agents
tf_agents/agents/dqn/dqn_agent_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/dqn/dqn_agent_test.py
Apache-2.0
def train_eval( root_dir, env_name='CartPole-v0', num_iterations=100000, train_sequence_length=1, # Params for QNetwork fc_layer_params=(100,), # Params for QRnnNetwork input_fc_layer_params=(50,), lstm_size=(20,), output_fc_layer_params=(20,), # Params for collect initia...
A simple train and eval for DQN.
train_eval
python
tensorflow/agents
tf_agents/agents/dqn/examples/v2/train_eval.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/dqn/examples/v2/train_eval.py
Apache-2.0
def tanh_and_scale_to_spec(inputs, spec): """Maps inputs with arbitrary range to range defined by spec using `tanh`.""" means = (spec.maximum + spec.minimum) / 2.0 magnitudes = (spec.maximum - spec.minimum) / 2.0 return means + magnitudes * tf.tanh(inputs)
Maps inputs with arbitrary range to range defined by spec using `tanh`.
tanh_and_scale_to_spec
python
tensorflow/agents
tf_agents/agents/ppo/ppo_actor_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_actor_network.py
Apache-2.0
def create_sequential_actor_net( self, fc_layer_units, action_tensor_spec, seed=None ): """Helper method for creating the actor network.""" self._seed_stream = self.seed_stream_class( seed=seed, salt='tf_agents_sequential_layers' ) def _get_seed(): seed = self._seed_stream() ...
Helper method for creating the actor network.
create_sequential_actor_net
python
tensorflow/agents
tf_agents/agents/ppo/ppo_actor_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_actor_network.py
Apache-2.0
def __init__( self, time_step_spec: ts.TimeStep, action_spec: types.NestedTensorSpec, optimizer: Optional[types.Optimizer] = None, actor_net: Optional[network.Network] = None, value_net: Optional[network.Network] = None, greedy_eval: bool = True, importance_ratio_clipping...
Creates a PPO Agent. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. optimizer: Optimizer to use for the agent, default to using `tf.compat.v1.train.AdamOptimizer`. actor_net: A `network.Distrib...
__init__
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def compute_advantages( self, rewards: types.NestedTensor, returns: types.Tensor, discounts: types.Tensor, value_preds: types.Tensor, ) -> types.Tensor: """Compute advantages, optionally using GAE. Based on baselines ppo1 implementation. Removes final timestep, as it needs t...
Compute advantages, optionally using GAE. Based on baselines ppo1 implementation. Removes final timestep, as it needs to use this timestep for next-step value prediction for TD error computation. Args: rewards: Tensor of per-timestep rewards. returns: Tensor of per-timestep returns. ...
compute_advantages
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def get_loss( self, time_steps: ts.TimeStep, actions: types.NestedTensorSpec, act_log_probs: types.Tensor, returns: types.Tensor, normalized_advantages: types.Tensor, action_distribution_parameters: types.NestedTensor, weights: types.Tensor, train_step: tf.Variable,...
Compute the loss and create optimization op for one training epoch. All tensors should have a single batch dimension. Args: time_steps: A minibatch of TimeStep tuples. actions: A minibatch of actions. act_log_probs: A minibatch of action probabilities (probability under the sampling ...
get_loss
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def compute_return_and_advantage( self, next_time_steps: ts.TimeStep, value_preds: types.Tensor ) -> Tuple[types.Tensor, types.Tensor]: """Compute the Monte Carlo return and advantage. Args: next_time_steps: batched tensor of TimeStep tuples after action is taken. value_preds: Batched value...
Compute the Monte Carlo return and advantage. Args: next_time_steps: batched tensor of TimeStep tuples after action is taken. value_preds: Batched value prediction tensor. Should have one more entry in time index than time_steps, with the final value corresponding to the value predictio...
compute_return_and_advantage
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def _preprocess(self, experience): """Performs advantage calculation for the collected experience. Args: experience: A (batch of) experience in the form of a `Trajectory`. The structure of `experience` must match that of `self.collect_data_spec`. All tensors in `experience` must be shaped...
Performs advantage calculation for the collected experience. Args: experience: A (batch of) experience in the form of a `Trajectory`. The structure of `experience` must match that of `self.collect_data_spec`. All tensors in `experience` must be shaped `[batch, time + 1, ...]` or [time...
_preprocess
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def _preprocess_sequence(self, experience): """Performs advantage calculation for the collected experience. This function is a no-op if self._compute_value_and_advantage_in_train is True, which means advantage calculation happens as part of agent.train(). Args: experience: A (batch of) experienc...
Performs advantage calculation for the collected experience. This function is a no-op if self._compute_value_and_advantage_in_train is True, which means advantage calculation happens as part of agent.train(). Args: experience: A (batch of) experience in the form of a `Trajectory`. The struct...
_preprocess_sequence
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def entropy_regularization_loss( self, time_steps: ts.TimeStep, entropy: types.Tensor, weights: types.Tensor, debug_summaries: bool = False, ) -> types.Tensor: """Create regularization loss tensor based on agent parameters.""" if self._entropy_regularization > 0: nest_utils...
Create regularization loss tensor based on agent parameters.
entropy_regularization_loss
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def value_estimation_loss( self, time_steps: ts.TimeStep, returns: types.Tensor, weights: types.Tensor, old_value_predictions: Optional[types.Tensor] = None, debug_summaries: bool = False, training: bool = False, ) -> types.Tensor: """Computes the value estimation loss fo...
Computes the value estimation loss for actor-critic training. All tensors should have a single batch dimension. Args: time_steps: A batch of timesteps. returns: Per-timestep returns for value function to predict. (Should come from TD-lambda computation.) weights: Optional scalar or e...
value_estimation_loss
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def policy_gradient_loss( self, time_steps: ts.TimeStep, actions: types.NestedTensor, sample_action_log_probs: types.Tensor, advantages: types.Tensor, current_policy_distribution: types.NestedDistribution, weights: types.Tensor, debug_summaries: bool = False, ) -> types...
Create tensor for policy gradient loss. All tensors should have a single batch dimension. Args: time_steps: TimeSteps with observations for each timestep. actions: Tensor of actions for timesteps, aligned on index. sample_action_log_probs: Tensor of sample probability of each action. a...
policy_gradient_loss
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def kl_penalty_loss( self, time_steps: ts.TimeStep, action_distribution_parameters: types.NestedTensor, current_policy_distribution: types.NestedDistribution, weights: types.Tensor, debug_summaries: bool = False, ) -> types.Tensor: """Compute a loss that penalizes policy steps ...
Compute a loss that penalizes policy steps with high KL. Based on KL divergence from old (data-collection) policy to new (updated) policy. All tensors should have a single batch dimension. Args: time_steps: TimeStep tuples with observations for each timestep. Used for computing new acti...
kl_penalty_loss
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def update_adaptive_kl_beta( self, kl_divergence: types.Tensor ) -> Optional[tf.Operation]: """Create update op for adaptive KL penalty coefficient. Args: kl_divergence: KL divergence of old policy to new policy for all timesteps. Returns: update_op: An op which runs the update...
Create update op for adaptive KL penalty coefficient. Args: kl_divergence: KL divergence of old policy to new policy for all timesteps. Returns: update_op: An op which runs the update for the adaptive kl penalty term.
update_adaptive_kl_beta
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def _get_discount(experience) -> types.Tensor: """Try to get the discount entry from `experience`. Typically experience is either a Trajectory or a Transition. Args: experience: Data collected from e.g. a replay buffer. Returns: discount: The discount tensor stored in `experience`. """ if isinsta...
Try to get the discount entry from `experience`. Typically experience is either a Trajectory or a Transition. Args: experience: Data collected from e.g. a replay buffer. Returns: discount: The discount tensor stored in `experience`.
_get_discount
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent.py
Apache-2.0
def _compute_returns_fn(rewards, discounts, next_state_return=0.0): """Python implementation of computing discounted returns.""" returns = np.zeros_like(rewards) for t in range(len(returns) - 1, -1, -1): returns[t] = rewards[t] + discounts[t] * next_state_return next_state_return = returns[t] return ret...
Python implementation of computing discounted returns.
_compute_returns_fn
python
tensorflow/agents
tf_agents/agents/ppo/ppo_agent_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_agent_test.py
Apache-2.0
def __init__( self, time_step_spec: ts.TimeStep, action_spec: types.NestedTensorSpec, optimizer: Optional[types.Optimizer] = None, actor_net: Optional[network.Network] = None, value_net: Optional[network.Network] = None, greedy_eval: bool = True, importance_ratio_clipping...
Creates a PPO Agent implementing the clipped probability ratios. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of BoundedTensorSpec representing the actions. optimizer: Optimizer to use for the agent. actor_net: A function actor_net(observations, ac...
__init__
python
tensorflow/agents
tf_agents/agents/ppo/ppo_clip_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_clip_agent.py
Apache-2.0
def __init__( self, time_step_spec: ts.TimeStep, action_spec: types.NestedTensorSpec, actor_net: network.Network, value_net: network.Network, num_epochs: int, initial_adaptive_kl_beta: types.Float, adaptive_kl_target: types.Float, adaptive_kl_tolerance: types.Float,...
Creates a PPO Agent implementing the KL penalty loss. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. actor_net: A `network.DistributionNetwork` which maps observations to action distributions. Common...
__init__
python
tensorflow/agents
tf_agents/agents/ppo/ppo_kl_penalty_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_kl_penalty_agent.py
Apache-2.0
def get_initial_value_state( self, batch_size: types.Int ) -> types.NestedTensor: """Returns the initial state of the value network. Args: batch_size: A constant or Tensor holding the batch size. Can be None, in which case the state will not have a batch dimension added. Returns: ...
Returns the initial state of the value network. Args: batch_size: A constant or Tensor holding the batch size. Can be None, in which case the state will not have a batch dimension added. Returns: A nest of zero tensors matching the spec of the value network state.
get_initial_value_state
python
tensorflow/agents
tf_agents/agents/ppo/ppo_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_policy.py
Apache-2.0
def apply_value_network( self, observations: types.NestedTensor, step_types: types.Tensor, value_state: Optional[types.NestedTensor] = None, training: bool = False, ) -> types.NestedTensor: """Apply value network to time_step, potentially a sequence. If observation_normalizer is...
Apply value network to time_step, potentially a sequence. If observation_normalizer is not None, applies observation normalization. Args: observations: A (possibly nested) observation tensor with outer_dims either (batch_size,) or (batch_size, time_index). If observations is a time serie...
apply_value_network
python
tensorflow/agents
tf_agents/agents/ppo/ppo_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_policy.py
Apache-2.0
def make_trajectory_mask(batched_traj: trajectory.Trajectory) -> types.Tensor: """Mask boundary trajectories and those with invalid returns and advantages. Args: batched_traj: Trajectory, doubly-batched [batch_dim, time_dim,...]. It must be preprocessed already. Returns: A mask, type tf.float32, t...
Mask boundary trajectories and those with invalid returns and advantages. Args: batched_traj: Trajectory, doubly-batched [batch_dim, time_dim,...]. It must be preprocessed already. Returns: A mask, type tf.float32, that is 0.0 for all between-episode Trajectory (batched_traj.step_type is LAST)...
make_trajectory_mask
python
tensorflow/agents
tf_agents/agents/ppo/ppo_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_utils.py
Apache-2.0
def make_timestep_mask( batched_next_time_step: ts.TimeStep, allow_partial_episodes: bool = False ) -> types.Tensor: """Create a mask for transitions and optionally final incomplete episodes. Args: batched_next_time_step: Next timestep, doubly-batched [batch_dim, time_dim, ...]. allow_partial_epi...
Create a mask for transitions and optionally final incomplete episodes. Args: batched_next_time_step: Next timestep, doubly-batched [batch_dim, time_dim, ...]. allow_partial_episodes: If true, then steps on incomplete episodes are allowed. Returns: A mask, type tf.float32, that is 0.0 for ...
make_timestep_mask
python
tensorflow/agents
tf_agents/agents/ppo/ppo_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_utils.py
Apache-2.0
def nested_kl_divergence( nested_from_distribution: types.NestedDistribution, nested_to_distribution: types.NestedDistribution, outer_dims: Sequence[int] = (), ) -> types.Tensor: """Given two nested distributions, sum the KL divergences of the leaves.""" nest_utils.assert_same_structure( nested_fr...
Given two nested distributions, sum the KL divergences of the leaves.
nested_kl_divergence
python
tensorflow/agents
tf_agents/agents/ppo/ppo_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_utils.py
Apache-2.0
def get_metric_observers(metrics): """Returns a list of observers, one for each metric.""" def get_metric_observer(metric): def metric_observer(time_step, action, next_time_step, policy_state): action_step = policy_step.PolicyStep(action, policy_state, ()) traj = trajectory.from_transition(time_st...
Returns a list of observers, one for each metric.
get_metric_observers
python
tensorflow/agents
tf_agents/agents/ppo/ppo_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_utils.py
Apache-2.0
def get_learning_rate(optimizer): """Gets the current learning rate from an optimizer to be graphed.""" # Keras optimizers uses `learning_rate`. if hasattr(optimizer, 'learning_rate'): learning_rate = optimizer.learning_rate # pylint: disable=protected-access # Adam optimizers store their learning rate in ...
Gets the current learning rate from an optimizer to be graphed.
get_learning_rate
python
tensorflow/agents
tf_agents/agents/ppo/ppo_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/ppo_utils.py
Apache-2.0
def train_eval( root_dir, env_name='HalfCheetah-v2', env_load_fn=suite_mujoco.load, random_seed=None, # TODO(b/127576522): rename to policy_fc_layers. actor_fc_layers=(200, 100), value_fc_layers=(200, 100), use_rnns=False, lstm_size=(20,), # Params for collect num_environment...
A simple train and eval for PPO.
train_eval
python
tensorflow/agents
tf_agents/agents/ppo/examples/v2/train_eval_clip_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/ppo/examples/v2/train_eval_clip_agent.py
Apache-2.0
def _get_target_updater(self, tau=1.0, period=1): """Performs a soft update of the target network. For each weight w_s in the q network, and its corresponding weight w_t in the target_q_network, a soft update is: w_t = (1 - tau) * w_t + tau * w_s Args: tau: A float scalar in [0, 1]. Default ...
Performs a soft update of the target network. For each weight w_s in the q network, and its corresponding weight w_t in the target_q_network, a soft update is: w_t = (1 - tau) * w_t + tau * w_s Args: tau: A float scalar in [0, 1]. Default `tau=1.0` means hard update. Used for target netw...
_get_target_updater
python
tensorflow/agents
tf_agents/agents/qtopt/qtopt_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/qtopt/qtopt_agent.py
Apache-2.0
def _get_target_updater_delayed(self, tau_delayed=1.0, period_delayed=1): """Performs a soft update of the delayed target network. For each weight w_s in the q network, and its corresponding weight w_t in the target_q_network, a soft update is: w_t = (1 - tau) * w_t + tau * w_s Args: tau_del...
Performs a soft update of the delayed target network. For each weight w_s in the q network, and its corresponding weight w_t in the target_q_network, a soft update is: w_t = (1 - tau) * w_t + tau * w_s Args: tau_delayed: A float scalar in [0, 1]. Default `tau=1.0` means hard update. Used...
_get_target_updater_delayed
python
tensorflow/agents
tf_agents/agents/qtopt/qtopt_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/qtopt/qtopt_agent.py
Apache-2.0
def _add_auxiliary_losses(self, transition, weights, losses_dict): """Computes auxiliary losses, updating losses_dict in place.""" total_auxiliary_loss = 0 if self._auxiliary_loss_fns is not None: for auxiliary_loss_fn in self._auxiliary_loss_fns: auxiliary_loss, auxiliary_reg_loss = auxiliary...
Computes auxiliary losses, updating losses_dict in place.
_add_auxiliary_losses
python
tensorflow/agents
tf_agents/agents/qtopt/qtopt_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/qtopt/qtopt_agent.py
Apache-2.0
def _loss(self, experience, weights=None, training=False): """Computes loss for QtOpt training. Args: experience: A batch of experience data in the form of a `Trajectory` or `Transition`. The structure of `experience` must match that of `self.collect_policy.step_spec`. If a `Trajectory`,...
Computes loss for QtOpt training. Args: experience: A batch of experience data in the form of a `Trajectory` or `Transition`. The structure of `experience` must match that of `self.collect_policy.step_spec`. If a `Trajectory`, all tensors in `experience` must be shaped `[B, T, ...]` ...
_loss
python
tensorflow/agents
tf_agents/agents/qtopt/qtopt_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/qtopt/qtopt_agent.py
Apache-2.0
def __init__( self, time_step_spec: ts.TimeStep, action_spec: types.NestedTensorSpec, policy_class: PolicyClassType, debug_summaries: bool = False, summarize_grads_and_vars: bool = False, train_step_counter: Optional[tf.Variable] = None, num_outer_dims: int = 1, nam...
Creates a fixed-policy agent with no-op for training. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of BoundedTensorSpec representing the actions. policy_class: a tf_policy.TFPolicy or py_policy.PyPolicy class to use as a policy. debug_summa...
__init__
python
tensorflow/agents
tf_agents/agents/random/fixed_policy_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/random/fixed_policy_agent.py
Apache-2.0
def _train(self, experience, weights): """Do nothing. Arguments are ignored and loss is always 0.""" del experience # Unused del weights # Unused # Incrementing the step counter. self.train_step_counter.assign_add(1) # Returning 0 loss. return tf_agent.LossInfo(0.0, None)
Do nothing. Arguments are ignored and loss is always 0.
_train
python
tensorflow/agents
tf_agents/agents/random/fixed_policy_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/random/fixed_policy_agent.py
Apache-2.0
def __init__( self, time_step_spec: ts.TimeStep, action_spec: types.NestedTensorSpec, debug_summaries: bool = False, summarize_grads_and_vars: bool = False, train_step_counter: Optional[tf.Variable] = None, num_outer_dims: int = 1, name: Optional[Text] = None, ): ""...
Creates a random agent. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of BoundedTensorSpec representing the actions. debug_summaries: A bool to gather debug summaries. summarize_grads_and_vars: If true, gradient summaries will be written. trai...
__init__
python
tensorflow/agents
tf_agents/agents/random/random_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/random/random_agent.py
Apache-2.0
def _standard_normalize(values, axes=(0,)): """Standard normalizes values `values`. Args: values: Tensor with values to be standardized. axes: Axes used to compute mean and variances. Returns: Standardized values (values - mean(values[axes])) / std(values[axes]). """ values_mean, values_var = tf...
Standard normalizes values `values`. Args: values: Tensor with values to be standardized. axes: Axes used to compute mean and variances. Returns: Standardized values (values - mean(values[axes])) / std(values[axes]).
_standard_normalize
python
tensorflow/agents
tf_agents/agents/reinforce/reinforce_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/reinforce/reinforce_agent.py
Apache-2.0
def _entropy_loss(distributions, spec, weights=None): """Computes entropy loss. Args: distributions: A possibly batched tuple of distributions. spec: A nested tuple representing the action spec. weights: Optional scalar or element-wise (per-batch-entry) importance weights. Includes a mask for in...
Computes entropy loss. Args: distributions: A possibly batched tuple of distributions. spec: A nested tuple representing the action spec. weights: Optional scalar or element-wise (per-batch-entry) importance weights. Includes a mask for invalid timesteps. Returns: A Tensor representing the ...
_entropy_loss
python
tensorflow/agents
tf_agents/agents/reinforce/reinforce_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/reinforce/reinforce_agent.py
Apache-2.0
def _get_initial_policy_state(policy, time_steps): """Gets the initial state of a policy.""" batch_size = ( tf.compat.dimension_at_index(time_steps.discount.shape, 0) or tf.shape(time_steps.discount)[0] ) return policy.get_initial_state(batch_size=batch_size)
Gets the initial state of a policy.
_get_initial_policy_state
python
tensorflow/agents
tf_agents/agents/reinforce/reinforce_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/reinforce/reinforce_agent.py
Apache-2.0
def __init__( self, time_step_spec: ts.TimeStep, action_spec: types.TensorSpec, actor_network: network.Network, optimizer: types.Optimizer, value_network: Optional[network.Network] = None, value_estimation_loss_coef: types.Float = 0.2, advantage_fn: Optional[AdvantageFnTy...
Creates a REINFORCE Agent. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of BoundedTensorSpec representing the actions. actor_network: A tf_agents.network.Network to be used by the agent. The network will be called with call(observation, step_type...
__init__
python
tensorflow/agents
tf_agents/agents/reinforce/reinforce_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/reinforce/reinforce_agent.py
Apache-2.0
def policy_gradient_loss( self, actions_distribution: types.NestedDistribution, actions: types.NestedTensor, is_boundary: types.Tensor, returns: types.Tensor, num_episodes: types.Int, weights: Optional[types.Tensor] = None, ) -> types.Tensor: """Computes the policy gradie...
Computes the policy gradient loss. Args: actions_distribution: A possibly batched tuple of action distributions. actions: Tensor with a batch of actions. is_boundary: Tensor of booleans that indicate if the corresponding action was in a boundary trajectory and should be ignored. ret...
policy_gradient_loss
python
tensorflow/agents
tf_agents/agents/reinforce/reinforce_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/reinforce/reinforce_agent.py
Apache-2.0
def entropy_regularization_loss( self, actions_distribution: types.NestedDistribution, weights: Optional[types.Tensor] = None, ) -> types.Tensor: """Computes the optional entropy regularization loss. Extending REINFORCE by entropy regularization was originally proposed in "Function opti...
Computes the optional entropy regularization loss. Extending REINFORCE by entropy regularization was originally proposed in "Function optimization using connectionist reinforcement learning algorithms." (Williams and Peng, 1991). Args: actions_distribution: A possibly batched tuple of action dis...
entropy_regularization_loss
python
tensorflow/agents
tf_agents/agents/reinforce/reinforce_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/reinforce/reinforce_agent.py
Apache-2.0
def value_estimation_loss( self, value_preds: types.Tensor, returns: types.Tensor, num_episodes: types.Int, weights: Optional[types.Tensor] = None, ) -> types.Tensor: """Computes the value estimation loss. Args: value_preds: Per-timestep estimated values. returns: Pe...
Computes the value estimation loss. Args: value_preds: Per-timestep estimated values. returns: Per-timestep returns for value function to predict. num_episodes: Number of episodes contained in the training data. weights: Optional scalar or element-wise (per-batch-entry) importance w...
value_estimation_loss
python
tensorflow/agents
tf_agents/agents/reinforce/reinforce_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/reinforce/reinforce_agent.py
Apache-2.0
def train_eval( root_dir, env_name='CartPole-v0', num_iterations=1000, actor_fc_layers=(100,), value_net_fc_layers=(100,), use_value_network=False, use_tf_functions=True, # Params for collect collect_episodes_per_iteration=2, replay_buffer_capacity=2000, # Params for train ...
A simple train and eval for Reinforce.
train_eval
python
tensorflow/agents
tf_agents/agents/reinforce/examples/v2/train_eval.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/reinforce/examples/v2/train_eval.py
Apache-2.0
def __init__( self, time_step_spec: ts.TimeStep, action_spec: types.NestedTensorSpec, critic_network: network.Network, actor_network: network.Network, actor_optimizer: types.Optimizer, critic_optimizer: types.Optimizer, alpha_optimizer: types.Optimizer, actor_loss_w...
Creates a SAC Agent. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of BoundedTensorSpec representing the actions. critic_network: A function critic_network((observations, actions)) that returns the q_values for each observation and action. a...
__init__
python
tensorflow/agents
tf_agents/agents/sac/sac_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py
Apache-2.0
def _initialize(self): """Returns an op to initialize the agent. Copies weights from the Q networks to the target Q network. """ common.soft_variables_update( self._critic_network_1.variables, self._target_critic_network_1.variables, tau=1.0, ) common.soft_variables_upda...
Returns an op to initialize the agent. Copies weights from the Q networks to the target Q network.
_initialize
python
tensorflow/agents
tf_agents/agents/sac/sac_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py
Apache-2.0
def _loss( self, experience: types.NestedTensor, weights: Optional[types.Tensor] = None, training: bool = False, ): """Returns the loss of the provided experience. This method is only used at test time! Args: experience: A time-stacked trajectory object. weights: Opti...
Returns the loss of the provided experience. This method is only used at test time! Args: experience: A time-stacked trajectory object. weights: Optional scalar or elementwise (per-batch-entry) importance weights. training: Whether this loss is being calculated as part of training. ...
_loss
python
tensorflow/agents
tf_agents/agents/sac/sac_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py
Apache-2.0
def _get_target_updater(self, tau=1.0, period=1): """Performs a soft update of the target network parameters. For each weight w_s in the original network, and its corresponding weight w_t in the target network, a soft update is: w_t = (1- tau) x w_t + tau x ws Args: tau: A float scalar in [0...
Performs a soft update of the target network parameters. For each weight w_s in the original network, and its corresponding weight w_t in the target network, a soft update is: w_t = (1- tau) x w_t + tau x ws Args: tau: A float scalar in [0, 1]. Default `tau=1.0` means hard update. period: ...
_get_target_updater
python
tensorflow/agents
tf_agents/agents/sac/sac_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py
Apache-2.0
def critic_loss( self, time_steps: ts.TimeStep, actions: types.Tensor, next_time_steps: ts.TimeStep, td_errors_loss_fn: types.LossFn, gamma: types.Float = 1.0, reward_scale_factor: types.Float = 1.0, weights: Optional[types.Tensor] = None, training: bool = False, ...
Computes the critic loss for SAC training. Args: time_steps: A batch of timesteps. actions: A batch of actions. next_time_steps: A batch of next timesteps. td_errors_loss_fn: A function(td_targets, predictions) to compute elementwise (per-batch-entry) loss. gamma: Discount for...
critic_loss
python
tensorflow/agents
tf_agents/agents/sac/sac_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py
Apache-2.0
def actor_loss( self, time_steps: ts.TimeStep, weights: Optional[types.Tensor] = None, training: Optional[bool] = True, ) -> types.Tensor: """Computes the actor_loss for SAC training. Args: time_steps: A batch of timesteps. weights: Optional scalar or elementwise (per-batc...
Computes the actor_loss for SAC training. Args: time_steps: A batch of timesteps. weights: Optional scalar or elementwise (per-batch-entry) importance weights. training: Whether training should be applied. Returns: actor_loss: A scalar actor loss.
actor_loss
python
tensorflow/agents
tf_agents/agents/sac/sac_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py
Apache-2.0
def alpha_loss( self, time_steps: ts.TimeStep, weights: Optional[types.Tensor] = None, training: bool = False, ) -> types.Tensor: """Computes the alpha_loss for EC-SAC training. Args: time_steps: A batch of timesteps. weights: Optional scalar or elementwise (per-batch-entr...
Computes the alpha_loss for EC-SAC training. Args: time_steps: A batch of timesteps. weights: Optional scalar or elementwise (per-batch-entry) importance weights. training: Whether this loss is being used during training. Returns: alpha_loss: A scalar alpha loss.
alpha_loss
python
tensorflow/agents
tf_agents/agents/sac/sac_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/sac_agent.py
Apache-2.0
def __init__( self, sample_spec: types.TensorSpec, activation_fn: Optional[Callable[[types.Tensor], types.Tensor]] = None, std_transform: Optional[Callable[[types.Tensor], types.Tensor]] = tf.exp, name: Text = 'TanhNormalProjectionNetwork', ): """Creates an instance of TanhNormalProj...
Creates an instance of TanhNormalProjectionNetwork. Args: sample_spec: A `tensor_spec.BoundedTensorSpec` detailing the shape and dtypes of samples pulled from the output distribution. activation_fn: Activation function to use in dense layer. std_transform: Transformation function to apply...
__init__
python
tensorflow/agents
tf_agents/agents/sac/tanh_normal_projection_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/tanh_normal_projection_network.py
Apache-2.0
def train_eval( root_dir, env_name='HalfCheetah-v2', eval_env_name=None, env_load_fn=suite_mujoco.load, # The SAC paper reported: # Hopper and Cartpole results up to 1000000 iters, # Humanoid results up to 10000000 iters, # Other mujoco tasks up to 3000000 iters. num_iterations=30000...
A simple train and eval for SAC.
train_eval
python
tensorflow/agents
tf_agents/agents/sac/examples/v2/train_eval.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/examples/v2/train_eval.py
Apache-2.0
def train_eval( root_dir, env_name='cartpole', task_name='balance', observations_allowlist='position', eval_env_name=None, num_iterations=1000000, # Params for networks. actor_fc_layers=(400, 300), actor_output_fc_layers=(100,), actor_lstm_size=(40,), critic_obs_fc_layers=Non...
A simple train and eval for RNN SAC on DM control.
train_eval
python
tensorflow/agents
tf_agents/agents/sac/examples/v2/train_eval_rnn.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/sac/examples/v2/train_eval_rnn.py
Apache-2.0
def __init__( self, time_step_spec: ts.TimeStep, action_spec: types.NestedTensor, actor_network: network.Network, critic_network: network.Network, actor_optimizer: types.Optimizer, critic_optimizer: types.Optimizer, exploration_noise_std: types.Float = 0.1, critic_n...
Creates a Td3Agent Agent. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of BoundedTensorSpec representing the actions. actor_network: A tf_agents.network.Network to be used by the agent. The network will be called with call(observation, step_type)...
__init__
python
tensorflow/agents
tf_agents/agents/td3/td3_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py
Apache-2.0
def _initialize(self): """Initialize the agent. Copies weights from the actor and critic networks to the respective target actor and critic networks. """ common.soft_variables_update( self._critic_network_1.variables, self._target_critic_network_1.variables, tau=1.0, ) ...
Initialize the agent. Copies weights from the actor and critic networks to the respective target actor and critic networks.
_initialize
python
tensorflow/agents
tf_agents/agents/td3/td3_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py
Apache-2.0
def _get_target_updater(self, tau=1.0, period=1): """Performs a soft update of the target network parameters. For each weight w_s in the original network, and its corresponding weight w_t in the target network, a soft update is: w_t = (1- tau) x w_t + tau x ws Args: tau: A float scalar in [0...
Performs a soft update of the target network parameters. For each weight w_s in the original network, and its corresponding weight w_t in the target network, a soft update is: w_t = (1- tau) x w_t + tau x ws Args: tau: A float scalar in [0, 1]. Default `tau=1.0` means hard update. period: ...
_get_target_updater
python
tensorflow/agents
tf_agents/agents/td3/td3_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py
Apache-2.0
def critic_loss( self, time_steps: ts.TimeStep, actions: types.Tensor, next_time_steps: ts.TimeStep, weights: Optional[types.Tensor] = None, training: bool = False, ) -> types.Tensor: """Computes the critic loss for TD3 training. Args: time_steps: A batch of timestep...
Computes the critic loss for TD3 training. Args: time_steps: A batch of timesteps. actions: A batch of actions. next_time_steps: A batch of next timesteps. weights: Optional scalar or element-wise (per-batch-entry) importance weights. training: Whether this loss is being used ...
critic_loss
python
tensorflow/agents
tf_agents/agents/td3/td3_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py
Apache-2.0
def actor_loss( self, time_steps: ts.TimeStep, weights: Optional[types.Tensor] = None, training: bool = False, ) -> types.Tensor: """Computes the actor_loss for TD3 training. Args: time_steps: A batch of timesteps. weights: Optional scalar or element-wise (per-batch-entry)...
Computes the actor_loss for TD3 training. Args: time_steps: A batch of timesteps. weights: Optional scalar or element-wise (per-batch-entry) importance weights. training: Whether this loss is being used for training. Returns: actor_loss: A scalar actor loss.
actor_loss
python
tensorflow/agents
tf_agents/agents/td3/td3_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/agents/td3/td3_agent.py
Apache-2.0
def __init__( self, num_actions: int, dtype: tf.DType = tf.float32, name: Optional[Text] = None, ): """Initializes an instance of `BernoulliBanditVariableCollection`. It creates all the variables needed for `BernoulliThompsonSamplingAgent`. For each action, the agent maintains the...
Initializes an instance of `BernoulliBanditVariableCollection`. It creates all the variables needed for `BernoulliThompsonSamplingAgent`. For each action, the agent maintains the `alpha` and `beta` parameters of the beta distribution. Args: num_actions: (int) The number of actions. dtype: ...
__init__
python
tensorflow/agents
tf_agents/bandits/agents/bernoulli_thompson_sampling_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/bernoulli_thompson_sampling_agent.py
Apache-2.0
def selective_sum( values: types.Tensor, partitions: types.Int, num_partitions: int ) -> types.Tensor: """Sums entries in `values`, partitioned using `partitions`. For example, ```python # Returns `[0 + 4 + 5, 2 + 3 + 4]` i.e. `[9, 6]`. selective_sum(values=[0, 1, 2, 3, 4, 5], p...
Sums entries in `values`, partitioned using `partitions`. For example, ```python # Returns `[0 + 4 + 5, 2 + 3 + 4]` i.e. `[9, 6]`. selective_sum(values=[0, 1, 2, 3, 4, 5], partitions=[0, 1, 1, 1, 0, 0]), num_partitions=2) ``` Args: values: a `Tensor` with n...
selective_sum
python
tensorflow/agents
tf_agents/bandits/agents/exp3_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_agent.py
Apache-2.0
def __init__( self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, learning_rate: float, name: Optional[Text] = None, ): """Initialize an instance of `Exp3Agent`. Args: time_step_spec: A `TimeStep` spec describing the expected `TimeStep`s. acti...
Initialize an instance of `Exp3Agent`. Args: time_step_spec: A `TimeStep` spec describing the expected `TimeStep`s. action_spec: A scalar `BoundedTensorSpec` with `int32` or `int64` dtype describing the number of actions for this agent. learning_rate: A float valued scalar. A higher value...
__init__
python
tensorflow/agents
tf_agents/bandits/agents/exp3_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_agent.py
Apache-2.0
def _train(self, experience, weights=None): """Updates the policy based on the data in `experience`. Note that `experience` should only contain data points that this agent has not previously seen. If `experience` comes from a replay buffer, this buffer should be cleared between each call to `train`. ...
Updates the policy based on the data in `experience`. Note that `experience` should only contain data points that this agent has not previously seen. If `experience` comes from a replay buffer, this buffer should be cleared between each call to `train`. Args: experience: A batch of experience da...
_train
python
tensorflow/agents
tf_agents/bandits/agents/exp3_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_agent.py
Apache-2.0
def testExp3Update( self, observation_shape, num_actions, action, log_prob, reward, learning_rate, ): """Check EXP3 updates for specified actions and rewards.""" # Compute expected update for each action. expected_update_value = exp3_agent.exp3_update_value(rewar...
Check EXP3 updates for specified actions and rewards.
testExp3Update
python
tensorflow/agents
tf_agents/bandits/agents/exp3_agent_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_agent_test.py
Apache-2.0
def __init__( self, num_agents: int, reward_aggregates: Optional[List[float]] = None, inverse_temperature: float = 0.0, ): """Initializes an instace of 'Exp3MixtureVariableCollection'. Args: num_agents: (int) the number of agents mixed by the mixture agent. reward_aggregat...
Initializes an instace of 'Exp3MixtureVariableCollection'. Args: num_agents: (int) the number of agents mixed by the mixture agent. reward_aggregates: A list of floats containing the reward aggregates for each agent. If not set, the initial values will be 0. inverse_temperature: The initi...
__init__
python
tensorflow/agents
tf_agents/bandits/agents/exp3_mixture_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_mixture_agent.py
Apache-2.0
def __init__( self, agents: List[tf_agent.TFAgent], variable_collection: Optional[Exp3MixtureVariableCollection] = None, forgetting: float = 0.999, max_inverse_temperature: float = 1000.0, name: Optional[Text] = None, ): """Initializes an instance of `Exp3MixtureAgent`. Ar...
Initializes an instance of `Exp3MixtureAgent`. Args: agents: List of TF-Agents agents that this mixture agent trains. variable_collection: An instance of `Exp3VariableCollection`. If not set, A default one will be created. It contains all the variables that are needed to restore the mix...
__init__
python
tensorflow/agents
tf_agents/bandits/agents/exp3_mixture_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/exp3_mixture_agent.py
Apache-2.0
def _single_objective_loss( self, objective_idx: int, observations: tf.Tensor, actions: tf.Tensor, single_objective_values: tf.Tensor, weights: types.Tensor = None, training: bool = False, ) -> tf.Tensor: """Computes loss for a single objective. Args: objective...
Computes loss for a single objective. Args: objective_idx: The index into `self._objective_networks` for a specific objective network. observations: A batch of observations. actions: A batch of actions. single_objective_values: A batch of objective values shaped as [batch_si...
_single_objective_loss
python
tensorflow/agents
tf_agents/bandits/agents/greedy_multi_objective_neural_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_multi_objective_neural_agent.py
Apache-2.0
def _loss( self, experience: types.NestedTensor, weights: types.Tensor = None, training: bool = False, ) -> tf_agent.LossInfo: """Computes loss for training the objective networks. Args: experience: A batch of experience data in the form of a `Trajectory` or `Transition`...
Computes loss for training the objective networks. Args: experience: A batch of experience data in the form of a `Trajectory` or `Transition`. weights: Optional scalar or elementwise (per-batch-entry) importance weights. The output batch loss will be scaled by these weights, and the ...
_loss
python
tensorflow/agents
tf_agents/bandits/agents/greedy_multi_objective_neural_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_multi_objective_neural_agent.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/agents/greedy_multi_objective_neural_agent_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_multi_objective_neural_agent_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/agents/greedy_multi_objective_neural_agent_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_multi_objective_neural_agent_test.py
Apache-2.0
def per_example_reward_loss( self, observations: types.NestedTensor, actions: types.Tensor, rewards: types.Tensor, weights: Optional[types.Float] = None, training: bool = False, ) -> types.Tensor: """Computes loss for reward prediction training. Args: observations: A...
Computes loss for reward prediction training. Args: observations: A batch of observations. actions: A batch of actions. rewards: A batch of rewards. weights: Optional scalar or elementwise (per-batch-entry) importance weights. The output batch loss will be scaled by these weights, ...
per_example_reward_loss
python
tensorflow/agents
tf_agents/bandits/agents/greedy_reward_prediction_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_reward_prediction_agent.py
Apache-2.0
def _loss( self, experience: types.NestedTensor, weights: Optional[types.Float] = None, training: bool = False, ) -> tf_agent.LossInfo: """Computes loss for training the reward and constraint networks. Args: experience: A batch of experience data in the form of a `Trajectory` or...
Computes loss for training the reward and constraint networks. Args: experience: A batch of experience data in the form of a `Trajectory` or `Transition`. weights: Optional scalar or elementwise (per-batch-entry) importance weights. The output batch loss will be scaled by these weights...
_loss
python
tensorflow/agents
tf_agents/bandits/agents/greedy_reward_prediction_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/greedy_reward_prediction_agent.py
Apache-2.0
def __init__( self, context_dim: int, num_models: int, use_eigendecomp: bool = False, dtype: tf.DType = tf.float32, name: Optional[Text] = None, ): """Initializes an instance of `LinearBanditVariableCollection`. It creates all the variables needed for `LinearBanditAgent`. ...
Initializes an instance of `LinearBanditVariableCollection`. It creates all the variables needed for `LinearBanditAgent`. Args: context_dim: (int) The context dimension of the bandit environment the agent will be used on. num_models: (int) The number of models maintained by the agent. This...
__init__
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py
Apache-2.0
def update_a_and_b_with_forgetting( a_prev: types.Tensor, b_prev: types.Tensor, r: types.Tensor, x: types.Tensor, gamma: float, ) -> Tuple[types.Tensor, types.Tensor]: r"""Update the covariance matrix `a` and the weighted sum of rewards `b`. This function updates the covariance matrix `a` and t...
Update the covariance matrix `a` and the weighted sum of rewards `b`. This function updates the covariance matrix `a` and the sum of weighted rewards `b` using a forgetting factor `gamma`. Args: a_prev: previous estimate of `a`. b_prev: previous estimate of `b`. r: a `Tensor` of shape [`batch_size`]...
update_a_and_b_with_forgetting
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py
Apache-2.0
def theta(self): """Returns the matrix of per-arm feature weights. The returned matrix has shape (num_actions, context_dim). It's equivalent to a stacking of theta vectors from the paper. """ thetas = [] for k in range(self._num_models): if self._use_eigendecomp: model_index = pol...
Returns the matrix of per-arm feature weights. The returned matrix has shape (num_actions, context_dim). It's equivalent to a stacking of theta vectors from the paper.
theta
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py
Apache-2.0
def _process_experience(self, experience): """Given an experience, returns reward, action, observation, and batch size.""" if self._accepts_per_arm_features: return self._process_experience_per_arm(experience) else: return self._process_experience_global(experience)
Given an experience, returns reward, action, observation, and batch size.
_process_experience
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py
Apache-2.0
def _process_experience_per_arm(self, experience): """Processes the experience in case the agent accepts per-arm features. In the experience coming from the replay buffer, the reward (and all other elements) have two batch dimensions `batch_size` and `time_steps`, where `time_steps` is the number of dr...
Processes the experience in case the agent accepts per-arm features. In the experience coming from the replay buffer, the reward (and all other elements) have two batch dimensions `batch_size` and `time_steps`, where `time_steps` is the number of driver steps executed in each training loop. We flatten ...
_process_experience_per_arm
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py
Apache-2.0
def _process_experience_global(self, experience): """Processes the experience in case the agent accepts only global features. In the experience coming from the replay buffer, the reward (and all other elements) have two batch dimensions `batch_size` and `time_steps`, where `time_steps` is the number of...
Processes the experience in case the agent accepts only global features. In the experience coming from the replay buffer, the reward (and all other elements) have two batch dimensions `batch_size` and `time_steps`, where `time_steps` is the number of driver steps executed in each training loop. We flat...
_process_experience_global
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py
Apache-2.0
def _maybe_apply_per_example_weight( self, observation: tf.Tensor, reward: tf.Tensor, weights: Optional[tf.Tensor], ) -> Tuple[tf.Tensor, tf.Tensor]: """Optionally applies per-example weight to observation and rewards.""" if weights is None: return (observation, reward) else:...
Optionally applies per-example weight to observation and rewards.
_maybe_apply_per_example_weight
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py
Apache-2.0
def _distributed_train_step(self, experience, weights=None): """Distributed train fn to be passed as input to run().""" experience_reward, action, experience_observation, batch_size = ( self._process_experience(experience) ) self._train_step_counter.assign_add(batch_size) observation, reward...
Distributed train fn to be passed as input to run().
_distributed_train_step
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py
Apache-2.0
def _train(self, experience, weights=None): """Updates the policy based on the data in `experience`. Note that `experience` should only contain data points that this agent has not previously seen. If `experience` comes from a replay buffer, this buffer should be cleared between each call to `train`. ...
Updates the policy based on the data in `experience`. Note that `experience` should only contain data points that this agent has not previously seen. If `experience` comes from a replay buffer, this buffer should be cleared between each call to `train`. Args: experience: A batch of experience da...
_train
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent.py
Apache-2.0
def testLinearAgentUpdate( self, batch_size, context_dim, exploration_policy, dtype, use_eigendecomp=False, set_example_weights=False, ): """Check that the agent updates for specified actions and rewards.""" # Construct a `Trajectory` for the given action, observatio...
Check that the agent updates for specified actions and rewards.
testLinearAgentUpdate
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent_test.py
Apache-2.0
def testDistributedLinearAgentUpdate( self, batch_size, context_dim, exploration_policy, dtype, use_eigendecomp=False, set_example_weights=False, ): """Same as above, but uses the distributed train function of the agent.""" del use_eigendecomp # Unused in this test. ...
Same as above, but uses the distributed train function of the agent.
testDistributedLinearAgentUpdate
python
tensorflow/agents
tf_agents/bandits/agents/linear_bandit_agent_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/linear_bandit_agent_test.py
Apache-2.0
def _dynamic_partition_of_nested_tensors( nested_tensor: types.NestedTensor, partitions: types.Int, num_partitions: int, ) -> List[types.NestedTensor]: """This function takes a nested structure and partitions every element of it. Specifically it outputs a list of nest that all have the same structure a...
This function takes a nested structure and partitions every element of it. Specifically it outputs a list of nest that all have the same structure as the original, and every element of the list is a nest that contains a dynamic partition of the corresponding original tensors. Note that this function uses tf.d...
_dynamic_partition_of_nested_tensors
python
tensorflow/agents
tf_agents/bandits/agents/mixture_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/mixture_agent.py
Apache-2.0
def __init__( self, mixture_distribution: types.Distribution, agents: Sequence[tf_agent.TFAgent], name: Optional[Text] = None, ): """Initializes an instance of `MixtureAgent`. Args: mixture_distribution: An instance of `tfd.Categorical` distribution. This distribution is...
Initializes an instance of `MixtureAgent`. Args: mixture_distribution: An instance of `tfd.Categorical` distribution. This distribution is used to draw sub-policies by the mixture policy. The parameters of the distribution is trained by the mixture agent. agents: List of instances of TF...
__init__
python
tensorflow/agents
tf_agents/bandits/agents/mixture_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/mixture_agent.py
Apache-2.0
def _update_mixture_distribution(self, experience): """This function updates the mixture weights given training experience.""" raise NotImplementedError( '`_update_mixture_distribution` should be ' 'implemented by subclasses of `MixtureAgent`.' )
This function updates the mixture weights given training experience.
_update_mixture_distribution
python
tensorflow/agents
tf_agents/bandits/agents/mixture_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/mixture_agent.py
Apache-2.0
def __init__( self, num_actions: int, encoding_dim: int, dtype: tf.DType = tf.float64, name: Optional[Text] = None, ): """Initializes an instance of `NeuralLinUCBVariableCollection`. Args: num_actions: (int) number of actions the agent acts on. encoding_dim: (int) Th...
Initializes an instance of `NeuralLinUCBVariableCollection`. Args: num_actions: (int) number of actions the agent acts on. encoding_dim: (int) The dimensionality of the output of the encoding network. dtype: The type of the variables. Should be one of `tf.float32` and `tf.float64`...
__init__
python
tensorflow/agents
tf_agents/bandits/agents/neural_linucb_agent.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/neural_linucb_agent.py
Apache-2.0