(self, conversations, language_model_inputs, modal_type="image")
| 318 | |
| 319 | @torch.no_grad() |
| 320 | def answer(self, conversations, language_model_inputs, modal_type="image"): |
| 321 | model_inputs = self.tokenizer( |
| 322 | conversations, |
| 323 | return_tensors="pt", |
| 324 | ) |
| 325 | model_inputs.pop("token_type_ids", None) |
| 326 | |
| 327 | input_ids = model_inputs["input_ids"].to(self.device) |
| 328 | attention_mask = model_inputs["attention_mask"].to(self.device) |
| 329 | |
| 330 | if modal_type == "text": |
| 331 | generation_output = self.model.language_model.generate( |
| 332 | input_ids=input_ids, |
| 333 | attention_mask=attention_mask, |
| 334 | generation_config=self.generation_config, |
| 335 | return_dict_in_generate=True, |
| 336 | output_scores=True |
| 337 | ) |
| 338 | else: |
| 339 | pixel_values = model_inputs.pop("pixel_values", None) |
| 340 | if pixel_values is not None: |
| 341 | pixel_values = pixel_values.to(self.device) |
| 342 | |
| 343 | generation_output = self.model.generate( |
| 344 | pixel_values=pixel_values, |
| 345 | input_ids=input_ids, |
| 346 | attention_mask=attention_mask, |
| 347 | language_model_inputs=language_model_inputs, |
| 348 | generation_config=self.generation_config, |
| 349 | return_dict_in_generate=True, |
| 350 | output_scores=True |
| 351 | ) |
| 352 | |
| 353 | preds = generation_output.sequences |
| 354 | outputs = self.tokenizer.batch_decode(preds, skip_special_tokens=True)[0] |
| 355 | |
| 356 | if modal_type == "text": |
| 357 | skip_echo_len = len(conversations[0]) - conversations[0].count("</s>") * 3 |
| 358 | outputs = outputs[skip_echo_len:].strip() |
| 359 | |
| 360 | return outputs |
| 361 | |
| 362 | if __name__ == '__main__': |
| 363 | model_path = “your path” |
no test coverage detected