


"""simple docstring"""
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    __A   (snake_case_):





							'''simple docstring'''

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



														"""simple docstring"""



														snake_case_							=						parent
														snake_case_							=						batch_size
														snake_case_							=						seq_length
														snake_case_							=						is_training
														snake_case_							=						use_input_mask
														snake_case_							=						use_token_type_ids
														snake_case_							=						use_labels
														snake_case_							=						vocab_size
														snake_case_							=						hidden_size
														snake_case_							=						num_hidden_layers
														snake_case_							=						num_attention_heads
														snake_case_							=						intermediate_size
														snake_case_							=						hidden_act
														snake_case_							=						hidden_dropout_prob
														snake_case_							=						attention_probs_dropout_prob
														snake_case_							=						max_position_embeddings
														snake_case_							=						type_vocab_size
														snake_case_							=						type_sequence_label_size
														snake_case_							=						initializer_range
														snake_case_							=						num_labels
														snake_case_							=						num_choices
														snake_case_							=						relative_attention
														snake_case_							=						position_biased_input
														snake_case_							=						pos_att_type
														snake_case_							=						scope



							def 						lowerCAmelCase				( self							:					int				)    ->Any:



														"""simple docstring"""



														snake_case_							=						ids_tensor([self.batch_size, self.seq_length]						,				self.vocab_size				)

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

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

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

														snake_case_							=						self.get_config()

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



							def 						lowerCAmelCase				( self							:					List[str]				)    ->Optional[Any]:



														"""simple docstring"""



														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 						lowerCAmelCase				( self							:					List[Any]						,				UpperCAmelCase_							:					Union[str, Any]				)    ->Union[str, Any]:



														"""simple docstring"""



														self.parent.assertListEqual(list(result.loss.size()				)						,				[]				)



							def 						lowerCAmelCase				( self							:					Optional[Any]						,				UpperCAmelCase_							:					List[str]						,				UpperCAmelCase_							:					Dict						,				UpperCAmelCase_							:					str						,				UpperCAmelCase_							:					Tuple						,				UpperCAmelCase_							:					Tuple						,				UpperCAmelCase_							:					Any						,				UpperCAmelCase_							:					Union[str, Any]				)    ->Tuple:



														"""simple docstring"""



														snake_case_							=						DebertaVaModel(config=UpperCAmelCase__				)
														model.to(UpperCAmelCase__				)
														model.eval()
														snake_case_							=						model(UpperCAmelCase__						,				attention_mask=UpperCAmelCase__						,				token_type_ids=UpperCAmelCase__				)[0]
														snake_case_							=						model(UpperCAmelCase__						,				token_type_ids=UpperCAmelCase__				)[0]
														snake_case_							=						model(UpperCAmelCase__				)[0]

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



							def 						lowerCAmelCase				( self							:					Dict						,				UpperCAmelCase_							:					Tuple						,				UpperCAmelCase_							:					Union[str, Any]						,				UpperCAmelCase_							:					Optional[Any]						,				UpperCAmelCase_							:					Optional[int]						,				UpperCAmelCase_							:					List[str]						,				UpperCAmelCase_							:					Tuple						,				UpperCAmelCase_							:					Any				)    ->int:



														"""simple docstring"""



														snake_case_							=						DebertaVaForMaskedLM(config=UpperCAmelCase__				)
														model.to(UpperCAmelCase__				)
														model.eval()
														snake_case_							=						model(UpperCAmelCase__						,				attention_mask=UpperCAmelCase__						,				token_type_ids=UpperCAmelCase__						,				labels=UpperCAmelCase__				)

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



							def 						lowerCAmelCase				( self							:					List[Any]						,				UpperCAmelCase_							:					Dict						,				UpperCAmelCase_							:					Union[str, Any]						,				UpperCAmelCase_							:					str						,				UpperCAmelCase_							:					Optional[int]						,				UpperCAmelCase_							:					str						,				UpperCAmelCase_							:					List[str]						,				UpperCAmelCase_							:					str				)    ->str:



														"""simple docstring"""



														snake_case_							=						self.num_labels
														snake_case_							=						DebertaVaForSequenceClassification(UpperCAmelCase__				)
														model.to(UpperCAmelCase__				)
														model.eval()
														snake_case_							=						model(UpperCAmelCase__						,				attention_mask=UpperCAmelCase__						,				token_type_ids=UpperCAmelCase__						,				labels=UpperCAmelCase__				)
														self.parent.assertListEqual(list(result.logits.size()				)						,				[self.batch_size, self.num_labels]				)
														self.check_loss_output(UpperCAmelCase__				)



							def 						lowerCAmelCase				( self							:					List[str]						,				UpperCAmelCase_							:					List[str]						,				UpperCAmelCase_							:					Optional[Any]						,				UpperCAmelCase_							:					List[str]						,				UpperCAmelCase_							:					List[str]						,				UpperCAmelCase_							:					str						,				UpperCAmelCase_							:					str						,				UpperCAmelCase_							:					int				)    ->Any:



														"""simple docstring"""



														snake_case_							=						self.num_labels
														snake_case_							=						DebertaVaForTokenClassification(config=UpperCAmelCase__				)
														model.to(UpperCAmelCase__				)
														model.eval()
														snake_case_							=						model(UpperCAmelCase__						,				attention_mask=UpperCAmelCase__						,				token_type_ids=UpperCAmelCase__						,				labels=UpperCAmelCase__				)
														self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.seq_length, self.num_labels)				)



							def 						lowerCAmelCase				( self							:					str						,				UpperCAmelCase_							:					Dict						,				UpperCAmelCase_							:					List[str]						,				UpperCAmelCase_							:					Optional[Any]						,				UpperCAmelCase_							:					Tuple						,				UpperCAmelCase_							:					Optional[int]						,				UpperCAmelCase_							:					List[str]						,				UpperCAmelCase_							:					Dict				)    ->Optional[Any]:



														"""simple docstring"""



														snake_case_							=						DebertaVaForQuestionAnswering(config=UpperCAmelCase__				)
														model.to(UpperCAmelCase__				)
														model.eval()
														snake_case_							=						model(
														    UpperCAmelCase__						,				attention_mask=UpperCAmelCase__						,				token_type_ids=UpperCAmelCase__						,				start_positions=UpperCAmelCase__						,				end_positions=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 						lowerCAmelCase				( self							:					List[str]						,				UpperCAmelCase_							:					Optional[Any]						,				UpperCAmelCase_							:					str						,				UpperCAmelCase_							:					int						,				UpperCAmelCase_							:					Any						,				UpperCAmelCase_							:					Tuple						,				UpperCAmelCase_							:					List[str]						,				UpperCAmelCase_							:					List[str]				)    ->Union[str, Any]:



														"""simple docstring"""



														snake_case_							=						DebertaVaForMultipleChoice(config=UpperCAmelCase__				)
														model.to(UpperCAmelCase__				)
														model.eval()
														snake_case_							=						input_ids.unsqueeze(1				).expand(-1						,				self.num_choices						,				-1				).contiguous()
														snake_case_							=						token_type_ids.unsqueeze(1				).expand(-1						,				self.num_choices						,				-1				).contiguous()
														snake_case_							=						input_mask.unsqueeze(1				).expand(-1						,				self.num_choices						,				-1				).contiguous()
														snake_case_							=						model(
														    UpperCAmelCase__						,				attention_mask=UpperCAmelCase__						,				token_type_ids=UpperCAmelCase__						,				labels=UpperCAmelCase__						,				)
														self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.num_choices)				)



							def 						lowerCAmelCase				( self							:					int				)    ->Dict:



														"""simple docstring"""



														snake_case_							=						self.prepare_config_and_inputs()
														(
														    snake_case_  
														)							=						config_and_inputs
														snake_case_							=						{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
														return config, inputs_dict





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





							'''simple docstring'''

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

							__lowercase:						Tuple												=			True
							__lowercase:						Any												=			False
							__lowercase:						Tuple												=			False
							__lowercase:						int												=			False
							__lowercase:						str												=			False



							def 						lowerCAmelCase				( self							:					str				)    ->List[Any]:



														"""simple docstring"""



														snake_case_							=						DebertaVaModelTester(self				)
														snake_case_							=						ConfigTester(self						,				config_class=UpperCAmelCase__						,				hidden_size=37				)



							def 						lowerCAmelCase				( self							:					str				)    ->Dict:



														"""simple docstring"""



														self.config_tester.run_common_tests()



							def 						lowerCAmelCase				( self							:					Dict				)    ->List[str]:



														"""simple docstring"""



														snake_case_							=						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_deberta_model(*UpperCAmelCase__				)



							def 						lowerCAmelCase				( self							:					Tuple				)    ->str:



														"""simple docstring"""



														snake_case_							=						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_deberta_for_sequence_classification(*UpperCAmelCase__				)



							def 						lowerCAmelCase				( self							:					Union[str, Any]				)    ->List[Any]:



														"""simple docstring"""



														snake_case_							=						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_deberta_for_masked_lm(*UpperCAmelCase__				)



							def 						lowerCAmelCase				( self							:					Optional[int]				)    ->int:



														"""simple docstring"""



														snake_case_							=						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_deberta_for_question_answering(*UpperCAmelCase__				)



							def 						lowerCAmelCase				( self							:					str				)    ->Union[str, Any]:



														"""simple docstring"""



														snake_case_							=						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_deberta_for_token_classification(*UpperCAmelCase__				)



							def 						lowerCAmelCase				( self							:					Any				)    ->Tuple:



														"""simple docstring"""



														snake_case_							=						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_deberta_for_multiple_choice(*UpperCAmelCase__				)



							@slow
							def 						lowerCAmelCase				( self							:					Tuple				)    ->Optional[int]:



														"""simple docstring"""



														for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					snake_case_							=						DebertaVaModel.from_pretrained(UpperCAmelCase__				)
																					self.assertIsNotNone(UpperCAmelCase__				)





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





							'''simple docstring'''

							@unittest.skip(reason="""Model not available yet"""				)
							def 						lowerCAmelCase				( self							:					Union[str, Any]				)    ->Optional[Any]:



														"""simple docstring"""



														pass



							@slow
							def 						lowerCAmelCase				( self							:					List[Any]				)    ->Union[str, Any]:



														"""simple docstring"""



														snake_case_							=						DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge"""				)

														snake_case_							=						torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]]				)
														snake_case_							=						torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]				)
														with torch.no_grad():
																					snake_case_							=						model(UpperCAmelCase__						,				attention_mask=UpperCAmelCase__				)[0]
														# compare the actual values for a slice.
														snake_case_							=						torch.tensor(
														    [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]]				)
														self.assertTrue(torch.allclose(output[:, 1:4, 1:4]						,				UpperCAmelCase__						,				atol=1E-4				)						,				F"""{output[:, 1:4, 1:4]}"""				)











"""simple docstring"""




import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
 from PIL import Image

 from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
 import torch

if is_tf_available():
 import tensorflow as tf






@require_vision
@require_torchvision
class        UpperCamelCase			(	unittest.TestCase      ):


 def _lowercase	(     self		:						List[Any]							)					->       Dict:
   _a  :       Optional[int]             =	tempfile.mkdtemp()
   _a  :       Optional[Any]             =	SamImageProcessor()
   _a  :       int             =	SamProcessor(UpperCAmelCase__							)
   processor.save_pretrained(self.tmpdirname							)


 def _lowercase	(     self		:						Tuple							,						**UpperCAmelCase__		:						Any							)					->       Any:
   return AutoProcessor.from_pretrained(self.tmpdirname							,						**UpperCAmelCase__							).image_processor


 def _lowercase	(     self		:						str							)					->       int:
   shutil.rmtree(self.tmpdirname							)


 def _lowercase	(     self		:						Tuple							)					->       Dict:
   _a  :       List[Any]             =	[np.random.randint(255							,						size=(3, 30, 400)							,						dtype=np.uinta							)]

   _a  :       Optional[int]             =	[Image.fromarray(np.moveaxis(UpperCAmelCase__							,						0							,						-1							)							) for x in image_inputs]

   return image_inputs


 def _lowercase	(     self		:						Dict							)					->       Dict:
   _a  :       List[Any]             =	SamProcessor(image_processor=self.get_image_processor()							)
   processor.save_pretrained(self.tmpdirname							)

   _a  :       Tuple             =	self.get_image_processor(do_normalize=UpperCAmelCase__							,						padding_value=1.0							)

   _a  :       Tuple             =	SamProcessor.from_pretrained(self.tmpdirname							,						do_normalize=UpperCAmelCase__							,						padding_value=1.0							)

   self.assertEqual(processor.image_processor.to_json_string()							,						image_processor_add_kwargs.to_json_string()							)
   self.assertIsInstance(processor.image_processor							,						UpperCAmelCase__							)


 def _lowercase	(     self		:						Union[str, Any]							)					->       Tuple:
   _a  :       Optional[Any]             =	self.get_image_processor()

   _a  :       int             =	SamProcessor(image_processor=UpperCAmelCase__							)

   _a  :       Union[str, Any]             =	self.prepare_image_inputs()

   _a  :       List[str]             =	image_processor(UpperCAmelCase__							,						return_tensors="""np"""							)
   _a  :       List[str]             =	processor(images=UpperCAmelCase__							,						return_tensors="""np"""							)

   input_feat_extract.pop("""original_sizes"""							)  # pop original_sizes as it is popped in the processor
   input_feat_extract.pop("""reshaped_input_sizes"""							)  # pop original_sizes as it is popped in the processor

   for key in input_feat_extract.keys():
     self.assertAlmostEqual(input_feat_extract[key].sum()							,						input_processor[key].sum()							,						delta=1E-2							)







 @require_torch
 def _lowercase	(     self		:						Optional[Any]							)					->       Optional[Any]:
   _a  :       Optional[Any]             =	self.get_image_processor()

   _a  :       Dict             =	SamProcessor(image_processor=UpperCAmelCase__							)
   _a  :       Tuple             =	[torch.ones((1, 3, 5, 5)							)]

   _a  :       Tuple             =	[[1764, 2646]]

   _a  :       Optional[int]             =	[[683, 1024]]
   _a  :       List[Any]             =	processor.post_process_masks(UpperCAmelCase__							,						UpperCAmelCase__							,						UpperCAmelCase__							)
   self.assertEqual(masks[0].shape							,						(1, 3, 1764, 2646)							)

   _a  :       int             =	processor.post_process_masks(
       UpperCAmelCase__							,						torch.tensor(UpperCAmelCase__							)							,						torch.tensor(UpperCAmelCase__							)							)
   self.assertEqual(masks[0].shape							,						(1, 3, 1764, 2646)							)

   # should also work with np
   _a  :       Optional[Any]             =	[np.ones((1, 3, 5, 5)							)]
   _a  :       Tuple             =	processor.post_process_masks(UpperCAmelCase__							,						np.array(UpperCAmelCase__							)							,						np.array(UpperCAmelCase__							)							)

   self.assertEqual(masks[0].shape							,						(1, 3, 1764, 2646)							)

   _a  :       List[str]             =	[[1, 0], [0, 1]]
   with self.assertRaises(UpperCAmelCase__							):
     _a  :       str             =	processor.post_process_masks(UpperCAmelCase__							,						np.array(UpperCAmelCase__							)							,						np.array(UpperCAmelCase__							)							)







@require_vision
@require_tf
class        UpperCamelCase			(	unittest.TestCase      ):


 def _lowercase	(     self		:						Any							)					->       List[str]:
   _a  :       List[str]             =	tempfile.mkdtemp()
   _a  :       Any             =	SamImageProcessor()
   _a  :       Union[str, Any]             =	SamProcessor(UpperCAmelCase__							)
   processor.save_pretrained(self.tmpdirname							)


 def _lowercase	(     self		:						List[str]							,						**UpperCAmelCase__		:						Any							)					->       List[str]:
   return AutoProcessor.from_pretrained(self.tmpdirname							,						**UpperCAmelCase__							).image_processor


 def _lowercase	(     self		:						Optional[Any]							)					->       Union[str, Any]:
   shutil.rmtree(self.tmpdirname							)


 def _lowercase	(     self		:						Dict							)					->       List[str]:
   _a  :       List[Any]             =	[np.random.randint(255							,						size=(3, 30, 400)							,						dtype=np.uinta							)]

   _a  :       List[Any]             =	[Image.fromarray(np.moveaxis(UpperCAmelCase__							,						0							,						-1							)							) for x in image_inputs]

   return image_inputs


 def _lowercase	(     self		:						Union[str, Any]							)					->       Union[str, Any]:
   _a  :       Optional[int]             =	SamProcessor(image_processor=self.get_image_processor()							)
   processor.save_pretrained(self.tmpdirname							)

   _a  :       str             =	self.get_image_processor(do_normalize=UpperCAmelCase__							,						padding_value=1.0							)

   _a  :       Union[str, Any]             =	SamProcessor.from_pretrained(self.tmpdirname							,						do_normalize=UpperCAmelCase__							,						padding_value=1.0							)

   self.assertEqual(processor.image_processor.to_json_string()							,						image_processor_add_kwargs.to_json_string()							)
   self.assertIsInstance(processor.image_processor							,						UpperCAmelCase__							)


 def _lowercase	(     self		:						List[Any]							)					->       str:
   _a  :       Union[str, Any]             =	self.get_image_processor()

   _a  :       Dict             =	SamProcessor(image_processor=UpperCAmelCase__							)

   _a  :       int             =	self.prepare_image_inputs()

   _a  :       List[str]             =	image_processor(UpperCAmelCase__							,						return_tensors="""np"""							)
   _a  :       List[str]             =	processor(images=UpperCAmelCase__							,						return_tensors="""np"""							)

   input_feat_extract.pop("""original_sizes"""							)  # pop original_sizes as it is popped in the processor
   input_feat_extract.pop("""reshaped_input_sizes"""							)  # pop reshaped_input_sizes as it is popped in the processor

   for key in input_feat_extract.keys():
     self.assertAlmostEqual(input_feat_extract[key].sum()							,						input_processor[key].sum()							,						delta=1E-2							)







 @require_tf
 def _lowercase	(     self		:						Optional[Any]							)					->       int:
   _a  :       Optional[Any]             =	self.get_image_processor()

   _a  :       Dict             =	SamProcessor(image_processor=UpperCAmelCase__							)
   _a  :       Any             =	[tf.ones((1, 3, 5, 5)							)]

   _a  :       Tuple             =	[[1764, 2646]]

   _a  :       str             =	[[683, 1024]]
   _a  :       Union[str, Any]             =	processor.post_process_masks(UpperCAmelCase__							,						UpperCAmelCase__							,						UpperCAmelCase__							,						return_tensors="""tf"""							)
   self.assertEqual(masks[0].shape							,						(1, 3, 1764, 2646)							)

   _a  :       Union[str, Any]             =	processor.post_process_masks(
       UpperCAmelCase__							,						tf.convert_to_tensor(UpperCAmelCase__							)							,						tf.convert_to_tensor(UpperCAmelCase__							)							,						return_tensors="""tf"""							,						)
   self.assertEqual(masks[0].shape							,						(1, 3, 1764, 2646)							)

   # should also work with np
   _a  :       List[Any]             =	[np.ones((1, 3, 5, 5)							)]
   _a  :       Optional[int]             =	processor.post_process_masks(
       UpperCAmelCase__							,						np.array(UpperCAmelCase__							)							,						np.array(UpperCAmelCase__							)							,						return_tensors="""tf"""							)

   self.assertEqual(masks[0].shape							,						(1, 3, 1764, 2646)							)

   _a  :       Dict             =	[[1, 0], [0, 1]]
   with self.assertRaises(tf.errors.InvalidArgumentError							):
     _a  :       List[Any]             =	processor.post_process_masks(
         UpperCAmelCase__							,						np.array(UpperCAmelCase__							)							,						np.array(UpperCAmelCase__							)							,						return_tensors="""tf"""							)







@require_vision
@require_torchvision
class        UpperCamelCase			(	unittest.TestCase      ):


 def _lowercase	(     self		:						str							)					->       Optional[Any]:
   _a  :       Optional[Any]             =	tempfile.mkdtemp()
   _a  :       Dict             =	SamImageProcessor()
   _a  :       List[str]             =	SamProcessor(UpperCAmelCase__							)
   processor.save_pretrained(self.tmpdirname							)


 def _lowercase	(     self		:						Any							,						**UpperCAmelCase__		:						Dict							)					->       int:
   return AutoProcessor.from_pretrained(self.tmpdirname							,						**UpperCAmelCase__							).image_processor


 def _lowercase	(     self		:						Tuple							)					->       List[Any]:
   shutil.rmtree(self.tmpdirname							)


 def _lowercase	(     self		:						str							)					->       int:
   _a  :       str             =	[np.random.randint(255							,						size=(3, 30, 400)							,						dtype=np.uinta							)]

   _a  :       int             =	[Image.fromarray(np.moveaxis(UpperCAmelCase__							,						0							,						-1							)							) for x in image_inputs]

   return image_inputs


 @is_pt_tf_cross_test
 def _lowercase	(     self		:						int							)					->       List[Any]:
   _a  :       Optional[Any]             =	self.get_image_processor()

   _a  :       Optional[Any]             =	SamProcessor(image_processor=UpperCAmelCase__							)
   _a  :       Tuple             =	np.random.randint(0							,						2							,						size=(1, 3, 5, 5)							).astype(np.floataa							)
   _a  :       str             =	[tf.convert_to_tensor(UpperCAmelCase__							)]
   _a  :       Optional[int]             =	[torch.tensor(UpperCAmelCase__							)]

   _a  :       Union[str, Any]             =	[[1764, 2646]]

   _a  :       List[str]             =	[[683, 1024]]
   _a  :       Optional[int]             =	processor.post_process_masks(
       UpperCAmelCase__							,						UpperCAmelCase__							,						UpperCAmelCase__							,						return_tensors="""tf"""							)
   _a  :       List[str]             =	processor.post_process_masks(
       UpperCAmelCase__							,						UpperCAmelCase__							,						UpperCAmelCase__							,						return_tensors="""pt"""							)

   self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()							)							)







 @is_pt_tf_cross_test
 def _lowercase	(     self		:						str							)					->       Optional[Any]:
   _a  :       List[Any]             =	self.get_image_processor()

   _a  :       Any             =	SamProcessor(image_processor=UpperCAmelCase__							)

   _a  :       Dict             =	self.prepare_image_inputs()

   _a  :       List[str]             =	image_processor(UpperCAmelCase__							,						return_tensors="""pt"""							)["""pixel_values"""].numpy()
   _a  :       str             =	processor(images=UpperCAmelCase__							,						return_tensors="""pt"""							)["""pixel_values"""].numpy()

   _a  :       Optional[Any]             =	image_processor(UpperCAmelCase__							,						return_tensors="""tf"""							)["""pixel_values"""].numpy()
   _a  :       Optional[int]             =	processor(images=UpperCAmelCase__							,						return_tensors="""tf"""							)["""pixel_values"""].numpy()

   self.assertTrue(np.allclose(UpperCAmelCase__							,						UpperCAmelCase__							)							)
   self.assertTrue(np.allclose(UpperCAmelCase__							,						UpperCAmelCase__							)							)
   self.assertTrue(np.allclose(UpperCAmelCase__							,						UpperCAmelCase__							)							)

