Transformers documentation

PI0.5

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

This model was published in HF papers on 2025-04-22 and contributed to Hugging Face Transformers on 2026-11-23.

FlashAttention SDPA

PI0.5

PI0.5 is a vision-language-action model for robot manipulation from Physical Intelligence. It keeps the PI0 layout: a PaliGemma backbone reads the camera images and the prompt, and a smaller Gemma action expert predicts a chunk of actions with flow matching.

PI0.5 changes two things compared to PI0:

  • The robot state is not projected into the action expert. The processor discretizes it into 256 bins and writes the bin indices into the text prompt (Task: ..., State: ...;\nAction:).
  • The action expert receives the denoising timestep through adaptive RMS norms. Each norm predicts a scale, a shift and a residual gate from the timestep embedding. The action tokens themselves only carry the noisy actions.

The processor normalizes the state and actions with the statistics of the dataset the checkpoint was trained on: mean and standard deviation, or the 1st and 99th percentiles. Pass them when creating the processor.

The original code can be found here. The checkpoints are the LeRobot ones, for example lerobot/pi05_base. LeRobot fine-tuned checkpoints, which store the weights under an extra model. prefix, load as well.

Usage examples

import torch

from transformers import PI05ForConditionalGeneration, PI05Processor
from transformers.image_utils import load_image


model = PI05ForConditionalGeneration.from_pretrained("lerobot/pi05_base", device_map="auto")
processor = PI05Processor.from_pretrained(
    "google/paligemma-3b-pt-224",
    state_q01=[-1.0] * 8,  # replace with the 1st percentile of your dataset's robot state
    state_q99=[1.0] * 8,  # replace with the 99th percentile of your dataset's robot state
)

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/vla_pi0.jpg")
state = torch.rand(1, 8) * 2 - 1  # replace with the robot state
inputs = processor(image, "Pick up the object", state=state, return_tensors="pt").to(model.device)

actions = model.sample_actions(**inputs, num_steps=10)
print(actions.shape)

PI05Config

class transformers.PI05Config

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevlm_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonedit_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonechunk_size: int = 50max_action_dim: int = 32num_inference_steps: int = 10time_sampling_beta_alpha: float = 1.5time_sampling_beta_beta: float = 1.0time_sampling_scale: float = 0.999time_sampling_offset: float = 0.001min_period: float = 0.004max_period: float = 4.0loss_reduction: str = 'mean' )

Parameters

  • vlm_config (Union[dict, ~configuration_utils.PreTrainedConfig], optional) — The config object or dictionary of the vision-language backbone.
  • dit_config (dict, optional) — Configuration for the action expert. Defaults to a Gemma 300M variant.
  • chunk_size (int, optional, defaults to 50) — Number of action steps to predict per chunk.
  • max_action_dim (int, optional, defaults to 32) — Maximum action vector dimension (shorter vectors are zero-padded).
  • num_inference_steps (int, optional, defaults to 10) — Number of denoising steps during inference.
  • time_sampling_beta_alpha (float, optional, defaults to 1.5) — Alpha parameter for Beta distribution used to sample diffusion time during training.
  • time_sampling_beta_beta (float, optional, defaults to 1.0) — Beta parameter for Beta distribution used to sample diffusion time during training.
  • time_sampling_scale (float, optional, defaults to 0.999) — Scale factor for sampled time values.
  • time_sampling_offset (float, optional, defaults to 0.001) — Offset added to sampled time values.
  • min_period (float, optional, defaults to 0.004) — Minimum period for sinusoidal time embedding.
  • max_period (float, optional, defaults to 4.0) — Maximum period for sinusoidal time embedding.
  • loss_reduction (str, optional, defaults to "mean") — The reduction to use on MSE loss.

This is the configuration class to store the configuration of a PI05Model. It is used to instantiate a Pi05 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the lerobot/pi05_base

Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.

Example:

>>> from transformers import PI05ForConditionalGeneration, PI05Config

>>> config = PI05Config()
>>> model = PI05ForConditionalGeneration(config)

PI05Processor

class transformers.PI05Processor

< >

( image_processor = Nonetokenizer = Nonechat_template = Nonestate_mean: list[float] | None = Nonestate_std: list[float] | None = Noneactions_mean: list[float] | None = Noneactions_std: list[float] | None = Nonestate_q01: list[float] | None = Nonestate_q99: list[float] | None = Noneactions_q01: list[float] | None = Noneactions_q99: list[float] | None = Nonemax_state_dim: int = 32chunk_size: int = 50**kwargs )

Parameters

  • image_processor (PI0ImageProcessor) — The image processor is a required input.
  • tokenizer (tokenizer_class) — The tokenizer is a required input.
  • chat_template (str) — A Jinja template to convert lists of messages in a chat into a tokenizable string.
  • state_mean (list[float], optional) — Dataset mean of the robot state. Required to process state unless state_q01 and state_q99 are set.
  • state_std (list[float], optional) — Dataset standard deviation of the robot state.
  • actions_mean (list[float], optional) — Dataset mean of the actions. Required to process actions unless actions_q01 and actions_q99 are set.
  • actions_std (list[float], optional) — Dataset standard deviation of the actions.
  • state_q01 (list[float], optional) — Dataset 1st percentile of the robot state. With state_q99, state is mapped to [-1, 1] by quantiles.
  • state_q99 (list[float], optional) — Dataset 99th percentile of the robot state.
  • actions_q01 (list[float], optional) — Dataset 1st percentile of the actions. With actions_q99, actions are mapped to [-1, 1] by quantiles.
  • actions_q99 (list[float], optional) — Dataset 99th percentile of the actions.
  • max_state_dim (int, optional, defaults to 32) — Size the actions are zero-padded to.
  • chunk_size (int, optional, defaults to 50) — Number of actions per chunk.

Constructs a PI05Processor which wraps a image processor and a tokenizer into a single processor.

PI05Processor offers all the functionalities of PI0ImageProcessor and tokenizer_class. See the ~PI0ImageProcessor and ~tokenizer_class for more information.

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]], list[list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]]], NoneType]text: str | list[str] | list[list[str]] | None = Noneactions: typing.Union[list, numpy.ndarray, torch.Tensor, NoneType] = Nonestate: typing.Union[list, numpy.ndarray, torch.Tensor, NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> ) → BatchFeature

Parameters

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], list[Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]], list[list[Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]]]], optional) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set do_rescale=False.
  • text (Union[str, list[str], list[list[str]]], optional) — The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If you pass a pretokenized input, set is_split_into_words=True to avoid ambiguity with batched inputs.
  • actions (list | np.ndarray | torch.Tensor, optional) — Actions to be predicted by the model. Normalized with the processor’s dataset statistics, then padded.
  • state (list | np.ndarray | torch.Tensor, optional) — Robot state. Normalized with the processor’s dataset statistics, then padded.
  • return_mm_token_type_ids (bool, kwargs) — Whether to return multimodal token type ids indicating multimodal placeholder token positions.
  • return_text_replacement_offsets (bool, kwargs) — Whether to return character offsets for each multimodal placeholder and its replacement.
  • return_tensors (str or TensorType, optional) — If set, will return tensors of a particular framework. Acceptable values are:
    • 'pt': Return PyTorch torch.Tensor objects.
    • 'np': Return NumPy np.ndarray objects.
  • **kwargs (ProcessingKwargs, optional) — Additional processing options for each modality (text, images, videos, audio). Model-specific parameters are listed above; see the TypedDict class for the complete list of supported arguments.

Returns

BatchFeature

A BatchFeature with the following fields:

  • input_ids — List of token ids to be fed to a model. Returned when text is not None. If suffix is provided, the input_ids will also contain the suffix input ids.
  • attention_mask — List of indices specifying which tokens should be attended to by the model (when return_attention_mask=True or if “attention_mask” is in self.model_input_names and if text is not None).
  • pixel_values — Pixel values to be fed to a model. Returned when images is not None.
  • pixel_attention_mask — Pixel values padding mask to be fed to a model. Returned when images is not None.
  • state — Robot state compatible with model if state is not None
  • actions — Label-actions compatible with training if actions is not None

PI05Model

class transformers.PI05Model

< >

( config: PI05Config )

Parameters

  • config (PI05Config) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

The bare Pi05 Model outputting raw hidden-states without any specific head on top.

This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

< >

( action_embeds: Tensorinput_ids: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonecache: transformers.cache_utils.Cache | None = None**kwargs ) → BaseModelOutputWithPast or tuple(torch.Tensor)

Parameters

  • action_embeds (torch.Tensor, optional) — Embeddings of the suffix tokens fed to the action expert.
  • input_ids (torch.Tensor of shape (batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    What are input IDs?

  • pixel_values (torch.Tensor of shape (batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using image_processor_class. See image_processor_class.__call__ for details (processor_class uses image_processor_class for processing images).
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    What are attention masks?

  • pixel_attention_mask (torch.Tensor, optional) — The mask indicating padded positions in the input image.
  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1].

    What are position IDs?

  • inputs_embeds (torch.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • cache (~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the cache returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no cache are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If cache are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

Returns

BaseModelOutputWithPast or tuple(torch.Tensor)

A BaseModelOutputWithPast or a tuple of torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (None) and inputs.

The PI05Model forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

  • last_hidden_state (torch.Tensor of shape (batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.

    If cache is used only the last hidden-state of the sequences of shape (batch_size, 1, hidden_size) is output.

  • cache (Cache, optional, returned when use_cache=True is passed or when config.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide.

    Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if config.is_encoder_decoder=True in the cross-attention blocks) that can be used (see cache input) to speed up sequential decoding.

  • hidden_states (tuple(torch.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.Tensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.

  • attentions (tuple(torch.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

embed_prefix

< >

( input_idspixel_valuespixel_attention_maskattention_mask = None )

PI05ForConditionalGeneration

class transformers.PI05ForConditionalGeneration

< >

( config: PI05Config )

Parameters

  • config (PI05Config) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

The Pi05 Model for token generation conditioned on other modalities (e.g. image-text-to-text generation).

This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonenoise: typing.Optional[torch.Tensor] = Nonetimestep: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonecache: transformers.cache_utils.Cache | None = Noneactions: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → CausalLMOutputWithPast or tuple(torch.Tensor)

Parameters

  • input_ids (torch.Tensor of shape (batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    What are input IDs?

  • pixel_values (torch.Tensor of shape (batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using PI0ImageProcessor. See PI0ImageProcessor.call() for details (PI05Processor uses PI0ImageProcessor for processing images).
  • noise (torch.Tensor, optional) — Noisy actions at the current timestep. Sampled from a normal distribution when actions are given.
  • timestep (torch.Tensor, optional) — Current denoising timestep.
  • pixel_attention_mask (torch.Tensor, optional) — The mask indicating padded positions in the input image.
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    What are attention masks?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1].

    What are position IDs?

  • inputs_embeds (torch.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • cache (~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the cache returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no cache are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If cache are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • actions (torch.Tensor, optional) — Input actions that need to be predicted. Used only when training to compute loss.

Returns

CausalLMOutputWithPast or tuple(torch.Tensor)

A CausalLMOutputWithPast or a tuple of torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (PI05Config) and inputs.

The PI05ForConditionalGeneration forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

  • loss (torch.Tensor of shape (1,), optional, returned when labels is provided) — Language modeling loss (for next-token prediction).

  • logits (torch.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

  • cache (Cache, optional, returned when use_cache=True is passed or when config.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide.

    Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see cache input) to speed up sequential decoding.

  • hidden_states (tuple(torch.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.Tensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.

  • attentions (tuple(torch.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

Example:

>>> from PIL import Image
>>> from transformers import AutoProcessor, PI05ForConditionalGeneration

>>> model = PI05ForConditionalGeneration.from_pretrained("lerobot/pi05_base")
>>> processor = AutoProcessor.from_pretrained("lerobot/pi05_base")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]

sample_actions

< >

( input_ids: LongTensorpixel_values: Tensornoise: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Nonenum_steps: int | None = None**kwargs )

Run flow matching inference to generate actions.

Update on GitHub