


import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
   from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor






class    UpperCAmelCase__	:



    """simple docstring"""






    def __init__(      self ,       A_ ,       A_=13 ,       A_=32 ,       A_=3 ,       A_=4 ,       A_=[10, 20, 30, 40] ,       A_=[2, 2, 3, 2] ,       A_=True ,       A_=True ,       A_=37 ,       A_="gelu" ,       A_=10 ,       A_=0.02 ,       A_=["stage2", "stage3", "stage4"] ,       A_=[2, 3, 4] ,       A_=None ,       )  ->	Optional[int]:
         __UpperCamelCase   							=parent
         __UpperCamelCase   							=batch_size
         __UpperCamelCase   							=image_size
         __UpperCamelCase   							=num_channels
         __UpperCamelCase   							=num_stages
         __UpperCamelCase   							=hidden_sizes
         __UpperCamelCase   							=depths
         __UpperCamelCase   							=is_training
         __UpperCamelCase   							=use_labels
         __UpperCamelCase   							=intermediate_size
         __UpperCamelCase   							=hidden_act
         __UpperCamelCase   							=num_labels
         __UpperCamelCase   							=initializer_range
         __UpperCamelCase   							=out_features
         __UpperCamelCase   							=out_indices
         __UpperCamelCase   							=scope






    def _a (      self   )  ->	Tuple:
         __UpperCamelCase   							=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

         __UpperCamelCase   							=self.get_config()

         return config, pixel_values, labels






    def _a (      self   )  ->	Union[str, Any]:
         return ConvNextVaConfig(
             num_channels=self.num_channels ,       hidden_sizes=self.hidden_sizes ,       depths=self.depths ,       num_stages=self.num_stages ,       hidden_act=self.hidden_act ,       is_decoder=A_ ,       initializer_range=self.initializer_range ,       out_features=self.out_features ,       out_indices=self.out_indices ,       num_labels=self.num_labels ,       )






    def _a (      self ,       A_ ,       A_ ,       A_   )  ->	str:
         __UpperCamelCase   							=ConvNextVaModel(config=A_   )
         model.to(A_   )
         model.eval()
         __UpperCamelCase   							=model(A_   )
         # expected last hidden states: B, C, H // 32, W // 32
         self.parent.assertEqual(
             result.last_hidden_state.shape ,       (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,       )






    def _a (      self ,       A_ ,       A_ ,       A_   )  ->	int:
         __UpperCamelCase   							=ConvNextVaForImageClassification(A_   )
         model.to(A_   )
         model.eval()
         __UpperCamelCase   							=model(A_ ,       labels=A_   )
         self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_labels)   )






    def _a (      self ,       A_ ,       A_ ,       A_   )  ->	Optional[int]:
         __UpperCamelCase   							=ConvNextVaBackbone(config=A_   )
         model.to(A_   )
         model.eval()
         __UpperCamelCase   							=model(A_   )

         # verify hidden states
         self.parent.assertEqual(len(result.feature_maps   ) ,       len(config.out_features   )   )
         self.parent.assertListEqual(list(result.feature_maps[0].shape   ) ,       [self.batch_size, self.hidden_sizes[1], 4, 4]   )

         # verify channels
         self.parent.assertEqual(len(model.channels   ) ,       len(config.out_features   )   )
         self.parent.assertListEqual(model.channels ,       config.hidden_sizes[1:]   )

         # verify backbone works with out_features=None
         __UpperCamelCase   							=None
         __UpperCamelCase   							=ConvNextVaBackbone(config=A_   )
         model.to(A_   )
         model.eval()
         __UpperCamelCase   							=model(A_   )

         # verify feature maps
         self.parent.assertEqual(len(result.feature_maps   ) ,       1   )
         self.parent.assertListEqual(list(result.feature_maps[0].shape   ) ,       [self.batch_size, self.hidden_sizes[-1], 1, 1]   )

         # verify channels
         self.parent.assertEqual(len(model.channels   ) ,       1   )
         self.parent.assertListEqual(model.channels ,       [config.hidden_sizes[-1]]   )






    def _a (      self   )  ->	Optional[int]:
         __UpperCamelCase   							=self.prepare_config_and_inputs()
         __UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase   							=config_and_inputs
         __UpperCamelCase   							={'pixel_values': pixel_values}
         return config, inputs_dict






    def _a (      self   )  ->	int:
         __UpperCamelCase   							=self.prepare_config_and_inputs()
         __UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase   							=config_and_inputs
         __UpperCamelCase   							={'pixel_values': pixel_values, 'labels': labels}
         return config, inputs_dict






@require_torch
class    UpperCAmelCase__	( A_       ,  A_       ,  unittest.TestCase		):



    """simple docstring"""






    UpperCAmelCase__						:		str              =  (
        (
            ConvNextVaModel,
            ConvNextVaForImageClassification,
            ConvNextVaBackbone,
        )
        if is_torch_available()
        else ()
    )
    UpperCAmelCase__						:		List[Any]              =  (
        {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
        if is_torch_available()
        else {}
    )

    UpperCAmelCase__						:		str              =  False
    UpperCAmelCase__						:		Tuple              =  False
    UpperCAmelCase__						:		Optional[Any]              =  False
    UpperCAmelCase__						:		Dict              =  False
    UpperCAmelCase__						:		Any              =  False






    def _a (      self   )  ->	Dict:
         __UpperCamelCase   							=ConvNextVaModelTester(self   )
         __UpperCamelCase   							=ConfigTester(self ,       config_class=A_ ,       has_text_modality=A_ ,       hidden_size=37   )






    def _a (      self   )  ->	Dict:
         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 _a (      self   )  ->	Union[str, Any]:
         return






    @unittest.skip(reason='ConvNextV2 does not use inputs_embeds'   )
    def _a (      self   )  ->	str:
         pass






    @unittest.skip(reason='ConvNextV2 does not support input and output embeddings'   )
    def _a (      self   )  ->	str:
         pass






    @unittest.skip(reason='ConvNextV2 does not use feedforward chunking'   )
    def _a (      self   )  ->	int:
         pass






    def _a (      self   )  ->	List[Any]:
         if not self.model_tester.is_training:
              return

         for model_class in self.all_model_classes:
              __UpperCamelCase							,				__UpperCamelCase   							=self.model_tester.prepare_config_and_inputs_with_labels()
              __UpperCamelCase   							=True

              if model_class.__name__ in [
                  *get_values(A_   ),
                  *get_values(A_   ),
              ]:
                   continue

              __UpperCamelCase   							=model_class(A_   )
              model.to(A_   )
              model.train()
              __UpperCamelCase   							=self._prepare_for_class(A_ ,       A_ ,       return_labels=A_   )
              __UpperCamelCase   							=model(**A_   ).loss
              loss.backward()






    def _a (      self   )  ->	Tuple:
         if not self.model_tester.is_training:
              return

         for model_class in self.all_model_classes:
              __UpperCamelCase							,				__UpperCamelCase   							=self.model_tester.prepare_config_and_inputs_with_labels()
              __UpperCamelCase   							=False
              __UpperCamelCase   							=True

              if (
                  model_class.__name__
                  in [*get_values(A_   ), *get_values(A_   )]
                  or not model_class.supports_gradient_checkpointing
              ):
                   continue

              __UpperCamelCase   							=model_class(A_   )
              model.to(A_   )
              model.gradient_checkpointing_enable()
              model.train()
              __UpperCamelCase   							=self._prepare_for_class(A_ ,       A_ ,       return_labels=A_   )
              __UpperCamelCase   							=model(**A_   ).loss
              loss.backward()






    def _a (      self   )  ->	Tuple:
         __UpperCamelCase							,				__UpperCamelCase   							=self.model_tester.prepare_config_and_inputs_for_common()

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

              __UpperCamelCase   							=['pixel_values']
              self.assertListEqual(arg_names[:1] ,       A_   )






    def _a (      self   )  ->	Dict:
         __UpperCamelCase   							=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*A_   )






    def _a (      self   )  ->	Union[str, Any]:
         def check_hidden_states_output(A_ ,       A_ ,       A_   ):
              __UpperCamelCase   							=model_class(A_   )
              model.to(A_   )
              model.eval()

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

              __UpperCamelCase   							=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              __UpperCamelCase   							=self.model_tester.num_stages
              self.assertEqual(len(A_   ) ,       expected_num_stages + 1   )

              # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width)
              self.assertListEqual(
                  list(hidden_states[0].shape[-2:]   ) ,       [self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,       )

         __UpperCamelCase							,				__UpperCamelCase   							=self.model_tester.prepare_config_and_inputs_for_common()

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

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

              check_hidden_states_output(A_ ,       A_ ,       A_   )






    def _a (      self   )  ->	Optional[int]:
         __UpperCamelCase   							=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*A_   )






    @slow
    def _a (      self   )  ->	int:
         for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __UpperCamelCase   							=ConvNextVaModel.from_pretrained(A_   )
              self.assertIsNotNone(A_   )

def 						_UpperCAmelCase    (      ):
     __UpperCamelCase   							=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
     return image






@require_torch
@require_vision
class    UpperCAmelCase__	( unittest.TestCase		):



    """simple docstring"""






    @cached_property
    def _a (      self   )  ->	Optional[Any]:
         return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224'   ) if is_vision_available() else None






    @slow
    def _a (      self   )  ->	str:
         __UpperCamelCase   							=ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'   ).to(A_   )

         __UpperCamelCase   							=self.default_image_processor
         __UpperCamelCase   							=prepare_img()
         __UpperCamelCase   							=preprocessor(images=A_ ,       return_tensors='pt'   ).to(A_   )

         # forward pass
         with torch.no_grad():
              __UpperCamelCase   							=model(**A_   )

         # verify the logits
         __UpperCamelCase   							=torch.Size((1, 1000)   )
         self.assertEqual(outputs.logits.shape ,       A_   )

         __UpperCamelCase   							=torch.tensor([0.9996, 0.1966, -0.4386]   ).to(A_   )
         self.assertTrue(torch.allclose(outputs.logits[0, :3] ,       A_ ,       atol=1E-4   )   )









import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image

from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig
from transformers.utils import logging


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

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : Optional[Any]    ):
     __UpperCamelCase   							=SwinConfig(
         embed_dim=1_92      ,					depths=(2, 2, 18, 2)      ,					num_heads=(6, 12, 24, 48)      ,					window_size=12      ,					out_features=['stage2', 'stage3', 'stage4']      ,					)

     __UpperCamelCase   							=DetaConfig(
         backbone_config=SCREAMING_SNAKE_CASE__      ,					num_queries=9_00      ,					encoder_ffn_dim=20_48      ,					decoder_ffn_dim=20_48      ,					num_feature_levels=5      ,					assign_first_stage=SCREAMING_SNAKE_CASE__      ,					with_box_refine=SCREAMING_SNAKE_CASE__      ,					two_stage=SCREAMING_SNAKE_CASE__      ,					)

     # set labels
     __UpperCamelCase   							='huggingface/label-files'
     if "o365" in model_name:
          __UpperCamelCase   							=3_66
          __UpperCamelCase   							='object365-id2label.json'
     else:
          __UpperCamelCase   							=91
          __UpperCamelCase   							='coco-detection-id2label.json'

     __UpperCamelCase   							=num_labels
     __UpperCamelCase   							=json.load(open(cached_download(hf_hub_url(SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__      ,					repo_type='dataset'    )    )      ,					'r'    )    )
     __UpperCamelCase   							={int(SCREAMING_SNAKE_CASE__    ): v for k, v in idalabel.items()}
     __UpperCamelCase   							=idalabel
     __UpperCamelCase   							={v: k for k, v in idalabel.items()}

     return config

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : Optional[Any]    ):
     __UpperCamelCase   							=[]

     # stem
     # fmt: off
     rename_keys.append(('backbone.0.body.patch_embed.proj.weight', 'model.backbone.model.embeddings.patch_embeddings.projection.weight')    )
     rename_keys.append(('backbone.0.body.patch_embed.proj.bias', 'model.backbone.model.embeddings.patch_embeddings.projection.bias')    )
     rename_keys.append(('backbone.0.body.patch_embed.norm.weight', 'model.backbone.model.embeddings.norm.weight')    )
     rename_keys.append(('backbone.0.body.patch_embed.norm.bias', 'model.backbone.model.embeddings.norm.bias')    )
     # stages
     for i in range(len(config.backbone_config.depths    )    ):
          for j in range(config.backbone_config.depths[i]    ):
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.norm1.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.norm1.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.norm2.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.norm2.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias', F'model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias')    )

          if i < 3:
               rename_keys.append((F'backbone.0.body.layers.{i}.downsample.reduction.weight', F'model.backbone.model.encoder.layers.{i}.downsample.reduction.weight')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.downsample.norm.weight', F'model.backbone.model.encoder.layers.{i}.downsample.norm.weight')    )
               rename_keys.append((F'backbone.0.body.layers.{i}.downsample.norm.bias', F'model.backbone.model.encoder.layers.{i}.downsample.norm.bias')    )

     rename_keys.append(('backbone.0.body.norm1.weight', 'model.backbone.model.hidden_states_norms.stage2.weight')    )
     rename_keys.append(('backbone.0.body.norm1.bias', 'model.backbone.model.hidden_states_norms.stage2.bias')    )
     rename_keys.append(('backbone.0.body.norm2.weight', 'model.backbone.model.hidden_states_norms.stage3.weight')    )
     rename_keys.append(('backbone.0.body.norm2.bias', 'model.backbone.model.hidden_states_norms.stage3.bias')    )
     rename_keys.append(('backbone.0.body.norm3.weight', 'model.backbone.model.hidden_states_norms.stage4.weight')    )
     rename_keys.append(('backbone.0.body.norm3.bias', 'model.backbone.model.hidden_states_norms.stage4.bias')    )

     # transformer encoder
     for i in range(config.encoder_layers    ):
          rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight', F'model.encoder.layers.{i}.self_attn.sampling_offsets.weight')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias', F'model.encoder.layers.{i}.self_attn.sampling_offsets.bias')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.attention_weights.weight', F'model.encoder.layers.{i}.self_attn.attention_weights.weight')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.attention_weights.bias', F'model.encoder.layers.{i}.self_attn.attention_weights.bias')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.value_proj.weight', F'model.encoder.layers.{i}.self_attn.value_proj.weight')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.value_proj.bias', F'model.encoder.layers.{i}.self_attn.value_proj.bias')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.output_proj.weight', F'model.encoder.layers.{i}.self_attn.output_proj.weight')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.self_attn.output_proj.bias', F'model.encoder.layers.{i}.self_attn.output_proj.bias')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.norm1.weight', F'model.encoder.layers.{i}.self_attn_layer_norm.weight')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.norm1.bias', F'model.encoder.layers.{i}.self_attn_layer_norm.bias')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.linear1.weight', F'model.encoder.layers.{i}.fc1.weight')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.linear1.bias', F'model.encoder.layers.{i}.fc1.bias')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.linear2.weight', F'model.encoder.layers.{i}.fc2.weight')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.linear2.bias', F'model.encoder.layers.{i}.fc2.bias')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.norm2.weight', F'model.encoder.layers.{i}.final_layer_norm.weight')    )
          rename_keys.append((F'transformer.encoder.layers.{i}.norm2.bias', F'model.encoder.layers.{i}.final_layer_norm.bias')    )

     # transformer decoder
     for i in range(config.decoder_layers    ):
          rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight', F'model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias', F'model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.attention_weights.weight', F'model.decoder.layers.{i}.encoder_attn.attention_weights.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.attention_weights.bias', F'model.decoder.layers.{i}.encoder_attn.attention_weights.bias')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.value_proj.weight', F'model.decoder.layers.{i}.encoder_attn.value_proj.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.value_proj.bias', F'model.decoder.layers.{i}.encoder_attn.value_proj.bias')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.output_proj.weight', F'model.decoder.layers.{i}.encoder_attn.output_proj.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.cross_attn.output_proj.bias', F'model.decoder.layers.{i}.encoder_attn.output_proj.bias')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.norm1.weight', F'model.decoder.layers.{i}.encoder_attn_layer_norm.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.norm1.bias', F'model.decoder.layers.{i}.encoder_attn_layer_norm.bias')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.self_attn.out_proj.weight', F'model.decoder.layers.{i}.self_attn.out_proj.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.self_attn.out_proj.bias', F'model.decoder.layers.{i}.self_attn.out_proj.bias')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.norm2.weight', F'model.decoder.layers.{i}.self_attn_layer_norm.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.norm2.bias', F'model.decoder.layers.{i}.self_attn_layer_norm.bias')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.linear1.weight', F'model.decoder.layers.{i}.fc1.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.linear1.bias', F'model.decoder.layers.{i}.fc1.bias')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.linear2.weight', F'model.decoder.layers.{i}.fc2.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.linear2.bias', F'model.decoder.layers.{i}.fc2.bias')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.norm3.weight', F'model.decoder.layers.{i}.final_layer_norm.weight')    )
          rename_keys.append((F'transformer.decoder.layers.{i}.norm3.bias', F'model.decoder.layers.{i}.final_layer_norm.bias')    )

     # fmt: on

     return rename_keys

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : List[str]      ,					SCREAMING_SNAKE_CASE__      : Tuple      ,					SCREAMING_SNAKE_CASE__      : List[Any]    ):
     __UpperCamelCase   							=dct.pop(SCREAMING_SNAKE_CASE__    )
     __UpperCamelCase   							=val

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : str    ):
     __UpperCamelCase   							=[int(backbone_config.embed_dim * 2**i    ) for i in range(len(backbone_config.depths    )    )]
     for i in range(len(backbone_config.depths    )    ):
          __UpperCamelCase   							=num_features[i]
          for j in range(backbone_config.depths[i]    ):
               # fmt: off
               # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
               __UpperCamelCase   							=state_dict.pop(F'backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight'    )
               __UpperCamelCase   							=state_dict.pop(F'backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias'    )
               # next, add query, keys and values (in that order) to the state dict
               __UpperCamelCase   							=in_proj_weight[:dim, :]
               __UpperCamelCase   							=in_proj_bias[: dim]
               __UpperCamelCase   							=in_proj_weight[
                   dim : dim * 2, :
               ]
               __UpperCamelCase   							=in_proj_bias[
                   dim : dim * 2
               ]
               __UpperCamelCase   							=in_proj_weight[
                   -dim :, :
               ]
               __UpperCamelCase   							=in_proj_bias[-dim :]
               # fmt: on

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : List[Any]      ,					SCREAMING_SNAKE_CASE__      : List[str]    ):
     # transformer decoder self-attention layers
     __UpperCamelCase   							=config.d_model
     for i in range(config.decoder_layers    ):
          # read in weights + bias of input projection layer of self-attention
          __UpperCamelCase   							=state_dict.pop(F'transformer.decoder.layers.{i}.self_attn.in_proj_weight'    )
          __UpperCamelCase   							=state_dict.pop(F'transformer.decoder.layers.{i}.self_attn.in_proj_bias'    )
          # next, add query, keys and values (in that order) to the state dict
          __UpperCamelCase   							=in_proj_weight[:hidden_size, :]
          __UpperCamelCase   							=in_proj_bias[:hidden_size]
          __UpperCamelCase   							=in_proj_weight[
              hidden_size : hidden_size * 2, :
          ]
          __UpperCamelCase   							=in_proj_bias[hidden_size : hidden_size * 2]
          __UpperCamelCase   							=in_proj_weight[-hidden_size:, :]
          __UpperCamelCase   							=in_proj_bias[-hidden_size:]

def 						_UpperCAmelCase    (      ):
     __UpperCamelCase   							='http://images.cocodataset.org/val2017/000000039769.jpg'
     __UpperCamelCase   							=Image.open(requests.get(SCREAMING_SNAKE_CASE__      ,					stream=SCREAMING_SNAKE_CASE__    ).raw    )

     return im

@torch.no_grad()
def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : Tuple      ,					SCREAMING_SNAKE_CASE__      : List[Any]      ,					SCREAMING_SNAKE_CASE__      : Tuple    ):
     __UpperCamelCase   							=get_deta_config(SCREAMING_SNAKE_CASE__    )

     # load original state dict
     if model_name == "deta-swin-large":
          __UpperCamelCase   							=hf_hub_download(repo_id='nielsr/deta-checkpoints'      ,					filename='adet_swin_ft.pth'    )
     elif model_name == "deta-swin-large-o365":
          __UpperCamelCase   							=hf_hub_download(repo_id='jozhang97/deta-swin-l-o365'      ,					filename='deta_swin_pt_o365.pth'    )
     else:
          raise ValueError(F'Model name {model_name} not supported'    )

     __UpperCamelCase   							=torch.load(SCREAMING_SNAKE_CASE__      ,					map_location='cpu'    )['model']

     # original state dict
     for name, param in state_dict.items():
          print(SCREAMING_SNAKE_CASE__      ,					param.shape    )

     # rename keys
     __UpperCamelCase   							=create_rename_keys(SCREAMING_SNAKE_CASE__    )
     for src, dest in rename_keys:
          rename_key(SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__    )
     read_in_swin_q_k_v(SCREAMING_SNAKE_CASE__      ,					config.backbone_config    )
     read_in_decoder_q_k_v(SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__    )

     # fix some prefixes
     for key in state_dict.copy().keys():
          if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
               __UpperCamelCase   							=state_dict.pop(SCREAMING_SNAKE_CASE__    )
               __UpperCamelCase   							=val
          if "input_proj" in key:
               __UpperCamelCase   							=state_dict.pop(SCREAMING_SNAKE_CASE__    )
               __UpperCamelCase   							=val
          if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
               __UpperCamelCase   							=state_dict.pop(SCREAMING_SNAKE_CASE__    )
               __UpperCamelCase   							=val

    # finally, create HuggingFace model and load state dict
     __UpperCamelCase   							=DetaForObjectDetection(SCREAMING_SNAKE_CASE__    )
     model.load_state_dict(SCREAMING_SNAKE_CASE__    )
     model.eval()

     __UpperCamelCase   							='cuda' if torch.cuda.is_available() else 'cpu'
     model.to(SCREAMING_SNAKE_CASE__    )

     # load image processor
     __UpperCamelCase   							=DetaImageProcessor(format='coco_detection'    )

     # verify our conversion on image
     __UpperCamelCase   							=prepare_img()
     __UpperCamelCase   							=processor(images=SCREAMING_SNAKE_CASE__      ,					return_tensors='pt'    )
     __UpperCamelCase   							=encoding['pixel_values']
     __UpperCamelCase   							=model(pixel_values.to(SCREAMING_SNAKE_CASE__    )    )

     # verify logits
     print('Logits:'      ,					outputs.logits[0, :3, :3]    )
     print('Boxes:'      ,					outputs.pred_boxes[0, :3, :3]    )
     if model_name == "deta-swin-large":
          __UpperCamelCase   							=torch.tensor(
              [[-7.6308, -2.8485, -5.3737], [-7.2037, -4.5505, -4.8027], [-7.2943, -4.2611, -4.6617]]    )
          __UpperCamelCase   							=torch.tensor([[0.4987, 0.4969, 0.9999], [0.2549, 0.5498, 0.4805], [0.5498, 0.2757, 0.0569]]    )
     elif model_name == "deta-swin-large-o365":
          __UpperCamelCase   							=torch.tensor(
              [[-8.0122, -3.5720, -4.9717], [-8.1547, -3.6886, -4.6389], [-7.6610, -3.6194, -5.0134]]    )
          __UpperCamelCase   							=torch.tensor([[0.2523, 0.5549, 0.4881], [0.7715, 0.4149, 0.4601], [0.5503, 0.2753, 0.0575]]    )
     assert torch.allclose(outputs.logits[0, :3, :3]      ,					expected_logits.to(SCREAMING_SNAKE_CASE__    )      ,					atol=1E-4    )
     assert torch.allclose(outputs.pred_boxes[0, :3, :3]      ,					expected_boxes.to(SCREAMING_SNAKE_CASE__    )      ,					atol=1E-4    )
     print('Everything ok!'    )

     if pytorch_dump_folder_path:
          # Save model and processor
          logger.info(F'Saving PyTorch model and processor to {pytorch_dump_folder_path}...'    )
          Path(SCREAMING_SNAKE_CASE__    ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__    )
          model.save_pretrained(SCREAMING_SNAKE_CASE__    )
          processor.save_pretrained(SCREAMING_SNAKE_CASE__    )

     # Push to hub
     if push_to_hub:
          print('Pushing model and processor to hub...'    )
          model.push_to_hub(F'jozhang97/{model_name}'    )
          processor.push_to_hub(F'jozhang97/{model_name}'    )


if __name__ == "__main__":
   _A			=						argparse.ArgumentParser()

   parser.add_argument(
       '--model_name',
       type=str,
       default='deta-swin-large',
       choices=['deta-swin-large', 'deta-swin-large-o365'],
       help='Name of the model you\'d like to convert.',
   )
   parser.add_argument(
       '--pytorch_dump_folder_path',
       default=None,
       type=str,
       help='Path to the folder to output PyTorch model.',
   )
   parser.add_argument(
       '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
   )
   _A			=						parser.parse_args()
   convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)





