






"""simple docstring"""





import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, 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      _lowercase (     lowerCAmelCase						):


      def __init__(    self				:	Union[str, Any]							,   *a				:	Tuple							,   a				:	List[Any]=None							,   a				:	List[str]=None							,   **a				:	Optional[Any]						):





            """simple docstring"""







            super().__init__(*a							,   **a						)
            __snake_case      :    Any  			=eval_examples
            __snake_case      :    Tuple  			=post_process_function


      def _UpperCamelCase						(    self				:	Optional[Any]							,   a				:	Optional[Dataset] = None							,   a				:	Optional[int]=None							,   a				:	Optional[List[str]] = None							,   a				:	str = "eval"							,   **a				:	Tuple							,   ):





            """simple docstring"""







            __snake_case      :    Any  			=gen_kwargs.copy()
            __snake_case      :    Union[str, Any]  			=(
                gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length'''						) is not None else self.args.generation_max_length
            )
            __snake_case      :    str  			=(
                gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams'''						) is not None else self.args.generation_num_beams
            )
            __snake_case      :    Optional[Any]  			=gen_kwargs

            __snake_case      :    Tuple  			=self.eval_dataset if eval_dataset is None else eval_dataset
            __snake_case      :    str  			=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      :    List[Any]  			=self.compute_metrics
            __snake_case      :    List[Any]  			=None
            __snake_case      :    Union[str, Any]  			=time.time()
            __snake_case      :    Union[str, Any]  			=self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
            try:
                  __snake_case      :    str  			=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      :    List[str]  			=compute_metrics
            __snake_case      :    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(
                    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      :    int  			=self.post_process_function(a							,   a							,   a						)
                  __snake_case      :    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}_'''						):
                              __snake_case      :    Optional[int]  			=metrics.pop(a						)

                  metrics.update(output.metrics						)
            else:
                  __snake_case      :    Dict  			=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      :    List[str]  			=self.callback_handler.on_evaluate(self.args							,   self.state							,   self.control							,   a						)
            return metrics







      def _UpperCamelCase						(    self				:	Optional[Any]							,   a				:	Any							,   a				:	Union[str, Any]							,   a				:	List[str]=None							,   a				:	str = "test"							,   **a				:	str						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=gen_kwargs.copy()

            __snake_case      :    List[Any]  			=self.get_test_dataloader(a						)

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

            __snake_case      :    Tuple  			=self.post_process_function(a							,   a							,   a							,   '''predict'''						)
            __snake_case      :    Dict  			=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      :    Optional[Any]  			=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_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


UpperCamelCase_	:				str										= {"""processing_layoutxlm""": ["""LayoutXLMProcessor"""]}

try:
    if not is_sentencepiece_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCamelCase_	:				Union[str, Any]										= ["""LayoutXLMTokenizer"""]

try:
    if not is_tokenizers_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCamelCase_	:				Optional[int]										= ["""LayoutXLMTokenizerFast"""]

if TYPE_CHECKING:
    from .processing_layoutxlm import LayoutXLMProcessor

    try:
        if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_layoutxlm import LayoutXLMTokenizer

    try:
        if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast

else:
    import sys

    UpperCamelCase_	:				List[Any]										= _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


