
"""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 			UpperCamelCase      :
     def __init__(     self  ,     snake_case__  ,     snake_case__=100  ,     snake_case__=13  ,     snake_case__=30  ,     snake_case__=2  ,     snake_case__=3  ,     snake_case__=True  ,     snake_case__=True  ,     snake_case__=32  ,     snake_case__=4  ,     snake_case__=4  ,     snake_case__=37  ,     snake_case__="gelu"  ,     snake_case__=0.1  ,     snake_case__=0.1  ,     snake_case__=10  ,     snake_case__=0.02  ,     snake_case__=3  ,     snake_case__=None  ,     snake_case__=[0, 1, 2, 3]  ,     ):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = parent
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = 100
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = batch_size
       _SCREAMING_SNAKE_CASE   :				Dict							    = image_size
       _SCREAMING_SNAKE_CASE   :				Dict							    = patch_size
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = num_channels
       _SCREAMING_SNAKE_CASE   :				int							    = is_training
       _SCREAMING_SNAKE_CASE   :				Tuple							    = use_labels
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = hidden_size
       _SCREAMING_SNAKE_CASE   :				int							    = num_hidden_layers
       _SCREAMING_SNAKE_CASE   :				List[str]							    = num_attention_heads
       _SCREAMING_SNAKE_CASE   :				List[str]							    = intermediate_size
       _SCREAMING_SNAKE_CASE   :				List[str]							    = hidden_act
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = hidden_dropout_prob
       _SCREAMING_SNAKE_CASE   :				Dict							    = attention_probs_dropout_prob
       _SCREAMING_SNAKE_CASE   :				List[str]							    = type_sequence_label_size
       _SCREAMING_SNAKE_CASE   :				int							    = initializer_range
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = scope
       _SCREAMING_SNAKE_CASE   :				Any							    = out_indices
       _SCREAMING_SNAKE_CASE   :				Any							    = num_labels

       # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = (image_size // patch_size) ** 2
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = num_patches + 1
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				int							    = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

       _SCREAMING_SNAKE_CASE   :				Any							    = self.get_config()

       return config, pixel_values, labels, pixel_labels
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       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=snake_case__  ,     initializer_range=self.initializer_range  ,     out_indices=self.out_indices  ,     )
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[str]							    = BeitModel(config=snake_case__				)
       model.to(snake_case__				)
       model.eval()
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = model(snake_case__				)
       self.parent.assertEqual(result.last_hidden_state.shape  ,     (self.batch_size, self.seq_length, self.hidden_size)				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				str							    = BeitForMaskedImageModeling(config=snake_case__				)
       model.to(snake_case__				)
       model.eval()
       _SCREAMING_SNAKE_CASE   :				int							    = model(snake_case__				)
       self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.seq_length - 1, self.vocab_size)				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Dict							    = self.type_sequence_label_size
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = BeitForImageClassification(snake_case__				)
       model.to(snake_case__				)
       model.eval()
       _SCREAMING_SNAKE_CASE   :				Any							    = model(snake_case__  ,     labels=snake_case__				)
       self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.type_sequence_label_size)				)

       # test greyscale images
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = 1
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = BeitForImageClassification(snake_case__				)
       model.to(snake_case__				)
       model.eval()

       _SCREAMING_SNAKE_CASE   :				int							    = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = model(snake_case__  ,     labels=snake_case__				)
       self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.type_sequence_label_size)				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = self.num_labels
       _SCREAMING_SNAKE_CASE   :				List[str]							    = BeitForSemanticSegmentation(snake_case__				)
       model.to(snake_case__				)
       model.eval()
       _SCREAMING_SNAKE_CASE   :				int							    = model(snake_case__				)
       self.parent.assertEqual(
           result.logits.shape  ,     (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)				)
       _SCREAMING_SNAKE_CASE   :				int							    = model(snake_case__  ,     labels=snake_case__				)
       self.parent.assertEqual(
           result.logits.shape  ,     (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)				)




     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[str]							    = self.prepare_config_and_inputs()
       _SCREAMING_SNAKE_CASE   :				List[str]							    = config_and_inputs
       _SCREAMING_SNAKE_CASE   :				Dict							    = {"pixel_values": pixel_values}
       return config, inputs_dict
@require_torch
class 			UpperCamelCase      (							__SCREAMING_SNAKE_CASE      ,       __SCREAMING_SNAKE_CASE      ,       unittest.TestCase  ):
     A__      =			(
         (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
         if is_torch_available()
         else ()
     )
     A__      =			(
         {
             """feature-extraction""": BeitModel,
             """image-classification""": BeitForImageClassification,
             """image-segmentation""": BeitForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     A__      =			False
     A__      =			False
     A__      =			False
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = BeitModelTester(self				)
       _SCREAMING_SNAKE_CASE   :				Tuple							    = ConfigTester(self  ,     config_class=snake_case__  ,     has_text_modality=snake_case__  ,     hidden_size=37				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       self.config_tester.run_common_tests()
     @unittest.skip(reason="BEiT does not use inputs_embeds"				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


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




       """simple docstring"""


       pass
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = self.model_tester.prepare_config_and_inputs_for_common()

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




       """simple docstring"""


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

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

         _SCREAMING_SNAKE_CASE   :				int							    = ["pixel_values"]
         self.assertListEqual(arg_names[:1]  ,     snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[Any]							    = self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Tuple							    = self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Any							    = self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       if not self.model_tester.is_training:
         return

       _SCREAMING_SNAKE_CASE   :				int							    = self.model_tester.prepare_config_and_inputs_for_common()
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = True

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

         _SCREAMING_SNAKE_CASE   :				Optional[int]							    = model_class(snake_case__				)
         model.to(snake_case__				)
         model.train()
         _SCREAMING_SNAKE_CASE   :				Tuple							    = self._prepare_for_class(snake_case__  ,     snake_case__  ,     return_labels=snake_case__				)
         _SCREAMING_SNAKE_CASE   :				List[Any]							    = model(**snake_case__				).loss
         loss.backward()
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Tuple							    = self.model_tester.prepare_config_and_inputs_for_common()
       if not self.model_tester.is_training:
         return

       _SCREAMING_SNAKE_CASE   :				List[Any]							    = False
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = True

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

         _SCREAMING_SNAKE_CASE   :				List[Any]							    = model_class(snake_case__				)
         model.gradient_checkpointing_enable()
         model.to(snake_case__				)
         model.train()
         _SCREAMING_SNAKE_CASE   :				Any							    = self._prepare_for_class(snake_case__  ,     snake_case__  ,     return_labels=snake_case__				)
         _SCREAMING_SNAKE_CASE   :				Dict							    = model(**snake_case__				).loss
         loss.backward()
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


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

       _SCREAMING_SNAKE_CASE   :				List[Any]							    = _config_zero_init(snake_case__				)
       for model_class in self.all_model_classes:
         _SCREAMING_SNAKE_CASE   :				List[str]							    = model_class(config=snake_case__				)
         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 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = BeitModel.from_pretrained(snake_case__				)
         self.assertIsNotNone(snake_case__				)





def    _lowerCAmelCase    (     )  ->    List[Any]:
  _SCREAMING_SNAKE_CASE   :				Dict							    = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
  return image

@require_torch
@require_vision
class 			UpperCamelCase      (							unittest.TestCase  ):
     @cached_property
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224"				) if is_vision_available() else None
     @slow
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k"				).to(snake_case__				)

       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = self.default_image_processor
       _SCREAMING_SNAKE_CASE   :				int							    = prepare_img()
       _SCREAMING_SNAKE_CASE   :				str							    = image_processor(images=snake_case__  ,     return_tensors="pt"				).pixel_values.to(snake_case__				)

       # prepare bool_masked_pos
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = torch.ones((1, 196)  ,     dtype=torch.bool				).to(snake_case__				)

       # forward pass
       with torch.no_grad():
         _SCREAMING_SNAKE_CASE   :				Optional[int]							    = model(pixel_values=snake_case__  ,     bool_masked_pos=snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Tuple							    = outputs.logits

       # verify the logits
       _SCREAMING_SNAKE_CASE   :				List[str]							    = torch.Size((1, 196, 8192)				)
       self.assertEqual(logits.shape  ,     snake_case__				)

       _SCREAMING_SNAKE_CASE   :				Dict							    = torch.tensor(
           [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]]				).to(snake_case__				)

       self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]  ,     snake_case__  ,     atol=1E-2				)				)
     @slow
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[Any]							    = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224"				).to(snake_case__				)

       _SCREAMING_SNAKE_CASE   :				List[Any]							    = self.default_image_processor
       _SCREAMING_SNAKE_CASE   :				Tuple							    = prepare_img()
       _SCREAMING_SNAKE_CASE   :				Dict							    = image_processor(images=snake_case__  ,     return_tensors="pt"				).to(snake_case__				)

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

       # verify the logits
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = torch.Size((1, 1000)				)
       self.assertEqual(logits.shape  ,     snake_case__				)

       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = torch.tensor([-1.2_385, -1.0_987, -1.0_108]				).to(snake_case__				)

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

       _SCREAMING_SNAKE_CASE   :				List[str]							    = 281
       self.assertEqual(logits.argmax(-1				).item()  ,     snake_case__				)
     @slow
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				int							    = BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k"				).to(
           snake_case__				)

       _SCREAMING_SNAKE_CASE   :				List[Any]							    = self.default_image_processor
       _SCREAMING_SNAKE_CASE   :				Tuple							    = prepare_img()
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = image_processor(images=snake_case__  ,     return_tensors="pt"				).to(snake_case__				)

       # forward pass
       with torch.no_grad():
         _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = model(**snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = outputs.logits

       # verify the logits
       _SCREAMING_SNAKE_CASE   :				Tuple							    = torch.Size((1, 21841)				)
       self.assertEqual(logits.shape  ,     snake_case__				)

       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = torch.tensor([1.6_881, -0.2_787, 0.5_901]				).to(snake_case__				)

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

       _SCREAMING_SNAKE_CASE   :				int							    = 2396
       self.assertEqual(logits.argmax(-1				).item()  ,     snake_case__				)
     @slow
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"				)
       _SCREAMING_SNAKE_CASE   :				int							    = model.to(snake_case__				)

       _SCREAMING_SNAKE_CASE   :				int							    = BeitImageProcessor(do_resize=snake_case__  ,     size=640  ,     do_center_crop=snake_case__				)

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

       # forward pass
       with torch.no_grad():
         _SCREAMING_SNAKE_CASE   :				Tuple							    = model(**snake_case__				)
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = outputs.logits

       # verify the logits
       _SCREAMING_SNAKE_CASE   :				Dict							    = torch.Size((1, 150, 160, 160)				)
       self.assertEqual(logits.shape  ,     snake_case__				)

       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = version.parse(PIL.__version__				) < version.parse("9.0.0"				)

       if is_pillow_less_than_a:
         _SCREAMING_SNAKE_CASE   :				Dict							    = torch.tensor(
             [
                 [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]],
                 [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]],
                 [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]],
             ]  ,     device=snake_case__  ,     )
       else:
         _SCREAMING_SNAKE_CASE   :				Tuple							    = torch.tensor(
             [
                 [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]],
                 [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]],
                 [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]],
             ]  ,     device=snake_case__  ,     )

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




     @slow
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				List[Any]							    = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"				)
       _SCREAMING_SNAKE_CASE   :				Any							    = model.to(snake_case__				)

       _SCREAMING_SNAKE_CASE   :				str							    = BeitImageProcessor(do_resize=snake_case__  ,     size=640  ,     do_center_crop=snake_case__				)

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

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

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

       _SCREAMING_SNAKE_CASE   :				str							    = image_processor.post_process_semantic_segmentation(outputs=snake_case__  ,     target_sizes=[(500, 300)]				)
       _SCREAMING_SNAKE_CASE   :				Tuple							    = torch.Size((500, 300)				)
       self.assertEqual(segmentation[0].shape  ,     snake_case__				)

       _SCREAMING_SNAKE_CASE   :				str							    = image_processor.post_process_semantic_segmentation(outputs=snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = torch.Size((160, 160)				)
       self.assertEqual(segmentation[0].shape  ,     snake_case__				)





"""simple docstring"""
import itertools
from dataclasses import dataclass
from typing import List, Optional

import pyarrow as pa
import pyarrow.parquet as pq

import datasets
from datasets.table import table_cast


lowercase_       :						List[str]     					=	datasets.utils.logging.get_logger(__name__)
@dataclass
class 			UpperCamelCase      (							datasets.BuilderConfig  ):
     A__      =			10000
     A__      =			None
     A__      =			None
class 			UpperCamelCase      (							datasets.ArrowBasedBuilder  ):
     A__      =			ParquetConfig
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       return datasets.DatasetInfo(features=self.config.features				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       if not self.config.data_files:
         raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}'''				)
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = dl_manager.download_and_extract(self.config.data_files				)
       if isinstance(snake_case__  ,     (str, list, tuple)				):
         _SCREAMING_SNAKE_CASE   :				int							    = data_files
         if isinstance(snake_case__  ,     snake_case__				):
           _SCREAMING_SNAKE_CASE   :				List[Any]							    = [files]
         # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
         _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = [dl_manager.iter_files(snake_case__				) for file in files]
         return [datasets.SplitGenerator(name=datasets.Split.TRAIN  ,     gen_kwargs={"files": files}				)]
       _SCREAMING_SNAKE_CASE   :				Tuple							    = []
       for split_name, files in data_files.items():
         if isinstance(snake_case__  ,     snake_case__				):
           _SCREAMING_SNAKE_CASE   :				Optional[int]							    = [files]
         # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
         _SCREAMING_SNAKE_CASE   :				Tuple							    = [dl_manager.iter_files(snake_case__				) for file in files]
         # Infer features is they are stoed in the arrow schema
         if self.info.features is None:
           for file in itertools.chain.from_iterable(snake_case__				):
             with open(snake_case__  ,     "rb"				) as f:
               _SCREAMING_SNAKE_CASE   :				Optional[int]							    = datasets.Features.from_arrow_schema(pq.read_schema(snake_case__				)				)
             break
         splits.append(datasets.SplitGenerator(name=snake_case__  ,     gen_kwargs={"files": files}				)				)
       return splits
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       if self.info.features is not None:
         # more expensive cast to support nested features with keys in a different order
         # allows str <-> int/float or str to Audio for example
         _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = table_cast(snake_case__  ,     self.info.features.arrow_schema				)
       return pa_table




     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Any							    = self.info.features.arrow_schema if self.info.features is not None else None
       if self.info.features is not None and self.config.columns is not None:
         if sorted(field.name for field in schema				) != sorted(self.config.columns				):
           raise ValueError(
               F'''Tried to load parquet data with columns \'{self.config.columns}\' with mismatching features \'{self.info.features}\''''				)
       for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case__				)				):
         with open(snake_case__  ,     "rb"				) as f:
           _SCREAMING_SNAKE_CASE   :				List[Any]							    = pq.ParquetFile(snake_case__				)
           try:
             for batch_idx, record_batch in enumerate(
                 parquet_file.iter_batches(batch_size=self.config.batch_size  ,     columns=self.config.columns				)				):
               _SCREAMING_SNAKE_CASE   :				int							    = pa.Table.from_batches([record_batch]				)
               # Uncomment for debugging (will print the Arrow table size and elements)
               # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
               # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
               yield F'''{file_idx}_{batch_idx}''', self._cast_table(snake_case__				)
           except ValueError as e:
             logger.error(F'''Failed to read file \'{file}\' with error {type(snake_case__				)}: {e}'''				)
             raise



