





import unittest

from transformers import DebertaVaConfig, 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 (
        DebertaVaForMaskedLM,
        DebertaVaForMultipleChoice,
        DebertaVaForQuestionAnswering,
        DebertaVaForSequenceClassification,
        DebertaVaForTokenClassification,
        DebertaVaModel,
    )
    from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST

class     snake_case_		(   a							):






 '''simple docstring'''





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

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

    UpperCAmelCase__						=None
    if self.use_input_mask:
       UpperCAmelCase__						=ids_tensor([self.batch_size, self.seq_length],		vocab_size=2		)

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

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

    UpperCAmelCase__						=self.get_config()

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

 def  __UpperCAmelCase						(  self		)	->       int:
    return 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,		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  __UpperCAmelCase						(  self,		A_		)	->       Union[str, Any]:
    self.parent.assertListEqual(list(result.loss.size()		),		[]		)

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_,		A_,		A_,		A_		)	->       List[str]:
    UpperCAmelCase__						=DebertaVaModel(config=A_		)
    model.to(A_		)
    model.eval()
    UpperCAmelCase__						=model(A_,		attention_mask=A_,		token_type_ids=A_		)[0]
    UpperCAmelCase__						=model(A_,		token_type_ids=A_		)[0]
    UpperCAmelCase__						=model(A_		)[0]

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

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_,		A_,		A_,		A_		)	->       Optional[int]:
    UpperCAmelCase__						=DebertaVaForMaskedLM(config=A_		)
    model.to(A_		)
    model.eval()
    UpperCAmelCase__						=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  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_,		A_,		A_,		A_		)	->       Union[str, Any]:
    UpperCAmelCase__						=self.num_labels
    UpperCAmelCase__						=DebertaVaForSequenceClassification(A_		)
    model.to(A_		)
    model.eval()
    UpperCAmelCase__						=model(A_,		attention_mask=A_,		token_type_ids=A_,		labels=A_		)
    self.parent.assertListEqual(list(result.logits.size()		),		[self.batch_size, self.num_labels]		)
    self.check_loss_output(A_		)

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_,		A_,		A_,		A_		)	->       Tuple:
    UpperCAmelCase__						=self.num_labels
    UpperCAmelCase__						=DebertaVaForTokenClassification(config=A_		)
    model.to(A_		)
    model.eval()
    UpperCAmelCase__						=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  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_,		A_,		A_,		A_		)	->       Union[str, Any]:
    UpperCAmelCase__						=DebertaVaForQuestionAnswering(config=A_		)
    model.to(A_		)
    model.eval()
    UpperCAmelCase__						=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  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_,		A_,		A_,		A_		)	->       Optional[Any]:
    UpperCAmelCase__						=DebertaVaForMultipleChoice(config=A_		)
    model.to(A_		)
    model.eval()
    UpperCAmelCase__						=input_ids.unsqueeze(1		).expand(-1,		self.num_choices,		-1		).contiguous()
    UpperCAmelCase__						=token_type_ids.unsqueeze(1		).expand(-1,		self.num_choices,		-1		).contiguous()
    UpperCAmelCase__						=input_mask.unsqueeze(1		).expand(-1,		self.num_choices,		-1		).contiguous()
    UpperCAmelCase__						=model(
        A_,		attention_mask=A_,		token_type_ids=A_,		labels=A_,		)
    self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.num_choices)		)






 def  __UpperCAmelCase						(  self		)	->       Tuple:
    UpperCAmelCase__						=self.prepare_config_and_inputs()
    (
        (
        UpperCAmelCase__
    )			,							(
        UpperCAmelCase__
    )			,							(
        UpperCAmelCase__
    )			,							(
        UpperCAmelCase__
    )			,							(
        UpperCAmelCase__
    )			,							(
        UpperCAmelCase__
    )			,							(
        UpperCAmelCase__
    )			,							
    )						=config_and_inputs
    UpperCAmelCase__						={"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
    return config, inputs_dict

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






 '''simple docstring'''





 __UpperCamelCase       =      (
     (
         DebertaVaModel,
         DebertaVaForMaskedLM,
         DebertaVaForSequenceClassification,
         DebertaVaForTokenClassification,
         DebertaVaForQuestionAnswering,
         DebertaVaForMultipleChoice,
     )
     if is_torch_available()
     else ()
 )
 __UpperCamelCase       =      (
     {
         'feature-extraction': DebertaVaModel,
         'fill-mask': DebertaVaForMaskedLM,
         'question-answering': DebertaVaForQuestionAnswering,
         'text-classification': DebertaVaForSequenceClassification,
         'token-classification': DebertaVaForTokenClassification,
         'zero-shot': DebertaVaForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )

 __UpperCamelCase       =      True
 __UpperCamelCase       =      False
 __UpperCamelCase       =      False
 __UpperCamelCase       =      False
 __UpperCamelCase       =      False

 def  __UpperCAmelCase						(  self		)	->       Any:
    UpperCAmelCase__						=DebertaVaModelTester(self		)
    UpperCAmelCase__						=ConfigTester(self,		config_class=A_,		hidden_size=37		)

 def  __UpperCAmelCase						(  self		)	->       int:
    self.config_tester.run_common_tests()

 def  __UpperCAmelCase						(  self		)	->       Tuple:
    UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_deberta_model(*A_		)

 def  __UpperCAmelCase						(  self		)	->       int:
    UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_deberta_for_sequence_classification(*A_		)

 def  __UpperCAmelCase						(  self		)	->       int:
    UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_deberta_for_masked_lm(*A_		)

 def  __UpperCAmelCase						(  self		)	->       Dict:
    UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_deberta_for_question_answering(*A_		)

 def  __UpperCAmelCase						(  self		)	->       List[str]:
    UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_deberta_for_token_classification(*A_		)

 def  __UpperCAmelCase						(  self		)	->       Optional[int]:
    UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_deberta_for_multiple_choice(*A_		)






 @slow
 def  __UpperCAmelCase						(  self		)	->       Union[str, Any]:
    for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCAmelCase__						=DebertaVaModel.from_pretrained(A_		)
       self.assertIsNotNone(A_		)

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






 '''simple docstring'''





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






 @slow
 def  __UpperCAmelCase						(  self		)	->       Union[str, Any]:
    UpperCAmelCase__						=DebertaVaModel.from_pretrained("microsoft/deberta-v2-xlarge"		)

    UpperCAmelCase__						=torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]		)
    UpperCAmelCase__						=torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]		)
    with torch.no_grad():
       UpperCAmelCase__						=model(A_,		attention_mask=A_		)[0]
    # compare the actual values for a slice.
    UpperCAmelCase__						=torch.tensor(
        [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]]		)
    self.assertTrue(torch.allclose(output[:, 1:4, 1:4],		A_,		atol=1E-4		),		f"""{output[:, 1:4, 1:4]}"""		)










import os
import tempfile
import unittest
import uuid
from pathlib import Path

from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision
from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText
from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available


if is_torch_available():
    import torch

if is_soundfile_availble():
    import soundfile as sf

if is_vision_available():
    from PIL import Image






def 				_UpperCAmelCase			(    A=""     ):




   '''simple docstring'''

   UpperCAmelCase__						=tempfile.mkdtemp()
   return os.path.join(A				,							str(uuid.uuida()     ) + suffix     )

@require_soundfile
@require_torch
class     snake_case_		(   unittest.TestCase							):






 '''simple docstring'''





 def  __UpperCAmelCase						(  self		)	->       str:
    UpperCAmelCase__						=torch.rand(12,		dtype=torch.floataa		) - 0.5
    UpperCAmelCase__						=AgentAudio(A_		)
    UpperCAmelCase__						=str(agent_type.to_string()		)

    # Ensure that the tensor and the agent_type's tensor are the same
    self.assertTrue(torch.allclose(A_,		agent_type.to_raw(),		atol=1E-4		)		)

    del agent_type

    # Ensure the path remains even after the object deletion
    self.assertTrue(os.path.exists(A_		)		)

    # Ensure that the file contains the same value as the original tensor
    UpperCAmelCase__			,							UpperCAmelCase__						=sf.read(A_		)
    self.assertTrue(torch.allclose(A_,		torch.tensor(A_		),		atol=1E-4		)		)






 def  __UpperCAmelCase						(  self		)	->       Optional[Any]:
    UpperCAmelCase__						=torch.rand(12,		dtype=torch.floataa		) - 0.5
    UpperCAmelCase__						=get_new_path(suffix=".wav"		)
    sf.write(A_,		A_,		1_6000		)

    UpperCAmelCase__						=AgentAudio(A_		)

    self.assertTrue(torch.allclose(A_,		agent_type.to_raw(),		atol=1E-4		)		)
    self.assertEqual(agent_type.to_string(),		A_		)

@require_vision
@require_torch
class     snake_case_		(   unittest.TestCase							):






 '''simple docstring'''





 def  __UpperCAmelCase						(  self		)	->       int:
    UpperCAmelCase__						=torch.randint(0,		256,		(64, 64, 3)		)
    UpperCAmelCase__						=AgentImage(A_		)
    UpperCAmelCase__						=str(agent_type.to_string()		)

    # Ensure that the tensor and the agent_type's tensor are the same
    self.assertTrue(torch.allclose(A_,		agent_type._tensor,		atol=1E-4		)		)

    self.assertIsInstance(agent_type.to_raw(),		Image.Image		)

    # Ensure the path remains even after the object deletion
    del agent_type
    self.assertTrue(os.path.exists(A_		)		)

 def  __UpperCAmelCase						(  self		)	->       List[str]:
    UpperCAmelCase__						=Path(get_tests_dir("fixtures/tests_samples/COCO"		)		) / "000000039769.png"
    UpperCAmelCase__						=Image.open(A_		)
    UpperCAmelCase__						=AgentImage(A_		)

    self.assertTrue(path.samefile(agent_type.to_string()		)		)
    self.assertTrue(image == agent_type.to_raw()		)

    # Ensure the path remains even after the object deletion
    del agent_type
    self.assertTrue(os.path.exists(A_		)		)






 def  __UpperCAmelCase						(  self		)	->       Tuple:
    UpperCAmelCase__						=Path(get_tests_dir("fixtures/tests_samples/COCO"		)		) / "000000039769.png"
    UpperCAmelCase__						=Image.open(A_		)
    UpperCAmelCase__						=AgentImage(A_		)

    self.assertFalse(path.samefile(agent_type.to_string()		)		)
    self.assertTrue(image == agent_type.to_raw()		)

    # Ensure the path remains even after the object deletion
    del agent_type
    self.assertTrue(os.path.exists(A_		)		)

class     snake_case_		(   unittest.TestCase							):






 '''simple docstring'''





 def  __UpperCAmelCase						(  self		)	->       List[Any]:
    UpperCAmelCase__						="Hey!"
    UpperCAmelCase__						=AgentText(A_		)

    self.assertEqual(A_,		agent_type.to_string()		)
    self.assertEqual(A_,		agent_type.to_raw()		)
    self.assertEqual(A_,		A_		)



