





import argparse
import os
import re


__UpperCAmelCase	:       Any    	=							"src/transformers/models/auto"


# re pattern that matches mapping introductions:
#    SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict
__UpperCAmelCase	:       List[str]    	=							re.compile(R"[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict")
# re pattern that matches identifiers in mappings
__UpperCAmelCase	:       Dict    	=							re.compile(R"\s*\(\s*\"(\S[^\"]+)\"")







def       A__							(   SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False)       ->   int:
  with open(SCREAMING_SNAKE_CASE__ , """r""" , encoding="""utf-8""") as f:
    __snake_case:						Any			  =						f.read()

  __snake_case:						str			  =						content.split("""\n""")
  __snake_case:						List[Any]			  =						[]
  __snake_case:						Any			  =						0
  while line_idx < len(SCREAMING_SNAKE_CASE__):
    if _re_intro_mapping.search(lines[line_idx]) is not None:
      __snake_case:						int			  =						len(re.search(r"""^(\s*)\S""" , lines[line_idx]).groups()[0]) + 8
      # Start of a new mapping!
      while not lines[line_idx].startswith(""" """ * indent + """("""):
        new_lines.append(lines[line_idx])
        line_idx += 1

      __snake_case:						int			  =						[]
      while lines[line_idx].strip() != "]":
        # Blocks either fit in one line or not
        if lines[line_idx].strip() == "(":
          __snake_case:						str			  =						line_idx
          while not lines[line_idx].startswith(""" """ * indent + """)"""):
            line_idx += 1
          blocks.append("""\n""".join(lines[start_idx : line_idx + 1]))
        else:
          blocks.append(lines[line_idx])
        line_idx += 1

      # Sort blocks by their identifiers
      __snake_case:						str			  =						sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__: _re_identifier.search(SCREAMING_SNAKE_CASE__).groups()[0])
      new_lines += blocks
    else:
      new_lines.append(lines[line_idx])
      line_idx += 1

  if overwrite:
    with open(SCREAMING_SNAKE_CASE__ , """w""" , encoding="""utf-8""") as f:
      f.write("""\n""".join(SCREAMING_SNAKE_CASE__))
  elif "\n".join(SCREAMING_SNAKE_CASE__) != content:
    return True







def       A__							(   SCREAMING_SNAKE_CASE__ = False)       ->   int:
  __snake_case:						Union[str, Any]			  =						[os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) for f in os.listdir(SCREAMING_SNAKE_CASE__) if f.endswith(""".py""")]
  __snake_case:						Optional[int]			  =						[sort_auto_mapping(SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__) for fname in fnames]

  if not overwrite and any(SCREAMING_SNAKE_CASE__):
    __snake_case:						int			  =						[f for f, d in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) if d]
    raise ValueError(
        F'''The following files have auto mappings that need sorting: {', '.join(SCREAMING_SNAKE_CASE__)}. Run `make style` to fix'''
        """ this.""")


if __name__ == "__main__":
      __UpperCAmelCase	:       int    	=							argparse.ArgumentParser()
      parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.")
      __UpperCAmelCase	:       int    	=							parser.parse_args()

      sort_all_auto_mappings(not args.check_only)













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    __snake_case	(							__lowerCamelCase      ):





       '''simple docstring'''







       def __init__(  self			:   str							,    *A			:   Dict							,    A			:   Optional[int]=None							,    A			:   Tuple=None							,    **A			:   Optional[int]		):
         super().__init__(*A							,    **A		)
         __snake_case:						List[Any]			  =						eval_examples
         __snake_case:						str			  =						post_process_function




       def 							UpperCAmelCase__			(  self			:   List[Any]							,    A			:   Dict=None							,    A			:   int=None							,    A			:   List[Any]=None							,    A			:   str = "eval"		):
         __snake_case:						int			  =						self.eval_dataset if eval_dataset is None else eval_dataset
         __snake_case:						Any			  =						self.get_eval_dataloader(A		)
         __snake_case:						Optional[Any]			  =						self.eval_examples if eval_examples is None else eval_examples

         # Temporarily disable metric computation, we will do it in the loop here.
         __snake_case:						Union[str, Any]			  =						self.compute_metrics
         __snake_case:						List[str]			  =						None
         __snake_case:						Tuple			  =						self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __snake_case:						Tuple			  =						time.time()
         try:
           __snake_case:						Any			  =						eval_loop(
               A							,    description="""Evaluation"""							,    prediction_loss_only=True if compute_metrics is None else None							,    ignore_keys=A							,    metric_key_prefix=A							,    )
         finally:
           __snake_case:						Optional[int]			  =						compute_metrics
         __snake_case:						Union[str, Any]			  =						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(
                 A							,    A							,    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
           __snake_case:						List[str]			  =						self.post_process_function(A							,    A							,    output.predictions		)
           __snake_case:						List[Any]			  =						self.compute_metrics(A		)

           # Prefix all keys with metric_key_prefix + '_'
           for key in list(metrics.keys()		):
             if not key.startswith(f'''{metric_key_prefix}_'''		):
               __snake_case:						str			  =						metrics.pop(A		)
           metrics.update(output.metrics		)
         else:
           __snake_case:						List[Any]			  =						output.metrics

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

         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()		)

         __snake_case:						str			  =						self.callback_handler.on_evaluate(self.args							,    self.state							,    self.control							,    A		)
         return metrics






       def 							UpperCAmelCase__			(  self			:   Optional[Any]							,    A			:   List[Any]							,    A			:   List[str]							,    A			:   str=None							,    A			:   str = "test"		):
         __snake_case:						Optional[Any]			  =						self.get_test_dataloader(A		)

         # Temporarily disable metric computation, we will do it in the loop here.
         __snake_case:						Optional[int]			  =						self.compute_metrics
         __snake_case:						List[Any]			  =						None
         __snake_case:						str			  =						self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __snake_case:						Dict			  =						time.time()
         try:
           __snake_case:						str			  =						eval_loop(
               A							,    description="""Prediction"""							,    prediction_loss_only=True if compute_metrics is None else None							,    ignore_keys=A							,    metric_key_prefix=A							,    )
         finally:
           __snake_case:						List[Any]			  =						compute_metrics
         __snake_case:						Dict			  =						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(
                 A							,    A							,    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

         __snake_case:						Union[str, Any]			  =						self.post_process_function(A							,    A							,    output.predictions							,    """predict"""		)
         __snake_case:						str			  =						self.compute_metrics(A		)

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






