



"""simple docstring"""







import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_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 torch import nn

       from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
       from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import ViTImageProcessor







class 				UpperCamelCase__       :




      """simple docstring"""




      def __init__(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				List[str]=1_3   ,      SCREAMING_SNAKE_CASE_    :				List[str]=3_0   ,      SCREAMING_SNAKE_CASE_    :				int=2   ,      SCREAMING_SNAKE_CASE_    :				Any=3   ,      SCREAMING_SNAKE_CASE_    :				List[str]=True   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=True   ,      SCREAMING_SNAKE_CASE_    :				List[str]=3_2   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=5   ,      SCREAMING_SNAKE_CASE_    :				List[str]=4   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=3_7   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]="gelu"   ,      SCREAMING_SNAKE_CASE_    :				Dict=0.1   ,      SCREAMING_SNAKE_CASE_    :				Tuple=0.1   ,      SCREAMING_SNAKE_CASE_    :				Tuple=1_0   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=0.02   ,      SCREAMING_SNAKE_CASE_    :				str=None   ,      SCREAMING_SNAKE_CASE_    :				Dict=2   ,      ):
        lowerCAmelCase_       :    Any								=			parent
        lowerCAmelCase_       :    Dict								=			batch_size
        lowerCAmelCase_       :    Optional[int]								=			image_size
        lowerCAmelCase_       :    Tuple								=			patch_size
        lowerCAmelCase_       :    str								=			num_channels
        lowerCAmelCase_       :    Any								=			is_training
        lowerCAmelCase_       :    List[Any]								=			use_labels
        lowerCAmelCase_       :    int								=			hidden_size
        lowerCAmelCase_       :    List[Any]								=			num_hidden_layers
        lowerCAmelCase_       :    List[str]								=			num_attention_heads
        lowerCAmelCase_       :    Tuple								=			intermediate_size
        lowerCAmelCase_       :    Dict								=			hidden_act
        lowerCAmelCase_       :    Tuple								=			hidden_dropout_prob
        lowerCAmelCase_       :    List[Any]								=			attention_probs_dropout_prob
        lowerCAmelCase_       :    int								=			type_sequence_label_size
        lowerCAmelCase_       :    int								=			initializer_range
        lowerCAmelCase_       :    List[Any]								=			scope
        lowerCAmelCase_       :    Any								=			encoder_stride

        # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
        lowerCAmelCase_       :    Dict								=			(image_size // patch_size) ** 2
        lowerCAmelCase_       :    Tuple								=			num_patches + 1



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        lowerCAmelCase_       :    Any								=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

        lowerCAmelCase_       :    str								=			None
        if self.use_labels:
          lowerCAmelCase_       :    Dict								=			ids_tensor([self.batch_size]   ,      self.type_sequence_label_size	)

        lowerCAmelCase_       :    str								=			self.get_config()

        return config, pixel_values, labels



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        return ViTConfig(
            image_size=self.image_size   ,      patch_size=self.patch_size   ,      num_channels=self.num_channels   ,      hidden_size=self.hidden_size   ,      num_hidden_layers=self.num_hidden_layers   ,      num_attention_heads=self.num_attention_heads   ,      intermediate_size=self.intermediate_size   ,      hidden_act=self.hidden_act   ,      hidden_dropout_prob=self.hidden_dropout_prob   ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,      is_decoder=SCREAMING_SNAKE_CASE_   ,      initializer_range=self.initializer_range   ,      encoder_stride=self.encoder_stride   ,      )



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				str	):
        lowerCAmelCase_       :    Tuple								=			ViTModel(config=SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()
        lowerCAmelCase_       :    Dict								=			model(SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.last_hidden_state.shape   ,      (self.batch_size, self.seq_length, self.hidden_size)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Any	):
        lowerCAmelCase_       :    Optional[Any]								=			ViTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()
        lowerCAmelCase_       :    List[str]								=			model(SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(
            result.reconstruction.shape   ,      (self.batch_size, self.num_channels, self.image_size, self.image_size)	)

        # test greyscale images
        lowerCAmelCase_       :    Tuple								=			1
        lowerCAmelCase_       :    Optional[Any]								=			ViTForMaskedImageModeling(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    Tuple								=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
        lowerCAmelCase_       :    Any								=			model(SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.reconstruction.shape   ,      (self.batch_size, 1, self.image_size, self.image_size)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				List[Any]	):
        lowerCAmelCase_       :    List[Any]								=			self.type_sequence_label_size
        lowerCAmelCase_       :    Optional[int]								=			ViTForImageClassification(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()
        lowerCAmelCase_       :    Any								=			model(SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.type_sequence_label_size)	)

        # test greyscale images
        lowerCAmelCase_       :    Dict								=			1
        lowerCAmelCase_       :    Tuple								=			ViTForImageClassification(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    Dict								=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
        lowerCAmelCase_       :    List[Any]								=			model(SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.type_sequence_label_size)	)





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







@require_torch
class 				UpperCamelCase__       (     __lowercase, __lowercase, unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					(
          (
              ViTModel,
              ViTForImageClassification,
              ViTForMaskedImageModeling,
          )
          if is_torch_available()
          else ()
      )
      _SCREAMING_SNAKE_CASE      =					(
          {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
          if is_torch_available()
          else {}
      )
      _SCREAMING_SNAKE_CASE      =					True

      _SCREAMING_SNAKE_CASE      =					False
      _SCREAMING_SNAKE_CASE      =					False
      _SCREAMING_SNAKE_CASE      =					False



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        lowerCAmelCase_       :    List[str]								=			ViTModelTester(self	)
        lowerCAmelCase_       :    Dict								=			ConfigTester(self   ,      config_class=SCREAMING_SNAKE_CASE_   ,      has_text_modality=SCREAMING_SNAKE_CASE_   ,      hidden_size=3_7	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        self.config_tester.run_common_tests()



      @unittest.skip(reason='ViT does not use inputs_embeds'	)
      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
        pass



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    Optional[int]								=			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          lowerCAmelCase_       :    Union[str, Any]								=			model_class(SCREAMING_SNAKE_CASE_	)
          self.assertIsInstance(model.get_input_embeddings()   ,      (nn.Module)	)
          lowerCAmelCase_       :    str								=			model.get_output_embeddings()
          self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_   ,      nn.Linear	)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        lowerCAmelCase_       :    Optional[Any]								=			self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase_       :    Optional[int]								=			["""pixel_values"""]
          self.assertListEqual(arg_names[:1]   ,      SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]	):
        lowerCAmelCase_       :    str								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
        lowerCAmelCase_       :    List[Any]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        lowerCAmelCase_       :    int								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_	)





      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]	):

        for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase_       :    str								=			ViTModel.from_pretrained(SCREAMING_SNAKE_CASE_	)
          self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)




def     UpperCamelCase_   (   )						->       List[Any]:

  """simple docstring"""




  lowerCAmelCase_       :    Dict								=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
  return image







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




      """simple docstring"""




      @cached_property
      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224'	) if is_vision_available() else None



      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				int	):
        lowerCAmelCase_       :    Any								=			ViTForImageClassification.from_pretrained('google/vit-base-patch16-224'	).to(SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    int								=			self.default_image_processor
        lowerCAmelCase_       :    List[str]								=			prepare_img()
        lowerCAmelCase_       :    Optional[Any]								=			image_processor(images=SCREAMING_SNAKE_CASE_   ,      return_tensors='pt'	).to(SCREAMING_SNAKE_CASE_	)

        # forward pass
        with torch.no_grad():
          lowerCAmelCase_       :    str								=			model(**SCREAMING_SNAKE_CASE_	)

        # verify the logits
        lowerCAmelCase_       :    Dict								=			torch.Size((1, 1_0_0_0)	)
        self.assertEqual(outputs.logits.shape   ,      SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    List[str]								=			torch.tensor([-0.27_44, 0.82_15, -0.08_36]	).to(SCREAMING_SNAKE_CASE_	)

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



      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        lowerCAmelCase_       :    Tuple								=			ViTModel.from_pretrained('facebook/dino-vits8'	).to(SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    Dict								=			ViTImageProcessor.from_pretrained('facebook/dino-vits8'   ,      size=4_8_0	)
        lowerCAmelCase_       :    List[Any]								=			prepare_img()
        lowerCAmelCase_       :    Optional[int]								=			image_processor(images=SCREAMING_SNAKE_CASE_   ,      return_tensors='pt'	)
        lowerCAmelCase_       :    str								=			inputs.pixel_values.to(SCREAMING_SNAKE_CASE_	)

        # forward pass
        with torch.no_grad():
          lowerCAmelCase_       :    List[str]								=			model(SCREAMING_SNAKE_CASE_   ,      interpolate_pos_encoding=SCREAMING_SNAKE_CASE_	)

        # verify the logits
        lowerCAmelCase_       :    Optional[Any]								=			torch.Size((1, 3_6_0_1, 3_8_4)	)
        self.assertEqual(outputs.last_hidden_state.shape   ,      SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    Optional[int]								=			torch.tensor(
            [[4.23_40, 4.39_06, -6.66_92], [4.54_63, 1.89_28, -6.72_57], [4.44_29, 0.84_96, -5.85_85]]	).to(SCREAMING_SNAKE_CASE_	)

        self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]   ,      SCREAMING_SNAKE_CASE_   ,      atol=1E-4	)	)





      @slow
      @require_accelerate
      @require_torch_gpu
      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
        lowerCAmelCase_       :    Dict								=			ViTModel.from_pretrained('facebook/dino-vits8'   ,      torch_dtype=torch.floataa   ,      device_map='auto'	)
        lowerCAmelCase_       :    Union[str, Any]								=			self.default_image_processor

        lowerCAmelCase_       :    List[str]								=			prepare_img()
        lowerCAmelCase_       :    Optional[Any]								=			image_processor(images=SCREAMING_SNAKE_CASE_   ,      return_tensors='pt'	)
        lowerCAmelCase_       :    Any								=			inputs.pixel_values.to(SCREAMING_SNAKE_CASE_	)

        # forward pass to make sure inference works in fp16
        with torch.no_grad():
          lowerCAmelCase_       :    List[Any]								=			model(SCREAMING_SNAKE_CASE_	)










"""simple docstring"""







def     UpperCamelCase_   (   lowerCAmelCase__				:    list[int]   ,       lowerCAmelCase__				:    list[int]						)						->       None:

  """simple docstring"""




  lowerCAmelCase_       :    List[Any]								=			len(lowerCAmelCase__						)
  print('The following activities are selected:'						)

  # The first activity is always selected
  lowerCAmelCase_       :    str								=			0
  print(lowerCAmelCase__   ,       end=','						)

  # Consider rest of the activities
  for j in range(lowerCAmelCase__						):
    # If this activity has start time greater than
    # or equal to the finish time of previously
    # selected activity, then select it
    if start[j] >= finish[i]:
      print(lowerCAmelCase__   ,       end=','						)
      lowerCAmelCase_       :    Tuple								=			j


if __name__ == "__main__":
     import doctest

     doctest.testmod()

     lowercase__		:    List[str]				   =     [1, 3, 0, 5, 8, 5]
     lowercase__		:    Dict				   =     [2, 4, 6, 7, 9, 9]
     print_max_activities(start, finish)





