





'''simple docstring'''






import unittest

from transformers import BertGenerationConfig, 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, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import BertGenerationDecoder, BertGenerationEncoder


class   _lowercase						:


   def __init__( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase=13    ,   _UpperCAmelCase=7    ,   _UpperCAmelCase=True    ,   _UpperCAmelCase=True    ,   _UpperCAmelCase=99    ,   _UpperCAmelCase=32    ,   _UpperCAmelCase=5    ,   _UpperCAmelCase=4    ,   _UpperCAmelCase=37    ,   _UpperCAmelCase="gelu"    ,   _UpperCAmelCase=0.1    ,   _UpperCAmelCase=0.1    ,   _UpperCAmelCase=50    ,   _UpperCAmelCase=0.02    ,   _UpperCAmelCase=True    ,   _UpperCAmelCase=None    ,   ):
       A       :       Optional[int]							=						parent
       A       :       Any							=						batch_size
       A       :       Union[str, Any]							=						seq_length
       A       :       List[str]							=						is_training
       A       :       Any							=						use_input_mask
       A       :       Optional[Any]							=						vocab_size
       A       :       str							=						hidden_size
       A       :       Any							=						num_hidden_layers
       A       :       Optional[int]							=						num_attention_heads
       A       :       Tuple							=						intermediate_size
       A       :       int							=						hidden_act
       A       :       int							=						hidden_dropout_prob
       A       :       Any							=						attention_probs_dropout_prob
       A       :       Tuple							=						max_position_embeddings
       A       :       List[str]							=						initializer_range
       A       :       Tuple							=						use_labels
       A       :       int							=						scope


   def 					snake_case				( self					):
       A       :       Tuple							=						ids_tensor([self.batch_size, self.seq_length]    ,   self.vocab_size					)

       A       :       Any							=						None
       if self.use_input_mask:
           A       :       Tuple							=						random_attention_mask([self.batch_size, self.seq_length]					)

       if self.use_labels:
           A       :       str							=						ids_tensor([self.batch_size, self.seq_length]    ,   self.vocab_size					)

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

       return config, input_ids, input_mask, token_labels


   def 					snake_case				( self					):
       return BertGenerationConfig(
           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    ,   is_decoder=snake_case_    ,   initializer_range=self.initializer_range    ,   )


   def 					snake_case				( self					):
       (
           A					
       )       :       int							=						self.prepare_config_and_inputs()

       A       :       Union[str, Any]							=						True
       A       :       Dict							=						floats_tensor([self.batch_size, self.seq_length, self.hidden_size]					)
       A       :       List[str]							=						ids_tensor([self.batch_size, self.seq_length]    ,   vocab_size=2					)

       return (
           config,
           input_ids,
           input_mask,
           token_labels,
           encoder_hidden_states,
           encoder_attention_mask,
       )


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   **_UpperCAmelCase    ,   ):
       A       :       Tuple							=						BertGenerationEncoder(config=snake_case_					)
       model.to(snake_case_					)
       model.eval()
       A       :       int							=						model(snake_case_    ,   attention_mask=snake_case_					)
       A       :       List[Any]							=						model(snake_case_					)
       self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)					)


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   **_UpperCAmelCase    ,   ):
       A       :       Any							=						True
       A       :       int							=						BertGenerationEncoder(config=snake_case_					)
       model.to(snake_case_					)
       model.eval()
       A       :       int							=						model(
           snake_case_    ,   attention_mask=snake_case_    ,   encoder_hidden_states=snake_case_    ,   encoder_attention_mask=snake_case_    ,   )
       A       :       int							=						model(
           snake_case_    ,   attention_mask=snake_case_    ,   encoder_hidden_states=snake_case_    ,   )
       self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)					)


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   **_UpperCAmelCase    ,   ):
       A       :       Tuple							=						True
       A       :       Optional[Any]							=						True
       A       :       Optional[int]							=						BertGenerationDecoder(config=snake_case_					).to(snake_case_					).eval()

       # first forward pass
       A       :       Dict							=						model(
           snake_case_    ,   attention_mask=snake_case_    ,   encoder_hidden_states=snake_case_    ,   encoder_attention_mask=snake_case_    ,   use_cache=snake_case_    ,   )
       A       :       Dict							=						outputs.past_key_values

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

       # append to next input_ids and
       A       :       Optional[int]							=						torch.cat([input_ids, next_tokens]    ,   dim=-1					)
       A       :       List[Any]							=						torch.cat([input_mask, next_mask]    ,   dim=-1					)

       A       :       Optional[int]							=						model(
           snake_case_    ,   attention_mask=snake_case_    ,   encoder_hidden_states=snake_case_    ,   encoder_attention_mask=snake_case_    ,   output_hidden_states=snake_case_    ,   )["hidden_states"][0]
       A       :       Tuple							=						model(
           snake_case_    ,   attention_mask=snake_case_    ,   encoder_hidden_states=snake_case_    ,   encoder_attention_mask=snake_case_    ,   past_key_values=snake_case_    ,   output_hidden_states=snake_case_    ,   )["hidden_states"][0]

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


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   *_UpperCAmelCase    ,   ):
       A       :       List[str]							=						BertGenerationDecoder(snake_case_					)
       model.to(snake_case_					)
       model.eval()
       A       :       Dict							=						model(snake_case_    ,   attention_mask=snake_case_    ,   labels=snake_case_					)
       self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.seq_length, self.vocab_size)					)


   def 					snake_case				( self					):
       A       :       Optional[Any]							=						self.prepare_config_and_inputs()
       A       :       Tuple							=						{"input_ids": input_ids, "attention_mask": input_mask}
       return config, inputs_dict







@require_torch
class   _lowercase						(							_snake_case		,					_snake_case		,					_snake_case		,					unittest.TestCase				):
   _UpperCamelCase       		=   (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
   _UpperCamelCase       		=   (BertGenerationDecoder,) if is_torch_available() else ()
   _UpperCamelCase       		=   (
       {"""feature-extraction""": BertGenerationEncoder, """text-generation""": BertGenerationDecoder}
       if is_torch_available()
       else {}
   )


   def 					snake_case				( self					):
       A       :       Optional[Any]							=						BertGenerationEncoderTester(self					)
       A       :       Optional[int]							=						ConfigTester(self    ,   config_class=snake_case_    ,   hidden_size=37					)


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


   def 					snake_case				( self					):
       A       :       List[Any]							=						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*snake_case_					)


   def 					snake_case				( self					):
       A       :       Any							=						self.model_tester.prepare_config_and_inputs()
       A       :       Optional[Any]							=						"bert"
       self.model_tester.create_and_check_model(snake_case_    ,   snake_case_    ,   snake_case_    ,   snake_case_					)


   def 					snake_case				( self					):
       A       :       Optional[int]							=						self.model_tester.prepare_config_and_inputs_for_decoder()
       self.model_tester.create_and_check_model_as_decoder(*snake_case_					)


   def 					snake_case				( self					):
       A       :       List[Any]							=						self.model_tester.prepare_config_and_inputs_for_decoder()
       self.model_tester.create_and_check_decoder_model_past_large_inputs(*snake_case_					)


   def 					snake_case				( self					):
       # This regression test was failing with PyTorch < 1.3
       (
           A					
       )       :       Tuple							=						self.model_tester.prepare_config_and_inputs_for_decoder()

       A       :       List[str]							=						None

       self.model_tester.create_and_check_model_as_decoder(
           snake_case_    ,   snake_case_    ,   snake_case_    ,   snake_case_    ,   snake_case_    ,   snake_case_    ,   )


   def 					snake_case				( self					):
       A       :       Optional[Any]							=						self.model_tester.prepare_config_and_inputs_for_decoder()
       self.model_tester.create_and_check_for_causal_lm(*snake_case_					)


   @slow
   def 					snake_case				( self					):
       A       :       int							=						BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder'''					)
       self.assertIsNotNone(snake_case_					)







@require_torch
class   _lowercase						(							unittest.TestCase				):


   @slow
   def 					snake_case				( self					):
       A       :       str							=						BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder'''					)
       A       :       Optional[int]							=						torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]					)
       with torch.no_grad():
           A       :       int							=						model(snake_case_					)[0]
       A       :       str							=						torch.Size([1, 8, 1_024]					)
       self.assertEqual(output.shape    ,   snake_case_					)
       A       :       Optional[int]							=						torch.tensor(
           [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]]					)
       self.assertTrue(torch.allclose(output[:, :3, :3]    ,   snake_case_    ,   atol=1E-4					)					)







@require_torch
class   _lowercase						(							unittest.TestCase				):


   @slow
   def 					snake_case				( self					):
       A       :       List[Any]							=						BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder'''					)
       A       :       List[Any]							=						torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]					)
       with torch.no_grad():
           A       :       List[str]							=						model(snake_case_					)[0]
       A       :       str							=						torch.Size([1, 8, 50_358]					)
       self.assertEqual(output.shape    ,   snake_case_					)
       A       :       Optional[int]							=						torch.tensor(
           [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]]					)
       self.assertTrue(torch.allclose(output[:, :3, :3]    ,   snake_case_    ,   atol=1E-4					)					)







'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


snake_case_     =	{
    """configuration_biogpt""": ["""BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BioGptConfig"""],
    """tokenization_biogpt""": ["""BioGptTokenizer"""],
}

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     snake_case_     =	[
         """BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """BioGptForCausalLM""",
         """BioGptForTokenClassification""",
         """BioGptForSequenceClassification""",
         """BioGptModel""",
         """BioGptPreTrainedModel""",
     ]


if TYPE_CHECKING:
     from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig
     from .tokenization_biogpt import BioGptTokenizer

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_biogpt import (
              BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST,
              BioGptForCausalLM,
              BioGptForSequenceClassification,
              BioGptForTokenClassification,
              BioGptModel,
              BioGptPreTrainedModel,
          )


else:
     import sys

     snake_case_     =	_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
