pi-zero-pytorch

repository·main·Indexed 20 days ago

https://github.com/lucidrains/pi-zero-pytorch

A PyTorch framework for training robotic agents using the π0 architecture and Efficient Flow Policy Optimization (EFPO). It provides tools for online learning orchestration, real-time control (RTC) guidance, soft inpainting for action chunking, and utilities for downloading weights from HuggingFace or Google Cloud Storage. The model architecture is based on a PaliGemma 2B backbone and a Gemma Expert 300M component.

Tokens
15.9K
Snippets
52
Records
62
Agent score
69%

What's inside pi-zero-pytorch

  1. How EFPO orchestrates online learning

    main

    The EFPO class is a wrapper designed for online learning orchestration. It bridges the gap between the model (the agent) and the environment. Instead of manual training loops, EFPO provides high-level methods to:

    • gather_experience_from_env: Interacts with a provided environment object for a specified number of steps to collect data (memories).
    • learn_agent: Processes the collected memories to perform weight updates on the underlying model using a specified batch size.
  2. Perform online learning with EFPO

    main

    To orchestrate online learning, wrap your π0 model with the EFPO class. This allows you to gather experience from an environment and learn from those memories.

    Workflow

    1. Initialize EFPO: Pass your trained or untrained model to EFPO(model).
    2. Gather Experience: Use epo.gather_experience_from_env(env, steps=N) to collect memories from your environment.
    3. Learn: Use epo.learn_agent(memories, batch_size=N) to update the model using the gathered memories.
    from pi_zero_pytorch import π0, EFPO
    
    # 1. Initialize model
    model = π0(
        dim = 512,
        dim_action_input = 6,
        dim_joint_state = 12,
        num_tokens = 20_000
    )
    
    # 2. Setup environment (replace with your own environment)
    from pi_zero_pytorch.mock_env import Env
    mock_env = Env((256, 256), 2, 32, 1024, 12)
    
    # 3. Wrap model with EFPO
    epo = EFPO(model)
    
    # 4. Gather memories from environment
    memories = epo.gather_experience_from_env(mock_env, steps = 10)
    
    # 5. Learn from memories
    epo.learn_agent(memories, batch_size = 2)
  3. Set up development and testing environment

    main

    To contribute to the project, install the package with test dependencies and run the test suite:

    1. Install dependencies:
    $ pip install '.[test]' # or `uv pip install '.[test]'`
    1. Run tests: Add your tests to tests/test_pi_zero.py and execute:
    $ pytest tests/
  4. Monitor training progress via WebSockets

    main
    The application uses a WebSocket connection to /ws/training to receive real-time updates during training processes (both Value Network and Policy Network training). The setupTrainingSocket function initializes this connection. When a training_update message is received, the UI is updated with the current epoch, loss, and step details.
  5. How the Agent class manages Actor-Critic and Evolutionary Learning

    main

    The Agent class wraps a PiZero model and manages its training components. It initializes an actor (the policy) and a critic (the value function).

    Evolutionary Learning: If num_latent_genes > 1, the agent enables evolutionary learning by maintaining a LatentGenePool. This allows the agent to evolve latent representations. You can trigger a genetic algorithm step using take_genetic_algorithm_step_(fitnesses).

    Optimization: The agent maintains separate optimizers for the actor (actor_optim) and the critic (critic_optim), allowing for different learning rates and weight decay settings.

    from pi_zero_pytorch.pi_zero import Agent
    
    # Creating an agent with evolutionary capabilities
    agent = Agent(
        model=my_pi_zero_model,
        num_latent_genes=5,  # Enables evolutionary learning
        actor_lr=3e-4,
        critic_lr=3e-4,
        actor_fpo_loss_fn=torch.nn.functional.huber_loss
    )
    
    # Perform a genetic step if evolutionary learning is active
    agent.take_genetic_algorithm_step_(fitnesses=my_fitness_scores)
  6. How the PiZero forward pass works

    main

    The forward method is the primary entry point for both training and inference.

    • Inference Mode: If actions is not provided, it calls sample_actions internally.
    • Training Mode: If actions is provided, it performs flow matching by noising the actions with noise and calculating the target flow (actions - noise).
    • Inputs: Accepts vision (images), language (token_ids), joint states (joint_state), and optional conditioning like latents, reward_tokens, or task_id.
    • Output: Returns the predicted action flow. If return_actions_flow=True, it returns the flow explicitly.
  7. How the RECAP training workflow works

    main

    The π0 training pipeline follows a specific progression to move from general pretraining to task-specific mastery:

    1. Pretraining (pretrain): Train a base model on a large, diverse dataset to learn general world dynamics and capabilities.
    2. SFT (sft): Perform Supervised Fine-Tuning on a specific task using the pretrained weights. This creates a 'specialist' (stored in the task workspace under folder 0).
    3. Rollouts (gather_experience_from_env): Use the specialist to interact with an environment and collect new experiences. These are stored in data.N folders.
    4. RECAP Finetuning (recap_finetune): Use the collected rollout data to iteratively improve the specialist. This involves training a critic on the new data, recalculating advantages, and then training the actor. Each iteration creates a new version (folder 1, 2, etc.) in the task workspace.
  8. Understand the UI state and visibility logic

    main

    The Web UI manages several global states to control what is displayed to the user:

    • videos: List of available rollout files.
    • labels: A mapping of filename -> {task_completed, marked_timestep, returns, value, advantages, advantage_ids, invalidated}.
    • tasks: List of available tasks that can be assigned to episodes.
    • activeVideo: The currently selected video being inspected.
    • recapState: If enabled, the UI switches to 'RECAP mode', which focuses on folder-based labeling and task management.

    Visibility is dynamic: the main player, timeline, and charts are hidden if no video is active. The 'Rollouts' sidebar is visible if videos exist, while the 'Tasks' sidebar is only visible in RECAP mode when data is loaded.

  9. Visualize proprioception data

    main

    The Web UI supports visualizing proprioception data (e.g., joint states) associated with a video.

    1. Fetching: The UI calls /api/video/${filename}/proprio to retrieve a 2D array of shape [T, D] and dimension names.
    2. Navigation: Users can cycle through different dimensions (e.g., different joints) using the proprio-prev and proprio-next buttons.
    3. Visualization: Each dimension is rendered as a time-series chart showing the value of that specific dimension over the duration of the video.
  10. Use the π0 model for training and inference

    main

    The π0 class implements the robotic foundation model architecture.

    Training

    During training, pass vision, commands, joint_state, and actions to the model. It returns a loss tensor.

    Inference (Sampling)

    After training, you can sample actions by providing vision, commands, and joint_state, and specifying a trajectory_length. This returns the sampled actions.

    Parameters

    • dim: Dimension of the model.
    • dim_action_input: Dimension of the action input.
    • dim_joint_state: Dimension of the joint state.
    • num_tokens: Number of tokens.
    import torch
    from pi_zero_pytorch import π0
    
    model = π0(
        dim = 512,
        dim_action_input = 6,
        dim_joint_state = 12,
        num_tokens = 20_000
    )
    
    vision = torch.randn(1, 1024, 512)
    commands = torch.randint(0, 20_000, (1, 1024))
    joint_state = torch.randn(1, 12)
    actions = torch.randn(1, 32, 6)
    
    # Training step
    loss, _ = model(vision, commands, joint_state, actions)
    loss.backward()
    
    # Inference/Sampling
    sampled_actions = model(vision, commands, joint_state, trajectory_length = 32) # (1, 32, 6)
  11. Sample action trajectories with `sample_actions`

    main

    Use sample_actions to generate a sequence of actions (a trajectory) from visual, language, and state inputs. This method implements a flow-matching sampling process (ODE integration).

    Key features:

    • Inpainting/Real-Time Chunking: If frozen_actions are provided, the model can perform inpainting to ensure the generated trajectory is consistent with already executed actions.
    • Classifier-Free Guidance (CFG): If reward_tokens are provided, you can use cond_scale to steer the sampling towards higher rewards.
    • Critic Support: If a critic module is passed, the method also returns predicted critic values for the sampled trajectory.
    • RTC Guidance: Supports Real-Time Chunking (RTC) guidance if rtc_guidance was configured during initialization.
    # Basic sampling
    actions = model.sample_actions(
        images=images,           # [b, nv, d] or [b, c, h, w]
        token_ids=token_ids,     # [b, nt]
        joint_states=joint_states, # [b, djs]
        trajectory_length=16,
        steps=18                 # Number of ODE steps
    )
    
    # Sampling with reward guidance and frozen actions (for chunking)
    actions, values = model.sample_actions(
        images=images,
        token_ids=token_ids,
        joint_states=joint_states,
        trajectory_length=16,
        frozen_actions=frozen_actions, # [b, nfa, da]
        reward_tokens=reward_tokens,    # [b, d]
        cond_scale=2.0,                # Guidance scale
        critic=critic_model             # Optional critic
    )