





import logging

import numpy as np
import pytest
from scipy.linalg import eigh

logging.basicConfig(level=logging.INFO, format="""%(message)s""")




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	)       ->     np.ndarray:
  return input_array.reshape((input_array.size, 1)	)




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     np.ndarray:
  lowercase__			    =						np.nan
  for i in range(_SCREAMING_SNAKE_CASE	):
    lowercase__			    =						features[:, labels == i]
    lowercase__			    =						data.mean(1	)
    # Centralize the data of class i
    lowercase__			    =						data - column_reshape(_SCREAMING_SNAKE_CASE	)
    if i > 0:
      # If covariance_sum is not None
      covariance_sum += np.dot(_SCREAMING_SNAKE_CASE	,		centered_data.T	)
    else:
      # If covariance_sum is np.nan (i.e. first loop)
      lowercase__			    =						np.dot(_SCREAMING_SNAKE_CASE	,		centered_data.T	)

  return covariance_sum / features.shape[1]




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     np.ndarray:
  lowercase__			    =						features.mean(1	)
  lowercase__			    =						np.nan
  for i in range(_SCREAMING_SNAKE_CASE	):
    lowercase__			    =						features[:, labels == i]
    lowercase__			    =						data.shape[1]
    lowercase__			    =						data.mean(1	)
    if i > 0:
      # If covariance_sum is not None
      covariance_sum += device_data * np.dot(
          column_reshape(_SCREAMING_SNAKE_CASE	) - column_reshape(_SCREAMING_SNAKE_CASE	)	,		(column_reshape(_SCREAMING_SNAKE_CASE	) - column_reshape(_SCREAMING_SNAKE_CASE	)).T	,		)
    else:
      # If covariance_sum is np.nan (i.e. first loop)
      lowercase__			    =						device_data * np.dot(
          column_reshape(_SCREAMING_SNAKE_CASE	) - column_reshape(_SCREAMING_SNAKE_CASE	)	,		(column_reshape(_SCREAMING_SNAKE_CASE	) - column_reshape(_SCREAMING_SNAKE_CASE	)).T	,		)

  return covariance_sum / features.shape[1]




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     np.ndarray:

  # Check if the features have been loaded
  if features.any():
    lowercase__			    =						features.mean(1	)
    # Center the dataset
    lowercase__			    =						features - np.reshape(_SCREAMING_SNAKE_CASE	,		(data_mean.size, 1)	)
    lowercase__			    =						np.dot(_SCREAMING_SNAKE_CASE	,		centered_data.T	) / features.shape[1]
    lowercase__    ,					lowercase__			    =						np.linalg.eigh(_SCREAMING_SNAKE_CASE	)
    # Take all the columns in the reverse order (-1), and then takes only the first
    lowercase__			    =						eigenvectors[:, ::-1][:, 0:dimensions]
    # Project the database on the new space
    lowercase__			    =						np.dot(filtered_eigenvectors.T	,		_SCREAMING_SNAKE_CASE	)
    logging.info('Principal Component Analysis computed'	)

    return projected_data
  else:
    logging.basicConfig(level=logging.ERROR	,		format='%(message)s'	,		force=_SCREAMING_SNAKE_CASE	)
    logging.error('Dataset empty'	)
    raise AssertionError




def     __UpperCamelCase						(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)       ->     np.ndarray:
  assert classes > dimensions

  # Check if features have been already loaded
  if features.any:
    lowercase__    ,					lowercase__			    =						eigh(
        covariance_between_classes(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)	,		covariance_within_classes(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)	,		)
    lowercase__			    =						eigenvectors[:, ::-1][:, :dimensions]
    lowercase__    ,					lowercase__    ,					lowercase__			    =						np.linalg.svd(_SCREAMING_SNAKE_CASE	)
    lowercase__			    =						svd_matrix[:, 0:dimensions]
    lowercase__			    =						np.dot(filtered_svd_matrix.T	,		_SCREAMING_SNAKE_CASE	)
    logging.info('Linear Discriminant Analysis computed'	)

    return projected_data
  else:
    logging.basicConfig(level=logging.ERROR	,		format='%(message)s'	,		force=_SCREAMING_SNAKE_CASE	)
    logging.error('Dataset empty'	)
    raise AssertionError




def     __UpperCamelCase						()       ->     None:
  # Create dummy dataset with 2 classes and 3 features
  lowercase__			    =						np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]	)
  lowercase__			    =						np.array([0, 0, 0, 1, 1]	)
  lowercase__			    =						2
  lowercase__			    =						2

  # Assert that the function raises an AssertionError if dimensions > classes
  with pytest.raises(_SCREAMING_SNAKE_CASE	) as error_info:
    lowercase__			    =						linear_discriminant_analysis(
        _SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)
    if isinstance(_SCREAMING_SNAKE_CASE	,		np.ndarray	):
      raise AssertionError(
          'Did not raise AssertionError for dimensions > classes'	)
    assert error_info.type is AssertionError




def     __UpperCamelCase						()       ->     None:
  lowercase__			    =						np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]	)
  lowercase__			    =						2
  lowercase__			    =						np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]]	)

  with pytest.raises(_SCREAMING_SNAKE_CASE	) as error_info:
    lowercase__			    =						principal_component_analysis(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	)
    if not np.allclose(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	):
      raise AssertionError
    assert error_info.type is AssertionError


if __name__ == "__main__":
      import doctest

      doctest.testmod()









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 )


