


import argparse
import json

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD


torch.set_grad_enabled(False)
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_=False )    ->List[str]:
   UpperCAmelCase      					=  []
   for i in range(config.num_hidden_layers ):
      # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
      rename_keys.append((F"""module.blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") )
      rename_keys.append((F"""module.blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") )
      rename_keys.append(
          (F"""module.blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") )
      rename_keys.append((F"""module.blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") )
      rename_keys.append((F"""module.blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") )
      rename_keys.append((F"""module.blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") )
      rename_keys.append((F"""module.blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") )
      rename_keys.append((F"""module.blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") )
      rename_keys.append((F"""module.blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") )
      rename_keys.append((F"""module.blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") )

   # projection layer + position embeddings
   rename_keys.extend(
       [
           ("""module.cls_token""", """vit.embeddings.cls_token"""),
           ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""),
           ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""),
           ("""module.pos_embed""", """vit.embeddings.position_embeddings"""),
       ] )

   if base_model:
      # layernorm + pooler
      rename_keys.extend(
          [
              ("""module.norm.weight""", """layernorm.weight"""),
              ("""module.norm.bias""", """layernorm.bias"""),
          ] )

      # if just the base model, we should remove "vit" from all keys that start with "vit"
      UpperCAmelCase      					=  [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys]
   else:
      # layernorm + classification head
      rename_keys.extend(
          [
              ("""norm.weight""", """vit.layernorm.weight"""),
              ("""norm.bias""", """vit.layernorm.bias"""),
              ("""head.weight""", """classifier.weight"""),
              ("""head.bias""", """classifier.bias"""),
          ] )

   return rename_keys
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_=False )    ->int:
   for i in range(config.num_hidden_layers ):
      if base_model:
         UpperCAmelCase      					=  """"""
      else:
         UpperCAmelCase      					=  """vit."""
      # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
      UpperCAmelCase      					=  state_dict.pop(F"""module.blocks.{i}.attn.qkv.weight""" )
      UpperCAmelCase      					=  state_dict.pop(F"""module.blocks.{i}.attn.qkv.bias""" )
      # next, add query, keys and values (in that order) to the state dict
      UpperCAmelCase      					=  in_proj_weight[
          : config.hidden_size, :
      ]
      UpperCAmelCase      					=  in_proj_bias[: config.hidden_size]
      UpperCAmelCase      					=  in_proj_weight[
          config.hidden_size : config.hidden_size * 2, :
      ]
      UpperCAmelCase      					=  in_proj_bias[
          config.hidden_size : config.hidden_size * 2
      ]
      UpperCAmelCase      					=  in_proj_weight[
          -config.hidden_size :, :
      ]
      UpperCAmelCase      					=  in_proj_bias[-config.hidden_size :]
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Optional[int]:
   UpperCAmelCase      					=  ["""head.weight""", """head.bias"""]
   for k in ignore_keys:
      state_dict.pop(lowerCAmelCase_	,    lowerCAmelCase_ )
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Any:
   # projection head is used in the self-supervised pre-training in MSN,
   # for downstream task it's not needed.
   UpperCAmelCase      					=  [
       """module.fc.fc1.weight""",
       """module.fc.fc1.bias""",
       """module.fc.bn1.weight""",
       """module.fc.bn1.bias""",
       """module.fc.bn1.running_mean""",
       """module.fc.bn1.running_var""",
       """module.fc.bn1.num_batches_tracked""",
       """module.fc.fc2.weight""",
       """module.fc.fc2.bias""",
       """module.fc.bn2.weight""",
       """module.fc.bn2.bias""",
       """module.fc.bn2.running_mean""",
       """module.fc.bn2.running_var""",
       """module.fc.bn2.num_batches_tracked""",
       """module.fc.fc3.weight""",
       """module.fc.fc3.bias""",
   ]
   for k in ignore_keys:
      state_dict.pop(lowerCAmelCase_	,    lowerCAmelCase_ )
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Optional[int]:
   UpperCAmelCase      					=  dct.pop(lowerCAmelCase_ )
   UpperCAmelCase      					=  val
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Optional[Any]:
   UpperCAmelCase      					=  ViTMSNConfig()
   UpperCAmelCase      					=  1_0_0_0

   UpperCAmelCase      					=  """datasets/huggingface/label-files"""
   UpperCAmelCase      					=  """imagenet-1k-id2label.json"""
   UpperCAmelCase      					=  json.load(open(hf_hub_download(lowerCAmelCase_	,    lowerCAmelCase_ )	,    """r""" ) )
   UpperCAmelCase      					=  {int(lowerCAmelCase_ ): v for k, v in idalabel.items()}
   UpperCAmelCase      					=  idalabel
   UpperCAmelCase      					=  {v: k for k, v in idalabel.items()}

   if "s16" in checkpoint_url:
      UpperCAmelCase      					=  3_8_4
      UpperCAmelCase      					=  1_5_3_6
      UpperCAmelCase      					=  6
   elif "l16" in checkpoint_url:
      UpperCAmelCase      					=  1_0_2_4
      UpperCAmelCase      					=  4_0_9_6
      UpperCAmelCase      					=  2_4
      UpperCAmelCase      					=  1_6
      UpperCAmelCase      					=  0.1
   elif "b4" in checkpoint_url:
      UpperCAmelCase      					=  4
   elif "l7" in checkpoint_url:
      UpperCAmelCase      					=  7
      UpperCAmelCase      					=  1_0_2_4
      UpperCAmelCase      					=  4_0_9_6
      UpperCAmelCase      					=  2_4
      UpperCAmelCase      					=  1_6
      UpperCAmelCase      					=  0.1

   UpperCAmelCase      					=  ViTMSNModel(lowerCAmelCase_ )

   UpperCAmelCase      					=  torch.hub.load_state_dict_from_url(lowerCAmelCase_	,    map_location="""cpu""" )["""target_encoder"""]

   UpperCAmelCase      					=  ViTImageProcessor(size=config.image_size )

   remove_projection_head(lowerCAmelCase_ )
   UpperCAmelCase      					=  create_rename_keys(lowerCAmelCase_	,    base_model=lowerCAmelCase_ )

   for src, dest in rename_keys:
      rename_key(lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )
   read_in_q_k_v(lowerCAmelCase_	,    lowerCAmelCase_	,    base_model=lowerCAmelCase_ )

   model.load_state_dict(lowerCAmelCase_ )
   model.eval()

   UpperCAmelCase      					=  """http://images.cocodataset.org/val2017/000000039769.jpg"""

   UpperCAmelCase      					=  Image.open(requests.get(lowerCAmelCase_	,    stream=lowerCAmelCase_ ).raw )
   UpperCAmelCase      					=  ViTImageProcessor(
       size=config.image_size	,    image_mean=lowerCAmelCase_	,    image_std=lowerCAmelCase_ )
   UpperCAmelCase      					=  image_processor(images=lowerCAmelCase_	,    return_tensors="""pt""" )

   # forward pass
   torch.manual_seed(2 )
   UpperCAmelCase      					=  model(**lowerCAmelCase_ )
   UpperCAmelCase      					=  outputs.last_hidden_state

   # The following Colab Notebook was used to generate these outputs:
   # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb
   if "s16" in checkpoint_url:
      UpperCAmelCase      					=  torch.tensor([[-1.0915, -1.4876, -1.1809]] )
   elif "b16" in checkpoint_url:
      UpperCAmelCase      					=  torch.tensor([[14.2889, -18.9045, 11.7281]] )
   elif "l16" in checkpoint_url:
      UpperCAmelCase      					=  torch.tensor([[41.5028, -22.8681, 45.6475]] )
   elif "b4" in checkpoint_url:
      UpperCAmelCase      					=  torch.tensor([[-4.3868, 5.2932, -0.4137]] )
   else:
      UpperCAmelCase      					=  torch.tensor([[-0.1792, -0.6465, 2.4263]] )

   # verify logits
   assert torch.allclose(last_hidden_state[:, 0, :3]	,    lowerCAmelCase_	,    atol=1e-4 )

   print(F"""Saving model to {pytorch_dump_folder_path}""" )
   model.save_pretrained(lowerCAmelCase_ )

   print(F"""Saving image processor to {pytorch_dump_folder_path}""" )
   image_processor.save_pretrained(lowerCAmelCase_ )


if __name__ == "__main__":
 __a	 =      argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     """--checkpoint_url""",
     default="""https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar""",
     type=str,
     help="""URL of the checkpoint you'd like to convert.""",
 )
 parser.add_argument(
     """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
 )

 __a	 =      parser.parse_args()
 convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)







import json
import multiprocessing as mp
import re
from collections import defaultdict
from functools import partial
from typing import Dict, List, Optional, Set, Tuple, Type

from datasets import Dataset
from datasketch import MinHash, MinHashLSH
from dpu_utils.utils.iterators import ThreadedIterator
from tqdm import tqdm


__a	 =      re.compile("""[^A-Za-z_0-9]""")
# parameters used in DuplicationIndex
__a	 =      10
__a	 =      256
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Optional[MinHash]:
   if len(lowerCAmelCase_ ) < MIN_NUM_TOKENS:
      return None
   UpperCAmelCase      					=  MinHash(num_perm=lowerCAmelCase_ )
   for token in set(lowerCAmelCase_ ):
      min_hash.update(token.encode() )
   return min_hash
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Set[str]:
   return {t for t in NON_ALPHA.split(lowerCAmelCase_ ) if len(t.strip() ) > 0}






class 	__lowercase					:





      def __init__(		self    :       List[str]       ,							*,
          __lowerCamelCase    :       float = 0.85       ,							)     -> Any:






         """simple docstring"""







         UpperCAmelCase      					=  duplication_jaccard_threshold
         UpperCAmelCase      					=  NUM_PERM
         UpperCAmelCase      					=  MinHashLSH(threshold=self._duplication_jaccard_threshold       ,							num_perm=self._num_perm							)

         UpperCAmelCase      					=  defaultdict(__lowerCamelCase							)





      def 							_lowercase					(		self    :       Tuple       ,							__lowerCamelCase    :       Tuple       ,							__lowerCamelCase    :       MinHash							)     -> None:






         """simple docstring"""







         UpperCAmelCase      					=  self._index.query(__lowerCamelCase							)
         if code_key in self._index.keys:
            print(F"""Duplicate key {code_key}"""							)
            return

         self._index.insert(__lowerCamelCase       ,							__lowerCamelCase							)
         if len(__lowerCamelCase							) > 0:
            for base_duplicate in close_duplicates:
               if base_duplicate in self._duplicate_clusters:
                  self._duplicate_clusters[base_duplicate].add(__lowerCamelCase							)
                  break
            else:
               self._duplicate_clusters[close_duplicates[0]].add(__lowerCamelCase							)





      def 							_lowercase					(		self    :       Union[str, Any]							)     -> List[List[Dict]]:






         """simple docstring"""







         UpperCAmelCase      					=  []
         for base, duplicates in self._duplicate_clusters.items():
            UpperCAmelCase      					=  [base] + list(__lowerCamelCase							)
            # reformat the cluster to be a list of dict
            UpperCAmelCase      					=  [{"""base_index""": el[0], """repo_name""": el[1], """path""": el[2]} for el in cluster]
            duplicate_clusters.append(__lowerCamelCase							)
         return duplicate_clusters





      def 							_lowercase					(		self    :       Tuple       ,							__lowerCamelCase    :       Optional[int]							)     -> None:






         """simple docstring"""







         UpperCAmelCase      					=  self.get_duplicate_clusters()
         with open(__lowerCamelCase       ,							"""w"""							) as f:
            json.dump(__lowerCamelCase       ,							__lowerCamelCase							)

def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Tuple:
   UpperCAmelCase					,	UpperCAmelCase      					=  element
   UpperCAmelCase      					=  get_min_hash([t for t in NON_ALPHA.split(data["""content"""] ) if len(t.strip() ) > 0] )
   if min_hash is not None:
      return (index, data["repo_name"], data["path"]), min_hash
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->int:
   with mp.Pool() as pool:
      for data in pool.imap_unordered(
          _compute_min_hash	,    ThreadedIterator(lowerCAmelCase_	,    max_queue_size=1_0_0_0_0 )	,    chunksize=1_0_0	,    ):
         if data is not None:
            yield data
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Any:
   UpperCAmelCase      					=  DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase_ )

   for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase_ ) )	,    max_queue_size=1_0_0 ) ):
      di.add(lowerCAmelCase_	,    lowerCAmelCase_ )

   # Returns a List[Cluster] where Cluster is List[str] with the filenames.
   return di.get_duplicate_clusters()
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ )    ->float:
   UpperCAmelCase      					=  get_tokens(lowerCAmelCase_ )
   UpperCAmelCase      					=  get_tokens(lowerCAmelCase_ )
   return len(tokensa & tokensa ) / len(tokensa | tokensa )


__a	 =      None
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Dict:
   UpperCAmelCase      					=  []
   for elementa in cluster:
      UpperCAmelCase      					=  _shared_dataset[elementa["""base_index"""]]["""content"""]
      for elementa in extremes:
         UpperCAmelCase      					=  _shared_dataset[elementa["""base_index"""]]["""content"""]
         if jaccard_similarity(lowerCAmelCase_	,    lowerCAmelCase_ ) >= jaccard_threshold:
            elementa["copies"] += 1
            break
      else:
         UpperCAmelCase      					=  1
         extremes.append(lowerCAmelCase_ )
   return extremes
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Optional[int]:
   global _shared_dataset
   UpperCAmelCase      					=  dataset
   UpperCAmelCase      					=  []
   UpperCAmelCase      					=  partial(_find_cluster_extremes_shared	,    jaccard_threshold=lowerCAmelCase_ )
   with mp.Pool() as pool:
      for extremes in tqdm(
          pool.imap_unordered(
              lowerCAmelCase_	,    lowerCAmelCase_	,    )	,    total=len(lowerCAmelCase_ )	,    ):
         extremes_list.append(lowerCAmelCase_ )
   return extremes_list







def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ = 0.85 )    ->Tuple[Type[Dataset], List[List[Dict]]]:
   UpperCAmelCase      					=  make_duplicate_clusters(lowerCAmelCase_	,    lowerCAmelCase_ )
   UpperCAmelCase      					=  {x["""base_index"""] for cluster in duplicate_clusters for x in cluster}
   UpperCAmelCase      					=  {}
   UpperCAmelCase      					=  find_extremes(lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )
   for extremes in extremes_clusters:
      for element in extremes:
         UpperCAmelCase      					=  element
   UpperCAmelCase      					=  duplicate_indices - set(extreme_dict.keys() )
   UpperCAmelCase      					=  dataset.filter(lambda lowerCAmelCase_	,    lowerCAmelCase_ : idx not in remove_indices	,    with_indices=lowerCAmelCase_ )

   # update duplicate_clusters
   for cluster in duplicate_clusters:
      for element in cluster:
         UpperCAmelCase      					=  element["""base_index"""] in extreme_dict
         if element["is_extreme"]:
            UpperCAmelCase      					=  extreme_dict[element["""base_index"""]]["""copies"""]

   print(F"""Original dataset size: {len(lowerCAmelCase_ )}""" )
   print(F"""Number of duplicate clusters: {len(lowerCAmelCase_ )}""" )
   print(F"""Files in duplicate cluster: {len(lowerCAmelCase_ )}""" )
   print(F"""Unique files in duplicate cluster: {len(lowerCAmelCase_ )}""" )
   print(F"""Filtered dataset size: {len(lowerCAmelCase_ )}""" )

   return ds_filter, duplicate_clusters



