



import argparse
import json
import os
from collections import OrderedDict

import torch

from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer
from transformers.tokenization_utils_base import AddedToken


@torch.no_grad()
def 			UpperCamelCase(  __UpperCamelCase							:		Any     ,__UpperCamelCase							:		Union[str, Any]     ,__UpperCamelCase							:		List[str]     ,__UpperCamelCase							:		Dict     ,__UpperCamelCase							:		Optional[Any] ):
		# Load configuration defined in the metadata file
		with open(__UpperCamelCase ) as metadata_file:
				lowerCAmelCase_			:     Tuple									= json.load(__UpperCamelCase )
		lowerCAmelCase_			:     Tuple									= LukeConfig(use_entity_aware_attention=__UpperCamelCase     ,**metadata['''model_config'''] )

		# Load in the weights from the checkpoint_path
		lowerCAmelCase_			:     int									= torch.load(__UpperCamelCase     ,map_location='''cpu''' )['''module''']

		# Load the entity vocab file
		lowerCAmelCase_			:     Dict									= load_original_entity_vocab(__UpperCamelCase )
		# add an entry for [MASK2]
		lowerCAmelCase_			:     Union[str, Any]									= max(entity_vocab.values() ) + 1
		config.entity_vocab_size += 1

		lowerCAmelCase_			:     Optional[Any]									= XLMRobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] )

		# Add special tokens to the token vocabulary for downstream tasks
		lowerCAmelCase_			:     int									= AddedToken('''<ent>'''     ,lstrip=__UpperCamelCase     ,rstrip=__UpperCamelCase )
		lowerCAmelCase_			:     List[str]									= AddedToken('''<ent2>'''     ,lstrip=__UpperCamelCase     ,rstrip=__UpperCamelCase )
		tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} )
		config.vocab_size += 2

		print(f"""Saving tokenizer to {pytorch_dump_folder_path}""" )
		tokenizer.save_pretrained(__UpperCamelCase )
		with open(os.path.join(__UpperCamelCase     ,'''tokenizer_config.json''' )     ,'''r''' ) as f:
				lowerCAmelCase_			:     str									= json.load(__UpperCamelCase )
		lowerCAmelCase_			:     Any									= '''MLukeTokenizer'''
		with open(os.path.join(__UpperCamelCase     ,'''tokenizer_config.json''' )     ,'''w''' ) as f:
				json.dump(__UpperCamelCase     ,__UpperCamelCase )

		with open(os.path.join(__UpperCamelCase     ,MLukeTokenizer.vocab_files_names['''entity_vocab_file'''] )     ,'''w''' ) as f:
				json.dump(__UpperCamelCase     ,__UpperCamelCase )

		lowerCAmelCase_			:     int									= MLukeTokenizer.from_pretrained(__UpperCamelCase )

		# Initialize the embeddings of the special tokens
		lowerCAmelCase_			:     Dict									= tokenizer.convert_tokens_to_ids(['''@'''] )[0]
		lowerCAmelCase_			:     Optional[int]									= tokenizer.convert_tokens_to_ids(['''#'''] )[0]

		lowerCAmelCase_			:     List[Any]									= state_dict['''embeddings.word_embeddings.weight''']
		lowerCAmelCase_			:     Optional[Any]									= word_emb[ent_init_index].unsqueeze(0 )
		lowerCAmelCase_			:     List[str]									= word_emb[enta_init_index].unsqueeze(0 )
		lowerCAmelCase_			:     Optional[Any]									= torch.cat([word_emb, ent_emb, enta_emb] )
		# add special tokens for 'entity_predictions.bias'
		for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]:
				lowerCAmelCase_			:     Optional[Any]									= state_dict[bias_name]
				lowerCAmelCase_			:     List[Any]									= decoder_bias[ent_init_index].unsqueeze(0 )
				lowerCAmelCase_			:     List[Any]									= decoder_bias[enta_init_index].unsqueeze(0 )
				lowerCAmelCase_			:     Optional[Any]									= torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] )

		# Initialize the query layers of the entity-aware self-attention mechanism
		for layer_index in range(config.num_hidden_layers ):
				for matrix_name in ["query.weight", "query.bias"]:
						lowerCAmelCase_			:     Union[str, Any]									= f"""encoder.layer.{layer_index}.attention.self."""
						lowerCAmelCase_			:     List[str]									= state_dict[prefix + matrix_name]
						lowerCAmelCase_			:     Optional[Any]									= state_dict[prefix + matrix_name]
						lowerCAmelCase_			:     Dict									= state_dict[prefix + matrix_name]

    # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks
		lowerCAmelCase_			:     str									= state_dict['''entity_embeddings.entity_embeddings.weight''']
		lowerCAmelCase_			:     Tuple									= entity_emb[entity_vocab['''[MASK]''']].unsqueeze(0 )
		lowerCAmelCase_			:     int									= torch.cat([entity_emb, entity_mask_emb] )
		# add [MASK2] for 'entity_predictions.bias'
		lowerCAmelCase_			:     Any									= state_dict['''entity_predictions.bias''']
		lowerCAmelCase_			:     Tuple									= entity_prediction_bias[entity_vocab['''[MASK]''']].unsqueeze(0 )
		lowerCAmelCase_			:     Union[str, Any]									= torch.cat([entity_prediction_bias, entity_mask_bias] )

		lowerCAmelCase_			:     Dict									= LukeForMaskedLM(config=__UpperCamelCase ).eval()

		state_dict.pop('''entity_predictions.decoder.weight''' )
		state_dict.pop('''lm_head.decoder.weight''' )
		state_dict.pop('''lm_head.decoder.bias''' )
		lowerCAmelCase_			:     str									= OrderedDict()
		for key, value in state_dict.items():
				if not (key.startswith('''lm_head''' ) or key.startswith('''entity_predictions''' )):
						lowerCAmelCase_			:     Tuple									= state_dict[key]
				else:
						lowerCAmelCase_			:     Any									= state_dict[key]

		lowerCAmelCase_					,  lowerCAmelCase_			:     int									= model.load_state_dict(__UpperCamelCase     ,strict=__UpperCamelCase )

		if set(__UpperCamelCase ) != {"luke.embeddings.position_ids"}:
				raise ValueError(f"""Unexpected unexpected_keys: {unexpected_keys}""" )
		if set(__UpperCamelCase ) != {
		    "lm_head.decoder.weight",
		    "lm_head.decoder.bias",
		    "entity_predictions.decoder.weight",
		}:
				raise ValueError(f"""Unexpected missing_keys: {missing_keys}""" )

		model.tie_weights()
		assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all()
		assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all()

		# Check outputs
		lowerCAmelCase_			:     Union[str, Any]									= MLukeTokenizer.from_pretrained(__UpperCamelCase     ,task='''entity_classification''' )

		lowerCAmelCase_			:     Any									= '''ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).'''
		lowerCAmelCase_			:     Union[str, Any]									= (0, 9)
		lowerCAmelCase_			:     Dict									= tokenizer(__UpperCamelCase     ,entity_spans=[span]     ,return_tensors='''pt''' )

		lowerCAmelCase_			:     Any									= model(**__UpperCamelCase )

		# Verify word hidden states
		if model_size == "large":
				raise NotImplementedError
		else:  # base
				lowerCAmelCase_			:     Union[str, Any]									= torch.Size((1, 33, 768) )
				lowerCAmelCase_			:     Any									= torch.tensor([[0.0_8_9_2, 0.0_5_9_6, -0.2_8_1_9], [0.0_1_3_4, 0.1_1_9_9, 0.0_5_7_3], [-0.0_1_6_9, 0.0_9_2_7, 0.0_6_4_4]] )

		if not (outputs.last_hidden_state.shape == expected_shape):
				raise ValueError(
				    f"""Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}""" )
		if not torch.allclose(outputs.last_hidden_state[0, :3, :3]     ,__UpperCamelCase     ,atol=1e-4 ):
				raise ValueError

		# Verify entity hidden states
		if model_size == "large":
				raise NotImplementedError
		else:  # base
				lowerCAmelCase_			:     List[str]									= torch.Size((1, 1, 768) )
				lowerCAmelCase_			:     Dict									= torch.tensor([[-0.1_4_8_2, 0.0_6_0_9, 0.0_3_2_2]] )

		if not (outputs.entity_last_hidden_state.shape == expected_shape):
				raise ValueError(
				    f"""Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is"""
				    f""" {expected_shape}""" )
		if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3]     ,__UpperCamelCase     ,atol=1e-4 ):
				raise ValueError

		# Verify masked word/entity prediction
		lowerCAmelCase_			:     Union[str, Any]									= MLukeTokenizer.from_pretrained(__UpperCamelCase )
		lowerCAmelCase_			:     str									= '''Tokyo is the capital of <mask>.'''
		lowerCAmelCase_			:     Dict									= (24, 30)
		lowerCAmelCase_			:     List[str]									= tokenizer(__UpperCamelCase     ,entity_spans=[span]     ,return_tensors='''pt''' )

		lowerCAmelCase_			:     Optional[int]									= model(**__UpperCamelCase )

		lowerCAmelCase_			:     str									= encoding['''input_ids'''][0].tolist()
		lowerCAmelCase_			:     Union[str, Any]									= input_ids.index(tokenizer.convert_tokens_to_ids('''<mask>''' ) )
		lowerCAmelCase_			:     Optional[int]									= outputs.logits[0][mask_position_id].argmax(dim=-1 )
		assert "Japan" == tokenizer.decode(__UpperCamelCase )

		lowerCAmelCase_			:     str									= outputs.entity_logits[0][0].argmax().item()
		lowerCAmelCase_			:     Optional[int]									= [
		    entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id
		]
		assert [e for e in multilingual_predicted_entities if e.startswith('''en:''' )][0] == "en:Japan"

		# Finally, save our PyTorch model and tokenizer
		print('''Saving PyTorch model to {}'''.format(__UpperCamelCase ) )
		model.save_pretrained(__UpperCamelCase )


def 			UpperCamelCase(  __UpperCamelCase							:		List[Any] ):
		lowerCAmelCase_			:     int									= ['''[MASK]''', '''[PAD]''', '''[UNK]''']

		lowerCAmelCase_			:     Dict									= [json.loads(__UpperCamelCase ) for line in open(__UpperCamelCase )]

		lowerCAmelCase_			:     List[str]									= {}
		for entry in data:
				lowerCAmelCase_			:     str									= entry['''id''']
				for entity_name, language in entry["entities"]:
						if entity_name in SPECIAL_TOKENS:
								lowerCAmelCase_			:     Optional[int]									= entity_id
								break
						lowerCAmelCase_			:     Tuple									= f"""{language}:{entity_name}"""
						lowerCAmelCase_			:     Optional[int]									= entity_id
		return new_mapping


if __name__ == "__main__":
						A__  :  str								=					argparse.ArgumentParser()
						# Required parameters
						parser.add_argument('''--checkpoint_path''', type=str, help='''Path to a pytorch_model.bin file.''')
						parser.add_argument(
						    '''--metadata_path''', default=None, type=str, help='''Path to a metadata.json file, defining the configuration.'''
						)
						parser.add_argument(
						    '''--entity_vocab_path''',
						    default=None,
						    type=str,
						    help='''Path to an entity_vocab.tsv file, containing the entity vocabulary.''',
						)
						parser.add_argument(
						    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to where to dump the output PyTorch model.'''
						)
						parser.add_argument(
						    '''--model_size''', default='''base''', type=str, choices=['''base''', '''large'''], help='''Size of the model to be converted.'''
						)
						A__  :  Dict								=					parser.parse_args()
						convert_luke_checkpoint(
						    args.checkpoint_path,
						    args.metadata_path,
						    args.entity_vocab_path,
						    args.pytorch_dump_folder_path,
						    args.model_size,
						)










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)





