




"""simple docstring"""

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


			def __init__(   self ,       SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE=13 ,       SCREAMING_SNAKE_CASE=32 ,       SCREAMING_SNAKE_CASE=3 ,       SCREAMING_SNAKE_CASE=4 ,       SCREAMING_SNAKE_CASE=[10, 20, 30, 40] ,       SCREAMING_SNAKE_CASE=[2, 2, 3, 2] ,       SCREAMING_SNAKE_CASE=True ,       SCREAMING_SNAKE_CASE=True ,       SCREAMING_SNAKE_CASE=37 ,       SCREAMING_SNAKE_CASE="gelu" ,       SCREAMING_SNAKE_CASE=10 ,       SCREAMING_SNAKE_CASE=0.02 ,       SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] ,       SCREAMING_SNAKE_CASE=3 ,       SCREAMING_SNAKE_CASE=None ,       ):



					"""simple docstring"""







					snake_case						:  int    	= parent
					snake_case						:  Tuple    	= batch_size
					snake_case						:  Tuple    	= image_size
					snake_case						:  Optional[Any]    	= num_channels
					snake_case						:  Optional[int]    	= num_stages
					snake_case						:  Dict    	= hidden_sizes
					snake_case						:  List[str]    	= depths
					snake_case						:  str    	= is_training
					snake_case						:  Optional[int]    	= use_labels
					snake_case						:  List[str]    	= intermediate_size
					snake_case						:  Union[str, Any]    	= hidden_act
					snake_case						:  Union[str, Any]    	= type_sequence_label_size
					snake_case						:  Any    	= initializer_range
					snake_case						:  Dict    	= out_features
					snake_case						:  Optional[int]    	= num_labels
					snake_case						:  Union[str, Any]    	= scope
					snake_case						:  List[str]    	= num_stages


			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					snake_case						:  Optional[Any]    	= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

					snake_case						:  str    	= self.get_config()

					return config, pixel_values, labels


			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					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 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					return UperNetConfig(
					    backbone_config=self.get_backbone_config() ,       hidden_size=512 ,       pool_scales=[1, 2, 3, 6] ,       use_auxiliary_head=SCREAMING_SNAKE_CASE__ ,       auxiliary_loss_weight=0.4 ,       auxiliary_in_channels=40 ,       auxiliary_channels=256 ,       auxiliary_num_convs=1 ,       auxiliary_concat_input=SCREAMING_SNAKE_CASE__ ,       loss_ignore_index=255 ,       num_labels=self.num_labels ,       )


			def 							lowerCamelCase_ (   self ,       SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE							):



					"""simple docstring"""







					snake_case						:  Any    	= UperNetForSemanticSegmentation(config=SCREAMING_SNAKE_CASE__							)
					model.to(SCREAMING_SNAKE_CASE__							)
					model.eval()
					snake_case						:  Union[str, Any]    	= model(SCREAMING_SNAKE_CASE__							)
					self.parent.assertEqual(
					    result.logits.shape ,       (self.batch_size, self.num_labels, self.image_size, self.image_size)							)



			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					snake_case						:  Tuple    	= self.prepare_config_and_inputs()
					(
					    (
					    snake_case       
					)	, (
					    snake_case       
					)	, (
					    snake_case       
					)	,        
					)						:  Optional[int]    	= config_and_inputs
					snake_case						:  Union[str, Any]    	= {"pixel_values": pixel_values}
					return config, inputs_dict







@require_torch
class 	lowerCamelCase__			(     UpperCAmelCase__ ,     UpperCAmelCase__ ,     unittest.TestCase	):
			a__       :					Any	    =   (UperNetForSemanticSegmentation,) if is_torch_available() else ()
			a__       :					Any	    =   {"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {}
			a__       :					Dict	    =   False
			a__       :					Any	    =   False
			a__       :					Dict	    =   False
			a__       :					Optional[Any]	    =   False
			a__       :					int	    =   False
			a__       :					List[str]	    =   False


			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					snake_case						:  Tuple    	= UperNetModelTester(self							)
					snake_case						:  Dict    	= ConfigTester(self ,       config_class=SCREAMING_SNAKE_CASE__ ,       has_text_modality=SCREAMING_SNAKE_CASE__ ,       hidden_size=37							)


			def 							lowerCamelCase_ (   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 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					return


			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					snake_case	, snake_case						:  List[Any]    	= self.model_tester.prepare_config_and_inputs_for_common()

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

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


			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					snake_case						:  Tuple    	= self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE__							)


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



					"""simple docstring"""







					pass


			@unittest.skip(reason="UperNet does not support input and output embeddings"							)
			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					pass


			@unittest.skip(reason="UperNet does not have a base model"							)
			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					pass


			@unittest.skip(reason="UperNet does not have a base model"							)
			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					pass


			@require_torch_multi_gpu
			@unittest.skip(reason="UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"							)
			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					pass


			@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."							)
			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					pass


			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					def check_hidden_states_output(SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE ,       SCREAMING_SNAKE_CASE							):
							snake_case						:  Any    	= model_class(SCREAMING_SNAKE_CASE__							)
							model.to(SCREAMING_SNAKE_CASE__							)
							model.eval()

							with torch.no_grad():
									snake_case						:  List[Any]    	= model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__							)							)

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

							snake_case						:  int    	= self.model_tester.num_stages
							self.assertEqual(len(SCREAMING_SNAKE_CASE__							) ,       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] ,       )

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

					for model_class in self.all_model_classes:
							snake_case						:  Tuple    	= True
							check_hidden_states_output(SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__							)

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

							check_hidden_states_output(SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__							)


			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







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

					snake_case						:  List[Any]    	= _config_zero_init(SCREAMING_SNAKE_CASE__							)
					snake_case						:  Optional[Any]    	= _config_zero_init(configs_no_init.backbone_config							)
					for model_class in self.all_model_classes:
							snake_case						:  str    	= model_class(config=SCREAMING_SNAKE_CASE__							)
							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 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					pass



			@slow
			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case						:  Tuple    	= UperNetForSemanticSegmentation.from_pretrained(SCREAMING_SNAKE_CASE__							)
							self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)







def      UpperCamelCase__   (						):
		snake_case						:  int    	= hf_hub_download(
		    repo_id="hf-internal-testing/fixtures_ade20k"				,   repo_type="dataset"				,   filename="ADE_val_00000001.jpg"      )
		snake_case						:  List[Any]    	= Image.open(snake_case_      ).convert("RGB"      )
		return image
@require_torch
@require_vision
@slow
class 	lowerCamelCase__			(     unittest.TestCase	):


			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					snake_case						:  int    	= AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"							)
					snake_case						:  Optional[int]    	= UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"							).to(SCREAMING_SNAKE_CASE__							)

					snake_case						:  Optional[Any]    	= prepare_img()
					snake_case						:  Optional[Any]    	= processor(images=SCREAMING_SNAKE_CASE__ ,       return_tensors="pt"							).to(SCREAMING_SNAKE_CASE__							)

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

					snake_case						:  Dict    	= torch.Size((1, model.config.num_labels, 512, 512)							)
					self.assertEqual(outputs.logits.shape ,       SCREAMING_SNAKE_CASE__							)

					snake_case						:  Any    	= 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(SCREAMING_SNAKE_CASE__							)
					self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] ,       SCREAMING_SNAKE_CASE__ ,       atol=1E-4							)							)



			def 							lowerCamelCase_ (   self							):



					"""simple docstring"""







					snake_case						:  Optional[int]    	= AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"							)
					snake_case						:  Optional[Any]    	= UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"							).to(SCREAMING_SNAKE_CASE__							)

					snake_case						:  List[str]    	= prepare_img()
					snake_case						:  Tuple    	= processor(images=SCREAMING_SNAKE_CASE__ ,       return_tensors="pt"							).to(SCREAMING_SNAKE_CASE__							)

					with torch.no_grad():
							snake_case						:  int    	= model(**SCREAMING_SNAKE_CASE__							)

					snake_case						:  List[str]    	= torch.Size((1, model.config.num_labels, 512, 512)							)
					self.assertEqual(outputs.logits.shape ,       SCREAMING_SNAKE_CASE__							)

					snake_case						:  Tuple    	= 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(SCREAMING_SNAKE_CASE__							)
					self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] ,       SCREAMING_SNAKE_CASE__ ,       atol=1E-4							)							)


'''simple docstring'''

from math import sqrt

import numpy as np
from sympy import symbols

# Coefficient
# Speed of light (m/s)
_A			:      List[Any]					      =				299792458

# Symbols
_A      ,     _A      ,     _A      ,     _A			:      Union[str, Any]					      =				symbols('''ct x y z''')







def      UpperCamelCase_						(					snake_case_       :       float      )					->     float:






 '''simple docstring'''

 if velocity > c:
  raise ValueError("""Speed must not exceed light speed 299,792,458 [m/s]!"""      )
 elif velocity < 1:
  # Usually the speed should be much higher than 1 (c order of magnitude)
  raise ValueError("""Speed must be greater than or equal to 1!"""      )

 return velocity / c







def      UpperCamelCase_						(					snake_case_       :       float      )					->     float:






 '''simple docstring'''

 return 1 / sqrt(1 - beta(snake_case_      ) ** 2      )







def      UpperCamelCase_						(					snake_case_       :       float      )					->     np.ndarray:






 '''simple docstring'''

 return np.array(
     [
         [gamma(snake_case_      ), -gamma(snake_case_      ) * beta(snake_case_      ), 0, 0],
         [-gamma(snake_case_      ) * beta(snake_case_      ), gamma(snake_case_      ), 0, 0],
         [0, 0, 1, 0],
         [0, 0, 0, 1],
     ]      )







def      UpperCamelCase_						(					snake_case_       :       float						,		snake_case_       :       np.ndarray | None = None      )					->     np.ndarray:






 '''simple docstring'''

 if event is None:
  __lowerCAmelCase											=						np.array([ct, x, y, z]      )  # Symbolic four vector
 else:
  event[0] *= c  # x0 is ct (speed of light * time)

 return transformation_matrix(snake_case_      ) @ event


if __name__ == "__main__":
 import doctest

 doctest.testmod()

 # Example of symbolic vector:
 _A			:      str					      =				transform(29979245)
 print('''Example of four vector: ''')
 print(f'ct\' = {four_vector[0]}')
 print(f'x\' = {four_vector[1]}')
 print(f'y\' = {four_vector[2]}')
 print(f'z\' = {four_vector[3]}')

 # Substitute symbols with numerical values
 _A			:      int					      =				{ct: c, x: 1, y: 1, z: 1}
 _A			:      Any					      =				[four_vector[i].subs(sub_dict) for i in range(4)]

 print(f'\n{numerical_vector}')






