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 get_action(self, observation): """Get single action from this policy for the input observation. Args: observation (numpy.ndarray): Observation from environment. Returns: numpy.ndarray: Predicted action. dict: Empty dict since this policy does not model a...
Get single action from this policy for the input observation. Args: observation (numpy.ndarray): Observation from environment. Returns: numpy.ndarray: Predicted action. dict: Empty dict since this policy does not model a distribution.
get_action
python
rlworkgroup/garage
src/garage/tf/policies/continuous_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/continuous_mlp_policy.py
MIT
def get_actions(self, observations): """Get multiple actions from this policy for the input observations. Args: observations (numpy.ndarray): Observations from environment. Returns: numpy.ndarray: Predicted actions. dict: Empty dict since this policy does no...
Get multiple actions from this policy for the input observations. Args: observations (numpy.ndarray): Observations from environment. Returns: numpy.ndarray: Predicted actions. dict: Empty dict since this policy does not model a distribution.
get_actions
python
rlworkgroup/garage
src/garage/tf/policies/continuous_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/continuous_mlp_policy.py
MIT
def get_regularizable_vars(self): """Get regularizable weight variables under the Policy scope. Returns: list(tf.Variable): List of regularizable variables. """ trainable = self.get_trainable_vars() return [ var for var in trainable if 'hidde...
Get regularizable weight variables under the Policy scope. Returns: list(tf.Variable): List of regularizable variables.
get_regularizable_vars
python
rlworkgroup/garage
src/garage/tf/policies/continuous_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/continuous_mlp_policy.py
MIT
def __getstate__(self): """Object.__getstate__. Returns: dict: the state to be pickled as the contents for the instance. """ new_dict = super().__getstate__() del new_dict['_f_prob'] return new_dict
Object.__getstate__. Returns: dict: the state to be pickled as the contents for the instance.
__getstate__
python
rlworkgroup/garage
src/garage/tf/policies/continuous_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/continuous_mlp_policy.py
MIT
def get_action(self, observation): """Get action from this policy for the input observation. Args: observation (numpy.ndarray): Observation from environment. Returns: numpy.ndarray: Single optimal action from this policy. dict: Predicted action and agent inf...
Get action from this policy for the input observation. Args: observation (numpy.ndarray): Observation from environment. Returns: numpy.ndarray: Single optimal action from this policy. dict: Predicted action and agent information. It returns an empty ...
get_action
python
rlworkgroup/garage
src/garage/tf/policies/discrete_qf_argmax_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/discrete_qf_argmax_policy.py
MIT
def get_actions(self, observations): """Get actions from this policy for the input observations. Args: observations (numpy.ndarray): Observations from environment. Returns: numpy.ndarray: Optimal actions from this policy. dict: Predicted action and agent inf...
Get actions from this policy for the input observations. Args: observations (numpy.ndarray): Observations from environment. Returns: numpy.ndarray: Optimal actions from this policy. dict: Predicted action and agent information. It returns an empty di...
get_actions
python
rlworkgroup/garage
src/garage/tf/policies/discrete_qf_argmax_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/discrete_qf_argmax_policy.py
MIT
def build(self, state_input, name=None): """Build policy. Args: state_input (tf.Tensor) : State input. name (str): Name of the policy, which is also the name scope. Returns: tfp.distributions.MultivariateNormalDiag: Policy distribution. tf.Tensor...
Build policy. Args: state_input (tf.Tensor) : State input. name (str): Name of the policy, which is also the name scope. Returns: tfp.distributions.MultivariateNormalDiag: Policy distribution. tf.Tensor: Step means, with shape :math:`(N, S^*)`. ...
build
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_gru_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_gru_policy.py
MIT
def reset(self, do_resets=None): """Reset the policy. Note: If `do_resets` is None, it will be by default `np.array([True])` which implies the policy will not be "vectorized", i.e. number of parallel environments for training data sampling = 1. Args: ...
Reset the policy. Note: If `do_resets` is None, it will be by default `np.array([True])` which implies the policy will not be "vectorized", i.e. number of parallel environments for training data sampling = 1. Args: do_resets (numpy.ndarray): Bool that in...
reset
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_gru_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_gru_policy.py
MIT
def get_action(self, observation): """Get single action from this policy for the input observation. Args: observation (numpy.ndarray): Observation from environment. Returns: numpy.ndarray: Actions dict: Predicted action and agent information. Note: ...
Get single action from this policy for the input observation. Args: observation (numpy.ndarray): Observation from environment. Returns: numpy.ndarray: Actions dict: Predicted action and agent information. Note: It returns an action and a dict, w...
get_action
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_gru_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_gru_policy.py
MIT
def get_actions(self, observations): """Get multiple actions from this policy for the input observations. Args: observations (numpy.ndarray): Observations from environment. Returns: numpy.ndarray: Actions dict: Predicted action and agent information. ...
Get multiple actions from this policy for the input observations. Args: observations (numpy.ndarray): Observations from environment. Returns: numpy.ndarray: Actions dict: Predicted action and agent information. Note: It returns an action and a d...
get_actions
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_gru_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_gru_policy.py
MIT
def build(self, state_input, name=None): """Build policy. Args: state_input (tf.Tensor) : State input. name (str): Name of the policy, which is also the name scope. Returns: tfp.distributions.MultivariateNormalDiag: Policy distribution. tf.Tensor...
Build policy. Args: state_input (tf.Tensor) : State input. name (str): Name of the policy, which is also the name scope. Returns: tfp.distributions.MultivariateNormalDiag: Policy distribution. tf.Tensor: Step means, with shape :math:`(N, S^*)`. ...
build
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_lstm_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_lstm_policy.py
MIT
def get_action(self, observation): """Get single action from this policy for the input observation. Args: observation (numpy.ndarray): Observation from environment. Returns: numpy.ndarray: Actions dict: Predicted action and agent information. Note: ...
Get single action from this policy for the input observation. Args: observation (numpy.ndarray): Observation from environment. Returns: numpy.ndarray: Actions dict: Predicted action and agent information. Note: It returns an action and a dict, w...
get_action
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_policy.py
MIT
def get_actions(self, observations): """Get multiple actions from this policy for the input observations. Args: observations (numpy.ndarray): Observations from environment. Returns: numpy.ndarray: Actions dict: Predicted action and agent information. ...
Get multiple actions from this policy for the input observations. Args: observations (numpy.ndarray): Observations from environment. Returns: numpy.ndarray: Actions dict: Predicted action and agent information. Note: It returns actions and a dic...
get_actions
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_policy.py
MIT
def _initialize(self): """Build policy to support sampling. After build, get_action_*() methods will be available. """ obs_input = tf.compat.v1.placeholder(tf.float32, shape=(None, None, self.obs_dim)) encoder_input = tf.compat.v1.pl...
Build policy to support sampling. After build, get_action_*() methods will be available.
_initialize
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
MIT
def build(self, obs_input, task_input, name=None): """Build policy. Args: obs_input (tf.Tensor): Observation input. task_input (tf.Tensor): One-hot task id input. name (str): Name of the model, which is also the name scope. Returns: namedtuple: P...
Build policy. Args: obs_input (tf.Tensor): Observation input. task_input (tf.Tensor): One-hot task id input. name (str): Name of the model, which is also the name scope. Returns: namedtuple: Policy network. namedtuple: Encoder network. ...
build
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
MIT
def get_action(self, observation): """Get action sampled from the policy. Args: observation (np.ndarray): Augmented observation from the environment, with shape :math:`(O+N, )`. O is the dimension of observation, N is the number of tasks. Returns: ...
Get action sampled from the policy. Args: observation (np.ndarray): Augmented observation from the environment, with shape :math:`(O+N, )`. O is the dimension of observation, N is the number of tasks. Returns: np.ndarray: Action sampled from the ...
get_action
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
MIT
def get_actions(self, observations): """Get actions sampled from the policy. Args: observations (np.ndarray): Augmented observation from the environment, with shape :math:`(T, O+N)`. T is the number of environment steps, O is the dimension of observation, N i...
Get actions sampled from the policy. Args: observations (np.ndarray): Augmented observation from the environment, with shape :math:`(T, O+N)`. T is the number of environment steps, O is the dimension of observation, N is the number of tasks. ...
get_actions
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
MIT
def get_action_given_latent(self, observation, latent): """Sample an action given observation and latent. Args: observation (np.ndarray): Observation from the environment, with shape :math:`(O, )`. O is the dimension of observation. latent (np.ndarray): Latent, w...
Sample an action given observation and latent. Args: observation (np.ndarray): Observation from the environment, with shape :math:`(O, )`. O is the dimension of observation. latent (np.ndarray): Latent, with shape :math:`(Z, )`. Z is the dimension of the ...
get_action_given_latent
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
MIT
def get_actions_given_latents(self, observations, latents): """Sample a batch of actions given observations and latents. Args: observations (np.ndarray): Observations from the environment, with shape :math:`(T, O)`. T is the number of environment steps, O is ...
Sample a batch of actions given observations and latents. Args: observations (np.ndarray): Observations from the environment, with shape :math:`(T, O)`. T is the number of environment steps, O is the dimension of observation. latents (np.ndarray): Latents...
get_actions_given_latents
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
MIT
def get_action_given_task(self, observation, task_id): """Sample an action given observation and task id. Args: observation (np.ndarray): Observation from the environment, with shape :math:`(O, )`. O is the dimension of the observation. task_id (np.ndarray): One-...
Sample an action given observation and task id. Args: observation (np.ndarray): Observation from the environment, with shape :math:`(O, )`. O is the dimension of the observation. task_id (np.ndarray): One-hot task id, with shape :math:`(N, ). N is the num...
get_action_given_task
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
MIT
def get_actions_given_tasks(self, observations, task_ids): """Sample a batch of actions given observations and task ids. Args: observations (np.ndarray): Observations from the environment, with shape :math:`(T, O)`. T is the number of environment steps, O is ...
Sample a batch of actions given observations and task ids. Args: observations (np.ndarray): Observations from the environment, with shape :math:`(T, O)`. T is the number of environment steps, O is the dimension of observation. task_ids (np.ndarry): One-ho...
get_actions_given_tasks
python
rlworkgroup/garage
src/garage/tf/policies/gaussian_mlp_task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/gaussian_mlp_task_embedding_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/tf/policies/policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/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/tf/policies/policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/policy.py
MIT
def get_action(self, observation): """Get action sampled from the policy. Args: observation (np.ndarray): Augmented observation from the environment, with shape :math:`(O+N, )`. O is the dimension of observation, N is the number of tasks. Returns: ...
Get action sampled from the policy. Args: observation (np.ndarray): Augmented observation from the environment, with shape :math:`(O+N, )`. O is the dimension of observation, N is the number of tasks. Returns: np.ndarray: Action sampled from the ...
get_action
python
rlworkgroup/garage
src/garage/tf/policies/task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/task_embedding_policy.py
MIT
def get_actions(self, observations): """Get actions sampled from the policy. Args: observations (np.ndarray): Augmented observation from the environment, with shape :math:`(T, O+N)`. T is the number of environment steps, O is the dimension of observation, N i...
Get actions sampled from the policy. Args: observations (np.ndarray): Augmented observation from the environment, with shape :math:`(T, O+N)`. T is the number of environment steps, O is the dimension of observation, N is the number of tasks. ...
get_actions
python
rlworkgroup/garage
src/garage/tf/policies/task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/task_embedding_policy.py
MIT
def get_action_given_task(self, observation, task_id): """Sample an action given observation and task id. Args: observation (np.ndarray): Observation from the environment, with shape :math:`(O, )`. O is the dimension of the observation. task_id (np.ndarray): One-...
Sample an action given observation and task id. Args: observation (np.ndarray): Observation from the environment, with shape :math:`(O, )`. O is the dimension of the observation. task_id (np.ndarray): One-hot task id, with shape :math:`(N, ). N is the num...
get_action_given_task
python
rlworkgroup/garage
src/garage/tf/policies/task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/task_embedding_policy.py
MIT
def get_actions_given_tasks(self, observations, task_ids): """Sample a batch of actions given observations and task ids. Args: observations (np.ndarray): Observations from the environment, with shape :math:`(T, O)`. T is the number of environment steps, O is ...
Sample a batch of actions given observations and task ids. Args: observations (np.ndarray): Observations from the environment, with shape :math:`(T, O)`. T is the number of environment steps, O is the dimension of observation. task_ids (np.ndarry): One-ho...
get_actions_given_tasks
python
rlworkgroup/garage
src/garage/tf/policies/task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/task_embedding_policy.py
MIT
def get_action_given_latent(self, observation, latent): """Sample an action given observation and latent. Args: observation (np.ndarray): Observation from the environment, with shape :math:`(O, )`. O is the dimension of observation. latent (np.ndarray): Latent, w...
Sample an action given observation and latent. Args: observation (np.ndarray): Observation from the environment, with shape :math:`(O, )`. O is the dimension of observation. latent (np.ndarray): Latent, with shape :math:`(Z, )`. Z is the dimension of late...
get_action_given_latent
python
rlworkgroup/garage
src/garage/tf/policies/task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/task_embedding_policy.py
MIT
def get_actions_given_latents(self, observations, latents): """Sample a batch of actions given observations and latents. Args: observations (np.ndarray): Observations from the environment, with shape :math:`(T, O)`. T is the number of environment steps, O is ...
Sample a batch of actions given observations and latents. Args: observations (np.ndarray): Observations from the environment, with shape :math:`(T, O)`. T is the number of environment steps, O is the dimension of observation. latents (np.ndarray): Latents...
get_actions_given_latents
python
rlworkgroup/garage
src/garage/tf/policies/task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/task_embedding_policy.py
MIT
def split_augmented_observation(self, collated): """Splits up observation into one-hot task and environment observation. Args: collated (np.ndarray): Environment observation concatenated with task one-hot, with shape :math:`(O+N, )`. O is the dimension of obs...
Splits up observation into one-hot task and environment observation. Args: collated (np.ndarray): Environment observation concatenated with task one-hot, with shape :math:`(O+N, )`. O is the dimension of observation, N is the number of tasks. Returns: ...
split_augmented_observation
python
rlworkgroup/garage
src/garage/tf/policies/task_embedding_policy.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/policies/task_embedding_policy.py
MIT
def get_qval(self, observation, action): """Q Value of the network. Args: observation (np.ndarray): Observation input of shape :math:`(N, O*)`. action (np.ndarray): Action input of shape :math:`(N, A*)`. Returns: np.ndarray: Array of shape :m...
Q Value of the network. Args: observation (np.ndarray): Observation input of shape :math:`(N, O*)`. action (np.ndarray): Action input of shape :math:`(N, A*)`. Returns: np.ndarray: Array of shape :math:`(N, )` containing Q values corr...
get_qval
python
rlworkgroup/garage
src/garage/tf/q_functions/continuous_cnn_q_function.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/q_functions/continuous_cnn_q_function.py
MIT
def build(self, state_input, action_input, name): """Build the symbolic graph for q-network. Args: state_input (tf.Tensor): The state input tf.Tensor of shape :math:`(N, O*)`. action_input (tf.Tensor): The action input tf.Tensor of shape :math:`(N...
Build the symbolic graph for q-network. Args: state_input (tf.Tensor): The state input tf.Tensor of shape :math:`(N, O*)`. action_input (tf.Tensor): The action input tf.Tensor of shape :math:`(N, A*)`. name (str): Network variable scope. ...
build
python
rlworkgroup/garage
src/garage/tf/q_functions/continuous_cnn_q_function.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/q_functions/continuous_cnn_q_function.py
MIT
def build(self, state_input, name): """Build the symbolic graph for q-network. Args: state_input (tf.Tensor): The state input tf.Tensor to the network. name (str): Network variable scope. Return: tf.Tensor: The tf.Tensor output of Discrete CNN QFunction. ...
Build the symbolic graph for q-network. Args: state_input (tf.Tensor): The state input tf.Tensor to the network. name (str): Network variable scope. Return: tf.Tensor: The tf.Tensor output of Discrete CNN QFunction.
build
python
rlworkgroup/garage
src/garage/tf/q_functions/discrete_cnn_q_function.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/q_functions/discrete_cnn_q_function.py
MIT
def __call__(self, *args, **kwargs): """Construct the inner class and wrap it. Args: *args: Passed on to inner worker class. **kwargs: Passed on to inner worker class. Returns: TFWorkerWrapper: The wrapped worker. """ wrapper = TFWorkerWrapp...
Construct the inner class and wrap it. Args: *args: Passed on to inner worker class. **kwargs: Passed on to inner worker class. Returns: TFWorkerWrapper: The wrapped worker.
__call__
python
rlworkgroup/garage
src/garage/tf/samplers/worker.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/tf/samplers/worker.py
MIT
def zero_optim_grads(optim, set_to_none=True): """Sets the gradient of all optimized tensors to None. This is an optimization alternative to calling `optimizer.zero_grad()` Args: optim (torch.nn.Optimizer): The optimizer instance to zero parameter gradients. set_to_none (bool):...
Sets the gradient of all optimized tensors to None. This is an optimization alternative to calling `optimizer.zero_grad()` Args: optim (torch.nn.Optimizer): The optimizer instance to zero parameter gradients. set_to_none (bool): Set gradients to None instead of calling ...
zero_optim_grads
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def compute_advantages(discount, gae_lambda, max_episode_length, baselines, rewards): """Calculate advantages. Advantages are a discounted cumulative sum. Calculate advantages using a baseline according to Generalized Advantage Estimation (GAE) The discounted cumulative sum...
Calculate advantages. Advantages are a discounted cumulative sum. Calculate advantages using a baseline according to Generalized Advantage Estimation (GAE) The discounted cumulative sum can be computed using conv2d with filter. filter: [1, (discount * gae_lambda), (discount * gae_lambda) ...
compute_advantages
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def pad_to_last(nums, total_length, axis=-1, val=0): """Pad val to last in nums in given axis. length of the result in given axis should be total_length. Raises: IndexError: If the input axis value is out of range of the nums array Args: nums (numpy.ndarray): The array to pad. t...
Pad val to last in nums in given axis. length of the result in given axis should be total_length. Raises: IndexError: If the input axis value is out of range of the nums array Args: nums (numpy.ndarray): The array to pad. total_length (int): The final width of the Array. axi...
pad_to_last
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def np_to_torch(array): """Numpy arrays to PyTorch tensors. Args: array (np.ndarray): Data in numpy array. Returns: torch.Tensor: float tensor on the global device. """ tensor = torch.from_numpy(array) if tensor.dtype != torch.float32: tensor = tensor.float() ret...
Numpy arrays to PyTorch tensors. Args: array (np.ndarray): Data in numpy array. Returns: torch.Tensor: float tensor on the global device.
np_to_torch
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def as_torch_dict(array_dict): """Convert a dict whose values are numpy arrays to PyTorch tensors. Modifies array_dict in place. Args: array_dict (dict): Dictionary of data in numpy arrays Returns: dict: Dictionary of data in PyTorch tensors """ for key, value in array_dict.i...
Convert a dict whose values are numpy arrays to PyTorch tensors. Modifies array_dict in place. Args: array_dict (dict): Dictionary of data in numpy arrays Returns: dict: Dictionary of data in PyTorch tensors
as_torch_dict
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def flatten_to_single_vector(tensor): """Collapse the C x H x W values per representation into a single long vector. Reshape a tensor of size (N, C, H, W) into (N, C * H * W). Args: tensor (torch.tensor): batch of data. Returns: torch.Tensor: Reshaped view of that data (analogous to n...
Collapse the C x H x W values per representation into a single long vector. Reshape a tensor of size (N, C, H, W) into (N, C * H * W). Args: tensor (torch.tensor): batch of data. Returns: torch.Tensor: Reshaped view of that data (analogous to numpy.reshape)
flatten_to_single_vector
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def update_module_params(module, new_params): # noqa: D202 """Load parameters to a module. This function acts like `torch.nn.Module._load_from_state_dict()`, but it replaces the tensors in module with those in new_params, while `_load_from_state_dict()` loads only the value. Use this function so t...
Load parameters to a module. This function acts like `torch.nn.Module._load_from_state_dict()`, but it replaces the tensors in module with those in new_params, while `_load_from_state_dict()` loads only the value. Use this function so that the `grad` and `grad_fn` of `new_params` can be restored A...
update_module_params
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def soft_update_model(target_model, source_model, tau): """Update model parameter of target and source model. # noqa: D417 Args: target_model (garage.torch.Policy/garage.torch.QFunction): Target model to update. source_model (garage.torch....
Update model parameter of target and source model. # noqa: D417 Args: target_model (garage.torch.Policy/garage.torch.QFunction): Target model to update. source_model (garage.torch.Policy/QFunction): Source network to update...
soft_update_model
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def set_gpu_mode(mode, gpu_id=0): """Set GPU mode and device ID. Args: mode (bool): Whether or not to use GPU gpu_id (int): GPU ID """ # pylint: disable=global-statement global _GPU_ID global _USE_GPU global _DEVICE _GPU_ID = gpu_id _USE_GPU = mode _DEVICE = tor...
Set GPU mode and device ID. Args: mode (bool): Whether or not to use GPU gpu_id (int): GPU ID
set_gpu_mode
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def prefer_gpu(): """Prefer to use GPU(s) if GPU(s) is detected.""" if torch.cuda.is_available(): set_gpu_mode(True) else: set_gpu_mode(False)
Prefer to use GPU(s) if GPU(s) is detected.
prefer_gpu
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def global_device(): """Returns the global device that torch.Tensors should be placed on. Note: The global device is set by using the function `garage.torch._functions.set_gpu_mode.` If this functions is never called `garage.torch._functions.device()` returns None. Returns: ...
Returns the global device that torch.Tensors should be placed on. Note: The global device is set by using the function `garage.torch._functions.set_gpu_mode.` If this functions is never called `garage.torch._functions.device()` returns None. Returns: `torch.Device`: The global ...
global_device
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def product_of_gaussians(mus, sigmas_squared): """Compute mu, sigma of product of gaussians. Args: mus (torch.Tensor): Means, with shape :math:`(N, M)`. M is the number of mean values. sigmas_squared (torch.Tensor): Variances, with shape :math:`(N, V)`. V is the number o...
Compute mu, sigma of product of gaussians. Args: mus (torch.Tensor): Means, with shape :math:`(N, M)`. M is the number of mean values. sigmas_squared (torch.Tensor): Variances, with shape :math:`(N, V)`. V is the number of variance values. Returns: torch.Tensor:...
product_of_gaussians
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def state_dict_to(state_dict, device): """Move optimizer to a specified device. Args: state_dict (dict): state dictionary to be moved device (str): ID of GPU or CPU. Returns: dict: state dictionary moved to device """ for param in state_dict.values(): if isinstance(...
Move optimizer to a specified device. Args: state_dict (dict): state dictionary to be moved device (str): ID of GPU or CPU. Returns: dict: state dictionary moved to device
state_dict_to
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def _value_at_axis(value, axis): """Get the value for a particular axis. Args: value (tuple or list or int): Possible tuple of per-axis values. axis (int): Axis to get value for. Returns: int: the value at the available axis. """ if not isinstance(value, (list, tuple)): ...
Get the value for a particular axis. Args: value (tuple or list or int): Possible tuple of per-axis values. axis (int): Axis to get value for. Returns: int: the value at the available axis.
_value_at_axis
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def output_height_2d(layer, height): """Compute the output height of a torch.nn.Conv2d, assuming NCHW format. This requires knowing the input height. Because NCHW format makes this very easy to mix up, this is a seperate function from conv2d_output_height. It also works on torch.nn.MaxPool2d. Thi...
Compute the output height of a torch.nn.Conv2d, assuming NCHW format. This requires knowing the input height. Because NCHW format makes this very easy to mix up, this is a seperate function from conv2d_output_height. It also works on torch.nn.MaxPool2d. This function implements the formula described ...
output_height_2d
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def output_width_2d(layer, width): """Compute the output width of a torch.nn.Conv2d, assuming NCHW format. This requires knowing the input width. Because NCHW format makes this very easy to mix up, this is a seperate function from conv2d_output_height. It also works on torch.nn.MaxPool2d. This fu...
Compute the output width of a torch.nn.Conv2d, assuming NCHW format. This requires knowing the input width. Because NCHW format makes this very easy to mix up, this is a seperate function from conv2d_output_height. It also works on torch.nn.MaxPool2d. This function implements the formula described in...
output_width_2d
python
rlworkgroup/garage
src/garage/torch/_functions.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/_functions.py
MIT
def train(self, trainer): """Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Experiment trainer, for services such as snapshotting and sampler control. """ if not self._eval_env: self._eval_env = trainer.get_env...
Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Experiment trainer, for services such as snapshotting and sampler control.
train
python
rlworkgroup/garage
src/garage/torch/algos/bc.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/bc.py
MIT
def _train_once(self, trainer, epoch): """Obtain samplers and train for one epoch. Args: trainer (Trainer): Experiment trainer, which may be used to obtain samples. epoch (int): The current epoch. Returns: List[float]: Losses. """ ...
Obtain samplers and train for one epoch. Args: trainer (Trainer): Experiment trainer, which may be used to obtain samples. epoch (int): The current epoch. Returns: List[float]: Losses.
_train_once
python
rlworkgroup/garage
src/garage/torch/algos/bc.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/bc.py
MIT
def _obtain_samples(self, trainer, epoch): """Obtain samples from self._source. Args: trainer (Trainer): Experiment trainer, which may be used to obtain samples. epoch (int): The current epoch. Returns: TimeStepBatch: Batch of samples. ...
Obtain samples from self._source. Args: trainer (Trainer): Experiment trainer, which may be used to obtain samples. epoch (int): The current epoch. Returns: TimeStepBatch: Batch of samples.
_obtain_samples
python
rlworkgroup/garage
src/garage/torch/algos/bc.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/bc.py
MIT
def _compute_loss(self, observations, expert_actions): """Compute loss of self._learner on the expert_actions. Args: observations (torch.Tensor): Observations used to select actions. Has shape :math:`(B, O^*)`, where :math:`B` is the batch dimension and :math...
Compute loss of self._learner on the expert_actions. Args: observations (torch.Tensor): Observations used to select actions. Has shape :math:`(B, O^*)`, where :math:`B` is the batch dimension and :math:`O^*` are the observation dimensions. expert_actions ...
_compute_loss
python
rlworkgroup/garage
src/garage/torch/algos/bc.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/bc.py
MIT
def train(self, trainer): """Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Experiment trainer. Returns: float: The average return in last epoch cycle. """ if not self._eval_env: self._eval_env = trainer.g...
Obtain samplers and start actual training for each epoch. Args: trainer (Trainer): Experiment trainer. Returns: float: The average return in last epoch cycle.
train
python
rlworkgroup/garage
src/garage/torch/algos/ddpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/ddpg.py
MIT
def train_once(self, itr, episodes): """Perform one iteration of training. Args: itr (int): Iteration number. episodes (EpisodeBatch): Batch of episodes. """ self.replay_buffer.add_episode_batch(episodes) epoch = itr / self._steps_per_epoch for...
Perform one iteration of training. Args: itr (int): Iteration number. episodes (EpisodeBatch): Batch of episodes.
train_once
python
rlworkgroup/garage
src/garage/torch/algos/ddpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/ddpg.py
MIT
def optimize_policy(self, samples_data): """Perform algorithm optimizing. Args: samples_data (dict): Processed batch data. Returns: action_loss: Loss of action predicted by the policy network. qval_loss: Loss of Q-value predicted by the Q-network. ...
Perform algorithm optimizing. Args: samples_data (dict): Processed batch data. Returns: action_loss: Loss of action predicted by the policy network. qval_loss: Loss of Q-value predicted by the Q-network. ys: y_s. qval: Q-value predicted by th...
optimize_policy
python
rlworkgroup/garage
src/garage/torch/algos/ddpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/ddpg.py
MIT
def update_target(self): """Update parameters in the target policy and Q-value network.""" for t_param, param in zip(self._target_qf.parameters(), self._qf.parameters()): t_param.data.copy_(t_param.data * (1.0 - self._tau) + pa...
Update parameters in the target policy and Q-value network.
update_target
python
rlworkgroup/garage
src/garage/torch/algos/ddpg.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/ddpg.py
MIT
def _log_eval_results(self, epoch): """Log evaluation results after an epoch. Args: epoch (int): Current epoch. """ logger.log('Training finished') if self.replay_buffer.n_transitions_stored >= self._min_buffer_size: tabular.record('Epoch', epoch) ...
Log evaluation results after an epoch. Args: epoch (int): Current epoch.
_log_eval_results
python
rlworkgroup/garage
src/garage/torch/algos/dqn.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/dqn.py
MIT
def _optimize_qf(self, timesteps): """Perform algorithm optimizing. Args: timesteps (TimeStepBatch): Processed batch data. Returns: qval_loss: Loss of Q-value predicted by the Q-network. ys: y_s. qval: Q-value predicted by the Q-network. ...
Perform algorithm optimizing. Args: timesteps (TimeStepBatch): Processed batch data. Returns: qval_loss: Loss of Q-value predicted by the Q-network. ys: y_s. qval: Q-value predicted by the Q-network.
_optimize_qf
python
rlworkgroup/garage
src/garage/torch/algos/dqn.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/dqn.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() logger.log('Using device: ' + str(device)) self._qf = self._qf.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/dqn.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/dqn.py
MIT
def train(self, trainer): """Obtain samples and start training for each epoch. Args: trainer (Trainer): Gives the algorithm access to :method:`~Trainer.step_epochs()`, which provides services such as snapshotting and sampler control. Returns: ...
Obtain samples and start training for each epoch. Args: trainer (Trainer): Gives the algorithm access to :method:`~Trainer.step_epochs()`, which provides services such as snapshotting and sampler control. Returns: float: The average return in las...
train
python
rlworkgroup/garage
src/garage/torch/algos/maml.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/maml.py
MIT
def _train_once(self, trainer, all_samples, all_params): """Train the algorithm once. Args: trainer (Trainer): The experiment runner. all_samples (list[list[_MAMLEpisodeBatch]]): A two dimensional list of _MAMLEpisodeBatch of size [meta_batch_size...
Train the algorithm once. Args: trainer (Trainer): The experiment runner. all_samples (list[list[_MAMLEpisodeBatch]]): A two dimensional list of _MAMLEpisodeBatch of size [meta_batch_size * (num_grad_updates + 1)] all_params (list[dict]): A li...
_train_once
python
rlworkgroup/garage
src/garage/torch/algos/maml.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/maml.py
MIT
def _train_value_function(self, paths): """Train the value function. Args: paths (list[dict]): A list of collected paths. Returns: torch.Tensor: Calculated mean scalar value of value function loss (float). """ # MAML resets a value funct...
Train the value function. Args: paths (list[dict]): A list of collected paths. Returns: torch.Tensor: Calculated mean scalar value of value function loss (float).
_train_value_function
python
rlworkgroup/garage
src/garage/torch/algos/maml.py
https://github.com/rlworkgroup/garage/blob/master/src/garage/torch/algos/maml.py
MIT
def _obtain_samples(self, trainer): """Obtain samples for each task before and after the fast-adaptation. Args: trainer (Trainer): A trainer instance to obtain samples. Returns: tuple: Tuple of (all_samples, all_params). all_samples (list[_MAMLEpisodeBat...
Obtain samples for each task before and after the fast-adaptation. Args: trainer (Trainer): A trainer instance to obtain samples. Returns: tuple: Tuple of (all_samples, all_params). all_samples (list[_MAMLEpisodeBatch]): A list of size [meta_...
_obtain_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 _adapt(self, batch_samples, set_grad=True): """Performs one MAML inner step to update the policy. Args: batch_samples (_MAMLEpisodeBatch): Samples data for one task and one gradient step. set_grad (bool): if False, update policy parameters in-place. ...
Performs one MAML inner step to update the policy. Args: batch_samples (_MAMLEpisodeBatch): Samples data for one task and one gradient step. set_grad (bool): if False, update policy parameters in-place. Else, allow taking gradient of functions of updated ...
_adapt
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_meta_loss(self, all_samples, all_params, set_grad=True): """Compute loss to meta-optimize. Args: all_samples (list[list[_MAMLEpisodeBatch]]): A two dimensional list of _MAMLEpisodeBatch of size [meta_batch_size * (num_grad_updates + 1)] ...
Compute loss to meta-optimize. Args: all_samples (list[list[_MAMLEpisodeBatch]]): A two dimensional list of _MAMLEpisodeBatch of size [meta_batch_size * (num_grad_updates + 1)] all_params (list[dict]): A list of named parameter dictionaries. ...
_compute_meta_loss
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_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 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 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 _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 _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 _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