Update modeling_internvl_chat.py
#3
by
ganlinyang
- opened
- modeling_internvl_chat.py +93 -5
modeling_internvl_chat.py
CHANGED
|
@@ -5,13 +5,15 @@
|
|
| 5 |
# --------------------------------------------------------
|
| 6 |
import warnings
|
| 7 |
from typing import Any, List, Optional, Tuple, Union
|
| 8 |
-
|
| 9 |
import torch.utils.checkpoint
|
| 10 |
import transformers
|
| 11 |
from torch import nn
|
| 12 |
from torch.nn import CrossEntropyLoss
|
| 13 |
from transformers import (AutoModel, GenerationConfig, LlamaForCausalLM,
|
| 14 |
LlamaTokenizer, Qwen2ForCausalLM)
|
|
|
|
|
|
|
| 15 |
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 16 |
from transformers.modeling_utils import PreTrainedModel
|
| 17 |
from transformers.utils import ModelOutput, logging
|
|
@@ -22,7 +24,8 @@ from .modeling_intern_vit import InternVisionModel, has_flash_attn
|
|
| 22 |
from .modeling_internlm2 import InternLM2ForCausalLM
|
| 23 |
|
| 24 |
logger = logging.get_logger(__name__)
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
def version_cmp(v1, v2, op='eq'):
|
| 28 |
import operator
|
|
@@ -31,6 +34,76 @@ def version_cmp(v1, v2, op='eq'):
|
|
| 31 |
op_func = getattr(operator, op)
|
| 32 |
return op_func(version.parse(v1), version.parse(v2))
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
class InternVLChatModel(PreTrainedModel):
|
| 36 |
config_class = InternVLChatConfig
|
|
@@ -252,10 +325,25 @@ class InternVLChatModel(PreTrainedModel):
|
|
| 252 |
responses = [response.split(template.sep)[0].strip() for response in responses]
|
| 253 |
return responses
|
| 254 |
|
| 255 |
-
def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
|
| 256 |
num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
|
| 257 |
verbose=False):
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
if history is None and pixel_values is not None and '<image>' not in question:
|
| 260 |
question = '<image>\n' + question
|
| 261 |
|
|
@@ -360,4 +448,4 @@ class InternVLChatModel(PreTrainedModel):
|
|
| 360 |
return self.language_model.get_input_embeddings()
|
| 361 |
|
| 362 |
def get_output_embeddings(self):
|
| 363 |
-
return self.language_model.get_output_embeddings()
|
|
|
|
| 5 |
# --------------------------------------------------------
|
| 6 |
import warnings
|
| 7 |
from typing import Any, List, Optional, Tuple, Union
|
| 8 |
+
from PIL import Image
|
| 9 |
import torch.utils.checkpoint
|
| 10 |
import transformers
|
| 11 |
from torch import nn
|
| 12 |
from torch.nn import CrossEntropyLoss
|
| 13 |
from transformers import (AutoModel, GenerationConfig, LlamaForCausalLM,
|
| 14 |
LlamaTokenizer, Qwen2ForCausalLM)
|
| 15 |
+
import torchvision.transforms as T
|
| 16 |
+
from torchvision.transforms.functional import InterpolationMode
|
| 17 |
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 18 |
from transformers.modeling_utils import PreTrainedModel
|
| 19 |
from transformers.utils import ModelOutput, logging
|
|
|
|
| 24 |
from .modeling_internlm2 import InternLM2ForCausalLM
|
| 25 |
|
| 26 |
logger = logging.get_logger(__name__)
|
| 27 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
| 28 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 29 |
|
| 30 |
def version_cmp(v1, v2, op='eq'):
|
| 31 |
import operator
|
|
|
|
| 34 |
op_func = getattr(operator, op)
|
| 35 |
return op_func(version.parse(v1), version.parse(v2))
|
| 36 |
|
| 37 |
+
def build_transform(input_size):
|
| 38 |
+
MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
|
| 39 |
+
transform = T.Compose([
|
| 40 |
+
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
|
| 41 |
+
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
|
| 42 |
+
T.ToTensor(),
|
| 43 |
+
T.Normalize(mean=MEAN, std=STD)
|
| 44 |
+
])
|
| 45 |
+
return transform
|
| 46 |
+
|
| 47 |
+
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
|
| 48 |
+
best_ratio_diff = float('inf')
|
| 49 |
+
best_ratio = (1, 1)
|
| 50 |
+
area = width * height
|
| 51 |
+
for ratio in target_ratios:
|
| 52 |
+
target_aspect_ratio = ratio[0] / ratio[1]
|
| 53 |
+
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
| 54 |
+
if ratio_diff < best_ratio_diff:
|
| 55 |
+
best_ratio_diff = ratio_diff
|
| 56 |
+
best_ratio = ratio
|
| 57 |
+
elif ratio_diff == best_ratio_diff:
|
| 58 |
+
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
| 59 |
+
best_ratio = ratio
|
| 60 |
+
return best_ratio
|
| 61 |
+
|
| 62 |
+
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
|
| 63 |
+
orig_width, orig_height = image.size
|
| 64 |
+
aspect_ratio = orig_width / orig_height
|
| 65 |
+
|
| 66 |
+
# calculate the existing image aspect ratio
|
| 67 |
+
target_ratios = set(
|
| 68 |
+
(i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
|
| 69 |
+
i * j <= max_num and i * j >= min_num)
|
| 70 |
+
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
| 71 |
+
|
| 72 |
+
# find the closest aspect ratio to the target
|
| 73 |
+
target_aspect_ratio = find_closest_aspect_ratio(
|
| 74 |
+
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
|
| 75 |
+
|
| 76 |
+
# calculate the target width and height
|
| 77 |
+
target_width = image_size * target_aspect_ratio[0]
|
| 78 |
+
target_height = image_size * target_aspect_ratio[1]
|
| 79 |
+
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
| 80 |
+
|
| 81 |
+
# resize the image
|
| 82 |
+
resized_img = image.resize((target_width, target_height))
|
| 83 |
+
processed_images = []
|
| 84 |
+
for i in range(blocks):
|
| 85 |
+
box = (
|
| 86 |
+
(i % (target_width // image_size)) * image_size,
|
| 87 |
+
(i // (target_width // image_size)) * image_size,
|
| 88 |
+
((i % (target_width // image_size)) + 1) * image_size,
|
| 89 |
+
((i // (target_width // image_size)) + 1) * image_size
|
| 90 |
+
)
|
| 91 |
+
# split the image
|
| 92 |
+
split_img = resized_img.crop(box)
|
| 93 |
+
processed_images.append(split_img)
|
| 94 |
+
assert len(processed_images) == blocks
|
| 95 |
+
if use_thumbnail and len(processed_images) != 1:
|
| 96 |
+
thumbnail_img = image.resize((image_size, image_size))
|
| 97 |
+
processed_images.append(thumbnail_img)
|
| 98 |
+
return processed_images
|
| 99 |
+
|
| 100 |
+
def load_image(image_file, input_size=448, max_num=12):
|
| 101 |
+
image = Image.open(image_file).convert('RGB')
|
| 102 |
+
transform = build_transform(input_size=input_size)
|
| 103 |
+
images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
| 104 |
+
pixel_values = [transform(image) for image in images]
|
| 105 |
+
pixel_values = torch.stack(pixel_values)
|
| 106 |
+
return pixel_values
|
| 107 |
|
| 108 |
class InternVLChatModel(PreTrainedModel):
|
| 109 |
config_class = InternVLChatConfig
|
|
|
|
| 325 |
responses = [response.split(template.sep)[0].strip() for response in responses]
|
| 326 |
return responses
|
| 327 |
|
| 328 |
+
def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False, image_dirs=None,
|
| 329 |
num_patches_list=None, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>', IMG_CONTEXT_TOKEN='<IMG_CONTEXT>',
|
| 330 |
verbose=False):
|
| 331 |
+
if image_dirs is not None:
|
| 332 |
+
print("----------------------------------")
|
| 333 |
+
print("Using image_dirs to load images. 'pixel_values' and 'num_patches_list' will be ignored.")
|
| 334 |
+
print("You should provide all the previous image files and the current image file in the 'image_dirs' argument.")
|
| 335 |
+
print("----------------------------------")
|
| 336 |
+
|
| 337 |
+
if isinstance(image_dirs, str):
|
| 338 |
+
image_dirs = [image_dirs]
|
| 339 |
+
elif isinstance(image_dirs, list):
|
| 340 |
+
pass
|
| 341 |
+
else:
|
| 342 |
+
raise ValueError(f'Invalid image_dirs: {image_dirs}. It should be a string or a list of strings.')
|
| 343 |
+
image_values = [load_image(image_file, max_num=12).to(torch.float16).cuda() for image_file in image_dirs]
|
| 344 |
+
pixel_values = torch.cat(image_values, dim=0)
|
| 345 |
+
num_patches_list = [image_values[i].shape[0] for i in range(len(image_values))]
|
| 346 |
+
|
| 347 |
if history is None and pixel_values is not None and '<image>' not in question:
|
| 348 |
question = '<image>\n' + question
|
| 349 |
|
|
|
|
| 448 |
return self.language_model.get_input_embeddings()
|
| 449 |
|
| 450 |
def get_output_embeddings(self):
|
| 451 |
+
return self.language_model.get_output_embeddings()
|