CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
modeling_idefics.py1311 linesDownload Raw Back to idefics
1# coding=utf-82# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.3#4# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX5# and OPT implementations in this library. It has been modified from its6# original forms to accommodate minor architectural differences compared7# to GPT-NeoX and OPT used by the Meta AI team that trained the model.8#9# Licensed under the Apache License, Version 2.0 (the "License");10# you may not use this file except in compliance with the License.11# You may obtain a copy of the License at12#13#     http://www.apache.org/licenses/LICENSE-2.014#15# Unless required by applicable law or agreed to in writing, software16# distributed under the License is distributed on an "AS IS" BASIS,17# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.18# See the License for the specific language governing permissions and19# limitations under the License.20"""PyTorch Idefics model."""21 22from dataclasses import dataclass23from typing import Any, Callable, Optional, Union24 25import torch26import torch.nn.functional as F27from torch import nn28 29from ...activations import ACT2FN30from ...cache_utils import Cache, DynamicCache31from ...generation import GenerationMixin32from ...masking_utils import create_causal_mask33from ...modeling_layers import GradientCheckpointingLayer34from ...modeling_outputs import ModelOutput35from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PretrainedConfig, PreTrainedModel36from ...processing_utils import Unpack37from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging38from ...utils.deprecation import deprecate_kwarg39from ...utils.generic import OutputRecorder, check_model_inputs40from .configuration_idefics import IdeficsConfig41from .perceiver import IdeficsPerceiverResampler42from .vision import IdeficsVisionEmbeddings, IdeficsVisionTransformer43 44 45logger = logging.get_logger(__name__)46 47 48@dataclass49@auto_docstring(50    custom_intro="""51    Base class for Idefics model's outputs that may also contain a past key/values (to speed up sequential decoding).52    """53)54class IdeficsBaseModelOutputWithPast(ModelOutput):55    r"""56    last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):57        Sequence of hidden-states at the output of the last layer of the model.58 59        If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,60        hidden_size)` is output.61    past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):62        It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).63 64        Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if65        `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`66        input) to speed up sequential decoding.67    image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):68        Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,69        sequence_length, hidden_size)`.70 71        image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver72    """73 74    last_hidden_state: Optional[torch.FloatTensor] = None75    past_key_values: Optional[Cache] = None76    hidden_states: Optional[tuple[torch.FloatTensor]] = None77    attentions: Optional[tuple[torch.FloatTensor]] = None78    image_hidden_states: Optional[tuple[torch.FloatTensor]] = None79 80 81@dataclass82@auto_docstring(83    custom_intro="""84    Base class for Idefics causal language model (or autoregressive) outputs.85    """86)87class IdeficsCausalLMOutputWithPast(ModelOutput):88    r"""89    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):90        Language modeling loss (for next-token prediction).91    logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):92        Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).93    past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):94        It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).95 96        Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see97        `past_key_values` input) to speed up sequential decoding.98    image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):99        Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,100        sequence_length, hidden_size)`.101 102        image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver103    """104 105    loss: Optional[torch.FloatTensor] = None106    logits: Optional[torch.FloatTensor] = None107    past_key_values: Optional[Cache] = None108    hidden_states: Optional[tuple[torch.FloatTensor]] = None109    attentions: Optional[tuple[torch.FloatTensor]] = None110    image_hidden_states: Optional[tuple[torch.FloatTensor]] = None111 112 113def expand_inputs_for_generation(114    input_ids,115    expand_size=1,116    is_encoder_decoder=False,117    attention_mask=None,118    encoder_outputs=None,119    **model_kwargs,120):121    expanded_return_idx = (122        torch.arange(input_ids.shape[0]).view(-1, 1).repeat(1, expand_size).view(-1).to(input_ids.device)123    )124    input_ids = input_ids.index_select(0, expanded_return_idx)125    model_kwargs["pixel_values"] = model_kwargs.get("pixel_values")126    model_kwargs["image_encoder_embeddings"] = model_kwargs.get("image_encoder_embeddings")127    model_kwargs["perceiver_embeddings"] = model_kwargs.get("perceiver_embeddings")128    model_kwargs["image_attention_mask"] = model_kwargs.get("image_attention_mask")129 130    if "token_type_ids" in model_kwargs:131        token_type_ids = model_kwargs["token_type_ids"]132        model_kwargs["token_type_ids"] = token_type_ids.index_select(0, expanded_return_idx)133 134    if attention_mask is not None:135        model_kwargs["attention_mask"] = attention_mask.index_select(0, expanded_return_idx)136 137    if model_kwargs["image_attention_mask"] is not None:138        model_kwargs["image_attention_mask"] = model_kwargs["image_attention_mask"].index_select(139            0, expanded_return_idx140        )141 142    if model_kwargs["pixel_values"] is not None:143        model_kwargs["pixel_values"] = model_kwargs["pixel_values"].index_select(0, expanded_return_idx)144 145    elif model_kwargs["image_encoder_embeddings"] is not None:146        model_kwargs["image_encoder_embeddings"] = model_kwargs["image_encoder_embeddings"].index_select(147            0, expanded_return_idx148        )149 150    elif model_kwargs["perceiver_embeddings"] is not None:151        model_kwargs["perceiver_embeddings"] = model_kwargs["perceiver_embeddings"].index_select(152            0, expanded_return_idx153        )154 155    return input_ids, model_kwargs156 157 158def freeze_model(model, module_exceptions=[]):159    mapping = {160        "LayerNorm": nn.LayerNorm,161        "Linear": nn.Linear,162        "Embedding": nn.Embedding,163    }164    module_exceptions_mapped = [mapping[m] for m in module_exceptions]165    for module in model.modules():166        if module_exceptions and any(isinstance(module, t) for t in module_exceptions_mapped):167            module.requires_grad_(True)  # Explicitly setting it to true to avoid any mistakes168        else:169            module.requires_grad_(False)170    return model171 172 173class IdeficsDecoupledEmbedding(nn.Embedding):174    # Derived from https://pytorch.org/docs/stable/_modules/torch/nn/modules/sparse.html#Embedding175    """176    Implements a decoupling of parameters to allow freezing (or not) a subset of the embeddings. In practise, the177    regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `num_additional_embeddings` > 0,178    then it will create `num_additional_embeddings` additional parameters that are always trained. If179    `num_additional_embeddings=0`, then the module defaults back to the regular behavior of `nn.Embedding`.180    """181 182    def __init__(183        self,184        num_embeddings,185        num_additional_embeddings,186        embedding_dim,187        partially_freeze: Optional[bool] = False,188        device=None,189        dtype=None,190        padding_idx=None,191        **kwargs,192    ) -> None:193        """194        Args:195            num_embeddings (`int`):196                Size of the dictionary of embeddings197            num_additional_embeddings (`int`):198                Number of additional embeddings. Only useful when you `partially_freeze=True`.199            embedding_dim (`int`):200                The size of each embedding vector201            partially_freeze: (`bool`, *optional*, defaults to `False`):202                If `True`, the regular `weight` will be frozen. `additional_weight` is never frozen.203            padding_idx (`int`, *optional*):204                The padding index (needs to be less than num_embeddings)205 206        Note: there are a lot of other parameters to initialize a standard `nn.Embedding` such as `padding_idx`,207        `max_norm` or `norm_type`. We are not supporting these.208        """209        if padding_idx is not None and padding_idx > num_embeddings:210            raise ValueError(f"padding_idx must be within num_embeddings. Got {padding_idx} and {num_embeddings}")211        super().__init__(212            num_embeddings=num_embeddings,213            embedding_dim=embedding_dim,214            device=device,215            dtype=dtype,216            padding_idx=padding_idx,217            **kwargs,218        )219        self.num_embeddings = num_embeddings220        self.padding_idx = padding_idx221        self.num_additional_embeddings = num_additional_embeddings222        self.partially_freeze = partially_freeze223 224        if partially_freeze:225            self.weight.requires_grad_(False)226 227        if self.num_additional_embeddings > 0:228            self.additional_embedding = nn.Embedding(229                num_embeddings=self.num_additional_embeddings,230                embedding_dim=embedding_dim,231                device=device,232                dtype=dtype,233            )234 235    def forward(self, input_ids):236        """237        we have 2 embeddings, with different indices - one pretrained self.weight and another238        self.additional_embedding.weight that is being trained.239 240        in order to make a lookup of the input ids, we:241        1. find out the indices of the entries belonging to the 2nd embedding242        2. extract those values while subtracting the size of the first embedding (num_embeddings), since the 2nd243           embedding starts from 0 and not num_embeddings244        3. perform the 2nd embedding lookup245        4. now we handle the 1st embedding, we overwrite indices belonging to the 2nd embedding with a padding index246        5. perform the 1st embedding lookup247        6. now we overwrite the values in the 1st embedding lookup with the values of the 2nd embedding lookup248 249        note: for the 1st embedding lookup we could have looked up only the low indices and not do the padding, but250        then we have to create a new tensor and populate it with 2 tensors that are spread out across various indices -251        i.e. not a simple concat - I haven't benchmarked the complex case if it's any faster, given that seqlens are252        usually relatively short it's probably not faster or if faster not by much - but might be a good idea to253        measure.254 255        """256        if self.num_additional_embeddings == 0:257            return F.embedding(input_ids, self.weight)258 259        # Clone so that we don't modify the original input_ids later on260        input_ids = input_ids.clone()261        additional_vocab_indices = torch.where(input_ids >= self.num_embeddings)262        input_ids_additional_vocab = input_ids[additional_vocab_indices]263        additional_embeddings = self.additional_embedding(input_ids_additional_vocab - self.num_embeddings)264 265        # for successful lookup replace input_ids with 0, the results of these will be discarded anyway266        input_ids[additional_vocab_indices] = 0267        full_vector = F.embedding(input_ids, self.weight)268 269        # overwrite the records with high indices270        full_vector[additional_vocab_indices] = additional_embeddings271 272        return full_vector273 274    def extra_repr(self) -> str:275        return f"num_embeddings={self.num_embeddings}, num_additional_embeddings={self.num_additional_embeddings}, embedding_dim={self.embedding_dim}, partially_freeze={self.partially_freeze}"276 277 278class IdeficsDecoupledLinear(nn.Linear):279    # Derived from https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear280    """281    Implements a decoupling of parameters to allow freezing (or not) a subset of the parameters. In practise, the282    regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `out_additional_features` > 0,283    then it will create `out_additional_features * in_features` additional parameters that are always trained. If284    `out_additional_features=0`, then the module defaults back to the regular behavior of `nn.Linear`.285    """286 287    def __init__(288        self,289        in_features: int,290        out_features: int,291        out_additional_features: int = 0,292        bias: bool = True,293        partially_freeze: bool = True,294        device=None,295        dtype=None,296    ) -> None:297        """298        out_additional_features: int. Number of additional trainable dimensions. Only makes sense when299        `partially_freeze=True`. partially_freeze: bool. If True, the regular `weight` will be frozen and extra300        parameters (if any) will be trainable. If False, default to the regular behavior of nn.Linear.301        """302        super().__init__(in_features, out_features, bias, device, dtype)303        self.out_additional_features = out_additional_features304        self.partially_freeze = partially_freeze305 306        self.in_features = in_features307        self.out_features = out_features308 309        if partially_freeze:310            self.weight.requires_grad_(False)311            if bias:312                self.bias.requires_grad_(False)313 314        if out_additional_features > 0:315            self.additional_fc = nn.Linear(316                in_features=in_features,317                out_features=out_additional_features,318                bias=bias,319                device=device,320                dtype=dtype,321            )322 323    def forward(self, input: torch.Tensor) -> torch.Tensor:324        output = F.linear(input, self.weight, self.bias)325 326        if self.out_additional_features > 0:327            additional_features = self.additional_fc(input)328            output = torch.cat((output, additional_features), -1)329 330        return output331 332    def extra_repr(self) -> str:333        """Overwriting `nn.Linear.extra_repr` to include new parameters."""334        return f"in_features={self.in_features}, out_features={self.out_features}, out_additional_features={self.out_additional_features}, bias={self.bias is not None}, partially_freeze={self.partially_freeze}"335 336 337# this was adapted from LlamaRMSNorm338class IdeficsRMSNorm(nn.Module):339    def __init__(self, hidden_size, eps=1e-6):340        """341        IdeficsRMSNorm is equivalent to T5LayerNorm342        """343        super().__init__()344        self.weight = nn.Parameter(torch.ones(hidden_size))345        self.variance_epsilon = eps346 347    def forward(self, hidden_states):348        variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)349        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)350 351        # convert into half-precision if necessary352        if self.weight.dtype in [torch.float16, torch.bfloat16]:353            hidden_states = hidden_states.to(self.weight.dtype)354 355        return self.weight * hidden_states356 357    def extra_repr(self):358        return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"359 360 361# this was adapted from LlamaRotaryEmbedding362class IdeficsEmbedding(torch.nn.Module):363    def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):364        super().__init__()365 366        self.dim = dim367        self.max_position_embeddings = max_position_embeddings368        self.base = base369        inv_freq = 1.0 / (370            self.base371            ** (torch.arange(0, self.dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / self.dim)372        )373        self.register_buffer("inv_freq", inv_freq, persistent=False)374 375        # Build here to make `torch.jit.trace` work.376        self._set_cos_sin_cache(377            seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()378        )379 380    def _set_cos_sin_cache(self, seq_len, device, dtype):381        self.max_seq_len_cached = seq_len382        t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)383 384        freqs = torch.einsum("i,j->ij", t, self.inv_freq)385        # Different from paper, but it uses a different permutation in order to obtain the same calculation386        emb = torch.cat((freqs, freqs), dim=-1)387        self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)388        self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)389 390    def forward(self, x, seq_len=None):391        # x: [bs, num_attention_heads, seq_len, head_size]392        if seq_len > self.max_seq_len_cached:393            self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)394 395        return (396            self.cos_cached[:seq_len].to(dtype=x.dtype),397            self.sin_cached[:seq_len].to(dtype=x.dtype),398        )399 400 401def rotate_half(x):402    """Rotates half the hidden dims of the input."""403    x1 = x[..., : x.shape[-1] // 2]404    x2 = x[..., x.shape[-1] // 2 :]405    return torch.cat((-x2, x1), dim=-1)406 407 408def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):409    """Applies Rotary Position Embedding to the query and key tensors.410 411    Args:412        q (`torch.Tensor`): The query tensor.413        k (`torch.Tensor`): The key tensor.414        cos (`torch.Tensor`): The cosine part of the rotary embedding.415        sin (`torch.Tensor`): The sine part of the rotary embedding.416        position_ids (`torch.Tensor`):417            The position indices of the tokens corresponding to the query and key tensors. For example, this can be418            used to pass offsetted position ids when working with a KV-cache.419        unsqueeze_dim (`int`, *optional*, defaults to 1):420            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and421            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note422            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and423            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes424            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have425            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.426    Returns:427        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.428    """429    cos = cos[position_ids].unsqueeze(unsqueeze_dim)430    sin = sin[position_ids].unsqueeze(unsqueeze_dim)431    q_embed = (q * cos) + (rotate_half(q) * sin)432    k_embed = (k * cos) + (rotate_half(k) * sin)433    return q_embed, k_embed434 435 436# this was adapted from LlamaMLP437class IdeficsMLP(nn.Module):438    def __init__(439        self,440        hidden_size: int,441        intermediate_size: int,442        hidden_act: str,443    ):444        super().__init__()445        self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)446        self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)447        self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)448        self.act_fn = ACT2FN[hidden_act]449 450    def forward(self, x):451        return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))452 453 454# Copied from transformers.models.siglip.modeling_siglip.eager_attention_forward455def eager_attention_forward(456    module: nn.Module,457    query: torch.Tensor,458    key: torch.Tensor,459    value: torch.Tensor,460    attention_mask: Optional[torch.Tensor],461    scaling: float,462    dropout: float = 0.0,463    **kwargs,464):465    attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling466    if attention_mask is not None:467        attn_weights = attn_weights + attention_mask468 469    attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)470    attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)471 472    attn_output = torch.matmul(attn_weights, value)473    attn_output = attn_output.transpose(1, 2).contiguous()474 475    return attn_output, attn_weights476 477 478# this was adapted from LlamaAttention479class IdeficsAttention(nn.Module):480    """Multi-headed attention from 'Attention Is All You Need' paper"""481 482    def __init__(483        self,484        hidden_size: int,485        num_heads: int,486        dropout: float = 0.0,487        is_cross_attention: bool = False,488        config: Optional[PretrainedConfig] = None,489        qk_layer_norms: bool = False,490        layer_idx: Optional[int] = None,491    ):492        super().__init__()493        self.config = config494        self.hidden_size = hidden_size495        self.num_heads = num_heads496        self.head_dim = hidden_size // num_heads497        self.dropout = dropout498        self.is_causal = True499        self.scaling = self.head_dim**-0.5500 501        self.layer_idx = layer_idx502        if layer_idx is None:503            logger.warning_once(504                f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "505                "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "506                "when creating this class."507            )508 509        if (self.head_dim * num_heads) != self.hidden_size:510            raise ValueError(511                f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"512                f" and `num_heads`: {num_heads})."513            )514 515        self.is_cross_attention = is_cross_attention516 517        if not hasattr(nn.functional, "scaled_dot_product_attention"):518            raise ValueError("this model requires pytorch 2.0 or higher")519 520        if self.is_cross_attention:521            kv_input_dim = (522                self.hidden_size if not hasattr(config.vision_config, "embed_dim") else config.vision_config.embed_dim523            )524            self.q_proj = nn.Linear(525                self.hidden_size,526                num_heads * self.head_dim,527                bias=False,528            )529            self.k_proj = nn.Linear(kv_input_dim, num_heads * self.head_dim, bias=False)530            self.v_proj = nn.Linear(531                kv_input_dim,532                num_heads * self.head_dim,533                bias=False,534            )535        else:536            self.q_proj = nn.Linear(537                self.hidden_size,538                num_heads * self.head_dim,539                bias=False,540            )541            self.k_proj = nn.Linear(542                self.hidden_size,543                num_heads * self.head_dim,544                bias=False,545            )546            self.v_proj = nn.Linear(547                self.hidden_size,548                num_heads * self.head_dim,549                bias=False,550            )551        self.o_proj = nn.Linear(552            num_heads * self.head_dim,553            hidden_size,554            bias=False,555        )556        self.rotary_emb = IdeficsEmbedding(self.head_dim)557 558        self.qk_layer_norms = qk_layer_norms559        if self.qk_layer_norms:560            self.q_layer_norm = IdeficsRMSNorm(self.head_dim, eps=config.rms_norm_eps)561            self.k_layer_norm = IdeficsRMSNorm(self.head_dim, eps=config.rms_norm_eps)562 563    def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):564        return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()565 566    @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")567    def forward(568        self,569        hidden_states: torch.Tensor,570        key_value_states: Optional[torch.Tensor] = None,571        attention_mask: Optional[torch.Tensor] = None,572        position_ids: Optional[torch.LongTensor] = None,573        past_key_values: Optional[Cache] = None,574        cache_position: Optional[torch.LongTensor] = None,575        **kwargs: Unpack[TransformersKwargs],576    ) -> tuple[torch.Tensor, torch.Tensor]:577        # if key_value_states are provided this layer is used as a cross-attention layer578        is_cross_attention = self.is_cross_attention or key_value_states is not None579 580        bsz, q_len, _ = hidden_states.size()581 582        query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)583        if not is_cross_attention:584            key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)585            value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)586        else:587            _, kv_len, _ = key_value_states.size()  # Note that, in this case, `kv_len` == `kv_seq_len`588            key_states = self.k_proj(key_value_states).view(bsz, kv_len, self.num_heads, self.head_dim).transpose(1, 2)589            value_states = (590                self.v_proj(key_value_states).view(bsz, kv_len, self.num_heads, self.head_dim).transpose(1, 2)591            )592 593        kv_seq_len = key_states.shape[-2]594        if past_key_values is not None:595            kv_seq_len += cache_position[0]596 597        if not is_cross_attention:598            cos, sin = self.rotary_emb(value_states, seq_len=max(kv_seq_len, q_len))599            query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)600        # [bsz, nh, t, hd]601 602        if past_key_values is not None:603            # sin and cos are specific to RoPE models; cache_position needed for the static cache604            cache_kwargs = {"cache_position": cache_position}605            key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)606 607        if self.qk_layer_norms:608            query_states = self.q_layer_norm(query_states)609            key_states = self.k_layer_norm(key_states)610 611        attention_interface: Callable = eager_attention_forward612 613        if self.config._attn_implementation != "eager":614            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]615 616        attn_output, attn_weights = attention_interface(617            self,618            query_states,619            key_states,620            value_states,621            attention_mask,622            dropout=0.0 if not self.training else self.dropout,623            scaling=self.scaling,624            **kwargs,625        )626 627        attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()628        attn_output = self.o_proj(attn_output)629 630        return attn_output, attn_weights631 632 633# this was adapted from LlamaDecoderLayer634class IdeficsDecoderLayer(GradientCheckpointingLayer):635    def __init__(self, config: IdeficsConfig, layer_idx: Optional[int] = None):636        super().__init__()637        self.hidden_size = config.hidden_size638        self.self_attn = IdeficsAttention(639            hidden_size=self.hidden_size,640            num_heads=config.num_attention_heads,641            dropout=config.dropout,642            config=config,643            layer_idx=layer_idx,644        )645        self.mlp = IdeficsMLP(646            hidden_size=self.hidden_size,647            intermediate_size=config.intermediate_size,648            hidden_act=config.hidden_act,649        )650        self.input_layernorm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)651        self.post_attention_layernorm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)652        self.dropout = config.dropout653 654    @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")655    @auto_docstring656    def forward(657        self,658        hidden_states: torch.Tensor,659        attention_mask: Optional[torch.Tensor] = None,660        position_ids: Optional[torch.LongTensor] = None,661        past_key_values: Optional[Cache] = None,662        cache_position: Optional[torch.LongTensor] = None,663        **kwargs: Unpack[TransformersKwargs],664    ) -> torch.FloatTensor:665        residual = hidden_states666 667        hidden_states = self.input_layernorm(hidden_states)668 669        # Self Attention670        hidden_states, _ = self.self_attn(671            hidden_states=hidden_states,672            attention_mask=attention_mask,673            position_ids=position_ids,674            past_key_values=past_key_values,675            cache_position=cache_position,676            **kwargs,677        )678        hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)679        hidden_states = residual + hidden_states680 681        # Fully Connected682        residual = hidden_states683        hidden_states = self.post_attention_layernorm(hidden_states)684        hidden_states = self.mlp(hidden_states)685        hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)686        hidden_states = residual + hidden_states687 688        return hidden_states689 690 691class IdeficsGatedCrossAttentionLayer(GradientCheckpointingLayer):692    def __init__(self, config: IdeficsConfig, layer_idx: Optional[int] = None):693        super().__init__()694        self.hidden_size = config.hidden_size695        self.cross_attn = IdeficsAttention(696            hidden_size=self.hidden_size,697            num_heads=config.num_attention_heads,698            is_cross_attention=True,699            dropout=config.dropout,700            config=config,701            qk_layer_norms=config.qk_layer_norms,702            layer_idx=layer_idx,703        )704        self.mlp = IdeficsMLP(705            hidden_size=self.hidden_size,706            intermediate_size=config.intermediate_size,707            hidden_act=config.hidden_act,708        )709        self.input_layernorm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)710        self.post_attention_layernorm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)711        self.config = config.dropout712 713        self.act_cross_attn = nn.Tanh()714        self.act_dense = nn.Tanh()715 716        if config.alpha_initializer == "zeros":717            if config.alpha_type == "vector":718                self.alpha_cross_attn = nn.Parameter(torch.zeros(1, 1, self.hidden_size))719                self.alpha_dense = nn.Parameter(torch.zeros(1, 1, self.hidden_size))720            elif config.alpha_type == "float":721                self.alpha_cross_attn = nn.Parameter(torch.zeros(1))722                self.alpha_dense = nn.Parameter(torch.zeros(1))723            else:724                raise ValueError(f"Unknown value for `alpha_type` ({config.alpha_type})")725 726        elif config.alpha_initializer == "ones":727            if config.alpha_type == "vector":728                self.alpha_cross_attn = nn.Parameter(torch.ones(1, 1, self.hidden_size))729                self.alpha_dense = nn.Parameter(torch.ones(1, 1, self.hidden_size))730            elif config.alpha_type == "float":731                self.alpha_cross_attn = nn.Parameter(torch.ones(1))732                self.alpha_dense = nn.Parameter(torch.ones(1))733            else:734                raise ValueError(f"Unknown value for `alpha_type` ({config.alpha_type})")735 736        elif config.alpha_initializer in {"normal", "gaussian", "random"}:737            if config.alpha_type == "vector":738                self.alpha_cross_attn = nn.Parameter(739                    torch.normal(mean=0.0, std=config.alphas_initializer_range, size=(1, 1, self.hidden_size))740                )741                self.alpha_dense = nn.Parameter(742                    torch.normal(mean=0.0, std=config.alphas_initializer_range, size=(1, 1, self.hidden_size))743                )744            elif config.alpha_type == "float":745                self.alpha_cross_attn = nn.Parameter(746                    torch.normal(mean=0.0, std=config.alphas_initializer_range, size=(1))747                )748                self.alpha_dense = nn.Parameter(torch.normal(mean=0.0, std=config.alphas_initializer_range, size=(1)))749            else:750                raise ValueError(f"Unknown value for `alpha_type` ({config.alpha_type})")751 752        else:753            raise NotImplementedError(f"Alpha initialization scheme {config.alpha_initializer} not yet implemented!")754 755        if not (hasattr(self, "alpha_cross_attn") and hasattr(self, "alpha_dense")):756            raise ValueError("Alpha parameters not initialized correctly!")757 758    @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")759    @auto_docstring760    def forward(761        self,762        hidden_states: torch.Tensor,763        attention_mask: Optional[torch.Tensor] = None,764        image_hidden_states: Optional[torch.Tensor] = None,765        image_attention_mask: Optional[torch.Tensor] = None,766        cross_attention_gate: Optional[torch.Tensor] = None,767        past_key_values: Optional[Cache] = None,768        **kwargs: Unpack[TransformersKwargs],769    ) -> torch.FloatTensor:770        r"""771        image_hidden_states (`torch.FloatTensor`):772            Input to the layer of shape `(batch, seq_len, embed_dim)`773        image_attention_mask (`torch.FloatTensor`, *optional*):774            image attention mask of size775            `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.776        cross_attention_gate (`torch.FloatTensor`, *optional*):777            gate of size `(batch, seq_len)` used to zero-out cross-attention output for tokens attending no images.778        """779        if image_hidden_states is None:780            raise ValueError(781                "`image_hidden_states` is required for Idefics cross attention module which are visual features to be"782                " conditioned on."783            )784 785        if cross_attention_gate is None:786            raise ValueError(787                "`cross_attention_gate` is required for Idefics cross attention module to zero-out the cross-attention hidden_states attending to no images."788            )789 790        if past_key_values is not None:791            raise NotImplementedError("Past key value states are not implemented for Idefics cross attention module.")792 793        residual = hidden_states794 795        hidden_states = self.input_layernorm(hidden_states)796 797        # Self Attention798        hidden_states, _ = self.cross_attn(799            hidden_states=hidden_states,800            key_value_states=image_hidden_states,801            attention_mask=image_attention_mask,802            **kwargs,803        )804        hidden_states = nn.functional.dropout(hidden_states, p=self.config, training=self.training)805        # Fill in zeros for cross_attention hidden_states of tokens attending to no images806        hidden_states = hidden_states.masked_fill((cross_attention_gate == 0)[:, :, None], 0.0)807        hidden_states = residual + self.act_cross_attn(self.alpha_cross_attn) * hidden_states808 809        # Fully Connected810        residual = hidden_states811        hidden_states = self.post_attention_layernorm(hidden_states)812        hidden_states = self.mlp(hidden_states)813        hidden_states = nn.functional.dropout(hidden_states, p=self.config, training=self.training)814        hidden_states = residual + self.act_dense(self.alpha_dense) * hidden_states815 816        return hidden_states817 818 819@auto_docstring820class IdeficsPreTrainedModel(PreTrainedModel):821    config: IdeficsConfig822    base_model_prefix = "model"823    supports_gradient_checkpointing = True824    _no_split_modules = ["IdeficsDecoderLayer", "IdeficsGatedCrossAttentionLayer"]825    _supports_sdpa = True826 827    _supports_flash_attn = False  # only eager/sdpa creation is supported828    _can_compile_fullgraph = False  # IDEFICS cannot compile due to dynamic control flow when checking inputs829    _supports_attention_backend = True830 831    _can_record_outputs = {832        "hidden_states": IdeficsDecoderLayer,833        "attentions": OutputRecorder(IdeficsAttention, index=1, layer_name="self_attn"),834    }835 836    def _init_weights(self, module):837        # important: this ported version of Idefics isn't meant for training from scratch - only838        # inference and fine-tuning - so the proper init weights code has been removed - the m4 code839        # base should be used for training from scratch and it contains the correct code.840        std = self.config.initializer_range841        if isinstance(module, (nn.Linear, nn.Conv2d)):842            module.weight.data.normal_(mean=0.0, std=std)843            if module.bias is not None:844                module.bias.data.zero_()845        elif isinstance(module, nn.Embedding):846            module.weight.data.normal_(mean=0.0, std=std)847            if module.padding_idx is not None:848                module.weight.data[module.padding_idx].zero_()849        elif isinstance(module, nn.LayerNorm):850            module.weight.data.fill_(1.0)851            module.bias.data.zero_()852        elif isinstance(module, IdeficsRMSNorm):853            module.weight.data.fill_(1.0)854        elif isinstance(module, IdeficsVisionEmbeddings):855            module.class_embedding.data.normal_()856        elif isinstance(module, IdeficsGatedCrossAttentionLayer):857            if self.config.alpha_initializer == "zeros":858                module.alpha_cross_attn.data.zero_()859                module.alpha_dense.data.zero_()860            elif self.config.alpha_initializer == "ones":861                module.alpha_cross_attn.data.fill_(1.0)862                module.alpha_dense.data.fill_(1.0)863            elif self.config.alpha_initializer in {"normal", "gaussian", "random"}:864                module.alpha_cross_attn.data.normal_(mean=0.0, std=self.config.alphas_initializer_range)865                module.alpha_dense.data.normal_(mean=0.0, std=self.config.alphas_initializer_range)866        elif isinstance(module, IdeficsPerceiverResampler):867            module.latents.data.normal_()868 869 870@auto_docstring871class IdeficsModel(IdeficsPreTrainedModel):872    """873    Transformer decoder consisting of `config.num_hidden_layers` layers. Each layer is a [`IdeficsDecoderLayer`]874 875    Args:876        config: IdeficsConfig877    """878 879    def __init__(self, config: IdeficsConfig):880        super().__init__(config)881        self.config = config882        self.padding_idx = config.pad_token_id883        self.vocab_size = config.vocab_size884 885        self.embed_tokens = IdeficsDecoupledEmbedding(886            num_embeddings=config.vocab_size,887            num_additional_embeddings=config.additional_vocab_size,888            embedding_dim=config.hidden_size,889            partially_freeze=config.freeze_text_layers,890            padding_idx=self.padding_idx,891        )892 893        self.image_size = config.vision_config.image_size894        self.vision_config = config.vision_config895        # The module using it is not a PreTrainedModel subclass so we need this896        self.vision_config._attn_implementation = config._attn_implementation897        self.vision_model = IdeficsVisionTransformer(config.vision_config)898 899        # Perceiver Resampler900        if config.use_resampler:901            perceiver_config = config.perceiver_config902            self.perceiver_resampler = IdeficsPerceiverResampler(903                config,904                config.vision_config.embed_dim,905                perceiver_config.resampler_depth,906                perceiver_config.resampler_n_heads,907                perceiver_config.resampler_head_dim,908                perceiver_config.resampler_n_latents,909            )910 911        self.layers = nn.ModuleList(912            [IdeficsDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]913        )914 915        self.cross_layer_interval = config.cross_layer_interval916        num_cross_layers = config.num_hidden_layers // self.cross_layer_interval917        self.gated_cross_attn_layers = nn.ModuleList(918            [IdeficsGatedCrossAttentionLayer(config, layer_idx=i) for i in range(num_cross_layers)]919        )920        self.gradient_checkpointing = False921 922        self.norm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)923 924        # Initialize weights and apply final processing925        self.post_init()926 927        self.freeze_relevant_params(config)928 929    def freeze_relevant_params(self, config=None):930        if config is None:931            config = self.config932 933        if config.freeze_text_layers:934            self.freeze_text_layers(config.freeze_text_module_exceptions)935 936        if config.freeze_vision_layers:937            freeze_model(self.vision_model, module_exceptions=config.freeze_vision_module_exceptions)938 939    def freeze_text_layers(self, module_exceptions=[]):940        for module in [self.layers, self.norm]:941            freeze_model(module, module_exceptions=module_exceptions)942 943    def freeze_vision_layers(self, module_exceptions=[]):944        freeze_model(self.vision_model, module_exceptions=module_exceptions)945 946    @check_model_inputs()947    @auto_docstring948    def forward(949        self,950        input_ids: Optional[torch.LongTensor] = None,951        attention_mask: Optional[torch.Tensor] = None,952        position_ids: Optional[torch.LongTensor] = None,953        past_key_values: Optional[Cache] = None,954        inputs_embeds: Optional[torch.FloatTensor] = None,955        pixel_values: Optional[torch.FloatTensor] = None,956        image_encoder_embeddings: Optional[torch.FloatTensor] = None,957        perceiver_embeddings: Optional[torch.FloatTensor] = None,958        image_attention_mask: Optional[torch.Tensor] = None,959        use_cache: Optional[bool] = None,960        interpolate_pos_encoding: Optional[bool] = False,961        cache_position: Optional[torch.LongTensor] = None,962        **kwargs: Unpack[TransformersKwargs],963    ) -> Union[tuple, IdeficsBaseModelOutputWithPast]:964        r"""965        image_encoder_embeddings (`torch.FloatTensor`, *optional*):966            The output of the image encoder.967        perceiver_embeddings (`torch.FloatTensor`, *optional*):968            The output of the perceiver resampler.969        image_attention_mask (`torch.LongTensor`, *optional*):970            The attention mask for the image encoder.971        """972        device = input_ids.device if input_ids is not None else inputs_embeds.device973 974        if (input_ids is None) ^ (inputs_embeds is not None):975            raise ValueError("You must specify exactly one of input_ids or inputs_embeds")976 977        if inputs_embeds is None:978            inputs_embeds = self.embed_tokens(input_ids)979 980        if use_cache and past_key_values is None:981            past_key_values = DynamicCache(config=self.config)982 983        batch_size, seq_length, _ = inputs_embeds.shape984        past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0985        seq_length_with_past = seq_length + past_key_values_length986 987        if cache_position is None:988            cache_position = torch.arange(989                past_key_values_length, past_key_values_length + inputs_embeds.shape[1], device=inputs_embeds.device990            )991 992        if attention_mask is not None and position_ids is None:993            # create position_ids on the fly for batch generation994            position_ids = attention_mask.long().cumsum(-1) - 1995            position_ids.masked_fill_(attention_mask == 0, 1)996            position_ids = position_ids[:, -seq_length:]997        elif position_ids is None:998            position_ids = cache_position.unsqueeze(0)999 1000        if sum(x is None for x in [pixel_values, image_encoder_embeddings, perceiver_embeddings]) != 2:1001            raise ValueError(1002                "Exactly 1 of pixel_values, image_encoder_embeddings or perceiver_embeddings has to be not-None."1003            )1004 1005        elif pixel_values is not None:1006            pixel_values = pixel_values.to(dtype=self.dtype, device=device)  # fp16 compatibility1007            batch_size, num_images = pixel_values.shape[:2]1008            pixel_values = pixel_values.contiguous().view(batch_size * num_images, *pixel_values.shape[2:])1009 1010            # Get sequence from the vision encoder1011            image_hidden_states = self.vision_model(1012                pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding1013            ).last_hidden_state1014 1015        elif image_encoder_embeddings is not None:1016            batch_size, num_images, image_seq_len, image_hidden_size = image_encoder_embeddings.size()1017            image_hidden_states = image_encoder_embeddings.to(dtype=self.dtype, device=device)1018            image_hidden_states = image_hidden_states.view(batch_size * num_images, image_seq_len, image_hidden_size)1019 1020        if self.config.use_resampler:1021            if perceiver_embeddings is None:1022                perceiver_embeddings = self.perceiver_resampler(image_hidden_states)1023                image_seq_len, image_hidden_size = perceiver_embeddings.size(1), perceiver_embeddings.size(2)1024            else:1025                batch_size, num_images, image_seq_len, image_hidden_size = perceiver_embeddings.size()1026            image_hidden_states = perceiver_embeddings1027        elif perceiver_embeddings is None:1028            image_seq_len, image_hidden_size = image_hidden_states.size(1), image_hidden_states.size(2)1029        else:1030            raise ValueError("If `perceiver_embeddings` are passed, use_resampler should be True")1031 1032        image_hidden_states = image_hidden_states.view(batch_size, num_images * image_seq_len, image_hidden_size)1033        # # Hack to use the model in full language modeling mode1034        # image_attention_mask = torch.zeros(batch_size, seq_length, 1, dtype=torch.long, device=image_hidden_states.device)1035        # Make image_attention_mask compatible with hidden states1036        text_seq_len = image_attention_mask.size(1)1037        image_attention_mask = image_attention_mask.unsqueeze(-1)1038        image_attention_mask = image_attention_mask.repeat(1, 1, 1, image_seq_len)1039        image_attention_mask = image_attention_mask.view(batch_size, text_seq_len, num_images * image_seq_len)1040 1041        if image_hidden_states is not None:1042            image_batch_size, image_sequence_length, _ = image_hidden_states.size()1043            image_hidden_shape = (image_batch_size, image_sequence_length)1044            if image_attention_mask is None:1045                image_attention_mask = torch.ones(image_hidden_shape, device=device)1046            image_attention_mask = self.invert_attention_mask(image_attention_mask)1047        else:1048            image_attention_mask = None1049 1050        # cross_attention_gate:1051        # For any tokens attending to no images, the hidden_states coming out of the cross-attention should be zeroed-out.1052        # `image_attention_mask` has shape [bsz, 1, num_images, hidden_size] with elements equal to either 0.0 or a very negative number.1053        # If any of the elements are 0.0, then the token is attending to at least one image and the gate value is 1. Otherwise the gate value is 0.1054        # `cross_attention_gate` has shape [bsz, seq_len] with elements equal to either 0.0 or 1.0.1055        cross_attention_gate = ((((image_attention_mask == 0.0).any(dim=-1)).to(dtype=self.dtype)).squeeze(dim=1)).to(1056            device1057        )1058 1059        # embed positions1060        if attention_mask is None:1061            attention_mask = torch.ones(1062                (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device1063            )1064 1065        causal_mask = create_causal_mask(1066            config=self.config,1067            input_embeds=inputs_embeds,1068            attention_mask=attention_mask,1069            cache_position=cache_position,1070            past_key_values=past_key_values,1071            position_ids=position_ids,1072        )1073 1074        hidden_states = inputs_embeds1075 1076        for idx, decoder_layer in enumerate(self.layers):1077            # TODO(ls): Add cross attention values to respective lists1078            if idx % self.cross_layer_interval == 0:1079                cross_attn_block = self.gated_cross_attn_layers[idx // self.cross_layer_interval]1080                hidden_states = cross_attn_block(1081                    hidden_states,1082                    causal_mask,1083                    image_hidden_states,1084                    image_attention_mask=image_attention_mask,1085                    cross_attention_gate=cross_attention_gate,1086                    past_key_values=None,  # not implemented1087                    **kwargs,1088                )1089 1090            hidden_states = decoder_layer(1091                hidden_states,1092                attention_mask=causal_mask,1093                position_ids=position_ids,1094                past_key_values=past_key_values,1095                cache_position=cache_position,1096                **kwargs,1097            )1098 1099        hidden_states = self.norm(hidden_states)1100        image_hidden_states = image_hidden_states.view(batch_size, num_images, image_seq_len, image_hidden_size)1101 1102        return IdeficsBaseModelOutputWithPast(1103            last_hidden_state=hidden_states,1104            image_hidden_states=image_hidden_states,1105            past_key_values=past_key_values,1106        )1107 1108 1109class IdeficsForVisionText2Text(IdeficsPreTrainedModel, GenerationMixin):1110    _tied_weights_keys = ["model.embed_tokens.weight", "lm_head.weight"]1111 1112    def __init__(self, config, vision_model=None):1113        super().__init__(config)1114        self.model = IdeficsModel(config)1115 1116        self.lm_head = IdeficsDecoupledLinear(1117            in_features=config.hidden_size,1118            out_features=config.vocab_size,1119            out_additional_features=config.additional_vocab_size,1120            bias=False,1121            partially_freeze=config.freeze_lm_head,1122        )1123 1124        # Initialize weights and apply final processing1125        self.post_init()1126 1127    def tie_weights(self):1128        """1129        Overwrite `transformers.modeling_utils.PreTrainedModel.tie_weights` to handle the case of1130        IdeficsDecoupledLinear and IdeficsDecoupledEmbedding.1131        """1132        output_embeddings = self.get_output_embeddings()1133        input_embeddings = self.get_input_embeddings()1134 1135        if getattr(self.config, "tie_word_embeddings", True):1136            output_embeddings.weight = input_embeddings.weight1137            if input_embeddings.num_additional_embeddings > 0:1138                assert output_embeddings.out_additional_features == input_embeddings.num_additional_embeddings1139                output_embeddings.additional_fc.weight = input_embeddings.additional_embedding.weight1140 1141        if hasattr(output_embeddings, "out_features") and hasattr(input_embeddings, "num_embeddings"):1142            output_embeddings.out_features = input_embeddings.num_embeddings1143            if hasattr(output_embeddings, "out_additional_features") and hasattr(1144                input_embeddings, "num_additional_embeddings"1145            ):1146                output_embeddings.out_additional_features = input_embeddings.num_additional_embeddings1147 1148    @can_return_tuple1149    @auto_docstring1150    def forward(1151        self,1152        input_ids: Optional[torch.LongTensor] = None,1153        attention_mask: Optional[torch.Tensor] = None,1154        position_ids: Optional[torch.LongTensor] = None,1155        past_key_values: Optional[Cache] = None,1156        inputs_embeds: Optional[torch.FloatTensor] = None,1157        pixel_values: Optional[torch.FloatTensor] = None,1158        image_encoder_embeddings: Optional[torch.FloatTensor] = None,1159        perceiver_embeddings: Optional[torch.FloatTensor] = None,1160        image_attention_mask: Optional[torch.Tensor] = None,1161        labels: Optional[torch.LongTensor] = None,1162        use_cache: Optional[bool] = None,1163        interpolate_pos_encoding: Optional[bool] = False,1164        cache_position: Optional[torch.LongTensor] = None,1165        **kwargs: Unpack[TransformersKwargs],1166    ) -> Union[tuple, IdeficsCausalLMOutputWithPast]:1167        r"""1168        image_encoder_embeddings (`torch.FloatTensor`, *optional*):1169            The output of the image encoder.1170        perceiver_embeddings (`torch.FloatTensor`, *optional*):1171            The output of the perceiver resampler.1172        image_attention_mask (`torch.LongTensor`, *optional*):1173            The attention mask for the image encoder.1174        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):1175            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,1176            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored1177            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.1178 1179        Example:1180 1181        ```python1182        >>> from transformers import AutoProcessor, IdeficsForVisionText2Text1183 1184        >>> model = IdeficsForVisionText2Text.from_pretrained("HuggingFaceM4/idefics-9b")1185        >>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics-9b")1186 1187        >>> dogs_image_url_1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image1.jpeg"1188        >>> dogs_image_url_2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image2.jpeg"1189 1190        >>> prompts = [1191        ...     [1192        ...         "User:",1193        ...         dogs_image_url_1,1194        ...         "Describe this image.\nAssistant: An image of two dogs.\n",1195        ...         "User:",1196        ...         dogs_image_url_2,1197        ...         "Describe this image.\nAssistant:",1198        ...     ]1199        ... ]1200        >>> inputs = processor(prompts, return_tensors="pt")

Showing the first 1,200 of 1311 lines. Download the file for the rest.

Aluode/PerceptionLabPortable · CoolFace