




from random import shuffle

import tensorflow as tf
from numpy import array







def lowerCamelCase__       (      _lowercase			,						_lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							int       =      int(_lowercase				)
     assert noofclusters < len(_lowercase				)

     # Find out the dimensionality
     UpperCAmelCase_      :							Any       =      len(vectors[0]				)

     # Will help select random centroids from among the available vectors
     UpperCAmelCase_      :							Optional[Any]       =      list(range(len(_lowercase				)				)				)
     shuffle(_lowercase				)

     # GRAPH OF COMPUTATION
     # We initialize a new graph and set it as the default during each run
     # of this algorithm. This ensures that as this function is called
     # multiple times, the default graph doesn't keep getting crowded with
     # unused ops and Variables from previous function calls.

     UpperCAmelCase_      :							Tuple       =      tf.Graph()

     with graph.as_default():
          # SESSION OF COMPUTATION

          UpperCAmelCase_      :							Dict       =      tf.Session()

          ##CONSTRUCTING THE ELEMENTS OF COMPUTATION

          ##First lets ensure we have a Variable vector for each centroid,
          ##initialized to one of the vectors from the available data points
          UpperCAmelCase_      :							List[str]       =      [
              tf.Variable(vectors[vector_indices[i]]				) for i in range(_lowercase				)
          ]
          ##These nodes will assign the centroid Variables the appropriate
          ##values
          UpperCAmelCase_      :							Optional[Any]       =      tf.placeholder('''float64'''			,						[dim]				)
          UpperCAmelCase_      :							str       =      []
          for centroid in centroids:
               cent_assigns.append(tf.assign(_lowercase			,						_lowercase				)				)

          ##Variables for cluster assignments of individual vectors(initialized
          ##to 0 at first)
          UpperCAmelCase_      :							Optional[Any]       =      [tf.Variable(0				) for i in range(len(_lowercase				)				)]
          ##These nodes will assign an assignment Variable the appropriate
          ##value
          UpperCAmelCase_      :							int       =      tf.placeholder('''int32'''				)
          UpperCAmelCase_      :							Optional[int]       =      []
          for assignment in assignments:
               cluster_assigns.append(tf.assign(_lowercase			,						_lowercase				)				)

          ##Now lets construct the node that will compute the mean
          # The placeholder for the input
          UpperCAmelCase_      :							Union[str, Any]       =      tf.placeholder('''float'''			,						[None, dim]				)
          # The Node/op takes the input and computes a mean along the 0th
          # dimension, i.e. the list of input vectors
          UpperCAmelCase_      :							Optional[int]       =      tf.reduce_mean(_lowercase			,						0				)

          ##Node for computing Euclidean distances
          # Placeholders for input
          UpperCAmelCase_      :							Dict       =      tf.placeholder('''float'''			,						[dim]				)
          UpperCAmelCase_      :							Any       =      tf.placeholder('''float'''			,						[dim]				)
          UpperCAmelCase_      :							Dict       =      tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(_lowercase			,						_lowercase				)			,						2				)				)				)

          ##This node will figure out which cluster to assign a vector to,
          ##based on Euclidean distances of the vector from the centroids.
          # Placeholder for input
          UpperCAmelCase_      :							Tuple       =      tf.placeholder('''float'''			,						[noofclusters]				)
          UpperCAmelCase_      :							Optional[int]       =      tf.argmin(_lowercase			,						0				)

          ##INITIALIZING STATE VARIABLES

          ##This will help initialization of all Variables defined with respect
          ##to the graph. The Variable-initializer should be defined after
          ##all the Variables have been constructed, so that each of them
          ##will be included in the initialization.
          UpperCAmelCase_      :							int       =      tf.initialize_all_variables()

          # Initialize all variables
          sess.run(_lowercase				)

          ##CLUSTERING ITERATIONS

          # Now perform the Expectation-Maximization steps of K-Means clustering
          # iterations. To keep things simple, we will only do a set number of
          # iterations, instead of using a Stopping Criterion.
          UpperCAmelCase_      :							int       =      100
          for _ in range(_lowercase				):
               ##EXPECTATION STEP
               ##Based on the centroid locations till last iteration, compute
               ##the _expected_ centroid assignments.
               # Iterate over each vector
               for vector_n in range(len(_lowercase				)				):
                    UpperCAmelCase_      :							Any       =      vectors[vector_n]
                    # Compute Euclidean distance between this vector and each
                    # centroid. Remember that this list cannot be named
                    #'centroid_distances', since that is the input to the
                    # cluster assignment node.
                    UpperCAmelCase_      :							Optional[int]       =      [
                        sess.run(_lowercase			,						feed_dict={va: vect, va: sess.run(_lowercase				)}				)
                        for centroid in centroids
                    ]
                    # Now use the cluster assignment node, with the distances
                    # as the input
                    UpperCAmelCase_      :							Tuple       =      sess.run(
                        _lowercase			,						feed_dict={centroid_distances: distances}				)
                    # Now assign the value to the appropriate state variable
                    sess.run(
                        cluster_assigns[vector_n]			,						feed_dict={assignment_value: assignment}				)

               ##MAXIMIZATION STEP
               # Based on the expected state computed from the Expectation Step,
               # compute the locations of the centroids so as to maximize the
               # overall objective of minimizing within-cluster Sum-of-Squares
               for cluster_n in range(_lowercase				):
                    # Collect all the vectors assigned to this cluster
                    UpperCAmelCase_      :							str       =      [
                        vectors[i]
                        for i in range(len(_lowercase				)				)
                        if sess.run(assignments[i]				) == cluster_n
                    ]
                    # Compute new centroid location
                    UpperCAmelCase_      :							List[Any]       =      sess.run(
                        _lowercase			,						feed_dict={mean_input: array(_lowercase				)}				)
                    # Assign value to appropriate variable
                    sess.run(
                        cent_assigns[cluster_n]			,						feed_dict={centroid_value: new_location}				)

        # Return centroids and assignments
          UpperCAmelCase_      :							Any       =      sess.run(_lowercase				)
          UpperCAmelCase_      :							List[str]       =      sess.run(_lowercase				)
          return centroids, assignments





import inspect
import unittest

import numpy as np

from transformers import BeitConfig
from transformers.testing_utils import require_flax, require_vision, slow
from transformers.utils import cached_property, is_flax_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor


if is_flax_available():
     import jax

     from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel

if is_vision_available():
     from PIL import Image

     from transformers import BeitImageProcessor

class   __a(					unittest.TestCase       ):






    """simple docstring"""





    def __init__(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE=100       ,_SCREAMING_SNAKE_CASE=13       ,_SCREAMING_SNAKE_CASE=30       ,_SCREAMING_SNAKE_CASE=2       ,_SCREAMING_SNAKE_CASE=3       ,_SCREAMING_SNAKE_CASE=True       ,_SCREAMING_SNAKE_CASE=True       ,_SCREAMING_SNAKE_CASE=32       ,_SCREAMING_SNAKE_CASE=5       ,_SCREAMING_SNAKE_CASE=4       ,_SCREAMING_SNAKE_CASE=37       ,_SCREAMING_SNAKE_CASE="gelu"       ,_SCREAMING_SNAKE_CASE=0.1       ,_SCREAMING_SNAKE_CASE=0.1       ,_SCREAMING_SNAKE_CASE=10       ,_SCREAMING_SNAKE_CASE=0.02       ,_SCREAMING_SNAKE_CASE=3       ,)			->		Dict:
         UpperCAmelCase_      :							Union[str, Any]       =      parent
         UpperCAmelCase_      :							Tuple       =      vocab_size
         UpperCAmelCase_      :							List[str]       =      batch_size
         UpperCAmelCase_      :							Any       =      image_size
         UpperCAmelCase_      :							Union[str, Any]       =      patch_size
         UpperCAmelCase_      :							Union[str, Any]       =      num_channels
         UpperCAmelCase_      :							Any       =      is_training
         UpperCAmelCase_      :							Union[str, Any]       =      use_labels
         UpperCAmelCase_      :							Union[str, Any]       =      hidden_size
         UpperCAmelCase_      :							Union[str, Any]       =      num_hidden_layers
         UpperCAmelCase_      :							int       =      num_attention_heads
         UpperCAmelCase_      :							Union[str, Any]       =      intermediate_size
         UpperCAmelCase_      :							Any       =      hidden_act
         UpperCAmelCase_      :							Optional[int]       =      hidden_dropout_prob
         UpperCAmelCase_      :							List[Any]       =      attention_probs_dropout_prob
         UpperCAmelCase_      :							List[str]       =      type_sequence_label_size
         UpperCAmelCase_      :							Union[str, Any]       =      initializer_range

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





    def 							a__				(				self  )			->		str:
         UpperCAmelCase_      :							List[Any]       =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

         UpperCAmelCase_      :							Tuple       =      None
         if self.use_labels:
              UpperCAmelCase_      :							Union[str, Any]       =      ids_tensor([self.batch_size]       ,self.type_sequence_label_size  )

         UpperCAmelCase_      :							Optional[int]       =      BeitConfig(
             vocab_size=self.vocab_size       ,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       ,)

         return config, pixel_values, labels





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		Optional[Any]:
         UpperCAmelCase_      :							Union[str, Any]       =      FlaxBeitModel(config=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							List[str]       =      model(_SCREAMING_SNAKE_CASE  )
         self.parent.assertEqual(result.last_hidden_state.shape       ,(self.batch_size, self.seq_length, self.hidden_size)  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		Tuple:
         UpperCAmelCase_      :							Union[str, Any]       =      FlaxBeitForMaskedImageModeling(config=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Any       =      model(_SCREAMING_SNAKE_CASE  )
         self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.seq_length - 1, self.vocab_size)  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		str:
         UpperCAmelCase_      :							Dict       =      self.type_sequence_label_size
         UpperCAmelCase_      :							int       =      FlaxBeitForImageClassification(config=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Union[str, Any]       =      model(_SCREAMING_SNAKE_CASE  )
         self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.type_sequence_label_size)  )

         # test greyscale images
         UpperCAmelCase_      :							Any       =      1
         UpperCAmelCase_      :							List[Any]       =      FlaxBeitForImageClassification(_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							str       =      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
         UpperCAmelCase_      :							Optional[Any]       =      model(_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Optional[Any]:
         UpperCAmelCase_      :							Optional[int]       =      self.prepare_config_and_inputs()
         (
             (
             UpperCAmelCase_
         ),   (
             UpperCAmelCase_
         ),   (
             UpperCAmelCase_
         ),   
         )      :							List[str]       =      config_and_inputs
         UpperCAmelCase_      :							int       =      {'''pixel_values''': pixel_values}
         return config, inputs_dict


@require_flax
class   __a(					_a    ,						unittest.TestCase       ):






    """simple docstring"""





    lowerCAmelCase        =				(
        (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else ()
    )





    def 							a__				(				self  )			->		None:
         UpperCAmelCase_      :							List[Any]       =      FlaxBeitModelTester(self  )
         UpperCAmelCase_      :							List[str]       =      ConfigTester(self       ,config_class=_SCREAMING_SNAKE_CASE       ,has_text_modality=_SCREAMING_SNAKE_CASE       ,hidden_size=37  )





    def 							a__				(				self  )			->		Optional[int]:
         self.config_tester.run_common_tests()





    def 							a__				(				self  )			->		List[Any]:
         UpperCAmelCase_,   UpperCAmelCase_      :							Optional[Any]       =      self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              UpperCAmelCase_      :							Union[str, Any]       =      model_class(_SCREAMING_SNAKE_CASE  )
              UpperCAmelCase_      :							Union[str, Any]       =      inspect.signature(model.__call__  )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              UpperCAmelCase_      :							Optional[Any]       =      [*signature.parameters.keys()]

              UpperCAmelCase_      :							Optional[int]       =      ['''pixel_values''']
              self.assertListEqual(arg_names[:1]       ,_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Union[str, Any]:
         UpperCAmelCase_,   UpperCAmelCase_      :							Any       =      self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__  ):
                   UpperCAmelCase_      :							List[Any]       =      self._prepare_for_class(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )
                   UpperCAmelCase_      :							Union[str, Any]       =      model_class(_SCREAMING_SNAKE_CASE  )

                   @jax.jit
                   def model_jitted(_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  ):
                        return model(pixel_values=_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )

                   with self.subTest('''JIT Enabled'''  ):
                        UpperCAmelCase_      :							Dict       =      model_jitted(**_SCREAMING_SNAKE_CASE  ).to_tuple()

                   with self.subTest('''JIT Disabled'''  ):
                        with jax.disable_jit():
                             UpperCAmelCase_      :							List[str]       =      model_jitted(**_SCREAMING_SNAKE_CASE  ).to_tuple()

                   self.assertEqual(len(_SCREAMING_SNAKE_CASE  )       ,len(_SCREAMING_SNAKE_CASE  )  )
                   for jitted_output, output in zip(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
                        self.assertEqual(jitted_output.shape       ,output.shape  )





    def 							a__				(				self  )			->		List[str]:
         UpperCAmelCase_      :							Dict       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Union[str, Any]:
         UpperCAmelCase_      :							Optional[Any]       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		List[str]:
         UpperCAmelCase_      :							int       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE  )





    @slow
    def 							a__				(				self  )			->		List[Any]:
         for model_class_name in self.all_model_classes:
              UpperCAmelCase_      :							List[Any]       =      model_class_name.from_pretrained('''microsoft/beit-base-patch16-224'''  )
              UpperCAmelCase_      :							Optional[int]       =      model(np.ones((1, 3, 224, 224)  )  )
              self.assertIsNotNone(_SCREAMING_SNAKE_CASE  )







def lowerCamelCase__       (      ):

     '''simple docstring'''


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



@require_vision
@require_flax
class   __a(					unittest.TestCase       ):






    """simple docstring"""





    @cached_property
    def 							a__				(				self  )			->		Dict:
         return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224'''  ) if is_vision_available() else None





    @slow
    def 							a__				(				self  )			->		Optional[int]:
         UpperCAmelCase_      :							Tuple       =      FlaxBeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k'''  )

         UpperCAmelCase_      :							List[Any]       =      self.default_image_processor
         UpperCAmelCase_      :							Optional[Any]       =      prepare_img()
         UpperCAmelCase_      :							Optional[Any]       =      image_processor(images=_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  ).pixel_values

         # prepare bool_masked_pos
         UpperCAmelCase_      :							Union[str, Any]       =      np.ones((1, 196)       ,dtype=_SCREAMING_SNAKE_CASE  )

         # forward pass
         UpperCAmelCase_      :							Optional[int]       =      model(pixel_values=_SCREAMING_SNAKE_CASE       ,bool_masked_pos=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							List[str]       =      outputs.logits

         # verify the logits
         UpperCAmelCase_      :							List[str]       =      (1, 196, 8_192)
         self.assertEqual(logits.shape       ,_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							List[str]       =      np.array(
             [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]]  )

         self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3]       ,_SCREAMING_SNAKE_CASE       ,atol=1e-2  )  )





    @slow
    def 							a__				(				self  )			->		Union[str, Any]:
         UpperCAmelCase_      :							Any       =      FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224'''  )

         UpperCAmelCase_      :							Any       =      self.default_image_processor
         UpperCAmelCase_      :							Any       =      prepare_img()
         UpperCAmelCase_      :							Union[str, Any]       =      image_processor(images=_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  )

         # forward pass
         UpperCAmelCase_      :							Optional[Any]       =      model(**_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Optional[Any]       =      outputs.logits

         # verify the logits
         UpperCAmelCase_      :							Dict       =      (1, 1_000)
         self.assertEqual(logits.shape       ,_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Dict       =      np.array([-1.23_85, -1.09_87, -1.01_08]  )

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

         UpperCAmelCase_      :							Dict       =      281
         self.assertEqual(logits.argmax(-1  ).item()       ,_SCREAMING_SNAKE_CASE  )





    @slow
    def 							a__				(				self  )			->		Union[str, Any]:
         UpperCAmelCase_      :							str       =      FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k'''  )

         UpperCAmelCase_      :							Tuple       =      self.default_image_processor
         UpperCAmelCase_      :							Any       =      prepare_img()
         UpperCAmelCase_      :							Dict       =      image_processor(images=_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  )

         # forward pass
         UpperCAmelCase_      :							Dict       =      model(**_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Optional[Any]       =      outputs.logits

         # verify the logits
         UpperCAmelCase_      :							Union[str, Any]       =      (1, 21_841)
         self.assertEqual(logits.shape       ,_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Dict       =      np.array([1.68_81, -0.27_87, 0.59_01]  )

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

         UpperCAmelCase_      :							Dict       =      2_396
         self.assertEqual(logits.argmax(-1  ).item()       ,_SCREAMING_SNAKE_CASE  )