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 _init_log(self) -> None: """Initialize the logger keys for the CCE algorithm. +----------------------------+-------------------------------+ | Things to log | Description | +============================+===============================+ | Plan/f...
Initialize the logger keys for the CCE algorithm. +----------------------------+-------------------------------+ | Things to log | Description | +============================+===============================+ | Plan/feasible_num | The number of fea...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/cce_pets.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/cce_pets.py
Apache-2.0
def _init_model(self) -> None: """Initialize the dynamics model and the planner. RCEPETS uses following models: - dynamics model: to predict the next state and the cost. - planner: to generate the action. """ self._dynamics_state_space = ( self._env.coordina...
Initialize the dynamics model and the planner. RCEPETS uses following models: - dynamics model: to predict the next state and the cost. - planner: to generate the action.
_init_model
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/rce_pets.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/rce_pets.py
Apache-2.0
def _init_log(self) -> None: """Initialize the logger. +----------------------------+-------------------------------+ | Things to log | Description | +============================+===============================+ | Plan/feasible_num | The ...
Initialize the logger. +----------------------------+-------------------------------+ | Things to log | Description | +============================+===============================+ | Plan/feasible_num | The number of feasible plans. | +---...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/rce_pets.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/rce_pets.py
Apache-2.0
def _init_model(self) -> None: """Initialize the dynamics model and the planner. SafeLOOP uses following models: - dynamics model: to predict the next state and the cost. - planner: to generate the action. """ self._dynamics_state_space: OmnisafeSpace = ( se...
Initialize the dynamics model and the planner. SafeLOOP uses following models: - dynamics model: to predict the next state and the cost. - planner: to generate the action.
_init_model
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/safeloop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/safeloop.py
Apache-2.0
def _init_log(self) -> None: """Initialize the logger keys for the algorithm. +----------------------------+-------------------------------+ | Things to log | Description | +============================+===============================+ | Plan/feasi...
Initialize the logger keys for the algorithm. +----------------------------+-------------------------------+ | Things to log | Description | +============================+===============================+ | Plan/feasible_num | The number of feasibl...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/safeloop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/safeloop.py
Apache-2.0
def __init__(self, device: torch.device) -> None: """Initialize an instance of :class:`StandardScaler`.""" self._mean: float = 0.0 self._std: float = 1.0 self._mean_t: torch.Tensor = torch.tensor(self._mean).to(device) self._std_t: torch.Tensor = torch.tensor(self._std).to(device...
Initialize an instance of :class:`StandardScaler`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def fit(self, data: np.ndarray) -> None: """Fits the scaler to the input data. Args: data (np.ndarray): A numpy array containing the input. """ self._mean = np.mean(data, axis=0, keepdims=True) self._std = np.std(data, axis=0, keepdims=True) self._std = np.ma...
Fits the scaler to the input data. Args: data (np.ndarray): A numpy array containing the input.
fit
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def init_weights(layer: nn.Module) -> None: """Initialize network weight. Args: layer (nn.Module): The layer to initialize. """ def truncated_normal_init( weight: torch.Tensor, mean: float = 0.0, std: float = 0.01, ) -> torch.Tensor: """Initialize network we...
Initialize network weight. Args: layer (nn.Module): The layer to initialize.
init_weights
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def truncated_normal_init( weight: torch.Tensor, mean: float = 0.0, std: float = 0.01, ) -> torch.Tensor: """Initialize network weight. Args: weight (torch.Tensor): The weight to be initialized. mean (float): The mean of the normal distribution. ...
Initialize network weight. Args: weight (torch.Tensor): The weight to be initialized. mean (float): The mean of the normal distribution. std (float): The standard deviation of the normal distribution. Returns: weight: The initialized weight.
truncated_normal_init
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def unbatched_forward( layer: nn.Module | EnsembleFC, input_data: torch.Tensor, index: int, ) -> torch.Tensor: """Special forward for nn.Sequential modules which contain BatchedLinear layers we want to use. Args: layer (nn.Module | EnsembleFC): The layer to forward through. input_da...
Special forward for nn.Sequential modules which contain BatchedLinear layers we want to use. Args: layer (nn.Module | EnsembleFC): The layer to forward through. input_data (torch.Tensor): The input data. index (int): The index of the model to use. Returns: output: The output of...
unbatched_forward
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def __init__( self, in_features: int, out_features: int, ensemble_size: int, weight_decay: float = 0.0, bias: bool = True, ) -> None: """Initialize an instance of fully connected network.""" super().__init__() self._constants_ = ['in_features',...
Initialize an instance of fully connected network.
__init__
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def forward(self, input_data: torch.Tensor) -> torch.Tensor: """Forward pass. Args: input_data (torch.Tensor): The input data. Returns: The forward output of the network. """ w_times_x = torch.bmm(input_data, self.weight) if self.bias is not None...
Forward pass. Args: input_data (torch.Tensor): The input data. Returns: The forward output of the network.
forward
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def forward( self, data: torch.Tensor | np.ndarray, ret_log_var: bool = False, ) -> tuple[torch.Tensor, torch.Tensor]: # pylint: disable=not-callable """Compute next state, reward, cost using all models. Args: data (torch.Tensor): Input data. ...
Compute next state, reward, cost using all models. Args: data (torch.Tensor): Input data. ret_log_var (bool, optional): Whether to return the log variance, defaults to False. Returns: mean: Mean of the next state, reward, cost. logvar or var: Log varianc...
forward
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def forward_idx( self, data: torch.Tensor | np.ndarray, idx_model: int, ret_log_var: bool = False, ) -> tuple[torch.Tensor, torch.Tensor]: """Compute next state, reward, cost from an certain model. Args: data (torch.Tensor | np.ndarray): Input data. ...
Compute next state, reward, cost from an certain model. Args: data (torch.Tensor | np.ndarray): Input data. idx_model (int): Index of the model. ret_log_var (bool): Whether to return the log variance. Returns: mean: Mean of the next state, reward, cost. ...
forward_idx
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def loss( self, mean: torch.Tensor, logvar: torch.Tensor, labels: torch.Tensor, inc_var_loss: bool = True, ) -> tuple[torch.Tensor, torch.Tensor]: """Compute loss. Args: mean (torch.Tensor): Mean of the next state, reward, cost. logvar...
Compute loss. Args: mean (torch.Tensor): Mean of the next state, reward, cost. logvar (torch.Tensor): Log variance of the next state, reward, cost. labels (torch.Tensor): Ground truth of the next state, reward, cost. inc_var_loss (bool, optional): Whether to incl...
loss
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def train_ensemble(self, loss: torch.Tensor) -> None: """Train the dynamics model. Args: loss (torch.Tensor): The loss of the dynamics model. """ self._optimizer.zero_grad() loss += 0.01 * torch.sum(torch.Tensor(self.max_logvar)) - 0.01 * torch.sum( torch...
Train the dynamics model. Args: loss (torch.Tensor): The loss of the dynamics model.
train_ensemble
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def train( self, inputs: np.ndarray, labels: np.ndarray, holdout_ratio: float = 0.0, ) -> tuple[np.ndarray, np.ndarray]: """Train the dynamics, holdout_ratio is the data ratio hold out for validation. Args: inputs (np.ndarray): Input data. lab...
Train the dynamics, holdout_ratio is the data ratio hold out for validation. Args: inputs (np.ndarray): Input data. labels (np.ndarray): Ground truth of the next state, reward, cost. holdout_ratio (float): The ratio of the data hold out for validation. Returns: ...
train
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def _save_best(self, epoch: int, holdout_losses: list) -> bool: """Save the best model. Args: epoch (int): The current epoch. holdout_losses (list): The holdout loss. Returns: Whether to break the training. """ updated = False for i, ...
Save the best model. Args: epoch (int): The current epoch. holdout_losses (list): The holdout loss. Returns: Whether to break the training.
_save_best
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def _compute_reward( self, network_output: torch.Tensor, ) -> torch.Tensor: """Compute the reward from the network output. Args: network_output (torch.Tensor): The output of the network. Returns: reward: The reward, from the network output or the rew...
Compute the reward from the network output. Args: network_output (torch.Tensor): The output of the network. Returns: reward: The reward, from the network output or the reward function. Raises: ValueError: If the reward function is not defined.
_compute_reward
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def _compute_cost( self, network_output: torch.Tensor, ) -> torch.Tensor: """Compute the cost from the network output. Args: network_output (torch.Tensor): The output of the network. Returns: cost: The cost, from the network output or the cost functi...
Compute the cost from the network output. Args: network_output (torch.Tensor): The output of the network. Returns: cost: The cost, from the network output or the cost function. Raises: ValueError: If the cost function is not defined.
_compute_cost
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def _compute_terminal( self, network_output: torch.Tensor, ) -> torch.Tensor: """Compute the terminal from the network output. Args: network_output (torch.Tensor): The output of the network. Returns: terminal: The terminal signal, from the network ou...
Compute the terminal from the network output. Args: network_output (torch.Tensor): The output of the network. Returns: terminal: The terminal signal, from the network output or the terminal function. Raises: ValueError: If the terminal function is not defin...
_compute_terminal
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def _predict( self, inputs: torch.Tensor, batch_size: int = 1024, idx: int | None = None, ret_log_var: bool = False, ) -> tuple[torch.Tensor, torch.Tensor]: """Input type and output type both are tensor, used for planning loop. Args: inputs (torch...
Input type and output type both are tensor, used for planning loop. Args: inputs (torch.Tensor): the inputs to the network. batch_size (int, optional): the batch size for prediction. idx (Union[int, None], optional): the index of the model to use. ret_log_var (bo...
_predict
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def sample( self, states: torch.Tensor, actions: torch.Tensor, idx: int | None = None, deterministic: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, dict[str, list[torch.Tensor]]]: # pylint: disable-next=line-too-long """Sample states and rewards from th...
Sample states and rewards from the ensemble model. Args: states (torch.Tensor): the states. actions (torch.Tensor): the actions. idx (Union[int, None], optional): the index of the model to use. Defaults to None. deterministic (bool, optional): whether to use the ...
sample
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def imagine( self, states: torch.Tensor, horizon: int, actions: torch.Tensor | None = None, actor_critic: ConstraintActorQCritic | None = None, idx: int | None = None, ) -> dict[str, torch.Tensor]: """Imagine the future states and rewards from the ensemble mod...
Imagine the future states and rewards from the ensemble model. Args: states (torch.Tensor): the states. horizon (int): the horizon. actions (torch.Tensor, optional): the actions. actor_critic (ConstraintActorQCritic, optional): the actor_critic to use if actions ...
imagine
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/ensemble.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/ensemble.py
Apache-2.0
def _init_model(self) -> None: """Initialize the dynamics model and the planner. LOOP uses following models: - dynamics model: to predict the next state and the cost. - actor_critic: to predict the action and the value. - planner: to generate the action. """ sel...
Initialize the dynamics model and the planner. LOOP uses following models: - dynamics model: to predict the next state and the cost. - actor_critic: to predict the action and the value. - planner: to generate the action.
_init_model
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _init(self) -> None: """The initialization of the algorithm. User can define the initialization of the algorithm by inheriting this method. Examples: >>> def _init(self) -> None: ... super()._init() ... self._buffer = CustomBuffer() ....
The initialization of the algorithm. User can define the initialization of the algorithm by inheriting this method. Examples: >>> def _init(self) -> None: ... super()._init() ... self._buffer = CustomBuffer() ... self._model = CustomModel() ...
_init
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _init_log(self) -> None: """Initialize logger. +-------------------------+----------------------------------------------------------------------+ | Things to log | Description | +=========================+===========...
Initialize logger. +-------------------------+----------------------------------------------------------------------+ | Things to log | Description | +=========================+===================================================...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _select_action( # pylint: disable=unused-argument self, current_step: int, state: torch.Tensor, ) -> torch.Tensor: """Select action. Args: current_step (int): The current step. state (torch.Tensor): The current state. Returns: ...
Select action. Args: current_step (int): The current step. state (torch.Tensor): The current state. Returns: The selected action.
_select_action
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _update_policy(self, current_step: int) -> None: """Update policy. - Get the ``data`` from buffer .. note:: +----------+---------------------------------------+ | obs | ``observaion`` stored in buffer. | +==========+==========================...
Update policy. - Get the ``data`` from buffer .. note:: +----------+---------------------------------------+ | obs | ``observaion`` stored in buffer. | +==========+=======================================+ | act | ``action`` stored in buf...
_update_policy
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _store_real_data( # pylint: disable=too-many-arguments,unused-argument self, state: torch.Tensor, action: torch.Tensor, reward: torch.Tensor, cost: torch.Tensor, terminated: torch.Tensor, truncated: torch.Tensor, next_state: torch.Tensor, info...
Store real data in buffer. Args: state (torch.Tensor): The state from the environment. action (torch.Tensor): The action from the agent. reward (torch.Tensor): The reward signal from the environment. cost (torch.Tensor): The cost signal from the environment. ...
_store_real_data
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _update_reward_critic( self, obs: torch.Tensor, action: torch.Tensor, reward: torch.Tensor, done: torch.Tensor, next_obs: torch.Tensor, ) -> None: """Update reward critic using Soft Actor-Critic. - Get the TD loss of reward critic. - Updat...
Update reward critic using Soft Actor-Critic. - Get the TD loss of reward critic. - Update critic network by loss. - Log useful information. Args: obs (torch.Tensor): The ``observation`` sampled from buffer. action (torch.Tensor): The ``action`` sampled from buf...
_update_reward_critic
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _update_cost_critic( self, obs: torch.Tensor, action: torch.Tensor, cost: torch.Tensor, done: torch.Tensor, next_obs: torch.Tensor, ) -> None: """Update cost critic using TD3 algorithm. - Get the TD loss of cost critic. - Update critic net...
Update cost critic using TD3 algorithm. - Get the TD loss of cost critic. - Update critic network by loss. - Log useful information. Args: obs (torch.Tensor): The ``observation`` sampled from buffer. action (torch.Tensor): The ``action`` sampled from buffer. ...
_update_cost_critic
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _update_actor( self, obs: torch.Tensor, ) -> None: """Update actor using Soft Actor-Critic algorithm. - Get the loss of actor. - Update actor by loss. - Log useful information. Args: obs (torch.Tensor): The ``observation`` sampled from buffer...
Update actor using Soft Actor-Critic algorithm. - Get the loss of actor. - Update actor by loss. - Log useful information. Args: obs (torch.Tensor): The ``observation`` sampled from buffer.
_update_actor
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _loss_pi( self, obs: torch.Tensor, ) -> torch.Tensor: r"""Computing ``pi/actor`` loss. The loss function in SAC is defined as: .. math:: L = -Q^V (s, \pi (s)) + \alpha \log \pi (s) where :math:`Q^V` is the min value of two reward critic networks, a...
Computing ``pi/actor`` loss. The loss function in SAC is defined as: .. math:: L = -Q^V (s, \pi (s)) + \alpha \log \pi (s) where :math:`Q^V` is the min value of two reward critic networks, and :math:`\pi` is the policy network, and :math:`\alpha` is the temperature parame...
_loss_pi
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/loop.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/loop.py
Apache-2.0
def _init_log(self) -> None: """Initialize logger. +---------------------------+-------------------------------------------------+ | Things to log | Description | +===========================+===============================================...
Initialize logger. +---------------------------+-------------------------------------------------+ | Things to log | Description | +===========================+=================================================+ | Train/Epoch ...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/pets.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/pets.py
Apache-2.0
def learn(self) -> tuple[float, float, float]: """This is main function for algorithm update. It is divided into the following steps: - :meth:`rollout`: collect interactive data from environment. - :meth:`update`: perform actor/critic updates. - :meth:`log`: epoch/update inform...
This is main function for algorithm update. It is divided into the following steps: - :meth:`rollout`: collect interactive data from environment. - :meth:`update`: perform actor/critic updates. - :meth:`log`: epoch/update information for visualization and terminal log print. R...
learn
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/pets.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/pets.py
Apache-2.0
def _evaluation_single_step( # pylint: disable=too-many-locals self, current_step: int, use_real_input: bool = True, ) -> None: """Evaluation dynamics model single step. Args: current_step (int): The current step. use_real_input (bool): Whether to us...
Evaluation dynamics model single step. Args: current_step (int): The current step. use_real_input (bool): Whether to use real input or not.
_evaluation_single_step
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/pets.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/pets.py
Apache-2.0
def draw_picture( self, timestep: int, num_episode: int, pred_state: list[float], true_state: list[float], save_replay_path: str = './', name: str = 'reward', ) -> None: """Draw a curve of the predicted value and the ground true value. Args: ...
Draw a curve of the predicted value and the ground true value. Args: timestep (int): The current step. num_episode (int): The number of episodes. pred_state (list[float]): The predicted state. true_state (list[float]): The true state. save_replay_path...
draw_picture
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/base/pets.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/base/pets.py
Apache-2.0
def __init__( # pylint: disable=too-many-locals, too-many-arguments self, dynamics: EnsembleDynamicsModel, planner_cfgs: Config, gamma: float, cost_gamma: float, dynamics_state_shape: tuple[int, ...], action_shape: tuple[int, ...], action_max: float, ...
Initialize the planner of Actor Regularized Control (ARC) algorithm.
__init__
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/arc.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/arc.py
Apache-2.0
def _act_from_last_gaus(self, last_mean: torch.Tensor, last_var: torch.Tensor) -> torch.Tensor: """Sample actions from the last gaussian distribution. Args: last_mean (torch.Tensor): Last mean of the gaussian distribution. last_var (torch.Tensor): Last variance of the gaussian d...
Sample actions from the last gaussian distribution. Args: last_mean (torch.Tensor): Last mean of the gaussian distribution. last_var (torch.Tensor): Last variance of the gaussian distribution. Returns: sampled actions: Sampled actions from the last gaussian distribu...
_act_from_last_gaus
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/arc.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/arc.py
Apache-2.0
def _act_from_actor(self, state: torch.Tensor) -> torch.Tensor: """Sample actions from the actor. Args: state (torch.Tensor): The current state. Returns: sampled actions: Sampled actions from the actor. """ assert state.shape == torch.Size( [...
Sample actions from the actor. Args: state (torch.Tensor): The current state. Returns: sampled actions: Sampled actions from the actor.
_act_from_actor
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/arc.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/arc.py
Apache-2.0
def _state_action_repeat( self, state: torch.Tensor, action: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor]: """Repeat the state for num_repeat * action.shape[0] times and action for num_repeat times. Args: state (torch.Tensor): The current state. ...
Repeat the state for num_repeat * action.shape[0] times and action for num_repeat times. Args: state (torch.Tensor): The current state. action (torch.Tensor): The sampled actions. Returns: states: The repeated states. actions: The repeated actions. ...
_state_action_repeat
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/arc.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/arc.py
Apache-2.0
def _select_elites( self, actions: torch.Tensor, traj: dict[str, torch.Tensor], ) -> tuple[torch.Tensor, torch.Tensor, dict[str, float]]: """Select elites from the sampled actions. Args: actions (torch.Tensor): Sampled actions. traj (dict[str, torch.T...
Select elites from the sampled actions. Args: actions (torch.Tensor): Sampled actions. traj (dict[str, torch.Tensor]): Trajectory dictionary. Returns: elites_value: The value of the elites. elites_action: The action of the elites. info: The d...
_select_elites
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/arc.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/arc.py
Apache-2.0
def _update_mean_var( self, elite_actions: torch.Tensor, elite_values: torch.Tensor, info: dict[str, float], ) -> tuple[torch.Tensor, torch.Tensor]: # pylint: disable-next=unused-argument """Update the mean and variance of the elite actions. Args: elite_...
Update the mean and variance of the elite actions. Args: elite_actions (torch.Tensor): The elite actions. elite_values (torch.Tensor): The elite values. info (dict[str, float]): The dictionary containing the information of the elite values and actions. Returns: ...
_update_mean_var
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/arc.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/arc.py
Apache-2.0
def output_action(self, state: torch.Tensor) -> tuple[torch.Tensor, dict[str, float]]: """Output the action given the state. Args: state (torch.Tensor): State of the environment. Returns: action: The action of the agent. info: The dictionary containing the i...
Output the action given the state. Args: state (torch.Tensor): State of the environment. Returns: action: The action of the agent. info: The dictionary containing the information of the action.
output_action
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/arc.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/arc.py
Apache-2.0
def __init__( # pylint: disable=too-many-locals, too-many-arguments self, dynamics: EnsembleDynamicsModel, planner_cfgs: Config, gamma: float, cost_gamma: float, dynamics_state_shape: tuple[int, ...], action_shape: tuple[int, ...], action_max: float, ...
Initializes the planner of Conservative and Adaptive Penalty (CAP) algorithm.
__init__
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/cap.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/cap.py
Apache-2.0
def __init__( # pylint: disable=too-many-locals, too-many-arguments self, dynamics: EnsembleDynamicsModel, planner_cfgs: Config, gamma: float, cost_gamma: float, dynamics_state_shape: tuple[int, ...], action_shape: tuple[int, ...], action_max: float, ...
Initializes the planner of Constrained Cross-Entropy (CCE) algorithm.
__init__
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/cce.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/cce.py
Apache-2.0
def __init__( # pylint: disable=too-many-locals, too-many-arguments self, dynamics: EnsembleDynamicsModel, planner_cfgs: Config, gamma: float, cost_gamma: float, dynamics_state_shape: tuple[int, ...], action_shape: tuple[int, ...], action_max: float, ...
Initializes the planner of Cross-Entropy Method optimization (CEM) algorithm.
__init__
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/cem.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/cem.py
Apache-2.0
def __init__( # pylint: disable=too-many-locals, too-many-arguments self, dynamics: EnsembleDynamicsModel, planner_cfgs: Config, gamma: float, cost_gamma: float, dynamics_state_shape: tuple[int, ...], action_shape: tuple[int, ...], action_max: float, ...
Initializes the planner of Safe Actor Regularized Control (ARC) algorithm.
__init__
python
PKU-Alignment/omnisafe
omnisafe/algorithms/model_based/planner/safe_arc.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/model_based/planner/safe_arc.py
Apache-2.0
def __init__(self, env_id: str, cfgs: Config) -> None: """Initialize an instance of :class:`BaseOffline`.""" super().__init__(env_id, cfgs) self._actor: Actor self.epoch: int = 0
Initialize an instance of :class:`BaseOffline`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/algorithms/offline/base.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/offline/base.py
Apache-2.0
def _init_log(self) -> None: """Log info each epoch. +----------------+--------------------------------+ | Things to log | Description | +================+================================+ | Metrics/EpCost | Average cost of the epoch. | +---------...
Log info each epoch. +----------------+--------------------------------+ | Things to log | Description | +================+================================+ | Metrics/EpCost | Average cost of the epoch. | +-------------------------------------------------...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/offline/base.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/offline/base.py
Apache-2.0
def _init_log(self) -> None: """Log the BCQ specific information. +-------------------------+----------------------------------------------------+ | Things to log | Description | +=========================+================================...
Log the BCQ specific information. +-------------------------+----------------------------------------------------+ | Things to log | Description | +=========================+====================================================+ | Loss/Los...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/offline/bcq.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/offline/bcq.py
Apache-2.0
def _init_log(self) -> None: """Log the BCQLag specific information. +----------------------------+---------------------------------------------------------+ | Things to log | Description | +============================+==========...
Log the BCQLag specific information. +----------------------------+---------------------------------------------------------+ | Things to log | Description | +============================+==================================================...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/offline/bcq_lag.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/offline/bcq_lag.py
Apache-2.0
def _init_log(self) -> None: """Log the COptiDICE specific information. +----------------------------+--------------------------------------------+ | Things to log | Description | +============================+=================================...
Log the COptiDICE specific information. +----------------------------+--------------------------------------------+ | Things to log | Description | +============================+============================================+ | Loss/Loss_actor ...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/offline/coptidice.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/offline/coptidice.py
Apache-2.0
def _init_log(self) -> None: """Log the CRR specific information. +-------------------------+----------------------------------------------------+ | Things to log | Description | +=========================+================================...
Log the CRR specific information. +-------------------------+----------------------------------------------------+ | Things to log | Description | +=========================+====================================================+ | Loss/Los...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/offline/crr.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/offline/crr.py
Apache-2.0
def _init_log(self) -> None: """Log the C-CRR specific information. +----------------------------+---------------------------------------------------------+ | Things to log | Description | +============================+===========...
Log the C-CRR specific information. +----------------------------+---------------------------------------------------------+ | Things to log | Description | +============================+===================================================...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/offline/c_crr.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/offline/c_crr.py
Apache-2.0
def _init_log(self) -> None: """Log the VAE-BC specific information. +-------------------------+----------------------------------------------------+ | Things to log | Description | +=========================+=============================...
Log the VAE-BC specific information. +-------------------------+----------------------------------------------------+ | Things to log | Description | +=========================+====================================================+ | Loss/...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/offline/vae_bc.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/offline/vae_bc.py
Apache-2.0
def _init_env(self) -> None: """Initialize the environment. OmniSafe uses :class:`omnisafe.adapter.CRABSAdapter` to adapt the environment to this algorithm. User can customize the environment by inheriting this method. Examples: >>> def _init_env(self) -> None: ...
Initialize the environment. OmniSafe uses :class:`omnisafe.adapter.CRABSAdapter` to adapt the environment to this algorithm. User can customize the environment by inheriting this method. Examples: >>> def _init_env(self) -> None: ... self._env = CustomAdapt...
_init_env
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/crabs.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/crabs.py
Apache-2.0
def _init_model(self) -> None: """Initialize the models. The ``num_critics`` in ``critic`` configuration must be 2. """ super()._init_model() self.s0 = torch.tensor( self._env.reset()[0], device=self._cfgs.train_cfgs.device, dtype=torch.float3...
Initialize the models. The ``num_critics`` in ``critic`` configuration must be 2.
_init_model
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/crabs.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/crabs.py
Apache-2.0
def _init(self) -> None: """The initialization of the algorithm. User can define the initialization of the algorithm by inheriting this method. Examples: >>> def _init(self) -> None: ... super()._init() ... self._buffer = CustomBuffer() ....
The initialization of the algorithm. User can define the initialization of the algorithm by inheriting this method. Examples: >>> def _init(self) -> None: ... super()._init() ... self._buffer = CustomBuffer() ... self._model = CustomModel() ...
_init
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/crabs.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/crabs.py
Apache-2.0
def learn(self): """This is the main learning function of CRABS, orchestrating the training process across multiple epochs. It performs the following operations sequentially: 1. Pretraining steps on s*. 2. Rollout and evaluation procedures using different policies. 3. Training t...
This is the main learning function of CRABS, orchestrating the training process across multiple epochs. It performs the following operations sequentially: 1. Pretraining steps on s*. 2. Rollout and evaluation procedures using different policies. 3. Training the world models using the co...
learn
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/crabs.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/crabs.py
Apache-2.0
def get_masked_q(self, min_q_value, states, actions): """Get the masked Q value. The loss function here is based on SAC, but with an additional term to mask the Q value. Args: min_q_value (torch.Tensor): The minimum Q value. states (torch.Tensor): The states. ...
Get the masked Q value. The loss function here is based on SAC, but with an additional term to mask the Q value. Args: min_q_value (torch.Tensor): The minimum Q value. states (torch.Tensor): The states. actions (torch.Tensor): The actions. Returns: ...
get_masked_q
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/crabs.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/crabs.py
Apache-2.0
def _update_reward_critic( self, obs: torch.Tensor, action: torch.Tensor, reward: torch.Tensor, done: torch.Tensor, next_obs: torch.Tensor, ) -> None: """Update reward critic. The loss function here is based on SAC, but with an additional term to mask...
Update reward critic. The loss function here is based on SAC, but with an additional term to mask the Q value when the barrier function is positive. Args: obs (torch.Tensor): The ``observation`` sampled from buffer. action (torch.Tensor): The ``action`` sampled from buf...
_update_reward_critic
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/crabs.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/crabs.py
Apache-2.0
def _loss_pi( self, obs: torch.Tensor, ) -> torch.Tensor: r"""Computing ``pi/actor`` loss. The loss function here is based on SAC, but with an additional term to mask the Q value when the barrier function is positive. Args: obs (torch.Tensor): The ``obse...
Computing ``pi/actor`` loss. The loss function here is based on SAC, but with an additional term to mask the Q value when the barrier function is positive. Args: obs (torch.Tensor): The ``observation`` sampled from buffer. Returns: The loss of pi/actor. ...
_loss_pi
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/crabs.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/crabs.py
Apache-2.0
def load_from_ckpt(self): """Load pretrained model from url. If the model is not found locally, download it from the cloud. """ model_url = ( 'https://drive.google.com/uc?export=download&id=1MciBSHU74HjADTINUMrlpa7s_9cX7f1P' ) model_path = '~/.cache/omnisafe/...
Load pretrained model from url. If the model is not found locally, download it from the cloud.
load_from_ckpt
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/crabs.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/crabs.py
Apache-2.0
def train_models(self, *, epochs): """Train the transition models. Args: epochs (int): The number of epochs to train the model. """ from torch.utils.data import DataLoader, IterableDataset class BufferDataset(IterableDataset): def __init__(self, buffer, ...
Train the transition models. Args: epochs (int): The number of epochs to train the model.
train_models
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/crabs.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/crabs.py
Apache-2.0
def _init_env(self) -> None: """Initialize the environment. OmniSafe uses :class:`omnisafe.adapter.OffPolicyAdapter` to adapt the environment to this algorithm. User can customize the environment by inheriting this method. Examples: >>> def _init_env(self) -> None:...
Initialize the environment. OmniSafe uses :class:`omnisafe.adapter.OffPolicyAdapter` to adapt the environment to this algorithm. User can customize the environment by inheriting this method. Examples: >>> def _init_env(self) -> None: ... self._env = CustomA...
_init_env
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def _init_model(self) -> None: """Initialize the model. OmniSafe uses :class:`omnisafe.models.actor_critic.constraint_actor_q_critic.ConstraintActorQCritic` as the default model. User can customize the model by inheriting this method. Examples: >>> def _init_model(...
Initialize the model. OmniSafe uses :class:`omnisafe.models.actor_critic.constraint_actor_q_critic.ConstraintActorQCritic` as the default model. User can customize the model by inheriting this method. Examples: >>> def _init_model(self) -> None: ... self._a...
_init_model
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def _init_log(self) -> None: """Log info about epoch. +-------------------------+----------------------------------------------------------------------+ | Things to log | Description | +=========================+========...
Log info about epoch. +-------------------------+----------------------------------------------------------------------+ | Things to log | Description | +=========================+================================================...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def learn(self) -> tuple[float, float, float]: """This is main function for algorithm update. It is divided into the following steps: - :meth:`rollout`: collect interactive data from environment. - :meth:`update`: perform actor/critic updates. - :meth:`log`: epoch/update inform...
This is main function for algorithm update. It is divided into the following steps: - :meth:`rollout`: collect interactive data from environment. - :meth:`update`: perform actor/critic updates. - :meth:`log`: epoch/update information for visualization and terminal log print. R...
learn
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def _update(self) -> None: """Update actor, critic. - Get the ``data`` from buffer .. note:: +----------+---------------------------------------+ | obs | ``observaion`` stored in buffer. | +==========+=======================================+ ...
Update actor, critic. - Get the ``data`` from buffer .. note:: +----------+---------------------------------------+ | obs | ``observaion`` stored in buffer. | +==========+=======================================+ | act | ``action`` stored...
_update
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def _update_reward_critic( self, obs: torch.Tensor, action: torch.Tensor, reward: torch.Tensor, done: torch.Tensor, next_obs: torch.Tensor, ) -> None: """Update reward critic. - Get the TD loss of reward critic. - Update critic network by loss...
Update reward critic. - Get the TD loss of reward critic. - Update critic network by loss. - Log useful information. Args: obs (torch.Tensor): The ``observation`` sampled from buffer. action (torch.Tensor): The ``action`` sampled from buffer. reward ...
_update_reward_critic
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def _update_cost_critic( self, obs: torch.Tensor, action: torch.Tensor, cost: torch.Tensor, done: torch.Tensor, next_obs: torch.Tensor, ) -> None: """Update cost critic. - Get the TD loss of cost critic. - Update critic network by loss. ...
Update cost critic. - Get the TD loss of cost critic. - Update critic network by loss. - Log useful information. Args: obs (torch.Tensor): The ``observation`` sampled from buffer. action (torch.Tensor): The ``action`` sampled from buffer. cost (torch...
_update_cost_critic
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def _update_actor( # pylint: disable=too-many-arguments self, obs: torch.Tensor, ) -> None: """Update actor. - Get the loss of actor. - Update actor by loss. - Log useful information. Args: obs (torch.Tensor): The ``observation`` sampled from bu...
Update actor. - Get the loss of actor. - Update actor by loss. - Log useful information. Args: obs (torch.Tensor): The ``observation`` sampled from buffer.
_update_actor
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def _loss_pi( self, obs: torch.Tensor, ) -> torch.Tensor: r"""Computing ``pi/actor`` loss. The loss function in DDPG is defined as: .. math:: L = -Q^V (s, \pi (s)) where :math:`Q^V` is the reward critic network, and :math:`\pi` is the policy network. ...
Computing ``pi/actor`` loss. The loss function in DDPG is defined as: .. math:: L = -Q^V (s, \pi (s)) where :math:`Q^V` is the reward critic network, and :math:`\pi` is the policy network. Args: obs (torch.Tensor): The ``observation`` sampled from buffer. ...
_loss_pi
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def _log_when_not_update(self) -> None: """Log default value when not update.""" self._logger.store( { 'Loss/Loss_reward_critic': 0.0, 'Loss/Loss_pi': 0.0, 'Value/reward_critic': 0.0, }, ) if self._cfgs.algo_cfgs.use...
Log default value when not update.
_log_when_not_update
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg.py
Apache-2.0
def _init(self) -> None: """The initialization of the algorithm. Here we additionally initialize the Lagrange multiplier. """ super()._init() self._lagrange: Lagrange = Lagrange(**self._cfgs.lagrange_cfgs)
The initialization of the algorithm. Here we additionally initialize the Lagrange multiplier.
_init
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg_lag.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg_lag.py
Apache-2.0
def _update(self) -> None: """Update actor, critic, as we used in the :class:`PolicyGradient` algorithm. Additionally, we update the Lagrange multiplier parameter by calling the :meth:`update_lagrange_multiplier` method. """ super()._update() Jc = self._logger.get_stats(...
Update actor, critic, as we used in the :class:`PolicyGradient` algorithm. Additionally, we update the Lagrange multiplier parameter by calling the :meth:`update_lagrange_multiplier` method.
_update
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg_lag.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg_lag.py
Apache-2.0
def _loss_pi( self, obs: torch.Tensor, ) -> torch.Tensor: r"""Computing ``pi/actor`` loss. The loss function in DDPGLag is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the min value of two reward critic ne...
Computing ``pi/actor`` loss. The loss function in DDPGLag is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the min value of two reward critic networks outputs, :math:`Q^C` is the value of cost critic network, and :math:`\pi` i...
_loss_pi
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg_lag.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg_lag.py
Apache-2.0
def _init(self) -> None: """The initialization of the DDPGPID algorithm. The DDPGPID algorithm uses a PID-Lagrange multiplier to balance the cost and reward. """ super()._init() self._lagrange: PIDLagrangian = PIDLagrangian(**self._cfgs.lagrange_cfgs)
The initialization of the DDPGPID algorithm. The DDPGPID algorithm uses a PID-Lagrange multiplier to balance the cost and reward.
_init
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg_pid.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg_pid.py
Apache-2.0
def _update(self) -> None: """Update actor, critic, as we used in the :class:`PolicyGradient` algorithm. Additionally, we update the Lagrange multiplier parameter by calling the :meth:`pid_update` method. """ super()._update() Jc = self._logger.get_stats('Metrics/EpCost'...
Update actor, critic, as we used in the :class:`PolicyGradient` algorithm. Additionally, we update the Lagrange multiplier parameter by calling the :meth:`pid_update` method.
_update
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg_pid.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg_pid.py
Apache-2.0
def _loss_pi( self, obs: torch.Tensor, ) -> torch.Tensor: r"""Computing ``pi/actor`` loss. The loss function in DDPGPID is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the value of reward critic network ou...
Computing ``pi/actor`` loss. The loss function in DDPGPID is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the value of reward critic network output, and :math:`\pi` is the policy network. Args: obs (torch...
_loss_pi
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/ddpg_pid.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/ddpg_pid.py
Apache-2.0
def _init_model(self) -> None: """Initialize the model. The ``num_critics`` in ``critic`` configuration must be 2. """ self._cfgs.model_cfgs.critic['num_critics'] = 2 self._actor_critic = ConstraintActorQCritic( obs_space=self._env.observation_space, act_...
Initialize the model. The ``num_critics`` in ``critic`` configuration must be 2.
_init_model
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/sac.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/sac.py
Apache-2.0
def _init(self) -> None: """The initialization of the algorithm. User can define the initialization of the algorithm by inheriting this method. Examples: >>> def _init(self) -> None: ... super()._init() ... self._buffer = CustomBuffer() ....
The initialization of the algorithm. User can define the initialization of the algorithm by inheriting this method. Examples: >>> def _init(self) -> None: ... super()._init() ... self._buffer = CustomBuffer() ... self._model = CustomModel() ...
_init
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/sac.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/sac.py
Apache-2.0
def _update_reward_critic( self, obs: torch.Tensor, action: torch.Tensor, reward: torch.Tensor, done: torch.Tensor, next_obs: torch.Tensor, ) -> None: """Update reward critic. - Sample the target action by target actor. - Get the target Q valu...
Update reward critic. - Sample the target action by target actor. - Get the target Q value by target critic. - Use the minimum target Q value to update reward critic. - Add the entropy loss to reward critic. - Log useful information. Args: obs (torch.Tensor)...
_update_reward_critic
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/sac.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/sac.py
Apache-2.0
def _update_actor( self, obs: torch.Tensor, ) -> None: """Update actor and alpha if ``auto_alpha`` is True. Args: obs (torch.Tensor): The ``observation`` sampled from buffer. """ super()._update_actor(obs) if self._cfgs.algo_cfgs.auto_alpha: ...
Update actor and alpha if ``auto_alpha`` is True. Args: obs (torch.Tensor): The ``observation`` sampled from buffer.
_update_actor
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/sac.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/sac.py
Apache-2.0
def _loss_pi( self, obs: torch.Tensor, ) -> torch.Tensor: r"""Computing ``pi/actor`` loss. The loss function in SACLag is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the min value of two reward critic net...
Computing ``pi/actor`` loss. The loss function in SACLag is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the min value of two reward critic networks outputs, :math:`Q^C` is the value of cost critic network, and :math:`\pi` is...
_loss_pi
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/sac_lag.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/sac_lag.py
Apache-2.0
def _init(self) -> None: """The initialization of the SACPID algorithm. The SACPID algorithm uses a PID-Lagrange multiplier to balance the cost and reward. """ super()._init() self._lagrange: PIDLagrangian = PIDLagrangian(**self._cfgs.lagrange_cfgs)
The initialization of the SACPID algorithm. The SACPID algorithm uses a PID-Lagrange multiplier to balance the cost and reward.
_init
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/sac_pid.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/sac_pid.py
Apache-2.0
def _loss_pi( self, obs: torch.Tensor, ) -> torch.Tensor: r"""Computing ``pi/actor`` loss. The loss function in SACPID is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the min value of two reward critic net...
Computing ``pi/actor`` loss. The loss function in SACPID is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the min value of two reward critic networks outputs, :math:`Q^C` is the value of cost critic network, and :math:`\pi` is...
_loss_pi
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/sac_pid.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/sac_pid.py
Apache-2.0
def _update_reward_critic( self, obs: torch.Tensor, action: torch.Tensor, reward: torch.Tensor, done: torch.Tensor, next_obs: torch.Tensor, ) -> None: """Update reward critic. - Get the target action by target actor. - Add noise to target acti...
Update reward critic. - Get the target action by target actor. - Add noise to target action. - Clip the noise. - Get the target Q value by target critic. - Use the minimum target Q value to update reward critic. - Log useful information. Args: obs (...
_update_reward_critic
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/td3.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/td3.py
Apache-2.0
def _loss_pi( self, obs: torch.Tensor, ) -> torch.Tensor: r"""Computing ``pi/actor`` loss. The loss function in TD3Lag is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the min value of two reward critic net...
Computing ``pi/actor`` loss. The loss function in TD3Lag is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the min value of two reward critic networks outputs, :math:`Q^C` is the value of cost critic network, and :math:`\pi` is...
_loss_pi
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/td3_lag.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/td3_lag.py
Apache-2.0
def _init(self) -> None: """The initialization of the DDPGPID algorithm. The TD3PID algorithm uses a PID-Lagrange multiplier to balance the cost and reward. """ super()._init() self._lagrange: PIDLagrangian = PIDLagrangian(**self._cfgs.lagrange_cfgs)
The initialization of the DDPGPID algorithm. The TD3PID algorithm uses a PID-Lagrange multiplier to balance the cost and reward.
_init
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/td3_pid.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/td3_pid.py
Apache-2.0
def _loss_pi( self, obs: torch.Tensor, ) -> torch.Tensor: r"""Computing ``pi/actor`` loss. The loss function in TD3PID is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the value of reward critic network out...
Computing ``pi/actor`` loss. The loss function in TD3PID is defined as: .. math:: L = -Q^V (s, \pi (s)) + \lambda Q^C (s, \pi (s)) where :math:`Q^V` is the value of reward critic network output, :math:`Q^C` is the value of cost critic network, and :math:`\pi` is the polic...
_loss_pi
python
PKU-Alignment/omnisafe
omnisafe/algorithms/off_policy/td3_pid.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/off_policy/td3_pid.py
Apache-2.0
def _init_log(self) -> None: r"""Log the Natural Policy Gradient specific information. +---------------------+--------------------------------------------------------+ | Things to log | Description | +=====================+===============...
Log the Natural Policy Gradient specific information. +---------------------+--------------------------------------------------------+ | Things to log | Description | +=====================+========================================================...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/on_policy/base/natural_pg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/natural_pg.py
Apache-2.0
def _fvp(self, params: torch.Tensor) -> torch.Tensor: """Build the Hessian-vector product. Build the `Hessian-vector product <https://en.wikipedia.org/wiki/Hessian_matrix>`_ , which is the second-order derivative of the KL-divergence. The Hessian-vector product is approximated by the F...
Build the Hessian-vector product. Build the `Hessian-vector product <https://en.wikipedia.org/wiki/Hessian_matrix>`_ , which is the second-order derivative of the KL-divergence. The Hessian-vector product is approximated by the Fisher information matrix, which is the second-order deriv...
_fvp
python
PKU-Alignment/omnisafe
omnisafe/algorithms/on_policy/base/natural_pg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/natural_pg.py
Apache-2.0
def _update_actor( # pylint: disable=too-many-arguments,too-many-locals self, obs: torch.Tensor, act: torch.Tensor, logp: torch.Tensor, adv_r: torch.Tensor, adv_c: torch.Tensor, ) -> None: r"""Update policy network. Natural Policy Gradient (NPG) upda...
Update policy network. Natural Policy Gradient (NPG) update policy network using the conjugate gradient algorithm, following the steps: - Calculate the gradient of the policy network, - Use the conjugate gradient algorithm to calculate the step direction. - Update the policy ne...
_update_actor
python
PKU-Alignment/omnisafe
omnisafe/algorithms/on_policy/base/natural_pg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/natural_pg.py
Apache-2.0
def _update(self) -> None: """Update actor, critic. .. hint:: Here are some differences between NPG and Policy Gradient (PG): In PG, the actor network and the critic network are updated together. When the KL divergence between the old policy, and the new policy is la...
Update actor, critic. .. hint:: Here are some differences between NPG and Policy Gradient (PG): In PG, the actor network and the critic network are updated together. When the KL divergence between the old policy, and the new policy is larger than a threshold, the update is r...
_update
python
PKU-Alignment/omnisafe
omnisafe/algorithms/on_policy/base/natural_pg.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/natural_pg.py
Apache-2.0
def _init_env(self) -> None: """Initialize the environment. OmniSafe uses :class:`omnisafe.adapter.OnPolicyAdapter` to adapt the environment to the algorithm. User can customize the environment by inheriting this method. Examples: >>> def _init_env(self) -> None: ...
Initialize the environment. OmniSafe uses :class:`omnisafe.adapter.OnPolicyAdapter` to adapt the environment to the algorithm. User can customize the environment by inheriting this method. Examples: >>> def _init_env(self) -> None: ... self._env = CustomAda...
_init_env
python
PKU-Alignment/omnisafe
omnisafe/algorithms/on_policy/base/policy_gradient.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/policy_gradient.py
Apache-2.0
def _init_model(self) -> None: """Initialize the model. OmniSafe uses :class:`omnisafe.models.actor_critic.constraint_actor_critic.ConstraintActorCritic` as the default model. User can customize the model by inheriting this method. Examples: >>> def _init_model(sel...
Initialize the model. OmniSafe uses :class:`omnisafe.models.actor_critic.constraint_actor_critic.ConstraintActorCritic` as the default model. User can customize the model by inheriting this method. Examples: >>> def _init_model(self) -> None: ... self._acto...
_init_model
python
PKU-Alignment/omnisafe
omnisafe/algorithms/on_policy/base/policy_gradient.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/policy_gradient.py
Apache-2.0
def _init_log(self) -> None: """Log info about epoch. +-----------------------+----------------------------------------------------------------------+ | Things to log | Description | +=======================+==============...
Log info about epoch. +-----------------------+----------------------------------------------------------------------+ | Things to log | Description | +=======================+======================================================...
_init_log
python
PKU-Alignment/omnisafe
omnisafe/algorithms/on_policy/base/policy_gradient.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/policy_gradient.py
Apache-2.0