

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()
__lowerCAmelCase			     =       logging.get_logger(__name__)

# here we list all keys to be renamed (original name on the left, our name on the right)
__lowerCAmelCase			     =       []
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    _lowercase			(	a__						:			Tuple							,  a__						:			Union[str, Any]							,  a__						:			str					)							->					Union[str, Any]:





	"""simple docstring"""


	_UpperCamelCase			=   state_dict.pop(snake_case_					)
	_UpperCamelCase			=   val



def    _lowercase			(	a__						:			Union[str, Any]					)							->					Tuple:





	"""simple docstring"""


	_UpperCamelCase			=   OrderedDict()
	for key, value in state_dict.items():
		if "backbone.0.body" in key:
			_UpperCamelCase			=   key.replace("backbone.0.body"							,  "backbone.conv_encoder.model"					)
			_UpperCamelCase			=   value
		else:
			_UpperCamelCase			=   value

	return new_state_dict



def    _lowercase			(	a__						:			Union[str, Any]					)							->					Union[str, Any]:





	"""simple docstring"""


	_UpperCamelCase			=   ''''''

	# 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)
		_UpperCamelCase			=   state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight'''					)
		_UpperCamelCase			=   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
		_UpperCamelCase			=   in_proj_weight[:2_56, :]
		_UpperCamelCase			=   in_proj_bias[:2_56]
		_UpperCamelCase			=   in_proj_weight[2_56:5_12, :]
		_UpperCamelCase			=   in_proj_bias[2_56:5_12]
		_UpperCamelCase			=   in_proj_weight[-2_56:, :]
		_UpperCamelCase			=   in_proj_bias[-2_56:]
	# 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
		_UpperCamelCase			=   state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight'''					)
		_UpperCamelCase			=   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
		_UpperCamelCase			=   in_proj_weight[:2_56, :]
		_UpperCamelCase			=   in_proj_bias[:2_56]
		_UpperCamelCase			=   in_proj_weight[2_56:5_12, :]
		_UpperCamelCase			=   in_proj_bias[2_56:5_12]
		_UpperCamelCase			=   in_proj_weight[-2_56:, :]
		_UpperCamelCase			=   in_proj_bias[-2_56:]
		# read in weights + bias of input projection layer of cross-attention
		_UpperCamelCase			=   state_dict.pop(
		    f'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight'''					)
		_UpperCamelCase			=   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
		_UpperCamelCase			=   in_proj_weight_cross_attn[:2_56, :]
		_UpperCamelCase			=   in_proj_bias_cross_attn[:2_56]
		_UpperCamelCase			=   in_proj_weight_cross_attn[2_56:5_12, :]
		_UpperCamelCase			=   in_proj_bias_cross_attn[2_56:5_12]
		_UpperCamelCase			=   in_proj_weight_cross_attn[-2_56:, :]
		_UpperCamelCase			=   in_proj_bias_cross_attn[-2_56:]



def    _lowercase			(	a__						:			Any							,  a__						:			List[str]					)							->					int:





	"""simple docstring"""


	_UpperCamelCase			=   image.size
	_UpperCamelCase			=   max(snake_case_							,  snake_case_					)
	_UpperCamelCase			=   8_00 if '''detection''' in checkpoint_url else 10_00
	_UpperCamelCase			=   target_max_size / current_max_size
	_UpperCamelCase			=   image.resize((int(round(scale * width					)					), int(round(scale * height					)					))					)

	return resized_image



def    _lowercase			(	a__						:			Optional[int]					)							->					str:





	"""simple docstring"""


	_UpperCamelCase			=   F.to_tensor(snake_case_					)
	_UpperCamelCase			=   F.normalize(snake_case_							,  mean=[0.485, 0.456, 0.406]							,  std=[0.229, 0.224, 0.225]					)
	return image



@torch.no_grad()
def    _lowercase			(	a__						:			Optional[int]							,  a__						:			Tuple							,  a__						:			Optional[Any]					)							->					List[str]:





	"""simple docstring"""


	logger.info("Converting model..."					)

	# load original state dict
	_UpperCamelCase			=   torch.hub.load_state_dict_from_url(snake_case_							,  map_location="cpu"					)
	# rename keys
	for src, dest in rename_keys:
		rename_key(snake_case_							,  snake_case_							,  snake_case_					)
	_UpperCamelCase			=   rename_backbone_keys(snake_case_					)
	# query, key and value matrices need special treatment
	read_in_q_k_v(snake_case_					)
	# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
	_UpperCamelCase			=   '''model.'''
	for key in state_dict.copy().keys():
		if not key.startswith("class_labels_classifier"					) and not key.startswith("bbox_predictor"					):
			_UpperCamelCase			=   state_dict.pop(snake_case_					)
			_UpperCamelCase			=   val
    # create HuggingFace model and load state dict
	_UpperCamelCase			=   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:
		_UpperCamelCase			=   15
		_UpperCamelCase			=   2
		_UpperCamelCase			=   {0: '''table''', 1: '''table rotated'''}
		_UpperCamelCase			=   idalabel
		_UpperCamelCase			=   {v: k for k, v in idalabel.items()}
	else:
		_UpperCamelCase			=   1_25
		_UpperCamelCase			=   6
		_UpperCamelCase			=   {
		    0: '''table''',
		    1: '''table column''',
		    2: '''table row''',
		    3: '''table column header''',
		    4: '''table projected row header''',
		    5: '''table spanning cell''',
		}
		_UpperCamelCase			=   idalabel
		_UpperCamelCase			=   {v: k for k, v in idalabel.items()}

	_UpperCamelCase			=   DetrImageProcessor(
	    format="coco_detection"							,  max_size=8_00 if "detection" in checkpoint_url else 10_00					)
	_UpperCamelCase			=   TableTransformerForObjectDetection(snake_case_					)
	model.load_state_dict(snake_case_					)
	model.eval()

	# verify our conversion
	_UpperCamelCase			=   '''example_pdf.png''' if '''detection''' in checkpoint_url else '''example_table.png'''
	_UpperCamelCase			=   hf_hub_download(repo_id="nielsr/example-pdf"							,  repo_type="dataset"							,  filename=snake_case_					)
	_UpperCamelCase			=   Image.open(snake_case_					).convert("RGB"					)
	_UpperCamelCase			=   normalize(resize(snake_case_							,  snake_case_					)					).unsqueeze(0					)

	_UpperCamelCase			=   model(snake_case_					)

	if "detection" in checkpoint_url:
		_UpperCamelCase			=   (1, 15, 3)
		_UpperCamelCase			=   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]]					)
		_UpperCamelCase			=   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:
		_UpperCamelCase			=   (1, 1_25, 7)
		_UpperCamelCase			=   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]]					)
		_UpperCamelCase			=   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]							,  snake_case_							,  atol=1e-4					)
	assert torch.allclose(outputs.pred_boxes[0, :3, :3]							,  snake_case_							,  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(snake_case_					).mkdir(exist_ok=snake_case_					)
		model.save_pretrained(snake_case_					)
		image_processor.save_pretrained(snake_case_					)

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


if __name__ == "__main__":
	__lowerCAmelCase			     =       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."""
	)
	__lowerCAmelCase			     =       parser.parse_args()
	convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)











"""simple docstring"""



import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/text-classification/requirements.txt""")

a_					=     logging.getLogger(__name__)






@dataclass
class 						__snake_case   :





 """simple docstring"""


 _lowerCamelCase								=	field(
     default=1_28				,				metadata={
         """help""": (
             """The maximum total input sequence length after tokenization. Sequences longer """
             """than this will be truncated, sequences shorter will be padded."""
         )
     }				,				)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}	)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={
         """help""": (
             """Whether to pad all samples to `max_seq_length`. """
             """If False, will pad the samples dynamically when batching to the maximum length in the batch."""
         )
     }				,				)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={
         """help""": (
             """For debugging purposes or quicker training, truncate the number of training examples to this """
             """value if set."""
         )
     }				,				)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={
         """help""": (
             """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
             """value if set."""
         )
     }				,				)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={
         """help""": (
             """For debugging purposes or quicker training, truncate the number of prediction examples to this """
             """value if set."""
         )
     }				,				)






@dataclass
class 						__snake_case   :





 """simple docstring"""


 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}	)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""}	)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """Train language if it is different from the evaluation language."""}	)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}	)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}	)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}				,				)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""}				,				)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""}				,				)
 _lowerCamelCase								=	field(
     default="""main"""				,				metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}				,				)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={
         """help""": (
             """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
             """with private models)."""
         )
     }				,				)
 _lowerCamelCase								=	field(
     default=SCREAMING_SNAKE_CASE__				,				metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""}				,				)







def 						__lowercase	(  )  ->List[str]:



    '''simple docstring'''







    __A       :		Dict							=	HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
    __A					,			__A					,			__A       :		Tuple							=	parser.parse_args_into_dataclasses()

    # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
    # information sent is the one passed as arguments along with your Python/PyTorch versions.
    send_example_telemetry('''run_xnli'''							,snake_case_		)

    # Setup logging
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''							,datefmt='''%m/%d/%Y %H:%M:%S'''							,handlers=[logging.StreamHandler(sys.stdout		)]							,)

    if training_args.should_log:
        # The default of training_args.log_level is passive, so we set log level at info here to have that default.
        transformers.utils.logging.set_verbosity_info()

    __A       :		Tuple							=	training_args.get_process_log_level()
    logger.setLevel(snake_case_		)
    datasets.utils.logging.set_verbosity(snake_case_		)
    transformers.utils.logging.set_verbosity(snake_case_		)
    transformers.utils.logging.enable_default_handler()
    transformers.utils.logging.enable_explicit_format()

    # Log on each process the small summary:
    logger.warning(
        F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
        + F"""distributed training: {bool(training_args.local_rank != -1		)}, 16-bits training: {training_args.fpaa}"""		)
    logger.info(F"""Training/evaluation parameters {training_args}"""		)

    # Detecting last checkpoint.
    __A       :		List[str]							=	None
    if os.path.isdir(training_args.output_dir		) and training_args.do_train and not training_args.overwrite_output_dir:
        __A       :		Optional[Any]							=	get_last_checkpoint(training_args.output_dir		)
        if last_checkpoint is None and len(os.listdir(training_args.output_dir		)		) > 0:
            raise ValueError(
                F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
                '''Use --overwrite_output_dir to overcome.'''		)
        elif last_checkpoint is not None:
            logger.info(
                F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
                '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''		)

    # Set seed before initializing model.
    set_seed(training_args.seed		)

    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # Downloading and loading xnli dataset from the hub.
    if training_args.do_train:
        if model_args.train_language is None:
            __A       :		Dict							=	load_dataset(
                '''xnli'''							,model_args.language							,split='''train'''							,cache_dir=model_args.cache_dir							,use_auth_token=True if model_args.use_auth_token else None							,)
        else:
            __A       :		List[str]							=	load_dataset(
                '''xnli'''							,model_args.train_language							,split='''train'''							,cache_dir=model_args.cache_dir							,use_auth_token=True if model_args.use_auth_token else None							,)
        __A       :		List[Any]							=	train_dataset.features['''label'''].names

    if training_args.do_eval:
        __A       :		int							=	load_dataset(
            '''xnli'''							,model_args.language							,split='''validation'''							,cache_dir=model_args.cache_dir							,use_auth_token=True if model_args.use_auth_token else None							,)
        __A       :		List[Any]							=	eval_dataset.features['''label'''].names

    if training_args.do_predict:
        __A       :		Dict							=	load_dataset(
            '''xnli'''							,model_args.language							,split='''test'''							,cache_dir=model_args.cache_dir							,use_auth_token=True if model_args.use_auth_token else None							,)
        __A       :		List[Any]							=	predict_dataset.features['''label'''].names

    # Labels
    __A       :		Dict							=	len(snake_case_		)

    # Load pretrained model and tokenizer
    # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.
    __A       :		Any							=	AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path							,num_labels=snake_case_							,idalabel={str(snake_case_		): label for i, label in enumerate(snake_case_		)}							,labelaid={label: i for i, label in enumerate(snake_case_		)}							,finetuning_task='''xnli'''							,cache_dir=model_args.cache_dir							,revision=model_args.model_revision							,use_auth_token=True if model_args.use_auth_token else None							,)
    __A       :		Any							=	AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path							,do_lower_case=model_args.do_lower_case							,cache_dir=model_args.cache_dir							,use_fast=model_args.use_fast_tokenizer							,revision=model_args.model_revision							,use_auth_token=True if model_args.use_auth_token else None							,)
    __A       :		str							=	AutoModelForSequenceClassification.from_pretrained(
        model_args.model_name_or_path							,from_tf=bool('''.ckpt''' in model_args.model_name_or_path		)							,config=snake_case_							,cache_dir=model_args.cache_dir							,revision=model_args.model_revision							,use_auth_token=True if model_args.use_auth_token else None							,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes							,)

    # Preprocessing the datasets
    # Padding strategy
    if data_args.pad_to_max_length:
        __A       :		Tuple							=	'''max_length'''
    else:
        # We will pad later, dynamically at batch creation, to the max sequence length in each batch
        __A       :		List[str]							=	False

    def preprocess_function(snake_case_    :    str		):
        # Tokenize the texts
        return tokenizer(
            examples['''premise''']							,examples['''hypothesis''']							,padding=snake_case_							,max_length=data_args.max_seq_length							,truncation=snake_case_							,)

    if training_args.do_train:
        if data_args.max_train_samples is not None:
            __A       :		Dict							=	min(len(snake_case_		)							,data_args.max_train_samples		)
            __A       :		Any							=	train_dataset.select(range(snake_case_		)		)
        with training_args.main_process_first(desc='''train dataset map pre-processing'''		):
            __A       :		Dict							=	train_dataset.map(
                snake_case_							,batched=snake_case_							,load_from_cache_file=not data_args.overwrite_cache							,desc='''Running tokenizer on train dataset'''							,)
        # Log a few random samples from the training set:
        for index in random.sample(range(len(snake_case_		)		)							,3		):
            logger.info(F"""Sample {index} of the training set: {train_dataset[index]}."""		)

    if training_args.do_eval:
        if data_args.max_eval_samples is not None:
            __A       :		Optional[Any]							=	min(len(snake_case_		)							,data_args.max_eval_samples		)
            __A       :		Any							=	eval_dataset.select(range(snake_case_		)		)
        with training_args.main_process_first(desc='''validation dataset map pre-processing'''		):
            __A       :		Dict							=	eval_dataset.map(
                snake_case_							,batched=snake_case_							,load_from_cache_file=not data_args.overwrite_cache							,desc='''Running tokenizer on validation dataset'''							,)

    if training_args.do_predict:
        if data_args.max_predict_samples is not None:
            __A       :		Union[str, Any]							=	min(len(snake_case_		)							,data_args.max_predict_samples		)
            __A       :		Union[str, Any]							=	predict_dataset.select(range(snake_case_		)		)
        with training_args.main_process_first(desc='''prediction dataset map pre-processing'''		):
            __A       :		List[str]							=	predict_dataset.map(
                snake_case_							,batched=snake_case_							,load_from_cache_file=not data_args.overwrite_cache							,desc='''Running tokenizer on prediction dataset'''							,)

    # Get the metric function
    __A       :		Dict							=	evaluate.load('''xnli'''		)

    # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
    # predictions and label_ids field) and has to return a dictionary string to float.
    def compute_metrics(snake_case_    :    EvalPrediction		):
        __A       :		List[str]							=	p.predictions[0] if isinstance(p.predictions							,snake_case_		) else p.predictions
        __A       :		int							=	np.argmax(snake_case_							,axis=1		)
        return metric.compute(predictions=snake_case_							,references=p.label_ids		)

    # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
    if data_args.pad_to_max_length:
        __A       :		Tuple							=	default_data_collator
    elif training_args.fpaa:
        __A       :		str							=	DataCollatorWithPadding(snake_case_							,pad_to_multiple_of=8		)
    else:
        __A       :		Dict							=	None

    # Initialize our Trainer
    __A       :		str							=	Trainer(
        model=snake_case_							,args=snake_case_							,train_dataset=train_dataset if training_args.do_train else None							,eval_dataset=eval_dataset if training_args.do_eval else None							,compute_metrics=snake_case_							,tokenizer=snake_case_							,data_collator=snake_case_							,)

    # Training
    if training_args.do_train:
        __A       :		Union[str, Any]							=	None
        if training_args.resume_from_checkpoint is not None:
            __A       :		List[str]							=	training_args.resume_from_checkpoint
        elif last_checkpoint is not None:
            __A       :		Any							=	last_checkpoint
        __A       :		int							=	trainer.train(resume_from_checkpoint=snake_case_		)
        __A       :		Union[str, Any]							=	train_result.metrics
        __A       :		Dict							=	(
            data_args.max_train_samples if data_args.max_train_samples is not None else len(snake_case_		)
        )
        __A       :		Any							=	min(snake_case_							,len(snake_case_		)		)

        trainer.save_model()  # Saves the tokenizer too for easy upload

        trainer.log_metrics('''train'''							,snake_case_		)
        trainer.save_metrics('''train'''							,snake_case_		)
        trainer.save_state()

    # Evaluation
    if training_args.do_eval:
        logger.info('''*** Evaluate ***'''		)
        __A       :		Any							=	trainer.evaluate(eval_dataset=snake_case_		)

        __A       :		List[str]							=	data_args.max_eval_samples if data_args.max_eval_samples is not None else len(snake_case_		)
        __A       :		str							=	min(snake_case_							,len(snake_case_		)		)

        trainer.log_metrics('''eval'''							,snake_case_		)
        trainer.save_metrics('''eval'''							,snake_case_		)

    # Prediction
    if training_args.do_predict:
        logger.info('''*** Predict ***'''		)
        __A					,			__A					,			__A       :		Union[str, Any]							=	trainer.predict(snake_case_							,metric_key_prefix='''predict'''		)

        __A       :		Dict							=	(
            data_args.max_predict_samples if data_args.max_predict_samples is not None else len(snake_case_		)
        )
        __A       :		Optional[Any]							=	min(snake_case_							,len(snake_case_		)		)

        trainer.log_metrics('''predict'''							,snake_case_		)
        trainer.save_metrics('''predict'''							,snake_case_		)

        __A       :		Optional[int]							=	np.argmax(snake_case_							,axis=1		)
        __A       :		Dict							=	os.path.join(training_args.output_dir							,'''predictions.txt'''		)
        if trainer.is_world_process_zero():
            with open(snake_case_							,'''w'''		) as writer:
                writer.write('''index\tprediction\n'''		)
                for index, item in enumerate(snake_case_		):
                    __A       :		str							=	label_list[item]
                    writer.write(F"""{index}\t{item}\n"""		)


if __name__ == "__main__":
       main()




