Upload modeling_ovis.py
Browse files- modeling_ovis.py +590 -0
 
    	
        modeling_ovis.py
    ADDED
    
    | 
         @@ -0,0 +1,590 @@ 
     | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            # Copyright (C) 2025 AIDC-AI
         
     | 
| 2 | 
         
            +
            #
         
     | 
| 3 | 
         
            +
            # Licensed under the Apache License, Version 2.0 (the "License");
         
     | 
| 4 | 
         
            +
            # you may not use this file except in compliance with the License.
         
     | 
| 5 | 
         
            +
            # You may obtain a copy of the License at
         
     | 
| 6 | 
         
            +
            #     http://www.apache.org/licenses/LICENSE-2.0
         
     | 
| 7 | 
         
            +
            #
         
     | 
| 8 | 
         
            +
            # Unless required by applicable law or agreed to in writing, software
         
     | 
| 9 | 
         
            +
            # distributed under the License is distributed on an "AS IS" BASIS,
         
     | 
| 10 | 
         
            +
            # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
         
     | 
| 11 | 
         
            +
            #
         
     | 
| 12 | 
         
            +
            # See the License for the specific language governing permissions and
         
     | 
| 13 | 
         
            +
            # limitations under the License.
         
     | 
| 14 | 
         
            +
             
     | 
| 15 | 
         
            +
            import logging
         
     | 
| 16 | 
         
            +
            import os
         
     | 
| 17 | 
         
            +
            import importlib.metadata
         
     | 
| 18 | 
         
            +
             
     | 
| 19 | 
         
            +
            from packaging import version
         
     | 
| 20 | 
         
            +
            from importlib import import_module
         
     | 
| 21 | 
         
            +
            from typing import List, Callable, Union, Optional, Dict
         
     | 
| 22 | 
         
            +
             
     | 
| 23 | 
         
            +
            import PIL.Image
         
     | 
| 24 | 
         
            +
            import torch
         
     | 
| 25 | 
         
            +
            from torch import Tensor
         
     | 
| 26 | 
         
            +
            from torch.nn import init
         
     | 
| 27 | 
         
            +
            from torch.nn.functional import softmax, gumbel_softmax, pad
         
     | 
| 28 | 
         
            +
            from transformers.utils import is_flash_attn_2_available
         
     | 
| 29 | 
         
            +
            from transformers import PreTrainedModel, AutoModel, AutoTokenizer, AutoModelForCausalLM, AutoImageProcessor
         
     | 
| 30 | 
         
            +
            from transformers.generation.utils import GenerateOutput
         
     | 
| 31 | 
         
            +
             
     | 
| 32 | 
         
            +
            from .configuration_ovis import BaseVisualTokenizerConfig, Aimv2VisualTokenizerConfig
         
     | 
| 33 | 
         
            +
            from .configuration_ovis import OvisConfig, ConversationFormatter
         
     | 
| 34 | 
         
            +
            from .configuration_ovis import IGNORE_ID, IMAGE_ATOM_ID, IMAGE_INDICATOR_IDS, IMAGE_TOKEN_ID
         
     | 
| 35 | 
         
            +
             
     | 
| 36 | 
         
            +
            # ----------------------------------------------------------------------
         
     | 
| 37 | 
         
            +
            #                            Visual Tokenizer
         
     | 
| 38 | 
         
            +
            # ----------------------------------------------------------------------
         
     | 
| 39 | 
         
            +
            class BaseVisualTokenizer(PreTrainedModel):
         
     | 
| 40 | 
         
            +
                base_model_prefix = "backbone"
         
     | 
| 41 | 
         
            +
                main_input_name = None
         
     | 
| 42 | 
         
            +
                _image_processor_class = None
         
     | 
| 43 | 
         
            +
                _image_processor_kwargs = {}
         
     | 
| 44 | 
         
            +
                _backbone_class = None
         
     | 
| 45 | 
         
            +
                _backbone_name_or_path = None
         
     | 
| 46 | 
         
            +
             
     | 
| 47 | 
         
            +
                def __init__(self, config: BaseVisualTokenizerConfig, *inputs, **kwargs):
         
     | 
| 48 | 
         
            +
                    super().__init__(config, *inputs, **kwargs)
         
     | 
| 49 | 
         
            +
                    self.image_processor = AutoImageProcessor.from_pretrained(kwargs['image_processor_name_or_path'])
         
     | 
| 50 | 
         
            +
                    self.backbone = AutoModel.from_config(self.config.backbone_config)
         
     | 
| 51 | 
         
            +
                    head_dim = self.config.vocab_size - len(IMAGE_INDICATOR_IDS)  # reserved tokens for IMAGE_INDICATORS
         
     | 
| 52 | 
         
            +
                    self.head = torch.nn.Sequential(
         
     | 
| 53 | 
         
            +
                        torch.nn.Linear(
         
     | 
| 54 | 
         
            +
                            self.backbone.config.hidden_size * self.config.hidden_stride * self.config.hidden_stride, head_dim,
         
     | 
| 55 | 
         
            +
                            bias=False
         
     | 
| 56 | 
         
            +
                        ),
         
     | 
| 57 | 
         
            +
                        torch.nn.LayerNorm(head_dim)
         
     | 
| 58 | 
         
            +
                    )
         
     | 
| 59 | 
         
            +
             
     | 
| 60 | 
         
            +
                    assert all((self.image_processor.do_resize,
         
     | 
| 61 | 
         
            +
                                not getattr(self.image_processor, 'do_center_crop', False),
         
     | 
| 62 | 
         
            +
                                self.image_processor.do_rescale,
         
     | 
| 63 | 
         
            +
                                self.image_processor.do_normalize
         
     | 
| 64 | 
         
            +
                                )), f"image_processor `{self.image_processor}` is not supported currently"
         
     | 
| 65 | 
         
            +
             
     | 
| 66 | 
         
            +
                def get_backbone(self):
         
     | 
| 67 | 
         
            +
                    return self.backbone
         
     | 
| 68 | 
         
            +
             
     | 
| 69 | 
         
            +
                def get_image_processor(self):
         
     | 
| 70 | 
         
            +
                    return self.image_processor
         
     | 
| 71 | 
         
            +
             
     | 
| 72 | 
         
            +
                def mock_input(self):
         
     | 
| 73 | 
         
            +
                    height, width = self.get_image_size()
         
     | 
| 74 | 
         
            +
                    return torch.zeros(1, 3, height, width), self.construct_image_placeholders((1, 1))
         
     | 
| 75 | 
         
            +
             
     | 
| 76 | 
         
            +
                def get_head(self):
         
     | 
| 77 | 
         
            +
                    return self.head
         
     | 
| 78 | 
         
            +
             
     | 
| 79 | 
         
            +
                def get_image_size(self):
         
     | 
| 80 | 
         
            +
                    raise NotImplementedError
         
     | 
| 81 | 
         
            +
             
     | 
| 82 | 
         
            +
                @staticmethod
         
     | 
| 83 | 
         
            +
                def construct_image_placeholders(grid):
         
     | 
| 84 | 
         
            +
                    image_placeholders = [IMAGE_INDICATOR_IDS[0], IMAGE_ATOM_ID, IMAGE_INDICATOR_IDS[1]]
         
     | 
| 85 | 
         
            +
                    if grid[0] * grid[1] > 1:
         
     | 
| 86 | 
         
            +
                        for r in range(grid[0]):
         
     | 
| 87 | 
         
            +
                            for c in range(grid[1]):
         
     | 
| 88 | 
         
            +
                                image_placeholders.append(IMAGE_ATOM_ID)
         
     | 
| 89 | 
         
            +
                                if c < grid[1] - 1:
         
     | 
| 90 | 
         
            +
                                    image_placeholders.append(IMAGE_INDICATOR_IDS[2])
         
     | 
| 91 | 
         
            +
                            if r < grid[0] - 1:
         
     | 
| 92 | 
         
            +
                                image_placeholders.append(IMAGE_INDICATOR_IDS[3])
         
     | 
| 93 | 
         
            +
                    image_placeholders.append(IMAGE_INDICATOR_IDS[4])
         
     | 
| 94 | 
         
            +
                    return image_placeholders
         
     | 
| 95 | 
         
            +
             
     | 
| 96 | 
         
            +
                def preprocess_image(self, image: PIL.Image.Image, max_partition=9, covering_threshold=0.9, convert_to_rgb=True):
         
     | 
| 97 | 
         
            +
                    def _preprocess(img: PIL.Image.Image, side):
         
     | 
| 98 | 
         
            +
                        # first resize and preprocess
         
     | 
| 99 | 
         
            +
                        w, h = img.size
         
     | 
| 100 | 
         
            +
                        if w == h:
         
     | 
| 101 | 
         
            +
                            new_width = new_height = side
         
     | 
| 102 | 
         
            +
                        elif w > h:
         
     | 
| 103 | 
         
            +
                            new_width = side
         
     | 
| 104 | 
         
            +
                            new_height = int(h / w * new_width)
         
     | 
| 105 | 
         
            +
                        else:
         
     | 
| 106 | 
         
            +
                            new_height = side
         
     | 
| 107 | 
         
            +
                            new_width = int(w / h * new_height)
         
     | 
| 108 | 
         
            +
                        new_size = dict(height=new_height, width=new_width)
         
     | 
| 109 | 
         
            +
                        pixel_values = self.image_processor.preprocess(img, size=new_size, return_tensors='pt')['pixel_values']
         
     | 
| 110 | 
         
            +
             
     | 
| 111 | 
         
            +
                        # then pad to square
         
     | 
| 112 | 
         
            +
                        square_values = torch.zeros([1, 3, side, side], dtype=pixel_values.dtype, device=pixel_values.device)
         
     | 
| 113 | 
         
            +
                        new_height, new_width = pixel_values.shape[2:]
         
     | 
| 114 | 
         
            +
                        if new_height == new_width:
         
     | 
| 115 | 
         
            +
                            square_values[:, :, :, :] = pixel_values
         
     | 
| 116 | 
         
            +
                        elif new_height > new_width:
         
     | 
| 117 | 
         
            +
                            from_index = (side - new_width) // 2
         
     | 
| 118 | 
         
            +
                            square_values[:, :, :, from_index:from_index + new_width] = pixel_values
         
     | 
| 119 | 
         
            +
                        else:
         
     | 
| 120 | 
         
            +
                            from_index = (side - new_height) // 2
         
     | 
| 121 | 
         
            +
                            square_values[:, :, from_index:from_index + new_height, :] = pixel_values
         
     | 
| 122 | 
         
            +
             
     | 
| 123 | 
         
            +
                        return square_values
         
     | 
| 124 | 
         
            +
             
     | 
| 125 | 
         
            +
                    def _partition(img, grid):
         
     | 
| 126 | 
         
            +
                        w, h = img.size
         
     | 
| 127 | 
         
            +
                        row_height = h // grid[0]
         
     | 
| 128 | 
         
            +
                        col_width = w // grid[1]
         
     | 
| 129 | 
         
            +
             
     | 
| 130 | 
         
            +
                        partition = []
         
     | 
| 131 | 
         
            +
                        for row in range(grid[0]):
         
     | 
| 132 | 
         
            +
                            for col in range(grid[1]):
         
     | 
| 133 | 
         
            +
                                left = col * col_width
         
     | 
| 134 | 
         
            +
                                upper = row * row_height
         
     | 
| 135 | 
         
            +
                                right = w if col == grid[1] - 1 else (col + 1) * col_width
         
     | 
| 136 | 
         
            +
                                lower = h if row == grid[0] - 1 else (row + 1) * row_height
         
     | 
| 137 | 
         
            +
                                partition.append((left, upper, right, lower))
         
     | 
| 138 | 
         
            +
             
     | 
| 139 | 
         
            +
                        return partition
         
     | 
| 140 | 
         
            +
             
     | 
| 141 | 
         
            +
                    def _covering_area(left, upper, right, lower, side):
         
     | 
| 142 | 
         
            +
                        w = right - left
         
     | 
| 143 | 
         
            +
                        h = lower - upper
         
     | 
| 144 | 
         
            +
                        w, h = max(w, h), min(w, h)
         
     | 
| 145 | 
         
            +
                        if w > side:
         
     | 
| 146 | 
         
            +
                            h = h / w * side
         
     | 
| 147 | 
         
            +
                            w = side
         
     | 
| 148 | 
         
            +
                        return w * h
         
     | 
| 149 | 
         
            +
             
     | 
| 150 | 
         
            +
                    def _get_best_grid(img, side):
         
     | 
| 151 | 
         
            +
                        img_area = img.size[0] * img.size[1]
         
     | 
| 152 | 
         
            +
             
     | 
| 153 | 
         
            +
                        candidate_grids = []
         
     | 
| 154 | 
         
            +
                        for i in range(1, max_partition + 1):
         
     | 
| 155 | 
         
            +
                            for j in range(1, max_partition + 1):
         
     | 
| 156 | 
         
            +
                                if i * j <= max_partition:
         
     | 
| 157 | 
         
            +
                                    candidate_grids.append((i, j))
         
     | 
| 158 | 
         
            +
             
     | 
| 159 | 
         
            +
                        all_grids = []
         
     | 
| 160 | 
         
            +
                        good_grids = []
         
     | 
| 161 | 
         
            +
                        for grid in candidate_grids:
         
     | 
| 162 | 
         
            +
                            partition = _partition(img, grid)
         
     | 
| 163 | 
         
            +
                            covering_ratio = sum([_covering_area(*p, side) for p in partition]) / img_area
         
     | 
| 164 | 
         
            +
                            assert covering_ratio <= 1.0
         
     | 
| 165 | 
         
            +
                            all_grids.append((grid, covering_ratio))
         
     | 
| 166 | 
         
            +
                            if covering_ratio > covering_threshold:
         
     | 
| 167 | 
         
            +
                                good_grids.append((grid, covering_ratio))
         
     | 
| 168 | 
         
            +
             
     | 
| 169 | 
         
            +
                        if len(good_grids) > 0:
         
     | 
| 170 | 
         
            +
                            # pick the good partition with minimum #sub_images and break the tie using covering_ratio
         
     | 
| 171 | 
         
            +
                            return sorted(good_grids, key=lambda x: (x[0][0] * x[0][1], -x[1]))[0][0]
         
     | 
| 172 | 
         
            +
                        else:
         
     | 
| 173 | 
         
            +
                            # pick the partition with maximum covering_ratio and break the tie using #sub_images
         
     | 
| 174 | 
         
            +
                            return sorted(all_grids, key=lambda x: (-x[1], x[0][0] * x[0][1]))[0][0]
         
     | 
| 175 | 
         
            +
             
     | 
| 176 | 
         
            +
                    if convert_to_rgb and image.mode != 'RGB':
         
     | 
| 177 | 
         
            +
                        image = image.convert('RGB')
         
     | 
| 178 | 
         
            +
             
     | 
| 179 | 
         
            +
                    sides = self.get_image_size()
         
     | 
| 180 | 
         
            +
                    if sides[0] != sides[1]:
         
     | 
| 181 | 
         
            +
                        raise ValueError('get_image_size() returns non-square size')
         
     | 
| 182 | 
         
            +
                    side = sides[0]
         
     | 
| 183 | 
         
            +
                    grid = _get_best_grid(image, side)
         
     | 
| 184 | 
         
            +
                    partition = _partition(image, grid)
         
     | 
| 185 | 
         
            +
                    crops = [image.crop(p) for p in partition]
         
     | 
| 186 | 
         
            +
                    if len(crops) > 1:
         
     | 
| 187 | 
         
            +
                        crops.insert(0, image)
         
     | 
| 188 | 
         
            +
                    pixel_values = torch.cat([_preprocess(crop, side) for crop in crops], dim=0)
         
     | 
| 189 | 
         
            +
                    image_placeholders = self.construct_image_placeholders(grid)
         
     | 
| 190 | 
         
            +
                    return pixel_values, image_placeholders
         
     | 
| 191 | 
         
            +
             
     | 
| 192 | 
         
            +
                def tokenize(self, logits):
         
     | 
| 193 | 
         
            +
                    def st_argmax(y_soft, dim):  # straight-through softmax
         
     | 
| 194 | 
         
            +
                        index = y_soft.max(dim, keepdim=True)[1]
         
     | 
| 195 | 
         
            +
                        y_hard = torch.zeros_like(y_soft, memory_format=torch.legacy_contiguous_format).scatter_(dim, index, 1.0)
         
     | 
| 196 | 
         
            +
                        ret = y_hard - y_soft.detach() + y_soft
         
     | 
| 197 | 
         
            +
                        return ret
         
     | 
| 198 | 
         
            +
             
     | 
| 199 | 
         
            +
                    if self.config.tokenize_function == 'softmax':
         
     | 
| 200 | 
         
            +
                        tokens = softmax(logits, dim=-1)
         
     | 
| 201 | 
         
            +
                    elif self.config.tokenize_function == 'gumbel_argmax':
         
     | 
| 202 | 
         
            +
                        tokens = gumbel_softmax(logits, tau=self.config.tau, hard=True)
         
     | 
| 203 | 
         
            +
                    elif self.config.tokenize_function == 'st_argmax':
         
     | 
| 204 | 
         
            +
                        tokens = st_argmax(logits, dim=-1)
         
     | 
| 205 | 
         
            +
                    else:
         
     | 
| 206 | 
         
            +
                        raise ValueError(
         
     | 
| 207 | 
         
            +
                            f'Invalid `max_type`, expected softmax or gumbel_argmax or st_argmax, but got {self.config.tokenize_function}')
         
     | 
| 208 | 
         
            +
                    return tokens
         
     | 
| 209 | 
         
            +
             
     | 
| 210 | 
         
            +
                def encode(self, pixel_values):
         
     | 
| 211 | 
         
            +
                    output = self.backbone(pixel_values, output_hidden_states=True, return_dict=True)
         
     | 
| 212 | 
         
            +
                    features = output.hidden_states[-1]
         
     | 
| 213 | 
         
            +
                    if self.config.drop_cls_token:
         
     | 
| 214 | 
         
            +
                        features = features[:, 1:, :]
         
     | 
| 215 | 
         
            +
             
     | 
| 216 | 
         
            +
                    # merge number of `hidden_stride * hidden_stride` hidden states together to reduce token sequence length
         
     | 
| 217 | 
         
            +
                    # e.g., for hidden_stride=2, this leads to a token length reduction: 1024 -> 256 for aimv2
         
     | 
| 218 | 
         
            +
                    if self.config.hidden_stride > 1:
         
     | 
| 219 | 
         
            +
                        n, l, d = features.shape  # this `d` maybe different from the above `d
         
     | 
| 220 | 
         
            +
                        sqrt_l = int(l ** 0.5)
         
     | 
| 221 | 
         
            +
                        assert sqrt_l ** 2 == l, "The token sequence length should be a perfect square."
         
     | 
| 222 | 
         
            +
                        features = features.reshape(n, sqrt_l, sqrt_l, d)
         
     | 
| 223 | 
         
            +
                        pl = (self.config.hidden_stride - (sqrt_l % self.config.hidden_stride)) % self.config.hidden_stride
         
     | 
| 224 | 
         
            +
                        features = pad(features, (0, 0, 0, pl, 0, pl), "constant", 0)
         
     | 
| 225 | 
         
            +
                        sqrt_l += pl
         
     | 
| 226 | 
         
            +
                        features = features.reshape(n, sqrt_l // self.config.hidden_stride, self.config.hidden_stride,
         
     | 
| 227 | 
         
            +
                                                    sqrt_l // self.config.hidden_stride, self.config.hidden_stride, d)
         
     | 
| 228 | 
         
            +
                        features = features.permute(0, 1, 3, 2, 4, 5)  # [n, sqrt_l/hs, sqrt_l/hs, hs, hs, d]
         
     | 
| 229 | 
         
            +
                        features = features.flatten(3)  # [n, sqrt_l/hs, sqrt_l/hs, hs*hs*d]
         
     | 
| 230 | 
         
            +
                        features = features.reshape(
         
     | 
| 231 | 
         
            +
                            n, -1, self.config.hidden_stride * self.config.hidden_stride * d)
         
     | 
| 232 | 
         
            +
             
     | 
| 233 | 
         
            +
                    return features
         
     | 
| 234 | 
         
            +
             
     | 
| 235 | 
         
            +
                def forward(self, pixel_values) -> torch.Tensor:  # [BatchSize, ImageShape] -> [BatchSize, #Token, VocabSize]
         
     | 
| 236 | 
         
            +
                    features = self.encode(pixel_values)
         
     | 
| 237 | 
         
            +
                    logits = self.head(features)
         
     | 
| 238 | 
         
            +
                    tokens = self.tokenize(logits)
         
     | 
| 239 | 
         
            +
                    # tokens' shape is [BatchSize, #Token, VocabSize-5], so padding with [BatchSize, #Token, 5], after
         
     | 
| 240 | 
         
            +
                    # which, tokens' shape should become [BatchSize, #Token, VocabSize]
         
     | 
| 241 | 
         
            +
                    batch_size, token_len, _ = tokens.shape
         
     | 
| 242 | 
         
            +
                    padding_tensor = torch.zeros(size=(batch_size, token_len, len(IMAGE_INDICATOR_IDS)),
         
     | 
| 243 | 
         
            +
                                                 dtype=tokens.dtype,
         
     | 
| 244 | 
         
            +
                                                 device=tokens.device,
         
     | 
| 245 | 
         
            +
                                                 layout=tokens.layout,
         
     | 
| 246 | 
         
            +
                                                 requires_grad=False)
         
     | 
| 247 | 
         
            +
                    tokens = torch.cat((tokens, padding_tensor), dim=2)
         
     | 
| 248 | 
         
            +
                    return tokens
         
     | 
| 249 | 
         
            +
             
     | 
| 250 | 
         
            +
             
     | 
| 251 | 
         
            +
            class Aimv2VisualTokenizer(BaseVisualTokenizer):
         
     | 
| 252 | 
         
            +
                config_class = Aimv2VisualTokenizerConfig
         
     | 
| 253 | 
         
            +
                supports_gradient_checkpointing = True
         
     | 
| 254 | 
         
            +
                _no_split_modules = ["AIMv2ViTPreprocessor", "AIMv2Block"]
         
     | 
| 255 | 
         
            +
                _image_processor_kwargs = dict(do_center_crop=False)
         
     | 
| 256 | 
         
            +
             
     | 
| 257 | 
         
            +
                def get_image_size(self):
         
     | 
| 258 | 
         
            +
                    height = self.image_processor.crop_size["height"]
         
     | 
| 259 | 
         
            +
                    width = self.image_processor.crop_size["width"]
         
     | 
| 260 | 
         
            +
                    return height, width
         
     | 
| 261 | 
         
            +
             
     | 
| 262 | 
         
            +
             
     | 
| 263 | 
         
            +
            AutoModel.register(Aimv2VisualTokenizerConfig, Aimv2VisualTokenizer)
         
     | 
| 264 | 
         
            +
             
     | 
| 265 | 
         
            +
             
     | 
| 266 | 
         
            +
            # ----------------------------------------------------------------------
         
     | 
| 267 | 
         
            +
            #                                  Ovis
         
     | 
| 268 | 
         
            +
            # ----------------------------------------------------------------------
         
     | 
| 269 | 
         
            +
            class VisualEmbedding(torch.nn.Embedding):
         
     | 
| 270 | 
         
            +
                def forward(self, visual_tokens: Tensor) -> Tensor:
         
     | 
| 271 | 
         
            +
                    if visual_tokens.dtype in [torch.int8, torch.int16, torch.int32, torch.int64, torch.long]:
         
     | 
| 272 | 
         
            +
                        return super().forward(visual_tokens)
         
     | 
| 273 | 
         
            +
                    return torch.matmul(visual_tokens, self.weight)
         
     | 
| 274 | 
         
            +
             
     | 
| 275 | 
         
            +
                def reset_parameters(self, mean=0., std=1.) -> None:
         
     | 
| 276 | 
         
            +
                    init.normal_(self.weight, mean=mean, std=std)
         
     | 
| 277 | 
         
            +
                    self._fill_padding_idx_with_zero()
         
     | 
| 278 | 
         
            +
             
     | 
| 279 | 
         
            +
             
     | 
| 280 | 
         
            +
            class OvisPreTrainedModel(PreTrainedModel):
         
     | 
| 281 | 
         
            +
                config_class = OvisConfig
         
     | 
| 282 | 
         
            +
                base_model_prefix = "ovis"
         
     | 
| 283 | 
         
            +
             
     | 
| 284 | 
         
            +
             
     | 
| 285 | 
         
            +
            class Ovis(OvisPreTrainedModel):
         
     | 
| 286 | 
         
            +
             
     | 
| 287 | 
         
            +
                def __init__(self, config: OvisConfig, *inputs, **kwargs):
         
     | 
| 288 | 
         
            +
                    super().__init__(config, *inputs, **kwargs)
         
     | 
| 289 | 
         
            +
                    attn_kwargs = dict()
         
     | 
| 290 | 
         
            +
                    if self.config.llm_attn_implementation:
         
     | 
| 291 | 
         
            +
                        if self.config.llm_attn_implementation == "flash_attention_2":
         
     | 
| 292 | 
         
            +
                            assert (is_flash_attn_2_available() and
         
     | 
| 293 | 
         
            +
                                    version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.6.3")), \
         
     | 
| 294 | 
         
            +
                                "Using `flash_attention_2` requires having `flash_attn>=2.6.3` installed."
         
     | 
| 295 | 
         
            +
                        attn_kwargs["attn_implementation"] = self.config.llm_attn_implementation
         
     | 
| 296 | 
         
            +
                    self.llm = AutoModelForCausalLM.from_config(self.config.llm_config, **attn_kwargs)
         
     | 
| 297 | 
         
            +
                    assert self.config.hidden_size == self.llm.config.hidden_size, "hidden size mismatch"
         
     | 
| 298 | 
         
            +
                    self.text_tokenizer = AutoTokenizer.from_pretrained(self.config.name_or_path)
         
     | 
| 299 | 
         
            +
                    self.visual_tokenizer = AutoModel.from_config(self.config.visual_tokenizer_config,
         
     | 
| 300 | 
         
            +
                                                                  image_processor_name_or_path=self.config.name_or_path)
         
     | 
| 301 | 
         
            +
                    self.vte = VisualEmbedding(
         
     | 
| 302 | 
         
            +
                        self.config.visual_tokenizer_config.vocab_size,
         
     | 
| 303 | 
         
            +
                        self.config.hidden_size,
         
     | 
| 304 | 
         
            +
                        device=self.visual_tokenizer.device,
         
     | 
| 305 | 
         
            +
                        dtype=self.visual_tokenizer.dtype
         
     | 
| 306 | 
         
            +
                    )
         
     | 
| 307 | 
         
            +
             
     | 
| 308 | 
         
            +
                    def _merge_modules(modules_list: tuple):
         
     | 
| 309 | 
         
            +
                        merged_modules = []
         
     | 
| 310 | 
         
            +
                        for modules in modules_list:
         
     | 
| 311 | 
         
            +
                            merged_modules.extend(modules if modules else [])
         
     | 
| 312 | 
         
            +
                        return merged_modules
         
     | 
| 313 | 
         
            +
             
     | 
| 314 | 
         
            +
                    self._no_split_modules = _merge_modules((self.llm._no_split_modules, self.visual_tokenizer._no_split_modules))
         
     | 
| 315 | 
         
            +
                    self._skip_keys_device_placement = self.llm._skip_keys_device_placement
         
     | 
| 316 | 
         
            +
                    self._keep_in_fp32_modules = _merge_modules(
         
     | 
| 317 | 
         
            +
                        (self.llm._keep_in_fp32_modules, self.visual_tokenizer._keep_in_fp32_modules))
         
     | 
| 318 | 
         
            +
                    self.is_parallelizable = all((self.llm.is_parallelizable, self.visual_tokenizer.is_parallelizable))
         
     | 
| 319 | 
         
            +
                    self.supports_gradient_checkpointing = True
         
     | 
| 320 | 
         
            +
                    self._supports_flash_attn_2 = True
         
     | 
| 321 | 
         
            +
             
     | 
| 322 | 
         
            +
                def get_text_tokenizer(self):
         
     | 
| 323 | 
         
            +
                    return self.text_tokenizer
         
     | 
| 324 | 
         
            +
             
     | 
| 325 | 
         
            +
                def get_visual_tokenizer(self):
         
     | 
| 326 | 
         
            +
                    return self.visual_tokenizer
         
     | 
| 327 | 
         
            +
             
     | 
| 328 | 
         
            +
                def tie_weights(self):
         
     | 
| 329 | 
         
            +
                    if not self.config.disable_tie_weight:
         
     | 
| 330 | 
         
            +
                        self.get_llm().tie_weights()
         
     | 
| 331 | 
         
            +
             
     | 
| 332 | 
         
            +
                def get_llm(self):
         
     | 
| 333 | 
         
            +
                    return self.llm
         
     | 
| 334 | 
         
            +
             
     | 
| 335 | 
         
            +
                def get_vte(self):
         
     | 
| 336 | 
         
            +
                    return self.vte
         
     | 
| 337 | 
         
            +
             
     | 
| 338 | 
         
            +
                def get_wte(self):
         
     | 
| 339 | 
         
            +
                    return self.llm.get_input_embeddings()
         
     | 
| 340 | 
         
            +
             
     | 
| 341 | 
         
            +
                def get_conversation_formatter(self) -> ConversationFormatter:
         
     | 
| 342 | 
         
            +
                    if getattr(self, 'conversation_formatter', None) is None:
         
     | 
| 343 | 
         
            +
                        self.conversation_formatter = getattr(import_module(".configuration_ovis", __package__),
         
     | 
| 344 | 
         
            +
                                                              self.config.conversation_formatter_class)(self.text_tokenizer)
         
     | 
| 345 | 
         
            +
                    return self.conversation_formatter
         
     | 
| 346 | 
         
            +
             
     | 
| 347 | 
         
            +
                def forward(
         
     | 
| 348 | 
         
            +
                    self,
         
     | 
| 349 | 
         
            +
                    input_ids: torch.Tensor,
         
     | 
| 350 | 
         
            +
                    attention_mask: torch.Tensor,
         
     | 
| 351 | 
         
            +
                    labels: Optional[torch.Tensor],
         
     | 
| 352 | 
         
            +
                    pixel_values: List[Optional[torch.Tensor]],
         
     | 
| 353 | 
         
            +
                    **kwargs
         
     | 
| 354 | 
         
            +
                ):
         
     | 
| 355 | 
         
            +
                    # assert self.training, "`forward` can only be used in training. For inference, use `generate`."
         
     | 
| 356 | 
         
            +
                    _, inputs_embeds, labels, attention_mask = self.merge_multimodal(
         
     | 
| 357 | 
         
            +
                        text_input_ids=input_ids,
         
     | 
| 358 | 
         
            +
                        text_attention_masks=attention_mask,
         
     | 
| 359 | 
         
            +
                        text_labels=labels,
         
     | 
| 360 | 
         
            +
                        pixel_values=pixel_values
         
     | 
| 361 | 
         
            +
                    )
         
     | 
| 362 | 
         
            +
                    return self.llm(inputs_embeds=inputs_embeds, labels=labels, attention_mask=attention_mask, **kwargs)
         
     | 
| 363 | 
         
            +
             
     | 
| 364 | 
         
            +
                def merge_multimodal(
         
     | 
| 365 | 
         
            +
                    self,
         
     | 
| 366 | 
         
            +
                    text_input_ids: torch.Tensor,
         
     | 
| 367 | 
         
            +
                    text_attention_masks: torch.Tensor,
         
     | 
| 368 | 
         
            +
                    text_labels: Optional[torch.Tensor],
         
     | 
| 369 | 
         
            +
                    pixel_values: List[Optional[torch.Tensor]],
         
     | 
| 370 | 
         
            +
                    left_padding: bool = False
         
     | 
| 371 | 
         
            +
                ):
         
     | 
| 372 | 
         
            +
                    input_device = text_input_ids.device
         
     | 
| 373 | 
         
            +
                    visual_vocab_szie = self.get_visual_tokenizer().config.vocab_size
         
     | 
| 374 | 
         
            +
                    visual_indicator_embeds = self.get_vte()(
         
     | 
| 375 | 
         
            +
                        torch.tensor(
         
     | 
| 376 | 
         
            +
                            list(range(visual_vocab_szie - 5, visual_vocab_szie)),
         
     | 
| 377 | 
         
            +
                            dtype=torch.long,
         
     | 
| 378 | 
         
            +
                            device=self.get_visual_tokenizer().device
         
     | 
| 379 | 
         
            +
                        )
         
     | 
| 380 | 
         
            +
                    ).to(device=input_device)
         
     | 
| 381 | 
         
            +
             
     | 
| 382 | 
         
            +
                    if self.training:
         
     | 
| 383 | 
         
            +
                        # When training, to be compatible with deepspeed zero, each sample has to include pixel_value tensor.
         
     | 
| 384 | 
         
            +
                        # For text-only sample, one can simply use a full zero tensor as pixel_value, which will be ignored
         
     | 
| 385 | 
         
            +
                        # (see below in this function); so, the gradient will not be affected.
         
     | 
| 386 | 
         
            +
                        num_images = [x.shape[0] for x in pixel_values]
         
     | 
| 387 | 
         
            +
                        visual_tokens = self.visual_tokenizer(torch.cat([x for x in pixel_values], dim=0))
         
     | 
| 388 | 
         
            +
                        visual_embeds = torch.split(self.get_vte()(visual_tokens).to(dtype=self.dtype, device=input_device),
         
     | 
| 389 | 
         
            +
                                                    split_size_or_sections=num_images, dim=0)
         
     | 
| 390 | 
         
            +
                        visual_input_ids = torch.split(torch.argmax(visual_tokens, dim=-1).to(device=input_device),
         
     | 
| 391 | 
         
            +
                                                       split_size_or_sections=num_images, dim=0)
         
     | 
| 392 | 
         
            +
                        visual_labels = [torch.full(x.shape, IGNORE_ID, dtype=torch.long, device=input_device) for x in
         
     | 
| 393 | 
         
            +
                                         visual_input_ids]
         
     | 
| 394 | 
         
            +
                    else:
         
     | 
| 395 | 
         
            +
                        # When inference, sample can include only text with `None` pixel_value
         
     | 
| 396 | 
         
            +
                        num_images = [x.shape[0] if x is not None else 0 for x in pixel_values]
         
     | 
| 397 | 
         
            +
                        if sum(num_images) > 0:
         
     | 
| 398 | 
         
            +
                            visual_tokens = self.visual_tokenizer(torch.cat([x for x in pixel_values if x is not None], dim=0))
         
     | 
| 399 | 
         
            +
                            visual_embeds = torch.split(self.get_vte()(visual_tokens).to(dtype=self.dtype, device=input_device),
         
     | 
| 400 | 
         
            +
                                                        split_size_or_sections=num_images, dim=0)
         
     | 
| 401 | 
         
            +
                            visual_input_ids = torch.split(torch.argmax(visual_tokens, dim=-1).to(device=input_device),
         
     | 
| 402 | 
         
            +
                                                           split_size_or_sections=num_images, dim=0)
         
     | 
| 403 | 
         
            +
                            visual_labels = [torch.full(x.shape, IGNORE_ID, dtype=torch.long, device=input_device) for x in
         
     | 
| 404 | 
         
            +
                                             visual_input_ids]
         
     | 
| 405 | 
         
            +
                        else:
         
     | 
| 406 | 
         
            +
                            # just placeholders
         
     | 
| 407 | 
         
            +
                            visual_embeds = [None] * len(num_images)
         
     | 
| 408 | 
         
            +
                            visual_input_ids = [None] * len(num_images)
         
     | 
| 409 | 
         
            +
                            visual_labels = [None] * len(num_images)
         
     | 
| 410 | 
         
            +
                    # just placeholders
         
     | 
| 411 | 
         
            +
                    if text_labels is None:
         
     | 
| 412 | 
         
            +
                        text_labels = torch.full(text_input_ids.shape, IGNORE_ID, dtype=torch.long, device=input_device)
         
     | 
| 413 | 
         
            +
             
     | 
| 414 | 
         
            +
                    input_embeds = []
         
     | 
| 415 | 
         
            +
                    attention_masks = []
         
     | 
| 416 | 
         
            +
                    labels = []
         
     | 
| 417 | 
         
            +
                    for text_input_id, text_label, text_attention_mask, visual_embed, visual_input_id, visual_label in zip(
         
     | 
| 418 | 
         
            +
                            text_input_ids, text_labels, text_attention_masks, visual_embeds, visual_input_ids, visual_labels
         
     | 
| 419 | 
         
            +
                    ):
         
     | 
| 420 | 
         
            +
                        placeholder_token_mask = torch.lt(text_input_id, 0)
         
     | 
| 421 | 
         
            +
                        text_embed = self.get_wte()(torch.masked_fill(text_input_id, placeholder_token_mask, 0))
         
     | 
| 422 | 
         
            +
                        for i, indicator_id in enumerate(IMAGE_INDICATOR_IDS):
         
     | 
| 423 | 
         
            +
                            text_embed[text_input_id == indicator_id] = visual_indicator_embeds[i]
         
     | 
| 424 | 
         
            +
                        image_atom_positions = torch.where(torch.eq(text_input_id, IMAGE_ATOM_ID))[0].tolist()
         
     | 
| 425 | 
         
            +
                        if len(image_atom_positions) > 0:
         
     | 
| 426 | 
         
            +
                            input_embed_parts = []
         
     | 
| 427 | 
         
            +
                            attention_mask_parts = []
         
     | 
| 428 | 
         
            +
                            label_parts = []
         
     | 
| 429 | 
         
            +
                            prev_image_atom_position = -1
         
     | 
| 430 | 
         
            +
                            for index, image_atom_position in enumerate(image_atom_positions):
         
     | 
| 431 | 
         
            +
                                input_embed_parts.append(
         
     | 
| 432 | 
         
            +
                                    text_embed[prev_image_atom_position + 1:image_atom_position, :])
         
     | 
| 433 | 
         
            +
                                label_parts.append(
         
     | 
| 434 | 
         
            +
                                    text_label[prev_image_atom_position + 1:image_atom_position])
         
     | 
| 435 | 
         
            +
                                attention_mask_parts.append(
         
     | 
| 436 | 
         
            +
                                    text_attention_mask[prev_image_atom_position + 1:image_atom_position])
         
     | 
| 437 | 
         
            +
                                input_embed_parts.append(visual_embed[index])
         
     | 
| 438 | 
         
            +
                                attention_mask_parts.append(
         
     | 
| 439 | 
         
            +
                                    torch.ones_like(visual_label[index], dtype=torch.bool))
         
     | 
| 440 | 
         
            +
                                label_parts.append(visual_label[index])
         
     | 
| 441 | 
         
            +
                                prev_image_atom_position = image_atom_position
         
     | 
| 442 | 
         
            +
                            if prev_image_atom_position + 1 < text_input_id.shape[0]:
         
     | 
| 443 | 
         
            +
                                input_embed_parts.append(
         
     | 
| 444 | 
         
            +
                                    text_embed[prev_image_atom_position + 1:, :])
         
     | 
| 445 | 
         
            +
                                attention_mask_parts.append(
         
     | 
| 446 | 
         
            +
                                    text_attention_mask[prev_image_atom_position + 1:])
         
     | 
| 447 | 
         
            +
                                label_parts.append(
         
     | 
| 448 | 
         
            +
                                    text_label[prev_image_atom_position + 1:])
         
     | 
| 449 | 
         
            +
                            input_embed = torch.cat(input_embed_parts, dim=0)
         
     | 
| 450 | 
         
            +
                            attention_mask = torch.cat(attention_mask_parts, dim=0)
         
     | 
| 451 | 
         
            +
                            label = torch.cat(label_parts, dim=0)
         
     | 
| 452 | 
         
            +
                        else:
         
     | 
| 453 | 
         
            +
                            input_embed = text_embed
         
     | 
| 454 | 
         
            +
                            attention_mask = text_attention_mask
         
     | 
| 455 | 
         
            +
                            label = text_label
         
     | 
| 456 | 
         
            +
                            if self.training:
         
     | 
| 457 | 
         
            +
                                # Make visual_embed & visual_indicator_embeds involved in the backward graph,
         
     | 
| 458 | 
         
            +
                                # to be compatible with deepspeed zero and ddp.
         
     | 
| 459 | 
         
            +
                                input_embed += torch.sum(visual_embed * 0.0) + torch.sum(visual_indicator_embeds * 0.0)
         
     | 
| 460 | 
         
            +
                        input_embeds.append(input_embed)
         
     | 
| 461 | 
         
            +
                        attention_masks.append(attention_mask)
         
     | 
| 462 | 
         
            +
                        labels.append(label)
         
     | 
| 463 | 
         
            +
             
     | 
| 464 | 
         
            +
                    if self.training:  # padding to self.config.multimodal_max_length for increased training speed
         
     | 
| 465 | 
         
            +
                        padding_size = max(0, self.config.multimodal_max_length - len(input_embeds[0]))
         
     | 
| 466 | 
         
            +
                        input_embeds[0] = torch.nn.ConstantPad2d((0, 0, 0, padding_size), 0.0)(input_embeds[0])
         
     | 
| 467 | 
         
            +
                        attention_masks[0] = torch.nn.ConstantPad1d((0, padding_size), False)(attention_masks[0])
         
     | 
| 468 | 
         
            +
                        labels[0] = torch.nn.ConstantPad1d((0, padding_size), IGNORE_ID)(labels[0])
         
     | 
| 469 | 
         
            +
                    batch_input_embeds = self.pad_truncate_sequence(input_embeds, batch_first=True, padding_value=0.0, left_padding=left_padding)
         
     | 
| 470 | 
         
            +
                    batch_attention_mask = self.pad_truncate_sequence(attention_masks, batch_first=True, padding_value=False, left_padding=left_padding)
         
     | 
| 471 | 
         
            +
                    batch_labels = self.pad_truncate_sequence(labels, batch_first=True, padding_value=IGNORE_ID, left_padding=left_padding)
         
     | 
| 472 | 
         
            +
             
     | 
| 473 | 
         
            +
                    return visual_input_ids, batch_input_embeds, batch_labels, batch_attention_mask
         
     | 
| 474 | 
         
            +
             
     | 
| 475 | 
         
            +
                def pad_truncate_sequence(self, sequences: List[torch.Tensor], batch_first: bool = True, padding_value: float = 0.0, left_padding: bool = False) -> torch.Tensor:
         
     | 
| 476 | 
         
            +
                    if not left_padding:
         
     | 
| 477 | 
         
            +
                        pad_sequence = torch.nn.utils.rnn.pad_sequence(sequences, batch_first=batch_first, padding_value=padding_value)
         
     | 
| 478 | 
         
            +
                        return pad_sequence[:,:self.config.multimodal_max_length]
         
     | 
| 479 | 
         
            +
                    else:
         
     | 
| 480 | 
         
            +
                        pad_sequence = torch.nn.utils.rnn.pad_sequence([i.flip(dims=[0]) for i in sequences],batch_first=True, padding_value=padding_value).flip(dims=[1])
         
     | 
| 481 | 
         
            +
                        return pad_sequence[:,-self.config.multimodal_max_length:]
         
     | 
| 482 | 
         
            +
             
     | 
| 483 | 
         
            +
                def preprocess_inputs(
         
     | 
| 484 | 
         
            +
                    self,
         
     | 
| 485 | 
         
            +
                    text_or_conversations: Union[List[Dict], str],
         
     | 
| 486 | 
         
            +
                    images: Optional[List[PIL.Image.Image]],
         
     | 
| 487 | 
         
            +
                    max_partition=9,
         
     | 
| 488 | 
         
            +
                    generation_preface='',
         
     | 
| 489 | 
         
            +
                    return_labels=False,
         
     | 
| 490 | 
         
            +
                    propagate_exception=True,
         
     | 
| 491 | 
         
            +
                    frame_selector=None,
         
     | 
| 492 | 
         
            +
                    frame_selector_kwargs=None
         
     | 
| 493 | 
         
            +
                ):
         
     | 
| 494 | 
         
            +
                    # convert text to conversations
         
     | 
| 495 | 
         
            +
                    if isinstance(text_or_conversations, str):
         
     | 
| 496 | 
         
            +
                        conversations = [{
         
     | 
| 497 | 
         
            +
                            "from": "human",
         
     | 
| 498 | 
         
            +
                            "value": text_or_conversations
         
     | 
| 499 | 
         
            +
                        }]
         
     | 
| 500 | 
         
            +
                    elif isinstance(text_or_conversations, list):
         
     | 
| 501 | 
         
            +
                        conversations = text_or_conversations
         
     | 
| 502 | 
         
            +
                    else:
         
     | 
| 503 | 
         
            +
                        raise ValueError(f'Invalid type of `text_or_conversations`, expected `List[Dict]` or `str`,'
         
     | 
| 504 | 
         
            +
                                         f' but got {type(text_or_conversations)}')
         
     | 
| 505 | 
         
            +
             
     | 
| 506 | 
         
            +
                    if frame_selector is not None:
         
     | 
| 507 | 
         
            +
                        frame_selector_kwargs = frame_selector_kwargs or {}
         
     | 
| 508 | 
         
            +
                        conversations, images = frame_selector(conversations=conversations, frames=images, **frame_selector_kwargs)
         
     | 
| 509 | 
         
            +
             
     | 
| 510 | 
         
            +
                    # format conversations
         
     | 
| 511 | 
         
            +
                    prompt, raw_input_ids, raw_labels = self.get_conversation_formatter().format(
         
     | 
| 512 | 
         
            +
                        conversations, generation_preface=generation_preface)
         
     | 
| 513 | 
         
            +
             
     | 
| 514 | 
         
            +
                    # place image placeholders
         
     | 
| 515 | 
         
            +
                    input_ids = []
         
     | 
| 516 | 
         
            +
                    labels = []
         
     | 
| 517 | 
         
            +
                    pixel_values = []
         
     | 
| 518 | 
         
            +
                    invalidate_label = False
         
     | 
| 519 | 
         
            +
                    image_token_indices = [i for i, v in enumerate(raw_input_ids) if v == IMAGE_TOKEN_ID]
         
     | 
| 520 | 
         
            +
                    last_image_token_index = -1
         
     | 
| 521 | 
         
            +
                    for i in range(len(image_token_indices)):
         
     | 
| 522 | 
         
            +
                        head = 0 if i == 0 else image_token_indices[i - 1] + 1
         
     | 
| 523 | 
         
            +
                        tail = image_token_indices[i]
         
     | 
| 524 | 
         
            +
                        last_image_token_index = tail
         
     | 
| 525 | 
         
            +
                        input_ids.extend(raw_input_ids[head:tail])
         
     | 
| 526 | 
         
            +
                        labels.extend(raw_labels[head:tail])
         
     | 
| 527 | 
         
            +
                        try:
         
     | 
| 528 | 
         
            +
                            image = images[i]
         
     | 
| 529 | 
         
            +
                            raw_pixel_values, image_placeholders = self.visual_tokenizer.preprocess_image(
         
     | 
| 530 | 
         
            +
                                image, max_partition=max_partition)
         
     | 
| 531 | 
         
            +
                        except Exception as e:
         
     | 
| 532 | 
         
            +
                            if propagate_exception:
         
     | 
| 533 | 
         
            +
                                raise e
         
     | 
| 534 | 
         
            +
                            logging.exception(e)
         
     | 
| 535 | 
         
            +
                            invalidate_label = True
         
     | 
| 536 | 
         
            +
                            raw_pixel_values, image_placeholders = self.visual_tokenizer.mock_input()
         
     | 
| 537 | 
         
            +
                        input_ids.extend(image_placeholders)
         
     | 
| 538 | 
         
            +
                        labels.extend([IGNORE_ID] * len(image_placeholders))
         
     | 
| 539 | 
         
            +
                        pixel_values.append(raw_pixel_values)
         
     | 
| 540 | 
         
            +
                    input_ids.extend(raw_input_ids[last_image_token_index + 1:])
         
     | 
| 541 | 
         
            +
                    labels.extend(raw_labels[last_image_token_index + 1:])
         
     | 
| 542 | 
         
            +
             
     | 
| 543 | 
         
            +
                    # return tensors
         
     | 
| 544 | 
         
            +
                    input_ids = torch.tensor(input_ids, dtype=torch.long)
         
     | 
| 545 | 
         
            +
                    labels = torch.tensor([IGNORE_ID] * len(labels) if invalidate_label else labels, dtype=torch.long)
         
     | 
| 546 | 
         
            +
                    pixel_values = torch.cat(pixel_values, dim=0) if len(pixel_values) > 0 else None
         
     | 
| 547 | 
         
            +
             
     | 
| 548 | 
         
            +
                    if return_labels:
         
     | 
| 549 | 
         
            +
                        return prompt, input_ids, pixel_values, labels
         
     | 
| 550 | 
         
            +
                    else:
         
     | 
| 551 | 
         
            +
                        return prompt, input_ids, pixel_values
         
     | 
| 552 | 
         
            +
             
     | 
| 553 | 
         
            +
                def save_pretrained(
         
     | 
| 554 | 
         
            +
                    self,
         
     | 
| 555 | 
         
            +
                    save_directory: Union[str, os.PathLike],
         
     | 
| 556 | 
         
            +
                    is_main_process: bool = True,
         
     | 
| 557 | 
         
            +
                    state_dict: Optional[dict] = None,
         
     | 
| 558 | 
         
            +
                    save_function: Callable = torch.save,
         
     | 
| 559 | 
         
            +
                    push_to_hub: bool = False,
         
     | 
| 560 | 
         
            +
                    max_shard_size: Union[int, str] = "5GB",
         
     | 
| 561 | 
         
            +
                    safe_serialization: bool = True,
         
     | 
| 562 | 
         
            +
                    variant: Optional[str] = None,
         
     | 
| 563 | 
         
            +
                    token: Optional[Union[str, bool]] = None,
         
     | 
| 564 | 
         
            +
                    save_peft_format: bool = True,
         
     | 
| 565 | 
         
            +
                    **kwargs
         
     | 
| 566 | 
         
            +
                ):
         
     | 
| 567 | 
         
            +
                    super().save_pretrained(save_directory,
         
     | 
| 568 | 
         
            +
                                            is_main_process=is_main_process,
         
     | 
| 569 | 
         
            +
                                            state_dict=state_dict,
         
     | 
| 570 | 
         
            +
                                            save_function=save_function,
         
     | 
| 571 | 
         
            +
                                            safe_serialization=safe_serialization)
         
     | 
| 572 | 
         
            +
                    self.get_text_tokenizer().save_pretrained(save_directory)
         
     | 
| 573 | 
         
            +
                    self.get_visual_tokenizer().get_image_processor().save_pretrained(save_directory)
         
     | 
| 574 | 
         
            +
             
     | 
| 575 | 
         
            +
                def generate(
         
     | 
| 576 | 
         
            +
                    self,
         
     | 
| 577 | 
         
            +
                    inputs: Optional[torch.Tensor] = None,
         
     | 
| 578 | 
         
            +
                    **kwargs
         
     | 
| 579 | 
         
            +
                ) -> Union[GenerateOutput, torch.LongTensor]:
         
     | 
| 580 | 
         
            +
                    _, inputs_embeds, labels, attention_mask = self.merge_multimodal(
         
     | 
| 581 | 
         
            +
                        text_input_ids=inputs,
         
     | 
| 582 | 
         
            +
                        text_attention_masks=kwargs.pop('attention_mask'),
         
     | 
| 583 | 
         
            +
                        text_labels=None,
         
     | 
| 584 | 
         
            +
                        pixel_values=kwargs.pop('pixel_values'),
         
     | 
| 585 | 
         
            +
                        left_padding=True
         
     | 
| 586 | 
         
            +
                    )
         
     | 
| 587 | 
         
            +
                    inputs_embeds = inputs_embeds.detach()
         
     | 
| 588 | 
         
            +
                    torch.cuda.empty_cache()
         
     | 
| 589 | 
         
            +
             
     | 
| 590 | 
         
            +
                    return self.llm.generate(inputs=None, inputs_embeds=inputs_embeds, attention_mask=attention_mask, **kwargs)
         
     |