CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
modeling_vipllava.py463 linesDownload Raw Back to vipllava
1#                ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ2#           This file was automatically generated from src/transformers/models/vipllava/modular_vipllava.py.3#               Do NOT edit this file manually as any edits will be overwritten by the generation of4#             the file from the modular. If any change should be done, please apply the change to the5#                          modular_vipllava.py file directly. One of our CI enforces this.6#                ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ7# coding=utf-88# Copyright 2023 the HuggingFace Inc. team. All rights reserved.9#10# Licensed under the Apache License, Version 2.0 (the "License");11# you may not use this file except in compliance with the License.12# You may obtain a copy of the License at13#14#     http://www.apache.org/licenses/LICENSE-2.015#16# Unless required by applicable law or agreed to in writing, software17# distributed under the License is distributed on an "AS IS" BASIS,18# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.19# See the License for the specific language governing permissions and20# limitations under the License.21 22from dataclasses import dataclass23from typing import Optional, Union24 25import torch26from torch import nn27 28from ...activations import ACT2FN29from ...cache_utils import Cache30from ...generation import GenerationMixin31from ...modeling_outputs import BaseModelOutputWithPast, ModelOutput32from ...modeling_utils import PreTrainedModel33from ...utils import auto_docstring, can_return_tuple34from ..auto import AutoModel35from .configuration_vipllava import VipLlavaConfig36 37 38@dataclass39@auto_docstring(40    custom_intro="""41    Base class for VipLlava outputs, with hidden states and attentions.42    """43)44class VipLlavaModelOutputWithPast(BaseModelOutputWithPast):45    r"""46    past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):47        It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).48 49        Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see50        `past_key_values` input) to speed up sequential decoding.51    image_hidden_states (`torch.FloatTensor`, *optional*):52        A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.53        image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.54    """55 56    image_hidden_states: Optional[torch.FloatTensor] = None57 58 59@dataclass60@auto_docstring(61    custom_intro="""62    Base class for VipLlava causal language model (or autoregressive) outputs.63    """64)65class VipLlavaCausalLMOutputWithPast(ModelOutput):66    r"""67    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):68        Language modeling loss (for next-token prediction).69    logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):70        Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).71    past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):72        It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).73 74        Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see75        `past_key_values` input) to speed up sequential decoding.76    image_hidden_states (`torch.FloatTensor`, *optional*):77        A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.78        image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.79    """80 81    loss: Optional[torch.FloatTensor] = None82    logits: Optional[torch.FloatTensor] = None83    past_key_values: Optional[Cache] = None84    hidden_states: Optional[tuple[torch.FloatTensor]] = None85    attentions: Optional[tuple[torch.FloatTensor]] = None86    image_hidden_states: Optional[torch.FloatTensor] = None87 88 89class VipLlavaMultiModalProjector(nn.Module):90    def __init__(self, config: VipLlavaConfig):91        super().__init__()92        num_feature_layers = 1 if isinstance(config.vision_feature_layers, int) else len(config.vision_feature_layers)93        self.projector_layernorm = nn.LayerNorm(94            num_feature_layers * config.vision_config.hidden_size, eps=config.projector_layernorm_eps95        )96 97        self.linear_1 = nn.Linear(98            num_feature_layers * config.vision_config.hidden_size,99            config.text_config.hidden_size,100            bias=True,101        )102        self.act = ACT2FN[config.projector_hidden_act]103        self.linear_2 = nn.Linear(config.text_config.hidden_size, config.text_config.hidden_size, bias=True)104 105    def forward(self, hidden_states):106        hidden_states = self.projector_layernorm(hidden_states)107        hidden_states = self.linear_1(hidden_states)108        hidden_states = self.act(hidden_states)109        hidden_states = self.linear_2(hidden_states)110        return hidden_states111 112 113@auto_docstring114class VipLlavaPreTrainedModel(PreTrainedModel):115    config: VipLlavaConfig116    base_model_prefix = ""117    supports_gradient_checkpointing = True118    _skip_keys_device_placement = "past_key_values"119 120    _supports_flash_attn = True121    _supports_sdpa = True122 123    _can_compile_fullgraph = True124    _supports_flex_attn = True125    _supports_attention_backend = True126 127 128@auto_docstring(129    custom_intro="""130    The VipLlava model which consists of a vision backbone and a language model, without a language modeling head.131    """132)133class VipLlavaModel(VipLlavaPreTrainedModel):134    _checkpoint_conversion_mapping = {"language_model.model": "language_model"}135 136    def __init__(self, config: VipLlavaConfig):137        super().__init__(config)138        self.vision_tower = AutoModel.from_config(config.vision_config)139 140        self.multi_modal_projector = VipLlavaMultiModalProjector(config)141        self.language_model = AutoModel.from_config(config.text_config)142        self.post_init()143 144    def get_input_embeddings(self):145        return self.language_model.get_input_embeddings()146 147    def set_input_embeddings(self, value):148        self.language_model.set_input_embeddings(value)149 150    def set_decoder(self, decoder):151        self.language_model = decoder152 153    def get_decoder(self):154        return self.language_model155 156    def get_image_features(157        self, pixel_values: torch.FloatTensor, vision_feature_layers: Optional[Union[int, list[int]]] = None158    ):159        """160        Obtains image last hidden states from the vision tower and apply multimodal projection.161 162        Args:163            pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)164               The tensors corresponding to the input images.165            vision_feature_layers (`Union[int, list[int]]`):166                The vision feature layer, or the list of indexes of the layers to select167                the vision feature.168        Returns:169            image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).170        """171        vision_feature_layers = (172            vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers173        )174        image_outputs = self.vision_tower(pixel_values, output_hidden_states=True)175 176        # If multiple feature layers are provided (which is usually the case)177        # then the image features are concatenated after the CLS is removed.178        if isinstance(vision_feature_layers, int):179            image_features = image_outputs.hidden_states[vision_feature_layers][:, 1:]180        else:181            # Usually, we select the features from index 1: the layers -2, -5, -8, -11 and 6182            image_features = [image_outputs.hidden_states[index][:, 1:] for index in vision_feature_layers]183            image_features = torch.cat(image_features, dim=-1)184        image_features = self.multi_modal_projector(image_features)185        return image_features186 187    def get_placeholder_mask(188        self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor189    ):190        """191        Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is192        equal to the length of multimodal features. If the lengths are different, an error is raised.193        """194        if input_ids is None:195            special_image_mask = inputs_embeds == self.get_input_embeddings()(196                torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)197            )198            special_image_mask = special_image_mask.all(-1)199        else:200            special_image_mask = input_ids == self.config.image_token_id201 202        n_image_tokens = special_image_mask.sum()203        special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)204        n_image_features = image_features.shape[0] * image_features.shape[1]205        if inputs_embeds[special_image_mask].numel() != image_features.numel():206            raise ValueError(207                f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"208            )209        return special_image_mask210 211    @auto_docstring212    def forward(213        self,214        input_ids: Optional[torch.LongTensor] = None,215        pixel_values: Optional[torch.FloatTensor] = None,216        attention_mask: Optional[torch.Tensor] = None,217        position_ids: Optional[torch.LongTensor] = None,218        past_key_values: Optional[Cache] = None,219        inputs_embeds: Optional[torch.FloatTensor] = None,220        vision_feature_layers: Optional[Union[int, list[int]]] = None,221        use_cache: Optional[bool] = None,222        output_attentions: Optional[bool] = None,223        output_hidden_states: Optional[bool] = None,224        return_dict: Optional[bool] = None,225        cache_position: Optional[torch.LongTensor] = None,226        **lm_kwargs,227    ) -> Union[tuple, VipLlavaModelOutputWithPast]:228        r"""229        vision_feature_layers (`Union[int, list[int]]`, *optional*):230            The vision feature layer, or the list of indexes of the layers to select231            the vision feature.232        """233        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions234        output_hidden_states = (235            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states236        )237        return_dict = return_dict if return_dict is not None else self.config.use_return_dict238        vision_feature_layers = (239            vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers240        )241 242        if (input_ids is None) ^ (inputs_embeds is not None):243            raise ValueError("You must specify exactly one of input_ids or inputs_embeds")244 245        if inputs_embeds is None:246            inputs_embeds = self.get_input_embeddings()(input_ids)247 248        if pixel_values is not None:249            image_features = self.get_image_features(250                pixel_values=pixel_values, vision_feature_layers=vision_feature_layers251            )252            image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)253            special_image_mask = self.get_placeholder_mask(254                input_ids, inputs_embeds=inputs_embeds, image_features=image_features255            )256            inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)257 258        outputs = self.language_model(259            attention_mask=attention_mask,260            position_ids=position_ids,261            past_key_values=past_key_values,262            inputs_embeds=inputs_embeds,263            use_cache=use_cache,264            output_attentions=output_attentions,265            output_hidden_states=output_hidden_states,266            return_dict=True,267            cache_position=cache_position,268            **lm_kwargs,269        )270 271        output = VipLlavaModelOutputWithPast(272            last_hidden_state=outputs.last_hidden_state,273            past_key_values=outputs.past_key_values,274            hidden_states=outputs.hidden_states,275            attentions=outputs.attentions,276            image_hidden_states=image_features if pixel_values is not None else None,277        )278        return output if return_dict else output.to_tuple()279 280 281@auto_docstring(282    custom_intro="""283    The VIPLLAVA model which consists of a vision backbone and a language model.284    """285)286class VipLlavaForConditionalGeneration(VipLlavaPreTrainedModel, GenerationMixin):287    _checkpoint_conversion_mapping = {288        "^language_model.model": "model.language_model",289        "^vision_tower": "model.vision_tower",290        "^multi_modal_projector": "model.multi_modal_projector",291        "^language_model.lm_head": "lm_head",292    }293    _tied_weights_keys = ["lm_head.weight"]294 295    def __init__(self, config: VipLlavaConfig):296        super().__init__(config)297        self.model = VipLlavaModel(config)298        self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)299        self.post_init()300 301    def get_input_embeddings(self):302        return self.model.get_input_embeddings()303 304    def set_input_embeddings(self, value):305        self.model.set_input_embeddings(value)306 307    def get_output_embeddings(self) -> nn.Module:308        return self.lm_head309 310    def set_decoder(self, decoder):311        self.model.set_decoder(decoder)312 313    def get_decoder(self):314        return self.model.get_decoder()315 316    def get_image_features(317        self, pixel_values: torch.FloatTensor, vision_feature_layers: Optional[Union[int, list[int]]] = None318    ):319        return self.model.get_image_features(pixel_values=pixel_values, vision_feature_layers=vision_feature_layers)320 321    # Make modules available through conditional class for BC322    @property323    def language_model(self):324        return self.model.language_model325 326    @property327    def vision_tower(self):328        return self.model.vision_tower329 330    @property331    def multi_modal_projector(self):332        return self.model.multi_modal_projector333 334    @can_return_tuple335    @auto_docstring336    def forward(337        self,338        input_ids: Optional[torch.LongTensor] = None,339        pixel_values: Optional[torch.FloatTensor] = None,340        attention_mask: Optional[torch.Tensor] = None,341        position_ids: Optional[torch.LongTensor] = None,342        past_key_values: Optional[Cache] = None,343        inputs_embeds: Optional[torch.FloatTensor] = None,344        vision_feature_layers: Optional[Union[int, list[int]]] = None,345        labels: Optional[torch.LongTensor] = None,346        use_cache: Optional[bool] = None,347        output_attentions: Optional[bool] = None,348        output_hidden_states: Optional[bool] = None,349        return_dict: Optional[bool] = None,350        cache_position: Optional[torch.LongTensor] = None,351        logits_to_keep: Union[int, torch.Tensor] = 0,352        **lm_kwargs,353    ) -> Union[tuple, VipLlavaCausalLMOutputWithPast]:354        r"""355        vision_feature_layers (`Union[int, list[int]]`, *optional*):356            The vision feature layer, or the list of indexes of the layers to select357            the vision feature.358        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):359            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,360            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored361            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.362 363        Example:364 365        ```python366        >>> import torch367        >>> from PIL import Image368        >>> import requests369        >>> from transformers import AutoProcessor, VipLlavaForConditionalGeneration370 371        >>> model = VipLlavaForConditionalGeneration.from_pretrained("llava-hf/vip-llava-7b-hf", device_map="auto", dtype=torch.float16)372        >>> processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-7b-hf")373 374        >>> prompt = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n{}###Assistant:"375        >>> question = "Can you please describe this image?"376        >>> prompt = prompt.format(question)377        >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/compel-neg.png"378        >>> image = Image.open(requests.get(url, stream=True).raw)379 380        >>> inputs = processor(text=text, images=image, return_tensors="pt").to(0, torch.float16)381 382        >>> # Generate383        >>> generate_ids = model.generate(**inputs, max_new_tokens=20)384        >>> processor.decode(generate_ids[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)385        The image features a brown and white cat sitting on a green surface, with a red ball in its386        ```"""387 388        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions389        output_hidden_states = (390            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states391        )392        return_dict = return_dict if return_dict is not None else self.config.use_return_dict393        vision_feature_layers = (394            vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers395        )396 397        outputs = self.model(398            input_ids=input_ids,399            pixel_values=pixel_values,400            attention_mask=attention_mask,401            position_ids=position_ids,402            past_key_values=past_key_values,403            inputs_embeds=inputs_embeds,404            use_cache=use_cache,405            vision_feature_layers=vision_feature_layers,406            output_attentions=output_attentions,407            output_hidden_states=output_hidden_states,408            return_dict=True,409            cache_position=cache_position,410            **lm_kwargs,411        )412 413        hidden_states = outputs[0]414        # Only compute necessary logits, and do not upcast them to float if we are not computing the loss415        slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep416        logits = self.lm_head(hidden_states[:, slice_indices, :])417 418        loss = None419        if labels is not None:420            loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)421 422        return VipLlavaCausalLMOutputWithPast(423            loss=loss,424            logits=logits,425            past_key_values=outputs.past_key_values,426            hidden_states=outputs.hidden_states,427            attentions=outputs.attentions,428            image_hidden_states=outputs.image_hidden_states,429        )430 431    def prepare_inputs_for_generation(432        self,433        input_ids,434        past_key_values=None,435        inputs_embeds=None,436        pixel_values=None,437        attention_mask=None,438        cache_position=None,439        logits_to_keep=None,440        **kwargs,441    ):442        # Overwritten -- in specific circumstances we don't want to forward image inputs to the model443 444        model_inputs = super().prepare_inputs_for_generation(445            input_ids,446            past_key_values=past_key_values,447            inputs_embeds=inputs_embeds,448            attention_mask=attention_mask,449            cache_position=cache_position,450            logits_to_keep=logits_to_keep,451            **kwargs,452        )453 454        if cache_position[0] == 0:455            # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore456            # Otherwise we need pixel values to be passed to model457            model_inputs["pixel_values"] = pixel_values458 459        return model_inputs460 461 462__all__ = ["VipLlavaModel", "VipLlavaForConditionalGeneration", "VipLlavaPreTrainedModel"]463 
Aluode/PerceptionLabPortable ยท CoolFace