-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmultimodal_model_runner.py
2277 lines (2063 loc) · 107 KB
/
multimodal_model_runner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import os
import sys
from io import BytesIO
import requests
# isort: off
import torch
import numpy as np
# isort: on
import math
from typing import Optional, Tuple
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from PIL import Image
from safetensors import safe_open
from torch import nn
from transformers import (AutoConfig, AutoModelForCausalLM, AutoProcessor,
AutoTokenizer)
from .. import profiler
from .._utils import (mpi_rank, str_dtype_to_torch, str_dtype_to_trt,
supports_inflight_batching, torch_dtype_to_trt,
trt_dtype_to_torch)
from ..functional import RopeEmbeddingUtils, RotaryScalingType
from ..layers import MropeParams
from ..logger import logger
from .enc_dec_model_runner import EncDecModelRunner
from .model_runner import ModelRunner
from .session import Session, TensorInfo
try:
import tensorrt_llm.bindings # NOQA
PYTHON_BINDINGS = True
except ImportError:
PYTHON_BINDINGS = False
if PYTHON_BINDINGS:
from .model_runner_cpp import ModelRunnerCpp
class LlavaNextUtils:
# https://github.com/haotian-liu/LLaVA/blob/main/llava/mm_utils.py
@staticmethod
def select_best_resolution(original_size, possible_resolutions):
"""
Selects the best resolution from a list of possible resolutions based on the original size.
Args:
original_size (tuple): The original size of the image in the format (width, height).
possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
Returns:
tuple: The best fit resolution in the format (width, height).
"""
original_width, original_height = original_size
best_fit = None
max_effective_resolution = 0
min_wasted_resolution = float('inf')
for width, height in possible_resolutions:
scale = min(width / original_width, height / original_height)
downscaled_width, downscaled_height = int(
original_width * scale), int(original_height * scale)
effective_resolution = min(downscaled_width * downscaled_height,
original_width * original_height)
wasted_resolution = (width * height) - effective_resolution
if effective_resolution > max_effective_resolution or (
effective_resolution == max_effective_resolution
and wasted_resolution < min_wasted_resolution):
max_effective_resolution = effective_resolution
min_wasted_resolution = wasted_resolution
best_fit = (width, height)
return best_fit
@staticmethod
def get_anyres_image_grid_shape(image_size,
patch_size,
image_grid_pinpoints=None):
"""
Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
Args:
image_size (tuple): The size of the input image in the format (width, height).
patch_size (int): The size of each image patch.
Returns:
tuple: The shape of the image patch grid in the format (width, height).
"""
if image_grid_pinpoints is None:
image_grid_pinpoints = [[336, 672], [672, 336], [672, 672],
[1008, 336], [336, 1008]]
width, height = LlavaNextUtils.select_best_resolution(
image_size, image_grid_pinpoints)
return width // patch_size, height // patch_size
@staticmethod
def unpad_image(tensor, original_size):
"""
Unpads a PyTorch tensor of a padded and resized image.
Args:
tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
original_size (tuple): The original size of the image (width, height).
Returns:
torch.Tensor: The unpadded image tensor.
"""
original_width, original_height = original_size
current_height, current_width = tensor.shape[1:]
original_aspect_ratio = original_width / original_height
current_aspect_ratio = current_width / current_height
if original_aspect_ratio > current_aspect_ratio:
scale_factor = current_width / original_width
new_height = int(original_height * scale_factor)
padding = (current_height - new_height) // 2
unpadded_tensor = tensor[:, padding:current_height - padding, :]
else:
scale_factor = current_height / original_height
new_width = int(original_width * scale_factor)
padding = (current_width - new_width) // 2
unpadded_tensor = tensor[:, :, padding:current_width - padding]
return unpadded_tensor
@staticmethod
def rearrange_image_features(image_feature, image_newline, image_size):
"""
Combine PyTorch feature grids from image patches.
Args:
image_feature (torch.Tensor): The feature grids, assumed to be in NxCxHxW format.
image_newline (torch.Tensor): The newline embedding.
image_size (tuple): Size of the original image (width, height).
"""
CLIP_IMAGE_SIZE = 336
CLIP_PATCH_SIZE = 14
NUM_PATCHES_PER_SIDE = CLIP_IMAGE_SIZE // CLIP_PATCH_SIZE
if image_feature.shape[0] == 1:
return torch.cat((image_feature, image_newline[None]), dim=0)
base_image_feature = image_feature[0]
image_feature = image_feature[1:]
height = width = NUM_PATCHES_PER_SIDE
assert height * width == base_image_feature.shape[0]
num_patch_width, num_patch_height = LlavaNextUtils.get_anyres_image_grid_shape(
image_size, CLIP_IMAGE_SIZE)
image_feature = image_feature.view(num_patch_height, num_patch_width,
height, width, -1)
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
image_feature = LlavaNextUtils.unpad_image(image_feature, image_size)
image_feature = torch.cat(
(image_feature, image_newline[:, None, None].expand(
*image_feature.shape[:-1], 1)),
dim=-1)
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
image_feature = torch.cat((base_image_feature, image_feature), dim=0)
return image_feature
class LlavaOnevisionUtils:
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_onevision/modeling_llava_onevision.py
@staticmethod
def pack_image_features(image_features, image_sizes, image_newline):
"""
Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
Args:
image_features (`torch.Tensor` of shape `(num_images, num_patches, image_length, embed_dim)`)
Image feature tensor, each contains all the visual feature of all patches.
image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
Actual image size of each images (H, W).
image_newline (`torch.Tensor` of shape `(embed_dim)`)
New line embedding vector.
Returns:
image_features (`torch.Tensor` of shape `(all_feat_len, embed_dim)`)
"""
IMAGE_SIZE = 384
PATCH_SIZE = 14
MAX_NUM_PATCHES = 9
new_image_features = []
for image_idx, image_feature in enumerate(image_features):
if image_feature.shape[0] > 1:
base_image_feature = image_feature[0]
image_feature = image_feature[1:]
height = width = IMAGE_SIZE // PATCH_SIZE
if height * width != base_image_feature.shape[0]:
raise ValueError(
"The number of patches is not consistent with the image size."
)
IMAGE_GRID_PINPOINTS = [[384, 384], [384, 768], [384, 1152],
[384, 1536], [384, 1920], [384, 2304],
[768, 384], [768, 768], [768, 1152],
[768, 1536], [768, 1920], [768, 2304],
[1152, 384], [1152, 768], [1152, 1152],
[1152, 1536],
[1152, 1920], [1152, 2304], [1536, 384],
[1536, 768], [1536, 1152], [1536, 1536],
[1536, 1920], [1536, 2304], [1920, 384],
[1920, 768], [1920, 1152], [1920, 1536],
[1920, 1920], [1920, 2304], [2304, 384],
[2304, 768], [2304, 1152], [2304, 1536],
[2304, 1920], [2304, 2304]]
num_patch_width, num_patch_height = LlavaNextUtils.get_anyres_image_grid_shape(
image_sizes[image_idx][[1, 0]].tolist(), IMAGE_SIZE,
IMAGE_GRID_PINPOINTS)
image_feature = image_feature.view(num_patch_height,
num_patch_width, height,
width, -1)
image_feature = image_feature.permute(4, 0, 2, 1,
3).contiguous()
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
image_feature = LlavaNextUtils.unpad_image(
image_feature, image_sizes[image_idx][[1, 0]])
channels, curr_height, curr_width = image_feature.shape
ratio = math.sqrt(curr_height * curr_width /
(MAX_NUM_PATCHES * height**2))
if ratio > 1.1:
image_feature = image_feature[None]
image_feature = nn.functional.interpolate(
image_feature,
[int(curr_height // ratio),
int(curr_width // ratio)],
mode="bilinear")[0]
image_feature = torch.cat(
(
image_feature,
image_newline[:, None, None].expand(
*image_feature.shape[:-1], 1).to(
image_feature.device, image_feature.dtype),
),
dim=-1,
)
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
image_feature = torch.cat((base_image_feature, image_feature),
dim=0)
else:
image_feature = image_feature[0]
if image_newline is not None:
image_feature = torch.cat(
(image_feature, image_newline[None].to(image_feature)),
dim=0)
new_image_features.append(image_feature)
image_features = torch.stack(new_image_features)
return image_features
@staticmethod
def apply_pooling(image_features):
IMAGE_SIZE = 384
PATCH_SIZE = 14
height = width = IMAGE_SIZE // PATCH_SIZE
batch_frames, seq_len, dim = image_features.shape
image_features = image_features.view(batch_frames, height, width, -1)
image_features = image_features.permute(0, 3, 1, 2).contiguous()
height, width = image_features.shape[2:]
scaled_shape = [math.ceil(height / 2), math.ceil(width / 2)]
image_features = nn.functional.interpolate(image_features,
size=scaled_shape,
mode="bilinear")
image_features = image_features.permute(0, 2, 3, 1)
image_features = image_features.view(batch_frames, -1, dim)
return image_features
class MultimodalModelRunner:
def __init__(self, args):
self.args = args
self.runtime_rank = mpi_rank()
device_id = self.runtime_rank % torch.cuda.device_count()
torch.cuda.set_device(device_id)
self.device = "cuda:%d" % (device_id)
self.stream = torch.cuda.Stream(torch.cuda.current_device())
torch.cuda.set_stream(self.stream)
# parse model type from visual engine config
with open(os.path.join(self.visual_engine_dir, "config.json"),
"r") as f:
config = json.load(f)
self.model_type = config['builder_config']['model_type']
self.vision_precision = config['builder_config']['precision']
if self.model_type == 'pix2struct':
self.vision_precision = 'float16'
self.decoder_llm = not (
't5' in self.model_type
or self.model_type in ['nougat', 'pix2struct']
) # BLIP2-T5, pix2struct and Nougat are using encoder-decoder models as LLMs
if self.model_type == 'video-neva':
self.num_frames = config['builder_config'].get('num_frames', None)
if self.model_type == "llava_next":
self.llm_name = AutoConfig.from_pretrained(
self.args.hf_model_dir).text_config._name_or_path
if 'internlm' in self.model_type:
self.args.lora_task_uids = ['0'] * args.batch_size
if self.model_type == "qwen2_vl":
hf_config = AutoConfig.from_pretrained(self.args.hf_model_dir)
self.vision_start_token_id = hf_config.vision_start_token_id
self.vision_end_token_id = hf_config.vision_end_token_id
self.vision_token_id = hf_config.vision_token_id
self.image_token_id = hf_config.image_token_id
self.video_token_id = hf_config.video_token_id
self.spatial_merge_size = hf_config.vision_config.spatial_merge_size
self.max_position_embeddings = hf_config.max_position_embeddings
self.hidden_size = hf_config.hidden_size
self.num_attention_heads = hf_config.num_attention_heads
self.rope_theta = hf_config.rope_theta
if self.model_type == 'llava_onevision':
self.num_frames = self.args.video_num_frames
if self.num_frames is None:
self.num_frames = 8
assert self.args.video_path is None or self.args.image_path is None
self.visual_output_shape = config['builder_config'].get(
'output_shape', None)
if self.model_type == "mllama":
self.vision_input_names = [
"pixel_values",
"aspect_ratio_ids",
"aspect_ratio_mask",
]
self.vision_output_names = [
"encoder_output",
]
else:
self.vision_input_names = ["input"]
self.vision_output_names = ["encoder_output"]
self.session = args.session
if self.decoder_llm:
if not supports_inflight_batching(self.llm_engine_dir):
logger.warning(
"The given engine does not support in-flight batching, both visual engine and LLM fallback to python session"
)
self.session = 'python'
if not PYTHON_BINDINGS and 'cpp' in args.session:
logger.warning(
"Python bindings of C++ session is unavailable, both visual engine and LLM fallback to Python session."
)
self.session = 'python'
args.debug_mode = False
if args.debug_mode and 'cpp' in args.session:
logger.warning(
"Debug mode is not supported in C++ session for now, both visual engine and LLM fallback to Python session."
)
self.session = 'python'
if self.model_type == 'qwen2_vl':
if self.args.session != "cpp_llm_only":
logger.warning(
"Qwen2-vl only support C++ session for now, fallback to C++ session."
)
self.args.session = "cpp_llm_only"
if (not (self.model_type in
('llava', 'vila', 'blip2-opt', 'kosmos-2', 'fuyu',
'cogvlm', 'neva', "internvl") or 'internlm'
in self.model_type)) and args.session == 'cpp':
logger.warning(
f'C++ end-to-end mode does not support {self.model_type}. Visual engine fallbacks to Python session. See support matrix in README.'
)
args.session = 'cpp_llm_only'
self.session = args.session
else:
self.session = 'cpp_llm_only'
self.init_tokenizer()
self.init_processor()
self.init_image_encoder()
self.init_llm()
@property
def cpp_e2e(self):
return self.session == 'cpp'
@property
def cpp_llm_only(self):
return self.session == 'cpp_llm_only'
@property
def python_e2e(self):
return self.session == 'python'
@property
def visual_engine_dir(self):
return os.path.join(self.args.engine_dir, 'vision')
@property
def llm_engine_dir(self):
return os.path.join(self.args.engine_dir, 'llm')
def init_tokenizer(self):
if self.model_type == 'nougat':
from transformers import NougatTokenizerFast
self.tokenizer = NougatTokenizerFast.from_pretrained(
self.args.hf_model_dir)
elif self.model_type == 'neva' or self.model_type == 'video-neva':
from sentencepiece import SentencePieceProcessor
sp = SentencePieceProcessor(
os.path.join(self.args.hf_model_dir, 'tokenizer.model'))
class return_obj:
def __init__(self, input_ids):
self.input_ids = input_ids
def __getitem__(self, name):
if name in "input_ids":
return self.input_ids
else:
raise AttributeError(
f"'return_obj' has no item '{name}'")
# sentencepiece does not follow the same interface as HF
class HFTokenizerInterface():
def encode(self, x, return_tensors=None, **kwargs):
out = sp.encode(x)
if return_tensors == "pt":
out = torch.tensor(out)
return return_obj(out)
def __call__(self, x, return_tensors=None, **kwargs):
return self.encode(x, return_tensors, **kwargs)
def decode(self, x, **kwargs):
return sp.decode(x.tolist())
def batch_decode(self, x, **kwargs):
return self.decode(x, **kwargs)
self.tokenizer = HFTokenizerInterface()
self.tokenizer.eos_token_id = sp.eos_id()
self.tokenizer.bos_token_id = sp.bos_id()
self.tokenizer.pad_token_id = sp.pad_id()
elif self.model_type == 'vila':
self.tokenizer = AutoTokenizer.from_pretrained(
self.args.hf_model_dir + "/llm",
use_fast=False,
use_legacy=False)
else:
use_fast = self.model_type in ["phi-3-vision", "internvl"]
self.tokenizer = AutoTokenizer.from_pretrained(
self.args.hf_model_dir,
use_fast=use_fast,
use_legacy=False,
trust_remote_code=True)
self.tokenizer.padding_side = "right"
def init_processor(self):
from torchvision import transforms
if 'blip2' in self.model_type:
from transformers import Blip2Processor
self.processor = Blip2Processor.from_pretrained(
self.args.hf_model_dir)
elif 'nougat' in self.model_type:
from transformers import NougatProcessor
self.processor = NougatProcessor.from_pretrained(
self.args.hf_model_dir)
elif 'cogvlm' in self.model_type:
image_size = 490
self.transform = transforms.Compose([
transforms.Resize(
(image_size, image_size),
interpolation=transforms.InterpolationMode.BICUBIC),
transforms.ToTensor(),
transforms.Normalize((0.48145466, 0.4578275, 0.40821073),
(0.26862954, 0.26130258, 0.27577711)),
transforms.ConvertImageDtype(torch.bfloat16),
])
elif self.model_type in [
'phi-3-vision', 'pix2struct', 'llava_next', 'llava', 'fuyu',
'kosmos-2', 'mllama', 'llava_onevision', 'qwen2_vl'
]:
self.processor = AutoProcessor.from_pretrained(
self.args.hf_model_dir, trust_remote_code=True, num_crops=16)
elif 'internlm' in self.model_type:
image_size = 490
self.processor = transforms.Compose([
transforms.Resize(
(image_size, image_size),
interpolation=transforms.InterpolationMode.BICUBIC),
transforms.ToTensor(),
transforms.Normalize((0.48145466, 0.4578275, 0.40821073),
(0.26862954, 0.26130258, 0.27577711)),
])
elif 'internvl' in self.model_type:
from transformers import CLIPImageProcessor
self.processor = CLIPImageProcessor.from_pretrained(
'OpenGVLab/InternViT-300M-448px'
) # You can change the InternViT model type according to your InternVL type
elif self.model_type == "neva":
image_size = 384
self.transform = transforms.Compose([
transforms.Resize(
(image_size, image_size),
interpolation=transforms.InterpolationMode.BICUBIC),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
transforms.ConvertImageDtype(torch.float32),
])
elif self.model_type == "video-neva":
pass
elif self.model_type == "vila":
sys.path.append(self.args.hf_model_dir + "/../VILA")
from llava.mm_utils import process_images
from llava.model import LlavaLlamaConfig # noqa
from transformers import AutoModel
model = AutoModel.from_pretrained(
self.args.hf_model_dir,
device_map='auto',
trust_remote_code=True,
)
vision_tower = model.get_vision_tower()
vision_tower.image_processor
def processor(raw_image):
return process_images(raw_image, vision_tower.image_processor,
model.config).to(model.device,
dtype=torch.float16)
self.processor = processor
if self.model_type == 'mllama':
from .processor_wrapper import MllamaProcessorWrapper
self.processor = MllamaProcessorWrapper(self.processor, logger)
def init_image_encoder(self):
if self.model_type == "phi-3-vision":
model = AutoModelForCausalLM.from_pretrained(
self.args.hf_model_dir,
torch_dtype=torch.float16,
trust_remote_code=True,
device_map='cpu')
self.vision_model = model.model.vision_embed_tokens.to(
self.device).eval()
# Test run vision_model.get_img_features to pre-allocate memory for flash attention
image = self.processor(text="<|image_1|>",
images=Image.new('RGB', [10, 10]),
return_tensors="pt")['pixel_values']
image = image.flatten(0, 1)
image = torch.rand(image.shape,
dtype=str_dtype_to_torch(self.vision_precision),
device=self.device)
self.vision_model.get_img_features(image)
return
if self.cpp_e2e:
logger.info(
"Using C++ runtime for both visual engine and LLM decoder, skip loading visual engine in Python runtime."
)
else:
vision_encoder_path = os.path.join(self.visual_engine_dir,
self.args.visual_engine_name)
logger.info(f'Loading engine from {vision_encoder_path}')
with open(vision_encoder_path, 'rb') as f:
engine_buffer = f.read()
logger.info(f'Creating session from engine {vision_encoder_path}')
self.visual_encoder_session = Session.from_serialized_engine(
engine_buffer)
if self.model_type in ["llava_next", "llava_onevision"]:
self.image_newlines = {}
image_newlines_path = os.path.join(self.visual_engine_dir,
'image_newlines.safetensors')
with safe_open(image_newlines_path,
framework="pt",
device=self.device) as f:
for k in f.keys():
self.image_newlines[k] = f.get_tensor(k)
def init_llm(self):
if self.decoder_llm:
cross_kv_cache_fraction = None
if self.model_type == 'mllama':
cross_kv_cache_fraction = self.args.cross_kv_cache_fraction
if self.python_e2e:
logger.info(f'Running LLM with Python runner')
self.model = ModelRunner.from_dir(
self.llm_engine_dir,
rank=tensorrt_llm.mpi_rank(),
debug_mode=False,
stream=self.stream,
enable_context_fmha_fp32_acc=self.args.
enable_context_fmha_fp32_acc,
multi_block_mode=self.args.multi_block_mode,
)
self.model_config = self.model.session._model_config
elif self.cpp_e2e:
logger.info(
f'Running both visual engine and LLM with Python runner')
self.model = ModelRunnerCpp.from_dir(
self.args.engine_dir,
rank=tensorrt_llm.mpi_rank(),
debug_mode=False,
is_enc_dec=True, # TODO: add a separate model variant here?
enable_context_fmha_fp32_acc=self.args.
enable_context_fmha_fp32_acc)
self.model_config = self.model.model_config
else:
logger.info(f'Running LLM with C++ runner')
self.model = ModelRunnerCpp.from_dir(
self.llm_engine_dir,
rank=tensorrt_llm.mpi_rank(),
debug_mode=False,
enable_chunked_context=self.args.enable_chunked_context,
enable_context_fmha_fp32_acc=self.args.
enable_context_fmha_fp32_acc,
kv_cache_free_gpu_memory_fraction=self.args.
kv_cache_free_gpu_memory_fraction,
cross_kv_cache_fraction=cross_kv_cache_fraction,
multi_block_mode=self.args.multi_block_mode,
)
self.model_config = self.model.model_config
self.runtime_mapping = self.model.mapping
else:
self.model = EncDecModelRunner.from_engine(
os.path.basename(self.args.hf_model_dir),
self.llm_engine_dir,
skip_encoder=self.model_type in ['nougat', 'pix2struct'],
debug_mode=False,
stream=self.stream,
enable_context_fmha_fp32_acc=self.args.
enable_context_fmha_fp32_acc)
if self.model_type in ['nougat', 'pix2struct']:
self.model_config = self.model.decoder_model_config
self.runtime_mapping = self.model.decoder_runtime_mapping
else:
self.model_config = self.model.encoder_model_config
self.runtime_mapping = self.model.encoder_runtime_mapping
def video_preprocess(self, video_path):
from decord import VideoReader
if isinstance(video_path, str):
vr = VideoReader(video_path)
num_frames = self.num_frames
if num_frames == -1:
frames = [
Image.fromarray(frame.asnumpy()[:, :, ::-1]).convert('RGB')
for frame in vr
]
else:
# equally sliced frames into self.num_frames frames
# if self.num_frames is greater than the number of frames in the video, we will repeat the last frame
num_frames = min(num_frames, len(vr))
indices = np.linspace(0, len(vr) - 1, num=num_frames, dtype=int)
frames = [
Image.fromarray(
vr[idx].asnumpy()[:, :, ::-1]).convert('RGB')
for idx in indices
]
if len(frames) < num_frames:
frames += [frames[-1]] * (num_frames - len(frames))
else:
frames = self.video_path
from transformers import CLIPImageProcessor
processor = CLIPImageProcessor.from_pretrained(
"openai/clip-vit-large-patch14", torch_dtype=torch.bfloat16)
frames = processor.preprocess(frames,
return_tensors="pt")['pixel_values']
# make dtype consistent with vision encoder
media_tensors = frames.to(str_dtype_to_torch(
self.vision_precision)) # [num_frames, 3, H, W]
return media_tensors.unsqueeze(0) #[1, num_frames, 3, H, W]
def preprocess(self, pre_prompt, post_prompt, image, other_vision_inputs):
# same prompt for single/multiple image(s)
n_prompts_n_images = False
if isinstance(post_prompt,
list) and len(post_prompt) > 1 and image is not None:
if hasattr(image, "pixel_values"):
if len(post_prompt) == image["pixel_values"].shape[0]:
n_prompts_n_images = True
# n prompts and n images
else:
if isinstance(
image,
torch.Tensor) and len(post_prompt) == image.shape[0]:
n_prompts_n_images = True
# n prompts and n images
if self.model_type == 'kosmos-2':
input_ids = image['input_ids'].clone()
image_mask = image["image_embeds_position_mask"]
image = image['pixel_values']
input_ids += image_mask * (self.model_config.vocab_size - 4)
input_ids = input_ids.expand(self.args.batch_size,
*input_ids.shape[1:])
length = input_ids.shape[1]
elif self.model_type == 'phi-3-vision':
input = image
image = input['pixel_values']
image = image.flatten(0, 1)
elif self.model_type == 'llava_next':
input = image
image = input['pixel_values']
image = image[0]
image_size = input['image_sizes'][0].cpu()
elif self.model_type == "qwen2_vl":
input = image
image = input['image']
input_ids = input['input_ids']
other_vision_inputs['image_grid_thw'].shape[0]
attention_mask = other_vision_inputs['attention_mask_llm']
other_vision_inputs.pop('attention_mask_llm')
image_grid_thw = other_vision_inputs['image_grid_thw']
other_vision_inputs.pop('image_grid_thw')
elif self.model_type == 'llava_onevision':
input = image
if self.args.video_path is None:
image = input['pixel_values']
image = image[0].repeat(self.args.batch_size, 1, 1, 1)
image_size = input['image_sizes'][0]
image_size = image_size.repeat(self.args.batch_size, 1).cpu()
else:
image = input['pixel_values_videos']
_, _, c, h, w = image.shape
image = image.repeat(self.args.batch_size, 1, 1, 1, 1)
image = image.view(-1, c, h, w)
elif self.model_type == "fuyu":
while len(image["image_patches"]) < self.args.batch_size:
image["image_patches"].append(image["image_patches"][0])
profiler.start("Vision encoder")
visual_features, visual_atts, model_runner_input = None, None, None
if image is not None:
model_runner_input = torch.stack(
image['image_patches'],
dim=0) if self.model_type == 'fuyu' else image
if self.model_type == "phi-3-vision":
visual_features = self.vision_model.get_img_features(
image).reshape(1, image.shape[0], -1,
self.vision_model.image_dim_out)
visual_atts = None
else:
if self.cpp_e2e:
# If using E2E C++ runtime, visual_features will not be computed here in Python runtime.
# Instead, it only contains a shape read from the engine config, and is used for generating
# decoder prompt later
logger.info(
'Skip running visual engine, get visual output shape from engine config.'
)
model_runner_input = model_runner_input.to(
str_dtype_to_torch(self.vision_precision))
batch_size = model_runner_input.shape[0]
output_shape = list(self.visual_output_shape)
output_shape[0] = batch_size
if self.model_type == 'fuyu':
output_shape[1] = model_runner_input.shape[
2] # fuyu's output patch number is not fixed, same as input patch number
visual_features = TensorInfo(
'encoder_output',
str_dtype_to_trt(self.vision_precision),
tuple(output_shape))
atts_shape = visual_features.shape[:-1]
visual_atts = TensorInfo('image_atts', None,
tuple(atts_shape))
model_runner_input = torch.vsplit(
model_runner_input, model_runner_input.shape[0])
else:
visual_features, visual_atts = self.get_visual_features(
model_runner_input, other_vision_inputs)
model_runner_input = None
profiler.stop("Vision encoder")
if self.model_type == 'fuyu':
input_ids = image['input_ids'].to(torch.int32)
image_patches_indices = image['image_patches_indices'].to(
torch.int32)
input_ids = input_ids.expand(self.args.batch_size,
*input_ids.shape[1:])
image_patches_indices = image_patches_indices.expand(
self.args.batch_size, *image_patches_indices.shape[1:])
input_ids = self.ptuning_setup_fuyu(input_ids,
image_patches_indices)
input_ids = torch.stack(input_ids, dim=0).to('cpu')
length = input_ids.shape[1]
if not self.cpp_e2e: # TODO: bs > 1 for C++ E2E Fuyu
visual_features = visual_features.repeat(
self.args.batch_size, 1, 1)
elif self.model_type == 'qwen2_vl':
length = input_ids.shape[1]
input_lengths = torch.IntTensor([length] * self.args.batch_size).to(
torch.int32)
input_ids, ptuning_args, mrope_args = self.setup_fake_prompts_qwen2vl(
visual_features, input_ids, image_grid_thw, attention_mask,
input_lengths)
return input_ids, input_lengths, ptuning_args, visual_features, mrope_args
elif self.model_type == 'kosmos-2':
visual_features = visual_features.squeeze(
) if visual_features is not None else None
elif self.model_type == 'vila':
if n_prompts_n_images:
input_ids = self.tokenizer_image_token(self.args.batch_size,
pre_prompt[0],
post_prompt,
self.tokenizer)
else:
input_ids = self.tokenizer_image_token(self.args.batch_size,
pre_prompt[0],
post_prompt[0],
self.tokenizer)
batch_split_prompts = self.split_prompt_by_images(input_ids)
if not n_prompts_n_images:
first_batch_split_prompts = batch_split_prompts[0]
# compute prompt length + visual length
length = sum(
[ids.shape[1] for ids in first_batch_split_prompts])
if self.args.batch_size == 1 and len(image) > 1:
# mode 1: multiple image as a whole, flatten visual dims
length += visual_atts.shape[0] * visual_atts.shape[1]
else:
length += visual_atts.shape[1]
input_lengths = torch.IntTensor(
[length] * self.args.batch_size).to(torch.int32)
input_ids, ptuning_args = self.setup_fake_prompts_vila(
self.args.batch_size, visual_features,
first_batch_split_prompts, input_lengths)
else:
# mode 2: multiple different prompts corresponding to multiple images (1-1 correspondence)
length = [
sum([ids.shape[1] for ids in batch_split_prompt])
for batch_split_prompt in batch_split_prompts
]
length = [l + visual_atts.shape[1] for l in length]
input_lengths = torch.IntTensor(length).to(torch.int32)
input_ids, ptuning_args = self.setup_fake_prompts_vila(
self.args.batch_size, visual_features, batch_split_prompts,
input_lengths)
return input_ids, input_lengths, ptuning_args, visual_features, model_runner_input
elif self.model_type == 'phi-3-vision':
image_sizes = input["image_sizes"]
profiler.start("Feature transform")
visual_features = self.vision_model.hd_feature_transform(
visual_features, image_sizes)
profiler.stop("Feature transform")
input_ids = input["input_ids"].clone()
input_ids = input_ids.expand(self.args.batch_size,
*input_ids.shape[1:])
num_img_tokens = [visual_features.shape[0]]
input_ids = self.ptuning_setup_phi3(visual_features, input_ids,
num_img_tokens)
visual_features = visual_features.unsqueeze(0).repeat(
self.args.batch_size, 1, 1)
length = input_ids.shape[1]
elif self.model_type == 'llava_next':
visual_features = LlavaNextUtils.rearrange_image_features(
visual_features, self.image_newlines["image_newline"],
image_size)
input_ids = self.ptuning_setup_llava_next(visual_features,
pre_prompt, post_prompt)
length = input_ids.shape[1]
elif self.model_type == 'mllama':
pre_input_ids = self.tokenizer(pre_prompt,
return_tensors="pt",
padding=True).input_ids
if n_prompts_n_images:
length = [pre_input_ids.shape[1]] * self.args.batch_size
else:
length = pre_input_ids.shape[1]
post_input_ids = None
elif self.model_type == 'llava_onevision':
if self.args.video_path is None:
visual_features = torch.split(visual_features,
visual_features.shape[0] //
self.args.batch_size,
dim=0)
visual_features = LlavaOnevisionUtils.pack_image_features(
visual_features,
image_size,
image_newline=self.image_newlines["image_newline"],
)
else:
visual_features = LlavaOnevisionUtils.apply_pooling(
visual_features)
visual_features = visual_features.reshape(
self.args.batch_size,
self.num_frames * visual_features.shape[1], -1)
image_newline = self.image_newlines["image_newline"][
None, None, :].repeat(self.args.batch_size, 1,
1).to(visual_features.device)
visual_features = torch.cat((visual_features, image_newline),
dim=1)
pre_input_ids = self.tokenizer(pre_prompt,
return_tensors="pt",
padding=True).input_ids
post_input_ids = self.tokenizer(post_prompt,
return_tensors="pt",
padding=True).input_ids
length = pre_input_ids.shape[1] + visual_features.shape[
1] + post_input_ids.shape[1]
else:
pre_input_ids = self.tokenizer(pre_prompt,
return_tensors="pt",
padding=True).input_ids
if post_prompt[0] is not None:
post_input_encoded = self.tokenizer(post_prompt,
return_tensors="pt",
padding=True)
post_input_ids = post_input_encoded.input_ids
if n_prompts_n_images and 'neva' not in self.model_type:
post_input_attention_mask = post_input_encoded.attention_mask
post_input_ids = [
input_id[mask.bool()] for input_id, mask in zip(
post_input_ids, post_input_attention_mask)
]
if self.model_type == 'video-neva':
length = pre_input_ids.shape[1] + post_input_ids.shape[
1] + visual_atts.shape[2] * visual_atts.shape[1]
elif self.model_type == 'internvl':
length = pre_input_ids.shape[1] + post_input_ids.shape[
1] + visual_atts.shape[0] * visual_atts.shape[1]
else:
if n_prompts_n_images:
length = [
pre_input_ids.shape[1] + visual_atts.shape[1] +
post_input_id.shape[0]
for post_input_id in post_input_ids
]
else:
length = pre_input_ids.shape[1] + post_input_ids.shape[
1] + visual_atts.shape[1]
else:
post_input_ids = None
assert pre_input_ids.shape[0] == visual_atts.shape[0]
if visual_atts.shape[0] == 1:
length = pre_input_ids.shape[1] + visual_atts.shape[1]
else:
length = [
pre_input_ids.shape[1] + visual_atts.shape[1]
for _ in range(visual_atts.shape[0])
]
if n_prompts_n_images:
if isinstance(length, int): length = [length]
assert isinstance(length, list)
input_lengths = torch.IntTensor(length).to(torch.int32)
else:
assert isinstance(length, int)
input_lengths = torch.IntTensor([length] * self.args.batch_size).to(
torch.int32)
if self.model_type in [
'fuyu', 'kosmos-2', 'phi-3-vision', 'llava_next'
]:
return input_ids, input_lengths, [
visual_features
], visual_features, model_runner_input
input_ids, ptuning_args = self.setup_fake_prompts(
visual_features, pre_input_ids, post_input_ids, input_lengths)
return input_ids, input_lengths, ptuning_args, visual_features, model_runner_input
@staticmethod
def tokenizer_image_token(batch_size,
pre_prompt,
post_prompt,