

import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import YolosForObjectDetection, YolosModel
					from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor

class 			a					:


						def __init__(    self  ,   A_  ,   A_=13  ,   A_=[30, 30]  ,   A_=2  ,   A_=3  ,   A_=True  ,   A_=True  ,   A_=32  ,   A_=5  ,   A_=4  ,   A_=37  ,   A_="gelu"  ,   A_=0.1  ,   A_=0.1  ,   A_=10  ,   A_=0.02  ,   A_=3  ,   A_=None  ,   A_=8  ,   A_=10  ,   ):







										'''simple docstring'''


										_UpperCAmelCase    :						List[str]							=      parent
										_UpperCAmelCase    :						List[str]							=      batch_size
										_UpperCAmelCase    :						Dict							=      image_size
										_UpperCAmelCase    :						Tuple							=      patch_size
										_UpperCAmelCase    :						int							=      num_channels
										_UpperCAmelCase    :						str							=      is_training
										_UpperCAmelCase    :						Any							=      use_labels
										_UpperCAmelCase    :						Dict							=      hidden_size
										_UpperCAmelCase    :						str							=      num_hidden_layers
										_UpperCAmelCase    :						Dict							=      num_attention_heads
										_UpperCAmelCase    :						Any							=      intermediate_size
										_UpperCAmelCase    :						str							=      hidden_act
										_UpperCAmelCase    :						Any							=      hidden_dropout_prob
										_UpperCAmelCase    :						Union[str, Any]							=      attention_probs_dropout_prob
										_UpperCAmelCase    :						Tuple							=      type_sequence_label_size
										_UpperCAmelCase    :						Optional[int]							=      initializer_range
										_UpperCAmelCase    :						str							=      num_labels
										_UpperCAmelCase    :						Union[str, Any]							=      scope
										_UpperCAmelCase    :						str							=      n_targets
										_UpperCAmelCase    :						Any							=      num_detection_tokens
										# we set the expected sequence length (which is used in several tests)
										# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
										_UpperCAmelCase    :						Union[str, Any]							=      (image_size[1] // patch_size) * (image_size[0] // patch_size)
										_UpperCAmelCase    :						Tuple							=      num_patches + 1 + self.num_detection_tokens


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]		)

										_UpperCAmelCase    :						int							=      None
										if self.use_labels:
														# labels is a list of Dict (each Dict being the labels for a given example in the batch)
														_UpperCAmelCase    :						str							=      []
														for i in range(self.batch_size		):
																		_UpperCAmelCase    :						int							=      {}
																		_UpperCAmelCase    :						Optional[int]							=      torch.randint(
																		    high=self.num_labels  ,   size=(self.n_targets,)  ,   device=A_		)
																		_UpperCAmelCase    :						List[Any]							=      torch.rand(self.n_targets  ,   4  ,   device=A_		)
																		labels.append(A_		)

										_UpperCAmelCase    :						Dict							=      self.get_config()

										return config, pixel_values, labels


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return YolosConfig(
										    image_size=self.image_size  ,   patch_size=self.patch_size  ,   num_channels=self.num_channels  ,   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  ,   is_decoder=A_  ,   initializer_range=self.initializer_range  ,   num_detection_tokens=self.num_detection_tokens  ,   num_labels=self.num_labels  ,   )


						def     _UpperCAmelCase			(    self  ,   A_  ,   A_  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						Tuple							=      YolosModel(config=A_		)
										model.to(A_		)
										model.eval()
										_UpperCAmelCase    :						List[Any]							=      model(A_		)
										self.parent.assertEqual(
										    result.last_hidden_state.shape  ,   (self.batch_size, self.expected_seq_len, self.hidden_size)		)


						def     _UpperCAmelCase			(    self  ,   A_  ,   A_  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      YolosForObjectDetection(A_		)
										model.to(A_		)
										model.eval()

										_UpperCAmelCase    :						Union[str, Any]							=      model(pixel_values=A_		)
										_UpperCAmelCase    :						Union[str, Any]							=      model(A_		)

										self.parent.assertEqual(result.logits.shape  ,   (self.batch_size, self.num_detection_tokens, self.num_labels + 1)		)
										self.parent.assertEqual(result.pred_boxes.shape  ,   (self.batch_size, self.num_detection_tokens, 4)		)

										_UpperCAmelCase    :						int							=      model(pixel_values=A_  ,   labels=A_		)

										self.parent.assertEqual(result.loss.shape  ,   ()		)
										self.parent.assertEqual(result.logits.shape  ,   (self.batch_size, self.num_detection_tokens, self.num_labels + 1)		)
										self.parent.assertEqual(result.pred_boxes.shape  ,   (self.batch_size, self.num_detection_tokens, 4)		)





						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[Any]							=      self.prepare_config_and_inputs()
										_UpperCAmelCase						,							_UpperCAmelCase						,							_UpperCAmelCase    :						List[Any]							=      config_and_inputs
										_UpperCAmelCase    :						Union[str, Any]							=      {"pixel_values": pixel_values}
										return config, inputs_dict







@require_torch
class 			a					(		UpperCAmelCase							,	UpperCAmelCase							,	unittest.TestCase			):
						_lowercase        =     (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
						_lowercase        =     (
						    {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {}
						)

						_lowercase        =     False
						_lowercase        =     False
						_lowercase        =     False
						_lowercase        =     False


						def     _UpperCAmelCase			(    self  ,   A_  ,   A_  ,   A_=False		):







										'''simple docstring'''


										_UpperCAmelCase    :						str							=      super()._prepare_for_class(A_  ,   A_  ,   return_labels=A_		)

										if return_labels:
														if model_class.__name__ == "YolosForObjectDetection":
																		_UpperCAmelCase    :						Union[str, Any]							=      []
																		for i in range(self.model_tester.batch_size		):
																						_UpperCAmelCase    :						List[Any]							=      {}
																						_UpperCAmelCase    :						List[Any]							=      torch.ones(
																						    size=(self.model_tester.n_targets,)  ,   device=A_  ,   dtype=torch.long		)
																						_UpperCAmelCase    :						Tuple							=      torch.ones(
																						    self.model_tester.n_targets  ,   4  ,   device=A_  ,   dtype=torch.float		)
																						labels.append(A_		)
																		_UpperCAmelCase    :						Dict							=      labels

										return inputs_dict


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						Any							=      YolosModelTester(self		)
										_UpperCAmelCase    :						List[str]							=      ConfigTester(self  ,   config_class=A_  ,   has_text_modality=A_  ,   hidden_size=37		)


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										self.config_tester.run_common_tests()


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										pass


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase						,							_UpperCAmelCase    :						Any							=      self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														_UpperCAmelCase    :						List[Any]							=      model_class(A_		)
														self.assertIsInstance(model.get_input_embeddings()  ,   (nn.Module)		)
														_UpperCAmelCase    :						int							=      model.get_output_embeddings()
														self.assertTrue(x is None or isinstance(A_  ,   nn.Linear		)		)


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase						,							_UpperCAmelCase    :						Optional[Any]							=      self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														_UpperCAmelCase    :						str							=      model_class(A_		)
														_UpperCAmelCase    :						Dict							=      inspect.signature(model.forward		)
														# signature.parameters is an OrderedDict => so arg_names order is deterministic
														_UpperCAmelCase    :						int							=      [*signature.parameters.keys()]

														_UpperCAmelCase    :						Optional[int]							=      ["pixel_values"]
														self.assertListEqual(arg_names[:1]  ,   A_		)


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						int							=      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*A_		)


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase						,							_UpperCAmelCase    :						Any							=      self.model_tester.prepare_config_and_inputs_for_common()
										_UpperCAmelCase    :						Union[str, Any]							=      True

										# in YOLOS, the seq_len is different
										_UpperCAmelCase    :						Dict							=      self.model_tester.expected_seq_len
										for model_class in self.all_model_classes:
														_UpperCAmelCase    :						Union[str, Any]							=      True
														_UpperCAmelCase    :						Union[str, Any]							=      False
														_UpperCAmelCase    :						List[Any]							=      True
														_UpperCAmelCase    :						Dict							=      model_class(A_		)
														model.to(A_		)
														model.eval()
														with torch.no_grad():
																		_UpperCAmelCase    :						List[Any]							=      model(**self._prepare_for_class(A_  ,   A_		)		)
														_UpperCAmelCase    :						Optional[Any]							=      outputs.attentions
														self.assertEqual(len(A_		)  ,   self.model_tester.num_hidden_layers		)

														# check that output_attentions also work using config
														del inputs_dict["output_attentions"]
														_UpperCAmelCase    :						List[str]							=      True
														_UpperCAmelCase    :						Tuple							=      model_class(A_		)
														model.to(A_		)
														model.eval()
														with torch.no_grad():
																		_UpperCAmelCase    :						Dict							=      model(**self._prepare_for_class(A_  ,   A_		)		)
														_UpperCAmelCase    :						Any							=      outputs.attentions
														self.assertEqual(len(A_		)  ,   self.model_tester.num_hidden_layers		)

														self.assertListEqual(
														    list(attentions[0].shape[-3:]		)  ,   [self.model_tester.num_attention_heads, seq_len, seq_len]  ,   )
														_UpperCAmelCase    :						Any							=      len(A_		)

														# Check attention is always last and order is fine
														_UpperCAmelCase    :						int							=      True
														_UpperCAmelCase    :						Any							=      True
														_UpperCAmelCase    :						Union[str, Any]							=      model_class(A_		)
														model.to(A_		)
														model.eval()
														with torch.no_grad():
																		_UpperCAmelCase    :						Union[str, Any]							=      model(**self._prepare_for_class(A_  ,   A_		)		)

														_UpperCAmelCase    :						List[Any]							=      1
														self.assertEqual(out_len + added_hidden_states  ,   len(A_		)		)

														_UpperCAmelCase    :						str							=      outputs.attentions

														self.assertEqual(len(A_		)  ,   self.model_tester.num_hidden_layers		)
														self.assertListEqual(
														    list(self_attentions[0].shape[-3:]		)  ,   [self.model_tester.num_attention_heads, seq_len, seq_len]  ,   )


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										def check_hidden_states_output(A_  ,   A_  ,   A_		):
														_UpperCAmelCase    :						Optional[int]							=      model_class(A_		)
														model.to(A_		)
														model.eval()

														with torch.no_grad():
																		_UpperCAmelCase    :						Dict							=      model(**self._prepare_for_class(A_  ,   A_		)		)

														_UpperCAmelCase    :						List[str]							=      outputs.hidden_states

														_UpperCAmelCase    :						Tuple							=      getattr(
														    self.model_tester  ,   "expected_num_hidden_layers"  ,   self.model_tester.num_hidden_layers + 1		)
														self.assertEqual(len(A_		)  ,   A_		)

														# YOLOS has a different seq_length
														_UpperCAmelCase    :						Dict							=      self.model_tester.expected_seq_len

														self.assertListEqual(
														    list(hidden_states[0].shape[-2:]		)  ,   [seq_length, self.model_tester.hidden_size]  ,   )

										_UpperCAmelCase						,							_UpperCAmelCase    :						int							=      self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														_UpperCAmelCase    :						Tuple							=      True
														check_hidden_states_output(A_  ,   A_  ,   A_		)

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														_UpperCAmelCase    :						Tuple							=      True

														check_hidden_states_output(A_  ,   A_  ,   A_		)


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[Any]							=      self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_object_detection(*A_		)





						@slow
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														_UpperCAmelCase    :						Union[str, Any]							=      YolosModel.from_pretrained(A_		)
														self.assertIsNotNone(A_		)







def 							__SCREAMING_SNAKE_CASE							(			)				->    Dict:
				_UpperCAmelCase    :						Dict							=      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
				return image





@require_torch
@require_vision
class 			a					(		unittest.TestCase			):


						@cached_property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return AutoImageProcessor.from_pretrained("hustvl/yolos-small"		) if is_vision_available() else None





						@slow
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						Any							=      YolosForObjectDetection.from_pretrained("hustvl/yolos-small"		).to(A_		)

										_UpperCAmelCase    :						Optional[Any]							=      self.default_image_processor
										_UpperCAmelCase    :						Any							=      prepare_img()
										_UpperCAmelCase    :						Dict							=      image_processor(images=A_  ,   return_tensors="pt"		).to(A_		)

										# forward pass
										with torch.no_grad():
														_UpperCAmelCase    :						List[str]							=      model(inputs.pixel_values		)

										# verify outputs
										_UpperCAmelCase    :						Union[str, Any]							=      torch.Size((1, 100, 92)		)
										self.assertEqual(outputs.logits.shape  ,   A_		)

										_UpperCAmelCase    :						str							=      torch.tensor(
										    [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]]  ,   device=A_  ,   )
										_UpperCAmelCase    :						int							=      torch.tensor(
										    [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]]  ,   device=A_		)
										self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]  ,   A_  ,   atol=1e-4		)		)
										self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]  ,   A_  ,   atol=1e-4		)		)

										# verify postprocessing
										_UpperCAmelCase    :						List[Any]							=      image_processor.post_process_object_detection(
										    A_  ,   threshold=0.3  ,   target_sizes=[image.size[::-1]]		)[0]
										_UpperCAmelCase    :						Tuple							=      torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]		).to(A_		)
										_UpperCAmelCase    :						List[str]							=      [75, 75, 17, 63, 17]
										_UpperCAmelCase    :						Optional[Any]							=      torch.tensor([3_35.06_09, 79.38_48, 3_75.42_16, 1_87.24_95]		).to(A_		)

										self.assertEqual(len(results["scores"]		)  ,   5		)
										self.assertTrue(torch.allclose(results["scores"]  ,   A_  ,   atol=1e-4		)		)
										self.assertSequenceEqual(results["labels"].tolist()  ,   A_		)
										self.assertTrue(torch.allclose(results["boxes"][0, :]  ,   A_		)		)





import argparse

import torch

from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt


if __name__ == "__main__":
					SCREAMING_SNAKE_CASE_            = 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.',
					)
					SCREAMING_SNAKE_CASE_            = parser.parse_args()

					SCREAMING_SNAKE_CASE_            = 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)


