



"""simple docstring"""


import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
				from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor







class 				A_      :



						"""simple docstring"""






						def __init__( self			:str       ,  lowercase_			:Optional[Any]       ,  lowercase_			:str=13       ,  lowercase_			:Dict=32       ,  lowercase_			:Any=3       ,  lowercase_			:str=4       ,  lowercase_			:str=[10, 20, 30, 40]       ,  lowercase_			:List[str]=[2, 2, 3, 2]       ,  lowercase_			:Tuple=True       ,  lowercase_			:int=True       ,  lowercase_			:Tuple=37       ,  lowercase_			:List[str]="gelu"       ,  lowercase_			:Optional[int]=10       ,  lowercase_			:str=0.02       ,  lowercase_			:Union[str, Any]=["stage2", "stage3", "stage4"]       ,  lowercase_			:int=[2, 3, 4]       ,  lowercase_			:List[str]=None       ,  )    ->      Optional[Any]:
												UpperCAmelCase					=			parent
												UpperCAmelCase					=			batch_size
												UpperCAmelCase					=			image_size
												UpperCAmelCase					=			num_channels
												UpperCAmelCase					=			num_stages
												UpperCAmelCase					=			hidden_sizes
												UpperCAmelCase					=			depths
												UpperCAmelCase					=			is_training
												UpperCAmelCase					=			use_labels
												UpperCAmelCase					=			intermediate_size
												UpperCAmelCase					=			hidden_act
												UpperCAmelCase					=			num_labels
												UpperCAmelCase					=			initializer_range
												UpperCAmelCase					=			out_features
												UpperCAmelCase					=			out_indices
												UpperCAmelCase					=			scope






						def      UpperCAmelCase__					( self			:List[str] )    ->      str:
												UpperCAmelCase					=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

												UpperCAmelCase					=			self.get_config()

												return config, pixel_values, labels






						def      UpperCAmelCase__					( self			:Tuple )    ->      str:
												return ConvNextVaConfig(
												    num_channels=self.num_channels       ,  hidden_sizes=self.hidden_sizes       ,  depths=self.depths       ,  num_stages=self.num_stages       ,  hidden_act=self.hidden_act       ,  is_decoder=lowercase_       ,  initializer_range=self.initializer_range       ,  out_features=self.out_features       ,  out_indices=self.out_indices       ,  num_labels=self.num_labels       ,  )






						def      UpperCAmelCase__					( self			:Optional[int]       ,  lowercase_			:Optional[int]       ,  lowercase_			:List[str]       ,  lowercase_			:Optional[int] )    ->      List[str]:
												UpperCAmelCase					=			ConvNextVaModel(config=lowercase_ )
												model.to(lowercase_ )
												model.eval()
												UpperCAmelCase					=			model(lowercase_ )
												# 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      UpperCAmelCase__					( self			:List[Any]       ,  lowercase_			:Tuple       ,  lowercase_			:Any       ,  lowercase_			:Union[str, Any] )    ->      int:
												UpperCAmelCase					=			ConvNextVaForImageClassification(lowercase_ )
												model.to(lowercase_ )
												model.eval()
												UpperCAmelCase					=			model(lowercase_       ,  labels=lowercase_ )
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels) )






						def      UpperCAmelCase__					( self			:Dict       ,  lowercase_			:Optional[int]       ,  lowercase_			:Tuple       ,  lowercase_			:str )    ->      Dict:
												UpperCAmelCase					=			ConvNextVaBackbone(config=lowercase_ )
												model.to(lowercase_ )
												model.eval()
												UpperCAmelCase					=			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, 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
												UpperCAmelCase					=			None
												UpperCAmelCase					=			ConvNextVaBackbone(config=lowercase_ )
												model.to(lowercase_ )
												model.eval()
												UpperCAmelCase					=			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, 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      UpperCAmelCase__					( self			:Optional[int] )    ->      int:
												UpperCAmelCase					=			self.prepare_config_and_inputs()
												UpperCAmelCase				,   UpperCAmelCase				,   UpperCAmelCase					=			config_and_inputs
												UpperCAmelCase					=			{'pixel_values': pixel_values}
												return config, inputs_dict






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Tuple:
												UpperCAmelCase					=			self.prepare_config_and_inputs()
												UpperCAmelCase				,   UpperCAmelCase				,   UpperCAmelCase					=			config_and_inputs
												UpperCAmelCase					=			{'pixel_values': pixel_values, 'labels': labels}
												return config, inputs_dict







@require_torch
class 				A_      (					SCREAMING_SNAKE_CASE_     ,       SCREAMING_SNAKE_CASE_     ,       unittest.TestCase    ):



						"""simple docstring"""
						__UpperCamelCase		    =							(
						    (
						        ConvNextVaModel,
						        ConvNextVaForImageClassification,
						        ConvNextVaBackbone,
						    )
						    if is_torch_available()
						    else ()
						)
						__UpperCamelCase		    =							(
						    {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
						    if is_torch_available()
						    else {}
						)

						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False






						def      UpperCAmelCase__					( self			:Optional[Any] )    ->      Any:
												UpperCAmelCase					=			ConvNextVaModelTester(self )
												UpperCAmelCase					=			ConfigTester(self       ,  config_class=lowercase_       ,  has_text_modality=lowercase_       ,  hidden_size=37 )






						def      UpperCAmelCase__					( self			:Dict )    ->      Dict:
												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			:Union[str, Any] )    ->      List[str]:
												return






						@unittest.skip(reason='ConvNextV2 does not use inputs_embeds' )
						def      UpperCAmelCase__					( self			:int )    ->      Any:
												pass






						@unittest.skip(reason='ConvNextV2 does not support input and output embeddings' )
						def      UpperCAmelCase__					( self			:List[Any] )    ->      int:
												pass






						@unittest.skip(reason='ConvNextV2 does not use feedforward chunking' )
						def      UpperCAmelCase__					( self			:List[Any] )    ->      List[str]:
												pass






						def      UpperCAmelCase__					( self			:Any )    ->      Optional[int]:
												if not self.model_tester.is_training:
																		return

												for model_class in self.all_model_classes:
																		UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_with_labels()
																		UpperCAmelCase					=			True

																		if model_class.__name__ in [
																		    *get_values(lowercase_ ),
																		    *get_values(lowercase_ ),
																		]:
																								continue

																		UpperCAmelCase					=			model_class(lowercase_ )
																		model.to(lowercase_ )
																		model.train()
																		UpperCAmelCase					=			self._prepare_for_class(lowercase_       ,  lowercase_       ,  return_labels=lowercase_ )
																		UpperCAmelCase					=			model(**lowercase_ ).loss
																		loss.backward()






						def      UpperCAmelCase__					( self			:Tuple )    ->      Optional[int]:
												if not self.model_tester.is_training:
																		return

												for model_class in self.all_model_classes:
																		UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_with_labels()
																		UpperCAmelCase					=			False
																		UpperCAmelCase					=			True

																		if (
																		    model_class.__name__
																		    in [*get_values(lowercase_ ), *get_values(lowercase_ )]
																		    or not model_class.supports_gradient_checkpointing
																		):
																								continue

																		UpperCAmelCase					=			model_class(lowercase_ )
																		model.to(lowercase_ )
																		model.gradient_checkpointing_enable()
																		model.train()
																		UpperCAmelCase					=			self._prepare_for_class(lowercase_       ,  lowercase_       ,  return_labels=lowercase_ )
																		UpperCAmelCase					=			model(**lowercase_ ).loss
																		loss.backward()






						def      UpperCAmelCase__					( self			:str )    ->      Union[str, Any]:
												UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_for_common()

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

																		UpperCAmelCase					=			['pixel_values']
																		self.assertListEqual(arg_names[:1]       ,  lowercase_ )






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Dict:
												UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*lowercase_ )






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      Optional[Any]:
												def check_hidden_states_output(lowercase_			:Optional[int]       ,  lowercase_			:Optional[Any]       ,  lowercase_			:List[Any] ):
																		UpperCAmelCase					=			model_class(lowercase_ )
																		model.to(lowercase_ )
																		model.eval()

																		with torch.no_grad():
																								UpperCAmelCase					=			model(**self._prepare_for_class(lowercase_       ,  lowercase_ ) )

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

																		UpperCAmelCase					=			self.model_tester.num_stages
																		self.assertEqual(len(lowercase_ )       ,  expected_num_stages + 1 )

																		# ConvNextV2'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]       ,  )

												UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_for_common()

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

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

																		check_hidden_states_output(lowercase_       ,  lowercase_       ,  lowercase_ )






						def      UpperCAmelCase__					( self			:Any )    ->      Union[str, Any]:
												UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*lowercase_ )






						@slow
						def      UpperCAmelCase__					( self			:Optional[int] )    ->      Optional[Any]:
												for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		UpperCAmelCase					=			ConvNextVaModel.from_pretrained(lowercase_ )
																		self.assertIsNotNone(lowercase_ )


def 			_lowerCAmelCase				(       ):
						UpperCAmelCase					=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
						return image







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



						"""simple docstring"""






						@cached_property
						def      UpperCAmelCase__					( self			:Dict )    ->      str:
												return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224' ) if is_vision_available() else None






						@slow
						def      UpperCAmelCase__					( self			:Dict )    ->      int:
												UpperCAmelCase					=			ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224' ).to(lowercase_ )

												UpperCAmelCase					=			self.default_image_processor
												UpperCAmelCase					=			prepare_img()
												UpperCAmelCase					=			preprocessor(images=lowercase_       ,  return_tensors='pt' ).to(lowercase_ )

												# forward pass
												with torch.no_grad():
																		UpperCAmelCase					=			model(**lowercase_ )

												# verify the logits
												UpperCAmelCase					=			torch.Size((1, 10_00) )
												self.assertEqual(outputs.logits.shape       ,  lowercase_ )

												UpperCAmelCase					=			torch.tensor([0.9996, 0.1966, -0.4386] ).to(lowercase_ )
												self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,  lowercase_       ,  atol=1E-4 ) )










"""simple docstring"""


from collections import deque







class 				A_      :



						"""simple docstring"""






						def __init__( self			:Any       ,  lowercase_			:str       ,  lowercase_			:int       ,  lowercase_			:int )    ->      None:
												UpperCAmelCase					=			process_name  # process name
												UpperCAmelCase					=			arrival_time  # arrival time of the process
												# completion time of finished process or last interrupted time
												UpperCAmelCase					=			arrival_time
												UpperCAmelCase					=			burst_time  # remaining burst time
												UpperCAmelCase					=			0  # total time of the process wait in ready queue
												UpperCAmelCase					=			0  # time from arrival time to completion time







class 				A_      :



						"""simple docstring"""






						def __init__( self			:Any       ,  lowercase_			:int       ,  lowercase_			:list[int]       ,  lowercase_			:deque[Process]       ,  lowercase_			:int       ,  )    ->      None:
												# total number of mlfq's queues
												UpperCAmelCase					=			number_of_queues
												# time slice of queues that round robin algorithm applied
												UpperCAmelCase					=			time_slices
												# unfinished process is in this ready_queue
												UpperCAmelCase					=			queue
												# current time
												UpperCAmelCase					=			current_time
												# finished process is in this sequence queue
												UpperCAmelCase					=			deque()






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      list[str]:
												UpperCAmelCase					=			[]
												for i in range(len(self.finish_queue ) ):
																		sequence.append(self.finish_queue[i].process_name )
												return sequence






						def      UpperCAmelCase__					( self			:List[str]       ,  lowercase_			:list[Process] )    ->      list[int]:
												UpperCAmelCase					=			[]
												for i in range(len(lowercase_ ) ):
																		waiting_times.append(queue[i].waiting_time )
												return waiting_times






						def      UpperCAmelCase__					( self			:List[str]       ,  lowercase_			:list[Process] )    ->      list[int]:
												UpperCAmelCase					=			[]
												for i in range(len(lowercase_ ) ):
																		turnaround_times.append(queue[i].turnaround_time )
												return turnaround_times






						def      UpperCAmelCase__					( self			:Dict       ,  lowercase_			:list[Process] )    ->      list[int]:
												UpperCAmelCase					=			[]
												for i in range(len(lowercase_ ) ):
																		completion_times.append(queue[i].stop_time )
												return completion_times






						def      UpperCAmelCase__					( self			:str       ,  lowercase_			:deque[Process] )    ->      list[int]:
												return [q.burst_time for q in queue]






						def      UpperCAmelCase__					( self			:int       ,  lowercase_			:Process )    ->      int:
												process.waiting_time += self.current_time - process.stop_time
												return process.waiting_time






						def      UpperCAmelCase__					( self			:Optional[int]       ,  lowercase_			:deque[Process] )    ->      deque[Process]:
												UpperCAmelCase					=			deque()  # sequence deque of finished process
												while len(lowercase_ ) != 0:
																		UpperCAmelCase					=			ready_queue.popleft()  # current process

																		# if process's arrival time is later than current time, update current time
																		if self.current_time < cp.arrival_time:
																								self.current_time += cp.arrival_time

																		# update waiting time of current process
																		self.update_waiting_time(lowercase_ )
																		# update current time
																		self.current_time += cp.burst_time
																		# finish the process and set the process's burst-time 0
																		UpperCAmelCase					=			0
																		# set the process's turnaround time because it is finished
																		UpperCAmelCase					=			self.current_time - cp.arrival_time
																		# set the completion time
																		UpperCAmelCase					=			self.current_time
																		# add the process to queue that has finished queue
																		finished.append(lowercase_ )

												self.finish_queue.extend(lowercase_ )  # add finished process to finish queue
												# FCFS will finish all remaining processes
												return finished






						def      UpperCAmelCase__					( self			:Tuple       ,  lowercase_			:deque[Process]       ,  lowercase_			:int )    ->      tuple[deque[Process], deque[Process]]:
												UpperCAmelCase					=			deque()  # sequence deque of terminated process
												# just for 1 cycle and unfinished processes will go back to queue
												for _ in range(len(lowercase_ ) ):
																		UpperCAmelCase					=			ready_queue.popleft()  # current process

																		# if process's arrival time is later than current time, update current time
																		if self.current_time < cp.arrival_time:
																								self.current_time += cp.arrival_time

																		# update waiting time of unfinished processes
																		self.update_waiting_time(lowercase_ )
																		# if the burst time of process is bigger than time-slice
																		if cp.burst_time > time_slice:
																								# use CPU for only time-slice
																								self.current_time += time_slice
																								# update remaining burst time
																								cp.burst_time -= time_slice
																								# update end point time
																								UpperCAmelCase					=			self.current_time
																								# locate the process behind the queue because it is not finished
																								ready_queue.append(lowercase_ )
																		else:
																								# use CPU for remaining burst time
																								self.current_time += cp.burst_time
																								# set burst time 0 because the process is finished
																								UpperCAmelCase					=			0
																								# set the finish time
																								UpperCAmelCase					=			self.current_time
																								# update the process' turnaround time because it is finished
																								UpperCAmelCase					=			self.current_time - cp.arrival_time
																								# add the process to queue that has finished queue
																								finished.append(lowercase_ )

												self.finish_queue.extend(lowercase_ )  # add finished process to finish queue
												# return finished processes queue and remaining processes queue
												return finished, ready_queue






						def      UpperCAmelCase__					( self			:Optional[Any] )    ->      deque[Process]:

												#  all queues except last one have round_robin algorithm
												for i in range(self.number_of_queues - 1 ):
																		UpperCAmelCase				,   UpperCAmelCase					=			self.round_robin(
																		    self.ready_queue       ,  self.time_slices[i] )
												#  the last queue has first_come_first_served algorithm
												self.first_come_first_served(self.ready_queue )

												return self.finish_queue


if __name__ == "__main__":
				import doctest

				snake_case_    					=	Process("""P1""", 0, 53)
				snake_case_    					=	Process("""P2""", 0, 17)
				snake_case_    					=	Process("""P3""", 0, 68)
				snake_case_    					=	Process("""P4""", 0, 24)
				snake_case_    					=	3
				snake_case_    					=	[17, 25]
				snake_case_    					=	deque([Pa, Pa, Pa, Pa])

				if len(time_slices) != number_of_queues - 1:
								raise SystemExit(0)

				doctest.testmod(extraglobs={"""queue""": deque([Pa, Pa, Pa, Pa])})

				snake_case_    					=	Process("""P1""", 0, 53)
				snake_case_    					=	Process("""P2""", 0, 17)
				snake_case_    					=	Process("""P3""", 0, 68)
				snake_case_    					=	Process("""P4""", 0, 24)
				snake_case_    					=	3
				snake_case_    					=	[17, 25]
				snake_case_    					=	deque([Pa, Pa, Pa, Pa])
				snake_case_    					=	MLFQ(number_of_queues, time_slices, queue, 0)
				snake_case_    					=	mlfq.multi_level_feedback_queue()

				# print total waiting times of processes(P1, P2, P3, P4)
				print(
				    f'''waiting time:\
        \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}'''
				)
				# print completion times of processes(P1, P2, P3, P4)
				print(
				    f'''completion time:\
        \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}'''
				)
				# print total turnaround times of processes(P1, P2, P3, P4)
				print(
				    f'''turnaround time:\
        \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}'''
				)
				# print sequence of finished processes
				print(
				    f'''sequence of finished processes:\
        {mlfq.calculate_sequence_of_finish_queue()}'''
				)





