






import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

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 transformers import UperNetForSemanticSegmentation
		from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor



class   lowerCamelCase      :







		'''simple docstring'''



		def __init__(							self				,		_UpperCamelCase				,		_UpperCamelCase=1_3				,		_UpperCamelCase=3_2				,		_UpperCamelCase=3				,		_UpperCamelCase=4				,		_UpperCamelCase=[1_0, 2_0, 3_0, 4_0]				,		_UpperCamelCase=[2, 2, 3, 2]				,		_UpperCamelCase=True				,		_UpperCamelCase=True				,		_UpperCamelCase=3_7				,		_UpperCamelCase="gelu"				,		_UpperCamelCase=1_0				,		_UpperCamelCase=0.02				,		_UpperCamelCase=["stage2", "stage3", "stage4"]				,		_UpperCamelCase=3				,		_UpperCamelCase=None				,		)	->							Tuple:
							UpperCAmelCase_    :      Optional[int]            =						parent
							UpperCAmelCase_    :      Any            =						batch_size
							UpperCAmelCase_    :      Union[str, Any]            =						image_size
							UpperCAmelCase_    :      Any            =						num_channels
							UpperCAmelCase_    :      Union[str, Any]            =						num_stages
							UpperCAmelCase_    :      Dict            =						hidden_sizes
							UpperCAmelCase_    :      Union[str, Any]            =						depths
							UpperCAmelCase_    :      Dict            =						is_training
							UpperCAmelCase_    :      List[Any]            =						use_labels
							UpperCAmelCase_    :      int            =						intermediate_size
							UpperCAmelCase_    :      List[Any]            =						hidden_act
							UpperCAmelCase_    :      List[Any]            =						type_sequence_label_size
							UpperCAmelCase_    :      Any            =						initializer_range
							UpperCAmelCase_    :      List[Any]            =						out_features
							UpperCAmelCase_    :      str            =						num_labels
							UpperCAmelCase_    :      Tuple            =						scope
							UpperCAmelCase_    :      List[Any]            =						num_stages



		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							UpperCAmelCase_    :      Tuple            =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

							UpperCAmelCase_    :      Dict            =						self.get_config()

							return config, pixel_values, labels



		def 					__UpperCAmelCase			(							self   )	->							Tuple:
							return ConvNextConfig(
							    num_channels=self.num_channels				,		num_stages=self.num_stages				,		hidden_sizes=self.hidden_sizes				,		depths=self.depths				,		is_training=self.is_training				,		intermediate_size=self.intermediate_size				,		hidden_act=self.hidden_act				,		out_features=self.out_features				,		)



		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							return UperNetConfig(
							    backbone_config=self.get_backbone_config()				,		hidden_size=5_1_2				,		pool_scales=[1, 2, 3, 6]				,		use_auxiliary_head=_UpperCamelCase				,		auxiliary_loss_weight=0.4				,		auxiliary_in_channels=4_0				,		auxiliary_channels=2_5_6				,		auxiliary_num_convs=1				,		auxiliary_concat_input=_UpperCamelCase				,		loss_ignore_index=2_5_5				,		num_labels=self.num_labels				,		)



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )	->							Any:
							UpperCAmelCase_    :      Optional[int]            =						UperNetForSemanticSegmentation(config=_UpperCamelCase   )
							model.to(_UpperCamelCase   )
							model.eval()
							UpperCAmelCase_    :      int            =						model(_UpperCamelCase   )
							self.parent.assertEqual(
							    result.logits.shape				,		(self.batch_size, self.num_labels, self.image_size, self.image_size)   )



		def 					__UpperCAmelCase			(							self   )	->							Optional[int]:
							UpperCAmelCase_    :      Tuple            =						self.prepare_config_and_inputs()
							(
							    (
							    UpperCAmelCase_
							)       ,  (
							    UpperCAmelCase_
							)       ,  (
							    UpperCAmelCase_
							)       ,  
							)    :      List[str]            =						config_and_inputs
							UpperCAmelCase_    :      Optional[Any]            =						{'pixel_values': pixel_values}
							return config, inputs_dict





@require_torch
class   lowerCamelCase      (_snake_case ,  _snake_case ,  unittest.TestCase			):







		'''simple docstring'''



		_snake_case    :    str       						=  (UperNetForSemanticSegmentation,) if is_torch_available() else ()
		_snake_case    :    List[str]       						=  {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
		_snake_case    :    Tuple       						=  False
		_snake_case    :    Optional[Any]       						=  False
		_snake_case    :    Optional[Any]       						=  False
		_snake_case    :    List[str]       						=  False
		_snake_case    :    Any       						=  False
		_snake_case    :    Dict       						=  False



		def 					__UpperCAmelCase			(							self   )	->							List[str]:
							UpperCAmelCase_    :      Optional[int]            =						UperNetModelTester(self   )
							UpperCAmelCase_    :      int            =						ConfigTester(self				,		config_class=_UpperCamelCase				,		has_text_modality=_UpperCamelCase				,		hidden_size=3_7   )



		def 					__UpperCAmelCase			(							self   )	->							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   )	->							List[Any]:
							return



		def 					__UpperCAmelCase			(							self   )	->							Tuple:
							UpperCAmelCase_       ,  UpperCAmelCase_    :      Any            =						self.model_tester.prepare_config_and_inputs_for_common()

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

												UpperCAmelCase_    :      List[str]            =						['pixel_values']
												self.assertListEqual(arg_names[:1]				,		_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							Union[str, Any]:
							UpperCAmelCase_    :      Any            =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCamelCase   )



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



		@unittest.skip(reason='UperNet does not support input and output embeddings'   )
		def 					__UpperCAmelCase			(							self   )	->							Any:
							pass



		@unittest.skip(reason='UperNet does not have a base model'   )
		def 					__UpperCAmelCase			(							self   )	->							List[Any]:
							pass



		@unittest.skip(reason='UperNet does not have a base model'   )
		def 					__UpperCAmelCase			(							self   )	->							Any:
							pass



		@require_torch_multi_gpu
		@unittest.skip(reason='UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'   )
		def 					__UpperCAmelCase			(							self   )	->							int:
							pass



		@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'   )
		def 					__UpperCAmelCase			(							self   )	->							str:
							pass



		def 					__UpperCAmelCase			(							self   )	->							Optional[int]:
							def check_hidden_states_output(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   ):
												UpperCAmelCase_    :      Tuple            =						model_class(_UpperCamelCase   )
												model.to(_UpperCamelCase   )
												model.eval()

												with torch.no_grad():
																	UpperCAmelCase_    :      int            =						model(**self._prepare_for_class(_UpperCamelCase				,		_UpperCamelCase   )   )

												UpperCAmelCase_    :      Optional[Any]            =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												UpperCAmelCase_    :      Tuple            =						self.model_tester.num_stages
												self.assertEqual(len(_UpperCamelCase   )				,		expected_num_stages + 1   )

												# ConvNext'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_    :      int            =						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												UpperCAmelCase_    :      Tuple            =						True
												check_hidden_states_output(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )

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

												check_hidden_states_output(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							Dict:
							UpperCAmelCase_       ,  UpperCAmelCase_    :      str            =						self.model_tester.prepare_config_and_inputs_for_common()

							UpperCAmelCase_    :      int            =						_config_zero_init(_UpperCamelCase   )
							UpperCAmelCase_    :      List[str]            =						_config_zero_init(configs_no_init.backbone_config   )
							for model_class in self.all_model_classes:
												UpperCAmelCase_    :      List[str]            =						model_class(config=_UpperCamelCase   )
												for name, param in model.named_parameters():
																	if 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"				,		)



		@unittest.skip(reason='UperNet does not have tied weights'   )
		def 					__UpperCAmelCase			(							self   )	->							Optional[int]:
							pass



		@slow
		def 					__UpperCAmelCase			(							self   )	->							List[Any]:
							for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase_    :      Tuple            =						UperNetForSemanticSegmentation.from_pretrained(_UpperCamelCase   )
												self.assertIsNotNone(_UpperCamelCase   )





def      lowercase__      (     ):


					'''simple docstring'''


					UpperCAmelCase_    :      str            =						hf_hub_download(
					    repo_id='hf-internal-testing/fixtures_ade20k'     ,       repo_type='dataset'     ,       filename='ADE_val_00000001.jpg'  )
					UpperCAmelCase_    :      Optional[Any]            =						Image.open(__snake_case  ).convert('RGB'  )
					return image






@require_torch
@require_vision
@slow
class   lowerCamelCase      (unittest.TestCase			):







		'''simple docstring'''



		def 					__UpperCAmelCase			(							self   )	->							Tuple:
							UpperCAmelCase_    :      int            =						AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'   )
							UpperCAmelCase_    :      Optional[int]            =						UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'   ).to(_UpperCamelCase   )

							UpperCAmelCase_    :      Union[str, Any]            =						prepare_img()
							UpperCAmelCase_    :      Optional[Any]            =						processor(images=_UpperCamelCase				,		return_tensors='pt'   ).to(_UpperCamelCase   )

							with torch.no_grad():
												UpperCAmelCase_    :      Optional[int]            =						model(**_UpperCamelCase   )

							UpperCAmelCase_    :      Any            =						torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)   )
							self.assertEqual(outputs.logits.shape				,		_UpperCamelCase   )

							UpperCAmelCase_    :      List[str]            =						torch.tensor(
							    [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]]   ).to(_UpperCamelCase   )
							self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]				,		_UpperCamelCase				,		atol=1E-4   )   )



		def 					__UpperCAmelCase			(							self   )	->							List[Any]:
							UpperCAmelCase_    :      Optional[int]            =						AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'   )
							UpperCAmelCase_    :      str            =						UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'   ).to(_UpperCamelCase   )

							UpperCAmelCase_    :      Any            =						prepare_img()
							UpperCAmelCase_    :      List[str]            =						processor(images=_UpperCamelCase				,		return_tensors='pt'   ).to(_UpperCamelCase   )

							with torch.no_grad():
												UpperCAmelCase_    :      Optional[Any]            =						model(**_UpperCamelCase   )

							UpperCAmelCase_    :      int            =						torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)   )
							self.assertEqual(outputs.logits.shape				,		_UpperCamelCase   )

							UpperCAmelCase_    :      Dict            =						torch.tensor(
							    [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]   ).to(_UpperCamelCase   )
							self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]				,		_UpperCamelCase				,		atol=1E-4   )   )







"""simple docstring"""
def 						__a   (	_SCREAMING_SNAKE_CASE = 1000000   )	->int:
  a__:     int										=	limit + 1
  a__:     Optional[int]										=	[0] * limit
  for first_term in range(1		,     _SCREAMING_SNAKE_CASE   ):
    for n in range(_SCREAMING_SNAKE_CASE		,     _SCREAMING_SNAKE_CASE		,     _SCREAMING_SNAKE_CASE   ):
      a__:     List[Any]										=	first_term + n / first_term
      if common_difference % 4:  # d must be divisble by 4
        continue
      else:
        common_difference /= 4
        if (
            first_term > common_difference
            and first_term < 4 * common_difference
        ):  # since x,y,z are positive integers
          frequency[n] += 1  # so z>0 and a>d ,also 4d<a

  a__:     Any										=	sum(1 for x in frequency[1:limit] if x == 10   )

  return count


if __name__ == "__main__":
 print(f"{solution() = }")


