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 reward_track_body_position_extended( self, body_state: BodyState, ref_motion_state: ReferenceMotionState, **kwargs, ) -> torch.Tensor: """ Computes a reward based on the difference between the body's extended position and the reference motion's extended po...
Computes a reward based on the difference between the body's extended position and the reference motion's extended position. This function is rewritten from _reward_teleop_body_position_extend of legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) represe...
reward_track_body_position_extended
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def reward_track_body_position_vr_key_points( self, body_state: BodyState, ref_motion_state: ReferenceMotionState, **kwargs, ) -> torch.Tensor: """ Computes a reward based on the difference between selected key points of the body's extended position and the re...
Computes a reward based on the difference between selected key points of the body's extended position and the reference motion's extended position. This function is rewritten from _reward_teleop_body_position_vr_3keypoints of legged_gym. Returns: torch.Tensor: A float tens...
reward_track_body_position_vr_key_points
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def reward_track_body_rotation( self, body_state: BodyState, ref_motion_state: ReferenceMotionState, **kwargs, ) -> torch.Tensor: """ Computes a reward based on the difference between the body's rotation and the reference motion's rotation. This function is r...
Computes a reward based on the difference between the body's rotation and the reference motion's rotation. This function is rewritten from _reward_teleop_body_rotation of legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed reward for eac...
reward_track_body_rotation
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_torques( self, articulation_data: ArticulationData, **kwargs, ) -> torch.Tensor: """ Computes the penalty on applied torques to minimize energy consumption. This function is adapted from _reward_torques in legged_gym. Returns: torch....
Computes the penalty on applied torques to minimize energy consumption. This function is adapted from _reward_torques in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_torques
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_joint_accelerations( self, articulation_data: ArticulationData, **kwargs, ) -> torch.Tensor: """ Computes the penalty on joint acceleration of each motor. This function is adapted from _reward_dof_acc in legged_gym. Returns: torch.Te...
Computes the penalty on joint acceleration of each motor. This function is adapted from _reward_dof_acc in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_joint_accelerations
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_joint_velocities( self, articulation_data: ArticulationData, **kwargs, ) -> torch.Tensor: """ Computes the penalty on joint velocity of each motor. This function is adapted from _reward_dof_vel in legged_gym. Returns: torch.Tensor: A...
Computes the penalty on joint velocity of each motor. This function is adapted from _reward_dof_vel in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_joint_velocities
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_lower_body_action_changes( self, previous_actions: torch.Tensor, actions: torch.Tensor, **kwargs, ) -> torch.Tensor: """ Computes the penalty for action changes in the lower body. This function is adapted from _reward_lower_action_rate in legged_...
Computes the penalty for action changes in the lower body. This function is adapted from _reward_lower_action_rate in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_lower_body_action_changes
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_upper_body_action_changes( self, previous_actions: torch.Tensor, actions: torch.Tensor, **kwargs, ) -> torch.Tensor: """ Computes the penalty for action changes in the upper body. This function is adapted from _reward_upper_action_rate in legged_...
Computes the penalty for action changes in the upper body. This function is adapted from _reward_upper_action_rate in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_upper_body_action_changes
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_early_termination(self, reset_buf: torch.Tensor, timeout_buf: torch.Tensor, **kwargs): """ Computes the penalty for episodes that terminate before timeout. This function is adapted from `_reward_termination` in `legged_gym`. Returns: torch.Tensor: A tensor of s...
Computes the penalty for episodes that terminate before timeout. This function is adapted from `_reward_termination` in `legged_gym`. Returns: torch.Tensor: A tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_early_termination
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_stumble(self, **kwargs): """ Computes the penalty for stumbling. This function is adapted from _reward_stumble in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment. """ f...
Computes the penalty for stumbling. This function is adapted from _reward_stumble in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_stumble
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_slippage(self, body_state: BodyState, **kwargs): """ Computes the penalty for slippage. This function is adapted from _reward_slippage in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environmen...
Computes the penalty for slippage. This function is adapted from _reward_slippage in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_slippage
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_feet_orientation(self, body_state: BodyState, **kwargs): """ Computes the penalty on feet orientation to make no x and y projected gravity. This function is adapted from _reward_feet_ori in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) r...
Computes the penalty on feet orientation to make no x and y projected gravity. This function is adapted from _reward_feet_ori in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_feet_orientation
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_feet_air_time(self, ref_motion_state: ReferenceMotionState, **kwargs): """ Computes the penalty for the time that the feet are in the air before the newest contact with the terrain. This function is adapted from _reward_feet_air_time_teleop in legged_gym. Returns: ...
Computes the penalty for the time that the feet are in the air before the newest contact with the terrain. This function is adapted from _reward_feet_air_time_teleop in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each...
penalize_feet_air_time
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_both_feet_in_air(self, **kwargs): """ Computes the penalty for both feet being in the air. This function is adapted from _reward_in_the_air in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each envir...
Computes the penalty for both feet being in the air. This function is adapted from _reward_in_the_air in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_both_feet_in_air
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_orientation(self, articulation_data: ArticulationData, **kwarg): """ Computes the penalty based on a non-flat base orientation. This function is adapted from _reward_orientation in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representi...
Computes the penalty based on a non-flat base orientation. This function is adapted from _reward_orientation in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for each environment.
penalize_orientation
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def penalize_max_feet_height_before_contact(self, body_state: BodyState, **kwargs): """ Computes the penalty based on the maximum height of the feet in the air before the current contact. This function is adapted from _reward_feet_max_height_for_this_air in legged_gym. Returns: ...
Computes the penalty based on the maximum height of the feet in the air before the current contact. This function is adapted from _reward_feet_max_height_for_this_air in legged_gym. Returns: torch.Tensor: A float tensor of shape (num_envs) representing the computed penalty for eac...
penalize_max_feet_height_before_contact
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/neural_wbc/isaac_lab_wrapper/rewards/rewards.py
Apache-2.0
def deep_compare_dicts(dict1, dict2): """Recursively compare two dictionaries, including torch tensors.""" if dict1.keys() != dict2.keys(): return False for key in dict1: value1 = dict1[key] value2 = dict2[key] if isinstance(value1, dict) and isinstance(value2, dict): ...
Recursively compare two dictionaries, including torch tensors.
deep_compare_dicts
python
NVlabs/HOVER
neural_wbc/isaac_lab_wrapper/tests/test_neural_wbc_env_cfg.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/isaac_lab_wrapper/tests/test_neural_wbc_env_cfg.py
Apache-2.0
def position_pd_control(env: NeuralWBCEnv, pos_actions: torch.Tensor, joint_ids=None): """Calculates the PD control torque based on the network output position actions""" robot = env.robot joint_pos = robot.joint_positions joint_vel = robot.joint_velocities if joint_ids: joint_pos = joint_p...
Calculates the PD control torque based on the network output position actions
position_pd_control
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/control.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/control.py
Apache-2.0
def update(self, obs_dict: dict[str, torch.Tensor | list[str] | None]) -> None: """Update the underlying model based on the observations from the environment/real robot. Args: obs_dict (dict[str, torch.Tensor]): A dictionary containing the latest robot observations. """ if "...
Update the underlying model based on the observations from the environment/real robot. Args: obs_dict (dict[str, torch.Tensor]): A dictionary containing the latest robot observations.
update
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_robot.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_robot.py
Apache-2.0
def reset(self, **kwargs) -> None: """Resets the wrapper Args: kwargs (dict[str, Any], optional): key-word arguments to pass to underlying models. Defaults to None. """ qpos = kwargs.get("qpos") qvel = kwargs.get("qvel") self._sim.reset(qpos=qpos, qvel=qvel) ...
Resets the wrapper Args: kwargs (dict[str, Any], optional): key-word arguments to pass to underlying models. Defaults to None.
reset
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_robot.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_robot.py
Apache-2.0
def __init__( self, model_path: str, sim_dt: float = 0.005, enable_viewer: bool = False, num_instances: int = 1, device=torch.device("cuda" if torch.cuda.is_available() else "cpu"), ) -> None: """Initialize the underlying mujoco simulator Args: ...
Initialize the underlying mujoco simulator Args: model_path: Path to the Mujoco model xml file sim_dt: Simulation timestep enable_viewer: Whether to enable the viewer num_instances: Number of instances to simulate device: torch device to use for the t...
__init__
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def joint_names(self) -> list[str]: """Get the names of all joints in the model except the free floating joint. Returns: list[str]: List of joint names """ offset = 0 if self.has_free_joint: offset = 1 # base/world joint return [get_entity_name(s...
Get the names of all joints in the model except the free floating joint. Returns: list[str]: List of joint names
joint_names
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def joint_positions(self) -> torch.Tensor: """Get the joint positions of the robot as tensor Returns: torch.Tensor: Tensor of joint positions """ return ( torch.from_numpy(self._data.qpos[self.joint_pos_offset :].copy()) .to(dtype=torch.float32, devic...
Get the joint positions of the robot as tensor Returns: torch.Tensor: Tensor of joint positions
joint_positions
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def joint_velocities(self) -> torch.Tensor: """Get the joint velocities of the robot as tensor Returns: torch.Tensor: Tensor of joint velocities """ return ( torch.from_numpy(self._data.qvel[self.joint_vel_offset :].copy()) .to(dtype=torch.float32, de...
Get the joint velocities of the robot as tensor Returns: torch.Tensor: Tensor of joint velocities
joint_velocities
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def body_positions(self) -> torch.Tensor: """Get the body positions of the robot as tensor Returns: torch.Tensor: Tensor of body positions """ # NOTE: Global frame, https://mujoco.readthedocs.io/en/stable/APIreference/APItypes.html # Get the body positions, excluding...
Get the body positions of the robot as tensor Returns: torch.Tensor: Tensor of body positions
body_positions
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def body_rotations(self) -> torch.Tensor: """Get the body rotations of the robot as tensor Returns: torch.Tensor: Tensor of body rotations """ # NOTE: Global frame, https://mujoco.readthedocs.io/en/stable/APIreference/APItypes.html # Get the body positions, excluding...
Get the body rotations of the robot as tensor Returns: torch.Tensor: Tensor of body rotations
body_rotations
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def body_velocities(self) -> tuple[torch.Tensor, torch.Tensor]: """Get the body linear and angular velocities of the robot as a pair of tensors Returns: tuple[torch.Tensor, torch.Tensor]: Tuple of linear and angular body velocities """ linear_velocities = torch.zeros(self.nu...
Get the body linear and angular velocities of the robot as a pair of tensors Returns: tuple[torch.Tensor, torch.Tensor]: Tuple of linear and angular body velocities
body_velocities
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def step(self, actions: np.ndarray | None = None, nsteps: int = 1) -> None: """Step the simulation forward nsteps with the given action. Args: actions (np.ndarray | None, optional): Action to apply to the robot. Defaults to None. nsteps (int, optional): Number of steps to take. ...
Step the simulation forward nsteps with the given action. Args: actions (np.ndarray | None, optional): Action to apply to the robot. Defaults to None. nsteps (int, optional): Number of steps to take. Defaults to 1.
step
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def reset( self, qpos: np.ndarray | torch.Tensor | None = None, qvel: np.ndarray | torch.Tensor | None = None, ) -> None: """Reset the model to its initial state Args: qpos (np.ndarray | torch.Tensor | None, optional): Positions of the generalized coordinates. De...
Reset the model to its initial state Args: qpos (np.ndarray | torch.Tensor | None, optional): Positions of the generalized coordinates. Defaults to None. qvel (np.ndarray | torch.Tensor | None, optional): Velocities of the generalized coordinates. Defaults to None.
reset
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def set_robot_state( self, qpos: np.ndarray | torch.Tensor | None = None, qvel: np.ndarray | torch.Tensor | None = None ): """ Set robot state including positions and velocities of the generalized coordinates. Args: qpos (np.ndarray | torch.Tensor | None, optional): Posi...
Set robot state including positions and velocities of the generalized coordinates. Args: qpos (np.ndarray | torch.Tensor | None, optional): Positions of the generalized coordinates. Defaults to None. qvel (np.ndarray | torch.Tensor | None, optional): Velocities of the generaliz...
set_robot_state
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_body_ids(self, body_names: list[str] | None = None, free_joint_offset: int = 1) -> dict[str, int]: """Get the IDs of all bodies in the model, indexed after removing the world body. Args: body_names (list[str] | None, optional): Names of the bodies. Defaults to None. free...
Get the IDs of all bodies in the model, indexed after removing the world body. Args: body_names (list[str] | None, optional): Names of the bodies. Defaults to None. free_joint_offset (int, optional): Offset to remove the free joint. Defaults to 1. Returns: dict[str,...
get_body_ids
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_joint_ids(self, joint_names: list[str] | None = None, free_joint_offset: int = 1) -> dict[str, int]: """Get the IDs of all joints in the model, indexed after removing the free joint. Args: joint_names (list[str] | None, optional): Names of the joints. Defaults to None. f...
Get the IDs of all joints in the model, indexed after removing the free joint. Args: joint_names (list[str] | None, optional): Names of the joints. Defaults to None. free_joint_offset (int, optional): Offset to remove the free joint. Defaults to 1. Returns: dict[str...
get_joint_ids
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_body_pose(self, body_name: str = "pelvis") -> tuple[torch.Tensor, torch.Tensor]: """Get the position and quaternion of the base Args: body_name (str, optional): Name of the body. Defaults to 'pelvis'. Returns: tuple[torch.Tensor, torch.Tensor]: Position and quat...
Get the position and quaternion of the base Args: body_name (str, optional): Name of the body. Defaults to 'pelvis'. Returns: tuple[torch.Tensor, torch.Tensor]: Position and quaternion of the base
get_body_pose
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_base_projected_gravity(self, base_name: str = "pelvis") -> torch.Tensor: """Get the projection of the gravity vector to the base frame Args: base_name (str, optional): Name of the base. Defaults to 'pelvis'. Returns: torch.Tensor: Projection of the gravity vecto...
Get the projection of the gravity vector to the base frame Args: base_name (str, optional): Name of the base. Defaults to 'pelvis'. Returns: torch.Tensor: Projection of the gravity vector to the base frame
get_base_projected_gravity
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_contact_forces_with_floor(self, body_name: str) -> torch.Tensor: """Get the contact forces on a given body with the floor Args: body_name (str): Name of the body Returns: torch.Tensor: Contact forces, shape (num_envs, 3), i.e. normal and two tangent directions ...
Get the contact forces on a given body with the floor Args: body_name (str): Name of the body Returns: torch.Tensor: Contact forces, shape (num_envs, 3), i.e. normal and two tangent directions Notes: Only checks contacts with the floor, and thus assumes the...
get_contact_forces_with_floor
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def print_actuator_info(self, actuators_id: list[int] | None = None): """Utility function to print out actuator types in the model. Args: actuators_id (list[int] | None, optional): Actuator ids. Defaults to None. """ actuators_id_ = range(self.model.nu) if actuators_id is No...
Utility function to print out actuator types in the model. Args: actuators_id (list[int] | None, optional): Actuator ids. Defaults to None.
print_actuator_info
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def _check_actuator_consistency(self): """Check whether all the actuators share the same control mode.""" actuator_type_system = None for actuator_id in range(self.model.nu): actuator_type = self.model.actuator_trntype[actuator_id] if actuator_type_system is None: ...
Check whether all the actuators share the same control mode.
_check_actuator_consistency
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_simulator.py
Apache-2.0
def get_entity_name(model: mj.MjModel, entity_type: str, entity_id: int) -> str: """Gets name of an entity based on ID Args: model (mj.MjModel): model entity_type (str): entity type entity_id (int): entity id Returns: str: entity name """ if entity_type == "body": ...
Gets name of an entity based on ID Args: model (mj.MjModel): model entity_type (str): entity type entity_id (int): entity id Returns: str: entity name
get_entity_name
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_utils.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/mujoco_utils.py
Apache-2.0
def to_numpy(x): """ Check if input is a PyTorch tensor and convert to numpy array if true. Otherwise return the input unchanged. Args: x: Input to check and potentially convert Returns: numpy array if input was torch tensor, otherwise original input """ if isinstance(x, to...
Check if input is a PyTorch tensor and convert to numpy array if true. Otherwise return the input unchanged. Args: x: Input to check and potentially convert Returns: numpy array if input was torch tensor, otherwise original input
to_numpy
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/utils.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/utils.py
Apache-2.0
def squeeze_if_tensor(x, dim: int = 0): """ Check if input is a PyTorch tensor and squeeze along the given dim if true. Args: x: Input to check and potentially convert dim: Dimension to squeeze Returns: numpy array if input was torch tensor, otherwise original input """ ...
Check if input is a PyTorch tensor and squeeze along the given dim if true. Args: x: Input to check and potentially convert dim: Dimension to squeeze Returns: numpy array if input was torch tensor, otherwise original input
squeeze_if_tensor
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/utils.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/utils.py
Apache-2.0
def draw_reference_state(self, state: ReferenceMotionState): """Visualize the reference state in Mujoco.""" body_pos_np = np.squeeze(state.body_pos.detach().cpu().numpy()) body_pos_extend_np = np.squeeze(state.body_pos_extend.detach().cpu().numpy()) body_pos = np.vstack([body_pos_np, bo...
Visualize the reference state in Mujoco.
draw_reference_state
python
NVlabs/HOVER
neural_wbc/mujoco_wrapper/mujoco_wrapper/visualization.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/mujoco_wrapper/mujoco_wrapper/visualization.py
Apache-2.0
def _produce_actions(self, obs: dict) -> torch.Tensor: """ Roll out the environment with either the expert policy or the student policy, depending on the current state of training. """ if self._iterations + self.start_iteration >= self._cfg.student_rollout_iteration: ...
Roll out the environment with either the expert policy or the student policy, depending on the current state of training.
_produce_actions
python
NVlabs/HOVER
neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer.py
Apache-2.0
def save(self, file_path: str): """ Save the dataclass fields to a JSON file. Args: file_path (str): The path to the file where the JSON will be saved. """ # Convert the dataclass to a dictionary data_dict = { field_info.name: getattr(self, field_...
Save the dataclass fields to a JSON file. Args: file_path (str): The path to the file where the JSON will be saved.
save
python
NVlabs/HOVER
neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer_cfg.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer_cfg.py
Apache-2.0
def add_args_to_parser(parser: argparse.ArgumentParser, default_overwrites: dict = {}): """ Add the fields of the dataclass (except for `teacher_policy`) to an ArgumentParser. This method iterates over the fields of the StudentPolicyTrainerCfg dataclass and adds them as arguments to the...
Add the fields of the dataclass (except for `teacher_policy`) to an ArgumentParser. This method iterates over the fields of the StudentPolicyTrainerCfg dataclass and adds them as arguments to the provided ArgumentParser. The `teacher_policy` field is skipped. If a field has a default value or ...
add_args_to_parser
python
NVlabs/HOVER
neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer_cfg.py
https://github.com/NVlabs/HOVER/blob/master/neural_wbc/student_policy/neural_wbc/student_policy/student_policy_trainer_cfg.py
Apache-2.0
def load(filepath: str) -> "TeacherPolicyCfg": """Loads the configuration from a YAML file.""" with open(filepath, encoding="utf-8") as file: data = json.load(file) cfg = fromdict(TeacherPolicyCfg, data) return cfg
Loads the configuration from a YAML file.
load
python
NVlabs/HOVER
scripts/rsl_rl/teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/teacher_policy_cfg.py
Apache-2.0
def add_args_to_parser(parser: argparse.ArgumentParser, default_overwrites: dict = {}): """Adds configuration fields to an ArgumentParser.""" group = parser.add_argument_group("Teacher policy configurations (RSL RL)") def add_fields_to_parser(fields): for field_info in fields: ...
Adds configuration fields to an ArgumentParser.
add_args_to_parser
python
NVlabs/HOVER
scripts/rsl_rl/teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/teacher_policy_cfg.py
Apache-2.0
def from_argparse_args(args: argparse.Namespace) -> "TeacherPolicyCfg": """Creates an instance from argparse arguments.""" def extract_fields(cls: Type) -> dict: """Helper function to extract fields for a given dataclass type.""" extracted_fields = { field.name: ...
Creates an instance from argparse arguments.
from_argparse_args
python
NVlabs/HOVER
scripts/rsl_rl/teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/teacher_policy_cfg.py
Apache-2.0
def extract_fields(cls: Type) -> dict: """Helper function to extract fields for a given dataclass type.""" extracted_fields = { field.name: getattr(args, TeacherPolicyCfg.args_prefix() + field.name) for field in fields(cls) if hasattr(args, Teacher...
Helper function to extract fields for a given dataclass type.
extract_fields
python
NVlabs/HOVER
scripts/rsl_rl/teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/teacher_policy_cfg.py
Apache-2.0
def resolve_student_policy_path(root_path: str, teacher_policy: NeuralWBCTeacherPolicy, append_timestamp: bool): """ Generates a path for storing student policy configurations based on the root path and teacher policy. This function appends a timestamp and the teacher policy name to the given root path to ...
Generates a path for storing student policy configurations based on the root path and teacher policy. This function appends a timestamp and the teacher policy name to the given root path to create a unique path for storing student policy configurations. Args: root_path (str): The root directo...
resolve_student_policy_path
python
NVlabs/HOVER
scripts/rsl_rl/train_student_policy.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/train_student_policy.py
Apache-2.0
def get_config_values_from_argparser(args: argparse.Namespace, teacher_policy: NeuralWBCTeacherPolicy): """ Extracts configuration values from command-line arguments based on a predefined prefix and field names. This function processes the command-line arguments, filters out those that match a specified pr...
Extracts configuration values from command-line arguments based on a predefined prefix and field names. This function processes the command-line arguments, filters out those that match a specified prefix, and returns a dictionary of configuration values that are relevant to the StudentPolicyTrainerCfg dat...
get_config_values_from_argparser
python
NVlabs/HOVER
scripts/rsl_rl/train_student_policy.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/train_student_policy.py
Apache-2.0
def get_student_trainer_cfg(args: argparse.Namespace, env: NeuralWBCEnv, teacher_policy: NeuralWBCTeacherPolicy): """ Create an instance of StudentPolicyTrainerCfg from command-line arguments, environment configuration, and a teacher policy. This function processes the command-line arguments, extracts nece...
Create an instance of StudentPolicyTrainerCfg from command-line arguments, environment configuration, and a teacher policy. This function processes the command-line arguments, extracts necessary values, fills in any missing values using the environment configuration, and creates an instance of the Student...
get_student_trainer_cfg
python
NVlabs/HOVER
scripts/rsl_rl/train_student_policy.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/train_student_policy.py
Apache-2.0
def load_student_policy_trainer_cfg(args: argparse.Namespace, teacher_policy: NeuralWBCTeacherPolicy): """ Loads the student policy trainer configuration from a specified resume path. This function checks if a resume path is provided in the command-line arguments. If so, it loads the configuration from...
Loads the student policy trainer configuration from a specified resume path. This function checks if a resume path is provided in the command-line arguments. If so, it loads the configuration from a config.json at the resume path, updates it with any new arguments provided, and returns an instance of ...
load_student_policy_trainer_cfg
python
NVlabs/HOVER
scripts/rsl_rl/train_student_policy.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/train_student_policy.py
Apache-2.0
def get_customized_rsl_rl(): """Helper function to ensure the correct version of rsl_rl is imported. This function does the following: 1. Gets the installed rsl_rl package location and adds it to sys.path 2. Removes any existing rsl_rl and submodules from sys.modules to force reimporting """ im...
Helper function to ensure the correct version of rsl_rl is imported. This function does the following: 1. Gets the installed rsl_rl package location and adds it to sys.path 2. Removes any existing rsl_rl and submodules from sys.modules to force reimporting
get_customized_rsl_rl
python
NVlabs/HOVER
scripts/rsl_rl/utils.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/utils.py
Apache-2.0
def __init__(self, env: NeuralWBCEnv): """Initializes the wrapper. Note: The wrapper calls :meth:`reset` at the start since the RSL-RL runner does not call reset. Args: env: The environment to wrap around. """ super().__init__(mode=env.cfg.mode) ...
Initializes the wrapper. Note: The wrapper calls :meth:`reset` at the start since the RSL-RL runner does not call reset. Args: env: The environment to wrap around.
__init__
python
NVlabs/HOVER
scripts/rsl_rl/vecenv_wrapper.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/vecenv_wrapper.py
Apache-2.0
def test_save_and_load(self): """Test saving and loading the configuration to/from a file.""" # Create a temporary file to save the configuration with tempfile.NamedTemporaryFile(delete=False) as tmp_file: file_path = tmp_file.name # Save the configuration to the file ...
Test saving and loading the configuration to/from a file.
test_save_and_load
python
NVlabs/HOVER
scripts/rsl_rl/tests/test_teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/tests/test_teacher_policy_cfg.py
Apache-2.0
def test_add_args_to_parser(self): """Test adding configuration fields to an argument parser.""" parser = argparse.ArgumentParser(description="RSL-RL configuration") TeacherPolicyCfg.add_args_to_parser(parser) # Create sample arguments args = [ "--teacher_policy.seed...
Test adding configuration fields to an argument parser.
test_add_args_to_parser
python
NVlabs/HOVER
scripts/rsl_rl/tests/test_teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/tests/test_teacher_policy_cfg.py
Apache-2.0
def test_default_values(self): """Test the default values of the configuration.""" # Verify default values self.assertEqual(self.config.seed, 1) self.assertEqual(self.config.policy.init_noise_std, 1.0) self.assertEqual(self.config.policy.actor_hidden_dims, [512, 256, 128]) ...
Test the default values of the configuration.
test_default_values
python
NVlabs/HOVER
scripts/rsl_rl/tests/test_teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/tests/test_teacher_policy_cfg.py
Apache-2.0
def test_add_args_to_parser_with_default_overwrites(self): """Test adding configuration fields to an argument parser with default overwrites.""" parser = argparse.ArgumentParser(description="RSL-RL configuration") default_overwrites = { "seed": 10, "init_noise_std": 0.5, ...
Test adding configuration fields to an argument parser with default overwrites.
test_add_args_to_parser_with_default_overwrites
python
NVlabs/HOVER
scripts/rsl_rl/tests/test_teacher_policy_cfg.py
https://github.com/NVlabs/HOVER/blob/master/scripts/rsl_rl/tests/test_teacher_policy_cfg.py
Apache-2.0
def format_seconds_to_human_readable(self, total_seconds): """Formats seconds into a human readable string with hours, minutes and seconds. Args: total_seconds (float): Number of seconds to format Returns: str: Formatted string in the format "Xh, Ym, Zs" where X=hours, ...
Formats seconds into a human readable string with hours, minutes and seconds. Args: total_seconds (float): Number of seconds to format Returns: str: Formatted string in the format "Xh, Ym, Zs" where X=hours, Y=minutes, Z=seconds
format_seconds_to_human_readable
python
NVlabs/HOVER
third_party/rsl_rl/rsl_rl/runners/on_policy_runner.py
https://github.com/NVlabs/HOVER/blob/master/third_party/rsl_rl/rsl_rl/runners/on_policy_runner.py
Apache-2.0
def split_and_pad_trajectories(tensor, dones): """ Splits trajectories at done indices. Then concatenates them and padds with zeros up to the length og the longest trajectory. Returns masks corresponding to valid parts of the trajectories Example: Input: [ [a1, a2, a3, a4 | a5, a6], ...
Splits trajectories at done indices. Then concatenates them and padds with zeros up to the length og the longest trajectory. Returns masks corresponding to valid parts of the trajectories Example: Input: [ [a1, a2, a3, a4 | a5, a6], [b1, b2 | b3, b4, b5 | b6] ] ...
split_and_pad_trajectories
python
NVlabs/HOVER
third_party/rsl_rl/rsl_rl/utils/utils.py
https://github.com/NVlabs/HOVER/blob/master/third_party/rsl_rl/rsl_rl/utils/utils.py
Apache-2.0
def setup(self) -> None: """Load the model into memory to make running multiple predictions efficient""" # if checkpoints folder does not exist, create it if not os.path.exists(MODEL_CACHE): download(MODEL_URL, MODEL_CACHE) disable_verbosity() cv2.setNumThrea...
Load the model into memory to make running multiple predictions efficient
setup
python
ali-vilab/AnyDoor
predict.py
https://github.com/ali-vilab/AnyDoor/blob/master/predict.py
MIT
def predict( self, reference_image_path: Path = Input(description="Source Image"), reference_image_mask: Path = Input(description="Source Image"), bg_image_path: Path = Input(description="Target Image"), bg_mask_path: Path = Input(description="Target Image mask"), control...
Run a single prediction on the model
predict
python
ali-vilab/AnyDoor
predict.py
https://github.com/ali-vilab/AnyDoor/blob/master/predict.py
MIT
def mask_score(mask): '''Scoring the mask according to connectivity.''' mask = mask.astype(np.uint8) if mask.sum() < 10: return 0 contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) cnt_area = [cv2.contourArea(cnt) for cnt in contours] conc_score = np.max(cnt_a...
Scoring the mask according to connectivity.
mask_score
python
ali-vilab/AnyDoor
datasets/data_utils.py
https://github.com/ali-vilab/AnyDoor/blob/master/datasets/data_utils.py
MIT
def resize_and_pad(image, box): '''Fitting an image to the box region while keeping the aspect ratio.''' y1,y2,x1,x2 = box H,W = y2-y1, x2-x1 h,w = image.shape[0], image.shape[1] r_box = W / H r_image = w / h if r_box >= r_image: h_target = H w_target = int(w * H / h) ...
Fitting an image to the box region while keeping the aspect ratio.
resize_and_pad
python
ali-vilab/AnyDoor
datasets/data_utils.py
https://github.com/ali-vilab/AnyDoor/blob/master/datasets/data_utils.py
MIT
def q_x(x_0,t=65): '''Adding noise for and given image.''' x_0 = torch.from_numpy(x_0).float() / 127.5 - 1 num_steps = 100 betas = torch.linspace(-6,6,num_steps) betas = torch.sigmoid(betas)*(0.5e-2 - 1e-5)+1e-5 alphas = 1-betas alphas_prod = torch.cumprod(alphas,0) alphas_pro...
Adding noise for and given image.
q_x
python
ali-vilab/AnyDoor
datasets/data_utils.py
https://github.com/ali-vilab/AnyDoor/blob/master/datasets/data_utils.py
MIT
def make_dataset( *, dataset_str: str, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, ): """ Creates a dataset with the specified parameters. Args: dataset_str: A dataset string description (e.g. ImageNet:split=TRAIN). transform: A transfo...
Creates a dataset with the specified parameters. Args: dataset_str: A dataset string description (e.g. ImageNet:split=TRAIN). transform: A transform to apply to images. target_transform: A transform to apply to targets. Returns: The created dataset.
make_dataset
python
ali-vilab/AnyDoor
dinov2/dinov2/data/loaders.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/data/loaders.py
MIT
def make_data_loader( *, dataset, batch_size: int, num_workers: int, shuffle: bool = True, seed: int = 0, sampler_type: Optional[SamplerType] = SamplerType.INFINITE, sampler_size: int = -1, sampler_advance: int = 0, drop_last: bool = True, persistent_workers: bool = False, ...
Creates a data loader with the specified parameters. Args: dataset: A dataset (third party, LaViDa or WebDataset). batch_size: The size of batches to generate. num_workers: The number of workers to use. shuffle: Whether to shuffle samples. seed: The random seed to use. ...
make_data_loader
python
ali-vilab/AnyDoor
dinov2/dinov2/data/loaders.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/data/loaders.py
MIT
def _generate_randperm_indices(*, size: int, generator: torch.Generator): """Generate the indices of a random permutation.""" dtype = _get_torch_dtype(size) # This is actually matching PyTorch's CPU implementation, see: https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/TensorFactories.cpp#...
Generate the indices of a random permutation.
_generate_randperm_indices
python
ali-vilab/AnyDoor
dinov2/dinov2/data/samplers.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/data/samplers.py
MIT
def __call__(self, pic): """ Args: pic (PIL Image, numpy.ndarray or torch.tensor): Image to be converted to tensor. Returns: Tensor: Converted image. """ if isinstance(pic, torch.Tensor): return pic return super().__call__(pic)
Args: pic (PIL Image, numpy.ndarray or torch.tensor): Image to be converted to tensor. Returns: Tensor: Converted image.
__call__
python
ali-vilab/AnyDoor
dinov2/dinov2/data/transforms.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/data/transforms.py
MIT
def get_local_rank() -> int: """ Returns: The rank of the current process within the local (per-machine) process group. """ if not is_enabled(): return 0 assert 0 <= _LOCAL_RANK < _LOCAL_WORLD_SIZE return _LOCAL_RANK
Returns: The rank of the current process within the local (per-machine) process group.
get_local_rank
python
ali-vilab/AnyDoor
dinov2/dinov2/distributed/__init__.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/distributed/__init__.py
MIT
def get_local_size() -> int: """ Returns: The size of the per-machine process group, i.e. the number of processes per machine. """ if not is_enabled(): return 1 assert 0 <= _LOCAL_RANK < _LOCAL_WORLD_SIZE return _LOCAL_WORLD_SIZE
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
get_local_size
python
ali-vilab/AnyDoor
dinov2/dinov2/distributed/__init__.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/distributed/__init__.py
MIT
def _restrict_print_to_main_process() -> None: """ This function disables printing when not in the main process """ import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop("force", False) if is_main_process() or force: ...
This function disables printing when not in the main process
_restrict_print_to_main_process
python
ali-vilab/AnyDoor
dinov2/dinov2/distributed/__init__.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/distributed/__init__.py
MIT
def enable(*, set_cuda_current_device: bool = True, overwrite: bool = False, allow_nccl_timeout: bool = False): """Enable distributed mode Args: set_cuda_current_device: If True, call torch.cuda.set_device() to set the current PyTorch CUDA device to the one matching the local rank. ...
Enable distributed mode Args: set_cuda_current_device: If True, call torch.cuda.set_device() to set the current PyTorch CUDA device to the one matching the local rank. overwrite: If True, overwrites already set variables. Else fails.
enable
python
ali-vilab/AnyDoor
dinov2/dinov2/distributed/__init__.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/distributed/__init__.py
MIT
def forward(self, features_rank): """ Compute the results on all values of `self.nb_knn` neighbors from the full `self.max_k` """ assert all(k <= self.max_k for k in self.nb_knn) topk_sims, neighbors_labels = self.compute_neighbors(features_rank) batch_size = neighbors_l...
Compute the results on all values of `self.nb_knn` neighbors from the full `self.max_k`
forward
python
ali-vilab/AnyDoor
dinov2/dinov2/eval/knn.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/eval/knn.py
MIT
def eval_log_regression( *, model, train_dataset, val_dataset, finetune_dataset, metric_type, batch_size, num_workers, finetune_on_val=False, train_dtype=torch.float64, train_features_device=_CPU_DEVICE, max_train_iters=DEFAULT_MAX_ITER, ): """ Implements the "sta...
Implements the "standard" process for log regression evaluation: The value of C is chosen by training on train_dataset and evaluating on finetune_dataset. Then, the final model is trained on a concatenation of train_dataset and finetune_dataset, and is evaluated on val_dataset. If there is no finet...
eval_log_regression
python
ali-vilab/AnyDoor
dinov2/dinov2/eval/log_regression.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/eval/log_regression.py
MIT
def save(self, name: str, **kwargs: Any) -> None: """ Dump model and checkpointables to a file. Args: name (str): name of the file. kwargs (dict): extra arbitrary data to save. """ if not self.save_dir or not self.save_to_disk: return ...
Dump model and checkpointables to a file. Args: name (str): name of the file. kwargs (dict): extra arbitrary data to save.
save
python
ali-vilab/AnyDoor
dinov2/dinov2/fsdp/__init__.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/fsdp/__init__.py
MIT
def get_checkpoint_file(self) -> str: """ Returns: str: The latest checkpoint file in target directory. """ save_file = os.path.join(self.save_dir, f"last_checkpoint.{rankstr()}") try: with self.path_manager.open(save_file, "r") as f: last_...
Returns: str: The latest checkpoint file in target directory.
get_checkpoint_file
python
ali-vilab/AnyDoor
dinov2/dinov2/fsdp/__init__.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/fsdp/__init__.py
MIT
def tag_last_checkpoint(self, last_filename_basename: str) -> None: """ Tag the last checkpoint. Args: last_filename_basename (str): the basename of the last filename. """ if distributed.is_enabled(): torch.distributed.barrier() save_file = os.pat...
Tag the last checkpoint. Args: last_filename_basename (str): the basename of the last filename.
tag_last_checkpoint
python
ali-vilab/AnyDoor
dinov2/dinov2/fsdp/__init__.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/fsdp/__init__.py
MIT
def get_attn_bias_and_cat(x_list, branges=None): """ this will perform the index select, cat the tensors, and provide the attn_bias from cache """ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list] all_shapes = tuple((b, x.shape[1]) for b, x in zip(b...
this will perform the index select, cat the tensors, and provide the attn_bias from cache
get_attn_bias_and_cat
python
ali-vilab/AnyDoor
dinov2/dinov2/layers/block.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/layers/block.py
MIT
def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]: """ x_list contains a list of tensors to nest together and run """ assert isinstance(self.attn, MemEffAttention) if self.training and self.sample_drop_ratio > 0.0: def attn_residual_func(x: Tensor, attn...
x_list contains a list of tensors to nest together and run
forward_nested
python
ali-vilab/AnyDoor
dinov2/dinov2/layers/block.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/layers/block.py
MIT
def synchronize_between_processes(self): """ Distributed synchronization of the metric Warning: does not synchronize the deque! """ if not distributed.is_enabled(): return t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda") t...
Distributed synchronization of the metric Warning: does not synchronize the deque!
synchronize_between_processes
python
ali-vilab/AnyDoor
dinov2/dinov2/logging/helpers.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/logging/helpers.py
MIT
def _configure_logger( name: Optional[str] = None, *, level: int = logging.DEBUG, output: Optional[str] = None, ): """ Configure a logger. Adapted from Detectron2. Args: name: The name of the logger to configure. level: The logging level to use. output: A file n...
Configure a logger. Adapted from Detectron2. Args: name: The name of the logger to configure. level: The logging level to use. output: A file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. ...
_configure_logger
python
ali-vilab/AnyDoor
dinov2/dinov2/logging/__init__.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/logging/__init__.py
MIT
def setup_logging( output: Optional[str] = None, *, name: Optional[str] = None, level: int = logging.DEBUG, capture_warnings: bool = True, ) -> None: """ Setup logging. Args: output: A file name or a directory to save log files. If None, log files will not be saved. ...
Setup logging. Args: output: A file name or a directory to save log files. If None, log files will not be saved. If output ends with ".txt" or ".log", it is assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. name: The name of the l...
setup_logging
python
ali-vilab/AnyDoor
dinov2/dinov2/logging/__init__.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/logging/__init__.py
MIT
def forward(self, student_output_list, teacher_out_softmaxed_centered_list): """ Cross-entropy between softmax outputs of the teacher and student networks. """ # TODO: Use cross_entropy_distribution here total_loss = 0 for s in student_output_list: lsm = F.log...
Cross-entropy between softmax outputs of the teacher and student networks.
forward
python
ali-vilab/AnyDoor
dinov2/dinov2/loss/dino_clstoken_loss.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/loss/dino_clstoken_loss.py
MIT
def forward(self, student_patch_tokens, teacher_patch_tokens, student_masks_flat): """ Cross-entropy between softmax outputs of the teacher and student networks. student_patch_tokens: (B, N, D) tensor teacher_patch_tokens: (B, N, D) tensor student_masks_flat: (B, N) tensor ...
Cross-entropy between softmax outputs of the teacher and student networks. student_patch_tokens: (B, N, D) tensor teacher_patch_tokens: (B, N, D) tensor student_masks_flat: (B, N) tensor
forward
python
ali-vilab/AnyDoor
dinov2/dinov2/loss/ibot_patch_loss.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/loss/ibot_patch_loss.py
MIT
def pairwise_NNs_inner(self, x): """ Pairwise nearest neighbors for L2-normalized vectors. Uses Torch rather than Faiss to remain on GPU. """ # parwise dot products (= inverse distance) dots = torch.mm(x, x.t()) n = x.shape[0] dots.view(-1)[:: (n + 1)].fil...
Pairwise nearest neighbors for L2-normalized vectors. Uses Torch rather than Faiss to remain on GPU.
pairwise_NNs_inner
python
ali-vilab/AnyDoor
dinov2/dinov2/loss/koleo_loss.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/loss/koleo_loss.py
MIT
def forward(self, student_output, eps=1e-8): """ Args: student_output (BxD): backbone output of student """ with torch.cuda.amp.autocast(enabled=False): student_output = F.normalize(student_output, eps=eps, p=2, dim=-1) I = self.pairwise_NNs_inner(stud...
Args: student_output (BxD): backbone output of student
forward
python
ali-vilab/AnyDoor
dinov2/dinov2/loss/koleo_loss.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/loss/koleo_loss.py
MIT
def __init__( self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, ffn_bias=True, proj_bias=True, drop_path_rate=0.0, drop_path_uniform=False, in...
Args: img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads ...
__init__
python
ali-vilab/AnyDoor
dinov2/dinov2/models/vision_transformer.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/models/vision_transformer.py
MIT
def init_weights_vit_timm(module: nn.Module, name: str = ""): """ViT weight initialization, original timm impl (for reproducibility)""" if isinstance(module, nn.Linear): trunc_normal_(module.weight, std=0.02) if module.bias is not None: nn.init.zeros_(module.bias)
ViT weight initialization, original timm impl (for reproducibility)
init_weights_vit_timm
python
ali-vilab/AnyDoor
dinov2/dinov2/models/vision_transformer.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/models/vision_transformer.py
MIT
def vit_giant2(patch_size=16, **kwargs): """ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 """ model = DinoVisionTransformer( patch_size=patch_size, embed_dim=1536, depth=40, num_heads=24, mlp_ratio=4, block_fn=partial(Block...
Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
vit_giant2
python
ali-vilab/AnyDoor
dinov2/dinov2/models/vision_transformer.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/models/vision_transformer.py
MIT
def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg_from_args(args) os.makedirs(args.output_dir, exist_ok=True) default_setup(args) apply_scaling_rules_to_cfg(cfg) write_config(cfg, args.output_dir) return cfg
Create configs and perform basic setups.
setup
python
ali-vilab/AnyDoor
dinov2/dinov2/utils/config.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/utils/config.py
MIT
def get_vit_lr_decay_rate(name, lr_decay_rate=1.0, num_layers=12, force_is_backbone=False, chunked_blocks=False): """ Calculate lr decay rate for different ViT blocks. Args: name (string): parameter name. lr_decay_rate (float): base lr decay rate. num_layers (int): number of ViT bloc...
Calculate lr decay rate for different ViT blocks. Args: name (string): parameter name. lr_decay_rate (float): base lr decay rate. num_layers (int): number of ViT blocks. Returns: lr decay rate for the given parameter.
get_vit_lr_decay_rate
python
ali-vilab/AnyDoor
dinov2/dinov2/utils/param_groups.py
https://github.com/ali-vilab/AnyDoor/blob/master/dinov2/dinov2/utils/param_groups.py
MIT
def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8, # TODO: check hyperparameters before using weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999, # ema decay to match previous code ema_power=1., param_names=()): """AdamW that saves EMA versions of the param...
AdamW that saves EMA versions of the parameters.
__init__
python
ali-vilab/AnyDoor
ldm/util.py
https://github.com/ali-vilab/AnyDoor/blob/master/ldm/util.py
MIT
def step(self, closure=None): """Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): ...
Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
ali-vilab/AnyDoor
ldm/util.py
https://github.com/ali-vilab/AnyDoor/blob/master/ldm/util.py
MIT
def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's...
Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape.
q_mean_variance
python
ali-vilab/AnyDoor
ldm/models/diffusion/ddpm.py
https://github.com/ali-vilab/AnyDoor/blob/master/ldm/models/diffusion/ddpm.py
MIT
def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = ...
:param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center
delta_border
python
ali-vilab/AnyDoor
ldm/models/diffusion/ddpm.py
https://github.com/ali-vilab/AnyDoor/blob/master/ldm/models/diffusion/ddpm.py
MIT
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # number of crops in i...
:param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
get_fold_unfold
python
ali-vilab/AnyDoor
ldm/models/diffusion/ddpm.py
https://github.com/ali-vilab/AnyDoor/blob/master/ldm/models/diffusion/ddpm.py
MIT
def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in b...
Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element.
_prior_bpd
python
ali-vilab/AnyDoor
ldm/models/diffusion/ddpm.py
https://github.com/ali-vilab/AnyDoor/blob/master/ldm/models/diffusion/ddpm.py
MIT
def append_dims(x, target_dims): """Appends dimensions to the end of a tensor until it has target_dims dimensions. From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py""" dims_to_append = target_dims - x.ndim if dims_to_append < 0: raise ValueError(f'input has {x.ndim} ...
Appends dimensions to the end of a tensor until it has target_dims dimensions. From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py
append_dims
python
ali-vilab/AnyDoor
ldm/models/diffusion/sampling_util.py
https://github.com/ali-vilab/AnyDoor/blob/master/ldm/models/diffusion/sampling_util.py
MIT
def __init__( self, schedule='discrete', betas=None, alphas_cumprod=None, continuous_beta_0=0.1, continuous_beta_1=20., ): """Create a wrapper class for the forward SDE (VP type). *** Update: We support discrete-time dif...
Create a wrapper class for the forward SDE (VP type). *** Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t. We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution imag...
__init__
python
ali-vilab/AnyDoor
ldm/models/diffusion/dpm_solver/dpm_solver.py
https://github.com/ali-vilab/AnyDoor/blob/master/ldm/models/diffusion/dpm_solver/dpm_solver.py
MIT