




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






			'''simple docstring'''





			def __init__( self			:   Optional[int]       ,						lowerCamelCase_			:   Optional[int]       ,						lowerCamelCase_			:   Any=100       ,						lowerCamelCase_			:   int=13       ,						lowerCamelCase_			:   str=30       ,						lowerCamelCase_			:   List[str]=2       ,						lowerCamelCase_			:   int=3       ,						lowerCamelCase_			:   Union[str, Any]=True       ,						lowerCamelCase_			:   str=True       ,						lowerCamelCase_			:   Dict=32       ,						lowerCamelCase_			:   Optional[int]=4       ,						lowerCamelCase_			:   List[Any]=4       ,						lowerCamelCase_			:   List[str]=37       ,						lowerCamelCase_			:   Any="gelu"       ,						lowerCamelCase_			:   int=0.1       ,						lowerCamelCase_			:   str=0.1       ,						lowerCamelCase_			:   Tuple=10       ,						lowerCamelCase_			:   Union[str, Any]=0.0_2       ,						lowerCamelCase_			:   Union[str, Any]=3       ,						lowerCamelCase_			:   Optional[Any]=None       ,						lowerCamelCase_			:   Tuple=[0, 1, 2, 3]       ,						)						->   Dict:
								__magic_name__							:	int    							=							parent
								__magic_name__							:	List[Any]    							=							100
								__magic_name__							:	List[Any]    							=							batch_size
								__magic_name__							:	Optional[int]    							=							image_size
								__magic_name__							:	Tuple    							=							patch_size
								__magic_name__							:	str    							=							num_channels
								__magic_name__							:	Any    							=							is_training
								__magic_name__							:	Tuple    							=							use_labels
								__magic_name__							:	Tuple    							=							hidden_size
								__magic_name__							:	Optional[Any]    							=							num_hidden_layers
								__magic_name__							:	int    							=							num_attention_heads
								__magic_name__							:	int    							=							intermediate_size
								__magic_name__							:	Optional[int]    							=							hidden_act
								__magic_name__							:	Dict    							=							hidden_dropout_prob
								__magic_name__							:	List[Any]    							=							attention_probs_dropout_prob
								__magic_name__							:	str    							=							type_sequence_label_size
								__magic_name__							:	Union[str, Any]    							=							initializer_range
								__magic_name__							:	int    							=							scope
								__magic_name__							:	Any    							=							out_indices
								__magic_name__							:	int    							=							num_labels

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

			def 							UpperCAmelCase__       ( self			:   Any  )						->   Optional[int]:
								__magic_name__							:	List[str]    							=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

								__magic_name__							:	Optional[int]    							=							None
								__magic_name__							:	int    							=							None
								if self.use_labels:
													__magic_name__							:	Tuple    							=							ids_tensor([self.batch_size]       ,						self.type_sequence_label_size  )
													__magic_name__							:	int    							=							ids_tensor([self.batch_size, self.image_size, self.image_size]       ,						self.num_labels  )

								__magic_name__							:	Dict    							=							self.get_config()

								return config, pixel_values, labels, pixel_labels

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]  )						->   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=lowerCamelCase_       ,						initializer_range=self.initializer_range       ,						out_indices=self.out_indices       ,						)

			def 							UpperCAmelCase__       ( self			:   Dict       ,						lowerCamelCase_			:   Dict       ,						lowerCamelCase_			:   str       ,						lowerCamelCase_			:   Optional[Any]       ,						lowerCamelCase_			:   List[str]  )						->   Union[str, Any]:
								__magic_name__							:	str    							=							BeitModel(config=lowerCamelCase_  )
								model.to(lowerCamelCase_  )
								model.eval()
								__magic_name__							:	Optional[int]    							=							model(lowerCamelCase_  )
								self.parent.assertEqual(result.last_hidden_state.shape       ,						(self.batch_size, self.seq_length, self.hidden_size)  )

			def 							UpperCAmelCase__       ( self			:   List[Any]       ,						lowerCamelCase_			:   Union[str, Any]       ,						lowerCamelCase_			:   int       ,						lowerCamelCase_			:   Union[str, Any]       ,						lowerCamelCase_			:   Dict  )						->   str:
								__magic_name__							:	Optional[int]    							=							BeitForMaskedImageModeling(config=lowerCamelCase_  )
								model.to(lowerCamelCase_  )
								model.eval()
								__magic_name__							:	Any    							=							model(lowerCamelCase_  )
								self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.seq_length - 1, self.vocab_size)  )

			def 							UpperCAmelCase__       ( self			:   List[str]       ,						lowerCamelCase_			:   List[str]       ,						lowerCamelCase_			:   Optional[Any]       ,						lowerCamelCase_			:   Optional[int]       ,						lowerCamelCase_			:   Union[str, Any]  )						->   Dict:
								__magic_name__							:	Tuple    							=							self.type_sequence_label_size
								__magic_name__							:	Any    							=							BeitForImageClassification(lowerCamelCase_  )
								model.to(lowerCamelCase_  )
								model.eval()
								__magic_name__							:	Any    							=							model(lowerCamelCase_       ,						labels=lowerCamelCase_  )
								self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.type_sequence_label_size)  )

								# test greyscale images
								__magic_name__							:	List[Any]    							=							1
								__magic_name__							:	Tuple    							=							BeitForImageClassification(lowerCamelCase_  )
								model.to(lowerCamelCase_  )
								model.eval()

								__magic_name__							:	int    							=							floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
								__magic_name__							:	Tuple    							=							model(lowerCamelCase_       ,						labels=lowerCamelCase_  )
								self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.type_sequence_label_size)  )

			def 							UpperCAmelCase__       ( self			:   Optional[int]       ,						lowerCamelCase_			:   Optional[int]       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   Optional[Any]  )						->   Optional[Any]:
								__magic_name__							:	Any    							=							self.num_labels
								__magic_name__							:	Dict    							=							BeitForSemanticSegmentation(lowerCamelCase_  )
								model.to(lowerCamelCase_  )
								model.eval()
								__magic_name__							:	Tuple    							=							model(lowerCamelCase_  )
								self.parent.assertEqual(
								    result.logits.shape       ,						(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)  )
								__magic_name__							:	Union[str, Any]    							=							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			:   Optional[Any]  )						->   List[Any]:
								__magic_name__							:	int    							=							self.prepare_config_and_inputs()
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Optional[Any]    							=							config_and_inputs
								__magic_name__							:	Dict    							=							{'''pixel_values''': pixel_values}
								return config, inputs_dict






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






			'''simple docstring'''





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

			UpperCamelCase__								=False
			UpperCamelCase__								=False
			UpperCamelCase__								=False

			def 							UpperCAmelCase__       ( self			:   int  )						->   Dict:
								__magic_name__							:	Union[str, Any]    							=							BeitModelTester(self  )
								__magic_name__							:	Dict    							=							ConfigTester(self       ,						config_class=lowerCamelCase_       ,						has_text_modality=lowerCamelCase_       ,						hidden_size=37  )

			def 							UpperCAmelCase__       ( self			:   List[str]  )						->   Tuple:
								self.config_tester.run_common_tests()

			@unittest.skip(reason='''BEiT does not use inputs_embeds'''  )
			def 							UpperCAmelCase__       ( self			:   str  )						->   Union[str, Any]:
								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			:   int  )						->   List[Any]:
								pass

			def 							UpperCAmelCase__       ( self			:   str  )						->   Tuple:
								__magic_name__							,    __magic_name__							:	Optional[int]    							=							self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													__magic_name__							:	Dict    							=							model_class(lowerCamelCase_  )
													self.assertIsInstance(model.get_input_embeddings()       ,						(nn.Module)  )
													__magic_name__							:	List[str]    							=							model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(lowerCamelCase_       ,						nn.Linear  )  )

			def 							UpperCAmelCase__       ( self			:   Optional[int]  )						->   Optional[int]:
								__magic_name__							,    __magic_name__							:	List[str]    							=							self.model_tester.prepare_config_and_inputs_for_common()

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

													__magic_name__							:	List[Any]    							=							['''pixel_values''']
													self.assertListEqual(arg_names[:1]       ,						lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   str  )						->   Tuple:
								__magic_name__							:	Optional[int]    							=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   int  )						->   Any:
								__magic_name__							:	Optional[int]    							=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   int  )						->   Optional[Any]:
								__magic_name__							:	List[Any]    							=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   List[str]  )						->   Optional[int]:
								__magic_name__							:	Tuple    							=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   List[str]  )						->   List[Any]:
								if not self.model_tester.is_training:
													return

								__magic_name__							,    __magic_name__							:	Any    							=							self.model_tester.prepare_config_and_inputs_for_common()
								__magic_name__							:	Any    							=							True

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

													__magic_name__							:	Any    							=							model_class(lowerCamelCase_  )
													model.to(lowerCamelCase_  )
													model.train()
													__magic_name__							:	List[Any]    							=							self._prepare_for_class(lowerCamelCase_       ,						lowerCamelCase_       ,						return_labels=lowerCamelCase_  )
													__magic_name__							:	Any    							=							model(**lowerCamelCase_  ).loss
													loss.backward()

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]  )						->   List[Any]:
								__magic_name__							,    __magic_name__							:	Optional[Any]    							=							self.model_tester.prepare_config_and_inputs_for_common()
								if not self.model_tester.is_training:
													return

								__magic_name__							:	Dict    							=							False
								__magic_name__							:	List[str]    							=							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

													__magic_name__							:	Optional[Any]    							=							model_class(lowerCamelCase_  )
													model.gradient_checkpointing_enable()
													model.to(lowerCamelCase_  )
													model.train()
													__magic_name__							:	List[Any]    							=							self._prepare_for_class(lowerCamelCase_       ,						lowerCamelCase_       ,						return_labels=lowerCamelCase_  )
													__magic_name__							:	List[Any]    							=							model(**lowerCamelCase_  ).loss
													loss.backward()

			def 							UpperCAmelCase__       ( self			:   Optional[int]  )						->   List[Any]:
								__magic_name__							,    __magic_name__							:	Union[str, Any]    							=							self.model_tester.prepare_config_and_inputs_for_common()

								__magic_name__							:	Any    							=							_config_zero_init(lowerCamelCase_  )
								for model_class in self.all_model_classes:
													__magic_name__							:	List[str]    							=							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			:   Optional[int]  )						->   Optional[Any]:
								for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__magic_name__							:	Optional[Any]    							=							BeitModel.from_pretrained(lowerCamelCase_  )
													self.assertIsNotNone(lowerCamelCase_  )







def 		lowercase__   (		):





					'''simple docstring'''






					__magic_name__							:	List[str]    							=							Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
					return image


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






			'''simple docstring'''





			@cached_property
			def 							UpperCAmelCase__       ( self			:   Any  )						->   List[Any]:
								return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224'''  ) if is_vision_available() else None

			@slow
			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   List[str]:
								__magic_name__							:	Optional[Any]    							=							BeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k'''  ).to(lowerCamelCase_  )

								__magic_name__							:	Optional[Any]    							=							self.default_image_processor
								__magic_name__							:	Optional[Any]    							=							prepare_img()
								__magic_name__							:	List[Any]    							=							image_processor(images=lowerCamelCase_       ,						return_tensors='''pt'''  ).pixel_values.to(lowerCamelCase_  )

								# prepare bool_masked_pos
								__magic_name__							:	Union[str, Any]    							=							torch.ones((1, 196)       ,						dtype=torch.bool  ).to(lowerCamelCase_  )

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

								# verify the logits
								__magic_name__							:	Tuple    							=							torch.Size((1, 196, 8192)  )
								self.assertEqual(logits.shape       ,						lowerCamelCase_  )

								__magic_name__							:	List[str]    							=							torch.tensor(
								    [[-3.2_4_3_7, 0.5_0_7_2, -1_3.9_1_7_4], [-3.2_4_5_6, 0.4_9_4_8, -1_3.9_4_0_1], [-3.2_0_3_3, 0.5_1_2_1, -1_3.8_5_5_0]]  ).to(lowerCamelCase_  )

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

			@slow
			def 							UpperCAmelCase__       ( self			:   Union[str, Any]  )						->   Optional[int]:
								__magic_name__							:	List[str]    							=							BeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224'''  ).to(lowerCamelCase_  )

								__magic_name__							:	str    							=							self.default_image_processor
								__magic_name__							:	List[Any]    							=							prepare_img()
								__magic_name__							:	int    							=							image_processor(images=lowerCamelCase_       ,						return_tensors='''pt'''  ).to(lowerCamelCase_  )

								# forward pass
								with torch.no_grad():
													__magic_name__							:	Optional[Any]    							=							model(**lowerCamelCase_  )
								__magic_name__							:	Optional[Any]    							=							outputs.logits

								# verify the logits
								__magic_name__							:	int    							=							torch.Size((1, 1000)  )
								self.assertEqual(logits.shape       ,						lowerCamelCase_  )

								__magic_name__							:	Union[str, Any]    							=							torch.tensor([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8]  ).to(lowerCamelCase_  )

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

								__magic_name__							:	List[Any]    							=							281
								self.assertEqual(logits.argmax(-1  ).item()       ,						lowerCamelCase_  )

			@slow
			def 							UpperCAmelCase__       ( self			:   Any  )						->   List[str]:
								__magic_name__							:	int    							=							BeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k'''  ).to(
								    lowerCamelCase_  )

								__magic_name__							:	List[Any]    							=							self.default_image_processor
								__magic_name__							:	Any    							=							prepare_img()
								__magic_name__							:	Tuple    							=							image_processor(images=lowerCamelCase_       ,						return_tensors='''pt'''  ).to(lowerCamelCase_  )

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

								# verify the logits
								__magic_name__							:	List[str]    							=							torch.Size((1, 21841)  )
								self.assertEqual(logits.shape       ,						lowerCamelCase_  )

								__magic_name__							:	Optional[int]    							=							torch.tensor([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1]  ).to(lowerCamelCase_  )

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

								__magic_name__							:	str    							=							2396
								self.assertEqual(logits.argmax(-1  ).item()       ,						lowerCamelCase_  )

			@slow
			def 							UpperCAmelCase__       ( self			:   Tuple  )						->   Any:
								__magic_name__							:	str    							=							BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''  )
								__magic_name__							:	Any    							=							model.to(lowerCamelCase_  )

								__magic_name__							:	Optional[Any]    							=							BeitImageProcessor(do_resize=lowerCamelCase_       ,						size=640       ,						do_center_crop=lowerCamelCase_  )

								__magic_name__							:	Any    							=							load_dataset('''hf-internal-testing/fixtures_ade20k'''       ,						split='''test'''  )
								__magic_name__							:	Tuple    							=							Image.open(ds[0]['''file''']  )
								__magic_name__							:	Optional[int]    							=							image_processor(images=lowerCamelCase_       ,						return_tensors='''pt'''  ).to(lowerCamelCase_  )

								# forward pass
								with torch.no_grad():
													__magic_name__							:	List[str]    							=							model(**lowerCamelCase_  )
								__magic_name__							:	List[Any]    							=							outputs.logits

								# verify the logits
								__magic_name__							:	Union[str, Any]    							=							torch.Size((1, 150, 160, 160)  )
								self.assertEqual(logits.shape       ,						lowerCamelCase_  )

								__magic_name__							:	List[str]    							=							version.parse(PIL.__version__  ) < version.parse('''9.0.0'''  )

								if is_pillow_less_than_a:
													__magic_name__							:	int    							=							torch.tensor(
													    [
													        [[-4.9_2_2_5, -2.3_9_5_4, -3.0_5_2_2], [-2.8_8_2_2, -1.0_0_4_6, -1.7_5_6_1], [-2.9_5_4_9, -1.3_2_2_8, -2.1_3_4_7]],
													        [[-5.8_1_6_8, -3.4_1_2_9, -4.0_7_7_8], [-3.8_6_5_1, -2.2_2_1_4, -3.0_2_7_7], [-3.8_3_5_6, -2.4_6_4_3, -3.3_5_3_5]],
													        [[-0.0_0_7_8, 3.9_9_5_2, 4.0_7_5_4], [2.9_8_5_6, 4.6_9_4_4, 5.0_0_3_5], [3.2_4_1_3, 4.7_8_1_3, 4.9_9_6_9]],
													    ]       ,						device=lowerCamelCase_       ,						)
								else:
													__magic_name__							:	List[Any]    							=							torch.tensor(
													    [
													        [[-4.8_9_6_0, -2.3_6_8_8, -3.0_3_5_5], [-2.8_4_7_8, -0.9_8_3_6, -1.7_4_1_8], [-2.9_4_4_9, -1.3_3_3_2, -2.1_4_5_6]],
													        [[-5.8_0_8_1, -3.4_1_2_4, -4.1_0_0_6], [-3.8_5_6_1, -2.2_0_8_1, -3.0_3_2_3], [-3.8_3_6_5, -2.4_6_0_1, -3.3_6_6_9]],
													        [[-0.0_3_0_9, 3.9_8_6_8, 4.0_5_4_0], [2.9_6_4_0, 4.6_8_7_7, 4.9_9_7_6], [3.2_0_8_1, 4.7_6_9_0, 4.9_9_4_2]],
													    ]       ,						device=lowerCamelCase_       ,						)

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


			@slow
			def 							UpperCAmelCase__       ( self			:   Any  )						->   int:
								__magic_name__							:	List[Any]    							=							BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''  )
								__magic_name__							:	Dict    							=							model.to(lowerCamelCase_  )

								__magic_name__							:	Union[str, Any]    							=							BeitImageProcessor(do_resize=lowerCamelCase_       ,						size=640       ,						do_center_crop=lowerCamelCase_  )

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

								# forward pass
								with torch.no_grad():
													__magic_name__							:	Optional[int]    							=							model(**lowerCamelCase_  )

								__magic_name__							:	Dict    							=							outputs.logits.detach().cpu()

								__magic_name__							:	Tuple    							=							image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase_       ,						target_sizes=[(500, 300)]  )
								__magic_name__							:	Optional[Any]    							=							torch.Size((500, 300)  )
								self.assertEqual(segmentation[0].shape       ,						lowerCamelCase_  )

								__magic_name__							:	Dict    							=							image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase_  )
								__magic_name__							:	int    							=							torch.Size((160, 160)  )
								self.assertEqual(segmentation[0].shape       ,						lowerCamelCase_  )









from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_tf_available,
    is_torch_available,
)


__lowerCamelCase   :						List[Any]				=			{
    '''configuration_speech_to_text''': ['''SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2TextConfig'''],
    '''processing_speech_to_text''': ['''Speech2TextProcessor'''],
}

try:
	if not is_sentencepiece_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__lowerCamelCase   :						Any				=			['''Speech2TextTokenizer''']

try:
	if not is_speech_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__lowerCamelCase   :						Optional[Any]				=			['''Speech2TextFeatureExtractor''']

try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__lowerCamelCase   :						Any				=			[
	    '''TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''TFSpeech2TextForConditionalGeneration''',
	    '''TFSpeech2TextModel''',
	    '''TFSpeech2TextPreTrainedModel''',
	]

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__lowerCamelCase   :						Any				=			[
	    '''SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''Speech2TextForConditionalGeneration''',
	    '''Speech2TextModel''',
	    '''Speech2TextPreTrainedModel''',
	]


if TYPE_CHECKING:
	from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig
	from .processing_speech_to_text import SpeechaTextProcessor

	try:
		if not is_sentencepiece_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .tokenization_speech_to_text import SpeechaTextTokenizer

	try:
		if not is_speech_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_tf_speech_to_text import (
		    TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFSpeechaTextForConditionalGeneration,
		    TFSpeechaTextModel,
		    TFSpeechaTextPreTrainedModel,
		)

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_speech_to_text import (
		    SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    SpeechaTextForConditionalGeneration,
		    SpeechaTextModel,
		    SpeechaTextPreTrainedModel,
		)

else:
	import sys

	__lowerCamelCase   :						List[str]				=			_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



