


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						:		Union[str, Any]		, _SCREAMING_SNAKE_CASE						:		List[Any]		, _SCREAMING_SNAKE_CASE						:		Optional[int]=13		, _SCREAMING_SNAKE_CASE						:		Dict=7		, _SCREAMING_SNAKE_CASE						:		Optional[int]=True		, _SCREAMING_SNAKE_CASE						:		Tuple=True		, _SCREAMING_SNAKE_CASE						:		List[str]=99		, _SCREAMING_SNAKE_CASE						:		Dict=32		, _SCREAMING_SNAKE_CASE						:		Optional[Any]=5		, _SCREAMING_SNAKE_CASE						:		List[Any]=4		, _SCREAMING_SNAKE_CASE						:		List[str]=37		, _SCREAMING_SNAKE_CASE						:		List[Any]="gelu"		, _SCREAMING_SNAKE_CASE						:		Optional[int]=0.1		, _SCREAMING_SNAKE_CASE						:		Optional[int]=0.1		, _SCREAMING_SNAKE_CASE						:		Union[str, Any]=50		, _SCREAMING_SNAKE_CASE						:		Dict=0.02		, _SCREAMING_SNAKE_CASE						:		Optional[int]=True		, _SCREAMING_SNAKE_CASE						:		Any=None		, )->	Any:
			lowerCAmelCase__       :      str   					= parent
			lowerCAmelCase__       :      Tuple   					= batch_size
			lowerCAmelCase__       :      Optional[int]   					= seq_length
			lowerCAmelCase__       :      Union[str, Any]   					= is_training
			lowerCAmelCase__       :      Optional[Any]   					= use_input_mask
			lowerCAmelCase__       :      Optional[Any]   					= vocab_size
			lowerCAmelCase__       :      Tuple   					= hidden_size
			lowerCAmelCase__       :      Tuple   					= num_hidden_layers
			lowerCAmelCase__       :      Union[str, Any]   					= num_attention_heads
			lowerCAmelCase__       :      Optional[int]   					= intermediate_size
			lowerCAmelCase__       :      int   					= hidden_act
			lowerCAmelCase__       :      Any   					= hidden_dropout_prob
			lowerCAmelCase__       :      Any   					= attention_probs_dropout_prob
			lowerCAmelCase__       :      int   					= max_position_embeddings
			lowerCAmelCase__       :      Any   					= initializer_range
			lowerCAmelCase__       :      Tuple   					= use_labels
			lowerCAmelCase__       :      str   					= scope




	def 							UpperCAmelCase__( self						:		str		)->	Optional[Any]:
			lowerCAmelCase__       :      Union[str, Any]   					= ids_tensor([self.batch_size, self.seq_length]		, self.vocab_size		)

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

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

			lowerCAmelCase__       :      List[Any]   					= self.get_config()

			return config, input_ids, input_mask, token_labels




	def 							UpperCAmelCase__( self						:		int		)->	Dict:
			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=_SCREAMING_SNAKE_CASE		, initializer_range=self.initializer_range		, )




	def 							UpperCAmelCase__( self						:		Tuple		)->	Tuple:
			(
			    (
			    lowerCAmelCase__
			)					,     (
			    lowerCAmelCase__
			)					,     (
			    lowerCAmelCase__
			)					,     (
			    lowerCAmelCase__
			)					,     
			)       :      int   					= self.prepare_config_and_inputs()

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




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




	def 							UpperCAmelCase__( self						:		Any		, _SCREAMING_SNAKE_CASE						:		List[str]		, _SCREAMING_SNAKE_CASE						:		Optional[Any]		, _SCREAMING_SNAKE_CASE						:		Optional[int]		, _SCREAMING_SNAKE_CASE						:		str		, _SCREAMING_SNAKE_CASE						:		Optional[Any]		, _SCREAMING_SNAKE_CASE						:		int		, **_SCREAMING_SNAKE_CASE						:		List[Any]		, )->	Any:
			lowerCAmelCase__       :      Optional[int]   					= True
			lowerCAmelCase__       :      int   					= True
			lowerCAmelCase__       :      Dict   					= BertGenerationDecoder(config=_SCREAMING_SNAKE_CASE		).to(_SCREAMING_SNAKE_CASE		).eval()

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

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

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

			lowerCAmelCase__       :      Tuple   					= model(
			    _SCREAMING_SNAKE_CASE		, attention_mask=_SCREAMING_SNAKE_CASE		, encoder_hidden_states=_SCREAMING_SNAKE_CASE		, encoder_attention_mask=_SCREAMING_SNAKE_CASE		, output_hidden_states=_SCREAMING_SNAKE_CASE		, )['''hidden_states'''][0]
			lowerCAmelCase__       :      Optional[Any]   					= model(
			    _SCREAMING_SNAKE_CASE		, attention_mask=_SCREAMING_SNAKE_CASE		, encoder_hidden_states=_SCREAMING_SNAKE_CASE		, encoder_attention_mask=_SCREAMING_SNAKE_CASE		, past_key_values=_SCREAMING_SNAKE_CASE		, output_hidden_states=_SCREAMING_SNAKE_CASE		, )['''hidden_states'''][0]

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




	def 							UpperCAmelCase__( self						:		str		, _SCREAMING_SNAKE_CASE						:		List[Any]		, _SCREAMING_SNAKE_CASE						:		str		, _SCREAMING_SNAKE_CASE						:		Any		, _SCREAMING_SNAKE_CASE						:		Union[str, Any]		, *_SCREAMING_SNAKE_CASE						:		List[str]		, )->	int:
			lowerCAmelCase__       :      Tuple   					= BertGenerationDecoder(_SCREAMING_SNAKE_CASE		)
			model.to(_SCREAMING_SNAKE_CASE		)
			model.eval()
			lowerCAmelCase__       :      Optional[Any]   					= model(_SCREAMING_SNAKE_CASE		, attention_mask=_SCREAMING_SNAKE_CASE		, labels=_SCREAMING_SNAKE_CASE		)
			self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.seq_length, self.vocab_size)		)




	def 							UpperCAmelCase__( self						:		str		)->	str:
			lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__       :      int   					= self.prepare_config_and_inputs()
			lowerCAmelCase__       :      str   					= {'''input_ids''': input_ids, '''attention_mask''': input_mask}
			return config, inputs_dict





@require_torch
class  _a							(    _lowercase					,						_lowercase					,						_lowercase					,						unittest.TestCase):
	_a  :  str				   =							(BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
	_a  :  Tuple				   =							(BertGenerationDecoder,) if is_torch_available() else ()
	_a  :  int				   =							(
	    {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder}
	    if is_torch_available()
	    else {}
	)




	def 							UpperCAmelCase__( self						:		Union[str, Any]		)->	List[Any]:
			lowerCAmelCase__       :      Tuple   					= BertGenerationEncoderTester(self		)
			lowerCAmelCase__       :      Union[str, Any]   					= ConfigTester(self		, config_class=_SCREAMING_SNAKE_CASE		, hidden_size=37		)




	def 							UpperCAmelCase__( self						:		str		)->	Tuple:
			self.config_tester.run_common_tests()




	def 							UpperCAmelCase__( self						:		Optional[int]		)->	Optional[Any]:
			lowerCAmelCase__       :      Optional[Any]   					= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE		)




	def 							UpperCAmelCase__( self						:		int		)->	Optional[Any]:
			lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__       :      Optional[int]   					= self.model_tester.prepare_config_and_inputs()
			lowerCAmelCase__       :      Union[str, Any]   					= '''bert'''
			self.model_tester.create_and_check_model(_SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		)




	def 							UpperCAmelCase__( self						:		Optional[Any]		)->	str:
			lowerCAmelCase__       :      Any   					= self.model_tester.prepare_config_and_inputs_for_decoder()
			self.model_tester.create_and_check_model_as_decoder(*_SCREAMING_SNAKE_CASE		)




	def 							UpperCAmelCase__( self						:		Any		)->	Dict:
			lowerCAmelCase__       :      Optional[Any]   					= self.model_tester.prepare_config_and_inputs_for_decoder()
			self.model_tester.create_and_check_decoder_model_past_large_inputs(*_SCREAMING_SNAKE_CASE		)




	def 							UpperCAmelCase__( self						:		List[str]		)->	Any:
			# This regression test was failing with PyTorch < 1.3
			(
			    (
			    lowerCAmelCase__
			)					,     (
			    lowerCAmelCase__
			)					,     (
			    lowerCAmelCase__
			)					,     (
			    lowerCAmelCase__
			)					,     (
			    lowerCAmelCase__
			)					,     (
			    lowerCAmelCase__
			)					,     
			)       :      Union[str, Any]   					= self.model_tester.prepare_config_and_inputs_for_decoder()

			lowerCAmelCase__       :      str   					= None

			self.model_tester.create_and_check_model_as_decoder(
			    _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, _SCREAMING_SNAKE_CASE		, )




	def 							UpperCAmelCase__( self						:		Tuple		)->	Any:
			lowerCAmelCase__       :      int   					= self.model_tester.prepare_config_and_inputs_for_decoder()
			self.model_tester.create_and_check_for_causal_lm(*_SCREAMING_SNAKE_CASE		)




	@slow
	def 							UpperCAmelCase__( self						:		Tuple		)->	str:
			lowerCAmelCase__       :      List[str]   					= BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder'''		)
			self.assertIsNotNone(_SCREAMING_SNAKE_CASE		)





@require_torch
class  _a							(    unittest.TestCase):




	@slow
	def 							UpperCAmelCase__( self						:		List[Any]		)->	Optional[int]:
			lowerCAmelCase__       :      Optional[int]   					= BertGenerationEncoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder'''		)
			lowerCAmelCase__       :      str   					= torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]]		)
			with torch.no_grad():
					lowerCAmelCase__       :      Optional[int]   					= model(_SCREAMING_SNAKE_CASE		)[0]
			lowerCAmelCase__       :      int   					= torch.Size([1, 8, 1024]		)
			self.assertEqual(output.shape		, _SCREAMING_SNAKE_CASE		)
			lowerCAmelCase__       :      str   					= 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]		, _SCREAMING_SNAKE_CASE		, atol=1E-4		)		)





@require_torch
class  _a							(    unittest.TestCase):




	@slow
	def 							UpperCAmelCase__( self						:		Union[str, Any]		)->	str:
			lowerCAmelCase__       :      Union[str, Any]   					= BertGenerationDecoder.from_pretrained('''google/bert_for_seq_generation_L-24_bbc_encoder'''		)
			lowerCAmelCase__       :      List[Any]   					= torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]]		)
			with torch.no_grad():
					lowerCAmelCase__       :      int   					= model(_SCREAMING_SNAKE_CASE		)[0]
			lowerCAmelCase__       :      Optional[int]   					= torch.Size([1, 8, 5_0358]		)
			self.assertEqual(output.shape		, _SCREAMING_SNAKE_CASE		)
			lowerCAmelCase__       :      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]		, _SCREAMING_SNAKE_CASE		, atol=1E-4		)		)








from __future__ import annotations






def 					lowerCamelCase_   (	_a     ,       _a     ,       _a     ,       _a	):  # noqa: E741




		"""simple docstring"""






		while r - l > 1:
				lowerCAmelCase__       :      Any   					= (l + r) // 2
				if v[m] >= key:
						lowerCAmelCase__       :      int   					= m
				else:
						lowerCAmelCase__       :      Tuple   					= m  # noqa: E741
		return r






def 					lowerCamelCase_   (	_a	):




		"""simple docstring"""






		if len(_a	) == 0:
				return 0

		lowerCAmelCase__       :      Optional[int]   					= [0] * len(_a	)
		lowerCAmelCase__       :      List[Any]   					= 1

		lowerCAmelCase__       :      int   					= v[0]

		for i in range(1     ,       len(_a	)	):
				if v[i] < tail[0]:
						lowerCAmelCase__       :      str   					= v[i]
				elif v[i] > tail[length - 1]:
						lowerCAmelCase__       :      Any   					= v[i]
						length += 1
				else:
						lowerCAmelCase__       :      int   					= v[i]

		return length


if __name__ == "__main__":
		import doctest

		doctest.testmod()




