




'''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        _a    (						__lowerCAmelCase							):






     def     _lowercase     (			self   )							->      Union[str, Any]:
          _snake_case							=				self.config_class(**self.inputs_dict   )
          self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE ,"width_multiplier"   )   )







class        _a    :






     def __init__(			self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=13 ,_SCREAMING_SNAKE_CASE=64 ,_SCREAMING_SNAKE_CASE=2 ,_SCREAMING_SNAKE_CASE=3 ,_SCREAMING_SNAKE_CASE="swish" ,_SCREAMING_SNAKE_CASE=3 ,_SCREAMING_SNAKE_CASE=32 ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.0_2 ,_SCREAMING_SNAKE_CASE=True ,_SCREAMING_SNAKE_CASE=True ,_SCREAMING_SNAKE_CASE=10 ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=0.2_5 ,_SCREAMING_SNAKE_CASE=0.0 ,_SCREAMING_SNAKE_CASE=0.0 ,)							->      Union[str, Any]:
          _snake_case							=				parent
          _snake_case							=				batch_size
          _snake_case							=				image_size
          _snake_case							=				patch_size
          _snake_case							=				num_channels
          _snake_case							=				make_divisible(512 * width_multiplier ,divisor=8   )
          _snake_case							=				hidden_act
          _snake_case							=				conv_kernel_size
          _snake_case							=				output_stride
          _snake_case							=				classifier_dropout_prob
          _snake_case							=				use_labels
          _snake_case							=				is_training
          _snake_case							=				num_labels
          _snake_case							=				initializer_range
          _snake_case							=				scope
          _snake_case							=				width_multiplier
          _snake_case							=				ffn_dropout
          _snake_case							=				attn_dropout






     def     _lowercase     (			self   )							->      Any:
          _snake_case							=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

          _snake_case							=				self.get_config()

          return config, pixel_values, labels, pixel_labels






     def     _lowercase     (			self   )							->      Tuple:
          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 ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )							->      Optional[int]:
          _snake_case							=				MobileViTVaModel(config=_SCREAMING_SNAKE_CASE   )
          model.to(_SCREAMING_SNAKE_CASE   )
          model.eval()
          _snake_case							=				model(_SCREAMING_SNAKE_CASE   )
          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 ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )							->      str:
          _snake_case							=				self.num_labels
          _snake_case							=				MobileViTVaForImageClassification(_SCREAMING_SNAKE_CASE   )
          model.to(_SCREAMING_SNAKE_CASE   )
          model.eval()
          _snake_case							=				model(_SCREAMING_SNAKE_CASE ,labels=_SCREAMING_SNAKE_CASE   )
          self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels)   )






     def     _lowercase     (			self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )							->      Any:
          _snake_case							=				self.num_labels
          _snake_case							=				MobileViTVaForSemanticSegmentation(_SCREAMING_SNAKE_CASE   )
          model.to(_SCREAMING_SNAKE_CASE   )
          model.eval()
          _snake_case							=				model(_SCREAMING_SNAKE_CASE   )
          self.parent.assertEqual(
              result.logits.shape ,(
                  self.batch_size,
                  self.num_labels,
                  self.image_size // self.output_stride,
                  self.image_size // self.output_stride,
              ) ,)
          _snake_case							=				model(_SCREAMING_SNAKE_CASE ,labels=_SCREAMING_SNAKE_CASE   )
          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[Any]:
          _snake_case							=				self.prepare_config_and_inputs()
          _snake_case							, _snake_case							, _snake_case							, _snake_case							=				config_and_inputs
          _snake_case							=				{"pixel_values": pixel_values}
          return config, inputs_dict







@require_torch
class        _a    (						__lowerCAmelCase , __lowerCAmelCase , unittest.TestCase							):
     SCREAMING_SNAKE_CASE_							:   Optional[int]       =						(
         (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )

     SCREAMING_SNAKE_CASE_							:   Any       =						(
         {
             """feature-extraction""": MobileViTVaModel,
             """image-classification""": MobileViTVaForImageClassification,
             """image-segmentation""": MobileViTVaForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE_							:   str       =						False
     SCREAMING_SNAKE_CASE_							:   List[str]       =						False
     SCREAMING_SNAKE_CASE_							:   str       =						False
     SCREAMING_SNAKE_CASE_							:   Optional[Any]       =						False






     def     _lowercase     (			self   )							->      List[Any]:
          _snake_case							=				MobileViTVaModelTester(self   )
          _snake_case							=				MobileViTVaConfigTester(self ,config_class=_SCREAMING_SNAKE_CASE ,has_text_modality=_SCREAMING_SNAKE_CASE   )






     def     _lowercase     (			self   )							->      Any:
          self.config_tester.run_common_tests()






     @unittest.skip(reason="MobileViTV2 does not use inputs_embeds"   )
     def     _lowercase     (			self   )							->      Union[str, Any]:
          pass






     @unittest.skip(reason="MobileViTV2 does not support input and output embeddings"   )
     def     _lowercase     (			self   )							->      Optional[int]:
          pass






     @unittest.skip(reason="MobileViTV2 does not output attentions"   )
     def     _lowercase     (			self   )							->      Tuple:
          pass






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






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






     def     _lowercase     (			self   )							->      Dict:
          _snake_case							, _snake_case							=				self.model_tester.prepare_config_and_inputs_for_common()

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

               _snake_case							=				["pixel_values"]
               self.assertListEqual(arg_names[:1] ,_SCREAMING_SNAKE_CASE   )






     def     _lowercase     (			self   )							->      str:
          _snake_case							=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE   )






     def     _lowercase     (			self   )							->      int:
          def check_hidden_states_output(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   ):
               _snake_case							=				model_class(_SCREAMING_SNAKE_CASE   )
               model.to(_SCREAMING_SNAKE_CASE   )
               model.eval()

               with torch.no_grad():
                    _snake_case							=				model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )   )

               _snake_case							=				outputs.hidden_states

               _snake_case							=				5
               self.assertEqual(len(_SCREAMING_SNAKE_CASE   ) ,_SCREAMING_SNAKE_CASE   )

               # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
               # with the width and height being successively divided by 2.
               _snake_case							=				2
               for i in range(len(_SCREAMING_SNAKE_CASE   )   ):
                    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   )

          _snake_case							, _snake_case							=				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               _snake_case							=				True
               check_hidden_states_output(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )

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

               check_hidden_states_output(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )






     def     _lowercase     (			self   )							->      Dict:
          _snake_case							=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE   )






     def     _lowercase     (			self   )							->      List[str]:
          _snake_case							=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE   )






     @slow
     def     _lowercase     (			self   )							->      Tuple:
          for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _snake_case							=				MobileViTVaModel.from_pretrained(_SCREAMING_SNAKE_CASE   )
               self.assertIsNotNone(_SCREAMING_SNAKE_CASE   )







def      __a     (       )						->			Optional[int]:

     """simple docstring"""




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





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






     @cached_property
     def     _lowercase     (			self   )							->      Optional[int]:
          return (
              MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"   )
              if is_vision_available()
              else None
          )






     @slow
     def     _lowercase     (			self   )							->      List[str]:
          _snake_case							=				MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"   ).to(
              _SCREAMING_SNAKE_CASE   )

          _snake_case							=				self.default_image_processor
          _snake_case							=				prepare_img()
          _snake_case							=				image_processor(images=_SCREAMING_SNAKE_CASE ,return_tensors="pt"   ).to(_SCREAMING_SNAKE_CASE   )

          # forward pass
          with torch.no_grad():
               _snake_case							=				model(**_SCREAMING_SNAKE_CASE   )

          # verify the logits
          _snake_case							=				torch.Size((1, 1_000)   )
          self.assertEqual(outputs.logits.shape ,_SCREAMING_SNAKE_CASE   )

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

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






     @slow
     def     _lowercase     (			self   )							->      int:
          _snake_case							=				MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"   )
          _snake_case							=				model.to(_SCREAMING_SNAKE_CASE   )

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

          _snake_case							=				prepare_img()
          _snake_case							=				image_processor(images=_SCREAMING_SNAKE_CASE ,return_tensors="pt"   ).to(_SCREAMING_SNAKE_CASE   )

          # forward pass
          with torch.no_grad():
               _snake_case							=				model(**_SCREAMING_SNAKE_CASE   )
          _snake_case							=				outputs.logits

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

          _snake_case							=				torch.tensor(
              [
                  [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]],
                  [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]],
                  [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]],
              ] ,device=_SCREAMING_SNAKE_CASE ,)

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






     @slow
     def     _lowercase     (			self   )							->      Tuple:
          _snake_case							=				MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"   )
          _snake_case							=				model.to(_SCREAMING_SNAKE_CASE   )

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

          _snake_case							=				prepare_img()
          _snake_case							=				image_processor(images=_SCREAMING_SNAKE_CASE ,return_tensors="pt"   ).to(_SCREAMING_SNAKE_CASE   )

          # forward pass
          with torch.no_grad():
               _snake_case							=				model(**_SCREAMING_SNAKE_CASE   )

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

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

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








'''simple docstring'''





def      __a     (       _UpperCamelCase:   int   )						->			None:

     """simple docstring"""




     _snake_case							=				generate_pascal_triangle(_UpperCamelCase   )
     for row_idx in range(_UpperCamelCase   ):
          # Print left spaces
          for _ in range(num_rows - row_idx - 1   ):
               print(end=" "   )
          # Print row values
          for col_idx in range(row_idx + 1   ):
               if col_idx != row_idx:
                    print(triangle[row_idx][col_idx] ,						end=" "   )
               else:
                    print(triangle[row_idx][col_idx] ,						end=""   )
          print()





def      __a     (       _UpperCamelCase:   int   )						->			list[list[int]]:

     """simple docstring"""




     if not isinstance(_UpperCamelCase ,						_UpperCamelCase   ):
          raise TypeError("The input value of 'num_rows' should be 'int'"   )

     if num_rows == 0:
          return []
     elif num_rows < 0:
          raise ValueError(
              "The input value of 'num_rows' should be greater than or equal to 0"   )

     _snake_case							=				[]
     for current_row_idx in range(_UpperCamelCase   ):
          _snake_case							=				populate_current_row(_UpperCamelCase ,						_UpperCamelCase   )
          triangle.append(_UpperCamelCase   )
     return triangle





def      __a     (       _UpperCamelCase:   list[list[int]] ,						_UpperCamelCase:   int   )						->			list[int]:

     """simple docstring"""




     _snake_case							=				[-1] * (current_row_idx + 1)
     # first and last elements of current row are equal to 1
     _snake_case							, _snake_case							=				1, 1
     for current_col_idx in range(1 ,						_UpperCamelCase   ):
          calculate_current_element(
              _UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase   )
     return current_row





def      __a     (       _UpperCamelCase:   list[list[int]] ,						_UpperCamelCase:   list[int] ,						_UpperCamelCase:   int ,						_UpperCamelCase:   int ,						)						->			None:

     """simple docstring"""




     _snake_case							=				triangle[current_row_idx - 1][current_col_idx - 1]
     _snake_case							=				triangle[current_row_idx - 1][current_col_idx]
     _snake_case							=				above_to_left_elt + above_to_right_elt





def      __a     (       _UpperCamelCase:   int   )						->			list[list[int]]:

     """simple docstring"""




     if not isinstance(_UpperCamelCase ,						_UpperCamelCase   ):
          raise TypeError("The input value of 'num_rows' should be 'int'"   )

     if num_rows == 0:
          return []
     elif num_rows < 0:
          raise ValueError(
              "The input value of 'num_rows' should be greater than or equal to 0"   )

     _snake_case							=				[[1]]

     for row_index in range(1 ,						_UpperCamelCase   ):
          _snake_case							=				[0] + result[-1] + [0]
          _snake_case							=				row_index + 1
          # Calculate the number of distinct elements in a row
          _snake_case							=				sum(divmod(_UpperCamelCase ,						2   )   )
          _snake_case							=				[
              temp_row[i - 1] + temp_row[i] for i in range(1 ,						distinct_elements + 1   )
          ]
          _snake_case							=				row_first_half[: (row_index + 1) // 2]
          row_second_half.reverse()
          _snake_case							=				row_first_half + row_second_half
          result.append(_UpperCamelCase   )

     return result





def      __a     (       )						->			None:

     """simple docstring"""




     from collections.abc import Callable
     from timeit import timeit

     def benchmark_a_function(_UpperCamelCase:   Callable ,						_UpperCamelCase:   int   ) -> None:
          _snake_case							=				F"""{func.__name__}({value})"""
          _snake_case							=				timeit(F"""__main__.{call}""" ,						setup="import __main__"   )
          # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
          print(F"""{call:38} -- {timing:.4f} seconds"""   )

     for value in range(15   ):  # (1, 7, 14):
          for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
               benchmark_a_function(_UpperCamelCase ,						_UpperCamelCase   )
          print()


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   benchmark()


