Transformers
  • 🌍GET STARTED
    • Transformers
    • Quick tour
    • Installation
  • 🌍TUTORIALS
    • Run inference with pipelines
    • Write portable code with AutoClass
    • Preprocess data
    • Fine-tune a pretrained model
    • Train with a script
    • Set up distributed training with BOINC AI Accelerate
    • Load and train adapters with BOINC AI PEFT
    • Share your model
    • Agents
    • Generation with LLMs
  • 🌍TASK GUIDES
    • 🌍NATURAL LANGUAGE PROCESSING
      • Text classification
      • Token classification
      • Question answering
      • Causal language modeling
      • Masked language modeling
      • Translation
      • Summarization
      • Multiple choice
    • 🌍AUDIO
      • Audio classification
      • Automatic speech recognition
    • 🌍COMPUTER VISION
      • Image classification
      • Semantic segmentation
      • Video classification
      • Object detection
      • Zero-shot object detection
      • Zero-shot image classification
      • Depth estimation
    • 🌍MULTIMODAL
      • Image captioning
      • Document Question Answering
      • Visual Question Answering
      • Text to speech
    • 🌍GENERATION
      • Customize the generation strategy
    • 🌍PROMPTING
      • Image tasks with IDEFICS
  • 🌍DEVELOPER GUIDES
    • Use fast tokenizers from BOINC AI Tokenizers
    • Run inference with multilingual models
    • Use model-specific APIs
    • Share a custom model
    • Templates for chat models
    • Run training on Amazon SageMaker
    • Export to ONNX
    • Export to TFLite
    • Export to TorchScript
    • Benchmarks
    • Notebooks with examples
    • Community resources
    • Custom Tools and Prompts
    • Troubleshoot
  • 🌍PERFORMANCE AND SCALABILITY
    • Overview
    • 🌍EFFICIENT TRAINING TECHNIQUES
      • Methods and tools for efficient training on a single GPU
      • Multiple GPUs and parallelism
      • Efficient training on CPU
      • Distributed CPU training
      • Training on TPUs
      • Training on TPU with TensorFlow
      • Training on Specialized Hardware
      • Custom hardware for training
      • Hyperparameter Search using Trainer API
    • 🌍OPTIMIZING INFERENCE
      • Inference on CPU
      • Inference on one GPU
      • Inference on many GPUs
      • Inference on Specialized Hardware
    • Instantiating a big model
    • Troubleshooting
    • XLA Integration for TensorFlow Models
    • Optimize inference using `torch.compile()`
  • 🌍CONTRIBUTE
    • How to contribute to transformers?
    • How to add a model to BOINC AI Transformers?
    • How to convert a BOINC AI Transformers model to TensorFlow?
    • How to add a pipeline to BOINC AI Transformers?
    • Testing
    • Checks on a Pull Request
  • 🌍CONCEPTUAL GUIDES
    • Philosophy
    • Glossary
    • What BOINC AI Transformers can do
    • How BOINC AI Transformers solve tasks
    • The Transformer model family
    • Summary of the tokenizers
    • Attention mechanisms
    • Padding and truncation
    • BERTology
    • Perplexity of fixed-length models
    • Pipelines for webserver inference
    • Model training anatomy
  • 🌍API
    • 🌍MAIN CLASSES
      • Agents and Tools
      • 🌍Auto Classes
        • Extending the Auto Classes
        • AutoConfig
        • AutoTokenizer
        • AutoFeatureExtractor
        • AutoImageProcessor
        • AutoProcessor
        • Generic model classes
          • AutoModel
          • TFAutoModel
          • FlaxAutoModel
        • Generic pretraining classes
          • AutoModelForPreTraining
          • TFAutoModelForPreTraining
          • FlaxAutoModelForPreTraining
        • Natural Language Processing
          • AutoModelForCausalLM
          • TFAutoModelForCausalLM
          • FlaxAutoModelForCausalLM
          • AutoModelForMaskedLM
          • TFAutoModelForMaskedLM
          • FlaxAutoModelForMaskedLM
          • AutoModelForMaskGenerationge
          • TFAutoModelForMaskGeneration
          • AutoModelForSeq2SeqLM
          • TFAutoModelForSeq2SeqLM
          • FlaxAutoModelForSeq2SeqLM
          • AutoModelForSequenceClassification
          • TFAutoModelForSequenceClassification
          • FlaxAutoModelForSequenceClassification
          • AutoModelForMultipleChoice
          • TFAutoModelForMultipleChoice
          • FlaxAutoModelForMultipleChoice
          • AutoModelForNextSentencePrediction
          • TFAutoModelForNextSentencePrediction
          • FlaxAutoModelForNextSentencePrediction
          • AutoModelForTokenClassification
          • TFAutoModelForTokenClassification
          • FlaxAutoModelForTokenClassification
          • AutoModelForQuestionAnswering
          • TFAutoModelForQuestionAnswering
          • FlaxAutoModelForQuestionAnswering
          • AutoModelForTextEncoding
          • TFAutoModelForTextEncoding
        • Computer vision
          • AutoModelForDepthEstimation
          • AutoModelForImageClassification
          • TFAutoModelForImageClassification
          • FlaxAutoModelForImageClassification
          • AutoModelForVideoClassification
          • AutoModelForMaskedImageModeling
          • TFAutoModelForMaskedImageModeling
          • AutoModelForObjectDetection
          • AutoModelForImageSegmentation
          • AutoModelForImageToImage
          • AutoModelForSemanticSegmentation
          • TFAutoModelForSemanticSegmentation
          • AutoModelForInstanceSegmentation
          • AutoModelForUniversalSegmentation
          • AutoModelForZeroShotImageClassification
          • TFAutoModelForZeroShotImageClassification
          • AutoModelForZeroShotObjectDetection
        • Audio
          • AutoModelForAudioClassification
          • AutoModelForAudioFrameClassification
          • TFAutoModelForAudioFrameClassification
          • AutoModelForCTC
          • AutoModelForSpeechSeq2Seq
          • TFAutoModelForSpeechSeq2Seq
          • FlaxAutoModelForSpeechSeq2Seq
          • AutoModelForAudioXVector
          • AutoModelForTextToSpectrogram
          • AutoModelForTextToWaveform
        • Multimodal
          • AutoModelForTableQuestionAnswering
          • TFAutoModelForTableQuestionAnswering
          • AutoModelForDocumentQuestionAnswering
          • TFAutoModelForDocumentQuestionAnswering
          • AutoModelForVisualQuestionAnswering
          • AutoModelForVision2Seq
          • TFAutoModelForVision2Seq
          • FlaxAutoModelForVision2Seq
      • Callbacks
      • Configuration
      • Data Collator
      • Keras callbacks
      • Logging
      • Models
      • Text Generation
      • ONNX
      • Optimization
      • Model outputs
      • Pipelines
      • Processors
      • Quantization
      • Tokenizer
      • Trainer
      • DeepSpeed Integration
      • Feature Extractor
      • Image Processor
    • 🌍MODELS
      • 🌍TEXT MODELS
        • ALBERT
        • BART
        • BARThez
        • BARTpho
        • BERT
        • BertGeneration
        • BertJapanese
        • Bertweet
        • BigBird
        • BigBirdPegasus
        • BioGpt
        • Blenderbot
        • Blenderbot Small
        • BLOOM
        • BORT
        • ByT5
        • CamemBERT
        • CANINE
        • CodeGen
        • CodeLlama
        • ConvBERT
        • CPM
        • CPMANT
        • CTRL
        • DeBERTa
        • DeBERTa-v2
        • DialoGPT
        • DistilBERT
        • DPR
        • ELECTRA
        • Encoder Decoder Models
        • ERNIE
        • ErnieM
        • ESM
        • Falcon
        • FLAN-T5
        • FLAN-UL2
        • FlauBERT
        • FNet
        • FSMT
        • Funnel Transformer
        • GPT
        • GPT Neo
        • GPT NeoX
        • GPT NeoX Japanese
        • GPT-J
        • GPT2
        • GPTBigCode
        • GPTSAN Japanese
        • GPTSw3
        • HerBERT
        • I-BERT
        • Jukebox
        • LED
        • LLaMA
        • LLama2
        • Longformer
        • LongT5
        • LUKE
        • M2M100
        • MarianMT
        • MarkupLM
        • MBart and MBart-50
        • MEGA
        • MegatronBERT
        • MegatronGPT2
        • Mistral
        • mLUKE
        • MobileBERT
        • MPNet
        • MPT
        • MRA
        • MT5
        • MVP
        • NEZHA
        • NLLB
        • NLLB-MoE
        • NystrΓΆmformer
        • Open-Llama
        • OPT
        • Pegasus
        • PEGASUS-X
        • Persimmon
        • PhoBERT
        • PLBart
        • ProphetNet
        • QDQBert
        • RAG
        • REALM
        • Reformer
        • RemBERT
        • RetriBERT
        • RoBERTa
        • RoBERTa-PreLayerNorm
        • RoCBert
        • RoFormer
        • RWKV
        • Splinter
        • SqueezeBERT
        • SwitchTransformers
        • T5
        • T5v1.1
        • TAPEX
        • Transformer XL
        • UL2
        • UMT5
        • X-MOD
        • XGLM
        • XLM
        • XLM-ProphetNet
        • XLM-RoBERTa
        • XLM-RoBERTa-XL
        • XLM-V
        • XLNet
        • YOSO
      • 🌍VISION MODELS
        • BEiT
        • BiT
        • Conditional DETR
        • ConvNeXT
        • ConvNeXTV2
        • CvT
        • Deformable DETR
        • DeiT
        • DETA
        • DETR
        • DiNAT
        • DINO V2
        • DiT
        • DPT
        • EfficientFormer
        • EfficientNet
        • FocalNet
        • GLPN
        • ImageGPT
        • LeViT
        • Mask2Former
        • MaskFormer
        • MobileNetV1
        • MobileNetV2
        • MobileViT
        • MobileViTV2
        • NAT
        • PoolFormer
        • Pyramid Vision Transformer (PVT)
        • RegNet
        • ResNet
        • SegFormer
        • SwiftFormer
        • Swin Transformer
        • Swin Transformer V2
        • Swin2SR
        • Table Transformer
        • TimeSformer
        • UperNet
        • VAN
        • VideoMAE
        • Vision Transformer (ViT)
        • ViT Hybrid
        • ViTDet
        • ViTMAE
        • ViTMatte
        • ViTMSN
        • ViViT
        • YOLOS
      • 🌍AUDIO MODELS
        • Audio Spectrogram Transformer
        • Bark
        • CLAP
        • EnCodec
        • Hubert
        • MCTCT
        • MMS
        • MusicGen
        • Pop2Piano
        • SEW
        • SEW-D
        • Speech2Text
        • Speech2Text2
        • SpeechT5
        • UniSpeech
        • UniSpeech-SAT
        • VITS
        • Wav2Vec2
        • Wav2Vec2-Conformer
        • Wav2Vec2Phoneme
        • WavLM
        • Whisper
        • XLS-R
        • XLSR-Wav2Vec2
      • 🌍MULTIMODAL MODELS
        • ALIGN
        • AltCLIP
        • BLIP
        • BLIP-2
        • BridgeTower
        • BROS
        • Chinese-CLIP
        • CLIP
        • CLIPSeg
        • Data2Vec
        • DePlot
        • Donut
        • FLAVA
        • GIT
        • GroupViT
        • IDEFICS
        • InstructBLIP
        • LayoutLM
        • LayoutLMV2
        • LayoutLMV3
        • LayoutXLM
        • LiLT
        • LXMERT
        • MatCha
        • MGP-STR
        • Nougat
        • OneFormer
        • OWL-ViT
        • Perceiver
        • Pix2Struct
        • Segment Anything
        • Speech Encoder Decoder Models
        • TAPAS
        • TrOCR
        • TVLT
        • ViLT
        • Vision Encoder Decoder Models
        • Vision Text Dual Encoder
        • VisualBERT
        • X-CLIP
      • 🌍REINFORCEMENT LEARNING MODELS
        • Decision Transformer
        • Trajectory Transformer
      • 🌍TIME SERIES MODELS
        • Autoformer
        • Informer
        • Time Series Transformer
      • 🌍GRAPH MODELS
        • Graphormer
  • 🌍INTERNAL HELPERS
    • Custom Layers and Utilities
    • Utilities for pipelines
    • Utilities for Tokenizers
    • Utilities for Trainer
    • Utilities for Generation
    • Utilities for Image Processors
    • Utilities for Audio processing
    • General Utilities
    • Utilities for Time Series
Powered by GitBook
On this page
  • IDEFICS
  • Overview
  • IdeficsConfig
  • IdeficsModel
  • IdeficsForVisionText2Text
  • IdeficsImageProcessor
  • IdeficsProcessor
  1. API
  2. MODELS
  3. MULTIMODAL MODELS

IDEFICS

PreviousGroupViTNextInstructBLIP

Last updated 1 year ago

IDEFICS

Overview

The IDEFICS model was proposed in 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 . The original code can be found . (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

( vocab_size = 32000additional_vocab_size = 0hidden_size = 4096intermediate_size = 11008num_hidden_layers = 32num_attention_heads = 32dropout = 0.0hidden_act = 'silu'initializer_range = 0.02alpha_initializer = 'zeros'alphas_initializer_range = 0.0alpha_type = 'float'rms_norm_eps = 1e-06use_cache = Truepad_token_id = 0bos_token_id = 1eos_token_id = 2tie_word_embeddings = Falsecross_layer_interval = 1qk_layer_norms = Falsefreeze_text_layers = Truefreeze_text_module_exceptions = []freeze_lm_head = Falsefreeze_vision_layers = Truefreeze_vision_module_exceptions = []use_resampler = Falsevision_config = Noneperceiver_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

  • 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

Example:

Copied

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

( config: IdeficsConfig )

Parameters

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

forward

( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: typing.Optional[typing.List[torch.FloatTensor]] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Noneimage_encoder_embeddings: typing.Optional[torch.FloatTensor] = Noneperceiver_embeddings: typing.Optional[torch.FloatTensor] = Noneimage_attention_mask: typing.Optional[torch.Tensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Noneinterpolate_pos_encoding: typing.Optional[bool] = Falsereturn_dict: typing.Optional[bool] = 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.

  • 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.

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

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • 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.

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

( configvision_model = None )

forward

( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: typing.Optional[typing.List[torch.FloatTensor]] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Noneimage_encoder_embeddings: typing.Optional[torch.FloatTensor] = Noneperceiver_embeddings: typing.Optional[torch.FloatTensor] = Noneimage_attention_mask: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Noneinterpolate_pos_encoding: typing.Optional[bool] = Falsereturn_dict: typing.Optional[bool] = 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.

  • 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.

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

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • 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.

  • 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)

  • 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

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:

Copied

>>> from transformers import AutoTokenizer, IdeficsForVisionText2Text

>>> model = IdeficsForVisionText2Text.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)

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

IdeficsImageProcessor

class transformers.IdeficsImageProcessor

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

Parameters

  • image_size (int, optional, defaults to 224) β€” Resize to image size

  • image_num_channels (int, optional, defaults to 3) β€” 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.

Constructs a Idefics image processor.

preprocess

( 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] = 3image_size: typing.Union[typing.Dict[str, int], NoneType] = Noneimage_mean: typing.Union[float, typing.List[float], NoneType] = Noneimage_std: typing.Union[float, typing.List[float], NoneType] = Nonetransform: typing.Callable = None**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

( image_processortokenizer = Noneimage_size = 224add_end_of_utterance_token = None**kwargs )

Parameters

  • 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.

__call__

( prompts: typing.Union[typing.List[str], typing.List[typing.List[str]]]padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = Falsetruncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = Nonemax_length: typing.Optional[int] = Nonetransform: typing.Callable = Noneadd_eos_token = Falseadd_end_of_utterance_token = Nonedebug = Falsereturn_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = <TensorType.PYTORCH: 'pt'> ) β†’ a dict with entries

Parameters

  • prompts (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.

    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).

    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.

    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).

  • max_length (int, optional) β€” Maximum length of the returned list and optionally padding length (see above).

  • truncation (bool, optional) β€” Activates truncation to cut input sequences longer than max_length to max_length.

  • transform (Callable, optional) β€” A custom transform function that accepts a single image can be passed for training. For example, torchvision.Compose can be used to compose multiple functions. If None a preset inference-specific set of transforms will be applied to the images

  • add_eos_token (bool, optional, defaults to False) β€” Adds eos_token at the end of the final prompt if True`

  • add_end_of_utterance_token (bool, optional) β€” Whether to automatically add <end_of_utterance> after each prompt’s text input (unless followed by an image). If None the tokenizer will be checked instead and if this token is found in additional_special_tokens then the value will be True.

  • debug (bool, optional, defaults to False) β€” True value will help debug prompt generation by dumping useful information

  • 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 prompts 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:

Copied

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(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:

Copied

<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:'

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:

Copied

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(prompts, transform=image_transform, return_tensors="pt")

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

This is the configuration class to store the configuration of a . 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.

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

config () β€” 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 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 . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

Indices can be obtained using . See and for details.

Indices can be obtained using . See and for details.

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 for more information on the default strategy.

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].

return_dict (bool, optional) β€” Whether or not to return a instead of a plain tuple.

The forward method, overrides the __call__ special method.

Indices can be obtained using . See and for details.

Indices can be obtained using . See and for details.

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 for more information on the default strategy.

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].

return_dict (bool, optional) β€” Whether or not to return a instead of a plain tuple.

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 () and inputs.

The forward method, overrides the __call__ special method.

image_processor (IdeficsImageProcessor) β€” An instance of . The image processor is a required input.

tokenizer (LlamaTokenizerFast) β€” An instance of . The tokenizer is a required input.

offers all the functionalities of and . See the docstring of and decode() for more information.

padding (bool, str or , optional, defaults to False) β€” Select a strategy to pad the returned sequences (according to the model’s padding side and padding index) among:

and the two images will be massaged using method and placed inside the pixel_values dict entry of the return value.

🌍
🌍
🌍
OBELICS: An Open Web-Scale Filtered Dataset of Interleaved Image-Text Documents
HuggingFaceM4
here
<source>
~IdeficsModel
IdeficsModel
HuggingFaceM4/idefics-9b
PretrainedConfig
PretrainedConfig
<source>
IdeficsConfig
from_pretrained()
PreTrainedModel
torch.nn.Module
<source>
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
the paper
What are position IDs?
ModelOutput
IdeficsModel
<source>
<source>
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
What are input IDs?
What are attention masks?
AutoTokenizer
PreTrainedTokenizer.encode()
PreTrainedTokenizer.call()
the paper
What are position IDs?
ModelOutput
IdeficsConfig
IdeficsForVisionText2Text
<source>
<source>
<source>
IdeficsImageProcessor
LlamaTokenizerFast
IdeficsProcessor
IdeficsImageProcessor
LlamaTokenizerFast
call()
<source>
PaddingStrategy
IdeficsImageProcessor.call()