huu-ontocord commited on
Commit
e558c61
·
verified ·
1 Parent(s): b392992

Create sample_inference.py

Browse files
Files changed (1) hide show
  1. sample_inference.py +129 -0
sample_inference.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ from PIL import Image
4
+ import requests
5
+ import torch
6
+ from transformers import AutoModelForCausalLM
7
+ from transformers import AutoProcessor
8
+ model_path = "./"
9
+
10
+ kwargs = {}
11
+ kwargs['torch_dtype'] = torch.bfloat16
12
+
13
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
14
+ model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True, torch_dtype="auto").cuda()
15
+
16
+ user_prompt = '<|user|>\n'
17
+ assistant_prompt = '<|assistant|>\n'
18
+ prompt_suffix = "<|end|>\n"
19
+
20
+ #################################################### text-only ####################################################
21
+ # single-image prompt
22
+ prompt = f"{user_prompt}what is the answer for 1+1? Explain it.{prompt_suffix}{assistant_prompt}"
23
+ print(f">>> Prompt\n{prompt}")
24
+ inputs = processor(prompt, images=None, return_tensors="pt").to("cuda:0")
25
+ generate_ids = model.generate(**inputs,
26
+ max_new_tokens=1000,
27
+ eos_token_id=processor.tokenizer.eos_token_id,
28
+ )
29
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
30
+ response = processor.batch_decode(generate_ids,
31
+ skip_special_tokens=True,
32
+ clean_up_tokenization_spaces=False)[0]
33
+ print(f'>>> Response\n{response}')
34
+
35
+ #################################################### text-only 2 ####################################################
36
+ # single-image prompt
37
+ prompt = f"{user_prompt}Give me the code for sloving two-sum problem.{prompt_suffix}{assistant_prompt}"
38
+ print(f">>> Prompt\n{prompt}")
39
+ inputs = processor(prompt, images=None, return_tensors="pt").to("cuda:0")
40
+ generate_ids = model.generate(**inputs,
41
+ max_new_tokens=1000,
42
+ eos_token_id=processor.tokenizer.eos_token_id,
43
+ )
44
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
45
+ response = processor.batch_decode(generate_ids,
46
+ skip_special_tokens=True,
47
+ clean_up_tokenization_spaces=False)[0]
48
+ print(f'>>> Response\n{response}')
49
+
50
+
51
+ #################################################### EXAMPLE 1 ####################################################
52
+ # single-image prompt
53
+ prompt = f"{user_prompt}<|image_1|>\nWhat is shown in this image?{prompt_suffix}{assistant_prompt}"
54
+ url = "https://www.ilankelman.org/stopsigns/australia.jpg"
55
+ print(f">>> Prompt\n{prompt}")
56
+ image = Image.open(requests.get(url, stream=True).raw)
57
+ inputs = processor(prompt, image, return_tensors="pt").to("cuda:0")
58
+ generate_ids = model.generate(**inputs,
59
+ max_new_tokens=1000,
60
+ eos_token_id=processor.tokenizer.eos_token_id,
61
+ )
62
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
63
+ response = processor.batch_decode(generate_ids,
64
+ skip_special_tokens=True,
65
+ clean_up_tokenization_spaces=False)[0]
66
+ print(f'>>> Response\n{response}')
67
+
68
+ #################################################### EXAMPLE 2 ####################################################
69
+ # multiple image prompt
70
+ # Note: image tokens must start from <|image_1|>
71
+ prompt = f"{user_prompt}<|image_1|>\n<|image_2|>\n What is shown in this two images?{prompt_suffix}{assistant_prompt}"
72
+ print(f">>> Prompt\n{prompt}")
73
+ url = "https://www.ilankelman.org/stopsigns/australia.jpg"
74
+ image_1 = Image.open(requests.get(url, stream=True).raw)
75
+ url = "https://img.freepik.com/free-photo/painting-mountain-lake-with-mountain-background_188544-9126.jpg?w=2000"
76
+ image_2 = Image.open(requests.get(url, stream=True).raw)
77
+ images = [image_1, image_2]
78
+ inputs = processor(prompt, images, return_tensors="pt").to("cuda:0")
79
+ generate_ids = model.generate(**inputs,
80
+ max_new_tokens=1000,
81
+ eos_token_id=processor.tokenizer.eos_token_id,
82
+ )
83
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
84
+ response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
85
+ print(f'>>> Response\n{response}')
86
+
87
+ #################################################### EXAMPLE 3 ####################################################
88
+ # chat template
89
+ chat = [
90
+ {"role": "user", "content": "<|image_1|>\nWhat is shown in this image?"},
91
+ {"role": "assistant", "content": "The image depicts a street scene with a prominent red stop sign in the foreground. The background showcases a building with traditional Chinese architecture, characterized by its red roof and ornate decorations. There are also several statues of lions, which are common in Chinese culture, positioned in front of the building. The street is lined with various shops and businesses, and there's a car passing by."},
92
+ {"role": "user", "content": "What is so special about this image"}
93
+ ]
94
+ url = "https://www.ilankelman.org/stopsigns/australia.jpg"
95
+ image = Image.open(requests.get(url, stream=True).raw)
96
+ prompt = processor.tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
97
+ # need to remove last <|endoftext|> if it is there, which is used for training, not inference. For training, make sure to add <|endoftext|> in the end.
98
+ if prompt.endswith("<|endoftext|>"):
99
+ prompt = prompt.rstrip("<|endoftext|>")
100
+
101
+ print(f">>> Prompt\n{prompt}")
102
+
103
+ inputs = processor(prompt, [image], return_tensors="pt").to("cuda:0")
104
+ generate_ids = model.generate(**inputs,
105
+ max_new_tokens=1000,
106
+ eos_token_id=processor.tokenizer.eos_token_id,
107
+ )
108
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
109
+ response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
110
+ print(f'>>> Response\n{response}')
111
+
112
+
113
+ ############################# to markdown #############################
114
+ # single-image prompt
115
+ prompt = f"{user_prompt}<|image_1|>\nCan you convert the table to markdown format?{prompt_suffix}{assistant_prompt}"
116
+ url = "https://support.content.office.net/en-us/media/3dd2b79b-9160-403d-9967-af893d17b580.png"
117
+ image = Image.open(requests.get(url, stream=True).raw)
118
+ inputs = processor(prompt, image, return_tensors="pt").to("cuda:0")
119
+
120
+ print(f">>> Prompt\n{prompt}")
121
+ generate_ids = model.generate(**inputs,
122
+ max_new_tokens=1000,
123
+ eos_token_id=processor.tokenizer.eos_token_id,
124
+ )
125
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
126
+ response = processor.batch_decode(generate_ids,
127
+ skip_special_tokens=False,
128
+ clean_up_tokenization_spaces=False)[0]
129
+ print(f'>>> Response\n{response}')