


from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('''3.8'''):
    import importlib_metadata
else:
    import importlib.metadata as importlib_metadata


__snake_case   							=						''''''


if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):



    class 	__lowerCamelCase			(tr.AbstractTransform						):







           def __init__(			self: Tuple,A_: str = " "					):






                '''simple docstring'''




                __UpperCamelCase =			sentence_delimiter







           def 		snake_case_	(			self: Union[str, Any],A_: str					):






                '''simple docstring'''




                return list(A_					)







           def 		snake_case_	(			self: Union[str, Any],A_: List[str]					):






                '''simple docstring'''




                __UpperCamelCase =			[]
                for sent_idx, sentence in enumerate(A_					):
                     chars.extend(self.process_string(A_					)					)
                     if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(A_					) - 1:
                          chars.append(self.sentence_delimiter					)
                return chars



    __snake_case   							=						tr.Compose(
        [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
    )
else:
    __snake_case   							=						tr.Compose(
        [
            tr.RemoveMultipleSpaces(),
            tr.Strip(),
            tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
            tr.ReduceToListOfListOfChars(),
        ]
    )


__snake_case   							=						'''\
@inproceedings{inproceedings,
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
    year = {2004},
    month = {01},
    pages = {},
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
'''

__snake_case   							=						'''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''

__snake_case   							=						'''
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = ["this is the prediction", "there is an other sample"]
    >>> references = ["this is the reference", "there is another one"]
    >>> cer = datasets.load_metric("cer")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
'''



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







       def 		snake_case_	(			self: int					):






            '''simple docstring'''




            return datasets.MetricInfo(
                description=_DESCRIPTION,citation=_CITATION,inputs_description=_KWARGS_DESCRIPTION,features=datasets.Features(
                    {
                        'predictions': datasets.Value('string',id='sequence'					),
                        'references': datasets.Value('string',id='sequence'					),
                    }					),codebase_urls=['https://github.com/jitsi/jiwer/'],reference_urls=[
                    'https://en.wikipedia.org/wiki/Word_error_rate',
                    'https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates',
                ],)







       def 		snake_case_	(			self: str,A_: int,A_: Optional[int],A_: List[Any]=False					):






            '''simple docstring'''




            if concatenate_texts:
                 return jiwer.compute_measures(
                     A_,A_,truth_transform=A_,hypothesis_transform=A_,)["wer"]

            __UpperCamelCase =			0
            __UpperCamelCase =			0
            for prediction, reference in zip(A_,A_					):
                 __UpperCamelCase =			jiwer.compute_measures(
                     A_,A_,truth_transform=A_,hypothesis_transform=A_,)
                 incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                 total += measures["substitutions"] + measures["deletions"] + measures["hits"]

            return incorrect / total







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



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

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



			def 				__lowercase					(			self							:				Tuple		)							->					Union[str, Any]:
									snake_case   :			Any						    = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

									snake_case   :			str						    = self.get_config()

									return config, pixel_values, labels, pixel_labels



			def 				__lowercase					(			self							:				str		)							->					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=_lowercase   ,	initializer_range=self.initializer_range   ,	out_indices=self.out_indices   ,	)



			def 				__lowercase					(			self							:				Union[str, Any]   ,	_lowercase							:				int   ,	_lowercase							:				Any   ,	_lowercase							:				List[Any]   ,	_lowercase							:				List[Any]		)							->					Any:
									snake_case   :			int						    = BeitModel(config=_lowercase		)
									model.to(_lowercase		)
									model.eval()
									snake_case   :			List[str]						    = model(_lowercase		)
									self.parent.assertEqual(result.last_hidden_state.shape   ,	(self.batch_size, self.seq_length, self.hidden_size)		)



			def 				__lowercase					(			self							:				Any   ,	_lowercase							:				Any   ,	_lowercase							:				Optional[int]   ,	_lowercase							:				Tuple   ,	_lowercase							:				List[Any]		)							->					Tuple:
									snake_case   :			str						    = BeitForMaskedImageModeling(config=_lowercase		)
									model.to(_lowercase		)
									model.eval()
									snake_case   :			Tuple						    = model(_lowercase		)
									self.parent.assertEqual(result.logits.shape   ,	(self.batch_size, self.seq_length - 1, self.vocab_size)		)



			def 				__lowercase					(			self							:				Optional[Any]   ,	_lowercase							:				List[Any]   ,	_lowercase							:				Tuple   ,	_lowercase							:				Any   ,	_lowercase							:				List[Any]		)							->					str:
									snake_case   :			str						    = self.type_sequence_label_size
									snake_case   :			Union[str, Any]						    = BeitForImageClassification(_lowercase		)
									model.to(_lowercase		)
									model.eval()
									snake_case   :			Union[str, Any]						    = model(_lowercase   ,	labels=_lowercase		)
									self.parent.assertEqual(result.logits.shape   ,	(self.batch_size, self.type_sequence_label_size)		)

									# test greyscale images
									snake_case   :			Dict						    = 1
									snake_case   :			Tuple						    = BeitForImageClassification(_lowercase		)
									model.to(_lowercase		)
									model.eval()

									snake_case   :			Optional[Any]						    = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
									snake_case   :			List[str]						    = model(_lowercase   ,	labels=_lowercase		)
									self.parent.assertEqual(result.logits.shape   ,	(self.batch_size, self.type_sequence_label_size)		)



			def 				__lowercase					(			self							:				str   ,	_lowercase							:				Dict   ,	_lowercase							:				Dict   ,	_lowercase							:				Optional[Any]   ,	_lowercase							:				List[Any]		)							->					List[Any]:
									snake_case   :			List[Any]						    = self.num_labels
									snake_case   :			Union[str, Any]						    = BeitForSemanticSegmentation(_lowercase		)
									model.to(_lowercase		)
									model.eval()
									snake_case   :			Tuple						    = model(_lowercase		)
									self.parent.assertEqual(
									    result.logits.shape   ,	(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)		)
									snake_case   :			Any						    = model(_lowercase   ,	labels=_lowercase		)
									self.parent.assertEqual(
									    result.logits.shape   ,	(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)		)



			def 				__lowercase					(			self							:				Any		)							->					Dict:
									snake_case   :			List[Any]						    = self.prepare_config_and_inputs()
									snake_case    ,			snake_case    ,			snake_case    ,			snake_case   :			Optional[int]						    = config_and_inputs
									snake_case   :			Dict						    = {"pixel_values": pixel_values}
									return config, inputs_dict



@require_torch
class       _a  ( SCREAMING_SNAKE_CASE__     ,	SCREAMING_SNAKE_CASE__     ,	unittest.TestCase):
			__magic_name__     					=     (
			    (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			__magic_name__     					=     (
			    {
			        """feature-extraction""": BeitModel,
			        """image-classification""": BeitForImageClassification,
			        """image-segmentation""": BeitForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			__magic_name__     					=     False
			__magic_name__     					=     False
			__magic_name__     					=     False



			def 				__lowercase					(			self							:				Optional[int]		)							->					Tuple:
									snake_case   :			Optional[Any]						    = BeitModelTester(self		)
									snake_case   :			Union[str, Any]						    = ConfigTester(self   ,	config_class=_lowercase   ,	has_text_modality=_lowercase   ,	hidden_size=37		)



			def 				__lowercase					(			self							:				int		)							->					str:
									self.config_tester.run_common_tests()



			@unittest.skip(reason="BEiT does not use inputs_embeds"		)
			def 				__lowercase					(			self							:				Optional[Any]		)							->					Tuple:
									pass



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



			def 				__lowercase					(			self							:				List[str]		)							->					Union[str, Any]:
									snake_case    ,			snake_case   :			Any						    = self.model_tester.prepare_config_and_inputs_for_common()

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



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

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

															snake_case   :			int						    = ["pixel_values"]
															self.assertListEqual(arg_names[:1]   ,	_lowercase		)



			def 				__lowercase					(			self							:				Any		)							->					List[str]:
									snake_case   :			List[str]						    = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_lowercase		)



			def 				__lowercase					(			self							:				Optional[int]		)							->					str:
									snake_case   :			Optional[Any]						    = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*_lowercase		)



			def 				__lowercase					(			self							:				List[Any]		)							->					Tuple:
									snake_case   :			Optional[Any]						    = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_lowercase		)



			def 				__lowercase					(			self							:				Union[str, Any]		)							->					Optional[int]:
									snake_case   :			List[str]						    = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*_lowercase		)



			def 				__lowercase					(			self							:				Optional[int]		)							->					Optional[Any]:
									if not self.model_tester.is_training:
															return

									snake_case    ,			snake_case   :			Dict						    = self.model_tester.prepare_config_and_inputs_for_common()
									snake_case   :			str						    = True

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

															snake_case   :			List[str]						    = model_class(_lowercase		)
															model.to(_lowercase		)
															model.train()
															snake_case   :			Dict						    = self._prepare_for_class(_lowercase   ,	_lowercase   ,	return_labels=_lowercase		)
															snake_case   :			Tuple						    = model(**_lowercase		).loss
															loss.backward()



			def 				__lowercase					(			self							:				Dict		)							->					str:
									snake_case    ,			snake_case   :			List[str]						    = self.model_tester.prepare_config_and_inputs_for_common()
									if not self.model_tester.is_training:
															return

									snake_case   :			Dict						    = False
									snake_case   :			Dict						    = True

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

															snake_case   :			str						    = model_class(_lowercase		)
															model.gradient_checkpointing_enable()
															model.to(_lowercase		)
															model.train()
															snake_case   :			Dict						    = self._prepare_for_class(_lowercase   ,	_lowercase   ,	return_labels=_lowercase		)
															snake_case   :			str						    = model(**_lowercase		).loss
															loss.backward()



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

									snake_case   :			List[Any]						    = _config_zero_init(_lowercase		)
									for model_class in self.all_model_classes:
															snake_case   :			Union[str, Any]						    = model_class(config=_lowercase		)
															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 				__lowercase					(			self							:				Optional[Any]		)							->					List[Any]:
									for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															snake_case   :			Tuple						    = BeitModel.from_pretrained(_lowercase		)
															self.assertIsNotNone(_lowercase		)



def  __SCREAMING_SNAKE_CASE		(			):
						"""simple docstring"""






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

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



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



			@slow
			def 				__lowercase					(			self							:				Dict		)							->					Tuple:
									snake_case   :			int						    = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k"		).to(_lowercase		)

									snake_case   :			str						    = self.default_image_processor
									snake_case   :			int						    = prepare_img()
									snake_case   :			int						    = image_processor(images=_lowercase   ,	return_tensors="pt"		).pixel_values.to(_lowercase		)

									# prepare bool_masked_pos
									snake_case   :			str						    = torch.ones((1, 196)   ,	dtype=torch.bool		).to(_lowercase		)

									# forward pass
									with torch.no_grad():
															snake_case   :			Optional[Any]						    = model(pixel_values=_lowercase   ,	bool_masked_pos=_lowercase		)
									snake_case   :			Any						    = outputs.logits

									# verify the logits
									snake_case   :			int						    = torch.Size((1, 196, 8192)		)
									self.assertEqual(logits.shape   ,	_lowercase		)

									snake_case   :			List[Any]						    = torch.tensor(
									    [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]		).to(_lowercase		)

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



			@slow
			def 				__lowercase					(			self							:				List[str]		)							->					Tuple:
									snake_case   :			List[Any]						    = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224"		).to(_lowercase		)

									snake_case   :			Tuple						    = self.default_image_processor
									snake_case   :			Dict						    = prepare_img()
									snake_case   :			int						    = image_processor(images=_lowercase   ,	return_tensors="pt"		).to(_lowercase		)

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

									# verify the logits
									snake_case   :			Dict						    = torch.Size((1, 1000)		)
									self.assertEqual(logits.shape   ,	_lowercase		)

									snake_case   :			Optional[Any]						    = torch.tensor([-1.2385, -1.0987, -1.0108]		).to(_lowercase		)

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

									snake_case   :			Optional[int]						    = 281
									self.assertEqual(logits.argmax(-1		).item()   ,	_lowercase		)



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

									snake_case   :			int						    = self.default_image_processor
									snake_case   :			List[str]						    = prepare_img()
									snake_case   :			Tuple						    = image_processor(images=_lowercase   ,	return_tensors="pt"		).to(_lowercase		)

									# forward pass
									with torch.no_grad():
															snake_case   :			Optional[Any]						    = model(**_lowercase		)
									snake_case   :			str						    = outputs.logits

									# verify the logits
									snake_case   :			int						    = torch.Size((1, 21841)		)
									self.assertEqual(logits.shape   ,	_lowercase		)

									snake_case   :			Optional[Any]						    = torch.tensor([1.6881, -0.2787, 0.5901]		).to(_lowercase		)

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

									snake_case   :			Dict						    = 2396
									self.assertEqual(logits.argmax(-1		).item()   ,	_lowercase		)



			@slow
			def 				__lowercase					(			self							:				int		)							->					Union[str, Any]:
									snake_case   :			Optional[Any]						    = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"		)
									snake_case   :			Optional[int]						    = model.to(_lowercase		)

									snake_case   :			Optional[Any]						    = BeitImageProcessor(do_resize=_lowercase   ,	size=640   ,	do_center_crop=_lowercase		)

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

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

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

									snake_case   :			Dict						    = version.parse(PIL.__version__		) < version.parse("9.0.0"		)

									if is_pillow_less_than_a:
															snake_case   :			Dict						    = 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=_lowercase   ,	)
									else:
															snake_case   :			List[Any]						    = 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=_lowercase   ,	)

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



			@slow
			def 				__lowercase					(			self							:				List[str]		)							->					Tuple:
									snake_case   :			str						    = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640"		)
									snake_case   :			Tuple						    = model.to(_lowercase		)

									snake_case   :			List[str]						    = BeitImageProcessor(do_resize=_lowercase   ,	size=640   ,	do_center_crop=_lowercase		)

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

									# forward pass
									with torch.no_grad():
															snake_case   :			Tuple						    = model(**_lowercase		)

									snake_case   :			Tuple						    = outputs.logits.detach().cpu()

									snake_case   :			Optional[Any]						    = image_processor.post_process_semantic_segmentation(outputs=_lowercase   ,	target_sizes=[(500, 300)]		)
									snake_case   :			List[str]						    = torch.Size((500, 300)		)
									self.assertEqual(segmentation[0].shape   ,	_lowercase		)

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



