"""simple docstring"""





import unittest

from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


_UpperCamelCase   :						int      =    get_tests_dir("fixtures/test_sentencepiece.model")


@require_sentencepiece
@require_tokenizers
class      UpperCAmelCase_	(    _a ,							unittest.TestCase):
      lowerCamelCase__		:    Optional[int]   =  ReformerTokenizer
      lowerCamelCase__		:    Tuple   =  ReformerTokenizerFast
      lowerCamelCase__		:    Optional[int]   =  True
      lowerCamelCase__		:    List[Any]   =  False
      lowerCamelCase__		:    Union[str, Any]   =  True


      def 		_UpperCAmelCase       (   self							)       ->					List[Any]:
             super().setUp()

             lowercase__			:		Union[str, Any]       =	ReformerTokenizer(a		,			keep_accents=a							)
             tokenizer.save_pretrained(self.tmpdirname							)


      def 		_UpperCAmelCase       (   self							)       ->					Tuple:
             lowercase__			:		Optional[Any]       =	'<s>'
             lowercase__			:		Any       =	1

             self.assertEqual(self.get_tokenizer()._convert_token_to_id(a							)		,			a							)
             self.assertEqual(self.get_tokenizer()._convert_id_to_token(a							)		,			a							)


      def 		_UpperCAmelCase       (   self							)       ->					Tuple:
             lowercase__			:		List[Any]       =	list(self.get_tokenizer().get_vocab().keys()							)

             self.assertEqual(vocab_keys[0]		,			'<unk>'							)
             self.assertEqual(vocab_keys[1]		,			'<s>'							)
             self.assertEqual(vocab_keys[-1]		,			'j'							)
             self.assertEqual(len(a							)		,			1_0_0_0							)


      def 		_UpperCAmelCase       (   self							)       ->					Union[str, Any]:
             self.assertEqual(self.get_tokenizer().vocab_size		,			1_0_0_0							)


      def 		_UpperCAmelCase       (   self							)       ->					int:
             if not self.test_rust_tokenizer:
                    return

             lowercase__			:		List[Any]       =	self.get_tokenizer()
             lowercase__			:		Dict       =	self.get_rust_tokenizer()

             lowercase__			:		List[Any]       =	'I was born in 92000, and this is falsé.'

             lowercase__			:		Dict       =	tokenizer.tokenize(a							)
             lowercase__			:		Tuple       =	rust_tokenizer.tokenize(a							)
             self.assertListEqual(a		,			a							)

             lowercase__			:		str       =	tokenizer.encode(a		,			add_special_tokens=a							)
             lowercase__			:		Tuple       =	rust_tokenizer.encode(a		,			add_special_tokens=a							)
             self.assertListEqual(a		,			a							)

             lowercase__			:		Any       =	self.get_rust_tokenizer()
             lowercase__			:		Optional[int]       =	tokenizer.encode(a							)
             lowercase__			:		Tuple       =	rust_tokenizer.encode(a							)
             self.assertListEqual(a		,			a							)


      def 		_UpperCAmelCase       (   self		,			a=1_5							)       ->					str:
             for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                    with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""							):
                           lowercase__			:		Tuple       =	self.rust_tokenizer_class.from_pretrained(a		,			**a							)

                           # Simple input
                           lowercase__			:		Tuple       =	'This is a simple input'
                           lowercase__			:		List[str]       =	['This is a simple input 1', 'This is a simple input 2']
                           lowercase__			:		Optional[int]       =	('This is a simple input', 'This is a pair')
                           lowercase__			:		List[Any]       =	[
                               ('This is a simple input 1', 'This is a simple input 2'),
                               ('This is a simple pair 1', 'This is a simple pair 2'),
                           ]

                           # Simple input tests
                           self.assertRaises(a		,			tokenizer_r.encode		,			a		,			max_length=a		,			padding='max_length'							)

                           # Simple input
                           self.assertRaises(a		,			tokenizer_r.encode_plus		,			a		,			max_length=a		,			padding='max_length'							)

                           # Simple input
                           self.assertRaises(
                               a		,			tokenizer_r.batch_encode_plus		,			a		,			max_length=a		,			padding='max_length'		,			)

                           # Pair input
                           self.assertRaises(a		,			tokenizer_r.encode		,			a		,			max_length=a		,			padding='max_length'							)

                           # Pair input
                           self.assertRaises(a		,			tokenizer_r.encode_plus		,			a		,			max_length=a		,			padding='max_length'							)

                           # Pair input
                           self.assertRaises(
                               a		,			tokenizer_r.batch_encode_plus		,			a		,			max_length=a		,			padding='max_length'		,			)


      def 		_UpperCAmelCase       (   self							)       ->					Optional[int]:
             pass


      def 		_UpperCAmelCase       (   self							)       ->					List[Any]:
             lowercase__			:		Union[str, Any]       =	ReformerTokenizer(a		,			keep_accents=a							)

             lowercase__			:		str       =	tokenizer.tokenize('This is a test'							)
             self.assertListEqual(a		,			['▁This', '▁is', '▁a', '▁t', 'est']							)

             self.assertListEqual(
                 tokenizer.convert_tokens_to_ids(a							)		,			[2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]		,			)

             lowercase__			:		int       =	tokenizer.tokenize('I was born in 92000, and this is falsé.'							)
             self.assertListEqual(
                 a		,			[
                     SPIECE_UNDERLINE + 'I',
                     SPIECE_UNDERLINE + 'was',
                     SPIECE_UNDERLINE + 'b',
                     'or',
                     'n',
                     SPIECE_UNDERLINE + 'in',
                     SPIECE_UNDERLINE + '',
                     '9',
                     '2',
                     '0',
                     '0',
                     '0',
                     ',',
                     SPIECE_UNDERLINE + 'and',
                     SPIECE_UNDERLINE + 'this',
                     SPIECE_UNDERLINE + 'is',
                     SPIECE_UNDERLINE + 'f',
                     'al',
                     's',
                     'é',
                     '.',
                 ]		,			)
             lowercase__			:		int       =	tokenizer.convert_tokens_to_ids(a							)
             self.assertListEqual(
                 a		,			[8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4]		,			)

             lowercase__			:		List[str]       =	tokenizer.convert_ids_to_tokens(a							)
             self.assertListEqual(
                 a		,			[
                     SPIECE_UNDERLINE + 'I',
                     SPIECE_UNDERLINE + 'was',
                     SPIECE_UNDERLINE + 'b',
                     'or',
                     'n',
                     SPIECE_UNDERLINE + 'in',
                     SPIECE_UNDERLINE + '',
                     '<unk>',
                     '2',
                     '0',
                     '0',
                     '0',
                     ',',
                     SPIECE_UNDERLINE + 'and',
                     SPIECE_UNDERLINE + 'this',
                     SPIECE_UNDERLINE + 'is',
                     SPIECE_UNDERLINE + 'f',
                     'al',
                     's',
                     '<unk>',
                     '.',
                 ]		,			)


      @cached_property
      def 		_UpperCAmelCase       (   self							)       ->					Optional[int]:
             return ReformerTokenizer.from_pretrained('google/reformer-crime-and-punishment'							)


      @slow
      def 		_UpperCAmelCase       (   self							)       ->					Optional[Any]:
             lowercase__			:		Union[str, Any]       =	'Hello World!'
             lowercase__			:		Optional[int]       =	[1_2_6, 3_2, 2_6_2, 1_5_2, 3_8, 7_2, 2_8_7]

             self.assertListEqual(a		,			self.big_tokenizer.encode(a							)							)


      @slow
      def 		_UpperCAmelCase       (   self							)       ->					Union[str, Any]:
             lowercase__			:		List[str]       =	(
                 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'
                 ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth'
             )
             lowercase__			:		int       =	[
                 1_0_8,
                 2_6_5,
                 2_4,
                 1_1_1,
                 4,
                 2_5_8,
                 1_5_6,
                 3_5,
                 2_8,
                 2_7_5,
                 3,
                 2_5_9,
                 2_9_7,
                 2_6_0,
                 8_4,
                 4,
                 3_5,
                 1_1_0,
                 4_4,
                 8,
                 2_5_9,
                 9_1,
                 2_6_8,
                 2_1,
                 1_1,
                 2_0_9,
                 2_7_4,
                 1_0_9,
                 2_6_6,
                 2_7_7,
                 1_1_7,
                 8_6,
                 9_3,
                 3_1_5,
                 2_5_8,
                 2_7_8,
                 2_5_8,
                 2_7_7,
                 2_5_8,
                 0,
                 2_5_8,
                 2_8_8,
                 2_5_8,
                 3_1_9,
                 2_5_8,
                 0,
                 2_5_8,
                 0,
                 2_5_8,
                 0,
                 2_5_8,
                 0,
                 2_5_8,
                 2_8_7,
                 2_5_8,
                 3_1_5,
                 2_5_8,
                 2_8_9,
                 2_5_8,
                 2_7_8,
                 9_9,
                 2_6_9,
                 2_6_6,
                 2_6_2,
                 8,
                 2_5_9,
                 2_4_1,
                 4,
                 2_1_7,
                 2_3_0,
                 2_6_8,
                 2_6_6,
                 5_5,
                 1_6_8,
                 1_0_6,
                 7_5,
                 1_9_3,
                 2_6_6,
                 2_2_3,
                 2_7,
                 4_9,
                 2_6,
                 2_8_2,
                 2_5,
                 2_6_4,
                 2_9_9,
                 1_9,
                 2_6,
                 0,
                 2_5_8,
                 2_7_7,
                 1_1_7,
                 8_6,
                 9_3,
                 1_7_6,
                 1_8_3,
                 2_7_0,
                 1_1,
                 2_6_2,
                 4_2,
                 6_1,
                 2_6_5,
             ]

             self.assertListEqual(a		,			self.big_tokenizer.encode(a							)							)


      @require_torch
      @slow
      def 		_UpperCAmelCase       (   self							)       ->					List[Any]:
             import torch

             from transformers import ReformerConfig, ReformerModel

             # Build sequence
             lowercase__			:		str       =	list(self.big_tokenizer.get_vocab().keys()							)[:1_0]
             lowercase__			:		List[Any]       =	' '.join(a							)
             lowercase__			:		List[Any]       =	self.big_tokenizer.encode_plus(a		,			return_tensors='pt'							)
             lowercase__			:		Optional[int]       =	self.big_tokenizer.batch_encode_plus([sequence, sequence]		,			return_tensors='pt'							)

             lowercase__			:		Optional[int]       =	ReformerConfig()
             # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024)
             lowercase__			:		Dict       =	encoded_sequence['input_ids'].shape
             lowercase__			:		Dict       =	ReformerModel(a							)

             # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320)
             assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size

             with torch.no_grad():
                    model(**a							)
                    model(**a							)


      @slow
      def 		_UpperCAmelCase       (   self							)       ->					Optional[Any]:
             # fmt: off
             lowercase__			:		Optional[Any]       =	{'input_ids': [[1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 7, 5_1, 2_7_9, 5_8, 7, 7_6, 2_5, 6_9, 2_7_8], [1_4_0, 2_4_3, 2_6_4, 1_3_4, 1_7, 2_6_7, 7_7, 2_6_3, 2_2, 2_6_2, 2_9_7, 2_5_8, 3_0_4, 1_7_7, 2_7_9, 2_6_6, 1_4, 8_9, 1_3, 3_5, 2_6_1, 2_9_9, 2_7_2, 1_3_7, 2_7_5, 2_7_8]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}  # noqa: E501
             # fmt: on

             # This tokenizer does not know some characters like ")".
             # That is the reason why we use very simple texts here.
             # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064
             lowercase__			:		List[Any]       =	[
                 'This is a very simple sentence.',
                 'The quick brown fox jumps over the lazy dog.',
             ]

             self.tokenizer_integration_test_util(
                 expected_encoding=a		,			model_name='google/reformer-crime-and-punishment'		,			revision='0e6c3decb8211d49bf881013425dc8b0448b3f5a'		,			padding=a		,			sequences=a		,			)






import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

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


if is_torch_available():
						import torch

						from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

						if is_vision_available():
												from transformers import MaskaFormerImageProcessor

if is_vision_available():
						from PIL import Image



class 				__snake_case						:




							def __init__(       self     :       Optional[Any]				,				A_     :       Dict				,				A_     :       Optional[Any]=2				,				A_     :       List[str]=True				,				A_     :       Dict=False				,				A_     :       Union[str, Any]=1_0				,				A_     :       Optional[Any]=3				,				A_     :       str=3_2 * 8				,				A_     :       List[str]=3_2 * 8				,				A_     :       Dict=4				,				A_     :       List[Any]=6_4				,				):
									lowerCAmelCase_			:     Any									= parent
									lowerCAmelCase_			:     Union[str, Any]									= batch_size
									lowerCAmelCase_			:     List[Any]									= is_training
									lowerCAmelCase_			:     int									= use_auxiliary_loss
									lowerCAmelCase_			:     str									= num_queries
									lowerCAmelCase_			:     Any									= num_channels
									lowerCAmelCase_			:     Union[str, Any]									= min_size
									lowerCAmelCase_			:     Optional[int]									= max_size
									lowerCAmelCase_			:     List[str]									= num_labels
									lowerCAmelCase_			:     str									= hidden_dim
									lowerCAmelCase_			:     List[str]									= hidden_dim




							def    UpperCAmelCase__			(       self     :       List[str]):
									lowerCAmelCase_			:     str									= floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to(
									    A_)

									lowerCAmelCase_			:     Optional[int]									= torch.ones([self.batch_size, self.min_size, self.max_size]				,				device=A_)

									lowerCAmelCase_			:     List[str]									= (
									    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]				,				device=A_) > 0.5
									).float()
									lowerCAmelCase_			:     Any									= (torch.rand((self.batch_size, self.num_labels)				,				device=A_) > 0.5).long()

									lowerCAmelCase_			:     Optional[int]									= self.get_config()
									return config, pixel_values, pixel_mask, mask_labels, class_labels




							def    UpperCAmelCase__			(       self     :       Optional[Any]):
									lowerCAmelCase_			:     Optional[Any]									= MaskaFormerConfig(
									    hidden_size=self.hidden_dim				,				)
									lowerCAmelCase_			:     Dict									= self.num_queries
									lowerCAmelCase_			:     str									= self.num_labels

									lowerCAmelCase_			:     str									= [1, 1, 1, 1]
									lowerCAmelCase_			:     Dict									= self.num_channels

									lowerCAmelCase_			:     List[str]									= 6_4
									lowerCAmelCase_			:     Union[str, Any]									= 1_2_8
									lowerCAmelCase_			:     str									= self.hidden_dim
									lowerCAmelCase_			:     Optional[Any]									= self.hidden_dim
									lowerCAmelCase_			:     Any									= self.hidden_dim
									return config




							def    UpperCAmelCase__			(       self     :       Union[str, Any]):
									lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_			:     Optional[Any]									= self.prepare_config_and_inputs()
									lowerCAmelCase_			:     List[str]									= {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
									return config, inputs_dict




							def    UpperCAmelCase__			(       self     :       Optional[Any]				,				A_     :       List[Any]				,				A_     :       Tuple):
									lowerCAmelCase_			:     Any									= output.encoder_hidden_states
									lowerCAmelCase_			:     int									= output.pixel_decoder_hidden_states
									lowerCAmelCase_			:     Union[str, Any]									= output.transformer_decoder_hidden_states

									self.parent.assertTrue(len(A_)				,				len(config.backbone_config.depths))
									self.parent.assertTrue(len(A_)				,				len(config.backbone_config.depths))
									self.parent.assertTrue(len(A_)				,				config.decoder_layers)




							def    UpperCAmelCase__			(       self     :       Optional[int]				,				A_     :       int				,				A_     :       Union[str, Any]				,				A_     :       Union[str, Any]				,				A_     :       str=False):
									with torch.no_grad():
											lowerCAmelCase_			:     Union[str, Any]									= MaskaFormerModel(config=A_)
											model.to(A_)
											model.eval()

											lowerCAmelCase_			:     List[Any]									= model(pixel_values=A_				,				pixel_mask=A_)
											lowerCAmelCase_			:     Any									= model(A_				,				output_hidden_states=A_)

									self.parent.assertEqual(
									    output.transformer_decoder_last_hidden_state.shape				,				(self.batch_size, self.num_queries, self.hidden_dim)				,				)
									# let's ensure the other two hidden state exists
									self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None)
									self.parent.assertTrue(output.encoder_last_hidden_state is not None)

									if output_hidden_states:
											self.check_output_hidden_state(A_				,				A_)







							def    UpperCAmelCase__			(       self     :       List[Any]				,				A_     :       Union[str, Any]				,				A_     :       List[str]				,				A_     :       List[Any]				,				A_     :       Tuple				,				A_     :       Any):
									lowerCAmelCase_			:     Any									= MaskaFormerForUniversalSegmentation(config=A_)
									model.to(A_)
									model.eval()

									def comm_check_on_output(A_     :       Optional[int]):
											# let's still check that all the required stuff is there
											self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None)
											self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None)
											self.parent.assertTrue(result.encoder_last_hidden_state is not None)
											# okay, now we need to check the logits shape
											# due to the encoder compression, masks have a //4 spatial size
											self.parent.assertEqual(
											    result.masks_queries_logits.shape				,				(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)				,				)
											# + 1 for null class
											self.parent.assertEqual(
											    result.class_queries_logits.shape				,				(self.batch_size, self.num_queries, self.num_labels + 1))

									with torch.no_grad():
											lowerCAmelCase_			:     List[Any]									= model(pixel_values=A_				,				pixel_mask=A_)
											lowerCAmelCase_			:     List[Any]									= model(A_)

											comm_check_on_output(A_)

											lowerCAmelCase_			:     Any									= model(
											    pixel_values=A_				,				pixel_mask=A_				,				mask_labels=A_				,				class_labels=A_)

									comm_check_on_output(A_)

									self.parent.assertTrue(result.loss is not None)
									self.parent.assertEqual(result.loss.shape				,				torch.Size([1]))





@require_torch
class 				__snake_case						(     UpperCamelCase_						,UpperCamelCase_						,unittest.TestCase						):
							_a			      = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
							_a			      = {'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {}

							_a			      = False
							_a			      = False
							_a			      = False
							_a			      = False




							def    UpperCAmelCase__			(       self     :       Any):
									lowerCAmelCase_			:     Tuple									= MaskaFormerModelTester(self)
									lowerCAmelCase_			:     Optional[Any]									= ConfigTester(self				,				config_class=A_				,				has_text_modality=A_)




							def    UpperCAmelCase__			(       self     :       Optional[int]):
									self.config_tester.run_common_tests()




							def    UpperCAmelCase__			(       self     :       Optional[Any]):
									lowerCAmelCase_					,  lowerCAmelCase_			:     Dict									= self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.create_and_check_maskaformer_model(A_				,				**A_				,				output_hidden_states=A_)




							def    UpperCAmelCase__			(       self     :       List[Any]):
									lowerCAmelCase_			:     int									= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A_)




							@unittest.skip(reason='''Mask2Former does not use inputs_embeds''')
							def    UpperCAmelCase__			(       self     :       Optional[Any]):
									pass




							@unittest.skip(reason='''Mask2Former does not have a get_input_embeddings method''')
							def    UpperCAmelCase__			(       self     :       str):
									pass




							@unittest.skip(reason='''Mask2Former is not a generative model''')
							def    UpperCAmelCase__			(       self     :       int):
									pass




							@unittest.skip(reason='''Mask2Former does not use token embeddings''')
							def    UpperCAmelCase__			(       self     :       Tuple):
									pass




							@require_torch_multi_gpu
							@unittest.skip(
							    reason='''Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''')
							def    UpperCAmelCase__			(       self     :       List[str]):
									pass




							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
							def    UpperCAmelCase__			(       self     :       Tuple):
									pass




							def    UpperCAmelCase__			(       self     :       Dict):
									lowerCAmelCase_					,  lowerCAmelCase_			:     List[str]									= self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											lowerCAmelCase_			:     Union[str, Any]									= model_class(A_)
											lowerCAmelCase_			:     Dict									= inspect.signature(model.forward)
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											lowerCAmelCase_			:     Tuple									= [*signature.parameters.keys()]

											lowerCAmelCase_			:     Dict									= ['''pixel_values''']
											self.assertListEqual(arg_names[:1]				,				A_)




							@slow
							def    UpperCAmelCase__			(       self     :       List[str]):
									for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
											lowerCAmelCase_			:     List[str]									= MaskaFormerModel.from_pretrained(A_)
											self.assertIsNotNone(A_)




							def    UpperCAmelCase__			(       self     :       Optional[Any]):
									lowerCAmelCase_			:     Optional[int]									= (self.model_tester.min_size,) * 2
									lowerCAmelCase_			:     str									= {
									    '''pixel_values''': torch.randn((2, 3, *size)				,				device=A_),
									    '''mask_labels''': torch.randn((2, 1_0, *size)				,				device=A_),
									    '''class_labels''': torch.zeros(2				,				1_0				,				device=A_).long(),
									}
									lowerCAmelCase_			:     Union[str, Any]									= self.model_tester.get_config()

									lowerCAmelCase_			:     Any									= MaskaFormerForUniversalSegmentation(A_).to(A_)
									lowerCAmelCase_			:     Union[str, Any]									= model(**A_)
									self.assertTrue(outputs.loss is not None)




							def    UpperCAmelCase__			(       self     :       Tuple):
									lowerCAmelCase_					,  lowerCAmelCase_			:     Dict									= self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.create_and_check_maskaformer_model(A_				,				**A_				,				output_hidden_states=A_)




							def    UpperCAmelCase__			(       self     :       Union[str, Any]):
									lowerCAmelCase_					,  lowerCAmelCase_			:     Tuple									= self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											lowerCAmelCase_			:     Union[str, Any]									= model_class(A_).to(A_)
											lowerCAmelCase_			:     List[str]									= model(**A_				,				output_attentions=A_)
											self.assertTrue(outputs.attentions is not None)




							def    UpperCAmelCase__			(       self     :       List[Any]):
									if not self.model_tester.is_training:
											return

									lowerCAmelCase_			:     Dict									= self.all_model_classes[1]
									lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_			:     str									= self.model_tester.prepare_config_and_inputs()

									lowerCAmelCase_			:     Optional[Any]									= model_class(A_)
									model.to(A_)
									model.train()

									lowerCAmelCase_			:     List[Any]									= model(A_				,				mask_labels=A_				,				class_labels=A_).loss
									loss.backward()







							def    UpperCAmelCase__			(       self     :       str):
									lowerCAmelCase_			:     str									= self.all_model_classes[1]
									lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_			:     Optional[Any]									= self.model_tester.prepare_config_and_inputs()
									lowerCAmelCase_			:     Optional[Any]									= True
									lowerCAmelCase_			:     Dict									= True

									lowerCAmelCase_			:     Any									= model_class(A_).to(A_)
									model.train()

									lowerCAmelCase_			:     List[str]									= model(A_				,				mask_labels=A_				,				class_labels=A_)

									lowerCAmelCase_			:     int									= outputs.encoder_hidden_states[0]
									encoder_hidden_states.retain_grad()

									lowerCAmelCase_			:     str									= outputs.pixel_decoder_hidden_states[0]
									pixel_decoder_hidden_states.retain_grad()

									lowerCAmelCase_			:     Dict									= outputs.transformer_decoder_hidden_states[0]
									transformer_decoder_hidden_states.retain_grad()

									lowerCAmelCase_			:     str									= outputs.attentions[0]
									attentions.retain_grad()

									outputs.loss.backward(retain_graph=A_)

									self.assertIsNotNone(encoder_hidden_states.grad)
									self.assertIsNotNone(pixel_decoder_hidden_states.grad)
									self.assertIsNotNone(transformer_decoder_hidden_states.grad)
									self.assertIsNotNone(attentions.grad)





A__  :  int								=					1E-4


def 			UpperCamelCase(  ):
		lowerCAmelCase_			:     Optional[int]									= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
		return image





@require_vision
@slow
class 				__snake_case						(     unittest.TestCase						):




							@cached_property
							def    UpperCAmelCase__			(       self     :       Tuple):
									return "facebook/mask2former-swin-small-coco-instance"




							@cached_property
							def    UpperCAmelCase__			(       self     :       Optional[Any]):
									return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None




							def    UpperCAmelCase__			(       self     :       int):
									lowerCAmelCase_			:     Any									= MaskaFormerModel.from_pretrained(self.model_checkpoints).to(A_)
									lowerCAmelCase_			:     str									= self.default_image_processor
									lowerCAmelCase_			:     Tuple									= prepare_img()
									lowerCAmelCase_			:     Any									= image_processor(A_				,				return_tensors='''pt''').to(A_)
									lowerCAmelCase_			:     str									= inputs['''pixel_values'''].shape
									# check size is divisible by 32
									self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0)
									# check size
									self.assertEqual(A_				,				(1, 3, 3_8_4, 3_8_4))

									with torch.no_grad():
											lowerCAmelCase_			:     Optional[Any]									= model(**A_)

									lowerCAmelCase_			:     List[str]									= torch.tensor(
									    [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]]).to(A_)
									self.assertTrue(
									    torch.allclose(
									        outputs.encoder_last_hidden_state[0, 0, :3, :3]				,				A_				,				atol=A_))

									lowerCAmelCase_			:     Union[str, Any]									= torch.tensor(
									    [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]]).to(A_)
									self.assertTrue(
									    torch.allclose(
									        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]				,				A_				,				atol=A_))

									lowerCAmelCase_			:     Optional[int]									= torch.tensor(
									    [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]]).to(A_)
									self.assertTrue(
									    torch.allclose(
									        outputs.transformer_decoder_last_hidden_state[0, :3, :3]				,				A_				,				atol=A_))




							def    UpperCAmelCase__			(       self     :       List[Any]):
									lowerCAmelCase_			:     List[str]									= MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(A_).eval()
									lowerCAmelCase_			:     Optional[int]									= self.default_image_processor
									lowerCAmelCase_			:     List[Any]									= prepare_img()
									lowerCAmelCase_			:     Tuple									= image_processor(A_				,				return_tensors='''pt''').to(A_)
									lowerCAmelCase_			:     Union[str, Any]									= inputs['''pixel_values'''].shape
									# check size is divisible by 32
									self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0)
									# check size
									self.assertEqual(A_				,				(1, 3, 3_8_4, 3_8_4))

									with torch.no_grad():
											lowerCAmelCase_			:     Tuple									= model(**A_)
									# masks_queries_logits
									lowerCAmelCase_			:     int									= outputs.masks_queries_logits
									self.assertEqual(
									    masks_queries_logits.shape				,				(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4))
									lowerCAmelCase_			:     Tuple									= [
									    [-8.7839, -9.0056, -8.8121],
									    [-7.4104, -7.0313, -6.5401],
									    [-6.6105, -6.3427, -6.4675],
									]
									lowerCAmelCase_			:     Optional[Any]									= torch.tensor(A_).to(A_)
									self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]				,				A_				,				atol=A_))
									# class_queries_logits
									lowerCAmelCase_			:     Dict									= outputs.class_queries_logits
									self.assertEqual(class_queries_logits.shape				,				(1, model.config.num_queries, model.config.num_labels + 1))
									lowerCAmelCase_			:     Any									= torch.tensor(
									    [
									        [1.8324, -8.0835, -4.1922],
									        [0.8450, -9.0050, -3.6053],
									        [0.3045, -7.7293, -3.0275],
									    ]).to(A_)
									self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]				,				A_				,				atol=A_))







							def    UpperCAmelCase__			(       self     :       Any):
									lowerCAmelCase_			:     List[str]									= MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(A_).eval()
									lowerCAmelCase_			:     Optional[Any]									= self.default_image_processor

									lowerCAmelCase_			:     Optional[Any]									= image_processor(
									    [np.zeros((3, 8_0_0, 1_3_3_3)), np.zeros((3, 8_0_0, 1_3_3_3))]				,				segmentation_maps=[np.zeros((3_8_4, 3_8_4)).astype(np.floataa), np.zeros((3_8_4, 3_8_4)).astype(np.floataa)]				,				return_tensors='''pt'''				,				)

									lowerCAmelCase_			:     Dict									= inputs['''pixel_values'''].to(A_)
									lowerCAmelCase_			:     Tuple									= [el.to(A_) for el in inputs['''mask_labels''']]
									lowerCAmelCase_			:     str									= [el.to(A_) for el in inputs['''class_labels''']]

									with torch.no_grad():
											lowerCAmelCase_			:     int									= model(**A_)

									self.assertTrue(outputs.loss is not None)





