



"""simple docstring"""






import collections
import inspect
import unittest

from transformers import FocalNetConfig
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, _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 (
	    FocalNetBackbone,
	    FocalNetForImageClassification,
	    FocalNetForMaskedImageModeling,
	    FocalNetModel,
	)
	from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor



class      A__  :




	'''simple docstring'''





	def __init__(	self:						Union[str, Any]			,     _SCREAMING_SNAKE_CASE:						Tuple			,     _SCREAMING_SNAKE_CASE:						Optional[int]=13			,     _SCREAMING_SNAKE_CASE:						Optional[Any]=32			,     _SCREAMING_SNAKE_CASE:						int=2			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=3			,     _SCREAMING_SNAKE_CASE:						List[str]=16			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=[32, 64, 128]			,     _SCREAMING_SNAKE_CASE:						Dict=[1, 2, 1]			,     _SCREAMING_SNAKE_CASE:						Optional[Any]=[2, 2, 4]			,     _SCREAMING_SNAKE_CASE:						str=2			,     _SCREAMING_SNAKE_CASE:						Optional[int]=2.0			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=True			,     _SCREAMING_SNAKE_CASE:						Dict=0.0			,     _SCREAMING_SNAKE_CASE:						Optional[int]=0.0			,     _SCREAMING_SNAKE_CASE:						Dict=0.1			,     _SCREAMING_SNAKE_CASE:						Dict="gelu"			,     _SCREAMING_SNAKE_CASE:						int=False			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=True			,     _SCREAMING_SNAKE_CASE:						List[str]=0.02			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=1e-5			,     _SCREAMING_SNAKE_CASE:						str=True			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]=None			,     _SCREAMING_SNAKE_CASE:						str=True			,     _SCREAMING_SNAKE_CASE:						Optional[int]=10			,     _SCREAMING_SNAKE_CASE:						Optional[int]=8			,     _SCREAMING_SNAKE_CASE:						List[str]=["stage1", "stage2"]			,     _SCREAMING_SNAKE_CASE:						Optional[int]=[1, 2]			,     )							->			List[Any]:

				"""simple docstring"""

				__lowerCAmelCase :    Optional[int]				=			parent
				__lowerCAmelCase :    Any				=			batch_size
				__lowerCAmelCase :    Union[str, Any]				=			image_size
				__lowerCAmelCase :    str				=			patch_size
				__lowerCAmelCase :    List[str]				=			num_channels
				__lowerCAmelCase :    List[str]				=			embed_dim
				__lowerCAmelCase :    int				=			hidden_sizes
				__lowerCAmelCase :    str				=			depths
				__lowerCAmelCase :    Union[str, Any]				=			num_heads
				__lowerCAmelCase :    Tuple				=			window_size
				__lowerCAmelCase :    str				=			mlp_ratio
				__lowerCAmelCase :    Any				=			qkv_bias
				__lowerCAmelCase :    int				=			hidden_dropout_prob
				__lowerCAmelCase :    List[str]				=			attention_probs_dropout_prob
				__lowerCAmelCase :    Optional[int]				=			drop_path_rate
				__lowerCAmelCase :    Any				=			hidden_act
				__lowerCAmelCase :    int				=			use_absolute_embeddings
				__lowerCAmelCase :    Union[str, Any]				=			patch_norm
				__lowerCAmelCase :    Tuple				=			layer_norm_eps
				__lowerCAmelCase :    Optional[int]				=			initializer_range
				__lowerCAmelCase :    Optional[Any]				=			is_training
				__lowerCAmelCase :    Union[str, Any]				=			scope
				__lowerCAmelCase :    Any				=			use_labels
				__lowerCAmelCase :    Optional[Any]				=			type_sequence_label_size
				__lowerCAmelCase :    Tuple				=			encoder_stride
				__lowerCAmelCase :    Optional[Any]				=			out_features
				__lowerCAmelCase :    List[Any]				=			out_indices

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[str])							->			List[str]:

				"""simple docstring"""

				__lowerCAmelCase :    List[Any]				=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

				__lowerCAmelCase :    List[Any]				=			None
				if self.use_labels:
							__lowerCAmelCase :    Any				=			ids_tensor([self.batch_size]			,     self.type_sequence_label_size)

				__lowerCAmelCase :    Dict				=			self.get_config()

				return config, pixel_values, labels

	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[int])							->			Union[str, Any]:

				"""simple docstring"""

				return FocalNetConfig(
				    image_size=self.image_size			,     patch_size=self.patch_size			,     num_channels=self.num_channels			,     embed_dim=self.embed_dim			,     hidden_sizes=self.hidden_sizes			,     depths=self.depths			,     num_heads=self.num_heads			,     window_size=self.window_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			,     use_absolute_embeddings=self.use_absolute_embeddings			,     path_norm=self.patch_norm			,     layer_norm_eps=self.layer_norm_eps			,     initializer_range=self.initializer_range			,     encoder_stride=self.encoder_stride			,     out_features=self.out_features			,     out_indices=self.out_indices			,     )

	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict			,     _SCREAMING_SNAKE_CASE:						Any			,     _SCREAMING_SNAKE_CASE:						str			,     _SCREAMING_SNAKE_CASE:						Tuple)							->			Tuple:

				"""simple docstring"""

				__lowerCAmelCase :    List[str]				=			FocalNetModel(config=_lowerCamelCase)
				model.to(_lowerCamelCase)
				model.eval()
				__lowerCAmelCase :    Union[str, Any]				=			model(_lowerCamelCase)

				__lowerCAmelCase :    int				=			((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1))
				__lowerCAmelCase :    Dict				=			int(config.embed_dim * 2 ** (len(config.depths) - 1))

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

	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[Any]			,     _SCREAMING_SNAKE_CASE:						List[Any]			,     _SCREAMING_SNAKE_CASE:						Tuple			,     _SCREAMING_SNAKE_CASE:						List[Any])							->			Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase :    Optional[Any]				=			FocalNetBackbone(config=_lowerCamelCase)
				model.to(_lowerCamelCase)
				model.eval()
				__lowerCAmelCase :    str				=			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.image_size, 8, 8])

				# 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
				__lowerCAmelCase :    Optional[Any]				=			None
				__lowerCAmelCase :    Optional[int]				=			FocalNetBackbone(config=_lowerCamelCase)
				model.to(_lowerCamelCase)
				model.eval()
				__lowerCAmelCase :    int				=			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.image_size * 2, 4, 4])

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

	def 				_SCREAMING_SNAKE_CASE  (	self:						Union[str, Any]			,     _SCREAMING_SNAKE_CASE:						List[str]			,     _SCREAMING_SNAKE_CASE:						Union[str, Any]			,     _SCREAMING_SNAKE_CASE:						int)							->			List[Any]:

				"""simple docstring"""

				__lowerCAmelCase :    Optional[int]				=			FocalNetForMaskedImageModeling(config=_lowerCamelCase)
				model.to(_lowerCamelCase)
				model.eval()
				__lowerCAmelCase :    List[str]				=			model(_lowerCamelCase)
				self.parent.assertEqual(
				    result.reconstruction.shape			,     (self.batch_size, self.num_channels, self.image_size, self.image_size))

				# test greyscale images
				__lowerCAmelCase :    Optional[int]				=			1
				__lowerCAmelCase :    List[Any]				=			FocalNetForMaskedImageModeling(_lowerCamelCase)
				model.to(_lowerCamelCase)
				model.eval()

				__lowerCAmelCase :    Tuple				=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
				__lowerCAmelCase :    Tuple				=			model(_lowerCamelCase)
				self.parent.assertEqual(result.reconstruction.shape			,     (self.batch_size, 1, self.image_size, self.image_size))

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[Any]			,     _SCREAMING_SNAKE_CASE:						List[Any]			,     _SCREAMING_SNAKE_CASE:						List[str]			,     _SCREAMING_SNAKE_CASE:						Any)							->			Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase :    Any				=			self.type_sequence_label_size
				__lowerCAmelCase :    Tuple				=			FocalNetForImageClassification(_lowerCamelCase)
				model.to(_lowerCamelCase)
				model.eval()
				__lowerCAmelCase :    Union[str, Any]				=			model(_lowerCamelCase			,     labels=_lowerCamelCase)
				self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size))

				# test greyscale images
				__lowerCAmelCase :    Tuple				=			1
				__lowerCAmelCase :    Optional[Any]				=			FocalNetForImageClassification(_lowerCamelCase)
				model.to(_lowerCamelCase)
				model.eval()

				__lowerCAmelCase :    str				=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
				__lowerCAmelCase :    Tuple				=			model(_lowerCamelCase)
				self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size))







	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict)							->			Tuple:

				"""simple docstring"""

				__lowerCAmelCase :    Tuple				=			self.prepare_config_and_inputs()

				__lowerCAmelCase		,      __lowerCAmelCase		,      __lowerCAmelCase :    Optional[Any]				=			config_and_inputs
				__lowerCAmelCase :    List[Any]				=			{"pixel_values": pixel_values}
				return config, inputs_dict






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




	'''simple docstring'''





	SCREAMING_SNAKE_CASE        =      (
	    (
	        FocalNetModel,
	        FocalNetForImageClassification,
	        FocalNetForMaskedImageModeling,
	        FocalNetBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	SCREAMING_SNAKE_CASE        =      (
	    {'feature-extraction': FocalNetModel, 'image-classification': FocalNetForImageClassification}
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE        =      False

	SCREAMING_SNAKE_CASE        =      False
	SCREAMING_SNAKE_CASE        =      False
	SCREAMING_SNAKE_CASE        =      False
	SCREAMING_SNAKE_CASE        =      False

	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict)							->			Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase :    Any				=			FocalNetModelTester(self)
				__lowerCAmelCase :    str				=			ConfigTester(self			,     config_class=_lowerCamelCase			,     embed_dim=37			,     has_text_modality=_lowerCamelCase)

	def 				_SCREAMING_SNAKE_CASE  (	self:						Any)							->			Optional[int]:

				"""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 				_SCREAMING_SNAKE_CASE  (	self:						int)							->			List[str]:

				"""simple docstring"""

				return

	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[Any])							->			Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase :    Optional[int]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_lowerCamelCase)

	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[int])							->			str:

				"""simple docstring"""

				__lowerCAmelCase :    Union[str, Any]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_backbone(*_lowerCamelCase)

	def 				_SCREAMING_SNAKE_CASE  (	self:						Union[str, Any])							->			Tuple:

				"""simple docstring"""

				__lowerCAmelCase :    List[str]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase)

	def 				_SCREAMING_SNAKE_CASE  (	self:						Any)							->			Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase :    List[Any]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase)

	@unittest.skip(reason="FocalNet does not use inputs_embeds")
	def 				_SCREAMING_SNAKE_CASE  (	self:						Any)							->			int:

				"""simple docstring"""

				pass

	@unittest.skip(reason="FocalNet does not use feedforward chunking")
	def 				_SCREAMING_SNAKE_CASE  (	self:						int)							->			str:

				"""simple docstring"""

				pass

	def 				_SCREAMING_SNAKE_CASE  (	self:						Optional[Any])							->			List[str]:

				"""simple docstring"""

				__lowerCAmelCase		,      __lowerCAmelCase :    Optional[int]				=			self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes[:-1]:
							__lowerCAmelCase :    List[str]				=			model_class(_lowerCamelCase)
							self.assertIsInstance(model.get_input_embeddings()			,     (nn.Module))
							__lowerCAmelCase :    str				=			model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(_lowerCamelCase			,     nn.Linear))

	def 				_SCREAMING_SNAKE_CASE  (	self:						int)							->			str:

				"""simple docstring"""

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

				for model_class in self.all_model_classes[:-1]:
							__lowerCAmelCase :    Optional[Any]				=			model_class(_lowerCamelCase)
							__lowerCAmelCase :    Any				=			inspect.signature(model.forward)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							__lowerCAmelCase :    Tuple				=			[*signature.parameters.keys()]

							__lowerCAmelCase :    str				=			["pixel_values"]
							self.assertListEqual(arg_names[:1]			,     _lowerCamelCase)

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[Any]			,     _SCREAMING_SNAKE_CASE:						Dict			,     _SCREAMING_SNAKE_CASE:						Optional[Any]			,     _SCREAMING_SNAKE_CASE:						Tuple			,     _SCREAMING_SNAKE_CASE:						Tuple)							->			Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase :    Optional[Any]				=			model_class(_lowerCamelCase)
				model.to(_lowerCamelCase)
				model.eval()

				with torch.no_grad():
							__lowerCAmelCase :    str				=			model(**self._prepare_for_class(_lowerCamelCase			,     _lowerCamelCase))

				__lowerCAmelCase :    List[str]				=			outputs.hidden_states

				__lowerCAmelCase :    List[Any]				=			getattr(
				    self.model_tester			,     "expected_num_hidden_layers"			,     len(self.model_tester.depths) + 1)
				self.assertEqual(len(_lowerCamelCase)			,     _lowerCamelCase)

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

				__lowerCAmelCase :    Optional[Any]				=			(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

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

				__lowerCAmelCase :    Optional[int]				=			outputs.reshaped_hidden_states
				self.assertEqual(len(_lowerCamelCase)			,     _lowerCamelCase)

				__lowerCAmelCase		,      __lowerCAmelCase		,      __lowerCAmelCase		,      __lowerCAmelCase :    Optional[Any]				=			reshaped_hidden_states[0].shape
				__lowerCAmelCase :    Union[str, Any]				=			(
				    reshaped_hidden_states[0].view(_lowerCamelCase			,     _lowerCamelCase			,     height * width).permute(0			,     2			,     1)
				)
				self.assertListEqual(
				    list(reshaped_hidden_states.shape[-2:])			,     [num_patches, self.model_tester.embed_dim]			,     )

	def 				_SCREAMING_SNAKE_CASE  (	self:						List[Any])							->			Any:

				"""simple docstring"""

				__lowerCAmelCase		,      __lowerCAmelCase :    List[str]				=			self.model_tester.prepare_config_and_inputs_for_common()

				__lowerCAmelCase :    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[:-1]:
							__lowerCAmelCase :    Optional[int]				=			True
							self.check_hidden_states_output(_lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase)

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

							self.check_hidden_states_output(_lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase)

	def 				_SCREAMING_SNAKE_CASE  (	self:						Any)							->			Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase		,      __lowerCAmelCase :    List[Any]				=			self.model_tester.prepare_config_and_inputs_for_common()
				__lowerCAmelCase :    Optional[int]				=			3

				__lowerCAmelCase :    str				=			(
				    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)
				)
				__lowerCAmelCase :    Optional[Any]				=			(
				    config.patch_size
				    if isinstance(config.patch_size			,     collections.abc.Iterable)
				    else (config.patch_size, config.patch_size)
				)

				__lowerCAmelCase :    Optional[int]				=			image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
				__lowerCAmelCase :    Optional[Any]				=			image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

				for model_class in self.all_model_classes[:-1]:
							__lowerCAmelCase :    Union[str, Any]				=			True
							self.check_hidden_states_output(_lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     (padded_height, padded_width))

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							__lowerCAmelCase :    Union[str, Any]				=			True
							self.check_hidden_states_output(_lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase			,     (padded_height, padded_width))

	@slow
	def 				_SCREAMING_SNAKE_CASE  (	self:						Tuple)							->			Any:

				"""simple docstring"""

				for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__lowerCAmelCase :    Tuple				=			FocalNetModel.from_pretrained(_lowerCamelCase)
							self.assertIsNotNone(_lowerCamelCase)







	def 				_SCREAMING_SNAKE_CASE  (	self:						int)							->			Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase		,      __lowerCAmelCase :    List[str]				=			self.model_tester.prepare_config_and_inputs_for_common()

				__lowerCAmelCase :    Tuple				=			_config_zero_init(_lowerCamelCase)
				for model_class in self.all_model_classes:
							__lowerCAmelCase :    Tuple				=			model_class(config=_lowerCamelCase)
							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_vision
@require_torch
class      A__  (    unittest.TestCase				):




	'''simple docstring'''





	@cached_property
	def 				_SCREAMING_SNAKE_CASE  (	self:						List[str])							->			Any:

				"""simple docstring"""

				return AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny") if is_vision_available() else None







	@slow
	def 				_SCREAMING_SNAKE_CASE  (	self:						List[str])							->			str:

				"""simple docstring"""

				__lowerCAmelCase :    str				=			FocalNetForImageClassification.from_pretrained("microsoft/focalnet-tiny").to(_lowerCamelCase)
				__lowerCAmelCase :    Dict				=			self.default_image_processor

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

				# forward pass
				with torch.no_grad():
							__lowerCAmelCase :    Union[str, Any]				=			model(**_lowerCamelCase)

				# verify the logits
				__lowerCAmelCase :    Any				=			torch.Size((1, 1000))
				self.assertEqual(outputs.logits.shape			,     _lowerCamelCase)
				__lowerCAmelCase :    int				=			torch.tensor([0.2166, -0.4368, 0.2191]).to(_lowerCamelCase)
				self.assertTrue(torch.allclose(outputs.logits[0, :3]			,     _lowerCamelCase			,     atol=1e-4))
				self.assertTrue(outputs.logits.argmax(dim=-1).item()			,     281)






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




	'''simple docstring'''





	SCREAMING_SNAKE_CASE        =      (FocalNetBackbone,) if is_torch_available() else ()
	SCREAMING_SNAKE_CASE        =      FocalNetConfig

	SCREAMING_SNAKE_CASE        =      False

	def 				_SCREAMING_SNAKE_CASE  (	self:						Dict)							->			Any:

				"""simple docstring"""

				__lowerCAmelCase :    Dict				=			FocalNetModelTester(self)
'''simple docstring'''

import gc
import threading
import time

import psutil
import torch


class     __UpperCAmelCase       :





  def __init__(	self ):
     lowerCAmelCase_			=      psutil.Process()
     lowerCAmelCase_			=      False





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      -1

     while True:
        lowerCAmelCase_			=      max(self.process.memory_info().rss    ,     self.cpu_memory_peak )

        # can't sleep or will not catch the peak right (this comment is here on purpose)
        if not self.peak_monitoring:
           break





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      True
     lowerCAmelCase_			=      threading.Thread(target=self.peak_monitor )
     lowerCAmelCase_			=      True
     self.thread.start()







  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      False
     self.thread.join()
     return self.cpu_memory_peak






A_     :						List[str]    							=PeakCPUMemory()



def snake_case_      (					)			->					Tuple:
   # Time
   lowerCAmelCase_			=      {'''time''': time.time()}

   gc.collect()
   torch.cuda.empty_cache()

   # CPU mem
   lowerCAmelCase_			=      psutil.Process().memory_info().rss
   cpu_peak_tracker.start()

   # GPU mem
   for i in range(torch.cuda.device_count()):
      lowerCAmelCase_			=      torch.cuda.memory_allocated(__snake_case)
   torch.cuda.reset_peak_memory_stats()

   return measures



def snake_case_      (					__snake_case  :							Any)			->					List[str]:
   # Time
   lowerCAmelCase_			=      {'''time''': time.time() - start_measures['''time''']}

   gc.collect()
   torch.cuda.empty_cache()

   # CPU mem
   lowerCAmelCase_			=      (psutil.Process().memory_info().rss - start_measures['''cpu''']) / 2**20
   lowerCAmelCase_			=      (cpu_peak_tracker.stop() - start_measures['''cpu''']) / 2**20

   # GPU mem
   for i in range(torch.cuda.device_count()):
      lowerCAmelCase_			=      (torch.cuda.memory_allocated(__snake_case) - start_measures[str(__snake_case)]) / 2**20
      lowerCAmelCase_			=      (torch.cuda.max_memory_allocated(__snake_case) - start_measures[str(__snake_case)]) / 2**20

   return measures






def snake_case_      (					__snake_case  :							Dict	,   __snake_case  :							Optional[int])			->					Dict:
   print(F'''{description}:''')
   print(F'''- Time: {measures['time']:.2f}s''')
   for i in range(torch.cuda.device_count()):
      print(F'''- GPU {i} allocated: {measures[str(__snake_case)]:.2f}MiB''')
      lowerCAmelCase_			=      measures[F'''{i}-peak''']
      print(F'''- GPU {i} peak: {peak:.2f}MiB''')
   print(F'''- CPU RAM allocated: {measures['cpu']:.2f}MiB''')
   print(F'''- CPU RAM peak: {measures['cpu-peak']:.2f}MiB''')





