#
IDEFICS

##
Overview

The IDEFICS model was proposed in OBELICS: An Open Web-Scale Filtered Dataset of Interleaved Image-Text Documents by Hugo Laurençon, Lucile Saulnier, Léo Tronchon, Stas Bekman, Amanpreet Singh, Anton Lozhkov, Thomas Wang, Siddharth Karamcheti, Alexander M. Rush, Douwe Kiela, Matthieu Cord, Victor Sanh

The abstract from the paper is the following:

Large multimodal models trained on natural documents, which interleave images and text, outperform models trained on image-text pairs on various multimodal benchmarks that require reasoning over one or multiple images to generate a text. However, the datasets used to train these models have not been released, and the collection process has not been fully specified. We introduce the OBELICS dataset, an open web-scale filtered dataset of interleaved image-text documents comprising 141 million web pages extracted from Common Crawl, 353 million associated images, and 115 billion text tokens. We describe the dataset creation process, present comprehensive filtering rules, and provide an analysis of the dataset’s content. To show the viability of OBELISC, we train an 80 billion parameters vision and language model on the dataset and obtain competitive performance on various multimodal benchmarks. We release the code to reproduce the dataset along with the dataset itself.

This model was contributed by HuggingFaceM4. The original code can be found here. (TODO: don’t have a public link yet).

IDEFICS modeling code in Transformers is for finetuning and inferencing the pre-trained IDEFICS models.

To train a new IDEFICS model from scratch use the m4 codebase (a link will be provided once it’s made public)

##
IdeficsConfig

###
class transformers.IdeficsConfig

< source >

( vocab_size = 32000 additional_vocab_size = 0 hidden_size = 4096 intermediate_size = 11008 num_hidden_layers = 32 num_attention_heads = 32 dropout = 0.0 hidden_act = 'silu' initializer_range = 0.02 alpha_initializer = 'zeros' alphas_initializer_range = 0.0 alpha_type = 'float' rms_norm_eps = 1e-06 use_cache = True pad_token_id = 0 bos_token_id = 1 eos_token_id = 2 tie_word_embeddings = False cross_layer_interval = 1 qk_layer_norms = False freeze_text_layers = True freeze_text_module_exceptions = [] freeze_lm_head = False freeze_vision_layers = True freeze_vision_module_exceptions = [] use_resampler = False vision_config = None perceiver_config = None **kwargs )

Parameters

- additional_vocab_size (`int`, optional, defaults to 0) — Additional vocabulary size of the model, typically for the special ”” token. Additional vocab tokens are always trainable whereas regular vocab tokens can be frozen or not.
- vocab_size (`int`, optional, defaults to 32000) — Vocabulary size of the Idefics model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling ~IdeficsModel
- hidden_size (`int`, optional, defaults to 4096) — Dimension of the hidden representations.
- intermediate_size (`int`, optional, defaults to 11008) — Dimension of the MLP representations.
- num_hidden_layers (`int`, optional, defaults to 32) — Number of hidden layers in the Transformer encoder.
- num_attention_heads (`int`, optional, defaults to 32) — Number of attention heads for each attention layer in the Transformer encoder.
- dropout (`float`, optional, defaults to 0.0) — The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
- hidden_act (`str` or `function`, optional, defaults to `"silu"`) — The non-linear activation function (function or string) in the decoder.
- initializer_range (`float`, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
- alpha_initializer (`str`, optional, defaults to `"zeros"`) — Initialization type for the alphas.
- alphas_initializer_range (`float`, optional, defaults to 0.0) — The standard deviation of the truncated_normal_initializer for initializing the alphas in the Gated Cross Attention.
- alpha_type (`str`, optional, defaults to `"float"`) — Whether the gating alphas should be vectors or single floats.
- rms_norm_eps (`float`, optional, defaults to 1e-6) — 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 0) — 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.
- tie_word_embeddings(`bool`, optional, defaults to `False`) — Whether to tie weight embeddings
- cross_layer_interval (`int`, optional, default to 1) — Interval for cross attention (from text to image) layers.
- qk_layer_norms (`bool`, optional, defaults to `False`) — Whether to add layer norm after q and k
- freeze_text_layers (`bool`, optional, defaults to `True`) — Whether to freeze text layers
- freeze_text_module_exceptions (`bool`, optional, defaults to `[]`) — Exceptions to freezing text layers when `freeze_text_layers` is `True`
- freeze_lm_head (`bool`, optional, defaults to `False`) — Whether to freeze lm head
- freeze_vision_layers (`bool`, optional, defaults to `True`) — Whether to freeze vision layers
- freeze_vision_module_exceptions (`bool`, optional, defaults to `[]`) — Exceptions to freezing vision layers when `freeze_vision_layers` is `True`
- use_resampler (`bool`, optional, defaults to `False`) — Whether to use the Resampler
- vision_config (`IdeficsVisionConfig`, optional) — Custom vision config or dict
- perceiver_config (`IdeficsPerceiverConfig`, optional) — Custom perceiver config or dict

This is the configuration class to store the configuration of a IdeficsModel. It is used to instantiate an Idefics 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 Idefics-9B.

e.g. HuggingFaceM4/idefics-9b

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 IdeficsModel, IdeficsConfig

    >>> # Initializing a Idefics idefics-9b style configuration
    >>> configuration = IdeficsConfig()

    >>> # Initializing a model from the idefics-9b style configuration
    >>> model = IdeficsModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config

##
IdeficsModel

###
class transformers.IdeficsModel

< source >

( config: IdeficsConfig )

Parameters

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

The bare LLaMA 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.

Transformer decoder consisting of `config.num_hidden_layers` layers. Each layer is a `IdeficsDecoderLayer`

####
forward

< source >

( input_ids: 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 pixel_values: typing.Optional[torch.FloatTensor] = None image_encoder_embeddings: typing.Optional[torch.FloatTensor] = None perceiver_embeddings: typing.Optional[torch.FloatTensor] = None image_attention_mask: typing.Optional[torch.Tensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: typing.Optional[bool] = False return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None )

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 should you provide it.

  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?

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

  If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).

  If you want to change padding behavior, you should read `modeling_opt._prepare_decoder_attention_mask` and modify to your needs. See diagram 1 in the paper for more information on the default strategy.

  - 1 indicates the head is not masked,
  - 0 indicates the head is masked.
- 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 (`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)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

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

  If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don’t have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_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.

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

##
IdeficsForVisionText2Text

###
class transformers.IdeficsForVisionText2Text

< source >

( config vision_model = None )

####
forward

< source >

( input_ids: 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 pixel_values: typing.Optional[torch.FloatTensor] = None image_encoder_embeddings: typing.Optional[torch.FloatTensor] = None perceiver_embeddings: typing.Optional[torch.FloatTensor] = None image_attention_mask: typing.Optional[torch.Tensor] = 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 interpolate_pos_encoding: typing.Optional[bool] = False return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None ) →
`transformers.models.idefics.modeling_idefics.IdeficsCausalLMOutputWithPast` 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 should you provide it.

  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?

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

  If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).

  If you want to change padding behavior, you should read `modeling_opt._prepare_decoder_attention_mask` and modify to your needs. See diagram 1 in the paper for more information on the default strategy.

  - 1 indicates the head is not masked,
  - 0 indicates the head is masked.
- 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 (`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)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

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

  If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don’t have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_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.
- Args — 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]`.

Returns

`transformers.models.idefics.modeling_idefics.IdeficsCausalLMOutputWithPast` or `tuple(torch.FloatTensor)`

A `transformers.models.idefics.modeling_idefics.IdeficsCausalLMOutputWithPast` 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 (IdeficsConfig) 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 (`tuple(torch.FloatTensor)`, optional) — Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images, sequence_length, hidden_size)`.

  image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver

The IdeficsForVisionText2Text 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 AutoProcessor, IdeficsForVisionText2Text

    >>> model = IdeficsForVisionText2Text.from_pretrained("HuggingFaceM4/idefics-9b")
    >>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics-9b")

    >>> dogs_image_url_1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image1.jpeg"
    >>> dogs_image_url_2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image2.jpeg"

    >>> prompts = [
    ...     [
    ...         "User:",
    ...         dogs_image_url_1,
    ...         "Describe this image.\nAssistant: An image of two dogs.\n",
    ...         "User:",
    ...         dogs_image_url_2,
    ...         "Describe this image.\nAssistant:",
    ...     ]
    ... ]
    >>> inputs = processor(prompts, return_tensors="pt")
    >>> generate_ids = model.generate(**inputs, max_new_tokens=6)
    >>> processor.batch_decode(generate_ids, skip_special_tokens=True)

##
TFIdeficsModel

###
class transformers.TFIdeficsModel

< source >

( config: IdeficsConfig *inputs **kwargs )

####
call

< source >

( input_ids: TFModelInputType | None = None attention_mask: Optional[tf.Tensor] = None position_ids: Optional[tf.Tensor] = None past_key_values: Optional[List[tf.Tensor]] = None inputs_embeds: Optional[tf.Tensor] = None pixel_values: Optional[tf.Tensor] = None image_encoder_embeddings: Optional[tf.Tensor] = None perceiver_embeddings: Optional[tf.Tensor] = None image_attention_mask: Optional[tf.Tensor] = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None interpolate_pos_encoding: Optional[bool] = False return_dict: Optional[bool] = None training: Optional[bool] = None )

##
TFIdeficsForVisionText2Text

###
class transformers.TFIdeficsForVisionText2Text

< source >

( config vision_model = None **kwargs )

####
call

< source >

( input_ids: TFModelInputType | None = None attention_mask: Optional[tf.Tensor] = None position_ids: Optional[tf.Tensor] = None past_key_values: Optional[List[tf.Tensor]] = None inputs_embeds: Optional[tf.Tensor] = None pixel_values: Optional[tf.Tensor] = None image_encoder_embeddings: Optional[tf.Tensor] = None perceiver_embeddings: Optional[tf.Tensor] = None image_attention_mask: Optional[tf.Tensor] = None labels: Optional[tf.Tensor] = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None interpolate_pos_encoding: Optional[bool] = False return_dict: Optional[bool] = None training = False ) →
`transformers.models.idefics.modeling_tf_idefics.TFIdeficsCausalLMOutputWithPast` or `tuple(tf.Tensor)`

Parameters

- input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

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

  What are input IDs?

- attention_mask (`tf.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?

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

  If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).

  If you want to change padding behavior, you should read `modeling_opt._prepare_decoder_attention_mask` and modify to your needs. See diagram 1 in the paper for more information on the default strategy.

  - 1 indicates the head is not masked,
  - 0 indicates the head is masked.
- position_ids (`tf.Tensor` 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 (`tuple(tuple(tf.Tensor))`, optional, returned when `use_cache=True` is passed or when `config.use_cache=True`) — Tuple of `tuple(tf.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

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

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

- inputs_embeds (`tf.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.
- 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.
- Args — labels (`tf.Tensor` 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]`.

Returns

`transformers.models.idefics.modeling_tf_idefics.TFIdeficsCausalLMOutputWithPast` or `tuple(tf.Tensor)`

A `transformers.models.idefics.modeling_tf_idefics.TFIdeficsCausalLMOutputWithPast` or a tuple of `tf.Tensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the configuration (IdeficsConfig) and inputs.

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

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

- image_hidden_states (`tuple(tf.Tensor)`, optional) — Tuple of `tf.Tensor` (one for the output of the image embeddings, `(batch_size, num_images, sequence_length, hidden_size)`.

  image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver

The TFIdeficsForVisionText2Text 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, TFIdeficsForVisionText2Text

    >> model = TFIdeficsForVisionText2Text.from_pretrained("HuggingFaceM4/idefics-9b")
    >> tokenizer = AutoTokenizer.from_pretrained("HuggingFaceM4/idefics-9b")

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

    >> # 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 consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."

##
IdeficsImageProcessor

###
class transformers.IdeficsImageProcessor

< source >

( image_size: int = 224 image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None image_num_channels: typing.Optional[int] = 3 **kwargs )

Parameters

- image_size (`int`, optional, defaults to 224) — Resize to image size
- image_mean (`float` or `List[float]`, optional, defaults to `IDEFICS_STANDARD_MEAN`) — Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be overridden by the `image_mean` parameter in the `preprocess` method.
- image_std (`float` or `List[float]`, optional, defaults to `IDEFICS_STANDARD_STD`) — Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method. Can be overridden by the `image_std` parameter in the `preprocess` method.
- image_num_channels (`int`, optional, defaults to 3) — Number of image channels.

Constructs a Idefics image processor.

####
preprocess

< source >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] image_num_channels: typing.Optional[int] = 3 image_size: typing.Optional[typing.Dict[str, int]] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None transform: typing.Callable = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = <TensorType.PYTORCH: 'pt'> **kwargs )

Parameters

- images (`ImageInput`) — A list of images to preprocess.
- image_size (`int`, optional, defaults to `self.image_size`) — Resize to image size
- image_num_channels (`int`, optional, defaults to `self.image_num_channels`) — Number of image channels.
- image_mean (`float` or `List[float]`, optional, defaults to `IDEFICS_STANDARD_MEAN`) — Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be overridden by the `image_mean` parameter in the `preprocess` method.
- image_std (`float` or `List[float]`, optional, defaults to `IDEFICS_STANDARD_STD`) — Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method. Can be overridden by the `image_std` parameter in the `preprocess` method.
- transform (`Callable`, optional, defaults to `None`) — A custom transform function that accepts a single image can be passed for training. For example, `torchvision.Compose` can be used to compose multiple transforms. If `None` - an inference mode is assumed - and then a preset of inference-specific transforms will be applied to the images

Preprocess a batch of images.

##
IdeficsProcessor

###
class transformers.IdeficsProcessor

< source >

( image_processor tokenizer = None image_size = 224 add_end_of_utterance_token = None **kwargs )

Parameters

- image_processor (`IdeficsImageProcessor`) — An instance of IdeficsImageProcessor. The image processor is a required input.
- tokenizer (`LlamaTokenizerFast`) — An instance of LlamaTokenizerFast. The tokenizer is a required input.
- image_size (`int`, optional, defaults to 224) — Image size (assuming a square image)

Constructs a IDEFICS processor which wraps a LLama tokenizer and IDEFICS image processor into a single processor.

IdeficsProcessor offers all the functionalities of IdeficsImageProcessor and LlamaTokenizerFast. See the docstring of call() and `decode()` for more information.

####
__call__

< source >

( images = None text: typing.Union[str, typing.List[str], typing.List[typing.List[str]], typing.List[typing.List[typing.List[str]]]] = None audio = None videos = None **kwargs: typing_extensions.Unpack[transformers.models.idefics.processing_idefics.IdeficsProcessorKwargs] ) →
a dict with entries

Parameters

- images (`Union[PIL.Image, str, List[PIL.Image], List[str]]`) — either a single image or a batched list of images - can be passed in when text contains only text prompts, in order to use the image-text-to-text behavior.
- text (`Union[List[TextInput], [List[List[TextInput]]]]`) — either a single prompt or a batched list of prompts - see the detailed description immediately after the end of the arguments doc section.
- return_tensors (`str` or `TensorType`, optional, defaults to `TensorType.PYTORCH`) — The type of tensors to return. Can be one of:
  - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.

Returns

a dict with entries

`input_ids`, `attention_mask`, `pixel_values`, `image_attention_mask` which can be directly passed to `model.generate`

This method takes batched or non-batched prompts made of text and images and converts them into prompts that the model was trained on and prepares the image pixel values for the model to process.

Detailed explanation:

Each entry in `text` is either a text to be passed as is or an image that will be processed.

An image can be either an image object (`PIL.Image`) or a url from which the image can be retrieved.

When the processor encounters an image it’ll inject `<fake_token_around_image><image><fake_token_around_image>` entry into the prompt.

Example:

    checkpoint = "HuggingFaceM4/idefics-9b"
    processor = AutoProcessor.from_pretrained(checkpoint)
    url = "https://hips.hearstapps.com/hmg-prod/images/cute-photos-of-cats-in-grass-1593184777.jpg"
    img = processor.image_processor.fetch_images([url])[0]

    prompts = [
        "User:",
        img,
        "Describe this image.
    t: An image of two kittens in grass.

        "User:",
        "https://hips.hearstapps.com/hmg-prod/images/dog-puns-1581708208.jpg",
        "Describe this image.
    t:",
    ]

    inputs = processor(text=prompts, return_tensors="pt")
    generated_ids = model.generate(**inputs, max_length=100)
    generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]

In this example the `prompts` will be converted into:

    <s>User:<fake_token_around_image><image><fake_token_around_image>Describe this image.
    Assistant: An image of two kittens in grass.
    User:<fake_token_around_image><image><fake_token_around_image>Describe this image.
    Assistant:'

and the two images will be massaged using IdeficsImageProcessor.call() method and placed inside the `pixel_values` dict entry of the return value.

This example also examplifies that images can be passed as objects or as text urls. It can be seen that the first image is passed as object and the second one as a url.

To do training do:

    image_transform = transforms.Compose(
        [
            transforms.RandomResizedCrop(
                (w, h), scale=(0.9, 1.0), interpolation=transforms.InterpolationMode.BICUBIC
            ),
            transforms.ToTensor(),
            transforms.Normalize(mean=self.image_mean, std=self.image_std),
        ]
    )
    inputs = processor(text=prompts, transform=image_transform, return_tensors="pt")

In order to help debug prompt generation enable `debug=True` which will show you what’s happening.

< > Update on GitHub