riddhimanrana commited on
Commit
e3a071a
·
verified ·
1 Parent(s): b56f974

Create predict.py

Browse files
Files changed (1) hide show
  1. predict.py +86 -0
predict.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Credit for this script goes to @ariG23498 who opened a PR on the apple/ml-fastvlm repo to add this model to hugging face transformers. The apple team still needs to convert the weights in order for it to be officially available.
2
+
3
+ import os
4
+ import argparse
5
+
6
+ import torch
7
+ from PIL import Image
8
+
9
+ from llava.conversation import conv_templates
10
+ from llava.mm_utils import tokenizer_image_token, process_images
11
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
12
+
13
+ from transformers import AutoTokenizer, AutoModelForCausalLM, CLIPImageProcessor
14
+
15
+ def predict(args):
16
+ model_id = args.model_path.split("/")[-1]
17
+ print(f"{model_id=}")
18
+
19
+ # Remove generation config from model folder
20
+ # to read generation parameters from args
21
+ model_path = os.path.expanduser(args.model_path)
22
+ generation_config = None
23
+ if os.path.exists(os.path.join(model_path, 'generation_config.json')):
24
+ generation_config = os.path.join(model_path, '.generation_config.json')
25
+ os.rename(os.path.join(model_path, 'generation_config.json'),
26
+ generation_config)
27
+
28
+ tokenizer = AutoTokenizer.from_pretrained(f"riddhimanrana/{model_id}")
29
+ model = AutoModelForCausalLM.from_pretrained(f"riddhimanrana/{model_id}", torch_dtype=torch.float16, device_map="cuda")
30
+ image_processor = CLIPImageProcessor.from_pretrained(f"riddhimanrana/{model_id}")
31
+
32
+ # Construct prompt
33
+ qs = args.prompt
34
+ if model.config.mm_use_im_start_end:
35
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
36
+ else:
37
+ qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
38
+ conv = conv_templates[args.conv_mode].copy()
39
+ conv.append_message(conv.roles[0], qs)
40
+ conv.append_message(conv.roles[1], None)
41
+ prompt = conv.get_prompt()
42
+
43
+ # Set the pad token id for generation
44
+ model.generation_config.pad_token_id = tokenizer.pad_token_id
45
+
46
+ # Tokenize prompt
47
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(torch.device("cuda"))
48
+
49
+ # Load and preprocess image
50
+ image = Image.open(args.image_file).convert('RGB')
51
+ image_tensor = process_images([image], image_processor, model.config)[0]
52
+
53
+ # Run inference
54
+ with torch.inference_mode():
55
+ output_ids = model.generate(
56
+ input_ids,
57
+ images=image_tensor.unsqueeze(0).half(),
58
+ image_sizes=[image.size],
59
+ do_sample=True if args.temperature > 0 else False,
60
+ temperature=args.temperature,
61
+ top_p=args.top_p,
62
+ num_beams=args.num_beams,
63
+ max_new_tokens=256,
64
+ use_cache=True)
65
+
66
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
67
+ print(outputs)
68
+
69
+ # Restore generation config
70
+ if generation_config is not None:
71
+ os.rename(generation_config, os.path.join(model_path, 'generation_config.json'))
72
+
73
+
74
+ if __name__ == "__main__":
75
+ parser = argparse.ArgumentParser()
76
+ parser.add_argument("--model-path", type=str, default="./llava-v1.5-0.5b")
77
+ parser.add_argument("--model-base", type=str, default=None)
78
+ parser.add_argument("--image-file", type=str, default=None, help="location of image file")
79
+ parser.add_argument("--prompt", type=str, default="Describe the image.", help="Prompt for VLM.")
80
+ parser.add_argument("--conv-mode", type=str, default="qwen_2")
81
+ parser.add_argument("--temperature", type=float, default=0.0)
82
+ parser.add_argument("--top_p", type=float, default=None)
83
+ parser.add_argument("--num_beams", type=int, default=1)
84
+ args = parser.parse_args()
85
+
86
+ predict(args)