#
Aria

##
Overview

The Aria model was proposed in Aria: An Open Multimodal Native Mixture-of-Experts Model by Li et al. from the Rhymes.AI team.

Aria is an open multimodal-native model with best-in-class performance across a wide range of multimodal, language, and coding tasks. It has a Mixture-of-Experts architecture, with respectively 3.9B and 3.5B activated parameters per visual token and text token.

The abstract from the paper is the following:

Information comes in diverse modalities. Multimodal native AI models are essential to integrate real-world information and deliver comprehensive understanding. While proprietary multimodal native models exist, their lack of openness imposes obstacles for adoptions, let alone adaptations. To fill this gap, we introduce Aria, an open multimodal native model with best-in-class performance across a wide range of multimodal, language, and coding tasks. Aria is a mixture-of-expert model with 3.9B and 3.5B activated parameters per visual token and text token, respectively. It outperforms Pixtral-12B and Llama3.2-11B, and is competitive against the best proprietary models on various multimodal tasks. We pre-train Aria from scratch following a 4-stage pipeline, which progressively equips the model with strong capabilities in language understanding, multimodal understanding, long context window, and instruction following. We open-source the model weights along with a codebase that facilitates easy adoptions and adaptations of Aria in real-world applications.

This model was contributed by m-ric. The original code can be found here.

##
Usage tips

Here’s how to use the model for vision tasks:

    import requests
    import torch
    from PIL import Image

    from transformers import AriaProcessor, AriaForConditionalGeneration

    model_id_or_path = "rhymes-ai/Aria"

    model = AriaForConditionalGeneration.from_pretrained(
        model_id_or_path, device_map="auto"
    )

    processor = AriaProcessor.from_pretrained(model_id_or_path)

    image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "image"},
                {"text": "what is the image?", "type": "text"},
            ],
        }
    ]

    text = processor.apply_chat_template(messages, add_generation_prompt=True)
    inputs = processor(text=text, images=image, return_tensors="pt")
    inputs.to(model.device)

    output = model.generate(
        **inputs,
        max_new_tokens=15,
        stop_strings=["<|im_end|>"],
        tokenizer=processor.tokenizer,
        do_sample=True,
        temperature=0.9,
    )
    output_ids = output[0][inputs["input_ids"].shape[1]:]
    response = processor.decode(output_ids, skip_special_tokens=True)

##
AriaImageProcessor

###
class transformers.AriaImageProcessor

< source >

( image_mean: typing.Optional[typing.List[float]] = None image_std: typing.Optional[typing.List[float]] = None max_image_size: int = 980 min_image_size: int = 336 split_resolutions: typing.Optional[typing.List[typing.Tuple[int, int]]] = None split_image: typing.Optional[bool] = False do_convert_rgb: typing.Optional[bool] = True do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: typing.Optional[bool] = True resample: Resampling = <Resampling.BICUBIC: 3> **kwargs )

Parameters

- image_mean (`list`, optional, defaults to [0.5, 0.5, 0.5]) — Mean values for normalization.
- image_std (`list`, optional, defaults to [0.5, 0.5, 0.5]) — Standard deviation values for normalization.
- max_image_size (`int`, optional, defaults to 980) — Maximum image size.
- min_image_size (`int`, optional, defaults to 336) — Minimum image size.
- split_resolutions (`list`, optional, defaults to a list of optimal,resolutions as tuples) — The optimal resolutions for splitting the image.
- split_image (`bool`, optional, defaults to `False`) — Whether to split the image.
- do_convert_rgb (`bool`, optional, defaults to `True`) — Whether to convert the image to RGB.
- do_rescale (`bool`, optional, defaults to `True`) — Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in the `preprocess` method.
- rescale_factor (`int` or `float`, optional, defaults to `1/255`) — Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess` method.
- do_normalize (`bool`, optional, defaults to `True`) — Whether to normalize the image.
- resample (PILImageResampling, optional, defaults to `BICUBIC`) — The resampling filter to use if resizing the image.

A vision processor for the Aria model that handles image preprocessing. Initialize the AriaImageProcessor.

####
get_image_patches

< source >

( image: <built-in function array> grid_pinpoints: typing.List[typing.Tuple[int, int]] patch_size: int resample: Resampling data_format: ChannelDimension input_data_format: ChannelDimension ) →
`List[np.array]`

Parameters

- image (`np.array`) — The input image to be processed.
- grid_pinpoints (List[Tuple[int, int]]) — A list of possible resolutions as tuples.
- patch_size (`int`) — Size of the patches to divide the image into.
- resample (`PILImageResampling`) — Resampling filter to use if resizing the image.
- data_format (`ChannelDimension` or `str`) — The channel dimension format for the output image.
- input_data_format (`ChannelDimension` or `str`) — The channel dimension format of the input image.

Returns

`List[np.array]`

A list of NumPy arrays containing the processed image patches.

Process an image with variable resolutions by dividing it into patches.

####
pad

< source >

( image: ndarray padding: typing.Union[int, typing.Tuple[int, int], typing.Iterable[typing.Tuple[int, int]]] mode: PaddingMode = <PaddingMode.CONSTANT: 'constant'> constant_values: typing.Union[float, typing.Iterable[float]] = 0.0 data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None ) →
`np.ndarray`

Parameters

- image (`np.ndarray`) — The image to pad.
- padding (`int` or `Tuple[int, int]` or `Iterable[Tuple[int, int]]`) — Padding to apply to the edges of the height, width axes. Can be one of three formats:
  - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis.
  - `((before, after),)` yields same before and after pad for height and width.
  - `(pad,)` or int is a shortcut for before = after = pad width for all axes.
- mode (`PaddingMode`) — The padding mode to use. Can be one of:
  - `"constant"`: pads with a constant value.
  - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.
  - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis.
  - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array.
- constant_values (`float` or `Iterable[float]`, optional) — The value to use for the padding if `mode` is `"constant"`.
- data_format (`str` or `ChannelDimension`, optional) — The channel dimension format for the output image. Can be one of:
  - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use same as the input image.
- input_data_format (`str` or `ChannelDimension`, optional) — The channel dimension format for the input image. Can be one of:
  - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use the inferred format of the input image.

Returns

`np.ndarray`

The padded image.

Pads the `image` with the specified `padding` and `mode`. Padding can be in the (`height`, `width`) dimension of in the (`num_patches`) dimension. In the second case an iterable if tuples is expected as input.

####
preprocess

< source >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], typing.List[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]]] image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None max_image_size: typing.Optional[int] = None min_image_size: typing.Optional[int] = None split_image: typing.Optional[bool] = None do_convert_rgb: typing.Optional[bool] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None resample: Resampling = None return_tensors: typing.Union[transformers.utils.generic.TensorType, str, NoneType] = 'pt' data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None ) →
BatchFeature

Parameters

- images (ImageInput or list of ImageInput) — The input image or a list of images.
- image_mean (`list`, optional, defaults to [0.5, 0.5, 0.5]) — Mean values for normalization.
- image_std (`list`, optional, defaults to [0.5, 0.5, 0.5]) — Standard deviation values for normalization.
- max_image_size (`int`, optional, defaults to `self.max_image_size` (980)) — Maximum image size.
- min_image_size (`int`, optional, defaults to `self.min_image_size` (336)) — Minimum image size.
- split_image (`bool`, optional, defaults to `self.split_image` (False)) — Whether to split the image.
- do_convert_rgb (`bool`, optional, defaults to `self.do_convert_rgb` (True)) — Whether to convert the image to RGB.
- do_rescale (`bool`, optional, defaults to `self.do_rescale`) — Whether to rescale the image.
- rescale_factor (`float`, optional, defaults to `self.rescale_factor`) — Rescale factor to rescale the image by if `do_rescale` is set to `True`.
- do_normalize (`bool`, optional, defaults to `self.do_normalize` (True)) — Whether to normalize the image.
- resample (PILImageResampling, optional, defaults to `self.resample` (BICUBIC)) — The resampling filter to use if resizing the image.
- return_tensors (`str` or `TensorType`, optional, defaults to “pt”) — The type of tensor to return.
- data_format (`str` or `ChannelDimension`, optional) — The channel dimension format for the output image. Can be one of:
  - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use same as the input image.
- input_data_format (`str` or `ChannelDimension`, optional) — The channel dimension format for the input image. Can be one of:
  - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use the inferred format of the input image.

Returns

BatchFeature

A BatchFeature object containing:

- ‘pixel_values’: Tensor of processed image pixel values.
- ‘pixel_mask’: Boolean pixel mask. This mask is a 2D tensor of shape (max_image_size, max_image_size) where:
  - True (1) values indicate pixels that belong to the original resized image.
  - False (0) values indicate pixels that are part of the padding. The mask helps distinguish between actual image content and padded areas in subsequent processing steps.
- ‘num_crops’: The maximum number of crops across all images.

Process a list of images.

##
AriaProcessor

###
class transformers.AriaProcessor

< source >

( image_processor = None tokenizer: typing.Union[transformers.models.auto.tokenization_auto.AutoTokenizer, str] = None chat_template: typing.Optional[str] = None size_conversion: typing.Optional[typing.Dict[typing.Union[float, int], int]] = None )

Parameters

- image_processor (`AriaImageProcessor`, optional) — The AriaImageProcessor to use for image preprocessing.
- tokenizer (`PreTrainedTokenizerBase`, optional) — An instance of PreTrainedTokenizerBase. This should correspond with the model’s text model. The tokenizer is a required input.
- chat_template (`str`, optional) — A Jinja template which will be used to convert lists of messages in a chat into a tokenizable string.
- size_conversion (`Dict`, optional) — A dictionary indicating size conversions for images.

AriaProcessor is a processor for the Aria model which wraps the Aria image preprocessor and the LLama slow tokenizer.

####
batch_decode

< source >

( *args **kwargs )

This method forwards all its arguments to LlamaTokenizerFast’s batch_decode(). Please refer to the docstring of this method for more information.

####
decode

< source >

( *args **kwargs )

This method forwards all its arguments to LlamaTokenizerFast’s decode(). Please refer to the docstring of this method for more information.

##
AriaTextConfig

###
class transformers.AriaTextConfig

< source >

( vocab_size = 32000 hidden_size = 4096 intermediate_size: int = 4096 num_hidden_layers = 32 num_attention_heads = 32 num_key_value_heads = None hidden_act = 'silu' max_position_embeddings = 2048 initializer_range = 0.02 rms_norm_eps = 1e-06 use_cache = True pad_token_id = 2 bos_token_id = 1 eos_token_id = 2 pretraining_tp = 1 tie_word_embeddings = False rope_theta = 10000.0 rope_scaling = None attention_bias = False attention_dropout = 0.0 mlp_bias = False head_dim = None moe_num_experts: int = 8 moe_topk: int = 2 moe_num_shared_experts: int = 2 **kwargs )

Parameters

- vocab_size (`int`, optional, defaults to 32000) — Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling LlamaModel
- hidden_size (`int`, optional, defaults to 4096) — Dimension of the hidden representations.
- intermediate_size (`int`, optional, defaults to 4096) — The size of the MLP representations.
- num_hidden_layers (`int`, optional, defaults to 32) — Number of hidden layers in the Transformer decoder.
- num_attention_heads (`int`, optional, defaults to 32) — Number of attention heads for each attention layer in the Transformer decoder.
- num_key_value_heads (`int`, optional) — This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details checkout this paper. If it is not specified, will default to `num_attention_heads`.
- hidden_act (`str` or `function`, optional, defaults to `"silu"`) — The non-linear activation function (function or string) in the decoder.
- max_position_embeddings (`int`, optional, defaults to 2048) — The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens, Llama 2 up to 4096, CodeLlama up to 16384.
- initializer_range (`float`, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
- rms_norm_eps (`float`, optional, defaults to 1e-06) — The epsilon used by the rms normalization layers.
- use_cache (`bool`, optional, defaults to `True`) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`.
- pad_token_id (`int`, optional, defaults to 2) — Padding token id.
- bos_token_id (`int`, optional, defaults to 1) — Beginning of stream token id.
- eos_token_id (`int`, optional, defaults to 2) — End of stream token id.
- pretraining_tp (`int`, optional, defaults to 1) — Experimental feature. Tensor parallelism rank used during pretraining. Please refer to this document to understand more about it. This value is necessary to ensure exact reproducibility of the pretraining results. Please refer to this issue.
- tie_word_embeddings (`bool`, optional, defaults to `False`) — Whether to tie weight embeddings
- rope_theta (`float`, optional, defaults to 10000.0) — The base period of the RoPE embeddings.
- rope_scaling (`Dict`, optional) — Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of [‘default’, ‘linear’, ‘dynamic’, ‘yarn’, ‘longrope’, ‘llama3’], with ‘default’ being the original RoPE implementation. `factor` (`float`, optional): Used with all rope types except ‘default’. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x original maximum pre-trained length. `original_max_position_embeddings` (`int`, optional): Used with ‘dynamic’, ‘longrope’ and ‘llama3’. The original max position embeddings used during pretraining. `attention_factor` (`float`, optional): Used with ‘yarn’ and ‘longrope’. The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. `beta_fast` (`float`, optional): Only used with ‘yarn’. Parameter to set the boundary for extrapolation (only) in the linear ramp function. If unspecified, it defaults to 32. `beta_slow` (`float`, optional): Only used with ‘yarn’. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. `short_factor` (`List[float]`, optional): Only used with ‘longrope’. The scaling factor to be applied to short contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `long_factor` (`List[float]`, optional): Only used with ‘longrope’. The scaling factor to be applied to long contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `low_freq_factor` (`float`, optional): Only used with ‘llama3’. Scaling factor applied to low frequency components of the RoPE `high_freq_factor` (`float`, optional*): Only used with ‘llama3’. Scaling factor applied to high frequency components of the RoPE
- attention_bias (`bool`, optional, defaults to `False`) — Whether to use a bias in the query, key, value and output projection layers during self-attention.
- attention_dropout (`float`, optional, defaults to 0.0) — The dropout ratio for the attention probabilities.
- mlp_bias (`bool`, optional, defaults to `False`) — Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
- head_dim (`int`, optional) — The attention head dimension. If None, it will default to hidden_size // num_heads
- moe_num_experts (`int`, optional, defaults to 8) — The number of experts in the MoE layer.
- moe_topk (`int`, optional, defaults to 2) — The number of top experts to route to for each token.
- moe_num_shared_experts (`int`, optional, defaults to 2) — The number of shared experts.

This class handles the configuration for the text component of the Aria model. Instantiating a configuration with the defaults will yield a similar configuration to that of the model of the Aria rhymes-ai/Aria architecture. This class extends the LlamaConfig to include additional parameters specific to the Mixture of Experts (MoE) architecture.

##
AriaConfig

###
class transformers.AriaConfig

< source >

( vision_config = None vision_feature_layer: int = -1 text_config: AriaTextConfig = None projector_patch_to_query_dict: typing.Optional[typing.Dict] = None image_token_index: int = 9 initializer_range: float = 0.02 **kwargs )

Parameters

- vision_config (`AriaVisionConfig` or `dict`, optional) — Configuration for the vision component.
- vision_feature_layer (`int`, optional, defaults to -1) — The index of the layer to select the vision feature.
- text_config (`AriaTextConfig` or `dict`, optional) — Configuration for the text component.
- projector_patch_to_query_dict (`dict`, optional) — Mapping of patch sizes to query dimensions.
- image_token_index (`int`, optional, defaults to 9) — Index used to represent image tokens.
- initializer_range (`float`, optional, defaults to 0.02) — The standard deviation of the truncated normal initializer for initializing all weight matrices.
- model_type (`str`) — Type of the model, set to `"aria"`.
- image_token_index (`int`) — Index used to represent image tokens.
- projector_patch_to_query_dict (`dict`) — Mapping of patch sizes to query dimensions.
- vision_config (`AriaVisionConfig`) — Configuration for the vision component.
- text_config (`AriaTextConfig`) — Configuration for the text component.

This class handles the configuration for both vision and text components of the Aria model, as well as additional parameters for image token handling and projector mapping. Instantiating a configuration with the defaults will yield a similar configuration to that of the model of the Aria rhymes-ai/Aria architecture.

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

##
AriaTextModel

###
class transformers.AriaTextModel

< source >

( config: AriaTextConfig )

Parameters

- config (AriaTextConfig) — 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 Aria Text Model outputting raw hidden-states without any specific head on to.

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

< source >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[transformers.cache_utils.Cache] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None **flash_attn_kwargs: typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs] ) →
transformers.modeling_outputs.BaseModelOutputWithPast or `tuple(torch.FloatTensor)`

Parameters

- input_ids (`torch.LongTensor` 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?

- 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?

- past_key_values (`~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 `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

  Two formats are allowed:

  - a Cache instance, see our kv cache guide;
  - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy cache format.

  The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned.

  If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don’t have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

- inputs_embeds (`torch.FloatTensor` 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.
- use_cache (`bool`, optional) — If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`).
- output_attentions (`bool`, optional) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
- output_hidden_states (`bool`, optional) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.

Returns

transformers.modeling_outputs.BaseModelOutputWithPast or `tuple(torch.FloatTensor)`

A transformers.modeling_outputs.BaseModelOutputWithPast or a tuple of `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the configuration (AriaConfig) and inputs.

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

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

- past_key_values (`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 `past_key_values` input) to speed up sequential decoding.

- hidden_states (`tuple(torch.FloatTensor)`, optional, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) — Tuple of `torch.FloatTensor` (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.FloatTensor)`, optional, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) — Tuple of `torch.FloatTensor` (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.

The AriaTextModel 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.

##
AriaModel

###
class transformers.AriaModel

< source >

( config: AriaConfig )

Parameters

- config (AriaConfig) — 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 Aria model which consists of a vision backbone and a language model, without a language modeling head.

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

< source >

( input_ids: LongTensor = None pixel_values: FloatTensor = None pixel_mask: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None **kwargs: typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs] ) →
`transformers.models.aria.modeling_aria.AriaModelOutputWithPast` or `tuple(torch.FloatTensor)`

Parameters

- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`) — 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.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`) — 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).
- pixel_mask (`torch.LongTensor` of shape `(batch_size, height, width)`) — Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:
  - 1 for pixels that are real (i.e. not masked),
  - 0 for pixels that are padding (i.e. masked).

  What are attention masks?

- 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?

- past_key_values (`List[torch.FloatTensor]`, 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 `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

  Two formats are allowed:

  - a Cache instance, see our kv cache guide;
  - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy cache format.

  The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned.

  If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don’t have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

- inputs_embeds (`torch.FloatTensor` 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.
- use_cache (`bool`, optional) — If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`).
- output_attentions (`bool`, optional) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
- output_hidden_states (`bool`, optional) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.
- return_dict (`bool`, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.

Returns

`transformers.models.aria.modeling_aria.AriaModelOutputWithPast` or `tuple(torch.FloatTensor)`

A `transformers.models.aria.modeling_aria.AriaModelOutputWithPast` or a tuple of `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the configuration (AriaConfig) and inputs.

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

- past_key_values (`tuple(tuple(torch.FloatTensor))`, optional, returned when `use_cache=True` is passed or when `config.use_cache=True`) — Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

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

- hidden_states (`tuple(torch.FloatTensor)`, optional, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) — Tuple of `torch.FloatTensor` (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.FloatTensor)`, optional, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) — Tuple of `torch.FloatTensor` (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.

- image_hidden_states (`torch.FloatTensor`, optional) — A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.

The AriaModel 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.

####
get_image_features

< source >

( pixel_values: FloatTensor pixel_mask: FloatTensor = None vision_feature_layer: int = -1 ) →
image_features (`torch.Tensor`)

Parameters

- pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`) — The tensors corresponding to the input images.
- pixel_mask (`torch.FloatTensor]`, optional) — The tensors corresponding to the input image mask.
- vision_feature_layer (`Union[int, List[int]]`) — The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the corresponding indices will be concatenated to form the vision features.

Returns

image_features (`torch.Tensor`)

Image feature tensor of shape `(num_images, image_length, embed_dim)`).

Obtains image last hidden states from the vision tower and apply multimodal projection.

##
AriaTextForCausalLM

###
class transformers.AriaTextForCausalLM

< source >

( config: AriaTextConfig )

Parameters

- config (AriaTextConfig) — 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 Aria Model for causal language modeling.

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

< source >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[transformers.cache_utils.Cache] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs: typing_extensions.Unpack[transformers.models.aria.modeling_aria.KwargsForCausalLM] ) →
transformers.modeling_outputs.CausalLMOutputWithPast or `tuple(torch.FloatTensor)`

Parameters

- input_ids (`torch.LongTensor` 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?

- 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?

- past_key_values (`~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 `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

  Two formats are allowed:

  - a Cache instance, see our kv cache guide;
  - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy cache format.

  The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned.

  If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don’t have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

- inputs_embeds (`torch.FloatTensor` 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.
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, optional) — Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
- use_cache (`bool`, optional) — If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`).
- output_attentions (`bool`, optional) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
- output_hidden_states (`bool`, optional) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
- logits_to_keep (`Union[int, torch.Tensor]`, defaults to `0`) — If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).

Returns

transformers.modeling_outputs.CausalLMOutputWithPast or `tuple(torch.FloatTensor)`

A transformers.modeling_outputs.CausalLMOutputWithPast or a tuple of `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the configuration (AriaConfig) and inputs.

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

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

- past_key_values (`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 `past_key_values` input) to speed up sequential decoding.

- hidden_states (`tuple(torch.FloatTensor)`, optional, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) — Tuple of `torch.FloatTensor` (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.FloatTensor)`, optional, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) — Tuple of `torch.FloatTensor` (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.

The AriaTextForCausalLM 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.

Example:

    >>> from transformers import AutoTokenizer, AriaTextForCausalLM

    >>> model = AriaTextForCausalLM.from_pretrained("meta-aria_text/AriaText-2-7b-hf")
    >>> tokenizer = AutoTokenizer.from_pretrained("meta-aria_text/AriaText-2-7b-hf")

    >>> prompt = "Hey, are you conscious? Can you talk to me?"
    >>> inputs = tokenizer(prompt, return_tensors="pt")

    >>> # Generate
    >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
    >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
    "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."

##
AriaForConditionalGeneration

###
class transformers.AriaForConditionalGeneration

< source >

( config: AriaConfig )

Parameters

- config (AriaConfig) — 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.

Aria model for conditional generation tasks.

This model combines a vision tower, a multi-modal projector, and a language model to perform tasks that involve both image and text inputs.

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

< source >

( input_ids: LongTensor = None pixel_values: FloatTensor = None pixel_mask: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 cache_position: typing.Optional[torch.LongTensor] = None **kwargs: typing_extensions.Unpack[transformers.models.aria.modeling_aria.KwargsForCausalLM] ) →
`transformers.models.aria.modeling_aria.AriaCausalLMOutputWithPast` or `tuple(torch.FloatTensor)`

Parameters

- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`) — 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.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`) — 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).
- pixel_mask (`torch.LongTensor` of shape `(batch_size, height, width)`) — Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:
  - 1 for pixels that are real (i.e. not masked),
  - 0 for pixels that are padding (i.e. masked).

  What are attention masks?

- 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?

- past_key_values (`List[torch.FloatTensor]`, 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 `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

  Two formats are allowed:

  - a Cache instance, see our kv cache guide;
  - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy cache format.

  The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned.

  If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don’t have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

- inputs_embeds (`torch.FloatTensor` 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.
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, optional) — Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `AriaForConditionalGeneration`). Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
- use_cache (`bool`, optional) — If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`).
- output_attentions (`bool`, optional) — Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
- output_hidden_states (`bool`, optional) — Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.
- return_dict (`bool`, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
- logits_to_keep (`Union[int, torch.Tensor]`, defaults to `0`) — If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.

Returns

`transformers.models.aria.modeling_aria.AriaCausalLMOutputWithPast` or `tuple(torch.FloatTensor)`

A `transformers.models.aria.modeling_aria.AriaCausalLMOutputWithPast` or a tuple of `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the configuration (AriaConfig) and inputs.

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

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

- past_key_values (`tuple(tuple(torch.FloatTensor))`, optional, returned when `use_cache=True` is passed or when `config.use_cache=True`) — Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

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

- hidden_states (`tuple(torch.FloatTensor)`, optional, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) — Tuple of `torch.FloatTensor` (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.FloatTensor)`, optional, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) — Tuple of `torch.FloatTensor` (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.

- image_hidden_states (`torch.FloatTensor`, optional) — A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.

The AriaForConditionalGeneration 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.

Example:

    >>> import requests
    >>> import torch
    >>> from PIL import Image
    >>> from io import BytesIO

    >>> from transformers import AutoProcessor, AutoModel
    >>> from transformers.image_utils import load_image

    >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
    >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
    >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
    >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")

    >>> processor = AutoProcessor.from_pretrained("Rhymes-AI/Aria")
    >>> model = AutoModel.from_pretrained("Rhymes-AI/Aria", torch_dtype=torch.bfloat16, device_map="auto")

    >>> # Create inputs
    >>> messages = [
    ...     {
    ...         "role": "user",
    ...         "content": [
    ...             {"type": "image"},
    ...             {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."},
    ...             {"type": "image"},
    ...             {"type": "text", "text": "What can we see in this image?"},
    ...         ]
    ...     },
    ...     {
    ...         "role": "user",
    ...         "content": [
    ...             {"type": "image"},
    ...             {"type": "text", "text": "In which city is that bridge located?"},
    ...         ]
    ...     }
    ... ]

    >>> prompts = [processor.apply_chat_template([message], add_generation_prompt=True) for message in messages]
    >>> images = [[image1, image2], [image3]]
    >>> inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(model.device)

    >>> # Generate
    >>> generated_ids = model.generate(**inputs, max_new_tokens=256)
    >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

    >>> print(generated_texts[0])
    Assistant: There are buildings, trees, lights, and water visible in this image.

    >>> print(generated_texts[1])
    Assistant: The bridge is in San Francisco.

< > Update on GitHub