
"""simple docstring"""





import collections
import inspect
import unittest

from transformers import NatConfig
from transformers.testing_utils import require_natten, 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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import NatBackbone, NatForImageClassification, NatModel
    from transformers.models.nat.modeling_nat import NAT_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor


class A_			:




  '''simple docstring'''







  def __init__(	self       ,     lowercase_       ,     lowercase_=13       ,     lowercase_=64       ,     lowercase_=4       ,     lowercase_=3       ,     lowercase_=16       ,     lowercase_=[1, 2, 1]       ,     lowercase_=[2, 4, 8]       ,     lowercase_=3       ,     lowercase_=2.0       ,     lowercase_=True       ,     lowercase_=0.0       ,     lowercase_=0.0       ,     lowercase_=0.1       ,     lowercase_="gelu"       ,     lowercase_=True       ,     lowercase_=0.02       ,     lowercase_=1E-5       ,     lowercase_=True       ,     lowercase_=None       ,     lowercase_=True       ,     lowercase_=10       ,     lowercase_=["stage1", "stage2"]       ,     lowercase_=[1, 2]       ,     ):

     """simple docstring"""
     UpperCAmelCase_      :      Any      =					parent
     UpperCAmelCase_      :      str      =					batch_size
     UpperCAmelCase_      :      Union[str, Any]      =					image_size
     UpperCAmelCase_      :      Dict      =					patch_size
     UpperCAmelCase_      :      str      =					num_channels
     UpperCAmelCase_      :      str      =					embed_dim
     UpperCAmelCase_      :      str      =					depths
     UpperCAmelCase_      :      int      =					num_heads
     UpperCAmelCase_      :      str      =					kernel_size
     UpperCAmelCase_      :      Optional[Any]      =					mlp_ratio
     UpperCAmelCase_      :      Dict      =					qkv_bias
     UpperCAmelCase_      :      int      =					hidden_dropout_prob
     UpperCAmelCase_      :      Union[str, Any]      =					attention_probs_dropout_prob
     UpperCAmelCase_      :      List[Any]      =					drop_path_rate
     UpperCAmelCase_      :      List[str]      =					hidden_act
     UpperCAmelCase_      :      Optional[Any]      =					patch_norm
     UpperCAmelCase_      :      Dict      =					layer_norm_eps
     UpperCAmelCase_      :      int      =					initializer_range
     UpperCAmelCase_      :      List[Any]      =					is_training
     UpperCAmelCase_      :      Optional[Any]      =					scope
     UpperCAmelCase_      :      Any      =					use_labels
     UpperCAmelCase_      :      List[str]      =					num_labels
     UpperCAmelCase_      :      int      =					out_features
     UpperCAmelCase_      :      Union[str, Any]      =					out_indices







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_      :      Any      =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

     UpperCAmelCase_      :      List[Any]      =					None
     if self.use_labels:
        UpperCAmelCase_      :      int      =					ids_tensor([self.batch_size]       ,     self.num_labels						)

     UpperCAmelCase_      :      List[str]      =					self.get_config()

     return config, pixel_values, labels







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     return NatConfig(
         num_labels=self.num_labels       ,     image_size=self.image_size       ,     patch_size=self.patch_size       ,     num_channels=self.num_channels       ,     embed_dim=self.embed_dim       ,     depths=self.depths       ,     num_heads=self.num_heads       ,     kernel_size=self.kernel_size       ,     mlp_ratio=self.mlp_ratio       ,     qkv_bias=self.qkv_bias       ,     hidden_dropout_prob=self.hidden_dropout_prob       ,     attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,     drop_path_rate=self.drop_path_rate       ,     hidden_act=self.hidden_act       ,     patch_norm=self.patch_norm       ,     layer_norm_eps=self.layer_norm_eps       ,     initializer_range=self.initializer_range       ,     out_features=self.out_features       ,     out_indices=self.out_indices       ,     )







  def  UpperCamelCase__      (	self       ,     lowercase_       ,     lowercase_       ,     lowercase_						):

     """simple docstring"""
     UpperCAmelCase_      :      List[Any]      =					NatModel(config=lowercase_						)
     model.to(lowercase_						)
     model.eval()
     UpperCAmelCase_      :      Union[str, Any]      =					model(lowercase_						)

     UpperCAmelCase_      :      int      =					(config.image_size // config.patch_size) // (2 ** (len(config.depths						) - 1))
     UpperCAmelCase_      :      Union[str, Any]      =					int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

     self.parent.assertEqual(
         result.last_hidden_state.shape       ,     (self.batch_size, expected_height, expected_width, expected_dim)						)







  def  UpperCamelCase__      (	self       ,     lowercase_       ,     lowercase_       ,     lowercase_						):

     """simple docstring"""
     UpperCAmelCase_      :      Union[str, Any]      =					NatForImageClassification(lowercase_						)
     model.to(lowercase_						)
     model.eval()
     UpperCAmelCase_      :      str      =					model(lowercase_       ,     labels=lowercase_						)
     self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels)						)

     # test greyscale images
     UpperCAmelCase_      :      Any      =					1
     UpperCAmelCase_      :      Optional[Any]      =					NatForImageClassification(lowercase_						)
     model.to(lowercase_						)
     model.eval()

     UpperCAmelCase_      :      Optional[int]      =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
     UpperCAmelCase_      :      int      =					model(lowercase_						)
     self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels)						)







  def  UpperCamelCase__      (	self       ,     lowercase_       ,     lowercase_       ,     lowercase_						):

     """simple docstring"""
     UpperCAmelCase_      :      List[str]      =					NatBackbone(config=lowercase_						)
     model.to(lowercase_						)
     model.eval()
     UpperCAmelCase_      :      Dict      =					model(lowercase_						)

     # verify hidden states
     self.parent.assertEqual(len(result.feature_maps						)       ,     len(config.out_features						)						)
     self.parent.assertListEqual(list(result.feature_maps[0].shape						)       ,     [self.batch_size, model.channels[0], 16, 16]						)

     # verify channels
     self.parent.assertEqual(len(model.channels						)       ,     len(config.out_features						)						)

     # verify backbone works with out_features=None
     UpperCAmelCase_      :      str      =					None
     UpperCAmelCase_      :      List[Any]      =					NatBackbone(config=lowercase_						)
     model.to(lowercase_						)
     model.eval()
     UpperCAmelCase_      :      Optional[Any]      =					model(lowercase_						)

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

     # verify channels
     self.parent.assertEqual(len(model.channels						)       ,     1						)







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_      :      List[str]      =					self.prepare_config_and_inputs()
     UpperCAmelCase_  ,     UpperCAmelCase_  ,     UpperCAmelCase_      :      List[str]      =					config_and_inputs
     UpperCAmelCase_      :      Optional[int]      =					{"pixel_values": pixel_values}
     return config, inputs_dict




@require_natten
@require_torch
class A_			(UpperCAmelCase_       ,UpperCAmelCase_       ,unittest.TestCase   ):




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__    :		Optional[int]						  =	(
      (
          NatModel,
          NatForImageClassification,
          NatBackbone,
      )
      if is_torch_available()
      else ()
  )
  SCREAMING_SNAKE_CASE__    :		Optional[int]						  =	(
      {"""feature-extraction""": NatModel, """image-classification""": NatForImageClassification}
      if is_torch_available()
      else {}
  )
  SCREAMING_SNAKE_CASE__    :		Union[str, Any]						  =	False

  SCREAMING_SNAKE_CASE__    :		Dict						  =	False
  SCREAMING_SNAKE_CASE__    :		Tuple						  =	False
  SCREAMING_SNAKE_CASE__    :		Optional[int]						  =	False
  SCREAMING_SNAKE_CASE__    :		Tuple						  =	False







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_      :      Tuple      =					NatModelTester(self						)
     UpperCAmelCase_      :      Any      =					ConfigTester(self       ,     config_class=lowercase_       ,     embed_dim=37						)







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     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  UpperCamelCase__      (	self						):

     """simple docstring"""
     return







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_      :      int      =					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_						)







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_      :      List[Any]      =					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowercase_						)







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_      :      Any      =					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_backbone(*lowercase_						)







  @unittest.skip(reason="Nat does not use inputs_embeds"						)
  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     pass







  @unittest.skip(reason="Nat does not use feedforward chunking"						)
  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     pass







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_  ,     UpperCAmelCase_      :      Tuple      =					self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCAmelCase_      :      List[Any]      =					model_class(lowercase_						)
        self.assertIsInstance(model.get_input_embeddings()       ,     (nn.Module)						)
        UpperCAmelCase_      :      Any      =					model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(lowercase_       ,     nn.Linear						)						)







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_  ,     UpperCAmelCase_      :      List[Any]      =					self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        UpperCAmelCase_      :      Optional[Any]      =					model_class(lowercase_						)
        UpperCAmelCase_      :      Union[str, Any]      =					inspect.signature(model.forward						)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        UpperCAmelCase_      :      Optional[int]      =					[*signature.parameters.keys()]

        UpperCAmelCase_      :      Optional[int]      =					["pixel_values"]
        self.assertListEqual(arg_names[:1]       ,     lowercase_						)







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     self.skipTest("Nat's attention operation is handled entirely by NATTEN."						)







  def  UpperCamelCase__      (	self       ,     lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_						):

     """simple docstring"""
     UpperCAmelCase_      :      str      =					model_class(lowercase_						)
     model.to(lowercase_						)
     model.eval()

     with torch.no_grad():
        UpperCAmelCase_      :      List[str]      =					model(**self._prepare_for_class(lowercase_       ,     lowercase_						)						)

     UpperCAmelCase_      :      Dict      =					outputs.hidden_states

     UpperCAmelCase_      :      Any      =					getattr(
         self.model_tester       ,     "expected_num_hidden_layers"       ,     len(self.model_tester.depths						) + 1						)
     self.assertEqual(len(lowercase_						)       ,     lowercase_						)

     # Nat has a different seq_length
     UpperCAmelCase_      :      Any      =					(
         config.patch_size
         if isinstance(config.patch_size       ,     collections.abc.Iterable						)
         else (config.patch_size, config.patch_size)
     )

     UpperCAmelCase_      :      int      =					image_size[0] // patch_size[0]
     UpperCAmelCase_      :      List[Any]      =					image_size[1] // patch_size[1]

     self.assertListEqual(
         list(hidden_states[0].shape[-3:]						)       ,     [height, width, self.model_tester.embed_dim]       ,     )

     if model_class.__name__ != "NatBackbone":
        UpperCAmelCase_      :      Union[str, Any]      =					outputs.reshaped_hidden_states
        self.assertEqual(len(lowercase_						)       ,     lowercase_						)

        UpperCAmelCase_  ,     UpperCAmelCase_  ,     UpperCAmelCase_  ,     UpperCAmelCase_      :      List[str]      =					reshaped_hidden_states[0].shape
        UpperCAmelCase_      :      str      =					(
            reshaped_hidden_states[0].view(lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_						).permute(0       ,     2       ,     3       ,     1						)
        )
        self.assertListEqual(
            list(reshaped_hidden_states.shape[-3:]						)       ,     [height, width, self.model_tester.embed_dim]       ,     )







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_  ,     UpperCAmelCase_      :      str      =					self.model_tester.prepare_config_and_inputs_for_common()

     UpperCAmelCase_      :      Dict      =					(
         self.model_tester.image_size
         if isinstance(self.model_tester.image_size       ,     collections.abc.Iterable						)
         else (self.model_tester.image_size, self.model_tester.image_size)
     )

     for model_class in self.all_model_classes:
        UpperCAmelCase_      :      str      =					True
        self.check_hidden_states_output(lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_						)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        UpperCAmelCase_      :      List[Any]      =					True

        self.check_hidden_states_output(lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_						)







  @slow
  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     for model_name in NAT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCAmelCase_      :      Union[str, Any]      =					NatModel.from_pretrained(lowercase_						)
        self.assertIsNotNone(lowercase_						)







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_  ,     UpperCAmelCase_      :      Optional[Any]      =					self.model_tester.prepare_config_and_inputs_for_common()

     UpperCAmelCase_      :      Optional[int]      =					_config_zero_init(lowercase_						)
     for model_class in self.all_model_classes:
        UpperCAmelCase_      :      Optional[Any]      =					model_class(config=lowercase_						)
        for name, param in model.named_parameters():
           if "embeddings" not in name and param.requires_grad:
              self.assertIn(
                  ((param.data.mean() * 1E9).round() / 1E9).item()       ,     [0.0, 1.0]       ,     msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""       ,     )




@require_natten
@require_vision
@require_torch
class A_			(unittest.TestCase   ):




  '''simple docstring'''







  @cached_property
  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     return AutoImageProcessor.from_pretrained("shi-labs/nat-mini-in1k-224"						) if is_vision_available() else None







  @slow
  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_      :      List[str]      =					NatForImageClassification.from_pretrained("shi-labs/nat-mini-in1k-224"						).to(lowercase_						)
     UpperCAmelCase_      :      Optional[Any]      =					self.default_image_processor

     UpperCAmelCase_      :      List[Any]      =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
     UpperCAmelCase_      :      str      =					image_processor(images=lowercase_       ,     return_tensors="pt"						).to(lowercase_						)

     # forward pass
     with torch.no_grad():
        UpperCAmelCase_      :      List[str]      =					model(**lowercase_						)

     # verify the logits
     UpperCAmelCase_      :      Optional[int]      =					torch.Size((1, 1000)						)
     self.assertEqual(outputs.logits.shape       ,     lowercase_						)
     UpperCAmelCase_      :      str      =					torch.tensor([0.38_05, -0.86_76, -0.39_12]						).to(lowercase_						)
     self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,     lowercase_       ,     atol=1E-4						)						)




@require_torch
@require_natten
class A_			(unittest.TestCase       ,UpperCAmelCase_   ):




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__    :		List[Any]						  =	(NatBackbone,) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE__    :		str						  =	NatConfig







  def  UpperCamelCase__      (	self						):

     """simple docstring"""
     UpperCAmelCase_      :      str      =					NatModelTester(self						)




"""simple docstring"""





from __future__ import annotations

from statistics import mean







def 			__a  (	__lowerCamelCase						):
   UpperCAmelCase_      :      Dict      =					2
   UpperCAmelCase_      :      Any      =					list(__lowerCamelCase						)
   UpperCAmelCase_      :      List[Any]      =					[0] * len(__lowerCamelCase						)
   UpperCAmelCase_      :      str      =					0
   while True:
      UpperCAmelCase_      :      int      =					True
      for i, burst_time in enumerate(__lowerCamelCase						):
         if rem_burst_times[i] > 0:
            UpperCAmelCase_      :      List[Any]      =					False
            if rem_burst_times[i] > quantum:
               t += quantum
               rem_burst_times[i] -= quantum
            else:
               t += rem_burst_times[i]
               UpperCAmelCase_      :      Optional[int]      =					t - burst_time
               UpperCAmelCase_      :      Union[str, Any]      =					0
      if done is True:
         return waiting_times







def 			__a  (	__lowerCamelCase,	__lowerCamelCase						):
   return [burst + waiting for burst, waiting in zip(__lowerCamelCase,	__lowerCamelCase						)]


if __name__ == "__main__":
    _a	 =							[3, 5, 7]
    _a	 =							calculate_waiting_times(burst_times)
    _a	 =							calculate_turn_around_times(burst_times, waiting_times)
    print('Process ID \tBurst Time \tWaiting Time \tTurnaround Time')
    for i, burst_time in enumerate(burst_times):
        print(
            f"""  {i + 1}\t\t  {burst_time}\t\t  {waiting_times[i]}\t\t  """
            f"""{turn_around_times[i]}"""
        )
    print(f"""\nAverage waiting time = {mean(waiting_times):.5f}""")
    print(f"""Average turn around time = {mean(turn_around_times):.5f}""")


