



"""simple docstring"""





import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
  import tensorflow as tf

if is_torch_available():
  import torch


lowerCamelCase      =		logging.get_logger(__name__)
class    lowercase__     :







       '''simple docstring'''


       def __init__(							self    :						Union[str, Any]	,       _UpperCAmelCase    :						str = None	,       _UpperCAmelCase    :						uuid.UUID = None	,       _UpperCAmelCase    :						Optional[int]=None	,       _UpperCAmelCase    :						Tuple=None					)				->		Tuple:


             '''simple docstring'''




             if not conversation_id:
                   UpperCAmelCase_    				=							uuid.uuida()
             if past_user_inputs is None:
                   UpperCAmelCase_    				=							[]
             if generated_responses is None:
                   UpperCAmelCase_    				=							[]

             UpperCAmelCase_    				=							conversation_id
             UpperCAmelCase_    				=							past_user_inputs
             UpperCAmelCase_    				=							generated_responses
             UpperCAmelCase_    				=							text



       def __eq__(							self    :						Any	,       _UpperCAmelCase    :						int					)				->		Union[str, Any]:


             '''simple docstring'''




             if not isinstance(_UpperCAmelCase	,       _UpperCAmelCase					):
                   return False
             if self.uuid == other.uuid:
                   return True
             return (
                 self.new_user_input == other.new_user_input
                 and self.past_user_inputs == other.past_user_inputs
                 and self.generated_responses == other.generated_responses
             )



       def   lowercase__       (							self    :						int	,       _UpperCAmelCase    :						str	,       _UpperCAmelCase    :						bool = False					)				->		int:


             '''simple docstring'''




             if self.new_user_input:
                   if overwrite:
                         logger.warning(
                             F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten """
                             F"""with: \"{text}\"."""					)
                         UpperCAmelCase_    				=							text
                   else:
                         logger.warning(
                             F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" new input """
                             F"""ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input"""					)
             else:
                   UpperCAmelCase_    				=							text



       def   lowercase__       (							self    :						Dict					)				->		int:


             '''simple docstring'''




             if self.new_user_input:
                   self.past_user_inputs.append(self.new_user_input					)
             UpperCAmelCase_    				=							None



       def   lowercase__       (							self    :						str	,       _UpperCAmelCase    :						str					)				->		Dict:


             '''simple docstring'''




             self.generated_responses.append(_UpperCAmelCase					)



       def   lowercase__       (							self    :						List[str]					)				->		Union[str, Any]:


             '''simple docstring'''




             for user_input, generated_response in zip(self.past_user_inputs	,       self.generated_responses					):
                   yield True, user_input
                   yield False, generated_response
             if self.new_user_input:
                   yield True, self.new_user_input







       def __repr__(							self    :						int					)				->		Union[str, Any]:


             '''simple docstring'''




             UpperCAmelCase_    				=							F"""Conversation id: {self.uuid} \n"""
             for is_user, text in self.iter_texts():
                   UpperCAmelCase_    				=							"user" if is_user else "bot"
                   output += F"""{name} >> {text} \n"""
             return output



@add_end_docstrings(
    SCREAMING_SNAKE_CASE       ,      R'''
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    '''       ,      )
class    lowercase__     (					SCREAMING_SNAKE_CASE   ):







       '''simple docstring'''


       def __init__(							self    :						Optional[Any]	,       *_UpperCAmelCase    :						int	,       **_UpperCAmelCase    :						int					)				->		Optional[int]:


             '''simple docstring'''




             super().__init__(*_UpperCAmelCase	,       **_UpperCAmelCase					)
             if self.tokenizer.pad_token_id is None:
                   UpperCAmelCase_    				=							self.tokenizer.eos_token



       def   lowercase__       (							self    :						str	,       _UpperCAmelCase    :						Dict=None	,       _UpperCAmelCase    :						Optional[int]=None	,       _UpperCAmelCase    :						Any=None	,       **_UpperCAmelCase    :						Dict					)				->		int:


             '''simple docstring'''




             UpperCAmelCase_    				=							{}
             UpperCAmelCase_    				=							{}
             UpperCAmelCase_    				=							{}

             if min_length_for_response is not None:
                   UpperCAmelCase_    				=							min_length_for_response
             if minimum_tokens is not None:
                   UpperCAmelCase_    				=							minimum_tokens

             if "max_length" in generate_kwargs:
                   UpperCAmelCase_    				=							generate_kwargs["max_length"]
                   # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
             if clean_up_tokenization_spaces is not None:
                   UpperCAmelCase_    				=							clean_up_tokenization_spaces

             if generate_kwargs:
                   forward_params.update(_UpperCAmelCase					)
             return preprocess_params, forward_params, postprocess_params



       def __call__(							self    :						Union[str, Any]	,       _UpperCAmelCase    :						Union[Conversation, List[Conversation]]	,       _UpperCAmelCase    :						Tuple=0	,       **_UpperCAmelCase    :						Union[str, Any]					)				->		List[str]:


             '''simple docstring'''




             UpperCAmelCase_    				=							super().__call__(_UpperCAmelCase	,       num_workers=_UpperCAmelCase	,       **_UpperCAmelCase					)
             if isinstance(_UpperCAmelCase	,       _UpperCAmelCase					) and len(_UpperCAmelCase					) == 1:
                   return outputs[0]
             return outputs



       def   lowercase__       (							self    :						Tuple	,       _UpperCAmelCase    :						Conversation	,       _UpperCAmelCase    :						str=32					)				->		Dict[str, Any]:


             '''simple docstring'''




             if not isinstance(_UpperCAmelCase	,       _UpperCAmelCase					):
                   raise ValueError("ConversationalPipeline, expects Conversation as inputs"					)
             if conversation.new_user_input is None:
                   raise ValueError(
                       F"""Conversation with UUID {type(conversation.uuid					)} does not contain new user input to process. """
                       "Add user inputs with the conversation's `add_user_input` method"					)
             if hasattr(self.tokenizer	,       "_build_conversation_input_ids"					):
                   UpperCAmelCase_    				=							self.tokenizer._build_conversation_input_ids(_UpperCAmelCase					)
             else:
                   # If the tokenizer cannot handle conversations, we default to only the old version
                   UpperCAmelCase_    				=							self._legacy_parse_and_tokenize(_UpperCAmelCase					)

             if self.framework == "pt":
                   UpperCAmelCase_    				=							torch.LongTensor([input_ids]					)
             elif self.framework == "tf":
                   UpperCAmelCase_    				=							tf.constant([input_ids]					)
             return {"input_ids": input_ids, "conversation": conversation}



       def   lowercase__       (							self    :						Union[str, Any]	,       _UpperCAmelCase    :						Optional[Any]	,       _UpperCAmelCase    :						int=10	,       **_UpperCAmelCase    :						Union[str, Any]					)				->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_    				=							generate_kwargs.get("max_length"	,       self.model.config.max_length					)

             UpperCAmelCase_    				=							model_inputs["input_ids"].shape[1]
             if max_length - minimum_tokens < n:
                   logger.warning(F"""Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})"""					)
                   UpperCAmelCase_    				=							max_length - minimum_tokens
                   UpperCAmelCase_    				=							model_inputs["input_ids"][:, -trim:]
                   if "attention_mask" in model_inputs:
                         UpperCAmelCase_    				=							model_inputs["attention_mask"][:, -trim:]
             UpperCAmelCase_    				=							model_inputs.pop("conversation"					)
             UpperCAmelCase_    				=							max_length
             UpperCAmelCase_    				=							self.model.generate(**_UpperCAmelCase	,       **_UpperCAmelCase					)
             if self.model.config.is_encoder_decoder:
                   UpperCAmelCase_    				=							1
             else:
                   UpperCAmelCase_    				=							n
             return {"output_ids": output_ids[:, start_position:], "conversation": conversation}



       def   lowercase__       (							self    :						int	,       _UpperCAmelCase    :						Optional[Any]	,       _UpperCAmelCase    :						int=True					)				->		List[str]:


             '''simple docstring'''




             UpperCAmelCase_    				=							model_outputs["output_ids"]
             UpperCAmelCase_    				=							self.tokenizer.decode(
                 output_ids[0]	,       skip_special_tokens=_UpperCAmelCase	,       clean_up_tokenization_spaces=_UpperCAmelCase	,       )
             UpperCAmelCase_    				=							model_outputs["conversation"]
             conversation.mark_processed()
             conversation.append_response(_UpperCAmelCase					)
             return conversation







       def   lowercase__       (							self    :						Tuple	,       _UpperCAmelCase    :						Conversation					)				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.tokenizer.eos_token_id
             UpperCAmelCase_    				=							[]
             for is_user, text in conversation.iter_texts():
                   if eos_token_id is not None:
                         input_ids.extend(self.tokenizer.encode(_UpperCAmelCase	,       add_special_tokens=_UpperCAmelCase					) + [eos_token_id]					)
                   else:
                         input_ids.extend(self.tokenizer.encode(_UpperCAmelCase	,       add_special_tokens=_UpperCAmelCase					)					)

             if len(_UpperCAmelCase					) > self.tokenizer.model_max_length:
                   UpperCAmelCase_    				=							input_ids[-self.tokenizer.model_max_length :]
             return input_ids









"""simple docstring"""





import inspect
import unittest

from transformers import MobileViTVaConfig
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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
  from transformers.models.mobilevitva.modeling_mobilevitva import (
      MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
      make_divisible,
  )


if is_vision_available():
  from PIL import Image

  from transformers import MobileViTImageProcessor
class    lowercase__     (					SCREAMING_SNAKE_CASE   ):







       '''simple docstring'''


       def   lowercase__       (							self    :						Union[str, Any]					)				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.config_class(**self.inputs_dict					)
             self.parent.assertTrue(hasattr(_UpperCAmelCase	,       "width_multiplier"					)					)



class    lowercase__     :







       '''simple docstring'''


       def __init__(							self    :						Optional[Any]	,       _UpperCAmelCase    :						int	,       _UpperCAmelCase    :						Optional[int]=13	,       _UpperCAmelCase    :						Any=64	,       _UpperCAmelCase    :						Union[str, Any]=2	,       _UpperCAmelCase    :						Any=3	,       _UpperCAmelCase    :						Dict="swish"	,       _UpperCAmelCase    :						List[Any]=3	,       _UpperCAmelCase    :						int=32	,       _UpperCAmelCase    :						str=0.1	,       _UpperCAmelCase    :						Tuple=0.02	,       _UpperCAmelCase    :						List[Any]=True	,       _UpperCAmelCase    :						Any=True	,       _UpperCAmelCase    :						int=10	,       _UpperCAmelCase    :						Optional[int]=None	,       _UpperCAmelCase    :						Any=0.25	,       _UpperCAmelCase    :						Any=0.0	,       _UpperCAmelCase    :						Optional[int]=0.0	,       )				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							parent
             UpperCAmelCase_    				=							batch_size
             UpperCAmelCase_    				=							image_size
             UpperCAmelCase_    				=							patch_size
             UpperCAmelCase_    				=							num_channels
             UpperCAmelCase_    				=							make_divisible(512 * width_multiplier	,       divisor=8					)
             UpperCAmelCase_    				=							hidden_act
             UpperCAmelCase_    				=							conv_kernel_size
             UpperCAmelCase_    				=							output_stride
             UpperCAmelCase_    				=							classifier_dropout_prob
             UpperCAmelCase_    				=							use_labels
             UpperCAmelCase_    				=							is_training
             UpperCAmelCase_    				=							num_labels
             UpperCAmelCase_    				=							initializer_range
             UpperCAmelCase_    				=							scope
             UpperCAmelCase_    				=							width_multiplier
             UpperCAmelCase_    				=							ffn_dropout
             UpperCAmelCase_    				=							attn_dropout



       def   lowercase__       (							self    :						Optional[int]					)				->		List[str]:


             '''simple docstring'''




             UpperCAmelCase_    				=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

             UpperCAmelCase_    				=							self.get_config()

             return config, pixel_values, labels, pixel_labels



       def   lowercase__       (							self    :						Tuple					)				->		Tuple:


             '''simple docstring'''




             return MobileViTVaConfig(
                 image_size=self.image_size	,       patch_size=self.patch_size	,       num_channels=self.num_channels	,       hidden_act=self.hidden_act	,       conv_kernel_size=self.conv_kernel_size	,       output_stride=self.output_stride	,       classifier_dropout_prob=self.classifier_dropout_prob	,       initializer_range=self.initializer_range	,       width_multiplier=self.width_multiplier	,       ffn_dropout=self.ffn_dropout_prob	,       attn_dropout=self.attn_dropout_prob	,       )



       def   lowercase__       (							self    :						List[str]	,       _UpperCAmelCase    :						str	,       _UpperCAmelCase    :						Optional[Any]	,       _UpperCAmelCase    :						Optional[Any]	,       _UpperCAmelCase    :						int					)				->		int:


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaModel(config=_UpperCAmelCase					)
             model.to(_UpperCAmelCase					)
             model.eval()
             UpperCAmelCase_    				=							model(_UpperCAmelCase					)
             self.parent.assertEqual(
                 result.last_hidden_state.shape	,       (
                     self.batch_size,
                     self.last_hidden_size,
                     self.image_size // self.output_stride,
                     self.image_size // self.output_stride,
                 )	,       )



       def   lowercase__       (							self    :						Optional[int]	,       _UpperCAmelCase    :						int	,       _UpperCAmelCase    :						Any	,       _UpperCAmelCase    :						str	,       _UpperCAmelCase    :						Tuple					)				->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.num_labels
             UpperCAmelCase_    				=							MobileViTVaForImageClassification(_UpperCAmelCase					)
             model.to(_UpperCAmelCase					)
             model.eval()
             UpperCAmelCase_    				=							model(_UpperCAmelCase	,       labels=_UpperCAmelCase					)
             self.parent.assertEqual(result.logits.shape	,       (self.batch_size, self.num_labels)					)



       def   lowercase__       (							self    :						Any	,       _UpperCAmelCase    :						int	,       _UpperCAmelCase    :						Optional[int]	,       _UpperCAmelCase    :						List[Any]	,       _UpperCAmelCase    :						Tuple					)				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.num_labels
             UpperCAmelCase_    				=							MobileViTVaForSemanticSegmentation(_UpperCAmelCase					)
             model.to(_UpperCAmelCase					)
             model.eval()
             UpperCAmelCase_    				=							model(_UpperCAmelCase					)
             self.parent.assertEqual(
                 result.logits.shape	,       (
                     self.batch_size,
                     self.num_labels,
                     self.image_size // self.output_stride,
                     self.image_size // self.output_stride,
                 )	,       )
             UpperCAmelCase_    				=							model(_UpperCAmelCase	,       labels=_UpperCAmelCase					)
             self.parent.assertEqual(
                 result.logits.shape	,       (
                     self.batch_size,
                     self.num_labels,
                     self.image_size // self.output_stride,
                     self.image_size // self.output_stride,
                 )	,       )







       def   lowercase__       (							self    :						List[str]					)				->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.prepare_config_and_inputs()
             UpperCAmelCase_				,					UpperCAmelCase_				,					UpperCAmelCase_				,					UpperCAmelCase_    				=							config_and_inputs
             UpperCAmelCase_    				=							{"pixel_values": pixel_values}
             return config, inputs_dict



@require_torch
class    lowercase__     (					SCREAMING_SNAKE_CASE       ,      SCREAMING_SNAKE_CASE       ,      unittest.TestCase   ):







       '''simple docstring'''


       UpperCamelCase		=  (
           (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
           if is_torch_available()
           else ()
       )

       UpperCamelCase		=  (
           {
               '''feature-extraction''': MobileViTVaModel,
               '''image-classification''': MobileViTVaForImageClassification,
               '''image-segmentation''': MobileViTVaForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       UpperCamelCase		=  False
       UpperCamelCase		=  False
       UpperCamelCase		=  False
       UpperCamelCase		=  False



       def   lowercase__       (							self    :						str					)				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaModelTester(self					)
             UpperCAmelCase_    				=							MobileViTVaConfigTester(self	,       config_class=_UpperCAmelCase	,       has_text_modality=_UpperCAmelCase					)



       def   lowercase__       (							self    :						int					)				->		List[str]:


             '''simple docstring'''




             self.config_tester.run_common_tests()



       @unittest.skip(reason="MobileViTV2 does not use inputs_embeds"					)
       def   lowercase__       (							self    :						List[Any]					)				->		List[str]:


             '''simple docstring'''




             pass



       @unittest.skip(reason="MobileViTV2 does not support input and output embeddings"					)
       def   lowercase__       (							self    :						Tuple					)				->		Dict:


             '''simple docstring'''




             pass



       @unittest.skip(reason="MobileViTV2 does not output attentions"					)
       def   lowercase__       (							self    :						Optional[int]					)				->		List[Any]:


             '''simple docstring'''




             pass



       @require_torch_multi_gpu
       @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."					)
       def   lowercase__       (							self    :						int					)				->		int:


             '''simple docstring'''




             pass



       @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."					)
       def   lowercase__       (							self    :						Tuple					)				->		Optional[int]:


             '''simple docstring'''




             pass



       def   lowercase__       (							self    :						int					)				->		int:


             '''simple docstring'''




             UpperCAmelCase_				,					UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs_for_common()

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

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



       def   lowercase__       (							self    :						Union[str, Any]					)				->		int:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*_UpperCAmelCase					)



       def   lowercase__       (							self    :						List[Any]					)				->		Optional[int]:


             '''simple docstring'''




             def check_hidden_states_output(_UpperCAmelCase    :						List[Any]	,       _UpperCAmelCase    :						Union[str, Any]	,       _UpperCAmelCase    :						int					):
                   UpperCAmelCase_    				=							model_class(_UpperCAmelCase					)
                   model.to(_UpperCAmelCase					)
                   model.eval()

                   with torch.no_grad():
                         UpperCAmelCase_    				=							model(**self._prepare_for_class(_UpperCAmelCase	,       _UpperCAmelCase					)					)

                   UpperCAmelCase_    				=							outputs.hidden_states

                   UpperCAmelCase_    				=							5
                   self.assertEqual(len(_UpperCAmelCase					)	,       _UpperCAmelCase					)

                   # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
                   # with the width and height being successively divided by 2.
                   UpperCAmelCase_    				=							2
                   for i in range(len(_UpperCAmelCase					)					):
                         self.assertListEqual(
                             list(hidden_states[i].shape[-2:]					)	,       [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]	,       )
                         divisor *= 2

                   self.assertEqual(self.model_tester.output_stride	,       divisor // 2					)

             UpperCAmelCase_				,					UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_    				=							True
                   check_hidden_states_output(_UpperCAmelCase	,       _UpperCAmelCase	,       _UpperCAmelCase					)

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   UpperCAmelCase_    				=							True

                   check_hidden_states_output(_UpperCAmelCase	,       _UpperCAmelCase	,       _UpperCAmelCase					)



       def   lowercase__       (							self    :						int					)				->		int:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase					)



       def   lowercase__       (							self    :						int					)				->		Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCAmelCase					)







       @slow
       def   lowercase__       (							self    :						Optional[int]					)				->		Union[str, Any]:


             '''simple docstring'''




             for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   UpperCAmelCase_    				=							MobileViTVaModel.from_pretrained(_UpperCAmelCase					)
                   self.assertIsNotNone(_UpperCAmelCase					)



def      a__			(   ):
      UpperCAmelCase_    				=							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
      return image


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







       '''simple docstring'''


       @cached_property
       def   lowercase__       (							self    :						int					)				->		List[Any]:


             '''simple docstring'''




             return (
                 MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"					)
                 if is_vision_available()
                 else None
             )



       @slow
       def   lowercase__       (							self    :						Union[str, Any]					)				->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"					).to(
                 _UpperCAmelCase					)

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

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

             # verify the logits
             UpperCAmelCase_    				=							torch.Size((1, 1000)					)
             self.assertEqual(outputs.logits.shape	,       _UpperCAmelCase					)

             UpperCAmelCase_    				=							torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]					).to(_UpperCAmelCase					)

             self.assertTrue(torch.allclose(outputs.logits[0, :3]	,       _UpperCAmelCase	,       atol=1e-4					)					)



       @slow
       def   lowercase__       (							self    :						List[str]					)				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)
             UpperCAmelCase_    				=							model.to(_UpperCAmelCase					)

             UpperCAmelCase_    				=							MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)

             UpperCAmelCase_    				=							prepare_img()
             UpperCAmelCase_    				=							image_processor(images=_UpperCAmelCase	,       return_tensors="pt"					).to(_UpperCAmelCase					)

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

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

             UpperCAmelCase_    				=							torch.tensor(
                 [
                     [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
                     [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
                     [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
                 ]	,       device=_UpperCAmelCase	,       )

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







       @slow
       def   lowercase__       (							self    :						Optional[int]					)				->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)
             UpperCAmelCase_    				=							model.to(_UpperCAmelCase					)

             UpperCAmelCase_    				=							MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)

             UpperCAmelCase_    				=							prepare_img()
             UpperCAmelCase_    				=							image_processor(images=_UpperCAmelCase	,       return_tensors="pt"					).to(_UpperCAmelCase					)

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

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

             UpperCAmelCase_    				=							image_processor.post_process_semantic_segmentation(outputs=_UpperCAmelCase	,       target_sizes=[(50, 60)]					)
             UpperCAmelCase_    				=							torch.Size((50, 60)					)
             self.assertEqual(segmentation[0].shape	,       _UpperCAmelCase					)

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




