





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





       '''simple docstring'''







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




       def 							UpperCAmelCase__			(  self			:   Optional[int]		):
         __snake_case:						int			  =						ids_tensor([self.batch_size, self.seq_length]							,    self.vocab_size		)

         __snake_case:						int			  =						None
         if self.use_input_mask:
           __snake_case:						Dict			  =						random_attention_mask([self.batch_size, self.seq_length]		)

         if self.use_labels:
           __snake_case:						Optional[int]			  =						ids_tensor([self.batch_size, self.seq_length]							,    self.vocab_size		)

         __snake_case:						Tuple			  =						self.get_config()

         return config, input_ids, input_mask, token_labels




       def 							UpperCAmelCase__			(  self			:   List[str]		):
         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=A							,    initializer_range=self.initializer_range							,    )




       def 							UpperCAmelCase__			(  self			:   Dict		):
         (
             (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       
         ):						Optional[Any]			  =						self.prepare_config_and_inputs()

         __snake_case:						List[str]			  =						True
         __snake_case:						Optional[Any]			  =						floats_tensor([self.batch_size, self.seq_length, self.hidden_size]		)
         __snake_case:						List[Any]			  =						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 							UpperCAmelCase__			(  self			:   Any							,    A			:   Optional[int]							,    A			:   Union[str, Any]							,    A			:   Any							,    A			:   Tuple							,    **A			:   int							,    ):
         __snake_case:						Any			  =						BertGenerationEncoder(config=A		)
         model.to(A		)
         model.eval()
         __snake_case:						Tuple			  =						model(A							,    attention_mask=A		)
         __snake_case:						Any			  =						model(A		)
         self.parent.assertEqual(result.last_hidden_state.shape							,    (self.batch_size, self.seq_length, self.hidden_size)		)




       def 							UpperCAmelCase__			(  self			:   Any							,    A			:   Optional[Any]							,    A			:   List[Any]							,    A			:   List[str]							,    A			:   Optional[int]							,    A			:   List[str]							,    A			:   int							,    **A			:   Tuple							,    ):
         __snake_case:						List[Any]			  =						True
         __snake_case:						Tuple			  =						BertGenerationEncoder(config=A		)
         model.to(A		)
         model.eval()
         __snake_case:						List[Any]			  =						model(
             A							,    attention_mask=A							,    encoder_hidden_states=A							,    encoder_attention_mask=A							,    )
         __snake_case:						List[str]			  =						model(
             A							,    attention_mask=A							,    encoder_hidden_states=A							,    )
         self.parent.assertEqual(result.last_hidden_state.shape							,    (self.batch_size, self.seq_length, self.hidden_size)		)




       def 							UpperCAmelCase__			(  self			:   Any							,    A			:   Optional[int]							,    A			:   List[Any]							,    A			:   Tuple							,    A			:   int							,    A			:   int							,    A			:   Optional[int]							,    **A			:   int							,    ):
         __snake_case:						Dict			  =						True
         __snake_case:						int			  =						True
         __snake_case:						Tuple			  =						BertGenerationDecoder(config=A		).to(A		).eval()

         # first forward pass
         __snake_case:						List[str]			  =						model(
             A							,    attention_mask=A							,    encoder_hidden_states=A							,    encoder_attention_mask=A							,    use_cache=A							,    )
         __snake_case:						List[Any]			  =						outputs.past_key_values

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

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

         __snake_case:						List[str]			  =						model(
             A							,    attention_mask=A							,    encoder_hidden_states=A							,    encoder_attention_mask=A							,    output_hidden_states=A							,    )["""hidden_states"""][0]
         __snake_case:						Union[str, Any]			  =						model(
             A							,    attention_mask=A							,    encoder_hidden_states=A							,    encoder_attention_mask=A							,    past_key_values=A							,    output_hidden_states=A							,    )["""hidden_states"""][0]

         # select random slice
         __snake_case:						Dict			  =						ids_tensor((1,)							,    output_from_past.shape[-1]		).item()
         __snake_case:						int			  =						output_from_no_past[:, -3:, random_slice_idx].detach()
         __snake_case:						str			  =						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			:   Dict							,    A			:   List[Any]							,    A			:   Optional[int]							,    A			:   List[Any]							,    A			:   List[Any]							,    *A			:   Optional[Any]							,    ):
         __snake_case:						Optional[int]			  =						BertGenerationDecoder(A		)
         model.to(A		)
         model.eval()
         __snake_case:						Optional[Any]			  =						model(A							,    attention_mask=A							,    labels=A		)
         self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.seq_length, self.vocab_size)		)






       def 							UpperCAmelCase__			(  self			:   Dict		):
         __snake_case  ,       __snake_case  ,       __snake_case  ,       __snake_case:						Dict			  =						self.prepare_config_and_inputs()
         __snake_case:						int			  =						{"""input_ids""": input_ids, """attention_mask""": input_mask}
         return config, inputs_dict







@require_torch
class    __snake_case	(							__lowerCamelCase       ,      __lowerCamelCase       ,      __lowerCamelCase       ,      unittest.TestCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					(BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
       lowerCAmelCase__						=					(BertGenerationDecoder,) if is_torch_available() else ()
       lowerCAmelCase__						=					(
           {"""feature-extraction""": BertGenerationEncoder, """text-generation""": BertGenerationDecoder}
           if is_torch_available()
           else {}
       )




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						Tuple			  =						BertGenerationEncoderTester(self		)
         __snake_case:						Union[str, Any]			  =						ConfigTester(self							,    config_class=A							,    hidden_size=37		)




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         self.config_tester.run_common_tests()




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						str			  =						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*A		)




       def 							UpperCAmelCase__			(  self			:   Any		):
         __snake_case  ,       __snake_case  ,       __snake_case  ,       __snake_case:						List[Any]			  =						self.model_tester.prepare_config_and_inputs()
         __snake_case:						List[str]			  =						"""bert"""
         self.model_tester.create_and_check_model(A							,    A							,    A							,    A		)




       def 							UpperCAmelCase__			(  self			:   int		):
         __snake_case:						str			  =						self.model_tester.prepare_config_and_inputs_for_decoder()
         self.model_tester.create_and_check_model_as_decoder(*A		)




       def 							UpperCAmelCase__			(  self			:   Optional[Any]		):
         __snake_case:						Tuple			  =						self.model_tester.prepare_config_and_inputs_for_decoder()
         self.model_tester.create_and_check_decoder_model_past_large_inputs(*A		)




       def 							UpperCAmelCase__			(  self			:   Optional[int]		):
         # This regression test was failing with PyTorch < 1.3
         (
             (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       
         ):						Union[str, Any]			  =						self.model_tester.prepare_config_and_inputs_for_decoder()

         __snake_case:						Union[str, Any]			  =						None

         self.model_tester.create_and_check_model_as_decoder(
             A							,    A							,    A							,    A							,    A							,    A							,    )




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						Optional[Any]			  =						self.model_tester.prepare_config_and_inputs_for_decoder()
         self.model_tester.create_and_check_for_causal_lm(*A		)






       @slow
       def 							UpperCAmelCase__			(  self			:   Optional[int]		):
         __snake_case:						Union[str, Any]			  =						BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""		)
         self.assertIsNotNone(A		)







@require_torch
class    __snake_case	(							unittest.TestCase      ):





       '''simple docstring'''







       @slow
       def 							UpperCAmelCase__			(  self			:   Optional[int]		):
         __snake_case:						Optional[int]			  =						BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""		)
         __snake_case:						Dict			  =						torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]		)
         with torch.no_grad():
           __snake_case:						Tuple			  =						model(A		)[0]
         __snake_case:						Tuple			  =						torch.Size([1, 8, 1_024]		)
         self.assertEqual(output.shape							,    A		)
         __snake_case:						Tuple			  =						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]							,    A							,    atol=1E-4		)		)







@require_torch
class    __snake_case	(							unittest.TestCase      ):





       '''simple docstring'''







       @slow
       def 							UpperCAmelCase__			(  self			:   str		):
         __snake_case:						Optional[Any]			  =						BertGenerationDecoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder"""		)
         __snake_case:						int			  =						torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]]		)
         with torch.no_grad():
           __snake_case:						str			  =						model(A		)[0]
         __snake_case:						List[str]			  =						torch.Size([1, 8, 50_358]		)
         self.assertEqual(output.shape							,    A		)
         __snake_case:						Dict			  =						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]							,    A							,    atol=1E-4		)		)













import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCAmelCase	:       Optional[Any]    	=							logging.get_logger(__name__)

__UpperCAmelCase	:       Union[str, Any]    	=							{
    "asapp/sew-d-tiny-100k": "https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}







class    __snake_case	(							__lowerCamelCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					"""sew-d"""




       def __init__(  self			:   Dict							,    A			:   Any=32							,    A			:   Dict=768							,    A			:   Optional[Any]=12							,    A			:   Union[str, Any]=12							,    A			:   Union[str, Any]=3_072							,    A			:   Optional[Any]=2							,    A			:   Union[str, Any]=512							,    A			:   List[Any]=256							,    A			:   Dict=True							,    A			:   Union[str, Any]=True							,    A			:   Optional[int]=("p2c", "c2p")							,    A			:   str="layer_norm"							,    A			:   Dict="gelu_python"							,    A			:   Tuple=0.1							,    A			:   Any=0.1							,    A			:   Tuple=0.1							,    A			:   Optional[int]=0.0							,    A			:   Any=0.1							,    A			:   Any=0.02							,    A			:   Dict=1E-7							,    A			:   str=1E-5							,    A			:   int="group"							,    A			:   int="gelu"							,    A			:   str=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)							,    A			:   Union[str, Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)							,    A			:   List[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)							,    A			:   Optional[int]=False							,    A			:   int=128							,    A			:   int=16							,    A			:   Optional[Any]=True							,    A			:   List[Any]=0.05							,    A			:   Any=10							,    A			:   Dict=2							,    A			:   List[Any]=0.0							,    A			:   Union[str, Any]=10							,    A			:   int=0							,    A			:   List[Any]="mean"							,    A			:   Union[str, Any]=False							,    A			:   Any=False							,    A			:   Optional[int]=256							,    A			:   List[Any]=0							,    A			:   Any=1							,    A			:   List[Any]=2							,    **A			:   List[Any]							,    ):
         super().__init__(**A							,    pad_token_id=A							,    bos_token_id=A							,    eos_token_id=A		)
         __snake_case:						Optional[int]			  =						hidden_size
         __snake_case:						str			  =						feat_extract_norm
         __snake_case:						int			  =						feat_extract_activation
         __snake_case:						str			  =						list(A		)
         __snake_case:						Any			  =						list(A		)
         __snake_case:						str			  =						list(A		)
         __snake_case:						Union[str, Any]			  =						conv_bias
         __snake_case:						int			  =						num_conv_pos_embeddings
         __snake_case:						str			  =						num_conv_pos_embedding_groups
         __snake_case:						List[Any]			  =						len(self.conv_dim		)
         __snake_case:						List[str]			  =						num_hidden_layers
         __snake_case:						Union[str, Any]			  =						intermediate_size
         __snake_case:						Dict			  =						squeeze_factor
         __snake_case:						List[Any]			  =						max_position_embeddings
         __snake_case:						List[Any]			  =						position_buckets
         __snake_case:						List[str]			  =						share_att_key
         __snake_case:						int			  =						relative_attention
         __snake_case:						Union[str, Any]			  =						norm_rel_ebd
         __snake_case:						List[str]			  =						list(A		)
         __snake_case:						Tuple			  =						hidden_act
         __snake_case:						List[Any]			  =						num_attention_heads
         __snake_case:						str			  =						hidden_dropout
         __snake_case:						int			  =						attention_dropout
         __snake_case:						Dict			  =						activation_dropout
         __snake_case:						Any			  =						feat_proj_dropout
         __snake_case:						int			  =						final_dropout
         __snake_case:						List[Any]			  =						layer_norm_eps
         __snake_case:						List[str]			  =						feature_layer_norm_eps
         __snake_case:						List[Any]			  =						initializer_range
         __snake_case:						List[Any]			  =						vocab_size

         if (
             (len(self.conv_stride		) != self.num_feat_extract_layers)
             or (len(self.conv_kernel		) != self.num_feat_extract_layers)
             or (len(self.conv_dim		) != self.num_feat_extract_layers)
         ):
           raise ValueError(
               """Configuration for convolutional layers is incorrect."""
               """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
               f'''but is `len(config.conv_dim) = {len(self.conv_dim		)}`, `len(config.conv_stride)'''
               f'''= {len(self.conv_stride		)}`, `len(config.conv_kernel) = {len(self.conv_kernel		)}`.'''		)

         # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
         __snake_case:						List[Any]			  =						apply_spec_augment
         __snake_case:						List[Any]			  =						mask_time_prob
         __snake_case:						str			  =						mask_time_length
         __snake_case:						List[str]			  =						mask_time_min_masks
         __snake_case:						str			  =						mask_feature_prob
         __snake_case:						Optional[int]			  =						mask_feature_length
         __snake_case:						Dict			  =						mask_feature_min_masks

         # ctc loss
         __snake_case:						Any			  =						ctc_loss_reduction
         __snake_case:						str			  =						ctc_zero_infinity

         # sequence classification
         __snake_case:						Optional[Any]			  =						use_weighted_layer_sum
         __snake_case:						List[Any]			  =						classifier_proj_size






       @property
       def 							UpperCAmelCase__			(  self			:   int		):
         return functools.reduce(operator.mul							,    self.conv_stride							,    1		)






