

'''simple docstring'''



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 						__lowerCamelCase	(       __snake_case					:		Union[str, Any],		__snake_case					:		List[Any],		__snake_case					:		Any,		__snake_case					:		str,		__snake_case					:		Union[str, Any]=True,		__snake_case					:		str="pt"	)	->							int:
						A__					:       Dict     ={"""add_prefix_space""": True} if isinstance(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	) and not line.startswith(""" """	) else {}
						A__					:       Any     =padding_side
						return tokenizer(
						    [line],		max_length=SCREAMING_SNAKE_CASE_,		padding="""max_length""" if pad_to_max_length else None,		truncation=SCREAMING_SNAKE_CASE_,		return_tensors=SCREAMING_SNAKE_CASE_,		add_special_tokens=SCREAMING_SNAKE_CASE_,		**SCREAMING_SNAKE_CASE_,		)
def 						__lowerCamelCase	(       __snake_case					:		Tuple,		__snake_case					:		Optional[Any],		__snake_case					:		int=None,		)	->							Optional[Any]:
						A__					:       Optional[int]     =input_ids.ne(SCREAMING_SNAKE_CASE_	).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 lowerCamelCase			(  lowerCamelCase_						):



			'''simple docstring'''






			def __init__(				self	:						List[str]		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Optional[Any]="train"		,      lowerCAmelCase_	:						Optional[Any]=None		,      lowerCAmelCase_	:						List[str]=None		,      lowerCAmelCase_	:						Optional[int]=None		,      lowerCAmelCase_	:						List[Any]=""		,      )      ->		List[Any]:





									'''simple docstring'''
									super().__init__()
									A__					:       Union[str, Any]     =Path(lowerCAmelCase__			).joinpath(type_path + """.source"""			)
									A__					:       Optional[Any]     =Path(lowerCAmelCase__			).joinpath(type_path + """.target"""			)
									A__					:       List[Any]     =self.get_char_lens(self.src_file			)
									A__					:       Tuple     =max_source_length
									A__					:       Tuple     =max_target_length
									assert min(self.src_lens			) > 0, f"found empty line in {self.src_file}"
									A__					:       List[str]     =tokenizer
									A__					:       Any     =prefix
									if n_obs is not None:
															A__					:       List[Any]     =self.src_lens[:n_obs]
									A__					:       Optional[Any]     =src_lang
									A__					:       List[str]     =tgt_lang


			def __len__(				self	:						int			)      ->		int:





									'''simple docstring'''
									return len(self.src_lens			)


			def __getitem__(				self	:						Tuple		,      lowerCAmelCase_	:						List[Any]			)      ->		Dict[str, torch.Tensor]:





									'''simple docstring'''
									A__					:       List[Any]     =index + 1  # linecache starts at 1
									A__					:       List[str]     =self.prefix + linecache.getline(str(self.src_file			)		,      lowerCAmelCase__			).rstrip("""\n"""			)
									A__					:       List[str]     =linecache.getline(str(self.tgt_file			)		,      lowerCAmelCase__			).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		,      lowerCAmelCase__			):
															source_line += self.tokenizer.eos_token
															tgt_line += self.tokenizer.eos_token

									# Pad source and target to the right
									A__					:       Optional[int]     =(
									    self.tokenizer.question_encoder if isinstance(self.tokenizer		,      lowerCAmelCase__			) else self.tokenizer
									)
									A__					:       Dict     =self.tokenizer.generator if isinstance(self.tokenizer		,      lowerCAmelCase__			) else self.tokenizer

									A__					:       Dict     =encode_line(lowerCAmelCase__		,      lowerCAmelCase__		,      self.max_source_length		,      """right"""			)
									A__					:       int     =encode_line(lowerCAmelCase__		,      lowerCAmelCase__		,      self.max_target_length		,      """right"""			)

									A__					:       List[Any]     =source_inputs["""input_ids"""].squeeze()
									A__					:       int     =target_inputs["""input_ids"""].squeeze()
									A__					:       List[str]     =source_inputs["""attention_mask"""].squeeze()
									return {
									    "input_ids": source_ids,
									    "attention_mask": src_mask,
									    "decoder_input_ids": target_ids,
									}


			@staticmethod
			def lowercase__						(				lowerCAmelCase_	:						Union[str, Any]			)      ->		Tuple:





									'''simple docstring'''
									return [len(lowerCAmelCase__			) for x in Path(lowerCAmelCase__			).open().readlines()]



			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						Dict			)      ->		Dict[str, torch.Tensor]:





									'''simple docstring'''
									A__					:       Union[str, Any]     =torch.stack([x["""input_ids"""] for x in batch]			)
									A__					:       List[str]     =torch.stack([x["""attention_mask"""] for x in batch]			)
									A__					:       List[Any]     =torch.stack([x["""decoder_input_ids"""] for x in batch]			)
									A__					:       Tuple     =(
									    self.tokenizer.generator.pad_token_id
									    if isinstance(self.tokenizer		,      lowerCAmelCase__			)
									    else self.tokenizer.pad_token_id
									)
									A__					:       List[str]     =(
									    self.tokenizer.question_encoder.pad_token_id
									    if isinstance(self.tokenizer		,      lowerCAmelCase__			)
									    else self.tokenizer.pad_token_id
									)
									A__					:       Union[str, Any]     =trim_batch(lowerCAmelCase__		,      lowerCAmelCase__			)
									A__   ,						A__					:       Tuple     =trim_batch(lowerCAmelCase__		,      lowerCAmelCase__		,      attention_mask=lowerCAmelCase__			)
									A__					:       Any     ={
									    """input_ids""": source_ids,
									    """attention_mask""": source_mask,
									    """decoder_input_ids""": y,
									}
									return batch


__snake_case			:     Tuple										=      getLogger(__name__)
def 						__lowerCamelCase	(       __snake_case					:		List[List]	)	->							Optional[Any]:
						return list(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE_	)	)
def 						__lowerCamelCase	(       __snake_case					:		str	)	->							None:
						A__					:       int     =get_git_info()
						save_json(SCREAMING_SNAKE_CASE_,		os.path.join(SCREAMING_SNAKE_CASE_,		"""git_log.json"""	)	)
def 						__lowerCamelCase	(       __snake_case					:		Optional[Any],		__snake_case					:		Any,		__snake_case					:		Optional[int]=4,		**__snake_case					:		str	)	->							Any:
						with open(SCREAMING_SNAKE_CASE_,		"""w"""	) as f:
												json.dump(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_,		indent=SCREAMING_SNAKE_CASE_,		**SCREAMING_SNAKE_CASE_	)
def 						__lowerCamelCase	(       __snake_case					:		Union[str, Any]	)	->							List[Any]:
						with open(SCREAMING_SNAKE_CASE_	) as f:
												return json.load(SCREAMING_SNAKE_CASE_	)
def 						__lowerCamelCase	(       )	->							Any:
						A__					:       str     =git.Repo(search_parent_directories=SCREAMING_SNAKE_CASE_	)
						A__					:       Optional[Any]     ={
						    """repo_id""": str(SCREAMING_SNAKE_CASE_	),
						    """repo_sha""": str(repo.head.object.hexsha	),
						    """repo_branch""": str(repo.active_branch	),
						    """hostname""": str(socket.gethostname()	),
						}
						return repo_infos
def 						__lowerCamelCase	(       __snake_case					:		Callable,		__snake_case					:		Iterable	)	->							List:
						return list(map(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	)	)
def 						__lowerCamelCase	(       __snake_case					:		List[Any],		__snake_case					:		int	)	->							List[Any]:
						with open(SCREAMING_SNAKE_CASE_,		"""wb"""	) as f:
												return pickle.dump(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	)
def 						__lowerCamelCase	(       __snake_case					:		List[Any]	)	->							Optional[int]:

						def remove_articles(__snake_case					:		Tuple	):
												return re.sub(r"""\b(a|an|the)\b""",		""" """,		SCREAMING_SNAKE_CASE_	)

						def white_space_fix(__snake_case					:		str	):
												return " ".join(text.split()	)

						def remove_punc(__snake_case					:		Dict	):
												A__					:       Dict     =set(string.punctuation	)
												return "".join(ch for ch in text if ch not in exclude	)

						def lower(__snake_case					:		Optional[Any]	):
												return text.lower()

						return white_space_fix(remove_articles(remove_punc(lower(SCREAMING_SNAKE_CASE_	)	)	)	)
def 						__lowerCamelCase	(       __snake_case					:		Tuple,		__snake_case					:		str	)	->							Tuple:
						A__					:       List[Any]     =normalize_answer(SCREAMING_SNAKE_CASE_	).split()
						A__					:       List[str]     =normalize_answer(SCREAMING_SNAKE_CASE_	).split()
						A__					:       Dict     =Counter(SCREAMING_SNAKE_CASE_	) & Counter(SCREAMING_SNAKE_CASE_	)
						A__					:       Optional[Any]     =sum(common.values()	)
						if num_same == 0:
												return 0
						A__					:       Tuple     =1.0 * num_same / len(SCREAMING_SNAKE_CASE_	)
						A__					:       List[Any]     =1.0 * num_same / len(SCREAMING_SNAKE_CASE_	)
						A__					:       Tuple     =(2 * precision * recall) / (precision + recall)
						return fa
def 						__lowerCamelCase	(       __snake_case					:		str,		__snake_case					:		List[str]	)	->							str:
						return normalize_answer(SCREAMING_SNAKE_CASE_	) == normalize_answer(SCREAMING_SNAKE_CASE_	)
def 						__lowerCamelCase	(       __snake_case					:		List[str],		__snake_case					:		List[str]	)	->							Dict:
						assert len(SCREAMING_SNAKE_CASE_	) == len(SCREAMING_SNAKE_CASE_	)
						A__					:       Optional[int]     =0
						for hypo, pred in zip(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	):
												em += exact_match_score(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	)
						if len(SCREAMING_SNAKE_CASE_	) > 0:
												em /= len(SCREAMING_SNAKE_CASE_	)
						return {"em": em}
def 						__lowerCamelCase	(       __snake_case					:		Tuple	)	->							List[Any]:
						return model_prefix.startswith("""rag"""	)
def 						__lowerCamelCase	(       __snake_case					:		List[str],		__snake_case					:		int,		__snake_case					:		Dict	)	->							Union[str, Any]:
						A__					:       Optional[int]     ={p: p for p in extra_params}
						# T5 models don't have `dropout` param, they have `dropout_rate` instead
						A__					:       List[Any]     ="""dropout_rate"""
						for p in extra_params:
												if getattr(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	):
																		if not hasattr(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	) and not hasattr(SCREAMING_SNAKE_CASE_,		equivalent_param[p]	):
																								logger.info("""config doesn\'t have a `{}` attribute""".format(SCREAMING_SNAKE_CASE_	)	)
																								delattr(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	)
																								continue
																		A__					:       Union[str, Any]     =p if hasattr(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	) else equivalent_param[p]
																		setattr(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_,		getattr(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	)	)
																		delattr(SCREAMING_SNAKE_CASE_,		SCREAMING_SNAKE_CASE_	)
						return hparams, config




'''simple docstring'''



import torch
from torch import nn



class lowerCamelCase			(  nn.Module						):



			'''simple docstring'''






			def __init__(				self	:						Any		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						Optional[int]=1		,      lowerCAmelCase_	:						str=False			)      ->		List[str]:





									'''simple docstring'''
									super().__init__()

									A__					:       Any     =n_token
									A__					:       int     =d_embed
									A__					:       Any     =d_proj

									A__					:       Tuple     =cutoffs + [n_token]
									A__					:       Optional[Any]     =[0] + self.cutoffs
									A__					:       Dict     =div_val

									A__					:       str     =self.cutoffs[0]
									A__					:       Optional[Any]     =len(self.cutoffs			) - 1
									A__					:       List[Any]     =self.shortlist_size + self.n_clusters

									if self.n_clusters > 0:
															A__					:       Any     =nn.Parameter(torch.zeros(self.n_clusters		,      self.d_embed			)			)
															A__					:       str     =nn.Parameter(torch.zeros(self.n_clusters			)			)

									A__					:       Union[str, Any]     =nn.ModuleList()
									A__					:       Optional[int]     =nn.ParameterList()

									if div_val == 1:
															for i in range(len(self.cutoffs			)			):
																					if d_proj != d_embed:
																											self.out_projs.append(nn.Parameter(torch.FloatTensor(lowerCAmelCase_		,      lowerCAmelCase_			)			)			)
																					else:
																											self.out_projs.append(lowerCAmelCase_			)

															self.out_layers.append(nn.Linear(lowerCAmelCase_		,      lowerCAmelCase_			)			)
									else:
															for i in range(len(self.cutoffs			)			):
																					A__   ,						A__					:       Optional[int]     =self.cutoff_ends[i], self.cutoff_ends[i + 1]
																					A__					:       Tuple     =d_embed // (div_val**i)

																					self.out_projs.append(nn.Parameter(torch.FloatTensor(lowerCAmelCase_		,      lowerCAmelCase_			)			)			)

																					self.out_layers.append(nn.Linear(lowerCAmelCase_		,      r_idx - l_idx			)			)

									A__					:       Optional[int]     =keep_order


			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Any			)      ->		Union[str, Any]:





									'''simple docstring'''
									if proj is None:
															A__					:       Optional[int]     =nn.functional.linear(lowerCAmelCase_		,      lowerCAmelCase_		,      bias=lowerCAmelCase_			)
									else:
															# if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
															A__					:       Optional[int]     =nn.functional.linear(lowerCAmelCase_		,      proj.t().contiguous()			)
															A__					:       Union[str, Any]     =nn.functional.linear(lowerCAmelCase_		,      lowerCAmelCase_		,      bias=lowerCAmelCase_			)
															# else:
															#     logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
															#     if bias is not None:
															#         logit = logit + bias

									return logit


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						List[Any]=None		,      lowerCAmelCase_	:						Dict=False			)      ->		Optional[int]:





									'''simple docstring'''

									if labels is not None:
															# Shift so that tokens < n predict n
															A__					:       Optional[Any]     =hidden[..., :-1, :].contiguous()
															A__					:       List[Any]     =labels[..., 1:].contiguous()
															A__					:       Optional[int]     =hidden.view(-1		,      hidden.size(-1			)			)
															A__					:       str     =labels.view(-1			)
															if hidden.size(0			) != labels.size(0			):
																					raise RuntimeError("""Input and labels should have the same size in the batch dimension."""			)
									else:
															A__					:       Optional[int]     =hidden.view(-1		,      hidden.size(-1			)			)

									if self.n_clusters == 0:
															A__					:       Optional[Any]     =self._compute_logit(lowerCAmelCase_		,      self.out_layers[0].weight		,      self.out_layers[0].bias		,      self.out_projs[0]			)
															if labels is not None:
																					A__					:       Tuple     =labels != -1_00
																					A__					:       int     =torch.zeros_like(lowerCAmelCase_		,      dtype=hidden.dtype		,      device=hidden.device			)
																					A__					:       Union[str, Any]     =(
																					    -nn.functional.log_softmax(lowerCAmelCase_		,      dim=-1			)[mask].gather(1		,      labels[mask].unsqueeze(1			)			).squeeze(1			)
																					)
															else:
																					A__					:       List[Any]     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=-1			)
									else:
															# construct weights and biases
															A__   ,						A__					:       Any     =[], []
															for i in range(len(self.cutoffs			)			):
																					if self.div_val == 1:
																											A__   ,						A__					:       Optional[int]     =self.cutoff_ends[i], self.cutoff_ends[i + 1]
																											A__					:       int     =self.out_layers[0].weight[l_idx:r_idx]
																											A__					:       List[str]     =self.out_layers[0].bias[l_idx:r_idx]
																					else:
																											A__					:       List[str]     =self.out_layers[i].weight
																											A__					:       Union[str, Any]     =self.out_layers[i].bias

																					if i == 0:
																											A__					:       Tuple     =torch.cat([weight_i, self.cluster_weight]		,      dim=0			)
																											A__					:       List[str]     =torch.cat([bias_i, self.cluster_bias]		,      dim=0			)

																					weights.append(lowerCAmelCase_			)
																					biases.append(lowerCAmelCase_			)

															A__   ,						A__   ,						A__					:       Tuple     =weights[0], biases[0], self.out_projs[0]

															A__					:       List[Any]     =self._compute_logit(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)
															A__					:       int     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=1			)

															if labels is None:
																					A__					:       Union[str, Any]     =hidden.new_empty((head_logit.size(0			), self.n_token)			)
															else:
																					A__					:       Union[str, Any]     =torch.zeros_like(lowerCAmelCase_		,      dtype=hidden.dtype		,      device=hidden.device			)

															A__					:       Any     =0
															A__					:       Tuple     =[0] + self.cutoffs
															for i in range(len(lowerCAmelCase_			) - 1			):
																					A__   ,						A__					:       Tuple     =cutoff_values[i], cutoff_values[i + 1]

																					if labels is not None:
																											A__					:       Tuple     =(labels >= l_idx) & (labels < r_idx)
																											A__					:       Any     =mask_i.nonzero().squeeze()

																											if indices_i.numel() == 0:
																																	continue

																											A__					:       int     =labels.index_select(0		,      lowerCAmelCase_			) - l_idx
																											A__					:       List[str]     =head_logprob.index_select(0		,      lowerCAmelCase_			)
																											A__					:       str     =hidden.index_select(0		,      lowerCAmelCase_			)
																					else:
																											A__					:       Optional[Any]     =hidden

																					if i == 0:
																											if labels is not None:
																																	A__					:       Optional[Any]     =head_logprob_i.gather(1		,      target_i[:, None]			).squeeze(1			)
																											else:
																																	A__					:       Union[str, Any]     =head_logprob[:, : self.cutoffs[0]]
																					else:
																											A__   ,						A__   ,						A__					:       Dict     =weights[i], biases[i], self.out_projs[i]

																											A__					:       List[Any]     =self._compute_logit(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)
																											A__					:       List[Any]     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=1			)
																											A__					:       Optional[Any]     =self.cutoffs[0] + i - 1  # No probability for the head cluster
																											if labels is not None:
																																	A__					:       Union[str, Any]     =head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
																																	    1		,      target_i[:, None]			).squeeze(1			)
																											else:
																																	A__					:       List[str]     =head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
																																	A__					:       Tuple     =logprob_i

																					if labels is not None:
																											if (hasattr(self		,      """keep_order"""			) and self.keep_order) or keep_order:
																																	out.index_copy_(0		,      lowerCAmelCase_		,      -logprob_i			)
																											else:
																																	out[offset : offset + logprob_i.size(0			)].copy_(-logprob_i			)
																											offset += logprob_i.size(0			)

									return out



			def lowercase__						(				self	:						List[str]		,      lowerCAmelCase_	:						Optional[Any]			)      ->		Any:





									'''simple docstring'''
									if self.n_clusters == 0:
															A__					:       List[str]     =self._compute_logit(lowerCAmelCase_		,      self.out_layers[0].weight		,      self.out_layers[0].bias		,      self.out_projs[0]			)
															return nn.functional.log_softmax(lowerCAmelCase_		,      dim=-1			)
									else:
															# construct weights and biases
															A__   ,						A__					:       List[str]     =[], []
															for i in range(len(self.cutoffs			)			):
																					if self.div_val == 1:
																											A__   ,						A__					:       int     =self.cutoff_ends[i], self.cutoff_ends[i + 1]
																											A__					:       List[str]     =self.out_layers[0].weight[l_idx:r_idx]
																											A__					:       List[Any]     =self.out_layers[0].bias[l_idx:r_idx]
																					else:
																											A__					:       Dict     =self.out_layers[i].weight
																											A__					:       Any     =self.out_layers[i].bias

																					if i == 0:
																											A__					:       List[str]     =torch.cat([weight_i, self.cluster_weight]		,      dim=0			)
																											A__					:       Tuple     =torch.cat([bias_i, self.cluster_bias]		,      dim=0			)

																					weights.append(lowerCAmelCase_			)
																					biases.append(lowerCAmelCase_			)

															A__   ,						A__   ,						A__					:       Optional[int]     =weights[0], biases[0], self.out_projs[0]
															A__					:       Any     =self._compute_logit(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)

															A__					:       Dict     =hidden.new_empty((head_logit.size(0			), self.n_token)			)
															A__					:       Dict     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=1			)

															A__					:       Tuple     =[0] + self.cutoffs
															for i in range(len(lowerCAmelCase_			) - 1			):
																					A__   ,						A__					:       List[Any]     =cutoff_values[i], cutoff_values[i + 1]

																					if i == 0:
																											A__					:       Tuple     =head_logprob[:, : self.cutoffs[0]]
																					else:
																											A__   ,						A__   ,						A__					:       Any     =weights[i], biases[i], self.out_projs[i]

																											A__					:       Dict     =self._compute_logit(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)
																											A__					:       str     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=1			)

																											A__					:       str     =head_logprob[:, -i] + tail_logprob_i
																											A__					:       List[Any]     =logprob_i

															return out

