






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 			snake_case__   (							lowercase_):

       '''simple docstring'''



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case			:List[Any]          =						self.config_class(**self.inputs_dict    )
            self.parent.assertTrue(hasattr(a__			,						"""width_multiplier"""    )    )




class 			snake_case__   :

       '''simple docstring'''



       def __init__(							self			,						a__			,						a__=13			,						a__=64			,						a__=2			,						a__=3			,						a__="swish"			,						a__=3			,						a__=32			,						a__=0.1			,						a__=0.02			,						a__=True			,						a__=True			,						a__=10			,						a__=None			,						a__=0.25			,						a__=0.0			,						a__=0.0			,						) ->      str:






            '''simple docstring'''





            __snake_case			:int          =						parent
            __snake_case			:Dict          =						batch_size
            __snake_case			:Optional[int]          =						image_size
            __snake_case			:Tuple          =						patch_size
            __snake_case			:int          =						num_channels
            __snake_case			:Optional[int]          =						make_divisible(5_12 * width_multiplier			,						divisor=8    )
            __snake_case			:Dict          =						hidden_act
            __snake_case			:Any          =						conv_kernel_size
            __snake_case			:Any          =						output_stride
            __snake_case			:Optional[int]          =						classifier_dropout_prob
            __snake_case			:Any          =						use_labels
            __snake_case			:Union[str, Any]          =						is_training
            __snake_case			:Optional[Any]          =						num_labels
            __snake_case			:List[Any]          =						initializer_range
            __snake_case			:Tuple          =						scope
            __snake_case			:Optional[int]          =						width_multiplier
            __snake_case			:int          =						ffn_dropout
            __snake_case			:str          =						attn_dropout



       def 					__lowercase						(							self    ) ->      Optional[Any]:






            '''simple docstring'''





            __snake_case			:int          =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

            __snake_case			:List[str]          =						None
            __snake_case			:List[str]          =						None
            if self.use_labels:
                 __snake_case			:List[str]          =						ids_tensor([self.batch_size]			,						self.num_labels    )
                 __snake_case			:Optional[int]          =						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    ) ->      Union[str, Any]:






            '''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			,						a__			,						a__			,						a__			,						a__    ) ->      Optional[Any]:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						MobileViTVaModel(config=a__    )
            model.to(a__    )
            model.eval()
            __snake_case			:Tuple          =						model(a__    )
            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			,						a__			,						a__			,						a__			,						a__    ) ->      Optional[Any]:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.num_labels
            __snake_case			:Optional[Any]          =						MobileViTVaForImageClassification(a__    )
            model.to(a__    )
            model.eval()
            __snake_case			:Any          =						model(a__			,						labels=a__    )
            self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_labels)    )



       def 					__lowercase						(							self			,						a__			,						a__			,						a__			,						a__    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:List[Any]          =						self.num_labels
            __snake_case			:Optional[int]          =						MobileViTVaForSemanticSegmentation(a__    )
            model.to(a__    )
            model.eval()
            __snake_case			:Tuple          =						model(a__    )
            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			:Union[str, Any]          =						model(a__			,						labels=a__    )
            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    ) ->      Any:






            '''simple docstring'''





            __snake_case			:List[Any]          =						self.prepare_config_and_inputs()
            __snake_case       , __snake_case       , __snake_case       , __snake_case			:Any          =						config_and_inputs
            __snake_case			:Dict          =						{"""pixel_values""": pixel_values}
            return config, inputs_dict




@require_torch
class 			snake_case__   (							lowercase_	,    lowercase_	,    unittest.TestCase):

       '''simple docstring'''
       lowerCamelCase							:				Optional[Any] 				= (
           (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
           if is_torch_available()
           else ()
       )

       lowerCamelCase							:				Union[str, Any] 				= (
           {
               "feature-extraction": MobileViTVaModel,
               "image-classification": MobileViTVaForImageClassification,
               "image-segmentation": MobileViTVaForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       lowerCamelCase							:				List[Any] 				= False
       lowerCamelCase							:				List[str] 				= False
       lowerCamelCase							:				List[Any] 				= False
       lowerCamelCase							:				Optional[int] 				= False



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:Union[str, Any]          =						MobileViTVaModelTester(self    )
            __snake_case			:int          =						MobileViTVaConfigTester(self			,						config_class=a__			,						has_text_modality=a__    )



       def 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            self.config_tester.run_common_tests()



       @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds"""    )
       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            pass



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






            '''simple docstring'''





            pass



       @unittest.skip(reason="""MobileViTV2 does not output attentions"""    )
       def 					__lowercase						(							self    ) ->      Optional[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    ) ->      Union[str, Any]:






            '''simple docstring'''





            pass



       @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""    )
       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            pass



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case       , __snake_case			:Dict          =						self.model_tester.prepare_config_and_inputs_for_common()

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

                 __snake_case			:str          =						["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]			,						a__    )



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:List[Any]          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*a__    )



       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            def check_hidden_states_output(a__			,						a__			,						a__    ):
                 __snake_case			:Optional[int]          =						model_class(a__    )
                 model.to(a__    )
                 model.eval()

                 with torch.no_grad():
                      __snake_case			:str          =						model(**self._prepare_for_class(a__			,						a__    )    )

                 __snake_case			:Any          =						outputs.hidden_states

                 __snake_case			:List[Any]          =						5
                 self.assertEqual(len(a__    )			,						a__    )

                 # 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			:str          =						2
                 for i in range(len(a__    )    ):
                      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			:Optional[Any]          =						self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 __snake_case			:Any          =						True
                 check_hidden_states_output(a__			,						a__			,						a__    )

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 __snake_case			:str          =						True

                 check_hidden_states_output(a__			,						a__			,						a__    )



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Optional[int]          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*a__    )



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            __snake_case			:str          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_semantic_segmentation(*a__    )



       @slow
       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __snake_case			:Dict          =						MobileViTVaModel.from_pretrained(a__    )
                 self.assertIsNotNone(a__    )






def   UpperCamelCase  (       ):




     '''simple docstring'''






     __snake_case			:Optional[int]          =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
     return image




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

       '''simple docstring'''



       @cached_property
       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





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



       @slow
       def 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:str          =						MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""    ).to(
                a__    )

            __snake_case			:Dict          =						self.default_image_processor
            __snake_case			:Optional[Any]          =						prepare_img()
            __snake_case			:Dict          =						image_processor(images=a__			,						return_tensors="""pt"""    ).to(a__    )

            # forward pass
            with torch.no_grad():
                 __snake_case			:Optional[Any]          =						model(**a__    )

            # verify the logits
            __snake_case			:int          =						torch.Size((1, 10_00)    )
            self.assertEqual(outputs.logits.shape			,						a__    )

            __snake_case			:List[Any]          =						torch.tensor([-1.63_36e00, -7.32_04e-02, -5.18_83e-01]    ).to(a__    )

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



       @slow
       def 					__lowercase						(							self    ) ->      Optional[Any]:






            '''simple docstring'''





            __snake_case			:List[str]          =						MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""    )
            __snake_case			:Any          =						model.to(a__    )

            __snake_case			:Tuple          =						MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""    )

            __snake_case			:Dict          =						prepare_img()
            __snake_case			:List[Any]          =						image_processor(images=a__			,						return_tensors="""pt"""    ).to(a__    )

            # forward pass
            with torch.no_grad():
                 __snake_case			:Tuple          =						model(**a__    )
            __snake_case			:List[Any]          =						outputs.logits

            # verify the logits
            __snake_case			:Any          =						torch.Size((1, 21, 32, 32)    )
            self.assertEqual(logits.shape			,						a__    )

            __snake_case			:Optional[Any]          =						torch.tensor(
                [
                    [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
                    [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
                    [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
                ]			,						device=a__			,						)

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



       @slow
       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case			:Union[str, Any]          =						MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""    )
            __snake_case			:Union[str, Any]          =						model.to(a__    )

            __snake_case			:Optional[Any]          =						MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""    )

            __snake_case			:int          =						prepare_img()
            __snake_case			:Tuple          =						image_processor(images=a__			,						return_tensors="""pt"""    ).to(a__    )

            # forward pass
            with torch.no_grad():
                 __snake_case			:Dict          =						model(**a__    )

            __snake_case			:Any          =						outputs.logits.detach().cpu()

            __snake_case			:Tuple          =						image_processor.post_process_semantic_segmentation(outputs=a__			,						target_sizes=[(50, 60)]    )
            __snake_case			:List[str]          =						torch.Size((50, 60)    )
            self.assertEqual(segmentation[0].shape			,						a__    )

            __snake_case			:Optional[int]          =						image_processor.post_process_semantic_segmentation(outputs=a__    )
            __snake_case			:Dict          =						torch.Size((32, 32)    )
            self.assertEqual(segmentation[0].shape			,						a__    )










from __future__ import annotations

lowerCamelCase__							=     list[list[int]]

# assigning initial values to the grid
lowerCamelCase__							=     [
    [3, 0, 6, 5, 0, 8, 4, 0, 0],
    [5, 2, 0, 0, 0, 0, 0, 0, 0],
    [0, 8, 7, 0, 0, 0, 0, 3, 1],
    [0, 0, 3, 0, 1, 0, 0, 8, 0],
    [9, 0, 0, 8, 6, 3, 0, 0, 5],
    [0, 5, 0, 0, 9, 0, 6, 0, 0],
    [1, 3, 0, 0, 0, 0, 2, 5, 0],
    [0, 0, 0, 0, 0, 0, 0, 7, 4],
    [0, 0, 5, 2, 0, 6, 3, 0, 0],
]

# a grid with no solution
lowerCamelCase__							=     [
    [5, 0, 6, 5, 0, 8, 4, 0, 3],
    [5, 2, 0, 0, 0, 0, 0, 0, 2],
    [1, 8, 7, 0, 0, 0, 0, 3, 1],
    [0, 0, 3, 0, 1, 0, 0, 8, 0],
    [9, 0, 0, 8, 6, 3, 0, 0, 5],
    [0, 5, 0, 0, 9, 0, 6, 0, 0],
    [1, 3, 0, 0, 0, 0, 2, 5, 0],
    [0, 0, 0, 0, 0, 0, 0, 7, 4],
    [0, 0, 5, 2, 0, 6, 3, 0, 0],
]






def   UpperCamelCase  (       snake_case__     :   Matrix	,snake_case__     :   int	,snake_case__     :   int	,snake_case__     :   int  ):




     '''simple docstring'''






     for i in range(9  ):
          if grid[row][i] == n or grid[i][column] == n:
               return False

     for i in range(3  ):
          for j in range(3  ):
               if grid[(row - row % 3) + i][(column - column % 3) + j] == n:
                    return False

     return True






def   UpperCamelCase  (       snake_case__     :   Matrix  ):




     '''simple docstring'''






     for i in range(9  ):
          for j in range(9  ):
               if grid[i][j] == 0:
                    return i, j
     return None






def   UpperCamelCase  (       snake_case__     :   Matrix  ):




     '''simple docstring'''






     if location := find_empty_location(snake_case__  ):
          __snake_case       , __snake_case			:Optional[int]          =						location
     else:
          # If the location is ``None``, then the grid is solved.
          return grid

     for digit in range(1	,10  ):
          if is_safe(snake_case__	,snake_case__	,snake_case__	,snake_case__  ):
               __snake_case			:Union[str, Any]          =						digit

               if sudoku(snake_case__  ) is not None:
                    return grid

               __snake_case			:Tuple          =						0

     return None






def   UpperCamelCase  (       snake_case__     :   Matrix  ):




     '''simple docstring'''






     for row in grid:
          for cell in row:
               print(snake_case__	,end=""" """  )
          print()


if __name__ == "__main__":
     # make a copy of grid so that you can compare with the unmodified grid
     for example_grid in (initial_grid, no_solution):
          print("""\nExample grid:\n""" + """=""" * 20)
          print_solution(example_grid)
          print("""\nExample grid solution:""")
          lowerCamelCase__							=     sudoku(example_grid)
          if solution is not None:
               print_solution(solution)
          else:
               print("""Cannot find a solution.""")


