






import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


a		:       int			     = logging.getLogger(__name__)
@dataclass
class     a    :



      """simple docstring"""


      a  : str
      a  : List[str]
      a  : Optional[List[str]]


@dataclass
class     a    :



      """simple docstring"""


      a  : List[int]
      a  : List[int]
      a  : Optional[List[int]]							       =	None
      a  : Optional[List[int]]							       =	None


class     a    ( lowercase__   ):



      """simple docstring"""


      a  : List[Any]							       =	'train'
      a  : Optional[int]							       =	'dev'
      a  : Any							       =	'test'


class     a    :



      """simple docstring"""


      @staticmethod
      def 	UpperCAmelCase      (      __lowercase					:			Union[str, Any]		,      __lowercase					:			Union[Split, str]					)							->      List[InputExample]:
        raise NotImplementedError
      @staticmethod
      def 	UpperCAmelCase      (      __lowercase					:			str					)							->      List[str]:
        raise NotImplementedError




      @staticmethod
      def 	UpperCAmelCase      (      __lowercase					:			List[InputExample]		,      __lowercase					:			List[str]		,      __lowercase					:			int		,      __lowercase					:			PreTrainedTokenizer		,      __lowercase					:			Optional[Any]=False		,      __lowercase					:			Any="[CLS]"		,      __lowercase					:			str=1		,      __lowercase					:			Union[str, Any]="[SEP]"		,      __lowercase					:			Optional[Any]=False		,      __lowercase					:			Union[str, Any]=False		,      __lowercase					:			Dict=0		,      __lowercase					:			int=0		,      __lowercase					:			str=-100		,      __lowercase					:			List[str]=0		,      __lowercase					:			List[Any]=True		,      )							->      List[InputFeatures]:
        __UpperCAmelCase							:	int           =  {label: i for i, label in enumerate(__lowercase					)}

        __UpperCAmelCase							:	str           =  []
        for ex_index, example in enumerate(__lowercase					):
          if ex_index % 10000 == 0:
            logger.info("""Writing example %d of %d"""		,      __lowercase		,      len(__lowercase					)					)

          __UpperCAmelCase							:	Tuple           =  []
          __UpperCAmelCase							:	str           =  []
          for word, label in zip(example.words		,      example.labels					):
            __UpperCAmelCase							:	Dict           =  tokenizer.tokenize(__lowercase					)

            # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
            if len(__lowercase					) > 0:
              tokens.extend(__lowercase					)
              # Use the real label id for the first token of the word, and padding ids for the remaining tokens
              label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__lowercase					) - 1)					)

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
          __UpperCAmelCase							:	Union[str, Any]           =  tokenizer.num_special_tokens_to_add()
          if len(__lowercase					) > max_seq_length - special_tokens_count:
            __UpperCAmelCase							:	List[str]           =  tokens[: (max_seq_length - special_tokens_count)]
            __UpperCAmelCase							:	Tuple           =  label_ids[: (max_seq_length - special_tokens_count)]

          # The convention in BERT is:
          # (a) For sequence pairs:
          #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
          #  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
          # (b) For single sequences:
          #  tokens:   [CLS] the dog is hairy . [SEP]
          #  type_ids:   0   0   0   0  0     0   0
          #
          # Where "type_ids" are used to indicate whether this is the first
          # sequence or the second sequence. The embedding vectors for `type=0` and
          # `type=1` were learned during pre-training and are added to the wordpiece
          # embedding vector (and position vector). This is not *strictly* necessary
          # since the [SEP] token unambiguously separates the sequences, but it makes
          # it easier for the model to learn the concept of sequences.
          #
          # For classification tasks, the first vector (corresponding to [CLS]) is
          # used as the "sentence vector". Note that this only makes sense because
          # the entire model is fine-tuned.
          tokens += [sep_token]
          label_ids += [pad_token_label_id]
          if sep_token_extra:
            # roberta uses an extra separator b/w pairs of sentences
            tokens += [sep_token]
            label_ids += [pad_token_label_id]
          __UpperCAmelCase							:	Optional[int]           =  [sequence_a_segment_id] * len(__lowercase					)

          if cls_token_at_end:
            tokens += [cls_token]
            label_ids += [pad_token_label_id]
            segment_ids += [cls_token_segment_id]
          else:
            __UpperCAmelCase							:	int           =  [cls_token] + tokens
            __UpperCAmelCase							:	int           =  [pad_token_label_id] + label_ids
            __UpperCAmelCase							:	Optional[int]           =  [cls_token_segment_id] + segment_ids

          __UpperCAmelCase							:	Dict           =  tokenizer.convert_tokens_to_ids(__lowercase					)

          # The mask has 1 for real tokens and 0 for padding tokens. Only real
          # tokens are attended to.
          __UpperCAmelCase							:	Any           =  [1 if mask_padding_with_zero else 0] * len(__lowercase					)

          # Zero-pad up to the sequence length.
          __UpperCAmelCase							:	Union[str, Any]           =  max_seq_length - len(__lowercase					)
          if pad_on_left:
            __UpperCAmelCase							:	Optional[int]           =  ([pad_token] * padding_length) + input_ids
            __UpperCAmelCase							:	List[str]           =  ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
            __UpperCAmelCase							:	Optional[int]           =  ([pad_token_segment_id] * padding_length) + segment_ids
            __UpperCAmelCase							:	Tuple           =  ([pad_token_label_id] * padding_length) + label_ids
          else:
            input_ids += [pad_token] * padding_length
            input_mask += [0 if mask_padding_with_zero else 1] * padding_length
            segment_ids += [pad_token_segment_id] * padding_length
            label_ids += [pad_token_label_id] * padding_length

          assert len(__lowercase					) == max_seq_length
          assert len(__lowercase					) == max_seq_length
          assert len(__lowercase					) == max_seq_length
          assert len(__lowercase					) == max_seq_length

          if ex_index < 5:
            logger.info("""*** Example ***"""					)
            logger.info("""guid: %s"""		,      example.guid					)
            logger.info("""tokens: %s"""		,      """ """.join([str(__lowercase					) for x in tokens]					)					)
            logger.info("""input_ids: %s"""		,      """ """.join([str(__lowercase					) for x in input_ids]					)					)
            logger.info("""input_mask: %s"""		,      """ """.join([str(__lowercase					) for x in input_mask]					)					)
            logger.info("""segment_ids: %s"""		,      """ """.join([str(__lowercase					) for x in segment_ids]					)					)
            logger.info("""label_ids: %s"""		,      """ """.join([str(__lowercase					) for x in label_ids]					)					)

          if "token_type_ids" not in tokenizer.model_input_names:
            __UpperCAmelCase							:	Optional[Any]           =  None

          features.append(
              InputFeatures(
                  input_ids=__lowercase		,      attention_mask=__lowercase		,      token_type_ids=__lowercase		,      label_ids=__lowercase					)					)
        return features


if is_torch_available():
       import torch
       from torch import nn
       from torch.utils.data import Dataset
       class     a    ( lowercase__   ):



             """simple docstring"""


             a  : List[InputFeatures]
             a  : int							       =	nn.CrossEntropyLoss().ignore_index
             def __init__(      self					:			List[Any]		,      __lowercase					:			TokenClassificationTask		,      __lowercase					:			str		,      __lowercase					:			PreTrainedTokenizer		,      __lowercase					:			List[str]		,      __lowercase					:			str		,      __lowercase					:			Optional[int] = None		,      __lowercase					:			str=False		,      __lowercase					:			Split = Split.train		,      )							->      Union[str, Any]:
               # Load data features from cache or dataset file
               __UpperCAmelCase							:	Optional[Any]           =  os.path.join(
                   __lowercase		,      """cached_{}_{}_{}""".format(mode.value		,      tokenizer.__class__.__name__		,      str(__lowercase					)					)		,      )

               # Make sure only the first process in distributed training processes the dataset,
               # and the others will use the cache.
               __UpperCAmelCase							:	Tuple           =  cached_features_file + """.lock"""
               with FileLock(__lowercase					):
                 if os.path.exists(__lowercase					) and not overwrite_cache:
                   logger.info(f"""Loading features from cached file {cached_features_file}"""					)
                   __UpperCAmelCase							:	Optional[int]           =  torch.load(__lowercase					)
                 else:
                   logger.info(f"""Creating features from dataset file at {data_dir}"""					)
                   __UpperCAmelCase							:	Union[str, Any]           =  token_classification_task.read_examples_from_file(__lowercase		,      __lowercase					)
                   # TODO clean up all this to leverage built-in features of tokenizers
                   __UpperCAmelCase							:	Dict           =  token_classification_task.convert_examples_to_features(
                       __lowercase		,      __lowercase		,      __lowercase		,      __lowercase		,      cls_token_at_end=bool(model_type in ["""xlnet"""]					)		,      cls_token=tokenizer.cls_token		,      cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0		,      sep_token=tokenizer.sep_token		,      sep_token_extra=__lowercase		,      pad_on_left=bool(tokenizer.padding_side == """left"""					)		,      pad_token=tokenizer.pad_token_id		,      pad_token_segment_id=tokenizer.pad_token_type_id		,      pad_token_label_id=self.pad_token_label_id		,      )
                   logger.info(f"""Saving features into cached file {cached_features_file}"""					)
                   torch.save(self.features		,      __lowercase					)
             def __len__(      self					:			List[str]					)							->      Union[str, Any]:
               return len(self.features					)




             def __getitem__(      self					:			Optional[Any]		,      __lowercase					:			Union[str, Any]					)							->      InputFeatures:
               return self.features[i]


if is_tf_available():
       import tensorflow as tf
       class     a    :



             """simple docstring"""


             a  : List[InputFeatures]
             a  : int							       =	-100
             def __init__(      self					:			str		,      __lowercase					:			TokenClassificationTask		,      __lowercase					:			str		,      __lowercase					:			PreTrainedTokenizer		,      __lowercase					:			List[str]		,      __lowercase					:			str		,      __lowercase					:			Optional[int] = None		,      __lowercase					:			Tuple=False		,      __lowercase					:			Split = Split.train		,      )							->      List[Any]:
               __UpperCAmelCase							:	Optional[int]           =  token_classification_task.read_examples_from_file(__lowercase		,      __lowercase					)
               # TODO clean up all this to leverage built-in features of tokenizers
               __UpperCAmelCase							:	Tuple           =  token_classification_task.convert_examples_to_features(
                   __lowercase		,      __lowercase		,      __lowercase		,      __lowercase		,      cls_token_at_end=bool(model_type in ["""xlnet"""]					)		,      cls_token=tokenizer.cls_token		,      cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0		,      sep_token=tokenizer.sep_token		,      sep_token_extra=__lowercase		,      pad_on_left=bool(tokenizer.padding_side == """left"""					)		,      pad_token=tokenizer.pad_token_id		,      pad_token_segment_id=tokenizer.pad_token_type_id		,      pad_token_label_id=self.pad_token_label_id		,      )

               def gen():
                 for ex in self.features:
                   if ex.token_type_ids is None:
                     yield (
                         {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
                         ex.label_ids,
                     )
                   else:
                     yield (
                         {
                             "input_ids": ex.input_ids,
                             "attention_mask": ex.attention_mask,
                             "token_type_ids": ex.token_type_ids,
                         },
                         ex.label_ids,
                     )

               if "token_type_ids" not in tokenizer.model_input_names:
                 __UpperCAmelCase							:	List[Any]           =  tf.data.Dataset.from_generator(
                     __lowercase		,      ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa)		,      (
                         {"""input_ids""": tf.TensorShape([None]					), """attention_mask""": tf.TensorShape([None]					)},
                         tf.TensorShape([None]					),
                     )		,      )
               else:
                 __UpperCAmelCase							:	Optional[Any]           =  tf.data.Dataset.from_generator(
                     __lowercase		,      ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa)		,      (
                         {
                             """input_ids""": tf.TensorShape([None]					),
                             """attention_mask""": tf.TensorShape([None]					),
                             """token_type_ids""": tf.TensorShape([None]					),
                         },
                         tf.TensorShape([None]					),
                     )		,      )
             def 	UpperCAmelCase      (      self					:			int					)							->      Dict:
               __UpperCAmelCase							:	Tuple           =  self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features					)					)					)

               return self.dataset
             def __len__(      self					:			List[Any]					)							->      Optional[Any]:
               return len(self.features					)




             def __getitem__(      self					:			Tuple		,      __lowercase					:			List[Any]					)							->      InputFeatures:
               return self.features[i]










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 				lowerCamelCase__      (    __lowerCamelCase			:     Dict  ,		__lowerCamelCase			:     int		):
  __UpperCAmelCase							:	List[Any]           =  checkpoint

  __UpperCAmelCase							:	Tuple           =  {}

  __UpperCAmelCase							:	Dict           =  vae_state_dict["""encoder.conv_in.weight"""]
  __UpperCAmelCase							:	Optional[Any]           =  vae_state_dict["""encoder.conv_in.bias"""]
  __UpperCAmelCase							:	Dict           =  vae_state_dict["""encoder.conv_out.weight"""]
  __UpperCAmelCase							:	Union[str, Any]           =  vae_state_dict["""encoder.conv_out.bias"""]
  __UpperCAmelCase							:	List[Any]           =  vae_state_dict["""encoder.norm_out.weight"""]
  __UpperCAmelCase							:	Tuple           =  vae_state_dict["""encoder.norm_out.bias"""]

  __UpperCAmelCase							:	Dict           =  vae_state_dict["""decoder.conv_in.weight"""]
  __UpperCAmelCase							:	Tuple           =  vae_state_dict["""decoder.conv_in.bias"""]
  __UpperCAmelCase							:	Optional[int]           =  vae_state_dict["""decoder.conv_out.weight"""]
  __UpperCAmelCase							:	Optional[int]           =  vae_state_dict["""decoder.conv_out.bias"""]
  __UpperCAmelCase							:	Optional[Any]           =  vae_state_dict["""decoder.norm_out.weight"""]
  __UpperCAmelCase							:	Union[str, Any]           =  vae_state_dict["""decoder.norm_out.bias"""]

  __UpperCAmelCase							:	Optional[int]           =  vae_state_dict["""quant_conv.weight"""]
  __UpperCAmelCase							:	int           =  vae_state_dict["""quant_conv.bias"""]
  __UpperCAmelCase							:	Union[str, Any]           =  vae_state_dict["""post_quant_conv.weight"""]
  __UpperCAmelCase							:	Any           =  vae_state_dict["""post_quant_conv.bias"""]

  # Retrieves the keys for the encoder down blocks only
  __UpperCAmelCase							:	int           =  len({""".""".join(layer.split("""."""		)[:3]		) for layer in vae_state_dict if """encoder.down""" in layer}		)
  __UpperCAmelCase							:	Optional[Any]           =  {
      layer_id: [key for key in vae_state_dict if f"""down.{layer_id}""" in key] for layer_id in range(__lowerCamelCase		)
  }

  # Retrieves the keys for the decoder up blocks only
  __UpperCAmelCase							:	Dict           =  len({""".""".join(layer.split("""."""		)[:3]		) for layer in vae_state_dict if """decoder.up""" in layer}		)
  __UpperCAmelCase							:	Optional[int]           =  {
      layer_id: [key for key in vae_state_dict if f"""up.{layer_id}""" in key] for layer_id in range(__lowerCamelCase		)
  }

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

    __UpperCAmelCase							:	Optional[int]           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	Optional[Any]           =  {"""old""": f"""down.{i}.block""", """new""": f"""down_blocks.{i}.resnets"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

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

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

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

  for i in range(__lowerCamelCase		):
    __UpperCAmelCase							:	Optional[Any]           =  num_up_blocks - 1 - i
    __UpperCAmelCase							:	Union[str, Any]           =  [
        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							:	int           =  vae_state_dict[
          f"""decoder.up.{block_id}.upsample.conv.weight"""
      ]
      __UpperCAmelCase							:	Dict           =  vae_state_dict[
          f"""decoder.up.{block_id}.upsample.conv.bias"""
      ]

    __UpperCAmelCase							:	Dict           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	Optional[Any]           =  {"""old""": f"""up.{block_id}.block""", """new""": f"""up_blocks.{i}.resnets"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

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

    __UpperCAmelCase							:	List[Any]           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	int           =  {"""old""": f"""mid.block_{i}""", """new""": f"""mid_block.resnets.{i - 1}"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

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






def 				lowerCamelCase__      (    __lowerCamelCase			:     str  ,		__lowerCamelCase			:     str  ,		):
  # Only support V1
  __UpperCAmelCase							:	Optional[int]           =  requests.get(
      """ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"""		)
  __UpperCAmelCase							:	Optional[int]           =  io.BytesIO(r.content		)

  __UpperCAmelCase							:	Dict           =  OmegaConf.load(__lowerCamelCase		)
  __UpperCAmelCase							:	str           =  512
  __UpperCAmelCase							:	Any           =  """cuda""" if torch.cuda.is_available() else """cpu"""
  if checkpoint_path.endswith("""safetensors"""		):
    from safetensors import safe_open

    __UpperCAmelCase							:	List[Any]           =  {}
    with safe_open(__lowerCamelCase  ,		framework="""pt"""  ,		device="""cpu"""		) as f:
      for key in f.keys():
        __UpperCAmelCase							:	str           =  f.get_tensor(__lowerCamelCase		)
  else:
    __UpperCAmelCase							:	Optional[int]           =  torch.load(__lowerCamelCase  ,		map_location=__lowerCamelCase		)["""state_dict"""]

  # Convert the VAE model.
  __UpperCAmelCase							:	Optional[int]           =  create_vae_diffusers_config(__lowerCamelCase  ,		image_size=__lowerCamelCase		)
  __UpperCAmelCase							:	Union[str, Any]           =  custom_convert_ldm_vae_checkpoint(__lowerCamelCase  ,		__lowerCamelCase		)

  __UpperCAmelCase							:	Optional[int]           =  AutoencoderKL(**__lowerCamelCase		)
  vae.load_state_dict(__lowerCamelCase		)
  vae.save_pretrained(__lowerCamelCase		)


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

       a		:       Optional[int]			     = parser.parse_args()

       vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)


