
'''simple docstring'''



import os
from pathlib import Path

import numpy as np
import pytest
from pack_dataset import pack_data_dir
from parameterized import parameterized
from save_len_file import save_len_file
from torch.utils.data import DataLoader

from transformers import AutoTokenizer
from transformers.models.mbart.modeling_mbart import shift_tokens_right
from transformers.testing_utils import TestCasePlus, slow
from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset


_lowercase          =						"""bert-base-cased"""
_lowercase          =						"""google/pegasus-xsum"""
_lowercase          =						[""" Sam ate lunch today.""", """Sams lunch ingredients."""]
_lowercase          =						["""A very interesting story about what I ate for lunch.""", """Avocado, celery, turkey, coffee"""]
_lowercase          =						"""patrickvonplaten/t5-tiny-random"""
_lowercase          =						"""sshleifer/bart-tiny-random"""
_lowercase          =						"""sshleifer/tiny-mbart"""
_lowercase          =						"""sshleifer/tiny-marian-en-de"""


def A (__lowerCamelCase :Path					,      __lowerCamelCase :list						):
						_lowerCAmelCase    		=					"""\n""".join(__lowerCamelCase						)
						Path(__lowerCamelCase						).open("""w"""						).writelines(__lowerCamelCase						)


def A (__lowerCamelCase :Union[str, Any]						):
						for split in ["train", "val", "test"]:
												_dump_articles(os.path.join(__lowerCamelCase					,      f'{split}.source'						)					,      __lowerCamelCase						)
												_dump_articles(os.path.join(__lowerCamelCase					,      f'{split}.target'						)					,      __lowerCamelCase						)
						return tmp_dir





class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						@parameterized.expand(
						    [
						        MBART_TINY,
						        MARIAN_TINY,
						        T5_TINY,
						        BART_TINY,
						        PEGASUS_XSUM,
						    ]       ,  )
						@slow
						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					AutoTokenizer.from_pretrained(_lowercase )
												_lowerCAmelCase    		=					make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() )
												_lowerCAmelCase    		=					max(len(tokenizer.encode(_lowercase ) ) for a in ARTICLES )
												_lowerCAmelCase    		=					max(len(tokenizer.encode(_lowercase ) ) for a in SUMMARIES )
												_lowerCAmelCase    		=					4
												_lowerCAmelCase    		=					8
												assert max_len_target > max_src_len  # Will be truncated
												assert max_len_source > max_src_len  # Will be truncated
												_lowerCAmelCase		,       _lowerCAmelCase    		=					"""ro_RO""", """de_DE"""  # ignored for all but mbart, but never causes error.
												_lowerCAmelCase    		=					SeqaSeqDataset(
												    _lowercase       ,  data_dir=_lowercase       ,  type_path="""train"""       ,  max_source_length=_lowercase       ,  max_target_length=_lowercase       ,  src_lang=_lowercase       ,  tgt_lang=_lowercase       ,  )
												_lowerCAmelCase    		=					DataLoader(_lowercase       ,  batch_size=2       ,  collate_fn=train_dataset.collate_fn )
												for batch in dataloader:
																		assert isinstance(_lowercase       ,  _lowercase )
																		assert batch["attention_mask"].shape == batch["input_ids"].shape
																		# show that articles were trimmed.
																		assert batch["input_ids"].shape[1] == max_src_len
																		# show that targets are the same len
																		assert batch["labels"].shape[1] == max_tgt_len
																		if tok_name != MBART_TINY:
																								continue
																		# check language codes in correct place
																		_lowerCAmelCase    		=					shift_tokens_right(batch["""labels"""]       ,  tokenizer.pad_token_id )
																		assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang]
																		assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id
																		assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id
																		assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang]

																		break  # No need to test every batch




						@parameterized.expand([BART_TINY, BERT_BASE_CASED] )
						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					AutoTokenizer.from_pretrained(_lowercase )
												_lowerCAmelCase    		=					make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() )
												_lowerCAmelCase    		=					max(len(tokenizer.encode(_lowercase ) ) for a in ARTICLES )
												_lowerCAmelCase    		=					max(len(tokenizer.encode(_lowercase ) ) for a in SUMMARIES )
												_lowerCAmelCase    		=					4
												_lowerCAmelCase    		=					LegacySeqaSeqDataset(
												    _lowercase       ,  data_dir=_lowercase       ,  type_path="""train"""       ,  max_source_length=20       ,  max_target_length=_lowercase       ,  )
												_lowerCAmelCase    		=					DataLoader(_lowercase       ,  batch_size=2       ,  collate_fn=train_dataset.collate_fn )
												for batch in dataloader:
																		assert batch["attention_mask"].shape == batch["input_ids"].shape
																		# show that articles were trimmed.
																		assert batch["input_ids"].shape[1] == max_len_source
																		assert 20 >= batch["input_ids"].shape[1]  # trimmed significantly
																		# show that targets were truncated
																		assert batch["labels"].shape[1] == trunc_target  # Truncated
																		assert max_len_target > trunc_target  # Truncated
																		break  # No need to test every batch




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					AutoTokenizer.from_pretrained("""facebook/mbart-large-cc25""" )

												_lowerCAmelCase    		=					Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) )
												_lowerCAmelCase    		=					tmp_dir.joinpath("""train.source""" ).open().readlines()
												_lowerCAmelCase    		=					Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) )
												pack_data_dir(_lowercase       ,  _lowercase       ,  128       ,  _lowercase )
												_lowerCAmelCase    		=					{x.name for x in tmp_dir.iterdir()}
												_lowerCAmelCase    		=					{x.name for x in save_dir.iterdir()}
												_lowerCAmelCase    		=					save_dir.joinpath("""train.source""" ).open().readlines()
												# orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.']
												# desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.']
												assert len(_lowercase ) < len(_lowercase )
												assert len(_lowercase ) == 1
												assert len(packed_examples[0] ) == sum(len(_lowercase ) for x in orig_examples )
												assert orig_paths == new_paths




						@pytest.mark.skipif(not FAIRSEQ_AVAILABLE       ,  reason="""This test requires fairseq""" )
						def    _lowercase      (   self ):

												"""simple docstring"""



												if not FAIRSEQ_AVAILABLE:
																		return
												_lowerCAmelCase		,       _lowerCAmelCase		,       _lowerCAmelCase    		=					self._get_dataset(max_len=64 )
												_lowerCAmelCase    		=					64
												_lowerCAmelCase    		=					ds.make_dynamic_sampler(_lowercase       ,  required_batch_size_multiple=_lowercase )
												_lowerCAmelCase    		=					[len(_lowercase ) for x in batch_sampler]
												assert len(set(_lowercase ) ) > 1  # it's not dynamic batch size if every batch is the same length
												assert sum(_lowercase ) == len(_lowercase )  # no dropped or added examples
												_lowerCAmelCase    		=					DataLoader(_lowercase       ,  batch_sampler=_lowercase       ,  collate_fn=ds.collate_fn       ,  num_workers=2 )
												_lowerCAmelCase    		=					[]
												_lowerCAmelCase    		=					[]
												for batch in data_loader:
																		_lowerCAmelCase    		=					batch["""input_ids"""].shape
																		_lowerCAmelCase    		=					src_shape[0]
																		assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple
																		_lowerCAmelCase    		=					np.product(batch["""input_ids"""].shape )
																		num_src_per_batch.append(_lowercase )
																		if num_src_tokens > (max_tokens * 1.1):
																								failures.append(_lowercase )
												assert num_src_per_batch[0] == max(_lowercase )
												if failures:
																		raise AssertionError(F'too many tokens in {len(_lowercase )} batches' )




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase		,       _lowerCAmelCase		,       _lowerCAmelCase    		=					self._get_dataset(max_len=512 )
												_lowerCAmelCase    		=					2
												_lowerCAmelCase    		=					ds.make_sortish_sampler(_lowercase       ,  shuffle=_lowercase )

												_lowerCAmelCase    		=					DataLoader(_lowercase       ,  batch_size=_lowercase       ,  collate_fn=ds.collate_fn       ,  num_workers=2 )
												_lowerCAmelCase    		=					DataLoader(_lowercase       ,  batch_size=_lowercase       ,  collate_fn=ds.collate_fn       ,  num_workers=2       ,  sampler=_lowercase )

												_lowerCAmelCase    		=					tokenizer.pad_token_id

												def count_pad_tokens(_lowercase       ,  _lowercase="input_ids" ):
																		return [batch[k].eq(_lowercase ).sum().item() for batch in data_loader]

												assert sum(count_pad_tokens(_lowercase       ,  k="""labels""" ) ) < sum(count_pad_tokens(_lowercase       ,  k="""labels""" ) )
												assert sum(count_pad_tokens(_lowercase ) ) < sum(count_pad_tokens(_lowercase ) )
												assert len(_lowercase ) == len(_lowercase )




						def    _lowercase      (   self       ,  _lowercase=1_000       ,  _lowercase=128 ):

												"""simple docstring"""



												if os.getenv("""USE_REAL_DATA"""       ,  _lowercase ):
																		_lowerCAmelCase    		=					"""examples/seq2seq/wmt_en_ro"""
																		_lowerCAmelCase    		=					max_len * 2 * 64
																		if not Path(_lowercase ).joinpath("""train.len""" ).exists():
																								save_len_file(_lowercase       ,  _lowercase )
												else:
																		_lowerCAmelCase    		=					"""examples/seq2seq/test_data/wmt_en_ro"""
																		_lowerCAmelCase    		=					max_len * 4
																		save_len_file(_lowercase       ,  _lowercase )

												_lowerCAmelCase    		=					AutoTokenizer.from_pretrained(_lowercase )
												_lowerCAmelCase    		=					SeqaSeqDataset(
												    _lowercase       ,  data_dir=_lowercase       ,  type_path="""train"""       ,  max_source_length=_lowercase       ,  max_target_length=_lowercase       ,  n_obs=_lowercase       ,  )
												return ds, max_tokens, tokenizer




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase		,       _lowerCAmelCase		,       _lowerCAmelCase    		=					self._get_dataset()
												_lowerCAmelCase    		=					set(DistributedSortishSampler(_lowercase       ,  256       ,  num_replicas=2       ,  rank=0       ,  add_extra_examples=_lowercase ) )
												_lowerCAmelCase    		=					set(DistributedSortishSampler(_lowercase       ,  256       ,  num_replicas=2       ,  rank=1       ,  add_extra_examples=_lowercase ) )
												assert idsa.intersection(_lowercase ) == set()




						@parameterized.expand(
						    [
						        MBART_TINY,
						        MARIAN_TINY,
						        T5_TINY,
						        BART_TINY,
						        PEGASUS_XSUM,
						    ]       ,  )
						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					AutoTokenizer.from_pretrained(_lowercase       ,  use_fast=_lowercase )
												if tok_name == MBART_TINY:
																		_lowerCAmelCase    		=					SeqaSeqDataset(
																		    _lowercase       ,  data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() )       ,  type_path="""train"""       ,  max_source_length=4       ,  max_target_length=8       ,  src_lang="""EN"""       ,  tgt_lang="""FR"""       ,  )
																		_lowerCAmelCase    		=					train_dataset.dataset_kwargs
																		assert "src_lang" in kwargs and "tgt_lang" in kwargs
												else:
																		_lowerCAmelCase    		=					SeqaSeqDataset(
																		    _lowercase       ,  data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() )       ,  type_path="""train"""       ,  max_source_length=4       ,  max_target_length=8       ,  )
																		_lowerCAmelCase    		=					train_dataset.dataset_kwargs
																		assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs
																		assert len(_lowercase ) == 1 if tok_name == BART_TINY else len(_lowercase ) == 0


'''simple docstring'''



import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


_lowercase          =						logging.get_logger(__name__)

_lowercase          =						list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_lowercase          =						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




@dataclass
class     UpperCAmelCase_	:






						'''simple docstring'''






						_lowercase						: str										=  field(
						    default=_SCREAMING_SNAKE_CASE			,				metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(_SCREAMING_SNAKE_CASE					)}					)
						_lowercase						: str										=  field(
						    default=_SCREAMING_SNAKE_CASE			,				metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''}					)
						_lowercase						: int										=  field(
						    default=1_2_8			,				metadata={
						        '''help''': (
						            '''The maximum total input sequence length after tokenization. Sequences longer '''
						            '''than this will be truncated, sequences shorter will be padded.'''
						        )
						    }			,				)
						_lowercase						: int										=  field(
						    default=1_2_8			,				metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''}			,				)
						_lowercase						: int										=  field(
						    default=6_4			,				metadata={
						        '''help''': (
						            '''The maximum number of tokens for the question. Questions longer than this will '''
						            '''be truncated to this length.'''
						        )
						    }			,				)
						_lowercase						: int										=  field(
						    default=3_0			,				metadata={
						        '''help''': (
						            '''The maximum length of an answer that can be generated. This is needed because the start '''
						            '''and end predictions are not conditioned on one another.'''
						        )
						    }			,				)
						_lowercase						: bool										=  field(
						    default=_SCREAMING_SNAKE_CASE			,				metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}					)
						_lowercase						: bool										=  field(
						    default=_SCREAMING_SNAKE_CASE			,				metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''}					)
						_lowercase						: float										=  field(
						    default=0.0			,				metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}					)
						_lowercase						: int										=  field(
						    default=2_0			,				metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}					)
						_lowercase						: int										=  field(
						    default=0			,				metadata={
						        '''help''': (
						            '''language id of input for language-specific xlm models (see'''
						            ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'''
						        )
						    }			,				)
						_lowercase						: int										=  field(default=1			,				metadata={'''help''': '''multiple threads for converting example to features'''}					)






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: str										=  '''train'''
						_lowercase						: Union[str, Any]										=  '''dev'''






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: SquadDataTrainingArguments
						_lowercase						: List[SquadFeatures]
						_lowercase						: Split
						_lowercase						: bool




						def __init__(   self       ,  _lowercase       ,  _lowercase       ,  _lowercase = None       ,  _lowercase = Split.train       ,  _lowercase = False       ,  _lowercase = None       ,  _lowercase = "pt"       ,  ):

												"""simple docstring"""



												_lowerCAmelCase    		=					args
												_lowerCAmelCase    		=					is_language_sensitive
												_lowerCAmelCase    		=					SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
												if isinstance(_lowercase       ,  _lowercase ):
																		try:
																								_lowerCAmelCase    		=					Split[mode]
																		except KeyError:
																								raise KeyError("""mode is not a valid split name""" )
												_lowerCAmelCase    		=					mode
												# Load data features from cache or dataset file
												_lowerCAmelCase    		=					"""v2""" if args.version_2_with_negative else """v1"""
												_lowerCAmelCase    		=					os.path.join(
												    cache_dir if cache_dir is not None else args.data_dir       ,  F'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'       ,  )

												# Make sure only the first process in distributed training processes the dataset,
												# and the others will use the cache.
												_lowerCAmelCase    		=					cached_features_file + """.lock"""
												with FileLock(_lowercase ):
																		if os.path.exists(_lowercase ) and not args.overwrite_cache:
																								_lowerCAmelCase    		=					time.time()
																								_lowerCAmelCase    		=					torch.load(_lowercase )

																								# Legacy cache files have only features, while new cache files
																								# will have dataset and examples also.
																								_lowerCAmelCase    		=					self.old_features["""features"""]
																								_lowerCAmelCase    		=					self.old_features.get("""dataset"""       ,  _lowercase )
																								_lowerCAmelCase    		=					self.old_features.get("""examples"""       ,  _lowercase )
																								logger.info(
																								    F'Loading features from cached file {cached_features_file} [took %.3f s]'       ,  time.time() - start )

																								if self.dataset is None or self.examples is None:
																														logger.warning(
																														    F'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
																														    """ future run""" )
																		else:
																								if mode == Split.dev:
																														_lowerCAmelCase    		=					self.processor.get_dev_examples(args.data_dir )
																								else:
																														_lowerCAmelCase    		=					self.processor.get_train_examples(args.data_dir )

																								_lowerCAmelCase		,       _lowerCAmelCase    		=					squad_convert_examples_to_features(
																								    examples=self.examples       ,  tokenizer=_lowercase       ,  max_seq_length=args.max_seq_length       ,  doc_stride=args.doc_stride       ,  max_query_length=args.max_query_length       ,  is_training=mode == Split.train       ,  threads=args.threads       ,  return_dataset=_lowercase       ,  )

																								_lowerCAmelCase    		=					time.time()
																								torch.save(
																								    {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples}       ,  _lowercase       ,  )
																								# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
																								logger.info(
																								    F'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]' )




						def __len__(   self ):

												"""simple docstring"""



												return len(self.features )




						def __getitem__(   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.features[i]

												_lowerCAmelCase    		=					torch.tensor(feature.input_ids       ,  dtype=torch.long )
												_lowerCAmelCase    		=					torch.tensor(feature.attention_mask       ,  dtype=torch.long )
												_lowerCAmelCase    		=					torch.tensor(feature.token_type_ids       ,  dtype=torch.long )
												_lowerCAmelCase    		=					torch.tensor(feature.cls_index       ,  dtype=torch.long )
												_lowerCAmelCase    		=					torch.tensor(feature.p_mask       ,  dtype=torch.float )
												_lowerCAmelCase    		=					torch.tensor(feature.is_impossible       ,  dtype=torch.float )

												_lowerCAmelCase    		=					{
												    """input_ids""": input_ids,
												    """attention_mask""": attention_mask,
												    """token_type_ids""": token_type_ids,
												}

												if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
																		del inputs["token_type_ids"]

												if self.args.model_type in ["xlnet", "xlm"]:
																		inputs.update({"""cls_index""": cls_index, """p_mask""": p_mask} )
																		if self.args.version_2_with_negative:
																								inputs.update({"""is_impossible""": is_impossible} )
																		if self.is_language_sensitive:
																								inputs.update({"""langs""": (torch.ones(input_ids.shape       ,  dtype=torch.intaa ) * self.args.lang_id)} )

												if self.mode == Split.train:
																		_lowerCAmelCase    		=					torch.tensor(feature.start_position       ,  dtype=torch.long )
																		_lowerCAmelCase    		=					torch.tensor(feature.end_position       ,  dtype=torch.long )
																		inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions} )

												return inputs
