from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block
@dataclass
class   _lowerCAmelCase		(     __SCREAMING_SNAKE_CASE				):
							_UpperCAmelCase						    =     42


class   _lowerCAmelCase		(     nn.Module				):







							def __init__(				self     :    Optional[int]	,					__snake_case     :    Optional[int]=3	,					__snake_case     :    Optional[int]=3	,					__snake_case     :    Optional[Any]=("DownEncoderBlock2D",)	,					__snake_case     :    Tuple=(64,)	,					__snake_case     :    Optional[int]=2	,					__snake_case     :    List[Any]=32	,					__snake_case     :    Dict="silu"	,					__snake_case     :    int=True	,					):
										super().__init__()
										lowerCamelCase						:Optional[Any]						  =     layers_per_block

										lowerCamelCase						:List[str]						  =     torch.nn.Convad(
										    __snake_case	,					block_out_channels[0]	,					kernel_size=3	,					stride=1	,					padding=1	,					)

										lowerCamelCase						:Optional[int]						  =     None
										lowerCamelCase						:str						  =     nn.ModuleList([]		)

										# down
										lowerCamelCase						:Tuple						  =     block_out_channels[0]
										for i, down_block_type in enumerate(__snake_case		):
													lowerCamelCase						:Union[str, Any]						  =     output_channel
													lowerCamelCase						:Tuple						  =     block_out_channels[i]
													lowerCamelCase						:Dict						  =     i == len(__snake_case		) - 1

													lowerCamelCase						:int						  =     get_down_block(
													    __snake_case	,					num_layers=self.layers_per_block	,					in_channels=__snake_case	,					out_channels=__snake_case	,					add_downsample=not is_final_block	,					resnet_eps=1e-6	,					downsample_padding=0	,					resnet_act_fn=__snake_case	,					resnet_groups=__snake_case	,					attention_head_dim=__snake_case	,					temb_channels=__snake_case	,					)
													self.down_blocks.append(__snake_case		)

										# mid
										lowerCamelCase						:List[Any]						  =     UNetMidBlockaD(
										    in_channels=block_out_channels[-1]	,					resnet_eps=1e-6	,					resnet_act_fn=__snake_case	,					output_scale_factor=1	,					resnet_time_scale_shift='''default'''	,					attention_head_dim=block_out_channels[-1]	,					resnet_groups=__snake_case	,					temb_channels=__snake_case	,					)

										# out
										lowerCamelCase						:Optional[int]						  =     nn.GroupNorm(num_channels=block_out_channels[-1]	,					num_groups=__snake_case	,					eps=1e-6		)
										lowerCamelCase						:Union[str, Any]						  =     nn.SiLU()

										lowerCamelCase						:Any						  =     2 * out_channels if double_z else out_channels
										lowerCamelCase						:Optional[int]						  =     nn.Convad(block_out_channels[-1]	,					__snake_case	,					3	,					padding=1		)

										lowerCamelCase						:str						  =     False







							def 				snake_case  (				self     :    str	,					__snake_case     :    Optional[Any]		):
										lowerCamelCase						:Optional[int]						  =     x
										lowerCamelCase						:Optional[Any]						  =     self.conv_in(__snake_case		)

										if self.training and self.gradient_checkpointing:

													def create_custom_forward(__snake_case     :    Optional[int]		):
																def custom_forward(*__snake_case     :    Union[str, Any]		):
																			return module(*__snake_case		)

																return custom_forward

													# down
													if is_torch_version('''>='''	,					'''1.11.0'''		):
																for down_block in self.down_blocks:
																			lowerCamelCase						:List[str]						  =     torch.utils.checkpoint.checkpoint(
																			    create_custom_forward(__snake_case		)	,					__snake_case	,					use_reentrant=__snake_case		)
																# middle
																lowerCamelCase						:int						  =     torch.utils.checkpoint.checkpoint(
																    create_custom_forward(self.mid_block		)	,					__snake_case	,					use_reentrant=__snake_case		)
													else:
																for down_block in self.down_blocks:
																			lowerCamelCase						:Optional[int]						  =     torch.utils.checkpoint.checkpoint(create_custom_forward(__snake_case		)	,					__snake_case		)
																# middle
																lowerCamelCase						:Tuple						  =     torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block		)	,					__snake_case		)

										else:
													# down
													for down_block in self.down_blocks:
																lowerCamelCase						:Optional[Any]						  =     down_block(__snake_case		)

													# middle
													lowerCamelCase						:List[str]						  =     self.mid_block(__snake_case		)

										# post-process
										lowerCamelCase						:Tuple						  =     self.conv_norm_out(__snake_case		)
										lowerCamelCase						:List[str]						  =     self.conv_act(__snake_case		)
										lowerCamelCase						:Tuple						  =     self.conv_out(__snake_case		)

										return sample


class   _lowerCAmelCase		(     nn.Module				):







							def __init__(				self     :    List[str]	,					__snake_case     :    List[Any]=3	,					__snake_case     :    Tuple=3	,					__snake_case     :    Optional[int]=("UpDecoderBlock2D",)	,					__snake_case     :    Tuple=(64,)	,					__snake_case     :    str=2	,					__snake_case     :    Optional[int]=32	,					__snake_case     :    List[str]="silu"	,					__snake_case     :    List[Any]="group"	,					):
										super().__init__()
										lowerCamelCase						:str						  =     layers_per_block

										lowerCamelCase						:Tuple						  =     nn.Convad(
										    __snake_case	,					block_out_channels[-1]	,					kernel_size=3	,					stride=1	,					padding=1	,					)

										lowerCamelCase						:Union[str, Any]						  =     None
										lowerCamelCase						:Tuple						  =     nn.ModuleList([]		)

										lowerCamelCase						:str						  =     in_channels if norm_type == '''spatial''' else None

										# mid
										lowerCamelCase						:str						  =     UNetMidBlockaD(
										    in_channels=block_out_channels[-1]	,					resnet_eps=1e-6	,					resnet_act_fn=__snake_case	,					output_scale_factor=1	,					resnet_time_scale_shift='''default''' if norm_type == '''group''' else norm_type	,					attention_head_dim=block_out_channels[-1]	,					resnet_groups=__snake_case	,					temb_channels=__snake_case	,					)

										# up
										lowerCamelCase						:Union[str, Any]						  =     list(reversed(__snake_case		)		)
										lowerCamelCase						:Optional[Any]						  =     reversed_block_out_channels[0]
										for i, up_block_type in enumerate(__snake_case		):
													lowerCamelCase						:Optional[Any]						  =     output_channel
													lowerCamelCase						:str						  =     reversed_block_out_channels[i]

													lowerCamelCase						:int						  =     i == len(__snake_case		) - 1

													lowerCamelCase						:List[Any]						  =     get_up_block(
													    __snake_case	,					num_layers=self.layers_per_block + 1	,					in_channels=__snake_case	,					out_channels=__snake_case	,					prev_output_channel=__snake_case	,					add_upsample=not is_final_block	,					resnet_eps=1e-6	,					resnet_act_fn=__snake_case	,					resnet_groups=__snake_case	,					attention_head_dim=__snake_case	,					temb_channels=__snake_case	,					resnet_time_scale_shift=__snake_case	,					)
													self.up_blocks.append(__snake_case		)
													lowerCamelCase						:Optional[Any]						  =     output_channel

										# out
										if norm_type == "spatial":
													lowerCamelCase						:Union[str, Any]						  =     SpatialNorm(block_out_channels[0]	,					__snake_case		)
										else:
													lowerCamelCase						:str						  =     nn.GroupNorm(num_channels=block_out_channels[0]	,					num_groups=__snake_case	,					eps=1e-6		)
										lowerCamelCase						:Any						  =     nn.SiLU()
										lowerCamelCase						:Optional[int]						  =     nn.Convad(block_out_channels[0]	,					__snake_case	,					3	,					padding=1		)

										lowerCamelCase						:str						  =     False







							def 				snake_case  (				self     :    str	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    Optional[Any]=None		):
										lowerCamelCase						:str						  =     z
										lowerCamelCase						:List[Any]						  =     self.conv_in(__snake_case		)

										lowerCamelCase						:int						  =     next(iter(self.up_blocks.parameters()		)		).dtype
										if self.training and self.gradient_checkpointing:

													def create_custom_forward(__snake_case     :    Any		):
																def custom_forward(*__snake_case     :    Optional[int]		):
																			return module(*__snake_case		)

																return custom_forward

													if is_torch_version('''>='''	,					'''1.11.0'''		):
																# middle
																lowerCamelCase						:int						  =     torch.utils.checkpoint.checkpoint(
																    create_custom_forward(self.mid_block		)	,					__snake_case	,					__snake_case	,					use_reentrant=__snake_case		)
																lowerCamelCase						:Optional[int]						  =     sample.to(__snake_case		)

																# up
																for up_block in self.up_blocks:
																			lowerCamelCase						:List[Any]						  =     torch.utils.checkpoint.checkpoint(
																			    create_custom_forward(__snake_case		)	,					__snake_case	,					__snake_case	,					use_reentrant=__snake_case		)
													else:
																# middle
																lowerCamelCase						:str						  =     torch.utils.checkpoint.checkpoint(
																    create_custom_forward(self.mid_block		)	,					__snake_case	,					__snake_case		)
																lowerCamelCase						:Tuple						  =     sample.to(__snake_case		)

																# up
																for up_block in self.up_blocks:
																			lowerCamelCase						:str						  =     torch.utils.checkpoint.checkpoint(create_custom_forward(__snake_case		)	,					__snake_case	,					__snake_case		)
										else:
													# middle
													lowerCamelCase						:str						  =     self.mid_block(__snake_case	,					__snake_case		)
													lowerCamelCase						:Optional[int]						  =     sample.to(__snake_case		)

													# up
													for up_block in self.up_blocks:
																lowerCamelCase						:Optional[Any]						  =     up_block(__snake_case	,					__snake_case		)

        # post-process
										if latent_embeds is None:
													lowerCamelCase						:Optional[int]						  =     self.conv_norm_out(__snake_case		)
										else:
													lowerCamelCase						:List[Any]						  =     self.conv_norm_out(__snake_case	,					__snake_case		)
										lowerCamelCase						:Tuple						  =     self.conv_act(__snake_case		)
										lowerCamelCase						:Union[str, Any]						  =     self.conv_out(__snake_case		)

										return sample


class   _lowerCAmelCase		(     nn.Module				):







							def __init__(				self     :    Optional[int]	,					__snake_case     :    Tuple	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    int	,					__snake_case     :    Optional[Any]=None	,					__snake_case     :    Optional[Any]="random"	,					__snake_case     :    Any=False	,					__snake_case     :    int=True		):
										super().__init__()
										lowerCamelCase						:List[str]						  =     n_e
										lowerCamelCase						:Dict						  =     vq_embed_dim
										lowerCamelCase						:int						  =     beta
										lowerCamelCase						:Optional[int]						  =     legacy

										lowerCamelCase						:Tuple						  =     nn.Embedding(self.n_e	,					self.vq_embed_dim		)
										self.embedding.weight.data.uniform_(-1.0 / self.n_e	,					1.0 / self.n_e		)

										lowerCamelCase						:Dict						  =     remap
										if self.remap is not None:
													self.register_buffer('''used'''	,					torch.tensor(np.load(self.remap		)		)		)
													lowerCamelCase						:Tuple						  =     self.used.shape[0]
													lowerCamelCase						:Tuple						  =     unknown_index  # "random" or "extra" or integer
													if self.unknown_index == "extra":
																lowerCamelCase						:List[Any]						  =     self.re_embed
																lowerCamelCase						:str						  =     self.re_embed + 1
													print(
													    F"Remapping {self.n_e} indices to {self.re_embed} indices. "
													    F"Using {self.unknown_index} for unknown indices."		)
										else:
													lowerCamelCase						:Dict						  =     n_e

										lowerCamelCase						:Optional[Any]						  =     sane_index_shape







							def 				snake_case  (				self     :    Optional[Any]	,					__snake_case     :    Optional[Any]		):
										lowerCamelCase						:Dict						  =     inds.shape
										assert len(__snake_case		) > 1
										lowerCamelCase						:List[str]						  =     inds.reshape(ishape[0]	,					-1		)
										lowerCamelCase						:List[Any]						  =     self.used.to(__snake_case		)
										lowerCamelCase						:Any						  =     (inds[:, :, None] == used[None, None, ...]).long()
										lowerCamelCase						:int						  =     match.argmax(-1		)
										lowerCamelCase						:Any						  =     match.sum(2		) < 1
										if self.unknown_index == "random":
													lowerCamelCase						:Optional[int]						  =     torch.randint(0	,					self.re_embed	,					size=new[unknown].shape		).to(device=new.device		)
										else:
													lowerCamelCase						:List[Any]						  =     self.unknown_index
										return new.reshape(__snake_case		)







							def 				snake_case  (				self     :    Any	,					__snake_case     :    Optional[Any]		):
										lowerCamelCase						:Tuple						  =     inds.shape
										assert len(__snake_case		) > 1
										lowerCamelCase						:Optional[Any]						  =     inds.reshape(ishape[0]	,					-1		)
										lowerCamelCase						:List[Any]						  =     self.used.to(__snake_case		)
										if self.re_embed > self.used.shape[0]:  # extra token
													lowerCamelCase						:Union[str, Any]						  =     0  # simply set to zero
										lowerCamelCase						:Union[str, Any]						  =     torch.gather(used[None, :][inds.shape[0] * [0], :]	,					1	,					__snake_case		)
										return back.reshape(__snake_case		)







							def 				snake_case  (				self     :    Any	,					__snake_case     :    Dict		):
										# reshape z -> (batch, height, width, channel) and flatten
										lowerCamelCase						:Any						  =     z.permute(0	,					2	,					3	,					1		).contiguous()
										lowerCamelCase						:Optional[int]						  =     z.view(-1	,					self.vq_embed_dim		)

										# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
										lowerCamelCase						:int						  =     torch.argmin(torch.cdist(__snake_case	,					self.embedding.weight		)	,					dim=1		)

										lowerCamelCase						:List[str]						  =     self.embedding(__snake_case		).view(z.shape		)
										lowerCamelCase						:Optional[int]						  =     None
										lowerCamelCase						:Tuple						  =     None

										# compute loss for embedding
										if not self.legacy:
													lowerCamelCase						:Optional[Any]						  =     self.beta * torch.mean((z_q.detach() - z) ** 2		) + torch.mean((z_q - z.detach()) ** 2		)
										else:
													lowerCamelCase						:Tuple						  =     torch.mean((z_q.detach() - z) ** 2		) + self.beta * torch.mean((z_q - z.detach()) ** 2		)

										# preserve gradients
										lowerCamelCase						:List[Any]						  =     z + (z_q - z).detach()

										# reshape back to match original input shape
										lowerCamelCase						:Optional[int]						  =     z_q.permute(0	,					3	,					1	,					2		).contiguous()

										if self.remap is not None:
													lowerCamelCase						:Dict						  =     min_encoding_indices.reshape(z.shape[0]	,					-1		)  # add batch axis
													lowerCamelCase						:int						  =     self.remap_to_used(__snake_case		)
													lowerCamelCase						:Union[str, Any]						  =     min_encoding_indices.reshape(-1	,					1		)  # flatten

										if self.sane_index_shape:
													lowerCamelCase						:Tuple						  =     min_encoding_indices.reshape(z_q.shape[0]	,					z_q.shape[2]	,					z_q.shape[3]		)

										return z_q, loss, (perplexity, min_encodings, min_encoding_indices)







							def 				snake_case  (				self     :    str	,					__snake_case     :    List[Any]	,					__snake_case     :    Union[str, Any]		):
										# shape specifying (batch, height, width, channel)
										if self.remap is not None:
													lowerCamelCase						:Optional[int]						  =     indices.reshape(shape[0]	,					-1		)  # add batch axis
													lowerCamelCase						:Tuple						  =     self.unmap_to_all(__snake_case		)
													lowerCamelCase						:List[Any]						  =     indices.reshape(-1		)  # flatten again

										# get quantized latent vectors
										lowerCamelCase						:Union[str, Any]						  =     self.embedding(__snake_case		)

										if shape is not None:
													lowerCamelCase						:Optional[Any]						  =     z_q.view(__snake_case		)
													# reshape back to match original input shape
													lowerCamelCase						:Optional[int]						  =     z_q.permute(0	,					3	,					1	,					2		).contiguous()

										return z_q


class   _lowerCAmelCase		(     __SCREAMING_SNAKE_CASE				):







							def __init__(				self     :    Union[str, Any]	,					__snake_case     :    Optional[int]	,					__snake_case     :    str=False		):
										lowerCamelCase						:Any						  =     parameters
										lowerCamelCase  ,    lowerCamelCase						:List[str]						  =     torch.chunk(__snake_case	,					2	,					dim=1		)
										lowerCamelCase						:List[Any]						  =     torch.clamp(self.logvar	,					-3_0.0	,					2_0.0		)
										lowerCamelCase						:str						  =     deterministic
										lowerCamelCase						:Dict						  =     torch.exp(0.5 * self.logvar		)
										lowerCamelCase						:Optional[int]						  =     torch.exp(self.logvar		)
										if self.deterministic:
													lowerCamelCase						:Optional[int]						  =     torch.zeros_like(
													    self.mean	,					device=self.parameters.device	,					dtype=self.parameters.dtype		)







							def 				snake_case  (				self     :    str	,					__snake_case     :    Optional[torch.Generator] = None		):
										# make sure sample is on the same device as the parameters and has same dtype
										lowerCamelCase						:Tuple						  =     randn_tensor(
										    self.mean.shape	,					generator=__snake_case	,					device=self.parameters.device	,					dtype=self.parameters.dtype		)
										lowerCamelCase						:str						  =     self.mean + self.std * sample
										return x







							def 				snake_case  (				self     :    List[str]	,					__snake_case     :    Optional[Any]=None		):
										if self.deterministic:
													return torch.Tensor([0.0]		)
										else:
													if other is None:
																return 0.5 * torch.sum(torch.pow(self.mean	,					2		) + self.var - 1.0 - self.logvar	,					dim=[1, 2, 3]		)
													else:
																return 0.5 * torch.sum(
																    torch.pow(self.mean - other.mean	,					2		) / other.var
																    + self.var / other.var
																    - 1.0
																    - self.logvar
																    + other.logvar	,					dim=[1, 2, 3]	,					)







							def 				snake_case  (				self     :    List[str]	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    Optional[Any]=[1, 2, 3]		):
										if self.deterministic:
													return torch.Tensor([0.0]		)
										lowerCamelCase						:List[str]						  =     np.log(2.0 * np.pi		)
										return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean	,					2		) / self.var	,					dim=__snake_case		)







							def 				snake_case  (				self     :    str		):
										return self.mean




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		:







							def __init__(				self     :    Any	,					__snake_case     :    Optional[int]	,					__snake_case     :    int=13	,					__snake_case     :    str=[30, 30]	,					__snake_case     :    Tuple=2	,					__snake_case     :    Optional[Any]=3	,					__snake_case     :    int=True	,					__snake_case     :    Tuple=True	,					__snake_case     :    List[Any]=32	,					__snake_case     :    int=5	,					__snake_case     :    Optional[Any]=4	,					__snake_case     :    Union[str, Any]=37	,					__snake_case     :    str="gelu"	,					__snake_case     :    Tuple=0.1	,					__snake_case     :    List[Any]=0.1	,					__snake_case     :    Union[str, Any]=10	,					__snake_case     :    str=0.0_2	,					__snake_case     :    Union[str, Any]=3	,					__snake_case     :    Union[str, Any]=None	,					__snake_case     :    List[str]=8	,					__snake_case     :    Any=10	,					):
										lowerCamelCase						:Optional[Any]						  =     parent
										lowerCamelCase						:List[Any]						  =     batch_size
										lowerCamelCase						:Any						  =     image_size
										lowerCamelCase						:Union[str, Any]						  =     patch_size
										lowerCamelCase						:Any						  =     num_channels
										lowerCamelCase						:List[Any]						  =     is_training
										lowerCamelCase						:Optional[Any]						  =     use_labels
										lowerCamelCase						:Any						  =     hidden_size
										lowerCamelCase						:List[Any]						  =     num_hidden_layers
										lowerCamelCase						:List[str]						  =     num_attention_heads
										lowerCamelCase						:Tuple						  =     intermediate_size
										lowerCamelCase						:List[str]						  =     hidden_act
										lowerCamelCase						:List[str]						  =     hidden_dropout_prob
										lowerCamelCase						:Any						  =     attention_probs_dropout_prob
										lowerCamelCase						:List[Any]						  =     type_sequence_label_size
										lowerCamelCase						:Optional[int]						  =     initializer_range
										lowerCamelCase						:List[Any]						  =     num_labels
										lowerCamelCase						:Any						  =     scope
										lowerCamelCase						:Union[str, Any]						  =     n_targets
										lowerCamelCase						:Optional[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
										lowerCamelCase						:Tuple						  =     (image_size[1] // patch_size) * (image_size[0] // patch_size)
										lowerCamelCase						:str						  =     num_patches + 1 + self.num_detection_tokens







							def 				snake_case  (				self     :    List[str]		):
										lowerCamelCase						:str						  =     floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]		)

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

										lowerCamelCase						:str						  =     self.get_config()

										return config, pixel_values, labels







							def 				snake_case  (				self     :    Union[str, Any]		):
										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 				snake_case  (				self     :    Tuple	,					__snake_case     :    Tuple	,					__snake_case     :    Tuple	,					__snake_case     :    Any		):
										lowerCamelCase						:Optional[Any]						  =     YolosModel(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:Union[str, Any]						  =     model(__snake_case		)
										self.parent.assertEqual(
										    result.last_hidden_state.shape	,					(self.batch_size, self.expected_seq_len, self.hidden_size)		)







							def 				snake_case  (				self     :    Dict	,					__snake_case     :    str	,					__snake_case     :    Optional[int]	,					__snake_case     :    Optional[Any]		):
										lowerCamelCase						:int						  =     YolosForObjectDetection(__snake_case		)
										model.to(__snake_case		)
										model.eval()

										lowerCamelCase						:str						  =     model(pixel_values=__snake_case		)
										lowerCamelCase						:Any						  =     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)		)

										lowerCamelCase						:int						  =     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 				snake_case  (				self     :    int		):
										lowerCamelCase						:List[Any]						  =     self.prepare_config_and_inputs()
										lowerCamelCase  ,    lowerCamelCase  ,    lowerCamelCase						:str						  =     config_and_inputs
										lowerCamelCase						:Union[str, Any]						  =     {'''pixel_values''': pixel_values}
										return config, inputs_dict


@require_torch
class   _lowerCAmelCase		(     __SCREAMING_SNAKE_CASE      ,   __SCREAMING_SNAKE_CASE      ,   unittest.TestCase				):
							_UpperCAmelCase						    =     (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
							_UpperCAmelCase						    =     (
							    {'feature-extraction': YolosModel, 'object-detection': YolosForObjectDetection} if is_torch_available() else {}
							)

							_UpperCAmelCase						    =     False
							_UpperCAmelCase						    =     False
							_UpperCAmelCase						    =     False
							_UpperCAmelCase						    =     False







							def 				snake_case  (				self     :    Any	,					__snake_case     :    List[Any]	,					__snake_case     :    Tuple	,					__snake_case     :    Dict=False		):
										lowerCamelCase						:Optional[int]						  =     super()._prepare_for_class(__snake_case	,					__snake_case	,					return_labels=__snake_case		)

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

										return inputs_dict







							def 				snake_case  (				self     :    Tuple		):
										lowerCamelCase						:Union[str, Any]						  =     YolosModelTester(self		)
										lowerCamelCase						:Dict						  =     ConfigTester(self	,					config_class=__snake_case	,					has_text_modality=__snake_case	,					hidden_size=37		)







							def 				snake_case  (				self     :    Union[str, Any]		):
										self.config_tester.run_common_tests()







							def 				snake_case  (				self     :    Optional[Any]		):
										# YOLOS does not use inputs_embeds
										pass







							def 				snake_case  (				self     :    Tuple		):
										lowerCamelCase  ,    lowerCamelCase						:str						  =     self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													lowerCamelCase						:Optional[int]						  =     model_class(__snake_case		)
													self.assertIsInstance(model.get_input_embeddings()	,					(nn.Module)		)
													lowerCamelCase						:str						  =     model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(__snake_case	,					nn.Linear		)		)







							def 				snake_case  (				self     :    str		):
										lowerCamelCase  ,    lowerCamelCase						:str						  =     self.model_tester.prepare_config_and_inputs_for_common()

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

													lowerCamelCase						:Tuple						  =     ['''pixel_values''']
													self.assertListEqual(arg_names[:1]	,					__snake_case		)







							def 				snake_case  (				self     :    int		):
										lowerCamelCase						:List[str]						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__snake_case		)







							def 				snake_case  (				self     :    str		):
										lowerCamelCase  ,    lowerCamelCase						:List[Any]						  =     self.model_tester.prepare_config_and_inputs_for_common()
										lowerCamelCase						:int						  =     True

										# in YOLOS, the seq_len is different
										lowerCamelCase						:str						  =     self.model_tester.expected_seq_len
										for model_class in self.all_model_classes:
													lowerCamelCase						:str						  =     True
													lowerCamelCase						:Tuple						  =     False
													lowerCamelCase						:Optional[int]						  =     True
													lowerCamelCase						:int						  =     model_class(__snake_case		)
													model.to(__snake_case		)
													model.eval()
													with torch.no_grad():
																lowerCamelCase						:str						  =     model(**self._prepare_for_class(__snake_case	,					__snake_case		)		)
													lowerCamelCase						:str						  =     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"]
													lowerCamelCase						:Optional[Any]						  =     True
													lowerCamelCase						:str						  =     model_class(__snake_case		)
													model.to(__snake_case		)
													model.eval()
													with torch.no_grad():
																lowerCamelCase						:Tuple						  =     model(**self._prepare_for_class(__snake_case	,					__snake_case		)		)
													lowerCamelCase						:Tuple						  =     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]	,					)
													lowerCamelCase						:Optional[int]						  =     len(__snake_case		)

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

													lowerCamelCase						:Dict						  =     1
													self.assertEqual(out_len + added_hidden_states	,					len(__snake_case		)		)

													lowerCamelCase						:Dict						  =     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 				snake_case  (				self     :    List[str]		):
										def check_hidden_states_output(__snake_case     :    Union[str, Any]	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    Tuple		):
													lowerCamelCase						:Union[str, Any]						  =     model_class(__snake_case		)
													model.to(__snake_case		)
													model.eval()

													with torch.no_grad():
																lowerCamelCase						:Any						  =     model(**self._prepare_for_class(__snake_case	,					__snake_case		)		)

													lowerCamelCase						:Optional[Any]						  =     outputs.hidden_states

													lowerCamelCase						:Any						  =     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
													lowerCamelCase						:List[str]						  =     self.model_tester.expected_seq_len

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

										lowerCamelCase  ,    lowerCamelCase						:List[Any]						  =     self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													lowerCamelCase						:Union[str, Any]						  =     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"]
													lowerCamelCase						:Any						  =     True

													check_hidden_states_output(__snake_case	,					__snake_case	,					__snake_case		)







							def 				snake_case  (				self     :    Optional[Any]		):
										lowerCamelCase						:Optional[Any]						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_object_detection(*__snake_case		)







							@slow
							def 				snake_case  (				self     :    Dict		):
										for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowerCamelCase						:Tuple						  =     YolosModel.from_pretrained(__snake_case		)
													self.assertIsNotNone(__snake_case		)





def  _lowerCamelCase					(   ):
			lowerCamelCase						:int						  =     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
			return image


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







							@cached_property
							def 				snake_case  (				self     :    Tuple		):
										return AutoImageProcessor.from_pretrained('''hustvl/yolos-small'''		) if is_vision_available() else None







							@slow
							def 				snake_case  (				self     :    Dict		):
										lowerCamelCase						:Union[str, Any]						  =     YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''		).to(__snake_case		)

										lowerCamelCase						:Optional[Any]						  =     self.default_image_processor
										lowerCamelCase						:str						  =     prepare_img()
										lowerCamelCase						:Dict						  =     image_processor(images=__snake_case	,					return_tensors='''pt'''		).to(__snake_case		)

										# forward pass
										with torch.no_grad():
													lowerCamelCase						:Optional[Any]						  =     model(inputs.pixel_values		)

										# verify outputs
										lowerCamelCase						:int						  =     torch.Size((1, 100, 92)		)
										self.assertEqual(outputs.logits.shape	,					__snake_case		)

										lowerCamelCase						:Any						  =     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	,					)
										lowerCamelCase						:Any						  =     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
										lowerCamelCase						:List[str]						  =     image_processor.post_process_object_detection(
										    __snake_case	,					threshold=0.3	,					target_sizes=[image.size[::-1]]		)[0]
										lowerCamelCase						:List[str]						  =     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		)
										lowerCamelCase						:str						  =     [75, 75, 17, 63, 17]
										lowerCamelCase						:Tuple						  =     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		)		)



