





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 					A_					:







       """simple docstring"""





       def __init__(     self						:						str    ,__A						:						Union[str, Any]    ,__A						:						Any=13    ,__A						:						Union[str, Any]=7    ,__A						:						List[Any]=True    ,__A						:						int=True    ,__A						:						Optional[Any]=False    ,__A						:						Union[str, Any]=True    ,__A						:						Union[str, Any]=99    ,__A						:						Any=32    ,__A						:						Tuple=5    ,__A						:						Tuple=4    ,__A						:						Union[str, Any]=37    ,__A						:						str="gelu"    ,__A						:						Optional[int]=0.1    ,__A						:						Dict=0.1    ,__A						:						Any=512    ,__A						:						Optional[Any]=16    ,__A						:						Any=2    ,__A						:						List[str]=0.02    ,__A						:						Dict=3    ,__A						:						Any=4    ,__A						:						int=None    ,)    ->       Dict:
         _lowercase						    =			parent
         _lowercase						    =			batch_size
         _lowercase						    =			seq_length
         _lowercase						    =			is_training
         _lowercase						    =			use_input_mask
         _lowercase						    =			use_token_type_ids
         _lowercase						    =			use_labels
         _lowercase						    =			vocab_size
         _lowercase						    =			hidden_size
         _lowercase						    =			num_hidden_layers
         _lowercase						    =			num_attention_heads
         _lowercase						    =			intermediate_size
         _lowercase						    =			hidden_act
         _lowercase						    =			hidden_dropout_prob
         _lowercase						    =			attention_probs_dropout_prob
         _lowercase						    =			max_position_embeddings
         _lowercase						    =			type_vocab_size
         _lowercase						    =			type_sequence_label_size
         _lowercase						    =			initializer_range
         _lowercase						    =			num_labels
         _lowercase						    =			num_choices
         _lowercase						    =			scope







       def  __UpperCAmelCase			(     self						:						List[Any]	)    ->       str:
         _lowercase						    =			ids_tensor([self.batch_size, self.seq_length]    ,self.vocab_size	)

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

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

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

         _lowercase						    =			self.get_config()

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







       def  __UpperCAmelCase			(     self						:						Union[str, Any]	)    ->       List[Any]:
         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						:						Optional[Any]    ,__A						:						List[Any]    ,__A						:						Optional[int]    ,__A						:						Optional[Any]    ,__A						:						str    ,__A						:						int    ,__A						:						int    ,__A						:						Optional[Any]	)    ->       int:
         _lowercase						    =			BioGptModel(config=__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			model(__A    ,attention_mask=__A	)
         _lowercase						    =			model(__A	)
         self.parent.assertEqual(result.last_hidden_state.shape    ,(self.batch_size, self.seq_length, self.hidden_size)	)







       def  __UpperCAmelCase			(     self						:						List[str]    ,__A						:						Optional[Any]    ,__A						:						Dict    ,__A						:						Dict    ,__A						:						Union[str, Any]    ,__A						:						str    ,__A						:						Any    ,__A						:						str    ,__A						:						List[Any]    ,__A						:						List[Any]    ,)    ->       Tuple:
         _lowercase						    =			BioGptForCausalLM(config=__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			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						:						Optional[int]    ,__A						:						str    ,__A						:						int    ,__A						:						int    ,__A						:						int    ,__A						:						List[Any]    ,*__A						:						Union[str, Any]	)    ->       Tuple:
         _lowercase						    =			BioGptModel(config=__A	)
         model.to(__A	)
         model.eval()

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

         # first forward pass
         _lowercase    ,		_lowercase						    =			model(__A    ,attention_mask=__A	).to_tuple()

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

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

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

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

         # select random slice
         _lowercase						    =			ids_tensor((1,)    ,output_from_past.shape[-1]	).item()
         _lowercase						    =			output_from_no_past[:, -1, random_slice_idx].detach()
         _lowercase						    =			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						:						Tuple    ,__A						:						List[str]    ,__A						:						Any    ,__A						:						List[Any]    ,__A						:						Dict    ,__A						:						Optional[int]    ,*__A						:						List[Any]	)    ->       List[str]:
         _lowercase						    =			BioGptModel(config=__A	).to(__A	).eval()

         _lowercase						    =			torch.ones(input_ids.shape    ,dtype=torch.long    ,device=__A	)

         # first forward pass
         _lowercase						    =			model(__A    ,attention_mask=__A    ,use_cache=__A	)

         _lowercase    ,		_lowercase						    =			outputs.to_tuple()

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

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

         _lowercase						    =			model(__A    ,attention_mask=__A	)['last_hidden_state']
         _lowercase						    =			model(__A    ,attention_mask=__A    ,past_key_values=__A	)[
             'last_hidden_state'
         ]

         # select random slice
         _lowercase						    =			ids_tensor((1,)    ,output_from_past.shape[-1]	).item()
         _lowercase						    =			output_from_no_past[:, -3:, random_slice_idx].detach()
         _lowercase						    =			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						:						Any    ,__A						:						List[str]    ,__A						:						int    ,__A						:						List[str]    ,__A						:						List[str]    ,__A						:						List[Any]    ,*__A						:						Any    ,__A						:						Union[str, Any]=False	)    ->       Any:
         _lowercase						    =			BioGptForCausalLM(__A	)
         model.to(__A	)
         if gradient_checkpointing:
           model.gradient_checkpointing_enable()

         _lowercase						    =			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						:						Tuple    ,__A						:						str    ,*__A						:						Tuple	)    ->       List[str]:
         _lowercase						    =			BioGptModel(__A	)
         _lowercase						    =			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						:						List[Any]    ,__A						:						Union[str, Any]    ,__A						:						Optional[Any]    ,__A						:						Any    ,__A						:						Union[str, Any]    ,__A						:						Dict    ,*__A						:						Any	)    ->       int:
         _lowercase						    =			self.num_labels
         _lowercase						    =			BioGptForTokenClassification(__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			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						:						Any	)    ->       Optional[int]:
         _lowercase						    =			self.prepare_config_and_inputs()
         (
             (
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		
         )						    =			config_and_inputs
         _lowercase						    =			{'input_ids': input_ids, 'attention_mask': input_mask}
         return config, inputs_dict





@require_torch
class 					A_					(   UpperCAmelCase       ,						UpperCAmelCase       ,						UpperCAmelCase       ,						unittest.TestCase						):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_   :			Tuple  			=	(
           (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
           if is_torch_available()
           else ()
       )
       SCREAMING_SNAKE_CASE_   :			Union[str, Any]  			=	(BioGptForCausalLM,) if is_torch_available() else ()
       SCREAMING_SNAKE_CASE_   :			List[Any]  			=	(
           {
               '''feature-extraction''': BioGptModel,
               '''text-classification''': BioGptForSequenceClassification,
               '''text-generation''': BioGptForCausalLM,
               '''token-classification''': BioGptForTokenClassification,
               '''zero-shot''': BioGptForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       SCREAMING_SNAKE_CASE_   :			Optional[Any]  			=	False







       def  __UpperCAmelCase			(     self						:						Optional[Any]	)    ->       Any:
         _lowercase						    =			BioGptModelTester(self	)
         _lowercase						    =			ConfigTester(self    ,config_class=__A    ,hidden_size=37	)







       def  __UpperCAmelCase			(     self						:						str	)    ->       Any:
         self.config_tester.run_common_tests()







       def  __UpperCAmelCase			(     self						:						str	)    ->       str:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__A	)







       def  __UpperCAmelCase			(     self						:						List[str]	)    ->       Optional[int]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
           _lowercase						    =			type
           self.model_tester.create_and_check_model(*__A	)







       def  __UpperCAmelCase			(     self						:						List[Any]	)    ->       List[str]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__A	)







       def  __UpperCAmelCase			(     self						:						Any	)    ->       List[Any]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_forward_and_backwards(*__A    ,gradient_checkpointing=__A	)







       def  __UpperCAmelCase			(     self						:						Any	)    ->       Tuple:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__A	)







       def  __UpperCAmelCase			(     self						:						Optional[int]	)    ->       List[str]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_biogpt_weight_initialization(*__A	)







       def  __UpperCAmelCase			(     self						:						Optional[int]	)    ->       Union[str, Any]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_biogpt_for_token_classification(*__A	)







       @slow
       def  __UpperCAmelCase			(     self						:						Any	)    ->       Optional[int]:
         _lowercase						    =			BioGptForCausalLM.from_pretrained('microsoft/biogpt'	)
         model.to(__A	)
         _lowercase						    =			BioGptTokenizer.from_pretrained('microsoft/biogpt'	)

         _lowercase						    =			'left'

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

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

         _lowercase						    =			tokenizer(__A    ,return_tensors='pt'    ,padding=__A	)
         _lowercase						    =			inputs['input_ids'].to(__A	)

         _lowercase						    =			model.generate(
             input_ids=__A    ,attention_mask=inputs['attention_mask'].to(__A	)    ,)

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

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

         _lowercase						    =			tokenizer.batch_decode(__A    ,skip_special_tokens=__A	)
         _lowercase						    =			tokenizer.decode(output_non_padded[0]    ,skip_special_tokens=__A	)
         _lowercase						    =			tokenizer.decode(output_padded[0]    ,skip_special_tokens=__A	)

         _lowercase						    =			[
             '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						:						Optional[Any]	)    ->       Optional[Any]:
         for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _lowercase						    =			BioGptModel.from_pretrained(__A	)
           self.assertIsNotNone(__A	)







       def  __UpperCAmelCase			(     self						:						int	)    ->       int:
         _lowercase    ,		_lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()
         _lowercase						    =			3
         _lowercase						    =			input_dict['input_ids']
         _lowercase						    =			input_ids.ne(1	).to(__A	)
         _lowercase						    =			ids_tensor([self.model_tester.batch_size]    ,self.model_tester.type_sequence_label_size	)
         _lowercase						    =			BioGptForSequenceClassification(__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			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[int]	)    ->       int:
         _lowercase    ,		_lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()
         _lowercase						    =			3
         _lowercase						    =			'multi_label_classification'
         _lowercase						    =			input_dict['input_ids']
         _lowercase						    =			input_ids.ne(1	).to(__A	)
         _lowercase						    =			ids_tensor(
             [self.model_tester.batch_size, config.num_labels]    ,self.model_tester.type_sequence_label_size	).to(torch.float	)
         _lowercase						    =			BioGptForSequenceClassification(__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			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 					A_					(   unittest.TestCase						):







       """simple docstring"""





       @slow
       def  __UpperCAmelCase			(     self						:						Union[str, Any]	)    ->       Optional[Any]:
         _lowercase						    =			BioGptForCausalLM.from_pretrained('microsoft/biogpt'	)
         _lowercase						    =			torch.tensor([[2, 4805, 9, 656, 21]]	)
         _lowercase						    =			model(__A	)[0]

         _lowercase						    =			4_2384

         _lowercase						    =			torch.Size((1, 5, vocab_size)	)
         self.assertEqual(output.shape    ,__A	)

         _lowercase						    =			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						:						Union[str, Any]	)    ->       List[str]:
         _lowercase						    =			BioGptTokenizer.from_pretrained('microsoft/biogpt'	)
         _lowercase						    =			BioGptForCausalLM.from_pretrained('microsoft/biogpt'	)
         model.to(__A	)

         torch.manual_seed(0	)
         _lowercase						    =			tokenizer('COVID-19 is'    ,return_tensors='pt'	).to(__A	)
         _lowercase						    =			model.generate(
             **__A    ,min_length=100    ,max_length=1024    ,num_beams=5    ,early_stopping=__A    ,)
         _lowercase						    =			tokenizer.decode(output_ids[0]    ,skip_special_tokens=__A	)

         _lowercase						    =			(
             '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	)



import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class 		__magic_name__						(snake_case_   ,snake_case_   ,unittest.TestCase				):





     '''simple docstring'''



     __lowercase				:							str	   =       IFImgaImgSuperResolutionPipeline
     __lowercase				:							Optional[Any]	   =       TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}
     __lowercase				:							int	   =       TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'}				)
     __lowercase				:							List[str]	   =       PipelineTesterMixin.required_optional_params - {'latents'}

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict   ):
       return self._get_superresolution_dummy_components()

     def 	SCREAMING_SNAKE_CASE__						(					self:Dict     ,		_a:int     ,		_a:Optional[Any]=0   ):
       if str(_a   ).startswith('''mps'''   ):
         snake_case__						= torch.manual_seed(_a   )
       else:
         snake_case__						= torch.Generator(device=_a   ).manual_seed(_a   )

       snake_case__						= floats_tensor((1, 3, 32, 32)     ,		rng=random.Random(_a   )   ).to(_a   )
       snake_case__						= floats_tensor((1, 3, 16, 16)     ,		rng=random.Random(_a   )   ).to(_a   )

       snake_case__						= {
           '''prompt''': '''A painting of a squirrel eating a burger''',
           '''image''': image,
           '''original_image''': original_image,
           '''generator''': generator,
           '''num_inference_steps''': 2,
           '''output_type''': '''numpy''',
       }

       return inputs

     @unittest.skipIf(
         torch_device != '''cuda''' or not is_xformers_available()     ,		reason='''XFormers attention is only available with CUDA and `xformers` installed'''     ,		)
     def 	SCREAMING_SNAKE_CASE__						(					self:Union[str, Any]   ):
       self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Tuple   ):
       self._test_save_load_optional_components()

     @unittest.skipIf(torch_device != '''cuda'''     ,		reason='''float16 requires CUDA'''   )
     def 	SCREAMING_SNAKE_CASE__						(					self:Dict   ):
       # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
       super().test_save_load_floataa(expected_max_diff=1e-1   )

     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[int]   ):
       self._test_attention_slicing_forward_pass(expected_max_diff=1e-2   )

     def 	SCREAMING_SNAKE_CASE__						(					self:str   ):
       self._test_save_load_local()







     def 	SCREAMING_SNAKE_CASE__						(					self:Union[str, Any]   ):
       self._test_inference_batch_single_identical(
           expected_max_diff=1e-2     ,		)

