shawn0wang commited on
Commit
ae0ae78
·
verified ·
1 Parent(s): cf116c6

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +107 -15
README.md CHANGED
@@ -256,18 +256,104 @@ The model follows a connection pattern of Vision Encoder → MLP Adapter → Lan
256
  ## 5. Usage
257
 
258
  ```python
259
- from transformers import AutoTokenizer, AutoConfig, AutoModel, CLIPImageProcessor
260
- from utils_ import split_model, load_image
261
- import sys, os
262
  import torch
 
 
 
 
263
 
 
 
264
 
265
- path = 'Skywork/Skywork-R1V-38B'
266
- image_path = "/path/to/image"
 
 
 
 
 
 
 
267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
- device_map, visible_devices = split_model(path)
270
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  model = AutoModel.from_pretrained(
272
  path,
273
  torch_dtype=torch.bfloat16,
@@ -276,19 +362,25 @@ model = AutoModel.from_pretrained(
276
  use_flash_attn=True,
277
  trust_remote_code=True,
278
  device_map=device_map).eval()
279
-
280
  generation_config = dict(max_new_tokens=64000, do_sample=True, temperature=0.6, top_p=0.95, repetition_penalty=1.05)
281
- pixel_values = load_image(image_path, max_num=12).to(torch.bfloat16).cuda()
282
-
283
- # pure-text conversation (纯文本对话)
284
- question = 'If all cats can fly, and Tom is a cat, can Tom fly?'
285
- response = model.chat(tokenizer, None, question, generation_config, history=None)
286
- print(f'User: {question}\nAssistant: {response}')
287
 
288
- # single-image single-round conversation (单图单轮对话)
 
289
  question = '<image>\nSelect the correct option from this question.'
290
  response = model.chat(tokenizer, pixel_values, question, generation_config)
291
  print(f'User: {question}\nAssistant: {response}')
 
 
 
 
 
 
 
 
 
 
 
292
  ```
293
 
294
  ---
 
256
  ## 5. Usage
257
 
258
  ```python
259
+ import math
 
 
260
  import torch
261
+ import torchvision.transforms as T
262
+ from PIL import Image
263
+ from torchvision.transforms.functional import InterpolationMode
264
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
265
 
266
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
267
+ IMAGENET_STD = (0.229, 0.224, 0.225)
268
 
269
+ def build_transform(input_size):
270
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
271
+ transform = T.Compose([
272
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
273
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
274
+ T.ToTensor(),
275
+ T.Normalize(mean=MEAN, std=STD)
276
+ ])
277
+ return transform
278
 
279
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
280
+ best_ratio_diff = float('inf')
281
+ best_ratio = (1, 1)
282
+ area = width * height
283
+ for ratio in target_ratios:
284
+ target_aspect_ratio = ratio[0] / ratio[1]
285
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
286
+ if ratio_diff < best_ratio_diff:
287
+ best_ratio_diff = ratio_diff
288
+ best_ratio = ratio
289
+ elif ratio_diff == best_ratio_diff:
290
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
291
+ best_ratio = ratio
292
+ return best_ratio
293
 
294
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
295
+ orig_width, orig_height = image.size
296
+ aspect_ratio = orig_width / orig_height
297
+ target_ratios = set(
298
+ (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
299
+ i * j <= max_num and i * j >= min_num)
300
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
301
+ target_aspect_ratio = find_closest_aspect_ratio(
302
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
303
+ target_width = image_size * target_aspect_ratio[0]
304
+ target_height = image_size * target_aspect_ratio[1]
305
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
306
+ resized_img = image.resize((target_width, target_height))
307
+ processed_images = []
308
+ for i in range(blocks):
309
+ box = (
310
+ (i % (target_width // image_size)) * image_size,
311
+ (i // (target_width // image_size)) * image_size,
312
+ ((i % (target_width // image_size)) + 1) * image_size,
313
+ ((i // (target_width // image_size)) + 1) * image_size
314
+ )
315
+ split_img = resized_img.crop(box)
316
+ processed_images.append(split_img)
317
+ assert len(processed_images) == blocks
318
+ if use_thumbnail and len(processed_images) != 1:
319
+ thumbnail_img = image.resize((image_size, image_size))
320
+ processed_images.append(thumbnail_img)
321
+ return processed_images
322
+
323
+ def load_image(image_file, input_size=448, max_num=12):
324
+ image = Image.open(image_file).convert('RGB')
325
+ transform = build_transform(input_size=input_size)
326
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
327
+ pixel_values = [transform(image) for image in images]
328
+ pixel_values = torch.stack(pixel_values)
329
+ return pixel_values
330
+
331
+ def split_model(model_path):
332
+ device_map = {}
333
+ world_size = torch.cuda.device_count()
334
+ config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
335
+ num_layers = config.llm_config.num_hidden_layers
336
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
337
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
338
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
339
+ layer_cnt = 0
340
+ for i, num_layer in enumerate(num_layers_per_gpu):
341
+ for j in range(num_layer):
342
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
343
+ layer_cnt += 1
344
+ device_map['vision_model'] = 0
345
+ device_map['mlp1'] = 0
346
+ device_map['language_model.model.tok_embeddings'] = 0
347
+ device_map['language_model.model.embed_tokens'] = 0
348
+ device_map['language_model.output'] = 0
349
+ device_map['language_model.model.norm'] = 0
350
+ device_map['language_model.model.rotary_emb'] = 0
351
+ device_map['language_model.lm_head'] = 0
352
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
353
+ return device_map
354
+
355
+ path = 'Skywork/Skywork-R1V-38B'
356
+ device_map = split_model(path)
357
  model = AutoModel.from_pretrained(
358
  path,
359
  torch_dtype=torch.bfloat16,
 
362
  use_flash_attn=True,
363
  trust_remote_code=True,
364
  device_map=device_map).eval()
365
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
366
  generation_config = dict(max_new_tokens=64000, do_sample=True, temperature=0.6, top_p=0.95, repetition_penalty=1.05)
 
 
 
 
 
 
367
 
368
+ # single-image conversation
369
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
370
  question = '<image>\nSelect the correct option from this question.'
371
  response = model.chat(tokenizer, pixel_values, question, generation_config)
372
  print(f'User: {question}\nAssistant: {response}')
373
+
374
+ # multi-image conversation
375
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
376
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
377
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
378
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
379
+ question = '<image>\n<image>\nSelect the correct option from this question.'
380
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
381
+ num_patches_list=num_patches_list,
382
+ history=None, return_history=True)
383
+ print(f'User: {question}\nAssistant: {response}')
384
  ```
385
 
386
  ---