

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
from transformers.utils import logging


logging.set_verbosity_info()
lowercase_     =       logging.get_logger(__name__)
def 					a				(      )   ->				str:





      """simple docstring"""



      _lowercase     	=DetaConfig(
          num_queries=900				,       encoder_ffn_dim=2048				,       decoder_ffn_dim=2048				,       num_feature_levels=5				,       assign_first_stage=A__				,       with_box_refine=A__				,       two_stage=A__				,       )

      # set labels
      _lowercase     	=91
      _lowercase     	='huggingface/label-files'
      _lowercase     	='coco-detection-id2label.json'
      _lowercase     	=json.load(open(cached_download(hf_hub_url(A__				,       A__				,       repo_type='dataset'					)					)				,       'r'					)					)
      _lowercase     	={int(A__					): v for k, v in idalabel.items()}
      _lowercase     	=idalabel
      _lowercase     	={v: k for k, v in idalabel.items()}

      return config
def 					a				(      A__     :       str					)   ->				Any:





      """simple docstring"""



      _lowercase     	=[]

      # stem
      # fmt: off
      rename_keys.append(('backbone.0.body.conv1.weight', 'model.backbone.model.embedder.embedder.convolution.weight')					)
      rename_keys.append(('backbone.0.body.bn1.weight', 'model.backbone.model.embedder.embedder.normalization.weight')					)
      rename_keys.append(('backbone.0.body.bn1.bias', 'model.backbone.model.embedder.embedder.normalization.bias')					)
      rename_keys.append(('backbone.0.body.bn1.running_mean', 'model.backbone.model.embedder.embedder.normalization.running_mean')					)
      rename_keys.append(('backbone.0.body.bn1.running_var', 'model.backbone.model.embedder.embedder.normalization.running_var')					)
      # stages
      for stage_idx in range(len(config.backbone_config.depths					)					):
            for layer_idx in range(config.backbone_config.depths[stage_idx]					):
                  # shortcut
                  if layer_idx == 0:
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight''',
                            )					)
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight''',
                            )					)
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias''',
                            )					)
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean''',
                            )					)
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var''',
                            )					)
                  # 3 convs
                  for i in range(3					):
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight''',
                            )					)
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight''',
                            )					)
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias''',
                            )					)
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean''',
                            )					)
                        rename_keys.append(
                            (
                                F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var''',
                                F'''model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var''',
                            )					)
    # 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 					a				(      A__     :       Tuple				,       A__     :       str				,       A__     :       Optional[int]					)   ->				Tuple:





      """simple docstring"""



      _lowercase     	=dct.pop(A__					)
      _lowercase     	=val
def 					a				(      A__     :       str				,       A__     :       str					)   ->				List[str]:





      """simple docstring"""



      _lowercase     	=config.d_model
      for i in range(config.decoder_layers					):
            # read in weights + bias of input projection layer of self-attention
            _lowercase     	=state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_weight'''					)
            _lowercase     	=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
            _lowercase     	=in_proj_weight[:hidden_size, :]
            _lowercase     	=in_proj_bias[:hidden_size]
            _lowercase     	=in_proj_weight[
                hidden_size : hidden_size * 2, :
            ]
            _lowercase     	=in_proj_bias[hidden_size : hidden_size * 2]
            _lowercase     	=in_proj_weight[-hidden_size:, :]
            _lowercase     	=in_proj_bias[-hidden_size:]
def 					a				(      )   ->				Union[str, Any]:





      """simple docstring"""



      _lowercase     	='http://images.cocodataset.org/val2017/000000039769.jpg'
      _lowercase     	=Image.open(requests.get(A__				,       stream=A__					).raw					)

      return im
@torch.no_grad()
def 					a				(      A__     :       Dict				,       A__     :       str				,       A__     :       int					)   ->				Optional[Any]:





      """simple docstring"""



      _lowercase     	=get_deta_config()

      # load original state dict
      if model_name == "deta-resnet-50":
            _lowercase     	='adet_checkpoint0011.pth'
      elif model_name == "deta-resnet-50-24-epochs":
            _lowercase     	='adet_2x_checkpoint0023.pth'
      else:
            raise ValueError(F'''Model name {model_name} not supported'''					)
      _lowercase     	=hf_hub_download(repo_id='nielsr/deta-checkpoints'				,       filename=A__					)
      _lowercase     	=torch.load(A__				,       map_location='cpu'					)['model']

      # rename keys
      _lowercase     	=create_rename_keys(A__					)
      for src, dest in rename_keys:
            rename_key(A__				,       A__				,       A__					)
      read_in_decoder_q_k_v(A__				,       A__					)

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

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

      _lowercase     	='cuda' if torch.cuda.is_available() else 'cpu'
      model.to(A__					)

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

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

      # verify logits
      if model_name == "deta-resnet-50":
            _lowercase     	=torch.tensor(
                [[-7.3978, -2.5406, -4.1668], [-8.2684, -3.9933, -3.8096], [-7.0515, -3.7973, -5.8516]]					)
            _lowercase     	=torch.tensor([[0.5043, 0.4973, 0.9998], [0.2542, 0.5489, 0.4748], [0.5490, 0.2765, 0.0570]]					)
      elif model_name == "deta-resnet-50-24-epochs":
            _lowercase     	=torch.tensor(
                [[-7.1688, -2.4857, -4.8669], [-7.8630, -3.8154, -4.2674], [-7.2730, -4.1865, -5.5323]]					)
            _lowercase     	=torch.tensor([[0.5021, 0.4971, 0.9994], [0.2546, 0.5486, 0.4731], [0.1686, 0.1986, 0.2142]]					)

      assert torch.allclose(outputs.logits[0, :3, :3]				,       expected_logits.to(A__					)				,       atol=1e-4					)
      assert torch.allclose(outputs.pred_boxes[0, :3, :3]				,       expected_boxes.to(A__					)				,       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(A__					).mkdir(exist_ok=A__					)
            model.save_pretrained(A__					)
            processor.save_pretrained(A__					)

      # 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__":
  lowercase_     =       argparse.ArgumentParser()

  parser.add_argument(
      '--model_name',
      type=str,
      default='deta-resnet-50',
      choices=['deta-resnet-50', 'deta-resnet-50-24-epochs'],
      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.'
  )
  lowercase_     =       parser.parse_args()
  convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)





#
# Sort large text files in a minimum amount of memory
#
import argparse
import os





class 			__lowerCAmelCase					:
  _a						      =  """block_{0}.dat"""




  def __init__(    self							,       lowerCAmelCase )  ->			List[str]:
        '''simple docstring'''






        _lowercase     	=filename
        _lowercase     	=[]




  def   A__					(    self							,       lowerCAmelCase							,       lowerCAmelCase )  ->			str:
        '''simple docstring'''






        _lowercase     	=self.BLOCK_FILENAME_FORMAT.format(lowerCAmelCase )
        with open(lowerCAmelCase							,       'w' ) as file:
              file.write(lowerCAmelCase )
        self.block_filenames.append(lowerCAmelCase )




  def   A__					(    self )  ->			Dict:
        '''simple docstring'''






        return self.block_filenames




  def   A__					(    self							,       lowerCAmelCase							,       lowerCAmelCase=None )  ->			Dict:
        '''simple docstring'''






        _lowercase     	=0
        with open(self.filename ) as file:
              while True:
                    _lowercase     	=file.readlines(lowerCAmelCase )

                    if lines == []:
                          break

                    if sort_key is None:
                          lines.sort()
                    else:
                          lines.sort(key=lowerCAmelCase )

                    self.write_block(''.join(lowerCAmelCase )							,       lowerCAmelCase )
                    i += 1




  def   A__					(    self )  ->			Optional[Any]:
        '''simple docstring'''






        map(os.remove							,       self.block_filenames )





class 			__lowerCAmelCase					:




  def   A__					(    self							,       lowerCAmelCase )  ->			Union[str, Any]:
        '''simple docstring'''






        _lowercase     	=-1
        _lowercase     	=None

        for i in range(len(lowerCAmelCase ) ):
              if min_str is None or choices[i] < min_str:
                    _lowercase     	=i

        return min_index





class 			__lowerCAmelCase					:




  def __init__(    self							,       lowerCAmelCase )  ->			int:
        '''simple docstring'''






        _lowercase     	=files
        _lowercase     	=set()
        _lowercase     	=len(lowerCAmelCase )
        _lowercase     	={i: None for i in range(self.num_buffers )}




  def   A__					(    self )  ->			int:
        '''simple docstring'''






        return {
            i: self.buffers[i] for i in range(self.num_buffers ) if i not in self.empty
        }




  def   A__					(    self )  ->			Union[str, Any]:
        '''simple docstring'''






        for i in range(self.num_buffers ):
              if self.buffers[i] is None and i not in self.empty:
                    _lowercase     	=self.files[i].readline()

                    if self.buffers[i] == "":
                          self.empty.add(lowerCAmelCase )
                          self.files[i].close()

        if len(self.empty ) == self.num_buffers:
              return False

        return True




  def   A__					(    self							,       lowerCAmelCase )  ->			Optional[int]:
        '''simple docstring'''






        _lowercase     	=self.buffers[index]
        _lowercase     	=None

        return value





class 			__lowerCAmelCase					:




  def __init__(    self							,       lowerCAmelCase )  ->			Any:
        '''simple docstring'''






        _lowercase     	=merge_strategy




  def   A__					(    self							,       lowerCAmelCase							,       lowerCAmelCase							,       lowerCAmelCase )  ->			str:
        '''simple docstring'''






        _lowercase     	=FilesArray(self.get_file_handles(lowerCAmelCase							,       lowerCAmelCase ) )
        with open(lowerCAmelCase							,       'w'							,       lowerCAmelCase ) as outfile:
              while buffers.refresh():
                    _lowercase     	=self.merge_strategy.select(buffers.get_dict() )
                    outfile.write(buffers.unshift(lowerCAmelCase ) )




  def   A__					(    self							,       lowerCAmelCase							,       lowerCAmelCase )  ->			Optional[int]:
        '''simple docstring'''






        _lowercase     	={}

        for i in range(len(lowerCAmelCase ) ):
              _lowercase     	=open(filenames[i]							,       'r'							,       lowerCAmelCase )  # noqa: UP015

        return files





class 			__lowerCAmelCase					:




  def __init__(    self							,       lowerCAmelCase )  ->			Union[str, Any]:
        '''simple docstring'''






        _lowercase     	=block_size




  def   A__					(    self							,       lowerCAmelCase							,       lowerCAmelCase=None )  ->			Dict:
        '''simple docstring'''






        _lowercase     	=self.get_number_blocks(lowerCAmelCase							,       self.block_size )
        _lowercase     	=FileSplitter(lowerCAmelCase )
        splitter.split(self.block_size							,       lowerCAmelCase )

        _lowercase     	=FileMerger(NWayMerge() )
        _lowercase     	=self.block_size / (num_blocks + 1)
        merger.merge(splitter.get_block_filenames()							,       filename + '.out'							,       lowerCAmelCase )

        splitter.cleanup()




  def   A__					(    self							,       lowerCAmelCase							,       lowerCAmelCase )  ->			Tuple:
        '''simple docstring'''






        return (os.stat(lowerCAmelCase ).st_size / block_size) + 1
def 					a				(      A__     :       Tuple					)   ->				Optional[Any]:





      """simple docstring"""



      if string[-1].lower() == "k":
            return int(string[:-1]					) * 1024
      elif string[-1].lower() == "m":
            return int(string[:-1]					) * 1024 * 1024
      elif string[-1].lower() == "g":
            return int(string[:-1]					) * 1024 * 1024 * 1024
      else:
            return int(A__					)
def 					a				(      )   ->				str:





      """simple docstring"""



      _lowercase     	=argparse.ArgumentParser()
      parser.add_argument(
          '-m'				,       '--mem'				,       help='amount of memory to use for sorting'				,       default='100M'					)
      parser.add_argument(
          'filename'				,       metavar='<filename>'				,       nargs=1				,       help='name of file to sort'					)
      _lowercase     	=parser.parse_args()

      _lowercase     	=ExternalSort(parse_memory(args.mem					)					)
      sorter.sort(args.filename[0]					)


if __name__ == "__main__":
  main()


