import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
		import jax
		import jax.numpy as jnp

		from transformers.modeling_flax_pytorch_utils import (
		    convert_pytorch_state_dict_to_flax,
		    load_flax_weights_in_pytorch_model,
		)
		from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel

if is_torch_available():
		import torch






class 		a__						:

					def __init__(    self      :       int,_A      :       Tuple,_A      :       Union[str, Any]=14,_A      :       int=7,_A      :       Tuple=True,_A      :       Tuple=True,_A      :       int=False,_A      :       Dict=True,_A      :       List[Any]=99,_A      :       List[Any]=32,_A      :       Union[str, Any]=4,_A      :       List[str]=4,_A      :       str=4,_A      :       List[Any]=37,_A      :       int="gelu",_A      :       str=0.1,_A      :       Tuple=0.1,_A      :       Tuple=512,_A      :       int=0.02,):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    parent
							SCREAMING_SNAKE_CASE_  :		Any				      =    batch_size
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    seq_length
							SCREAMING_SNAKE_CASE_  :		Dict				      =    is_training
							SCREAMING_SNAKE_CASE_  :		str				      =    use_input_mask
							SCREAMING_SNAKE_CASE_  :		int				      =    use_token_type_ids
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    use_labels
							SCREAMING_SNAKE_CASE_  :		Any				      =    vocab_size
							SCREAMING_SNAKE_CASE_  :		int				      =    hidden_size
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    rotary_dim
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    num_hidden_layers
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    num_attention_heads
							SCREAMING_SNAKE_CASE_  :		Any				      =    intermediate_size
							SCREAMING_SNAKE_CASE_  :		Any				      =    hidden_act
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    hidden_dropout_prob
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    attention_probs_dropout_prob
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    max_position_embeddings
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    initializer_range
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    None
							SCREAMING_SNAKE_CASE_  :		str				      =    vocab_size - 1
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    vocab_size - 1
							SCREAMING_SNAKE_CASE_  :		int				      =    vocab_size - 1

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






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

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

							SCREAMING_SNAKE_CASE_  :		int				      =    GPTJConfig(
							    vocab_size=self.vocab_size,n_embd=self.hidden_size,n_layer=self.num_hidden_layers,n_head=self.num_attention_heads,n_positions=self.max_position_embeddings,use_cache=_A,bos_token_id=self.bos_token_id,eos_token_id=self.eos_token_id,pad_token_id=self.pad_token_id,rotary_dim=self.rotary_dim,)

							return (config, input_ids, input_mask)

					def 				__UpperCamelCase   (    self      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.prepare_config_and_inputs()
							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		List[Any]				      =    config_and_inputs
							SCREAMING_SNAKE_CASE_  :		Dict				      =    {"input_ids": input_ids, "attention_mask": attention_mask}
							return config, inputs_dict

					def 				__UpperCamelCase   (    self      :       int,_A      :       Tuple,_A      :       str,_A      :       Union[str, Any],_A      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    20
							SCREAMING_SNAKE_CASE_  :		Any				      =    model_class_name(_A    )

							SCREAMING_SNAKE_CASE_  :		Dict				      =    model.init_cache(input_ids.shape[0],_A    )
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    jnp.ones((input_ids.shape[0], max_decoder_length),dtype="i4"    )

							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    jnp.broadcast_to(
							    jnp.arange(input_ids.shape[-1] - 1    )[None, :],(input_ids.shape[0], input_ids.shape[-1] - 1)    )
							SCREAMING_SNAKE_CASE_  :		str				      =    model(
							    input_ids[:, :-1],attention_mask=_A,past_key_values=_A,position_ids=_A,)

							SCREAMING_SNAKE_CASE_  :		List[str]				      =    jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]],dtype="i4"    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    model(
							    input_ids[:, -1:],attention_mask=_A,past_key_values=outputs_cache.past_key_values,position_ids=_A,)

							SCREAMING_SNAKE_CASE_  :		Any				      =    model(_A    )

							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])    )    )
							self.parent.assertTrue(diff < 1E-3,msg=F'Max diff is {diff}'    )






					def 				__UpperCamelCase   (    self      :       Optional[Any],_A      :       int,_A      :       Union[str, Any],_A      :       int,_A      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    20
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    model_class_name(_A    )

							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    jnp.concatenate(
							    [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])    )],axis=-1,)

							SCREAMING_SNAKE_CASE_  :		Tuple				      =    model.init_cache(input_ids.shape[0],_A    )
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    jnp.broadcast_to(
							    jnp.arange(input_ids.shape[-1] - 1    )[None, :],(input_ids.shape[0], input_ids.shape[-1] - 1)    )

							SCREAMING_SNAKE_CASE_  :		List[str]				      =    model(
							    input_ids[:, :-1],attention_mask=_A,past_key_values=_A,position_ids=_A,)
							SCREAMING_SNAKE_CASE_  :		Dict				      =    jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]],dtype="i4"    )
							SCREAMING_SNAKE_CASE_  :		int				      =    model(
							    input_ids[:, -1:],past_key_values=outputs_cache.past_key_values,attention_mask=_A,position_ids=_A,)

							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    model(_A,attention_mask=_A    )

							SCREAMING_SNAKE_CASE_  :		int				      =    np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])    )    )
							self.parent.assertTrue(diff < 1E-3,msg=F'Max diff is {diff}'    )







@require_flax
class 		a__						(					A__    ,		A__    ,		unittest.TestCase					):
					A	       =							(FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else ()
					A	       =							(FlaxGPTJForCausalLM,) if is_flax_available() else ()

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Tuple				      =    FlaxGPTJModelTester(self    )

					def 				__UpperCamelCase   (    self      :       Dict    ):







							"""simple docstring"""






							for model_class_name in self.all_model_classes:
									SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.check_use_cache_forward(_A,_A,_A,_A    )

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							for model_class_name in self.all_model_classes:
									SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.check_use_cache_forward_with_attn_mask(
									    _A,_A,_A,_A    )

					@tooslow
					def 				__UpperCamelCase   (    self      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    GPTaTokenizer.from_pretrained("gpt2",pad_token="<|endoftext|>",padding_side="left"    )
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    tokenizer(["Hello this is a long string", "Hey"],return_tensors="np",padding=_A,truncation=_A    )

							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    FlaxGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B"    )
							SCREAMING_SNAKE_CASE_  :		str				      =    False
							SCREAMING_SNAKE_CASE_  :		Any				      =    model.config.eos_token_id

							SCREAMING_SNAKE_CASE_  :		Dict				      =    jax.jit(model.generate    )

							SCREAMING_SNAKE_CASE_  :		str				      =    jit_generate(
							    inputs["input_ids"],attention_mask=inputs["attention_mask"],pad_token_id=tokenizer.pad_token_id    ).sequences

							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    tokenizer.batch_decode(_A,skip_special_tokens=_A    )

							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    [
							    "Hello this is a long string of text.\n\nI'm trying to get the text of the",
							    "Hey, I'm a little late to the party. I'm going to",
							]

							self.assertListEqual(_A,_A    )

					@is_pt_flax_cross_test
					def 				__UpperCamelCase   (    self      :       Any    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__    ):
											# prepare inputs
											SCREAMING_SNAKE_CASE_  :		Tuple				      =    self._prepare_for_class(_A,_A    )
											SCREAMING_SNAKE_CASE_  :		Tuple				      =    {k: torch.tensor(v.tolist()    ) for k, v in prepared_inputs_dict.items()}

											# load corresponding PyTorch class
											SCREAMING_SNAKE_CASE_  :		str				      =    model_class.__name__[4:]  # Skip the "Flax" at the beginning
											SCREAMING_SNAKE_CASE_  :		str				      =    getattr(_A,_A    )

											SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		List[Any]				      =    pt_inputs["input_ids"].shape
											SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    np.random.randint(0,seq_length - 1,size=(batch_size,)    )
											for batch_idx, start_index in enumerate(_A    ):
													SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    0
													SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    1
													SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    0
													SCREAMING_SNAKE_CASE_  :		Any				      =    1
											SCREAMING_SNAKE_CASE_  :		List[Any]				      =    pt_model_class(_A    ).eval()
											SCREAMING_SNAKE_CASE_  :		Dict				      =    model_class(_A,dtype=jnp.floataa    )

											SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    convert_pytorch_state_dict_to_flax(pt_model.state_dict(),_A    )
											SCREAMING_SNAKE_CASE_  :		Any				      =    fx_state

											with torch.no_grad():
													SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    pt_model(**_A    ).to_tuple()

											SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    fx_model(**_A    ).to_tuple()
											self.assertEqual(len(_A    ),len(_A    ),"Output lengths differ between Flax and PyTorch"    )
											for fx_output, pt_output in zip(_A,_A    ):
													self.assert_almost_equals(fx_output[:, -1],pt_output[:, -1].numpy(),4E-2    )

											with tempfile.TemporaryDirectory() as tmpdirname:
													pt_model.save_pretrained(_A    )
													SCREAMING_SNAKE_CASE_  :		int				      =    model_class.from_pretrained(_A,from_pt=_A    )

											SCREAMING_SNAKE_CASE_  :		str				      =    fx_model_loaded(**_A    ).to_tuple()
											self.assertEqual(
											    len(_A    ),len(_A    ),"Output lengths differ between Flax and PyTorch"    )
											for fx_output_loaded, pt_output in zip(_A,_A    ):
													self.assert_almost_equals(fx_output_loaded[:, -1],pt_output[:, -1].numpy(),4E-2    )

					@is_pt_flax_cross_test
					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		int				      =    self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__    ):
											# prepare inputs
											SCREAMING_SNAKE_CASE_  :		str				      =    self._prepare_for_class(_A,_A    )
											SCREAMING_SNAKE_CASE_  :		Any				      =    {k: torch.tensor(v.tolist()    ) for k, v in prepared_inputs_dict.items()}

											# load corresponding PyTorch class
											SCREAMING_SNAKE_CASE_  :		Tuple				      =    model_class.__name__[4:]  # Skip the "Flax" at the beginning
											SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    getattr(_A,_A    )

											SCREAMING_SNAKE_CASE_  :		List[str]				      =    pt_model_class(_A    ).eval()
											SCREAMING_SNAKE_CASE_  :		Any				      =    model_class(_A,dtype=jnp.floataa    )

											SCREAMING_SNAKE_CASE_  :		Tuple				      =    load_flax_weights_in_pytorch_model(_A,fx_model.params    )
											SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    pt_inputs["input_ids"].shape
											SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    np.random.randint(0,seq_length - 1,size=(batch_size,)    )
											for batch_idx, start_index in enumerate(_A    ):
													SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    0
													SCREAMING_SNAKE_CASE_  :		Tuple				      =    1
													SCREAMING_SNAKE_CASE_  :		int				      =    0
													SCREAMING_SNAKE_CASE_  :		int				      =    1

											# make sure weights are tied in PyTorch
											pt_model.tie_weights()

											with torch.no_grad():
													SCREAMING_SNAKE_CASE_  :		Any				      =    pt_model(**_A    ).to_tuple()

											SCREAMING_SNAKE_CASE_  :		List[str]				      =    fx_model(**_A    ).to_tuple()
											self.assertEqual(len(_A    ),len(_A    ),"Output lengths differ between Flax and PyTorch"    )
											for fx_output, pt_output in zip(_A,_A    ):
													self.assert_almost_equals(fx_output[:, -1],pt_output[:, -1].numpy(),4E-2    )

											with tempfile.TemporaryDirectory() as tmpdirname:
													fx_model.save_pretrained(_A    )
													SCREAMING_SNAKE_CASE_  :		Tuple				      =    pt_model_class.from_pretrained(_A,from_flax=_A    )

											with torch.no_grad():
													SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    pt_model_loaded(**_A    ).to_tuple()

											self.assertEqual(
											    len(_A    ),len(_A    ),"Output lengths differ between Flax and PyTorch"    )
											for fx_output, pt_output in zip(_A,_A    ):
													self.assert_almost_equals(fx_output[:, -1],pt_output[:, -1].numpy(),4E-2    )






					@tooslow
					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							for model_class_name in self.all_model_classes:
									SCREAMING_SNAKE_CASE_  :		str				      =    model_class_name.from_pretrained("EleutherAI/gpt-j-6B"    )
									SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    model(np.ones((1, 1)    )    )
									self.assertIsNotNone(_A    )

from __future__ import annotations

import os
import tempfile
import unittest

from transformers import ConvBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    TFConvBertForMaskedLM,
		    TFConvBertForMultipleChoice,
		    TFConvBertForQuestionAnswering,
		    TFConvBertForSequenceClassification,
		    TFConvBertForTokenClassification,
		    TFConvBertModel,
		)






class 		a__						:

					def __init__(    self      :       Optional[int],_A      :       Dict,_A      :       List[str]=13,_A      :       List[str]=7,_A      :       int=True,_A      :       str=True,_A      :       Union[str, Any]=True,_A      :       Tuple=True,_A      :       Dict=99,_A      :       Tuple=32,_A      :       Tuple=2,_A      :       Tuple=4,_A      :       Optional[Any]=37,_A      :       str="gelu",_A      :       Dict=0.1,_A      :       List[Any]=0.1,_A      :       List[str]=512,_A      :       str=16,_A      :       int=2,_A      :       Dict=0.02,_A      :       List[Any]=3,_A      :       Optional[Any]=4,_A      :       Optional[int]=None,):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    parent
							SCREAMING_SNAKE_CASE_  :		Any				      =    13
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    7
							SCREAMING_SNAKE_CASE_  :		Dict				      =    True
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    True
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    True
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    True
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    99
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    384
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    2
							SCREAMING_SNAKE_CASE_  :		Any				      =    4
							SCREAMING_SNAKE_CASE_  :		str				      =    37
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    "gelu"
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    0.1
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    0.1
							SCREAMING_SNAKE_CASE_  :		Dict				      =    512
							SCREAMING_SNAKE_CASE_  :		int				      =    16
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    2
							SCREAMING_SNAKE_CASE_  :		Any				      =    0.02
							SCREAMING_SNAKE_CASE_  :		str				      =    3
							SCREAMING_SNAKE_CASE_  :		int				      =    4
							SCREAMING_SNAKE_CASE_  :		Dict				      =    128
							SCREAMING_SNAKE_CASE_  :		Any				      =    2
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    9
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    1
							SCREAMING_SNAKE_CASE_  :		Any				      =    None

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






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

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

							SCREAMING_SNAKE_CASE_  :		List[str]				      =    None
							if self.use_token_type_ids:
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    ids_tensor([self.batch_size, self.seq_length],self.type_vocab_size    )

							SCREAMING_SNAKE_CASE_  :		Dict				      =    None
							SCREAMING_SNAKE_CASE_  :		Dict				      =    None
							SCREAMING_SNAKE_CASE_  :		str				      =    None
							if self.use_labels:
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    ids_tensor([self.batch_size],self.type_sequence_label_size    )
									SCREAMING_SNAKE_CASE_  :		Dict				      =    ids_tensor([self.batch_size, self.seq_length],self.num_labels    )
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    ids_tensor([self.batch_size],self.num_choices    )

							SCREAMING_SNAKE_CASE_  :		Any				      =    ConvBertConfig(
							    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,type_vocab_size=self.type_vocab_size,initializer_range=self.initializer_range,return_dict=_A,)

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

					def 				__UpperCamelCase   (    self      :       Optional[int],_A      :       List[Any],_A      :       int,_A      :       Tuple,_A      :       Optional[int],_A      :       Union[str, Any],_A      :       Union[str, Any],_A      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    TFConvBertModel(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}

							SCREAMING_SNAKE_CASE_  :		str				      =    [input_ids, input_mask]
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    model(_A    )

							SCREAMING_SNAKE_CASE_  :		Dict				      =    model(_A    )

							self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)    )

					def 				__UpperCamelCase   (    self      :       Dict,_A      :       Dict,_A      :       int,_A      :       Union[str, Any],_A      :       List[Any],_A      :       int,_A      :       str,_A      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    TFConvBertForMaskedLM(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size)    )

					def 				__UpperCamelCase   (    self      :       Any,_A      :       Optional[int],_A      :       List[Any],_A      :       Union[str, Any],_A      :       List[Any],_A      :       Union[str, Any],_A      :       Optional[int],_A      :       Dict    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.num_labels
							SCREAMING_SNAKE_CASE_  :		Any				      =    TFConvBertForSequenceClassification(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}

							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)    )

					def 				__UpperCamelCase   (    self      :       int,_A      :       int,_A      :       Dict,_A      :       List[str],_A      :       Tuple,_A      :       Dict,_A      :       Optional[int],_A      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.num_choices
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    TFConvBertForMultipleChoice(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    tf.tile(tf.expand_dims(_A,1    ),(1, self.num_choices, 1)    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    tf.tile(tf.expand_dims(_A,1    ),(1, self.num_choices, 1)    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    tf.tile(tf.expand_dims(_A,1    ),(1, self.num_choices, 1)    )
							SCREAMING_SNAKE_CASE_  :		int				      =    {
							    "input_ids": multiple_choice_inputs_ids,
							    "attention_mask": multiple_choice_input_mask,
							    "token_type_ids": multiple_choice_token_type_ids,
							}
							SCREAMING_SNAKE_CASE_  :		int				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_choices)    )

					def 				__UpperCamelCase   (    self      :       List[Any],_A      :       Union[str, Any],_A      :       int,_A      :       Optional[int],_A      :       str,_A      :       str,_A      :       Tuple,_A      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.num_labels
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    TFConvBertForTokenClassification(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}
							SCREAMING_SNAKE_CASE_  :		str				      =    model(_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.num_labels)    )

					def 				__UpperCamelCase   (    self      :       List[Any],_A      :       int,_A      :       List[str],_A      :       List[Any],_A      :       Any,_A      :       Optional[int],_A      :       List[str],_A      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    TFConvBertForQuestionAnswering(config=_A    )
							SCREAMING_SNAKE_CASE_  :		Dict				      =    {
							    "input_ids": input_ids,
							    "attention_mask": input_mask,
							    "token_type_ids": token_type_ids,
							}

							SCREAMING_SNAKE_CASE_  :		Any				      =    model(_A    )
							self.parent.assertEqual(result.start_logits.shape,(self.batch_size, self.seq_length)    )
							self.parent.assertEqual(result.end_logits.shape,(self.batch_size, self.seq_length)    )






					def 				__UpperCamelCase   (    self      :       Tuple    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    self.prepare_config_and_inputs()
							(
							    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    (
							    SCREAMING_SNAKE_CASE_
							)      ,    
							)  :		List[Any]				      =    config_and_inputs
							SCREAMING_SNAKE_CASE_  :		Any				      =    {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
							return config, inputs_dict







@require_tf
class 		a__						(					A__    ,		A__    ,		unittest.TestCase					):
					A	       =							(
					    (
					        TFConvBertModel,
					        TFConvBertForMaskedLM,
					        TFConvBertForQuestionAnswering,
					        TFConvBertForSequenceClassification,
					        TFConvBertForTokenClassification,
					        TFConvBertForMultipleChoice,
					    )
					    if is_tf_available()
					    else ()
					)
					A	       =							(
					    {
					        'feature-extraction': TFConvBertModel,
					        'fill-mask': TFConvBertForMaskedLM,
					        'question-answering': TFConvBertForQuestionAnswering,
					        'text-classification': TFConvBertForSequenceClassification,
					        'token-classification': TFConvBertForTokenClassification,
					        'zero-shot': TFConvBertForSequenceClassification,
					    }
					    if is_tf_available()
					    else {}
					)
					A	       =							False
					A	       =							False
					A	       =							False

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    TFConvBertModelTester(self    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    ConfigTester(self,config_class=_A,hidden_size=37    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							self.config_tester.run_common_tests()

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		int				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*_A    )

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*_A    )

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*_A    )

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*_A    )

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*_A    )

					@slow
					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.model_tester.prepare_config_and_inputs_for_common()
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    True
							SCREAMING_SNAKE_CASE_  :		Any				      =    True

							if hasattr(_A,"use_cache"    ):
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    True

							SCREAMING_SNAKE_CASE_  :		int				      =    getattr(self.model_tester,"encoder_seq_length",self.model_tester.seq_length    )
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    getattr(self.model_tester,"key_length",_A    )

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    self._prepare_for_class(_A,_A    )
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    len(model(_A    )    )

									with tempfile.TemporaryDirectory() as tmpdirname:
											model.save_pretrained(_A,saved_model=_A    )
											SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    os.path.join(_A,"saved_model","1"    )
											SCREAMING_SNAKE_CASE_  :		Tuple				      =    tf.keras.models.load_model(_A    )
											SCREAMING_SNAKE_CASE_  :		str				      =    model(_A    )

											if self.is_encoder_decoder:
													SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    outputs["encoder_hidden_states"]
													SCREAMING_SNAKE_CASE_  :		str				      =    outputs["encoder_attentions"]
											else:
													SCREAMING_SNAKE_CASE_  :		Any				      =    outputs["hidden_states"]
													SCREAMING_SNAKE_CASE_  :		List[str]				      =    outputs["attentions"]

											self.assertEqual(len(_A    ),_A    )

											SCREAMING_SNAKE_CASE_  :		Any				      =    getattr(
											    self.model_tester,"expected_num_hidden_layers",self.model_tester.num_hidden_layers + 1    )

											self.assertEqual(len(_A    ),_A    )
											self.assertListEqual(
											    list(output_hidden_states[0].shape[-2:]    ),[self.model_tester.seq_length, self.model_tester.hidden_size],)

											self.assertEqual(len(_A    ),self.model_tester.num_hidden_layers    )
											self.assertListEqual(
											    list(output_attentions[0].shape[-3:]    ),[self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length],)

					@slow
					def 				__UpperCamelCase   (    self      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    TFConvBertModel.from_pretrained("YituTech/conv-bert-base"    )
							self.assertIsNotNone(_A    )






					def 				__UpperCamelCase   (    self      :       Tuple    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Any				      =    self.model_tester.prepare_config_and_inputs_for_common()
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    True
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    getattr(self.model_tester,"decoder_seq_length",self.model_tester.seq_length    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    getattr(self.model_tester,"encoder_seq_length",self.model_tester.seq_length    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    getattr(self.model_tester,"key_length",_A    )
							SCREAMING_SNAKE_CASE_  :		int				      =    getattr(self.model_tester,"key_length",_A    )

							def check_decoder_attentions_output(_A      :       Dict    ):
									SCREAMING_SNAKE_CASE_  :		int				      =    len(_A    )
									self.assertEqual(out_len % 2,0    )
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    outputs.decoder_attentions
									self.assertEqual(len(_A    ),self.model_tester.num_hidden_layers    )
									self.assertListEqual(
									    list(decoder_attentions[0].shape[-3:]    ),[self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length],)

							def check_encoder_attentions_output(_A      :       Tuple    ):
									SCREAMING_SNAKE_CASE_  :		int				      =    [
									    t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
									]
									self.assertEqual(len(_A    ),self.model_tester.num_hidden_layers    )
									self.assertListEqual(
									    list(attentions[0].shape[-3:]    ),[self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length],)

							for model_class in self.all_model_classes:
									SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    True
									SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    False
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		Any				      =    model(self._prepare_for_class(_A,_A    )    )
									SCREAMING_SNAKE_CASE_  :		Tuple				      =    len(_A    )
									self.assertEqual(config.output_hidden_states,_A    )
									check_encoder_attentions_output(_A    )

									if self.is_encoder_decoder:
											SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    model_class(_A    )
											SCREAMING_SNAKE_CASE_  :		int				      =    model(self._prepare_for_class(_A,_A    )    )
											self.assertEqual(config.output_hidden_states,_A    )
											check_decoder_attentions_output(_A    )

									# Check that output attentions can also be changed via the config
									del inputs_dict["output_attentions"]
									SCREAMING_SNAKE_CASE_  :		str				      =    True
									SCREAMING_SNAKE_CASE_  :		int				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    model(self._prepare_for_class(_A,_A    )    )
									self.assertEqual(config.output_hidden_states,_A    )
									check_encoder_attentions_output(_A    )

									# Check attention is always last and order is fine
									SCREAMING_SNAKE_CASE_  :		str				      =    True
									SCREAMING_SNAKE_CASE_  :		int				      =    True
									SCREAMING_SNAKE_CASE_  :		Dict				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		str				      =    model(self._prepare_for_class(_A,_A    )    )

									self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1),len(_A    )    )
									self.assertEqual(model.config.output_hidden_states,_A    )
									check_encoder_attentions_output(_A    )







@require_tf
class 		a__						(					unittest.TestCase					):

					@slow
					def 				__UpperCamelCase   (    self      :       Union[str, Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    TFConvBertModel.from_pretrained("YituTech/conv-bert-base"    )
							SCREAMING_SNAKE_CASE_  :		int				      =    tf.constant([[0, 1, 2, 3, 4, 5]]    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    model(_A    )[0]

							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    [1, 6, 768]
							self.assertEqual(output.shape,_A    )

							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    tf.constant(
							    [
							        [
							            [-0.03475493, -0.4686034, -0.30638832],
							            [0.22637248, -0.26988646, -0.7423424],
							            [0.10324868, -0.45013508, -0.58280784],
							        ]
							    ]    )
							tf.debugging.assert_near(output[:, :3, :3],_A,atol=1E-4    )
