

'''simple docstring'''



import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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 transformers import (
      MODEL_MAPPING,
      SegformerForImageClassification,
      SegformerForSemanticSegmentation,
      SegformerModel,
  )
  from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import SegformerImageProcessor







class 						lowerCAmelCase__   (      a					):



 """simple docstring"""



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


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.config_class(**self.inputs_dict			)
      self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE					,							"""hidden_sizes"""			)			)
      self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE					,							"""num_attention_heads"""			)			)
      self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE					,							"""num_encoder_blocks"""			)			)







class 						lowerCAmelCase__   :



 """simple docstring"""



 def __init__(		self					:       Any					,							__SCREAMING_SNAKE_CASE					:       List[Any]					,							__SCREAMING_SNAKE_CASE					:       List[str]=13					,							__SCREAMING_SNAKE_CASE					:       Dict=64					,							__SCREAMING_SNAKE_CASE					:       Any=3					,							__SCREAMING_SNAKE_CASE					:       int=4					,							__SCREAMING_SNAKE_CASE					:       Dict=[2, 2, 2, 2]					,							__SCREAMING_SNAKE_CASE					:       Any=[8, 4, 2, 1]					,							__SCREAMING_SNAKE_CASE					:       int=[16, 32, 64, 128]					,							__SCREAMING_SNAKE_CASE					:       List[Any]=[1, 4, 8, 16]					,							__SCREAMING_SNAKE_CASE					:       int=[1, 2, 4, 8]					,							__SCREAMING_SNAKE_CASE					:       Optional[int]=True					,							__SCREAMING_SNAKE_CASE					:       int=True					,							__SCREAMING_SNAKE_CASE					:       List[Any]="gelu"					,							__SCREAMING_SNAKE_CASE					:       Union[str, Any]=0.1					,							__SCREAMING_SNAKE_CASE					:       int=0.1					,							__SCREAMING_SNAKE_CASE					:       List[str]=0.02					,							__SCREAMING_SNAKE_CASE					:       int=3					,							__SCREAMING_SNAKE_CASE					:       Any=None					,							)  -> Dict:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      parent
      __SCREAMING_SNAKE_CASE     =      batch_size
      __SCREAMING_SNAKE_CASE     =      image_size
      __SCREAMING_SNAKE_CASE     =      num_channels
      __SCREAMING_SNAKE_CASE     =      num_encoder_blocks
      __SCREAMING_SNAKE_CASE     =      sr_ratios
      __SCREAMING_SNAKE_CASE     =      depths
      __SCREAMING_SNAKE_CASE     =      hidden_sizes
      __SCREAMING_SNAKE_CASE     =      downsampling_rates
      __SCREAMING_SNAKE_CASE     =      num_attention_heads
      __SCREAMING_SNAKE_CASE     =      is_training
      __SCREAMING_SNAKE_CASE     =      use_labels
      __SCREAMING_SNAKE_CASE     =      hidden_act
      __SCREAMING_SNAKE_CASE     =      hidden_dropout_prob
      __SCREAMING_SNAKE_CASE     =      attention_probs_dropout_prob
      __SCREAMING_SNAKE_CASE     =      initializer_range
      __SCREAMING_SNAKE_CASE     =      num_labels
      __SCREAMING_SNAKE_CASE     =      scope
 def       UpperCAmelCase__		(		self					:       str			)  -> Optional[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

      __SCREAMING_SNAKE_CASE     =      None
      if self.use_labels:
           __SCREAMING_SNAKE_CASE     =      ids_tensor([self.batch_size, self.image_size, self.image_size]					,							self.num_labels			)

      __SCREAMING_SNAKE_CASE     =      self.get_config()
      return config, pixel_values, labels
 def       UpperCAmelCase__		(		self					:       int			)  -> Union[str, Any]:


      """simple docstring"""




      return SegformerConfig(
          image_size=self.image_size					,							num_channels=self.num_channels					,							num_encoder_blocks=self.num_encoder_blocks					,							depths=self.depths					,							hidden_sizes=self.hidden_sizes					,							num_attention_heads=self.num_attention_heads					,							hidden_act=self.hidden_act					,							hidden_dropout_prob=self.hidden_dropout_prob					,							attention_probs_dropout_prob=self.attention_probs_dropout_prob					,							initializer_range=self.initializer_range					,							)
 def       UpperCAmelCase__		(		self					:       str					,							__SCREAMING_SNAKE_CASE					:       List[str]					,							__SCREAMING_SNAKE_CASE					:       Optional[int]					,							__SCREAMING_SNAKE_CASE					:       Any			)  -> List[str]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      SegformerModel(config=__SCREAMING_SNAKE_CASE			)
      model.to(__SCREAMING_SNAKE_CASE			)
      model.eval()
      __SCREAMING_SNAKE_CASE     =      model(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      __SCREAMING_SNAKE_CASE     =      self.image_size // (self.downsampling_rates[-1] * 2)
      self.parent.assertEqual(
          result.last_hidden_state.shape					,							(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)			)
 def       UpperCAmelCase__		(		self					:       List[Any]					,							__SCREAMING_SNAKE_CASE					:       Dict					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]					,							__SCREAMING_SNAKE_CASE					:       int			)  -> int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.num_labels
      __SCREAMING_SNAKE_CASE     =      SegformerForSemanticSegmentation(__SCREAMING_SNAKE_CASE			)
      model.to(__SCREAMING_SNAKE_CASE			)
      model.eval()
      __SCREAMING_SNAKE_CASE     =      model(__SCREAMING_SNAKE_CASE			)
      self.parent.assertEqual(
          result.logits.shape					,							(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)			)
      __SCREAMING_SNAKE_CASE     =      model(__SCREAMING_SNAKE_CASE					,							labels=__SCREAMING_SNAKE_CASE			)
      self.parent.assertEqual(
          result.logits.shape					,							(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)			)
      self.parent.assertGreater(result.loss					,							0.0			)
 def       UpperCAmelCase__		(		self					:       Dict					,							__SCREAMING_SNAKE_CASE					:       Any					,							__SCREAMING_SNAKE_CASE					:       List[str]					,							__SCREAMING_SNAKE_CASE					:       str			)  -> Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      1
      __SCREAMING_SNAKE_CASE     =      SegformerForSemanticSegmentation(config=__SCREAMING_SNAKE_CASE			)
      model.to(__SCREAMING_SNAKE_CASE			)
      model.eval()
      __SCREAMING_SNAKE_CASE     =      torch.randint(0					,							1					,							(self.batch_size, self.image_size, self.image_size)			).to(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      model(__SCREAMING_SNAKE_CASE					,							labels=__SCREAMING_SNAKE_CASE			)
      self.parent.assertGreater(result.loss					,							0.0			)


 def       UpperCAmelCase__		(		self					:       Any			)  -> str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.prepare_config_and_inputs()
      __SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE     =      config_and_inputs
      __SCREAMING_SNAKE_CASE     =      {"""pixel_values""": pixel_values}
      return config, inputs_dict







@require_torch
class 						lowerCAmelCase__   (      a ,					a ,					unittest.TestCase					):



 """simple docstring"""



 lowerCAmelCase__  					=      (
     (
         SegformerModel,
         SegformerForSemanticSegmentation,
         SegformerForImageClassification,
     )
     if is_torch_available()
     else ()
 )
 lowerCAmelCase__  					=      (
     {
         "feature-extraction": SegformerModel,
         "image-classification": SegformerForImageClassification,
         "image-segmentation": SegformerForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 lowerCAmelCase__  					=      True
 lowerCAmelCase__  					=      False
 lowerCAmelCase__  					=      False
 lowerCAmelCase__  					=      False
 def       UpperCAmelCase__		(		self					:       Union[str, Any]			)  -> int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      SegformerModelTester(self			)
      __SCREAMING_SNAKE_CASE     =      SegformerConfigTester(self					,							config_class=__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Union[str, Any]			)  -> Optional[int]:


      """simple docstring"""




      self.config_tester.run_common_tests()
 def       UpperCAmelCase__		(		self					:       Dict			)  -> int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       List[Any]			)  -> Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_binary_image_segmentation(*__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Any			)  -> List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_segmentation(*__SCREAMING_SNAKE_CASE			)
 @unittest.skip("""SegFormer does not use inputs_embeds"""			)
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> Tuple:


      """simple docstring"""




      pass
 @unittest.skip("""SegFormer does not have get_input_embeddings method and get_output_embeddings methods"""			)
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> Optional[Any]:


      """simple docstring"""




      pass
 def       UpperCAmelCase__		(		self					:       Union[str, Any]			)  -> Any:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs_for_common()

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

           __SCREAMING_SNAKE_CASE     =      ["""pixel_values"""]
           self.assertListEqual(arg_names[:1]					,							__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Any			)  -> List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs_for_common()
      __SCREAMING_SNAKE_CASE     =      True

      for model_class in self.all_model_classes:
           __SCREAMING_SNAKE_CASE     =      True
           __SCREAMING_SNAKE_CASE     =      False
           __SCREAMING_SNAKE_CASE     =      True
           __SCREAMING_SNAKE_CASE     =      model_class(__SCREAMING_SNAKE_CASE			)
           model.to(__SCREAMING_SNAKE_CASE			)
           model.eval()
           with torch.no_grad():
                __SCREAMING_SNAKE_CASE     =      model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)			)
           __SCREAMING_SNAKE_CASE     =      outputs.attentions

           __SCREAMING_SNAKE_CASE     =      sum(self.model_tester.depths			)
           self.assertEqual(len(__SCREAMING_SNAKE_CASE			)					,							__SCREAMING_SNAKE_CASE			)

           # check that output_attentions also work using config
           del inputs_dict["output_attentions"]
           __SCREAMING_SNAKE_CASE     =      True
           __SCREAMING_SNAKE_CASE     =      model_class(__SCREAMING_SNAKE_CASE			)
           model.to(__SCREAMING_SNAKE_CASE			)
           model.eval()
           with torch.no_grad():
                __SCREAMING_SNAKE_CASE     =      model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)			)
           __SCREAMING_SNAKE_CASE     =      outputs.attentions

           self.assertEqual(len(__SCREAMING_SNAKE_CASE			)					,							__SCREAMING_SNAKE_CASE			)

           # verify the first attentions (first block, first layer)
           __SCREAMING_SNAKE_CASE     =      (self.model_tester.image_size // 4) ** 2
           __SCREAMING_SNAKE_CASE     =      (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
           self.assertListEqual(
               list(attentions[0].shape[-3:]			)					,							[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]					,							)

           # verify the last attentions (last block, last layer)
           __SCREAMING_SNAKE_CASE     =      (self.model_tester.image_size // 32) ** 2
           __SCREAMING_SNAKE_CASE     =      (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
           self.assertListEqual(
               list(attentions[-1].shape[-3:]			)					,							[self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]					,							)
           __SCREAMING_SNAKE_CASE     =      len(__SCREAMING_SNAKE_CASE			)

           # Check attention is always last and order is fine
           __SCREAMING_SNAKE_CASE     =      True
           __SCREAMING_SNAKE_CASE     =      True
           __SCREAMING_SNAKE_CASE     =      model_class(__SCREAMING_SNAKE_CASE			)
           model.to(__SCREAMING_SNAKE_CASE			)
           model.eval()
           with torch.no_grad():
                __SCREAMING_SNAKE_CASE     =      model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)			)

           self.assertEqual(out_len + 1					,							len(__SCREAMING_SNAKE_CASE			)			)

           __SCREAMING_SNAKE_CASE     =      outputs.attentions

           self.assertEqual(len(__SCREAMING_SNAKE_CASE			)					,							__SCREAMING_SNAKE_CASE			)
           # verify the first attentions (first block, first layer)
           __SCREAMING_SNAKE_CASE     =      (self.model_tester.image_size // 4) ** 2
           __SCREAMING_SNAKE_CASE     =      (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
           self.assertListEqual(
               list(self_attentions[0].shape[-3:]			)					,							[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]					,							)
 def       UpperCAmelCase__		(		self					:       Union[str, Any]			)  -> Union[str, Any]:


      """simple docstring"""




      def check_hidden_states_output(__SCREAMING_SNAKE_CASE					:       Any					,							__SCREAMING_SNAKE_CASE					:       Optional[int]					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]			):
           __SCREAMING_SNAKE_CASE     =      model_class(__SCREAMING_SNAKE_CASE			)
           model.to(__SCREAMING_SNAKE_CASE			)
           model.eval()

           with torch.no_grad():
                __SCREAMING_SNAKE_CASE     =      model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)			)

           __SCREAMING_SNAKE_CASE     =      outputs.hidden_states

           __SCREAMING_SNAKE_CASE     =      self.model_tester.num_encoder_blocks
           self.assertEqual(len(__SCREAMING_SNAKE_CASE			)					,							__SCREAMING_SNAKE_CASE			)

           # verify the first hidden states (first block)
           self.assertListEqual(
               list(hidden_states[0].shape[-3:]			)					,							[
                   self.model_tester.hidden_sizes[0],
                   self.model_tester.image_size // 4,
                   self.model_tester.image_size // 4,
               ]					,							)

      __SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           __SCREAMING_SNAKE_CASE     =      True
           check_hidden_states_output(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           __SCREAMING_SNAKE_CASE     =      True

           check_hidden_states_output(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Optional[Any]			)  -> List[str]:


      """simple docstring"""




      if not self.model_tester.is_training:
           return

      __SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE     =      self.model_tester.prepare_config_and_inputs_for_common()
      __SCREAMING_SNAKE_CASE     =      True

      for model_class in self.all_model_classes:
           if model_class in get_values(__SCREAMING_SNAKE_CASE			):
                continue

           __SCREAMING_SNAKE_CASE     =      model_class(__SCREAMING_SNAKE_CASE			)
           model.to(__SCREAMING_SNAKE_CASE			)
           model.train()
           __SCREAMING_SNAKE_CASE     =      self._prepare_for_class(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							return_labels=__SCREAMING_SNAKE_CASE			)
           __SCREAMING_SNAKE_CASE     =      model(**__SCREAMING_SNAKE_CASE			).loss
           loss.backward()
 @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
 def       UpperCAmelCase__		(		self					:       List[Any]			)  -> Tuple:


      """simple docstring"""




      pass


 @slow
 def       UpperCAmelCase__		(		self					:       str			)  -> Optional[int]:


      """simple docstring"""




      for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __SCREAMING_SNAKE_CASE     =      SegformerModel.from_pretrained(__SCREAMING_SNAKE_CASE			)
           self.assertIsNotNone(__SCREAMING_SNAKE_CASE			)







def    a__       (  ):




     """simple docstring"""


     __SCREAMING_SNAKE_CASE     =      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
     return image







@require_torch
class 						lowerCAmelCase__   (      unittest.TestCase					):



 """simple docstring"""



 @slow
 def       UpperCAmelCase__		(		self					:       str			)  -> Dict:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      SegformerImageProcessor(
          image_scale=(512, 512)					,							keep_ratio=__SCREAMING_SNAKE_CASE					,							align=__SCREAMING_SNAKE_CASE					,							do_random_crop=__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512"""			).to(
          __SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      prepare_img()
      __SCREAMING_SNAKE_CASE     =      image_processor(images=__SCREAMING_SNAKE_CASE					,							return_tensors="""pt"""			)
      __SCREAMING_SNAKE_CASE     =      encoded_inputs.pixel_values.to(__SCREAMING_SNAKE_CASE			)

      with torch.no_grad():
           __SCREAMING_SNAKE_CASE     =      model(__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      torch.Size((1, model.config.num_labels, 128, 128)			)
      self.assertEqual(outputs.logits.shape					,							__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      torch.tensor(
          [
              [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
              [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
              [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
          ]			).to(__SCREAMING_SNAKE_CASE			)
      self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]					,							__SCREAMING_SNAKE_CASE					,							atol=1E-4			)			)
 @slow
 def       UpperCAmelCase__		(		self					:       Dict			)  -> str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      SegformerImageProcessor(
          image_scale=(512, 512)					,							keep_ratio=__SCREAMING_SNAKE_CASE					,							align=__SCREAMING_SNAKE_CASE					,							do_random_crop=__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      SegformerForSemanticSegmentation.from_pretrained(
          """nvidia/segformer-b1-finetuned-cityscapes-1024-1024"""			).to(__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      prepare_img()
      __SCREAMING_SNAKE_CASE     =      image_processor(images=__SCREAMING_SNAKE_CASE					,							return_tensors="""pt"""			)
      __SCREAMING_SNAKE_CASE     =      encoded_inputs.pixel_values.to(__SCREAMING_SNAKE_CASE			)

      with torch.no_grad():
           __SCREAMING_SNAKE_CASE     =      model(__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      torch.Size((1, model.config.num_labels, 128, 128)			)
      self.assertEqual(outputs.logits.shape					,							__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      torch.tensor(
          [
              [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
              [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
              [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
          ]			).to(__SCREAMING_SNAKE_CASE			)
      self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]					,							__SCREAMING_SNAKE_CASE					,							atol=1E-1			)			)


 @slow
 def       UpperCAmelCase__		(		self					:       Dict			)  -> List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      SegformerImageProcessor(
          image_scale=(512, 512)					,							keep_ratio=__SCREAMING_SNAKE_CASE					,							align=__SCREAMING_SNAKE_CASE					,							do_random_crop=__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512"""			).to(
          __SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      prepare_img()
      __SCREAMING_SNAKE_CASE     =      image_processor(images=__SCREAMING_SNAKE_CASE					,							return_tensors="""pt"""			)
      __SCREAMING_SNAKE_CASE     =      encoded_inputs.pixel_values.to(__SCREAMING_SNAKE_CASE			)

      with torch.no_grad():
           __SCREAMING_SNAKE_CASE     =      model(__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      outputs.logits.detach().cpu()

      __SCREAMING_SNAKE_CASE     =      image_processor.post_process_semantic_segmentation(outputs=__SCREAMING_SNAKE_CASE					,							target_sizes=[(500, 300)]			)
      __SCREAMING_SNAKE_CASE     =      torch.Size((500, 300)			)
      self.assertEqual(segmentation[0].shape					,							__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      image_processor.post_process_semantic_segmentation(outputs=__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      torch.Size((128, 128)			)
      self.assertEqual(segmentation[0].shape					,							__SCREAMING_SNAKE_CASE			)









'''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 :       Tuple			   =     {
    '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    a__       (  a__      ,    a__      ,    a__      ,    a__      ,    a__=False      ,    a__=True						):




     """simple docstring"""


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

     __SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE     =      MODEL_CLASSES[model_type]

     # Initialise TF model
     if config_file in aws_config_map:
          __SCREAMING_SNAKE_CASE     =      cached_file(a__      ,    a__      ,    force_download=not use_cached_models						)
     __SCREAMING_SNAKE_CASE     =      config_class.from_json_file(a__						)
     __SCREAMING_SNAKE_CASE     =      True
     __SCREAMING_SNAKE_CASE     =      True
     print(F'Building TensorFlow model from configuration: {config}'						)
     __SCREAMING_SNAKE_CASE     =      model_class(a__						)

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

     if compare_with_pt_model:
          __SCREAMING_SNAKE_CASE     =      tf_model(tf_model.dummy_inputs      ,    training=a__						)  # build the network

          __SCREAMING_SNAKE_CASE     =      torch.load(a__      ,    map_location="""cpu"""						)
          __SCREAMING_SNAKE_CASE     =      pt_model_class.from_pretrained(
              pretrained_model_name_or_path=a__      ,    config=a__      ,    state_dict=a__						)

          with torch.no_grad():
               __SCREAMING_SNAKE_CASE     =      pt_model(**pt_model.dummy_inputs						)

          __SCREAMING_SNAKE_CASE     =      pto[0].numpy()
          __SCREAMING_SNAKE_CASE     =      tfo[0].numpy()
          __SCREAMING_SNAKE_CASE     =      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    a__       (  a__      ,    a__      ,    a__=None      ,    a__=None      ,    a__=False      ,    a__=False      ,    a__=False      ,    a__=False      ,    ):




     """simple docstring"""


     if args_model_type is None:
          __SCREAMING_SNAKE_CASE     =      list(MODEL_CLASSES.keys()						)
     else:
          __SCREAMING_SNAKE_CASE     =      [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()						)}.'						)

          __SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE     =      MODEL_CLASSES[model_type]

          if model_shortcut_names_or_path is None:
               __SCREAMING_SNAKE_CASE     =      list(aws_model_maps.keys()						)
          if config_shortcut_names_or_path is None:
               __SCREAMING_SNAKE_CASE     =      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
                    __SCREAMING_SNAKE_CASE     =      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:
                    __SCREAMING_SNAKE_CASE     =      cached_file(a__      ,    a__      ,    force_download=not use_cached_models						)
               else:
                    __SCREAMING_SNAKE_CASE     =      config_shortcut_name

               if model_shortcut_name in aws_model_maps:
                    __SCREAMING_SNAKE_CASE     =      cached_file(a__      ,    a__      ,    force_download=not use_cached_models						)
               else:
                    __SCREAMING_SNAKE_CASE     =      model_shortcut_name

               if os.path.isfile(a__						):
                    __SCREAMING_SNAKE_CASE     =      """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 :       List[str]			   =     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[Any]			   =     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,
  )






