






import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer


def        _a  (     UpperCamelCase_					:				Dict    ,   UpperCamelCase_					:				Dict    ,   UpperCamelCase_					:				List[str]    ,   UpperCamelCase_					:				List[Any]    ,   UpperCamelCase_					:				List[str]=True    ,   UpperCamelCase_					:				List[str]="pt"   ) ->   Tuple:
						"""simple docstring"""







						lowerCAmelCase__       =						{"add_prefix_space": True} if isinstance(UpperCamelCase_    ,   UpperCamelCase_   ) and not line.startswith(" "   ) else {}
						lowerCAmelCase__       =						padding_side
						return tokenizer(
						    [line]    ,   max_length=UpperCamelCase_    ,   padding="max_length" if pad_to_max_length else None    ,   truncation=UpperCamelCase_    ,   return_tensors=UpperCamelCase_    ,   add_special_tokens=UpperCamelCase_    ,   **UpperCamelCase_    ,   )


def        _a  (     UpperCamelCase_					:				Optional[Any]    ,   UpperCamelCase_					:				str    ,   UpperCamelCase_					:				Dict=None    ,   ) ->   Dict:
						"""simple docstring"""







						lowerCAmelCase__       =						input_ids.ne(UpperCamelCase_   ).any(dim=0   )
						if attention_mask is None:
												return input_ids[:, keep_column_mask]
						else:
												return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])


class      lowercase__     (			_UpperCAmelCase	):

	def __init__(							self		,    __UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase="train"		,    __UpperCAmelCase=None		,    __UpperCAmelCase=None		,    __UpperCAmelCase=None		,    __UpperCAmelCase=""		,    )->					Optional[Any]:







							'''simple docstring'''





							super().__init__()
							lowerCAmelCase__       =						Path(__UpperCAmelCase       ).joinpath(type_path + ".source"       )
							lowerCAmelCase__       =						Path(__UpperCAmelCase       ).joinpath(type_path + ".target"       )
							lowerCAmelCase__       =						self.get_char_lens(self.src_file       )
							lowerCAmelCase__       =						max_source_length
							lowerCAmelCase__       =						max_target_length
							assert min(self.src_lens       ) > 0, F"found empty line in {self.src_file}"
							lowerCAmelCase__       =						tokenizer
							lowerCAmelCase__       =						prefix
							if n_obs is not None:
													lowerCAmelCase__       =						self.src_lens[:n_obs]
							lowerCAmelCase__       =						src_lang
							lowerCAmelCase__       =						tgt_lang

	def __len__(							self       )->					List[Any]:







							'''simple docstring'''





							return len(self.src_lens       )

	def __getitem__(							self		,    __UpperCAmelCase       )->					Dict[str, torch.Tensor]:







							'''simple docstring'''





							lowerCAmelCase__       =						index + 1  # linecache starts at 1
							lowerCAmelCase__       =						self.prefix + linecache.getline(str(self.src_file       )		,    __UpperCAmelCase       ).rstrip("\n"       )
							lowerCAmelCase__       =						linecache.getline(str(self.tgt_file       )		,    __UpperCAmelCase       ).rstrip("\n"       )
							assert source_line, F"empty source line for index {index}"
							assert tgt_line, F"empty tgt line for index {index}"

							# Need to add eos token manually for T5
							if isinstance(self.tokenizer		,    __UpperCAmelCase       ):
													source_line += self.tokenizer.eos_token
													tgt_line += self.tokenizer.eos_token

							# Pad source and target to the right
							lowerCAmelCase__       =						(
							    self.tokenizer.question_encoder if isinstance(self.tokenizer		,    __UpperCAmelCase       ) else self.tokenizer
							)
							lowerCAmelCase__       =						self.tokenizer.generator if isinstance(self.tokenizer		,    __UpperCAmelCase       ) else self.tokenizer

							lowerCAmelCase__       =						encode_line(__UpperCAmelCase		,    __UpperCAmelCase		,    self.max_source_length		,    "right"       )
							lowerCAmelCase__       =						encode_line(__UpperCAmelCase		,    __UpperCAmelCase		,    self.max_target_length		,    "right"       )

							lowerCAmelCase__       =						source_inputs["input_ids"].squeeze()
							lowerCAmelCase__       =						target_inputs["input_ids"].squeeze()
							lowerCAmelCase__       =						source_inputs["attention_mask"].squeeze()
							return {
							    "input_ids": source_ids,
							    "attention_mask": src_mask,
							    "decoder_input_ids": target_ids,
							}

	@staticmethod
	def 		UpperCAmelCase  (							__UpperCAmelCase       )->					Optional[Any]:







							'''simple docstring'''





							return [len(__UpperCAmelCase       ) for x in Path(__UpperCAmelCase       ).open().readlines()]


	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase       )->					Dict[str, torch.Tensor]:







							'''simple docstring'''





							lowerCAmelCase__       =						torch.stack([x["input_ids"] for x in batch]       )
							lowerCAmelCase__       =						torch.stack([x["attention_mask"] for x in batch]       )
							lowerCAmelCase__       =						torch.stack([x["decoder_input_ids"] for x in batch]       )
							lowerCAmelCase__       =						(
							    self.tokenizer.generator.pad_token_id
							    if isinstance(self.tokenizer		,    __UpperCAmelCase       )
							    else self.tokenizer.pad_token_id
							)
							lowerCAmelCase__       =						(
							    self.tokenizer.question_encoder.pad_token_id
							    if isinstance(self.tokenizer		,    __UpperCAmelCase       )
							    else self.tokenizer.pad_token_id
							)
							lowerCAmelCase__       =						trim_batch(__UpperCAmelCase		,    __UpperCAmelCase       )
							lowerCAmelCase__      ,							lowerCAmelCase__       =						trim_batch(__UpperCAmelCase		,    __UpperCAmelCase		,    attention_mask=__UpperCAmelCase       )
							lowerCAmelCase__       =						{
							    "input_ids": source_ids,
							    "attention_mask": source_mask,
							    "decoder_input_ids": y,
							}
							return batch





a_     :   Dict							=    getLogger(__name__)


def        _a  (     UpperCamelCase_					:				List[List]   ) ->   List[str]:
						"""simple docstring"""







						return list(itertools.chain.from_iterable(UpperCamelCase_   )   )


def        _a  (     UpperCamelCase_					:				str   ) ->   None:
						"""simple docstring"""







						lowerCAmelCase__       =						get_git_info()
						save_json(UpperCamelCase_    ,   os.path.join(UpperCamelCase_    ,   "git_log.json"   )   )


def        _a  (     UpperCamelCase_					:				List[str]    ,   UpperCamelCase_					:				Optional[Any]    ,   UpperCamelCase_					:				Dict=4    ,   **UpperCamelCase_					:				Tuple   ) ->   int:
						"""simple docstring"""







						with open(UpperCamelCase_    ,   "w"   ) as f:
												json.dump(UpperCamelCase_    ,   UpperCamelCase_    ,   indent=UpperCamelCase_    ,   **UpperCamelCase_   )


def        _a  (     UpperCamelCase_					:				Optional[Any]   ) ->   Tuple:
						"""simple docstring"""







						with open(UpperCamelCase_   ) as f:
												return json.load(UpperCamelCase_   )


def        _a  (     ) ->   Union[str, Any]:
						"""simple docstring"""







						lowerCAmelCase__       =						git.Repo(search_parent_directories=UpperCamelCase_   )
						lowerCAmelCase__       =						{
						    "repo_id": str(UpperCamelCase_   ),
						    "repo_sha": str(repo.head.object.hexsha   ),
						    "repo_branch": str(repo.active_branch   ),
						    "hostname": str(socket.gethostname()   ),
						}
						return repo_infos


def        _a  (     UpperCamelCase_					:				Callable    ,   UpperCamelCase_					:				Iterable   ) ->   List:
						"""simple docstring"""







						return list(map(UpperCamelCase_    ,   UpperCamelCase_   )   )


def        _a  (     UpperCamelCase_					:				List[str]    ,   UpperCamelCase_					:				List[Any]   ) ->   Optional[int]:
						"""simple docstring"""







						with open(UpperCamelCase_    ,   "wb"   ) as f:
												return pickle.dump(UpperCamelCase_    ,   UpperCamelCase_   )


def        _a  (     UpperCamelCase_					:				Dict   ) ->   Tuple:
						"""simple docstring"""







						def remove_articles(UpperCamelCase_					:				List[str]   ):
												return re.sub(R"\b(a|an|the)\b"    ,   " "    ,   UpperCamelCase_   )

						def white_space_fix(UpperCamelCase_					:				Dict   ):
												return " ".join(text.split()   )

						def remove_punc(UpperCamelCase_					:				Union[str, Any]   ):
												lowerCAmelCase__       =						set(string.punctuation   )
												return "".join(ch for ch in text if ch not in exclude   )

						def lower(UpperCamelCase_					:				Optional[int]   ):
												return text.lower()

						return white_space_fix(remove_articles(remove_punc(lower(UpperCamelCase_   )   )   )   )


def        _a  (     UpperCamelCase_					:				Union[str, Any]    ,   UpperCamelCase_					:				Union[str, Any]   ) ->   Optional[int]:
						"""simple docstring"""







						lowerCAmelCase__       =						normalize_answer(UpperCamelCase_   ).split()
						lowerCAmelCase__       =						normalize_answer(UpperCamelCase_   ).split()
						lowerCAmelCase__       =						Counter(UpperCamelCase_   ) & Counter(UpperCamelCase_   )
						lowerCAmelCase__       =						sum(common.values()   )
						if num_same == 0:
												return 0
						lowerCAmelCase__       =						1.0 * num_same / len(UpperCamelCase_   )
						lowerCAmelCase__       =						1.0 * num_same / len(UpperCamelCase_   )
						lowerCAmelCase__       =						(2 * precision * recall) / (precision + recall)
						return fa


def        _a  (     UpperCamelCase_					:				Tuple    ,   UpperCamelCase_					:				int   ) ->   List[str]:
						"""simple docstring"""







						return normalize_answer(UpperCamelCase_   ) == normalize_answer(UpperCamelCase_   )


def        _a  (     UpperCamelCase_					:				List[str]    ,   UpperCamelCase_					:				List[str]   ) ->   Dict:
						"""simple docstring"""







						assert len(UpperCamelCase_   ) == len(UpperCamelCase_   )
						lowerCAmelCase__       =						0
						for hypo, pred in zip(UpperCamelCase_    ,   UpperCamelCase_   ):
												em += exact_match_score(UpperCamelCase_    ,   UpperCamelCase_   )
						if len(UpperCamelCase_   ) > 0:
												em /= len(UpperCamelCase_   )
						return {"em": em}


def        _a  (     UpperCamelCase_					:				List[Any]   ) ->   Optional[Any]:
						"""simple docstring"""







						return model_prefix.startswith("rag"   )





def        _a  (     UpperCamelCase_					:				int    ,   UpperCamelCase_					:				Tuple    ,   UpperCamelCase_					:				Optional[int]   ) ->   Optional[Any]:
						"""simple docstring"""







						lowerCAmelCase__       =						{p: p for p in extra_params}
						# T5 models don't have `dropout` param, they have `dropout_rate` instead
						lowerCAmelCase__       =						"dropout_rate"
						for p in extra_params:
												if getattr(UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_   ):
																		if not hasattr(UpperCamelCase_    ,   UpperCamelCase_   ) and not hasattr(UpperCamelCase_    ,   equivalent_param[p]   ):
																								logger.info("config doesn't have a `{}` attribute".format(UpperCamelCase_   )   )
																								delattr(UpperCamelCase_    ,   UpperCamelCase_   )
																								continue
																		lowerCAmelCase__       =						p if hasattr(UpperCamelCase_    ,   UpperCamelCase_   ) else equivalent_param[p]
																		setattr(UpperCamelCase_    ,   UpperCamelCase_    ,   getattr(UpperCamelCase_    ,   UpperCamelCase_   )   )
																		delattr(UpperCamelCase_    ,   UpperCamelCase_   )
						return hparams, config














import json
import logging
import os
import sys
from time import time
from unittest.mock import patch

from transformers.testing_utils import TestCasePlus, require_torch_tpu


logging.basicConfig(level=logging.DEBUG)

a_							=    logging.getLogger()


def        _a  (     UpperCamelCase_					:				Union[str, Any]   ) ->   Dict:
						"""simple docstring"""







						lowerCAmelCase__       =						{}
						lowerCAmelCase__       =						os.path.join(UpperCamelCase_    ,   "all_results.json"   )
						if os.path.exists(UpperCamelCase_   ):
												with open(UpperCamelCase_    ,   "r"   ) as f:
																		lowerCAmelCase__       =						json.load(UpperCamelCase_   )
						else:
												raise ValueError(F"can't find {path}"   )
						return results


a_							=    logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)





@require_torch_tpu
class      lowercase__     (			_UpperCAmelCase	):

	def 		UpperCAmelCase  (							self       )->					Optional[Any]:







							'''simple docstring'''





							import xla_spawn

							lowerCAmelCase__       =						self.get_auto_remove_tmp_dir()
							lowerCAmelCase__       =						F"\n            ./examples/pytorch/text-classification/run_glue.py\n            --num_cores=8\n            ./examples/pytorch/text-classification/run_glue.py\n            --model_name_or_path distilbert-base-uncased\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n            --do_train\n            --do_eval\n            --debug tpu_metrics_debug\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --learning_rate=1e-4\n            --max_steps=10\n            --warmup_steps=2\n            --seed=42\n            --max_seq_length=128\n            ".split()

							with patch.object(__UpperCAmelCase		,    "argv"		,    __UpperCAmelCase       ):
													lowerCAmelCase__       =						time()
													xla_spawn.main()
													lowerCAmelCase__       =						time()

													lowerCAmelCase__       =						get_results(__UpperCAmelCase       )
													self.assertGreaterEqual(result["eval_accuracy"]		,    0.75       )

													# Assert that the script takes less than 500 seconds to make sure it doesn't hang.
													self.assertLess(end - start		,    500       )


	def 		UpperCAmelCase  (							self       )->					Dict:







							'''simple docstring'''





							import xla_spawn

							lowerCAmelCase__       =						"\n            ./tests/test_trainer_tpu.py\n            --num_cores=8\n            ./tests/test_trainer_tpu.py\n            ".split()
							with patch.object(__UpperCAmelCase		,    "argv"		,    __UpperCAmelCase       ):
													xla_spawn.main()






