



'''simple docstring'''





from dataclasses import dataclass
from typing import Any, Dict, Optional

import torch
import torch.nn.functional as F
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..models.embeddings import ImagePositionalEmbeddings
from ..utils import BaseOutput, deprecate
from .attention import BasicTransformerBlock
from .embeddings import PatchEmbed
from .modeling_utils import ModelMixin


@dataclass
class 							_lowerCAmelCase	(  _a							):


 """simple docstring"""

 lowerCamelCase									=     42


class 							_lowerCAmelCase	(  _a,							_a							):


 """simple docstring"""

 @register_to_config
 def __init__(      self					,    _lowerCamelCase = 16					,    _lowerCamelCase = 88					,    _lowerCamelCase = None					,    _lowerCamelCase = None					,    _lowerCamelCase = 1					,    _lowerCamelCase = 0.0					,    _lowerCamelCase = 32					,    _lowerCamelCase = None					,    _lowerCamelCase = False					,    _lowerCamelCase = None					,    _lowerCamelCase = None					,    _lowerCamelCase = None					,    _lowerCamelCase = "geglu"					,    _lowerCamelCase = None					,    _lowerCamelCase = False					,    _lowerCamelCase = False					,    _lowerCamelCase = False					,    _lowerCamelCase = "layer_norm"					,    _lowerCamelCase = True					,    )    ->    Any:
    super().__init__()
    A_  :		List[str]						=					use_linear_projection
    A_  :		Tuple						=					num_attention_heads
    A_  :		Union[str, Any]						=					attention_head_dim
    A_  :		Tuple						=					num_attention_heads * attention_head_dim

    # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
    # Define whether input is continuous or discrete depending on configuration
    A_  :		int						=					(in_channels is not None) and (patch_size is None)
    A_  :		Optional[int]						=					num_vector_embeds is not None
    A_  :		Any						=					in_channels is not None and patch_size is not None

    if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
       A_  :		List[Any]						=					(
           F"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
           """ incorrectly set to `\'layer_norm\'`.Make sure to set `norm_type` to `\'ada_norm\'` in the config."""
           """ Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"""
           """ results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"""
           """ would be very nice if you could open a Pull request for the `transformer/config.json` file"""
       )
       deprecate("""norm_type!=num_embeds_ada_norm"""					,    """1.0.0"""					,    lowerCAmelCase__					,    standard_warn=lowerCAmelCase__  )
       A_  :		int						=					"""ada_norm"""

    if self.is_input_continuous and self.is_input_vectorized:
       raise ValueError(
           F"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
           """ sure that either `in_channels` or `num_vector_embeds` is None."""  )
    elif self.is_input_vectorized and self.is_input_patches:
       raise ValueError(
           F"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
           """ sure that either `num_vector_embeds` or `num_patches` is None."""  )
    elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
       raise ValueError(
           F"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
           F" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."  )

    # 2. Define input layers
    if self.is_input_continuous:
       A_  :		List[str]						=					in_channels

       A_  :		Optional[int]						=					torch.nn.GroupNorm(num_groups=lowerCAmelCase__					,    num_channels=lowerCAmelCase__					,    eps=1e-6					,    affine=lowerCAmelCase__  )
       if use_linear_projection:
          A_  :		Optional[int]						=					nn.Linear(lowerCAmelCase__					,    lowerCAmelCase__  )
       else:
          A_  :		Dict						=					nn.Convad(lowerCAmelCase__					,    lowerCAmelCase__					,    kernel_size=1					,    stride=1					,    padding=0  )
    elif self.is_input_vectorized:
       assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
       assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"

       A_  :		Any						=					sample_size
       A_  :		str						=					sample_size
       A_  :		Any						=					num_vector_embeds
       A_  :		Union[str, Any]						=					self.height * self.width

       A_  :		Dict						=					ImagePositionalEmbeddings(
           num_embed=lowerCAmelCase__					,    embed_dim=lowerCAmelCase__					,    height=self.height					,    width=self.width  )
    elif self.is_input_patches:
       assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"

       A_  :		Optional[int]						=					sample_size
       A_  :		Optional[Any]						=					sample_size

       A_  :		Tuple						=					patch_size
       A_  :		Any						=					PatchEmbed(
           height=lowerCAmelCase__					,    width=lowerCAmelCase__					,    patch_size=lowerCAmelCase__					,    in_channels=lowerCAmelCase__					,    embed_dim=lowerCAmelCase__					,    )

    # 3. Define transformers blocks
    A_  :		List[Any]						=					nn.ModuleList(
        [
            BasicTransformerBlock(
                lowerCAmelCase__					,    lowerCAmelCase__					,    lowerCAmelCase__					,    dropout=lowerCAmelCase__					,    cross_attention_dim=lowerCAmelCase__					,    activation_fn=lowerCAmelCase__					,    num_embeds_ada_norm=lowerCAmelCase__					,    attention_bias=lowerCAmelCase__					,    only_cross_attention=lowerCAmelCase__					,    upcast_attention=lowerCAmelCase__					,    norm_type=lowerCAmelCase__					,    norm_elementwise_affine=lowerCAmelCase__					,    )
            for d in range(lowerCAmelCase__  )
        ]  )

    # 4. Define output layers
    A_  :		Union[str, Any]						=					in_channels if out_channels is None else out_channels
    if self.is_input_continuous:
       # TODO: should use out_channels for continuous projections
       if use_linear_projection:
          A_  :		Union[str, Any]						=					nn.Linear(lowerCAmelCase__					,    lowerCAmelCase__  )
       else:
          A_  :		Union[str, Any]						=					nn.Convad(lowerCAmelCase__					,    lowerCAmelCase__					,    kernel_size=1					,    stride=1					,    padding=0  )
    elif self.is_input_vectorized:
       A_  :		List[Any]						=					nn.LayerNorm(lowerCAmelCase__  )
       A_  :		List[Any]						=					nn.Linear(lowerCAmelCase__					,    self.num_vector_embeds - 1  )
    elif self.is_input_patches:
       A_  :		Union[str, Any]						=					nn.LayerNorm(lowerCAmelCase__					,    elementwise_affine=lowerCAmelCase__					,    eps=1e-6  )
       A_  :		Optional[Any]						=					nn.Linear(lowerCAmelCase__					,    2 * inner_dim  )
       A_  :		Optional[int]						=					nn.Linear(lowerCAmelCase__					,    patch_size * patch_size * self.out_channels  )







 def       UpperCAmelCase_       (      self					,    _lowerCamelCase					,    _lowerCamelCase = None					,    _lowerCamelCase = None					,    _lowerCamelCase = None					,    _lowerCamelCase = None					,    _lowerCamelCase = None					,    _lowerCamelCase = None					,    _lowerCamelCase = True					,    )    ->    Optional[int]:
    # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
    #   we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
    #   we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
    # expects mask of shape:
    #   [batch, key_tokens]
    # adds singleton query_tokens dimension:
    #   [batch,                    1, key_tokens]
    # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
    #   [batch,  heads, query_tokens, key_tokens] (e.g. torch sdp attn)
    #   [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
    if attention_mask is not None and attention_mask.ndim == 2:
       # assume that mask is expressed as:
       #   (1 = keep,      0 = discard)
       # convert mask into a bias that can be added to attention scores:
       #       (keep = +0,     discard = -10000.0)
       A_  :		int						=					(1 - attention_mask.to(hidden_states.dtype  )) * -1_0000.0
       A_  :		List[str]						=					attention_mask.unsqueeze(1  )

    # convert encoder_attention_mask to a bias the same way we do for attention_mask
    if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
       A_  :		Union[str, Any]						=					(1 - encoder_attention_mask.to(hidden_states.dtype  )) * -1_0000.0
       A_  :		Optional[Any]						=					encoder_attention_mask.unsqueeze(1  )

    # 1. Input
    if self.is_input_continuous:
       A_						,  A_						,  A_						,  A_  :		Dict						=					hidden_states.shape
       A_  :		Optional[int]						=					hidden_states

       A_  :		Tuple						=					self.norm(lowerCAmelCase__  )
       if not self.use_linear_projection:
          A_  :		Optional[int]						=					self.proj_in(lowerCAmelCase__  )
          A_  :		Optional[int]						=					hidden_states.shape[1]
          A_  :		int						=					hidden_states.permute(0					,    2					,    3					,    1  ).reshape(lowerCAmelCase__					,    height * width					,    lowerCAmelCase__  )
       else:
          A_  :		List[Any]						=					hidden_states.shape[1]
          A_  :		Dict						=					hidden_states.permute(0					,    2					,    3					,    1  ).reshape(lowerCAmelCase__					,    height * width					,    lowerCAmelCase__  )
          A_  :		Optional[Any]						=					self.proj_in(lowerCAmelCase__  )
    elif self.is_input_vectorized:
       A_  :		Tuple						=					self.latent_image_embedding(lowerCAmelCase__  )
    elif self.is_input_patches:
       A_  :		str						=					self.pos_embed(lowerCAmelCase__  )

    # 2. Blocks
    for block in self.transformer_blocks:
       A_  :		Optional[int]						=					block(
           lowerCAmelCase__					,    attention_mask=lowerCAmelCase__					,    encoder_hidden_states=lowerCAmelCase__					,    encoder_attention_mask=lowerCAmelCase__					,    timestep=lowerCAmelCase__					,    cross_attention_kwargs=lowerCAmelCase__					,    class_labels=lowerCAmelCase__					,    )

    # 3. Output
    if self.is_input_continuous:
       if not self.use_linear_projection:
          A_  :		int						=					hidden_states.reshape(lowerCAmelCase__					,    lowerCAmelCase__					,    lowerCAmelCase__					,    lowerCAmelCase__  ).permute(0					,    3					,    1					,    2  ).contiguous()
          A_  :		Optional[int]						=					self.proj_out(lowerCAmelCase__  )
       else:
          A_  :		str						=					self.proj_out(lowerCAmelCase__  )
          A_  :		str						=					hidden_states.reshape(lowerCAmelCase__					,    lowerCAmelCase__					,    lowerCAmelCase__					,    lowerCAmelCase__  ).permute(0					,    3					,    1					,    2  ).contiguous()

       A_  :		Tuple						=					hidden_states + residual
    elif self.is_input_vectorized:
       A_  :		str						=					self.norm_out(lowerCAmelCase__  )
       A_  :		Any						=					self.out(lowerCAmelCase__  )
       # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
       A_  :		List[Any]						=					logits.permute(0					,    2					,    1  )

       # log(p(x_0))
       A_  :		List[Any]						=					F.log_softmax(logits.double()					,    dim=1  ).float()
    elif self.is_input_patches:
       # TODO: cleanup!
       A_  :		Optional[Any]						=					self.transformer_blocks[0].norma.emb(
           lowerCAmelCase__					,    lowerCAmelCase__					,    hidden_dtype=hidden_states.dtype  )
       A_						,  A_  :		Any						=					self.proj_out_a(F.silu(lowerCAmelCase__  )  ).chunk(2					,    dim=1  )
       A_  :		Optional[int]						=					self.norm_out(lowerCAmelCase__  ) * (1 + scale[:, None]) + shift[:, None]
       A_  :		Tuple						=					self.proj_out_a(lowerCAmelCase__  )

       # unpatchify
       A_  :		str						=					int(hidden_states.shape[1] ** 0.5  )
       A_  :		Optional[int]						=					hidden_states.reshape(
           shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)  )
       A_  :		int						=					torch.einsum("""nhwpqc->nchpwq"""					,    lowerCAmelCase__  )
       A_  :		int						=					hidden_states.reshape(
           shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)  )

    if not return_dict:
       return (output,)

    return TransformeraDModelOutput(sample=lowerCAmelCase__  )

import argparse
import collections
from pathlib import Path

import torch
from torch.serialization import default_restore_location

from transformers import BertConfig, DPRConfig, DPRContextEncoder, DPRQuestionEncoder, DPRReader


UpperCAmelCase_    		=				collections.namedtuple(
    '''CheckpointState''', ['''model_dict''', '''optimizer_dict''', '''scheduler_dict''', '''offset''', '''epoch''', '''encoder_params''']
)

def 				UpperCamelCase					(     lowerCAmelCase_ )		->    CheckpointState:




       '''simple docstring'''






       print(F"Reading saved model from {model_file}" )
       _A=						torch.load(lowerCAmelCase_							,       map_location=lambda lowerCAmelCase_							,       lowerCAmelCase_ : default_restore_location(lowerCAmelCase_							,       'cpu' ) )
       return CheckpointState(**lowerCAmelCase_ )





class   lowerCAmelCase    :



     def __init__(       self					,   lowerCAmelCase__							):
            _A=						src_file



     def       a__	(       self							):
            raise NotImplementedError





     @staticmethod
     def       a__	(       lowerCAmelCase__					,   *lowerCAmelCase__					,   **lowerCAmelCase__							):
            if comp_type.startswith('c'							):
                   return DPRContextEncoderState(*lowerCAmelCase__					,   **lowerCAmelCase__							)
            if comp_type.startswith('q'							):
                   return DPRQuestionEncoderState(*lowerCAmelCase__					,   **lowerCAmelCase__							)
            if comp_type.startswith('r'							):
                   return DPRReaderState(*lowerCAmelCase__					,   **lowerCAmelCase__							)
            else:
                   raise ValueError('Component type must be either \'ctx_encoder\', \'question_encoder\' or \'reader\'.'							)





class   lowerCAmelCase    (       _a      ):



     def       a__	(       self							):
            _A=						DPRContextEncoder(DPRConfig(**BertConfig.get_config_dict('bert-base-uncased'							)[0]							)							)
            print(f"Loading DPR biencoder from {self.src_file}"							)
            _A=						load_states_from_checkpoint(self.src_file							)
            _A,      _A=						model.ctx_encoder, 'ctx_model.'
            # Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
            _A=						{'bert_model.embeddings.position_ids': model.ctx_encoder.bert_model.embeddings.position_ids}
            for key, value in saved_state.model_dict.items():
                   if key.startswith(lowerCAmelCase__							):
                          _A=						key[len(lowerCAmelCase__							) :]
                          if not key.startswith('encode_proj.'							):
                                 _A=						'bert_model.' + key
                          _A=						value
            encoder.load_state_dict(lowerCAmelCase__							)
            return model





class   lowerCAmelCase    (       _a      ):



     def       a__	(       self							):
            _A=						DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict('bert-base-uncased'							)[0]							)							)
            print(f"Loading DPR biencoder from {self.src_file}"							)
            _A=						load_states_from_checkpoint(self.src_file							)
            _A,      _A=						model.question_encoder, 'question_model.'
            # Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
            _A=						{'bert_model.embeddings.position_ids': model.question_encoder.bert_model.embeddings.position_ids}
            for key, value in saved_state.model_dict.items():
                   if key.startswith(lowerCAmelCase__							):
                          _A=						key[len(lowerCAmelCase__							) :]
                          if not key.startswith('encode_proj.'							):
                                 _A=						'bert_model.' + key
                          _A=						value
            encoder.load_state_dict(lowerCAmelCase__							)
            return model





class   lowerCAmelCase    (       _a      ):



     def       a__	(       self							):
            _A=						DPRReader(DPRConfig(**BertConfig.get_config_dict('bert-base-uncased'							)[0]							)							)
            print(f"Loading DPR reader from {self.src_file}"							)
            _A=						load_states_from_checkpoint(self.src_file							)
            # Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
            _A=						{
                'encoder.bert_model.embeddings.position_ids': model.span_predictor.encoder.bert_model.embeddings.position_ids
            }
            for key, value in saved_state.model_dict.items():
                   if key.startswith('encoder.'							) and not key.startswith('encoder.encode_proj'							):
                          _A=						'encoder.bert_model.' + key[len('encoder.'							) :]
                   _A=						value
            model.span_predictor.load_state_dict(lowerCAmelCase__							)
            return model


def 				UpperCamelCase					(     lowerCAmelCase_							,       lowerCAmelCase_							,       lowerCAmelCase_ )		->    Tuple:




       '''simple docstring'''






       _A=						Path(lowerCAmelCase_ )
       dest_dir.mkdir(exist_ok=lowerCAmelCase_ )

       _A=						DPRState.from_type(lowerCAmelCase_							,       src_file=lowerCAmelCase_ )
       _A=						dpr_state.load_dpr_model()
       model.save_pretrained(lowerCAmelCase_ )
       model.from_pretrained(lowerCAmelCase_ )  # sanity check


if __name__ == "__main__":
      UpperCAmelCase_    		=				argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          '''--type''', type=str, help='''Type of the component to convert: \'ctx_encoder\', \'question_encoder\' or \'reader\'.'''
      )
      parser.add_argument(
          '''--src''',
          type=str,
          help=(
              '''Path to the dpr checkpoint file. They can be downloaded from the official DPR repo'''
              ''' https://github.com/facebookresearch/DPR. Note that in the official repo, both encoders are stored in the'''
              ''' \'retriever\' checkpoints.'''
          ),
      )
      parser.add_argument('''--dest''', type=str, default=None, help='''Path to the output PyTorch model directory.''')
      UpperCAmelCase_    		=				parser.parse_args()

      UpperCAmelCase_    		=				Path(args.src)
      UpperCAmelCase_    		=				F"converted-{src_file.name}" if args.dest is None else args.dest
      UpperCAmelCase_    		=				Path(dest_dir)
      assert src_file.exists()
      assert (
          args.type is not None
      ), "Please specify the component type of the DPR model to convert: 'ctx_encoder', 'question_encoder' or 'reader'."
      convert(args.type, src_file, dest_dir)