




"""simple docstring"""

import argparse
from collections import OrderedDict
from pathlib import Path

import torch

from transformers import (
    VisualBertConfig,
    VisualBertForMultipleChoice,
    VisualBertForPreTraining,
    VisualBertForQuestionAnswering,
    VisualBertForVisualReasoning,
)
from transformers.utils import logging


logging.set_verbosity_info()
a							      =     logging.get_logger(__name__)

a							      =     [
    ('''bert.bert''', '''visual_bert'''),
    ('''bert.cls''', '''cls'''),
    ('''bert.classifier''', '''cls'''),
    ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''),
    ('''position_embeddings_visual''', '''visual_position_embeddings'''),
    ('''projection''', '''visual_projection'''),
]

a							      =     [
    '''nlvr2_coco_pre_trained.th''',
    '''nlvr2_fine_tuned.th''',
    '''nlvr2_pre_trained.th''',
    '''vcr_coco_pre_train.th''',
    '''vcr_fine_tune.th''',
    '''vcr_pre_train.th''',
    '''vqa_coco_pre_trained.th''',
    '''vqa_fine_tuned.th''',
    '''vqa_pre_trained.th''',
]






def 		_snake_case	(   _snake_case				:   Optional[Any]				)       ->   str:






      '''simple docstring'''


      _A     =  torch.load(_snake_case							,    map_location='cpu'				)
      return sd






def 		_snake_case	(   _snake_case				:   Union[str, Any]							,    _snake_case				:   str							,    _snake_case				:   Tuple=rename_keys_prefix				)       ->   List[str]:






      '''simple docstring'''


      _A     =  OrderedDict()
      _A     =  torch.arange(config.max_position_embeddings				).expand((1, -1)				)
      # detector_d = OrderedDict()
      for key in d:
            if "detector" in key:
                  # detector_d[key.replace('detector.','')] = d[key]
                  continue
            _A     =  key
            for name_pair in rename_keys_prefix:
                  _A     =  new_key.replace(name_pair[0]							,    name_pair[1]				)
            _A     =  d[key]
            if key == "bert.cls.predictions.decoder.weight":
                  # Old bert code didn't have `decoder.bias`, but was added separately
                  _A     =  new_d['cls.predictions.bias']
      return new_d






@torch.no_grad()
def 		_snake_case	(   _snake_case				:   List[str]							,    _snake_case				:   Dict				)       ->   Dict:






      '''simple docstring'''


      assert (
          checkpoint_path.split('/'				)[-1] in ACCEPTABLE_CHECKPOINTS
      ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.'''

      # Get Config
      if "pre" in checkpoint_path:
            _A     =  'pretraining'
            if "vcr" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 5_12}
            elif "vqa_advanced" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48}
            elif "vqa" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48}
            elif "nlvr" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 10_24}
            else:
                  raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.'''				)
      else:
            if "vcr" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 5_12}
                  _A     =  'multichoice'
            elif "vqa_advanced" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48}
                  _A     =  'vqa_advanced'
            elif "vqa" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48, 'num_labels': 31_29}
                  _A     =  'vqa'
            elif "nlvr" in checkpoint_path:
                  _A     =  {
                      'visual_embedding_dim': 10_24,
                      'num_labels': 2,
                  }
                  _A     =  'nlvr'

      _A     =  VisualBertConfig(**_snake_case				)

      # Load State Dict
      _A     =  load_state_dict(_snake_case				)

      _A     =  get_new_dict(_snake_case							,    _snake_case				)

      if model_type == "pretraining":
            _A     =  VisualBertForPreTraining(_snake_case				)
      elif model_type == "vqa":
            _A     =  VisualBertForQuestionAnswering(_snake_case				)
      elif model_type == "nlvr":
            _A     =  VisualBertForVisualReasoning(_snake_case				)
      elif model_type == "multichoice":
            _A     =  VisualBertForMultipleChoice(_snake_case				)

      model.load_state_dict(_snake_case				)
      # Save Checkpoints
      Path(_snake_case				).mkdir(exist_ok=_snake_case				)
      model.save_pretrained(_snake_case				)


if __name__ == "__main__":
       a							      =     argparse.ArgumentParser()
       # Required parameters
       parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''')
       parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''')
       a							      =     parser.parse_args()
       convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)





import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
				from PIL import Image
else:







				class 	__lowercase    :





											"""simple docstring"""







											@staticmethod
											def 					UpperCamelCase__     (      *lowerCAmelCase__			,						**lowerCAmelCase__       ):





														"""simple docstring"""




														pass







@is_pipeline_test
@require_vision
@require_torch
class 	__lowercase    (unittest.TestCase  ):





							"""simple docstring"""







							_UpperCAmelCase      =						MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     List[str]					=					pipeline(
										    'zero-shot-object-detection'			,						model='hf-internal-testing/tiny-random-owlvit-object-detection'       )

										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					[
										    {
										        'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
										        'candidate_labels': ['cat', 'remote', 'couch'],
										    }
										]
										return object_detector, examples






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					object_detector(examples[0]			,						threshold=0.0       )

										SCREAMING_SNAKE_CASE_		:     int					=					len(lowerCAmelCase__       )
										self.assertGreater(lowerCAmelCase__			,						0       )
										self.assertEqual(
										    lowerCAmelCase__			,						[
										        {
										            'score': ANY(lowerCAmelCase__       ),
										            'label': ANY(lowerCAmelCase__       ),
										            'box': {'xmin': ANY(lowerCAmelCase__       ), 'ymin': ANY(lowerCAmelCase__       ), 'xmax': ANY(lowerCAmelCase__       ), 'ymax': ANY(lowerCAmelCase__       )},
										        }
										        for i in range(lowerCAmelCase__       )
										    ]			,						)






							@require_tf
							@unittest.skip('Zero Shot Object Detection not implemented in TF'       )
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										pass






							@require_torch
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     List[Any]					=					pipeline(
										    'zero-shot-object-detection'			,						model='hf-internal-testing/tiny-random-owlvit-object-detection'       )

										SCREAMING_SNAKE_CASE_		:     str					=					object_detector(
										    './tests/fixtures/tests_samples/COCO/000000039769.png'			,						candidate_labels=['cat', 'remote', 'couch']			,						threshold=0.64			,						)

										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,						decimals=4       )			,						[
										        {'score': 0.7_235, 'label': 'cat', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
										        {'score': 0.7_218, 'label': 'remote', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
										        {'score': 0.7_184, 'label': 'couch', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
										        {'score': 0.6_748, 'label': 'remote', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
										        {'score': 0.6_656, 'label': 'cat', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
										        {'score': 0.6_614, 'label': 'couch', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
										        {'score': 0.6_456, 'label': 'remote', 'box': {'xmin': 4_9_4, 'ymin': 1_0_5, 'xmax': 5_2_1, 'ymax': 1_2_7}},
										        {'score': 0.642, 'label': 'remote', 'box': {'xmin': 6_7, 'ymin': 2_7_4, 'xmax': 9_3, 'ymax': 2_9_7}},
										        {'score': 0.6_419, 'label': 'cat', 'box': {'xmin': 4_9_4, 'ymin': 1_0_5, 'xmax': 5_2_1, 'ymax': 1_2_7}},
										    ]			,						)

										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					object_detector(
										    [
										        {
										            'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
										            'candidate_labels': ['cat', 'remote', 'couch'],
										        }
										    ]			,						threshold=0.64			,						)

										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,						decimals=4       )			,						[
										        [
										            {'score': 0.7_235, 'label': 'cat', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
										            {'score': 0.7_218, 'label': 'remote', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
										            {'score': 0.7_184, 'label': 'couch', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
										            {'score': 0.6_748, 'label': 'remote', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
										            {'score': 0.6_656, 'label': 'cat', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
										            {'score': 0.6_614, 'label': 'couch', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
										            {'score': 0.6_456, 'label': 'remote', 'box': {'xmin': 4_9_4, 'ymin': 1_0_5, 'xmax': 5_2_1, 'ymax': 1_2_7}},
										            {'score': 0.642, 'label': 'remote', 'box': {'xmin': 6_7, 'ymin': 2_7_4, 'xmax': 9_3, 'ymax': 2_9_7}},
										            {'score': 0.6_419, 'label': 'cat', 'box': {'xmin': 4_9_4, 'ymin': 1_0_5, 'xmax': 5_2_1, 'ymax': 1_2_7}},
										        ]
										    ]			,						)






							@require_torch
							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     List[str]					=					pipeline('zero-shot-object-detection'       )

										SCREAMING_SNAKE_CASE_		:     List[str]					=					object_detector(
										    'http://images.cocodataset.org/val2017/000000039769.jpg'			,						candidate_labels=['cat', 'remote', 'couch']			,						)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,						decimals=4       )			,						[
										        {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
										        {'score': 0.277, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
										        {'score': 0.2_537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 5_5, 'xmax': 3_1_5, 'ymax': 4_7_2}},
										        {'score': 0.1_474, 'label': 'remote', 'box': {'xmin': 3_3_5, 'ymin': 7_4, 'xmax': 3_7_1, 'ymax': 1_8_7}},
										        {'score': 0.1_208, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 6_4_2, 'ymax': 4_7_6}},
										    ]			,						)

										SCREAMING_SNAKE_CASE_		:     List[Any]					=					object_detector(
										    [
										        {
										            'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
										            'candidate_labels': ['cat', 'remote', 'couch'],
										        },
										        {
										            'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
										            'candidate_labels': ['cat', 'remote', 'couch'],
										        },
										    ]			,						)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,						decimals=4       )			,						[
										        [
										            {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
										            {'score': 0.277, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
										            {'score': 0.2_537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 5_5, 'xmax': 3_1_5, 'ymax': 4_7_2}},
										            {'score': 0.1_474, 'label': 'remote', 'box': {'xmin': 3_3_5, 'ymin': 7_4, 'xmax': 3_7_1, 'ymax': 1_8_7}},
										            {'score': 0.1_208, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 6_4_2, 'ymax': 4_7_6}},
										        ],
										        [
										            {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
										            {'score': 0.277, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
										            {'score': 0.2_537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 5_5, 'xmax': 3_1_5, 'ymax': 4_7_2}},
										            {'score': 0.1_474, 'label': 'remote', 'box': {'xmin': 3_3_5, 'ymin': 7_4, 'xmax': 3_7_1, 'ymax': 1_8_7}},
										            {'score': 0.1_208, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 6_4_2, 'ymax': 4_7_6}},
										        ],
										    ]			,						)






							@require_tf
							@unittest.skip('Zero Shot Object Detection not implemented in TF'       )
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										pass






							@require_torch
							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     str					=					0.2
										SCREAMING_SNAKE_CASE_		:     str					=					pipeline('zero-shot-object-detection'       )

										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					object_detector(
										    'http://images.cocodataset.org/val2017/000000039769.jpg'			,						candidate_labels=['cat', 'remote', 'couch']			,						threshold=lowerCAmelCase__			,						)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,						decimals=4       )			,						[
										        {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
										        {'score': 0.277, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
										        {'score': 0.2_537, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 5_5, 'xmax': 3_1_5, 'ymax': 4_7_2}},
										    ]			,						)






							@require_torch
							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Dict					=					2
										SCREAMING_SNAKE_CASE_		:     int					=					pipeline('zero-shot-object-detection'       )

										SCREAMING_SNAKE_CASE_		:     Tuple					=					object_detector(
										    'http://images.cocodataset.org/val2017/000000039769.jpg'			,						candidate_labels=['cat', 'remote', 'couch']			,						top_k=lowerCAmelCase__			,						)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,						decimals=4       )			,						[
										        {'score': 0.2_868, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
										        {'score': 0.277, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
										    ]			,						)





