





'''simple docstring'''







# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# this script dumps information about the environment

import os
import sys

import transformers


_lowercase       						=			'3'

print('Python version:', sys.version)
print('transformers version:', transformers.__version__)

try:
   import torch

   print('Torch version:', torch.__version__)
   print('Cuda available:', torch.cuda.is_available())
   print('Cuda version:', torch.version.cuda)
   print('CuDNN version:', torch.backends.cudnn.version())
   print('Number of GPUs available:', torch.cuda.device_count())
   print('NCCL version:', torch.cuda.nccl.version())
except ImportError:
   print('Torch version:', None)

try:
   import deepspeed

   print('DeepSpeed version:', deepspeed.__version__)
except ImportError:
   print('DeepSpeed version:', None)

try:
   import tensorflow as tf

   print('TensorFlow version:', tf.__version__)
   print('TF GPUs available:', bool(tf.config.list_physical_devices('GPU')))
   print('Number of TF GPUs available:', len(tf.config.list_physical_devices('GPU')))
except ImportError:
   print('TensorFlow version:', None)








'''simple docstring'''







from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers import TFViTForImageClassification, TFViTModel


if is_vision_available():
   from PIL import Image

   from transformers import ViTImageProcessor
class 			_lowercase						:







     def __init__( self    ,   A__    ,   A__=13    ,   A__=30    ,   A__=2    ,   A__=3    ,   A__=True    ,   A__=True    ,   A__=32    ,   A__=2    ,   A__=4    ,   A__=37    ,   A__="gelu"    ,   A__=0.1    ,   A__=0.1    ,   A__=10    ,   A__=0.0_2    ,   A__=3    ,   A__=None    ,   ) ->	List[Any]:
      snake_case				=			parent
      snake_case				=			batch_size
      snake_case				=			image_size
      snake_case				=			patch_size
      snake_case				=			num_channels
      snake_case				=			is_training
      snake_case				=			use_labels
      snake_case				=			hidden_size
      snake_case				=			num_hidden_layers
      snake_case				=			num_attention_heads
      snake_case				=			intermediate_size
      snake_case				=			hidden_act
      snake_case				=			hidden_dropout_prob
      snake_case				=			attention_probs_dropout_prob
      snake_case				=			type_sequence_label_size
      snake_case				=			initializer_range
      snake_case				=			scope

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







     def     UpperCamelCase			( self    ) ->	int:
      snake_case				=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

      snake_case				=			self.get_config()

      return config, pixel_values, labels







     def     UpperCamelCase			( self    ) ->	int:
      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    ,   )







     def     UpperCamelCase			( self    ,   A__    ,   A__    ,   A__    ) ->	Union[str, Any]:
      snake_case				=			TFViTModel(config=A__    )
      snake_case				=			model(A__    ,   training=A__    )
      self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)    )

      # Test with an image with different size than the one specified in config.
      snake_case				=			self.image_size // 2
      snake_case				=			pixel_values[:, :, :image_size, :image_size]
      snake_case				=			model(A__    ,   interpolate_pos_encoding=A__    ,   training=A__    )
      snake_case				=			(image_size // self.patch_size) ** 2 + 1
      self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, seq_length, self.hidden_size)    )







     def     UpperCamelCase			( self    ,   A__    ,   A__    ,   A__    ) ->	Optional[int]:
      snake_case				=			self.type_sequence_label_size
      snake_case				=			TFViTForImageClassification(A__    )
      snake_case				=			model(A__    ,   labels=A__    ,   training=A__    )
      self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.type_sequence_label_size)    )

      # Test with an image with different size than the one specified in config.
      snake_case				=			self.image_size // 2
      snake_case				=			pixel_values[:, :, :image_size, :image_size]
      snake_case				=			model(A__    ,   interpolate_pos_encoding=A__    ,   training=A__    )
      self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.type_sequence_label_size)    )

      # test greyscale images
      snake_case				=			1
      snake_case				=			TFViTForImageClassification(A__    )
      snake_case				=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
      snake_case				=			model(A__    )
      self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.type_sequence_label_size)    )







     def     UpperCamelCase			( self    ) ->	Union[str, Any]:
      snake_case				=			self.prepare_config_and_inputs()
      snake_case				,		snake_case				,		snake_case				=			config_and_inputs
      snake_case				=			{'''pixel_values''': pixel_values}
      return config, inputs_dict




@require_tf
class 			_lowercase						(       __a				,		__a				,		unittest.TestCase					):
     _UpperCAmelCase										=					(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
     _UpperCAmelCase										=					(
         {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification}
         if is_tf_available()
         else {}
     )

     _UpperCAmelCase										=					False
     _UpperCAmelCase										=					False
     _UpperCAmelCase										=					False







     def     UpperCamelCase			( self    ) ->	List[Any]:
      snake_case				=			TFViTModelTester(self    )
      snake_case				=			ConfigTester(self    ,   config_class=A__    ,   has_text_modality=A__    ,   hidden_size=37    )







     def     UpperCamelCase			( self    ) ->	int:
      self.config_tester.run_common_tests()







     @unittest.skip(reason='''ViT does not use inputs_embeds'''    )
     def     UpperCamelCase			( self    ) ->	int:
      pass







     @unittest.skip(reason='''ViT does not use inputs_embeds'''    )
     def     UpperCamelCase			( self    ) ->	str:
      pass







     def     UpperCamelCase			( self    ) ->	Union[str, Any]:
      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(A__    )
       self.assertIsInstance(model.get_input_embeddings()    ,   (tf.keras.layers.Layer)    )
       snake_case				=			model.get_output_embeddings()
       self.assertTrue(x is None or isinstance(A__    ,   tf.keras.layers.Layer    )    )







     def     UpperCamelCase			( self    ) ->	List[Any]:
      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(A__    )
       snake_case				=			inspect.signature(model.call    )
       # 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]    ,   A__    )







     def     UpperCamelCase			( self    ) ->	Union[str, Any]:
      snake_case				=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A__    )







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      snake_case				=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*A__    )







     @slow
     def     UpperCamelCase			( self    ) ->	Any:
      snake_case				=			TFViTModel.from_pretrained('''google/vit-base-patch16-224'''    )
      self.assertIsNotNone(A__    )




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






@require_tf
@require_vision
class 			_lowercase						(       unittest.TestCase					):







     @cached_property
     def     UpperCamelCase			( self    ) ->	Optional[int]:
      return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224'''    ) if is_vision_available() else None







     @slow
     def     UpperCamelCase			( self    ) ->	Dict:
      snake_case				=			TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''    )

      snake_case				=			self.default_image_processor
      snake_case				=			prepare_img()
      snake_case				=			image_processor(images=A__    ,   return_tensors='''tf'''    )

      # forward pass
      snake_case				=			model(**A__    )

      # verify the logits
      snake_case				=			tf.TensorShape((1, 10_00)    )
      self.assertEqual(outputs.logits.shape    ,   A__    )

      snake_case				=			tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]    )

      tf.debugging.assert_near(outputs.logits[0, :3]    ,   A__    ,   atol=1e-4    )

