


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						:




							"""simple docstring"""


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

							def        __snake_case   (				self			:    Tuple							)      ->       List[Any]:
														__snake_case						:     Optional[Any]									=  floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]							)

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

														__snake_case						:     Union[str, Any]									=  self.get_config()

														return config, pixel_values, labels

							def        __snake_case   (				self			:    Dict							)      ->       str:
														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=lowerCamelCase       ,      initializer_range=self.initializer_range       ,      num_detection_tokens=self.num_detection_tokens       ,      num_labels=self.num_labels       ,      )

							def        __snake_case   (				self			:    Dict       ,      lowerCamelCase			:    str       ,      lowerCamelCase			:    Optional[Any]       ,      lowerCamelCase			:    str							)      ->       Optional[Any]:
														__snake_case						:     int									=  YolosModel(config=lowerCamelCase							)
														model.to(lowerCamelCase							)
														model.eval()
														__snake_case						:     Dict									=  model(lowerCamelCase							)
														self.parent.assertEqual(
														    result.last_hidden_state.shape       ,      (self.batch_size, self.expected_seq_len, self.hidden_size)							)

							def        __snake_case   (				self			:    Tuple       ,      lowerCamelCase			:    int       ,      lowerCamelCase			:    Union[str, Any]       ,      lowerCamelCase			:    Optional[int]							)      ->       Any:
														__snake_case						:     List[str]									=  YolosForObjectDetection(lowerCamelCase							)
														model.to(lowerCamelCase							)
														model.eval()

														__snake_case						:     Optional[Any]									=  model(pixel_values=lowerCamelCase							)
														__snake_case						:     Dict									=  model(lowerCamelCase							)

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

														__snake_case						:     Optional[int]									=  model(pixel_values=lowerCamelCase       ,      labels=lowerCamelCase							)

														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			:    Dict							)      ->       Any:
														__snake_case						:     Tuple									=  self.prepare_config_and_inputs()
														__snake_case					,     __snake_case					,     __snake_case						:     Dict									=  config_and_inputs
														__snake_case						:     str									=  {"pixel_values": pixel_values}
														return config, inputs_dict

@require_torch
class 							a						(_lowerCAmelCase	,							_lowerCAmelCase	,							unittest.TestCase ):




							"""simple docstring"""


							__UpperCAmelCase       :				int	    =    (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
							__UpperCAmelCase       :				List[str]	    =    (
							    {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {}
							)

							__UpperCAmelCase       :				List[Any]	    =    False
							__UpperCAmelCase       :				Any	    =    False
							__UpperCAmelCase       :				int	    =    False
							__UpperCAmelCase       :				Optional[Any]	    =    False

							def        __snake_case   (				self			:    Optional[int]       ,      lowerCamelCase			:    int       ,      lowerCamelCase			:    List[str]       ,      lowerCamelCase			:    Union[str, Any]=False							)      ->       List[Any]:
														__snake_case						:     Union[str, Any]									=  super()._prepare_for_class(lowerCamelCase       ,      lowerCamelCase       ,      return_labels=lowerCamelCase							)

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

														return inputs_dict

							def        __snake_case   (				self			:    Tuple							)      ->       Dict:
														__snake_case						:     Any									=  YolosModelTester(self							)
														__snake_case						:     str									=  ConfigTester(self       ,      config_class=lowerCamelCase       ,      has_text_modality=lowerCamelCase       ,      hidden_size=37							)

							def        __snake_case   (				self			:    str							)      ->       Optional[Any]:
														self.config_tester.run_common_tests()

							def        __snake_case   (				self			:    Dict							)      ->       Optional[int]:
														# YOLOS does not use inputs_embeds
														pass

							def        __snake_case   (				self			:    int							)      ->       int:
														__snake_case					,     __snake_case						:     str									=  self.model_tester.prepare_config_and_inputs_for_common()

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

							def        __snake_case   (				self			:    Any							)      ->       Optional[int]:
														__snake_case					,     __snake_case						:     Dict									=  self.model_tester.prepare_config_and_inputs_for_common()

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

																					__snake_case						:     int									=  ["pixel_values"]
																					self.assertListEqual(arg_names[:1]       ,      lowerCamelCase							)

							def        __snake_case   (				self			:    Tuple							)      ->       Optional[int]:
														__snake_case						:     Union[str, Any]									=  self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*lowerCamelCase							)

							def        __snake_case   (				self			:    Union[str, Any]							)      ->       Optional[int]:
														__snake_case					,     __snake_case						:     Optional[Any]									=  self.model_tester.prepare_config_and_inputs_for_common()
														__snake_case						:     int									=  True

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

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

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

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

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

																					__snake_case						:     Any									=  outputs.attentions

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

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

																					__snake_case						:     List[Any]									=  outputs.hidden_states

																					__snake_case						:     str									=  getattr(
																					    self.model_tester       ,      "expected_num_hidden_layers"       ,      self.model_tester.num_hidden_layers + 1							)
																					self.assertEqual(len(lowerCamelCase							)       ,      lowerCamelCase							)

																					# YOLOS has a different seq_length
																					__snake_case						:     Optional[Any]									=  self.model_tester.expected_seq_len

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

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

														for model_class in self.all_model_classes:
																					__snake_case						:     Any									=  True
																					check_hidden_states_output(lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase							)

																					# check that output_hidden_states also work using config
																					del inputs_dict["output_hidden_states"]
																					__snake_case						:     Optional[int]									=  True

																					check_hidden_states_output(lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase							)

							def        __snake_case   (				self			:    Tuple							)      ->       Optional[Any]:
														__snake_case						:     str									=  self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_object_detection(*lowerCamelCase							)






							@slow
							def        __snake_case   (				self			:    str							)      ->       int:
														for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					__snake_case						:     List[Any]									=  YolosModel.from_pretrained(lowerCamelCase							)
																					self.assertIsNotNone(lowerCamelCase							)







def 							lowerCAmelCase_	(   ):
							__snake_case						:     List[Any]									=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
							return image

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




							"""simple docstring"""


							@cached_property
							def        __snake_case   (				self			:    List[Any]							)      ->       Union[str, Any]:
														return AutoImageProcessor.from_pretrained("hustvl/yolos-small"							) if is_vision_available() else None






							@slow
							def        __snake_case   (				self			:    Any							)      ->       Optional[Any]:
														__snake_case						:     int									=  YolosForObjectDetection.from_pretrained("hustvl/yolos-small"							).to(lowerCamelCase							)

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

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

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

														__snake_case						:     Optional[Any]									=  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=lowerCamelCase       ,      )
														__snake_case						:     Optional[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=lowerCamelCase							)
														self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]       ,      lowerCamelCase       ,      atol=1E-4							)							)
														self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]       ,      lowerCamelCase       ,      atol=1E-4							)							)

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

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





from collections.abc import Callable




def  a   (lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__   ):
   __a					=  a
   __a					=  b
   if function(lowerCAmelCase__   ) == 0:  # one of the a or b is a root for the function
      return a
   elif function(lowerCAmelCase__   ) == 0:
      return b
   elif (
       function(lowerCAmelCase__   ) * function(lowerCAmelCase__   ) > 0
   ):  # if none of these are root and they are both positive or negative,
      # then this algorithm can't find the root
      raise ValueError("""could not find root in given interval."""   )
   else:
      __a					=  start + (end - start) / 2.0
      while abs(start - mid   ) > 10**-7:  # until precisely equals to 10^-7
         if function(lowerCAmelCase__   ) == 0:
            return mid
         elif function(lowerCAmelCase__   ) * function(lowerCAmelCase__   ) < 0:
            __a					=  mid
         else:
            __a					=  mid
         __a					=  start + (end - start) / 2.0
      return mid




def  a   (lowerCAmelCase__   ):
   return x**3 - 2 * x - 5


if __name__ == "__main__":
  print(bisection(f, 1, 1_0_0_0))

  import doctest

  doctest.testmod()



