




import inspect
import unittest

from transformers import ResNetConfig
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_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch
   from torch import nn

   from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
   from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor





class  lowerCamelCase_							:


 '''simple docstring'''







 def __init__(							self						:	List[Any]       ,       _lowerCAmelCase						:	Optional[Any]       ,       _lowerCAmelCase						:	Union[str, Any]=3       ,       _lowerCAmelCase						:	Dict=32       ,       _lowerCAmelCase						:	int=3       ,       _lowerCAmelCase						:	Tuple=10       ,       _lowerCAmelCase						:	Optional[Any]=[10, 20, 30, 40]       ,       _lowerCAmelCase						:	Optional[Any]=[1, 1, 2, 1]       ,       _lowerCAmelCase						:	int=True       ,       _lowerCAmelCase						:	Dict=True       ,       _lowerCAmelCase						:	List[Any]="relu"       ,       _lowerCAmelCase						:	Optional[Any]=3       ,       _lowerCAmelCase						:	List[str]=None       ,       _lowerCAmelCase						:	int=["stage2", "stage3", "stage4"]       ,       _lowerCAmelCase						:	Tuple=[2, 3, 4]       ,       ):
       SCREAMING_SNAKE_CASE_					=    parent
       SCREAMING_SNAKE_CASE_					=    batch_size
       SCREAMING_SNAKE_CASE_					=    image_size
       SCREAMING_SNAKE_CASE_					=    num_channels
       SCREAMING_SNAKE_CASE_					=    embeddings_size
       SCREAMING_SNAKE_CASE_					=    hidden_sizes
       SCREAMING_SNAKE_CASE_					=    depths
       SCREAMING_SNAKE_CASE_					=    is_training
       SCREAMING_SNAKE_CASE_					=    use_labels
       SCREAMING_SNAKE_CASE_					=    hidden_act
       SCREAMING_SNAKE_CASE_					=    num_labels
       SCREAMING_SNAKE_CASE_					=    scope
       SCREAMING_SNAKE_CASE_					=    len(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_					=    out_features
       SCREAMING_SNAKE_CASE_					=    out_indices



 def    lowerCAmelCase_						(							self						:	str		):
       SCREAMING_SNAKE_CASE_					=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

       SCREAMING_SNAKE_CASE_					=    None
       if self.use_labels:
             SCREAMING_SNAKE_CASE_					=    ids_tensor([self.batch_size]       ,       self.num_labels		)

       SCREAMING_SNAKE_CASE_					=    self.get_config()

       return config, pixel_values, labels



 def    lowerCAmelCase_						(							self						:	str		):
       return ResNetConfig(
           num_channels=self.num_channels       ,       embeddings_size=self.embeddings_size       ,       hidden_sizes=self.hidden_sizes       ,       depths=self.depths       ,       hidden_act=self.hidden_act       ,       num_labels=self.num_labels       ,       out_features=self.out_features       ,       out_indices=self.out_indices       ,       )



 def    lowerCAmelCase_						(							self						:	Optional[int]       ,       _lowerCAmelCase						:	Optional[int]       ,       _lowerCAmelCase						:	Union[str, Any]       ,       _lowerCAmelCase						:	List[str]		):
       SCREAMING_SNAKE_CASE_					=    ResNetModel(config=_lowerCAmelCase		)
       model.to(_lowerCAmelCase		)
       model.eval()
       SCREAMING_SNAKE_CASE_					=    model(_lowerCAmelCase		)
       # expected last hidden states: B, C, H // 32, W // 32
       self.parent.assertEqual(
           result.last_hidden_state.shape       ,       (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)       ,       )



 def    lowerCAmelCase_						(							self						:	Optional[int]       ,       _lowerCAmelCase						:	Union[str, Any]       ,       _lowerCAmelCase						:	Optional[int]       ,       _lowerCAmelCase						:	Tuple		):
       SCREAMING_SNAKE_CASE_					=    self.num_labels
       SCREAMING_SNAKE_CASE_					=    ResNetForImageClassification(_lowerCAmelCase		)
       model.to(_lowerCAmelCase		)
       model.eval()
       SCREAMING_SNAKE_CASE_					=    model(_lowerCAmelCase       ,       labels=_lowerCAmelCase		)
       self.parent.assertEqual(result.logits.shape       ,       (self.batch_size, self.num_labels)		)



 def    lowerCAmelCase_						(							self						:	int       ,       _lowerCAmelCase						:	Union[str, Any]       ,       _lowerCAmelCase						:	Optional[Any]       ,       _lowerCAmelCase						:	Union[str, Any]		):
       SCREAMING_SNAKE_CASE_					=    ResNetBackbone(config=_lowerCAmelCase		)
       model.to(_lowerCAmelCase		)
       model.eval()
       SCREAMING_SNAKE_CASE_					=    model(_lowerCAmelCase		)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps		)       ,       len(config.out_features		)		)
       self.parent.assertListEqual(list(result.feature_maps[0].shape		)       ,       [self.batch_size, self.hidden_sizes[1], 4, 4]		)

       # verify channels
       self.parent.assertEqual(len(model.channels		)       ,       len(config.out_features		)		)
       self.parent.assertListEqual(model.channels       ,       config.hidden_sizes[1:]		)

       # verify backbone works with out_features=None
       SCREAMING_SNAKE_CASE_					=    None
       SCREAMING_SNAKE_CASE_					=    ResNetBackbone(config=_lowerCAmelCase		)
       model.to(_lowerCAmelCase		)
       model.eval()
       SCREAMING_SNAKE_CASE_					=    model(_lowerCAmelCase		)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps		)       ,       1		)
       self.parent.assertListEqual(list(result.feature_maps[0].shape		)       ,       [self.batch_size, self.hidden_sizes[-1], 1, 1]		)

       # verify channels
       self.parent.assertEqual(len(model.channels		)       ,       1		)
       self.parent.assertListEqual(model.channels       ,       [config.hidden_sizes[-1]]		)




 def    lowerCAmelCase_						(							self						:	Tuple		):
       SCREAMING_SNAKE_CASE_					=    self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE_		,				SCREAMING_SNAKE_CASE_		,				SCREAMING_SNAKE_CASE_					=    config_and_inputs
       SCREAMING_SNAKE_CASE_					=    {'pixel_values': pixel_values}
       return config, inputs_dict





@require_torch
class  lowerCamelCase_							(   _SCREAMING_SNAKE_CASE ,     _SCREAMING_SNAKE_CASE ,     unittest.TestCase      ):


 '''simple docstring'''







 lowercase_       					=					(
     (
         ResNetModel,
         ResNetForImageClassification,
         ResNetBackbone,
     )
     if is_torch_available()
     else ()
 )
 lowercase_       					=					(
     {"feature-extraction": ResNetModel, "image-classification": ResNetForImageClassification}
     if is_torch_available()
     else {}
 )

 lowercase_       					=					True
 lowercase_       					=					False
 lowercase_       					=					False
 lowercase_       					=					False
 lowercase_       					=					False



 def    lowerCAmelCase_						(							self						:	Optional[Any]		):
       SCREAMING_SNAKE_CASE_					=    ResNetModelTester(self		)
       SCREAMING_SNAKE_CASE_					=    ConfigTester(self       ,       config_class=_lowerCAmelCase       ,       has_text_modality=_lowerCAmelCase		)



 def    lowerCAmelCase_						(							self						:	List[str]		):
       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()



 def    lowerCAmelCase_						(							self						:	List[Any]		):
       return



 @unittest.skip(reason='ResNet does not use inputs_embeds'		)
 def    lowerCAmelCase_						(							self						:	List[Any]		):
       pass



 @unittest.skip(reason='ResNet does not support input and output embeddings'		)
 def    lowerCAmelCase_						(							self						:	Union[str, Any]		):
       pass



 def    lowerCAmelCase_						(							self						:	List[Any]		):
       SCREAMING_SNAKE_CASE_		,				SCREAMING_SNAKE_CASE_					=    self.model_tester.prepare_config_and_inputs_for_common()

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

             SCREAMING_SNAKE_CASE_					=    ['pixel_values']
             self.assertListEqual(arg_names[:1]       ,       _lowerCAmelCase		)



 def    lowerCAmelCase_						(							self						:	List[str]		):
       SCREAMING_SNAKE_CASE_					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_lowerCAmelCase		)



 def    lowerCAmelCase_						(							self						:	List[str]		):
       SCREAMING_SNAKE_CASE_					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*_lowerCAmelCase		)



 def    lowerCAmelCase_						(							self						:	List[str]		):
       SCREAMING_SNAKE_CASE_		,				SCREAMING_SNAKE_CASE_					=    self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE_					=    model_class(config=_lowerCAmelCase		)
             for name, module in model.named_modules():
                   if isinstance(_lowerCAmelCase       ,       (nn.BatchNormad, nn.GroupNorm)		):
                         self.assertTrue(
                             torch.all(module.weight == 1		)       ,       msg=F"Parameter {name} of model {model_class} seems not properly initialized"       ,       )
                         self.assertTrue(
                             torch.all(module.bias == 0		)       ,       msg=F"Parameter {name} of model {model_class} seems not properly initialized"       ,       )



 def    lowerCAmelCase_						(							self						:	Any		):
       def check_hidden_states_output(_lowerCAmelCase						:	Optional[Any]       ,       _lowerCAmelCase						:	Union[str, Any]       ,       _lowerCAmelCase						:	str		):
             SCREAMING_SNAKE_CASE_					=    model_class(_lowerCAmelCase		)
             model.to(_lowerCAmelCase		)
             model.eval()

             with torch.no_grad():
                   SCREAMING_SNAKE_CASE_					=    model(**self._prepare_for_class(_lowerCAmelCase       ,       _lowerCAmelCase		)		)

             SCREAMING_SNAKE_CASE_					=    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             SCREAMING_SNAKE_CASE_					=    self.model_tester.num_stages
             self.assertEqual(len(_lowerCAmelCase		)       ,       expected_num_stages + 1		)

             # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
             self.assertListEqual(
                 list(hidden_states[0].shape[-2:]		)       ,       [self.model_tester.image_size // 4, self.model_tester.image_size // 4]       ,       )

       SCREAMING_SNAKE_CASE_		,				SCREAMING_SNAKE_CASE_					=    self.model_tester.prepare_config_and_inputs_for_common()
       SCREAMING_SNAKE_CASE_					=    ['basic', 'bottleneck']
       for model_class in self.all_model_classes:
             for layer_type in layers_type:
                   SCREAMING_SNAKE_CASE_					=    layer_type
                   SCREAMING_SNAKE_CASE_					=    True
                   check_hidden_states_output(_lowerCAmelCase       ,       _lowerCAmelCase       ,       _lowerCAmelCase		)

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

                   check_hidden_states_output(_lowerCAmelCase       ,       _lowerCAmelCase       ,       _lowerCAmelCase		)



 @unittest.skip(reason='ResNet does not use feedforward chunking'		)
 def    lowerCAmelCase_						(							self						:	Optional[Any]		):
       pass



 def    lowerCAmelCase_						(							self						:	List[str]		):
       SCREAMING_SNAKE_CASE_					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase		)




 @slow
 def    lowerCAmelCase_						(							self						:	Dict		):
       for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE_					=    ResNetModel.from_pretrained(_lowerCAmelCase		)
             self.assertIsNotNone(_lowerCAmelCase		)


def       UpperCAmelCase_							(   )      ->				List[Any]:
      SCREAMING_SNAKE_CASE_					=    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						:	Tuple		):
       return (
           AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
           if is_vision_available()
           else None
       )




 @slow
 def    lowerCAmelCase_						(							self						:	List[Any]		):
       SCREAMING_SNAKE_CASE_					=    ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_					=    self.default_image_processor
       SCREAMING_SNAKE_CASE_					=    prepare_img()
       SCREAMING_SNAKE_CASE_					=    image_processor(images=_lowerCAmelCase       ,       return_tensors='pt'		).to(_lowerCAmelCase		)

       # forward pass
       with torch.no_grad():
             SCREAMING_SNAKE_CASE_					=    model(**_lowerCAmelCase		)

       # verify the logits
       SCREAMING_SNAKE_CASE_					=    torch.Size((1, 1_000)		)
       self.assertEqual(outputs.logits.shape       ,       _lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_					=    torch.tensor([-11.1069, -9.7877, -8.3777]		).to(_lowerCAmelCase		)

       self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,       _lowerCAmelCase       ,       atol=1E-4		)		)





@require_torch
class  lowerCamelCase_							(   _SCREAMING_SNAKE_CASE ,     unittest.TestCase      ):


 '''simple docstring'''







 lowercase_       					=					(ResNetBackbone,) if is_torch_available() else ()
 lowercase_       					=					False
 lowercase_       					=					ResNetConfig



 def    lowerCAmelCase_						(							self						:	Optional[int]		):
       SCREAMING_SNAKE_CASE_					=    ResNetModelTester(self		)





from __future__ import annotations

def       UpperCAmelCase_							(   __UpperCAmelCase		:			list[int]							)      ->				list[int]:
      SCREAMING_SNAKE_CASE_					=    [0] * len(__UpperCAmelCase							)
      for i in range(1    ,    len(__UpperCAmelCase							)							):
            SCREAMING_SNAKE_CASE_					=    duration_times[i - 1] + waiting_times[i - 1]
      return waiting_times

def       UpperCAmelCase_							(   __UpperCAmelCase		:			list[int]    ,    __UpperCAmelCase		:			list[int]							)      ->				list[int]:
      return [
          duration_time + waiting_times[i]
          for i, duration_time in enumerate(__UpperCAmelCase							)
      ]

def       UpperCAmelCase_							(   __UpperCAmelCase		:			list[int]							)      ->				float:
      return sum(__UpperCAmelCase							) / len(__UpperCAmelCase							)

def       UpperCAmelCase_							(   __UpperCAmelCase		:			list[int]							)      ->				float:
      return sum(__UpperCAmelCase							) / len(__UpperCAmelCase							)


if __name__ == "__main__":
   # process id's
   lowerCamelCase__				:     Union[str, Any]			       =							[1, 2, 3]

   # ensure that we actually have processes
   if len(processes) == 0:
      print('Zero amount of processes')
      raise SystemExit(0)

   # duration time of all processes
   lowerCamelCase__				:     Optional[Any]			       =							[19, 8, 9]

   # ensure we can match each id to a duration time
   if len(duration_times) != len(processes):
      print('Unable to match all id\'s with their duration time')
      raise SystemExit(0)

   # get the waiting times and the turnaround times
   lowerCamelCase__				:     Dict			       =							calculate_waiting_times(duration_times)
   lowerCamelCase__				:     int			       =							calculate_turnaround_times(duration_times, waiting_times)

   # get the average times
   lowerCamelCase__				:     Any			       =							calculate_average_waiting_time(waiting_times)
   lowerCamelCase__				:     Tuple			       =							calculate_average_turnaround_time(turnaround_times)

   # print all the results
   print('Process ID\tDuration Time\tWaiting Time\tTurnaround Time')
   for i, process in enumerate(processes):
      print(
          f'''{process}\t\t{duration_times[i]}\t\t{waiting_times[i]}\t\t'''
          f'''{turnaround_times[i]}'''
      )
   print(f'''Average waiting time = {average_waiting_time}''')
   print(f'''Average turn around time = {average_turnaround_time}''')