import gc
import importlib.metadata
import tempfile
import unittest

from packaging import version

from transformers import (
    AutoModel,
    AutoModelForCausalLM,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    BitsAndBytesConfig,
    pipeline,
)
from transformers.testing_utils import (
    is_torch_available,
    require_accelerate,
    require_bitsandbytes,
    require_torch,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)




def       _snake_case	(   lowerCAmelCase							:   Optional[int]	):
		"""simple docstring"""







		if model.config.model_type == "gpt2":
				return model.transformer.h[0].mlp.c_fc
		return model.transformer.h[0].mlp.dense_ah_to_h


if is_torch_available():
		import torch
		import torch.nn as nn






		class 		a__						(					nn.Module					):

							def __init__(    self      :       str,_A      :       nn.Module,_A      :       int    ):







									"""simple docstring"""






									super().__init__()
									SCREAMING_SNAKE_CASE_  :		str				      =    module
									SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    nn.Sequential(
									    nn.Linear(module.in_features,_A,bias=_A    ),nn.Linear(_A,module.out_features,bias=_A    ),)
									SCREAMING_SNAKE_CASE_  :		str				      =    (2.0 / (5 * min(module.in_features,module.out_features    ))) ** 0.5
									nn.init.normal_(self.adapter[0].weight,std=_A    )
									nn.init.zeros_(self.adapter[1].weight    )
									self.adapter.to(module.weight.device    )






							def 				__UpperCamelCase   (    self      :       Optional[Any],_A      :       Dict,*_A      :       int,**_A      :       Dict    ):







									"""simple docstring"""






									return self.module(_A,*_A,**_A    ) + self.adapter(_A    )






@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class 		a__						(					unittest.TestCase					):
					# We keep the constants inside the init function and model loading inside setUp function

					# We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
					# Therefore here we use only bloom-1b3 to test our module
					A	       =							'bigscience/bloom-1b7'

					# Constant values
					A	       =							2.109_6595_5269_2574

					A	       =							'Hello my name is'
					A	       =							set()
					EXPECTED_OUTPUTS.add('Hello my name is John and I am a professional photographer. I'					)
					EXPECTED_OUTPUTS.add('Hello my name is John.\nI am a friend of your father.\n'					)
					EXPECTED_OUTPUTS.add('Hello my name is John Doe, I am a student at the University'					)
					A	       =							10

					def 				__UpperCamelCase   (    self      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    AutoTokenizer.from_pretrained(self.model_name    )







class 		a__						(					A__					):

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							super().setUp()

							# Models and tokenizer
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    AutoModelForCausalLM.from_pretrained(
							    self.model_name,torch_dtype=torch.floataa,device_map="auto"    )
							SCREAMING_SNAKE_CASE_  :		Dict				      =    AutoModelForCausalLM.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto"    )

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							del self.model_fpaa
							del self.model_abit

							gc.collect()
							torch.cuda.empty_cache()

					def 				__UpperCamelCase   (    self      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.model_abit.config

							self.assertTrue(hasattr(_A,"quantization_config"    )    )

							SCREAMING_SNAKE_CASE_  :		Any				      =    config.to_dict()
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    config.to_diff_dict()

							SCREAMING_SNAKE_CASE_  :		int				      =    config.to_json_string()

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							from bitsandbytes.nn import Paramsabit

							SCREAMING_SNAKE_CASE_  :		str				      =    self.model_fpaa.get_memory_footprint()
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.model_abit.get_memory_footprint()

							self.assertAlmostEqual(mem_fpaa / mem_abit,self.EXPECTED_RELATIVE_DIFFERENCE    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    get_some_linear_layer(self.model_abit    )
							self.assertTrue(linear.weight.__class__ == Paramsabit    )

					def 				__UpperCamelCase   (    self      :       int    ):







							"""simple docstring"""






							from transformers import TaPreTrainedModel

							self.model_fpaa.get_memory_footprint()
							self.model_abit.get_memory_footprint()

							for name, module in self.model_abit.named_modules():
									if isinstance(_A,torch.nn.Linear    ):
											if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules:
													# 4-bit parameters are packed in uint8 variables
													self.assertTrue(module.weight.dtype == torch.uinta    )

					def 				__UpperCamelCase   (    self      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.tokenizer(self.input_text,return_tensors="pt"    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    self.model_abit.generate(input_ids=encoded_input["input_ids"].to(0    ),max_new_tokens=10    )

							self.assertIn(self.tokenizer.decode(output_sequences[0],skip_special_tokens=_A    ),self.EXPECTED_OUTPUTS    )

					def 				__UpperCamelCase   (    self      :       Tuple    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    BitsAndBytesConfig()
							SCREAMING_SNAKE_CASE_  :		str				      =    True

							SCREAMING_SNAKE_CASE_  :		str				      =    AutoModelForCausalLM.from_pretrained(
							    self.model_name,quantization_config=_A,device_map="auto"    )

							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.tokenizer(self.input_text,return_tensors="pt"    )
							SCREAMING_SNAKE_CASE_  :		int				      =    model_abit_from_config.generate(
							    input_ids=encoded_input["input_ids"].to(0    ),max_new_tokens=10    )

							self.assertIn(self.tokenizer.decode(output_sequences[0],skip_special_tokens=_A    ),self.EXPECTED_OUTPUTS    )

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							with self.assertRaises(_A    ), tempfile.TemporaryDirectory() as tmpdirname:
									self.model_abit.save_pretrained(_A    )

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    BitsAndBytesConfig()

							with self.assertRaises(_A    ):
									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    AutoModelForCausalLM.from_pretrained(
									    self.model_name,quantization_config=_A,load_in_abit=_A,device_map="auto",bnb_abit_quant_type="nf4",)

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







							"""simple docstring"""






							with self.assertRaises(_A    ):
									# Tries with `str`
									self.model_abit.to("cpu"    )

							with self.assertRaises(_A    ):
									# Tries with a `dtype``
									self.model_abit.to(torch.floataa    )

							with self.assertRaises(_A    ):
									# Tries with a `device`
									self.model_abit.to(torch.device("cuda:0"    )    )

							with self.assertRaises(_A    ):
									# Tries with a `device`
									self.model_abit.float()

							with self.assertRaises(_A    ):
									# Tries with a `device`
									self.model_abit.half()

							# Test if we did not break anything
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    self.tokenizer(self.input_text,return_tensors="pt"    )

							SCREAMING_SNAKE_CASE_  :		int				      =    self.model_fpaa.to(torch.floataa    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.model_fpaa.generate(input_ids=encoded_input["input_ids"].to(0    ),max_new_tokens=10    )

							# Check this does not throw an error
							SCREAMING_SNAKE_CASE_  :		str				      =    self.model_fpaa.to("cpu"    )

							# Check this does not throw an error
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.model_fpaa.half()

							# Check this does not throw an error
							SCREAMING_SNAKE_CASE_  :		int				      =    self.model_fpaa.float()






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







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    AutoModelForSeqaSeqLM.from_pretrained("t5-small",load_in_abit=_A,device_map="auto"    )
							self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa    )







@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class 		a__						(					unittest.TestCase					):

					@classmethod
					def 				__UpperCamelCase   (    cls      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    "t5-small"
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    "google/flan-t5-small"  # flan-t5 uses dense-act instead of dense-relu-dense
							SCREAMING_SNAKE_CASE_  :		Dict				      =    AutoTokenizer.from_pretrained(cls.model_name    )
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    "Translate in German: Hello, my dog is cute"

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







							"""simple docstring"""






							gc.collect()
							torch.cuda.empty_cache()

					def 				__UpperCamelCase   (    self      :       List[Any]    ):







							"""simple docstring"""






							from transformers import TaForConditionalGeneration

							SCREAMING_SNAKE_CASE_  :		Any				      =    TaForConditionalGeneration._keep_in_fpaa_modules
							SCREAMING_SNAKE_CASE_  :		Dict				      =    None

							# test with `t5-small`
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    TaForConditionalGeneration.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto"    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.tokenizer(self.input_text,return_tensors="pt"    ).to(0    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    model.generate(**_A    )

							# test with `flan-t5-small`
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    TaForConditionalGeneration.from_pretrained(
							    self.dense_act_model_name,load_in_abit=_A,device_map="auto"    )
							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.tokenizer(self.input_text,return_tensors="pt"    ).to(0    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    model.generate(**_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    modules






					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							import bitsandbytes as bnb

							from transformers import TaForConditionalGeneration

							# test with `t5-small`
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    TaForConditionalGeneration.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto"    )

							# there was a bug with decoders - this test checks that it is fixed
							self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q,bnb.nn.Linearabit    )    )

							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.tokenizer(self.input_text,return_tensors="pt"    ).to(0    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    model.generate(**_A    )

							# test with `flan-t5-small`
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    TaForConditionalGeneration.from_pretrained(
							    self.dense_act_model_name,load_in_abit=_A,device_map="auto"    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.tokenizer(self.input_text,return_tensors="pt"    ).to(0    )
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    model.generate(**_A    )







class 		a__						(					A__					):

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







							"""simple docstring"""






							super().setUp()
							# model_name
							SCREAMING_SNAKE_CASE_  :		str				      =    "bigscience/bloom-560m"
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    "t5-small"

							# Different types of model

							SCREAMING_SNAKE_CASE_  :		List[str]				      =    AutoModel.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto"    )
							# Sequence classification model
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    AutoModelForSequenceClassification.from_pretrained(
							    self.model_name,load_in_abit=_A,device_map="auto"    )
							# CausalLM model
							SCREAMING_SNAKE_CASE_  :		int				      =    AutoModelForCausalLM.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto"    )
							# Seq2seq model
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    AutoModelForSeqaSeqLM.from_pretrained(
							    self.seq_to_seq_name,load_in_abit=_A,device_map="auto"    )

					def 				__UpperCamelCase   (    self      :       Dict    ):







							"""simple docstring"""






							del self.base_model
							del self.sequence_model
							del self.model_abit
							del self.seq_to_seq_model

							gc.collect()
							torch.cuda.empty_cache()






					def 				__UpperCamelCase   (    self      :       Any    ):







							"""simple docstring"""






							from bitsandbytes.nn import Paramsabit

							self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit    )

							# Other heads should be nn.Parameter
							self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter    )
							self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter    )
							self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter    )







class 		a__						(					A__					):

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							super().setUp()

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							del self.pipe

							gc.collect()
							torch.cuda.empty_cache()






					def 				__UpperCamelCase   (    self      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    pipeline(
							    "text-generation",model=self.model_name,model_kwargs={"device_map": "auto", "load_in_4bit": True, "torch_dtype": torch.floataa},max_new_tokens=self.MAX_NEW_TOKENS,)

							# Real second forward pass
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.pipe(self.input_text    )
							self.assertIn(pipeline_output[0]["generated_text"],self.EXPECTED_OUTPUTS    )







@require_torch_multi_gpu
class 		a__						(					A__					):

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							super().setUp()






					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Tuple				      =    AutoModelForCausalLM.from_pretrained(
							    self.model_name,load_in_abit=_A,device_map="balanced"    )

							# Check correct device map
							self.assertEqual(set(model_parallel.hf_device_map.values()    ),{0, 1}    )

							# Check that inference pass works on the model
							SCREAMING_SNAKE_CASE_  :		Any				      =    self.tokenizer(self.input_text,return_tensors="pt"    )

							# Second real batch
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    model_parallel.generate(input_ids=encoded_input["input_ids"].to(0    ),max_new_tokens=10    )
							self.assertIn(self.tokenizer.decode(output_parallel[0],skip_special_tokens=_A    ),self.EXPECTED_OUTPUTS    )







class 		a__						(					A__					):

					def 				__UpperCamelCase   (    self      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		int				      =    "facebook/opt-350m"
							super().setUp()






					def 				__UpperCamelCase   (    self      :       Any    ):







							"""simple docstring"""






							if version.parse(importlib.metadata.version("bitsandbytes"    )    ) < version.parse("0.37.0"    ):
									return

							# Step 1: freeze all parameters
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    AutoModelForCausalLM.from_pretrained(self.model_name,load_in_abit=_A    )

							self.assertEqual(set(model.hf_device_map.values()    ),{torch.cuda.current_device()}    )

							for param in model.parameters():
									SCREAMING_SNAKE_CASE_  :		Any				      =    False  # freeze the model - train adapters later
									if param.ndim == 1:
											# cast the small parameters (e.g. layernorm) to fp32 for stability
											SCREAMING_SNAKE_CASE_  :		List[Any]				      =    param.data.to(torch.floataa    )

        # Step 2: add adapters
							for _, module in model.named_modules():
									if "OPTAttention" in repr(type(_A    )    ):
											SCREAMING_SNAKE_CASE_  :		Dict				      =    LoRALayer(module.q_proj,rank=16    )
											SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    LoRALayer(module.k_proj,rank=16    )
											SCREAMING_SNAKE_CASE_  :		List[Any]				      =    LoRALayer(module.v_proj,rank=16    )

        # Step 3: dummy batch
							SCREAMING_SNAKE_CASE_  :		int				      =    self.tokenizer("Test batch ",return_tensors="pt"    ).to(0    )

							# Step 4: Check if the gradient is not None
							with torch.cuda.amp.autocast():
									SCREAMING_SNAKE_CASE_  :		int				      =    model.forward(**_A    )
									out.logits.norm().backward()

							for module in model.modules():
									if isinstance(_A,_A    ):
											self.assertTrue(module.adapter[1].weight.grad is not None    )
											self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0    )
									elif isinstance(_A,nn.Embedding    ):
											self.assertTrue(module.weight.grad is None    )







class 		a__						(					A__					):
					A	       =							'gpt2-xl'
					A	       =							3.3191_8548_5415_2187


import os
import tempfile
import unittest

from transformers import NezhaConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_gpu, 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 (
					    MODEL_FOR_PRETRAINING_MAPPING,
					    NezhaForMaskedLM,
					    NezhaForMultipleChoice,
					    NezhaForNextSentencePrediction,
					    NezhaForPreTraining,
					    NezhaForQuestionAnswering,
					    NezhaForSequenceClassification,
					    NezhaForTokenClassification,
					    NezhaModel,
					)
					from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST







class      A__							:






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






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[Any]         =		parent
							lowerCAmelCase__      :      Dict         =		batch_size
							lowerCAmelCase__      :      Optional[Any]         =		seq_length
							lowerCAmelCase__      :      Optional[Any]         =		is_training
							lowerCAmelCase__      :      Union[str, Any]         =		use_input_mask
							lowerCAmelCase__      :      List[Any]         =		use_token_type_ids
							lowerCAmelCase__      :      str         =		use_labels
							lowerCAmelCase__      :      Optional[Any]         =		vocab_size
							lowerCAmelCase__      :      Union[str, Any]         =		hidden_size
							lowerCAmelCase__      :      Optional[int]         =		num_hidden_layers
							lowerCAmelCase__      :      Optional[int]         =		num_attention_heads
							lowerCAmelCase__      :      List[Any]         =		intermediate_size
							lowerCAmelCase__      :      List[str]         =		hidden_act
							lowerCAmelCase__      :      List[Any]         =		hidden_dropout_prob
							lowerCAmelCase__      :      Optional[int]         =		attention_probs_dropout_prob
							lowerCAmelCase__      :      Dict         =		max_position_embeddings
							lowerCAmelCase__      :      Any         =		type_vocab_size
							lowerCAmelCase__      :      Any         =		type_sequence_label_size
							lowerCAmelCase__      :      List[Any]         =		initializer_range
							lowerCAmelCase__      :      Dict         =		num_labels
							lowerCAmelCase__      :      Any         =		num_choices
							lowerCAmelCase__      :      Union[str, Any]         =		scope






				def 							_lowerCamelCase		(						self					:      Dict   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		ids_tensor([self.batch_size, self.seq_length]    ,     self.vocab_size   )

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

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

							lowerCAmelCase__      :      Optional[int]         =		None
							lowerCAmelCase__      :      Optional[Any]         =		None
							lowerCAmelCase__      :      Optional[int]         =		None
							if self.use_labels:
										lowerCAmelCase__      :      Any         =		ids_tensor([self.batch_size]    ,     self.type_sequence_label_size   )
										lowerCAmelCase__      :      Union[str, Any]         =		ids_tensor([self.batch_size, self.seq_length]    ,     self.num_labels   )
										lowerCAmelCase__      :      List[Any]         =		ids_tensor([self.batch_size]    ,     self.num_choices   )

							lowerCAmelCase__      :      Dict         =		self.get_config()

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






				def 							_lowerCamelCase		(						self					:      List[Any]   ):






							'''simple docstring'''







							return NezhaConfig(
							    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    ,     is_decoder=a    ,     initializer_range=self.initializer_range    ,     )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							(
							    (
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				
							)      :      List[Any]         =		self.prepare_config_and_inputs()

							lowerCAmelCase__      :      List[Any]         =		True
							lowerCAmelCase__      :      Tuple         =		floats_tensor([self.batch_size, self.seq_length, self.hidden_size]   )
							lowerCAmelCase__      :      Tuple         =		ids_tensor([self.batch_size, self.seq_length]    ,     vocab_size=2   )

							return (
							    config,
							    input_ids,
							    token_type_ids,
							    input_mask,
							    sequence_labels,
							    token_labels,
							    choice_labels,
							    encoder_hidden_states,
							    encoder_attention_mask,
							)






				def 							_lowerCamelCase		(						self					:      Optional[Any]    ,     a					:      Optional[int]    ,     a					:      Tuple    ,     a					:      Optional[int]    ,     a					:      List[Any]    ,     a					:      Tuple    ,     a					:      List[str]    ,     a					:      Any   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[str]         =		NezhaModel(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Dict         =		model(a    ,     attention_mask=a    ,     token_type_ids=a   )
							lowerCAmelCase__      :      List[str]         =		model(a    ,     token_type_ids=a   )
							lowerCAmelCase__      :      Any         =		model(a   )
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.hidden_size)   )
							self.parent.assertEqual(result.pooler_output.shape    ,     (self.batch_size, self.hidden_size)   )






				def 							_lowerCamelCase		(						self					:      List[Any]    ,     a					:      Union[str, Any]    ,     a					:      Dict    ,     a					:      List[Any]    ,     a					:      Optional[Any]    ,     a					:      int    ,     a					:      Tuple    ,     a					:      List[Any]    ,     a					:      Tuple    ,     a					:      List[str]    ,     ):






							'''simple docstring'''







							lowerCAmelCase__      :      Union[str, Any]         =		True
							lowerCAmelCase__      :      Optional[int]         =		NezhaModel(a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Any         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     encoder_hidden_states=a    ,     encoder_attention_mask=a    ,     )
							lowerCAmelCase__      :      Dict         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     encoder_hidden_states=a    ,     )
							lowerCAmelCase__      :      List[str]         =		model(a    ,     attention_mask=a    ,     token_type_ids=a   )
							self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.hidden_size)   )
							self.parent.assertEqual(result.pooler_output.shape    ,     (self.batch_size, self.hidden_size)   )






				def 							_lowerCamelCase		(						self					:      Tuple    ,     a					:      Optional[Any]    ,     a					:      List[Any]    ,     a					:      str    ,     a					:      List[str]    ,     a					:      Tuple    ,     a					:      List[Any]    ,     a					:      Optional[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[Any]         =		NezhaForMaskedLM(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Dict         =		model(a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a   )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.seq_length, self.vocab_size)   )






				def 							_lowerCamelCase		(						self					:      List[Any]    ,     a					:      Optional[int]    ,     a					:      List[Any]    ,     a					:      int    ,     a					:      List[str]    ,     a					:      Union[str, Any]    ,     a					:      int    ,     a					:      Any   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[Any]         =		NezhaForNextSentencePrediction(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      str         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a    ,     )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, 2)   )






				def 							_lowerCamelCase		(						self					:      int    ,     a					:      Optional[int]    ,     a					:      str    ,     a					:      List[str]    ,     a					:      int    ,     a					:      Dict    ,     a					:      Optional[Any]    ,     a					:      Optional[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Tuple         =		NezhaForPreTraining(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Optional[int]         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a    ,     next_sentence_label=a    ,     )
							self.parent.assertEqual(result.prediction_logits.shape    ,     (self.batch_size, self.seq_length, self.vocab_size)   )
							self.parent.assertEqual(result.seq_relationship_logits.shape    ,     (self.batch_size, 2)   )






				def 							_lowerCamelCase		(						self					:      Union[str, Any]    ,     a					:      Dict    ,     a					:      List[str]    ,     a					:      Any    ,     a					:      Any    ,     a					:      Union[str, Any]    ,     a					:      Tuple    ,     a					:      List[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[Any]         =		NezhaForQuestionAnswering(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Tuple         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     start_positions=a    ,     end_positions=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 							_lowerCamelCase		(						self					:      Tuple    ,     a					:      str    ,     a					:      Union[str, Any]    ,     a					:      Tuple    ,     a					:      Optional[Any]    ,     a					:      Dict    ,     a					:      str    ,     a					:      int   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Any         =		self.num_labels
							lowerCAmelCase__      :      Optional[Any]         =		NezhaForSequenceClassification(a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Tuple         =		model(a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a   )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels)   )






				def 							_lowerCamelCase		(						self					:      List[str]    ,     a					:      Dict    ,     a					:      str    ,     a					:      Optional[Any]    ,     a					:      Optional[int]    ,     a					:      List[str]    ,     a					:      Dict    ,     a					:      str   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Dict         =		self.num_labels
							lowerCAmelCase__      :      str         =		NezhaForTokenClassification(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      Any         =		model(a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a   )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.seq_length, self.num_labels)   )






				def 							_lowerCamelCase		(						self					:      int    ,     a					:      Tuple    ,     a					:      List[Any]    ,     a					:      Tuple    ,     a					:      List[Any]    ,     a					:      Optional[int]    ,     a					:      Optional[int]    ,     a					:      Optional[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[Any]         =		self.num_choices
							lowerCAmelCase__      :      Any         =		NezhaForMultipleChoice(config=a   )
							model.to(a   )
							model.eval()
							lowerCAmelCase__      :      int         =		input_ids.unsqueeze(1   ).expand(-1    ,     self.num_choices    ,     -1   ).contiguous()
							lowerCAmelCase__      :      str         =		token_type_ids.unsqueeze(1   ).expand(-1    ,     self.num_choices    ,     -1   ).contiguous()
							lowerCAmelCase__      :      Optional[Any]         =		input_mask.unsqueeze(1   ).expand(-1    ,     self.num_choices    ,     -1   ).contiguous()
							lowerCAmelCase__      :      Any         =		model(
							    a    ,     attention_mask=a    ,     token_type_ids=a    ,     labels=a    ,     )
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_choices)   )






				def 							_lowerCamelCase		(						self					:      Tuple   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		self.prepare_config_and_inputs()
							(
							    (
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				
							)      :      Any         =		config_and_inputs
							lowerCAmelCase__      :      str         =		{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
							return config, inputs_dict







@require_torch
class      A__							(     __magic_name__						,   __magic_name__						,   __magic_name__						,   unittest.TestCase	):
				lowercase			    =  (
				    (
				        NezhaModel,
				        NezhaForMaskedLM,
				        NezhaForMultipleChoice,
				        NezhaForNextSentencePrediction,
				        NezhaForPreTraining,
				        NezhaForQuestionAnswering,
				        NezhaForSequenceClassification,
				        NezhaForTokenClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				lowercase			    =  (
				    {
				        'feature-extraction': NezhaModel,
				        'fill-mask': NezhaForMaskedLM,
				        'question-answering': NezhaForQuestionAnswering,
				        'text-classification': NezhaForSequenceClassification,
				        'token-classification': NezhaForTokenClassification,
				        'zero-shot': NezhaForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				lowercase			    =  True






				def 							_lowerCamelCase		(						self					:      str    ,     a					:      Tuple    ,     a					:      int    ,     a					:      Dict=False   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		super()._prepare_for_class(a    ,     a    ,     return_labels=a   )

							if return_labels:
										if model_class in get_values(a   ):
													lowerCAmelCase__      :      Tuple         =		torch.zeros(
													    (self.model_tester.batch_size, self.model_tester.seq_length)    ,     dtype=torch.long    ,     device=a   )
													lowerCAmelCase__      :      Optional[Any]         =		torch.zeros(
													    self.model_tester.batch_size    ,     dtype=torch.long    ,     device=a   )
							return inputs_dict






				def 							_lowerCamelCase		(						self					:      Union[str, Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[int]         =		NezhaModelTester(self   )
							lowerCAmelCase__      :      Optional[int]         =		ConfigTester(self    ,     config_class=a    ,     hidden_size=37   )






				def 							_lowerCamelCase		(						self					:      Union[str, Any]   ):






							'''simple docstring'''







							self.config_tester.run_common_tests()






				def 							_lowerCamelCase		(						self					:      Optional[int]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[str]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*a   )






				def 							_lowerCamelCase		(						self					:      List[str]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		self.model_tester.prepare_config_and_inputs_for_decoder()
							self.model_tester.create_and_check_model_as_decoder(*a   )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							(
							    (
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				(
							    lowerCAmelCase__
							)      ,				
							)      :      str         =		self.model_tester.prepare_config_and_inputs_for_decoder()

							lowerCAmelCase__      :      str         =		None

							self.model_tester.create_and_check_model_as_decoder(
							    a    ,     a    ,     a    ,     a    ,     a    ,     a    ,     a    ,     a    ,     a    ,     )






				def 							_lowerCamelCase		(						self					:      int   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*a   )






				def 							_lowerCamelCase		(						self					:      List[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Union[str, Any]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*a   )






				def 							_lowerCamelCase		(						self					:      int   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[int]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_next_sequence_prediction(*a   )






				def 							_lowerCamelCase		(						self					:      Union[str, Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[str]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_pretraining(*a   )






				def 							_lowerCamelCase		(						self					:      int   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[int]         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*a   )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      int         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*a   )






				def 							_lowerCamelCase		(						self					:      List[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Any         =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*a   )






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






							'''simple docstring'''







							for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowerCAmelCase__      :      Optional[Any]         =		NezhaModel.from_pretrained(a   )
										self.assertIsNotNone(a   )






				@slow
				@require_torch_gpu
				def 							_lowerCamelCase		(						self					:      Optional[int]   ):






							'''simple docstring'''







							lowerCAmelCase__      ,				lowerCAmelCase__      :      Optional[int]         =		self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
										# NezhaForMultipleChoice behaves incorrectly in JIT environments.
										if model_class == NezhaForMultipleChoice:
													return

										lowerCAmelCase__      :      Dict         =		True
										lowerCAmelCase__      :      Any         =		model_class(config=a   )

										lowerCAmelCase__      :      Union[str, Any]         =		self._prepare_for_class(a    ,     a   )
										lowerCAmelCase__      :      int         =		torch.jit.trace(
										    a    ,     (inputs_dict['input_ids'].to('cpu'   ), inputs_dict['attention_mask'].to('cpu'   ))   )

										with tempfile.TemporaryDirectory() as tmp:
													torch.jit.save(a    ,     os.path.join(a    ,     'bert.pt'   )   )
													lowerCAmelCase__      :      Any         =		torch.jit.load(os.path.join(a    ,     'bert.pt'   )    ,     map_location=a   )
													loaded(inputs_dict['input_ids'].to(a   )    ,     inputs_dict['attention_mask'].to(a   )   )







@require_torch
class      A__							(     unittest.TestCase	):






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






							'''simple docstring'''







							lowerCAmelCase__      :      str         =		NezhaModel.from_pretrained('sijunhe/nezha-cn-base'   )
							lowerCAmelCase__      :      Any         =		torch.tensor([[0, 1, 2, 3, 4, 5]]   )
							lowerCAmelCase__      :      Union[str, Any]         =		torch.tensor([[0, 1, 1, 1, 1, 1]]   )
							with torch.no_grad():
										lowerCAmelCase__      :      Optional[int]         =		model(a    ,     attention_mask=a   )[0]
							lowerCAmelCase__      :      Union[str, Any]         =		torch.Size((1, 6, 768)   )
							self.assertEqual(output.shape    ,     a   )
							lowerCAmelCase__      :      Optional[int]         =		torch.tensor([[[0.0_6_8_5, 0.2_4_4_1, 0.1_1_0_2], [0.0_6_0_0, 0.1_9_0_6, 0.1_3_4_9], [0.0_2_2_1, 0.0_8_1_9, 0.0_5_8_6]]]   )

							self.assertTrue(torch.allclose(output[:, 1:4, 1:4]    ,     a    ,     atol=1E-4   )   )






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






							'''simple docstring'''







							lowerCAmelCase__      :      Any         =		NezhaForMaskedLM.from_pretrained('sijunhe/nezha-cn-base'   )
							lowerCAmelCase__      :      Optional[int]         =		torch.tensor([[0, 1, 2, 3, 4, 5]]   )
							lowerCAmelCase__      :      Optional[int]         =		torch.tensor([[1, 1, 1, 1, 1, 1]]   )
							with torch.no_grad():
										lowerCAmelCase__      :      Optional[int]         =		model(a    ,     attention_mask=a   )[0]
							lowerCAmelCase__      :      int         =		torch.Size((1, 6, 21_128)   )
							self.assertEqual(output.shape    ,     a   )
							lowerCAmelCase__      :      List[Any]         =		torch.tensor(
							    [[-2.7_9_3_9, -1.7_9_0_2, -2.2_1_8_9], [-2.8_5_8_5, -1.8_9_0_8, -2.3_7_2_3], [-2.6_4_9_9, -1.7_7_5_0, -2.2_5_5_8]]   )

							self.assertTrue(torch.allclose(output[:, 1:4, 1:4]    ,     a    ,     atol=1E-4   )   )