





"""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  _UpperCAmelCase  :



      '''simple docstring'''

      def __init__(     self					,      snake_case_					,      snake_case_=1_3					,      snake_case_=7					,      snake_case_=True					,      snake_case_=True					,      snake_case_=9_9					,      snake_case_=3_2					,      snake_case_=5					,      snake_case_=4					,      snake_case_=3_7					,      snake_case_="gelu"					,      snake_case_=0.1					,      snake_case_=0.1					,      snake_case_=5_0					,      snake_case_=0.02					,      snake_case_=True					,      snake_case_=None					,      ):

        """simple docstring"""

        A_  :       List[Any]										=  parent
        A_  :       Dict										=  batch_size
        A_  :       Union[str, Any]										=  seq_length
        A_  :       Union[str, Any]										=  is_training
        A_  :       int										=  use_input_mask
        A_  :       Dict										=  vocab_size
        A_  :       Tuple										=  hidden_size
        A_  :       List[str]										=  num_hidden_layers
        A_  :       Any										=  num_attention_heads
        A_  :       Optional[int]										=  intermediate_size
        A_  :       Optional[int]										=  hidden_act
        A_  :       int										=  hidden_dropout_prob
        A_  :       str										=  attention_probs_dropout_prob
        A_  :       Union[str, Any]										=  max_position_embeddings
        A_  :       List[str]										=  initializer_range
        A_  :       str										=  use_labels
        A_  :       Optional[int]										=  scope

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       str										=  ids_tensor([self.batch_size, self.seq_length]					,      self.vocab_size  )

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

        if self.use_labels:
          A_  :       Any										=  ids_tensor([self.batch_size, self.seq_length]					,      self.vocab_size  )

        A_  :       str										=  self.get_config()

        return config, input_ids, input_mask, token_labels

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        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 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        (
            (
            A_
        )						,       (
            A_
        )						,       (
            A_
        )						,       (
            A_
        )						,       
        )  :       Optional[Any]										=  self.prepare_config_and_inputs()

        A_  :       Any										=  True
        A_  :       Dict										=  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]  )
        A_  :       Tuple										=  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 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      **snake_case_					,      ):

        """simple docstring"""

        A_  :       Dict										=  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 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      **snake_case_					,      ):

        """simple docstring"""

        A_  :       Optional[int]										=  True
        A_  :       List[str]										=  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 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      **snake_case_					,      ):

        """simple docstring"""

        A_  :       str										=  True
        A_  :       List[Any]										=  True
        A_  :       Any										=  BertGenerationDecoder(config=snake_case_  ).to(snake_case_  ).eval()

        # first forward pass
        A_  :       Optional[Any]										=  model(
            snake_case_					,      attention_mask=snake_case_					,      encoder_hidden_states=snake_case_					,      encoder_attention_mask=snake_case_					,      use_cache=snake_case_					,      )
        A_  :       Optional[int]										=  outputs.past_key_values

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

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

        A_  :       Union[str, Any]										=  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_  :       Optional[Any]										=  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_  :       int										=  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 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      *snake_case_					,      ):

        """simple docstring"""

        A_  :       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 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_						,       A_						,       A_						,       A_  :       Union[str, Any]										=  self.prepare_config_and_inputs()
        A_  :       str										=  {'input_ids': input_ids, 'attention_mask': input_mask}
        return config, inputs_dict


@require_torch
class  _UpperCAmelCase  (   UpperCAmelCase__			,   UpperCAmelCase__			,   UpperCAmelCase__			,   unittest.TestCase		):



      '''simple docstring'''
      lowercase_      : List[str]	    =   (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
      lowercase_      : str	    =   (BertGenerationDecoder,) if is_torch_available() else ()
      lowercase_      : Any	    =   (
          {"""feature-extraction""": BertGenerationEncoder, """text-generation""": BertGenerationDecoder}
          if is_torch_available()
          else {}
      )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Any										=  BertGenerationEncoderTester(self  )
        A_  :       int										=  ConfigTester(self					,      config_class=snake_case_					,      hidden_size=3_7  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        self.config_tester.run_common_tests()

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       List[Any]										=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*snake_case_  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_						,       A_						,       A_						,       A_  :       Dict										=  self.model_tester.prepare_config_and_inputs()
        A_  :       Any										=  'bert'
        self.model_tester.create_and_check_model(snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Union[str, Any]										=  self.model_tester.prepare_config_and_inputs_for_decoder()
        self.model_tester.create_and_check_model_as_decoder(*snake_case_  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        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 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        (
            (
            A_
        )						,       (
            A_
        )						,       (
            A_
        )						,       (
            A_
        )						,       (
            A_
        )						,       (
            A_
        )						,       
        )  :       str										=  self.model_tester.prepare_config_and_inputs_for_decoder()

        A_  :       str										=  None

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

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       int										=  self.model_tester.prepare_config_and_inputs_for_decoder()
        self.model_tester.create_and_check_for_causal_lm(*snake_case_  )

      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Tuple										=  BertGenerationEncoder.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder'  )
        self.assertIsNotNone(snake_case_  )


@require_torch
class  _UpperCAmelCase  (   unittest.TestCase		):



      '''simple docstring'''

      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Optional[int]										=  BertGenerationEncoder.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder'  )
        A_  :       Tuple										=  torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]]  )
        with torch.no_grad():
          A_  :       Any										=  model(snake_case_  )[0]
        A_  :       str										=  torch.Size([1, 8, 1_0_2_4]  )
        self.assertEqual(output.shape					,      snake_case_  )
        A_  :       Dict										=  torch.tensor(
            [[[0.17_75, 0.00_83, -0.03_21], [1.60_02, 0.12_87, 0.39_12], [2.14_73, 0.57_91, 0.60_66]]]  )
        self.assertTrue(torch.allclose(output[:, :3, :3]					,      snake_case_					,      atol=1E-4  )  )


@require_torch
class  _UpperCAmelCase  (   unittest.TestCase		):



      '''simple docstring'''

      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Union[str, Any]										=  BertGenerationDecoder.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder'  )
        A_  :       Any										=  torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]]  )
        with torch.no_grad():
          A_  :       Any										=  model(snake_case_  )[0]
        A_  :       int										=  torch.Size([1, 8, 5_0_3_5_8]  )
        self.assertEqual(output.shape					,      snake_case_  )
        A_  :       int										=  torch.tensor(
            [[[-0.57_88, -2.59_94, -3.70_54], [0.04_38, 4.79_97, 1.87_95], [1.58_62, 6.64_09, 4.46_38]]]  )
        self.assertTrue(torch.allclose(output[:, :3, :3]					,      snake_case_					,      atol=1E-4  )  )






"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_     :						str						=					logging.get_logger(__name__)

lowerCamelCase_     :						Any						=					{
    'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json',
    'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json',
    'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json',
    'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json',
    'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json',
    'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json',
    'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json',
    'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json',
    'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json',
}

class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_      : Tuple	    =   """xmod"""

      def __init__(     self					,      snake_case_=3_0_5_2_2					,      snake_case_=7_6_8					,      snake_case_=1_2					,      snake_case_=1_2					,      snake_case_=3_0_7_2					,      snake_case_="gelu"					,      snake_case_=0.1					,      snake_case_=0.1					,      snake_case_=5_1_2					,      snake_case_=2					,      snake_case_=0.02					,      snake_case_=1E-12					,      snake_case_=1					,      snake_case_=0					,      snake_case_=2					,      snake_case_="absolute"					,      snake_case_=True					,      snake_case_=None					,      snake_case_=False					,      snake_case_=2					,      snake_case_=False					,      snake_case_=True					,      snake_case_=True					,      snake_case_=("en_XX",)					,      snake_case_=None					,      **snake_case_					,      ):

        """simple docstring"""

        super().__init__(pad_token_id=snake_case_					,      bos_token_id=snake_case_					,      eos_token_id=snake_case_					,      **snake_case_  )

        A_  :       Union[str, Any]										=  vocab_size
        A_  :       Any										=  hidden_size
        A_  :       List[str]										=  num_hidden_layers
        A_  :       Tuple										=  num_attention_heads
        A_  :       int										=  hidden_act
        A_  :       Any										=  intermediate_size
        A_  :       Any										=  hidden_dropout_prob
        A_  :       Dict										=  attention_probs_dropout_prob
        A_  :       Union[str, Any]										=  max_position_embeddings
        A_  :       List[Any]										=  type_vocab_size
        A_  :       List[str]										=  initializer_range
        A_  :       Any										=  layer_norm_eps
        A_  :       Optional[Any]										=  position_embedding_type
        A_  :       int										=  use_cache
        A_  :       Dict										=  classifier_dropout
        A_  :       int										=  pre_norm
        A_  :       Optional[Any]										=  adapter_reduction_factor
        A_  :       List[Any]										=  adapter_layer_norm
        A_  :       int										=  adapter_reuse_layer_norm
        A_  :       Dict										=  ln_before_adapter
        A_  :       List[str]										=  list(snake_case_  )
        A_  :       Union[str, Any]										=  default_language


class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''

      @property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        if self.task == "multiple-choice":
          A_  :       Dict										=  {0: 'batch', 1: 'choice', 2: 'sequence'}
        else:
          A_  :       int										=  {0: 'batch', 1: 'sequence'}
        return OrderedDict(
            [
                ('input_ids', dynamic_axis),
                ('attention_mask', dynamic_axis),
            ]  )