
"""simple docstring"""





import math
import unittest

from transformers import BioGptConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    BioGptForCausalLM,
				    BioGptForSequenceClassification,
				    BioGptForTokenClassification,
				    BioGptModel,
				    BioGptTokenizer,
				)
				from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST






class    _UpperCAmelCase:



		def __init__( self    ,		__a    ,		__a=13    ,		__a=7    ,		__a=True    ,		__a=True    ,		__a=False    ,		__a=True    ,		__a=99    ,		__a=32    ,		__a=5    ,		__a=4    ,		__a=37    ,		__a="gelu"    ,		__a=0.1    ,		__a=0.1    ,		__a=5_12    ,		__a=16    ,		__a=2    ,		__a=0.02    ,		__a=3    ,		__a=4    ,		__a=None    ,		)	->	Tuple:






							'''simple docstring'''
							_UpperCamelCase										=  parent
							_UpperCamelCase										=  batch_size
							_UpperCamelCase										=  seq_length
							_UpperCamelCase										=  is_training
							_UpperCamelCase										=  use_input_mask
							_UpperCamelCase										=  use_token_type_ids
							_UpperCamelCase										=  use_labels
							_UpperCamelCase										=  vocab_size
							_UpperCamelCase										=  hidden_size
							_UpperCamelCase										=  num_hidden_layers
							_UpperCamelCase										=  num_attention_heads
							_UpperCamelCase										=  intermediate_size
							_UpperCamelCase										=  hidden_act
							_UpperCamelCase										=  hidden_dropout_prob
							_UpperCamelCase										=  attention_probs_dropout_prob
							_UpperCamelCase										=  max_position_embeddings
							_UpperCamelCase										=  type_vocab_size
							_UpperCamelCase										=  type_sequence_label_size
							_UpperCamelCase										=  initializer_range
							_UpperCamelCase										=  num_labels
							_UpperCamelCase										=  num_choices
							_UpperCamelCase										=  scope



		def 						UpperCAmelCase							( self)	->	Tuple:






							'''simple docstring'''
							_UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]    ,		self.vocab_size)

							_UpperCamelCase										=  None
							if self.use_input_mask:
												_UpperCamelCase										=  random_attention_mask([self.batch_size, self.seq_length])

							_UpperCamelCase										=  None
							if self.use_token_type_ids:
												_UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]    ,		self.type_vocab_size)

							_UpperCamelCase										=  None
							_UpperCamelCase										=  None
							_UpperCamelCase										=  None
							if self.use_labels:
												_UpperCamelCase										=  ids_tensor([self.batch_size]    ,		self.type_sequence_label_size)
												_UpperCamelCase										=  ids_tensor([self.batch_size, self.seq_length]    ,		self.num_labels)
												_UpperCamelCase										=  ids_tensor([self.batch_size]    ,		self.num_choices)

							_UpperCamelCase										=  self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



		def 						UpperCAmelCase							( self)	->	str:






							'''simple docstring'''
							return BioGptConfig(
							    vocab_size=self.vocab_size    ,		hidden_size=self.hidden_size    ,		num_hidden_layers=self.num_hidden_layers    ,		num_attention_heads=self.num_attention_heads    ,		intermediate_size=self.intermediate_size    ,		hidden_act=self.hidden_act    ,		hidden_dropout_prob=self.hidden_dropout_prob    ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,		max_position_embeddings=self.max_position_embeddings    ,		type_vocab_size=self.type_vocab_size    ,		is_decoder=__a    ,		initializer_range=self.initializer_range    ,		)



		def 						UpperCAmelCase							( self    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a)	->	Any:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptModel(config=__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase										=  model(__a    ,		attention_mask=__a)
							_UpperCamelCase										=  model(__a)
							self.parent.assertEqual(result.last_hidden_state.shape    ,		(self.batch_size, self.seq_length, self.hidden_size))



		def 						UpperCAmelCase							( self    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		)	->	Optional[int]:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptForCausalLM(config=__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase										=  model(__a    ,		attention_mask=__a    ,		token_type_ids=__a    ,		labels=__a)
							self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.seq_length, self.vocab_size))



		def 						UpperCAmelCase							( self    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		*__a)	->	Optional[int]:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptModel(config=__a)
							model.to(__a)
							model.eval()

							# create attention mask
							_UpperCamelCase										=  torch.ones(input_ids.shape    ,		dtype=torch.long    ,		device=__a)
							_UpperCamelCase										=  self.seq_length // 2
							_UpperCamelCase										=  0

							# first forward pass
							_UpperCamelCase			,  _UpperCamelCase										=  model(__a    ,		attention_mask=__a).to_tuple()

							# create hypothetical next token and extent to next_input_ids
							_UpperCamelCase										=  ids_tensor((self.batch_size, 1)    ,		config.vocab_size)

							# change a random masked slice from input_ids
							_UpperCamelCase										=  ids_tensor((1,)    ,		__a).item() + 1
							_UpperCamelCase										=  ids_tensor((self.batch_size, 1)    ,		config.vocab_size).squeeze(-1)
							_UpperCamelCase										=  random_other_next_tokens

							# append to next input_ids and attn_mask
							_UpperCamelCase										=  torch.cat([input_ids, next_tokens]    ,		dim=-1)
							_UpperCamelCase										=  torch.cat(
							    [attn_mask, torch.ones((attn_mask.shape[0], 1)    ,		dtype=torch.long    ,		device=__a)]    ,		dim=1    ,		)

							# get two different outputs
							_UpperCamelCase										=  model(__a    ,		attention_mask=__a)['''last_hidden_state''']
							_UpperCamelCase										=  model(__a    ,		past_key_values=__a    ,		attention_mask=__a)['''last_hidden_state''']

							# select random slice
							_UpperCamelCase										=  ids_tensor((1,)    ,		output_from_past.shape[-1]).item()
							_UpperCamelCase										=  output_from_no_past[:, -1, random_slice_idx].detach()
							_UpperCamelCase										=  output_from_past[:, 0, random_slice_idx].detach()

							# test that outputs are equal for slice
							self.parent.assertTrue(torch.allclose(__a    ,		__a    ,		atol=1e-3))



		def 						UpperCAmelCase							( self    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		*__a)	->	Optional[int]:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptModel(config=__a).to(__a).eval()

							_UpperCamelCase										=  torch.ones(input_ids.shape    ,		dtype=torch.long    ,		device=__a)

							# first forward pass
							_UpperCamelCase										=  model(__a    ,		attention_mask=__a    ,		use_cache=__a)

							_UpperCamelCase			,  _UpperCamelCase										=  outputs.to_tuple()

							# create hypothetical multiple next token and extent to next_input_ids
							_UpperCamelCase										=  ids_tensor((self.batch_size, 3)    ,		config.vocab_size)
							_UpperCamelCase										=  ids_tensor((self.batch_size, 3)    ,		2)

							# append to next input_ids and
							_UpperCamelCase										=  torch.cat([input_ids, next_tokens]    ,		dim=-1)
							_UpperCamelCase										=  torch.cat([attention_mask, next_attn_mask]    ,		dim=-1)

							_UpperCamelCase										=  model(__a    ,		attention_mask=__a)['''last_hidden_state''']
							_UpperCamelCase										=  model(__a    ,		attention_mask=__a    ,		past_key_values=__a)[
							    '''last_hidden_state'''
							]

							# select random slice
							_UpperCamelCase										=  ids_tensor((1,)    ,		output_from_past.shape[-1]).item()
							_UpperCamelCase										=  output_from_no_past[:, -3:, random_slice_idx].detach()
							_UpperCamelCase										=  output_from_past[:, :, random_slice_idx].detach()

							self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])

							# test that outputs are equal for slice
							self.parent.assertTrue(torch.allclose(__a    ,		__a    ,		atol=1e-3))



		def 						UpperCAmelCase							( self    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		*__a    ,		__a=False)	->	List[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptForCausalLM(__a)
							model.to(__a)
							if gradient_checkpointing:
												model.gradient_checkpointing_enable()

							_UpperCamelCase										=  model(__a    ,		labels=__a)
							self.parent.assertEqual(result.loss.shape    ,		())
							self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.seq_length, self.vocab_size))
							result.loss.backward()



		def 						UpperCAmelCase							( self    ,		__a    ,		*__a)	->	Any:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptModel(__a)
							_UpperCamelCase										=  model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers)
							for key in model.state_dict().keys():
												if "c_proj" in key and "weight" in key:
																	self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]) - model_std)    ,		0.001)
																	self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]) - 0.0)    ,		0.01)



		def 						UpperCAmelCase							( self    ,		__a    ,		__a    ,		__a    ,		__a    ,		__a    ,		*__a)	->	List[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  self.num_labels
							_UpperCamelCase										=  BioGptForTokenClassification(__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase										=  model(__a    ,		attention_mask=__a    ,		token_type_ids=__a)
							self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.seq_length, self.num_labels))




		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  self.prepare_config_and_inputs()
							(
							    (
							    _UpperCamelCase
							)			,  (
							    _UpperCamelCase
							)			,  (
							    _UpperCamelCase
							)			,  (
							    _UpperCamelCase
							)			,  (
							    _UpperCamelCase
							)			,  (
							    _UpperCamelCase
							)			,  (
							    _UpperCamelCase
							)			,  
							)										=  config_and_inputs
							_UpperCamelCase										=  {'''input_ids''': input_ids, '''attention_mask''': input_mask}
							return config, inputs_dict






@require_torch
class    _UpperCAmelCase(   lowerCamelCase				,					lowerCamelCase				,					lowerCamelCase				,					unittest.TestCase     ):
		lowercase__      =				(
		    (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
		    if is_torch_available()
		    else ()
		)
		lowercase__      =				(BioGptForCausalLM,) if is_torch_available() else ()
		lowercase__      =				(
		    {
		        'feature-extraction': BioGptModel,
		        'text-classification': BioGptForSequenceClassification,
		        'text-generation': BioGptForCausalLM,
		        'token-classification': BioGptForTokenClassification,
		        'zero-shot': BioGptForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		lowercase__      =				False



		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptModelTester(self)
							_UpperCamelCase										=  ConfigTester(self    ,		config_class=__a    ,		hidden_size=37)



		def 						UpperCAmelCase							( self)	->	str:






							'''simple docstring'''
							self.config_tester.run_common_tests()



		def 						UpperCAmelCase							( self)	->	int:






							'''simple docstring'''
							_UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__a)



		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
												_UpperCamelCase										=  type
												self.model_tester.create_and_check_model(*__a)



		def 						UpperCAmelCase							( self)	->	Any:






							'''simple docstring'''
							_UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__a)



		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_forward_and_backwards(*__a    ,		gradient_checkpointing=__a)



		def 						UpperCAmelCase							( self)	->	Tuple:






							'''simple docstring'''
							_UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__a)



		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_biogpt_weight_initialization(*__a)



		def 						UpperCAmelCase							( self)	->	List[str]:






							'''simple docstring'''
							_UpperCamelCase										=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_biogpt_for_token_classification(*__a)



		@slow
		def 						UpperCAmelCase							( self)	->	Tuple:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptForCausalLM.from_pretrained('''microsoft/biogpt''')
							model.to(__a)
							_UpperCamelCase										=  BioGptTokenizer.from_pretrained('''microsoft/biogpt''')

							_UpperCamelCase										=  '''left'''

							# Define PAD Token = EOS Token = 50256
							_UpperCamelCase										=  tokenizer.eos_token
							_UpperCamelCase										=  model.config.eos_token_id

							# use different length sentences to test batching
							_UpperCamelCase										=  [
							    '''Hello, my dog is a little''',
							    '''Today, I''',
							]

							_UpperCamelCase										=  tokenizer(__a    ,		return_tensors='''pt'''    ,		padding=__a)
							_UpperCamelCase										=  inputs['''input_ids'''].to(__a)

							_UpperCamelCase										=  model.generate(
							    input_ids=__a    ,		attention_mask=inputs['''attention_mask'''].to(__a)    ,		)

							_UpperCamelCase										=  tokenizer(sentences[0]    ,		return_tensors='''pt''').input_ids.to(__a)
							_UpperCamelCase										=  model.generate(input_ids=__a)

							_UpperCamelCase										=  inputs_non_padded.shape[-1] - inputs['''attention_mask'''][-1].long().sum().cpu().item()
							_UpperCamelCase										=  tokenizer(sentences[1]    ,		return_tensors='''pt''').input_ids.to(__a)
							_UpperCamelCase										=  model.generate(input_ids=__a    ,		max_length=model.config.max_length - num_paddings)

							_UpperCamelCase										=  tokenizer.batch_decode(__a    ,		skip_special_tokens=__a)
							_UpperCamelCase										=  tokenizer.decode(output_non_padded[0]    ,		skip_special_tokens=__a)
							_UpperCamelCase										=  tokenizer.decode(output_padded[0]    ,		skip_special_tokens=__a)

							_UpperCamelCase										=  [
							    '''Hello, my dog is a little bit bigger than a little bit.''',
							    '''Today, I have a good idea of how to use the information''',
							]
							self.assertListEqual(__a    ,		__a)
							self.assertListEqual(__a    ,		[non_padded_sentence, padded_sentence])



		@slow
		def 						UpperCAmelCase							( self)	->	int:






							'''simple docstring'''
							for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												_UpperCamelCase										=  BioGptModel.from_pretrained(__a)
												self.assertIsNotNone(__a)



		def 						UpperCAmelCase							( self)	->	List[Any]:






							'''simple docstring'''
							_UpperCamelCase			,  _UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCamelCase										=  3
							_UpperCamelCase										=  input_dict['''input_ids''']
							_UpperCamelCase										=  input_ids.ne(1).to(__a)
							_UpperCamelCase										=  ids_tensor([self.model_tester.batch_size]    ,		self.model_tester.type_sequence_label_size)
							_UpperCamelCase										=  BioGptForSequenceClassification(__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase										=  model(__a    ,		attention_mask=__a    ,		labels=__a)
							self.assertEqual(result.logits.shape    ,		(self.model_tester.batch_size, self.model_tester.num_labels))




		def 						UpperCAmelCase							( self)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase			,  _UpperCamelCase										=  self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCamelCase										=  3
							_UpperCamelCase										=  '''multi_label_classification'''
							_UpperCamelCase										=  input_dict['''input_ids''']
							_UpperCamelCase										=  input_ids.ne(1).to(__a)
							_UpperCamelCase										=  ids_tensor(
							    [self.model_tester.batch_size, config.num_labels]    ,		self.model_tester.type_sequence_label_size).to(torch.float)
							_UpperCamelCase										=  BioGptForSequenceClassification(__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase										=  model(__a    ,		attention_mask=__a    ,		labels=__a)
							self.assertEqual(result.logits.shape    ,		(self.model_tester.batch_size, self.model_tester.num_labels))






@require_torch
class    _UpperCAmelCase(   unittest.TestCase     ):



		@slow
		def 						UpperCAmelCase							( self)	->	Dict:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptForCausalLM.from_pretrained('''microsoft/biogpt''')
							_UpperCamelCase										=  torch.tensor([[2, 48_05, 9, 6_56, 21]])
							_UpperCamelCase										=  model(__a)[0]

							_UpperCamelCase										=  4_23_84

							_UpperCamelCase										=  torch.Size((1, 5, vocab_size))
							self.assertEqual(output.shape    ,		__a)

							_UpperCamelCase										=  torch.tensor(
							    [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]])

							self.assertTrue(torch.allclose(output[:, :3, :3]    ,		__a    ,		atol=1e-4))




		@slow
		def 						UpperCAmelCase							( self)	->	int:






							'''simple docstring'''
							_UpperCamelCase										=  BioGptTokenizer.from_pretrained('''microsoft/biogpt''')
							_UpperCamelCase										=  BioGptForCausalLM.from_pretrained('''microsoft/biogpt''')
							model.to(__a)

							torch.manual_seed(0)
							_UpperCamelCase										=  tokenizer('''COVID-19 is'''    ,		return_tensors='''pt''').to(__a)
							_UpperCamelCase										=  model.generate(
							    **__a    ,		min_length=1_00    ,		max_length=10_24    ,		num_beams=5    ,		early_stopping=__a    ,		)
							_UpperCamelCase										=  tokenizer.decode(output_ids[0]    ,		skip_special_tokens=__a)

							_UpperCamelCase										=  (
							    '''COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the'''
							    ''' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and'''
							    ''' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),'''
							    ''' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and'''
							    ''' more than 800,000 deaths.'''
							)
							self.assertEqual(__a    ,		__a)








"""simple docstring"""





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

import torch

from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
				from PIL import Image






class    _UpperCAmelCase(   lowerCamelCase     ):
		lowercase__      =				'dandelin/vilt-b32-finetuned-vqa'
		lowercase__      =				(
		    'This is a tool that answers a question about an image. It takes an input named `image` which should be the '
		    'image containing the information, as well as a `question` which should be the question in English. It '
		    'returns a text that is the answer to the question.'
		)
		lowercase__      =				'image_qa'
		lowercase__      =				AutoProcessor
		lowercase__      =				AutoModelForVisualQuestionAnswering

		lowercase__      =				['image', 'text']
		lowercase__      =				['text']



		def __init__( self    ,		*__a    ,		**__a)	->	int:






							'''simple docstring'''
							requires_backends(self    ,		['''vision'''])
							super().__init__(*__a    ,		**__a)



		def 						UpperCAmelCase							( self    ,		__a    ,		__a)	->	Dict:






							'''simple docstring'''
							return self.pre_processor(__a    ,		__a    ,		return_tensors='''pt''')



		def 						UpperCAmelCase							( self    ,		__a)	->	Tuple:






							'''simple docstring'''
							with torch.no_grad():
												return self.model(**__a).logits




		def 						UpperCAmelCase							( self    ,		__a)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  outputs.argmax(-1).item()
							return self.model.config.idalabel[idx]






