
"""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 						a__		( a_		):
   def __init__(     self      ,       *_a      ,       _a=None      ,       _a=None      ,       **_a							):
          super().__init__(*_a      ,       **_a							)
          lowercase       :							List[Any]									=				eval_examples
          lowercase       :							List[Any]									=				post_process_function
   def      __magic_name__     (     self      ,       _a=None      ,       _a=None      ,       _a=None      ,       _a = "eval"							):
          lowercase       :							List[str]									=				self.eval_dataset if eval_dataset is None else eval_dataset
          lowercase       :							int									=				self.get_eval_dataloader(_a							)
          lowercase       :							str									=				self.eval_examples if eval_examples is None else eval_examples

          # Temporarily disable metric computation, we will do it in the loop here.
          lowercase       :							Tuple									=				self.compute_metrics
          lowercase       :							List[str]									=				None
          lowercase       :							Union[str, Any]									=				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
          lowercase       :							Optional[int]									=				time.time()
          try:
                 lowercase       :							Dict									=				eval_loop(
                     _a      ,       description="Evaluation"      ,       prediction_loss_only=True if compute_metrics is None else None      ,       ignore_keys=_a      ,       metric_key_prefix=_a      ,       )
          finally:
                 lowercase       :							Tuple									=				compute_metrics
          lowercase       :							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 not None and self.compute_metrics is not None and self.args.should_save:
                 # Only the main node write the results by default
                 lowercase       :							List[Any]									=				self.post_process_function(_a      ,       _a      ,       output.predictions							)
                 lowercase       :							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}_"""							):
                               lowercase       :							Tuple									=				metrics.pop(_a							)
                 metrics.update(output.metrics							)
          else:
                 lowercase       :							Optional[int]									=				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()							)

          lowercase       :							int									=				self.callback_handler.on_evaluate(self.args      ,       self.state      ,       self.control      ,       _a							)
          return metrics

   def      __magic_name__     (     self      ,       _a      ,       _a      ,       _a=None      ,       _a = "test"							):
          lowercase       :							List[Any]									=				self.get_test_dataloader(_a							)

          # Temporarily disable metric computation, we will do it in the loop here.
          lowercase       :							Any									=				self.compute_metrics
          lowercase       :							int									=				None
          lowercase       :							List[Any]									=				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
          lowercase       :							Optional[int]									=				time.time()
          try:
                 lowercase       :							List[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:
                 lowercase       :							Optional[int]									=				compute_metrics
          lowercase       :							int									=				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

          lowercase       :							str									=				self.post_process_function(_a      ,       _a      ,       output.predictions      ,       "predict"							)
          lowercase       :							Optional[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}_"""							):
                        lowercase       :							str									=				metrics.pop(_a							)
          metrics.update(output.metrics							)
          return PredictionOutput(predictions=predictions.predictions      ,       label_ids=predictions.label_ids      ,       metrics=_a							)




"""simple docstring"""




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


_A     :			Optional[Any]  						=			{
    """configuration_bridgetower""": [
        """BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """BridgeTowerConfig""",
        """BridgeTowerTextConfig""",
        """BridgeTowerVisionConfig""",
    ],
    """processing_bridgetower""": ["""BridgeTowerProcessor"""],
}

try:
   if not is_vision_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A     :			Any  						=			["""BridgeTowerImageProcessor"""]

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A     :			List[Any]  						=			[
       """BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST""",
       """BridgeTowerForContrastiveLearning""",
       """BridgeTowerForImageAndTextRetrieval""",
       """BridgeTowerForMaskedLM""",
       """BridgeTowerModel""",
       """BridgeTowerPreTrainedModel""",
   ]


if TYPE_CHECKING:
   from .configuration_bridgetower import (
       BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP,
       BridgeTowerConfig,
       BridgeTowerTextConfig,
       BridgeTowerVisionConfig,
   )
   from .processing_bridgetower import BridgeTowerProcessor

   try:
      if not is_vision_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .image_processing_bridgetower import BridgeTowerImageProcessor

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_bridgetower import (
          BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST,
          BridgeTowerForContrastiveLearning,
          BridgeTowerForImageAndTextRetrieval,
          BridgeTowerForMaskedLM,
          BridgeTowerModel,
          BridgeTowerPreTrainedModel,
      )


else:
   import sys

   _A     :			Any  						=			_LazyModule(__name__, globals()["""__file__"""], _import_structure)


