
from ...configuration_utils import PretrainedConfig
from ...utils import logging


_snake_case      :							Union[str, Any]     	=    logging.get_logger(__name__)

_snake_case      :							Optional[Any]     	=    {
    """s-JoL/Open-Llama-V1""": """https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json""",
}





class   UpperCamelCase_      (      UpperCAmelCase_		):







						'''simple docstring'''



						UpperCamelCase      :  int				   =					'open-llama'





						def __init__(			self							:Dict		,    lowerCAmelCase__							:List[Any]=100000		,    lowerCAmelCase__							:Union[str, Any]=4096		,    lowerCAmelCase__							:Optional[int]=11008		,    lowerCAmelCase__							:Optional[int]=32		,    lowerCAmelCase__							:Union[str, Any]=32		,    lowerCAmelCase__							:Union[str, Any]="silu"		,    lowerCAmelCase__							:Any=2048		,    lowerCAmelCase__							:Tuple=0.02		,    lowerCAmelCase__							:Optional[int]=1E-6		,    lowerCAmelCase__							:Tuple=True		,    lowerCAmelCase__							:Dict=0		,    lowerCAmelCase__							:List[Any]=1		,    lowerCAmelCase__							:str=2		,    lowerCAmelCase__							:Union[str, Any]=False		,    lowerCAmelCase__							:Dict=True		,    lowerCAmelCase__							:Any=0.1		,    lowerCAmelCase__							:int=0.1		,    lowerCAmelCase__							:Optional[Any]=True		,    lowerCAmelCase__							:Any=True		,    lowerCAmelCase__							:Union[str, Any]=None		,    **lowerCAmelCase__							:Dict		,    )  ->List[str]:
										lowercase         =      vocab_size
										lowercase         =      max_position_embeddings
										lowercase         =      hidden_size
										lowercase         =      intermediate_size
										lowercase         =      num_hidden_layers
										lowercase         =      num_attention_heads
										lowercase         =      hidden_act
										lowercase         =      initializer_range
										lowercase         =      rms_norm_eps
										lowercase         =      use_cache
										lowercase         =      kwargs.pop(
										    "use_memorry_efficient_attention"		,    SCREAMING_SNAKE_CASE_     )
										lowercase         =      hidden_dropout_prob
										lowercase         =      attention_dropout_prob
										lowercase         =      use_stable_embedding
										lowercase         =      shared_input_output_embedding
										lowercase         =      rope_scaling
										self._rope_scaling_validation()

										super().__init__(
										    pad_token_id=SCREAMING_SNAKE_CASE_		,    bos_token_id=SCREAMING_SNAKE_CASE_		,    eos_token_id=SCREAMING_SNAKE_CASE_		,    tie_word_embeddings=SCREAMING_SNAKE_CASE_		,    **SCREAMING_SNAKE_CASE_		,    )





						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->int:




										if self.rope_scaling is None:
														return

										if not isinstance(self.rope_scaling		,    SCREAMING_SNAKE_CASE_     ) or len(self.rope_scaling     ) != 2:
														raise ValueError(
														    "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
														    F'''got {self.rope_scaling}'''     )
										lowercase         =      self.rope_scaling.get("type"		,    SCREAMING_SNAKE_CASE_     )
										lowercase         =      self.rope_scaling.get("factor"		,    SCREAMING_SNAKE_CASE_     )
										if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
														raise ValueError(
														    F'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}'''     )
										if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_     ) or rope_scaling_factor <= 1.0:
														raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}'''     )


import argparse
import os

import torch

from transformers import FlavaConfig, FlavaForPreTraining
from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint

def 		UpperCamelCase						(   lowercase_ )		->						Union[str, Any]:


  '''simple docstring'''






  return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() )

def 		UpperCamelCase						(   lowercase_			,			lowercase_ )		->						List[Any]:


  '''simple docstring'''






  lowercase__	: int     		=   {}

  for key, value in state_dict.items():
    if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key:
      continue

    lowercase__	: Optional[Any]     		=   key.replace("""heads.cmd.mim_head.cls.predictions"""			,			"""mmm_image_head""" )
    lowercase__	: Optional[Any]     		=   key.replace("""heads.cmd.mlm_head.cls.predictions"""			,			"""mmm_text_head""" )
    lowercase__	: Optional[Any]     		=   key.replace("""heads.cmd.itm_head.cls"""			,			"""itm_head""" )
    lowercase__	: Tuple     		=   key.replace("""heads.cmd.itm_head.pooler"""			,			"""itm_head.pooler""" )
    lowercase__	: Optional[Any]     		=   key.replace("""heads.cmd.clip_head.logit_scale"""			,			"""flava.logit_scale""" )
    lowercase__	: Optional[int]     		=   key.replace("""heads.fairseq_mlm.cls.predictions"""			,			"""mlm_head""" )
    lowercase__	: List[Any]     		=   key.replace("""heads.imagenet.mim_head.cls.predictions"""			,			"""mim_head""" )
    lowercase__	: int     		=   key.replace("""mm_text_projection"""			,			"""flava.text_to_mm_projection""" )
    lowercase__	: Optional[Any]     		=   key.replace("""mm_image_projection"""			,			"""flava.image_to_mm_projection""" )
    lowercase__	: Optional[Any]     		=   key.replace("""image_encoder.module"""			,			"""flava.image_model""" )
    lowercase__	: Any     		=   key.replace("""text_encoder.module"""			,			"""flava.text_model""" )
    lowercase__	: Optional[Any]     		=   key.replace("""mm_encoder.module.encoder.cls_token"""			,			"""flava.multimodal_model.cls_token""" )
    lowercase__	: Tuple     		=   key.replace("""mm_encoder.module"""			,			"""flava.multimodal_model""" )
    lowercase__	: Any     		=   key.replace("""text_projection"""			,			"""flava.text_projection""" )
    lowercase__	: List[Any]     		=   key.replace("""image_projection"""			,			"""flava.image_projection""" )

    lowercase__	: str     		=   value.float()

  for key, value in codebook_state_dict.items():
    lowercase__	: Any     		=   value

  return upgrade

@torch.no_grad()
def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_			,			lowercase_=None )		->						Union[str, Any]:


  '''simple docstring'''






  if config_path is not None:
    lowercase__	: int     		=   FlavaConfig.from_pretrained(lowercase_ )
  else:
    lowercase__	: Optional[int]     		=   FlavaConfig()

  lowercase__	: List[Any]     		=   FlavaForPreTraining(lowercase_ ).eval()

  lowercase__	: Dict     		=   convert_dalle_checkpoint(lowercase_			,			lowercase_			,			save_checkpoint=lowercase_ )

  if os.path.exists(lowercase_ ):
    lowercase__	: Dict     		=   torch.load(lowercase_			,			map_location="""cpu""" )
  else:
    lowercase__	: Dict     		=   torch.hub.load_state_dict_from_url(lowercase_			,			map_location="""cpu""" )

  lowercase__	: int     		=   upgrade_state_dict(lowercase_			,			lowercase_ )
  hf_model.load_state_dict(lowercase_ )
  lowercase__	: Optional[int]     		=   hf_model.state_dict()
  lowercase__	: Optional[int]     		=   count_parameters(lowercase_ )
  lowercase__	: Any     		=   count_parameters(lowercase_ ) + count_parameters(lowercase_ )

  assert torch.allclose(lowercase_			,			lowercase_			,			atol=1E-3 )

  hf_model.save_pretrained(lowercase_ )


if __name__ == "__main__":
     lowerCamelCase__     :		int        = argparse.ArgumentParser()
     parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
     parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to flava checkpoint""")
     parser.add_argument("""--codebook_path""", default=None, type=str, help="""Path to flava codebook checkpoint""")
     parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
     lowerCamelCase__     :		List[str]        = parser.parse_args()

     convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)






