



'''simple docstring'''





import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available


class 				snake_case (UpperCamelCase   ):
       lowerCAmelCase__  :Tuple						   =					["image_processor", "tokenizer"]
       lowerCAmelCase__  :Optional[int]						   =					"OwlViTImageProcessor"
       lowerCAmelCase__  :Tuple						   =					("CLIPTokenizer", "CLIPTokenizerFast")



       def __init__(				self     ,UpperCAmelCase_=None     ,UpperCAmelCase_=None     ,**UpperCAmelCase_      )  ->							Union[str, Any]:
           lowercase__		       =						None
           if "feature_extractor" in kwargs:
               warnings.warn(
                   "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
                   " instead."     ,UpperCAmelCase_     ,)
               lowercase__		       =						kwargs.pop("feature_extractor"      )

           lowercase__		       =						image_processor if image_processor is not None else feature_extractor
           if image_processor is None:
               raise ValueError("You need to specify an `image_processor`."      )
           if tokenizer is None:
               raise ValueError("You need to specify a `tokenizer`."      )

           super().__init__(UpperCAmelCase_     ,UpperCAmelCase_      )



       def __call__(				self     ,UpperCAmelCase_=None     ,UpperCAmelCase_=None     ,UpperCAmelCase_=None     ,UpperCAmelCase_="max_length"     ,UpperCAmelCase_="np"     ,**UpperCAmelCase_      )  ->							List[str]:

           if text is None and query_images is None and images is None:
               raise ValueError(
                   "You have to specify at least one text or query image or image. All three cannot be none."      )

           if text is not None:
               if isinstance(UpperCAmelCase_     ,UpperCAmelCase_      ) or (isinstance(UpperCAmelCase_     ,UpperCAmelCase_      ) and not isinstance(text[0]     ,UpperCAmelCase_      )):
                   lowercase__		       =						[self.tokenizer(UpperCAmelCase_     ,padding=UpperCAmelCase_     ,return_tensors=UpperCAmelCase_     ,**UpperCAmelCase_      )]

               elif isinstance(UpperCAmelCase_     ,UpperCAmelCase_      ) and isinstance(text[0]     ,UpperCAmelCase_      ):
                   lowercase__		       =						[]

                   # Maximum number of queries across batch
                   lowercase__		       =						max([len(UpperCAmelCase_      ) for t in text]      )

                   # Pad all batch samples to max number of text queries
                   for t in text:
                       if len(UpperCAmelCase_      ) != max_num_queries:
                           lowercase__		       =						t + [" "] * (max_num_queries - len(UpperCAmelCase_      ))

                       lowercase__		       =						self.tokenizer(UpperCAmelCase_     ,padding=UpperCAmelCase_     ,return_tensors=UpperCAmelCase_     ,**UpperCAmelCase_      )
                       encodings.append(UpperCAmelCase_      )
               else:
                   raise TypeError("Input text should be a string, a list of strings or a nested list of strings"      )

               if return_tensors == "np":
                   lowercase__		       =						np.concatenate([encoding["input_ids"] for encoding in encodings]     ,axis=0      )
                   lowercase__		       =						np.concatenate([encoding["attention_mask"] for encoding in encodings]     ,axis=0      )

               elif return_tensors == "jax" and is_flax_available():
                   import jax.numpy as jnp

                   lowercase__		       =						jnp.concatenate([encoding["input_ids"] for encoding in encodings]     ,axis=0      )
                   lowercase__		       =						jnp.concatenate([encoding["attention_mask"] for encoding in encodings]     ,axis=0      )

               elif return_tensors == "pt" and is_torch_available():
                   import torch

                   lowercase__		       =						torch.cat([encoding["input_ids"] for encoding in encodings]     ,dim=0      )
                   lowercase__		       =						torch.cat([encoding["attention_mask"] for encoding in encodings]     ,dim=0      )

               elif return_tensors == "tf" and is_tf_available():
                   import tensorflow as tf

                   lowercase__		       =						tf.stack([encoding["input_ids"] for encoding in encodings]     ,axis=0      )
                   lowercase__		       =						tf.stack([encoding["attention_mask"] for encoding in encodings]     ,axis=0      )

               else:
                   raise ValueError("Target return tensor type could not be returned"      )

               lowercase__		       =						BatchEncoding()
               lowercase__		       =						input_ids
               lowercase__		       =						attention_mask

           if query_images is not None:
               lowercase__		       =						BatchEncoding()
               lowercase__		       =						self.image_processor(
                   UpperCAmelCase_     ,return_tensors=UpperCAmelCase_     ,**UpperCAmelCase_      ).pixel_values
               lowercase__		       =						query_pixel_values

           if images is not None:
               lowercase__		       =						self.image_processor(UpperCAmelCase_     ,return_tensors=UpperCAmelCase_     ,**UpperCAmelCase_      )

           if text is not None and images is not None:
               lowercase__		       =						image_features.pixel_values
               return encoding
           elif query_images is not None and images is not None:
               lowercase__		       =						image_features.pixel_values
               return encoding
           elif text is not None or query_images is not None:
               return encoding
           else:
               return BatchEncoding(data=dict(**UpperCAmelCase_      )     ,tensor_type=UpperCAmelCase_      )



       def 							_a      (				self     ,*UpperCAmelCase_     ,**UpperCAmelCase_      )  ->							Any:
           return self.image_processor.post_process(*UpperCAmelCase_     ,**UpperCAmelCase_      )



       def 							_a      (				self     ,*UpperCAmelCase_     ,**UpperCAmelCase_      )  ->							Dict:
           return self.image_processor.post_process_object_detection(*UpperCAmelCase_     ,**UpperCAmelCase_      )



       def 							_a      (				self     ,*UpperCAmelCase_     ,**UpperCAmelCase_      )  ->							int:
           return self.image_processor.post_process_image_guided_detection(*UpperCAmelCase_     ,**UpperCAmelCase_      )



       def 							_a      (				self     ,*UpperCAmelCase_     ,**UpperCAmelCase_      )  ->							Union[str, Any]:
           return self.tokenizer.batch_decode(*UpperCAmelCase_     ,**UpperCAmelCase_      )



       def 							_a      (				self     ,*UpperCAmelCase_     ,**UpperCAmelCase_      )  ->							List[str]:
           return self.tokenizer.decode(*UpperCAmelCase_     ,**UpperCAmelCase_      )



       @property
       def 							_a      (				self      )  ->							Any:
           warnings.warn(
               "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."     ,UpperCAmelCase_     ,)
           return self.image_processor_class







       @property
       def 							_a      (				self      )  ->							Any:
           warnings.warn(
               "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."     ,UpperCAmelCase_     ,)
           return self.image_processor









'''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 				snake_case :



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

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



       def 							_a      (				self      )  ->							str:
           lowercase__		       =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

           lowercase__		       =						self.get_config()

           return config, pixel_values, labels, pixel_labels



       def 							_a      (				self      )  ->							List[str]:
           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=UpperCAmelCase_     ,initializer_range=self.initializer_range     ,out_indices=self.out_indices     ,)



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Optional[int]:
           lowercase__		       =						BeitModel(config=UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_      )
           self.parent.assertEqual(result.last_hidden_state.shape     ,(self.batch_size, self.seq_length, self.hidden_size)      )



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Tuple:
           lowercase__		       =						BeitForMaskedImageModeling(config=UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_      )
           self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.seq_length - 1, self.vocab_size)      )



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Dict:
           lowercase__		       =						self.type_sequence_label_size
           lowercase__		       =						BeitForImageClassification(UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_     ,labels=UpperCAmelCase_      )
           self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.type_sequence_label_size)      )

           # test greyscale images
           lowercase__		       =						1
           lowercase__		       =						BeitForImageClassification(UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()

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



       def 							_a      (				self     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_     ,UpperCAmelCase_      )  ->							Dict:
           lowercase__		       =						self.num_labels
           lowercase__		       =						BeitForSemanticSegmentation(UpperCAmelCase_      )
           model.to(UpperCAmelCase_      )
           model.eval()
           lowercase__		       =						model(UpperCAmelCase_      )
           self.parent.assertEqual(
               result.logits.shape     ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )
           lowercase__		       =						model(UpperCAmelCase_     ,labels=UpperCAmelCase_      )
           self.parent.assertEqual(
               result.logits.shape     ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )







       def 							_a      (				self      )  ->							str:
           lowercase__		       =						self.prepare_config_and_inputs()
           lowercase__       ,       lowercase__       ,       lowercase__       ,       lowercase__		       =						config_and_inputs
           lowercase__		       =						{"pixel_values": pixel_values}
           return config, inputs_dict





@require_torch
class 				snake_case (UpperCamelCase		,      UpperCamelCase		,      unittest.TestCase   ):
       lowerCAmelCase__  :Optional[Any]						   =					(
           (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       lowerCAmelCase__  :Optional[int]						   =					(
           {
               "feature-extraction": BeitModel,
               "image-classification": BeitForImageClassification,
               "image-segmentation": BeitForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       lowerCAmelCase__  :Any						   =					False
       lowerCAmelCase__  :Optional[Any]						   =					False
       lowerCAmelCase__  :Optional[Any]						   =					False



       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__		       =						BeitModelTester(self      )
           lowercase__		       =						ConfigTester(self     ,config_class=UpperCAmelCase_     ,has_text_modality=UpperCAmelCase_     ,hidden_size=37      )



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



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



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



       def 							_a      (				self      )  ->							Any:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()

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



       def 							_a      (				self      )  ->							Tuple:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()

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

               lowercase__		       =						["pixel_values"]
               self.assertListEqual(arg_names[:1]     ,UpperCAmelCase_      )



       def 							_a      (				self      )  ->							Tuple:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCAmelCase_      )



       def 							_a      (				self      )  ->							List[Any]:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase_      )



       def 							_a      (				self      )  ->							Any:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_      )



       def 							_a      (				self      )  ->							str:
           lowercase__		       =						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_      )



       def 							_a      (				self      )  ->							int:
           if not self.model_tester.is_training:
               return

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

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

               lowercase__		       =						model_class(UpperCAmelCase_      )
               model.to(UpperCAmelCase_      )
               model.train()
               lowercase__		       =						self._prepare_for_class(UpperCAmelCase_     ,UpperCAmelCase_     ,return_labels=UpperCAmelCase_      )
               lowercase__		       =						model(**UpperCAmelCase_      ).loss
               loss.backward()



       def 							_a      (				self      )  ->							str:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()
           if not self.model_tester.is_training:
               return

           lowercase__		       =						False
           lowercase__		       =						True

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

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



       def 							_a      (				self      )  ->							int:
           lowercase__       ,       lowercase__		       =						self.model_tester.prepare_config_and_inputs_for_common()

           lowercase__		       =						_config_zero_init(UpperCAmelCase_      )
           for model_class in self.all_model_classes:
               lowercase__		       =						model_class(config=UpperCAmelCase_      )
               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 							_a      (				self      )  ->							Optional[Any]:
           for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowercase__		       =						BeitModel.from_pretrained(UpperCAmelCase_      )
               self.assertIsNotNone(UpperCAmelCase_      )





def        lowerCamelCase  (				):





    '''simple docstring'''


    lowercase__		       =						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
    return image



@require_torch
@require_vision
class 				snake_case (unittest.TestCase   ):



       @cached_property
       def 							_a      (				self      )  ->							Any:
           return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224"      ) if is_vision_available() else None



       @slow
       def 							_a      (				self      )  ->							int:
           lowercase__		       =						BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k"      ).to(UpperCAmelCase_      )

           lowercase__		       =						self.default_image_processor
           lowercase__		       =						prepare_img()
           lowercase__		       =						image_processor(images=UpperCAmelCase_     ,return_tensors="pt"      ).pixel_values.to(UpperCAmelCase_      )

           # prepare bool_masked_pos
           lowercase__		       =						torch.ones((1, 196)     ,dtype=torch.bool      ).to(UpperCAmelCase_      )

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

           # verify the logits
           lowercase__		       =						torch.Size((1, 196, 8_192)      )
           self.assertEqual(logits.shape     ,UpperCAmelCase_      )

           lowercase__		       =						torch.tensor(
               [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]]      ).to(UpperCAmelCase_      )

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



       @slow
       def 							_a      (				self      )  ->							Optional[Any]:
           lowercase__		       =						BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224"      ).to(UpperCAmelCase_      )

           lowercase__		       =						self.default_image_processor
           lowercase__		       =						prepare_img()
           lowercase__		       =						image_processor(images=UpperCAmelCase_     ,return_tensors="pt"      ).to(UpperCAmelCase_      )

           # forward pass
           with torch.no_grad():
               lowercase__		       =						model(**UpperCAmelCase_      )
           lowercase__		       =						outputs.logits

           # verify the logits
           lowercase__		       =						torch.Size((1, 1_000)      )
           self.assertEqual(logits.shape     ,UpperCAmelCase_      )

           lowercase__		       =						torch.tensor([-1.23_85, -1.09_87, -1.01_08]      ).to(UpperCAmelCase_      )

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

           lowercase__		       =						281
           self.assertEqual(logits.argmax(-1      ).item()     ,UpperCAmelCase_      )



       @slow
       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__		       =						BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k"      ).to(
               UpperCAmelCase_      )

           lowercase__		       =						self.default_image_processor
           lowercase__		       =						prepare_img()
           lowercase__		       =						image_processor(images=UpperCAmelCase_     ,return_tensors="pt"      ).to(UpperCAmelCase_      )

           # forward pass
           with torch.no_grad():
               lowercase__		       =						model(**UpperCAmelCase_      )
           lowercase__		       =						outputs.logits

           # verify the logits
           lowercase__		       =						torch.Size((1, 21_841)      )
           self.assertEqual(logits.shape     ,UpperCAmelCase_      )

           lowercase__		       =						torch.tensor([1.68_81, -0.27_87, 0.59_01]      ).to(UpperCAmelCase_      )

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

           lowercase__		       =						2_396
           self.assertEqual(logits.argmax(-1      ).item()     ,UpperCAmelCase_      )



       @slow
       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__		       =						BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"      )
           lowercase__		       =						model.to(UpperCAmelCase_      )

           lowercase__		       =						BeitImageProcessor(do_resize=UpperCAmelCase_     ,size=640     ,do_center_crop=UpperCAmelCase_      )

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

           # forward pass
           with torch.no_grad():
               lowercase__		       =						model(**UpperCAmelCase_      )
           lowercase__		       =						outputs.logits

           # verify the logits
           lowercase__		       =						torch.Size((1, 150, 160, 160)      )
           self.assertEqual(logits.shape     ,UpperCAmelCase_      )

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

           if is_pillow_less_than_a:
               lowercase__		       =						torch.tensor(
                   [
                       [[-4.92_25, -2.39_54, -3.05_22], [-2.88_22, -1.00_46, -1.75_61], [-2.95_49, -1.32_28, -2.13_47]],
                       [[-5.81_68, -3.41_29, -4.07_78], [-3.86_51, -2.22_14, -3.02_77], [-3.83_56, -2.46_43, -3.35_35]],
                       [[-0.00_78, 3.99_52, 4.07_54], [2.98_56, 4.69_44, 5.00_35], [3.24_13, 4.78_13, 4.99_69]],
                   ]     ,device=UpperCAmelCase_     ,)
           else:
               lowercase__		       =						torch.tensor(
                   [
                       [[-4.89_60, -2.36_88, -3.03_55], [-2.84_78, -0.98_36, -1.74_18], [-2.94_49, -1.33_32, -2.14_56]],
                       [[-5.80_81, -3.41_24, -4.10_06], [-3.85_61, -2.20_81, -3.03_23], [-3.83_65, -2.46_01, -3.36_69]],
                       [[-0.03_09, 3.98_68, 4.05_40], [2.96_40, 4.68_77, 4.99_76], [3.20_81, 4.76_90, 4.99_42]],
                   ]     ,device=UpperCAmelCase_     ,)

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







       @slow
       def 							_a      (				self      )  ->							str:
           lowercase__		       =						BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"      )
           lowercase__		       =						model.to(UpperCAmelCase_      )

           lowercase__		       =						BeitImageProcessor(do_resize=UpperCAmelCase_     ,size=640     ,do_center_crop=UpperCAmelCase_      )

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

           # forward pass
           with torch.no_grad():
               lowercase__		       =						model(**UpperCAmelCase_      )

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

           lowercase__		       =						image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_     ,target_sizes=[(500, 300)]      )
           lowercase__		       =						torch.Size((500, 300)      )
           self.assertEqual(segmentation[0].shape     ,UpperCAmelCase_      )

           lowercase__		       =						image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_      )
           lowercase__		       =						torch.Size((160, 160)      )
           self.assertEqual(segmentation[0].shape     ,UpperCAmelCase_      )




