


'''simple docstring'''



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


__UpperCAmelCase      :Optional[Any]			    =       logging.getLogger(__name__)




def      _a     (						_lowercase :     Optional[int]=2      , _lowercase :     List[Any]=3      , _lowercase :     List[str]=16      , _lowercase :     int = 10      , _lowercase :     int = 2  ):





     '''simple docstring'''






     def get_dataset(_lowercase :     Union[str, Any]  ):
          __UpperCAmelCase     :			int  							=      torch.randn(batch_size * n_batches      , 1  )
          return TensorDataset(_lowercase      , a * x + b + 0.1 * torch.randn(batch_size * n_batches      , 1  )  )

     __UpperCAmelCase     :			Dict  							=      get_dataset(_lowercase  )
     __UpperCAmelCase     :			List[Any]  							=      get_dataset(_lowercase  )
     __UpperCAmelCase     :			Dict  							=      DataLoader(_lowercase      , shuffle=_lowercase      , batch_size=_lowercase      , num_workers=4  )
     __UpperCAmelCase     :			Any  							=      DataLoader(_lowercase      , shuffle=_lowercase      , batch_size=_lowercase      , num_workers=4  )
     return (train_dataloader, valid_dataloader)




def      _a     (						_lowercase :     Union[str, Any]      , _lowercase :     int      , _lowercase :     Any      , _lowercase :     str      , _lowercase :     Tuple      , _lowercase :     List[Any]=None  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Optional[int]  							=      []
     for epoch in range(_lowercase  ):
          # Train quickly
          model.train()
          for batch in dataloader:
               __UpperCAmelCase     :			int  							=      batch
               __UpperCAmelCase     :			Optional[Any]  							=      model(_lowercase  )
               __UpperCAmelCase     :			Any  							=      torch.nn.functional.mse_loss(_lowercase      , _lowercase  )
               accelerator.backward(_lowercase  )
               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	):


     """simple docstring"""






     def __init__(    self					:		List[Any]      )						->							int:
          super().__init__()
          __UpperCAmelCase     :			int  							=      nn.Parameter(torch.randn(1      )      )
          __UpperCAmelCase     :			Union[str, Any]  							=      nn.Parameter(torch.randn(1      )      )






     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		str      )						->							Dict:
          return x * self.a + self.b



class      a    (		unittest.TestCase	):


     """simple docstring"""






     def 			lowerCamelCase__			(    self					:		Any      )						->							str:
          with tempfile.TemporaryDirectory() as tmpdir:
               set_seed(42      )
               __UpperCAmelCase     :			Optional[int]  							=      DummyModel()
               __UpperCAmelCase     :			Optional[Any]  							=      torch.optim.Adam(params=model.parameters()							,			lr=1E-3      )
               __UpperCAmelCase     :			List[str]  							=      dummy_dataloaders()
               __UpperCAmelCase     :			Any  							=      ProjectConfiguration(total_limit=1							,			project_dir=snake_case							,			automatic_checkpoint_naming=snake_case      )
               # Train baseline
               __UpperCAmelCase     :			str  							=      Accelerator(project_config=snake_case      )
               __UpperCAmelCase     :			Optional[int]  							=      accelerator.prepare(
                   snake_case							,			snake_case							,			snake_case							,			snake_case      )
               # Save initial
               accelerator.save_state()

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

     def 			lowerCamelCase__			(    self					:		List[str]      )						->							str:
          with tempfile.TemporaryDirectory() as tmpdir:
               set_seed(42      )
               __UpperCAmelCase     :			Any  							=      DummyModel()
               __UpperCAmelCase     :			List[Any]  							=      torch.optim.Adam(params=model.parameters()							,			lr=1E-3      )
               __UpperCAmelCase     :			Tuple  							=      dummy_dataloaders()
               # Train baseline
               __UpperCAmelCase     :			Dict  							=      Accelerator()
               __UpperCAmelCase     :			int  							=      accelerator.prepare(
                   snake_case							,			snake_case							,			snake_case							,			snake_case      )
               # Save initial
               __UpperCAmelCase     :			Dict  							=      os.path.join(snake_case							,			'''initial'''      )
               accelerator.save_state(snake_case      )
               (__UpperCAmelCase)     :			Optional[Any]  							=      model.a.item(), model.b.item()
               __UpperCAmelCase     :			Any  							=      optimizer.state_dict()
               __UpperCAmelCase     :			Dict  							=      train(3							,			snake_case							,			snake_case							,			snake_case							,			snake_case      )
               (__UpperCAmelCase)     :			str  							=      model.a.item(), model.b.item()
               __UpperCAmelCase     :			Dict  							=      optimizer.state_dict()

               # Train partially
               set_seed(42      )
               __UpperCAmelCase     :			List[Any]  							=      DummyModel()
               __UpperCAmelCase     :			List[Any]  							=      torch.optim.Adam(params=model.parameters()							,			lr=1E-3      )
               __UpperCAmelCase     :			Optional[Any]  							=      dummy_dataloaders()
               __UpperCAmelCase     :			List[Any]  							=      Accelerator()
               __UpperCAmelCase     :			List[Any]  							=      accelerator.prepare(
                   snake_case							,			snake_case							,			snake_case							,			snake_case      )
               accelerator.load_state(snake_case      )
               (__UpperCAmelCase)     :			Optional[int]  							=      model.a.item(), model.b.item()
               __UpperCAmelCase     :			Union[str, Any]  							=      optimizer.state_dict()
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )

               __UpperCAmelCase     :			str  							=      train(2							,			snake_case							,			snake_case							,			snake_case							,			snake_case      )
               # Save everything
               __UpperCAmelCase     :			Any  							=      os.path.join(snake_case							,			'''checkpoint'''      )
               accelerator.save_state(snake_case      )

               # Load everything back in and make sure all states work
               accelerator.load_state(snake_case      )
               test_rands += train(1							,			snake_case							,			snake_case							,			snake_case							,			snake_case      )
               (__UpperCAmelCase)     :			Optional[Any]  							=      model.a.item(), model.b.item()
               __UpperCAmelCase     :			Any  							=      optimizer.state_dict()
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )

     def 			lowerCamelCase__			(    self					:		str      )						->							str:
          with tempfile.TemporaryDirectory() as tmpdir:
               set_seed(42      )
               __UpperCAmelCase     :			List[str]  							=      DummyModel()
               __UpperCAmelCase     :			Optional[int]  							=      torch.optim.Adam(params=model.parameters()							,			lr=1E-3      )
               __UpperCAmelCase     :			Tuple  							=      dummy_dataloaders()
               __UpperCAmelCase     :			List[str]  							=      ProjectConfiguration(automatic_checkpoint_naming=snake_case      )

               # Train baseline
               __UpperCAmelCase     :			Optional[Any]  							=      Accelerator(project_dir=snake_case							,			project_config=snake_case      )
               __UpperCAmelCase     :			Tuple  							=      accelerator.prepare(
                   snake_case							,			snake_case							,			snake_case							,			snake_case      )
               # Save initial
               accelerator.save_state()
               (__UpperCAmelCase)     :			Tuple  							=      model.a.item(), model.b.item()
               __UpperCAmelCase     :			List[str]  							=      optimizer.state_dict()
               __UpperCAmelCase     :			List[Any]  							=      train(3							,			snake_case							,			snake_case							,			snake_case							,			snake_case      )
               (__UpperCAmelCase)     :			Any  							=      model.a.item(), model.b.item()
               __UpperCAmelCase     :			Tuple  							=      optimizer.state_dict()

               # Train partially
               set_seed(42      )
               __UpperCAmelCase     :			Optional[Any]  							=      DummyModel()
               __UpperCAmelCase     :			int  							=      torch.optim.Adam(params=model.parameters()							,			lr=1E-3      )
               __UpperCAmelCase     :			str  							=      dummy_dataloaders()
               __UpperCAmelCase     :			Any  							=      ProjectConfiguration(iteration=1							,			automatic_checkpoint_naming=snake_case      )
               __UpperCAmelCase     :			List[Any]  							=      Accelerator(project_dir=snake_case							,			project_config=snake_case      )
               __UpperCAmelCase     :			Union[str, Any]  							=      accelerator.prepare(
                   snake_case							,			snake_case							,			snake_case							,			snake_case      )
               accelerator.load_state(os.path.join(snake_case							,			'''checkpoints'''							,			'''checkpoint_0'''      )      )
               (__UpperCAmelCase)     :			int  							=      model.a.item(), model.b.item()
               __UpperCAmelCase     :			Optional[Any]  							=      optimizer.state_dict()
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )

               __UpperCAmelCase     :			Any  							=      train(2							,			snake_case							,			snake_case							,			snake_case							,			snake_case      )
               # Save everything
               accelerator.save_state()

               # Load everything back in and make sure all states work
               accelerator.load_state(os.path.join(snake_case							,			'''checkpoints'''							,			'''checkpoint_1'''      )      )
               test_rands += train(1							,			snake_case							,			snake_case							,			snake_case							,			snake_case      )
               (__UpperCAmelCase)     :			str  							=      model.a.item(), model.b.item()
               __UpperCAmelCase     :			Any  							=      optimizer.state_dict()
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )
               self.assertEqual(snake_case							,			snake_case      )

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							int:
          __UpperCAmelCase     :			str  							=      torch.tensor([1, 2, 3]      )
          __UpperCAmelCase     :			Union[str, Any]  							=      torch.tensor([2, 3, 4]      )
          __UpperCAmelCase     :			List[Any]  							=      DummyModel()
          __UpperCAmelCase     :			List[str]  							=      torch.optim.Adam(net.parameters()      )
          __UpperCAmelCase     :			Tuple  							=      Accelerator()
          with self.assertRaises(snake_case      ) as ve:
               accelerator.register_for_checkpointing(snake_case							,			snake_case							,			snake_case							,			snake_case      )
          __UpperCAmelCase     :			Tuple  							=      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 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Optional[int]:
          with tempfile.TemporaryDirectory() as tmpdir:
               set_seed(42      )
               __UpperCAmelCase     :			Union[str, Any]  							=      DummyModel()
               __UpperCAmelCase     :			List[str]  							=      torch.optim.Adam(params=model.parameters()							,			lr=1E-3      )
               __UpperCAmelCase     :			Any  							=      torch.optim.lr_scheduler.StepLR(snake_case							,			step_size=1							,			gamma=0.99      )
               __UpperCAmelCase     :			List[Any]  							=      dummy_dataloaders()
               __UpperCAmelCase     :			Dict  							=      ProjectConfiguration(automatic_checkpoint_naming=snake_case      )
               # Train baseline
               __UpperCAmelCase     :			Any  							=      Accelerator(project_dir=snake_case							,			project_config=snake_case      )
               __UpperCAmelCase     :			Any  							=      accelerator.prepare(
                   snake_case							,			snake_case							,			snake_case							,			snake_case							,			snake_case      )
               # Save initial
               accelerator.save_state()
               __UpperCAmelCase     :			int  							=      scheduler.state_dict()
               train(3							,			snake_case							,			snake_case							,			snake_case							,			snake_case							,			snake_case      )
               self.assertNotEqual(snake_case							,			scheduler.state_dict()      )

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

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Any:
          with tempfile.TemporaryDirectory() as tmpdir:
               set_seed(42      )
               __UpperCAmelCase     :			Tuple  							=      DummyModel()
               __UpperCAmelCase     :			Tuple  							=      ProjectConfiguration(automatic_checkpoint_naming=snake_case							,			total_limit=2      )
               # Train baseline
               __UpperCAmelCase     :			Optional[Any]  							=      Accelerator(project_dir=snake_case							,			project_config=snake_case      )
               __UpperCAmelCase     :			Optional[Any]  							=      accelerator.prepare(snake_case      )
               # Save 3 states:
               for _ in range(11      ):
                    accelerator.save_state()
               self.assertTrue(not os.path.exists(os.path.join(snake_case							,			'''checkpoints'''							,			'''checkpoint_0'''      )      )      )
               self.assertTrue(os.path.exists(os.path.join(snake_case							,			'''checkpoints'''							,			'''checkpoint_9'''      )      )      )
               self.assertTrue(os.path.exists(os.path.join(snake_case							,			'''checkpoints'''							,			'''checkpoint_10'''      )      )      )






     @require_cuda
     def 			lowerCamelCase__			(    self					:		str      )						->							List[Any]:
          __UpperCAmelCase     :			int  							=      ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__      )]
          execute_subprocess_async(snake_case							,			env=os.environ.copy()      )


if __name__ == "__main__":
      __UpperCAmelCase      :Optional[Any]			    =       "/tmp/accelerate/state_checkpointing"
      __UpperCAmelCase      :Tuple			    =       DummyModel()
      __UpperCAmelCase      :Dict			    =       torch.optim.Adam(params=model.parameters(), lr=1e-3)
      __UpperCAmelCase      :Optional[Any]			    =       torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
      __UpperCAmelCase      :Any			    =       dummy_dataloaders()
      __UpperCAmelCase      :Optional[int]			    =       ProjectConfiguration(automatic_checkpoint_naming=True)
      # Train baseline
      __UpperCAmelCase      :Any			    =       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)
      __UpperCAmelCase      :Dict			    =       accelerator.prepare(
          model, optimizer, train_dataloader, valid_dataloader, scheduler
      )
      __UpperCAmelCase      :List[str]			    =       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:
            __UpperCAmelCase      :Optional[int]			    =       group["params"][0].device
            break
      assert param_device.type == accelerator.device.type
      __UpperCAmelCase      :Union[str, Any]			    =       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:
            __UpperCAmelCase      :Optional[int]			    =       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:
            __UpperCAmelCase      :Tuple			    =       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()





'''simple docstring'''



import unittest

from transformers import DebertaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          DebertaForMaskedLM,
          DebertaForQuestionAnswering,
          DebertaForSequenceClassification,
          DebertaForTokenClassification,
          DebertaModel,
      )
      from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST



class      a    (		_a	):


     """simple docstring"""






     def __init__(    self					:		Optional[Any]							,			snake_case					:		Dict							,			snake_case					:		Dict=13							,			snake_case					:		str=7							,			snake_case					:		Dict=True							,			snake_case					:		Any=True							,			snake_case					:		Optional[Any]=True							,			snake_case					:		Optional[Any]=True							,			snake_case					:		List[str]=99							,			snake_case					:		str=32							,			snake_case					:		Any=5							,			snake_case					:		List[str]=4							,			snake_case					:		List[str]=37							,			snake_case					:		int="gelu"							,			snake_case					:		int=0.1							,			snake_case					:		int=0.1							,			snake_case					:		Union[str, Any]=512							,			snake_case					:		int=16							,			snake_case					:		Optional[Any]=2							,			snake_case					:		List[Any]=0.02							,			snake_case					:		Any=False							,			snake_case					:		int=True							,			snake_case					:		Union[str, Any]="None"							,			snake_case					:		str=3							,			snake_case					:		Union[str, Any]=4							,			snake_case					:		Any=None							,			)						->							List[Any]:
          __UpperCAmelCase     :			List[str]  							=      parent
          __UpperCAmelCase     :			Dict  							=      batch_size
          __UpperCAmelCase     :			Any  							=      seq_length
          __UpperCAmelCase     :			List[Any]  							=      is_training
          __UpperCAmelCase     :			List[str]  							=      use_input_mask
          __UpperCAmelCase     :			Union[str, Any]  							=      use_token_type_ids
          __UpperCAmelCase     :			Any  							=      use_labels
          __UpperCAmelCase     :			Any  							=      vocab_size
          __UpperCAmelCase     :			Dict  							=      hidden_size
          __UpperCAmelCase     :			List[str]  							=      num_hidden_layers
          __UpperCAmelCase     :			Union[str, Any]  							=      num_attention_heads
          __UpperCAmelCase     :			List[str]  							=      intermediate_size
          __UpperCAmelCase     :			str  							=      hidden_act
          __UpperCAmelCase     :			Union[str, Any]  							=      hidden_dropout_prob
          __UpperCAmelCase     :			int  							=      attention_probs_dropout_prob
          __UpperCAmelCase     :			Tuple  							=      max_position_embeddings
          __UpperCAmelCase     :			Any  							=      type_vocab_size
          __UpperCAmelCase     :			Tuple  							=      type_sequence_label_size
          __UpperCAmelCase     :			Union[str, Any]  							=      initializer_range
          __UpperCAmelCase     :			Dict  							=      num_labels
          __UpperCAmelCase     :			Any  							=      num_choices
          __UpperCAmelCase     :			Any  							=      relative_attention
          __UpperCAmelCase     :			Dict  							=      position_biased_input
          __UpperCAmelCase     :			Optional[int]  							=      pos_att_type
          __UpperCAmelCase     :			Dict  							=      scope

     def 			lowerCamelCase__			(    self					:		Dict      )						->							Optional[int]:
          __UpperCAmelCase     :			int  							=      ids_tensor([self.batch_size, self.seq_length]							,			self.vocab_size      )

          __UpperCAmelCase     :			Optional[Any]  							=      None
          if self.use_input_mask:
               __UpperCAmelCase     :			str  							=      ids_tensor([self.batch_size, self.seq_length]							,			vocab_size=2      )

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

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

          __UpperCAmelCase     :			str  							=      self.get_config()

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

     def 			lowerCamelCase__			(    self					:		Tuple      )						->							List[str]:
          return DebertaConfig(
              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							,			relative_attention=self.relative_attention							,			position_biased_input=self.position_biased_input							,			pos_att_type=self.pos_att_type							,			)

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							str:
          __UpperCAmelCase     :			Optional[int]  							=      self.get_config()
          __UpperCAmelCase     :			Dict  							=      300
          return config

     def 			lowerCamelCase__			(    self					:		Any							,			snake_case					:		int      )						->							Any:
          self.parent.assertListEqual(list(result.loss.size()      )							,			[]      )

     def 			lowerCamelCase__			(    self					:		List[Any]							,			snake_case					:		Optional[int]							,			snake_case					:		Any							,			snake_case					:		List[Any]							,			snake_case					:		Any							,			snake_case					:		Union[str, Any]							,			snake_case					:		Optional[Any]							,			snake_case					:		Union[str, Any]      )						->							Optional[Any]:
          __UpperCAmelCase     :			List[str]  							=      DebertaModel(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			str  							=      model(snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case      )[0]
          __UpperCAmelCase     :			Tuple  							=      model(snake_case							,			token_type_ids=snake_case      )[0]
          __UpperCAmelCase     :			Optional[int]  							=      model(snake_case      )[0]

          self.parent.assertListEqual(list(sequence_output.size()      )							,			[self.batch_size, self.seq_length, self.hidden_size]      )

     def 			lowerCamelCase__			(    self					:		Optional[int]							,			snake_case					:		int							,			snake_case					:		Tuple							,			snake_case					:		Any							,			snake_case					:		Tuple							,			snake_case					:		Union[str, Any]							,			snake_case					:		Optional[int]							,			snake_case					:		List[str]      )						->							Optional[int]:
          __UpperCAmelCase     :			Union[str, Any]  							=      DebertaForMaskedLM(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			int  							=      model(snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case							,			labels=snake_case      )

          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.seq_length, self.vocab_size)      )

     def 			lowerCamelCase__			(    self					:		str							,			snake_case					:		Union[str, Any]							,			snake_case					:		Tuple							,			snake_case					:		Optional[Any]							,			snake_case					:		Tuple							,			snake_case					:		List[Any]							,			snake_case					:		str							,			snake_case					:		Tuple      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Tuple  							=      self.num_labels
          __UpperCAmelCase     :			List[Any]  							=      DebertaForSequenceClassification(snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			Any  							=      model(snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case							,			labels=snake_case      )
          self.parent.assertListEqual(list(result.logits.size()      )							,			[self.batch_size, self.num_labels]      )
          self.check_loss_output(snake_case      )

     def 			lowerCamelCase__			(    self					:		str							,			snake_case					:		List[str]							,			snake_case					:		Union[str, Any]							,			snake_case					:		List[str]							,			snake_case					:		Dict							,			snake_case					:		Optional[Any]							,			snake_case					:		Dict							,			snake_case					:		Optional[int]      )						->							int:
          __UpperCAmelCase     :			List[Any]  							=      self.num_labels
          __UpperCAmelCase     :			Union[str, Any]  							=      DebertaForTokenClassification(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			Any  							=      model(snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case							,			labels=snake_case      )
          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.seq_length, self.num_labels)      )

     def 			lowerCamelCase__			(    self					:		str							,			snake_case					:		List[Any]							,			snake_case					:		Optional[Any]							,			snake_case					:		str							,			snake_case					:		Optional[int]							,			snake_case					:		int							,			snake_case					:		int							,			snake_case					:		str      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Union[str, Any]  							=      DebertaForQuestionAnswering(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			Optional[int]  							=      model(
              snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case							,			start_positions=snake_case							,			end_positions=snake_case							,			)
          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					:		str      )						->							int:
          __UpperCAmelCase     :			int  							=      self.prepare_config_and_inputs()
          (
              (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       
          )     :			Any  							=      config_and_inputs
          __UpperCAmelCase     :			str  							=      {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
          return config, inputs_dict



@require_torch
class      a    (		_a     ,  _a     ,  unittest.TestCase	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Optional[int]							       =       (
         (
             DebertaModel,
             DebertaForMaskedLM,
             DebertaForSequenceClassification,
             DebertaForTokenClassification,
             DebertaForQuestionAnswering,
         )
         if is_torch_available()
         else ()
     )
     SCREAMING_SNAKE_CASE	:			Dict							       =       (
         {
             "feature-extraction": DebertaModel,
             "fill-mask": DebertaForMaskedLM,
             "question-answering": DebertaForQuestionAnswering,
             "text-classification": DebertaForSequenceClassification,
             "token-classification": DebertaForTokenClassification,
             "zero-shot": DebertaForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE	:			Union[str, Any]							       =       True
     SCREAMING_SNAKE_CASE	:			Dict							       =       False
     SCREAMING_SNAKE_CASE	:			List[Any]							       =       False
     SCREAMING_SNAKE_CASE	:			List[str]							       =       False
     SCREAMING_SNAKE_CASE	:			Any							       =       False

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Dict  							=      DebertaModelTester(self      )
          __UpperCAmelCase     :			List[Any]  							=      ConfigTester(self							,			config_class=snake_case							,			hidden_size=37      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Dict:
          self.config_tester.run_common_tests()

     def 			lowerCamelCase__			(    self					:		List[str]      )						->							Optional[Any]:
          __UpperCAmelCase     :			Any  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_model(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Dict      )						->							List[str]:
          __UpperCAmelCase     :			Tuple  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_sequence_classification(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Dict      )						->							str:
          __UpperCAmelCase     :			Any  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_masked_lm(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Any:
          __UpperCAmelCase     :			Optional[int]  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_question_answering(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Dict      )						->							Optional[Any]:
          __UpperCAmelCase     :			Any  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_token_classification(*snake_case      )






     @slow
     def 			lowerCamelCase__			(    self					:		Dict      )						->							Tuple:
          for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCAmelCase     :			str  							=      DebertaModel.from_pretrained(snake_case      )
               self.assertIsNotNone(snake_case      )



@require_torch
@require_sentencepiece
@require_tokenizers
class      a    (		unittest.TestCase	):


     """simple docstring"""






     @unittest.skip(reason='''Model not available yet'''      )
     def 			lowerCamelCase__			(    self					:		Dict      )						->							Tuple:
          pass






     @slow
     def 			lowerCamelCase__			(    self					:		int      )						->							Optional[Any]:
          __UpperCAmelCase     :			Any  							=      DebertaModel.from_pretrained('''microsoft/deberta-base'''      )

          __UpperCAmelCase     :			Any  							=      torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]      )
          __UpperCAmelCase     :			Dict  							=      torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]      )
          with torch.no_grad():
               __UpperCAmelCase     :			int  							=      model(snake_case							,			attention_mask=snake_case      )[0]
          # compare the actual values for a slice.
          __UpperCAmelCase     :			Optional[Any]  							=      torch.tensor(
              [[[-0.5_986, -0.8_055, -0.8_462], [1.4_484, -0.9_348, -0.8_059], [0.3_123, 0.0_032, -1.4_131]]]      )
          self.assertTrue(torch.allclose(output[:, 1:4, 1:4]							,			snake_case							,			atol=1E-4      )							,			f'{output[:, 1:4, 1:4]}'      )