






'''simple docstring'''
import argparse

import torch

from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt


if __name__ == "__main__":
  a_					=	argparse.ArgumentParser()

  parser.add_argument(
      '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
  )
  # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
  parser.add_argument(
      '--original_config_file',
      default=None,
      type=str,
      help='The YAML config file corresponding to the original architecture.',
  )
  parser.add_argument(
      '--num_in_channels',
      default=None,
      type=int,
      help='The number of input channels. If `None` number of input channels will be automatically inferred.',
  )
  parser.add_argument(
      '--scheduler_type',
      default='pndm',
      type=str,
      help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']',
  )
  parser.add_argument(
      '--pipeline_type',
      default=None,
      type=str,
      help=(
          'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\''
          '. If `None` pipeline will be automatically inferred.'
      ),
  )
  parser.add_argument(
      '--image_size',
      default=None,
      type=int,
      help=(
          'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2'
          ' Base. Use 768 for Stable Diffusion v2.'
      ),
  )
  parser.add_argument(
      '--prediction_type',
      default=None,
      type=str,
      help=(
          'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable'
          ' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.'
      ),
  )
  parser.add_argument(
      '--extract_ema',
      action='store_true',
      help=(
          'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights'
          ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield'
          ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.'
      ),
  )
  parser.add_argument(
      '--upcast_attention',
      action='store_true',
      help=(
          'Whether the attention computation should always be upcasted. This is necessary when running stable'
          ' diffusion 2.1.'
      ),
  )
  parser.add_argument(
      '--from_safetensors',
      action='store_true',
      help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.',
  )
  parser.add_argument(
      '--to_safetensors',
      action='store_true',
      help='Whether to store pipeline in safetensors format or not.',
  )
  parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
  parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)')
  parser.add_argument(
      '--stable_unclip',
      type=str,
      default=None,
      required=False,
      help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.',
  )
  parser.add_argument(
      '--stable_unclip_prior',
      type=str,
      default=None,
      required=False,
      help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.',
  )
  parser.add_argument(
      '--clip_stats_path',
      type=str,
      help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.',
      required=False,
  )
  parser.add_argument(
      '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.'
  )
  parser.add_argument('--half', action='store_true', help='Save weights in half precision.')
  parser.add_argument(
      '--vae_path',
      type=str,
      default=None,
      required=False,
      help='Set to a path, hub id to an already converted vae to not convert it again.',
  )
  a_					=	parser.parse_args()

  a_					=	download_from_original_stable_diffusion_ckpt(
      checkpoint_path=args.checkpoint_path,
      original_config_file=args.original_config_file,
      image_size=args.image_size,
      prediction_type=args.prediction_type,
      model_type=args.pipeline_type,
      extract_ema=args.extract_ema,
      scheduler_type=args.scheduler_type,
      num_in_channels=args.num_in_channels,
      upcast_attention=args.upcast_attention,
      from_safetensors=args.from_safetensors,
      device=args.device,
      stable_unclip=args.stable_unclip,
      stable_unclip_prior=args.stable_unclip_prior,
      clip_stats_path=args.clip_stats_path,
      controlnet=args.controlnet,
      vae_path=args.vae_path,
  )

  if args.half:
    pipe.to(torch_dtype=torch.floataa)

  if args.controlnet:
    # only save the controlnet model
    pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
  else:
    pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)







'''simple docstring'''
from __future__ import annotations

from random import random
from typing import Generic, TypeVar

a_					=	TypeVar('KT')
a_					=	TypeVar('VT')






class        __SCREAMING_SNAKE_CASE (     Generic[KT, VT]			):




 def __init__( self		:							Dict   , __lowercase		:							KT | str = "root"   , __lowercase		:							VT | None = None )		->  Dict:
       SCREAMING_SNAKE_CASE__       :			Any													=key
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=value
       SCREAMING_SNAKE_CASE__       :			list[Node[KT, VT]]													=[]




 def __repr__( self		:							Any )		->  str:
       return F"Node({self.key}: {self.value})"




 @property
 def        __magic_name__		( self		:							List[Any] )		->  int:
       return len(self.forward )






class        __SCREAMING_SNAKE_CASE (     Generic[KT, VT]			):




 def __init__( self		:							int   , __lowercase		:							float = 0.5   , __lowercase		:							int = 16 )		->  int:
       SCREAMING_SNAKE_CASE__       :			Node[KT, VT]													=Node[KT, VT]()
       SCREAMING_SNAKE_CASE__       :			Any													=0
       SCREAMING_SNAKE_CASE__       :			Dict													=p
       SCREAMING_SNAKE_CASE__       :			Any													=max_level




 def __str__( self		:							Optional[Any] )		->  str:
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=list(self )

       if len(__lowercase ) == 0:
             return F"SkipList(level={self.level})"

       SCREAMING_SNAKE_CASE__       :			List[str]													=max((len(str(__lowercase ) ) for item in items)   , default=4 )
       SCREAMING_SNAKE_CASE__       :			Any													=max(__lowercase   , 4 ) + 4

       SCREAMING_SNAKE_CASE__       :			Any													=self.head
       SCREAMING_SNAKE_CASE__       :			List[Any]													=[]

       SCREAMING_SNAKE_CASE__       :			Tuple													=node.forward.copy()
       lines.append(F"[{node.key}]".ljust(__lowercase   , '''-''' ) + '''* ''' * len(__lowercase ) )
       lines.append(''' ''' * label_size + '''| ''' * len(__lowercase ) )

       while len(node.forward ) != 0:
             SCREAMING_SNAKE_CASE__       :			Optional[Any]													=node.forward[0]

             lines.append(
                 F"[{node.key}]".ljust(__lowercase   , '''-''' )
                 + ''' '''.join(str(n.key ) if n.key == node.key else '''|''' for n in forwards ) )
             lines.append(''' ''' * label_size + '''| ''' * len(__lowercase ) )
             SCREAMING_SNAKE_CASE__       :			Any													=node.forward

       lines.append('''None'''.ljust(__lowercase ) + '''* ''' * len(__lowercase ) )
       return F"SkipList(level={self.level})\n" + "\n".join(__lowercase )




 def __iter__( self		:							Union[str, Any] )		->  Optional[int]:
       SCREAMING_SNAKE_CASE__       :			List[str]													=self.head

       while len(node.forward ) != 0:
             yield node.forward[0].key
             SCREAMING_SNAKE_CASE__       :			List[Any]													=node.forward[0]




 def        __magic_name__		( self		:							Any )		->  int:
       SCREAMING_SNAKE_CASE__       :			Tuple													=1
       while random() < self.p and level < self.max_level:
             level += 1

       return level




 def        __magic_name__		( self		:							str   , __lowercase		:							List[str] )		->  tuple[Node[KT, VT] | None, list[Node[KT, VT]]]:
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=[]

       SCREAMING_SNAKE_CASE__       :			int													=self.head

       for i in reversed(range(self.level ) ):
             # i < node.level - When node level is lesser than `i` decrement `i`.
             # node.forward[i].key < key - Jumping to node with key value higher
             #                             or equal to searched key would result
             #                             in skipping searched key.
             while i < node.level and node.forward[i].key < key:
                   SCREAMING_SNAKE_CASE__       :			str													=node.forward[i]
             # Each leftmost node (relative to searched node) will potentially have to
             # be updated.
             update_vector.append(__lowercase )

       update_vector.reverse()  # Note that we were inserting values in reverse order.

       # len(node.forward) != 0 - If current node doesn't contain any further
       #                          references then searched key is not present.
       # node.forward[0].key == key - Next node key should be equal to search key
       #                              if key is present.
       if len(node.forward ) != 0 and node.forward[0].key == key:
             return node.forward[0], update_vector
       else:
             return None, update_vector




 def        __magic_name__		( self		:							Optional[int]   , __lowercase		:							KT )		->  List[Any]:
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			Dict													=self._locate_node(__lowercase )

       if node is not None:
             for i, update_node in enumerate(__lowercase ):
                   # Remove or replace all references to removed node.
                   if update_node.level > i and update_node.forward[i].key == key:
                         if node.level > i:
                               SCREAMING_SNAKE_CASE__       :			List[str]													=node.forward[i]
                         else:
                               SCREAMING_SNAKE_CASE__       :			str													=update_node.forward[:i]




 def        __magic_name__		( self		:							str   , __lowercase		:							KT   , __lowercase		:							VT )		->  Optional[Any]:
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			str													=self._locate_node(__lowercase )
       if node is not None:
             SCREAMING_SNAKE_CASE__       :			Dict													=value
       else:
             SCREAMING_SNAKE_CASE__       :			List[Any]													=self.random_level()

             if level > self.level:
                   # After level increase we have to add additional nodes to head.
                   for _ in range(self.level - 1   , __lowercase ):
                         update_vector.append(self.head )
                   SCREAMING_SNAKE_CASE__       :			List[str]													=level

             SCREAMING_SNAKE_CASE__       :			List[str]													=Node(__lowercase   , __lowercase )

             for i, update_node in enumerate(update_vector[:level] ):
                   # Change references to pass through new node.
                   if update_node.level > i:
                         new_node.forward.append(update_node.forward[i] )

                   if update_node.level < i + 1:
                         update_node.forward.append(__lowercase )
                   else:
                         SCREAMING_SNAKE_CASE__       :			int													=new_node




 def        __magic_name__		( self		:							Tuple   , __lowercase		:							VT )		->  VT | None:
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			List[str]													=self._locate_node(__lowercase )

       if node is not None:
             return node.value

       return None





def 	_a(					):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=SkipList()
      skip_list.insert('''Key1''',		3							)
      skip_list.insert('''Key2''',		1_2							)
      skip_list.insert('''Key3''',		4_1							)
      skip_list.insert('''Key4''',		-1_9							)

      SCREAMING_SNAKE_CASE__       :			Any													=skip_list.head
      SCREAMING_SNAKE_CASE__       :			Union[str, Any]													={}
      while node.level != 0:
            SCREAMING_SNAKE_CASE__       :			Dict													=node.forward[0]
            SCREAMING_SNAKE_CASE__       :			Optional[Any]													=node.value

      assert len(UpperCamelCase__							) == 4
      assert all_values["Key1"] == 3
      assert all_values["Key2"] == 1_2
      assert all_values["Key3"] == 4_1
      assert all_values["Key4"] == -1_9





def 	_a(					):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=SkipList()
      skip_list.insert('''Key1''',		1_0							)
      skip_list.insert('''Key1''',		1_2							)

      skip_list.insert('''Key5''',		7							)
      skip_list.insert('''Key7''',		1_0							)
      skip_list.insert('''Key10''',		5							)

      skip_list.insert('''Key7''',		7							)
      skip_list.insert('''Key5''',		5							)
      skip_list.insert('''Key10''',		1_0							)

      SCREAMING_SNAKE_CASE__       :			Optional[Any]													=skip_list.head
      SCREAMING_SNAKE_CASE__       :			List[Any]													={}
      while node.level != 0:
            SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=node.forward[0]
            SCREAMING_SNAKE_CASE__       :			List[Any]													=node.value

      if len(UpperCamelCase__							) != 4:
            print()
      assert len(UpperCamelCase__							) == 4
      assert all_values["Key1"] == 1_2
      assert all_values["Key7"] == 7
      assert all_values["Key5"] == 5
      assert all_values["Key10"] == 1_0





def 	_a(					):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__       :			int													=SkipList()
      assert skip_list.find('''Some key'''							) is None





def 	_a(					):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__       :			int													=SkipList()

      skip_list.insert('''Key2''',		2_0							)
      assert skip_list.find('''Key2'''							) == 2_0

      skip_list.insert('''Some Key''',		1_0							)
      skip_list.insert('''Key2''',		8							)
      skip_list.insert('''V''',		1_3							)

      assert skip_list.find('''Y'''							) is None
      assert skip_list.find('''Key2'''							) == 8
      assert skip_list.find('''Some Key'''							) == 1_0
      assert skip_list.find('''V'''							) == 1_3





def 	_a(					):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__       :			List[str]													=SkipList()
      skip_list.delete('''Some key'''							)

      assert len(skip_list.head.forward							) == 0





def 	_a(					):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__       :			str													=SkipList()

      skip_list.insert('''Key1''',		1_2							)
      skip_list.insert('''V''',		1_3							)
      skip_list.insert('''X''',		1_4							)
      skip_list.insert('''Key2''',		1_5							)

      skip_list.delete('''V'''							)
      skip_list.delete('''Key2'''							)

      assert skip_list.find('''V'''							) is None
      assert skip_list.find('''Key2'''							) is None





def 	_a(					):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__       :			Optional[int]													=SkipList()

      skip_list.insert('''Key1''',		1_2							)
      skip_list.insert('''V''',		1_3							)
      skip_list.insert('''X''',		1_4							)
      skip_list.insert('''Key2''',		1_5							)

      skip_list.delete('''V'''							)
      assert skip_list.find('''V'''							) is None
      assert skip_list.find('''X'''							) == 1_4
      assert skip_list.find('''Key1'''							) == 1_2
      assert skip_list.find('''Key2'''							) == 1_5

      skip_list.delete('''X'''							)
      assert skip_list.find('''V'''							) is None
      assert skip_list.find('''X'''							) is None
      assert skip_list.find('''Key1'''							) == 1_2
      assert skip_list.find('''Key2'''							) == 1_5

      skip_list.delete('''Key1'''							)
      assert skip_list.find('''V'''							) is None
      assert skip_list.find('''X'''							) is None
      assert skip_list.find('''Key1'''							) is None
      assert skip_list.find('''Key2'''							) == 1_5

      skip_list.delete('''Key2'''							)
      assert skip_list.find('''V'''							) is None
      assert skip_list.find('''X'''							) is None
      assert skip_list.find('''Key1'''							) is None
      assert skip_list.find('''Key2'''							) is None





def 	_a(					):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__       :			str													=SkipList()

      skip_list.insert('''Key1''',		1_2							)
      skip_list.insert('''V''',		1_3							)
      skip_list.insert('''X''',		1_4_2							)
      skip_list.insert('''Key2''',		1_5							)

      skip_list.delete('''X'''							)

      def traverse_keys(UpperCamelCase__			:  Dict							):
            yield node.key
            for forward_node in node.forward:
                  yield from traverse_keys(UpperCamelCase__							)

      assert len(set(traverse_keys(skip_list.head							)							)							) == 4





def 	_a(					):




      '''simple docstring'''






      def is_sorted(UpperCamelCase__			:  List[Any]							):
            return all(next_item >= item for item, next_item in zip(UpperCamelCase__,		lst[1:]							)							)

      SCREAMING_SNAKE_CASE__       :			Tuple													=SkipList()
      for i in range(1_0							):
            skip_list.insert(UpperCamelCase__,		UpperCamelCase__							)
      assert is_sorted(list(UpperCamelCase__							)							)
      skip_list.delete(5							)
      skip_list.delete(8							)
      skip_list.delete(2							)
      assert is_sorted(list(UpperCamelCase__							)							)
      skip_list.insert(-1_2,		-1_2							)
      skip_list.insert(7_7,		7_7							)
      assert is_sorted(list(UpperCamelCase__							)							)





def 	_a(					):




      '''simple docstring'''






      for _ in range(1_0_0							):
            # Repeat test 100 times due to the probabilistic nature of skip list
            # random values == random bugs
            test_insert()
            test_insert_overrides_existing_value()

            test_searching_empty_list_returns_none()
            test_search()

            test_deleting_item_from_empty_list_do_nothing()
            test_deleted_items_are_not_founded_by_find_method()
            test_delete_removes_only_given_key()
            test_delete_doesnt_leave_dead_nodes()

            test_iter_always_yields_sorted_values()





def 	_a(					):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__       :			Any													=SkipList()
      skip_list.insert(2,		'''2'''							)
      skip_list.insert(4,		'''4'''							)
      skip_list.insert(6,		'''4'''							)
      skip_list.insert(4,		'''5'''							)
      skip_list.insert(8,		'''4'''							)
      skip_list.insert(9,		'''4'''							)

      skip_list.delete(4							)

      print(UpperCamelCase__							)


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  main()