


'''simple docstring'''


import inspect
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
_UpperCamelCase 							=  """src/transformers"""


# This is to make sure the transformers module imported is the one in the repo.
_UpperCamelCase 							=  direct_transformers_import(PATH_TO_TRANSFORMERS)

_UpperCamelCase 							=  transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
_UpperCamelCase 							=  re.compile(r"""\[(.+?)\]\((https://huggingface\.co/.+?)\)""")


_UpperCamelCase 							=  {
    """DecisionTransformerConfig""",
    """EncoderDecoderConfig""",
    """MusicgenConfig""",
    """RagConfig""",
    """SpeechEncoderDecoderConfig""",
    """TimmBackboneConfig""",
    """VisionEncoderDecoderConfig""",
    """VisionTextDualEncoderConfig""",
    """LlamaConfig""",
}


def 		_lowercase (SCREAMING_SNAKE_CASE							):




     '''simple docstring'''





     __A	:       Tuple      =							None

     # source code of `config_class`
     __A	:       List[Any]      =							inspect.getsource(SCREAMING_SNAKE_CASE							)
     __A	:       Any      =							_re_checkpoint.findall(SCREAMING_SNAKE_CASE							)

     # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
     # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
     for ckpt_name, ckpt_link in checkpoints:
          # allow the link to end with `/`
          if ckpt_link.endswith("/"							):
               __A	:       Dict      =							ckpt_link[:-1]

          # verify the checkpoint name corresponds to the checkpoint link
          __A	:       List[Any]      =							f"https://huggingface.co/{ckpt_name}"
          if ckpt_link == ckpt_link_from_name:
               __A	:       Optional[int]      =							ckpt_name
               break

     return checkpoint


def 		_lowercase ():




     '''simple docstring'''





     __A	:       List[Any]      =							[]

     for config_class in list(CONFIG_MAPPING.values()							):
          # Skip deprecated models
          if "models.deprecated" in config_class.__module__:
               continue
          __A	:       int      =							get_checkpoint_from_config_class(SCREAMING_SNAKE_CASE							)

          __A	:       str      =							config_class.__name__
          if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
               configs_without_checkpoint.append(SCREAMING_SNAKE_CASE							)

     if len(SCREAMING_SNAKE_CASE							) > 0:
          __A	:       Optional[int]      =							"\n".join(sorted(SCREAMING_SNAKE_CASE							)							)
          raise ValueError(f"The following configurations don't contain any valid checkpoint:\n{message}"							)


if __name__ == "__main__":
      check_config_docstrings_have_checkpoints()





'''simple docstring'''


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 							__magic_name__	(       lowerCAmelCase ):

     """simple docstring"""






     def __init__(   self			,     *lowerCamelCase			,     lowerCamelCase=None			,     lowerCamelCase=None			,     **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(*lowerCamelCase			,     **lowerCamelCase		)
          __A	:       Tuple      =							eval_examples
          __A	:       List[str]      =							post_process_function


     def lowerCAmelCase__  (   self			,     lowerCamelCase=None			,     lowerCamelCase=None			,     lowerCamelCase=None			,     lowerCamelCase = "eval"		):


          '''simple docstring'''





          __A	:       Any      =							self.eval_dataset if eval_dataset is None else eval_dataset
          __A	:       Dict      =							self.get_eval_dataloader(lowerCamelCase		)
          __A	:       str      =							self.eval_examples if eval_examples is None else eval_examples

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

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

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

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

          __A	:       str      =							self.callback_handler.on_evaluate(self.args			,     self.state			,     self.control			,     lowerCamelCase		)
          return metrics


     def lowerCAmelCase__  (   self			,     lowerCamelCase			,     lowerCamelCase			,     lowerCamelCase=None			,     lowerCamelCase = "test"		):


          '''simple docstring'''





          __A	:       Tuple      =							self.get_test_dataloader(lowerCamelCase		)

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

          __A	:       Dict      =							self.post_process_function(lowerCamelCase			,     lowerCamelCase			,     output.predictions			,     "predict"		)
          __A	:       Tuple      =							self.compute_metrics(lowerCamelCase		)

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

