


import os

import jsonlines
import numpy as np
from tqdm import tqdm


lowerCAmelCase           =		2_0_4_8
lowerCAmelCase           =		4_0_9_6
lowerCAmelCase           =		4_2
lowerCAmelCase           =		os.environ.pop('''PROCESS_TRAIN''', '''false''')
lowerCAmelCase           =		{'''null''': 0, '''short''': 1, '''long''': 2, '''yes''': 3, '''no''': 4}







def        _lowerCamelCase(	lowercase__	)						->	Any:

		'''simple docstring'''







		def choose_first(lowercase__   , lowercase__=False	):
				assert isinstance(lowercase__   , lowercase__	)
				if len(lowercase__	) == 1:
						__lowercase=			answer[0]
						return {k: [answer[k]] for k in answer} if is_long_answer else answer
				for a in answer:
						if is_long_answer:
								__lowercase=			{k: [a[k]] for k in a}
						if len(a['start_token']	) > 0:
								break
				return a

		__lowercase=			{'id': example['id']}
		__lowercase=			example['annotations']
		__lowercase=			annotation['yes_no_answer']
		if 0 in yes_no_answer or 1 in yes_no_answer:
				__lowercase=			['yes'] if 1 in yes_no_answer else ['no']
				__lowercase=			__lowercase=			[]
				__lowercase=			__lowercase=			[]
				__lowercase=			['<cls>']
		else:
				__lowercase=			['short']
				__lowercase=			choose_first(annotation['short_answers']	)
				if len(out['start_token']	) == 0:
						# answer will be long if short is not available
						__lowercase=			['long']
						__lowercase=			choose_first(annotation['long_answer']   , is_long_answer=lowercase__	)
						__lowercase=			[]
				answer.update(lowercase__	)

		# disregard some samples
		if len(answer['start_token']	) > 1 or answer["start_token"] == answer["end_token"]:
				__lowercase=			True
		else:
				__lowercase=			False

		__lowercase=			['start_token', 'end_token', 'start_byte', 'end_byte', 'text']
		if not all(isinstance(answer[k]   , lowercase__	) for k in cols	):
				raise ValueError('Issue in ID'   , example['id']	)

		return answer







def        _lowerCamelCase(	lowercase__   , lowercase__=False	)						->	str:

		'''simple docstring'''







		__lowercase=			_get_single_answer(lowercase__	)
		# bytes are of no use
		del answer["start_byte"]
		del answer["end_byte"]

		# handle yes_no answers explicitly
		if answer["category"][0] in ["yes", "no"]:  # category is list with one element
				__lowercase=			example['document']['tokens']
				__lowercase=			[]
				for i in range(len(doc['token']	)	):
						if not doc["is_html"][i]:
								context.append(doc['token'][i]	)
				return {
				    "context": " ".join(lowercase__	),
				    "answer": {
				        "start_token": -1_0_0,  # ignore index in cross-entropy
				        "end_token": -1_0_0,  # ignore index in cross-entropy
				        "category": answer["category"],
				        "span": answer["category"],  # extra
				    },
				}

		# later, help in removing all no answers
		if answer["start_token"] == [-1]:
				return {
				    "context": "None",
				    "answer": {
				        "start_token": -1,
				        "end_token": -1,
				        "category": "null",
				        "span": "None",  # extra
				    },
				}

		# handling normal samples

		__lowercase=			['start_token', 'end_token']
		answer.update({k: answer[k][0] if len(answer[k]	) > 0 else answer[k] for k in cols}	)  # e.g. [10] == 10

		__lowercase=			example['document']['tokens']
		__lowercase=			answer['start_token']
		__lowercase=			answer['end_token']

		__lowercase=			[]
		for i in range(len(doc['token']	)	):
				if not doc["is_html"][i]:
						context.append(doc['token'][i]	)
				else:
						if answer["start_token"] > i:
								start_token -= 1
						if answer["end_token"] > i:
								end_token -= 1
		__lowercase=			' '.join(context[start_token:end_token]	)

		# checking above code
		if assertion:
				__lowercase=			doc['is_html'][answer['start_token'] : answer['end_token']]
				__lowercase=			doc['token'][answer['start_token'] : answer['end_token']]
				__lowercase=			' '.join([old[i] for i in range(len(lowercase__	)	) if not is_html[i]]	)
				if new != old:
						print('ID:'   , example['id']	)
						print('New:'   , lowercase__   , end='\n'	)
						print('Old:'   , lowercase__   , end='\n\n'	)

		return {
		    "context": " ".join(lowercase__	),
		    "answer": {
		        "start_token": start_token,
		        "end_token": end_token - 1,  # this makes it inclusive
		        "category": answer["category"],  # either long or short
		        "span": new,  # extra
		    },
		}







def        _lowerCamelCase(	lowercase__   , lowercase__   , lowercase__=2_0_4_8   , lowercase__=4_0_9_6   , lowercase__=True	)						->	Optional[Any]:

		'''simple docstring'''







		__lowercase=			get_context_and_ans(lowercase__   , assertion=lowercase__	)
		__lowercase=			out['answer']

		# later, removing these samples
		if answer["start_token"] == -1:
				return {
				    "example_id": example["id"],
				    "input_ids": [[-1]],
				    "labels": {
				        "start_token": [-1],
				        "end_token": [-1],
				        "category": ["null"],
				    },
				}

		__lowercase=			tokenizer(example['question']['text']   , out['context']	).input_ids
		__lowercase=			input_ids.index(tokenizer.sep_token_id	) + 1

		# return yes/no
		if answer["category"][0] in ["yes", "no"]:  # category is list with one element
				__lowercase=			[]
				__lowercase=			[]
				__lowercase=			input_ids[:q_len]
				__lowercase=			range(lowercase__   , len(lowercase__	)   , max_length - doc_stride	)
				for i in doc_start_indices:
						__lowercase=			i + max_length - q_len
						__lowercase=			input_ids[i:end_index]
						inputs.append(q_indices + slice	)
						category.append(answer['category'][0]	)
						if slice[-1] == tokenizer.sep_token_id:
								break

				return {
				    "example_id": example["id"],
				    "input_ids": inputs,
				    "labels": {
				        "start_token": [-1_0_0] * len(lowercase__	),
				        "end_token": [-1_0_0] * len(lowercase__	),
				        "category": category,
				    },
				}

		__lowercase=			out['context'].split()
		__lowercase=			splitted_context[answer['end_token']]
		__lowercase=			len(
		    tokenizer(
		        ' '.join(splitted_context[: answer['start_token']]	)   , add_special_tokens=lowercase__   , ).input_ids	)
		__lowercase=			len(
		    tokenizer(' '.join(splitted_context[: answer['end_token']]	)   , add_special_tokens=lowercase__	).input_ids	)

		answer["start_token"] += q_len
		answer["end_token"] += q_len

		# fixing end token
		__lowercase=			len(tokenizer(lowercase__   , add_special_tokens=lowercase__	).input_ids	)
		if num_sub_tokens > 1:
				answer["end_token"] += num_sub_tokens - 1

		__lowercase=			input_ids[answer['start_token'] : answer['end_token'] + 1]  # right & left are inclusive
		__lowercase=			answer['start_token']
		__lowercase=			answer['end_token']

		if assertion:
				__lowercase=			tokenizer.decode(lowercase__	)
				if answer["span"] != new:
						print('ISSUE IN TOKENIZATION'	)
						print('OLD:'   , answer['span']	)
						print('NEW:'   , lowercase__   , end='\n\n'	)

		if len(lowercase__	) <= max_length:
				return {
				    "example_id": example["id"],
				    "input_ids": [input_ids],
				    "labels": {
				        "start_token": [answer["start_token"]],
				        "end_token": [answer["end_token"]],
				        "category": answer["category"],
				    },
				}

		__lowercase=			input_ids[:q_len]
		__lowercase=			range(lowercase__   , len(lowercase__	)   , max_length - doc_stride	)

		__lowercase=			[]
		__lowercase=			[]
		__lowercase=			[]
		__lowercase=			[]  # null, yes, no, long, short
		for i in doc_start_indices:
				__lowercase=			i + max_length - q_len
				__lowercase=			input_ids[i:end_index]
				inputs.append(q_indices + slice	)
				assert len(inputs[-1]	) <= max_length, "Issue in truncating length"

				if start_token >= i and end_token <= end_index - 1:
						__lowercase=			start_token - i + q_len
						__lowercase=			end_token - i + q_len
						answers_category.append(answer['category'][0]	)  # ["short"] -> "short"
				else:
						__lowercase=			-1_0_0
						__lowercase=			-1_0_0
						answers_category.append('null'	)
				__lowercase=			inputs[-1][start_token : end_token + 1]

				answers_start_token.append(lowercase__	)
				answers_end_token.append(lowercase__	)
				if assertion:
						if new != old and new != [tokenizer.cls_token_id]:
								print('ISSUE in strided for ID:'   , example['id']	)
								print('New:'   , tokenizer.decode(lowercase__	)	)
								print('Old:'   , tokenizer.decode(lowercase__	)   , end='\n\n'	)
				if slice[-1] == tokenizer.sep_token_id:
						break

		return {
		    "example_id": example["id"],
		    "input_ids": inputs,
		    "labels": {
		        "start_token": answers_start_token,
		        "end_token": answers_end_token,
		        "category": answers_category,
		    },
		}







def        _lowerCamelCase(	lowercase__   , lowercase__   , lowercase__=2_0_4_8   , lowercase__=4_0_9_6   , lowercase__=False	)						->	Tuple:

		'''simple docstring'''







		__lowercase=			get_strided_contexts_and_ans(
		    lowercase__   , lowercase__   , doc_stride=lowercase__   , max_length=lowercase__   , assertion=lowercase__   , )

		return example







def        _lowerCamelCase(	lowercase__   , lowercase__	)						->	str:

		'''simple docstring'''







		with jsonlines.open(lowercase__   , 'a'	) as writer:
				for example in tqdm(lowercase__   , total=len(lowercase__	)   , desc='Saving samples ... '	):
						__lowercase=			example['labels']
						for ids, start, end, cat in zip(
						    example['input_ids']   , labels['start_token']   , labels['end_token']   , labels['category']   , ):
								if start == -1 and end == -1:
										continue  # leave waste samples with no answer
								if cat == "null" and np.random.rand() < 0.6:
										continue  # removing 50 % samples
								writer.write(
								    {
								        'input_ids': ids,
								        'start_token': start,
								        'end_token': end,
								        'category': CATEGORY_MAPPING[cat],
								    }	)


if __name__ == "__main__":
	from datasets import load_dataset

	from transformers import BigBirdTokenizer

	lowerCAmelCase           =		load_dataset('''natural_questions''')
	lowerCAmelCase           =		BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''')

	lowerCAmelCase           =		data['''train''' if PROCESS_TRAIN == '''true''' else '''validation''']

	lowerCAmelCase           =		{
	    '''tokenizer''': tokenizer,
	    '''doc_stride''': DOC_STRIDE,
	    '''max_length''': MAX_LENGTH,
	    '''assertion''': False,
	}
	lowerCAmelCase           =		data.map(prepare_inputs, fn_kwargs=fn_kwargs)
	lowerCAmelCase           =		data.remove_columns(['''annotations''', '''document''', '''id''', '''question'''])
	print(data)

	np.random.seed(SEED)
	lowerCAmelCase           =		'''nq-training.jsonl''' if PROCESS_TRAIN == '''true''' else '''nq-validation.jsonl'''
	save_to_disk(data, file_name=cache_file_name)










import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

from transformers import HfArgumentParser







def        _lowerCamelCase(	lowercase__=None   , lowercase__=None	)						->	Dict:

		'''simple docstring'''







		return field(default_factory=lambda: default   , metadata=lowercase__	)





@dataclass
class       A    :
							UpperCamelCase_   :							str       =field(
							    metadata={'''help''': '''The csv file to plot.'''}					,				)
							UpperCamelCase_   :							bool       =field(
							    default=A_					,				metadata={'''help''': '''Whether to plot along batch size or sequence length. Defaults to sequence length.'''}					,				)
							UpperCamelCase_   :							bool       =field(
							    default=A_					,				metadata={'''help''': '''Whether the csv file has time results or memory results. Defaults to memory results.'''}					,				)
							UpperCamelCase_   :							bool       =field(
							    default=A_					,				metadata={'''help''': '''Disable logarithmic scale when plotting'''}					,				)
							UpperCamelCase_   :							bool       =field(
							    default=A_					,				metadata={
							        '''help''': '''Whether the csv file has training results or inference results. Defaults to inference results.'''
							    }					,				)
							UpperCamelCase_   :							Optional[str]       =field(
							    default=A_					,				metadata={'''help''': '''Filename under which the plot will be saved. If unused no plot is saved.'''}					,				)
							UpperCamelCase_   :							Optional[List[str]]       =list_field(
							    default=A_					,				metadata={'''help''': '''List of model names that are used instead of the ones in the csv file.'''} )







def        _lowerCamelCase(	lowercase__	)						->	int:

		'''simple docstring'''







		try:
				int(lowercase__	)
				return True
		except ValueError:
				return False







def        _lowerCamelCase(	lowercase__	)						->	int:

		'''simple docstring'''







		try:
				float(lowercase__	)
				return True
		except ValueError:
				return False





class       A    :


							def __init__(self      ,				lowerCAmelCase					):
									__lowercase=			args
									__lowercase=			defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}					)

									with open(self.args.csv_file      ,				newline=''					) as csv_file:
											__lowercase=			csv.DictReader(lowerCAmelCase					)
											for row in reader:
													__lowercase=			row['model']
													self.result_dict[model_name]["bsz"].append(int(row['batch_size']					)					)
													self.result_dict[model_name]["seq_len"].append(int(row['sequence_length']					)					)
													if can_convert_to_int(row['result']					):
															# value is not None
															__lowercase=			int(row['result']					)
													elif can_convert_to_float(row['result']					):
															# value is not None
															__lowercase=			float(row['result']					)







							def 			_A       (self					):
									__lowercase,							__lowercase=			plt.subplots()
									__lowercase=			'Time usage' if self.args.is_time else 'Memory usage'
									__lowercase=			title_str + ' for training' if self.args.is_train else title_str + ' for inference'

									if not self.args.no_log_scale:
											# set logarithm scales
											ax.set_xscale('log'					)
											ax.set_yscale('log'					)

									for axis in [ax.xaxis, ax.yaxis]:
											axis.set_major_formatter(ScalarFormatter()					)

									for model_name_idx, model_name in enumerate(self.result_dict.keys()					):
											__lowercase=			sorted(set(self.result_dict[model_name]['bsz']					)					)
											__lowercase=			sorted(set(self.result_dict[model_name]['seq_len']					)					)
											__lowercase=			self.result_dict[model_name]['result']

											((__lowercase),							(__lowercase))=			(
											    (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
											)

											__lowercase=			(
											    model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
											)

											for inner_loop_value in inner_loop_array:
													if self.args.plot_along_batch:
															__lowercase=			np.asarray(
															    [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results]      ,				dtype=lowerCAmelCase      ,				)
													else:
															__lowercase=			np.asarray(
															    [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results]      ,				dtype=np.floataa      ,				)

													((__lowercase),							(__lowercase))=			(
													    ('batch_size', 'len') if self.args.plot_along_batch else ('in #tokens', 'bsz')
													)

													__lowercase=			np.asarray(lowerCAmelCase      ,				lowerCAmelCase					)[: len(lowerCAmelCase					)]
													plt.scatter(
													    lowerCAmelCase      ,				lowerCAmelCase      ,				label=f'{label_model_name} - {inner_loop_label}: {inner_loop_value}'					)
													plt.plot(lowerCAmelCase      ,				lowerCAmelCase      ,				'--'					)

											title_str += f' {label_model_name} vs.'

									__lowercase=			title_str[:-4]
									__lowercase=			'Time in s' if self.args.is_time else 'Memory in MB'

									# plot
									plt.title(lowerCAmelCase					)
									plt.xlabel(lowerCAmelCase					)
									plt.ylabel(lowerCAmelCase					)
									plt.legend()

									if self.args.figure_png_file is not None:
											plt.savefig(self.args.figure_png_file					)
									else:
											plt.show()







def        _lowerCamelCase(	)						->	str:

		'''simple docstring'''







		__lowercase=			HfArgumentParser(lowercase__	)
		__lowercase=			parser.parse_args_into_dataclasses()[0]
		__lowercase=			Plot(args=lowercase__	)
		plot.plot()


if __name__ == "__main__":
	main()






