
import logging

import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEncoder,
    BertModel,
    BertPreTrainedModel,
)


lowercase__       =logging.getLogger(__name__)



class 		UpperCamelCase__  (       snake_case__    ):
   def       lowerCAmelCase			(self :					Optional[int]					,				snake_case_ :					List[Any]					,				snake_case_ :					Union[str, Any]					,				snake_case_ :					str=None					,				snake_case_ :					Dict=None   ):
    __a :  Optional[int]						=  self.layer[current_layer](snake_case_					,				snake_case_					,				head_mask[current_layer]   )

    __a :  Any						=  layer_outputs[0]

    return hidden_states





@add_start_docstrings(
    "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top."    ,snake_case__    ,)
class 		UpperCamelCase__  (       snake_case__    ):
   def __init__(self :					Union[str, Any]					,				snake_case_ :					Optional[Any]   ):
    super().__init__(snake_case_   )

    __a :  Any						=  BertEncoderWithPabee(snake_case_   )

    self.init_weights()
    __a :  Tuple						=  0
    __a :  List[Any]						=  0
    __a :  str						=  0

    __a :  Union[str, Any]						=  0
   def       lowerCAmelCase			(self :					Tuple					,				snake_case_ :					Any   ):
    __a :  int						=  threshold
   def       lowerCAmelCase			(self :					Union[str, Any]					,				snake_case_ :					Dict   ):
    __a :  Any						=  patience
   def       lowerCAmelCase			(self :					Union[str, Any]   ):
    __a :  Tuple						=  0
    __a :  Union[str, Any]						=  0
   def       lowerCAmelCase			(self :					int   ):
    __a :  List[str]						=  self.inference_layers_num / self.inference_instances_num
    __a :  Tuple						=  (
        f"*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ="
        f" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***"
    )
    print(snake_case_   )







   @add_start_docstrings_to_model_forward(snake_case_   )
   def       lowerCAmelCase			(self :					Optional[int]					,				snake_case_ :					Optional[Any]=None					,				snake_case_ :					List[str]=None					,				snake_case_ :					Union[str, Any]=None					,				snake_case_ :					List[Any]=None					,				snake_case_ :					Any=None					,				snake_case_ :					Tuple=None					,				snake_case_ :					Dict=None					,				snake_case_ :					Tuple=None					,				snake_case_ :					List[str]=None					,				snake_case_ :					List[str]=None					,				snake_case_ :					List[str]=False					,				):







    if input_ids is not None and inputs_embeds is not None:
     raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time'''   )
    elif input_ids is not None:
     __a :  List[str]						=  input_ids.size()
    elif inputs_embeds is not None:
     __a :  List[Any]						=  inputs_embeds.size()[:-1]
    else:
     raise ValueError('''You have to specify either input_ids or inputs_embeds'''   )

    __a :  Optional[Any]						=  input_ids.device if input_ids is not None else inputs_embeds.device

    if attention_mask is None:
     __a :  Tuple						=  torch.ones(snake_case_					,				device=snake_case_   )
    if token_type_ids is None:
     __a :  Optional[int]						=  torch.zeros(snake_case_					,				dtype=torch.long					,				device=snake_case_   )

    # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
    # ourselves in which case we just need to make it broadcastable to all heads.
    __a :  str						=  self.get_extended_attention_mask(snake_case_					,				snake_case_					,				snake_case_   )

    # If a 2D ou 3D attention mask is provided for the cross-attention
    # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
    if self.config.is_decoder and encoder_hidden_states is not None:
     __a				,       __a				,       __a :  str						=  encoder_hidden_states.size()
     __a :  Optional[Any]						=  (encoder_batch_size, encoder_sequence_length)
     if encoder_attention_mask is None:
      __a :  List[Any]						=  torch.ones(snake_case_					,				device=snake_case_   )
     __a :  List[Any]						=  self.invert_attention_mask(snake_case_   )
    else:
     __a :  int						=  None

    # Prepare head mask if needed
    # 1.0 in head_mask indicate we keep the head
    # attention_probs has shape bsz x n_heads x N x N
    # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
    # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
    __a :  Tuple						=  self.get_head_mask(snake_case_					,				self.config.num_hidden_layers   )

    __a :  Union[str, Any]						=  self.embeddings(
        input_ids=snake_case_					,				position_ids=snake_case_					,				token_type_ids=snake_case_					,				inputs_embeds=snake_case_   )
    __a :  Dict						=  embedding_output

    if self.training:
     __a :  List[str]						=  []
     for i in range(self.config.num_hidden_layers   ):
      __a :  int						=  self.encoder.adaptive_forward(
          snake_case_					,				current_layer=snake_case_					,				attention_mask=snake_case_					,				head_mask=snake_case_   )

      __a :  List[str]						=  self.pooler(snake_case_   )
      __a :  Union[str, Any]						=  output_layers[i](output_dropout(snake_case_   )   )
      res.append(snake_case_   )
    elif self.patience == 0:  # Use all layers for inference
     __a :  Union[str, Any]						=  self.encoder(
         snake_case_					,				attention_mask=snake_case_					,				head_mask=snake_case_					,				encoder_hidden_states=snake_case_					,				encoder_attention_mask=snake_case_					,				)
     __a :  Optional[Any]						=  self.pooler(encoder_outputs[0]   )
     __a :  str						=  [output_layers[self.config.num_hidden_layers - 1](snake_case_   )]
    else:
     __a :  Dict						=  0
     __a :  Tuple						=  None
     __a :  Any						=  0
     for i in range(self.config.num_hidden_layers   ):
      calculated_layer_num += 1
      __a :  Union[str, Any]						=  self.encoder.adaptive_forward(
          snake_case_					,				current_layer=snake_case_					,				attention_mask=snake_case_					,				head_mask=snake_case_   )

      __a :  Union[str, Any]						=  self.pooler(snake_case_   )
      __a :  Tuple						=  output_layers[i](snake_case_   )
      if regression:
       __a :  int						=  logits.detach()
       if patient_result is not None:
        __a :  List[str]						=  patient_result.detach()
       if (patient_result is not None) and torch.abs(patient_result - labels   ) < self.regression_threshold:
        patient_counter += 1
       else:
        __a :  List[Any]						=  0
      else:
       __a :  List[str]						=  logits.detach().argmax(dim=1   )
       if patient_result is not None:
        __a :  Optional[int]						=  patient_result.detach().argmax(dim=1   )
       if (patient_result is not None) and torch.all(labels.eq(snake_case_   )   ):
        patient_counter += 1
       else:
        __a :  str						=  0

      __a :  List[Any]						=  logits
      if patient_counter == self.patience:
       break
     __a :  List[str]						=  [patient_result]
     self.inference_layers_num += calculated_layer_num
     self.inference_instances_num += 1

    return res





@add_start_docstrings(
    "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n    the pooled output) e.g. for GLUE tasks. "    ,snake_case__    ,)
class 		UpperCamelCase__  (       snake_case__    ):
   def __init__(self :					Union[str, Any]					,				snake_case_ :					Optional[Any]   ):
    super().__init__(snake_case_   )
    __a :  Any						=  config.num_labels

    __a :  List[Any]						=  BertModelWithPabee(snake_case_   )
    __a :  Dict						=  nn.Dropout(config.hidden_dropout_prob   )
    __a :  str						=  nn.ModuleList(
        [nn.Linear(config.hidden_size					,				self.config.num_labels   ) for _ in range(config.num_hidden_layers   )]   )

    self.init_weights()







   @add_start_docstrings_to_model_forward(snake_case_   )
   def       lowerCAmelCase			(self :					Tuple					,				snake_case_ :					Any=None					,				snake_case_ :					Optional[Any]=None					,				snake_case_ :					int=None					,				snake_case_ :					Optional[int]=None					,				snake_case_ :					str=None					,				snake_case_ :					List[Any]=None					,				snake_case_ :					Any=None					,				):
    __a :  Optional[Any]						=  self.bert(
        input_ids=snake_case_					,				attention_mask=snake_case_					,				token_type_ids=snake_case_					,				position_ids=snake_case_					,				head_mask=snake_case_					,				inputs_embeds=snake_case_					,				output_dropout=self.dropout					,				output_layers=self.classifiers					,				regression=self.num_labels == 1					,				)

    __a :  Any						=  (logits[-1],)

    if labels is not None:
     __a :  Optional[Any]						=  None
     __a :  Tuple						=  0
     for ix, logits_item in enumerate(snake_case_   ):
      if self.num_labels == 1:
       #  We are doing regression
       __a :  Dict						=  MSELoss()
       __a :  Union[str, Any]						=  loss_fct(logits_item.view(-1   )					,				labels.view(-1   )   )
      else:
       __a :  Any						=  CrossEntropyLoss()
       __a :  List[Any]						=  loss_fct(logits_item.view(-1					,				self.num_labels   )					,				labels.view(-1   )   )
      if total_loss is None:
       __a :  Optional[Any]						=  loss
      else:
       total_loss += loss * (ix + 1)
      total_weights += ix + 1
     __a :  str						=  (total_loss / total_weights,) + outputs

    return outputs








import argparse
import json
from pathlib import Path

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

from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging


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


def __A    (      __lowerCAmelCase ,		__lowerCAmelCase=False	)->  Union[str, Any]:





						"""simple docstring"""



						_UpperCAmelCase									=			[]
						for i in range(config.num_hidden_layers	):
												# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
												rename_keys.append((F"""blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""")	)
												rename_keys.append((F"""blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""")	)
												rename_keys.append((F"""blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""")	)
												rename_keys.append((F"""blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""")	)
												rename_keys.append((F"""blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""")	)
												rename_keys.append((F"""blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""")	)
												rename_keys.append((F"""blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""")	)
												rename_keys.append((F"""blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""")	)
												rename_keys.append((F"""blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""")	)
												rename_keys.append((F"""blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""")	)

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

						if base_model:
												# layernorm + pooler
												rename_keys.extend(
												    [
												        ('norm.weight', 'layernorm.weight'),
												        ('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 __A    (      __lowerCAmelCase ,		__lowerCAmelCase ,		__lowerCAmelCase=False	)->  List[str]:





						"""simple docstring"""



						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"""blocks.{i}.attn.qkv.weight"""	)
												_UpperCAmelCase									=			state_dict.pop(F"""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 __A    (      __lowerCAmelCase	)->  Optional[Any]:





						"""simple docstring"""



						_UpperCAmelCase									=			['head.weight', 'head.bias']
						for k in ignore_keys:
												state_dict.pop(__lowerCAmelCase ,		__lowerCAmelCase	)


def __A    (      __lowerCAmelCase ,		__lowerCAmelCase ,		__lowerCAmelCase	)->  int:





						"""simple docstring"""



						_UpperCAmelCase									=			dct.pop(__lowerCAmelCase	)
						_UpperCAmelCase									=			val


def __A    (      )->  str:





						"""simple docstring"""



						_UpperCAmelCase									=			'http://images.cocodataset.org/val2017/000000039769.jpg'
						_UpperCAmelCase									=			Image.open(requests.get(__lowerCAmelCase ,		stream=__lowerCAmelCase	).raw	)
						return im


@torch.no_grad()
def __A    (      __lowerCAmelCase ,		__lowerCAmelCase ,		__lowerCAmelCase=True	)->  List[str]:





						"""simple docstring"""



						_UpperCAmelCase									=			ViTConfig()
						# patch_size
						if model_name[-1] == "8":
												_UpperCAmelCase									=			8
						# set labels if required
						if not base_model:
												_UpperCAmelCase									=			1_000
												_UpperCAmelCase									=			'huggingface/label-files'
												_UpperCAmelCase									=			'imagenet-1k-id2label.json'
												_UpperCAmelCase									=			json.load(open(hf_hub_download(__lowerCAmelCase ,		__lowerCAmelCase ,		repo_type='dataset'	) ,		'r'	)	)
												_UpperCAmelCase									=			{int(__lowerCAmelCase	): v for k, v in idalabel.items()}
												_UpperCAmelCase									=			idalabel
												_UpperCAmelCase									=			{v: k for k, v in idalabel.items()}
						# size of the architecture
						if model_name in ["dino_vits8", "dino_vits16"]:
												_UpperCAmelCase									=			384
												_UpperCAmelCase									=			1_536
												_UpperCAmelCase									=			12
												_UpperCAmelCase									=			6

						# load original model from torch hub
						_UpperCAmelCase									=			torch.hub.load('facebookresearch/dino:main' ,		__lowerCAmelCase	)
						original_model.eval()

						# load state_dict of original model, remove and rename some keys
						_UpperCAmelCase									=			original_model.state_dict()
						if base_model:
												remove_classification_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 ,		__lowerCAmelCase	)

						# load HuggingFace model
						if base_model:
												_UpperCAmelCase									=			ViTModel(__lowerCAmelCase ,		add_pooling_layer=__lowerCAmelCase	).eval()
						else:
												_UpperCAmelCase									=			ViTForImageClassification(__lowerCAmelCase	).eval()
						model.load_state_dict(__lowerCAmelCase	)

						# Check outputs on an image, prepared by ViTImageProcessor
						_UpperCAmelCase									=			ViTImageProcessor()
						_UpperCAmelCase									=			image_processor(images=prepare_img() ,		return_tensors='pt'	)
						_UpperCAmelCase									=			encoding['pixel_values']
						_UpperCAmelCase									=			model(__lowerCAmelCase	)

						if base_model:
												_UpperCAmelCase									=			original_model(__lowerCAmelCase	)
												assert torch.allclose(__lowerCAmelCase ,		outputs.last_hidden_state[:, 0, :] ,		atol=1E-1	)
						else:
												_UpperCAmelCase									=			original_model(__lowerCAmelCase	)
												assert logits.shape == outputs.logits.shape
												assert torch.allclose(__lowerCAmelCase ,		outputs.logits ,		atol=1E-3	)

						Path(__lowerCAmelCase	).mkdir(exist_ok=__lowerCAmelCase	)
						print(F"""Saving model {model_name} 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(
		    '''--model_name''',
		    default='''dino_vitb16''',
		    type=str,
		    help='''Name of the model trained with DINO you\'d like to convert.''',
		)
		parser.add_argument(
		    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
		)
		parser.add_argument(
		    '''--base_model''',
		    action='''store_true''',
		    help='''Whether to only convert the base model (no projection head weights).''',
		)

		parser.set_defaults(base_model=True)
		_a      	=  parser.parse_args()
		convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
