
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from ...utils.dataclasses import (
    ComputeEnvironment,
    DistributedType,
    DynamoBackend,
    PrecisionType,
    SageMakerDistributedType,
)
from ..menu import BulletMenu


_snake_case      :							Optional[int]     	=    [
    """EAGER""",
    """AOT_EAGER""",
    """INDUCTOR""",
    """NVFUSER""",
    """AOT_NVFUSER""",
    """AOT_CUDAGRAPHS""",
    """OFI""",
    """FX2TRT""",
    """ONNXRT""",
    """IPEX""",
]

def  __snake_case							(	__magic_name__		,    __magic_name__=None		,    __magic_name__=None		,    __magic_name__=None						):







				'''simple docstring'''


				lowercase         =      True
				while ask_again:
								lowercase         =      input(lowercase_						)
								try:
												if default is not None and len(lowercase_						) == 0:
																return default
												return convert_value(lowercase_						) if convert_value is not None else result
								except Exception:
												if error_message is not None:
																print(lowercase_						)

def  __snake_case							(	__magic_name__		,    __magic_name__=[]		,    __magic_name__=None		,    __magic_name__=0						):







				'''simple docstring'''


				lowercase         =      BulletMenu(lowercase_		,    lowercase_						)
				lowercase         =      menu.run(default_choice=lowercase_						)
				return convert_value(lowercase_						) if convert_value is not None else result

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				lowercase         =      int(lowercase_						)
				return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value]						)

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				lowercase         =      int(lowercase_						)
				return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value]						)

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				lowercase         =      int(lowercase_						)
				return DynamoBackend(DYNAMO_BACKENDS[value]						).value

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				lowercase         =      int(lowercase_						)
				return PrecisionType(["no", "fp16", "bf16", "fp8"][value]						)

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				lowercase         =      int(lowercase_						)
				return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value]						)

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				return {"yes": True, "no": False}[value.lower()]





class   UpperCamelCase_      (      argparse.RawDescriptionHelpFormatter		):







						'''simple docstring'''



						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]		,    lowerCAmelCase__							:Optional[int]		,    lowerCAmelCase__							:List[str]		,    lowerCAmelCase__							:Union[str, Any]		,    lowerCAmelCase__							:Tuple     )  ->List[str]:
										lowercase         =      super()._format_usage(SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_     )
										lowercase         =      usage.replace("<command> [<args>] "		,    ""     )
										return usage


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)






