gym-aloha

repository·main·Indexed 42 days ago

https://github.com/huggingface/gym-aloha

A Gymnasium-compatible environment for the ALOHA robotic platform, version 0.1.4. It supports robotic tasks such as TransferCubeTask (cube transfer) and InsertionTask (peg-in-socket insertion). The package provides the AlohaEnv class, supporting observation types including pixels and pixels_agent_pos, and includes utilities for normalizing gripper positions and joint values between master and puppet devices.

Tokens
4.1K
Snippets
16
Records
20
Agent score
52%

What's inside gym-aloha

  1. Available gym-aloha environments and tasks

    main

    The gym-aloha package provides two main tasks:

    1. TransferCubeTask: The right arm picks up a red cube from the table and places it into the gripper of the left arm.
    2. InsertionTask: The left and right arms pick up a socket and a peg respectively, then perform an insertion task in mid-air.

    Success is defined as achieving a maximum reward of 4 points.

  2. Quickstart with gym-aloha

    main

    The following example demonstrates how to initialize an environment, run a random policy loop, render frames, and save the result as an MP4 video using imageio.

    # example.py
    import imageio
    import gymnasium as gym
    import numpy as np
    import gym_aloha
    
    env = gym.make("gym_aloha/AlohaInsertion-v0")
    observation, info = env.reset()
    frames = []
    
    for _ in range(1000):
        action = env.action_space.sample()
        observation, reward, terminated, truncated, info = env.step(action)
        image = env.render()
        frames.append(image)
    
        if terminated or truncated:
            observation, info = env.reset()
    
    env.close()
    imageio.mimsave("example.mp4", np.stack(frames), fps=25)
  3. Install gym-aloha

    main

    To install gym-aloha, it is recommended to use a Python 3.10 virtual environment. You can use conda to create and activate the environment before installing via pip.

    conda create -y -n aloha python=3.10 && conda activate aloha
    pip install gym-aloha
  4. Configure GPU Rendering (EGL) for MuJoCo

    main

    To ensure MuJoCo uses GPU rendering via EGL instead of falling back to CPU, you may need to manually create an NVIDIA ICD configuration file if it is missing from your system. Additionally, setting XLA_FLAGS with triton_gemm_any=True can improve performance on some GPUs.

    import os
    import subprocess
    
    # Ensure GPU is available
    if subprocess.run('nvidia-smi').returncode:
        raise RuntimeError('Cannot communicate with GPU.')
    
    # Add an ICD config for Nvidia EGL driver
    NVIDIA_ICD_CONFIG_PATH = '/usr/share/glvnd/egl_vendor.d/10_nvidia.json'
    if not os.path.exists(NVIDIA_ICD_CONFIG_PATH):
        with open(NVIDIA_ICD_CONFIG_PATH, 'w') as f:
            f.write('{
        "file_format_version" : "1.0.0",
        "ICD" : {
            "library_path" : "libEGL_nvidia.so.0"
        }
    }')
    
    # Improve steps/sec on some GPUs
    xla_flags = os.environ.get('XLA_FLAGS', '')
    xla_flags += ' --xla_gpu_triton_gemm_any=True'
    os.environ['XLA_FLAGS'] = xla_flags
  5. Understand AlohaEnv observation spaces

    main

    The structure of the returned observation depends on the obs_type provided during initialization:

    1. pixels:

      • A gymnasium.spaces.Dict containing:
        • top: A Box array of shape (observation_height, observation_width, 3) with uint8 values (0-255).
    2. pixels_agent_pos:

      • A gymnasium.spaces.Dict containing:
        • pixels: A nested Dict with the top camera image (as described above).
        • agent_pos: A Box array of shape (len(JOINTS),) containing joint positions as float64.
    3. state:

      • Not currently implemented; calling this will raise a NotImplementedError.
  6. Configure gym.make() arguments for gym-aloha

    main

    When creating an environment with gym.make(), you can pass the following arguments:

    ArgumentTypeDescription
    obs_typestrObservation type. Options: pixels (default) or pixels_agent_pos.
    render_modestrRendering mode. Currently only rgb_array is supported.
    observation_widthintWidth of the observed image. Default: 640.
    observation_heightintHeight of the observed image. Default: 480.
    visualization_widthintWidth of the visualized image. Default: 640.
    visualization_heightintHeight of the visualized image. Default: 480.
    import gymnasium as gym
    import gym_aloha
    
    env = gym.make("gym_aloha/AlohaInsertion-v0", obs_type="pixels", render_mode="rgb_array")
  7. Reference the gym-aloha Action Space

    main

    The action space is a 14-dimensional continuous vector representing the state of both arms and grippers:

    • 6 values per arm: Absolute joint positions.
    • 1 value per gripper: Position normalized between 0 (closed) and 1 (open).
  8. Reference the gym-aloha Observation Space

    main

    Observations are returned as a dictionary containing:

    • qpos: Position data for arms and grippers.
    • qvel: Velocity data for arms and grippers.
    • images: Camera feeds from various angles.
    • env_state: Additional environment state (e.g., positions of the peg and sockets).
  9. Sample peg and socket poses with `sample_insertion_pose`

    main

    Use sample_insertion_pose to generate random 7D poses for both a peg and a socket, typically used for insertion tasks. The function returns a tuple of two numpy arrays: (peg_pose, socket_pose).

    Each pose is a concatenation of a 3D position [x, y, z] and a 4D quaternion [w, x, y, z] (fixed at [1, 0, 0, 0]).

    Peg Position Ranges:

    • X: [0.1, 0.2]
    • Y: [0.4, 0.6]
    • Z: [0.05, 0.05]

    Socket Position Ranges:

    • X: [-0.2, -0.1]
    • Y: [0.4, 0.6]
    • Z: [0.05, 0.05]

    Args: seed (int, optional): Random seed for reproducibility.

    from gym_aloha.utils import sample_insertion_pose
    
    # Sample poses for both peg and socket
    peg_pose, socket_pose = sample_insertion_pose(seed=42)
  10. Sample a box pose with `sample_box_pose`

    main

    Use sample_box_pose to generate a random 7D pose for a box. The returned pose is a concatenation of a 3D position [x, y, z] and a 4D quaternion [w, x, y, z].

    By default, the position is sampled from the following ranges:

    • X: [0.0, 0.2]
    • Y: [0.4, 0.6]
    • Z: [0.05, 0.05]

    The quaternion is fixed at [1, 0, 0, 0] (no rotation).

    Args: seed (int, optional): Random seed for reproducibility.

    from gym_aloha.utils import sample_box_pose
    
    # Sample a random box pose
    pose = sample_box_pose(seed=42)
    # pose is a numpy array: [x, y, z, qw, qx, qy, qz]
  11. Use AlohaEnv.reset() to restart the environment

    main

    The reset method restarts the environment to a starting state. It accepts an optional seed for reproducibility.

    Returns:

    • observation: The initial observation formatted by obs_type.
    • info (dict): Metadata dictionary, initialized with {"is_success": False}.

    Seeding: If a seed is provided, it is used to seed the underlying task's random number generator and the NumPy random state.

    observation, info = env.reset(seed=42)
  12. Initialize the AlohaEnv class

    main

    The AlohaEnv class is a Gymnasium-compatible environment for ALOHA robotic tasks. It is initialized with a specific task name and observation configuration.

    Initialization Parameters

    • task (str): The name of the task to perform. Supported tasks include:
      • transfer_cube
      • insertion
      • end_effector_transfer_cube (Note: may raise NotImplementedError depending on version)
      • end_effector_insertion (Note: may raise NotImplementedError depending on version)
    • obs_type (str): Defines the observation format. Options:
      • pixels: Returns a dictionary containing a top camera image.
      • pixels_agent_pos: Returns a dictionary containing pixels (with a top camera image) and agent_pos (joint positions).
      • state: Currently not implemented (raises NotImplementedError).
    • render_mode (str): The mode for rendering. Currently supports rgb_array.
    • observation_width / observation_height (int): Dimensions for the observation images.
    • visualization_width / visualization_height (int): Dimensions for the rendered visualization images.
    from gym_aloha.env import AlohaEnv
    
    env = AlohaEnv(
        task="transfer_cube",
        obs_type="pixels_agent_pos",
        render_mode="rgb_array",
        observation_width=640,
        observation_height=480
    )