




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

						def __init__(		self   :Optional[Any]    , __snake_case   :List[str]    , __snake_case   :Dict=13    , __snake_case   :Union[str, Any]=7    , __snake_case   :Tuple=True    , __snake_case   :int=True    , __snake_case   :Any=99    , __snake_case   :Dict=32    , __snake_case   :List[str]=5    , __snake_case   :str=4    , __snake_case   :Any=37    , __snake_case   :List[Any]="gelu"    , __snake_case   :Any=0.1    , __snake_case   :Dict=0.1    , __snake_case   :List[str]=50    , __snake_case   :Tuple=0.02    , __snake_case   :Optional[int]=True    , __snake_case   :List[Any]=None    , ):
										'''simple docstring'''

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

						def     A__						(		self   :Dict ):
										'''simple docstring'''

										__magic_name__	:	Optional[Any]								=ids_tensor([self.batch_size, self.seq_length]    , self.vocab_size )

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

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

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

										return config, input_ids, input_mask, token_labels

						def     A__						(		self   :List[str] ):
										'''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     A__						(		self   :str ):
										'''simple docstring'''

										(
										    __magic_name__ 
										)	:	List[Any]								=self.prepare_config_and_inputs()

										__magic_name__	:	str								=True
										__magic_name__	:	str								=floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
										__magic_name__	:	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     A__						(		self   :Optional[int]    , __snake_case   :str    , __snake_case   :str    , __snake_case   :Optional[Any]    , __snake_case   :Tuple    , **__snake_case   :List[Any]    , ):
										'''simple docstring'''

										__magic_name__	:	Optional[Any]								=BertGenerationEncoder(config=__snake_case )
										model.to(__snake_case )
										model.eval()
										__magic_name__	:	int								=model(__snake_case    , attention_mask=__snake_case )
										__magic_name__	:	Union[str, Any]								=model(__snake_case )
										self.parent.assertEqual(result.last_hidden_state.shape    , (self.batch_size, self.seq_length, self.hidden_size) )

						def     A__						(		self   :Any    , __snake_case   :Optional[int]    , __snake_case   :List[str]    , __snake_case   :Union[str, Any]    , __snake_case   :Any    , __snake_case   :str    , __snake_case   :Dict    , **__snake_case   :Optional[int]    , ):
										'''simple docstring'''

										__magic_name__	:	Tuple								=True
										__magic_name__	:	Union[str, Any]								=BertGenerationEncoder(config=__snake_case )
										model.to(__snake_case )
										model.eval()
										__magic_name__	:	Any								=model(
										    __snake_case    , attention_mask=__snake_case    , encoder_hidden_states=__snake_case    , encoder_attention_mask=__snake_case    , )
										__magic_name__	:	List[str]								=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     A__						(		self   :Optional[int]    , __snake_case   :List[str]    , __snake_case   :Optional[int]    , __snake_case   :int    , __snake_case   :int    , __snake_case   :int    , __snake_case   :Union[str, Any]    , **__snake_case   :List[str]    , ):
										'''simple docstring'''

										__magic_name__	:	Tuple								=True
										__magic_name__	:	int								=True
										__magic_name__	:	Any								=BertGenerationDecoder(config=__snake_case ).to(__snake_case ).eval()

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

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

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

										__magic_name__	:	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]
										__magic_name__	:	Dict								=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
										__magic_name__	:	Optional[Any]								=ids_tensor((1,)    , output_from_past.shape[-1] ).item()
										__magic_name__	:	Optional[Any]								=output_from_no_past[:, -3:, random_slice_idx].detach()
										__magic_name__	:	List[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(__snake_case    , __snake_case    , atol=1E-3 ) )

						def     A__						(		self   :List[str]    , __snake_case   :Optional[int]    , __snake_case   :Dict    , __snake_case   :Any    , __snake_case   :List[str]    , *__snake_case   :Dict    , ):
										'''simple docstring'''

										__magic_name__	:	Tuple								=BertGenerationDecoder(__snake_case )
										model.to(__snake_case )
										model.eval()
										__magic_name__	:	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     A__						(		self   :Any ):
										'''simple docstring'''

										__magic_name__	:	Tuple								=self.prepare_config_and_inputs()
										__magic_name__	:	Optional[int]								={"""input_ids""": input_ids, """attention_mask""": input_mask}
										return config, inputs_dict




@require_torch
class 		__A      (			UpperCamelCase__					,						UpperCamelCase__					,						UpperCamelCase__					,						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     A__						(		self   :Tuple ):
										'''simple docstring'''

										__magic_name__	:	int								=BertGenerationEncoderTester(self )
										__magic_name__	:	List[str]								=ConfigTester(self    , config_class=__snake_case    , hidden_size=37 )

						def     A__						(		self   :Any ):
										'''simple docstring'''

										self.config_tester.run_common_tests()

						def     A__						(		self   :Optional[int] ):
										'''simple docstring'''

										__magic_name__	:	List[str]								=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__snake_case )

						def     A__						(		self   :Optional[Any] ):
										'''simple docstring'''

										__magic_name__	:	str								=self.model_tester.prepare_config_and_inputs()
										__magic_name__	:	str								="""bert"""
										self.model_tester.create_and_check_model(__snake_case    , __snake_case    , __snake_case    , __snake_case )

						def     A__						(		self   :Union[str, Any] ):
										'''simple docstring'''

										__magic_name__	:	List[Any]								=self.model_tester.prepare_config_and_inputs_for_decoder()
										self.model_tester.create_and_check_model_as_decoder(*__snake_case )

						def     A__						(		self   :Optional[int] ):
										'''simple docstring'''

										__magic_name__	:	str								=self.model_tester.prepare_config_and_inputs_for_decoder()
										self.model_tester.create_and_check_decoder_model_past_large_inputs(*__snake_case )

						def     A__						(		self   :Any ):
										'''simple docstring'''

										(
										    __magic_name__ 
										)	:	Union[str, Any]								=self.model_tester.prepare_config_and_inputs_for_decoder()

										__magic_name__	:	str								=None

										self.model_tester.create_and_check_model_as_decoder(
										    __snake_case    , __snake_case    , __snake_case    , __snake_case    , __snake_case    , __snake_case    , )

						def     A__						(		self   :Dict ):
										'''simple docstring'''

										__magic_name__	:	Union[str, Any]								=self.model_tester.prepare_config_and_inputs_for_decoder()
										self.model_tester.create_and_check_for_causal_lm(*__snake_case )


						@slow
						def     A__						(		self   :Union[str, Any] ):
										'''simple docstring'''

										__magic_name__	:	Tuple								=BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" )
										self.assertIsNotNone(__snake_case )




@require_torch
class 		__A      (			unittest.TestCase			):

						@slow
						def     A__						(		self   :List[Any] ):
										'''simple docstring'''

										__magic_name__	:	int								=BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" )
										__magic_name__	:	List[str]								=torch.tensor([[1_01, 75_92, 10_10, 20_26, 38_99, 20_03, 1_01_40, 1_02]] )
										with torch.no_grad():
														__magic_name__	:	Any								=model(__snake_case )[0]
										__magic_name__	:	Optional[int]								=torch.Size([1, 8, 10_24] )
										self.assertEqual(output.shape    , __snake_case )
										__magic_name__	:	List[Any]								=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 		__A      (			unittest.TestCase			):

						@slow
						def     A__						(		self   :List[str] ):
										'''simple docstring'''

										__magic_name__	:	Any								=BertGenerationDecoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" )
										__magic_name__	:	int								=torch.tensor([[1_01, 75_92, 10_10, 20_26, 38_99, 20_03, 1_01_40, 1_02]] )
										with torch.no_grad():
														__magic_name__	:	int								=model(__snake_case )[0]
										__magic_name__	:	Tuple								=torch.Size([1, 8, 5_03_58] )
										self.assertEqual(output.shape    , __snake_case )
										__magic_name__	:	str								=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 ) )










import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin




class 		__A      (			UpperCamelCase__			):
						UpperCamelCase     						=					"""Speech2TextFeatureExtractor"""
						UpperCamelCase     						=					"""Speech2TextTokenizer"""

						def __init__(		self   :Any    , __snake_case   :int    , __snake_case   :Any ):
										'''simple docstring'''

										super().__init__(__snake_case    , __snake_case )
										__magic_name__	:	Optional[int]								=self.feature_extractor
										__magic_name__	:	Any								=False

						def __call__(		self   :Tuple    , *__snake_case   :List[str]    , **__snake_case   :List[str] ):
										'''simple docstring'''

										if self._in_target_context_manager:
														return self.current_processor(*__snake_case    , **__snake_case )

										if "raw_speech" in kwargs:
														warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" )
														__magic_name__	:	Tuple								=kwargs.pop("""raw_speech""" )
										else:
														__magic_name__	:	List[Any]								=kwargs.pop("""audio"""    , __snake_case )
										__magic_name__	:	Union[str, Any]								=kwargs.pop("""sampling_rate"""    , __snake_case )
										__magic_name__	:	Dict								=kwargs.pop("""text"""    , __snake_case )
										if len(__snake_case ) > 0:
														__magic_name__	:	Union[str, Any]								=args[0]
														__magic_name__	:	int								=args[1:]

										if audio is None and text is None:
														raise ValueError("""You need to specify either an `audio` or `text` input to process.""" )

										if audio is not None:
														__magic_name__	:	List[str]								=self.feature_extractor(__snake_case    , *__snake_case    , sampling_rate=__snake_case    , **__snake_case )
										if text is not None:
														__magic_name__	:	Any								=self.tokenizer(__snake_case    , **__snake_case )

										if text is None:
														return inputs
										elif audio is None:
														return encodings
										else:
														__magic_name__	:	List[str]								=encodings["""input_ids"""]
														return inputs

						def     A__						(		self   :List[Any]    , *__snake_case   :str    , **__snake_case   :List[str] ):
										'''simple docstring'''

										return self.tokenizer.batch_decode(*__snake_case    , **__snake_case )

						def     A__						(		self   :int    , *__snake_case   :int    , **__snake_case   :Optional[int] ):
										'''simple docstring'''

										return self.tokenizer.decode(*__snake_case    , **__snake_case )


						@contextmanager
						def     A__						(		self   :int ):
										'''simple docstring'''

										warnings.warn(
										    """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
										    """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
										    """your audio inputs, or in a separate call.""" )
										__magic_name__	:	int								=True
										__magic_name__	:	List[Any]								=self.tokenizer
										yield
										__magic_name__	:	List[Any]								=self.feature_extractor
										__magic_name__	:	str								=False




