






import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging


__A      =				logging.get_logger(__name__)

__A      =				'▁'

__A      =				{'vocab_file': 'sentencepiece.bpe.model'}

__A      =				{
    'vocab_file': {
        'facebook/nllb-200-distilled-600M': (
            'https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model'
        ),
    }
}

__A      =				{
    'facebook/nllb-200-distilled-600M': 1024,
}

# fmt: off
__A      =				['ace_Arab', 'ace_Latn', 'acm_Arab', 'acq_Arab', 'aeb_Arab', 'afr_Latn', 'ajp_Arab', 'aka_Latn', 'amh_Ethi', 'apc_Arab', 'arb_Arab', 'ars_Arab', 'ary_Arab', 'arz_Arab', 'asm_Beng', 'ast_Latn', 'awa_Deva', 'ayr_Latn', 'azb_Arab', 'azj_Latn', 'bak_Cyrl', 'bam_Latn', 'ban_Latn', 'bel_Cyrl', 'bem_Latn', 'ben_Beng', 'bho_Deva', 'bjn_Arab', 'bjn_Latn', 'bod_Tibt', 'bos_Latn', 'bug_Latn', 'bul_Cyrl', 'cat_Latn', 'ceb_Latn', 'ces_Latn', 'cjk_Latn', 'ckb_Arab', 'crh_Latn', 'cym_Latn', 'dan_Latn', 'deu_Latn', 'dik_Latn', 'dyu_Latn', 'dzo_Tibt', 'ell_Grek', 'eng_Latn', 'epo_Latn', 'est_Latn', 'eus_Latn', 'ewe_Latn', 'fao_Latn', 'pes_Arab', 'fij_Latn', 'fin_Latn', 'fon_Latn', 'fra_Latn', 'fur_Latn', 'fuv_Latn', 'gla_Latn', 'gle_Latn', 'glg_Latn', 'grn_Latn', 'guj_Gujr', 'hat_Latn', 'hau_Latn', 'heb_Hebr', 'hin_Deva', 'hne_Deva', 'hrv_Latn', 'hun_Latn', 'hye_Armn', 'ibo_Latn', 'ilo_Latn', 'ind_Latn', 'isl_Latn', 'ita_Latn', 'jav_Latn', 'jpn_Jpan', 'kab_Latn', 'kac_Latn', 'kam_Latn', 'kan_Knda', 'kas_Arab', 'kas_Deva', 'kat_Geor', 'knc_Arab', 'knc_Latn', 'kaz_Cyrl', 'kbp_Latn', 'kea_Latn', 'khm_Khmr', 'kik_Latn', 'kin_Latn', 'kir_Cyrl', 'kmb_Latn', 'kon_Latn', 'kor_Hang', 'kmr_Latn', 'lao_Laoo', 'lvs_Latn', 'lij_Latn', 'lim_Latn', 'lin_Latn', 'lit_Latn', 'lmo_Latn', 'ltg_Latn', 'ltz_Latn', 'lua_Latn', 'lug_Latn', 'luo_Latn', 'lus_Latn', 'mag_Deva', 'mai_Deva', 'mal_Mlym', 'mar_Deva', 'min_Latn', 'mkd_Cyrl', 'plt_Latn', 'mlt_Latn', 'mni_Beng', 'khk_Cyrl', 'mos_Latn', 'mri_Latn', 'zsm_Latn', 'mya_Mymr', 'nld_Latn', 'nno_Latn', 'nob_Latn', 'npi_Deva', 'nso_Latn', 'nus_Latn', 'nya_Latn', 'oci_Latn', 'gaz_Latn', 'ory_Orya', 'pag_Latn', 'pan_Guru', 'pap_Latn', 'pol_Latn', 'por_Latn', 'prs_Arab', 'pbt_Arab', 'quy_Latn', 'ron_Latn', 'run_Latn', 'rus_Cyrl', 'sag_Latn', 'san_Deva', 'sat_Beng', 'scn_Latn', 'shn_Mymr', 'sin_Sinh', 'slk_Latn', 'slv_Latn', 'smo_Latn', 'sna_Latn', 'snd_Arab', 'som_Latn', 'sot_Latn', 'spa_Latn', 'als_Latn', 'srd_Latn', 'srp_Cyrl', 'ssw_Latn', 'sun_Latn', 'swe_Latn', 'swh_Latn', 'szl_Latn', 'tam_Taml', 'tat_Cyrl', 'tel_Telu', 'tgk_Cyrl', 'tgl_Latn', 'tha_Thai', 'tir_Ethi', 'taq_Latn', 'taq_Tfng', 'tpi_Latn', 'tsn_Latn', 'tso_Latn', 'tuk_Latn', 'tum_Latn', 'tur_Latn', 'twi_Latn', 'tzm_Tfng', 'uig_Arab', 'ukr_Cyrl', 'umb_Latn', 'urd_Arab', 'uzn_Latn', 'vec_Latn', 'vie_Latn', 'war_Latn', 'wol_Latn', 'xho_Latn', 'ydd_Hebr', 'yor_Latn', 'yue_Hant', 'zho_Hans', 'zho_Hant', 'zul_Latn']





class 						SCREAMING_SNAKE_CASE				( snake_case					):





							"""simple docstring"""

							A_						  =					VOCAB_FILES_NAMES
							A_						  =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							A_						  =					PRETRAINED_VOCAB_FILES_MAP
							A_						  =					["input_ids", "attention_mask"]

							A_						  =					[]
							A_						  =					[]

							def __init__(  self:   Dict		,     __A:   List[Any]		,     __A:   Optional[Any]="<s>"		,     __A:   Any="</s>"		,     __A:   List[Any]="</s>"		,     __A:   Optional[Any]="<s>"		,     __A:   Optional[int]="<unk>"		,     __A:   Any="<pad>"		,     __A:   List[str]="<mask>"		,     __A:   Union[str, Any]=None		,     __A:   Tuple=None		,     __A:   Tuple=None		,     __A:   Optional[Dict[str, Any]] = None		,     __A:   Optional[Any]=None		,     __A:   Optional[int]=False		,     **__A:   Optional[Any]		,     )    ->				str:
												# Mask token behave like a normal word, i.e. include the space before it
												_A								= AddedToken(__A		,     lstrip=__A		,     rstrip=__A   ) if isinstance(__A		,     __A   ) else mask_token

												_A								= {} if sp_model_kwargs is None else sp_model_kwargs
												_A								= legacy_behaviour

												super().__init__(
												    bos_token=__A		,     eos_token=__A		,     unk_token=__A		,     sep_token=__A		,     cls_token=__A		,     pad_token=__A		,     mask_token=__A		,     tokenizer_file=__A		,     src_lang=__A		,     tgt_lang=__A		,     additional_special_tokens=__A		,     sp_model_kwargs=self.sp_model_kwargs		,     legacy_behaviour=__A		,     **__A		,     )

												_A								= spm.SentencePieceProcessor(**self.sp_model_kwargs   )
												self.sp_model.Load(str(__A   )   )
												_A								= vocab_file
												# Original fairseq vocab and spm vocab must be "aligned":
												# Vocab    |    0    |    1    |   2    |    3    |  4   |  5   |  6   |   7  |   8  |  9
												# -------- | ------- | ------- | ------ | ------- | ---- | ---- | ---- | ---- | ---- | ----
												# fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a'
												# spm      | '<unk>' | '<s>'   | '</s>' | 'an'    | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s'

												# Mimic fairseq token-to-id alignment for the first 4 token
												_A								= {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

												# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
												_A								= 1

												_A								= len(self.sp_model   )
												_A								= {
												    code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__A   )
												}
												_A								= {v: k for k, v in self.lang_code_to_id.items()}
												_A								= len(self.sp_model   ) + len(self.lang_code_to_id   ) + self.fairseq_offset

												self.fairseq_tokens_to_ids.update(self.lang_code_to_id   )
												_A								= {v: k for k, v in self.fairseq_tokens_to_ids.items()}
												_A								= list(self.lang_code_to_id.keys()   )

												if additional_special_tokens is not None:
																	# Only add those special tokens if they are not already there.
																	self._additional_special_tokens.extend(
																	    [t for t in additional_special_tokens if t not in self._additional_special_tokens]   )

												_A								= src_lang if src_lang is not None else '''eng_Latn'''
												_A								= self.lang_code_to_id[self._src_lang]
												_A								= tgt_lang
												self.set_src_lang_special_tokens(self._src_lang   )

							def __getstate__(  self:   Any   )    ->				Dict:
												_A								= self.__dict__.copy()
												_A								= None
												_A								= self.sp_model.serialized_model_proto()
												return state

							def __setstate__(  self:   Any		,     __A:   List[str]   )    ->				Any:
												_A								= d

												# for backward compatibility
												if not hasattr(self		,     '''sp_model_kwargs'''   ):
																	_A								= {}

												_A								= spm.SentencePieceProcessor(**self.sp_model_kwargs   )
												self.sp_model.LoadFromSerializedProto(self.sp_model_proto   )

							@property
							def       __A (  self:   Tuple   )    ->				Union[str, Any]:
												return len(self.sp_model   ) + len(self.lang_code_to_id   ) + self.fairseq_offset + 1  # Plus 1 for the mask token

							@property
							def       __A (  self:   Tuple   )    ->				str:
												return self._src_lang

							@src_lang.setter
							def       __A (  self:   Any		,     __A:   str   )    ->				None:
												_A								= new_src_lang
												self.set_src_lang_special_tokens(self._src_lang   )

							def       __A (  self:   List[str]		,     __A:   List[int]		,     __A:   Optional[List[int]] = None		,     __A:   bool = False   )    ->				List[int]:

												if already_has_special_tokens:
																	return super().get_special_tokens_mask(
																	    token_ids_a=__A		,     token_ids_a=__A		,     already_has_special_tokens=__A   )

												_A								= [1] * len(self.prefix_tokens   )
												_A								= [1] * len(self.suffix_tokens   )
												if token_ids_a is None:
																	return prefix_ones + ([0] * len(__A   )) + suffix_ones
												return prefix_ones + ([0] * len(__A   )) + ([0] * len(__A   )) + suffix_ones

							def       __A (  self:   int		,     __A:   List[int]		,     __A:   Optional[List[int]] = None   )    ->				List[int]:
												if token_ids_a is None:
																	return self.prefix_tokens + token_ids_a + self.suffix_tokens
												# We don't expect to process pairs, but leave the pair logic for API consistency
												return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens

							def       __A (  self:   Optional[int]		,     __A:   List[int]		,     __A:   Optional[List[int]] = None   )    ->				List[int]:
												_A								= [self.sep_token_id]
												_A								= [self.cls_token_id]

												if token_ids_a is None:
																	return len(cls + token_ids_a + sep   ) * [0]
												return len(cls + token_ids_a + sep + sep + token_ids_a + sep   ) * [0]

							def       __A (  self:   List[str]		,     __A:   Any		,     __A:   str		,     __A:   Optional[str]		,     __A:   Optional[str]		,     **__A:   Dict   )    ->				int:
												if src_lang is None or tgt_lang is None:
																	raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model'''   )
												_A								= src_lang
												_A								= self(__A		,     add_special_tokens=__A		,     return_tensors=__A		,     **__A   )
												_A								= self.convert_tokens_to_ids(__A   )
												_A								= tgt_lang_id
												return inputs

							def       __A (  self:   str   )    ->				str:
												_A								= {self.convert_ids_to_tokens(__A   ): i for i in range(self.vocab_size   )}
												vocab.update(self.added_tokens_encoder   )
												return vocab

							def       __A (  self:   Optional[Any]		,     __A:   str   )    ->				List[str]:
												return self.sp_model.encode(__A		,     out_type=__A   )

							def       __A (  self:   Any		,     __A:   Optional[Any]   )    ->				str:
												if token in self.fairseq_tokens_to_ids:
																	return self.fairseq_tokens_to_ids[token]
												_A								= self.sp_model.PieceToId(__A   )

												# Need to return unknown token if the SP model returned 0
												return spm_id + self.fairseq_offset if spm_id else self.unk_token_id

							def       __A (  self:   List[str]		,     __A:   int   )    ->				Any:
												if index in self.fairseq_ids_to_tokens:
																	return self.fairseq_ids_to_tokens[index]
												return self.sp_model.IdToPiece(index - self.fairseq_offset   )

							def       __A (  self:   int		,     __A:   Tuple   )    ->				str:
												_A								= ''''''.join(__A   ).replace(__A		,     ''' '''   ).strip()
												return out_string

							def       __A (  self:   Any		,     __A:   str		,     __A:   Optional[str] = None   )    ->				Tuple[str]:
												if not os.path.isdir(__A   ):
																	logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""   )
																	return
												_A								= os.path.join(
												    __A		,     (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']   )

												if os.path.abspath(self.vocab_file   ) != os.path.abspath(__A   ) and os.path.isfile(self.vocab_file   ):
																	copyfile(self.vocab_file		,     __A   )
												elif not os.path.isfile(self.vocab_file   ):
																	with open(__A		,     '''wb'''   ) as fi:
																						_A								= self.sp_model.serialized_model_proto()
																						fi.write(__A   )

												return (out_vocab_file,)

							def       __A (  self:   List[Any]		,     __A:   List[str]		,     __A:   str = "eng_Latn"		,     __A:   Optional[List[str]] = None		,     __A:   str = "fra_Latn"		,     **__A:   str		,     )    ->				BatchEncoding:
												_A								= src_lang
												_A								= tgt_lang
												return super().prepare_seqaseq_batch(__A		,     __A		,     **__A   )

							def       __A (  self:   Optional[int]   )    ->				Union[str, Any]:
												return self.set_src_lang_special_tokens(self.src_lang   )

							def       __A (  self:   str   )    ->				Optional[Any]:
												return self.set_tgt_lang_special_tokens(self.tgt_lang   )

							def       __A (  self:   Any		,     __A:   Any   )    ->				None:
												_A								= self.lang_code_to_id[src_lang]
												if self.legacy_behaviour:
																	_A								= []
																	_A								= [self.eos_token_id, self.cur_lang_code]
												else:
																	_A								= [self.cur_lang_code]
																	_A								= [self.eos_token_id]



							def       __A (  self:   Union[str, Any]		,     __A:   str   )    ->				None:
												_A								= self.lang_code_to_id[lang]
												if self.legacy_behaviour:
																	_A								= []
																	_A								= [self.eos_token_id, self.cur_lang_code]
												else:
																	_A								= [self.cur_lang_code]
																	_A								= [self.eos_token_id]











import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, 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 MaskFormerForInstanceSegmentation, MaskFormerModel

				if is_vision_available():
								from transformers import MaskFormerImageProcessor

if is_vision_available():
				from PIL import Image





class 						SCREAMING_SNAKE_CASE				:





							"""simple docstring"""

							def __init__(  self:   Optional[int]		,     __A:   Union[str, Any]		,     __A:   int=2		,     __A:   List[str]=True		,     __A:   List[Any]=False		,     __A:   Union[str, Any]=10		,     __A:   Optional[int]=3		,     __A:   List[Any]=32 * 4		,     __A:   Dict=32 * 6		,     __A:   Optional[Any]=4		,     __A:   Any=32		,     )    ->				str:
												_A								= parent
												_A								= batch_size
												_A								= is_training
												_A								= use_auxiliary_loss
												_A								= num_queries
												_A								= num_channels
												_A								= min_size
												_A								= max_size
												_A								= num_labels
												_A								= mask_feature_size

							def       __A (  self:   Dict   )    ->				Optional[int]:
												_A								= floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]   ).to(
												    __A   )

												_A								= torch.ones([self.batch_size, self.min_size, self.max_size]		,     device=__A   )

												_A								= (
												    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]		,     device=__A   ) > 0.5
												).float()
												_A								= (torch.rand((self.batch_size, self.num_labels)		,     device=__A   ) > 0.5).long()

												_A								= self.get_config()
												return config, pixel_values, pixel_mask, mask_labels, class_labels

							def       __A (  self:   Optional[Any]   )    ->				Tuple:
												return MaskFormerConfig.from_backbone_and_decoder_configs(
												    backbone_config=SwinConfig(
												        depths=[1, 1, 1, 1]		,     )		,     decoder_config=DetrConfig(
												        decoder_ffn_dim=1_28		,     num_queries=self.num_queries		,     decoder_attention_heads=2		,     d_model=self.mask_feature_size		,     )		,     mask_feature_size=self.mask_feature_size		,     fpn_feature_size=self.mask_feature_size		,     num_channels=self.num_channels		,     num_labels=self.num_labels		,     )

							def       __A (  self:   Dict   )    ->				Tuple:
												_A							,_A							,_A							,_A							,_A								= self.prepare_config_and_inputs()
												_A								= {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
												return config, inputs_dict

							def       __A (  self:   Optional[int]		,     __A:   Union[str, Any]		,     __A:   Dict   )    ->				int:
												_A								= output.encoder_hidden_states
												_A								= output.pixel_decoder_hidden_states
												_A								= 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_config.decoder_layers   )

							def       __A (  self:   Optional[Any]		,     __A:   Union[str, Any]		,     __A:   Optional[Any]		,     __A:   Any		,     __A:   Dict=False   )    ->				Any:
												with torch.no_grad():
																	_A								= MaskFormerModel(config=__A   )
																	model.to(__A   )
																	model.eval()

																	_A								= model(pixel_values=__A		,     pixel_mask=__A   )
																	_A								= model(__A		,     output_hidden_states=__A   )
												# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
												# encoder and pixel decoder
												self.parent.assertEqual(
												    output.transformer_decoder_last_hidden_state.shape		,     (self.batch_size, self.num_queries, self.mask_feature_size)		,     )
												# 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       __A (  self:   Optional[Any]		,     __A:   Union[str, Any]		,     __A:   Optional[Any]		,     __A:   Union[str, Any]		,     __A:   Union[str, Any]		,     __A:   List[Any]   )    ->				int:
												_A								= MaskFormerForInstanceSegmentation(config=__A   )
												model.to(__A   )
												model.eval()

												def comm_check_on_output(__A:   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():
																	_A								= model(pixel_values=__A		,     pixel_mask=__A   )
																	_A								= model(__A   )

																	comm_check_on_output(__A   )

																	_A								= 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 						SCREAMING_SNAKE_CASE				( snake_case  ,	snake_case  ,	unittest.TestCase					):





							"""simple docstring"""

							A_						  =					(MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
							A_						  =					(
							    {"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
							    if is_torch_available()
							    else {}
							)

							A_						  =					False
							A_						  =					False
							A_						  =					False
							A_						  =					False

							def       __A (  self:   int   )    ->				Tuple:
												_A								= MaskFormerModelTester(self   )
												_A								= ConfigTester(self		,     config_class=__A		,     has_text_modality=__A   )

							def       __A (  self:   List[Any]   )    ->				Dict:
												self.config_tester.run_common_tests()

							def       __A (  self:   Optional[Any]   )    ->				int:
												_A							,_A								= self.model_tester.prepare_config_and_inputs_for_common()
												self.model_tester.create_and_check_maskformer_model(__A		,     **__A		,     output_hidden_states=__A   )

							def       __A (  self:   Dict   )    ->				Optional[Any]:
												_A								= self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__A   )

							@unittest.skip(reason='''MaskFormer does not use inputs_embeds'''   )
							def       __A (  self:   int   )    ->				Tuple:
												pass

							@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method'''   )
							def       __A (  self:   List[Any]   )    ->				Any:
												pass

							@unittest.skip(reason='''MaskFormer is not a generative model'''   )
							def       __A (  self:   Union[str, Any]   )    ->				Optional[int]:
												pass

							@unittest.skip(reason='''MaskFormer does not use token embeddings'''   )
							def       __A (  self:   int   )    ->				List[str]:
												pass

							@require_torch_multi_gpu
							@unittest.skip(
							    reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''   )
							def       __A (  self:   Union[str, Any]   )    ->				List[Any]:
												pass

							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
							def       __A (  self:   List[Any]   )    ->				Any:
												pass

							def       __A (  self:   Dict   )    ->				Optional[Any]:
												_A							,_A								= self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_A								= model_class(__A   )
																	_A								= inspect.signature(model.forward   )
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	_A								= [*signature.parameters.keys()]

																	_A								= ['''pixel_values''']
																	self.assertListEqual(arg_names[:1]		,     __A   )

							@slow
							def       __A (  self:   int   )    ->				Optional[Any]:
												for model_name in ["facebook/maskformer-swin-small-coco"]:
																	_A								= MaskFormerModel.from_pretrained(__A   )
																	self.assertIsNotNone(__A   )

							def       __A (  self:   Optional[Any]   )    ->				Optional[int]:
												_A								= (self.model_tester.min_size,) * 2
												_A								= {
												    '''pixel_values''': torch.randn((2, 3, *size)		,     device=__A   ),
												    '''mask_labels''': torch.randn((2, 10, *size)		,     device=__A   ),
												    '''class_labels''': torch.zeros(2		,     10		,     device=__A   ).long(),
												}

												_A								= MaskFormerForInstanceSegmentation(MaskFormerConfig()   ).to(__A   )
												_A								= model(**__A   )
												self.assertTrue(outputs.loss is not None   )

							def       __A (  self:   Optional[Any]   )    ->				List[Any]:
												_A							,_A								= self.model_tester.prepare_config_and_inputs_for_common()
												self.model_tester.create_and_check_maskformer_model(__A		,     **__A		,     output_hidden_states=__A   )

							def       __A (  self:   Any   )    ->				Tuple:
												_A							,_A								= self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_A								= model_class(__A   ).to(__A   )
																	_A								= model(**__A		,     output_attentions=__A   )
																	self.assertTrue(outputs.attentions is not None   )

							def       __A (  self:   Dict   )    ->				Union[str, Any]:
												if not self.model_tester.is_training:
																	return
												# only MaskFormerForInstanceSegmentation has the loss
												_A								= self.all_model_classes[1]
												_A							,_A							,_A							,_A							,_A								= self.model_tester.prepare_config_and_inputs()

												_A								= model_class(__A   )
												model.to(__A   )
												model.train()

												_A								= model(__A		,     mask_labels=__A		,     class_labels=__A   ).loss
												loss.backward()



							def       __A (  self:   Tuple   )    ->				Optional[Any]:
												# only MaskFormerForInstanceSegmentation has the loss
												_A								= self.all_model_classes[1]
												_A							,_A							,_A							,_A							,_A								= self.model_tester.prepare_config_and_inputs()
												_A								= True
												_A								= True

												_A								= model_class(__A   )
												model.to(__A   )
												model.train()

												_A								= model(__A		,     mask_labels=__A		,     class_labels=__A   )

												_A								= outputs.encoder_hidden_states[0]
												encoder_hidden_states.retain_grad()

												_A								= outputs.pixel_decoder_hidden_states[0]
												pixel_decoder_hidden_states.retain_grad()
												# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
												_A								= outputs.transformer_decoder_hidden_states[0]
												transformer_decoder_hidden_states.retain_grad()

												_A								= 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      =				1e-4




def      __A					(     ):

					'''simple docstring'''







					_A								= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
					return image





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





							"""simple docstring"""

							@cached_property
							def       __A (  self:   Union[str, Any]   )    ->				Optional[int]:
												return (
												    MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco'''   )
												    if is_vision_available()
												    else None
												)

							def       __A (  self:   List[Any]   )    ->				Any:
												_A								= MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco'''   ).to(__A   )
												_A								= self.default_image_processor
												_A								= prepare_img()
												_A								= image_processor(__A		,     return_tensors='''pt'''   ).to(__A   )
												_A								= inputs['''pixel_values'''].shape
												# check size is divisible by 32
												self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
												# check size
												self.assertEqual(__A		,     (1, 3, 8_00, 10_88)   )

												with torch.no_grad():
																	_A								= model(**__A   )

												_A								= torch.tensor(
												    [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]]   ).to(__A   )
												self.assertTrue(
												    torch.allclose(
												        outputs.encoder_last_hidden_state[0, 0, :3, :3]		,     __A		,     atol=__A   )   )

												_A								= torch.tensor(
												    [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]]   ).to(__A   )
												self.assertTrue(
												    torch.allclose(
												        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]		,     __A		,     atol=__A   )   )

												_A								= torch.tensor(
												    [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]]   ).to(__A   )
												self.assertTrue(
												    torch.allclose(
												        outputs.transformer_decoder_last_hidden_state[0, :3, :3]		,     __A		,     atol=__A   )   )

							def       __A (  self:   Dict   )    ->				Dict:
												_A								= (
												    MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''   )
												    .to(__A   )
												    .eval()
												)
												_A								= self.default_image_processor
												_A								= prepare_img()
												_A								= image_processor(__A		,     return_tensors='''pt'''   ).to(__A   )
												_A								= inputs['''pixel_values'''].shape
												# check size is divisible by 32
												self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
												# check size
												self.assertEqual(__A		,     (1, 3, 8_00, 10_88)   )

												with torch.no_grad():
																	_A								= model(**__A   )
												# masks_queries_logits
												_A								= outputs.masks_queries_logits
												self.assertEqual(
												    masks_queries_logits.shape		,     (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)		,     )
												_A								= [
												    [-1.3_737_124, -1.7_724_937, -1.9_364_233],
												    [-1.5_977_281, -1.9_867_939, -2.1_523_695],
												    [-1.5_795_398, -1.9_269_832, -2.093_942],
												]
												_A								= torch.tensor(__A   ).to(__A   )
												self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]		,     __A		,     atol=__A   )   )
												# class_queries_logits
												_A								= outputs.class_queries_logits
												self.assertEqual(
												    class_queries_logits.shape		,     (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)   )
												_A								= torch.tensor(
												    [
												        [1.65_12e00, -5.25_72e00, -3.35_19e00],
												        [3.61_69e-02, -5.90_25e00, -2.93_13e00],
												        [1.07_66e-04, -7.76_30e00, -5.12_63e00],
												    ]   ).to(__A   )
												self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]		,     __A		,     atol=__A   )   )

							def       __A (  self:   List[Any]   )    ->				Dict:
												_A								= (
												    MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff'''   )
												    .to(__A   )
												    .eval()
												)
												_A								= self.default_image_processor
												_A								= prepare_img()
												_A								= image_processor(__A		,     return_tensors='''pt'''   ).to(__A   )
												_A								= inputs['''pixel_values'''].shape
												# check size is divisible by 32
												self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0   )
												# check size
												self.assertEqual(__A		,     (1, 3, 8_00, 10_88)   )

												with torch.no_grad():
																	_A								= model(**__A   )
												# masks_queries_logits
												_A								= outputs.masks_queries_logits
												self.assertEqual(
												    masks_queries_logits.shape		,     (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)		,     )
												_A								= [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
												_A								= torch.tensor(__A   ).to(__A   )
												self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]		,     __A		,     atol=__A   )   )
												# class_queries_logits
												_A								= outputs.class_queries_logits
												self.assertEqual(
												    class_queries_logits.shape		,     (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)   )
												_A								= torch.tensor(
												    [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]]   ).to(__A   )
												self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]		,     __A		,     atol=__A   )   )



							def       __A (  self:   Optional[Any]   )    ->				str:
												_A								= (
												    MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco'''   )
												    .to(__A   )
												    .eval()
												)
												_A								= self.default_image_processor

												_A								= image_processor(
												    [np.zeros((3, 8_00, 13_33)   ), np.zeros((3, 8_00, 13_33)   )]		,     segmentation_maps=[np.zeros((3_84, 3_84)   ).astype(np.floataa   ), np.zeros((3_84, 3_84)   ).astype(np.floataa   )]		,     return_tensors='''pt'''		,     )

												_A								= inputs['''pixel_values'''].to(__A   )
												_A								= [el.to(__A   ) for el in inputs['''mask_labels''']]
												_A								= [el.to(__A   ) for el in inputs['''class_labels''']]

												with torch.no_grad():
																	_A								= model(**__A   )

												self.assertTrue(outputs.loss is not None   )



