



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)










from datetime import datetime as dt
import os

from github import Github


A__  :  List[str]								=					[
    '''good first issue''',
    '''good second issue''',
    '''good difficult issue''',
    '''feature request''',
    '''new model''',
    '''wip''',
]


def 			UpperCamelCase(  ):
		lowerCAmelCase_			:     Union[str, Any]									= Github(os.environ['''GITHUB_TOKEN'''] )
		lowerCAmelCase_			:     Tuple									= g.get_repo('''huggingface/transformers''' )
		lowerCAmelCase_			:     int									= repo.get_issues(state='''open''' )

		for issue in open_issues:
				lowerCAmelCase_			:     Optional[Any]									= sorted([comment for comment in issue.get_comments()]     ,key=lambda __UpperCamelCase : i.created_at     ,reverse=__UpperCamelCase )
				lowerCAmelCase_			:     Tuple									= comments[0] if len(__UpperCamelCase ) > 0 else None
				if (
				    last_comment is not None
				    and last_comment.user.login == "github-actions[bot]"
				    and (dt.utcnow() - issue.updated_at).days > 7
				    and (dt.utcnow() - issue.created_at).days >= 30
				    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
				):
						# print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.")
						issue.edit(state='''closed''' )
				elif (
				    (dt.utcnow() - issue.updated_at).days > 23
				    and (dt.utcnow() - issue.created_at).days >= 30
				    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
				):
						# print(f"Would add stale comment to {issue.number}")
						issue.create_comment(
						    '''This issue has been automatically marked as stale because it has not had '''
						    '''recent activity. If you think this still needs to be addressed '''
						    '''please comment on this thread.\n\nPlease note that issues that do not follow the '''
						    '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) '''
						    '''are likely to be ignored.''' )


if __name__ == "__main__":
						main()





