
"""simple docstring"""





import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu



class __lowerCAmelCase					(       unittest.TestCase   ):




			"""simple docstring"""







			def   lowerCamelCase__  (					self    :       Optional[Any]						)   ->			List[str]:







								"""simple docstring"""
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()




			@property
			def   lowerCamelCase__  (					self    :       List[str]						)   ->			Any:







								"""simple docstring"""
								A_								=    1
								A_								=    3
								A_								=    (32, 32)

								A_								=    floats_tensor((batch_size, num_channels) + sizes							, rng=random.Random(0						)						).to(_snake_case						)
								return image




			@property
			def   lowerCamelCase__  (					self    :       List[str]						)   ->			Tuple:







								"""simple docstring"""
								torch.manual_seed(0						)
								A_								=    UNetaDConditionModel(
								    block_out_channels=(32, 64)							, layers_per_block=2							, sample_size=32							, in_channels=4							, out_channels=4							, down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")							, up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")							, cross_attention_dim=32							, )
								return model




			@property
			def   lowerCamelCase__  (					self    :       Optional[int]						)   ->			str:







								"""simple docstring"""
								torch.manual_seed(0						)
								A_								=    AutoencoderKL(
								    block_out_channels=[32, 64]							, in_channels=3							, out_channels=3							, down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]							, up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]							, latent_channels=4							, )
								return model




			@property
			def   lowerCamelCase__  (					self    :       str						)   ->			Dict:







								"""simple docstring"""
								torch.manual_seed(0						)
								A_								=    CLIPTextConfig(
								    bos_token_id=0							, eos_token_id=2							, hidden_size=32							, intermediate_size=37							, layer_norm_eps=1e-05							, num_attention_heads=4							, num_hidden_layers=5							, pad_token_id=1							, vocab_size=1_000							, )
								return CLIPTextModel(_snake_case						)




			@property
			def   lowerCamelCase__  (					self    :       str						)   ->			int:







								"""simple docstring"""
								def extract(*_snake_case    :       Tuple							, **_snake_case    :       Any						):



													class __lowerCAmelCase					:




																"""simple docstring"""







																def __init__(					self    :       Optional[Any]						)   ->			Tuple:







																					"""simple docstring"""
																					A_								=    torch.ones([0]						)






																def   lowerCamelCase__  (					self    :       Optional[int]							, _snake_case    :       int						)   ->			Optional[int]:







																					"""simple docstring"""
																					self.pixel_values.to(_snake_case						)
																					return self





													return Out()

								return extract




			def   lowerCamelCase__  (					self    :       List[Any]						)   ->			Union[str, Any]:







								"""simple docstring"""
								A_								=    "cpu"  # ensure determinism for the device-dependent torch.Generator
								A_								=    self.dummy_cond_unet
								A_								=    DDIMScheduler(
								    beta_start=0.0_0_0_8_5							, beta_end=0.0_1_2							, beta_schedule="scaled_linear"							, clip_sample=_snake_case							, set_alpha_to_one=_snake_case							, )

								A_								=    self.dummy_vae
								A_								=    self.dummy_text_encoder
								A_								=    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)

								# make sure here that pndm scheduler skips prk
								A_								=    StableDiffusionPipeline(
								    unet=_snake_case							, scheduler=_snake_case							, vae=_snake_case							, text_encoder=_snake_case							, tokenizer=_snake_case							, safety_checker=_snake_case							, feature_extractor=self.dummy_extractor							, )
								A_								=    sd_pipe.to(_snake_case						)
								sd_pipe.set_progress_bar_config(disable=_snake_case						)

								A_								=    "A painting of a squirrel eating a burger"

								A_								=    torch.Generator(device=_snake_case						).manual_seed(0						)
								A_								=    sd_pipe([prompt]							, generator=_snake_case							, guidance_scale=6.0							, num_inference_steps=2							, output_type="np"						)
								A_								=    output.images

								A_								=    torch.Generator(device=_snake_case						).manual_seed(0						)
								A_								=    sd_pipe(
								    [prompt]							, generator=_snake_case							, guidance_scale=6.0							, num_inference_steps=2							, output_type="np"							, return_dict=_snake_case							, )[0]

								A_								=    image[0, -3:, -3:, -1]
								A_								=    image_from_tuple[0, -3:, -3:, -1]

								assert image.shape == (1, 64, 64, 3)
								A_								=    np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4]						)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2
								assert np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < 1e-2




			def   lowerCamelCase__  (					self    :       Optional[Any]						)   ->			Any:







								"""simple docstring"""
								A_								=    "cpu"  # ensure determinism for the device-dependent torch.Generator
								A_								=    self.dummy_cond_unet
								A_								=    PNDMScheduler(skip_prk_steps=_snake_case						)
								A_								=    self.dummy_vae
								A_								=    self.dummy_text_encoder
								A_								=    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)

								# make sure here that pndm scheduler skips prk
								A_								=    StableDiffusionPipeline(
								    unet=_snake_case							, scheduler=_snake_case							, vae=_snake_case							, text_encoder=_snake_case							, tokenizer=_snake_case							, safety_checker=_snake_case							, feature_extractor=self.dummy_extractor							, )
								A_								=    sd_pipe.to(_snake_case						)
								sd_pipe.set_progress_bar_config(disable=_snake_case						)

								A_								=    "A painting of a squirrel eating a burger"
								A_								=    torch.Generator(device=_snake_case						).manual_seed(0						)
								A_								=    sd_pipe([prompt]							, generator=_snake_case							, guidance_scale=6.0							, num_inference_steps=2							, output_type="np"						)

								A_								=    output.images

								A_								=    torch.Generator(device=_snake_case						).manual_seed(0						)
								A_								=    sd_pipe(
								    [prompt]							, generator=_snake_case							, guidance_scale=6.0							, num_inference_steps=2							, output_type="np"							, return_dict=_snake_case							, )[0]

								A_								=    image[0, -3:, -3:, -1]
								A_								=    image_from_tuple[0, -3:, -3:, -1]

								assert image.shape == (1, 64, 64, 3)
								A_								=    np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3]						)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2
								assert np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < 1e-2




			def   lowerCamelCase__  (					self    :       Union[str, Any]						)   ->			List[str]:







								"""simple docstring"""
								A_								=    StableDiffusionPipeline.from_pretrained(
								    "hf-internal-testing/tiny-stable-diffusion-lms-pipe"							, safety_checker=_snake_case						)
								assert isinstance(_snake_case							, _snake_case						)
								assert isinstance(pipe.scheduler							, _snake_case						)
								assert pipe.safety_checker is None

								A_								=    pipe("example prompt"							, num_inference_steps=2						).images[0]
								assert image is not None

								# check that there's no error when saving a pipeline with one of the models being None
								with tempfile.TemporaryDirectory() as tmpdirname:
													pipe.save_pretrained(_snake_case						)
													A_								=    StableDiffusionPipeline.from_pretrained(_snake_case						)

								# sanity check that the pipeline still works
								assert pipe.safety_checker is None
								A_								=    pipe("example prompt"							, num_inference_steps=2						).images[0]
								assert image is not None






			@unittest.skipIf(torch_device != "cuda"							, "This test requires a GPU"						)
			def   lowerCamelCase__  (					self    :       Optional[int]						)   ->			Union[str, Any]:







								"""simple docstring"""
								A_								=    self.dummy_cond_unet
								A_								=    PNDMScheduler(skip_prk_steps=_snake_case						)
								A_								=    self.dummy_vae
								A_								=    self.dummy_text_encoder
								A_								=    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)

								# put models in fp16
								A_								=    unet.half()
								A_								=    vae.half()
								A_								=    bert.half()

								# make sure here that pndm scheduler skips prk
								A_								=    StableDiffusionPipeline(
								    unet=_snake_case							, scheduler=_snake_case							, vae=_snake_case							, text_encoder=_snake_case							, tokenizer=_snake_case							, safety_checker=_snake_case							, feature_extractor=self.dummy_extractor							, )
								A_								=    sd_pipe.to(_snake_case						)
								sd_pipe.set_progress_bar_config(disable=_snake_case						)

								A_								=    "A painting of a squirrel eating a burger"
								A_								=    sd_pipe([prompt]							, num_inference_steps=2							, output_type="np"						).images

								assert image.shape == (1, 64, 64, 3)





@nightly
@require_torch_gpu
class __lowerCAmelCase					(       unittest.TestCase   ):




			"""simple docstring"""







			def   lowerCamelCase__  (					self    :       List[Any]						)   ->			Any:







								"""simple docstring"""
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()




			def   lowerCamelCase__  (					self    :       int						)   ->			Tuple:







								"""simple docstring"""
								A_								=    StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"							, safety_checker=_snake_case						)
								A_								=    LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config						)
								A_								=    sd_pipe.to(_snake_case						)
								sd_pipe.set_progress_bar_config(disable=_snake_case						)

								A_								=    (
								    "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle"
								    " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with"
								    " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and"
								    " children from bahnhof zoo, detailed "
								)
								A_								=    4_003_660_346
								A_								=    7

								# without safety guidance (sld_guidance_scale = 0)
								A_								=    torch.manual_seed(_snake_case						)
								A_								=    sd_pipe(
								    [prompt]							, generator=_snake_case							, guidance_scale=_snake_case							, num_inference_steps=50							, output_type="np"							, width=512							, height=512							, sld_guidance_scale=0							, )

								A_								=    output.images
								A_								=    image[0, -3:, -3:, -1]
								A_								=    [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6]

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2

								# without safety guidance (strong configuration)
								A_								=    torch.manual_seed(_snake_case						)
								A_								=    sd_pipe(
								    [prompt]							, generator=_snake_case							, guidance_scale=_snake_case							, num_inference_steps=50							, output_type="np"							, width=512							, height=512							, sld_guidance_scale=2_000							, sld_warmup_steps=7							, sld_threshold=0.0_2_5							, sld_momentum_scale=0.5							, sld_mom_beta=0.7							, )

								A_								=    output.images
								A_								=    image[0, -3:, -3:, -1]
								A_								=    [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9]

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2




			def   lowerCamelCase__  (					self    :       str						)   ->			int:







								"""simple docstring"""
								A_								=    StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"							, safety_checker=_snake_case						)
								A_								=    LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config						)
								A_								=    sd_pipe.to(_snake_case						)
								sd_pipe.set_progress_bar_config(disable=_snake_case						)

								A_								=    "padme amidala taking a bath artwork, safe for work, no nudity"
								A_								=    2_734_971_755
								A_								=    7

								A_								=    torch.manual_seed(_snake_case						)
								A_								=    sd_pipe(
								    [prompt]							, generator=_snake_case							, guidance_scale=_snake_case							, num_inference_steps=50							, output_type="np"							, width=512							, height=512							, sld_guidance_scale=0							, )

								A_								=    output.images
								A_								=    image[0, -3:, -3:, -1]
								A_								=    [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7]

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2

								A_								=    torch.manual_seed(_snake_case						)
								A_								=    sd_pipe(
								    [prompt]							, generator=_snake_case							, guidance_scale=_snake_case							, num_inference_steps=50							, output_type="np"							, width=512							, height=512							, sld_guidance_scale=2_000							, sld_warmup_steps=7							, sld_threshold=0.0_2_5							, sld_momentum_scale=0.5							, sld_mom_beta=0.7							, )

								A_								=    output.images
								A_								=    image[0, -3:, -3:, -1]
								A_								=    [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3]

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2






			def   lowerCamelCase__  (					self    :       Dict						)   ->			Optional[Any]:







								"""simple docstring"""
								A_								=    StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"						)
								A_								=    sd_pipe.to(_snake_case						)
								sd_pipe.set_progress_bar_config(disable=_snake_case						)

								A_								=    (
								    "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c."
								    " leyendecker"
								)
								A_								=    1_044_355_234
								A_								=    12

								A_								=    torch.manual_seed(_snake_case						)
								A_								=    sd_pipe(
								    [prompt]							, generator=_snake_case							, guidance_scale=_snake_case							, num_inference_steps=50							, output_type="np"							, width=512							, height=512							, sld_guidance_scale=0							, )

								A_								=    output.images
								A_								=    image[0, -3:, -3:, -1]
								A_								=    np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]						)

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-7

								A_								=    torch.manual_seed(_snake_case						)
								A_								=    sd_pipe(
								    [prompt]							, generator=_snake_case							, guidance_scale=_snake_case							, num_inference_steps=50							, output_type="np"							, width=512							, height=512							, sld_guidance_scale=2_000							, sld_warmup_steps=7							, sld_threshold=0.0_2_5							, sld_momentum_scale=0.5							, sld_mom_beta=0.7							, )

								A_								=    output.images
								A_								=    image[0, -3:, -3:, -1]
								A_								=    np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1]						)
								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2






"""simple docstring"""





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 __lowerCAmelCase					:




			"""simple docstring"""







			def __init__(					self    :       Union[str, Any]							, _snake_case    :       Optional[Any]							, _snake_case    :       Any=13							, _snake_case    :       Union[str, Any]=[30, 30]							, _snake_case    :       Optional[int]=2							, _snake_case    :       str=3							, _snake_case    :       List[str]=True							, _snake_case    :       Tuple=True							, _snake_case    :       Union[str, Any]=32							, _snake_case    :       List[str]=5							, _snake_case    :       str=4							, _snake_case    :       Tuple=37							, _snake_case    :       Tuple="gelu"							, _snake_case    :       str=0.1							, _snake_case    :       Tuple=0.1							, _snake_case    :       Optional[Any]=10							, _snake_case    :       Dict=0.0_2							, _snake_case    :       int=3							, _snake_case    :       Optional[int]=None							, _snake_case    :       str=8							, _snake_case    :       Dict=10							, )   ->			int:







								"""simple docstring"""
								A_								=    parent
								A_								=    batch_size
								A_								=    image_size
								A_								=    patch_size
								A_								=    num_channels
								A_								=    is_training
								A_								=    use_labels
								A_								=    hidden_size
								A_								=    num_hidden_layers
								A_								=    num_attention_heads
								A_								=    intermediate_size
								A_								=    hidden_act
								A_								=    hidden_dropout_prob
								A_								=    attention_probs_dropout_prob
								A_								=    type_sequence_label_size
								A_								=    initializer_range
								A_								=    num_labels
								A_								=    scope
								A_								=    n_targets
								A_								=    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
								A_								=    (image_size[1] // patch_size) * (image_size[0] // patch_size)
								A_								=    num_patches + 1 + self.num_detection_tokens




			def   lowerCamelCase__  (					self    :       Any						)   ->			str:







								"""simple docstring"""
								A_								=    floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]						)

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

								A_								=    self.get_config()

								return config, pixel_values, labels




			def   lowerCamelCase__  (					self    :       List[str]						)   ->			str:







								"""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=_snake_case							, initializer_range=self.initializer_range							, num_detection_tokens=self.num_detection_tokens							, num_labels=self.num_labels							, )




			def   lowerCamelCase__  (					self    :       Any							, _snake_case    :       Union[str, Any]							, _snake_case    :       Optional[Any]							, _snake_case    :       Union[str, Any]						)   ->			List[str]:







								"""simple docstring"""
								A_								=    YolosModel(config=_snake_case						)
								model.to(_snake_case						)
								model.eval()
								A_								=    model(_snake_case						)
								self.parent.assertEqual(
								    result.last_hidden_state.shape							, (self.batch_size, self.expected_seq_len, self.hidden_size)						)




			def   lowerCamelCase__  (					self    :       Tuple							, _snake_case    :       Tuple							, _snake_case    :       Optional[Any]							, _snake_case    :       Any						)   ->			Optional[int]:







								"""simple docstring"""
								A_								=    YolosForObjectDetection(_snake_case						)
								model.to(_snake_case						)
								model.eval()

								A_								=    model(pixel_values=_snake_case						)
								A_								=    model(_snake_case						)

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

								A_								=    model(pixel_values=_snake_case							, labels=_snake_case						)

								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   lowerCamelCase__  (					self    :       int						)   ->			Union[str, Any]:







								"""simple docstring"""
								A_								=    self.prepare_config_and_inputs()
								A_			,     A_			,     A_								=    config_and_inputs
								A_								=    {"pixel_values": pixel_values}
								return config, inputs_dict





@require_torch
class __lowerCAmelCase					(       _lowercase  ,					_lowercase  ,					unittest.TestCase   ):




			"""simple docstring"""







			snake_case						   =					(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
			snake_case						   =					(
			    {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {}
			)

			snake_case						   =					False
			snake_case						   =					False
			snake_case						   =					False
			snake_case						   =					False




			def   lowerCamelCase__  (					self    :       int							, _snake_case    :       Optional[int]							, _snake_case    :       Any							, _snake_case    :       Dict=False						)   ->			List[Any]:







								"""simple docstring"""
								A_								=    super()._prepare_for_class(_snake_case							, _snake_case							, return_labels=_snake_case						)

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

								return inputs_dict




			def   lowerCamelCase__  (					self    :       Tuple						)   ->			Union[str, Any]:







								"""simple docstring"""
								A_								=    YolosModelTester(self						)
								A_								=    ConfigTester(self							, config_class=_snake_case							, has_text_modality=_snake_case							, hidden_size=37						)




			def   lowerCamelCase__  (					self    :       List[Any]						)   ->			str:







								"""simple docstring"""
								self.config_tester.run_common_tests()




			def   lowerCamelCase__  (					self    :       Optional[Any]						)   ->			List[str]:







								"""simple docstring"""
								# YOLOS does not use inputs_embeds
								pass




			def   lowerCamelCase__  (					self    :       Dict						)   ->			List[str]:







								"""simple docstring"""
								A_			,     A_								=    self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													A_								=    model_class(_snake_case						)
													self.assertIsInstance(model.get_input_embeddings()							, (nn.Module)						)
													A_								=    model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_snake_case							, nn.Linear						)						)




			def   lowerCamelCase__  (					self    :       List[Any]						)   ->			List[str]:







								"""simple docstring"""
								A_			,     A_								=    self.model_tester.prepare_config_and_inputs_for_common()

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

													A_								=    ["pixel_values"]
													self.assertListEqual(arg_names[:1]							, _snake_case						)




			def   lowerCamelCase__  (					self    :       List[str]						)   ->			Tuple:







								"""simple docstring"""
								A_								=    self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case						)




			def   lowerCamelCase__  (					self    :       Union[str, Any]						)   ->			List[Any]:







								"""simple docstring"""
								A_			,     A_								=    self.model_tester.prepare_config_and_inputs_for_common()
								A_								=    True

								# in YOLOS, the seq_len is different
								A_								=    self.model_tester.expected_seq_len
								for model_class in self.all_model_classes:
													A_								=    True
													A_								=    False
													A_								=    True
													A_								=    model_class(_snake_case						)
													model.to(_snake_case						)
													model.eval()
													with torch.no_grad():
																		A_								=    model(**self._prepare_for_class(_snake_case							, _snake_case						)						)
													A_								=    outputs.attentions
													self.assertEqual(len(_snake_case						)							, self.model_tester.num_hidden_layers						)

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

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

													# Check attention is always last and order is fine
													A_								=    True
													A_								=    True
													A_								=    model_class(_snake_case						)
													model.to(_snake_case						)
													model.eval()
													with torch.no_grad():
																		A_								=    model(**self._prepare_for_class(_snake_case							, _snake_case						)						)

													A_								=    1
													self.assertEqual(out_len + added_hidden_states							, len(_snake_case						)						)

													A_								=    outputs.attentions

													self.assertEqual(len(_snake_case						)							, 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   lowerCamelCase__  (					self    :       Any						)   ->			List[Any]:







								"""simple docstring"""
								def check_hidden_states_output(_snake_case    :       str							, _snake_case    :       Dict							, _snake_case    :       Dict						):
													A_								=    model_class(_snake_case						)
													model.to(_snake_case						)
													model.eval()

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

													A_								=    outputs.hidden_states

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

													# YOLOS has a different seq_length
													A_								=    self.model_tester.expected_seq_len

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

								A_			,     A_								=    self.model_tester.prepare_config_and_inputs_for_common()

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

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													A_								=    True

													check_hidden_states_output(_snake_case							, _snake_case							, _snake_case						)




			def   lowerCamelCase__  (					self    :       Dict						)   ->			Any:







								"""simple docstring"""
								A_								=    self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*_snake_case						)






			@slow
			def   lowerCamelCase__  (					self    :       Optional[Any]						)   ->			Optional[Any]:







								"""simple docstring"""
								for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													A_								=    YolosModel.from_pretrained(_snake_case						)
													self.assertIsNotNone(_snake_case						)





def 				A_  ():

					'''simple docstring'''





					A_								=    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
					return image




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




			"""simple docstring"""







			@cached_property
			def   lowerCamelCase__  (					self    :       str						)   ->			Any:







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






			@slow
			def   lowerCamelCase__  (					self    :       str						)   ->			Union[str, Any]:







								"""simple docstring"""
								A_								=    YolosForObjectDetection.from_pretrained("hustvl/yolos-small"						).to(_snake_case						)

								A_								=    self.default_image_processor
								A_								=    prepare_img()
								A_								=    image_processor(images=_snake_case							, return_tensors="pt"						).to(_snake_case						)

								# forward pass
								with torch.no_grad():
													A_								=    model(inputs.pixel_values						)

								# verify outputs
								A_								=    torch.Size((1, 100, 92)						)
								self.assertEqual(outputs.logits.shape							, _snake_case						)

								A_								=    torch.tensor(
								    [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]]							, device=_snake_case							, )
								A_								=    torch.tensor(
								    [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]]							, device=_snake_case						)
								self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]							, _snake_case							, atol=1e-4						)						)
								self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]							, _snake_case							, atol=1e-4						)						)

								# verify postprocessing
								A_								=    image_processor.post_process_object_detection(
								    _snake_case							, threshold=0.3							, target_sizes=[image.size[::-1]]						)[0]
								A_								=    torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1]						).to(_snake_case						)
								A_								=    [75, 75, 17, 63, 17]
								A_								=    torch.tensor([3_3_5.0_6_0_9, 7_9.3_8_4_8, 3_7_5.4_2_1_6, 1_8_7.2_4_9_5]						).to(_snake_case						)

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




