

import argparse

import torch

from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt


if __name__ == "__main__":
			UpperCAmelCase_							:					str		 =   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.''',
			)
			UpperCAmelCase_							:					Union[str, Any]		 =   parser.parse_args()

			UpperCAmelCase_							:					Any		 =   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)












from __future__ import annotations

import unittest

from transformers import DebertaVaConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import (
      TFDebertaVaForMaskedLM,
      TFDebertaVaForQuestionAnswering,
      TFDebertaVaForSequenceClassification,
      TFDebertaVaForTokenClassification,
      TFDebertaVaModel,
  )







class 	__lowerCAmelCase      :





   def __init__(			self       ,      snake_case       ,      snake_case=13       ,      snake_case=7       ,      snake_case=True       ,      snake_case=True       ,      snake_case=True       ,      snake_case=True       ,      snake_case=99       ,      snake_case=32       ,      snake_case=2       ,      snake_case=4       ,      snake_case=37       ,      snake_case="gelu"       ,      snake_case=0.1       ,      snake_case=0.1       ,      snake_case=512       ,      snake_case=16       ,      snake_case=2       ,      snake_case=0.02       ,      snake_case=False       ,      snake_case=True       ,      snake_case="None"       ,      snake_case=3       ,      snake_case=4       ,      snake_case=None       ,      )					->	int:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	parent
      a__						:    Dict   		=	batch_size
      a__						:    List[Any]   		=	seq_length
      a__						:    List[str]   		=	is_training
      a__						:    str   		=	use_input_mask
      a__						:    Union[str, Any]   		=	use_token_type_ids
      a__						:    Optional[int]   		=	use_labels
      a__						:    List[Any]   		=	vocab_size
      a__						:    Optional[Any]   		=	hidden_size
      a__						:    Union[str, Any]   		=	num_hidden_layers
      a__						:    Optional[int]   		=	num_attention_heads
      a__						:    Dict   		=	intermediate_size
      a__						:    Union[str, Any]   		=	hidden_act
      a__						:    str   		=	hidden_dropout_prob
      a__						:    Dict   		=	attention_probs_dropout_prob
      a__						:    str   		=	max_position_embeddings
      a__						:    int   		=	type_vocab_size
      a__						:    Any   		=	type_sequence_label_size
      a__						:    Optional[Any]   		=	initializer_range
      a__						:    List[Any]   		=	num_labels
      a__						:    Optional[int]   		=	num_choices
      a__						:    int   		=	relative_attention
      a__						:    str   		=	position_biased_input
      a__						:    List[Any]   		=	pos_att_type
      a__						:    Union[str, Any]   		=	scope





   def 						_snake_case			(			self   )					->	Tuple:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	ids_tensor([self.batch_size, self.seq_length]       ,      self.vocab_size   )

      a__						:    Union[str, Any]   		=	None
      if self.use_input_mask:
         a__						:    Any   		=	random_attention_mask([self.batch_size, self.seq_length]   )

      a__						:    Optional[Any]   		=	None
      if self.use_token_type_ids:
         a__						:    str   		=	ids_tensor([self.batch_size, self.seq_length]       ,      self.type_vocab_size   )

      a__						:    Dict   		=	None
      a__						:    List[Any]   		=	None
      a__						:    Dict   		=	None
      if self.use_labels:
         a__						:    List[Any]   		=	ids_tensor([self.batch_size]       ,      self.type_sequence_label_size   )
         a__						:    List[str]   		=	ids_tensor([self.batch_size, self.seq_length]       ,      self.num_labels   )

      a__						:    List[str]   		=	DebertaVaConfig(
          vocab_size=self.vocab_size       ,      hidden_size=self.hidden_size       ,      num_hidden_layers=self.num_hidden_layers       ,      num_attention_heads=self.num_attention_heads       ,      intermediate_size=self.intermediate_size       ,      hidden_act=self.hidden_act       ,      hidden_dropout_prob=self.hidden_dropout_prob       ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,      max_position_embeddings=self.max_position_embeddings       ,      type_vocab_size=self.type_vocab_size       ,      relative_attention=self.relative_attention       ,      position_biased_input=self.position_biased_input       ,      initializer_range=self.initializer_range       ,      return_dict=snake_case       ,      )

      return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case   )					->	List[Any]:
      """simple docstring"""





      a__						:    Dict   		=	TFDebertaVaModel(config=snake_case   )
      a__						:    Union[str, Any]   		=	{"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}

      a__						:    Union[str, Any]   		=	[input_ids, input_mask]
      a__						:    Any   		=	model(snake_case   )

      a__						:    Optional[Any]   		=	model(snake_case   )

      self.parent.assertEqual(result.last_hidden_state.shape       ,      (self.batch_size, self.seq_length, self.hidden_size)   )





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case   )					->	Any:
      """simple docstring"""





      a__						:    Optional[Any]   		=	TFDebertaVaForMaskedLM(config=snake_case   )
      a__						:    Optional[Any]   		=	{
          "input_ids": input_ids,
          "attention_mask": input_mask,
          "token_type_ids": token_type_ids,
      }
      a__						:    List[str]   		=	model(snake_case   )
      self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.seq_length, self.vocab_size)   )





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case   )					->	Optional[Any]:
      """simple docstring"""





      a__						:    List[Any]   		=	self.num_labels
      a__						:    int   		=	TFDebertaVaForSequenceClassification(config=snake_case   )
      a__						:    Optional[Any]   		=	{
          "input_ids": input_ids,
          "attention_mask": input_mask,
          "token_type_ids": token_type_ids,
      }

      a__						:    int   		=	model(snake_case   )
      self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.num_labels)   )





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case   )					->	Dict:
      """simple docstring"""





      a__						:    Dict   		=	self.num_labels
      a__						:    str   		=	TFDebertaVaForTokenClassification(config=snake_case   )
      a__						:    Dict   		=	{
          "input_ids": input_ids,
          "attention_mask": input_mask,
          "token_type_ids": token_type_ids,
      }
      a__						:    Tuple   		=	model(snake_case   )
      self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.seq_length, self.num_labels)   )





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case   )					->	List[str]:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	TFDebertaVaForQuestionAnswering(config=snake_case   )
      a__						:    Optional[int]   		=	{
          "input_ids": input_ids,
          "attention_mask": input_mask,
          "token_type_ids": token_type_ids,
      }

      a__						:    List[Any]   		=	model(snake_case   )
      self.parent.assertEqual(result.start_logits.shape       ,      (self.batch_size, self.seq_length)   )
      self.parent.assertEqual(result.end_logits.shape       ,      (self.batch_size, self.seq_length)   )





   def 						_snake_case			(			self   )					->	List[str]:
      """simple docstring"""





      a__						:    List[str]   		=	self.prepare_config_and_inputs()
      (
          (
          a__
      )		,  (
          a__
      )		,  (
          a__
      )		,  (
          a__
      )		,  (
          a__
      )		,  (
          a__
      )		,  (
          a__
      )		,  
      )						:    int   		=	config_and_inputs
      a__						:    Any   		=	{"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
      return config, inputs_dict







@require_tf
class 	__lowerCAmelCase      (       _UpperCamelCase		,_UpperCamelCase		,unittest.TestCase	):
   _UpperCamelCase			:    int  		=					(
       (
           TFDebertaVaModel,
           TFDebertaVaForMaskedLM,
           TFDebertaVaForQuestionAnswering,
           TFDebertaVaForSequenceClassification,
           TFDebertaVaForTokenClassification,
       )
       if is_tf_available()
       else ()
   )
   _UpperCamelCase			:    List[str]  		=					(
       {
           """feature-extraction""": TFDebertaVaModel,
           """fill-mask""": TFDebertaVaForMaskedLM,
           """question-answering""": TFDebertaVaForQuestionAnswering,
           """text-classification""": TFDebertaVaForSequenceClassification,
           """token-classification""": TFDebertaVaForTokenClassification,
           """zero-shot""": TFDebertaVaForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )

   _UpperCamelCase			:    str  		=					False
   _UpperCamelCase			:    List[str]  		=					False





   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      a__						:    Any   		=	TFDebertaVaModelTester(self   )
      a__						:    int   		=	ConfigTester(self       ,      config_class=snake_case       ,      hidden_size=37   )





   def 						_snake_case			(			self   )					->	Union[str, Any]:
      """simple docstring"""





      self.config_tester.run_common_tests()





   def 						_snake_case			(			self   )					->	Any:
      """simple docstring"""





      a__						:    Dict   		=	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case   )





   def 						_snake_case			(			self   )					->	str:
      """simple docstring"""





      a__						:    List[str]   		=	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*snake_case   )





   def 						_snake_case			(			self   )					->	List[Any]:
      """simple docstring"""





      a__						:    Tuple   		=	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*snake_case   )





   def 						_snake_case			(			self   )					->	List[Any]:
      """simple docstring"""





      a__						:    Any   		=	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(*snake_case   )





   def 						_snake_case			(			self   )					->	List[Any]:
      """simple docstring"""





      a__						:    int   		=	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*snake_case   )





   @slow
   def 						_snake_case			(			self   )					->	List[str]:
      """simple docstring"""





      a__						:    Tuple   		=	TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge"   )
      self.assertIsNotNone(snake_case   )







@require_tf
class 	__lowerCAmelCase      (       unittest.TestCase	):





   @unittest.skip(reason="Model not available yet"   )
   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      pass





   @slow
   def 						_snake_case			(			self   )					->	List[Any]:
      """simple docstring"""





      a__						:    Optional[Any]   		=	TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge"   )
      a__						:    Any   		=	tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]]   )
      a__						:    List[str]   		=	tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]   )
      a__						:    Tuple   		=	model(snake_case       ,      attention_mask=snake_case   )[0]

      a__						:    List[Any]   		=	tf.constant(
          [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]]   )
      tf.debugging.assert_near(output[:, 1:4, 1:4]       ,      snake_case       ,      atol=1E-4   )

