






import argparse
from collections import OrderedDict
from pathlib import Path

import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from torchvision.transforms import functional as F

from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection
from transformers.utils import logging


logging.set_verbosity_info()
A        =			logging.get_logger(__name__)

# here we list all keys to be renamed (original name on the left, our name on the right)
A        =			[]
for i in range(6):
				# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
				rename_keys.append(
				    (f"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", f"""encoder.layers.{i}.self_attn.out_proj.weight""")
				)
				rename_keys.append(
				    (f"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", f"""encoder.layers.{i}.self_attn.out_proj.bias""")
				)
				rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""encoder.layers.{i}.fc1.weight"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""encoder.layers.{i}.fc1.bias"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""encoder.layers.{i}.fc2.weight"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""encoder.layers.{i}.fc2.bias"""))
				rename_keys.append(
				    (f"""transformer.encoder.layers.{i}.norm1.weight""", f"""encoder.layers.{i}.self_attn_layer_norm.weight""")
				)
				rename_keys.append((f"""transformer.encoder.layers.{i}.norm1.bias""", f"""encoder.layers.{i}.self_attn_layer_norm.bias"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.weight""", f"""encoder.layers.{i}.final_layer_norm.weight"""))
				rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""encoder.layers.{i}.final_layer_norm.bias"""))
				# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", f"""decoder.layers.{i}.self_attn.out_proj.weight""")
				)
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""decoder.layers.{i}.self_attn.out_proj.bias""")
				)
				rename_keys.append(
				    (
				        f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""",
				        f"""decoder.layers.{i}.encoder_attn.out_proj.weight""",
				    )
				)
				rename_keys.append(
				    (
				        f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""",
				        f"""decoder.layers.{i}.encoder_attn.out_proj.bias""",
				    )
				)
				rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""decoder.layers.{i}.fc1.weight"""))
				rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""decoder.layers.{i}.fc1.bias"""))
				rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""decoder.layers.{i}.fc2.weight"""))
				rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""decoder.layers.{i}.fc2.bias"""))
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.norm1.weight""", f"""decoder.layers.{i}.self_attn_layer_norm.weight""")
				)
				rename_keys.append((f"""transformer.decoder.layers.{i}.norm1.bias""", f"""decoder.layers.{i}.self_attn_layer_norm.bias"""))
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.norm2.weight""", f"""decoder.layers.{i}.encoder_attn_layer_norm.weight""")
				)
				rename_keys.append(
				    (f"""transformer.decoder.layers.{i}.norm2.bias""", f"""decoder.layers.{i}.encoder_attn_layer_norm.bias""")
				)
				rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.weight""", f"""decoder.layers.{i}.final_layer_norm.weight"""))
				rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""decoder.layers.{i}.final_layer_norm.bias"""))

# convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads
rename_keys.extend(
    [
        ('input_proj.weight', 'input_projection.weight'),
        ('input_proj.bias', 'input_projection.bias'),
        ('query_embed.weight', 'query_position_embeddings.weight'),
        ('transformer.encoder.norm.weight', 'encoder.layernorm.weight'),
        ('transformer.encoder.norm.bias', 'encoder.layernorm.bias'),
        ('transformer.decoder.norm.weight', 'decoder.layernorm.weight'),
        ('transformer.decoder.norm.bias', 'decoder.layernorm.bias'),
        ('class_embed.weight', 'class_labels_classifier.weight'),
        ('class_embed.bias', 'class_labels_classifier.bias'),
        ('bbox_embed.layers.0.weight', 'bbox_predictor.layers.0.weight'),
        ('bbox_embed.layers.0.bias', 'bbox_predictor.layers.0.bias'),
        ('bbox_embed.layers.1.weight', 'bbox_predictor.layers.1.weight'),
        ('bbox_embed.layers.1.bias', 'bbox_predictor.layers.1.bias'),
        ('bbox_embed.layers.2.weight', 'bbox_predictor.layers.2.weight'),
        ('bbox_embed.layers.2.bias', 'bbox_predictor.layers.2.bias'),
    ]
)



def 					_lowerCamelCase(			lowerCAmelCase__				:		int    ,    lowerCAmelCase__				:		Tuple    ,    lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   state_dict.pop(lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   val



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	List[str]													=   OrderedDict()
				for key, value in state_dict.items():
								if "backbone.0.body" in key:
												SCREAMING_SNAKE_CASE_   :	Dict													=   key.replace('backbone.0.body'    ,    'backbone.conv_encoder.model'      )
												SCREAMING_SNAKE_CASE_   :	List[str]													=   value
								else:
												SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   value

				return new_state_dict



def 					_lowerCamelCase(			lowerCAmelCase__				:		str      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   ''

				# first: transformer encoder
				for i in range(6      ):
								# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
								SCREAMING_SNAKE_CASE_   :	Dict													=   state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight'''      )
								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias'''      )
								# next, add query, keys and values (in that order) to the state dict
								SCREAMING_SNAKE_CASE_   :	List[str]													=   in_proj_weight[:256, :]
								SCREAMING_SNAKE_CASE_   :	Dict													=   in_proj_bias[:256]
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   in_proj_weight[256:512, :]
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   in_proj_bias[256:512]
								SCREAMING_SNAKE_CASE_   :	Any													=   in_proj_weight[-256:, :]
								SCREAMING_SNAKE_CASE_   :	Any													=   in_proj_bias[-256:]
				# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
				for i in range(6      ):
								# read in weights + bias of input projection layer of self-attention
								SCREAMING_SNAKE_CASE_   :	List[str]													=   state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight'''      )
								SCREAMING_SNAKE_CASE_   :	int													=   state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias'''      )
								# next, add query, keys and values (in that order) to the state dict
								SCREAMING_SNAKE_CASE_   :	Dict													=   in_proj_weight[:256, :]
								SCREAMING_SNAKE_CASE_   :	str													=   in_proj_bias[:256]
								SCREAMING_SNAKE_CASE_   :	int													=   in_proj_weight[256:512, :]
								SCREAMING_SNAKE_CASE_   :	int													=   in_proj_bias[256:512]
								SCREAMING_SNAKE_CASE_   :	Dict													=   in_proj_weight[-256:, :]
								SCREAMING_SNAKE_CASE_   :	str													=   in_proj_bias[-256:]
								# read in weights + bias of input projection layer of cross-attention
								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   state_dict.pop(
								    F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight'''      )
								SCREAMING_SNAKE_CASE_   :	Any													=   state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias'''      )
								# next, add query, keys and values (in that order) of cross-attention to the state dict
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   in_proj_weight_cross_attn[:256, :]
								SCREAMING_SNAKE_CASE_   :	str													=   in_proj_bias_cross_attn[:256]
								SCREAMING_SNAKE_CASE_   :	Any													=   in_proj_weight_cross_attn[256:512, :]
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   in_proj_bias_cross_attn[256:512]
								SCREAMING_SNAKE_CASE_   :	Tuple													=   in_proj_weight_cross_attn[-256:, :]
								SCREAMING_SNAKE_CASE_   :	List[Any]													=   in_proj_bias_cross_attn[-256:]



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[str]    ,    lowerCAmelCase__				:		Optional[int]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Any													=   image.size
				SCREAMING_SNAKE_CASE_   :	Tuple													=   max(lowerCAmelCase__    ,    lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	int													=   800 if 'detection' in checkpoint_url else 1000
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   target_max_size / current_max_size
				SCREAMING_SNAKE_CASE_   :	Tuple													=   image.resize((int(round(scale * width      )      ), int(round(scale * height      )      ))      )

				return resized_image



def 					_lowerCamelCase(			lowerCAmelCase__				:		Tuple      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	str													=   F.to_tensor(lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   F.normalize(lowerCAmelCase__    ,    mean=[0.485, 0.456, 0.406]    ,    std=[0.229, 0.224, 0.225]      )
				return image



@torch.no_grad()
def 					_lowerCamelCase(			lowerCAmelCase__				:		Optional[Any]    ,    lowerCAmelCase__				:		str    ,    lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				logger.info('Converting model...'      )

				# load original state dict
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   torch.hub.load_state_dict_from_url(lowerCAmelCase__    ,    map_location='cpu'      )
				# rename keys
				for src, dest in rename_keys:
								rename_key(lowerCAmelCase__    ,    lowerCAmelCase__    ,    lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   rename_backbone_keys(lowerCAmelCase__      )
				# query, key and value matrices need special treatment
				read_in_q_k_v(lowerCAmelCase__      )
				# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
				SCREAMING_SNAKE_CASE_   :	str													=   'model.'
				for key in state_dict.copy().keys():
								if not key.startswith('class_labels_classifier'      ) and not key.startswith('bbox_predictor'      ):
												SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   state_dict.pop(lowerCAmelCase__      )
												SCREAMING_SNAKE_CASE_   :	Any													=   val
    # create HuggingFace model and load state dict
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   TableTransformerConfig(
				    backbone='resnet18'    ,    mask_loss_coefficient=1    ,    dice_loss_coefficient=1    ,    ce_loss_coefficient=1    ,    bbox_loss_coefficient=5    ,    giou_loss_coefficient=2    ,    eos_coefficient=0.4    ,    class_cost=1    ,    bbox_cost=5    ,    giou_cost=2    ,    )

				if "detection" in checkpoint_url:
								SCREAMING_SNAKE_CASE_   :	int													=   15
								SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   2
								SCREAMING_SNAKE_CASE_   :	int													=   {0: 'table', 1: 'table rotated'}
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   idalabel
								SCREAMING_SNAKE_CASE_   :	Any													=   {v: k for k, v in idalabel.items()}
				else:
								SCREAMING_SNAKE_CASE_   :	Tuple													=   125
								SCREAMING_SNAKE_CASE_   :	Dict													=   6
								SCREAMING_SNAKE_CASE_   :	List[Any]													=   {
								    0: 'table',
								    1: 'table column',
								    2: 'table row',
								    3: 'table column header',
								    4: 'table projected row header',
								    5: 'table spanning cell',
								}
								SCREAMING_SNAKE_CASE_   :	Tuple													=   idalabel
								SCREAMING_SNAKE_CASE_   :	List[str]													=   {v: k for k, v in idalabel.items()}

				SCREAMING_SNAKE_CASE_   :	int													=   DetrImageProcessor(
				    format='coco_detection'    ,    max_size=800 if 'detection' in checkpoint_url else 1000      )
				SCREAMING_SNAKE_CASE_   :	List[Any]													=   TableTransformerForObjectDetection(lowerCAmelCase__      )
				model.load_state_dict(lowerCAmelCase__      )
				model.eval()

				# verify our conversion
				SCREAMING_SNAKE_CASE_   :	Dict													=   'example_pdf.png' if 'detection' in checkpoint_url else 'example_table.png'
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   hf_hub_download(repo_id='nielsr/example-pdf'    ,    repo_type='dataset'    ,    filename=lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   Image.open(lowerCAmelCase__      ).convert('RGB'      )
				SCREAMING_SNAKE_CASE_   :	Dict													=   normalize(resize(lowerCAmelCase__    ,    lowerCAmelCase__      )      ).unsqueeze(0      )

				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   model(lowerCAmelCase__      )

				if "detection" in checkpoint_url:
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   (1, 15, 3)
								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   torch.tensor(
								    [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]]      )
								SCREAMING_SNAKE_CASE_   :	List[Any]													=   torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]]      )

				else:
								SCREAMING_SNAKE_CASE_   :	Dict													=   (1, 125, 7)
								SCREAMING_SNAKE_CASE_   :	int													=   torch.tensor(
								    [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]]      )
								SCREAMING_SNAKE_CASE_   :	Any													=   torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]]      )

				assert outputs.logits.shape == expected_shape
				assert torch.allclose(outputs.logits[0, :3, :3]    ,    lowerCAmelCase__    ,    atol=1E-4      )
				assert torch.allclose(outputs.pred_boxes[0, :3, :3]    ,    lowerCAmelCase__    ,    atol=1E-4      )
				print('Looks ok!'      )

				if pytorch_dump_folder_path is not None:
								# Save model and image processor
								logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...'''      )
								Path(lowerCAmelCase__      ).mkdir(exist_ok=lowerCAmelCase__      )
								model.save_pretrained(lowerCAmelCase__      )
								image_processor.save_pretrained(lowerCAmelCase__      )

				if push_to_hub:
								# Push model to HF hub
								logger.info('Pushing model to the hub...'      )
								SCREAMING_SNAKE_CASE_   :	Any													=   (
								    'microsoft/table-transformer-detection'
								    if 'detection' in checkpoint_url
								    else 'microsoft/table-transformer-structure-recognition'
								)
								model.push_to_hub(lowerCAmelCase__      )
								image_processor.push_to_hub(lowerCAmelCase__      )


if __name__ == "__main__":
				A        =			argparse.ArgumentParser()

				parser.add_argument(
				    '--checkpoint_url',
				    default='https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth',
				    type=str,
				    choices=[
				        'https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth',
				        'https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth',
				    ],
				    help='URL of the Table Transformer checkpoint you\'d like to convert.',
				)
				parser.add_argument(
				    '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.'
				)
				parser.add_argument(
				    '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
				)
				A        =			parser.parse_args()
				convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)







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 							__a							(  __A						):





		'''simple docstring'''



		def __init__(						self ,    *UpperCamelCase__ ,    UpperCamelCase__=None ,    UpperCamelCase__=None ,    **UpperCamelCase__       ):
						super().__init__(*UpperCamelCase__ ,    **UpperCamelCase__       )
						SCREAMING_SNAKE_CASE_   :	Dict													=   eval_examples
						SCREAMING_SNAKE_CASE_   :	int													=   post_process_function


		def   __snake_case			(						self ,    UpperCamelCase__ = None ,    UpperCamelCase__=None ,    UpperCamelCase__ = None ,    UpperCamelCase__ = "eval" ,    **UpperCamelCase__ ,    ):
						SCREAMING_SNAKE_CASE_   :	int													=   gen_kwargs.copy()
						SCREAMING_SNAKE_CASE_   :	Tuple													=   (
						    gen_kwargs['max_length'] if gen_kwargs.get('max_length'       ) is not None else self.args.generation_max_length
						)
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   (
						    gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'       ) is not None else self.args.generation_num_beams
						)
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   gen_kwargs

						SCREAMING_SNAKE_CASE_   :	Tuple													=   self.eval_dataset if eval_dataset is None else eval_dataset
						SCREAMING_SNAKE_CASE_   :	int													=   self.get_eval_dataloader(UpperCamelCase__       )
						SCREAMING_SNAKE_CASE_   :	Any													=   self.eval_examples if eval_examples is None else eval_examples

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

										# Prefix all keys with metric_key_prefix + '_'
										for key in list(metrics.keys()       ):
														if not key.startswith(F'''{metric_key_prefix}_'''       ):
																		SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   metrics.pop(UpperCamelCase__       )

										metrics.update(output.metrics       )
						else:
										SCREAMING_SNAKE_CASE_   :	Tuple													=   output.metrics

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

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

						SCREAMING_SNAKE_CASE_   :	Dict													=   self.callback_handler.on_evaluate(self.args ,    self.state ,    self.control ,    UpperCamelCase__       )
						return metrics






		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__=None ,    UpperCamelCase__ = "test" ,    **UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   gen_kwargs.copy()

						SCREAMING_SNAKE_CASE_   :	Any													=   self.get_test_dataloader(UpperCamelCase__       )

						# Temporarily disable metric computation, we will do it in the loop here.
						SCREAMING_SNAKE_CASE_   :	Tuple													=   self.compute_metrics
						SCREAMING_SNAKE_CASE_   :	str													=   None
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   time.time()
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
						try:
										SCREAMING_SNAKE_CASE_   :	List[str]													=   eval_loop(
										    UpperCamelCase__ ,    description='Prediction' ,    prediction_loss_only=True if compute_metrics is None else None ,    ignore_keys=UpperCamelCase__ ,    metric_key_prefix=UpperCamelCase__ ,    )
						finally:
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   compute_metrics

						SCREAMING_SNAKE_CASE_   :	List[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(
						        UpperCamelCase__ ,    UpperCamelCase__ ,    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

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   self.post_process_function(UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    'predict'       )
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.compute_metrics(UpperCamelCase__       )

						# Prefix all keys with metric_key_prefix + '_'
						for key in list(metrics.keys()       ):
										if not key.startswith(F'''{metric_key_prefix}_'''       ):
														SCREAMING_SNAKE_CASE_   :	Optional[int]													=   metrics.pop(UpperCamelCase__       )
						metrics.update(output.metrics       )
						return PredictionOutput(predictions=predictions.predictions ,    label_ids=predictions.label_ids ,    metrics=UpperCamelCase__       )