'''simple docstring'''




import json
from typing import Dict, List, Optional, Tuple, Union

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_led import LEDTokenizer


_A								=   logging.get_logger(__name__)


_A								=   {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

_A								=   {
    'vocab_file': {
        'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json',
    },
    'merges_file': {
        'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt',
    },
    'tokenizer_file': {
        'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json',
    },
}

_A								=   {
    'allenai/led-base-16384': 1_6_3_8_4,
}


class       UpperCAmelCase__  (       _snake_case			):






   """simple docstring"""
   A							:       Optional[Any]     =    VOCAB_FILES_NAMES
   A							:       Optional[int]     =    PRETRAINED_VOCAB_FILES_MAP
   A							:       Union[str, Any]     =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A							:       int     =    LEDTokenizer
   A							:       Optional[int]     =    ['''input_ids''', '''attention_mask''']
   def __init__(self       ,				_a=None       ,				_a=None       ,				_a=None       ,				_a="replace"       ,				_a="<s>"       ,				_a="</s>"       ,				_a="</s>"       ,				_a="<s>"       ,				_a="<unk>"       ,				_a="<pad>"       ,				_a="<mask>"       ,				_a=False       ,				_a=True       ,				**_a       ,				)    ->     int:
        super().__init__(
            _a       ,				_a       ,				tokenizer_file=_a       ,				errors=_a       ,				bos_token=_a       ,				eos_token=_a       ,				sep_token=_a       ,				cls_token=_a       ,				unk_token=_a       ,				pad_token=_a       ,				mask_token=_a       ,				add_prefix_space=_a       ,				trim_offsets=_a       ,				**_a       ,				)

        lowercase_					:       Tuple     				=					json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()				)
        if pre_tok_state.get('add_prefix_space'       ,				_a				) != add_prefix_space:
             lowercase_					:       int     				=					getattr(_a       ,				pre_tok_state.pop('type'				)				)
             lowercase_					:       Any     				=					add_prefix_space
             lowercase_					:       List[Any]     				=					pre_tok_class(**_a				)

        lowercase_					:       Optional[int]     				=					add_prefix_space

        # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
        lowercase_					:       str     				=					'post_processor'
        lowercase_					:       List[str]     				=					getattr(self.backend_tokenizer       ,				_a       ,				_a				)
        if tokenizer_component_instance:
             lowercase_					:       Union[str, Any]     				=					json.loads(tokenizer_component_instance.__getstate__()				)

             # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
             if "sep" in state:
                  lowercase_					:       Any     				=					tuple(state['sep']				)
             if "cls" in state:
                  lowercase_					:       Tuple     				=					tuple(state['cls']				)

             lowercase_					:       Any     				=					False

             if state.get('add_prefix_space'       ,				_a				) != add_prefix_space:
                  lowercase_					:       int     				=					add_prefix_space
                  lowercase_					:       Dict     				=					True

             if state.get('trim_offsets'       ,				_a				) != trim_offsets:
                  lowercase_					:       List[Any]     				=					trim_offsets
                  lowercase_					:       Dict     				=					True

             if changes_to_apply:
                  lowercase_					:       Union[str, Any]     				=					getattr(_a       ,				state.pop('type'				)				)
                  lowercase_					:       int     				=					component_class(**_a				)
                  setattr(self.backend_tokenizer       ,				_a       ,				_a				)
   @property
   # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED
   def 		_lowerCamelCase (self				)    ->     str:
        if self._mask_token is None:
             if self.verbose:
                  logger.error('Using mask_token, but it is not set yet.'				)
             return None
        return str(self._mask_token				)
   @mask_token.setter
   def 		_lowerCamelCase (self       ,				_a				)    ->     Dict:
        lowercase_					:       Optional[Any]     				=					AddedToken(_a       ,				lstrip=_a       ,				rstrip=_a				) if isinstance(_a       ,				_a				) else value
        lowercase_					:       int     				=					value
   def 		_lowerCamelCase (self       ,				*_a       ,				**_a				)    ->     BatchEncoding:
        lowercase_					:       Any     				=					kwargs.get('is_split_into_words'       ,				_a				)

        if is_split_into_words and not self.add_prefix_space:
             raise ValueError(
                 f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
                 'to use it with pretokenized inputs.'				)

        return super()._batch_encode_plus(*_a       ,				**_a				)
   def 		_lowerCamelCase (self       ,				*_a       ,				**_a				)    ->     BatchEncoding:
        lowercase_					:       List[str]     				=					kwargs.get('is_split_into_words'       ,				_a				)

        if is_split_into_words and not self.add_prefix_space:
             raise ValueError(
                 f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
                 'to use it with pretokenized inputs.'				)

        return super()._encode_plus(*_a       ,				**_a				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a = None				)    ->     Tuple[str]:
        lowercase_					:       Any     				=					self._tokenizer.model.save(_a       ,				name=_a				)
        return tuple(_a				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a=None				)    ->     Tuple:
        lowercase_					:       Tuple     				=					[self.bos_token_id] + token_ids_a + [self.eos_token_id]
        if token_ids_a is None:
             return output

        return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
   def 		_lowerCamelCase (self       ,				_a       ,				_a = None				)    ->     List[int]:
        lowercase_					:       str     				=					[self.sep_token_id]
        lowercase_					:       Optional[int]     				=					[self.cls_token_id]

        if token_ids_a is None:
             return len(cls + token_ids_a + sep				) * [0]
        return len(cls + token_ids_a + sep + sep + token_ids_a + sep				) * [0]





   def 		_lowerCamelCase (self       ,				_a       ,				_a = None       ,				_a = PaddingStrategy.DO_NOT_PAD       ,				_a = None       ,				_a = None       ,				)    ->     dict:
        lowercase_					:       Tuple     				=					super()._pad(
            encoded_inputs=_a       ,				max_length=_a       ,				padding_strategy=_a       ,				pad_to_multiple_of=_a       ,				return_attention_mask=_a       ,				)

        # Load from model defaults
        if return_attention_mask is None:
             lowercase_					:       Optional[int]     				=					'attention_mask' in self.model_input_names

        if return_attention_mask and "global_attention_mask" in encoded_inputs:
             lowercase_					:       List[Any]     				=					encoded_inputs[self.model_input_names[0]]
             # `global_attention_mask` need to have the same length as other (sequential) inputs.
             lowercase_					:       Any     				=					len(encoded_inputs['global_attention_mask']				) != len(_a				)

             if needs_to_be_padded:
                  lowercase_					:       Union[str, Any]     				=					len(_a				) - len(encoded_inputs['global_attention_mask']				)

                  if self.padding_side == "right":
                       # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
                       lowercase_					:       int     				=					(
                           encoded_inputs['global_attention_mask'] + [-1] * difference
                       )
                  elif self.padding_side == "left":
                       lowercase_					:       str     				=					[-1] * difference + encoded_inputs[
                           'global_attention_mask'
                       ]
                  else:
                       raise ValueError('Invalid padding strategy:' + str(self.padding_side				)				)

        return encoded_inputs





'''simple docstring'''




import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     MODEL_MAPPING,
     SegformerForImageClassification,
     SegformerForSemanticSegmentation,
     SegformerModel,
 )
 from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import SegformerImageProcessor


class       UpperCAmelCase__  (       _snake_case			):






   """simple docstring"""
   def 		_lowerCamelCase (self				)    ->     Any:
        lowercase_					:       Optional[Any]     				=					self.config_class(**self.inputs_dict				)
        self.parent.assertTrue(hasattr(_a       ,				'hidden_sizes'				)				)
        self.parent.assertTrue(hasattr(_a       ,				'num_attention_heads'				)				)
        self.parent.assertTrue(hasattr(_a       ,				'num_encoder_blocks'				)				)



class       UpperCAmelCase__  :






   """simple docstring"""
   def __init__(self       ,				_a       ,				_a=13       ,				_a=64       ,				_a=3       ,				_a=4       ,				_a=[2, 2, 2, 2]       ,				_a=[8, 4, 2, 1]       ,				_a=[16, 32, 64, 128]       ,				_a=[1, 4, 8, 16]       ,				_a=[1, 2, 4, 8]       ,				_a=True       ,				_a=True       ,				_a="gelu"       ,				_a=0.1       ,				_a=0.1       ,				_a=0.02       ,				_a=3       ,				_a=None       ,				)    ->     List[Any]:
        lowercase_					:       Dict     				=					parent
        lowercase_					:       int     				=					batch_size
        lowercase_					:       Any     				=					image_size
        lowercase_					:       List[str]     				=					num_channels
        lowercase_					:       str     				=					num_encoder_blocks
        lowercase_					:       Tuple     				=					sr_ratios
        lowercase_					:       Tuple     				=					depths
        lowercase_					:       Dict     				=					hidden_sizes
        lowercase_					:       Optional[int]     				=					downsampling_rates
        lowercase_					:       List[str]     				=					num_attention_heads
        lowercase_					:       List[Any]     				=					is_training
        lowercase_					:       Dict     				=					use_labels
        lowercase_					:       Optional[Any]     				=					hidden_act
        lowercase_					:       Any     				=					hidden_dropout_prob
        lowercase_					:       int     				=					attention_probs_dropout_prob
        lowercase_					:       Any     				=					initializer_range
        lowercase_					:       List[str]     				=					num_labels
        lowercase_					:       str     				=					scope
   def 		_lowerCamelCase (self				)    ->     str:
        lowercase_					:       Union[str, Any]     				=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

        lowercase_					:       str     				=					None
        if self.use_labels:
             lowercase_					:       Optional[Any]     				=					ids_tensor([self.batch_size, self.image_size, self.image_size]       ,				self.num_labels				)

        lowercase_					:       Tuple     				=					self.get_config()
        return config, pixel_values, labels
   def 		_lowerCamelCase (self				)    ->     List[Any]:
        return SegformerConfig(
            image_size=self.image_size       ,				num_channels=self.num_channels       ,				num_encoder_blocks=self.num_encoder_blocks       ,				depths=self.depths       ,				hidden_sizes=self.hidden_sizes       ,				num_attention_heads=self.num_attention_heads       ,				hidden_act=self.hidden_act       ,				hidden_dropout_prob=self.hidden_dropout_prob       ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,				initializer_range=self.initializer_range       ,				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a				)    ->     Dict:
        lowercase_					:       Union[str, Any]     				=					SegformerModel(config=_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       int     				=					model(_a				)
        lowercase_					:       Any     				=					self.image_size // (self.downsampling_rates[-1] * 2)
        self.parent.assertEqual(
            result.last_hidden_state.shape       ,				(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a				)    ->     Tuple:
        lowercase_					:       Optional[Any]     				=					self.num_labels
        lowercase_					:       Union[str, Any]     				=					SegformerForSemanticSegmentation(_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       Tuple     				=					model(_a				)
        self.parent.assertEqual(
            result.logits.shape       ,				(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)				)
        lowercase_					:       str     				=					model(_a       ,				labels=_a				)
        self.parent.assertEqual(
            result.logits.shape       ,				(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)				)
        self.parent.assertGreater(result.loss       ,				0.0				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a				)    ->     int:
        lowercase_					:       Dict     				=					1
        lowercase_					:       Dict     				=					SegformerForSemanticSegmentation(config=_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       List[str]     				=					torch.randint(0       ,				1       ,				(self.batch_size, self.image_size, self.image_size)				).to(_a				)
        lowercase_					:       Any     				=					model(_a       ,				labels=_a				)
        self.parent.assertGreater(result.loss       ,				0.0				)





   def 		_lowerCamelCase (self				)    ->     str:
        lowercase_					:       Any     				=					self.prepare_config_and_inputs()
        lowercase_				,lowercase_				,lowercase_					:       Dict     				=					config_and_inputs
        lowercase_					:       int     				=					{'pixel_values': pixel_values}
        return config, inputs_dict



@require_torch
class       UpperCAmelCase__  (       _snake_case					,     _snake_case					,     unittest.TestCase			):






   """simple docstring"""
   A							:       int     =    (
       (
           SegformerModel,
           SegformerForSemanticSegmentation,
           SegformerForImageClassification,
       )
       if is_torch_available()
       else ()
   )
   A							:       Tuple     =    (
       {
           '''feature-extraction''': SegformerModel,
           '''image-classification''': SegformerForImageClassification,
           '''image-segmentation''': SegformerForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   A							:       str     =    True
   A							:       int     =    False
   A							:       int     =    False
   A							:       Optional[Any]     =    False
   def 		_lowerCamelCase (self				)    ->     int:
        lowercase_					:       List[str]     				=					SegformerModelTester(self				)
        lowercase_					:       str     				=					SegformerConfigTester(self       ,				config_class=_a				)
   def 		_lowerCamelCase (self				)    ->     str:
        self.config_tester.run_common_tests()
   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_					:       Dict     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_a				)
   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_					:       Any     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_binary_image_segmentation(*_a				)
   def 		_lowerCamelCase (self				)    ->     Union[str, Any]:
        lowercase_					:       int     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_segmentation(*_a				)
   @unittest.skip('SegFormer does not use inputs_embeds'				)
   def 		_lowerCamelCase (self				)    ->     Any:
        pass
   @unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'				)
   def 		_lowerCamelCase (self				)    ->     Optional[int]:
        pass
   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_				,lowercase_					:       Optional[int]     				=					self.model_tester.prepare_config_and_inputs_for_common()

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

             lowercase_					:       Dict     				=					['pixel_values']
             self.assertListEqual(arg_names[:1]       ,				_a				)
   def 		_lowerCamelCase (self				)    ->     Tuple:
        lowercase_				,lowercase_					:       Dict     				=					self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_					:       Optional[Any]     				=					True

        for model_class in self.all_model_classes:
             lowercase_					:       Any     				=					True
             lowercase_					:       int     				=					False
             lowercase_					:       int     				=					True
             lowercase_					:       Tuple     				=					model_class(_a				)
             model.to(_a				)
             model.eval()
             with torch.no_grad():
                  lowercase_					:       int     				=					model(**self._prepare_for_class(_a       ,				_a				)				)
             lowercase_					:       Union[str, Any]     				=					outputs.attentions

             lowercase_					:       Tuple     				=					sum(self.model_tester.depths				)
             self.assertEqual(len(_a				)       ,				_a				)

             # check that output_attentions also work using config
             del inputs_dict["output_attentions"]
             lowercase_					:       List[str]     				=					True
             lowercase_					:       Dict     				=					model_class(_a				)
             model.to(_a				)
             model.eval()
             with torch.no_grad():
                  lowercase_					:       Optional[Any]     				=					model(**self._prepare_for_class(_a       ,				_a				)				)
             lowercase_					:       List[Any]     				=					outputs.attentions

             self.assertEqual(len(_a				)       ,				_a				)

             # verify the first attentions (first block, first layer)
             lowercase_					:       Any     				=					(self.model_tester.image_size // 4) ** 2
             lowercase_					:       Dict     				=					(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
             self.assertListEqual(
                 list(attentions[0].shape[-3:]				)       ,				[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]       ,				)

             # verify the last attentions (last block, last layer)
             lowercase_					:       Optional[int]     				=					(self.model_tester.image_size // 32) ** 2
             lowercase_					:       Optional[int]     				=					(self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
             self.assertListEqual(
                 list(attentions[-1].shape[-3:]				)       ,				[self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]       ,				)
             lowercase_					:       Optional[Any]     				=					len(_a				)

             # Check attention is always last and order is fine
             lowercase_					:       List[Any]     				=					True
             lowercase_					:       Union[str, Any]     				=					True
             lowercase_					:       Optional[int]     				=					model_class(_a				)
             model.to(_a				)
             model.eval()
             with torch.no_grad():
                  lowercase_					:       Any     				=					model(**self._prepare_for_class(_a       ,				_a				)				)

             self.assertEqual(out_len + 1       ,				len(_a				)				)

             lowercase_					:       List[Any]     				=					outputs.attentions

             self.assertEqual(len(_a				)       ,				_a				)
             # verify the first attentions (first block, first layer)
             lowercase_					:       Any     				=					(self.model_tester.image_size // 4) ** 2
             lowercase_					:       List[str]     				=					(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]				)       ,				[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]       ,				)
   def 		_lowerCamelCase (self				)    ->     List[str]:
        def check_hidden_states_output(_a       ,				_a       ,				_a				):
             lowercase_					:       Dict     				=					model_class(_a				)
             model.to(_a				)
             model.eval()

             with torch.no_grad():
                  lowercase_					:       List[Any]     				=					model(**self._prepare_for_class(_a       ,				_a				)				)

             lowercase_					:       Any     				=					outputs.hidden_states

             lowercase_					:       str     				=					self.model_tester.num_encoder_blocks
             self.assertEqual(len(_a				)       ,				_a				)

             # verify the first hidden states (first block)
             self.assertListEqual(
                 list(hidden_states[0].shape[-3:]				)       ,				[
                     self.model_tester.hidden_sizes[0],
                     self.model_tester.image_size // 4,
                     self.model_tester.image_size // 4,
                 ]       ,				)

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

        for model_class in self.all_model_classes:
             lowercase_					:       str     				=					True
             check_hidden_states_output(_a       ,				_a       ,				_a				)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             lowercase_					:       Optional[Any]     				=					True

             check_hidden_states_output(_a       ,				_a       ,				_a				)
   def 		_lowerCamelCase (self				)    ->     Dict:
        if not self.model_tester.is_training:
             return

        lowercase_				,lowercase_					:       Optional[Any]     				=					self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_					:       List[Any]     				=					True

        for model_class in self.all_model_classes:
             if model_class in get_values(_a				):
                  continue

             lowercase_					:       Optional[int]     				=					model_class(_a				)
             model.to(_a				)
             model.train()
             lowercase_					:       List[Any]     				=					self._prepare_for_class(_a       ,				_a       ,				return_labels=_a				)
             lowercase_					:       str     				=					model(**_a				).loss
             loss.backward()
   @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'				)
   def 		_lowerCamelCase (self				)    ->     str:
        pass





   @slow
   def 		_lowerCamelCase (self				)    ->     Any:
        for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowercase_					:       List[Any]     				=					SegformerModel.from_pretrained(_a				)
             self.assertIsNotNone(_a				)



def _UpperCamelCase   (       ):
     lowercase_					:       int     				=					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
     return image






@require_torch
class       UpperCAmelCase__  (       unittest.TestCase			):






   """simple docstring"""
   @slow
   def 		_lowerCamelCase (self				)    ->     Union[str, Any]:
        # only resize + normalize
        lowercase_					:       Union[str, Any]     				=					SegformerImageProcessor(
            image_scale=(512, 512)       ,				keep_ratio=_a       ,				align=_a       ,				do_random_crop=_a				)
        lowercase_					:       List[str]     				=					SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'				).to(
            _a				)

        lowercase_					:       int     				=					prepare_img()
        lowercase_					:       int     				=					image_processor(images=_a       ,				return_tensors='pt'				)
        lowercase_					:       int     				=					encoded_inputs.pixel_values.to(_a				)

        with torch.no_grad():
             lowercase_					:       List[Any]     				=					model(_a				)

        lowercase_					:       Union[str, Any]     				=					torch.Size((1, model.config.num_labels, 128, 128)				)
        self.assertEqual(outputs.logits.shape       ,				_a				)

        lowercase_					:       int     				=					torch.tensor(
            [
                [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]],
                [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]],
                [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]],
            ]				).to(_a				)
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]       ,				_a       ,				atol=1e-4				)				)
   @slow
   def 		_lowerCamelCase (self				)    ->     Dict:
        # only resize + normalize
        lowercase_					:       Optional[Any]     				=					SegformerImageProcessor(
            image_scale=(512, 512)       ,				keep_ratio=_a       ,				align=_a       ,				do_random_crop=_a				)
        lowercase_					:       Union[str, Any]     				=					SegformerForSemanticSegmentation.from_pretrained(
            'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'				).to(_a				)

        lowercase_					:       Optional[Any]     				=					prepare_img()
        lowercase_					:       Tuple     				=					image_processor(images=_a       ,				return_tensors='pt'				)
        lowercase_					:       Any     				=					encoded_inputs.pixel_values.to(_a				)

        with torch.no_grad():
             lowercase_					:       Union[str, Any]     				=					model(_a				)

        lowercase_					:       str     				=					torch.Size((1, model.config.num_labels, 128, 128)				)
        self.assertEqual(outputs.logits.shape       ,				_a				)

        lowercase_					:       List[Any]     				=					torch.tensor(
            [
                [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]],
                [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]],
                [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]],
            ]				).to(_a				)
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]       ,				_a       ,				atol=1e-1				)				)





   @slow
   def 		_lowerCamelCase (self				)    ->     Optional[Any]:
        # only resize + normalize
        lowercase_					:       List[Any]     				=					SegformerImageProcessor(
            image_scale=(512, 512)       ,				keep_ratio=_a       ,				align=_a       ,				do_random_crop=_a				)
        lowercase_					:       List[Any]     				=					SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'				).to(
            _a				)

        lowercase_					:       List[str]     				=					prepare_img()
        lowercase_					:       List[str]     				=					image_processor(images=_a       ,				return_tensors='pt'				)
        lowercase_					:       Optional[Any]     				=					encoded_inputs.pixel_values.to(_a				)

        with torch.no_grad():
             lowercase_					:       Dict     				=					model(_a				)

        lowercase_					:       Optional[int]     				=					outputs.logits.detach().cpu()

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

        lowercase_					:       List[str]     				=					image_processor.post_process_semantic_segmentation(outputs=_a				)
        lowercase_					:       Optional[int]     				=					torch.Size((128, 128)				)
        self.assertEqual(segmentation[0].shape       ,				_a				)




