



'''simple docstring'''





import argparse
import os

from . import (
    ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    AlbertConfig,
    BartConfig,
    BertConfig,
    CamembertConfig,
    CTRLConfig,
    DistilBertConfig,
    DPRConfig,
    ElectraConfig,
    FlaubertConfig,
    GPTaConfig,
    LayoutLMConfig,
    LxmertConfig,
    OpenAIGPTConfig,
    RobertaConfig,
    TaConfig,
    TFAlbertForPreTraining,
    TFBartForConditionalGeneration,
    TFBartForSequenceClassification,
    TFBertForPreTraining,
    TFBertForQuestionAnswering,
    TFBertForSequenceClassification,
    TFCamembertForMaskedLM,
    TFCTRLLMHeadModel,
    TFDistilBertForMaskedLM,
    TFDistilBertForQuestionAnswering,
    TFDPRContextEncoder,
    TFDPRQuestionEncoder,
    TFDPRReader,
    TFElectraForPreTraining,
    TFFlaubertWithLMHeadModel,
    TFGPTaLMHeadModel,
    TFLayoutLMForMaskedLM,
    TFLxmertForPreTraining,
    TFLxmertVisualFeatureEncoder,
    TFOpenAIGPTLMHeadModel,
    TFRobertaForCausalLM,
    TFRobertaForMaskedLM,
    TFRobertaForSequenceClassification,
    TFTaForConditionalGeneration,
    TFTransfoXLLMHeadModel,
    TFWavaVecaModel,
    TFXLMRobertaForMaskedLM,
    TFXLMWithLMHeadModel,
    TFXLNetLMHeadModel,
    TransfoXLConfig,
    WavaVecaConfig,
    WavaVecaModel,
    XLMConfig,
    XLMRobertaConfig,
    XLNetConfig,
    is_torch_available,
    load_pytorch_checkpoint_in_tfa_model,
)
from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging


if is_torch_available():
 import numpy as np
 import torch

 from . import (
     AlbertForPreTraining,
     BartForConditionalGeneration,
     BertForPreTraining,
     BertForQuestionAnswering,
     BertForSequenceClassification,
     CamembertForMaskedLM,
     CTRLLMHeadModel,
     DistilBertForMaskedLM,
     DistilBertForQuestionAnswering,
     DPRContextEncoder,
     DPRQuestionEncoder,
     DPRReader,
     ElectraForPreTraining,
     FlaubertWithLMHeadModel,
     GPTaLMHeadModel,
     LayoutLMForMaskedLM,
     LxmertForPreTraining,
     LxmertVisualFeatureEncoder,
     OpenAIGPTLMHeadModel,
     RobertaForMaskedLM,
     RobertaForSequenceClassification,
     TaForConditionalGeneration,
     TransfoXLLMHeadModel,
     XLMRobertaForMaskedLM,
     XLMWithLMHeadModel,
     XLNetLMHeadModel,
 )


logging.set_verbosity_info()

_lowerCAmelCase      						=	{
    '''bart''': (
        BartConfig,
        TFBartForConditionalGeneration,
        TFBartForSequenceClassification,
        BartForConditionalGeneration,
        BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    '''bert''': (
        BertConfig,
        TFBertForPreTraining,
        BertForPreTraining,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''bert-large-uncased-whole-word-masking-finetuned-squad''': (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''bert-large-cased-whole-word-masking-finetuned-squad''': (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''bert-base-cased-finetuned-mrpc''': (
        BertConfig,
        TFBertForSequenceClassification,
        BertForSequenceClassification,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''dpr''': (
        DPRConfig,
        TFDPRQuestionEncoder,
        TFDPRContextEncoder,
        TFDPRReader,
        DPRQuestionEncoder,
        DPRContextEncoder,
        DPRReader,
        DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    '''gpt2''': (
        GPTaConfig,
        TFGPTaLMHeadModel,
        GPTaLMHeadModel,
        GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''xlnet''': (
        XLNetConfig,
        TFXLNetLMHeadModel,
        XLNetLMHeadModel,
        XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''xlm''': (
        XLMConfig,
        TFXLMWithLMHeadModel,
        XLMWithLMHeadModel,
        XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''xlm-roberta''': (
        XLMRobertaConfig,
        TFXLMRobertaForMaskedLM,
        XLMRobertaForMaskedLM,
        XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''transfo-xl''': (
        TransfoXLConfig,
        TFTransfoXLLMHeadModel,
        TransfoXLLMHeadModel,
        TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''openai-gpt''': (
        OpenAIGPTConfig,
        TFOpenAIGPTLMHeadModel,
        OpenAIGPTLMHeadModel,
        OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''roberta''': (
        RobertaConfig,
        TFRobertaForCausalLM,
        TFRobertaForMaskedLM,
        RobertaForMaskedLM,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''layoutlm''': (
        LayoutLMConfig,
        TFLayoutLMForMaskedLM,
        LayoutLMForMaskedLM,
        LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    '''roberta-large-mnli''': (
        RobertaConfig,
        TFRobertaForSequenceClassification,
        RobertaForSequenceClassification,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''camembert''': (
        CamembertConfig,
        TFCamembertForMaskedLM,
        CamembertForMaskedLM,
        CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''flaubert''': (
        FlaubertConfig,
        TFFlaubertWithLMHeadModel,
        FlaubertWithLMHeadModel,
        FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''distilbert''': (
        DistilBertConfig,
        TFDistilBertForMaskedLM,
        DistilBertForMaskedLM,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''distilbert-base-distilled-squad''': (
        DistilBertConfig,
        TFDistilBertForQuestionAnswering,
        DistilBertForQuestionAnswering,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''lxmert''': (
        LxmertConfig,
        TFLxmertForPreTraining,
        LxmertForPreTraining,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''lxmert-visual-feature-encoder''': (
        LxmertConfig,
        TFLxmertVisualFeatureEncoder,
        LxmertVisualFeatureEncoder,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''ctrl''': (
        CTRLConfig,
        TFCTRLLMHeadModel,
        CTRLLMHeadModel,
        CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''albert''': (
        AlbertConfig,
        TFAlbertForPreTraining,
        AlbertForPreTraining,
        ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''t5''': (
        TaConfig,
        TFTaForConditionalGeneration,
        TaForConditionalGeneration,
        T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''electra''': (
        ElectraConfig,
        TFElectraForPreTraining,
        ElectraForPreTraining,
        ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''wav2vec2''': (
        WavaVecaConfig,
        TFWavaVecaModel,
        WavaVecaModel,
        WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
}
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase							,    UpperCamelCase							,    UpperCamelCase							,    UpperCamelCase							,    UpperCamelCase=False							,    UpperCamelCase=True			):



    """simple docstring"""





    if model_type not in MODEL_CLASSES:
        raise ValueError(f"""Unrecognized model type, should be one of {list(MODEL_CLASSES.keys()			)}."""			)

    lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__ :  Union[str, Any]							      =					MODEL_CLASSES[model_type]

    # Initialise TF model
    if config_file in aws_config_map:
        lowerCAmelCase__ :  Tuple							      =					cached_file(UpperCamelCase							,    UpperCamelCase							,    force_download=not use_cached_models			)
    lowerCAmelCase__ :  List[Any]							      =					config_class.from_json_file(UpperCamelCase			)
    lowerCAmelCase__ :  str							      =					True
    lowerCAmelCase__ :  int							      =					True
    print(f"""Building TensorFlow model from configuration: {config}"""			)
    lowerCAmelCase__ :  Optional[int]							      =					model_class(UpperCamelCase			)

    # Load weights from tf checkpoint
    if pytorch_checkpoint_path in aws_config_map.keys():
        lowerCAmelCase__ :  int							      =					cached_file(
            UpperCamelCase							,    UpperCamelCase							,    force_download=not use_cached_models			)
    # Load PyTorch checkpoint in tf2 model:
    lowerCAmelCase__ :  Any							      =					load_pytorch_checkpoint_in_tfa_model(UpperCamelCase							,    UpperCamelCase			)

    if compare_with_pt_model:
        lowerCAmelCase__ :  Optional[Any]							      =					tf_model(tf_model.dummy_inputs							,    training=UpperCamelCase			)  # build the network

        lowerCAmelCase__ :  List[Any]							      =					torch.load(UpperCamelCase							,    map_location="""cpu"""			)
        lowerCAmelCase__ :  Optional[Any]							      =					pt_model_class.from_pretrained(
            pretrained_model_name_or_path=UpperCamelCase							,    config=UpperCamelCase							,    state_dict=UpperCamelCase			)

        with torch.no_grad():
            lowerCAmelCase__ :  int							      =					pt_model(**pt_model.dummy_inputs			)

        lowerCAmelCase__ :  Dict							      =					pto[0].numpy()
        lowerCAmelCase__ :  Union[str, Any]							      =					tfo[0].numpy()
        lowerCAmelCase__ :  Any							      =					np.amax(np.abs(np_pt - np_tf			)			)
        print(f"""Max absolute difference between models outputs {diff}"""			)
        assert diff <= 2e-2, f"""Error, model absolute difference is >2e-2: {diff}"""

    # Save pytorch-model
    print(f"""Save TensorFlow model to {tf_dump_path}"""			)
    tf_model.save_weights(UpperCamelCase							,    save_format="""h5"""			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase							,    UpperCamelCase							,    UpperCamelCase=None							,    UpperCamelCase=None							,    UpperCamelCase=False							,    UpperCamelCase=False							,    UpperCamelCase=False							,    UpperCamelCase=False							,    ):



    """simple docstring"""





    if args_model_type is None:
        lowerCAmelCase__ :  int							      =					list(MODEL_CLASSES.keys()			)
    else:
        lowerCAmelCase__ :  List[str]							      =					[args_model_type]

    for j, model_type in enumerate(UpperCamelCase							,    start=1			):
        print("""=""" * 100			)
        print(f""" Converting model type {j}/{len(UpperCamelCase			)}: {model_type}"""			)
        print("""=""" * 100			)
        if model_type not in MODEL_CLASSES:
            raise ValueError(f"""Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys()			)}."""			)

        lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__ :  Union[str, Any]							      =					MODEL_CLASSES[model_type]

        if model_shortcut_names_or_path is None:
            lowerCAmelCase__ :  List[str]							      =					list(aws_model_maps.keys()			)
        if config_shortcut_names_or_path is None:
            lowerCAmelCase__ :  int							      =					model_shortcut_names_or_path

        for i, (model_shortcut_name, config_shortcut_name) in enumerate(
            zip(UpperCamelCase							,    UpperCamelCase			)							,    start=1			):
            print("""-""" * 100			)
            if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name:
                if not only_convert_finetuned_models:
                    print(f"""    Skipping finetuned checkpoint {model_shortcut_name}"""			)
                    continue
                lowerCAmelCase__ :  str							      =					model_shortcut_name
            elif only_convert_finetuned_models:
                print(f"""    Skipping not finetuned checkpoint {model_shortcut_name}"""			)
                continue
            print(
                f"""    Converting checkpoint {i}/{len(UpperCamelCase			)}: {model_shortcut_name} - model_type {model_type}"""			)
            print("""-""" * 100			)

            if config_shortcut_name in aws_config_map:
                lowerCAmelCase__ :  List[Any]							      =					cached_file(UpperCamelCase							,    UpperCamelCase							,    force_download=not use_cached_models			)
            else:
                lowerCAmelCase__ :  Tuple							      =					config_shortcut_name

            if model_shortcut_name in aws_model_maps:
                lowerCAmelCase__ :  List[Any]							      =					cached_file(UpperCamelCase							,    UpperCamelCase							,    force_download=not use_cached_models			)
            else:
                lowerCAmelCase__ :  Optional[int]							      =					model_shortcut_name

            if os.path.isfile(UpperCamelCase			):
                lowerCAmelCase__ :  int							      =					"""converted_model"""

            convert_pt_checkpoint_to_tf(
                model_type=UpperCamelCase							,    pytorch_checkpoint_path=UpperCamelCase							,    config_file=UpperCamelCase							,    tf_dump_path=os.path.join(UpperCamelCase							,    model_shortcut_name + """-tf_model.h5"""			)							,    compare_with_pt_model=UpperCamelCase							,    )
            if remove_cached_files:
                os.remove(UpperCamelCase			)
                os.remove(UpperCamelCase			)


if __name__ == "__main__":
 _lowerCAmelCase      						=	argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     '''--tf_dump_path''', default=None, type=str, required=True, help='''Path to the output Tensorflow dump file.'''
 )
 parser.add_argument(
     '''--model_type''',
     default=None,
     type=str,
     help=(
         F"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """
         '''convert all the models from AWS.'''
     ),
 )
 parser.add_argument(
     '''--pytorch_checkpoint_path''',
     default=None,
     type=str,
     help=(
         '''Path to the PyTorch checkpoint path or shortcut name to download from AWS. '''
         '''If not given, will download and convert all the checkpoints from AWS.'''
     ),
 )
 parser.add_argument(
     '''--config_file''',
     default=None,
     type=str,
     help=(
         '''The config json file corresponding to the pre-trained model. \n'''
         '''This specifies the model architecture. If not given and '''
         '''--pytorch_checkpoint_path is not given or is a shortcut name '''
         '''use the configuration associated to the shortcut name on the AWS'''
     ),
 )
 parser.add_argument(
     '''--compare_with_pt_model''', action='''store_true''', help='''Compare Tensorflow and PyTorch model predictions.'''
 )
 parser.add_argument(
     '''--use_cached_models''',
     action='''store_true''',
     help='''Use cached models if possible instead of updating to latest checkpoint versions.''',
 )
 parser.add_argument(
     '''--remove_cached_files''',
     action='''store_true''',
     help='''Remove pytorch models after conversion (save memory when converting in batches).''',
 )
 parser.add_argument('''--only_convert_finetuned_models''', action='''store_true''', help='''Only convert finetuned models.''')
 _lowerCAmelCase      						=	parser.parse_args()

 # if args.pytorch_checkpoint_path is not None:
 #     convert_pt_checkpoint_to_tf(args.model_type.lower(),
 #                                 args.pytorch_checkpoint_path,
 #                                 args.config_file if args.config_file is not None else args.pytorch_checkpoint_path,
 #                                 args.tf_dump_path,
 #                                 compare_with_pt_model=args.compare_with_pt_model,
 #                                 use_cached_models=args.use_cached_models)
 # else:
 convert_all_pt_checkpoints_to_tf(
     args.model_type.lower() if args.model_type is not None else None,
     args.tf_dump_path,
     model_shortcut_names_or_path=[args.pytorch_checkpoint_path]
     if args.pytorch_checkpoint_path is not None
     else None,
     config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None,
     compare_with_pt_model=args.compare_with_pt_model,
     use_cached_models=args.use_cached_models,
     remove_cached_files=args.remove_cached_files,
     only_convert_finetuned_models=args.only_convert_finetuned_models,
 )







'''simple docstring'''





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        lowerCAmelCase_:
  '''simple docstring'''




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




  def 							UpperCAmelCase_	(    self      )    ->		Tuple:
      lowerCAmelCase__ :  str							      =					floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]      ).to(
          __UpperCAmelCase      )

      lowerCAmelCase__ :  str							      =					torch.ones([self.batch_size, self.min_size, self.max_size]  ,device=__UpperCAmelCase      )

      lowerCAmelCase__ :  Any							      =					(
          torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]  ,device=__UpperCAmelCase      ) > 0.5
      ).float()
      lowerCAmelCase__ :  Optional[int]							      =					(torch.rand((self.batch_size, self.num_labels)  ,device=__UpperCAmelCase      ) > 0.5).long()

      lowerCAmelCase__ :  Any							      =					self.get_config()
      return config, pixel_values, pixel_mask, mask_labels, class_labels




  def 							UpperCAmelCase_	(    self      )    ->		Dict:
      return MaskFormerConfig.from_backbone_and_decoder_configs(
          backbone_config=SwinConfig(
              depths=[1, 1, 1, 1]  ,)  ,decoder_config=DetrConfig(
              decoder_ffn_dim=128  ,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 							UpperCAmelCase_	(    self      )    ->		Optional[int]:
      lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__ :  List[str]							      =					self.prepare_config_and_inputs()
      lowerCAmelCase__ :  List[str]							      =					{"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
      return config, inputs_dict




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase      )    ->		Any:
      lowerCAmelCase__ :  Optional[int]							      =					output.encoder_hidden_states
      lowerCAmelCase__ :  Optional[int]							      =					output.pixel_decoder_hidden_states
      lowerCAmelCase__ :  Dict							      =					output.transformer_decoder_hidden_states

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




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase=False      )    ->		Optional[Any]:
      with torch.no_grad():
          lowerCAmelCase__ :  int							      =					MaskFormerModel(config=__UpperCAmelCase      )
          model.to(__UpperCAmelCase      )
          model.eval()

          lowerCAmelCase__ :  str							      =					model(pixel_values=__UpperCAmelCase  ,pixel_mask=__UpperCAmelCase      )
          lowerCAmelCase__ :  int							      =					model(__UpperCAmelCase  ,output_hidden_states=__UpperCAmelCase      )
      # 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(__UpperCAmelCase  ,__UpperCAmelCase      )






  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase      )    ->		Optional[int]:
      lowerCAmelCase__ :  Dict							      =					MaskFormerForInstanceSegmentation(config=__UpperCAmelCase      )
      model.to(__UpperCAmelCase      )
      model.eval()

      def comm_check_on_output(__UpperCAmelCase      ):
          # 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=__UpperCAmelCase  ,pixel_mask=__UpperCAmelCase      )
          lowerCAmelCase__ :  Dict							      =					model(__UpperCAmelCase      )

          comm_check_on_output(__UpperCAmelCase      )

          lowerCAmelCase__ :  Optional[int]							      =					model(
              pixel_values=__UpperCAmelCase  ,pixel_mask=__UpperCAmelCase  ,mask_labels=__UpperCAmelCase  ,class_labels=__UpperCAmelCase      )

      comm_check_on_output(__UpperCAmelCase      )

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







@require_torch
class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_						, unittest.TestCase     ):
  '''simple docstring'''




  __lowercase							:      Optional[Any]				=      (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
  __lowercase							:      int				=      (
      {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
      if is_torch_available()
      else {}
  )

  __lowercase							:      Union[str, Any]				=      False
  __lowercase							:      Dict				=      False
  __lowercase							:      Tuple				=      False
  __lowercase							:      List[Any]				=      False




  def 							UpperCAmelCase_	(    self      )    ->		Optional[int]:
      lowerCAmelCase__ :  str							      =					MaskFormerModelTester(self      )
      lowerCAmelCase__ :  List[Any]							      =					ConfigTester(self  ,config_class=__UpperCAmelCase  ,has_text_modality=__UpperCAmelCase      )




  def 							UpperCAmelCase_	(    self      )    ->		List[str]:
      self.config_tester.run_common_tests()




  def 							UpperCAmelCase_	(    self      )    ->		Union[str, Any]:
      lowerCAmelCase__      ,   lowerCAmelCase__ :  str							      =					self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.create_and_check_maskformer_model(__UpperCAmelCase  ,**__UpperCAmelCase  ,output_hidden_states=__UpperCAmelCase      )




  def 							UpperCAmelCase_	(    self      )    ->		Optional[int]:
      lowerCAmelCase__ :  List[str]							      =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__UpperCAmelCase      )




  @unittest.skip(reason="""MaskFormer does not use inputs_embeds"""      )
  def 							UpperCAmelCase_	(    self      )    ->		List[Any]:
      pass




  @unittest.skip(reason="""MaskFormer does not have a get_input_embeddings method"""      )
  def 							UpperCAmelCase_	(    self      )    ->		str:
      pass




  @unittest.skip(reason="""MaskFormer is not a generative model"""      )
  def 							UpperCAmelCase_	(    self      )    ->		Any:
      pass




  @unittest.skip(reason="""MaskFormer does not use token embeddings"""      )
  def 							UpperCAmelCase_	(    self      )    ->		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 							UpperCAmelCase_	(    self      )    ->		Union[str, Any]:
      pass




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




  def 							UpperCAmelCase_	(    self      )    ->		Tuple:
      lowerCAmelCase__      ,   lowerCAmelCase__ :  Union[str, Any]							      =					self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase__ :  Tuple							      =					["""pixel_values"""]
          self.assertListEqual(arg_names[:1]  ,__UpperCAmelCase      )




  @slow
  def 							UpperCAmelCase_	(    self      )    ->		Union[str, Any]:
      for model_name in ["facebook/maskformer-swin-small-coco"]:
          lowerCAmelCase__ :  List[str]							      =					MaskFormerModel.from_pretrained(__UpperCAmelCase      )
          self.assertIsNotNone(__UpperCAmelCase      )




  def 							UpperCAmelCase_	(    self      )    ->		str:
      lowerCAmelCase__ :  List[Any]							      =					(self.model_tester.min_size,) * 2
      lowerCAmelCase__ :  Any							      =					{
          """pixel_values""": torch.randn((2, 3, *size)  ,device=__UpperCAmelCase      ),
          """mask_labels""": torch.randn((2, 10, *size)  ,device=__UpperCAmelCase      ),
          """class_labels""": torch.zeros(2  ,10  ,device=__UpperCAmelCase      ).long(),
      }

      lowerCAmelCase__ :  Tuple							      =					MaskFormerForInstanceSegmentation(MaskFormerConfig()      ).to(__UpperCAmelCase      )
      lowerCAmelCase__ :  Union[str, Any]							      =					model(**__UpperCAmelCase      )
      self.assertTrue(outputs.loss is not None      )




  def 							UpperCAmelCase_	(    self      )    ->		str:
      lowerCAmelCase__      ,   lowerCAmelCase__ :  List[str]							      =					self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.create_and_check_maskformer_model(__UpperCAmelCase  ,**__UpperCAmelCase  ,output_hidden_states=__UpperCAmelCase      )




  def 							UpperCAmelCase_	(    self      )    ->		Tuple:
      lowerCAmelCase__      ,   lowerCAmelCase__ :  Any							      =					self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          lowerCAmelCase__ :  int							      =					model_class(__UpperCAmelCase      ).to(__UpperCAmelCase      )
          lowerCAmelCase__ :  List[Any]							      =					model(**__UpperCAmelCase  ,output_attentions=__UpperCAmelCase      )
          self.assertTrue(outputs.attentions is not None      )




  def 							UpperCAmelCase_	(    self      )    ->		int:
      if not self.model_tester.is_training:
          return
      # only MaskFormerForInstanceSegmentation has the loss
      lowerCAmelCase__ :  Dict							      =					self.all_model_classes[1]
      lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__ :  Optional[int]							      =					self.model_tester.prepare_config_and_inputs()

      lowerCAmelCase__ :  List[Any]							      =					model_class(__UpperCAmelCase      )
      model.to(__UpperCAmelCase      )
      model.train()

      lowerCAmelCase__ :  List[str]							      =					model(__UpperCAmelCase  ,mask_labels=__UpperCAmelCase  ,class_labels=__UpperCAmelCase      ).loss
      loss.backward()






  def 							UpperCAmelCase_	(    self      )    ->		List[str]:
      # only MaskFormerForInstanceSegmentation has the loss
      lowerCAmelCase__ :  Tuple							      =					self.all_model_classes[1]
      lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__ :  Optional[int]							      =					self.model_tester.prepare_config_and_inputs()
      lowerCAmelCase__ :  Union[str, Any]							      =					True
      lowerCAmelCase__ :  Tuple							      =					True

      lowerCAmelCase__ :  Optional[Any]							      =					model_class(__UpperCAmelCase      )
      model.to(__UpperCAmelCase      )
      model.train()

      lowerCAmelCase__ :  Dict							      =					model(__UpperCAmelCase  ,mask_labels=__UpperCAmelCase  ,class_labels=__UpperCAmelCase      )

      lowerCAmelCase__ :  Optional[Any]							      =					outputs.encoder_hidden_states[0]
      encoder_hidden_states.retain_grad()

      lowerCAmelCase__ :  str							      =					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
      lowerCAmelCase__ :  Union[str, Any]							      =					outputs.transformer_decoder_hidden_states[0]
      transformer_decoder_hidden_states.retain_grad()

      lowerCAmelCase__ :  List[Any]							      =					outputs.attentions[0]
      attentions.retain_grad()

      outputs.loss.backward(retain_graph=__UpperCAmelCase      )

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







_lowerCAmelCase      						=	1e-4
def    _SCREAMING_SNAKE_CASE  (       ):



    """simple docstring"""





    lowerCAmelCase__ :  Union[str, Any]							      =					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
    return image






@require_vision
@slow
class        lowerCAmelCase_(				unittest.TestCase     ):
  '''simple docstring'''




  @cached_property
  def 							UpperCAmelCase_	(    self      )    ->		List[Any]:
      return (
          MaskFormerImageProcessor.from_pretrained("""facebook/maskformer-swin-small-coco"""      )
          if is_vision_available()
          else None
      )




  def 							UpperCAmelCase_	(    self      )    ->		Any:
      lowerCAmelCase__ :  Any							      =					MaskFormerModel.from_pretrained("""facebook/maskformer-swin-small-coco"""      ).to(__UpperCAmelCase      )
      lowerCAmelCase__ :  str							      =					self.default_image_processor
      lowerCAmelCase__ :  str							      =					prepare_img()
      lowerCAmelCase__ :  Optional[int]							      =					image_processor(__UpperCAmelCase  ,return_tensors="""pt"""      ).to(__UpperCAmelCase      )
      lowerCAmelCase__ :  Dict							      =					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(__UpperCAmelCase  ,(1, 3, 800, 1088)      )

      with torch.no_grad():
          lowerCAmelCase__ :  Union[str, Any]							      =					model(**__UpperCAmelCase      )

      lowerCAmelCase__ :  Optional[Any]							      =					torch.tensor(
          [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]]      ).to(__UpperCAmelCase      )
      self.assertTrue(
          torch.allclose(
              outputs.encoder_last_hidden_state[0, 0, :3, :3]  ,__UpperCAmelCase  ,atol=__UpperCAmelCase      )      )

      lowerCAmelCase__ :  Dict							      =					torch.tensor(
          [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]]      ).to(__UpperCAmelCase      )
      self.assertTrue(
          torch.allclose(
              outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]  ,__UpperCAmelCase  ,atol=__UpperCAmelCase      )      )

      lowerCAmelCase__ :  Optional[int]							      =					torch.tensor(
          [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]]      ).to(__UpperCAmelCase      )
      self.assertTrue(
          torch.allclose(
              outputs.transformer_decoder_last_hidden_state[0, :3, :3]  ,__UpperCAmelCase  ,atol=__UpperCAmelCase      )      )




  def 							UpperCAmelCase_	(    self      )    ->		Optional[Any]:
      lowerCAmelCase__ :  List[Any]							      =					(
          MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""      )
          .to(__UpperCAmelCase      )
          .eval()
      )
      lowerCAmelCase__ :  Optional[Any]							      =					self.default_image_processor
      lowerCAmelCase__ :  List[str]							      =					prepare_img()
      lowerCAmelCase__ :  str							      =					image_processor(__UpperCAmelCase  ,return_tensors="""pt"""      ).to(__UpperCAmelCase      )
      lowerCAmelCase__ :  Optional[int]							      =					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(__UpperCAmelCase  ,(1, 3, 800, 1088)      )

      with torch.no_grad():
          lowerCAmelCase__ :  List[Any]							      =					model(**__UpperCAmelCase      )
      # masks_queries_logits
      lowerCAmelCase__ :  Optional[int]							      =					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)  ,)
      lowerCAmelCase__ :  Optional[int]							      =					[
          [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3],
          [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5],
          [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2],
      ]
      lowerCAmelCase__ :  Optional[int]							      =					torch.tensor(__UpperCAmelCase      ).to(__UpperCAmelCase      )
      self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]  ,__UpperCAmelCase  ,atol=__UpperCAmelCase      )      )
      # class_queries_logits
      lowerCAmelCase__ :  Tuple							      =					outputs.class_queries_logits
      self.assertEqual(
          class_queries_logits.shape  ,(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)      )
      lowerCAmelCase__ :  Union[str, Any]							      =					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(__UpperCAmelCase      )
      self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]  ,__UpperCAmelCase  ,atol=__UpperCAmelCase      )      )




  def 							UpperCAmelCase_	(    self      )    ->		str:
      lowerCAmelCase__ :  List[Any]							      =					(
          MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-resnet101-coco-stuff"""      )
          .to(__UpperCAmelCase      )
          .eval()
      )
      lowerCAmelCase__ :  Optional[Any]							      =					self.default_image_processor
      lowerCAmelCase__ :  int							      =					prepare_img()
      lowerCAmelCase__ :  Optional[Any]							      =					image_processor(__UpperCAmelCase  ,return_tensors="""pt"""      ).to(__UpperCAmelCase      )
      lowerCAmelCase__ :  str							      =					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(__UpperCAmelCase  ,(1, 3, 800, 1088)      )

      with torch.no_grad():
          lowerCAmelCase__ :  str							      =					model(**__UpperCAmelCase      )
      # masks_queries_logits
      lowerCAmelCase__ :  Optional[Any]							      =					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)  ,)
      lowerCAmelCase__ :  int							      =					[[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]]
      lowerCAmelCase__ :  List[str]							      =					torch.tensor(__UpperCAmelCase      ).to(__UpperCAmelCase      )
      self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]  ,__UpperCAmelCase  ,atol=__UpperCAmelCase      )      )
      # class_queries_logits
      lowerCAmelCase__ :  Optional[Any]							      =					outputs.class_queries_logits
      self.assertEqual(
          class_queries_logits.shape  ,(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)      )
      lowerCAmelCase__ :  Tuple							      =					torch.tensor(
          [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]]      ).to(__UpperCAmelCase      )
      self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]  ,__UpperCAmelCase  ,atol=__UpperCAmelCase      )      )






  def 							UpperCAmelCase_	(    self      )    ->		Optional[Any]:
      lowerCAmelCase__ :  str							      =					(
          MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""      )
          .to(__UpperCAmelCase      )
          .eval()
      )
      lowerCAmelCase__ :  Dict							      =					self.default_image_processor

      lowerCAmelCase__ :  Union[str, Any]							      =					image_processor(
          [np.zeros((3, 800, 1333)      ), np.zeros((3, 800, 1333)      )]  ,segmentation_maps=[np.zeros((384, 384)      ).astype(np.floataa      ), np.zeros((384, 384)      ).astype(np.floataa      )]  ,return_tensors="""pt"""  ,)

      lowerCAmelCase__ :  Tuple							      =					inputs["""pixel_values"""].to(__UpperCAmelCase      )
      lowerCAmelCase__ :  Union[str, Any]							      =					[el.to(__UpperCAmelCase      ) for el in inputs["""mask_labels"""]]
      lowerCAmelCase__ :  Union[str, Any]							      =					[el.to(__UpperCAmelCase      ) for el in inputs["""class_labels"""]]

      with torch.no_grad():
          lowerCAmelCase__ :  Any							      =					model(**__UpperCAmelCase      )

      self.assertTrue(outputs.loss is not None      )


