imitation

repository·master·Indexed 23 days ago

https://github.com/humancompatibleai/imitation

A library providing clean, high-quality implementations of imitation learning and reward learning algorithms, including GAIL, AIRL, Behavioral Cloning (BC), DAgger, Density-Based Reward Modeling, Maximum Causal Entropy IRL, Deep RL from Human Preferences, and Soft Q Imitation Learning (SQIL). It includes tools for benchmarking, hyperparameter tuning via Sacred, and generating expert demonstrations.

Tokens
38.3K
Snippets
69
Records
170
Agent score
82%

What's inside imitation

  1. Overview of Imitation Learning algorithms in imitation

    master

    The imitation library provides modular PyTorch implementations of several imitation and reward learning algorithms designed to work with Stable Baselines 3 (SB3) policies.

    Supported algorithms include:

    • Behavioral Cloning (BC)
    • DAgger (with synthetic examples)
    • Density-based reward modeling
    • Maximum Causal Entropy Inverse Reinforcement Learning (MCE IRL)
    • Adversarial Inverse Reinforcement Learning (AIRL)
    • Generative Adversarial Imitation Learning (GAIL)
    • Deep RL from Human Preferences

    Key features:

    • SB3 Compatibility: Built on and compatible with Stable Baselines 3.
    • Modular Implementations: GAIL and AIRL allow for customizable reward and discriminator networks.
    • Demonstration Management: Includes scripts and data structures for loading, storing, and saving expert demonstrations (rollouts).
  2. Overview of imitation learning algorithms

    master

    The imitation library provides clean implementations of several imitation and reward learning algorithms. Algorithms are categorized by whether they support discrete or continuous action/state spaces.

    AlgorithmAPI DocsDiscreteContinuous
    Behavioral Cloningalgorithms.bc
    DAggeralgorithms.dagger
    Density-Based Reward Modelingalgorithms.density
    Maximum Causal Entropy IRLalgorithms.mce_irl
    Adversarial IRL (AIRL)algorithms.airl
    Generative Adversarial Imitation Learning (GAIL)algorithms.gail
    Deep RL from Human Preferencesalgorithms.preference_comparisons
    Soft Q Imitation Learning (SQIL)algorithms.sqil
  3. Understand the imitation library structure

    master

    The imitation library is organized into several functional subpackages located in src/imitation:

    • algorithms: Core implementation of imitation and reward learning algorithms.
    • data: Modules for collecting, storing, and manipulating transitions and trajectories.
    • envs: Test environments.
    • policies: Modules defining policies and manipulation methods (e.g., serialization).
    • regularization: Neural network weight regularization techniques.
    • rewards: Modules for building, serializing, and preprocessing neural network-based reward functions.
    • scripts: Command-line scripts for running experiments via Sacred.
    • util: Utility functions for logging, configurations, and neural network building.
  4. What is Density-Based Reward Modeling?

    master

    Density-based reward modeling is an Inverse Reinforcement Learning (IRL) technique that assigns higher rewards to states or state-action pairs that occur more frequently in expert demonstrations. It uses kernel density estimation to model the distribution of expert behavior and assigns rewards based on the estimated log-likelihood of the agent's actions under that distribution.

    Key Characteristics:

    • Goal: Incentivize the agent to take actions that resemble the expert's actions in similar states.
    • Limitations:
      • Assumes expert demonstrations are perfectly representative.
      • Does not provide an interpretable reward function.
      • Kernel density estimation scales poorly to high-dimensional state-action spaces.
  5. What is Soft Q Imitation Learning (SQIL)?

    master

    Soft Q Imitation Learning (SQIL) is an imitation learning algorithm that uses the DQN algorithm with modified rewards to imitate a policy from demonstrations.

    How it works: During each policy update, the training batch is split: half is sampled from expert demonstrations and half is sampled from the environment.

    • Expert demonstrations are assigned a reward of 1.
    • Environment transitions are assigned a reward of 0.

    This mechanism encourages the policy to imitate the demonstrations while simultaneously learning to avoid states not present in the expert data.

    Important Limitations:

    • This implementation is based on the Stable Baselines 3 DQN implementation.
    • It does not support continuous actions; it only supports discrete actions.
    • Because it relies on DQN, the term "soft" Q-learning in this specific implementation may be misleading as it does not implement true soft Q-learning.
  6. How Reward Network API modes differ

    master

    Reward networks in imitation support two distinct modes of operation:

    1. forward(state, action, next_state, done): Produces a reward that is differentiable. This is used during the training of the reward network (e.g., in GAIL or AIRL).
    2. predict_processed(...): Produces a reward used for training policies. This method applies post-processing (like normalization or shaping) that is not needed during reward network training. It is generally not used for gradient-based optimization of the reward network itself.
  7. Understand benchmark output structure

    master

    Training scripts use sacred to manage experiments. Outputs are organized into two main areas:

    1. Algorithm/Environment folders: Grouped by algorithm and environment name. These contain log files, model checkpoints, and a symlink to the sacred run folder.
    2. sacred folder: Contains all runs grouped by training script, with each run having a unique ID folder.

    Each run folder contains:

    • config.json: Hyperparameters used (includes environment.gym_id).
    • run.json: Run metadata, including result.imit_stats.monitor_return_mean (the score) and result.expert_stats.monitor_return_mean (the expert score).
    • cout.txt: Standard output of the run.
  8. How the Command Line Interface works with Sacred

    master

    The imitation.scripts package provides a CLI built on the Sacred library to run imitation learning algorithms and utility tasks.

    Key concepts:

    • Experiments: The core unit of execution.
    • Ingredients: Reusable components (like environments, expert policies, or reward functions) that have their own configuration namespaces.
    • Named Configurations: Pre-defined sets of configuration values (e.g., cartpole or seals_mountain_car) that can be passed to a script to set up an environment quickly.
    • Configuration Namespaces: Each ingredient (e.g., expert, demonstrations, environment) has its own namespace for setting parameters.

    To explore all available configuration values for a specific script, use the print_config command.

    python -m imitation.scripts.<script> print_config
  9. Understand the Trajectory data structure

    master

    In imitation, trajectories (also called rollouts or episodes) are sequences of observations and actions generated by an agent interacting with an environment. They are represented by the Trajectory dataclass.

    If your data includes rewards, use the TrajectoryWithRew subclass. Some algorithms may prefer individual Transitions instead of full trajectories, which can be obtained by flattening trajectories using imitation.data.rollout.flatten_trajectories.

    @dataclasses.dataclass(frozen=True)
    class Trajectory:
        obs: np.ndarray
        """Observations, shape (trajectory_len + 1, ) + observation_shape."""
    
        acts: np.ndarray
        """Actions, shape (trajectory_len, ) + action_shape."""
    
        infos: Optional[np.ndarray]
            """An array of info dicts, shape (trajectory_len, )."""
    
        terminal: bool
        """Does this trajectory (fragment) end in a terminal state?"""
  10. Avoid variable horizon environments for evaluation

    master

    In imitation, variable horizon environments (where episodes end based on a termination condition like success or failure rather than a fixed step count) are considered harmful for evaluating reward and imitation learning algorithms.

    Why this is a problem:

    • Information Leakage: Termination conditions act as a significant source of information about the reward. Algorithms can often learn to predict the reward simply by observing when an episode ends, rather than learning the actual task.
    • Inductive Bias: Different algorithms (like GAIL) may have biases toward certain reward signs, leading to illusory performance differences that don't translate to real-world tasks.

    Recommendation: Evaluate algorithms in fixed-horizon environments to ensure the agent relies on environment feedback and human guidance rather than the termination signal. Many MuJoCo tasks (like HalfCheetah) are naturally fixed-horizon, and other tasks can be converted using tools like the seals project.

  11. Use Reward Network Wrappers for shaping and normalization

    master

    Wrappers can modify reward network outputs. There are two types:

    • ForwardWrapper: Modifies the output of the forward method. These are applied first and must be differentiable because they are used during reward network learning (e.g., ShapedRewardNet for potential shaping).
    • PredictProcessedWrapper: Modifies the predict_processed call. These are used only when training/evaluating a policy and do not need to be differentiable.

    NormalizedRewardNet is a common PredictProcessedWrapper that uses a normalization layer (like RunningNorm) to standardize reward outputs, which helps stabilize RL training. Unlike Stable Baselines3's VecNormalize, it normalizes the reward output itself, not the observations or the returns.

    from imitation.rewards.reward_nets import NormalizedRewardNet
    from imitation.util.networks import RunningNorm
    
    train_reward_net = NormalizedRewardNet(
        reward_net,
        normalize_output_layer=RunningNorm,
    )