mohitsha HF staff commited on
Commit
3eea21f
1 Parent(s): cc18b83

Upload test_llava_ort.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. test_llava_ort.py +257 -0
test_llava_ort.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Optional, Tuple
3
+
4
+ import onnxruntime as onnxrt
5
+ import requests
6
+ import torch
7
+ from PIL import Image
8
+ from transformers import AutoConfig, AutoProcessor, GenerationConfig, PreTrainedModel
9
+ from transformers.generation import GenerationMixin
10
+ from transformers.modeling_outputs import BaseModelOutput, CausalLMOutputWithPast
11
+
12
+ from optimum.utils import NormalizedConfigManager
13
+
14
+
15
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
16
+
17
+
18
+ device = torch.device("cpu")
19
+
20
+
21
+ model_name = "llava-1.5-7b-hf/"
22
+
23
+ processor = AutoProcessor.from_pretrained(model_name)
24
+ config = AutoConfig.from_pretrained(model_name)
25
+
26
+ prompt = "<image>\nUSER: What's the content of the image?\nASSISTANT:"
27
+ url = "https://www.ilankelman.org/stopsigns/australia.jpg"
28
+ image = Image.open(requests.get(url, stream=True).raw)
29
+
30
+ inputs = processor(text=prompt, images=image, return_tensors="pt")
31
+
32
+
33
+ class ORTModel(torch.nn.Module):
34
+ def __init__(self, path, config):
35
+ super().__init__()
36
+ self._device = device
37
+ self.config = config
38
+ self.session = onnxrt.InferenceSession(path, providers=["CPUExecutionProvider"])
39
+
40
+ self.input_names = {input_key.name: idx for idx, input_key in enumerate(self.session.get_inputs())}
41
+ self.output_names = {output_key.name: idx for idx, output_key in enumerate(self.session.get_outputs())}
42
+
43
+
44
+ class ORTEncoder(ORTModel):
45
+ def forward(
46
+ self,
47
+ input_ids: torch.FloatTensor,
48
+ pixel_values: torch.FloatTensor,
49
+ attention_mask: torch.LongTensor,
50
+ **kwargs,
51
+ ) -> BaseModelOutput:
52
+ onnx_inputs = {
53
+ "input_ids": input_ids.cpu().detach().numpy(),
54
+ "pixel_values": pixel_values.cpu().detach().numpy(),
55
+ "attention_mask": attention_mask.cpu().detach().numpy(),
56
+ }
57
+
58
+ # Run inference
59
+ outputs = self.session.run(None, onnx_inputs)
60
+
61
+ for i, output in enumerate(outputs):
62
+ outputs[i] = torch.from_numpy(output).to(self._device)
63
+
64
+ return (
65
+ outputs[self.output_names["inputs_embeds"]],
66
+ outputs[self.output_names["decoder_attention_mask"]],
67
+ outputs[self.output_names["position_ids"]],
68
+ )
69
+
70
+
71
+ class ORTDecoderProcessor(ORTModel):
72
+ def forward(
73
+ self,
74
+ input_ids: torch.FloatTensor,
75
+ attention_mask: torch.LongTensor,
76
+ past_key_value: torch.FloatTensor,
77
+ **kwargs,
78
+ ) -> BaseModelOutput:
79
+ onnx_inputs = {
80
+ "input_ids": input_ids.cpu().detach().numpy(),
81
+ "attention_mask": attention_mask.cpu().detach().numpy(),
82
+ "past_key_values.0.key": past_key_value.cpu().detach().numpy(),
83
+ }
84
+
85
+ # Run inference
86
+ outputs = self.session.run(None, onnx_inputs)
87
+
88
+ for i, output in enumerate(outputs):
89
+ outputs[i] = torch.from_numpy(output).to(self._device)
90
+
91
+ return (
92
+ outputs[self.output_names["inputs_embeds"]],
93
+ outputs[self.output_names["decoder_attention_mask"]],
94
+ outputs[self.output_names["position_ids"]],
95
+ )
96
+
97
+
98
+ class ORTDecoder(ORTModel):
99
+ def __init__(self, path, config):
100
+ super().__init__(path, config)
101
+
102
+ self.normalized_config = NormalizedConfigManager.get_normalized_config_class(config.text_config.model_type)(
103
+ config.text_config
104
+ )
105
+ self.generation_config = GenerationConfig.from_model_config(config)
106
+
107
+ self.key_value_input_names = [key for key in self.input_names if (".key" in key) or (".value" in key)]
108
+ self.key_value_output_names = [key for key in self.output_names if (".key" in key) or (".value" in key)]
109
+
110
+ self.num_pkv = 2
111
+
112
+ def prepare_pkv(self, batch_size: int):
113
+ if self.config.text_config.model_type in {"mistral", "llama"}:
114
+ num_attention_heads = self.normalized_config.num_key_value_heads
115
+ else:
116
+ num_attention_heads = self.normalized_config.num_attention_heads
117
+
118
+ embed_size_per_head = self.normalized_config.hidden_size // self.normalized_config.num_attention_heads
119
+
120
+ shape = (batch_size, num_attention_heads, 0, embed_size_per_head)
121
+ key_or_value = torch.zeros(shape, dtype=torch.float32)
122
+
123
+ past_key_values = tuple(key_or_value for _ in range(len(self.key_value_input_names)))
124
+
125
+ return past_key_values
126
+
127
+ def forward(
128
+ self,
129
+ attention_mask: torch.LongTensor,
130
+ position_ids: torch.LongTensor,
131
+ inputs_embeds: torch.FloatTensor,
132
+ past_key_values: Tuple[Tuple[torch.FloatTensor]] = None,
133
+ ) -> CausalLMOutputWithPast:
134
+ onnx_inputs = {
135
+ "attention_mask": attention_mask.cpu().detach().numpy(),
136
+ "position_ids": position_ids.cpu().detach().numpy(),
137
+ "inputs_embeds": inputs_embeds.cpu().detach().numpy(),
138
+ }
139
+
140
+ if past_key_values is None:
141
+ past_key_values = self.prepare_pkv(inputs_embeds.shape[0])
142
+ else:
143
+ past_key_values = tuple(
144
+ past_key_value for pkv_per_layer in past_key_values for past_key_value in pkv_per_layer
145
+ )
146
+
147
+ for input_name, past_key_value in zip(self.key_value_input_names, past_key_values):
148
+ onnx_inputs[input_name] = past_key_value.cpu().detach().numpy()
149
+
150
+ # Run inference
151
+ outputs = self.session.run(None, onnx_inputs)
152
+
153
+ logits = torch.from_numpy(outputs[self.output_names["logits"]])
154
+
155
+ past_key_values = tuple(
156
+ torch.from_numpy(outputs[self.output_names[key]]) for key in self.key_value_output_names
157
+ )
158
+
159
+ past_key_values = tuple(
160
+ past_key_values[i : i + self.num_pkv] for i in range(0, len(past_key_values), self.num_pkv)
161
+ )
162
+
163
+ return CausalLMOutputWithPast(logits=logits, past_key_values=past_key_values)
164
+
165
+
166
+ class ORTModelForLLava(PreTrainedModel, GenerationMixin):
167
+ def __init__(self, *args, **kwargs):
168
+ config = AutoConfig.from_pretrained(model_name)
169
+ super().__init__(config)
170
+
171
+ self.config = config
172
+ self._device = device
173
+
174
+ self.vision_tower = ORTEncoder(model_name + "encoder_model.onnx", config)
175
+ self.language_model = ORTDecoder(model_name + "decoder_model.onnx", config)
176
+ self.decoder_input_processor = ORTDecoderProcessor(model_name + "decoder_input_processor_model.onnx", config)
177
+
178
+ def forward(
179
+ self,
180
+ input_ids: torch.LongTensor = None,
181
+ pixel_values: torch.FloatTensor = None,
182
+ attention_mask: Optional[torch.Tensor] = None,
183
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
184
+ **kwargs,
185
+ ) -> CausalLMOutputWithPast:
186
+ if past_key_values is None:
187
+ inputs_embeds, attention_mask, position_ids = self.vision_tower(
188
+ input_ids=input_ids,
189
+ pixel_values=pixel_values,
190
+ attention_mask=attention_mask,
191
+ )
192
+ else:
193
+ inputs_embeds, attention_mask, position_ids = self.decoder_input_processor(
194
+ input_ids=input_ids,
195
+ attention_mask=attention_mask,
196
+ past_key_value=past_key_values[0][0][:, :, :, 0],
197
+ )
198
+
199
+ # Decode
200
+ decoder_outputs = self.language_model(
201
+ attention_mask=attention_mask,
202
+ position_ids=position_ids,
203
+ inputs_embeds=inputs_embeds,
204
+ past_key_values=past_key_values,
205
+ )
206
+
207
+ return decoder_outputs
208
+
209
+ def can_generate(self):
210
+ return True
211
+
212
+ def prepare_inputs_for_generation(
213
+ self, input_ids, past_key_values=None, inputs_embeds=None, pixel_values=None, attention_mask=None, **kwargs
214
+ ):
215
+ if past_key_values is not None:
216
+ cache_length = past_length = past_key_values[0][0].shape[2]
217
+
218
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
219
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
220
+ elif past_length < input_ids.shape[1]:
221
+ input_ids = input_ids[:, past_length:]
222
+ elif self.config.image_token_index in input_ids:
223
+ input_ids = input_ids[:, input_ids.shape[1] - 1 :]
224
+ if cache_length < past_length and attention_mask is not None:
225
+ attention_mask = attention_mask[:, -(cache_length + input_ids.shape[1]) :]
226
+
227
+ model_inputs = {"input_ids": input_ids}
228
+
229
+ model_inputs.update(
230
+ {
231
+ "past_key_values": past_key_values,
232
+ "use_cache": kwargs.get("use_cache"),
233
+ "attention_mask": attention_mask,
234
+ "pixel_values": pixel_values,
235
+ }
236
+ )
237
+ return model_inputs
238
+
239
+ @property
240
+ def device(self) -> torch.device:
241
+ return self._device
242
+
243
+ @device.setter
244
+ def device(self, value: torch.device):
245
+ self._device = value
246
+
247
+ def to(self, device):
248
+ self.device = device
249
+ return self
250
+
251
+
252
+ model = ORTModelForLLava()
253
+
254
+ generated_ids = model.generate(**inputs, max_length=30)
255
+ out = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
256
+
257
+ print(out)