mehmetseferioglu commited on
Commit
1059faf
·
verified ·
1 Parent(s): d6135ab

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -0
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModel
3
+ import math
4
+ from PIL import Image
5
+ import torchvision.transforms as T
6
+ from torchvision.transforms.functional import InterpolationMode
7
+
8
+
9
+ def split_model():
10
+ device_map = {}
11
+ world_size = torch.cuda.device_count()
12
+ num_layers = 80
13
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
14
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
15
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
16
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
17
+ layer_cnt = 0
18
+ for i, num_layer in enumerate(num_layers_per_gpu):
19
+ for j in range(num_layer):
20
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
21
+ layer_cnt += 1
22
+ device_map['vision_model'] = 0
23
+ device_map['mlp1'] = 0
24
+ device_map['language_model.model.tok_embeddings'] = 0
25
+ device_map['language_model.model.embed_tokens'] = 0
26
+ device_map['language_model.output'] = 0
27
+ device_map['language_model.model.norm'] = 0
28
+ device_map['language_model.lm_head'] = 0
29
+ device_map['language_model.model.rotary_emb'] = 0
30
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
31
+
32
+ return device_map
33
+
34
+
35
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
36
+ IMAGENET_STD = (0.229, 0.224, 0.225)
37
+
38
+
39
+ def build_transform(input_size):
40
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
41
+ transform = T.Compose([
42
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
43
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
44
+ T.ToTensor(),
45
+ T.Normalize(mean=MEAN, std=STD)
46
+ ])
47
+ return transform
48
+
49
+
50
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
51
+ best_ratio_diff = float('inf')
52
+ best_ratio = (1, 1)
53
+ area = width * height
54
+ for ratio in target_ratios:
55
+ target_aspect_ratio = ratio[0] / ratio[1]
56
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
57
+ if ratio_diff < best_ratio_diff:
58
+ best_ratio_diff = ratio_diff
59
+ best_ratio = ratio
60
+ elif ratio_diff == best_ratio_diff:
61
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
62
+ best_ratio = ratio
63
+ return best_ratio
64
+
65
+
66
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
67
+ orig_width, orig_height = image.size
68
+ aspect_ratio = orig_width / orig_height
69
+
70
+ # calculate the existing image aspect ratio
71
+ target_ratios = set(
72
+ (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
73
+ i * j <= max_num and i * j >= min_num)
74
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
75
+
76
+ # find the closest aspect ratio to the target
77
+ target_aspect_ratio = find_closest_aspect_ratio(
78
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
79
+
80
+ # calculate the target width and height
81
+ target_width = image_size * target_aspect_ratio[0]
82
+ target_height = image_size * target_aspect_ratio[1]
83
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
84
+
85
+ # resize the image
86
+ resized_img = image.resize((target_width, target_height))
87
+ processed_images = []
88
+ for i in range(blocks):
89
+ box = (
90
+ (i % (target_width // image_size)) * image_size,
91
+ (i // (target_width // image_size)) * image_size,
92
+ ((i % (target_width // image_size)) + 1) * image_size,
93
+ ((i // (target_width // image_size)) + 1) * image_size
94
+ )
95
+ # split the image
96
+ split_img = resized_img.crop(box)
97
+ processed_images.append(split_img)
98
+ assert len(processed_images) == blocks
99
+ if use_thumbnail and len(processed_images) != 1:
100
+ thumbnail_img = image.resize((image_size, image_size))
101
+ processed_images.append(thumbnail_img)
102
+ return processed_images
103
+
104
+
105
+ def load_image(image_file, input_size=448, max_num=12):
106
+ image = Image.open(image_file).convert('RGB')
107
+ transform = build_transform(input_size=input_size)
108
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
109
+ pixel_values = [transform(image) for image in images]
110
+ pixel_values = torch.stack(pixel_values)
111
+ return pixel_values
112
+
113
+ path = "nvidia/NVLM-D-72B"
114
+ device_map = split_model()
115
+ model = AutoModel.from_pretrained(
116
+ path,
117
+ torch_dtype=torch.bfloat16,
118
+ low_cpu_mem_usage=True,
119
+ use_flash_attn=False,
120
+ trust_remote_code=True,
121
+ device_map=device_map).eval()
122
+
123
+ print(model)
124
+
125
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
126
+ generation_config = dict(max_new_tokens=1024, do_sample=False)
127
+
128
+ # pure-text conversation
129
+ question = 'Hello, who are you?'
130
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
131
+ print(f'User: {question}\nAssistant: {response}')
132
+
133
+ # single-image single-round conversation
134
+ pixel_values = load_image('path/to/your/example/image.jpg', max_num=6).to(
135
+ torch.bfloat16)
136
+ question = '<image>\nPlease describe the image shortly.'
137
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
138
+ print(f'User: {question}\nAssistant: {response}')