






"""simple docstring"""





from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
    import tensorflow as tf

    from ..tf_utils import stable_softmax


if is_torch_available():
    import torch


UpperCamelCase_	:				str										= logging.get_logger(__name__)


@add_end_docstrings(
    _UpperCAmelCase		,  R'''
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    '''		,  )
class      _lowercase (     _UpperCAmelCase						):


      def _UpperCamelCase						(    self				:	Optional[Any]							,   a				:	Optional[int]						):





            """simple docstring"""







            if self.framework == "tf":
                  __snake_case      :    Union[str, Any]  			=tf.where(input_ids == self.tokenizer.mask_token_id						).numpy()
            elif self.framework == "pt":
                  __snake_case      :    str  			=torch.nonzero(input_ids == self.tokenizer.mask_token_id							,   as_tuple=lowercase__						)
            else:
                  raise ValueError('''Unsupported framework'''						)
            return masked_index


      def _UpperCamelCase						(    self				:	Dict							,   a				:	int						):





            """simple docstring"""







            __snake_case      :    Optional[int]  			=self.get_masked_index(lowercase__						)
            __snake_case      :    Tuple  			=np.prod(masked_index.shape						)
            if numel < 1:
                  raise PipelineException(
                      '''fill-mask'''							,   self.model.base_model_prefix							,   f'''No mask_token ({self.tokenizer.mask_token}) found on the input'''							,   )


      def _UpperCamelCase						(    self				:	Optional[Any]							,   a				:	Optional[int]						):





            """simple docstring"""







            if isinstance(lowercase__							,   lowercase__						):
                  for model_input in model_inputs:
                        self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0]						)
            else:
                  for input_ids in model_inputs["input_ids"]:
                        self._ensure_exactly_one_mask_token(lowercase__						)


      def _UpperCamelCase						(    self				:	str							,   a				:	str							,   a				:	int=None							,   **a				:	int						):





            """simple docstring"""







            if return_tensors is None:
                  __snake_case      :    str  			=self.framework
            __snake_case      :    Dict  			=self.tokenizer(lowercase__							,   return_tensors=lowercase__						)
            self.ensure_exactly_one_mask_token(lowercase__						)
            return model_inputs


      def _UpperCamelCase						(    self				:	int							,   a				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    Tuple  			=self.model(**lowercase__						)
            __snake_case      :    Optional[Any]  			=model_inputs["""input_ids"""]
            return model_outputs


      def _UpperCamelCase						(    self				:	List[str]							,   a				:	List[Any]							,   a				:	Optional[Any]=5							,   a				:	Union[str, Any]=None						):





            """simple docstring"""







            if target_ids is not None and target_ids.shape[0] < top_k:
                  __snake_case      :    List[str]  			=target_ids.shape[0]
            __snake_case      :    Union[str, Any]  			=model_outputs["""input_ids"""][0]
            __snake_case      :    str  			=model_outputs["""logits"""]

            if self.framework == "tf":
                  __snake_case      :    Optional[int]  			=tf.where(input_ids == self.tokenizer.mask_token_id						).numpy()[:, 0]

                  __snake_case      :    Union[str, Any]  			=outputs.numpy()

                  __snake_case      :    Dict  			=outputs[0, masked_index, :]
                  __snake_case      :    Optional[Any]  			=stable_softmax(lowercase__							,   axis=-1						)
                  if target_ids is not None:
                        __snake_case      :    Tuple  			=tf.gather_nd(tf.squeeze(lowercase__							,   0						)							,   target_ids.reshape(-1							,   1						)						)
                        __snake_case      :    List[str]  			=tf.expand_dims(lowercase__							,   0						)

                  __snake_case      :    str  			=tf.math.top_k(lowercase__							,   k=lowercase__						)
                  __snake_case      :    Any  			=topk.values.numpy(), topk.indices.numpy()
            else:
                  __snake_case      :    List[Any]  			=torch.nonzero(input_ids == self.tokenizer.mask_token_id							,   as_tuple=lowercase__						).squeeze(-1						)
                  # Fill mask pipeline supports only one ${mask_token} per sample

                  __snake_case      :    List[Any]  			=outputs[0, masked_index, :]
                  __snake_case      :    Any  			=logits.softmax(dim=-1						)
                  if target_ids is not None:
                        __snake_case      :    int  			=probs[..., target_ids]

                  __snake_case      :    Dict  			=probs.topk(lowercase__						)

            __snake_case      :    Tuple  			=[]
            __snake_case      :    Union[str, Any]  			=values.shape[0] == 1
            for i, (_values, _predictions) in enumerate(zip(values.tolist()							,   predictions.tolist()						)						):
                  __snake_case      :    int  			=[]
                  for v, p in zip(_values							,   _predictions						):
                        # Copy is important since we're going to modify this array in place
                        __snake_case      :    Any  			=input_ids.numpy().copy()
                        if target_ids is not None:
                              __snake_case      :    int  			=target_ids[p].tolist()

                        __snake_case      :    Union[str, Any]  			=p
                        # Filter padding out:
                        __snake_case      :    int  			=tokens[np.where(tokens != self.tokenizer.pad_token_id						)]
                        # Originally we skip special tokens to give readable output.
                        # For multi masks though, the other [MASK] would be removed otherwise
                        # making the output look odd, so we add them back
                        __snake_case      :    Dict  			=self.tokenizer.decode(lowercase__							,   skip_special_tokens=lowercase__						)
                        __snake_case      :    List[str]  			={"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]						), """sequence""": sequence}
                        row.append(lowercase__						)
                  result.append(lowercase__						)
            if single_mask:
                  return result[0]
            return result


      def _UpperCamelCase						(    self				:	Union[str, Any]							,   a				:	List[Any]							,   a				:	Dict=None						):





            """simple docstring"""







            if isinstance(lowercase__							,   lowercase__						):
                  __snake_case      :    Union[str, Any]  			=[targets]
            try:
                  __snake_case      :    Union[str, Any]  			=self.tokenizer.get_vocab()
            except Exception:
                  __snake_case      :    Any  			={}
            __snake_case      :    Optional[int]  			=[]
            for target in targets:
                  __snake_case      :    Optional[Any]  			=vocab.get(lowercase__							,   lowercase__						)
                  if id_ is None:
                        __snake_case      :    int  			=self.tokenizer(
                            lowercase__							,   add_special_tokens=lowercase__							,   return_attention_mask=lowercase__							,   return_token_type_ids=lowercase__							,   max_length=1							,   truncation=lowercase__							,   )["""input_ids"""]
                        if len(lowercase__						) == 0:
                              logger.warning(
                                  f'''The specified target token `{target}` does not exist in the model vocabulary. '''
                                  '''We cannot replace it with anything meaningful, ignoring it'''						)
                              continue
                        __snake_case      :    int  			=input_ids[0]
                        # XXX: If users encounter this pass
                        # it becomes pretty slow, so let's make sure
                        # The warning enables them to fix the input to
                        # get faster performance.
                        logger.warning(
                            f'''The specified target token `{target}` does not exist in the model vocabulary. '''
                            f'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_						)}`.'''						)
                  target_ids.append(id_						)
            __snake_case      :    str  			=list(set(lowercase__						)						)
            if len(lowercase__						) == 0:
                  raise ValueError('''At least one target must be provided when passed.'''						)
            __snake_case      :    List[str]  			=np.array(lowercase__						)
            return target_ids


      def _UpperCamelCase						(    self				:	Union[str, Any]							,   a				:	str=None							,   a				:	List[str]=None						):





            """simple docstring"""







            __snake_case      :    List[Any]  			={}

            if targets is not None:
                  __snake_case      :    Union[str, Any]  			=self.get_target_ids(lowercase__							,   lowercase__						)
                  __snake_case      :    Optional[Any]  			=target_ids

            if top_k is not None:
                  __snake_case      :    List[str]  			=top_k

            if self.tokenizer.mask_token_id is None:
                  raise PipelineException(
                      '''fill-mask'''							,   self.model.base_model_prefix							,   '''The tokenizer does not define a `mask_token`.'''						)
            return {}, {}, postprocess_params







      def __call__(    self				:	int							,   a				:	List[Any]							,   *a				:	List[str]							,   **a				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    Tuple  			=super().__call__(lowercase__							,   **lowercase__						)
            if isinstance(lowercase__							,   lowercase__						) and len(lowercase__						) == 1:
                  return outputs[0]
            return outputs








"""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     __lowercase					(    a :				Any       ,		a :				List[Any] )					->					Dict:
      __snake_case      :    Any  			=checkpoint

      __snake_case      :    Dict  			={}

      __snake_case      :    List[Any]  			=vae_state_dict['''encoder.conv_in.weight''']
      __snake_case      :    List[str]  			=vae_state_dict['''encoder.conv_in.bias''']
      __snake_case      :    Union[str, Any]  			=vae_state_dict['''encoder.conv_out.weight''']
      __snake_case      :    Union[str, Any]  			=vae_state_dict['''encoder.conv_out.bias''']
      __snake_case      :    str  			=vae_state_dict['''encoder.norm_out.weight''']
      __snake_case      :    str  			=vae_state_dict['''encoder.norm_out.bias''']

      __snake_case      :    Tuple  			=vae_state_dict['''decoder.conv_in.weight''']
      __snake_case      :    str  			=vae_state_dict['''decoder.conv_in.bias''']
      __snake_case      :    List[str]  			=vae_state_dict['''decoder.conv_out.weight''']
      __snake_case      :    Tuple  			=vae_state_dict['''decoder.conv_out.bias''']
      __snake_case      :    Union[str, Any]  			=vae_state_dict['''decoder.norm_out.weight''']
      __snake_case      :    List[str]  			=vae_state_dict['''decoder.norm_out.bias''']

      __snake_case      :    Tuple  			=vae_state_dict['''quant_conv.weight''']
      __snake_case      :    List[str]  			=vae_state_dict['''quant_conv.bias''']
      __snake_case      :    Optional[int]  			=vae_state_dict['''post_quant_conv.weight''']
      __snake_case      :    Tuple  			=vae_state_dict['''post_quant_conv.bias''']

      # Retrieves the keys for the encoder down blocks only
      __snake_case      :    Union[str, Any]  			=len({'''.'''.join(layer.split('''.''' )[:3] ) for layer in vae_state_dict if '''encoder.down''' in layer} )
      __snake_case      :    Union[str, Any]  			={
          layer_id: [key for key in vae_state_dict if f'''down.{layer_id}''' in key] for layer_id in range(a )
      }

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

      for i in range(a ):
            __snake_case      :    Any  			=[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:
                  __snake_case      :    Optional[Any]  			=vae_state_dict.pop(
                      f'''encoder.down.{i}.downsample.conv.weight''' )
                  __snake_case      :    Optional[int]  			=vae_state_dict.pop(
                      f'''encoder.down.{i}.downsample.conv.bias''' )

            __snake_case      :    Optional[Any]  			=renew_vae_resnet_paths(a )
            __snake_case      :    Union[str, Any]  			={'''old''': f'''down.{i}.block''', '''new''': f'''down_blocks.{i}.resnets'''}
            assign_to_checkpoint(a       ,		a       ,		a       ,		additional_replacements=[meta_path]       ,		config=a )

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

            __snake_case      :    List[str]  			=renew_vae_resnet_paths(a )
            __snake_case      :    List[str]  			={'''old''': f'''mid.block_{i}''', '''new''': f'''mid_block.resnets.{i - 1}'''}
            assign_to_checkpoint(a       ,		a       ,		a       ,		additional_replacements=[meta_path]       ,		config=a )

      __snake_case      :    int  			=[key for key in vae_state_dict if '''encoder.mid.attn''' in key]
      __snake_case      :    List[Any]  			=renew_vae_attention_paths(a )
      __snake_case      :    Union[str, Any]  			={'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''}
      assign_to_checkpoint(a       ,		a       ,		a       ,		additional_replacements=[meta_path]       ,		config=a )
      conv_attn_to_linear(a )

      for i in range(a ):
            __snake_case      :    List[Any]  			=num_up_blocks - 1 - i
            __snake_case      :    Dict  			=[
                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:
                  __snake_case      :    int  			=vae_state_dict[
                      f'''decoder.up.{block_id}.upsample.conv.weight'''
                  ]
                  __snake_case      :    Optional[Any]  			=vae_state_dict[
                      f'''decoder.up.{block_id}.upsample.conv.bias'''
                  ]

            __snake_case      :    List[str]  			=renew_vae_resnet_paths(a )
            __snake_case      :    int  			={'''old''': f'''up.{block_id}.block''', '''new''': f'''up_blocks.{i}.resnets'''}
            assign_to_checkpoint(a       ,		a       ,		a       ,		additional_replacements=[meta_path]       ,		config=a )

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

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

      __snake_case      :    Optional[Any]  			=[key for key in vae_state_dict if '''decoder.mid.attn''' in key]
      __snake_case      :    Dict  			=renew_vae_attention_paths(a )
      __snake_case      :    List[str]  			={'''old''': '''mid.attn_1''', '''new''': '''mid_block.attentions.0'''}
      assign_to_checkpoint(a       ,		a       ,		a       ,		additional_replacements=[meta_path]       ,		config=a )
      conv_attn_to_linear(a )
      return new_checkpoint



def     __lowercase					(    a :				str       ,		a :				str       ,		)					->					Optional[int]:
      # Only support V1
      __snake_case      :    Union[str, Any]  			=requests.get(
          ''' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml''' )
      __snake_case      :    Union[str, Any]  			=io.BytesIO(r.content )

      __snake_case      :    Any  			=OmegaConf.load(a )
      __snake_case      :    Union[str, Any]  			=512
      __snake_case      :    List[str]  			='''cuda''' if torch.cuda.is_available() else '''cpu'''
      if checkpoint_path.endswith('''safetensors''' ):
            from safetensors import safe_open

            __snake_case      :    Any  			={}
            with safe_open(a       ,		framework='''pt'''       ,		device='''cpu''' ) as f:
                  for key in f.keys():
                        __snake_case      :    Optional[int]  			=f.get_tensor(a )
      else:
            __snake_case      :    Optional[int]  			=torch.load(a       ,		map_location=a )['''state_dict''']

      # Convert the VAE model.
      __snake_case      :    Dict  			=create_vae_diffusers_config(a       ,		image_size=a )
      __snake_case      :    Union[str, Any]  			=custom_convert_ldm_vae_checkpoint(a       ,		a )

      __snake_case      :    str  			=AutoencoderKL(**a )
      vae.load_state_dict(a )
      vae.save_pretrained(a )


if __name__ == "__main__":
    UpperCamelCase_	:				Optional[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.""")

    UpperCamelCase_	:				Optional[Any]										= parser.parse_args()

    vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)


