





import inspect
import os

import torch
from transformers import AutoModel
from transformers.testing_utils import mockenv_context
from transformers.trainer_utils import set_seed

import accelerate
from accelerate.accelerator import Accelerator
from accelerate.state import AcceleratorState
from accelerate.test_utils.testing import (
    AccelerateTestCase,
    TempDirTestCase,
    execute_subprocess_async,
    require_cuda,
    require_fsdp,
    require_multi_gpu,
    slow,
)
from accelerate.utils.constants import (
    FSDP_AUTO_WRAP_POLICY,
    FSDP_BACKWARD_PREFETCH,
    FSDP_SHARDING_STRATEGY,
    FSDP_STATE_DICT_TYPE,
)
from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin
from accelerate.utils.other import patch_environment


set_seed(42)

lowercase_					     =	"""bert-base-cased"""
lowercase_					     =	"""fp16"""
lowercase_					     =	"""bf16"""
lowercase_					     =	[FPaa, BFaa]
@require_fsdp
@require_cuda
class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict )->     Optional[int]:





     """simple docstring"""







     super().setUp()

     lowercase__			    =						dict(
         ACCELERATE_USE_FSDP='true'    ,  MASTER_ADDR='localhost'    ,  MASTER_PORT='10999'    ,  RANK='0'    ,  LOCAL_RANK='0'    ,  WORLD_SIZE='1'    ,  )


   def  SCREAMING_SNAKE_CASE_							(					self    :       int )->     Dict:





     """simple docstring"""







     from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy

     for i, strategy in enumerate(a ):
       lowercase__			    =						self.dist_env.copy()
       lowercase__			    =						f"""{i + 1}"""
       lowercase__			    =						strategy
       with mockenv_context(**a ):
         lowercase__			    =						FullyShardedDataParallelPlugin()
         self.assertEqual(fsdp_plugin.sharding_strategy    ,  ShardingStrategy(i + 1 ) )


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





     """simple docstring"""







     from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch

     for i, prefetch_policy in enumerate(a ):
       lowercase__			    =						self.dist_env.copy()
       lowercase__			    =						prefetch_policy
       with mockenv_context(**a ):
         lowercase__			    =						FullyShardedDataParallelPlugin()
         if prefetch_policy == "NO_PREFETCH":
           self.assertIsNone(fsdp_plugin.backward_prefetch )
         else:
           self.assertEqual(fsdp_plugin.backward_prefetch    ,  BackwardPrefetch(i + 1 ) )


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





     """simple docstring"""







     from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType

     for i, state_dict_type in enumerate(a ):
       lowercase__			    =						self.dist_env.copy()
       lowercase__			    =						state_dict_type
       with mockenv_context(**a ):
         lowercase__			    =						FullyShardedDataParallelPlugin()
         self.assertEqual(fsdp_plugin.state_dict_type    ,  StateDictType(i + 1 ) )
         if state_dict_type == "FULL_STATE_DICT":
           self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu )
           self.assertTrue(fsdp_plugin.state_dict_config.ranka_only )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any] )->     str:





     """simple docstring"""







     lowercase__			    =						AutoModel.from_pretrained(a )
     for policy in FSDP_AUTO_WRAP_POLICY:
       lowercase__			    =						self.dist_env.copy()
       lowercase__			    =						policy
       if policy == "TRANSFORMER_BASED_WRAP":
         lowercase__			    =						'BertLayer'
       elif policy == "SIZE_BASED_WRAP":
         lowercase__			    =						'2000'
       with mockenv_context(**a ):
         lowercase__			    =						FullyShardedDataParallelPlugin()
         fsdp_plugin.set_auto_wrap_policy(a )
         if policy == "NO_WRAP":
           self.assertIsNone(fsdp_plugin.auto_wrap_policy )
         else:
           self.assertIsNotNone(fsdp_plugin.auto_wrap_policy )

     lowercase__			    =						self.dist_env.copy()
     lowercase__			    =						'TRANSFORMER_BASED_WRAP'
     lowercase__			    =						'T5Layer'
     with mockenv_context(**a ):
       lowercase__			    =						FullyShardedDataParallelPlugin()
       with self.assertRaises(a ) as cm:
         fsdp_plugin.set_auto_wrap_policy(a )
       self.assertTrue('Could not find the transformer layer class to wrap in the model.' in str(cm.exception ) )

     lowercase__			    =						self.dist_env.copy()
     lowercase__			    =						'SIZE_BASED_WRAP'
     lowercase__			    =						'0'
     with mockenv_context(**a ):
       lowercase__			    =						FullyShardedDataParallelPlugin()
       fsdp_plugin.set_auto_wrap_policy(a )
       self.assertIsNone(fsdp_plugin.auto_wrap_policy )


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





     """simple docstring"""







     from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
     from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler

     for mp_dtype in dtypes:
       lowercase__			    =						self.dist_env.copy()
       lowercase__			    =						mp_dtype
       with mockenv_context(**a ):
         lowercase__			    =						Accelerator()
         if mp_dtype == "fp16":
           lowercase__			    =						torch.floataa
         elif mp_dtype == "bf16":
           lowercase__			    =						torch.bfloataa
         lowercase__			    =						MixedPrecision(param_dtype=a    ,  reduce_dtype=a    ,  buffer_dtype=a )
         self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy    ,  a )
         if mp_dtype == FPaa:
           self.assertTrue(isinstance(accelerator.scaler    ,  a ) )
         elif mp_dtype == BFaa:
           self.assertIsNone(accelerator.scaler )
         AcceleratorState._reset_state(a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Any:





     """simple docstring"""







     from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload

     for flag in [True, False]:
       lowercase__			    =						self.dist_env.copy()
       lowercase__			    =						str(a ).lower()
       with mockenv_context(**a ):
         lowercase__			    =						FullyShardedDataParallelPlugin()
         self.assertEqual(fsdp_plugin.cpu_offload    ,  CPUOffload(offload_params=a ) )






@require_fsdp
@require_multi_gpu
@slow
class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):


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





     """simple docstring"""







     super().setUp()
     lowercase__			    =						0.82
     lowercase__			    =						[
         'fsdp_shard_grad_op_transformer_based_wrap',
         'fsdp_full_shard_transformer_based_wrap',
     ]
     lowercase__			    =						{
         'multi_gpu_fp16': 3_200,
         'fsdp_shard_grad_op_transformer_based_wrap_fp16': 2_000,
         'fsdp_full_shard_transformer_based_wrap_fp16': 1_900,
         # Disabling below test as it overwhelms the RAM memory usage
         # on CI self-hosted runner leading to tests getting killed.
         # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500,  # fp16 was leading to indefinite hang
     }
     lowercase__			    =						160
     lowercase__			    =						160

     lowercase__			    =						inspect.getfile(accelerate.test_utils )
     lowercase__			    =						os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps'] )


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





     """simple docstring"""







     lowercase__			    =						os.path.join(self.test_scripts_folder    ,  'test_performance.py' )
     lowercase__			    =						['accelerate', 'launch', '--num_processes=2', '--num_machines=1', '--machine_rank=0', '--use_fsdp']
     for config in self.performance_configs:
       lowercase__			    =						cmd.copy()
       for i, strategy in enumerate(a ):
         if strategy.lower() in config:
           cmd_config.append(f"""--fsdp_sharding_strategy={i+1}""" )
           break

       if "fp32" in config:
         cmd_config.append('--mixed_precision=no' )
       else:
         cmd_config.append('--mixed_precision=fp16' )

       if "cpu_offload" in config:
         cmd_config.append('--fsdp_offload_params=True' )

       for policy in FSDP_AUTO_WRAP_POLICY:
         if policy.lower() in config:
           cmd_config.append(f"""--fsdp_auto_wrap_policy={policy}""" )
           break

       if policy == "TRANSFORMER_BASED_WRAP":
         cmd_config.append('--fsdp_transformer_layer_cls_to_wrap=BertLayer' )
       elif policy == "SIZE_BASED_WRAP":
         cmd_config.append('--fsdp_min_num_params=2000' )

       cmd_config.extend(
           [
               self.test_file_path,
               f"""--output_dir={self.tmpdir}""",
               f"""--performance_lower_bound={self.performance_lower_bound}""",
           ] )
       with patch_environment(omp_num_threads=1 ):
         execute_subprocess_async(a    ,  env=os.environ.copy() )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Dict )->     Dict:





     """simple docstring"""







     lowercase__			    =						os.path.join(self.test_scripts_folder    ,  'test_checkpointing.py' )
     lowercase__			    =						[
         'accelerate',
         'launch',
         '--num_processes=2',
         '--num_machines=1',
         '--machine_rank=0',
         '--use_fsdp',
         '--mixed_precision=fp16',
         '--fsdp_transformer_layer_cls_to_wrap=BertLayer',
     ]

     for i, strategy in enumerate(a ):
       lowercase__			    =						cmd.copy()
       cmd_config.append(f"""--fsdp_sharding_strategy={i+1}""" )
       if strategy != "FULL_SHARD":
         continue
       lowercase__			    =						len(a )
       for state_dict_type in FSDP_STATE_DICT_TYPE:
         lowercase__			    =						cmd_config[:state_dict_config_index]
         cmd_config.append(f"""--fsdp_state_dict_type={state_dict_type}""" )
         cmd_config.extend(
             [
                 self.test_file_path,
                 f"""--output_dir={self.tmpdir}""",
                 '--partial_train_epoch=1',
             ] )
         with patch_environment(omp_num_threads=1 ):
           execute_subprocess_async(a    ,  env=os.environ.copy() )

         lowercase__			    =						cmd_config[:-1]
         lowercase__			    =						os.path.join(self.tmpdir    ,  'epoch_0' )
         cmd_config.extend(
             [
                 f"""--resume_from_checkpoint={resume_from_checkpoint}""",
             ] )
         with patch_environment(omp_num_threads=1 ):
           execute_subprocess_async(a    ,  env=os.environ.copy() )


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





     """simple docstring"""







     lowercase__			    =						os.path.join(self.test_scripts_folder    ,  'test_peak_memory_usage.py' )
     lowercase__			    =						[
         'accelerate',
         'launch',
         '--num_processes=2',
         '--num_machines=1',
         '--machine_rank=0',
     ]
     for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items():
       lowercase__			    =						cmd.copy()
       if "fp16" in spec:
         cmd_config.extend(['--mixed_precision=fp16'] )
       else:
         cmd_config.extend(['--mixed_precision=no'] )

       if "multi_gpu" in spec:
         continue
       else:
         cmd_config.extend(['--use_fsdp'] )
         for i, strategy in enumerate(a ):
           if strategy.lower() in spec:
             cmd_config.append(f"""--fsdp_sharding_strategy={i+1}""" )
             break

         if "cpu_offload" in spec:
           cmd_config.append('--fsdp_offload_params=True' )

         for policy in FSDP_AUTO_WRAP_POLICY:
           if policy.lower() in spec:
             cmd_config.append(f"""--fsdp_auto_wrap_policy={policy}""" )
             break

         if policy == "TRANSFORMER_BASED_WRAP":
           cmd_config.append('--fsdp_transformer_layer_cls_to_wrap=BertLayer' )
         elif policy == "SIZE_BASED_WRAP":
           cmd_config.append('--fsdp_min_num_params=2000' )

       cmd_config.extend(
           [
               self.test_file_path,
               f"""--output_dir={self.tmpdir}""",
               f"""--peak_memory_upper_bound={peak_mem_upper_bound}""",
               f"""--n_train={self.n_train}""",
               f"""--n_val={self.n_val}""",
           ] )
       with patch_environment(omp_num_threads=1 ):
         execute_subprocess_async(a    ,  env=os.environ.copy() )









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        SCREAMING_SNAKE_CASE     :


   def __init__(					self    :       List[Any]    ,  a    :       Any    ,  a    :       Optional[int]=13    ,  a    :       Tuple=30    ,  a    :       Union[str, Any]=2    ,  a    :       List[str]=3    ,  a    :       Dict=True    ,  a    :       List[str]=True    ,  a    :       List[Any]=32    ,  a    :       List[str]=5    ,  a    :       Optional[int]=4    ,  a    :       List[str]=37    ,  a    :       Dict="gelu"    ,  a    :       Dict=0.1    ,  a    :       List[str]=0.1    ,  a    :       int=10    ,  a    :       List[str]=0.02    ,  a    :       int=None    ,  a    :       List[str]=2    ,  )->     Dict:





     """simple docstring"""







     lowercase__			    =						parent
     lowercase__			    =						batch_size
     lowercase__			    =						image_size
     lowercase__			    =						patch_size
     lowercase__			    =						num_channels
     lowercase__			    =						is_training
     lowercase__			    =						use_labels
     lowercase__			    =						hidden_size
     lowercase__			    =						num_hidden_layers
     lowercase__			    =						num_attention_heads
     lowercase__			    =						intermediate_size
     lowercase__			    =						hidden_act
     lowercase__			    =						hidden_dropout_prob
     lowercase__			    =						attention_probs_dropout_prob
     lowercase__			    =						type_sequence_label_size
     lowercase__			    =						initializer_range
     lowercase__			    =						scope
     lowercase__			    =						encoder_stride

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


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Any:





     """simple docstring"""







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

     lowercase__			    =						None
     if self.use_labels:
       lowercase__			    =						ids_tensor([self.batch_size]    ,  self.type_sequence_label_size )

     lowercase__			    =						self.get_config()

     return config, pixel_values, labels


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     List[Any]:





     """simple docstring"""







     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=a    ,  initializer_range=self.initializer_range    ,  encoder_stride=self.encoder_stride    ,  )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Union[str, Any]    ,  a    :       List[Any]    ,  a    :       List[str]    ,  a    :       Dict )->     Optional[Any]:





     """simple docstring"""







     lowercase__			    =						ViTModel(config=a )
     model.to(a )
     model.eval()
     lowercase__			    =						model(a )
     self.parent.assertEqual(result.last_hidden_state.shape    ,  (self.batch_size, self.seq_length, self.hidden_size) )


   def  SCREAMING_SNAKE_CASE_							(					self    :       int    ,  a    :       Optional[Any]    ,  a    :       int    ,  a    :       Tuple )->     Union[str, Any]:





     """simple docstring"""







     lowercase__			    =						ViTForMaskedImageModeling(config=a )
     model.to(a )
     model.eval()
     lowercase__			    =						model(a )
     self.parent.assertEqual(
         result.reconstruction.shape    ,  (self.batch_size, self.num_channels, self.image_size, self.image_size) )

     # test greyscale images
     lowercase__			    =						1
     lowercase__			    =						ViTForMaskedImageModeling(a )
     model.to(a )
     model.eval()

     lowercase__			    =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
     lowercase__			    =						model(a )
     self.parent.assertEqual(result.reconstruction.shape    ,  (self.batch_size, 1, self.image_size, self.image_size) )


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str]    ,  a    :       List[str]    ,  a    :       int    ,  a    :       List[Any] )->     str:





     """simple docstring"""







     lowercase__			    =						self.type_sequence_label_size
     lowercase__			    =						ViTForImageClassification(a )
     model.to(a )
     model.eval()
     lowercase__			    =						model(a    ,  labels=a )
     self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.type_sequence_label_size) )

     # test greyscale images
     lowercase__			    =						1
     lowercase__			    =						ViTForImageClassification(a )
     model.to(a )
     model.eval()

     lowercase__			    =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
     lowercase__			    =						model(a )
     self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.type_sequence_label_size) )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     List[str]:





     """simple docstring"""







     lowercase__			    =						self.prepare_config_and_inputs()
     (
         (
         lowercase__
     )    ,					(
         lowercase__
     )    ,					(
         lowercase__
     )    ,					
     )			    =						config_and_inputs
     lowercase__			    =						{'pixel_values': pixel_values}
     return config, inputs_dict






@require_torch
class        SCREAMING_SNAKE_CASE     (UpperCAmelCase    ,			UpperCAmelCase    ,			unittest.TestCase   ):
   _UpperCamelCase					:	Any				      = (
       (
           ViTModel,
           ViTForImageClassification,
           ViTForMaskedImageModeling,
       )
       if is_torch_available()
       else ()
   )
   _UpperCamelCase					:	Union[str, Any]				      = (
       {'feature-extraction': ViTModel, 'image-classification': ViTForImageClassification}
       if is_torch_available()
       else {}
   )
   _UpperCamelCase					:	int				      = True

   _UpperCamelCase					:	int				      = False
   _UpperCamelCase					:	Union[str, Any]				      = False
   _UpperCamelCase					:	Dict				      = False


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[Any] )->     List[str]:





     """simple docstring"""







     lowercase__			    =						ViTModelTester(self )
     lowercase__			    =						ConfigTester(self    ,  config_class=a    ,  has_text_modality=a    ,  hidden_size=37 )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Union[str, Any]:





     """simple docstring"""







     self.config_tester.run_common_tests()


   @unittest.skip(reason='ViT does not use inputs_embeds' )
   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Optional[Any]:





     """simple docstring"""







     pass


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





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       lowercase__			    =						model_class(a )
       self.assertIsInstance(model.get_input_embeddings()    ,  (nn.Module) )
       lowercase__			    =						model.get_output_embeddings()
       self.assertTrue(x is None or isinstance(a    ,  nn.Linear ) )


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





     """simple docstring"""







     lowercase__    ,					lowercase__			    =						self.model_tester.prepare_config_and_inputs_for_common()

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

       lowercase__			    =						['pixel_values']
       self.assertListEqual(arg_names[:1]    ,  a )


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





     """simple docstring"""







     lowercase__			    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     Tuple:





     """simple docstring"""







     lowercase__			    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_image_modeling(*a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     int:





     """simple docstring"""







     lowercase__			    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*a )


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





     """simple docstring"""







     for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       lowercase__			    =						ViTModel.from_pretrained(a )
       self.assertIsNotNone(a )






def     __UpperCamelCase						()       ->     str:
  lowercase__			    =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
  return image


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


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





     """simple docstring"""







     return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224' ) if is_vision_available() else None


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





     """simple docstring"""







     lowercase__			    =						ViTForImageClassification.from_pretrained('google/vit-base-patch16-224' ).to(a )

     lowercase__			    =						self.default_image_processor
     lowercase__			    =						prepare_img()
     lowercase__			    =						image_processor(images=a    ,  return_tensors='pt' ).to(a )

     # forward pass
     with torch.no_grad():
       lowercase__			    =						model(**a )

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

     lowercase__			    =						torch.tensor([-0.2744, 0.8215, -0.0836] ).to(a )

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


   @slow
   def  SCREAMING_SNAKE_CASE_							(					self    :       int )->     List[str]:





     """simple docstring"""







     lowercase__			    =						ViTModel.from_pretrained('facebook/dino-vits8' ).to(a )

     lowercase__			    =						ViTImageProcessor.from_pretrained('facebook/dino-vits8'    ,  size=480 )
     lowercase__			    =						prepare_img()
     lowercase__			    =						image_processor(images=a    ,  return_tensors='pt' )
     lowercase__			    =						inputs.pixel_values.to(a )

     # forward pass
     with torch.no_grad():
       lowercase__			    =						model(a    ,  interpolate_pos_encoding=a )

     # verify the logits
     lowercase__			    =						torch.Size((1, 3_601, 384) )
     self.assertEqual(outputs.last_hidden_state.shape    ,  a )

     lowercase__			    =						torch.tensor(
         [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(a )

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


   @slow
   @require_accelerate
   @require_torch_gpu
   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     str:





     """simple docstring"""







     lowercase__			    =						ViTModel.from_pretrained('facebook/dino-vits8'    ,  torch_dtype=torch.floataa    ,  device_map='auto' )
     lowercase__			    =						self.default_image_processor

     lowercase__			    =						prepare_img()
     lowercase__			    =						image_processor(images=a    ,  return_tensors='pt' )
     lowercase__			    =						inputs.pixel_values.to(a )

     # forward pass to make sure inference works in fp16
     with torch.no_grad():
       lowercase__			    =						model(a )


