AllenAct Documentation

repository·main·Indexed 18 days ago

https://github.com/allenai/allenact

An open-source, modular learning framework for Embodied AI research using PyTorch. It supports on-policy algorithms (PPO, DD-PPO, A2C), Imitation Learning, DAgger, and offline training. The framework provides baseline experiments for BabyAI, MuJoCo Gym environments, and navigation tasks (ObjectNav and PointNav) in Habitat, RoboTHOR, and iTHOR.

Tokens
40.8K
Snippets
98
Records
135
Agent score
63%

What's inside AllenAct

  1. Overview of Distributed ObjectNav Training

    main

    This tutorial demonstrates how to scale training using DD-PPO (Distributed Data-Parallel Proximal Policy Optimization) to collect rollout data across multiple nodes.

    In the ObjectNav task, an agent must navigate to a target object of a known class (which may be unseen during training) and signal completion upon arrival. The distributed approach allows for massive parallelization of experience collection, significantly speeding up training by utilizing multiple GPUs and nodes simultaneously.

  2. Overview of AllenAct for Embodied AI Research

    main

    AllenAct is a modular and flexible learning framework specifically designed for Embodied AI research. It provides first-class support for various embodied environments, tasks, and algorithms, with a focus on PyTorch.

    Key capabilities include:

    • Decoupled Tasks and Environments: Researchers can implement multiple tasks within the same environment.
    • Algorithm Support: Includes on-policy algorithms (PPO, DD-PPO, A2C), Imitation Learning, DAgger, and offline training.
    • Sequential Training: Easy experimentation with sequences of training routines.
    • Simultaneous Losses: Ability to combine multiple losses (e.g., self-supervised loss with PPO loss) during training.
    • Multi-agent Support: Built-in support for multi-agent algorithms and tasks.
    • Visualizations: Integrated Tensorboard support for first/third-person views and intermediate model tensors.
    • Action Spaces: Supports both discrete and continuous action spaces.
  3. Understand the AllenAct codebase structure

    main

    The AllenAct repository is organized into several functional directories that separate core framework logic, environment plugins, datasets, and project-specific code:

    • allenact/: The core framework. Contains training/inference algorithms (allenact.algorithms), base abstractions (allenact.base_abstractions), and basic embodied AI models (allenact.embodiedai).
    • allenact_plugins/: Environment-specific implementations. Each plugin (e.g., {environment}_plugin) contains configs/, data/, and scripts/ for setting up that specific environment.
    • datasets/: Task-specific data storage. Includes scripts for automated downloading (e.g., download_navigation_datasets.sh).
    • projects/: Project-specific code, including experiment configurations and scripts for result processing or visualization.
    • pretrained_model_ckpts/: Storage for pretrained model checkpoints.
    • scripts/: Framework-wide utility scripts (e.g., documentation building, code formatting, running tests, or starting an xserver).
    • tests/: Unit tests for the allenact core.
  4. What is the PointNav task in AllenAct?

    main

    The Point Navigation (PointNav) task involves an agent spawning at a location in an environment (such as Habitat, RoboTHOR, or iTHOR) and moving toward a target position.

    Key mechanics:

    • Compass: The agent receives a 'compass' at every frame providing the distance and bearing to the target.
    • Termination: The agent executes an END action when it believes it has reached the target.
    • Success Condition: An episode is successful if the agent is within 0.2 meters of the target; otherwise, it is a failure.
    • Inputs: Models can be configured to use RGB, Depth, or RGBD inputs.
    • Algorithm: Baselines in this project are trained using the DD-PPO Reinforcement Learning algorithm.
  5. How VizSuite and visualization plugins work

    main

    Visualization in AllenAct is managed by the VizSuite class (defined in allenact.utils.viz_utils). You can customize visualizations by instantiating different visualization types as plugins to the VizSuite within your ExperimentConfig when in test mode.

    Data Sources

    VizSuite can pull data from several sources:

    • Task output: e.g., 2D trajectories.
    • Vector task: e.g., egocentric views.
    • Rollout storage: e.g., recurrent memory, taken action logprobs, episode masks.
    • ActorCriticOutput: e.g., action probabilities.

    Available Visualization Types

    • TrajectoryViz: Generic 2D trajectory view.
    • AgentViewViz: RGB egocentric view.
    • ActorViz: Action probabilities from ActorCriticOutput[CategoricalDistr].
    • TensorViz1D: Evolution of a 1D point from RolloutStorage over time.
    • TensorViz2D: Evolution of a 2D vector from RolloutStorage over time.
    • ThorViz: Specialized 2D trajectory view for RoboThor.

    To enable these, override the machine_params method in your ExperimentConfig to call res.set_visualizer(self.get_viz(mode)) when mode == "test".

    class PointNavRoboThorRGBPPOVizExperimentConfig(PointNavRoboThorRGBPPOExperimentConfig):
        viz_ep_ids = ["FloorPlan_Train1_1_3", "FloorPlan_Train1_1_4"]
        viz_video_ids = [["FloorPlan_Train1_1_3"], ["FloorPlan_Train1_1_4"]]
        viz: Optional[VizSuite] = None
    
        def get_viz(self, mode):
            if self.viz is not None:
                return self.viz
    
            self.viz = VizSuite(
                episode_ids=self.viz_ep_ids,
                mode=mode,
                base_trajectory=TrajectoryViz(path_to_target_location=("task_info", "target",)),
                egeocentric=AgentViewViz(max_video_length=100, episode_ids=self.viz_video_ids),
                action_probs=ActorViz(figsize=(3.25, 10), fontsize=18),
                taken_action_logprobs=TensorViz1D(),
                episode_mask=TensorViz1D(rollout_source=("masks",)),
                rnn_memory=TensorViz2D(rollout_source=("memory", "single_belief")),
                thor_trajectory=ThorViz(figsize=(16, 8), viz_rows_cols=(448, 448), scenes=("FloorPlan_Train{}_{}", 1, 1, 1, 1)),
            )
            return self.viz
    
        def machine_params(self, mode="train", **kwargs):
            res = super().machine_params(mode, **kwargs)
            if mode == "test":
                res.set_visualizer(self.get_viz(mode))
            return res
  6. Use the Builder pattern for deferred instantiation

    main

    AllenAct uses a Builder object to allow you to defer the instantiation of objects (like optimizers or LR schedulers) while passing configuration arguments to their initializers. This is useful within ExperimentConfig classes where you want to define how an object is created without creating it immediately.

    # Example of using Builder for an optimizer
    optimizer_builder=Builder(optim.Adam, dict(lr=2.5e-4))
    
    # Example of using Builder for a learning rate scheduler
    lr_scheduler_builder=Builder(LambdaLR, {"lr_lambda": LinearDecay(steps=ppo_steps)})
  7. Implement Actor-Critic and Off-Policy Losses

    main

    Losses are used to train models via back-propagation. allenact provides two main categories:

    1. Actor-Critic Losses: These compute a combination of action loss and value loss from collected experience. They are used for on-policy algorithms like PPO or A2C. These implement the AbstractActorCriticLoss class.
    2. Off-Policy Losses: These implement generic training iterations where a batch of data is passed through a model (or a subgraph of an ActorCriticModel) and a loss is computed on the output. These implement the AbstractOffPolicyLoss class.
  8. Define experiments using ExperimentConfig

    main

    In allenact, all experiments are defined by implementing the abstract ExperimentConfig class. This class serves as the central blueprint for an experiment. During training or inference, the system calls specific methods on your implementation to set up the environment, create models, and manage the lifecycle.

    Key methods include:

    • create_model: Called at the beginning of training to instantiate the model to be trained.
    • training_pipeline: Defines the sequence of training stages and how losses are applied.
  9. Understand ExperienceStorage for off-policy training

    main

    An ExperienceStorage manages data for training. In AllenAct, it serves two primary roles:

    1. Data Management: Similar to a PyTorch Dataset, it stores and manages relevant data.
    2. Batch Loading: Similar to a PyTorch DataLoader, it loads stored data into batches for loss computation.

    Unlike standard PyTorch datasets, ExperienceStorage can build its dataset at runtime by processing rollouts from an agent, which allows for implementing structures like experience replay in deep Q-learning. For fixed off-policy datasets, it acts as a collection of expert trajectories.

  10. Understand the PointNav task in RoboTHOR

    main

    Point Navigation (PointNav) is a task where an embodied agent must find a beacon in an environment. The agent receives the direction and Euclidean distance to the target. The goal is to learn to navigate complex human spaces (rooms, doors, hallways) rather than just moving in straight lines.

    In AllenAct, the simulator (like RoboTHOR) is wrapped in an Environment class abstraction, which provides a uniform interface for the agent to interact with the simulator via actions (e.g., "move forward", "turn left") and receive observations (frames).

  11. Define an experiment using ExperimentConfig

    main

    To define a complete experiment in allenact, you must implement the ExperimentConfig abstraction. This class encapsulates all configuration for training, validation, and testing. An OnPolicyRunner uses this config to orchestrate OnPolicyTrainer (for training) and OnPolicyInference (for validation/testing).

    Key methods to implement in your ExperimentConfig subclass:

    • tag(): Returns a str to identify the experiment.
    • create_model(**kwargs): Returns an nn.Module (the agent's actor-critic model).
    • make_sampler_fn(**kwargs): Returns a TaskSampler instance.
    • {train,valid,test}_task_sampler_args(...): Returns a dictionary of initialization parameters for the task samplers used in each phase.
    • machine_params(mode="train", **kwargs): Returns a dictionary specifying nprocesses and devices (e.g., GPU IDs).
    • training_pipeline(**kwargs): Returns a TrainingPipeline object describing losses, optimizers, and scheduling.
    class MiniGridTutorialExperimentConfig(ExperimentConfig):
        @classmethod
        def tag(cls) -> str:
            return "MiniGridTutorial"
    
        @classmethod
        def create_model(cls, **kwargs) -> nn.Module:
            # Return your model here
            pass
    
        @classmethod
        def make_sampler_fn(cls, **kwargs) -> TaskSampler:
            # Return your sampler here
            pass
    
        def train_task_sampler_args(self, ...) -> Dict[str, Any]:
            # Return training sampler args
            pass
    
        def machine_params(cls, mode="train", **kwargs) -> Dict[str, Any]:
            # Return hardware config
            pass
    
        @classmethod
        def training_pipeline(cls, **kwargs) -> TrainingPipeline:
            # Return pipeline config
            pass