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 _update_reward_critic(self, obs: torch.Tensor, target_value_r: torch.Tensor) -> None:
r"""Update value network under a double for loop.
The loss function is ``MSE loss``, which is defined in ``torch.nn.MSELoss``.
Specifically, the loss function is defined as:
.. math::
... | Update value network under a double for loop.
The loss function is ``MSE loss``, which is defined in ``torch.nn.MSELoss``.
Specifically, the loss function is defined as:
.. math::
L = \frac{1}{N} \sum_{i=1}^N (\hat{V} - V)^2
where :math:`\hat{V}` is the predicted cost and... | _update_reward_critic | 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 _update_cost_critic(self, obs: torch.Tensor, target_value_c: torch.Tensor) -> None:
r"""Update value network under a double for loop.
The loss function is ``MSE loss``, which is defined in ``torch.nn.MSELoss``.
Specifically, the loss function is defined as:
.. math::
L... | Update value network under a double for loop.
The loss function is ``MSE loss``, which is defined in ``torch.nn.MSELoss``.
Specifically, the loss function is defined as:
.. math::
L = \frac{1}{N} \sum_{i=1}^N (\hat{V} - V)^2
where :math:`\hat{V}` is the predicted cost and... | _update_cost_critic | 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 _update_actor( # pylint: disable=too-many-arguments
self,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv_r: torch.Tensor,
adv_c: torch.Tensor,
) -> None:
"""Update policy network under a double for loop.
#. Compute the loss functio... | Update policy network under a double for loop.
#. Compute the loss function.
#. Clip the gradient if ``use_max_grad_norm`` is ``True``.
#. Update the network by loss function.
.. warning::
For some ``KL divergence`` based algorithms (e.g. TRPO, CPO, etc.),
the `... | _update_actor | 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 _compute_adv_surrogate( # pylint: disable=unused-argument
self,
adv_r: torch.Tensor,
adv_c: torch.Tensor,
) -> torch.Tensor:
"""Compute surrogate loss.
Policy Gradient only use reward advantage.
Args:
adv_r (torch.Tensor): The ``reward_advantage`` s... | Compute surrogate loss.
Policy Gradient only use reward advantage.
Args:
adv_r (torch.Tensor): The ``reward_advantage`` sampled from buffer.
adv_c (torch.Tensor): The ``cost_advantage`` sampled from buffer.
Returns:
The advantage function of reward to updat... | _compute_adv_surrogate | 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 _loss_pi(
self,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv: torch.Tensor,
) -> torch.Tensor:
r"""Computing pi/actor loss.
In Policy Gradient, the loss is defined as:
.. math::
L = -\underset{s_t \sim \rho_{\theta}}... | Computing pi/actor loss.
In Policy Gradient, the loss is defined as:
.. math::
L = -\underset{s_t \sim \rho_{\theta}}{\mathbb{E}} [
\sum_{t=0}^T ( \frac{\pi^{'}_{\theta}(a_t|s_t)}{\pi_{\theta}(a_t|s_t)} )
A^{R}_{\pi_{\theta}}(s_t, a_t)
]
... | _loss_pi | 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 _loss_pi(
self,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv: torch.Tensor,
) -> torch.Tensor:
r"""Computing pi/actor loss.
In Proximal Policy Optimization, the loss is defined as:
.. math::
L^{CLIP} = \underset{s_t ... | Computing pi/actor loss.
In Proximal Policy Optimization, the loss is defined as:
.. math::
L^{CLIP} = \underset{s_t \sim \rho_{\theta}}{\mathbb{E}} \left[
\min ( r_t A^{R}_{\pi_{\theta}} (s_t, a_t) , \text{clip} (r_t, 1 - \epsilon, 1 + \epsilon)
A^{R}_{\pi... | _loss_pi | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/base/ppo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/ppo.py | Apache-2.0 |
def _search_step_size(
self,
step_direction: torch.Tensor,
grads: torch.Tensor,
p_dist: Distribution,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv: torch.Tensor,
loss_before: torch.Tensor,
total_steps: int = 15,
dec... | TRPO performs `line-search <https://en.wikipedia.org/wiki/Line_search>`_ until constraint satisfaction.
.. hint::
TRPO search around for a satisfied step of policy update to improve loss and reward performance. The search
is done by line-search, which is a way to find a step size that s... | _search_step_size | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/base/trpo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/trpo.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:
"""Update policy network.
Trust Policy Region Optimization up... | Update policy network.
Trust Policy Region Optimization updates policy network using the
`conjugate gradient <https://en.wikipedia.org/wiki/Conjugate_gradient_method>`_ algorithm,
following the steps:
- Compute the gradient of the policy.
- Compute the step direction.
-... | _update_actor | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/base/trpo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/base/trpo.py | Apache-2.0 |
def _init_env(self) -> None:
"""Initialize the environment.
OmniSafe uses :class:`omnisafe.adapter.EarlyTerminatedAdapter` to adapt the environment to
the algorithm.
User can customize the environment by inheriting this method.
Examples:
>>> def _init_env(self) -> ... | Initialize the environment.
OmniSafe uses :class:`omnisafe.adapter.EarlyTerminatedAdapter` to adapt the environment to
the algorithm.
User can customize the environment by inheriting this method.
Examples:
>>> def _init_env(self) -> None:
... self._env = Cu... | _init_env | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/early_terminated/ppo_early_terminated.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/early_terminated/ppo_early_terminated.py | Apache-2.0 |
def _init_log(self) -> None:
"""Log the CUP specific information.
+-----------------------------+----------------------------------------------------------+
| Things to log | Description |
+=============================+========... | Log the CUP specific information.
+-----------------------------+----------------------------------------------------------+
| Things to log | Description |
+=============================+================================================... | _init_log | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/first_order/cup.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/first_order/cup.py | Apache-2.0 |
def _loss_pi_cost(
self,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv_c: torch.Tensor,
) -> torch.Tensor:
r"""Compute the performance of cost on this moment.
We compute the KL divergence between the current policy and the old policy, the entr... | Compute the performance of cost on this moment.
We compute the KL divergence between the current policy and the old policy, the entropy of
the current policy, and the ratio between the current policy and the old policy.
The loss of the cost performance is defined as:
.. math::
... | _loss_pi_cost | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/first_order/cup.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/first_order/cup.py | Apache-2.0 |
def _update(self) -> None:
r"""Update actor, critic, and Lagrange multiplier parameters.
In CUP, the Lagrange multiplier is updated as the naive lagrange multiplier update.
Then in each iteration of the policy update, CUP calculates current policy's distribution,
which used to calculat... | Update actor, critic, and Lagrange multiplier parameters.
In CUP, the Lagrange multiplier is updated as the naive lagrange multiplier update.
Then in each iteration of the policy update, CUP calculates current policy's distribution,
which used to calculate the policy loss.
| _update | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/first_order/cup.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/first_order/cup.py | Apache-2.0 |
def _init(self) -> None:
"""Initialize the FOCOPS specific model.
The FOCOPS algorithm uses a Lagrange multiplier to balance the cost and reward.
"""
super()._init()
self._lagrange: Lagrange = Lagrange(**self._cfgs.lagrange_cfgs) | Initialize the FOCOPS specific model.
The FOCOPS algorithm uses a Lagrange multiplier to balance the cost and reward.
| _init | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/first_order/focops.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/first_order/focops.py | Apache-2.0 |
def _loss_pi(
self,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv: torch.Tensor,
) -> torch.Tensor:
r"""Compute pi/actor loss.
In FOCOPS, the loss is defined as:
.. math::
:nowrap:
\begin{eqnarray}
... | Compute pi/actor loss.
In FOCOPS, the loss is defined as:
.. math::
:nowrap:
\begin{eqnarray}
L = \nabla_{\theta} D_{K L} \left( \pi_{\theta}^{'} \| \pi_{\theta} \right)[s]
- \frac{1}{\eta} \underset{a \sim \pi_{\theta}}{\mathbb{E}} \left[
... | _loss_pi | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/first_order/focops.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/first_order/focops.py | Apache-2.0 |
def _compute_adv_surrogate(self, adv_r: torch.Tensor, adv_c: torch.Tensor) -> torch.Tensor:
r"""Compute surrogate loss.
FOCOPS uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\... | Compute surrogate loss.
FOCOPS uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\theta}} (s, a)
]
Args:
adv_r (torch.Tensor): The ``reward_advantage`` s... | _compute_adv_surrogate | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/first_order/focops.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/first_order/focops.py | Apache-2.0 |
def _update(self) -> None:
r"""Update actor, critic, and Lagrange multiplier parameters.
In FOCOPS, the Lagrange multiplier is updated as the naive lagrange multiplier update.
Then in each iteration of the policy update, FOCOPS calculates current policy's
distribution, which used to ca... | Update actor, critic, and Lagrange multiplier parameters.
In FOCOPS, the Lagrange multiplier is updated as the naive lagrange multiplier update.
Then in each iteration of the policy update, FOCOPS calculates current policy's
distribution, which used to calculate the policy loss.
| _update | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/first_order/focops.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/first_order/focops.py | Apache-2.0 |
def _update(self) -> None:
r"""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.
.. note::
The :meth:`compute_loss_pi` is defined in ... | 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.
.. note::
The :meth:`compute_loss_pi` is defined in the :class:`PolicyGradient` algorithm. ... | _update | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/naive_lagrange/pdo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/naive_lagrange/pdo.py | Apache-2.0 |
def _compute_adv_surrogate(self, adv_r: torch.Tensor, adv_c: torch.Tensor) -> torch.Tensor:
r"""Compute surrogate loss.
PDO uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\the... | Compute surrogate loss.
PDO uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\theta}} (s, a)
]
Args:
adv_r (torch.Tensor): The ``reward_advantage`` samp... | _compute_adv_surrogate | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/naive_lagrange/pdo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/naive_lagrange/pdo.py | Apache-2.0 |
def _init(self) -> None:
"""Initialize the PPOLag specific model.
The PPOLag algorithm uses a Lagrange multiplier to balance the cost and reward.
"""
super()._init()
self._lagrange: Lagrange = Lagrange(**self._cfgs.lagrange_cfgs) | Initialize the PPOLag specific model.
The PPOLag algorithm uses a Lagrange multiplier to balance the cost and reward.
| _init | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/naive_lagrange/ppo_lag.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/naive_lagrange/ppo_lag.py | Apache-2.0 |
def _update(self) -> None:
r"""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.
.. note::
The :meth:`_loss_pi` is defined in the :cl... | 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.
.. note::
The :meth:`_loss_pi` is defined in the :class:`PolicyGradient` algorithm. When a
... | _update | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/naive_lagrange/ppo_lag.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/naive_lagrange/ppo_lag.py | Apache-2.0 |
def _compute_adv_surrogate(self, adv_r: torch.Tensor, adv_c: torch.Tensor) -> torch.Tensor:
r"""Compute surrogate loss.
PPOLag uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\... | Compute surrogate loss.
PPOLag uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\theta}} (s, a)
]
Args:
adv_r (torch.Tensor): The ``reward_advantage`` s... | _compute_adv_surrogate | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/naive_lagrange/ppo_lag.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/naive_lagrange/ppo_lag.py | Apache-2.0 |
def _compute_adv_surrogate(self, adv_r: torch.Tensor, adv_c: torch.Tensor) -> torch.Tensor:
r"""Compute surrogate loss.
RCPO uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\th... | Compute surrogate loss.
RCPO uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\theta}} (s, a)
]
Args:
adv_r (torch.Tensor): The ``reward_advantage`` sam... | _compute_adv_surrogate | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/naive_lagrange/rcpo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/naive_lagrange/rcpo.py | Apache-2.0 |
def _init(self) -> None:
"""Initialize the TRPOLag specific model.
The TRPOLag algorithm uses a Lagrange multiplier to balance the cost and reward.
"""
super()._init()
self._lagrange: Lagrange = Lagrange(**self._cfgs.lagrange_cfgs) | Initialize the TRPOLag specific model.
The TRPOLag algorithm uses a Lagrange multiplier to balance the cost and reward.
| _init | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/naive_lagrange/trpo_lag.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/naive_lagrange/trpo_lag.py | Apache-2.0 |
def _compute_adv_surrogate(self, adv_r: torch.Tensor, adv_c: torch.Tensor) -> torch.Tensor:
r"""Compute surrogate loss.
TRPOLag uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{... | Compute surrogate loss.
TRPOLag uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\theta}} (s, a)
]
Args:
adv_r (torch.Tensor): The ``reward_advantage`` ... | _compute_adv_surrogate | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/naive_lagrange/trpo_lag.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/naive_lagrange/trpo_lag.py | Apache-2.0 |
def _loss_pi_cost(
self,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv_c: torch.Tensor,
) -> torch.Tensor:
r"""Compute the performance of cost on this moment.
We compute the loss of cost of policy cost from real cost.
.. math::
... | Compute the performance of cost on this moment.
We compute the loss of cost of policy cost from real cost.
.. math::
L = -\underset{s_t \sim \rho_{\theta}}{\mathbb{E}} \left[
\frac{\pi^{'} (a|s)}{\pi (a|s)} A^{C}_{\pi_{\theta}} (s, a)
\right]
where :m... | _loss_pi_cost | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/penalty_function/p3o.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/penalty_function/p3o.py | Apache-2.0 |
def _update_actor(
self,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv_r: torch.Tensor,
adv_c: torch.Tensor,
) -> None:
"""Update policy network under a double for loop.
The pseudo code is shown below:
.. code-block:: python
... | Update policy network under a double for loop.
The pseudo code is shown below:
.. code-block:: python
for _ in range(self.cfgs.actor_iters):
for _ in range(self.cfgs.num_mini_batches):
# Get mini-batch data
# Compute loss
... | _update_actor | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/penalty_function/p3o.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/penalty_function/p3o.py | Apache-2.0 |
def _init(self) -> None:
"""Initialize the CPPOPID specific model.
The CPPOPID algorithm uses a PID-Lagrange multiplier to balance the cost and reward.
"""
super()._init()
self._lagrange: PIDLagrangian = PIDLagrangian(**self._cfgs.lagrange_cfgs) | Initialize the CPPOPID specific model.
The CPPOPID algorithm uses a PID-Lagrange multiplier to balance the cost and reward.
| _init | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/pid_lagrange/cppo_pid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/pid_lagrange/cppo_pid.py | Apache-2.0 |
def _update(self) -> None:
r"""Update actor, critic, as we used in the :class:`PolicyGradient` algorithm.
Additionally, we update the PID-Lagrange multiplier parameter by calling the
:meth:`update_lagrange_multiplier` method.
.. note::
The :meth:`_loss_pi` is defined in the... | Update actor, critic, as we used in the :class:`PolicyGradient` algorithm.
Additionally, we update the PID-Lagrange multiplier parameter by calling the
:meth:`update_lagrange_multiplier` method.
.. note::
The :meth:`_loss_pi` is defined in the :class:`PolicyGradient` algorithm.
... | _update | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/pid_lagrange/cppo_pid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/pid_lagrange/cppo_pid.py | Apache-2.0 |
def _compute_adv_surrogate(self, adv_r: torch.Tensor, adv_c: torch.Tensor) -> torch.Tensor:
r"""Compute surrogate loss.
CPPOPID uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{... | Compute surrogate loss.
CPPOPID uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [
A^{R}_{\pi_{\theta}} (s, a)
- \lambda A^C_{\pi_{\theta}} (s, a)
]
Args:
adv_r (torch.Tensor): The ``reward_advantage`` ... | _compute_adv_surrogate | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/pid_lagrange/cppo_pid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/pid_lagrange/cppo_pid.py | Apache-2.0 |
def _init(self) -> None:
"""Initialize the TRPOPID specific model.
The TRPOPID algorithm uses a PID-Lagrange multiplier to balance the cost and reward.
"""
super()._init()
self._lagrange: PIDLagrangian = PIDLagrangian(**self._cfgs.lagrange_cfgs) | Initialize the TRPOPID specific model.
The TRPOPID algorithm uses a PID-Lagrange multiplier to balance the cost and reward.
| _init | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/pid_lagrange/trpo_pid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/pid_lagrange/trpo_pid.py | Apache-2.0 |
def _update(self) -> None:
r"""Update actor, critic, as we used in the :class:`PolicyGradient` algorithm.
Additionally, we update the PID-Lagrange multiplier parameter by calling the
:meth:`update_lagrange_multiplier` method.
.. note::
The :meth:`_loss_pi` is defined in the... | Update actor, critic, as we used in the :class:`PolicyGradient` algorithm.
Additionally, we update the PID-Lagrange multiplier parameter by calling the
:meth:`update_lagrange_multiplier` method.
.. note::
The :meth:`_loss_pi` is defined in the :class:`PolicyGradient` algorithm. Whe... | _update | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/pid_lagrange/trpo_pid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/pid_lagrange/trpo_pid.py | Apache-2.0 |
def _compute_adv_surrogate(self, adv_r: torch.Tensor, adv_c: torch.Tensor) -> torch.Tensor:
r"""Compute surrogate loss.
TRPOPID uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [A^{R}_{\pi_{\theta}}(s, a)
- \lambda A^C_{\pi_{\theta}}(s, a)]
... | Compute surrogate loss.
TRPOPID uses the following surrogate loss:
.. math::
L = \frac{1}{1 + \lambda} [A^{R}_{\pi_{\theta}}(s, a)
- \lambda A^C_{\pi_{\theta}}(s, a)]
Args:
adv_r (torch.Tensor): The ``reward_advantage`` sampled from buffer.
adv... | _compute_adv_surrogate | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/pid_lagrange/trpo_pid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/pid_lagrange/trpo_pid.py | Apache-2.0 |
def __init__(self, env_id: str, cfgs: Config) -> None:
"""Initialize an instance of :class:`OnCRPO`."""
super().__init__(env_id, cfgs)
self._rew_update: int = 0
self._cost_update: int = 0 | Initialize an instance of :class:`OnCRPO`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/primal/crpo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/primal/crpo.py | Apache-2.0 |
def _init_env(self) -> None:
"""Initialize the environment.
OmniSafe uses :class:`omnisafe.adapter.SauteAdapter` 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.SauteAdapter` to adapt the environment to the algorithm.
User can customize the environment by inheriting this method.
Examples:
>>> def _init_env(self) -> None:
... self._env = CustomAdapter()
... | _init_env | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/saute/ppo_saute.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/saute/ppo_saute.py | Apache-2.0 |
def _cpo_search_step(
self,
step_direction: torch.Tensor,
grads: torch.Tensor,
p_dist: torch.distributions.Distribution,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv_r: torch.Tensor,
adv_c: torch.Tensor,
loss_reward_before:... | Use line-search to find the step size that satisfies the constraint.
CPO uses line-search to find the step size that satisfies the constraint. The constraint is
defined as:
.. math::
J^C (\theta + \alpha \delta) - J^C (\theta) \leq \max \{ 0, c \} \\
D_{KL} (\pi_{\thet... | _cpo_search_step | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/second_order/cpo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/second_order/cpo.py | Apache-2.0 |
def _loss_pi_cost(
self,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv_c: torch.Tensor,
) -> torch.Tensor:
r"""Compute the performance of cost on this moment.
We compute the loss of cost of policy cost from real cost.
.. math::
... | Compute the performance of cost on this moment.
We compute the loss of cost of policy cost from real cost.
.. math::
L = \mathbb{E}_{\pi} \left[ \frac{\pi^{'} (a|s)}{\pi (a|s)} A^C (s, a) \right]
where :math:`A^C (s, a)` is the cost advantage, :math:`\pi (a|s)` is the old policy,... | _loss_pi_cost | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/second_order/cpo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/second_order/cpo.py | Apache-2.0 |
def _determine_case(
self,
b_grads: torch.Tensor,
ep_costs: torch.Tensor,
q: torch.Tensor,
r: torch.Tensor,
s: torch.Tensor,
) -> tuple[int, torch.Tensor, torch.Tensor]:
"""Determine the case of the trust region update.
Args:
b_grad (torch... | Determine the case of the trust region update.
Args:
b_grad (torch.Tensor): Gradient of the cost function.
ep_costs (torch.Tensor): Cost of the current episode.
q (torch.Tensor): The quadratic term of the quadratic approximation of the cost function.
r (torch.Ten... | _determine_case | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/second_order/cpo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/second_order/cpo.py | Apache-2.0 |
def _update_actor(
self,
obs: torch.Tensor,
act: torch.Tensor,
logp: torch.Tensor,
adv_r: torch.Tensor,
adv_c: torch.Tensor,
) -> None:
"""Update policy network.
Constrained Policy Optimization updates policy network using the
`conjugate gradi... | Update policy network.
Constrained Policy Optimization updates policy network using the
`conjugate gradient <https://en.wikipedia.org/wiki/Conjugate_gradient_method>`_ algorithm,
following the steps:
- Compute the gradient of the policy.
- Compute the step direction.
- ... | _update_actor | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/second_order/cpo.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/second_order/cpo.py | Apache-2.0 |
def _init_env(self) -> None:
"""Initialize the environment.
OmniSafe uses :class:`omnisafe.adapter.SimmerAdapter` 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.SimmerAdapter` to adapt the environment to the algorithm.
User can customize the environment by inheriting this method.
Examples:
>>> def _init_env(self) -> None:
... self._env = CustomAdapter()
... | _init_env | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/simmer/ppo_simmer_pid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/simmer/ppo_simmer_pid.py | Apache-2.0 |
def _update(self) -> None:
"""Update actor, critic, as we used in the :class:`PolicyGradient` algorithm."""
Jc = self._logger.get_stats('Metrics/EpCost')[0]
self._env.control_budget(torch.as_tensor(Jc, dtype=torch.float32, device=self._device))
super()._update() | Update actor, critic, as we used in the :class:`PolicyGradient` algorithm. | _update | python | PKU-Alignment/omnisafe | omnisafe/algorithms/on_policy/simmer/ppo_simmer_pid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/algorithms/on_policy/simmer/ppo_simmer_pid.py | Apache-2.0 |
def __init__(self, exp_name: str = '') -> None:
"""Initialize an instance of :class:`ExperimentGrid`."""
self.keys: list[str] = []
self.vals: list[Any] = []
self.shs: list[str] = []
self.in_names: list[bool] = []
self.div_line_width: int = 80
assert isinstance(exp... | Initialize an instance of :class:`ExperimentGrid`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def print(self) -> None:
"""Print a helpful report about the experiment grid.
This function prints a helpful report about the experiment grid, including the name of the
experiment grid, the parameters being varied, and the possible values for each parameter.
In Command Line:
.... | Print a helpful report about the experiment grid.
This function prints a helpful report about the experiment grid, including the name of the
experiment grid, the parameters being varied, and the possible values for each parameter.
In Command Line:
.. code-block:: bash
===... | print | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def _default_shorthand(self, key: str) -> str:
"""Get the default shorthand.
Create a default shorthand for the key, built from the first
three letters of each colon-separated part.
But if the first three letters contains something which isn't
alphanumeric, shear that off.
... | Get the default shorthand.
Create a default shorthand for the key, built from the first
three letters of each colon-separated part.
But if the first three letters contains something which isn't
alphanumeric, shear that off.
Examples:
>>> _default_shorthand('env_name... | _default_shorthand | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def add(
self,
key: str,
vals: list[Any] | Any,
shorthand: str | None = None,
in_name: bool = False,
) -> None:
"""Add a parameter (key) to the grid config, with potential values (vals).
By default, if a shorthand isn't given, one is automatically generated f... | Add a parameter (key) to the grid config, with potential values (vals).
By default, if a shorthand isn't given, one is automatically generated from the key using
the first three letters of each colon-separated term.
.. hint::
This function is called in ``omnisafe/examples/benchmark... | add | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def variant_name(self, variant: dict[str, Any]) -> str:
"""Given a variant (dict of valid param/value pairs), make an exp_name.
A variant's name is constructed as the grid name (if you've given it one), plus param names
(or shorthands if available) and values separated by underscores.
... | Given a variant (dict of valid param/value pairs), make an exp_name.
A variant's name is constructed as the grid name (if you've given it one), plus param names
(or shorthands if available) and values separated by underscores.
..warning::
if ``seed`` is a parameter, it is not inclu... | variant_name | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def get_val(value: dict[str, Any], key: str) -> Any:
"""Get value from variant.
Utility method for getting the correct value out of a variant
given as a nested dict. Assumes that a parameter name, k,
describes a path into the nested dict, such that k='a:b:c'
... | Get value from variant.
Utility method for getting the correct value out of a variant
given as a nested dict. Assumes that a parameter name, k,
describes a path into the nested dict, such that k='a:b:c'
corresponds to value=variant['a']['b']['c']. Uses recursion
... | get_val | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def update_dict(self, total_dict: dict[str, Any], item_dict: dict[str, Any]) -> None:
"""Updater of multi-level dictionary.
This function is used to update the total dictionary with the item dictionary.
Args:
total_dict (dict[str, Any]): Total dictionary.
item_dict (dic... | Updater of multi-level dictionary.
This function is used to update the total dictionary with the item dictionary.
Args:
total_dict (dict[str, Any]): Total dictionary.
item_dict (dict[str, Any]): Item dictionary.
| update_dict | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def _variants(self, keys: list[str], vals: list[Any]) -> list[dict[str, Any]]:
"""Recursively builds list of valid variants.
Args:
keys (keys: list[str]): List of keys.
vals (list[Any]): List of values.
Returns:
List of valid variants.
"""
if... | Recursively builds list of valid variants.
Args:
keys (keys: list[str]): List of keys.
vals (list[Any]): List of values.
Returns:
List of valid variants.
| _variants | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def variants(self) -> list[dict[str, Any]]:
"""Makes a list of dict, where each dict is a valid config in the grid.
There is special handling for variant parameters whose names take the form
``'full:param:name'``.
The colons are taken to indicate that these parameters should have a nes... | Makes a list of dict, where each dict is a valid config in the grid.
There is special handling for variant parameters whose names take the form
``'full:param:name'``.
The colons are taken to indicate that these parameters should have a nested dict structure.
For example, if there are t... | variants | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def check_duplicate(var: dict[str, Any]) -> dict[str, Any]:
"""Build the full nested dict version of var, based on key names."""
new_var: dict[str, Any] = {}
unflatten_set: set = set()
for key, value in var.items():
assert key not in new_var, "You can't a... | Build the full nested dict version of var, based on key names. | check_duplicate | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def save_results(
self,
exp_names: list[str],
variants: list[dict[str, Any]],
results: list,
) -> None:
"""Save results to a file.
Args:
exp_names (list of str): List of experiment names.
variants (list[dict[str, Any]]): List of experiment var... | Save results to a file.
Args:
exp_names (list of str): List of experiment names.
variants (list[dict[str, Any]]): List of experiment variants.
results (list): List of experiment results.
| save_results | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def save_same_exps_config(self, exps_log_dir: str, variant: dict[str, Any]) -> None:
"""Save experiment grid configurations as json.
Args:
exps_log_dir (str): Experiment log directory.
variant (dict[str, Any]): Experiment variant.
"""
os.makedirs(exps_log_dir, ex... | Save experiment grid configurations as json.
Args:
exps_log_dir (str): Experiment log directory.
variant (dict[str, Any]): Experiment variant.
| save_same_exps_config | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def save_grid_config(self) -> None:
"""Save experiment grid configurations as json."""
os.makedirs(self.log_dir, exist_ok=True)
path = os.path.join(self.log_dir, 'grid_config.json')
self._console.print(
'Save with config of experiment grid in grid_config.json',
st... | Save experiment grid configurations as json. | save_grid_config | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def check_variant_vaild(self, variant: dict[str, Any]) -> None:
"""Check if the variant is valid.
Args:
variant (dict[str, Any]): Experiment variant to be checked.
"""
path = os.path.dirname(os.path.abspath(__file__))
algo_type = ALGORITHM2TYPE.get(variant['algo'], '... | Check if the variant is valid.
Args:
variant (dict[str, Any]): Experiment variant to be checked.
| check_variant_vaild | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def evaluate(self, num_episodes: int = 10, cost_criteria: float = 1.0) -> None:
"""Agent Evaluation.
Args:
num_episodes (int, optional): Number of episodes to evaluate. Defaults to 10.
cost_criteria (float, optional): Cost criteria for evaluation. Defaults to 1.0.
"""
... | Agent Evaluation.
Args:
num_episodes (int, optional): Number of episodes to evaluate. Defaults to 10.
cost_criteria (float, optional): Cost criteria for evaluation. Defaults to 1.0.
| evaluate | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def render(
self,
num_episodes: int = 10,
render_mode: str = 'rgb_array',
camera_name: str = 'track',
width: int = 256,
height: int = 256,
) -> None: # pragma: no cover
"""Evaluate and render some episodes.
Args:
num_episodes (int, option... | Evaluate and render some episodes.
Args:
num_episodes (int, optional): Number of episodes to render. Defaults to 10.
render_mode (str, optional): Render mode, can be 'rgb_array', 'depth_array' or 'human'.
Defaults to 'rgb_array'.
camera_name (str, optional): ... | render | python | PKU-Alignment/omnisafe | omnisafe/common/experiment_grid.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/experiment_grid.py | Apache-2.0 |
def __init__(
self,
cost_limit: float,
lagrangian_multiplier_init: float,
lambda_lr: float,
lambda_optimizer: str,
lagrangian_upper_bound: float | None = None,
) -> None:
"""Initialize an instance of :class:`Lagrange`."""
self.cost_limit: float = cost_... | Initialize an instance of :class:`Lagrange`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/lagrange.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/lagrange.py | Apache-2.0 |
def __init__( # pylint: disable=too-many-arguments,too-many-locals
self,
output_dir: str,
exp_name: str,
output_fname: str = 'progress.csv',
seed: int = 0,
use_tensorboard: bool = True,
use_wandb: bool = False,
config: Config | None = None,
models... | Initialize an instance of :class:`Logger`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/logger.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/logger.py | Apache-2.0 |
def log(self, msg: str, color: str = 'green', bold: bool = False) -> None:
"""Log the message to the console and the file.
Args:
msg (str): The message to be logged.
color (str, optional): The color of the message. Defaults to 'green'.
bold (bool, optional): Whether ... | Log the message to the console and the file.
Args:
msg (str): The message to be logged.
color (str, optional): The color of the message. Defaults to 'green'.
bold (bool, optional): Whether the message is bold. Defaults to False.
| log | python | PKU-Alignment/omnisafe | omnisafe/common/logger.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/logger.py | Apache-2.0 |
def save_config(self, config: Config) -> None:
"""Save the configuration to the log directory.
Args:
config (Config): The configuration to be saved.
"""
if self._maste_proc:
self.log('Save with config in config.json', 'yellow', bold=True)
with open(os... | Save the configuration to the log directory.
Args:
config (Config): The configuration to be saved.
| save_config | python | PKU-Alignment/omnisafe | omnisafe/common/logger.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/logger.py | Apache-2.0 |
def register_key(
self,
key: str,
window_length: int | None = None,
min_and_max: bool = False,
delta: bool = False,
) -> None:
"""Register a key to the logger.
The logger can record the following data:
.. code-block:: text
--------------... | Register a key to the logger.
The logger can record the following data:
.. code-block:: text
----------------------------------------------------
| Name | Value |
----------------------------------------------------
|... | register_key | python | PKU-Alignment/omnisafe | omnisafe/common/logger.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/logger.py | Apache-2.0 |
def store(
self,
data: dict[str, Any] | None = None,
/,
**kwargs: Any | float | np.ndarray | torch.Tensor,
) -> None:
"""Store the data to the logger.
.. note ::
The data stored in ``data`` will be updated by ``kwargs``.
Args:
data (d... | Store the data to the logger.
.. note ::
The data stored in ``data`` will be updated by ``kwargs``.
Args:
data (dict[str, float | np.ndarray | torch.Tensor] or None, optional): The data to
be stored. Defaults to None.
Keyword Args:
kwargs (i... | store | python | PKU-Alignment/omnisafe | omnisafe/common/logger.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/logger.py | Apache-2.0 |
def dump_tabular(self) -> None:
"""Dump the tabular data to the console and the file.
The dumped data will be separated by the following steps:
- If the key is registered with window_length, the data will be averaged in the window.
- Write the data to the csv file.
- Write the ... | Dump the tabular data to the console and the file.
The dumped data will be separated by the following steps:
- If the key is registered with window_length, the data will be averaged in the window.
- Write the data to the csv file.
- Write the data to the tensorboard.
- Update t... | dump_tabular | python | PKU-Alignment/omnisafe | omnisafe/common/logger.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/logger.py | Apache-2.0 |
def _update_current_row(self) -> None:
"""Update the current row.
Update the current row with the data stored in the logger.
"""
for key in self._data:
old_data = self._current_row[key]
if self._headers_minmax[key]:
mean, min_val, max_val, std = s... | Update the current row.
Update the current row with the data stored in the logger.
| _update_current_row | python | PKU-Alignment/omnisafe | omnisafe/common/logger.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/logger.py | Apache-2.0 |
def get_stats(
self,
key: str,
min_and_max: bool = False,
) -> tuple[float, ...]:
"""Get the statistics of the key.
Args:
key (str): The key to be registered.
min_and_max (bool, optional): Whether to record the min and max value of the key.
... | Get the statistics of the key.
Args:
key (str): The key to be registered.
min_and_max (bool, optional): Whether to record the min and max value of the key.
Defaults to False.
Returns:
The mean value of the key or (mean, min, max, std) of the key.
... | get_stats | python | PKU-Alignment/omnisafe | omnisafe/common/logger.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/logger.py | Apache-2.0 |
def __init__(self, shape: tuple[int, ...], clip: float = 1e6) -> None:
"""Initialize an instance of :class:`Normalizer`."""
super().__init__()
if shape == ():
self.register_buffer('_mean', torch.tensor(0.0))
self.register_buffer('_sumsq', torch.tensor(0.0))
se... | Initialize an instance of :class:`Normalizer`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/normalizer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/normalizer.py | Apache-2.0 |
def normalize(self, data: torch.Tensor) -> torch.Tensor:
"""Normalize the data.
.. hint::
- If the data is the first data, the data will be used to initialize the mean and std.
- If the data is not the first data, the data will be normalized by the mean and std.
- Up... | Normalize the data.
.. hint::
- If the data is the first data, the data will be used to initialize the mean and std.
- If the data is not the first data, the data will be normalized by the mean and std.
- Update the mean and std by the data.
Args:
data (... | normalize | python | PKU-Alignment/omnisafe | omnisafe/common/normalizer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/normalizer.py | Apache-2.0 |
def _push(self, raw_data: torch.Tensor) -> None:
"""Update the mean and std by the raw_data.
Args:
raw_data (torch.Tensor): The raw data to be normalized.
"""
if raw_data.shape == self._shape:
raw_data = raw_data.unsqueeze(0)
assert raw_data.shape[1:] == ... | Update the mean and std by the raw_data.
Args:
raw_data (torch.Tensor): The raw data to be normalized.
| _push | python | PKU-Alignment/omnisafe | omnisafe/common/normalizer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/normalizer.py | Apache-2.0 |
def load_state_dict(
self,
state_dict: Mapping[str, Any],
strict: bool = True,
assign: bool = False,
) -> Any:
"""Load the state_dict to the normalizer.
Args:
state_dict (Mapping[str, Any]): The state_dict to be loaded.
strict (bool, optional)... | Load the state_dict to the normalizer.
Args:
state_dict (Mapping[str, Any]): The state_dict to be loaded.
strict (bool, optional): Whether to strictly enforce that the keys in :attr:`state_dict`.
Defaults to True.
Returns:
The loaded normalizer.
... | load_state_dict | python | PKU-Alignment/omnisafe | omnisafe/common/normalizer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/normalizer.py | Apache-2.0 |
def __init__(
self,
pid_kp: float,
pid_ki: float,
pid_kd: float,
pid_d_delay: int,
pid_delta_p_ema_alpha: float,
pid_delta_d_ema_alpha: float,
sum_norm: bool,
diff_norm: bool,
penalty_max: int,
lagrangian_multiplier_init: float,
... | Initialize an instance of :class:`PIDLagrangian`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/pid_lagrange.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/pid_lagrange.py | Apache-2.0 |
def __init__(
self,
cfgs: Config,
budget_bound: torch.Tensor,
obs_space: tuple[int,] = (0,),
action_space: tuple[int, int] = (-1, 1),
history_len: int = 100,
) -> None:
"""Initialize an instance of :class:`BaseSimmerAgent`."""
assert obs_space is not N... | Initialize an instance of :class:`BaseSimmerAgent`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/simmer_agent.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/simmer_agent.py | Apache-2.0 |
def get_greedy_action(
self,
safety_budget: torch.Tensor,
observation: torch.Tensor,
) -> torch.Tensor:
"""Get the greedy action.
Args:
safety_budget (torch.Tensor): The current safety budget.
observation (torch.Tensor): The current observation.
... | Get the greedy action.
Args:
safety_budget (torch.Tensor): The current safety budget.
observation (torch.Tensor): The current observation.
Raises:
NotImplementedError: The method is not implemented.
| get_greedy_action | python | PKU-Alignment/omnisafe | omnisafe/common/simmer_agent.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/simmer_agent.py | Apache-2.0 |
def act(
self,
safety_budget: torch.Tensor,
observation: torch.Tensor,
) -> torch.Tensor:
"""Get the action.
Args:
safety_budget (torch.Tensor): The current safety budget.
observation (torch.Tensor): The current observation.
Raises:
... | Get the action.
Args:
safety_budget (torch.Tensor): The current safety budget.
observation (torch.Tensor): The current observation.
Raises:
NotImplementedError: The method is not implemented.
| act | python | PKU-Alignment/omnisafe | omnisafe/common/simmer_agent.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/simmer_agent.py | Apache-2.0 |
def __init__(
self,
cfgs: Config,
budget_bound: torch.Tensor,
obs_space: tuple[int,] = (0,),
action_space: tuple[int, int] = (-1, 1),
history_len: int = 100,
) -> None:
"""Initialize an instance of :class:`SimmerPIDAgent`."""
super().__init__(
... | Initialize an instance of :class:`SimmerPIDAgent`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/simmer_agent.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/simmer_agent.py | Apache-2.0 |
def get_greedy_action(
self,
safety_budget: torch.Tensor,
observation: torch.Tensor,
) -> torch.Tensor:
"""Get the greedy action.
Args:
safety_budget (torch.Tensor): The current safety budget.
observation (torch.Tensor): The current observation.
... | Get the greedy action.
Args:
safety_budget (torch.Tensor): The current safety budget.
observation (torch.Tensor): The current observation.
Returns:
The greedy action.
| get_greedy_action | python | PKU-Alignment/omnisafe | omnisafe/common/simmer_agent.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/simmer_agent.py | Apache-2.0 |
def act(
self,
safety_budget: torch.Tensor,
observation: torch.Tensor,
) -> torch.Tensor:
"""Get the action.
Args:
safety_budget (torch.Tensor): The current safety budget.
observation (torch.Tensor): The current observation.
Returns:
... | Get the action.
Args:
safety_budget (torch.Tensor): The current safety budget.
observation (torch.Tensor): The current observation.
Returns:
The selected action.
| act | python | PKU-Alignment/omnisafe | omnisafe/common/simmer_agent.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/simmer_agent.py | Apache-2.0 |
def load_source(self, path: str) -> None:
"""Load experiment results.
Args:
path (str): The experiment directory.
"""
# recursively find directory which is generated by experiment grid
grid_config_dirs = []
for root, _, files in os.walk(path):
if ... | Load experiment results.
Args:
path (str): The experiment directory.
| load_source | python | PKU-Alignment/omnisafe | omnisafe/common/statistics_tools.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/statistics_tools.py | Apache-2.0 |
def make_config_groups(
self,
parameter: str,
parameter_values: list[str],
values: list[Any] | None = None,
compare_num: int | None = None,
) -> list[dict[tuple[str, Any], str]]:
"""Make config groups.
Each group contains a list of config paths to compare.
... | Make config groups.
Each group contains a list of config paths to compare.
.. warning::
`values` and `compare_num` cannot be set at the same time.
Args:
parameter (str): The parameter to compare.
parameter_values (list[str]): The values of the parameter to ... | make_config_groups | python | PKU-Alignment/omnisafe | omnisafe/common/statistics_tools.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/statistics_tools.py | Apache-2.0 |
def decompress_key(self, compressed_key: str, value: Any) -> dict[str, Any]:
"""This function is used to convert the custom configurations to dict.
.. note::
This function is used to convert the custom configurations to dict. For example, if the
custom configurations are ``train... | This function is used to convert the custom configurations to dict.
.. note::
This function is used to convert the custom configurations to dict. For example, if the
custom configurations are ``train_cfgs:use_wandb`` and ``True``, then the output dict
will be ``{'train_cfgs'... | decompress_key | python | PKU-Alignment/omnisafe | omnisafe/common/statistics_tools.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/statistics_tools.py | Apache-2.0 |
def _variants(self, keys: list[str], vals: list[Any]) -> list[dict[str, Any]]:
"""Recursively builds list of valid variants.
Args:
keys (list[str]): The keys of the config.
vals (list[Any]): The values of the config.
Returns:
List of valid variants.
... | Recursively builds list of valid variants.
Args:
keys (list[str]): The keys of the config.
vals (list[Any]): The values of the config.
Returns:
List of valid variants.
| _variants | python | PKU-Alignment/omnisafe | omnisafe/common/statistics_tools.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/statistics_tools.py | Apache-2.0 |
def update_dict(self, total_dict: dict[str, Any], item_dict: dict[str, Any]) -> None:
"""Updater of multi-level dictionary.
Args:
total_dict (dict[str, Any]): The total dictionary.
item_dict (dict[str, Any]): The item dictionary.
"""
for idd in item_dict:
... | Updater of multi-level dictionary.
Args:
total_dict (dict[str, Any]): The total dictionary.
item_dict (dict[str, Any]): The item dictionary.
| update_dict | python | PKU-Alignment/omnisafe | omnisafe/common/statistics_tools.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/statistics_tools.py | Apache-2.0 |
def variants(self, keys: list[str], vals: list[Any]) -> list[dict[str, Any]]:
"""Makes a list of dict, where each dict is a valid config in the grid.
There is special handling for variant parameters whose names take the form
``'full:param:name'``
The colons are taken to indicate t... | Makes a list of dict, where each dict is a valid config in the grid.
There is special handling for variant parameters whose names take the form
``'full:param:name'``
The colons are taken to indicate that these parameters should have a nested dict structure.
For example, if there a... | variants | python | PKU-Alignment/omnisafe | omnisafe/common/statistics_tools.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/statistics_tools.py | Apache-2.0 |
def combine(self, sequence: list[str], num_choosen: int) -> Generator:
"""Combine elements in sequence to n elements.
Args:
sequence (list[str]): The sequence to be combined.
num_choosen (int): The number of elements to be combined.
Returns:
The generator of... | Combine elements in sequence to n elements.
Args:
sequence (list[str]): The sequence to be combined.
num_choosen (int): The number of elements to be combined.
Returns:
The generator of the combined elements.
| combine | python | PKU-Alignment/omnisafe | omnisafe/common/statistics_tools.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/statistics_tools.py | Apache-2.0 |
def dict_permutations(self, input_dict: dict[str, Any]) -> list[dict[str, Any]]:
"""Generate all possible combinations of the values in a dictionary.
Takes a dictionary with string keys and list values, and returns a dictionary with all
possible combinations of the lists as values for each key.... | Generate all possible combinations of the values in a dictionary.
Takes a dictionary with string keys and list values, and returns a dictionary with all
possible combinations of the lists as values for each key.
Args:
input_dict (dict[str, Any]): The input dictionary.
Retu... | dict_permutations | python | PKU-Alignment/omnisafe | omnisafe/common/statistics_tools.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/statistics_tools.py | Apache-2.0 |
def get_compressed_key(self, dictionary: dict[str, Any], key: str) -> Any:
"""Get the compressed value of the key.
Args:
dictionary (dict[str, Any]): the uncompressed dictionary.
key (str): the key.
Returns:
The compressed value of the key.
"""
... | Get the compressed value of the key.
Args:
dictionary (dict[str, Any]): the uncompressed dictionary.
key (str): the key.
Returns:
The compressed value of the key.
| get_compressed_key | python | PKU-Alignment/omnisafe | omnisafe/common/statistics_tools.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/statistics_tools.py | Apache-2.0 |
def __init__(
self,
obs_space: OmnisafeSpace,
act_space: OmnisafeSpace,
size: int,
device: torch.device = DEVICE_CPU,
) -> None:
"""Initialize an instance of :class:`BaseBuffer`."""
self._device: torch.device = device
if isinstance(obs_space, Box):
... | Initialize an instance of :class:`BaseBuffer`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/base.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/base.py | Apache-2.0 |
def store(self, **data: torch.Tensor) -> None:
"""Store a transition in the buffer.
.. warning::
This is an abstract method.
Examples:
>>> buffer = BaseBuffer(...)
>>> buffer.store(obs=obs, act=act, reward=reward, cost=cost, done=done)
Args:
... | Store a transition in the buffer.
.. warning::
This is an abstract method.
Examples:
>>> buffer = BaseBuffer(...)
>>> buffer.store(obs=obs, act=act, reward=reward, cost=cost, done=done)
Args:
data (torch.Tensor): The data to store.
| store | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/base.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/base.py | Apache-2.0 |
def __init__( # pylint: disable=too-many-arguments
self,
obs_space: OmnisafeSpace,
act_space: OmnisafeSpace,
size: int,
batch_size: int,
penalty_coefficient: float = 0.0,
device: torch.device = DEVICE_CPU,
) -> None:
"""Initialize an instance of :clas... | Initialize an instance of :class:`OffPolicyBuffer`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/offpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/offpolicy_buffer.py | Apache-2.0 |
def store(self, **data: torch.Tensor) -> None:
"""Store data into the buffer.
.. hint::
The ReplayBuffer is a circular buffer. When the buffer is full, the oldest data will be
overwritten.
Args:
data (torch.Tensor): The data to be stored.
"""
... | Store data into the buffer.
.. hint::
The ReplayBuffer is a circular buffer. When the buffer is full, the oldest data will be
overwritten.
Args:
data (torch.Tensor): The data to be stored.
| store | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/offpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/offpolicy_buffer.py | Apache-2.0 |
def sample_batch(self) -> dict[str, torch.Tensor]:
"""Sample a batch of data from the buffer.
Returns:
The sampled batch of data.
"""
idxs = torch.randint(0, self._size, (self._batch_size,))
return {key: value[idxs] for key, value in self.data.items()} | Sample a batch of data from the buffer.
Returns:
The sampled batch of data.
| sample_batch | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/offpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/offpolicy_buffer.py | Apache-2.0 |
def __init__( # pylint: disable=too-many-arguments
self,
obs_space: OmnisafeSpace,
act_space: OmnisafeSpace,
size: int,
gamma: float,
lam: float,
lam_c: float,
advantage_estimator: AdvatageEstimator,
penalty_coefficient: float = 0,
standar... | Initialize an instance of :class:`OnPolicyBuffer`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/onpolicy_buffer.py | Apache-2.0 |
def store(self, **data: torch.Tensor) -> None:
"""Store data into the buffer.
.. warning::
The total size of the data must be less than the buffer size.
Args:
data (torch.Tensor): The data to store.
"""
assert self.ptr < self.max_size, 'No more space in ... | Store data into the buffer.
.. warning::
The total size of the data must be less than the buffer size.
Args:
data (torch.Tensor): The data to store.
| store | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/onpolicy_buffer.py | Apache-2.0 |
def finish_path(
self,
last_value_r: torch.Tensor | None = None,
last_value_c: torch.Tensor | None = None,
) -> None:
"""Finish the current path and calculate the advantages of state-action pairs.
On-policy algorithms need to calculate the advantages of state-action pairs
... | Finish the current path and calculate the advantages of state-action pairs.
On-policy algorithms need to calculate the advantages of state-action pairs
after the path is finished. This function calculates the advantages of
state-action pairs and stores them in the buffer, following the steps:
... | finish_path | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/onpolicy_buffer.py | Apache-2.0 |
def get(self) -> dict[str, torch.Tensor]:
"""Get the data in the buffer.
.. hint::
We provide a trick to standardize the advantages of state-action pairs. We calculate the
mean and standard deviation of the advantages of state-action pairs and then standardize
the ad... | Get the data in the buffer.
.. hint::
We provide a trick to standardize the advantages of state-action pairs. We calculate the
mean and standard deviation of the advantages of state-action pairs and then standardize
the advantages of state-action pairs. You can turn on this ... | get | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/onpolicy_buffer.py | Apache-2.0 |
def _calculate_adv_and_value_targets(
self,
values: torch.Tensor,
rewards: torch.Tensor,
lam: float,
) -> tuple[torch.Tensor, torch.Tensor]:
r"""Compute the estimated advantage.
Three methods are supported:
- GAE (Generalized Advantage Estimation)
... | Compute the estimated advantage.
Three methods are supported:
- GAE (Generalized Advantage Estimation)
GAE is a variance reduction method for the actor-critic algorithm. It is proposed in the
paper `High-Dimensional Continuous Control Using Generalized Advantage Estimation <ht... | _calculate_adv_and_value_targets | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/onpolicy_buffer.py | Apache-2.0 |
def _calculate_v_trace(
policy_action_probs: torch.Tensor,
values: torch.Tensor, # including bootstrap
rewards: torch.Tensor, # including bootstrap
behavior_action_probs: torch.Tensor,
gamma: float = 0.99,
rho_bar: float = 1.0,
c_bar: float = 1.0,
) -> tuple... | This function is used to calculate V-trace targets.
.. math::
A_t = \sum_{k=0}^{n-1} (\lambda \gamma)^k \delta_{t+k} +
(\lambda \gamma)^n \rho_{t+n} (1 - d_{t+n}) (V(x_{t+n}) - b_{t+n})
Calculate V-trace targets for off-policy actor-critic learning recursively. For more
... | _calculate_v_trace | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/onpolicy_buffer.py | Apache-2.0 |
def __init__( # pylint: disable=super-init-not-called,too-many-arguments
self,
obs_space: OmnisafeSpace,
act_space: OmnisafeSpace,
size: int,
batch_size: int,
num_envs: int,
penalty_coefficient: float = 0.0,
device: torch.device = DEVICE_CPU,
) -> Non... | Initialize an instance of :class:`VectorOffPolicyBuffer`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/vector_offpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/vector_offpolicy_buffer.py | Apache-2.0 |
def add_field(self, name: str, shape: tuple[int, ...], dtype: torch.dtype) -> None:
"""Add a field to the buffer.
Examples:
>>> buffer = BaseBuffer(...)
>>> buffer.add_field('new_field', (2, 3), torch.float32)
>>> buffer.data['new_field'].shape
>>> (buffe... | Add a field to the buffer.
Examples:
>>> buffer = BaseBuffer(...)
>>> buffer.add_field('new_field', (2, 3), torch.float32)
>>> buffer.data['new_field'].shape
>>> (buffer.size, 2, 3)
Args:
name (str): The name of the field.
shape (... | add_field | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/vector_offpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/vector_offpolicy_buffer.py | Apache-2.0 |
def __init__( # pylint: disable=super-init-not-called,too-many-arguments
self,
obs_space: OmnisafeSpace,
act_space: OmnisafeSpace,
size: int,
gamma: float,
lam: float,
lam_c: float,
advantage_estimator: AdvatageEstimator,
penalty_coefficient: floa... | Initialize an instance of :class:`VectorOnPolicyBuffer`. | __init__ | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/vector_onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/vector_onpolicy_buffer.py | Apache-2.0 |
def store(self, **data: torch.Tensor) -> None:
"""Store vectorized data into vectorized buffer."""
for i, buffer in enumerate(self.buffers):
buffer.store(**{k: v[i] for k, v in data.items()}) | Store vectorized data into vectorized buffer. | store | python | PKU-Alignment/omnisafe | omnisafe/common/buffer/vector_onpolicy_buffer.py | https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/common/buffer/vector_onpolicy_buffer.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.