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 predict(self, obs: torch.Tensor, deterministic: bool = False) -> torch.Tensor: """Predict the action given observation. The predicted action depends on the ``deterministic`` flag. - If ``deterministic`` is ``True``, the predicted action is the mean of the distribution. - If ``deter...
Predict the action given observation. The predicted action depends on the ``deterministic`` flag. - If ``deterministic`` is ``True``, the predicted action is the mean of the distribution. - If ``deterministic`` is ``False``, the predicted action is sampled from the distribution. Args:...
predict
python
PKU-Alignment/omnisafe
omnisafe/models/actor/gaussian_learning_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/gaussian_learning_actor.py
Apache-2.0
def forward(self, obs: torch.Tensor) -> Distribution: """Forward method. Args: obs (torch.Tensor): Observation from environments. Returns: The current distribution. """ self._current_dist = self._distribution(obs) self._after_inference = True ...
Forward method. Args: obs (torch.Tensor): Observation from environments. Returns: The current distribution.
forward
python
PKU-Alignment/omnisafe
omnisafe/models/actor/gaussian_learning_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/gaussian_learning_actor.py
Apache-2.0
def log_prob(self, act: torch.Tensor) -> torch.Tensor: """Compute the log probability of the action given the current distribution. .. warning:: You must call :meth:`forward` or :meth:`predict` before calling this method. Args: act (torch.Tensor): Action from :meth:`pre...
Compute the log probability of the action given the current distribution. .. warning:: You must call :meth:`forward` or :meth:`predict` before calling this method. Args: act (torch.Tensor): Action from :meth:`predict` or :meth:`forward` . Returns: Log proba...
log_prob
python
PKU-Alignment/omnisafe
omnisafe/models/actor/gaussian_learning_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/gaussian_learning_actor.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, hidden_sizes: list[int], activation: Activation = 'relu', weight_initialization_mode: InitFunction = 'kaiming_uniform', ) -> None: """Initialize an instance of :class:`GaussianSACActor`.""...
Initialize an instance of :class:`GaussianSACActor`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/actor/gaussian_sac_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/gaussian_sac_actor.py
Apache-2.0
def _distribution(self, obs: torch.Tensor) -> Normal: """Get the distribution of the actor. .. warning:: This method is not supposed to be called by users. You should call :meth:`forward` instead. **Specifically, this method will clip the standard deviation to a range o...
Get the distribution of the actor. .. warning:: This method is not supposed to be called by users. You should call :meth:`forward` instead. **Specifically, this method will clip the standard deviation to a range of [-20, 2].** Args: obs (torch.Tensor): Obse...
_distribution
python
PKU-Alignment/omnisafe
omnisafe/models/actor/gaussian_sac_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/gaussian_sac_actor.py
Apache-2.0
def log_prob(self, act: torch.Tensor) -> torch.Tensor: # pylint: disable=not-callable r"""Compute the log probability of the action given the current distribution. .. warning:: You must call :meth:`forward` or :meth:`predict` before calling this method. .. note:: ...
Compute the log probability of the action given the current distribution. .. warning:: You must call :meth:`forward` or :meth:`predict` before calling this method. .. note:: In this method, we will regularize the log probability of the action. The regularization is ...
log_prob
python
PKU-Alignment/omnisafe
omnisafe/models/actor/gaussian_sac_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/gaussian_sac_actor.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, hidden_sizes: list[int], activation: Activation = 'relu', output_activation: Activation = 'tanh', weight_initialization_mode: InitFunction = 'kaiming_uniform', ) -> None: """Initia...
Initialize an instance of :class:`MLPActor`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/actor/mlp_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/mlp_actor.py
Apache-2.0
def predict( self, obs: torch.Tensor, deterministic: bool = True, ) -> torch.Tensor: """Predict the action given observation. The predicted action depends on the ``deterministic`` flag. - If ``deterministic`` is ``True``, the predicted action is the mean of the dist...
Predict the action given observation. The predicted action depends on the ``deterministic`` flag. - If ``deterministic`` is ``True``, the predicted action is the mean of the distribution. - If ``deterministic`` is ``False``, the predicted action is sampled from the distribution. Args:...
predict
python
PKU-Alignment/omnisafe
omnisafe/models/actor/mlp_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/mlp_actor.py
Apache-2.0
def __init__( # pylint: disable=too-many-arguments self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, hidden_sizes: List[int], activation: Activation = 'relu', weight_initialization_mode: InitFunction = 'kaiming_uniform', ) -> None: """Initialize an in...
Initialize an instance of :class:`PerturbationActor`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/actor/perturbation_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/perturbation_actor.py
Apache-2.0
def predict(self, obs: torch.Tensor, deterministic: bool = False) -> torch.Tensor: """Predict action from observation. deterministic is not used in this method, it is just for compatibility. Args: obs (torch.Tensor): Observation. deterministic (bool, optional): Whether ...
Predict action from observation. deterministic is not used in this method, it is just for compatibility. Args: obs (torch.Tensor): Observation. deterministic (bool, optional): Whether to return deterministic action. Defaults to False. Returns: torch.Tensor:...
predict
python
PKU-Alignment/omnisafe
omnisafe/models/actor/perturbation_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/perturbation_actor.py
Apache-2.0
def __init__( # pylint: disable=too-many-arguments self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, hidden_sizes: List[int], activation: Activation = 'relu', weight_initialization_mode: InitFunction = 'kaiming_uniform', ) -> None: """Initialize an in...
Initialize an instance of :class:`VAE`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/actor/vae_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/vae_actor.py
Apache-2.0
def encode(self, obs: torch.Tensor, act: torch.Tensor) -> Normal: """Encode observation to latent distribution. Args: obs (torch.Tensor): Observation. act (torch.Tensor): Action from :meth:`predict` or :meth:`forward` . Returns: Normal: Latent distribution. ...
Encode observation to latent distribution. Args: obs (torch.Tensor): Observation. act (torch.Tensor): Action from :meth:`predict` or :meth:`forward` . Returns: Normal: Latent distribution.
encode
python
PKU-Alignment/omnisafe
omnisafe/models/actor/vae_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/vae_actor.py
Apache-2.0
def decode(self, obs: torch.Tensor, latent: Optional[torch.Tensor] = None) -> torch.Tensor: """Decode latent vector to action. When ``latent`` is None, sample latent vector from standard normal distribution. Args: obs (torch.Tensor): Observation. latent (Optional[torch....
Decode latent vector to action. When ``latent`` is None, sample latent vector from standard normal distribution. Args: obs (torch.Tensor): Observation. latent (Optional[torch.Tensor], optional): Latent vector. Defaults to None. Returns: torch.Tensor: Action...
decode
python
PKU-Alignment/omnisafe
omnisafe/models/actor/vae_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/vae_actor.py
Apache-2.0
def loss(self, obs: torch.Tensor, act: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """Compute loss for VAE. Args: obs (torch.Tensor): Observation. act (torch.Tensor): Action from :meth:`predict` or :meth:`forward` . """ dist = self.encode(obs, act) ...
Compute loss for VAE. Args: obs (torch.Tensor): Observation. act (torch.Tensor): Action from :meth:`predict` or :meth:`forward` .
loss
python
PKU-Alignment/omnisafe
omnisafe/models/actor/vae_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/vae_actor.py
Apache-2.0
def predict( # pylint: disable=unused-argument self, obs: torch.Tensor, deterministic: bool = False, ) -> torch.Tensor: """Predict the action given observation. deterministic if not used in VAE model. VAE actor's default behavior is stochastic, sampling from the lat...
Predict the action given observation. deterministic if not used in VAE model. VAE actor's default behavior is stochastic, sampling from the latent standard normal distribution. Args: obs (torch.Tensor): Observation from environments. deterministic (bool, optional): Whet...
predict
python
PKU-Alignment/omnisafe
omnisafe/models/actor/vae_actor.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor/vae_actor.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, model_cfgs: ModelConfig, epochs: int, ) -> None: """Initialize an instance of :class:`ActorCritic`.""" super().__init__() self.actor: Actor = ActorBuilder( obs_space=o...
Initialize an instance of :class:`ActorCritic`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/actor_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/actor_critic.py
Apache-2.0
def step( self, obs: torch.Tensor, deterministic: bool = False, ) -> tuple[torch.Tensor, ...]: """Choose the action based on the observation. used in rollout without gradient. Args: obs (torch.tensor): The observation from environments. deterministic ...
Choose the action based on the observation. used in rollout without gradient. Args: obs (torch.tensor): The observation from environments. deterministic (bool, optional): Whether to use deterministic action. Defaults to False. Returns: action: The deterministic acti...
step
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/actor_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/actor_critic.py
Apache-2.0
def forward( self, obs: torch.Tensor, deterministic: bool = False, ) -> tuple[torch.Tensor, ...]: """Choose the action based on the observation. used in training with gradient. Args: obs (torch.tensor): The observation from environments. deterministic...
Choose the action based on the observation. used in training with gradient. Args: obs (torch.tensor): The observation from environments. deterministic (bool, optional): Whether to use deterministic action. Defaults to False. Returns: action: The deterministic action...
forward
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/actor_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/actor_critic.py
Apache-2.0
def set_annealing(self, epochs: list[int], std: list[float]) -> None: """Set the annealing mode for the actor. Args: epochs (list of int): The list of epochs. std (list of float): The list of standard deviation. """ assert isinstance( self.actor, ...
Set the annealing mode for the actor. Args: epochs (list of int): The list of epochs. std (list of float): The list of standard deviation.
set_annealing
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/actor_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/actor_critic.py
Apache-2.0
def annealing(self, epoch: int) -> None: """Set the annealing mode for the actor. Args: epoch (int): The current epoch. """ assert isinstance( self.actor, GaussianLearningActor, ), 'Only GaussianLearningActor support annealing.' self.a...
Set the annealing mode for the actor. Args: epoch (int): The current epoch.
annealing
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/actor_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/actor_critic.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, model_cfgs: ModelConfig, epochs: int, ) -> None: """Initialize an instance of :class:`ActorQCritic`.""" super().__init__() self.actor: Actor = ActorBuilder( obs_space=...
Initialize an instance of :class:`ActorQCritic`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/actor_q_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/actor_q_critic.py
Apache-2.0
def step(self, obs: torch.Tensor, deterministic: bool = False) -> torch.Tensor: """Choose the action based on the observation. used in rollout without gradient. Args: obs (torch.tensor): The observation from environments. deterministic (bool, optional): Whether to use determinis...
Choose the action based on the observation. used in rollout without gradient. Args: obs (torch.tensor): The observation from environments. deterministic (bool, optional): Whether to use deterministic action. Defaults to False. Returns: The deterministic action if de...
step
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/actor_q_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/actor_q_critic.py
Apache-2.0
def polyak_update(self, tau: float) -> None: """Update the target network with polyak averaging. Args: tau (float): The polyak averaging factor. """ for param, target_param in zip( self.reward_critic.parameters(), self.target_reward_critic.parameters(...
Update the target network with polyak averaging. Args: tau (float): The polyak averaging factor.
polyak_update
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/actor_q_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/actor_q_critic.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, model_cfgs: ModelConfig, epochs: int, ) -> None: """Initialize an instance of :class:`ConstraintActorCritic`.""" super().__init__(obs_space, act_space, model_cfgs, epochs) self.cos...
Initialize an instance of :class:`ConstraintActorCritic`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/constraint_actor_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/constraint_actor_critic.py
Apache-2.0
def step( self, obs: torch.Tensor, deterministic: bool = False, ) -> tuple[torch.Tensor, ...]: """Choose action based on observation. Args: obs (torch.Tensor): Observation from environments. deterministic (bool, optional): Whether to use deterministic...
Choose action based on observation. Args: obs (torch.Tensor): Observation from environments. deterministic (bool, optional): Whether to use deterministic policy. Defaults to False. Returns: action: The deterministic action if ``deterministic`` is True, otherwise the...
step
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/constraint_actor_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/constraint_actor_critic.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, model_cfgs: ModelConfig, epochs: int, ) -> None: """Initialize an instance of :class:`ConstraintActorQCritic`.""" super().__init__(obs_space, act_space, model_cfgs, epochs) self.c...
Initialize an instance of :class:`ConstraintActorQCritic`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/actor_critic/constraint_actor_q_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/actor_critic/constraint_actor_q_critic.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, hidden_sizes: list[int], activation: Activation = 'relu', weight_initialization_mode: InitFunction = 'kaiming_uniform', num_critics: int = 1, use_obs_encoder: bool = False, ) -> No...
Initialize an instance of :class:`CriticBuilder`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/critic/critic_builder.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/critic/critic_builder.py
Apache-2.0
def build_critic( self, critic_type: CriticType, ) -> Critic: """Build critic. Currently, we support two types of critics: ``q`` and ``v``. If you want to add a new critic type, you can simply add it here. Args: critic_type (str): Critic type. R...
Build critic. Currently, we support two types of critics: ``q`` and ``v``. If you want to add a new critic type, you can simply add it here. Args: critic_type (str): Critic type. Returns: An instance of V-Critic or Q-Critic Raises: NotImple...
build_critic
python
PKU-Alignment/omnisafe
omnisafe/models/critic/critic_builder.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/critic/critic_builder.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, hidden_sizes: list[int], activation: Activation = 'relu', weight_initialization_mode: InitFunction = 'kaiming_uniform', num_critics: int = 1, use_obs_encoder: bool = False, ) -> No...
Initialize an instance of :class:`QCritic`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/critic/q_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/critic/q_critic.py
Apache-2.0
def forward( self, obs: torch.Tensor, act: torch.Tensor, ) -> list[torch.Tensor]: """Forward function. As a multi-critic network, the output of the network is a list of Q-values. If you want to use it as a single-critic network, you only need to set the ``num_critics...
Forward function. As a multi-critic network, the output of the network is a list of Q-values. If you want to use it as a single-critic network, you only need to set the ``num_critics`` parameter to 1 when initializing the network, and then use the index 0 to get the Q-value. Args: ...
forward
python
PKU-Alignment/omnisafe
omnisafe/models/critic/q_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/critic/q_critic.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, hidden_sizes: list[int], activation: Activation = 'relu', weight_initialization_mode: InitFunction = 'kaiming_uniform', num_critics: int = 1, ) -> None: """Initialize an instance o...
Initialize an instance of :class:`VCritic`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/critic/v_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/critic/v_critic.py
Apache-2.0
def forward( self, obs: torch.Tensor, ) -> list[torch.Tensor]: """Forward function. Specifically, V function approximator maps observations to V-values. Args: obs (torch.Tensor): Observations from environments. Returns: The V critic value of...
Forward function. Specifically, V function approximator maps observations to V-values. Args: obs (torch.Tensor): Observations from environments. Returns: The V critic value of observation.
forward
python
PKU-Alignment/omnisafe
omnisafe/models/critic/v_critic.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/critic/v_critic.py
Apache-2.0
def __init__( self, obs_space: OmnisafeSpace, act_space: OmnisafeSpace, hidden_sizes: list[int], activation: Activation = 'relu', weight_initialization_mode: InitFunction = 'kaiming_uniform', out_dim: int = 1, ) -> None: """Initialize an instance of :c...
Initialize an instance of :class:`ObsEncoder`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/models/offline/dice.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/offline/dice.py
Apache-2.0
def forward(self, obs: torch.Tensor) -> torch.Tensor: """Forward function. When ``out_dim`` is 1, the output is squeezed to remove the last dimension. Args: obs (torch.Tensor): Observation. """ if self._out_dim == 1: return self.net(obs).squeeze(-1) ...
Forward function. When ``out_dim`` is 1, the output is squeezed to remove the last dimension. Args: obs (torch.Tensor): Observation.
forward
python
PKU-Alignment/omnisafe
omnisafe/models/offline/dice.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/models/offline/dice.py
Apache-2.0
def train( # pylint: disable=too-many-arguments algo: str = typer.Option( 'PPOLag', help=f"algorithm to train {omnisafe.ALGORITHMS['all']}", case_sensitive=False, ), env_id: str = typer.Option( 'SafetyHumanoidVelocity-v1', help='the name of test environment', ...
Train a single policy in OmniSafe via command line. Examples: .. code-block:: bash python -m omnisafe train --algo PPOLag --env_id SafetyPointGoal1-v0 --parallel 1 \ --total_steps 1000000 --device cpu --vector_env_nums 1 Args: algo (str): Algorithm to train. ...
train
python
PKU-Alignment/omnisafe
omnisafe/utils/command_app.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/command_app.py
Apache-2.0
def benchmark( exp_name: str = typer.Argument( ..., help='experiment name', ), num_pool: int = typer.Argument( ..., help='number of paralleled experiments.', ), config_path: str = typer.Argument( ..., help='path to config file, it is supposed to be yam...
Benchmark algorithms configured by .yaml file in OmniSafe via command line. Examples: .. code-block:: bash python -m omnisafe benchmark --exp_name exp-1 --num_pool 1 \ --config_path ./configs/on-policy/PPOLag.yaml --log_dir ./runs Args: exp_name: experiment name ...
benchmark
python
PKU-Alignment/omnisafe
omnisafe/utils/command_app.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/command_app.py
Apache-2.0
def evaluate_model( result_dir: str = typer.Argument( ..., help='directory of experiment results to evaluate, e.g. ./runs/PPO-{SafetyPointGoal1-v0}', ), num_episode: int = typer.Option( 10, help='number of episodes to render', ), render: bool = typer.Option( T...
Evaluate a policy which trained by OmniSafe via command line. Examples: .. code-block:: bash python -m omnisafe eval --result_dir ./runs/PPOLag-{SafetyPointGoal1-v0} --num_episode 10 \ --render True --render_mode rgb_array --camera_name track --width 256 --height 256 Args:...
evaluate_model
python
PKU-Alignment/omnisafe
omnisafe/utils/command_app.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/command_app.py
Apache-2.0
def train_config( config_path: str = typer.Argument( ..., help='path to config file, it is supposed to be yaml file, e.g. ./configs/ppo.yaml', ), log_dir: str = typer.Option( os.path.abspath('.'), help='directory to save logs, default is current directory', ), plot: b...
Train a policy configured by .yaml file in OmniSafe via command line. Examples: .. code-block:: bash python -m omnisafe train_config --config_path ./configs/on-policy/PPOLag.yaml \ --log_dir ./runs Args: config_path (str): path to config file, it is supposed to be ...
train_config
python
PKU-Alignment/omnisafe
omnisafe/utils/command_app.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/command_app.py
Apache-2.0
def __init__(self, **kwargs: Any) -> None: """Initialize an instance of :class:`Config`.""" for key, value in kwargs.items(): if isinstance(value, dict): self[key] = Config.dict2config(value) else: self[key] = value
Initialize an instance of :class:`Config`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/utils/config.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/config.py
Apache-2.0
def todict(self) -> dict[str, Any]: """Convert Config to dictionary. Returns: The dictionary of Config. """ config_dict: dict[str, Any] = {} for key, value in self.items(): if isinstance(value, Config): config_dict[key] = value.todict() ...
Convert Config to dictionary. Returns: The dictionary of Config.
todict
python
PKU-Alignment/omnisafe
omnisafe/utils/config.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/config.py
Apache-2.0
def dict2config(config_dict: dict[str, Any]) -> Config: """Convert dictionary to Config. Args: config_dict (dict[str, Any]): The dictionary to be converted. Returns: The algorithm config. """ config = Config() for key, value in config_dict.items(...
Convert dictionary to Config. Args: config_dict (dict[str, Any]): The dictionary to be converted. Returns: The algorithm config.
dict2config
python
PKU-Alignment/omnisafe
omnisafe/utils/config.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/config.py
Apache-2.0
def recurisve_update(self, update_args: dict[str, Any]) -> None: """Recursively update args. Args: update_args (dict[str, Any]): Args to be updated. """ for key, value in self.items(): if key in update_args: if isinstance(update_args[key], dict): ...
Recursively update args. Args: update_args (dict[str, Any]): Args to be updated.
recurisve_update
python
PKU-Alignment/omnisafe
omnisafe/utils/config.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/config.py
Apache-2.0
def get_default_kwargs_yaml(algo: str, env_id: str, algo_type: str) -> Config: """Get the default kwargs from ``yaml`` file. .. note:: This function search the ``yaml`` file by the algorithm name and environment name. Make sure your new implemented algorithm or environment has the same name as ...
Get the default kwargs from ``yaml`` file. .. note:: This function search the ``yaml`` file by the algorithm name and environment name. Make sure your new implemented algorithm or environment has the same name as the yaml file. Args: algo (str): The algorithm name. env_id (str)...
get_default_kwargs_yaml
python
PKU-Alignment/omnisafe
omnisafe/utils/config.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/config.py
Apache-2.0
def check_all_configs(configs: Config, algo_type: str) -> None: """Check all configs. This function is used to check the configs. Args: configs (Config): The configs to be checked. algo_type (str): The algorithm type. """ __check_algo_configs(configs.algo_cfgs, algo_type) __che...
Check all configs. This function is used to check the configs. Args: configs (Config): The configs to be checked. algo_type (str): The algorithm type.
check_all_configs
python
PKU-Alignment/omnisafe
omnisafe/utils/config.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/config.py
Apache-2.0
def __check_parallel_and_vectorized(configs: Config, algo_type: str) -> None: """Check parallel and vectorized configs. This function is used to check the parallel and vectorized configs. Args: configs (Config): The configs to be checked. algo_type (str): The algorithm type. """ if...
Check parallel and vectorized configs. This function is used to check the parallel and vectorized configs. Args: configs (Config): The configs to be checked. algo_type (str): The algorithm type.
__check_parallel_and_vectorized
python
PKU-Alignment/omnisafe
omnisafe/utils/config.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/config.py
Apache-2.0
def __check_algo_configs(configs: Config, algo_type: str) -> None: """Check algorithm configs. This function is used to check the algorithm configs. .. note:: - ``update_iters`` must be greater than 0 and must be int. - ``steps_per_epoch`` must be greater than 0 and must be int. - ...
Check algorithm configs. This function is used to check the algorithm configs. .. note:: - ``update_iters`` must be greater than 0 and must be int. - ``steps_per_epoch`` must be greater than 0 and must be int. - ``batch_size`` must be greater than 0 and must be int. - ``target_...
__check_algo_configs
python
PKU-Alignment/omnisafe
omnisafe/utils/config.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/config.py
Apache-2.0
def __check_logger_configs(configs: Config) -> None: """Check logger configs. Args: configs (Config): The configs to be checked. algo_type (str): The algorithm type. """ assert isinstance(configs.use_wandb, bool) and isinstance( configs.wandb_project, str, ), 'use_wa...
Check logger configs. Args: configs (Config): The configs to be checked. algo_type (str): The algorithm type.
__check_logger_configs
python
PKU-Alignment/omnisafe
omnisafe/utils/config.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/config.py
Apache-2.0
def setup_distributed() -> None: """Setup the distributed training environment. Avoid slowdowns caused by each separate process's PyTorch, using more than its fair share of CPU resources. """ old_num_threads = torch.get_num_threads() # decrease number of torch threads for MPI if old_num_thr...
Setup the distributed training environment. Avoid slowdowns caused by each separate process's PyTorch, using more than its fair share of CPU resources.
setup_distributed
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def get_rank() -> int: """Get the rank of calling process. Examples: >>> # In process 0 >>> get_rank() 0 Returns: The rank of calling process. """ if os.getenv('MASTER_ADDR') is None: return 0 return dist.get_rank()
Get the rank of calling process. Examples: >>> # In process 0 >>> get_rank() 0 Returns: The rank of calling process.
get_rank
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def world_size() -> int: """Count active MPI processes. Returns: The number of active MPI processes. """ if os.getenv('MASTER_ADDR') is None: return 1 return dist.get_world_size()
Count active MPI processes. Returns: The number of active MPI processes.
world_size
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def fork( parallel: int, device: str = 'cpu', manual_args: list[str] | None = None, ) -> bool: """The entrance method of multi-processing. Re-launches the current script with workers linked by MPI. Also, terminates the original process that launched it. Taken almost without modification from th...
The entrance method of multi-processing. Re-launches the current script with workers linked by MPI. Also, terminates the original process that launched it. Taken almost without modification from the Baselines function of the `same name <https://github.com/openai/baselines/blob/master/baselines/common/mpi_f...
fork
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def avg_tensor(value: torch.Tensor) -> None: """Average a torch tensor over MPI processes. Since torch and numpy share same memory space, tensors of dim > 0 can be be manipulated through call by reference, scalars must be assigned. Examples: >>> # In process 0 >>> x = torch.tensor(1.0)...
Average a torch tensor over MPI processes. Since torch and numpy share same memory space, tensors of dim > 0 can be be manipulated through call by reference, scalars must be assigned. Examples: >>> # In process 0 >>> x = torch.tensor(1.0) >>> # In process 1 >>> x = torch.te...
avg_tensor
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def avg_grads(module: torch.nn.Module) -> None: """Average contents of gradient buffers across MPI processes. .. note:: This function only works when the training is multi-processing. Examples: >>> # In process 0 >>> x = torch.tensor(1.0, requires_grad=True) >>> y = x ** 2 ...
Average contents of gradient buffers across MPI processes. .. note:: This function only works when the training is multi-processing. Examples: >>> # In process 0 >>> x = torch.tensor(1.0, requires_grad=True) >>> y = x ** 2 >>> y.backward() >>> x.grad ten...
avg_grads
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def sync_params(module: torch.nn.Module) -> None: """Sync all parameters of module across all MPI processes. .. note:: This function only works when the training is multi-processing. Examples: >>> # In process 0 >>> model = torch.nn.Linear(1, 1) >>> model.weight.data = torc...
Sync all parameters of module across all MPI processes. .. note:: This function only works when the training is multi-processing. Examples: >>> # In process 0 >>> model = torch.nn.Linear(1, 1) >>> model.weight.data = torch.tensor([[1.]]) >>> model.weight.data te...
sync_params
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def avg_params(module: torch.nn.Module) -> None: """Average contents of all parameters across MPI processes. Examples: >>> # In process 0 >>> model = torch.nn.Linear(1, 1) >>> model.weight.data = torch.tensor([[1.]]) >>> model.weight.data tensor([[1.]]) >>> # In ...
Average contents of all parameters across MPI processes. Examples: >>> # In process 0 >>> model = torch.nn.Linear(1, 1) >>> model.weight.data = torch.tensor([[1.]]) >>> model.weight.data tensor([[1.]]) >>> # In process 1 >>> model = torch.nn.Linear(1, 1) ...
avg_params
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def dist_op(value: np.ndarray | torch.Tensor | float, operation: Any) -> torch.Tensor: """Multi-processing operation. .. note:: The operation can be ``ReduceOp.SUM``, ``ReduceOp.MAX``, ``ReduceOp.MIN``. corresponding to :meth:`dist_sum`, :meth:`dist_max`, :meth:`dist_min`, respectively. Ar...
Multi-processing operation. .. note:: The operation can be ``ReduceOp.SUM``, ``ReduceOp.MAX``, ``ReduceOp.MIN``. corresponding to :meth:`dist_sum`, :meth:`dist_max`, :meth:`dist_min`, respectively. Args: value (np.ndarray, torch.Tensor, int, or float): The value to be operated. ...
dist_op
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def dist_statistics_scalar( value: torch.Tensor, with_min_and_max: bool = False, ) -> tuple[torch.Tensor, ...]: r"""Get mean/std and optional min/max of scalar x across MPI processes. Examples: >>> # In process 0 >>> x = torch.tensor(1.0) >>> # In process 1 >>> x = torch...
Get mean/std and optional min/max of scalar x across MPI processes. Examples: >>> # In process 0 >>> x = torch.tensor(1.0) >>> # In process 1 >>> x = torch.tensor(2.0) >>> dist_statistics_scalar(x) (tensor(1.5), tensor(0.5)) Args: value (torch.Tensor): V...
dist_statistics_scalar
python
PKU-Alignment/omnisafe
omnisafe/utils/distributed.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/distributed.py
Apache-2.0
def valid_str(vals: list[Any] | str) -> str: """Convert a value or values to a string which could go in a path of file. Partly based on `this gist`_. .. _`this gist`: https://gist.github.com/seanh/93666 Args: vals (list[Any] or str): Values to convert. Returns: Converted string. ...
Convert a value or values to a string which could go in a path of file. Partly based on `this gist`_. .. _`this gist`: https://gist.github.com/seanh/93666 Args: vals (list[Any] or str): Values to convert. Returns: Converted string.
valid_str
python
PKU-Alignment/omnisafe
omnisafe/utils/exp_grid_tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/exp_grid_tools.py
Apache-2.0
def train( exp_id: str, algo: str, env_id: str, custom_cfgs: dict[str, Any], ) -> Tuple[float, float, float]: """Train a policy from exp-x config with OmniSafe. Args: exp_id (str): Experiment ID. algo (str): Algorithm to train. env_id (str): The name of test environment....
Train a policy from exp-x config with OmniSafe. Args: exp_id (str): Experiment ID. algo (str): Algorithm to train. env_id (str): The name of test environment. custom_cfgs (Config): Custom configurations.
train
python
PKU-Alignment/omnisafe
omnisafe/utils/exp_grid_tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/exp_grid_tools.py
Apache-2.0
def make_isaac_gym_env( env_id: str, num_envs: int, device: torch.device = DEVICE_CPU, ) -> GymnasiumIsaacEnv: """Creates and initializes an Isaac Gym environment with specified configurations. Args: env_id (str): Identifier for the specific environment to be instantiated. num_envs ...
Creates and initializes an Isaac Gym environment with specified configurations. Args: env_id (str): Identifier for the specific environment to be instantiated. num_envs (int): The number of parallel environments to create. device (torch.device, optional): The computational device ('cpu' or ...
make_isaac_gym_env
python
PKU-Alignment/omnisafe
omnisafe/utils/isaac_gym_utils.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/isaac_gym_utils.py
Apache-2.0
def discount_cumsum(vector_x: torch.Tensor, discount: float) -> torch.Tensor: """Compute the discounted cumulative sum of vectors. Examples: >>> vector_x = torch.arange(1, 5) >>> vector_x tensor([1, 2, 3, 4]) >>> discount_cumsum(vector_x, 0.9) tensor([8.15, 5.23, 2.80, 1...
Compute the discounted cumulative sum of vectors. Examples: >>> vector_x = torch.arange(1, 5) >>> vector_x tensor([1, 2, 3, 4]) >>> discount_cumsum(vector_x, 0.9) tensor([8.15, 5.23, 2.80, 1.00]) Args: vector_x (torch.Tensor): A sequence of shape (B, T). ...
discount_cumsum
python
PKU-Alignment/omnisafe
omnisafe/utils/math.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/math.py
Apache-2.0
def conjugate_gradients( fisher_product: Callable[[torch.Tensor], torch.Tensor], vector_b: torch.Tensor, num_steps: int = 10, residual_tol: float = 1e-10, eps: float = 1e-6, ) -> torch.Tensor: """Implementation of Conjugate gradient algorithm. Conjugate gradient algorithm is used to solve t...
Implementation of Conjugate gradient algorithm. Conjugate gradient algorithm is used to solve the linear system of equations :math:`A x = b`. The algorithm is described in detail in the paper `Conjugate Gradient Method`_. .. _Conjugate Gradient Method: https://en.wikipedia.org/wiki/Conjugate_gradient_meth...
conjugate_gradients
python
PKU-Alignment/omnisafe
omnisafe/utils/math.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/math.py
Apache-2.0
def __init__(self, loc: torch.Tensor, scale: torch.Tensor) -> None: """Initialize an instance of :class:`TanhNormal`.""" base_dist = Normal(loc, scale) super().__init__(base_dist, SafeTanhTransformer()) self.arg_constraints = { 'loc': constraints.real, 'scale': co...
Initialize an instance of :class:`TanhNormal`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/utils/math.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/math.py
Apache-2.0
def initialize_layer(init_function: InitFunction, layer: nn.Linear) -> None: """Initialize the layer with the given initialization function. The ``init_function`` can be chosen from: ``kaiming_uniform``, ``xavier_normal``, ``glorot``, ``xavier_uniform``, ``orthogonal``. Args: init_function (In...
Initialize the layer with the given initialization function. The ``init_function`` can be chosen from: ``kaiming_uniform``, ``xavier_normal``, ``glorot``, ``xavier_uniform``, ``orthogonal``. Args: init_function (InitFunction): The initialization function. layer (nn.Linear): The layer to be...
initialize_layer
python
PKU-Alignment/omnisafe
omnisafe/utils/model.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/model.py
Apache-2.0
def get_activation( activation: Activation, ) -> type[nn.Identity | nn.ReLU | nn.Sigmoid | nn.Softplus | nn.Tanh]: """Get the activation function. The ``activation`` can be chosen from: ``identity``, ``relu``, ``sigmoid``, ``softplus``, ``tanh``. Args: activation (Activation): The activati...
Get the activation function. The ``activation`` can be chosen from: ``identity``, ``relu``, ``sigmoid``, ``softplus``, ``tanh``. Args: activation (Activation): The activation function. Returns: The activation function, ranging from ``nn.Identity``, ``nn.ReLU``, ``nn.Sigmoid``, ...
get_activation
python
PKU-Alignment/omnisafe
omnisafe/utils/model.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/model.py
Apache-2.0
def build_mlp_network( sizes: list[int], activation: Activation, output_activation: Activation = 'identity', weight_initialization_mode: InitFunction = 'kaiming_uniform', ) -> nn.Module: """Build the MLP network. Examples: >>> build_mlp_network([64, 64, 64], 'relu', 'tanh') Sequ...
Build the MLP network. Examples: >>> build_mlp_network([64, 64, 64], 'relu', 'tanh') Sequential( (0): Linear(in_features=64, out_features=64, bias=True) (1): ReLU() (2): Linear(in_features=64, out_features=64, bias=True) (3): ReLU() (4): L...
build_mlp_network
python
PKU-Alignment/omnisafe
omnisafe/utils/model.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/model.py
Apache-2.0
def __init__(self) -> None: """Initialize an instance of :class:`Plotter`.""" self.div_line_width: int = 50 self.exp_idx: int = 0 self.units: dict[str, Any] = {}
Initialize an instance of :class:`Plotter`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/utils/plotter.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/plotter.py
Apache-2.0
def plot_data( self, sub_figures: np.ndarray, data: list[DataFrame], xaxis: str = 'Steps', value: str = 'Rewards', condition: str = 'Condition1', smooth: int = 1, **kwargs: Any, ) -> None: """Plot data from a pandas dataframe. .. note:...
Plot data from a pandas dataframe. .. note:: The ``smooth`` means smoothing the data with moving window average. Example: >>> smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k]) where the "smooth" param is width of that window (2k+1) Args: ...
plot_data
python
PKU-Alignment/omnisafe
omnisafe/utils/plotter.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/plotter.py
Apache-2.0
def get_datasets(self, logdir: str, condition: str | None = None) -> list[DataFrame]: """Recursively look through logdir for files named "progress.txt". Assumes that any file "progress.txt" is a valid hit. Args: logdir (str): The directory to search for progress.txt files ...
Recursively look through logdir for files named "progress.txt". Assumes that any file "progress.txt" is a valid hit. Args: logdir (str): The directory to search for progress.txt files condition (str or None, optional): The condition label. Defaults to None. Returns: ...
get_datasets
python
PKU-Alignment/omnisafe
omnisafe/utils/plotter.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/plotter.py
Apache-2.0
def get_all_datasets( self, all_logdirs: list[str], legend: list[str] | None = None, select: str | None = None, exclude: str | None = None, ) -> list[DataFrame]: """Get all the data from all the log directories. For every entry in all_logdirs. 1) ...
Get all the data from all the log directories. For every entry in all_logdirs. 1) check if the entry is a real directory and if it is, pull data from it; 2) if not, check to see if the entry is a prefix for a real directory, and pull data from that. Args: all_logdir...
get_all_datasets
python
PKU-Alignment/omnisafe
omnisafe/utils/plotter.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/plotter.py
Apache-2.0
def __init__( self, endpoints: list[tuple[int, float]], outside_value: float, ) -> None: """Initialize an instance of :class:`PiecewiseSchedule`.""" idxes = [e[0] for e in endpoints] assert idxes == sorted(idxes) self._interpolation: Callable[[float, float, fl...
Initialize an instance of :class:`PiecewiseSchedule`.
__init__
python
PKU-Alignment/omnisafe
omnisafe/utils/schedule.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/schedule.py
Apache-2.0
def value(self, time: float) -> float: """Value at time t. Args: time (int or float): Current time step. Returns: The interpolation value at time t or outside_value if t is before the first time in endpoints of after the last one. Raises: ...
Value at time t. Args: time (int or float): Current time step. Returns: The interpolation value at time t or outside_value if t is before the first time in endpoints of after the last one. Raises: AssertionError: If the time is not in the endpoi...
value
python
PKU-Alignment/omnisafe
omnisafe/utils/schedule.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/schedule.py
Apache-2.0
def get_flat_params_from(model: torch.nn.Module) -> torch.Tensor: """This function is used to get the flattened parameters from the model. .. note:: Some algorithms need to get the flattened parameters from the model, such as the :class:`TRPO` and :class:`CPO` algorithm. In these algorithms, th...
This function is used to get the flattened parameters from the model. .. note:: Some algorithms need to get the flattened parameters from the model, such as the :class:`TRPO` and :class:`CPO` algorithm. In these algorithms, the parameters are flattened and then used to calculate the loss. ...
get_flat_params_from
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def get_flat_gradients_from(model: torch.nn.Module) -> torch.Tensor: """This function is used to get the flattened gradients from the model. .. note:: Some algorithms need to get the flattened gradients from the model, such as the :class:`TRPO` and :class:`CPO` algorithm. In these algorithms, t...
This function is used to get the flattened gradients from the model. .. note:: Some algorithms need to get the flattened gradients from the model, such as the :class:`TRPO` and :class:`CPO` algorithm. In these algorithms, the gradients are flattened and then used to calculate the loss. ...
get_flat_gradients_from
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def set_param_values_to_model(model: torch.nn.Module, vals: torch.Tensor) -> None: """This function is used to set the parameters to the model. .. note:: Some algorithms (e.g. TRPO, CPO, etc.) need to set the parameters to the model, instead of using the ``optimizer.step()``. Examples: ...
This function is used to set the parameters to the model. .. note:: Some algorithms (e.g. TRPO, CPO, etc.) need to set the parameters to the model, instead of using the ``optimizer.step()``. Examples: >>> model = torch.nn.Linear(2, 2) >>> model.weight.data = torch.tensor([[1.0,...
set_param_values_to_model
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def seed_all(seed: int) -> None: """This function is used to set the random seed for all the packages. .. hint:: To reproduce the results, you need to set the random seed for all the packages. Including ``numpy``, ``random``, ``torch``, ``torch.cuda``, ``torch.backends.cudnn``. .. warning:...
This function is used to set the random seed for all the packages. .. hint:: To reproduce the results, you need to set the random seed for all the packages. Including ``numpy``, ``random``, ``torch``, ``torch.cuda``, ``torch.backends.cudnn``. .. warning:: If you want to use the ``torch...
seed_all
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def custom_cfgs_to_dict(key_list: 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_cfgs:use_wandb`` and `...
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': {'use_wandb': ...
custom_cfgs_to_dict
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def update_dict(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. Examples: >>> total_dict = {'a': {'b': 1, 'c': 2}} ...
Updater of multi-level dictionary. Args: total_dict (dict[str, Any]): The total dictionary. item_dict (dict[str, Any]): The item dictionary. Examples: >>> total_dict = {'a': {'b': 1, 'c': 2}} >>> item_dict = {'a': {'b': 3, 'd': 4}} >>> update_dict(total_dict, item_dict)...
update_dict
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def load_yaml(path: str) -> dict[str, Any]: """Get the default kwargs from ``yaml`` file. .. note:: This function search the ``yaml`` file by the algorithm name and environment name. Make sure your new implemented algorithm or environment has the same name as the yaml file. Args: p...
Get the default kwargs from ``yaml`` file. .. note:: This function search the ``yaml`` file by the algorithm name and environment name. Make sure your new implemented algorithm or environment has the same name as the yaml file. Args: path (str): The path of the ``yaml`` file. Retu...
load_yaml
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def recursive_check_config( config: dict[str, Any], default_config: dict[str, Any], exclude_keys: tuple[str, ...] = (), ) -> None: """Check whether config is valid in default_config. Args: config (dict[str, Any]): The config to be checked. default_config (dict[str, Any]): The defaul...
Check whether config is valid in default_config. Args: config (dict[str, Any]): The config to be checked. default_config (dict[str, Any]): The default config. exclude_keys (tuple of str, optional): The keys to be excluded. Defaults to (). Raises: AssertionError: If the type of ...
recursive_check_config
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def assert_with_exit(condition: bool, msg: str) -> None: """Assert with message. Examples: >>> assert_with_exit(1 == 2, '1 must equal to 2') AssertionError: 1 must equal to 2 Args: condition (bool): condition to be checked. msg (str): message to be printed. Raises: ...
Assert with message. Examples: >>> assert_with_exit(1 == 2, '1 must equal to 2') AssertionError: 1 must equal to 2 Args: condition (bool): condition to be checked. msg (str): message to be printed. Raises: AssertionError: If the condition is not satisfied.
assert_with_exit
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def recursive_dict2json(dict_obj: dict[str, Any]) -> str: """This function is used to recursively convert the dict to json. Args: dict_obj (dict[str, Any]): dict to be converted. Returns: The converted json string. Raises: AssertionError: If the instance of the input is not ``...
This function is used to recursively convert the dict to json. Args: dict_obj (dict[str, Any]): dict to be converted. Returns: The converted json string. Raises: AssertionError: If the instance of the input is not ``dict``.
recursive_dict2json
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def hash_string(string: str) -> str: """This function is used to generate the folder name. Args: string (str): string to be hashed. Returns: The hashed string. """ salt = b'\xf8\x99/\xe4\xe6J\xd8d\x1a\x9b\x8b\x98\xa2\x1d\xff3*^\\\xb1\xc1:e\x11M=PW\x03\xa5\\h' # convert string t...
This function is used to generate the folder name. Args: string (str): string to be hashed. Returns: The hashed string.
hash_string
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def get_device(device: torch.device | str | int = DEVICE_CPU) -> torch.device: """Retrieve PyTorch device. It checks that the requested device is available first. For now, it supports only cpu and cuda. By default, it tries to use the gpu. Args: device (torch.device, str, or int, optional): Th...
Retrieve PyTorch device. It checks that the requested device is available first. For now, it supports only cpu and cuda. By default, it tries to use the gpu. Args: device (torch.device, str, or int, optional): The device to use. Defaults to ``torch.device('cpu')``. Returns: ...
get_device
python
PKU-Alignment/omnisafe
omnisafe/utils/tools.py
https://github.com/PKU-Alignment/omnisafe/blob/master/omnisafe/utils/tools.py
Apache-2.0
def get_answer(gamma: float): """Input gamma and return the answer.""" if gamma == 0.9: return torch.tensor([11.4265, 11.5850, 10.6500, 8.5000, 5.0000], dtype=torch.float64) if gamma == 0.99: return torch.tensor([14.6045, 13.7419, 11.8605, 8.9500, 5.0000], dtype=torch.float64) if gamma =...
Input gamma and return the answer.
get_answer
python
PKU-Alignment/omnisafe
tests/test_utils.py
https://github.com/PKU-Alignment/omnisafe/blob/master/tests/test_utils.py
Apache-2.0
def make_mo(self, po_filename, mo_filename): """Create a machine object (.mo) from a portable object (.po) file.""" try: call(['msgfmt', po_filename, '-o', mo_filename]) except OSError as e: # ignore failures since i18n support is optional: logging.warning(e)
Create a machine object (.mo) from a portable object (.po) file.
make_mo
python
coldfix/udiskie
setup.py
https://github.com/coldfix/udiskie/blob/master/setup.py
MIT
def pack(*values): """Unpack a return tuple to a yield expression return value.""" # Schizophrenic returns from asyncs. Inspired by # gi.overrides.Gio.DBusProxy. if len(values) == 0: return None elif len(values) == 1: return values[0] else: return values
Unpack a return tuple to a yield expression return value.
pack
python
coldfix/udiskie
udiskie/async_.py
https://github.com/coldfix/udiskie/blob/master/udiskie/async_.py
MIT
def call_func(fn, *args): """ Call the function with the specified arguments but return None. This rather boring helper function is used by run_soon to make sure the function is executed only once. """ # NOTE: Apparently, idle_add does not re-execute its argument if an # exception is raised...
Call the function with the specified arguments but return None. This rather boring helper function is used by run_soon to make sure the function is executed only once.
call_func
python
coldfix/udiskie
udiskie/async_.py
https://github.com/coldfix/udiskie/blob/master/udiskie/async_.py
MIT
def __init__(self, generator): """Create and start a ``Task`` from the specified generator.""" self._generator = generator run_soon(self._resume, next, self._generator)
Create and start a ``Task`` from the specified generator.
__init__
python
coldfix/udiskie
udiskie/async_.py
https://github.com/coldfix/udiskie/blob/master/udiskie/async_.py
MIT
def _resume(self, func, *args): """Resume the coroutine by throwing a value or returning a value from the ``await`` and handle further awaits.""" try: value = func(*args) except StopIteration as e: self._generator.close() self.set_result(e.value) ...
Resume the coroutine by throwing a value or returning a value from the ``await`` and handle further awaits.
_resume
python
coldfix/udiskie
udiskie/async_.py
https://github.com/coldfix/udiskie/blob/master/udiskie/async_.py
MIT
async def exec_subprocess(argv, capture=True): """ An Future task that represents a subprocess. If successful, the task's result is set to the collected STDOUT of the subprocess. :raises subprocess.CalledProcessError: if the subprocess returns a non-zero exit ...
An Future task that represents a subprocess. If successful, the task's result is set to the collected STDOUT of the subprocess. :raises subprocess.CalledProcessError: if the subprocess returns a non-zero exit code
exec_subprocess
python
coldfix/udiskie
udiskie/async_.py
https://github.com/coldfix/udiskie/blob/master/udiskie/async_.py
MIT
def _check(self, args): """Exit in case of multiple exclusive arguments.""" if sum(bool(args[arg]) for arg in self._mapping) > 1: raise DocoptExit(_('These options are mutually exclusive: {0}', ', '.join(self._mapping)))
Exit in case of multiple exclusive arguments.
_check
python
coldfix/udiskie
udiskie/cli.py
https://github.com/coldfix/udiskie/blob/master/udiskie/cli.py
MIT
def __call__(self, args): """Get the option value from the parsed arguments.""" self._check(args) for arg, val in self._mapping.items(): if args[arg] not in (None, False): return val
Get the option value from the parsed arguments.
__call__
python
coldfix/udiskie
udiskie/cli.py
https://github.com/coldfix/udiskie/blob/master/udiskie/cli.py
MIT
def __init__(self, argv=None): """Parse command line options, read config and initialize members.""" # parse program options (retrieve log level and config file name): args = docopt(self.usage, version='udiskie ' + self.version) default_opts = self.option_defaults program_opts = ...
Parse command line options, read config and initialize members.
__init__
python
coldfix/udiskie
udiskie/cli.py
https://github.com/coldfix/udiskie/blob/master/udiskie/cli.py
MIT
def program_options(self, args): """Get program options from docopt parsed options.""" options = {} for name, rule in self.option_rules.items(): val = rule(args) if val is not None: options[name] = val return options
Get program options from docopt parsed options.
program_options
python
coldfix/udiskie
udiskie/cli.py
https://github.com/coldfix/udiskie/blob/master/udiskie/cli.py
MIT
def run(self): """Run the main loop. Returns exit code.""" self.exit_code = 1 self.mainloop = GLib.MainLoop() try: future = ensure_future(self._start_async_tasks()) future.callbacks.append(self.set_exit_code) self.mainloop.run() return self...
Run the main loop. Returns exit code.
run
python
coldfix/udiskie
udiskie/cli.py
https://github.com/coldfix/udiskie/blob/master/udiskie/cli.py
MIT
def __init__(self, event_names=(), *args, **kwargs): """Initialize with empty lists of event handlers.""" super().__init__(*args, **kwargs) self._event_handlers = {} for evt in event_names: self._event_handlers[evt] = []
Initialize with empty lists of event handlers.
__init__
python
coldfix/udiskie
udiskie/common.py
https://github.com/coldfix/udiskie/blob/master/udiskie/common.py
MIT
def samefile(a: str, b: str) -> bool: """Check if two paths represent the same file.""" try: return os.path.samefile(a, b) except OSError: return os.path.normpath(a) == os.path.normpath(b)
Check if two paths represent the same file.
samefile
python
coldfix/udiskie
udiskie/common.py
https://github.com/coldfix/udiskie/blob/master/udiskie/common.py
MIT
def extend(a: dict, b: dict) -> dict: """Merge two dicts and return a new dict. Much like subclassing works.""" res = a.copy() res.update(b) return res
Merge two dicts and return a new dict. Much like subclassing works.
extend
python
coldfix/udiskie
udiskie/common.py
https://github.com/coldfix/udiskie/blob/master/udiskie/common.py
MIT
def decode_ay(ay): """Convert binary blob from DBus queries to strings.""" if ay is None: return '' elif isinstance(ay, str): return ay elif isinstance(ay, bytes): return ay.decode('utf-8') else: # dbus.Array([dbus.Byte]) or any similar sequence type: return b...
Convert binary blob from DBus queries to strings.
decode_ay
python
coldfix/udiskie
udiskie/common.py
https://github.com/coldfix/udiskie/blob/master/udiskie/common.py
MIT