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_kl_constraint(self, all_samples, all_params, set_grad=True): """Compute KL divergence. For each task, compute the KL divergence between the old policy distribution and current policy distribution. Args: all_samples (list[list[_MAMLEpisodeBatch]]): Two ...
Compute KL divergence. For each task, compute the KL divergence between the old policy distribution and current policy distribution. Args: all_samples (list[list[_MAMLEpisodeBatch]]): Two dimensional list of _MAMLEpisodeBatch of size [meta_batch_size...
_compute_kl_constraint
python
rlworkgroup/garage
src/garage/torch/algos/maml.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/maml.py
MIT
def _compute_policy_entropy(self, task_samples): """Compute policy entropy. Args: task_samples (list[_MAMLEpisodeBatch]): Samples data for one task. Returns: torch.Tensor: Computed entropy value. """ obs = torch.cat([samples.observations...
Compute policy entropy. Args: task_samples (list[_MAMLEpisodeBatch]): Samples data for one task. Returns: torch.Tensor: Computed entropy value.
_compute_policy_entropy
python
rlworkgroup/garage
src/garage/torch/algos/maml.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/maml.py
MIT
def _process_samples(self, episodes): """Process sample data based on the collected paths. Args: episodes (EpisodeBatch): Collected batch of episodes. Returns: _MAMLEpisodeBatch: Processed samples data. """ paths = episodes.to_list() for path in...
Process sample data based on the collected paths. Args: episodes (EpisodeBatch): Collected batch of episodes. Returns: _MAMLEpisodeBatch: Processed samples data.
_process_samples
python
rlworkgroup/garage
src/garage/torch/algos/maml.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/maml.py
MIT
def _log_performance(self, itr, all_samples, loss_before, loss_after, kl_before, kl, policy_entropy): """Evaluate performance of this batch. Args: itr (int): Iteration number. all_samples (list[list[_MAMLEpisodeBatch]]): Two dimensional l...
Evaluate performance of this batch. Args: itr (int): Iteration number. all_samples (list[list[_MAMLEpisodeBatch]]): Two dimensional list of _MAMLEpisodeBatch of size [meta_batch_size * (num_grad_updates + 1)] loss_before (float): Loss before o...
_log_performance
python
rlworkgroup/garage
src/garage/torch/algos/maml.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/maml.py
MIT
def adapt_policy(self, exploration_policy, exploration_episodes): """Adapt the policy by one gradient steps for a task. Args: exploration_policy (Policy): A policy which was returned from get_exploration_policy(), and which generated exploration_episodes by i...
Adapt the policy by one gradient steps for a task. Args: exploration_policy (Policy): A policy which was returned from get_exploration_policy(), and which generated exploration_episodes by interacting with an environment. The caller may not use this o...
adapt_policy
python
rlworkgroup/garage
src/garage/torch/algos/maml.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/maml.py
MIT
def _get_log_alpha(self, samples_data): """Return the value of log_alpha. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'terminal', and 'next_observations'....
Return the value of log_alpha. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'terminal', and 'next_observations'. Note: samples_data's entries ...
_get_log_alpha
python
rlworkgroup/garage
src/garage/torch/algos/mtsac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/mtsac.py
MIT
def _evaluate_policy(self, epoch): """Evaluate the performance of the policy via deterministic sampling. Statistics such as (average) discounted return and success rate are recorded. Args: epoch (int): The current training epoch. Returns: float:...
Evaluate the performance of the policy via deterministic sampling. Statistics such as (average) discounted return and success rate are recorded. Args: epoch (int): The current training epoch. Returns: float: The average return across self._num_evaluatio...
_evaluate_policy
python
rlworkgroup/garage
src/garage/torch/algos/mtsac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/mtsac.py
MIT
def to(self, device=None): """Put all the networks within the model on device. Args: device (str): ID of GPU or CPU. """ super().to(device) if device is None: device = global_device() if not self._use_automatic_entropy_tuning: self._l...
Put all the networks within the model on device. Args: device (str): ID of GPU or CPU.
to
python
rlworkgroup/garage
src/garage/torch/algos/mtsac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/mtsac.py
MIT
def __getstate__(self): """Object.__getstate__. Returns: dict: the state to be pickled for the instance. """ data = self.__dict__.copy() del data['_replay_buffers'] del data['_context_replay_buffers'] return data
Object.__getstate__. Returns: dict: the state to be pickled for the instance.
__getstate__
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def __setstate__(self, state): """Object.__setstate__. Args: state (dict): unpickled state. """ self.__dict__.update(state) self._replay_buffers = { i: PathBuffer(self._replay_buffer_size) for i in range(self._num_train_tasks) } ...
Object.__setstate__. Args: state (dict): unpickled state.
__setstate__
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def train(self, trainer): """Obtain samples, train, and evaluate for each epoch. Args: trainer (Trainer): Gives the algorithm the access to :method:`Trainer..step_epochs()`, which provides services such as snapshotting and sampler control. """ ...
Obtain samples, train, and evaluate for each epoch. Args: trainer (Trainer): Gives the algorithm the access to :method:`Trainer..step_epochs()`, which provides services such as snapshotting and sampler control.
train
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def _optimize_policy(self, indices): """Perform algorithm optimizing. Args: indices (list): Tasks used for training. """ num_tasks = len(indices) context = self._sample_context(indices) # clear context and reset belief of policy self._policy.reset_be...
Perform algorithm optimizing. Args: indices (list): Tasks used for training.
_optimize_policy
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def _obtain_samples(self, trainer, itr, num_samples, update_posterior_rate, add_to_enc_buffer=True): """Obtain samples. Args: trainer (Trainer): Trainer. itr (...
Obtain samples. Args: trainer (Trainer): Trainer. itr (int): Index of iteration (epoch). num_samples (int): Number of samples to obtain. update_posterior_rate (int): How often (in episodes) to infer posterior of policy. add_to_enc_buff...
_obtain_samples
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def _sample_data(self, indices): """Sample batch of training data from a list of tasks. Args: indices (list): List of task indices to sample from. Returns: torch.Tensor: Obervations, with shape :math:`(X, N, O^*)` where X is the number of tasks. N is bat...
Sample batch of training data from a list of tasks. Args: indices (list): List of task indices to sample from. Returns: torch.Tensor: Obervations, with shape :math:`(X, N, O^*)` where X is the number of tasks. N is batch size. torch.Tensor: Actions, ...
_sample_data
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def _sample_context(self, indices): """Sample batch of context from a list of tasks. Args: indices (list): List of task indices to sample from. Returns: torch.Tensor: Context data, with shape :math:`(X, N, C)`. X is the number of tasks. N is batch size. ...
Sample batch of context from a list of tasks. Args: indices (list): List of task indices to sample from. Returns: torch.Tensor: Context data, with shape :math:`(X, N, C)`. X is the number of tasks. N is batch size. C is the combined size of obser...
_sample_context
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def _update_target_network(self): """Update parameters in the target vf network.""" for target_param, param in zip(self.target_vf.parameters(), self._vf.parameters()): target_param.data.copy_(target_param.data * (1.0 ...
Update parameters in the target vf network.
_update_target_network
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def networks(self): """Return all the networks within the model. Returns: list: A list of networks. """ return self._policy.networks + [self._policy] + [ self._qf1, self._qf2, self._vf, self.target_vf ]
Return all the networks within the model. Returns: list: A list of networks.
networks
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def adapt_policy(self, exploration_policy, exploration_episodes): """Produce a policy adapted for a task. Args: exploration_policy (Policy): A policy which was returned from get_exploration_policy(), and which generated exploration_episodes by interacting wit...
Produce a policy adapted for a task. Args: exploration_policy (Policy): A policy which was returned from get_exploration_policy(), and which generated exploration_episodes by interacting with an environment. The caller may not use this object after pa...
adapt_policy
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def to(self, device=None): """Put all the networks within the model on device. Args: device (str): ID of GPU or CPU. """ device = device or global_device() for net in self.networks: net.to(device)
Put all the networks within the model on device. Args: device (str): ID of GPU or CPU.
to
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def augment_env_spec(cls, env_spec, latent_dim): """Augment environment by a size of latent dimension. Args: env_spec (EnvSpec): Environment specs to be augmented. latent_dim (int): Latent dimension. Returns: EnvSpec: Augmented environment specs. ""...
Augment environment by a size of latent dimension. Args: env_spec (EnvSpec): Environment specs to be augmented. latent_dim (int): Latent dimension. Returns: EnvSpec: Augmented environment specs.
augment_env_spec
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def get_env_spec(cls, env_spec, latent_dim, module): """Get environment specs of encoder with latent dimension. Args: env_spec (EnvSpec): Environment specification. latent_dim (int): Latent dimension. module (str): Module to get environment specs for. Return...
Get environment specs of encoder with latent dimension. Args: env_spec (EnvSpec): Environment specification. latent_dim (int): Latent dimension. module (str): Module to get environment specs for. Returns: InOutSpec: Module environment specs with latent d...
get_env_spec
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def step_episode(self): """Take a single time-step in the current episode. Returns: bool: True iff the episode is done, either due to the environment indicating termination of due to reaching `max_episode_length`. """ if self._eps_length < self._max_episode_leng...
Take a single time-step in the current episode. Returns: bool: True iff the episode is done, either due to the environment indicating termination of due to reaching `max_episode_length`.
step_episode
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def rollout(self): """Sample a single episode of the agent in the environment. Returns: EpisodeBatch: The collected episode. """ self.agent.sample_from_belief() self.start_episode() while not self.step_episode(): pass return self.collect_...
Sample a single episode of the agent in the environment. Returns: EpisodeBatch: The collected episode.
rollout
python
rlworkgroup/garage
src/garage/torch/algos/pearl.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/pearl.py
MIT
def _compute_objective(self, advantages, obs, actions, rewards): r"""Compute objective value. Args: advantages (torch.Tensor): Advantage value at each step with shape :math:`(N \dot [T], )`. obs (torch.Tensor): Observation from the environment wit...
Compute objective value. Args: advantages (torch.Tensor): Advantage value at each step with shape :math:`(N \dot [T], )`. obs (torch.Tensor): Observation from the environment with shape :math:`(N \dot [T], O*)`. actions (torch.Tensor): Actions...
_compute_objective
python
rlworkgroup/garage
src/garage/torch/algos/ppo.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/ppo.py
MIT
def train(self, trainer): """Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Gives the algorithm the access to :method:`~Trainer.step_epochs()`, which provides services such as snapshotting and sampler control. Retu...
Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Gives the algorithm the access to :method:`~Trainer.step_epochs()`, which provides services such as snapshotting and sampler control. Returns: float: The average r...
train
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def train_once(self, itr=None, paths=None): """Complete 1 training iteration of SAC. Args: itr (int): Iteration number. This argument is deprecated. paths (list[dict]): A list of collected paths. This argument is deprecated. Returns: torch.Te...
Complete 1 training iteration of SAC. Args: itr (int): Iteration number. This argument is deprecated. paths (list[dict]): A list of collected paths. This argument is deprecated. Returns: torch.Tensor: loss from actor/policy network after optimization...
train_once
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def _get_log_alpha(self, samples_data): """Return the value of log_alpha. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'terminal', and 'next_observations'....
Return the value of log_alpha. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'terminal', and 'next_observations'. This function exists in case there are ve...
_get_log_alpha
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def _temperature_objective(self, log_pi, samples_data): """Compute the temperature/alpha coefficient loss. Args: log_pi(torch.Tensor): log probability of actions that are sampled from the replay buffer. Shape is (1, buffer_batch_size). samples_data (dict): Transi...
Compute the temperature/alpha coefficient loss. Args: log_pi(torch.Tensor): log probability of actions that are sampled from the replay buffer. Shape is (1, buffer_batch_size). samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay bu...
_temperature_objective
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def _actor_objective(self, samples_data, new_actions, log_pi_new_actions): """Compute the Policy/Actor loss. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', '...
Compute the Policy/Actor loss. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'terminal', and 'next_observations'. new_actions (torch.Tensor): Actions re...
_actor_objective
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def _critic_objective(self, samples_data): """Compute the Q-function/critic loss. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'terminal', and 'next_observ...
Compute the Q-function/critic loss. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'terminal', and 'next_observations'. Note: samples_data's ent...
_critic_objective
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def _caps_regularization_objective(self, action_dists, samples_data): """Compute the spatial and temporal regularization loss as in CAPS. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', ...
Compute the spatial and temporal regularization loss as in CAPS. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'terminal', and 'next_observations'. acti...
_caps_regularization_objective
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def _update_targets(self): """Update parameters in the target q-functions.""" target_qfs = [self._target_qf1, self._target_qf2] qfs = [self._qf1, self._qf2] for target_qf, qf in zip(target_qfs, qfs): for t_param, param in zip(target_qf.parameters(), qf.parameters()): ...
Update parameters in the target q-functions.
_update_targets
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def optimize_policy(self, samples_data): """Optimize the policy q_functions, and temperature coefficient. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'ter...
Optimize the policy q_functions, and temperature coefficient. Args: samples_data (dict): Transitions(S,A,R,S') that are sampled from the replay buffer. It should have the keys 'observation', 'action', 'reward', 'terminal', and 'next_observations'. Note: ...
optimize_policy
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def _evaluate_policy(self, epoch): """Evaluate the performance of the policy via deterministic sampling. Statistics such as (average) discounted return and success rate are recorded. Args: epoch (int): The current training epoch. Returns: float:...
Evaluate the performance of the policy via deterministic sampling. Statistics such as (average) discounted return and success rate are recorded. Args: epoch (int): The current training epoch. Returns: float: The average return across self._num_evaluatio...
_evaluate_policy
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def _log_statistics(self, policy_loss, qf1_loss, qf2_loss): """Record training statistics to dowel such as losses and returns. Args: policy_loss (torch.Tensor): loss from actor/policy network. qf1_loss (torch.Tensor): loss from 1st qf/critic network. qf2_loss (torch....
Record training statistics to dowel such as losses and returns. Args: policy_loss (torch.Tensor): loss from actor/policy network. qf1_loss (torch.Tensor): loss from 1st qf/critic network. qf2_loss (torch.Tensor): loss from 2nd qf/critic network.
_log_statistics
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def networks(self): """Return all the networks within the model. Returns: list: A list of networks. """ return [ self.policy, self._qf1, self._qf2, self._target_qf1, self._target_qf2 ]
Return all the networks within the model. Returns: list: A list of networks.
networks
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def to(self, device=None): """Put all the networks within the model on device. Args: device (str): ID of GPU or CPU. """ if device is None: device = global_device() for net in self.networks: net.to(device) if not self._use_automatic_e...
Put all the networks within the model on device. Args: device (str): ID of GPU or CPU.
to
python
rlworkgroup/garage
src/garage/torch/algos/sac.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/sac.py
MIT
def _get_action(self, action, noise_scale): """Select action based on policy. Action can be added with noise. Args: action (float): Action. noise_scale (float): Noise scale added to action. Return: float: Action selected by the policy. """ ...
Select action based on policy. Action can be added with noise. Args: action (float): Action. noise_scale (float): Noise scale added to action. Return: float: Action selected by the policy.
_get_action
python
rlworkgroup/garage
src/garage/torch/algos/td3.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/td3.py
MIT
def train(self, trainer): """Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Experiment trainer, which provides services such as snapshotting and sampler control. """ if not self._eval_env: self._eval_env = trai...
Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Experiment trainer, which provides services such as snapshotting and sampler control.
train
python
rlworkgroup/garage
src/garage/torch/algos/td3.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/td3.py
MIT
def _train_once(self, itr): """Perform one iteration of training. Args: itr (int): Iteration number. """ for grad_step_timer in range(self._grad_steps_per_env_step): if (self._replay_buffer.n_transitions_stored >= self._min_buffer_size): ...
Perform one iteration of training. Args: itr (int): Iteration number.
_train_once
python
rlworkgroup/garage
src/garage/torch/algos/td3.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/td3.py
MIT
def _optimize_policy(self, samples_data, grad_step_timer): """Perform algorithm optimization. Args: samples_data (dict): Processed batch data. grad_step_timer (int): Iteration number of the gradient time taken in the env. Returns: float: Loss...
Perform algorithm optimization. Args: samples_data (dict): Processed batch data. grad_step_timer (int): Iteration number of the gradient time taken in the env. Returns: float: Loss predicted by the q networks (critic networks). ...
_optimize_policy
python
rlworkgroup/garage
src/garage/torch/algos/td3.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/td3.py
MIT
def _evaluate_policy(self): """Evaluate the performance of the policy via deterministic rollouts. Statistics such as (average) discounted return and success rate are recorded. Returns: TrajectoryBatch: Evaluation trajectories, representing the best curre...
Evaluate the performance of the policy via deterministic rollouts. Statistics such as (average) discounted return and success rate are recorded. Returns: TrajectoryBatch: Evaluation trajectories, representing the best current performance of the algorithm. ...
_evaluate_policy
python
rlworkgroup/garage
src/garage/torch/algos/td3.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/td3.py
MIT
def _update_network_parameters(self): """Update parameters in actor network and critic networks.""" soft_update_model(self._target_qf_1, self._qf_1, self._tau) soft_update_model(self._target_qf_2, self._qf_2, self._tau) soft_update_model(self._target_policy, self.policy, self._tau)
Update parameters in actor network and critic networks.
_update_network_parameters
python
rlworkgroup/garage
src/garage/torch/algos/td3.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/td3.py
MIT
def _log_statistics(self): """Output training statistics to dowel such as losses and returns.""" tabular.record('Policy/AveragePolicyLoss', np.mean(self._episode_policy_losses)) tabular.record('QFunction/AverageQFunctionLoss', np.mean(self._episode_q...
Output training statistics to dowel such as losses and returns.
_log_statistics
python
rlworkgroup/garage
src/garage/torch/algos/td3.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/td3.py
MIT
def networks(self): """Return all the networks within the model. Returns: list: A list of networks. """ return [ self.policy, self._qf_1, self._qf_2, self._target_policy, self._target_qf_1, self._target_qf_2 ]
Return all the networks within the model. Returns: list: A list of networks.
networks
python
rlworkgroup/garage
src/garage/torch/algos/td3.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/td3.py
MIT
def to(self, device=None): """Put all the networks within the model on device. Args: device (str): ID of GPU or CPU. """ device = device or global_device() for net in self.networks: net.to(device)
Put all the networks within the model on device. Args: device (str): ID of GPU or CPU.
to
python
rlworkgroup/garage
src/garage/torch/algos/td3.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/td3.py
MIT
def _compute_objective(self, advantages, obs, actions, rewards): r"""Compute objective value. Args: advantages (torch.Tensor): Advantage value at each step with shape :math:`(N \dot [T], )`. obs (torch.Tensor): Observation from the environment wit...
Compute objective value. Args: advantages (torch.Tensor): Advantage value at each step with shape :math:`(N \dot [T], )`. obs (torch.Tensor): Observation from the environment with shape :math:`(N \dot [T], O*)`. actions (torch.Tensor): Actions...
_compute_objective
python
rlworkgroup/garage
src/garage/torch/algos/trpo.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/trpo.py
MIT
def _train_policy(self, obs, actions, rewards, advantages): r"""Train the policy. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, O*)`. actions (torch.Tensor): Actions fed to the environment with shape :math:`(N, A...
Train the policy. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, O*)`. actions (torch.Tensor): Actions fed to the environment with shape :math:`(N, A*)`. rewards (torch.Tensor): Acquired rewards ...
_train_policy
python
rlworkgroup/garage
src/garage/torch/algos/trpo.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/trpo.py
MIT
def _train_once(self, itr, eps): """Train the algorithm once. Args: itr (int): Iteration number. eps (EpisodeBatch): A batch of collected paths. Returns: numpy.float64: Calculated mean value of undiscounted returns. """ obs = np_to_torch(eps...
Train the algorithm once. Args: itr (int): Iteration number. eps (EpisodeBatch): A batch of collected paths. Returns: numpy.float64: Calculated mean value of undiscounted returns.
_train_once
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def train(self, trainer): """Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Gives the algorithm the access to :method:`~Trainer.step_epochs()`, which provides services such as snapshotting and sampler control. Retu...
Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Gives the algorithm the access to :method:`~Trainer.step_epochs()`, which provides services such as snapshotting and sampler control. Returns: float: The average r...
train
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def _train(self, obs, actions, rewards, returns, advs): r"""Train the policy and value function with minibatch. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, O*)`. actions (torch.Tensor): Actions fed to the environment with shap...
Train the policy and value function with minibatch. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, O*)`. actions (torch.Tensor): Actions fed to the environment with shape :math:`(N, A*)`. rewards (torch.Tensor...
_train
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def _train_policy(self, obs, actions, rewards, advantages): r"""Train the policy. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, O*)`. actions (torch.Tensor): Actions fed to the environment with shape :math:`(N, A...
Train the policy. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, O*)`. actions (torch.Tensor): Actions fed to the environment with shape :math:`(N, A*)`. rewards (torch.Tensor): Acquired rewards ...
_train_policy
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def _train_value_function(self, obs, returns): r"""Train the value function. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, O*)`. returns (torch.Tensor): Acquired returns with shape :math:`(N, )`. Returns...
Train the value function. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, O*)`. returns (torch.Tensor): Acquired returns with shape :math:`(N, )`. Returns: torch.Tensor: Calculated mean scalar value of...
_train_value_function
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def _compute_loss(self, obs, actions, rewards, valids, baselines): r"""Compute mean value of loss. Notes: P is the maximum episode length (self.max_episode_length) Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, P, O*)`. ...
Compute mean value of loss. Notes: P is the maximum episode length (self.max_episode_length) Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, P, O*)`. actions (torch.Tensor): Actions fed to the environment with sha...
_compute_loss
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def _compute_loss_with_adv(self, obs, actions, rewards, advantages): r"""Compute mean value of loss. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N \dot [T], O*)`. actions (torch.Tensor): Actions fed to the environment ...
Compute mean value of loss. Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N \dot [T], O*)`. actions (torch.Tensor): Actions fed to the environment with shape :math:`(N \dot [T], A*)`. rewards (torch.Tensor): Acq...
_compute_loss_with_adv
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def _compute_advantage(self, rewards, valids, baselines): r"""Compute mean value of loss. Notes: P is the maximum episode length (self.max_episode_length) Args: rewards (torch.Tensor): Acquired rewards with shape :math:`(N, P)`. valids (list[int]): Numbe...
Compute mean value of loss. Notes: P is the maximum episode length (self.max_episode_length) Args: rewards (torch.Tensor): Acquired rewards with shape :math:`(N, P)`. valids (list[int]): Numbers of valid steps in each episode baselines (torch.Tensor)...
_compute_advantage
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def _compute_kl_constraint(self, obs): r"""Compute KL divergence. Compute the KL divergence between the old policy distribution and current policy distribution. Notes: P is the maximum episode length (self.max_episode_length) Args: obs (torch.Tensor): Observation f...
Compute KL divergence. Compute the KL divergence between the old policy distribution and current policy distribution. Notes: P is the maximum episode length (self.max_episode_length) Args: obs (torch.Tensor): Observation from the environment with shape :mat...
_compute_kl_constraint
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def _compute_policy_entropy(self, obs): r"""Compute entropy value of probability distribution. Notes: P is the maximum episode length (self.max_episode_length) Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, P, O*)`. Returns...
Compute entropy value of probability distribution. Notes: P is the maximum episode length (self.max_episode_length) Args: obs (torch.Tensor): Observation from the environment with shape :math:`(N, P, O*)`. Returns: torch.Tensor: Calculated entropy value...
_compute_policy_entropy
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def _compute_objective(self, advantages, obs, actions, rewards): r"""Compute objective value. Args: advantages (torch.Tensor): Advantage value at each step with shape :math:`(N \dot [T], )`. obs (torch.Tensor): Observation from the environment wit...
Compute objective value. Args: advantages (torch.Tensor): Advantage value at each step with shape :math:`(N \dot [T], )`. obs (torch.Tensor): Observation from the environment with shape :math:`(N \dot [T], O*)`. actions (torch.Tensor): Actions...
_compute_objective
python
rlworkgroup/garage
src/garage/torch/algos/vpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/vpg.py
MIT
def log_prob(self, value, pre_tanh_value=None, epsilon=1e-6): """The log likelihood of a sample on the this Tanh Distribution. Args: value (torch.Tensor): The sample whose loglikelihood is being computed. pre_tanh_value (torch.Tensor): The value prior to having t...
The log likelihood of a sample on the this Tanh Distribution. Args: value (torch.Tensor): The sample whose loglikelihood is being computed. pre_tanh_value (torch.Tensor): The value prior to having the tanh function applied to it but after it has been samp...
log_prob
python
rlworkgroup/garage
src/garage/torch/distributions/tanh_normal.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/distributions/tanh_normal.py
MIT
def rsample_with_pre_tanh_value(self, sample_shape=torch.Size()): """Return a sample, sampled from this TanhNormal distribution. Returns the sampled value before the tanh transform is applied and the sampled value with the tanh transform applied to it. Args: sample_shape (l...
Return a sample, sampled from this TanhNormal distribution. Returns the sampled value before the tanh transform is applied and the sampled value with the tanh transform applied to it. Args: sample_shape (list): shape of the return. Note: Gradients pass through ...
rsample_with_pre_tanh_value
python
rlworkgroup/garage
src/garage/torch/distributions/tanh_normal.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/distributions/tanh_normal.py
MIT
def _from_distribution(cls, new_normal): """Construct a new TanhNormal distribution from a normal distribution. Args: new_normal (Independent(Normal)): underlying normal dist for the new TanhNormal distribution. Returns: TanhNormal: A new distribution wh...
Construct a new TanhNormal distribution from a normal distribution. Args: new_normal (Independent(Normal)): underlying normal dist for the new TanhNormal distribution. Returns: TanhNormal: A new distribution whose underlying normal dist is new_no...
_from_distribution
python
rlworkgroup/garage
src/garage/torch/distributions/tanh_normal.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/distributions/tanh_normal.py
MIT
def expand(self, batch_shape, _instance=None): """Returns a new TanhNormal distribution. (or populates an existing instance provided by a derived class) with batch dimensions expanded to `batch_shape`. This method calls :class:`~torch.Tensor.expand` on the distribution's parameters. As ...
Returns a new TanhNormal distribution. (or populates an existing instance provided by a derived class) with batch dimensions expanded to `batch_shape`. This method calls :class:`~torch.Tensor.expand` on the distribution's parameters. As such, this does not allocate new memory for the ex...
expand
python
rlworkgroup/garage
src/garage/torch/distributions/tanh_normal.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/distributions/tanh_normal.py
MIT
def _clip_but_pass_gradient(x, lower=0., upper=1.): """Clipping function that allows for gradients to flow through. Args: x (torch.Tensor): value to be clipped lower (float): lower bound of clipping upper (float): upper bound of clipping Returns: ...
Clipping function that allows for gradients to flow through. Args: x (torch.Tensor): value to be clipped lower (float): lower bound of clipping upper (float): upper bound of clipping Returns: torch.Tensor: x clipped between lower and upper.
_clip_but_pass_gradient
python
rlworkgroup/garage
src/garage/torch/distributions/tanh_normal.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/distributions/tanh_normal.py
MIT
def spec(self): """garage.InOutSpec: Input and output space.""" input_space = akro.Box(-np.inf, np.inf, self._input_dim) output_space = akro.Box(-np.inf, np.inf, self._output_dim) return InOutSpec(input_space, output_space)
garage.InOutSpec: Input and output space.
spec
python
rlworkgroup/garage
src/garage/torch/embeddings/mlp_encoder.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/embeddings/mlp_encoder.py
MIT
def reset(self, do_resets=None): """Reset the encoder. This is effective only to recurrent encoder. do_resets is effective only to vectoried encoder. For a vectorized encoder, do_resets is an array of boolean indicating which internal states to be reset. The length of do_resets...
Reset the encoder. This is effective only to recurrent encoder. do_resets is effective only to vectoried encoder. For a vectorized encoder, do_resets is an array of boolean indicating which internal states to be reset. The length of do_resets should be equal to the length of in...
reset
python
rlworkgroup/garage
src/garage/torch/embeddings/mlp_encoder.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/embeddings/mlp_encoder.py
MIT
def forward(self, x): """Forward method. Args: x (torch.Tensor): Input values. Should match image_format specified at construction (either NCHW or NCWH). Returns: List[torch.Tensor]: Output values """ # Transform single values into batch...
Forward method. Args: x (torch.Tensor): Input values. Should match image_format specified at construction (either NCHW or NCWH). Returns: List[torch.Tensor]: Output values
forward
python
rlworkgroup/garage
src/garage/torch/modules/cnn_module.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/modules/cnn_module.py
MIT
def _check_spec(spec, image_format): """Check that an InOutSpec is suitable for a CNNModule. Args: spec (garage.InOutSpec): Specification of inputs and outputs. The input should be in 'NCHW' format: [batch_size, channel, height, width]. Will print a warning if the channel size...
Check that an InOutSpec is suitable for a CNNModule. Args: spec (garage.InOutSpec): Specification of inputs and outputs. The input should be in 'NCHW' format: [batch_size, channel, height, width]. Will print a warning if the channel size is not 1 or 3. If output_space ...
_check_spec
python
rlworkgroup/garage
src/garage/torch/modules/cnn_module.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/modules/cnn_module.py
MIT
def to(self, *args, **kwargs): """Move the module to the specified device. Args: *args: args to pytorch to function. **kwargs: keyword args to pytorch to function. """ super().to(*args, **kwargs) buffers = dict(self.named_buffers()) if not isinst...
Move the module to the specified device. Args: *args: args to pytorch to function. **kwargs: keyword args to pytorch to function.
to
python
rlworkgroup/garage
src/garage/torch/modules/gaussian_mlp_module.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/modules/gaussian_mlp_module.py
MIT
def forward(self, *inputs): """Forward method. Args: *inputs: Input to the module. Returns: torch.distributions.independent.Independent: Independent distribution. """ mean, log_std_uncentered = self._get_mean_and_log_std(*inputs) ...
Forward method. Args: *inputs: Input to the module. Returns: torch.distributions.independent.Independent: Independent distribution.
forward
python
rlworkgroup/garage
src/garage/torch/modules/gaussian_mlp_module.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/modules/gaussian_mlp_module.py
MIT
def _get_mean_and_log_std(self, x): """Get mean and std of Gaussian distribution given inputs. Args: x: Input to the module. Returns: torch.Tensor: The mean of Gaussian distribution. torch.Tensor: The variance of Gaussian distribution. """ m...
Get mean and std of Gaussian distribution given inputs. Args: x: Input to the module. Returns: torch.Tensor: The mean of Gaussian distribution. torch.Tensor: The variance of Gaussian distribution.
_get_mean_and_log_std
python
rlworkgroup/garage
src/garage/torch/modules/gaussian_mlp_module.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/modules/gaussian_mlp_module.py
MIT
def _check_parameter_for_output_layer(cls, var_name, var, n_heads): """Check input parameters for output layer are valid. Args: var_name (str): variable name var (any): variable to be checked n_heads (int): number of head Returns: list: list of v...
Check input parameters for output layer are valid. Args: var_name (str): variable name var (any): variable to be checked n_heads (int): number of head Returns: list: list of variables (length of n_heads) Raises: ValueError: if the va...
_check_parameter_for_output_layer
python
rlworkgroup/garage
src/garage/torch/modules/multi_headed_mlp_module.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/modules/multi_headed_mlp_module.py
MIT
def forward(self, input_val): """Forward method. Args: input_val (torch.Tensor): Input values with (N, *, input_dim) shape. Returns: List[torch.Tensor]: Output values """ x = input_val for layer in self._layers: x = l...
Forward method. Args: input_val (torch.Tensor): Input values with (N, *, input_dim) shape. Returns: List[torch.Tensor]: Output values
forward
python
rlworkgroup/garage
src/garage/torch/modules/multi_headed_mlp_module.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/modules/multi_headed_mlp_module.py
MIT
def _build_hessian_vector_product(func, params, reg_coeff=1e-5): """Computes Hessian-vector product using Pearlmutter's algorithm. `Pearlmutter, Barak A. "Fast exact multiplication by the Hessian." Neural computation 6.1 (1994): 147-160.` Args: func (callable): A function that returns a torch....
Computes Hessian-vector product using Pearlmutter's algorithm. `Pearlmutter, Barak A. "Fast exact multiplication by the Hessian." Neural computation 6.1 (1994): 147-160.` Args: func (callable): A function that returns a torch.Tensor. Hessian of the return value will be computed. ...
_build_hessian_vector_product
python
rlworkgroup/garage
src/garage/torch/optimizers/conjugate_gradient_optimizer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/optimizers/conjugate_gradient_optimizer.py
MIT
def _eval(vector): """The evaluation function. Args: vector (torch.Tensor): The vector to be multiplied with Hessian. Returns: torch.Tensor: The product of Hessian of function f and v. """ unflatten_vector = unflatten_tensors(vector, par...
The evaluation function. Args: vector (torch.Tensor): The vector to be multiplied with Hessian. Returns: torch.Tensor: The product of Hessian of function f and v.
_eval
python
rlworkgroup/garage
src/garage/torch/optimizers/conjugate_gradient_optimizer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/optimizers/conjugate_gradient_optimizer.py
MIT
def _conjugate_gradient(f_Ax, b, cg_iters, residual_tol=1e-10): """Use Conjugate Gradient iteration to solve Ax = b. Demmel p 312. Args: f_Ax (callable): A function to compute Hessian vector product. b (torch.Tensor): Right hand side of the equation to solve. cg_iters (int): Number of i...
Use Conjugate Gradient iteration to solve Ax = b. Demmel p 312. Args: f_Ax (callable): A function to compute Hessian vector product. b (torch.Tensor): Right hand side of the equation to solve. cg_iters (int): Number of iterations to run conjugate gradient algorithm. resi...
_conjugate_gradient
python
rlworkgroup/garage
src/garage/torch/optimizers/conjugate_gradient_optimizer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/optimizers/conjugate_gradient_optimizer.py
MIT
def step(self, f_loss, f_constraint): # pylint: disable=arguments-differ """Take an optimization step. Args: f_loss (callable): Function to compute the loss. f_constraint (callable): Function to compute the constraint value. """ # Collect trainable parameters a...
Take an optimization step. Args: f_loss (callable): Function to compute the loss. f_constraint (callable): Function to compute the constraint value.
step
python
rlworkgroup/garage
src/garage/torch/optimizers/conjugate_gradient_optimizer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/optimizers/conjugate_gradient_optimizer.py
MIT
def state(self): """dict: The hyper-parameters of the optimizer.""" return { 'max_constraint_value': self._max_constraint_value, 'cg_iters': self._cg_iters, 'max_backtracks': self._max_backtracks, 'backtrack_ratio': self._backtrack_ratio, 'hvp_...
dict: The hyper-parameters of the optimizer.
state
python
rlworkgroup/garage
src/garage/torch/optimizers/conjugate_gradient_optimizer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/optimizers/conjugate_gradient_optimizer.py
MIT
def __setstate__(self, state): """Restore the optimizer state. Args: state (dict): State dictionary. """ if 'hvp_reg_coeff' not in state['state']: warnings.warn( 'Resuming ConjugateGradientOptimizer with lost state. ' 'This behavi...
Restore the optimizer state. Args: state (dict): State dictionary.
__setstate__
python
rlworkgroup/garage
src/garage/torch/optimizers/conjugate_gradient_optimizer.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/optimizers/conjugate_gradient_optimizer.py
MIT
def zero_grad(self): """Sets gradients of all model parameters to zero.""" for param in self.module.parameters(): if param.grad is not None: param.grad.detach_() param.grad.zero_()
Sets gradients of all model parameters to zero.
zero_grad
python
rlworkgroup/garage
src/garage/torch/optimizers/differentiable_sgd.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/optimizers/differentiable_sgd.py
MIT
def set_grads_none(self): """Sets gradients for all model parameters to None. This is an alternative to `zero_grad` which sets gradients to zero. """ for param in self.module.parameters(): if param.grad is not None: param.grad = None
Sets gradients for all model parameters to None. This is an alternative to `zero_grad` which sets gradients to zero.
set_grads_none
python
rlworkgroup/garage
src/garage/torch/optimizers/differentiable_sgd.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/optimizers/differentiable_sgd.py
MIT
def get_minibatch(self, *inputs): r"""Yields a batch of inputs. Notes: P is the size of minibatch (self._minibatch_size) Args: *inputs (list[torch.Tensor]): A list of inputs. Each input has shape :math:`(N \dot [T], *)`. Yields: list[torch.Tenso...
Yields a batch of inputs. Notes: P is the size of minibatch (self._minibatch_size) Args: *inputs (list[torch.Tensor]): A list of inputs. Each input has shape :math:`(N \dot [T], *)`. Yields: list[torch.Tensor]: A list batch of inputs. Each batch has sha...
get_minibatch
python
rlworkgroup/garage
src/garage/torch/optimizers/optimizer_wrapper.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/optimizers/optimizer_wrapper.py
MIT
def forward(self, observations): """Compute the action distributions from the observations. Args: observations (torch.Tensor): Observations to act on. Returns: torch.distributions.Distribution: Batch distribution of actions. dict[str, torch.Tensor]: Addition...
Compute the action distributions from the observations. Args: observations (torch.Tensor): Observations to act on. Returns: torch.distributions.Distribution: Batch distribution of actions. dict[str, torch.Tensor]: Additional agent_info, as torch Tensors. ...
forward
python
rlworkgroup/garage
src/garage/torch/policies/categorical_cnn_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/categorical_cnn_policy.py
MIT
def reset_belief(self, num_tasks=1): r"""Reset :math:`q(z \| c)` to the prior and sample a new z from the prior. Args: num_tasks (int): Number of tasks. """ # reset distribution over z to the prior mu = torch.zeros(num_tasks, self._latent_dim).to(global_device()) ...
Reset :math:`q(z \| c)` to the prior and sample a new z from the prior. Args: num_tasks (int): Number of tasks.
reset_belief
python
rlworkgroup/garage
src/garage/torch/policies/context_conditioned_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/context_conditioned_policy.py
MIT
def sample_from_belief(self): """Sample z using distributions from current means and variances.""" if self._use_information_bottleneck: posteriors = [ torch.distributions.Normal(m, torch.sqrt(s)) for m, s in zip( torch.unbind(self.z_means), torch.unbind(se...
Sample z using distributions from current means and variances.
sample_from_belief
python
rlworkgroup/garage
src/garage/torch/policies/context_conditioned_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/context_conditioned_policy.py
MIT
def update_context(self, timestep): """Append single transition to the current context. Args: timestep (garage._dtypes.TimeStep): Timestep containing transition information to be added to context. """ o = torch.as_tensor(timestep.observation[None, None, ...]...
Append single transition to the current context. Args: timestep (garage._dtypes.TimeStep): Timestep containing transition information to be added to context.
update_context
python
rlworkgroup/garage
src/garage/torch/policies/context_conditioned_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/context_conditioned_policy.py
MIT
def infer_posterior(self, context): r"""Compute :math:`q(z \| c)` as a function of input context and sample new z. Args: context (torch.Tensor): Context values, with shape :math:`(X, N, C)`. X is the number of tasks. N is batch size. C is the combined size of...
Compute :math:`q(z \| c)` as a function of input context and sample new z. Args: context (torch.Tensor): Context values, with shape :math:`(X, N, C)`. X is the number of tasks. N is batch size. C is the combined size of observation, action, reward, and next ...
infer_posterior
python
rlworkgroup/garage
src/garage/torch/policies/context_conditioned_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/context_conditioned_policy.py
MIT
def forward(self, obs, context): """Given observations and context, get actions and probs from policy. Args: obs (torch.Tensor): Observation values, with shape :math:`(X, N, O)`. X is the number of tasks. N is batch size. O is the size of the flattened obser...
Given observations and context, get actions and probs from policy. Args: obs (torch.Tensor): Observation values, with shape :math:`(X, N, O)`. X is the number of tasks. N is batch size. O is the size of the flattened observation space. context (torch.Ten...
forward
python
rlworkgroup/garage
src/garage/torch/policies/context_conditioned_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/context_conditioned_policy.py
MIT
def get_action(self, obs): """Sample action from the policy, conditioned on the task embedding. Args: obs (torch.Tensor): Observation values, with shape :math:`(1, O)`. O is the size of the flattened observation space. Returns: torch.Tensor: Output actio...
Sample action from the policy, conditioned on the task embedding. Args: obs (torch.Tensor): Observation values, with shape :math:`(1, O)`. O is the size of the flattened observation space. Returns: torch.Tensor: Output action value, with shape :math:`(1, A)`. ...
get_action
python
rlworkgroup/garage
src/garage/torch/policies/context_conditioned_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/context_conditioned_policy.py
MIT
def compute_kl_div(self): r"""Compute :math:`KL(q(z|c) \| p(z))`. Returns: float: :math:`KL(q(z|c) \| p(z))`. """ prior = torch.distributions.Normal( torch.zeros(self._latent_dim).to(global_device()), torch.ones(self._latent_dim).to(global_device()))...
Compute :math:`KL(q(z|c) \| p(z))`. Returns: float: :math:`KL(q(z|c) \| p(z))`.
compute_kl_div
python
rlworkgroup/garage
src/garage/torch/policies/context_conditioned_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/context_conditioned_policy.py
MIT
def __init__(self, env_spec, name='DeterministicMLPPolicy', **kwargs): """Initialize class with multiple attributes. Args: env_spec (EnvSpec): Environment specification. name (str): Policy name. **kwargs: Additional keyword arguments passed to the MLPModule. ...
Initialize class with multiple attributes. Args: env_spec (EnvSpec): Environment specification. name (str): Policy name. **kwargs: Additional keyword arguments passed to the MLPModule.
__init__
python
rlworkgroup/garage
src/garage/torch/policies/deterministic_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/deterministic_mlp_policy.py
MIT
def get_action(self, observation): """Get a single action given an observation. Args: observation (np.ndarray): Observation from the environment. Returns: tuple: * np.ndarray: Predicted action. * dict: * np.ndarray[flo...
Get a single action given an observation. Args: observation (np.ndarray): Observation from the environment. Returns: tuple: * np.ndarray: Predicted action. * dict: * np.ndarray[float]: Mean of the distribution ...
get_action
python
rlworkgroup/garage
src/garage/torch/policies/deterministic_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/deterministic_mlp_policy.py
MIT
def get_actions(self, observations): """Get actions given observations. Args: observations (np.ndarray): Observations from the environment. Returns: tuple: * np.ndarray: Predicted actions. * dict: * np.ndarray[float]: ...
Get actions given observations. Args: observations (np.ndarray): Observations from the environment. Returns: tuple: * np.ndarray: Predicted actions. * dict: * np.ndarray[float]: Mean of the distribution * n...
get_actions
python
rlworkgroup/garage
src/garage/torch/policies/deterministic_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/deterministic_mlp_policy.py
MIT
def forward(self, observations): """Compute the action distributions from the observations. Args: observations(torch.Tensor): Batch of observations of shape :math:`(N, O)`. Observations should be flattened even if they are images as the underlying Q network h...
Compute the action distributions from the observations. Args: observations(torch.Tensor): Batch of observations of shape :math:`(N, O)`. Observations should be flattened even if they are images as the underlying Q network handles unflattening. ...
forward
python
rlworkgroup/garage
src/garage/torch/policies/discrete_cnn_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/discrete_cnn_policy.py
MIT
def forward(self, observations): """Get actions corresponding to a batch of observations. Args: observations(torch.Tensor): Batch of observations of shape :math:`(N, O)`. Observations should be flattened even if they are images as the underlying Q network han...
Get actions corresponding to a batch of observations. Args: observations(torch.Tensor): Batch of observations of shape :math:`(N, O)`. Observations should be flattened even if they are images as the underlying Q network handles unflattening. ...
forward
python
rlworkgroup/garage
src/garage/torch/policies/discrete_qf_argmax_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/discrete_qf_argmax_policy.py
MIT
def get_action(self, observation): """Get a single action given an observation. Args: observation (np.ndarray): Observation with shape :math:`(O, )`. Returns: torch.Tensor: Predicted action with shape :math:`(A, )`. dict: Empty since this policy does not pro...
Get a single action given an observation. Args: observation (np.ndarray): Observation with shape :math:`(O, )`. Returns: torch.Tensor: Predicted action with shape :math:`(A, )`. dict: Empty since this policy does not produce a distribution.
get_action
python
rlworkgroup/garage
src/garage/torch/policies/discrete_qf_argmax_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/discrete_qf_argmax_policy.py
MIT
def get_actions(self, observations): """Get actions given observations. Args: observations (np.ndarray): Batch of observations, should have shape :math:`(N, O)`. Returns: torch.Tensor: Predicted actions. Tensor has shape :math:`(N, A)`. dict:...
Get actions given observations. Args: observations (np.ndarray): Batch of observations, should have shape :math:`(N, O)`. Returns: torch.Tensor: Predicted actions. Tensor has shape :math:`(N, A)`. dict: Empty since this policy does not produce a dist...
get_actions
python
rlworkgroup/garage
src/garage/torch/policies/discrete_qf_argmax_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/discrete_qf_argmax_policy.py
MIT
def forward(self, observations): """Compute the action distributions from the observations. Args: observations (torch.Tensor): Batch of observations on default torch device. Returns: torch.distributions.Distribution: Batch distribution of actions. ...
Compute the action distributions from the observations. Args: observations (torch.Tensor): Batch of observations on default torch device. Returns: torch.distributions.Distribution: Batch distribution of actions. dict[str, torch.Tensor]: Additional ag...
forward
python
rlworkgroup/garage
src/garage/torch/policies/gaussian_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/gaussian_mlp_policy.py
MIT
def get_action(self, observation): """Get action sampled from the policy. Args: observation (np.ndarray): Observation from the environment. Returns: Tuple[np.ndarray, dict[str,np.ndarray]]: Action and extra agent info. """
Get action sampled from the policy. Args: observation (np.ndarray): Observation from the environment. Returns: Tuple[np.ndarray, dict[str,np.ndarray]]: Action and extra agent info.
get_action
python
rlworkgroup/garage
src/garage/torch/policies/policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/policy.py
MIT
def get_actions(self, observations): """Get actions given observations. Args: observations (np.ndarray): Observations from the environment. Returns: Tuple[np.ndarray, dict[str,np.ndarray]]: Actions and extra agent infos. """
Get actions given observations. Args: observations (np.ndarray): Observations from the environment. Returns: Tuple[np.ndarray, dict[str,np.ndarray]]: Actions and extra agent infos.
get_actions
python
rlworkgroup/garage
src/garage/torch/policies/policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/policies/policy.py
MIT