


import math
from typing import Optional

import torch
import torch.utils.checkpoint as checkpoint
from torch import nn

from ....modeling_utils import PreTrainedModel
from ....utils import add_start_docstrings, logging
from ...bert.modeling_bert import BertModel
from .configuration_retribert import RetriBertConfig


snake_case_  :     Any							  =							logging.get_logger(__name__)

snake_case_  :     Optional[int]							  =							[
    '''yjernite/retribert-base-uncased''',
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]

class   A__							(						UpperCamelCase__					):
      UpperCAmelCase     =  RetriBertConfig
      UpperCAmelCase     =  None
      UpperCAmelCase     =  "retribert"




      def 							__UpperCamelCase			(    self   : Dict			,      _a   : Dict					)							->       int:


          """simple docstring"""





          if isinstance(_a			,      nn.Linear					):
              module.weight.data.normal_(mean=0.0			,      std=self.config.initializer_range					)
              if module.bias is not None:
                  module.bias.data.zero_()
          elif isinstance(_a			,      nn.Embedding					):
              module.weight.data.normal_(mean=0.0			,      std=self.config.initializer_range					)
              if module.padding_idx is not None:
                  module.weight.data[module.padding_idx].zero_()
          elif isinstance(_a			,      nn.LayerNorm					):
              module.bias.data.zero_()
              module.weight.data.fill_(1.0					)
snake_case_  :     Any							  =							R'''

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

@add_start_docstrings(
    "Bert Based model to embed queries or document for document retrieval."				,       UpperCamelCase__				,       )
class   A__							(						UpperCamelCase__					):




      def __init__(    self   : Optional[int]			,      _a   : RetriBertConfig					)							->       None:


          """simple docstring"""





          super().__init__(_a					)
          _SCREAMING_SNAKE_CASE     					=config.projection_dim

          _SCREAMING_SNAKE_CASE     					=BertModel(_a					)
          _SCREAMING_SNAKE_CASE     					=None if config.share_encoders else BertModel(_a					)
          _SCREAMING_SNAKE_CASE     					=nn.Dropout(config.hidden_dropout_prob					)
          _SCREAMING_SNAKE_CASE     					=nn.Linear(config.hidden_size			,      config.projection_dim			,      bias=_a					)
          _SCREAMING_SNAKE_CASE     					=nn.Linear(config.hidden_size			,      config.projection_dim			,      bias=_a					)

          _SCREAMING_SNAKE_CASE     					=nn.CrossEntropyLoss(reduction='''mean'''					)

          # Initialize weights and apply final processing
          self.post_init()




      def 							__UpperCamelCase			(    self   : Union[str, Any]			,      _a   : Optional[Any]			,      _a   : List[str]			,      _a   : Dict			,      _a   : Optional[Any]=-1			,      )							->       int:


          """simple docstring"""





          if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
              return sent_encoder(_a			,      attention_mask=_a					)[1]
          else:
              # prepare implicit variables
              _SCREAMING_SNAKE_CASE     					=input_ids.device
              _SCREAMING_SNAKE_CASE     					=input_ids.size()
              _SCREAMING_SNAKE_CASE     					=torch.zeros(_a			,      dtype=torch.long			,      device=_a					)
              _SCREAMING_SNAKE_CASE     					=[None] * sent_encoder.config.num_hidden_layers
              _SCREAMING_SNAKE_CASE     					=sent_encoder.get_extended_attention_mask(
                  _a			,      _a					)

              # define function for checkpointing
              def partial_encode(*_a   : List[str]					):
                  _SCREAMING_SNAKE_CASE     					=sent_encoder.encoder(
                      inputs[0]			,      attention_mask=inputs[1]			,      head_mask=_a			,      )
                  _SCREAMING_SNAKE_CASE     					=encoder_outputs[0]
                  _SCREAMING_SNAKE_CASE     					=sent_encoder.pooler(_a					)
                  return pooled_output

              # run embedding layer on everything at once
              _SCREAMING_SNAKE_CASE     					=sent_encoder.embeddings(
                  input_ids=_a			,      position_ids=_a			,      token_type_ids=_a			,      inputs_embeds=_a					)
              # run encoding and pooling on one mini-batch at a time
              _SCREAMING_SNAKE_CASE     					=[]
              for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size					)					):
                  _SCREAMING_SNAKE_CASE     					=embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
                  _SCREAMING_SNAKE_CASE     					=extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
                  _SCREAMING_SNAKE_CASE     					=checkpoint.checkpoint(_a			,      _a			,      _a					)
                  pooled_output_list.append(_a					)
              return torch.cat(_a			,      dim=0					)




      def 							__UpperCamelCase			(    self   : Optional[Any]			,      _a   : str			,      _a   : Tuple=None			,      _a   : Any=-1			,      )							->       Any:


          """simple docstring"""





          _SCREAMING_SNAKE_CASE     					=self.embed_sentences_checkpointed(
              _a			,      _a			,      self.bert_query			,      _a			,      )
          return self.project_query(_a					)




      def 							__UpperCamelCase			(    self   : int			,      _a   : Optional[Any]			,      _a   : int=None			,      _a   : int=-1			,      )							->       Any:


          """simple docstring"""





          _SCREAMING_SNAKE_CASE     					=self.embed_sentences_checkpointed(
              _a			,      _a			,      self.bert_query if self.bert_doc is None else self.bert_doc			,      _a			,      )
          return self.project_doc(_a					)




      def 							__UpperCamelCase			(    self   : Optional[Any]			,      _a   : torch.LongTensor			,      _a   : Optional[torch.FloatTensor]			,      _a   : torch.LongTensor			,      _a   : Optional[torch.FloatTensor]			,      _a   : int = -1			,      )							->       torch.FloatTensor:


          """simple docstring"""





          _SCREAMING_SNAKE_CASE     					=input_ids_query.device
          _SCREAMING_SNAKE_CASE     					=self.embed_questions(_a			,      _a			,      _a					)
          _SCREAMING_SNAKE_CASE     					=self.embed_answers(_a			,      _a			,      _a					)
          _SCREAMING_SNAKE_CASE     					=torch.mm(_a			,      a_reps.t()					)
          _SCREAMING_SNAKE_CASE     					=self.ce_loss(_a			,      torch.arange(compare_scores.shape[1]					).to(_a					)					)
          _SCREAMING_SNAKE_CASE     					=self.ce_loss(compare_scores.t()			,      torch.arange(compare_scores.shape[0]					).to(_a					)					)
          _SCREAMING_SNAKE_CASE     					=(loss_qa + loss_aq) / 2
          return loss



import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel







def   lowerCamelCase(				a__		,a__		,a__):
				_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=pt_weights[f"{prefix}.in_proj_weight"].chunk(3		,dim=0)
				_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=pt_weights[f"{prefix}.in_proj_bias"].chunk(3		,dim=0)

				_SCREAMING_SNAKE_CASE     					=pt_weights[f"{prefix}.out_proj.weight"]
				_SCREAMING_SNAKE_CASE     					=pt_weights[f"{prefix}.out_proj.bias"]

				_SCREAMING_SNAKE_CASE     					=q_proj
				_SCREAMING_SNAKE_CASE     					=q_proj_bias

				_SCREAMING_SNAKE_CASE     					=k_proj
				_SCREAMING_SNAKE_CASE     					=k_proj_bias

				_SCREAMING_SNAKE_CASE     					=v_proj
				_SCREAMING_SNAKE_CASE     					=v_proj_bias

				_SCREAMING_SNAKE_CASE     					=out_proj_weights
				_SCREAMING_SNAKE_CASE     					=out_proj_bias







def   lowerCamelCase(				a__		,a__		,a__):
				copy_linear(hf_mlp.fca		,a__		,f"{prefix}.c_fc")
				copy_linear(hf_mlp.fca		,a__		,f"{prefix}.c_proj")







def   lowerCamelCase(				a__		,a__		,a__):
				_SCREAMING_SNAKE_CASE     					=pt_weights[f"{prefix}.weight"].data
				_SCREAMING_SNAKE_CASE     					=pt_weights[f"{prefix}.bias"].data







def   lowerCamelCase(				a__		,a__		,a__):
				# copy layer norms
				copy_linear(hf_layer.layer_norma		,a__		,f"{prefix}.ln_1")
				copy_linear(hf_layer.layer_norma		,a__		,f"{prefix}.ln_2")

				# copy MLP
				copy_mlp(hf_layer.mlp		,a__		,f"{prefix}.mlp")

				# copy attn
				copy_attn_layer(hf_layer.self_attn		,a__		,f"{prefix}.attn")







def   lowerCamelCase(				a__		,a__		,a__):
				for layer_id, hf_layer in enumerate(a__):
								copy_layer(a__		,a__		,f"{prefix}.{layer_id}")







def   lowerCamelCase(				a__		,a__):
				# copy projection
				_SCREAMING_SNAKE_CASE     					=pt_weights['''text_projection'''].data.T

				# copy text encoder
				for name, param in hf_model.text_model.named_parameters():
								_SCREAMING_SNAKE_CASE     					=pt_weights[f"bert.{name}"].data







def   lowerCamelCase(				a__		,a__):
				# copy projection
				_SCREAMING_SNAKE_CASE     					=pt_weights['''visual.proj'''].data.T

				# copy layer norms
				copy_linear(hf_model.vision_model.pre_layrnorm		,a__		,'''visual.ln_pre''')
				copy_linear(hf_model.vision_model.post_layernorm		,a__		,'''visual.ln_post''')

				# copy embeddings
				_SCREAMING_SNAKE_CASE     					=pt_weights['''visual.conv1.weight'''].data
				_SCREAMING_SNAKE_CASE     					=pt_weights['''visual.class_embedding'''].data
				_SCREAMING_SNAKE_CASE     					=pt_weights['''visual.positional_embedding'''].data

				# copy encoder
				copy_layers(hf_model.vision_model.encoder.layers		,a__		,'''visual.transformer.resblocks''')







@torch.no_grad()
def   lowerCamelCase(				a__		,a__		,a__=None):
				assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
				_SCREAMING_SNAKE_CASE     					=ChineseCLIPConfig.from_pretrained(a__)

				_SCREAMING_SNAKE_CASE     					=ChineseCLIPModel(a__).eval()

				_SCREAMING_SNAKE_CASE     					=torch.load(a__		,map_location='''cpu''')['''state_dict''']
				_SCREAMING_SNAKE_CASE     					={(name[7:] if name.startswith('''module.''') else name): value for name, value in pt_weights.items()}

				copy_text_model_and_projection(a__		,a__)
				copy_vision_model_and_projection(a__		,a__)
				_SCREAMING_SNAKE_CASE     					=pt_weights['''logit_scale'''].data

				hf_model.save_pretrained(a__)


if __name__ == "__main__":
							snake_case_  :     Tuple							  =							argparse.ArgumentParser()
							parser.add_argument(
							    '''--pytorch_dump_folder_path''',
							    default=None,
							    type=str,
							    help='''Path to the output folder storing converted hf PyTorch model.''',
							)
							parser.add_argument(
							    '''--checkpoint_path''', default=None, type=str, help='''Path to original github format ChineseCLIP checkpoint.'''
							)
							parser.add_argument(
							    '''--config_path''', default=None, required=True, type=str, help='''Path to hf config.json of model to convert.'''
							)
							snake_case_  :     List[str]							  =							parser.parse_args()

							convert_chinese_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
							print('''The conversion is finished!''')