




from .imports import is_rich_available


if is_rich_available():
    from rich.traceback import install

    install(show_locals=False)

else:
    raise ModuleNotFoundError("To use the rich extension, install rich with `pip install rich`")











'''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 	_lowerCAmelCase							:


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


	def     _a	(self							):
				A_	:						Tuple	=     ids_tensor([self.batch_size, self.seq_length]       ,      self.vocab_size							)

				A_	:						List[str]	=     None
				if self.use_input_mask:
							A_	:						Any	=     random_attention_mask([self.batch_size, self.seq_length]							)

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

				A_	:						Tuple	=     None
				A_	:						List[str]	=     None
				A_	:						List[str]	=     None
				if self.use_labels:
							A_	:						Any	=     ids_tensor([self.batch_size]       ,      self.type_sequence_label_size							)
							A_	:						Dict	=     ids_tensor([self.batch_size, self.seq_length]       ,      self.num_labels							)
							A_	:						str	=     ids_tensor([self.batch_size]       ,      self.num_choices							)

				A_	:						Optional[Any]	=     self.get_config()

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


	def     _a	(self							):
				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=lowercase       ,      initializer_range=self.initializer_range       ,      )


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase							):
				A_	:						List[Any]	=     BioGptModel(config=lowercase							)
				model.to(lowercase							)
				model.eval()
				A_	:						List[Any]	=     model(lowercase       ,      attention_mask=lowercase							)
				A_	:						str	=     model(lowercase							)
				self.parent.assertEqual(result.last_hidden_state.shape       ,      (self.batch_size, self.seq_length, self.hidden_size)							)


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      ):
				A_	:						List[Any]	=     BioGptForCausalLM(config=lowercase							)
				model.to(lowercase							)
				model.eval()
				A_	:						Dict	=     model(lowercase       ,      attention_mask=lowercase       ,      token_type_ids=lowercase       ,      labels=lowercase							)
				self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.seq_length, self.vocab_size)							)


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      *lowercase							):
				A_	:						Optional[Any]	=     BioGptModel(config=lowercase							)
				model.to(lowercase							)
				model.eval()

				# create attention mask
				A_	:						str	=     torch.ones(input_ids.shape       ,      dtype=torch.long       ,      device=lowercase							)
				A_	:						Optional[Any]	=     self.seq_length // 2
				A_	:						List[Any]	=     0

				# first forward pass
				A_,    A_	:						List[str]	=     model(lowercase       ,      attention_mask=lowercase							).to_tuple()

				# create hypothetical next token and extent to next_input_ids
				A_	:						Optional[Any]	=     ids_tensor((self.batch_size, 1)       ,      config.vocab_size							)

				# change a random masked slice from input_ids
				A_	:						Union[str, Any]	=     ids_tensor((1,)       ,      lowercase							).item() + 1
				A_	:						List[str]	=     ids_tensor((self.batch_size, 1)       ,      config.vocab_size							).squeeze(-1							)
				A_	:						Optional[int]	=     random_other_next_tokens

				# append to next input_ids and attn_mask
				A_	:						Union[str, Any]	=     torch.cat([input_ids, next_tokens]       ,      dim=-1							)
				A_	:						Any	=     torch.cat(
				    [attn_mask, torch.ones((attn_mask.shape[0], 1)       ,      dtype=torch.long       ,      device=lowercase							)]       ,      dim=1       ,      )

				# get two different outputs
				A_	:						List[Any]	=     model(lowercase       ,      attention_mask=lowercase							)["""last_hidden_state"""]
				A_	:						Optional[int]	=     model(lowercase       ,      past_key_values=lowercase       ,      attention_mask=lowercase							)["""last_hidden_state"""]

				# select random slice
				A_	:						List[str]	=     ids_tensor((1,)       ,      output_from_past.shape[-1]							).item()
				A_	:						int	=     output_from_no_past[:, -1, random_slice_idx].detach()
				A_	:						List[Any]	=     output_from_past[:, 0, random_slice_idx].detach()

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


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      *lowercase							):
				A_	:						Optional[int]	=     BioGptModel(config=lowercase							).to(lowercase							).eval()

				A_	:						Union[str, Any]	=     torch.ones(input_ids.shape       ,      dtype=torch.long       ,      device=lowercase							)

				# first forward pass
				A_	:						int	=     model(lowercase       ,      attention_mask=lowercase       ,      use_cache=lowercase							)

				A_,    A_	:						int	=     outputs.to_tuple()

				# create hypothetical multiple next token and extent to next_input_ids
				A_	:						Optional[int]	=     ids_tensor((self.batch_size, 3)       ,      config.vocab_size							)
				A_	:						str	=     ids_tensor((self.batch_size, 3)       ,      2							)

				# append to next input_ids and
				A_	:						Union[str, Any]	=     torch.cat([input_ids, next_tokens]       ,      dim=-1							)
				A_	:						int	=     torch.cat([attention_mask, next_attn_mask]       ,      dim=-1							)

				A_	:						List[str]	=     model(lowercase       ,      attention_mask=lowercase							)["""last_hidden_state"""]
				A_	:						Tuple	=     model(lowercase       ,      attention_mask=lowercase       ,      past_key_values=lowercase							)[
				    """last_hidden_state"""
				]

				# select random slice
				A_	:						List[str]	=     ids_tensor((1,)       ,      output_from_past.shape[-1]							).item()
				A_	:						List[str]	=     output_from_no_past[:, -3:, random_slice_idx].detach()
				A_	:						Any	=     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(lowercase       ,      lowercase       ,      atol=1E-3							)							)


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      *lowercase       ,      lowercase=False							):
				A_	:						Union[str, Any]	=     BioGptForCausalLM(lowercase							)
				model.to(lowercase							)
				if gradient_checkpointing:
							model.gradient_checkpointing_enable()

				A_	:						Dict	=     model(lowercase       ,      labels=lowercase							)
				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     _a	(self       ,      lowercase       ,      *lowercase							):
				A_	:						Union[str, Any]	=     BioGptModel(lowercase							)
				A_	:						str	=     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.0_01							)
										self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]							) - 0.0							)       ,      0.01							)


	def     _a	(self       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      lowercase       ,      *lowercase							):
				A_	:						Union[str, Any]	=     self.num_labels
				A_	:						Optional[int]	=     BioGptForTokenClassification(lowercase							)
				model.to(lowercase							)
				model.eval()
				A_	:						Dict	=     model(lowercase       ,      attention_mask=lowercase       ,      token_type_ids=lowercase							)
				self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.seq_length, self.num_labels)							)


	def     _a	(self							):
				A_	:						List[Any]	=     self.prepare_config_and_inputs()
				(
				    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    (
				    A_
				),    
				)	:						Dict	=     config_and_inputs
				A_	:						Tuple	=     {"""input_ids""": input_ids, """attention_mask""": input_mask}
				return config, inputs_dict







@require_torch
class 	_lowerCAmelCase							(			__UpperCAmelCase      ,			__UpperCAmelCase      ,			__UpperCAmelCase      ,			unittest.TestCase ):
	__SCREAMING_SNAKE_CASE   :		str					=					(
	    (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
	    if is_torch_available()
	    else ()
	)
	__SCREAMING_SNAKE_CASE   :		int					=					(BioGptForCausalLM,) if is_torch_available() else ()
	__SCREAMING_SNAKE_CASE   :		Optional[Any]					=					(
	    {
	        'feature-extraction': BioGptModel,
	        'text-classification': BioGptForSequenceClassification,
	        'text-generation': BioGptForCausalLM,
	        'token-classification': BioGptForTokenClassification,
	        'zero-shot': BioGptForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	__SCREAMING_SNAKE_CASE   :		List[str]					=					False


	def     _a	(self							):
				A_	:						Tuple	=     BioGptModelTester(self							)
				A_	:						List[Any]	=     ConfigTester(self       ,      config_class=lowercase       ,      hidden_size=37							)


	def     _a	(self							):
				self.config_tester.run_common_tests()


	def     _a	(self							):
				A_	:						Optional[Any]	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowercase							)


	def     _a	(self							):
				A_	:						Tuple	=     self.model_tester.prepare_config_and_inputs()
				for type in ["absolute", "relative_key", "relative_key_query"]:
							A_	:						int	=     type
							self.model_tester.create_and_check_model(*lowercase							)


	def     _a	(self							):
				A_	:						Union[str, Any]	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_biogpt_model_attention_mask_past(*lowercase							)


	def     _a	(self							):
				A_	:						Dict	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_forward_and_backwards(*lowercase       ,      gradient_checkpointing=lowercase							)


	def     _a	(self							):
				A_	:						Optional[int]	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_biogpt_model_past_large_inputs(*lowercase							)


	def     _a	(self							):
				A_	:						int	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_biogpt_weight_initialization(*lowercase							)


	def     _a	(self							):
				A_	:						List[str]	=     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_biogpt_for_token_classification(*lowercase							)


	@slow
	def     _a	(self							):
				A_	:						str	=     BioGptForCausalLM.from_pretrained("""microsoft/biogpt"""							)
				model.to(lowercase							)
				A_	:						List[str]	=     BioGptTokenizer.from_pretrained("""microsoft/biogpt"""							)

				A_	:						List[str]	=     """left"""

				# Define PAD Token = EOS Token = 50256
				A_	:						Any	=     tokenizer.eos_token
				A_	:						Dict	=     model.config.eos_token_id

				# use different length sentences to test batching
				A_	:						List[Any]	=     [
				    """Hello, my dog is a little""",
				    """Today, I""",
				]

				A_	:						List[str]	=     tokenizer(lowercase       ,      return_tensors="""pt"""       ,      padding=lowercase							)
				A_	:						List[str]	=     inputs["""input_ids"""].to(lowercase							)

				A_	:						List[Any]	=     model.generate(
				    input_ids=lowercase       ,      attention_mask=inputs["""attention_mask"""].to(lowercase							)       ,      )

				A_	:						List[str]	=     tokenizer(sentences[0]       ,      return_tensors="""pt"""							).input_ids.to(lowercase							)
				A_	:						List[Any]	=     model.generate(input_ids=lowercase							)

				A_	:						List[str]	=     inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item()
				A_	:						Union[str, Any]	=     tokenizer(sentences[1]       ,      return_tensors="""pt"""							).input_ids.to(lowercase							)
				A_	:						Any	=     model.generate(input_ids=lowercase       ,      max_length=model.config.max_length - num_paddings							)

				A_	:						List[str]	=     tokenizer.batch_decode(lowercase       ,      skip_special_tokens=lowercase							)
				A_	:						str	=     tokenizer.decode(output_non_padded[0]       ,      skip_special_tokens=lowercase							)
				A_	:						List[str]	=     tokenizer.decode(output_padded[0]       ,      skip_special_tokens=lowercase							)

				A_	:						Union[str, Any]	=     [
				    """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(lowercase       ,      lowercase							)
				self.assertListEqual(lowercase       ,      [non_padded_sentence, padded_sentence]							)


	@slow
	def     _a	(self							):
				for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A_	:						int	=     BioGptModel.from_pretrained(lowercase							)
							self.assertIsNotNone(lowercase							)


	def     _a	(self							):
				A_,    A_	:						Tuple	=     self.model_tester.prepare_config_and_inputs_for_common()
				A_	:						List[Any]	=     3
				A_	:						Union[str, Any]	=     input_dict["""input_ids"""]
				A_	:						List[Any]	=     input_ids.ne(1							).to(lowercase							)
				A_	:						str	=     ids_tensor([self.model_tester.batch_size]       ,      self.model_tester.type_sequence_label_size							)
				A_	:						Union[str, Any]	=     BioGptForSequenceClassification(lowercase							)
				model.to(lowercase							)
				model.eval()
				A_	:						Tuple	=     model(lowercase       ,      attention_mask=lowercase       ,      labels=lowercase							)
				self.assertEqual(result.logits.shape       ,      (self.model_tester.batch_size, self.model_tester.num_labels)							)


	def     _a	(self							):
				A_,    A_	:						Dict	=     self.model_tester.prepare_config_and_inputs_for_common()
				A_	:						Tuple	=     3
				A_	:						Dict	=     """multi_label_classification"""
				A_	:						List[Any]	=     input_dict["""input_ids"""]
				A_	:						Tuple	=     input_ids.ne(1							).to(lowercase							)
				A_	:						List[str]	=     ids_tensor(
				    [self.model_tester.batch_size, config.num_labels]       ,      self.model_tester.type_sequence_label_size							).to(torch.float							)
				A_	:						Dict	=     BioGptForSequenceClassification(lowercase							)
				model.to(lowercase							)
				model.eval()
				A_	:						int	=     model(lowercase       ,      attention_mask=lowercase       ,      labels=lowercase							)
				self.assertEqual(result.logits.shape       ,      (self.model_tester.batch_size, self.model_tester.num_labels)							)







@require_torch
class 	_lowerCAmelCase							(			unittest.TestCase ):


	@slow
	def     _a	(self							):
				A_	:						Dict	=     BioGptForCausalLM.from_pretrained("""microsoft/biogpt"""							)
				A_	:						Optional[Any]	=     torch.tensor([[2, 4805, 9, 656, 21]]							)
				A_	:						Dict	=     model(lowercase							)[0]

				A_	:						Any	=     42384

				A_	:						Union[str, Any]	=     torch.Size((1, 5, vocab_size)							)
				self.assertEqual(output.shape       ,      lowercase							)

				A_	:						Union[str, Any]	=     torch.tensor(
				    [[[-9.52_36, -9.89_18, 10.45_57], [-11.04_69, -9.64_23, 8.10_22], [-8.86_64, -7.88_26, 5.53_25]]]							)

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


	@slow
	def     _a	(self							):
				A_	:						Union[str, Any]	=     BioGptTokenizer.from_pretrained("""microsoft/biogpt"""							)
				A_	:						Dict	=     BioGptForCausalLM.from_pretrained("""microsoft/biogpt"""							)
				model.to(lowercase							)

				torch.manual_seed(0							)
				A_	:						Dict	=     tokenizer("""COVID-19 is"""       ,      return_tensors="""pt"""							).to(lowercase							)
				A_	:						Optional[int]	=     model.generate(
				    **lowercase       ,      min_length=100       ,      max_length=1024       ,      num_beams=5       ,      early_stopping=lowercase       ,      )
				A_	:						Union[str, Any]	=     tokenizer.decode(output_ids[0]       ,      skip_special_tokens=lowercase							)

				A_	:						Any	=     (
				    """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(lowercase       ,      lowercase							)