





'''simple docstring'''




import argparse
import io

import requests
import torch
from omegaconf import OmegaConf

from diffusers import AutoencoderKL
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
    assign_to_checkpoint,
    conv_attn_to_linear,
    create_vae_diffusers_config,
    renew_vae_attention_paths,
    renew_vae_resnet_paths,
)
def 	UpperCAmelCase_							(					__lowercase							:      str			,     __lowercase							:      List[Any]       )		->       List[Any]:


     '''simple docstring'''



     _UpperCAmelCase     							=   checkpoint

     _UpperCAmelCase     							=   {}

     _UpperCAmelCase     							=   vae_state_dict["encoder.conv_in.weight"]
     _UpperCAmelCase     							=   vae_state_dict["encoder.conv_in.bias"]
     _UpperCAmelCase     							=   vae_state_dict["encoder.conv_out.weight"]
     _UpperCAmelCase     							=   vae_state_dict["encoder.conv_out.bias"]
     _UpperCAmelCase     							=   vae_state_dict["encoder.norm_out.weight"]
     _UpperCAmelCase     							=   vae_state_dict["encoder.norm_out.bias"]

     _UpperCAmelCase     							=   vae_state_dict["decoder.conv_in.weight"]
     _UpperCAmelCase     							=   vae_state_dict["decoder.conv_in.bias"]
     _UpperCAmelCase     							=   vae_state_dict["decoder.conv_out.weight"]
     _UpperCAmelCase     							=   vae_state_dict["decoder.conv_out.bias"]
     _UpperCAmelCase     							=   vae_state_dict["decoder.norm_out.weight"]
     _UpperCAmelCase     							=   vae_state_dict["decoder.norm_out.bias"]

     _UpperCAmelCase     							=   vae_state_dict["quant_conv.weight"]
     _UpperCAmelCase     							=   vae_state_dict["quant_conv.bias"]
     _UpperCAmelCase     							=   vae_state_dict["post_quant_conv.weight"]
     _UpperCAmelCase     							=   vae_state_dict["post_quant_conv.bias"]

     # Retrieves the keys for the encoder down blocks only
     _UpperCAmelCase     							=   len({".".join(layer.split("."       )[:3]       ) for layer in vae_state_dict if "encoder.down" in layer}       )
     _UpperCAmelCase     							=   {
         layer_id: [key for key in vae_state_dict if f'down.{layer_id}' in key] for layer_id in range(__lowercase       )
     }

     # Retrieves the keys for the decoder up blocks only
     _UpperCAmelCase     							=   len({".".join(layer.split("."       )[:3]       ) for layer in vae_state_dict if "decoder.up" in layer}       )
     _UpperCAmelCase     							=   {
         layer_id: [key for key in vae_state_dict if f'up.{layer_id}' in key] for layer_id in range(__lowercase       )
     }

     for i in range(__lowercase       ):
          _UpperCAmelCase     							=   [key for key in down_blocks[i] if f'down.{i}' in key and f'down.{i}.downsample' not in key]

          if f'encoder.down.{i}.downsample.conv.weight' in vae_state_dict:
               _UpperCAmelCase     							=   vae_state_dict.pop(
                   f'encoder.down.{i}.downsample.conv.weight'       )
               _UpperCAmelCase     							=   vae_state_dict.pop(
                   f'encoder.down.{i}.downsample.conv.bias'       )

          _UpperCAmelCase     							=   renew_vae_resnet_paths(__lowercase       )
          _UpperCAmelCase     							=   {"old": f'down.{i}.block', "new": f'down_blocks.{i}.resnets'}
          assign_to_checkpoint(__lowercase			,     __lowercase			,     __lowercase			,     additional_replacements=[meta_path]			,     config=__lowercase       )

     _UpperCAmelCase     							=   [key for key in vae_state_dict if "encoder.mid.block" in key]
     _UpperCAmelCase     							=   2
     for i in range(1			,     num_mid_res_blocks + 1       ):
          _UpperCAmelCase     							=   [key for key in mid_resnets if f'encoder.mid.block_{i}' in key]

          _UpperCAmelCase     							=   renew_vae_resnet_paths(__lowercase       )
          _UpperCAmelCase     							=   {"old": f'mid.block_{i}', "new": f'mid_block.resnets.{i - 1}'}
          assign_to_checkpoint(__lowercase			,     __lowercase			,     __lowercase			,     additional_replacements=[meta_path]			,     config=__lowercase       )

     _UpperCAmelCase     							=   [key for key in vae_state_dict if "encoder.mid.attn" in key]
     _UpperCAmelCase     							=   renew_vae_attention_paths(__lowercase       )
     _UpperCAmelCase     							=   {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
     assign_to_checkpoint(__lowercase			,     __lowercase			,     __lowercase			,     additional_replacements=[meta_path]			,     config=__lowercase       )
     conv_attn_to_linear(__lowercase       )

     for i in range(__lowercase       ):
          _UpperCAmelCase     							=   num_up_blocks - 1 - i
          _UpperCAmelCase     							=   [
              key for key in up_blocks[block_id] if f'up.{block_id}' in key and f'up.{block_id}.upsample' not in key
          ]

          if f'decoder.up.{block_id}.upsample.conv.weight' in vae_state_dict:
               _UpperCAmelCase     							=   vae_state_dict[
                   f'decoder.up.{block_id}.upsample.conv.weight'
               ]
               _UpperCAmelCase     							=   vae_state_dict[
                   f'decoder.up.{block_id}.upsample.conv.bias'
               ]

          _UpperCAmelCase     							=   renew_vae_resnet_paths(__lowercase       )
          _UpperCAmelCase     							=   {"old": f'up.{block_id}.block', "new": f'up_blocks.{i}.resnets'}
          assign_to_checkpoint(__lowercase			,     __lowercase			,     __lowercase			,     additional_replacements=[meta_path]			,     config=__lowercase       )

     _UpperCAmelCase     							=   [key for key in vae_state_dict if "decoder.mid.block" in key]
     _UpperCAmelCase     							=   2
     for i in range(1			,     num_mid_res_blocks + 1       ):
          _UpperCAmelCase     							=   [key for key in mid_resnets if f'decoder.mid.block_{i}' in key]

          _UpperCAmelCase     							=   renew_vae_resnet_paths(__lowercase       )
          _UpperCAmelCase     							=   {"old": f'mid.block_{i}', "new": f'mid_block.resnets.{i - 1}'}
          assign_to_checkpoint(__lowercase			,     __lowercase			,     __lowercase			,     additional_replacements=[meta_path]			,     config=__lowercase       )

     _UpperCAmelCase     							=   [key for key in vae_state_dict if "decoder.mid.attn" in key]
     _UpperCAmelCase     							=   renew_vae_attention_paths(__lowercase       )
     _UpperCAmelCase     							=   {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
     assign_to_checkpoint(__lowercase			,     __lowercase			,     __lowercase			,     additional_replacements=[meta_path]			,     config=__lowercase       )
     conv_attn_to_linear(__lowercase       )
     return new_checkpoint
def 	UpperCAmelCase_							(					__lowercase							:      str			,     __lowercase							:      str			,     )		->       int:


     '''simple docstring'''



     _UpperCAmelCase     							=   requests.get(
         " https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"       )
     _UpperCAmelCase     							=   io.BytesIO(r.content       )

     _UpperCAmelCase     							=   OmegaConf.load(__lowercase       )
     _UpperCAmelCase     							=   512
     _UpperCAmelCase     							=   "cuda" if torch.cuda.is_available() else "cpu"
     if checkpoint_path.endswith("safetensors"       ):
          from safetensors import safe_open

          _UpperCAmelCase     							=   {}
          with safe_open(__lowercase			,     framework="pt"			,     device="cpu"       ) as f:
               for key in f.keys():
                    _UpperCAmelCase     							=   f.get_tensor(__lowercase       )
     else:
          _UpperCAmelCase     							=   torch.load(__lowercase			,     map_location=__lowercase       )["state_dict"]

     # Convert the VAE model.
     _UpperCAmelCase     							=   create_vae_diffusers_config(__lowercase			,     image_size=__lowercase       )
     _UpperCAmelCase     							=   custom_convert_ldm_vae_checkpoint(__lowercase			,     __lowercase       )

     _UpperCAmelCase     							=   AutoencoderKL(**__lowercase       )
     vae.load_state_dict(__lowercase       )
     vae.save_pretrained(__lowercase       )


if __name__ == "__main__":
  __SCREAMING_SNAKE_CASE     :Union[str, Any]       =				argparse.ArgumentParser()

  parser.add_argument('''--vae_pt_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''')
  parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''')

  __SCREAMING_SNAKE_CASE     :Any       =				parser.parse_args()

  vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)











'''simple docstring'''




import warnings

from ...utils import is_sklearn_available, requires_backends


if is_sklearn_available():
  from scipy.stats import pearsonr, spearmanr
  from sklearn.metrics import fa_score, matthews_corrcoef


__SCREAMING_SNAKE_CASE     :List[str]       =				(
    '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate '''
    '''library. You can have a look at this example script for pointers: '''
    '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'''
)
def 	UpperCAmelCase_							(					__lowercase							:      Any			,     __lowercase							:      Tuple       )		->       int:


     '''simple docstring'''



     warnings.warn(__lowercase			,     __lowercase       )
     requires_backends(__lowercase			,     "sklearn"       )
     return (preds == labels).mean()
def 	UpperCAmelCase_							(					__lowercase							:      int			,     __lowercase							:      str       )		->       Optional[Any]:


     '''simple docstring'''



     warnings.warn(__lowercase			,     __lowercase       )
     requires_backends(__lowercase			,     "sklearn"       )
     _UpperCAmelCase     							=   simple_accuracy(__lowercase			,     __lowercase       )
     _UpperCAmelCase     							=   fa_score(y_true=__lowercase			,     y_pred=__lowercase       )
     return {
         "acc": acc,
         "f1": fa,
         "acc_and_f1": (acc + fa) / 2,
     }
def 	UpperCAmelCase_							(					__lowercase							:      Optional[int]			,     __lowercase							:      List[str]       )		->       List[Any]:


     '''simple docstring'''



     warnings.warn(__lowercase			,     __lowercase       )
     requires_backends(__lowercase			,     "sklearn"       )
     _UpperCAmelCase     							=   pearsonr(__lowercase			,     __lowercase       )[0]
     _UpperCAmelCase     							=   spearmanr(__lowercase			,     __lowercase       )[0]
     return {
         "pearson": pearson_corr,
         "spearmanr": spearman_corr,
         "corr": (pearson_corr + spearman_corr) / 2,
     }
def 	UpperCAmelCase_							(					__lowercase							:      Optional[Any]			,     __lowercase							:      str			,     __lowercase							:      str       )		->       Tuple:


     '''simple docstring'''



     warnings.warn(__lowercase			,     __lowercase       )
     requires_backends(__lowercase			,     "sklearn"       )
     assert len(__lowercase       ) == len(__lowercase       ), f'Predictions and labels have mismatched lengths {len(__lowercase       )} and {len(__lowercase       )}'
     if task_name == "cola":
          return {"mcc": matthews_corrcoef(__lowercase			,     __lowercase       )}
     elif task_name == "sst-2":
          return {"acc": simple_accuracy(__lowercase			,     __lowercase       )}
     elif task_name == "mrpc":
          return acc_and_fa(__lowercase			,     __lowercase       )
     elif task_name == "sts-b":
          return pearson_and_spearman(__lowercase			,     __lowercase       )
     elif task_name == "qqp":
          return acc_and_fa(__lowercase			,     __lowercase       )
     elif task_name == "mnli":
          return {"mnli/acc": simple_accuracy(__lowercase			,     __lowercase       )}
     elif task_name == "mnli-mm":
          return {"mnli-mm/acc": simple_accuracy(__lowercase			,     __lowercase       )}
     elif task_name == "qnli":
          return {"acc": simple_accuracy(__lowercase			,     __lowercase       )}
     elif task_name == "rte":
          return {"acc": simple_accuracy(__lowercase			,     __lowercase       )}
     elif task_name == "wnli":
          return {"acc": simple_accuracy(__lowercase			,     __lowercase       )}
     elif task_name == "hans":
          return {"acc": simple_accuracy(__lowercase			,     __lowercase       )}
     else:
          raise KeyError(__lowercase       )






def 	UpperCAmelCase_							(					__lowercase							:      List[Any]			,     __lowercase							:      Dict			,     __lowercase							:      str       )		->       Union[str, Any]:


     '''simple docstring'''



     warnings.warn(__lowercase			,     __lowercase       )
     requires_backends(__lowercase			,     "sklearn"       )
     if len(__lowercase       ) != len(__lowercase       ):
          raise ValueError(f'Predictions and labels have mismatched lengths {len(__lowercase       )} and {len(__lowercase       )}'       )
     if task_name == "xnli":
          return {"acc": simple_accuracy(__lowercase			,     __lowercase       )}
     else:
          raise KeyError(__lowercase       )




