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				:   List[str]		,							_UpperCamelCase				:   Union[str, Any]		,							_UpperCamelCase				:   Tuple=13		,							_UpperCamelCase				:   int=7		,							_UpperCamelCase				:   Optional[Any]=True		,							_UpperCamelCase				:   Any=True		,							_UpperCamelCase				:   Dict=99		,							_UpperCamelCase				:   Union[str, Any]=32		,							_UpperCamelCase				:   List[str]=5		,							_UpperCamelCase				:   int=4		,							_UpperCamelCase				:   List[Any]=37		,							_UpperCamelCase				:   Tuple="gelu"		,							_UpperCamelCase				:   Optional[Any]=0.1		,							_UpperCamelCase				:   Union[str, Any]=0.1		,							_UpperCamelCase				:   List[str]=50		,							_UpperCamelCase				:   Tuple=0.0_2		,							_UpperCamelCase				:   List[Any]=True		,							_UpperCamelCase				:   List[str]=None		,							)   ->			Any:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    parent
												SCREAMING_SNAKE_CASE           =    batch_size
												SCREAMING_SNAKE_CASE           =    seq_length
												SCREAMING_SNAKE_CASE           =    is_training
												SCREAMING_SNAKE_CASE           =    use_input_mask
												SCREAMING_SNAKE_CASE           =    vocab_size
												SCREAMING_SNAKE_CASE           =    hidden_size
												SCREAMING_SNAKE_CASE           =    num_hidden_layers
												SCREAMING_SNAKE_CASE           =    num_attention_heads
												SCREAMING_SNAKE_CASE           =    intermediate_size
												SCREAMING_SNAKE_CASE           =    hidden_act
												SCREAMING_SNAKE_CASE           =    hidden_dropout_prob
												SCREAMING_SNAKE_CASE           =    attention_probs_dropout_prob
												SCREAMING_SNAKE_CASE           =    max_position_embeddings
												SCREAMING_SNAKE_CASE           =    initializer_range
												SCREAMING_SNAKE_CASE           =    use_labels
												SCREAMING_SNAKE_CASE           =    scope




							def 		__snake_case(  self				:   Tuple )   ->			List[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    ids_tensor([self.batch_size, self.seq_length]		,							self.vocab_size )

												SCREAMING_SNAKE_CASE           =    None
												if self.use_input_mask:
																	SCREAMING_SNAKE_CASE           =    random_attention_mask([self.batch_size, self.seq_length] )

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

												SCREAMING_SNAKE_CASE           =    self.get_config()

												return config, input_ids, input_mask, token_labels




							def 		__snake_case(  self				:   List[Any] )   ->			Any:



												'''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=_UpperCamelCase		,							initializer_range=self.initializer_range		,							)




							def 		__snake_case(  self				:   Tuple )   ->			Dict:



												'''simple docstring'''

												(
												    (
												    SCREAMING_SNAKE_CASE
												)     ,				(
												    SCREAMING_SNAKE_CASE
												)     ,				(
												    SCREAMING_SNAKE_CASE
												)     ,				(
												    SCREAMING_SNAKE_CASE
												)     ,				
												)           =    self.prepare_config_and_inputs()

												SCREAMING_SNAKE_CASE           =    True
												SCREAMING_SNAKE_CASE           =    floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
												SCREAMING_SNAKE_CASE           =    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				:   int		,							_UpperCamelCase				:   int		,							_UpperCamelCase				:   List[str]		,							_UpperCamelCase				:   str		,							_UpperCamelCase				:   Optional[Any]		,							**_UpperCamelCase				:   List[Any]		,							)   ->			List[str]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    BertGenerationEncoder(config=_UpperCamelCase )
												model.to(_UpperCamelCase )
												model.eval()
												SCREAMING_SNAKE_CASE           =    model(_UpperCamelCase		,							attention_mask=_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    model(_UpperCamelCase )
												self.parent.assertEqual(result.last_hidden_state.shape		,							(self.batch_size, self.seq_length, self.hidden_size) )




							def 		__snake_case(  self				:   Any		,							_UpperCamelCase				:   Dict		,							_UpperCamelCase				:   str		,							_UpperCamelCase				:   List[Any]		,							_UpperCamelCase				:   Tuple		,							_UpperCamelCase				:   Optional[Any]		,							_UpperCamelCase				:   List[str]		,							**_UpperCamelCase				:   str		,							)   ->			List[str]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    True
												SCREAMING_SNAKE_CASE           =    BertGenerationEncoder(config=_UpperCamelCase )
												model.to(_UpperCamelCase )
												model.eval()
												SCREAMING_SNAKE_CASE           =    model(
												    _UpperCamelCase		,							attention_mask=_UpperCamelCase		,							encoder_hidden_states=_UpperCamelCase		,							encoder_attention_mask=_UpperCamelCase		,							)
												SCREAMING_SNAKE_CASE           =    model(
												    _UpperCamelCase		,							attention_mask=_UpperCamelCase		,							encoder_hidden_states=_UpperCamelCase		,							)
												self.parent.assertEqual(result.last_hidden_state.shape		,							(self.batch_size, self.seq_length, self.hidden_size) )




							def 		__snake_case(  self				:   int		,							_UpperCamelCase				:   int		,							_UpperCamelCase				:   str		,							_UpperCamelCase				:   Optional[int]		,							_UpperCamelCase				:   Optional[Any]		,							_UpperCamelCase				:   str		,							_UpperCamelCase				:   Optional[Any]		,							**_UpperCamelCase				:   Dict		,							)   ->			Union[str, Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    True
												SCREAMING_SNAKE_CASE           =    True
												SCREAMING_SNAKE_CASE           =    BertGenerationDecoder(config=_UpperCamelCase ).to(_UpperCamelCase ).eval()

												# first forward pass
												SCREAMING_SNAKE_CASE           =    model(
												    _UpperCamelCase		,							attention_mask=_UpperCamelCase		,							encoder_hidden_states=_UpperCamelCase		,							encoder_attention_mask=_UpperCamelCase		,							use_cache=_UpperCamelCase		,							)
												SCREAMING_SNAKE_CASE           =    outputs.past_key_values

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

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

												SCREAMING_SNAKE_CASE           =    model(
												    _UpperCamelCase		,							attention_mask=_UpperCamelCase		,							encoder_hidden_states=_UpperCamelCase		,							encoder_attention_mask=_UpperCamelCase		,							output_hidden_states=_UpperCamelCase		,							)["hidden_states"][0]
												SCREAMING_SNAKE_CASE           =    model(
												    _UpperCamelCase		,							attention_mask=_UpperCamelCase		,							encoder_hidden_states=_UpperCamelCase		,							encoder_attention_mask=_UpperCamelCase		,							past_key_values=_UpperCamelCase		,							output_hidden_states=_UpperCamelCase		,							)["hidden_states"][0]

												# select random slice
												SCREAMING_SNAKE_CASE           =    ids_tensor((1,)		,							output_from_past.shape[-1] ).item()
												SCREAMING_SNAKE_CASE           =    output_from_no_past[:, -3:, random_slice_idx].detach()
												SCREAMING_SNAKE_CASE           =    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(_UpperCamelCase		,							_UpperCamelCase		,							atol=1e-3 ) )




							def 		__snake_case(  self				:   Optional[int]		,							_UpperCamelCase				:   Optional[int]		,							_UpperCamelCase				:   Tuple		,							_UpperCamelCase				:   Union[str, Any]		,							_UpperCamelCase				:   Any		,							*_UpperCamelCase				:   Tuple		,							)   ->			List[str]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    BertGenerationDecoder(_UpperCamelCase )
												model.to(_UpperCamelCase )
												model.eval()
												SCREAMING_SNAKE_CASE           =    model(_UpperCamelCase		,							attention_mask=_UpperCamelCase		,							labels=_UpperCamelCase )
												self.parent.assertEqual(result.logits.shape		,							(self.batch_size, self.seq_length, self.vocab_size) )





							def 		__snake_case(  self				:   List[Any] )   ->			List[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE     ,				SCREAMING_SNAKE_CASE     ,				SCREAMING_SNAKE_CASE     ,				SCREAMING_SNAKE_CASE           =    self.prepare_config_and_inputs()
												SCREAMING_SNAKE_CASE           =    {"input_ids": input_ids, "attention_mask": input_mask}
												return config, inputs_dict



@require_torch
class   lowercase      (       a			,    a			,    a			,    unittest.TestCase       ):
							lowercase__  :    str									=							(BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
							lowercase__  :    List[str]									=							(BertGenerationDecoder,) if is_torch_available() else ()
							lowercase__  :    Optional[int]									=							(
							    {"""feature-extraction""": BertGenerationEncoder, """text-generation""": BertGenerationDecoder}
							    if is_torch_available()
							    else {}
							)




							def 		__snake_case(  self				:   str )   ->			Tuple:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    BertGenerationEncoderTester(self )
												SCREAMING_SNAKE_CASE           =    ConfigTester(self		,							config_class=_UpperCamelCase		,							hidden_size=37 )




							def 		__snake_case(  self				:   Dict )   ->			Union[str, Any]:



												'''simple docstring'''

												self.config_tester.run_common_tests()




							def 		__snake_case(  self				:   Dict )   ->			Optional[int]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_UpperCamelCase )




							def 		__snake_case(  self				:   Union[str, Any] )   ->			Tuple:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE     ,				SCREAMING_SNAKE_CASE     ,				SCREAMING_SNAKE_CASE     ,				SCREAMING_SNAKE_CASE           =    self.model_tester.prepare_config_and_inputs()
												SCREAMING_SNAKE_CASE           =    "bert"
												self.model_tester.create_and_check_model(_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase )




							def 		__snake_case(  self				:   Optional[Any] )   ->			str:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    self.model_tester.prepare_config_and_inputs_for_decoder()
												self.model_tester.create_and_check_model_as_decoder(*_UpperCamelCase )




							def 		__snake_case(  self				:   List[Any] )   ->			Tuple:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    self.model_tester.prepare_config_and_inputs_for_decoder()
												self.model_tester.create_and_check_decoder_model_past_large_inputs(*_UpperCamelCase )




							def 		__snake_case(  self				:   List[str] )   ->			Union[str, Any]:



												'''simple docstring'''

												(
												    (
												    SCREAMING_SNAKE_CASE
												)     ,				(
												    SCREAMING_SNAKE_CASE
												)     ,				(
												    SCREAMING_SNAKE_CASE
												)     ,				(
												    SCREAMING_SNAKE_CASE
												)     ,				(
												    SCREAMING_SNAKE_CASE
												)     ,				(
												    SCREAMING_SNAKE_CASE
												)     ,				
												)           =    self.model_tester.prepare_config_and_inputs_for_decoder()

												SCREAMING_SNAKE_CASE           =    None

												self.model_tester.create_and_check_model_as_decoder(
												    _UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase		,							)




							def 		__snake_case(  self				:   Optional[Any] )   ->			List[str]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    self.model_tester.prepare_config_and_inputs_for_decoder()
												self.model_tester.create_and_check_for_causal_lm(*_UpperCamelCase )





							@slow
							def 		__snake_case(  self				:   Tuple )   ->			List[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" )
												self.assertIsNotNone(_UpperCamelCase )



@require_torch
class   lowercase      (       unittest.TestCase       ):




							@slow
							def 		__snake_case(  self				:   Tuple )   ->			Optional[int]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" )
												SCREAMING_SNAKE_CASE           =    torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]] )
												with torch.no_grad():
																	SCREAMING_SNAKE_CASE           =    model(_UpperCamelCase )[0]
												SCREAMING_SNAKE_CASE           =    torch.Size([1, 8, 1_024] )
												self.assertEqual(output.shape		,							_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    torch.tensor(
												    [[[0.1_7_7_5, 0.0_0_8_3, -0.0_3_2_1], [1.6_0_0_2, 0.1_2_8_7, 0.3_9_1_2], [2.1_4_7_3, 0.5_7_9_1, 0.6_0_6_6]]] )
												self.assertTrue(torch.allclose(output[:, :3, :3]		,							_UpperCamelCase		,							atol=1e-4 ) )



@require_torch
class   lowercase      (       unittest.TestCase       ):




							@slow
							def 		__snake_case(  self				:   Union[str, Any] )   ->			Union[str, Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" )
												SCREAMING_SNAKE_CASE           =    torch.tensor([[101, 7_592, 1_010, 2_026, 3_899, 2_003, 10_140, 102]] )
												with torch.no_grad():
																	SCREAMING_SNAKE_CASE           =    model(_UpperCamelCase )[0]
												SCREAMING_SNAKE_CASE           =    torch.Size([1, 8, 50_358] )
												self.assertEqual(output.shape		,							_UpperCamelCase )
												SCREAMING_SNAKE_CASE           =    torch.tensor(
												    [[[-0.5_7_8_8, -2.5_9_9_4, -3.7_0_5_4], [0.0_4_3_8, 4.7_9_9_7, 1.8_7_9_5], [1.5_8_6_2, 6.6_4_0_9, 4.4_6_3_8]]] )
												self.assertTrue(torch.allclose(output[:, :3, :3]		,							_UpperCamelCase		,							atol=1e-4 ) )





import unittest

from transformers import AutoTokenizer, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow


if is_flax_available():
							import jax.numpy as jnp

							from transformers import FlaxXLMRobertaModel


@require_sentencepiece
@require_tokenizers
@require_flax
class   lowercase      (       unittest.TestCase       ):




							@slow
							def 		__snake_case(  self				:   Optional[int] )   ->			List[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE           =    FlaxXLMRobertaModel.from_pretrained("xlm-roberta-base" )
												SCREAMING_SNAKE_CASE           =    AutoTokenizer.from_pretrained("xlm-roberta-base" )
												SCREAMING_SNAKE_CASE           =    "The dog is cute and lives in the garden house"
												SCREAMING_SNAKE_CASE           =    jnp.array([tokenizer.encode(_UpperCamelCase )] )

												SCREAMING_SNAKE_CASE           =    (1, 12, 768)  # batch_size, sequence_length, embedding_vector_dim
												SCREAMING_SNAKE_CASE           =    jnp.array(
												    [[-0.0_1_0_1, 0.1_2_1_8, -0.0_8_0_3, 0.0_8_0_1, 0.1_3_2_7, 0.0_7_7_6, -0.1_2_1_5, 0.2_3_8_3, 0.3_3_3_8, 0.3_1_0_6, 0.0_3_0_0, 0.0_2_5_2]] )

												SCREAMING_SNAKE_CASE           =    model(_UpperCamelCase )["last_hidden_state"]
												self.assertEqual(output.shape		,							_UpperCamelCase )
												# compare the actual values for a slice of last dim
												self.assertTrue(jnp.allclose(output[:, :, -1]		,							_UpperCamelCase		,							atol=1e-3 ) )




