'''simple docstring'''

import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import MaskFormerSwinBackbone
  from transformers.models.maskformer import MaskFormerSwinModel


class 				_lowercase	:
      '''simple docstring'''


      def __init__(				self					,lowerCamelCase_					,lowerCamelCase_=13					,lowerCamelCase_=32					,lowerCamelCase_=2					,lowerCamelCase_=3					,lowerCamelCase_=16					,lowerCamelCase_=[1, 2, 1]					,lowerCamelCase_=[2, 2, 4]					,lowerCamelCase_=2					,lowerCamelCase_=2.0					,lowerCamelCase_=True					,lowerCamelCase_=0.0					,lowerCamelCase_=0.0					,lowerCamelCase_=0.1					,lowerCamelCase_="gelu"					,lowerCamelCase_=False					,lowerCamelCase_=True					,lowerCamelCase_=0.02					,lowerCamelCase_=1e-5					,lowerCamelCase_=True					,lowerCamelCase_=None					,lowerCamelCase_=True					,lowerCamelCase_=10					,lowerCamelCase_=8					,lowerCamelCase_=["stage1", "stage2", "stage3"]					,lowerCamelCase_=[1, 2, 3]					,)			->			str:



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[Any]   				=  parent
         UpperCAmelCase__							:				Optional[Any]   				=  batch_size
         UpperCAmelCase__							:				Tuple   				=  image_size
         UpperCAmelCase__							:				Tuple   				=  patch_size
         UpperCAmelCase__							:				int   				=  num_channels
         UpperCAmelCase__							:				str   				=  embed_dim
         UpperCAmelCase__							:				List[str]   				=  depths
         UpperCAmelCase__							:				List[Any]   				=  num_heads
         UpperCAmelCase__							:				Optional[Any]   				=  window_size
         UpperCAmelCase__							:				Tuple   				=  mlp_ratio
         UpperCAmelCase__							:				List[str]   				=  qkv_bias
         UpperCAmelCase__							:				List[str]   				=  hidden_dropout_prob
         UpperCAmelCase__							:				str   				=  attention_probs_dropout_prob
         UpperCAmelCase__							:				Any   				=  drop_path_rate
         UpperCAmelCase__							:				List[Any]   				=  hidden_act
         UpperCAmelCase__							:				Optional[int]   				=  use_absolute_embeddings
         UpperCAmelCase__							:				int   				=  patch_norm
         UpperCAmelCase__							:				Dict   				=  layer_norm_eps
         UpperCAmelCase__							:				Tuple   				=  initializer_range
         UpperCAmelCase__							:				Optional[int]   				=  is_training
         UpperCAmelCase__							:				List[Any]   				=  scope
         UpperCAmelCase__							:				Any   				=  use_labels
         UpperCAmelCase__							:				Any   				=  type_sequence_label_size
         UpperCAmelCase__							:				Any   				=  encoder_stride
         UpperCAmelCase__							:				Optional[int]   				=  out_features
         UpperCAmelCase__							:				Optional[Any]   				=  out_indices




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         UpperCAmelCase__							:				List[str]   				=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

         UpperCAmelCase__							:				Any   				=  None
         if self.use_labels:
            UpperCAmelCase__							:				List[str]   				=  ids_tensor([self.batch_size]					,self.type_sequence_label_size							)

         UpperCAmelCase__							:				Tuple   				=  self.get_config()

         return config, pixel_values, labels




      def 		lowerCAmelCase__					(				self							)			->			Optional[int]:



         '''simple docstring'''



         return MaskFormerSwinConfig(
             image_size=self.image_size					,patch_size=self.patch_size					,num_channels=self.num_channels					,embed_dim=self.embed_dim					,depths=self.depths					,num_heads=self.num_heads					,window_size=self.window_size					,mlp_ratio=self.mlp_ratio					,qkv_bias=self.qkv_bias					,hidden_dropout_prob=self.hidden_dropout_prob					,attention_probs_dropout_prob=self.attention_probs_dropout_prob					,drop_path_rate=self.drop_path_rate					,hidden_act=self.hidden_act					,use_absolute_embeddings=self.use_absolute_embeddings					,path_norm=self.patch_norm					,layer_norm_eps=self.layer_norm_eps					,initializer_range=self.initializer_range					,encoder_stride=self.encoder_stride					,out_features=self.out_features					,out_indices=self.out_indices					,)




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)			->			List[str]:



         '''simple docstring'''



         UpperCAmelCase__							:				Union[str, Any]   				=  MaskFormerSwinModel(config=lowerCamelCase_							)
         model.to(lowerCamelCase_							)
         model.eval()
         UpperCAmelCase__							:				Union[str, Any]   				=  model(lowerCamelCase_							)

         UpperCAmelCase__							:				Any   				=  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths							) - 1))
         UpperCAmelCase__							:				Optional[int]   				=  int(config.embed_dim * 2 ** (len(config.depths							) - 1)							)

         self.parent.assertEqual(result.last_hidden_state.shape					,(self.batch_size, expected_seq_len, expected_dim)							)




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)			->			Union[str, Any]:



         '''simple docstring'''



         UpperCAmelCase__							:				Union[str, Any]   				=  MaskFormerSwinBackbone(config=lowerCamelCase_							)
         model.to(lowerCamelCase_							)
         model.eval()
         UpperCAmelCase__							:				Optional[Any]   				=  model(lowerCamelCase_							)

         # verify feature maps
         self.parent.assertEqual(len(result.feature_maps							)					,len(config.out_features							)							)
         self.parent.assertListEqual(list(result.feature_maps[0].shape							)					,[13, 16, 16, 16]							)

         # verify channels
         self.parent.assertEqual(len(model.channels							)					,len(config.out_features							)							)
         self.parent.assertListEqual(model.channels					,[16, 32, 64]							)

         # verify ValueError
         with self.parent.assertRaises(lowerCamelCase_							):
            UpperCAmelCase__							:				List[Any]   				=  ['''stem''']
            UpperCAmelCase__							:				int   				=  MaskFormerSwinBackbone(config=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			Tuple:



         '''simple docstring'''



         UpperCAmelCase__							:				List[Any]   				=  self.prepare_config_and_inputs()
         UpperCAmelCase__				,      UpperCAmelCase__				,      UpperCAmelCase__							:				List[Any]   				=  config_and_inputs
         UpperCAmelCase__							:				str   				=  {'''pixel_values''': pixel_values}
         return config, inputs_dict




@require_torch
class 				_lowercase	(      lowerCAmelCase		,lowerCAmelCase		,unittest.TestCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      str      							=   (
          (
              MaskFormerSwinModel,
              MaskFormerSwinBackbone,
          )
          if is_torch_available()
          else ()
      )
      UpperCAmelCase_      :      Union[str, Any]      							=   {'''feature-extraction''': MaskFormerSwinModel} if is_torch_available() else {}
      UpperCAmelCase_      :      Optional[Any]      							=   False
      UpperCAmelCase_      :      Any      							=   False
      UpperCAmelCase_      :      str      							=   False
      UpperCAmelCase_      :      Union[str, Any]      							=   False
      UpperCAmelCase_      :      List[str]      							=   False




      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         UpperCAmelCase__							:				Tuple   				=  MaskFormerSwinModelTester(self							)
         UpperCAmelCase__							:				List[str]   				=  ConfigTester(self					,config_class=lowerCamelCase_					,embed_dim=37							)




      @require_torch_multi_gpu
      @unittest.skip(
          reason=(
              '''`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with'''
              ''' `nn.DataParallel`'''
          )							)
      def 		lowerCAmelCase__					(				self							)			->			int:



         '''simple docstring'''



         pass




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         self.create_and_test_config_common_properties()
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()




      def 		lowerCAmelCase__					(				self							)			->			List[Any]:



         '''simple docstring'''



         return




      def 		lowerCAmelCase__					(				self							)			->			Optional[int]:



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[Any]   				=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			Optional[Any]:



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[Any]   				=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_backbone(*lowerCamelCase_							)




      @unittest.skip('''Swin does not use inputs_embeds'''							)
      def 		lowerCAmelCase__					(				self							)			->			int:



         '''simple docstring'''



         pass




      @unittest.skip('''Swin does not support feedforward chunking'''							)
      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         pass




      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				Optional[Any]   				=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase__							:				Optional[int]   				=  model_class(lowerCamelCase_							)
            self.assertIsInstance(model.get_input_embeddings()					,(nn.Module)							)
            UpperCAmelCase__							:				int   				=  model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(lowerCamelCase_					,nn.Linear							)							)




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



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

         for model_class in self.all_model_classes:
            UpperCAmelCase__							:				List[Any]   				=  model_class(lowerCamelCase_							)
            UpperCAmelCase__							:				Optional[Any]   				=  inspect.signature(model.forward							)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            UpperCAmelCase__							:				Dict   				=  [*signature.parameters.keys()]

            UpperCAmelCase__							:				Optional[int]   				=  ['''pixel_values''']
            self.assertListEqual(arg_names[:1]					,lowerCamelCase_							)




      @unittest.skip(reason='''MaskFormerSwin is only used as backbone and doesn\'t support output_attentions'''							)
      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         pass




      @unittest.skip(reason='''MaskFormerSwin is only used as an internal backbone'''							)
      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         pass




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)			->			Optional[int]:



         '''simple docstring'''



         UpperCAmelCase__							:				str   				=  model_class(lowerCamelCase_							)
         model.to(lowerCamelCase_							)
         model.eval()

         with torch.no_grad():
            UpperCAmelCase__							:				List[Any]   				=  model(**self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_							)							)

         UpperCAmelCase__							:				Optional[int]   				=  outputs.hidden_states

         UpperCAmelCase__							:				Union[str, Any]   				=  getattr(
             self.model_tester					,'''expected_num_hidden_layers'''					,len(self.model_tester.depths							) + 1							)
         self.assertEqual(len(lowerCamelCase_							)					,lowerCamelCase_							)

         # Swin has a different seq_length
         UpperCAmelCase__							:				Tuple   				=  (
             config.patch_size
             if isinstance(config.patch_size					,collections.abc.Iterable							)
             else (config.patch_size, config.patch_size)
         )

         UpperCAmelCase__							:				Union[str, Any]   				=  (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

         self.assertListEqual(
             list(hidden_states[0].shape[-2:]							)					,[num_patches, self.model_tester.embed_dim]					,)




      def 		lowerCAmelCase__					(				self							)			->			Dict:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				int   				=  self.model_tester.prepare_config_and_inputs_for_common()

         UpperCAmelCase__							:				Optional[int]   				=  (
             self.model_tester.image_size
             if isinstance(self.model_tester.image_size					,collections.abc.Iterable							)
             else (self.model_tester.image_size, self.model_tester.image_size)
         )

         for model_class in self.all_model_classes:
            UpperCAmelCase__							:				Tuple   				=  True
            self.check_hidden_states_output(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            UpperCAmelCase__							:				Optional[Any]   				=  True

            self.check_hidden_states_output(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self							)			->			str:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				Optional[Any]   				=  self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase__							:				List[Any]   				=  3

         UpperCAmelCase__							:				List[Any]   				=  (
             self.model_tester.image_size
             if isinstance(self.model_tester.image_size					,collections.abc.Iterable							)
             else (self.model_tester.image_size, self.model_tester.image_size)
         )
         UpperCAmelCase__							:				Optional[Any]   				=  (
             config.patch_size
             if isinstance(config.patch_size					,collections.abc.Iterable							)
             else (config.patch_size, config.patch_size)
         )

         UpperCAmelCase__							:				List[Any]   				=  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
         UpperCAmelCase__							:				Optional[int]   				=  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

         for model_class in self.all_model_classes:
            UpperCAmelCase__							:				Optional[int]   				=  True
            self.check_hidden_states_output(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,(padded_height, padded_width)							)

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            UpperCAmelCase__							:				int   				=  True
            self.check_hidden_states_output(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,(padded_height, padded_width)							)




      @unittest.skip(reason='''MaskFormerSwin doesn\'t have pretrained checkpoints'''							)
      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         pass




      @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin'''							)
      def 		lowerCAmelCase__					(				self							)			->			Union[str, Any]:



         '''simple docstring'''



         pass




      @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin'''							)
      def 		lowerCAmelCase__					(				self							)			->			Any:



         '''simple docstring'''



         pass




      def 		lowerCAmelCase__					(				self							)			->			int:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				Optional[int]   				=  self.model_tester.prepare_config_and_inputs_for_common()

         def set_nan_tensor_to_zero(lowerCamelCase_							):
            UpperCAmelCase__							:				int   				=  0
            return t

         def check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_={}							):
            with torch.no_grad():
               UpperCAmelCase__							:				Any   				=  model(**lowerCamelCase_					,return_dict=lowerCamelCase_					,**lowerCamelCase_							)
               UpperCAmelCase__							:				Optional[int]   				=  model(**lowerCamelCase_					,return_dict=lowerCamelCase_					,**lowerCamelCase_							).to_tuple()

               def recursive_check(lowerCamelCase_					,lowerCamelCase_							):
                  if isinstance(lowerCamelCase_					,(List, Tuple)							):
                     for tuple_iterable_value, dict_iterable_value in zip(lowerCamelCase_					,lowerCamelCase_							):
                        recursive_check(lowerCamelCase_					,lowerCamelCase_							)
                  elif isinstance(lowerCamelCase_					,lowerCamelCase_							):
                     for tuple_iterable_value, dict_iterable_value in zip(
                         tuple_object.values()					,dict_object.values()							):
                        recursive_check(lowerCamelCase_					,lowerCamelCase_							)
                  elif tuple_object is None:
                     return
                  else:
                     self.assertTrue(
                         torch.allclose(
                             set_nan_tensor_to_zero(lowerCamelCase_							)					,set_nan_tensor_to_zero(lowerCamelCase_							)					,atol=1e-5							)					,msg=(
                             '''Tuple and dict output are not equal. Difference:'''
                             f''' {torch.max(torch.abs(tuple_object - dict_object							)							)}. Tuple has `nan`:'''
                             f''' {torch.isnan(lowerCamelCase_							).any()} and `inf`: {torch.isinf(lowerCamelCase_							)}. Dict has'''
                             f''' `nan`: {torch.isnan(lowerCamelCase_							).any()} and `inf`: {torch.isinf(lowerCamelCase_							)}.'''
                         )					,)

               recursive_check(lowerCamelCase_					,lowerCamelCase_							)

         for model_class in self.all_model_classes:
            UpperCAmelCase__							:				List[str]   				=  model_class(lowerCamelCase_							)
            model.to(lowerCamelCase_							)
            model.eval()

            UpperCAmelCase__							:				Optional[int]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_							)
            UpperCAmelCase__							:				Any   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_							)
            check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)

            UpperCAmelCase__							:				List[str]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_					,return_labels=lowerCamelCase_							)
            UpperCAmelCase__							:				Tuple   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_					,return_labels=lowerCamelCase_							)
            check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_							)

            UpperCAmelCase__							:				int   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_							)
            UpperCAmelCase__							:				Optional[Any]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_							)
            check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,{'''output_hidden_states''': True}							)

            UpperCAmelCase__							:				List[Any]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_					,return_labels=lowerCamelCase_							)
            UpperCAmelCase__							:				List[str]   				=  self._prepare_for_class(lowerCamelCase_					,lowerCamelCase_					,return_labels=lowerCamelCase_							)
            check_equivalence(lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_					,{'''output_hidden_states''': True}							)




@require_torch
class 				_lowercase	(      unittest.TestCase		,lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Dict      							=   (MaskFormerSwinBackbone,) if is_torch_available() else ()
      UpperCAmelCase_      :      Optional[int]      							=   MaskFormerSwinConfig




      def 		lowerCAmelCase__					(				self							)			->			Dict:



         '''simple docstring'''



         UpperCAmelCase__							:				Tuple   				=  MaskFormerSwinModelTester(self							)




      def 		lowerCAmelCase__					(				self							)			->			Tuple:



         '''simple docstring'''



         UpperCAmelCase__				,      UpperCAmelCase__							:				str   				=  self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase__							:				List[str]   				=  inputs_dict['''pixel_values'''].shape[0]

         for backbone_class in self.all_model_classes:
            UpperCAmelCase__							:				List[str]   				=  backbone_class(lowerCamelCase_							)
            backbone.to(lowerCamelCase_							)
            backbone.eval()

            UpperCAmelCase__							:				List[Any]   				=  backbone(**lowerCamelCase_							)

            # Test default outputs and verify feature maps
            self.assertIsInstance(outputs.feature_maps					,lowerCamelCase_							)
            self.assertTrue(len(outputs.feature_maps							) == len(backbone.channels							)							)
            for feature_map, n_channels in zip(outputs.feature_maps					,backbone.channels							):
               self.assertTrue(feature_map.shape[:2]					,(batch_size, n_channels)							)
            self.assertIsNone(outputs.hidden_states							)
            self.assertIsNone(outputs.attentions							)

            # Test output_hidden_states=True
            UpperCAmelCase__							:				str   				=  backbone(**lowerCamelCase_					,output_hidden_states=lowerCamelCase_							)
            self.assertIsNotNone(outputs.hidden_states							)
            self.assertTrue(len(outputs.hidden_states							)					,len(backbone.stage_names							)							)
            # We skip the stem layer
            for hidden_states, n_channels in zip(outputs.hidden_states[1:]					,backbone.channels							):
               for hidden_state in hidden_states:
                  # Hidden states are in the format (batch_size, (height * width), n_channels)
                  UpperCAmelCase__				,      UpperCAmelCase__				,      UpperCAmelCase__							:				int   				=  hidden_state.shape
                  self.assertTrue((h_batch_size, h_n_channels)					,(batch_size, n_channels)							)

            # Test output_attentions=True
            if self.has_attentions:
               UpperCAmelCase__							:				List[str]   				=  backbone(**lowerCamelCase_					,output_attentions=lowerCamelCase_							)
               self.assertIsNotNone(outputs.attentions							)





'''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()

UpperCamelCase__     :	Optional[int]				=			{
    '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 __UpperCamelCase(   _A					:				Dict  ,			_A					:				List[Any]  ,			_A					:				List[Any]  ,			_A					:				Optional[int]  ,			_A					:				Dict=False  ,			_A					:				List[Any]=True    ):
   '''simple docstring'''
   if model_type not in MODEL_CLASSES:
      raise ValueError(F'''Unrecognized model type, should be one of {list(MODEL_CLASSES.keys()    )}.'''    )

   UpperCAmelCase__				,      UpperCAmelCase__				,      UpperCAmelCase__				,      UpperCAmelCase__							:				Optional[int]   				=  MODEL_CLASSES[model_type]

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

   # Load weights from tf checkpoint
   if pytorch_checkpoint_path in aws_config_map.keys():
      UpperCAmelCase__							:				Optional[int]   				=  cached_file(
          _A  ,			_A  ,			force_download=not use_cached_models    )
   # Load PyTorch checkpoint in tf2 model:
   UpperCAmelCase__							:				int   				=  load_pytorch_checkpoint_in_tfa_model(_A  ,			_A    )

   if compare_with_pt_model:
      UpperCAmelCase__							:				Optional[int]   				=  tf_model(tf_model.dummy_inputs  ,			training=_A    )  # build the network

      UpperCAmelCase__							:				Union[str, Any]   				=  torch.load(_A  ,			map_location='''cpu'''    )
      UpperCAmelCase__							:				Union[str, Any]   				=  pt_model_class.from_pretrained(
          pretrained_model_name_or_path=_A  ,			config=_A  ,			state_dict=_A    )

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

      UpperCAmelCase__							:				List[str]   				=  pto[0].numpy()
      UpperCAmelCase__							:				Union[str, Any]   				=  tfo[0].numpy()
      UpperCAmelCase__							:				Optional[int]   				=  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(_A  ,			save_format='''h5'''    )







def __UpperCamelCase(   _A					:				Any  ,			_A					:				Union[str, Any]  ,			_A					:				Union[str, Any]=None  ,			_A					:				Optional[Any]=None  ,			_A					:				Dict=False  ,			_A					:				str=False  ,			_A					:				Optional[Any]=False  ,			_A					:				List[str]=False  ,			):
   '''simple docstring'''
   if args_model_type is None:
      UpperCAmelCase__							:				Any   				=  list(MODEL_CLASSES.keys()    )
   else:
      UpperCAmelCase__							:				List[Any]   				=  [args_model_type]

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

      UpperCAmelCase__				,      UpperCAmelCase__				,      UpperCAmelCase__				,      UpperCAmelCase__				,      UpperCAmelCase__							:				str   				=  MODEL_CLASSES[model_type]

      if model_shortcut_names_or_path is None:
         UpperCAmelCase__							:				int   				=  list(aws_model_maps.keys()    )
      if config_shortcut_names_or_path is None:
         UpperCAmelCase__							:				Tuple   				=  model_shortcut_names_or_path

      for i, (model_shortcut_name, config_shortcut_name) in enumerate(
          zip(_A  ,			_A    )  ,			start=1    ):
         print('''-''' * 1_00    )
         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
            UpperCAmelCase__							:				Tuple   				=  model_shortcut_name
         elif only_convert_finetuned_models:
            print(F'''    Skipping not finetuned checkpoint {model_shortcut_name}'''    )
            continue
         print(
             F'''    Converting checkpoint {i}/{len(_A    )}: {model_shortcut_name} - model_type {model_type}'''    )
         print('''-''' * 1_00    )

         if config_shortcut_name in aws_config_map:
            UpperCAmelCase__							:				Optional[int]   				=  cached_file(_A  ,			_A  ,			force_download=not use_cached_models    )
         else:
            UpperCAmelCase__							:				Optional[Any]   				=  config_shortcut_name

         if model_shortcut_name in aws_model_maps:
            UpperCAmelCase__							:				Any   				=  cached_file(_A  ,			_A  ,			force_download=not use_cached_models    )
         else:
            UpperCAmelCase__							:				List[str]   				=  model_shortcut_name

         if os.path.isfile(_A    ):
            UpperCAmelCase__							:				Optional[int]   				=  '''converted_model'''

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


if __name__ == "__main__":
  UpperCamelCase__     :	Tuple				=			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.')
  UpperCamelCase__     :	List[str]				=			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,
  )




