
'''simple docstring'''



import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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, _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 (
         MODEL_MAPPING,
         BeitForImageClassification,
         BeitForMaskedImageModeling,
         BeitForSemanticSegmentation,
         BeitModel,
     )
     from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     import PIL
     from PIL import Image

     from transformers import BeitImageProcessor

class  _a					:





       """simple docstring"""




       def __init__(				self							,				A__							,				A__=1_00							,				A__=13							,				A__=30							,				A__=2							,				A__=3							,				A__=True							,				A__=True							,				A__=32							,				A__=4							,				A__=4							,				A__=37							,				A__="gelu"							,				A__=0.1							,				A__=0.1							,				A__=10							,				A__=0.02							,				A__=3							,				A__=None							,				A__=[0, 1, 2, 3]							,				)     ->      Optional[int]:
          _SCREAMING_SNAKE_CASE  			=					parent
          _SCREAMING_SNAKE_CASE  			=					1_00
          _SCREAMING_SNAKE_CASE  			=					batch_size
          _SCREAMING_SNAKE_CASE  			=					image_size
          _SCREAMING_SNAKE_CASE  			=					patch_size
          _SCREAMING_SNAKE_CASE  			=					num_channels
          _SCREAMING_SNAKE_CASE  			=					is_training
          _SCREAMING_SNAKE_CASE  			=					use_labels
          _SCREAMING_SNAKE_CASE  			=					hidden_size
          _SCREAMING_SNAKE_CASE  			=					num_hidden_layers
          _SCREAMING_SNAKE_CASE  			=					num_attention_heads
          _SCREAMING_SNAKE_CASE  			=					intermediate_size
          _SCREAMING_SNAKE_CASE  			=					hidden_act
          _SCREAMING_SNAKE_CASE  			=					hidden_dropout_prob
          _SCREAMING_SNAKE_CASE  			=					attention_probs_dropout_prob
          _SCREAMING_SNAKE_CASE  			=					type_sequence_label_size
          _SCREAMING_SNAKE_CASE  			=					initializer_range
          _SCREAMING_SNAKE_CASE  			=					scope
          _SCREAMING_SNAKE_CASE  			=					out_indices
          _SCREAMING_SNAKE_CASE  			=					num_labels

          # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
          _SCREAMING_SNAKE_CASE  			=					(image_size // patch_size) ** 2
          _SCREAMING_SNAKE_CASE  			=					num_patches + 1






       def 							UpperCamelCase					(				self   )     ->      Any:
          _SCREAMING_SNAKE_CASE  			=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

          _SCREAMING_SNAKE_CASE  			=					None
          _SCREAMING_SNAKE_CASE  			=					None
          if self.use_labels:
             _SCREAMING_SNAKE_CASE  			=					ids_tensor([self.batch_size]							,				self.type_sequence_label_size   )
             _SCREAMING_SNAKE_CASE  			=					ids_tensor([self.batch_size, self.image_size, self.image_size]							,				self.num_labels   )

          _SCREAMING_SNAKE_CASE  			=					self.get_config()

          return config, pixel_values, labels, pixel_labels






       def 							UpperCamelCase					(				self   )     ->      List[Any]:
          return BeitConfig(
              vocab_size=self.vocab_size							,				image_size=self.image_size							,				patch_size=self.patch_size							,				num_channels=self.num_channels							,				hidden_size=self.hidden_size							,				num_hidden_layers=self.num_hidden_layers							,				num_attention_heads=self.num_attention_heads							,				intermediate_size=self.intermediate_size							,				hidden_act=self.hidden_act							,				hidden_dropout_prob=self.hidden_dropout_prob							,				attention_probs_dropout_prob=self.attention_probs_dropout_prob							,				is_decoder=lowerCamelCase__							,				initializer_range=self.initializer_range							,				out_indices=self.out_indices							,				)






       def 							UpperCamelCase					(				self							,				A__							,				A__							,				A__							,				A__   )     ->      Optional[int]:
          _SCREAMING_SNAKE_CASE  			=					BeitModel(config=lowerCamelCase__   )
          model.to(lowerCamelCase__   )
          model.eval()
          _SCREAMING_SNAKE_CASE  			=					model(lowerCamelCase__   )
          self.parent.assertEqual(result.last_hidden_state.shape							,				(self.batch_size, self.seq_length, self.hidden_size)   )






       def 							UpperCamelCase					(				self							,				A__							,				A__							,				A__							,				A__   )     ->      str:
          _SCREAMING_SNAKE_CASE  			=					BeitForMaskedImageModeling(config=lowerCamelCase__   )
          model.to(lowerCamelCase__   )
          model.eval()
          _SCREAMING_SNAKE_CASE  			=					model(lowerCamelCase__   )
          self.parent.assertEqual(result.logits.shape							,				(self.batch_size, self.seq_length - 1, self.vocab_size)   )






       def 							UpperCamelCase					(				self							,				A__							,				A__							,				A__							,				A__   )     ->      Optional[Any]:
          _SCREAMING_SNAKE_CASE  			=					self.type_sequence_label_size
          _SCREAMING_SNAKE_CASE  			=					BeitForImageClassification(lowerCamelCase__   )
          model.to(lowerCamelCase__   )
          model.eval()
          _SCREAMING_SNAKE_CASE  			=					model(lowerCamelCase__							,				labels=lowerCamelCase__   )
          self.parent.assertEqual(result.logits.shape							,				(self.batch_size, self.type_sequence_label_size)   )

          # test greyscale images
          _SCREAMING_SNAKE_CASE  			=					1
          _SCREAMING_SNAKE_CASE  			=					BeitForImageClassification(lowerCamelCase__   )
          model.to(lowerCamelCase__   )
          model.eval()

          _SCREAMING_SNAKE_CASE  			=					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
          _SCREAMING_SNAKE_CASE  			=					model(lowerCamelCase__							,				labels=lowerCamelCase__   )
          self.parent.assertEqual(result.logits.shape							,				(self.batch_size, self.type_sequence_label_size)   )






       def 							UpperCamelCase					(				self							,				A__							,				A__							,				A__							,				A__   )     ->      List[str]:
          _SCREAMING_SNAKE_CASE  			=					self.num_labels
          _SCREAMING_SNAKE_CASE  			=					BeitForSemanticSegmentation(lowerCamelCase__   )
          model.to(lowerCamelCase__   )
          model.eval()
          _SCREAMING_SNAKE_CASE  			=					model(lowerCamelCase__   )
          self.parent.assertEqual(
              result.logits.shape							,				(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)   )
          _SCREAMING_SNAKE_CASE  			=					model(lowerCamelCase__							,				labels=lowerCamelCase__   )
          self.parent.assertEqual(
              result.logits.shape							,				(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)   )






       def 							UpperCamelCase					(				self   )     ->      Tuple:
          _SCREAMING_SNAKE_CASE  			=					self.prepare_config_and_inputs()
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					config_and_inputs
          _SCREAMING_SNAKE_CASE  			=					{"""pixel_values""": pixel_values}
          return config, inputs_dict






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





       """simple docstring"""




       SCREAMING_SNAKE_CASE   =	(
           (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       SCREAMING_SNAKE_CASE   =	(
           {
               'feature-extraction': BeitModel,
               'image-classification': BeitForImageClassification,
               'image-segmentation': BeitForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       SCREAMING_SNAKE_CASE   =	False
       SCREAMING_SNAKE_CASE   =	False
       SCREAMING_SNAKE_CASE   =	False






       def 							UpperCamelCase					(				self   )     ->      Union[str, Any]:
          _SCREAMING_SNAKE_CASE  			=					BeitModelTester(self   )
          _SCREAMING_SNAKE_CASE  			=					ConfigTester(self							,				config_class=lowerCamelCase__							,				has_text_modality=lowerCamelCase__							,				hidden_size=37   )






       def 							UpperCamelCase					(				self   )     ->      Tuple:
          self.config_tester.run_common_tests()






       @unittest.skip(reason="""BEiT does not use inputs_embeds"""   )
       def 							UpperCamelCase					(				self   )     ->      str:
          pass






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






       def 							UpperCamelCase					(				self   )     ->      str:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
             _SCREAMING_SNAKE_CASE  			=					model_class(lowerCamelCase__   )
             self.assertIsInstance(model.get_input_embeddings()							,				(nn.Module)   )
             _SCREAMING_SNAKE_CASE  			=					model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(lowerCamelCase__							,				nn.Linear   )   )






       def 							UpperCamelCase					(				self   )     ->      List[Any]:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs_for_common()

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

             _SCREAMING_SNAKE_CASE  			=					["""pixel_values"""]
             self.assertListEqual(arg_names[:1]							,				lowerCamelCase__   )






       def 							UpperCamelCase					(				self   )     ->      Union[str, Any]:
          _SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowerCamelCase__   )






       def 							UpperCamelCase					(				self   )     ->      str:
          _SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase__   )






       def 							UpperCamelCase					(				self   )     ->      Tuple:
          _SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__   )






       def 							UpperCamelCase					(				self   )     ->      Union[str, Any]:
          _SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__   )






       def 							UpperCamelCase					(				self   )     ->      Any:
          if not self.model_tester.is_training:
             return

          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs_for_common()
          _SCREAMING_SNAKE_CASE  			=					True

          for model_class in self.all_model_classes:
             # we don't test BeitForMaskedImageModeling
             if model_class in [*get_values(lowerCamelCase__   ), BeitForMaskedImageModeling]:
                continue

             _SCREAMING_SNAKE_CASE  			=					model_class(lowerCamelCase__   )
             model.to(lowerCamelCase__   )
             model.train()
             _SCREAMING_SNAKE_CASE  			=					self._prepare_for_class(lowerCamelCase__							,				lowerCamelCase__							,				return_labels=lowerCamelCase__   )
             _SCREAMING_SNAKE_CASE  			=					model(**lowerCamelCase__   ).loss
             loss.backward()






       def 							UpperCamelCase					(				self   )     ->      int:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs_for_common()
          if not self.model_tester.is_training:
             return

          _SCREAMING_SNAKE_CASE  			=					False
          _SCREAMING_SNAKE_CASE  			=					True

          for model_class in self.all_model_classes:
             # we don't test BeitForMaskedImageModeling
             if (
                 model_class in [*get_values(lowerCamelCase__   ), BeitForMaskedImageModeling]
                 or not model_class.supports_gradient_checkpointing
             ):
                continue

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






       def 							UpperCamelCase					(				self   )     ->      Any:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self.model_tester.prepare_config_and_inputs_for_common()

          _SCREAMING_SNAKE_CASE  			=					_config_zero_init(lowerCamelCase__   )
          for model_class in self.all_model_classes:
             _SCREAMING_SNAKE_CASE  			=					model_class(config=lowerCamelCase__   )
             for name, param in model.named_parameters():
                # we skip lambda parameters as these require special initial values
                # determined by config.layer_scale_init_value
                if "lambda" in name:
                   continue
                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"							,				)






       @slow
       def 							UpperCamelCase					(				self   )     ->      Tuple:
          for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _SCREAMING_SNAKE_CASE  			=					BeitModel.from_pretrained(lowerCamelCase__   )
             self.assertIsNotNone(lowerCamelCase__   )






def  lowerCAmelCase_						(					)  ->  Optional[Any]:




   """simple docstring"""
   _SCREAMING_SNAKE_CASE  			=					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   )     ->      Tuple:
          return BeitImageProcessor.from_pretrained("""microsoft/beit-base-patch16-224"""   ) if is_vision_available() else None






       @slow
       def 							UpperCamelCase					(				self   )     ->      Optional[int]:
          _SCREAMING_SNAKE_CASE  			=					BeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k"""   ).to(lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					self.default_image_processor
          _SCREAMING_SNAKE_CASE  			=					prepare_img()
          _SCREAMING_SNAKE_CASE  			=					image_processor(images=lowerCamelCase__							,				return_tensors="""pt"""   ).pixel_values.to(lowerCamelCase__   )

          # prepare bool_masked_pos
          _SCREAMING_SNAKE_CASE  			=					torch.ones((1, 1_96)							,				dtype=torch.bool   ).to(lowerCamelCase__   )

          # forward pass
          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					model(pixel_values=lowerCamelCase__							,				bool_masked_pos=lowerCamelCase__   )
          _SCREAMING_SNAKE_CASE  			=					outputs.logits

          # verify the logits
          _SCREAMING_SNAKE_CASE  			=					torch.Size((1, 1_96, 81_92)   )
          self.assertEqual(logits.shape							,				lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					torch.tensor(
              [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]   ).to(lowerCamelCase__   )

          self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]							,				lowerCamelCase__							,				atol=1E-2   )   )






       @slow
       def 							UpperCamelCase					(				self   )     ->      str:
          _SCREAMING_SNAKE_CASE  			=					BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224"""   ).to(lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					self.default_image_processor
          _SCREAMING_SNAKE_CASE  			=					prepare_img()
          _SCREAMING_SNAKE_CASE  			=					image_processor(images=lowerCamelCase__							,				return_tensors="""pt"""   ).to(lowerCamelCase__   )

          # forward pass
          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					model(**lowerCamelCase__   )
          _SCREAMING_SNAKE_CASE  			=					outputs.logits

          # verify the logits
          _SCREAMING_SNAKE_CASE  			=					torch.Size((1, 10_00)   )
          self.assertEqual(logits.shape							,				lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					torch.tensor([-1.2385, -1.0987, -1.0108]   ).to(lowerCamelCase__   )

          self.assertTrue(torch.allclose(logits[0, :3]							,				lowerCamelCase__							,				atol=1E-4   )   )

          _SCREAMING_SNAKE_CASE  			=					2_81
          self.assertEqual(logits.argmax(-1   ).item()							,				lowerCamelCase__   )






       @slow
       def 							UpperCamelCase					(				self   )     ->      int:
          _SCREAMING_SNAKE_CASE  			=					BeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k"""   ).to(
              lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					self.default_image_processor
          _SCREAMING_SNAKE_CASE  			=					prepare_img()
          _SCREAMING_SNAKE_CASE  			=					image_processor(images=lowerCamelCase__							,				return_tensors="""pt"""   ).to(lowerCamelCase__   )

          # forward pass
          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					model(**lowerCamelCase__   )
          _SCREAMING_SNAKE_CASE  			=					outputs.logits

          # verify the logits
          _SCREAMING_SNAKE_CASE  			=					torch.Size((1, 2_18_41)   )
          self.assertEqual(logits.shape							,				lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					torch.tensor([1.6881, -0.2787, 0.5901]   ).to(lowerCamelCase__   )

          self.assertTrue(torch.allclose(logits[0, :3]							,				lowerCamelCase__							,				atol=1E-4   )   )

          _SCREAMING_SNAKE_CASE  			=					23_96
          self.assertEqual(logits.argmax(-1   ).item()							,				lowerCamelCase__   )






       @slow
       def 							UpperCamelCase					(				self   )     ->      Optional[Any]:
          _SCREAMING_SNAKE_CASE  			=					BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""   )
          _SCREAMING_SNAKE_CASE  			=					model.to(lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					BeitImageProcessor(do_resize=lowerCamelCase__							,				size=6_40							,				do_center_crop=lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					load_dataset("""hf-internal-testing/fixtures_ade20k"""							,				split="""test"""   )
          _SCREAMING_SNAKE_CASE  			=					Image.open(ds[0]["""file"""]   )
          _SCREAMING_SNAKE_CASE  			=					image_processor(images=lowerCamelCase__							,				return_tensors="""pt"""   ).to(lowerCamelCase__   )

          # forward pass
          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					model(**lowerCamelCase__   )
          _SCREAMING_SNAKE_CASE  			=					outputs.logits

          # verify the logits
          _SCREAMING_SNAKE_CASE  			=					torch.Size((1, 1_50, 1_60, 1_60)   )
          self.assertEqual(logits.shape							,				lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					version.parse(PIL.__version__   ) < version.parse("""9.0.0"""   )

          if is_pillow_less_than_a:
             _SCREAMING_SNAKE_CASE  			=					torch.tensor(
                 [
                     [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]],
                     [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]],
                     [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]],
                 ]							,				device=lowerCamelCase__							,				)
          else:
             _SCREAMING_SNAKE_CASE  			=					torch.tensor(
                 [
                     [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]],
                     [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]],
                     [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]],
                 ]							,				device=lowerCamelCase__							,				)

          self.assertTrue(torch.allclose(logits[0, :3, :3, :3]							,				lowerCamelCase__							,				atol=1E-4   )   )






       @slow
       def 							UpperCamelCase					(				self   )     ->      Dict:
          _SCREAMING_SNAKE_CASE  			=					BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""   )
          _SCREAMING_SNAKE_CASE  			=					model.to(lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					BeitImageProcessor(do_resize=lowerCamelCase__							,				size=6_40							,				do_center_crop=lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					load_dataset("""hf-internal-testing/fixtures_ade20k"""							,				split="""test"""   )
          _SCREAMING_SNAKE_CASE  			=					Image.open(ds[0]["""file"""]   )
          _SCREAMING_SNAKE_CASE  			=					image_processor(images=lowerCamelCase__							,				return_tensors="""pt"""   ).to(lowerCamelCase__   )

          # forward pass
          with torch.no_grad():
             _SCREAMING_SNAKE_CASE  			=					model(**lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					outputs.logits.detach().cpu()

          _SCREAMING_SNAKE_CASE  			=					image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase__							,				target_sizes=[(5_00, 3_00)]   )
          _SCREAMING_SNAKE_CASE  			=					torch.Size((5_00, 3_00)   )
          self.assertEqual(segmentation[0].shape							,				lowerCamelCase__   )

          _SCREAMING_SNAKE_CASE  			=					image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase__   )
          _SCREAMING_SNAKE_CASE  			=					torch.Size((1_60, 1_60)   )
          self.assertEqual(segmentation[0].shape							,				lowerCamelCase__   )












from sklearn.metrics import mean_squared_error

import datasets


__A								=       "\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n"

__A								=       "\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n"


__A								=       "\nArgs:\n    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Estimated target values.\n    references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Ground truth (correct) target values.\n    sample_weight: array-like of shape (n_samples,), default=None\n        Sample weights.\n    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\n        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n        \"raw_values\" : Returns a full set of errors in case of multioutput input.\n\n        \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\n\n    squared : bool, default=True\n        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n    mse : mean squared error.\nExamples:\n\n    >>> mse_metric = datasets.load_metric(\"mse\")\n    >>> predictions = [2.5, 0.0, 2, 8]\n    >>> references = [3, -0.5, 2, 7]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'mse': 0.375}\n    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n    >>> print(rmse_result)\n    {'mse': 0.6123724356957945}\n\n    If you're using multi-dimensional lists, then set the config as follows :\n\n    >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")\n    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n    >>> references = [[0, 2], [-1, 2], [8, -5]]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'mse': 0.7083333333333334}\n    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {'mse': array([0.41666667, 1. ])}\n"







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,							_KWARGS_DESCRIPTION					)
class        __lowerCAmelCase					(			datasets.Metric					):

			"""simple docstring"""







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



							'''simple docstring'''
							return datasets.MetricInfo(
							    description=_DESCRIPTION     ,		citation=_CITATION     ,		inputs_description=_KWARGS_DESCRIPTION     ,		features=datasets.Features(self._get_feature_types()				)     ,		reference_urls=[
							        'https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html'
							    ]     ,		)


			def  lowercase_       ( self				)       -> Tuple:



							'''simple docstring'''
							if self.config_name == "multilist":
											return {
											    "predictions": datasets.Sequence(datasets.Value('float'				)				),
											    "references": datasets.Sequence(datasets.Value('float'				)				),
											}
							else:
											return {
											    "predictions": datasets.Value('float'				),
											    "references": datasets.Value('float'				),
											}






			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__=None     ,		lowerCamelCase__="uniform_average"     ,		lowerCamelCase__=True				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       mean_squared_error(
							    lowerCamelCase__     ,		lowerCamelCase__     ,		sample_weight=lowerCamelCase__     ,		multioutput=lowerCamelCase__     ,		squared=lowerCamelCase__				)

							return {"mse": mse}


