
import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest

import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed


lowercase   =	logging.getLogger(__name__)



def   __lowerCAmelCase    (				UpperCAmelCase__					:   List[str]=2      ,					UpperCAmelCase__					:   List[Any]=3      ,					UpperCAmelCase__					:   Any=1_6      ,					UpperCAmelCase__					:   int = 1_0      ,					UpperCAmelCase__					:   int = 2							)	->     Union[str, Any]:

							def get_dataset(UpperCAmelCase__					:   int							):
														lowerCamelCase_					=       torch.randn(batch_size * n_batches      ,					1							)
														return TensorDataset(UpperCAmelCase__      ,					a * x + b + 0.1 * torch.randn(batch_size * n_batches      ,					1							)							)

							lowerCamelCase_					=       get_dataset(UpperCAmelCase__							)
							lowerCamelCase_					=       get_dataset(UpperCAmelCase__							)
							lowerCamelCase_					=       DataLoader(UpperCAmelCase__      ,					shuffle=UpperCAmelCase__      ,					batch_size=UpperCAmelCase__      ,					num_workers=4							)
							lowerCamelCase_					=       DataLoader(UpperCAmelCase__      ,					shuffle=UpperCAmelCase__      ,					batch_size=UpperCAmelCase__      ,					num_workers=4							)
							return (train_dataloader, valid_dataloader)



def   __lowerCAmelCase    (				UpperCAmelCase__					:   List[Any]      ,					UpperCAmelCase__					:   List[str]      ,					UpperCAmelCase__					:   Optional[int]      ,					UpperCAmelCase__					:   Dict      ,					UpperCAmelCase__					:   List[Any]      ,					UpperCAmelCase__					:   List[Any]=None							)	->     Any:
							lowerCamelCase_					=       []
							for epoch in range(UpperCAmelCase__							):
														# Train quickly
														model.train()
														for batch in dataloader:
																					lowerCamelCase_	, lowerCamelCase_					=       batch
																					lowerCamelCase_					=       model(UpperCAmelCase__							)
																					lowerCamelCase_					=       torch.nn.functional.mse_loss(UpperCAmelCase__      ,					UpperCAmelCase__							)
																					accelerator.backward(UpperCAmelCase__							)
																					optimizer.step()
																					optimizer.zero_grad()
														rands.append(random.random()							)  # Introduce some randomness
														if scheduler is not None:
																					scheduler.step()
							return rands





class    __A(					nn.Module							):

					def __init__(						self       :  Union[str, Any] ):
												super().__init__()
												lowerCamelCase_					=       nn.Parameter(torch.randn(1 ) )
												lowerCamelCase_					=       nn.Parameter(torch.randn(1 ) )



					def  lowercase__   (						self       :  str ,       __UpperCamelCase       :  Union[str, Any] ):
												return x * self.a + self.b





class    __A(					unittest.TestCase							):

					def  lowercase__   (						self       :  str ):
												with tempfile.TemporaryDirectory() as tmpdir:
																			set_seed(4_2 )
																			lowerCamelCase_					=       DummyModel()
																			lowerCamelCase_					=       torch.optim.Adam(params=model.parameters() ,       lr=1E-3 )
																			lowerCamelCase_	, lowerCamelCase_					=       dummy_dataloaders()
																			lowerCamelCase_					=       ProjectConfiguration(total_limit=1 ,       project_dir=__UpperCamelCase ,       automatic_checkpoint_naming=__UpperCamelCase )
																			# Train baseline
																			lowerCamelCase_					=       Accelerator(project_config=__UpperCamelCase )
																			lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_					=       accelerator.prepare(
																			    __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			# Save initial
																			accelerator.save_state()

																			# Save second state
																			accelerator.save_state()
																			self.assertEqual(len(os.listdir(accelerator.project_dir ) ) ,       1 )

					def  lowercase__   (						self       :  int ):
												with tempfile.TemporaryDirectory() as tmpdir:
																			set_seed(4_2 )
																			lowerCamelCase_					=       DummyModel()
																			lowerCamelCase_					=       torch.optim.Adam(params=model.parameters() ,       lr=1E-3 )
																			lowerCamelCase_	, lowerCamelCase_					=       dummy_dataloaders()
																			# Train baseline
																			lowerCamelCase_					=       Accelerator()
																			lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_					=       accelerator.prepare(
																			    __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			# Save initial
																			lowerCamelCase_					=       os.path.join(__UpperCamelCase ,       """initial""" )
																			accelerator.save_state(__UpperCamelCase )
																			((lowerCamelCase_)	, (lowerCamelCase_))					=       model.a.item(), model.b.item()
																			lowerCamelCase_					=       optimizer.state_dict()
																			lowerCamelCase_					=       train(3 ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			((lowerCamelCase_)	, (lowerCamelCase_))					=       model.a.item(), model.b.item()
																			lowerCamelCase_					=       optimizer.state_dict()

																			# Train partially
																			set_seed(4_2 )
																			lowerCamelCase_					=       DummyModel()
																			lowerCamelCase_					=       torch.optim.Adam(params=model.parameters() ,       lr=1E-3 )
																			lowerCamelCase_	, lowerCamelCase_					=       dummy_dataloaders()
																			lowerCamelCase_					=       Accelerator()
																			lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_					=       accelerator.prepare(
																			    __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			accelerator.load_state(__UpperCamelCase )
																			((lowerCamelCase_)	, (lowerCamelCase_))					=       model.a.item(), model.b.item()
																			lowerCamelCase_					=       optimizer.state_dict()
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )

																			lowerCamelCase_					=       train(2 ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			# Save everything
																			lowerCamelCase_					=       os.path.join(__UpperCamelCase ,       """checkpoint""" )
																			accelerator.save_state(__UpperCamelCase )

																			# Load everything back in and make sure all states work
																			accelerator.load_state(__UpperCamelCase )
																			test_rands += train(1 ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			((lowerCamelCase_)	, (lowerCamelCase_))					=       model.a.item(), model.b.item()
																			lowerCamelCase_					=       optimizer.state_dict()
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )

					def  lowercase__   (						self       :  Optional[Any] ):
												with tempfile.TemporaryDirectory() as tmpdir:
																			set_seed(4_2 )
																			lowerCamelCase_					=       DummyModel()
																			lowerCamelCase_					=       torch.optim.Adam(params=model.parameters() ,       lr=1E-3 )
																			lowerCamelCase_	, lowerCamelCase_					=       dummy_dataloaders()
																			lowerCamelCase_					=       ProjectConfiguration(automatic_checkpoint_naming=__UpperCamelCase )

																			# Train baseline
																			lowerCamelCase_					=       Accelerator(project_dir=__UpperCamelCase ,       project_config=__UpperCamelCase )
																			lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_					=       accelerator.prepare(
																			    __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			# Save initial
																			accelerator.save_state()
																			((lowerCamelCase_)	, (lowerCamelCase_))					=       model.a.item(), model.b.item()
																			lowerCamelCase_					=       optimizer.state_dict()
																			lowerCamelCase_					=       train(3 ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			((lowerCamelCase_)	, (lowerCamelCase_))					=       model.a.item(), model.b.item()
																			lowerCamelCase_					=       optimizer.state_dict()

																			# Train partially
																			set_seed(4_2 )
																			lowerCamelCase_					=       DummyModel()
																			lowerCamelCase_					=       torch.optim.Adam(params=model.parameters() ,       lr=1E-3 )
																			lowerCamelCase_	, lowerCamelCase_					=       dummy_dataloaders()
																			lowerCamelCase_					=       ProjectConfiguration(iteration=1 ,       automatic_checkpoint_naming=__UpperCamelCase )
																			lowerCamelCase_					=       Accelerator(project_dir=__UpperCamelCase ,       project_config=__UpperCamelCase )
																			lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_					=       accelerator.prepare(
																			    __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			accelerator.load_state(os.path.join(__UpperCamelCase ,       """checkpoints""" ,       """checkpoint_0""" ) )
																			((lowerCamelCase_)	, (lowerCamelCase_))					=       model.a.item(), model.b.item()
																			lowerCamelCase_					=       optimizer.state_dict()
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )

																			lowerCamelCase_					=       train(2 ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			# Save everything
																			accelerator.save_state()

																			# Load everything back in and make sure all states work
																			accelerator.load_state(os.path.join(__UpperCamelCase ,       """checkpoints""" ,       """checkpoint_1""" ) )
																			test_rands += train(1 ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			((lowerCamelCase_)	, (lowerCamelCase_))					=       model.a.item(), model.b.item()
																			lowerCamelCase_					=       optimizer.state_dict()
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )
																			self.assertEqual(__UpperCamelCase ,       __UpperCamelCase )

					def  lowercase__   (						self       :  Tuple ):
												lowerCamelCase_					=       torch.tensor([1, 2, 3] )
												lowerCamelCase_					=       torch.tensor([2, 3, 4] )
												lowerCamelCase_					=       DummyModel()
												lowerCamelCase_					=       torch.optim.Adam(net.parameters() )
												lowerCamelCase_					=       Accelerator()
												with self.assertRaises(__UpperCamelCase ) as ve:
																			accelerator.register_for_checkpointing(__UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
												lowerCamelCase_					=       str(ve.exception )
												self.assertTrue("""Item at index 0""" in message )
												self.assertTrue("""Item at index 1""" in message )
												self.assertFalse("""Item at index 2""" in message )
												self.assertFalse("""Item at index 3""" in message )

					def  lowercase__   (						self       :  List[Any] ):
												with tempfile.TemporaryDirectory() as tmpdir:
																			set_seed(4_2 )
																			lowerCamelCase_					=       DummyModel()
																			lowerCamelCase_					=       torch.optim.Adam(params=model.parameters() ,       lr=1E-3 )
																			lowerCamelCase_					=       torch.optim.lr_scheduler.StepLR(__UpperCamelCase ,       step_size=1 ,       gamma=0.99 )
																			lowerCamelCase_	, lowerCamelCase_					=       dummy_dataloaders()
																			lowerCamelCase_					=       ProjectConfiguration(automatic_checkpoint_naming=__UpperCamelCase )
																			# Train baseline
																			lowerCamelCase_					=       Accelerator(project_dir=__UpperCamelCase ,       project_config=__UpperCamelCase )
																			lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_	, lowerCamelCase_					=       accelerator.prepare(
																			    __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			# Save initial
																			accelerator.save_state()
																			lowerCamelCase_					=       scheduler.state_dict()
																			train(3 ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase ,       __UpperCamelCase )
																			self.assertNotEqual(__UpperCamelCase ,       scheduler.state_dict() )

																			# Load everything back in and make sure all states work
																			accelerator.load_state(os.path.join(__UpperCamelCase ,       """checkpoints""" ,       """checkpoint_0""" ) )
																			self.assertEqual(__UpperCamelCase ,       scheduler.state_dict() )

					def  lowercase__   (						self       :  Any ):
												with tempfile.TemporaryDirectory() as tmpdir:
																			set_seed(4_2 )
																			lowerCamelCase_					=       DummyModel()
																			lowerCamelCase_					=       ProjectConfiguration(automatic_checkpoint_naming=__UpperCamelCase ,       total_limit=2 )
																			# Train baseline
																			lowerCamelCase_					=       Accelerator(project_dir=__UpperCamelCase ,       project_config=__UpperCamelCase )
																			lowerCamelCase_					=       accelerator.prepare(__UpperCamelCase )
																			# Save 3 states:
																			for _ in range(1_1 ):
																										accelerator.save_state()
																			self.assertTrue(not os.path.exists(os.path.join(__UpperCamelCase ,       """checkpoints""" ,       """checkpoint_0""" ) ) )
																			self.assertTrue(os.path.exists(os.path.join(__UpperCamelCase ,       """checkpoints""" ,       """checkpoint_9""" ) ) )
																			self.assertTrue(os.path.exists(os.path.join(__UpperCamelCase ,       """checkpoints""" ,       """checkpoint_10""" ) ) )



					@require_cuda
					def  lowercase__   (						self       :  Union[str, Any] ):
												lowerCamelCase_					=       ["""torchrun""", F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )]
												execute_subprocess_async(__UpperCamelCase ,       env=os.environ.copy() )


if __name__ == "__main__":
		lowercase   =	'''/tmp/accelerate/state_checkpointing'''
		lowercase   =	DummyModel()
		lowercase   =	torch.optim.Adam(params=model.parameters(), lr=1E-3)
		lowercase   =	torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
		lowercase ,    lowercase   =	dummy_dataloaders()
		lowercase   =	ProjectConfiguration(automatic_checkpoint_naming=True)
		# Train baseline
		lowercase   =	Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='''no''')
		if accelerator.process_index == 0:
				if os.path.exists(savedir):
						shutil.rmtree(savedir)
				os.makedirs(savedir)
		lowercase ,    lowercase ,    lowercase ,    lowercase ,    lowercase   =	accelerator.prepare(
		    model, optimizer, train_dataloader, valid_dataloader, scheduler
		)
		lowercase ,    lowercase   =	accelerator.prepare(model, optimizer)
		train(3, model, train_dataloader, optimizer, accelerator, scheduler)
		# Check that the intial optimizer is loaded on the GPU
		for group in optimizer.param_groups:
				lowercase   =	group['''params'''][0].device
				break
		assert param_device.type == accelerator.device.type
		lowercase   =	model.cpu()
		accelerator.wait_for_everyone()
		accelerator.save_state()
		accelerator.wait_for_everyone()

		# Check CPU state
		accelerator.load_state(os.path.join(savedir, '''checkpoints''', '''checkpoint_0'''), map_location='''cpu''')
		for group in optimizer.param_groups:
				lowercase   =	group['''params'''][0].device
				break
		assert (
		    param_device.type == torch.device('''cpu''').type
		), F"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"

		# Check device state
		model.to(accelerator.device)
		accelerator.load_state(os.path.join(savedir, '''checkpoints''', '''checkpoint_0'''), map_location='''on_device''')
		for group in optimizer.param_groups:
				lowercase   =	group['''params'''][0].device
				break
		assert (
		    param_device.type == accelerator.device.type
		), F"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"

		# Check error
		with pytest.raises(TypeError, match='''Unsupported optimizer map location passed'''):
				accelerator.load_state(os.path.join(savedir, '''checkpoints''', '''checkpoint_0'''), map_location='''invalid''')
		accelerator.wait_for_everyone()
		if accelerator.process_index == 0:
				shutil.rmtree(savedir)
		accelerator.wait_for_everyone()







from __future__ import annotations

import unittest

from transformers import DebertaVaConfig, 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 (
		    TFDebertaVaForMaskedLM,
		    TFDebertaVaForQuestionAnswering,
		    TFDebertaVaForSequenceClassification,
		    TFDebertaVaForTokenClassification,
		    TFDebertaVaModel,
		)





class    __A:

					def __init__(						self       :  List[Any] ,       __UpperCamelCase       :  Tuple ,       __UpperCamelCase       :  Any=1_3 ,       __UpperCamelCase       :  Optional[int]=7 ,       __UpperCamelCase       :  Any=True ,       __UpperCamelCase       :  Dict=True ,       __UpperCamelCase       :  Optional[Any]=True ,       __UpperCamelCase       :  Dict=True ,       __UpperCamelCase       :  Union[str, Any]=9_9 ,       __UpperCamelCase       :  List[str]=3_2 ,       __UpperCamelCase       :  int=2 ,       __UpperCamelCase       :  Optional[Any]=4 ,       __UpperCamelCase       :  Optional[int]=3_7 ,       __UpperCamelCase       :  Optional[Any]="gelu" ,       __UpperCamelCase       :  int=0.1 ,       __UpperCamelCase       :  str=0.1 ,       __UpperCamelCase       :  Tuple=5_1_2 ,       __UpperCamelCase       :  Any=1_6 ,       __UpperCamelCase       :  Dict=2 ,       __UpperCamelCase       :  Optional[Any]=0.02 ,       __UpperCamelCase       :  Optional[Any]=False ,       __UpperCamelCase       :  Dict=True ,       __UpperCamelCase       :  Any="None" ,       __UpperCamelCase       :  List[Any]=3 ,       __UpperCamelCase       :  Optional[int]=4 ,       __UpperCamelCase       :  Dict=None ,       ):
												lowerCamelCase_					=       parent
												lowerCamelCase_					=       batch_size
												lowerCamelCase_					=       seq_length
												lowerCamelCase_					=       is_training
												lowerCamelCase_					=       use_input_mask
												lowerCamelCase_					=       use_token_type_ids
												lowerCamelCase_					=       use_labels
												lowerCamelCase_					=       vocab_size
												lowerCamelCase_					=       hidden_size
												lowerCamelCase_					=       num_hidden_layers
												lowerCamelCase_					=       num_attention_heads
												lowerCamelCase_					=       intermediate_size
												lowerCamelCase_					=       hidden_act
												lowerCamelCase_					=       hidden_dropout_prob
												lowerCamelCase_					=       attention_probs_dropout_prob
												lowerCamelCase_					=       max_position_embeddings
												lowerCamelCase_					=       type_vocab_size
												lowerCamelCase_					=       type_sequence_label_size
												lowerCamelCase_					=       initializer_range
												lowerCamelCase_					=       num_labels
												lowerCamelCase_					=       num_choices
												lowerCamelCase_					=       relative_attention
												lowerCamelCase_					=       position_biased_input
												lowerCamelCase_					=       pos_att_type
												lowerCamelCase_					=       scope

					def  lowercase__   (						self       :  Optional[Any] ):
												lowerCamelCase_					=       ids_tensor([self.batch_size, self.seq_length] ,       self.vocab_size )

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

												lowerCamelCase_					=       None
												if self.use_token_type_ids:
																			lowerCamelCase_					=       ids_tensor([self.batch_size, self.seq_length] ,       self.type_vocab_size )

												lowerCamelCase_					=       None
												lowerCamelCase_					=       None
												lowerCamelCase_					=       None
												if self.use_labels:
																			lowerCamelCase_					=       ids_tensor([self.batch_size] ,       self.type_sequence_label_size )
																			lowerCamelCase_					=       ids_tensor([self.batch_size, self.seq_length] ,       self.num_labels )

												lowerCamelCase_					=       DebertaVaConfig(
												    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 ,       relative_attention=self.relative_attention ,       position_biased_input=self.position_biased_input ,       initializer_range=self.initializer_range ,       return_dict=__UpperCamelCase ,       )

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

					def  lowercase__   (						self       :  str ,       __UpperCamelCase       :  Union[str, Any] ,       __UpperCamelCase       :  Optional[int] ,       __UpperCamelCase       :  Optional[Any] ,       __UpperCamelCase       :  Optional[int] ,       __UpperCamelCase       :  Any ,       __UpperCamelCase       :  int ,       __UpperCamelCase       :  List[str] ):
												lowerCamelCase_					=       TFDebertaVaModel(config=__UpperCamelCase )
												lowerCamelCase_					=       {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}

												lowerCamelCase_					=       [input_ids, input_mask]
												lowerCamelCase_					=       model(__UpperCamelCase )

												lowerCamelCase_					=       model(__UpperCamelCase )

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

					def  lowercase__   (						self       :  Optional[int] ,       __UpperCamelCase       :  List[str] ,       __UpperCamelCase       :  str ,       __UpperCamelCase       :  Dict ,       __UpperCamelCase       :  str ,       __UpperCamelCase       :  List[str] ,       __UpperCamelCase       :  Tuple ,       __UpperCamelCase       :  int ):
												lowerCamelCase_					=       TFDebertaVaForMaskedLM(config=__UpperCamelCase )
												lowerCamelCase_					=       {
												    """input_ids""": input_ids,
												    """attention_mask""": input_mask,
												    """token_type_ids""": token_type_ids,
												}
												lowerCamelCase_					=       model(__UpperCamelCase )
												self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.seq_length, self.vocab_size) )

					def  lowercase__   (						self       :  List[Any] ,       __UpperCamelCase       :  Union[str, Any] ,       __UpperCamelCase       :  str ,       __UpperCamelCase       :  int ,       __UpperCamelCase       :  Optional[int] ,       __UpperCamelCase       :  List[Any] ,       __UpperCamelCase       :  str ,       __UpperCamelCase       :  List[Any] ):
												lowerCamelCase_					=       self.num_labels
												lowerCamelCase_					=       TFDebertaVaForSequenceClassification(config=__UpperCamelCase )
												lowerCamelCase_					=       {
												    """input_ids""": input_ids,
												    """attention_mask""": input_mask,
												    """token_type_ids""": token_type_ids,
												}

												lowerCamelCase_					=       model(__UpperCamelCase )
												self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_labels) )

					def  lowercase__   (						self       :  int ,       __UpperCamelCase       :  Tuple ,       __UpperCamelCase       :  Any ,       __UpperCamelCase       :  str ,       __UpperCamelCase       :  Optional[int] ,       __UpperCamelCase       :  List[str] ,       __UpperCamelCase       :  List[Any] ,       __UpperCamelCase       :  List[Any] ):
												lowerCamelCase_					=       self.num_labels
												lowerCamelCase_					=       TFDebertaVaForTokenClassification(config=__UpperCamelCase )
												lowerCamelCase_					=       {
												    """input_ids""": input_ids,
												    """attention_mask""": input_mask,
												    """token_type_ids""": token_type_ids,
												}
												lowerCamelCase_					=       model(__UpperCamelCase )
												self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.seq_length, self.num_labels) )

					def  lowercase__   (						self       :  List[Any] ,       __UpperCamelCase       :  Optional[int] ,       __UpperCamelCase       :  Optional[Any] ,       __UpperCamelCase       :  Optional[int] ,       __UpperCamelCase       :  str ,       __UpperCamelCase       :  Optional[Any] ,       __UpperCamelCase       :  List[str] ,       __UpperCamelCase       :  int ):
												lowerCamelCase_					=       TFDebertaVaForQuestionAnswering(config=__UpperCamelCase )
												lowerCamelCase_					=       {
												    """input_ids""": input_ids,
												    """attention_mask""": input_mask,
												    """token_type_ids""": token_type_ids,
												}

												lowerCamelCase_					=       model(__UpperCamelCase )
												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  lowercase__   (						self       :  Dict ):
												lowerCamelCase_					=       self.prepare_config_and_inputs()
												(
												    (
												    lowerCamelCase_
												)	, (
												    lowerCamelCase_
												)	, (
												    lowerCamelCase_
												)	, (
												    lowerCamelCase_
												)	, (
												    lowerCamelCase_
												)	, (
												    lowerCamelCase_
												)	, (
												    lowerCamelCase_
												)	, 
												)					=       config_and_inputs
												lowerCamelCase_					=       {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
												return config, inputs_dict





@require_tf
class    __A(					UpperCAmelCase  ,		UpperCAmelCase  ,		unittest.TestCase							):
					SCREAMING_SNAKE_CASE           =     (
					    (
					        TFDebertaVaModel,
					        TFDebertaVaForMaskedLM,
					        TFDebertaVaForQuestionAnswering,
					        TFDebertaVaForSequenceClassification,
					        TFDebertaVaForTokenClassification,
					    )
					    if is_tf_available()
					    else ()
					)
					SCREAMING_SNAKE_CASE           =     (
					    {
					        '''feature-extraction''': TFDebertaVaModel,
					        '''fill-mask''': TFDebertaVaForMaskedLM,
					        '''question-answering''': TFDebertaVaForQuestionAnswering,
					        '''text-classification''': TFDebertaVaForSequenceClassification,
					        '''token-classification''': TFDebertaVaForTokenClassification,
					        '''zero-shot''': TFDebertaVaForSequenceClassification,
					    }
					    if is_tf_available()
					    else {}
					)

					SCREAMING_SNAKE_CASE           =     False
					SCREAMING_SNAKE_CASE           =     False

					def  lowercase__   (						self       :  Dict ):
												lowerCamelCase_					=       TFDebertaVaModelTester(self )
												lowerCamelCase_					=       ConfigTester(self ,       config_class=__UpperCamelCase ,       hidden_size=3_7 )

					def  lowercase__   (						self       :  Dict ):
												self.config_tester.run_common_tests()

					def  lowercase__   (						self       :  Optional[Any] ):
												lowerCamelCase_					=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__UpperCamelCase )

					def  lowercase__   (						self       :  Dict ):
												lowerCamelCase_					=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_lm(*__UpperCamelCase )

					def  lowercase__   (						self       :  List[Any] ):
												lowerCamelCase_					=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_question_answering(*__UpperCamelCase )

					def  lowercase__   (						self       :  Tuple ):
												lowerCamelCase_					=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_sequence_classification(*__UpperCamelCase )

					def  lowercase__   (						self       :  Any ):
												lowerCamelCase_					=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_token_classification(*__UpperCamelCase )



					@slow
					def  lowercase__   (						self       :  int ):
												lowerCamelCase_					=       TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge""" )
												self.assertIsNotNone(__UpperCamelCase )





@require_tf
class    __A(					unittest.TestCase							):

					@unittest.skip(reason="""Model not available yet""" )
					def  lowercase__   (						self       :  Optional[int] ):
												pass



					@slow
					def  lowercase__   (						self       :  Any ):
												lowerCamelCase_					=       TFDebertaVaModel.from_pretrained("""kamalkraj/deberta-v2-xlarge""" )
												lowerCamelCase_					=       tf.constant([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] )
												lowerCamelCase_					=       tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
												lowerCamelCase_					=       model(__UpperCamelCase ,       attention_mask=__UpperCamelCase )[0]

												lowerCamelCase_					=       tf.constant(
												    [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] )
												tf.debugging.assert_near(output[:, 1:4, 1:4] ,       __UpperCamelCase ,       atol=1E-4 )





