




"""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  lowercase:







 '''simple docstring'''





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




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  parent
   _snake_case							:		Dict								=  batch_size
   _snake_case							:		Dict								=  image_size
   _snake_case							:		Tuple								=  patch_size
   _snake_case							:		str								=  num_channels
   _snake_case							:		Optional[int]								=  is_training
   _snake_case							:		str								=  use_labels
   _snake_case							:		int								=  hidden_size
   _snake_case							:		str								=  num_hidden_layers
   _snake_case							:		Dict								=  num_attention_heads
   _snake_case							:		int								=  intermediate_size
   _snake_case							:		Optional[int]								=  hidden_act
   _snake_case							:		Any								=  hidden_dropout_prob
   _snake_case							:		Tuple								=  attention_probs_dropout_prob
   _snake_case							:		Union[str, Any]								=  type_sequence_label_size
   _snake_case							:		Any								=  initializer_range
   _snake_case							:		Optional[Any]								=  num_labels
   _snake_case							:		List[Any]								=  scope
   _snake_case							:		List[str]								=  n_targets
   _snake_case							:		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
   _snake_case							:		Dict								=  (image_size[1] // patch_size) * (image_size[0] // patch_size)
   _snake_case							:		Union[str, Any]								=  num_patches + 1 + self.num_detection_tokens


 def 			UpperCamelCase_       (    self:		Union[str, Any]		):




   '''simple docstring'''



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

   _snake_case							:		Any								=  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							:		List[str]								=  []
     for i in range(self.batch_size		):
       _snake_case							:		List[str]								=  {}
       _snake_case							:		Union[str, Any]								=  torch.randint(
           high=self.num_labels,				size=(self.n_targets,),				device=a_		)
       _snake_case							:		str								=  torch.rand(self.n_targets,				4,				device=a_		)
       labels.append(a_		)

   _snake_case							:		int								=  self.get_config()

   return config, pixel_values, labels


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   return YolosConfig(
       image_size=self.image_size,				patch_size=self.patch_size,				num_channels=self.num_channels,				hidden_size=self.hidden_size,				num_hidden_layers=self.num_hidden_layers,				num_attention_heads=self.num_attention_heads,				intermediate_size=self.intermediate_size,				hidden_act=self.hidden_act,				hidden_dropout_prob=self.hidden_dropout_prob,				attention_probs_dropout_prob=self.attention_probs_dropout_prob,				is_decoder=a_,				initializer_range=self.initializer_range,				num_detection_tokens=self.num_detection_tokens,				num_labels=self.num_labels,				)


 def 			UpperCamelCase_       (    self:		Tuple,				a_:		Optional[int],				a_:		List[Any],				a_:		Dict		):




   '''simple docstring'''



   _snake_case							:		Tuple								=  YolosModel(config=a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		Optional[int]								=  model(a_		)
   self.parent.assertEqual(
       result.last_hidden_state.shape,				(self.batch_size, self.expected_seq_len, self.hidden_size)		)


 def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		List[str],				a_:		str,				a_:		Tuple		):




   '''simple docstring'''



   _snake_case							:		List[str]								=  YolosForObjectDetection(a_		)
   model.to(a_		)
   model.eval()

   _snake_case							:		List[Any]								=  model(pixel_values=a_		)
   _snake_case							:		Optional[Any]								=  model(a_		)

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

   _snake_case							:		List[Any]								=  model(pixel_values=a_,				labels=a_		)

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


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



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







@require_torch
class  lowercase(					__a	,      __a	,      unittest.TestCase			):







 '''simple docstring'''





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

 lowercase__			 = False
 lowercase__			 = False
 lowercase__			 = False
 lowercase__			 = False


 def 			UpperCamelCase_       (    self:		Dict,				a_:		Optional[Any],				a_:		Dict,				a_:		Tuple=False		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  super()._prepare_for_class(a_,				a_,				return_labels=a_		)

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

   return inputs_dict


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  YolosModelTester(self		)
   _snake_case							:		Optional[int]								=  ConfigTester(self,				config_class=a_,				has_text_modality=a_,				hidden_size=37		)


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   self.config_tester.run_common_tests()


 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   pass


 def 			UpperCamelCase_       (    self:		int		):




   '''simple docstring'''



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

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


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



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

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

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


 def 			UpperCamelCase_       (    self:		Tuple		):




   '''simple docstring'''



   _snake_case							:		Any								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*a_		)


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   _snake_case		, _snake_case							:		List[Any]								=  self.model_tester.prepare_config_and_inputs_for_common()
   _snake_case							:		List[str]								=  True

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

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

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

     # Check attention is always last and order is fine
     _snake_case							:		Any								=  True
     _snake_case							:		Dict								=  True
     _snake_case							:		Any								=  model_class(a_		)
     model.to(a_		)
     model.eval()
     with torch.no_grad():
       _snake_case							:		List[Any]								=  model(**self._prepare_for_class(a_,				a_		)		)

     _snake_case							:		Dict								=  1
     self.assertEqual(out_len + added_hidden_states,				len(a_		)		)

     _snake_case							:		Optional[int]								=  outputs.attentions

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


 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   def check_hidden_states_output(a_:		List[Any],				a_:		List[Any],				a_:		Tuple		):
     _snake_case							:		List[str]								=  model_class(a_		)
     model.to(a_		)
     model.eval()

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

     _snake_case							:		List[Any]								=  outputs.hidden_states

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

     # YOLOS has a different seq_length
     _snake_case							:		List[str]								=  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							:		Optional[Any]								=  True
     check_hidden_states_output(a_,				a_,				a_		)

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

     check_hidden_states_output(a_,				a_,				a_		)


 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



   _snake_case							:		Tuple								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_object_detection(*a_		)


 @slow
 def 			UpperCamelCase_       (    self:		Dict		):




   '''simple docstring'''



   for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case							:		List[Any]								=  YolosModel.from_pretrained(a_		)
     self.assertIsNotNone(a_		)







def  UpperCAmelCase__	():
  """simple docstring"""

  _snake_case							:		List[str]								=  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
  return image






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







 '''simple docstring'''





 @cached_property
 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



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


 @slow
 def 			UpperCamelCase_       (    self:		List[str]		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""		).to(a_		)

   _snake_case							:		str								=  self.default_image_processor
   _snake_case							:		Dict								=  prepare_img()
   _snake_case							:		str								=  image_processor(images=a_,				return_tensors="""pt"""		).to(a_		)

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

   # verify outputs
   _snake_case							:		List[str]								=  torch.Size((1, 100, 92)		)
   self.assertEqual(outputs.logits.shape,				a_		)

   _snake_case							:		Any								=  torch.tensor(
       [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]],				device=a_,				)
   _snake_case							:		str								=  torch.tensor(
       [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]],				device=a_		)
   self.assertTrue(torch.allclose(outputs.logits[0, :3, :3],				a_,				atol=1E-4		)		)
   self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3],				a_,				atol=1E-4		)		)

   # verify postprocessing
   _snake_case							:		Union[str, Any]								=  image_processor.post_process_object_detection(
       a_,				threshold=0.3,				target_sizes=[image.size[::-1]]		)[0]
   _snake_case							:		str								=  torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]		).to(a_		)
   _snake_case							:		Tuple								=  [75, 75, 17, 63, 17]
   _snake_case							:		int								=  torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]		).to(a_		)

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








"""simple docstring"""


from collections.abc import Generator
from math import sin


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  if len(snake_case__   ) != 32:
    raise ValueError("""Input must be of length 32"""   )

  _snake_case							:		Optional[int]								=  B""""""
  for i in [3, 2, 1, 0]:
    little_endian += string_aa[8 * i : 8 * i + 8]
  return little_endian


def  UpperCAmelCase__	(snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )

  _snake_case							:		Optional[Any]								=  format(snake_case__		,       """08x"""   )[-8:]
  _snake_case							:		Optional[Any]								=  B""""""
  for i in [3, 2, 1, 0]:
    little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8"""   )
  return little_endian_hex


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  _snake_case							:		Union[str, Any]								=  B""""""
  for char in message:
    bit_string += format(snake_case__		,       """08b"""   ).encode("""utf-8"""   )
  _snake_case							:		List[Any]								=  format(len(snake_case__   )		,       """064b"""   ).encode("""utf-8"""   )

  # Pad bit_string to a multiple of 512 chars
  bit_string += b"1"
  while len(snake_case__   ) % 5_12 != 4_48:
    bit_string += b"0"
  bit_string += to_little_endian(start_len[32:]   ) + to_little_endian(start_len[:32]   )

  return bit_string


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  if len(snake_case__   ) % 5_12 != 0:
    raise ValueError("""Input must have length that's a multiple of 512"""   )

  for pos in range(0		,       len(snake_case__   )		,       5_12   ):
    _snake_case							:		List[str]								=  bit_string[pos : pos + 5_12]
    _snake_case							:		List[str]								=  []
    for i in range(0		,       5_12		,       32   ):
      block_words.append(int(to_little_endian(block[i : i + 32]   )		,       2   )   )
    yield block_words


def  UpperCAmelCase__	(snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )

  _snake_case							:		Optional[int]								=  format(snake_case__		,       """032b"""   )
  _snake_case							:		str								=  """"""
  for c in i_str:
    new_str += "1" if c == "0" else "0"
  return int(snake_case__		,       2   )


def  UpperCAmelCase__	(snake_case__							: int		,       snake_case__							: int   ):
  """simple docstring"""

  return (a + b) % 2**32


def  UpperCAmelCase__	(snake_case__							: int		,       snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )
  if shift < 0:
    raise ValueError("""Shift must be non-negative"""   )
  return ((i << shift) ^ (i >> (32 - shift))) % 2**32


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  _snake_case							:		Any								=  preprocess(snake_case__   )

  _snake_case							:		Optional[Any]								=  [int(2**32 * abs(sin(i + 1   )   )   ) for i in range(64   )]

  # Starting states
  _snake_case							:		Union[str, Any]								=  0x6745_2301
  _snake_case							:		List[Any]								=  0xEFCD_AB89
  _snake_case							:		Optional[Any]								=  0x98BA_DCFE
  _snake_case							:		Optional[int]								=  0x1032_5476

  _snake_case							:		Tuple								=  [
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
  ]

  # Process bit string in chunks, each with 16 32-char words
  for block_words in get_block_words(snake_case__   ):
    _snake_case							:		Tuple								=  aa
    _snake_case							:		str								=  ba
    _snake_case							:		int								=  ca
    _snake_case							:		Dict								=  da

    # Hash current chunk
    for i in range(64   ):
      if i <= 15:
        # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
        _snake_case							:		int								=  d ^ (b & (c ^ d))
        _snake_case							:		Dict								=  i
      elif i <= 31:
        # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
        _snake_case							:		Tuple								=  c ^ (d & (b ^ c))
        _snake_case							:		int								=  (5 * i + 1) % 16
      elif i <= 47:
        _snake_case							:		List[Any]								=  b ^ c ^ d
        _snake_case							:		Union[str, Any]								=  (3 * i + 5) % 16
      else:
        _snake_case							:		Tuple								=  c ^ (b | not_aa(snake_case__   ))
        _snake_case							:		Optional[int]								=  (7 * i) % 16
      _snake_case							:		Dict								=  (f + a + added_consts[i] + block_words[g]) % 2**32
      _snake_case							:		List[str]								=  d
      _snake_case							:		List[Any]								=  c
      _snake_case							:		str								=  b
      _snake_case							:		List[str]								=  sum_aa(snake_case__		,       left_rotate_aa(snake_case__		,       shift_amounts[i]   )   )

    # Add hashed chunk to running total
    _snake_case							:		Union[str, Any]								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		str								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		Any								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		List[str]								=  sum_aa(snake_case__		,       snake_case__   )

  _snake_case							:		Any								=  reformat_hex(snake_case__   ) + reformat_hex(snake_case__   ) + reformat_hex(snake_case__   ) + reformat_hex(snake_case__   )
  return digest


if __name__ == "__main__":
     import doctest

     doctest.testmod()


