




import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
     import torch_xla.core.xla_model as xm
     import torch_xla.debug.metrics as met

class   __a(					_a       ):






    """simple docstring"""





    def __init__(				self       ,*_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,**_SCREAMING_SNAKE_CASE  )			->		Optional[Any]:
         super().__init__(*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Any       =      eval_examples
         UpperCAmelCase_      :							int       =      post_process_function





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE = "eval"  )			->		Optional[int]:
         UpperCAmelCase_      :							Union[str, Any]       =      self.eval_dataset if eval_dataset is None else eval_dataset
         UpperCAmelCase_      :							Optional[int]       =      self.get_eval_dataloader(_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Optional[int]       =      self.eval_examples if eval_examples is None else eval_examples

         # Temporarily disable metric computation, we will do it in the loop here.
         UpperCAmelCase_      :							Tuple       =      self.compute_metrics
         UpperCAmelCase_      :							List[str]       =      None
         UpperCAmelCase_      :							str       =      self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         UpperCAmelCase_      :							List[str]       =      time.time()
         try:
              UpperCAmelCase_      :							List[Any]       =      eval_loop(
                  _SCREAMING_SNAKE_CASE       ,description='''Evaluation'''       ,prediction_loss_only=True if compute_metrics is None else None       ,ignore_keys=_SCREAMING_SNAKE_CASE       ,metric_key_prefix=_SCREAMING_SNAKE_CASE       ,)
         finally:
              UpperCAmelCase_      :							List[Any]       =      compute_metrics
         UpperCAmelCase_      :							str       =      self.args.eval_batch_size * self.args.world_size
         if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
              start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
         output.metrics.update(
             speed_metrics(
                 _SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,num_samples=output.num_samples       ,num_steps=math.ceil(output.num_samples / total_batch_size  )       ,)  )
         if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
              # Only the main node write the results by default
              UpperCAmelCase_      :							List[Any]       =      self.post_process_function(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,output.predictions  )
              UpperCAmelCase_      :							List[str]       =      self.compute_metrics(_SCREAMING_SNAKE_CASE  )

              # Prefix all keys with metric_key_prefix + '_'
              for key in list(metrics.keys()  ):
                   if not key.startswith(f'''{metric_key_prefix}_'''  ):
                        UpperCAmelCase_      :							str       =      metrics.pop(_SCREAMING_SNAKE_CASE  )
              metrics.update(output.metrics  )
         else:
              UpperCAmelCase_      :							Dict       =      output.metrics

         if self.args.should_log:
              # Only the main node log the results by default
              self.log(_SCREAMING_SNAKE_CASE  )

         if self.args.tpu_metrics_debug or self.args.debug:
              # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
              xm.master_print(met.metrics_report()  )

         UpperCAmelCase_      :							Any       =      self.callback_handler.on_evaluate(self.args       ,self.state       ,self.control       ,_SCREAMING_SNAKE_CASE  )
         return metrics





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE = "test"  )			->		Tuple:
         UpperCAmelCase_      :							Any       =      self.get_test_dataloader(_SCREAMING_SNAKE_CASE  )

         # Temporarily disable metric computation, we will do it in the loop here.
         UpperCAmelCase_      :							Tuple       =      self.compute_metrics
         UpperCAmelCase_      :							str       =      None
         UpperCAmelCase_      :							List[str]       =      self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         UpperCAmelCase_      :							List[str]       =      time.time()
         try:
              UpperCAmelCase_      :							Optional[int]       =      eval_loop(
                  _SCREAMING_SNAKE_CASE       ,description='''Prediction'''       ,prediction_loss_only=True if compute_metrics is None else None       ,ignore_keys=_SCREAMING_SNAKE_CASE       ,metric_key_prefix=_SCREAMING_SNAKE_CASE       ,)
         finally:
              UpperCAmelCase_      :							List[str]       =      compute_metrics
         UpperCAmelCase_      :							List[str]       =      self.args.eval_batch_size * self.args.world_size
         if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
              start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
         output.metrics.update(
             speed_metrics(
                 _SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,num_samples=output.num_samples       ,num_steps=math.ceil(output.num_samples / total_batch_size  )       ,)  )

         if self.post_process_function is None or self.compute_metrics is None:
              return output

         UpperCAmelCase_      :							Optional[Any]       =      self.post_process_function(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,output.predictions       ,'''predict'''  )
         UpperCAmelCase_      :							str       =      self.compute_metrics(_SCREAMING_SNAKE_CASE  )

         # Prefix all keys with metric_key_prefix + '_'
         for key in list(metrics.keys()  ):
              if not key.startswith(f'''{metric_key_prefix}_'''  ):
                   UpperCAmelCase_      :							Optional[Any]       =      metrics.pop(_SCREAMING_SNAKE_CASE  )
         metrics.update(output.metrics  )
         return PredictionOutput(predictions=predictions.predictions       ,label_ids=predictions.label_ids       ,metrics=_SCREAMING_SNAKE_CASE  )





from random import shuffle

import tensorflow as tf
from numpy import array







def lowerCamelCase__       (      _lowercase			,						_lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							Union[str, Any]       =      int(_lowercase				)
     assert noofclusters < len(_lowercase				)

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

     # Will help select random centroids from among the available vectors
     UpperCAmelCase_      :							Optional[int]       =      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_      :							List[str]       =      tf.Graph()

     with graph.as_default():
          # SESSION OF COMPUTATION

          UpperCAmelCase_      :							Tuple       =      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_      :							str       =      [
              tf.Variable(vectors[vector_indices[i]]				) for i in range(_lowercase				)
          ]
          ##These nodes will assign the centroid Variables the appropriate
          ##values
          UpperCAmelCase_      :							List[Any]       =      tf.placeholder('''float64'''			,						[dim]				)
          UpperCAmelCase_      :							List[Any]       =      []
          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[int]       =      [tf.Variable(0				) for i in range(len(_lowercase				)				)]
          ##These nodes will assign an assignment Variable the appropriate
          ##value
          UpperCAmelCase_      :							List[Any]       =      tf.placeholder('''int32'''				)
          UpperCAmelCase_      :							Union[str, Any]       =      []
          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_      :							Tuple       =      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_      :							str       =      tf.reduce_mean(_lowercase			,						0				)

          ##Node for computing Euclidean distances
          # Placeholders for input
          UpperCAmelCase_      :							List[Any]       =      tf.placeholder('''float'''			,						[dim]				)
          UpperCAmelCase_      :							Tuple       =      tf.placeholder('''float'''			,						[dim]				)
          UpperCAmelCase_      :							Optional[Any]       =      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_      :							int       =      tf.placeholder('''float'''			,						[noofclusters]				)
          UpperCAmelCase_      :							Any       =      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_      :							List[Any]       =      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_      :							Tuple       =      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_      :							Optional[int]       =      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_      :							Tuple       =      [
                        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_      :							Dict       =      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_      :							List[str]       =      [
                        vectors[i]
                        for i in range(len(_lowercase				)				)
                        if sess.run(assignments[i]				) == cluster_n
                    ]
                    # Compute new centroid location
                    UpperCAmelCase_      :							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_      :							Optional[int]       =      sess.run(_lowercase				)
          UpperCAmelCase_      :							int       =      sess.run(_lowercase				)
          return centroids, assignments