





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    _a     :






							"""simple docstring"""

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

							def      A_  (      self				:     Optional[Any]    )	->Optional[int]:
													SCREAMING_SNAKE_CASE__     :				Tuple   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					None
													if self.use_labels:
																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					ids_tensor([self.batch_size]							,	self.type_sequence_label_size    )

													SCREAMING_SNAKE_CASE__     :				Dict   =					self.get_config()

													return config, pixel_values, labels

							def      A_  (      self				:     Union[str, Any]    )	->int:
													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      A_  (      self				:     List[Any]    )	->Any:
													return UperNetConfig(
													    backbone_config=self.get_backbone_config()							,	hidden_size=5_12							,	pool_scales=[1, 2, 3, 6]							,	use_auxiliary_head=a							,	auxiliary_loss_weight=0.4							,	auxiliary_in_channels=40							,	auxiliary_channels=2_56							,	auxiliary_num_convs=1							,	auxiliary_concat_input=a							,	loss_ignore_index=2_55							,	num_labels=self.num_labels							,	)

							def      A_  (      self				:     str							,	a				:     Tuple							,	a				:     List[Any]							,	a				:     Optional[int]    )	->Optional[int]:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					UperNetForSemanticSegmentation(config=a    )
													model.to(a    )
													model.eval()
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					model(a    )
													self.parent.assertEqual(
													    result.logits.shape							,	(self.batch_size, self.num_labels, self.image_size, self.image_size)    )






							def      A_  (      self				:     Optional[int]    )	->str:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					self.prepare_config_and_inputs()
													(
													    (
													    SCREAMING_SNAKE_CASE__
													),							(
													    SCREAMING_SNAKE_CASE__
													),							(
													    SCREAMING_SNAKE_CASE__
													),							
													)     :				Tuple   =					config_and_inputs
													SCREAMING_SNAKE_CASE__     :				Dict   =					{"pixel_values": pixel_values}
													return config, inputs_dict







@require_torch
class    _a     (				lowercase__					,							lowercase__					,							unittest.TestCase							):






							"""simple docstring"""

							snake_case_							 =						(UperNetForSemanticSegmentation,) if is_torch_available() else ()
							snake_case_							 =						{"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {}
							snake_case_							 =						False
							snake_case_							 =						False
							snake_case_							 =						False
							snake_case_							 =						False
							snake_case_							 =						False
							snake_case_							 =						False

							def      A_  (      self				:     Any    )	->Optional[int]:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					UperNetModelTester(self    )
													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					ConfigTester(self							,	config_class=a							,	has_text_modality=a							,	hidden_size=37    )

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

							def      A_  (      self				:     Dict    )	->Dict:
													SCREAMING_SNAKE_CASE__,							SCREAMING_SNAKE_CASE__     :				Optional[int]   =					self.model_tester.prepare_config_and_inputs_for_common()

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

																			SCREAMING_SNAKE_CASE__     :				Tuple   =					["pixel_values"]
																			self.assertListEqual(arg_names[:1]							,	a    )

							def      A_  (      self				:     List[Any]    )	->Optional[Any]:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_semantic_segmentation(*a    )

							@unittest.skip(reason="UperNet does not use inputs_embeds"    )
							def      A_  (      self				:     Optional[Any]    )	->str:
													pass

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

							@unittest.skip(reason="UperNet does not have a base model"    )
							def      A_  (      self				:     Union[str, Any]    )	->List[Any]:
													pass

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

							@require_torch_multi_gpu
							@unittest.skip(reason="UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"    )
							def      A_  (      self				:     Dict    )	->List[str]:
													pass

							@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."    )
							def      A_  (      self				:     str    )	->List[Any]:
													pass

							def      A_  (      self				:     List[str]    )	->Tuple:
													def check_hidden_states_output(a				:     Tuple							,	a				:     Any							,	a				:     Optional[Any]    ):
																			SCREAMING_SNAKE_CASE__     :				Optional[int]   =					model_class(a    )
																			model.to(a    )
																			model.eval()

																			with torch.no_grad():
																									SCREAMING_SNAKE_CASE__     :				str   =					model(**self._prepare_for_class(a							,	a    )    )

																			SCREAMING_SNAKE_CASE__     :				Any   =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																			SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					self.model_tester.num_stages
																			self.assertEqual(len(a    )							,	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]							,	)

													SCREAMING_SNAKE_CASE__,							SCREAMING_SNAKE_CASE__     :				str   =					self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																			SCREAMING_SNAKE_CASE__     :				List[str]   =					True
																			check_hidden_states_output(a							,	a							,	a    )

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

																			check_hidden_states_output(a							,	a							,	a    )

							def      A_  (      self				:     Tuple    )	->Union[str, Any]:
													SCREAMING_SNAKE_CASE__,							SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					self.model_tester.prepare_config_and_inputs_for_common()

													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					_config_zero_init(a    )
													SCREAMING_SNAKE_CASE__     :				List[str]   =					_config_zero_init(configs_no_init.backbone_config    )
													for model_class in self.all_model_classes:
																			SCREAMING_SNAKE_CASE__     :				Tuple   =					model_class(config=a    )
																			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      A_  (      self				:     List[str]    )	->List[str]:
													pass






							@slow
							def      A_  (      self				:     Any    )	->List[str]:
													for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			SCREAMING_SNAKE_CASE__     :				Dict   =					UperNetForSemanticSegmentation.from_pretrained(a    )
																			self.assertIsNotNone(a    )







def       UpperCAmelCase							(     ):





						'''simple docstring'''


						SCREAMING_SNAKE_CASE__     :				Optional[int]   =					hf_hub_download(
						    repo_id="hf-internal-testing/fixtures_ade20k"			,   repo_type="dataset"			,   filename="ADE_val_00000001.jpg"     )
						SCREAMING_SNAKE_CASE__     :				Tuple   =					Image.open(_lowerCamelCase     ).convert("RGB"     )
						return image



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






							"""simple docstring"""

							def      A_  (      self				:     Any    )	->Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"    )
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"    ).to(a    )

													SCREAMING_SNAKE_CASE__     :				int   =					prepare_img()
													SCREAMING_SNAKE_CASE__     :				Dict   =					processor(images=a							,	return_tensors="pt"    ).to(a    )

													with torch.no_grad():
																			SCREAMING_SNAKE_CASE__     :				str   =					model(**a    )

													SCREAMING_SNAKE_CASE__     :				Dict   =					torch.Size((1, model.config.num_labels, 5_12, 5_12)    )
													self.assertEqual(outputs.logits.shape							,	a    )

													SCREAMING_SNAKE_CASE__     :				Dict   =					torch.tensor(
													    [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]    ).to(a    )
													self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]							,	a							,	atol=1E-4    )    )






							def      A_  (      self				:     Tuple    )	->Optional[int]:
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"    )
													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"    ).to(a    )

													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					prepare_img()
													SCREAMING_SNAKE_CASE__     :				Dict   =					processor(images=a							,	return_tensors="pt"    ).to(a    )

													with torch.no_grad():
																			SCREAMING_SNAKE_CASE__     :				Any   =					model(**a    )

													SCREAMING_SNAKE_CASE__     :				Any   =					torch.Size((1, model.config.num_labels, 5_12, 5_12)    )
													self.assertEqual(outputs.logits.shape							,	a    )

													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					torch.tensor(
													    [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]    ).to(a    )
													self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]							,	a							,	atol=1E-4    )    )






def       UpperCAmelCase							(     _lowerCamelCase      :  int			,   _lowerCamelCase      :  bool = False     ):





						'''simple docstring'''


						if n == 2:
												return True
						if not n % 2 or n < 2:
												return False
						if n > 5 and n % 10 not in (1, 3, 7, 9):  # can quickly check last digit
												return False
						if n > 3_317_044_064_679_887_385_961_981 and not allow_probable:
												raise ValueError(
												    "Warning: upper bound of deterministic test is exceeded. "
												    "Pass allow_probable=True to allow probabilistic test. "
												    "A return value of True indicates a probable prime."     )
						# array bounds provided by analysis
						SCREAMING_SNAKE_CASE__     :				List[str]   =					[
						    2_047,
						    1_373_653,
						    25_326_001,
						    3_215_031_751,
						    2_152_302_898_747,
						    3_474_749_660_383,
						    341_550_071_728_321,
						    1,
						    3_825_123_056_546_413_051,
						    1,
						    1,
						    318_665_857_834_031_151_167_461,
						    3_317_044_064_679_887_385_961_981,
						]

						SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
						for idx, _p in enumerate(_lowerCamelCase			,   1     ):
												if n < _p:
																		# then we have our last prime to check
																		SCREAMING_SNAKE_CASE__     :				Dict   =					primes[:idx]
																		break
						SCREAMING_SNAKE_CASE__,							SCREAMING_SNAKE_CASE__     :				Dict   =					n - 1, 0
						# break up n -1 into a power of 2 (s) and
						# remaining odd component
						# essentially, solve for d * 2 ** s == n - 1
						while d % 2 == 0:
												d //= 2
												s += 1
						for prime in plist:
												SCREAMING_SNAKE_CASE__     :				str   =					False
												for r in range(_lowerCamelCase     ):
																		SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					pow(_lowerCamelCase			,   d * 2**r			,   _lowerCamelCase     )
																		# see article for analysis explanation for m
																		if (r == 0 and m == 1) or ((m + 1) % n == 0):
																								SCREAMING_SNAKE_CASE__     :				str   =					True
																								# this loop will not determine compositeness
																								break
												if pr:
																		continue
												# if pr is False, then the above loop never evaluated to true,
												# and the n MUST be composite
												return False
						return True







def       UpperCAmelCase							(     ):





						'''simple docstring'''


						assert not miller_rabin(561     )
						assert miller_rabin(563     )
						# 2047

						assert not miller_rabin(838_201     )
						assert miller_rabin(838_207     )
						# 1_373_653

						assert not miller_rabin(17_316_001     )
						assert miller_rabin(17_316_017     )
						# 25_326_001

						assert not miller_rabin(3_078_386_641     )
						assert miller_rabin(3_078_386_653     )
						# 3_215_031_751

						assert not miller_rabin(1_713_045_574_801     )
						assert miller_rabin(1_713_045_574_819     )
						# 2_152_302_898_747

						assert not miller_rabin(2_779_799_728_307     )
						assert miller_rabin(2_779_799_728_327     )
						# 3_474_749_660_383

						assert not miller_rabin(113_850_023_909_441     )
						assert miller_rabin(113_850_023_909_527     )
						# 341_550_071_728_321

						assert not miller_rabin(1_275_041_018_848_804_351     )
						assert miller_rabin(1_275_041_018_848_804_391     )
						# 3_825_123_056_546_413_051

						assert not miller_rabin(79_666_464_458_507_787_791_867     )
						assert miller_rabin(79_666_464_458_507_787_791_951     )
						# 318_665_857_834_031_151_167_461

						assert not miller_rabin(552_840_677_446_647_897_660_333     )
						assert miller_rabin(552_840_677_446_647_897_660_359     )
						# 3_317_044_064_679_887_385_961_981
						# upper limit for probabilistic test


if __name__ == "__main__":
				test_miller_rabin()