



"""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   lowerCAmelCase_    (			__lowerCAmelCase					):



				"""simple docstring"""

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






										"""simple docstring"""

										super().__init__(*lowerCAmelCase_		,    **lowerCAmelCase_    )
										snake_case								=			eval_examples
										snake_case								=			post_process_function

				def 		snake_case (				self		,    lowerCAmelCase=None		,    lowerCAmelCase=None		,    lowerCAmelCase=None		,    lowerCAmelCase = "eval"    ):






										"""simple docstring"""

										snake_case								=			self.eval_dataset if eval_dataset is None else eval_dataset
										snake_case								=			self.get_eval_dataloader(lowerCAmelCase_    )
										snake_case								=			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								=			self.compute_metrics
										snake_case								=			None
										snake_case								=			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
										snake_case								=			time.time()
										try:
																snake_case								=			eval_loop(
																    lowerCAmelCase_		,    description='Evaluation'		,    prediction_loss_only=True if compute_metrics is None else None		,    ignore_keys=lowerCAmelCase_		,    metric_key_prefix=lowerCAmelCase_		,    )
										finally:
																snake_case								=			compute_metrics
										snake_case								=			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
																snake_case								=			self.post_process_function(lowerCAmelCase_		,    lowerCAmelCase_		,    output.predictions    )
																snake_case								=			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}_"""    ):
																												snake_case								=			metrics.pop(lowerCAmelCase_    )
																metrics.update(output.metrics    )
										else:
																snake_case								=			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()    )

										snake_case								=			self.callback_handler.on_evaluate(self.args		,    self.state		,    self.control		,    lowerCAmelCase_    )
										return metrics

				def 		snake_case (				self		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase=None		,    lowerCAmelCase = "test"    ):






										"""simple docstring"""

										snake_case								=			self.get_test_dataloader(lowerCAmelCase_    )

										# Temporarily disable metric computation, we will do it in the loop here.
										snake_case								=			self.compute_metrics
										snake_case								=			None
										snake_case								=			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
										snake_case								=			time.time()
										try:
																snake_case								=			eval_loop(
																    lowerCAmelCase_		,    description='Prediction'		,    prediction_loss_only=True if compute_metrics is None else None		,    ignore_keys=lowerCAmelCase_		,    metric_key_prefix=lowerCAmelCase_		,    )
										finally:
																snake_case								=			compute_metrics
										snake_case								=			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

										snake_case								=			self.post_process_function(lowerCAmelCase_		,    lowerCAmelCase_		,    output.predictions		,    'predict'    )
										snake_case								=			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}_"""    ):
																						snake_case								=			metrics.pop(lowerCAmelCase_    )
										metrics.update(output.metrics    )
										return PredictionOutput(predictions=predictions.predictions		,    label_ids=predictions.label_ids		,    metrics=lowerCAmelCase_    )



"""simple docstring"""
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


if TYPE_CHECKING:
					from ...processing_utils import ProcessorMixin
					from ...utils import TensorType


SCREAMING_SNAKE_CASE__      						=  logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__      						=  {
    "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json",
}



class   lowerCAmelCase_    (			lowerCAmelCase					):



				"""simple docstring"""
				_lowerCAmelCase     :    Dict			  =						"""layoutlmv3"""

				def __init__(				self		,    lowerCAmelCase=5_02_65		,    lowerCAmelCase=7_68		,    lowerCAmelCase=12		,    lowerCAmelCase=12		,    lowerCAmelCase=30_72		,    lowerCAmelCase="gelu"		,    lowerCAmelCase=0.1		,    lowerCAmelCase=0.1		,    lowerCAmelCase=5_12		,    lowerCAmelCase=2		,    lowerCAmelCase=0.02		,    lowerCAmelCase=1E-5		,    lowerCAmelCase=1		,    lowerCAmelCase=0		,    lowerCAmelCase=2		,    lowerCAmelCase=10_24		,    lowerCAmelCase=1_28		,    lowerCAmelCase=1_28		,    lowerCAmelCase=True		,    lowerCAmelCase=32		,    lowerCAmelCase=1_28		,    lowerCAmelCase=64		,    lowerCAmelCase=2_56		,    lowerCAmelCase=True		,    lowerCAmelCase=True		,    lowerCAmelCase=True		,    lowerCAmelCase=2_24		,    lowerCAmelCase=3		,    lowerCAmelCase=16		,    lowerCAmelCase=None		,    **lowerCAmelCase		,    ):






										"""simple docstring"""

										super().__init__(
										    vocab_size=lowerCAmelCase		,    hidden_size=lowerCAmelCase		,    num_hidden_layers=lowerCAmelCase		,    num_attention_heads=lowerCAmelCase		,    intermediate_size=lowerCAmelCase		,    hidden_act=lowerCAmelCase		,    hidden_dropout_prob=lowerCAmelCase		,    attention_probs_dropout_prob=lowerCAmelCase		,    max_position_embeddings=lowerCAmelCase		,    type_vocab_size=lowerCAmelCase		,    initializer_range=lowerCAmelCase		,    layer_norm_eps=lowerCAmelCase		,    pad_token_id=lowerCAmelCase		,    bos_token_id=lowerCAmelCase		,    eos_token_id=lowerCAmelCase		,    **lowerCAmelCase		,    )
										snake_case								=			max_ad_position_embeddings
										snake_case								=			coordinate_size
										snake_case								=			shape_size
										snake_case								=			has_relative_attention_bias
										snake_case								=			rel_pos_bins
										snake_case								=			max_rel_pos
										snake_case								=			has_spatial_attention_bias
										snake_case								=			rel_ad_pos_bins
										snake_case								=			max_rel_ad_pos
										snake_case								=			text_embed
										snake_case								=			visual_embed
										snake_case								=			input_size
										snake_case								=			num_channels
										snake_case								=			patch_size
										snake_case								=			classifier_dropout





class   lowerCAmelCase_    (			lowerCAmelCase					):



				"""simple docstring"""
				_lowerCAmelCase     :    List[str]			  =						version.parse("""1.12"""					)

				@property
				def 		snake_case (				self    ):






										"""simple docstring"""

										if self.task in ["question-answering", "sequence-classification"]:
																return OrderedDict(
																    [
																        ('input_ids', {0: 'batch', 1: 'sequence'}),
																        ('attention_mask', {0: 'batch', 1: 'sequence'}),
																        ('bbox', {0: 'batch', 1: 'sequence'}),
																        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
																    ]    )
										else:
																return OrderedDict(
																    [
																        ('input_ids', {0: 'batch', 1: 'sequence'}),
																        ('bbox', {0: 'batch', 1: 'sequence'}),
																        ('attention_mask', {0: 'batch', 1: 'sequence'}),
																        ('pixel_values', {0: 'batch', 1: 'num_channels'}),
																    ]    )

				@property
				def 		snake_case (				self    ):






										"""simple docstring"""

										return 1E-5

				@property
				def 		snake_case (				self    ):






										"""simple docstring"""

										return 12

				def 		snake_case (				self		,    lowerCAmelCase		,    lowerCAmelCase = -1		,    lowerCAmelCase = -1		,    lowerCAmelCase = False		,    lowerCAmelCase = None		,    lowerCAmelCase = 3		,    lowerCAmelCase = 40		,    lowerCAmelCase = 40		,    ):






										"""simple docstring"""

										setattr(processor.image_processor		,    'apply_ocr'		,    lowerCAmelCase    )

										# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
										snake_case								=			compute_effective_axis_dimension(
										    lowerCAmelCase		,    fixed_dimension=OnnxConfig.default_fixed_batch		,    num_token_to_add=0    )
										# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
										snake_case								=			processor.tokenizer.num_special_tokens_to_add(lowerCAmelCase    )
										snake_case								=			compute_effective_axis_dimension(
										    lowerCAmelCase		,    fixed_dimension=OnnxConfig.default_fixed_sequence		,    num_token_to_add=lowerCAmelCase    )
										# Generate dummy inputs according to compute batch and sequence
										snake_case								=			[[' '.join([processor.tokenizer.unk_token]    ) * seq_length]] * batch_size

										# Generate dummy bounding boxes
										snake_case								=			[[[48, 84, 73, 1_28]]] * batch_size

										# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
										# batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
										snake_case								=			self._generate_dummy_images(lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )

										snake_case								=			dict(
										    processor(
										        lowerCAmelCase		,    text=lowerCAmelCase		,    boxes=lowerCAmelCase		,    return_tensors=lowerCAmelCase		,    )    )

										return inputs


