
"""simple docstring"""






# Copyright (c) 2019 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import csv
import json
import math
import time

import numpy as np
import torch
import torch.optim as optim
import torch.utils.data as data
from nltk.tokenize.treebank import TreebankWordDetokenizer
from pplm_classification_head import ClassificationHead
from torch import nn
from torchtext import data as torchtext_data
from torchtext import datasets
from tqdm import tqdm, trange

from transformers import GPTaLMHeadModel, GPTaTokenizer


torch.manual_seed(0)
np.random.seed(0)
_lowercase							 =							1e-10
_lowercase							 =							'''This is incredible! I love it, this is the best chicken I have ever had.'''
_lowercase							 =							100

class 				__a    (   nn.Module					):
							def __init__(    self     ,						_lowerCamelCase     ,						_lowerCamelCase="gpt2-medium"     ,						_lowerCamelCase=False     ,						_lowerCamelCase="cpu"					) ->       List[str]:




										'''simple docstring'''
										super().__init__()
										__lowercase						      =					GPTaTokenizer.from_pretrained(_lowerCamelCase					)
										__lowercase						      =					GPTaLMHeadModel.from_pretrained(_lowerCamelCase					)
										__lowercase						      =					self.encoder.transformer.config.hidden_size
										__lowercase						      =					ClassificationHead(class_size=_lowerCamelCase     ,						embed_size=self.embed_size					)
										__lowercase						      =					cached_mode
										__lowercase						      =					device
							def      SCREAMING_SNAKE_CASE	(    self					) ->       str:




										'''simple docstring'''
										return self.classifier_head
							def      SCREAMING_SNAKE_CASE	(    self					) ->       Union[str, Any]:




										'''simple docstring'''
										for param in self.encoder.parameters():
													__lowercase						      =					False
										self.classifier_head.train()
							def      SCREAMING_SNAKE_CASE	(    self     ,						_lowerCamelCase					) ->       List[Any]:




										'''simple docstring'''
										__lowercase						      =					x.ne(0					).unsqueeze(2					).repeat(1     ,						1     ,						self.embed_size					).float().to(self.device					).detach()
										__lowercase						      =					self.encoder.transformer(_lowerCamelCase					)["last_hidden_state"]
										__lowercase						      =					hidden * mask
										__lowercase						      =					torch.sum(_lowerCamelCase     ,						dim=1					) / (torch.sum(_lowerCamelCase     ,						dim=1					).detach() + EPSILON)
										return avg_hidden





							def      SCREAMING_SNAKE_CASE	(    self     ,						_lowerCamelCase					) ->       Union[str, Any]:




										'''simple docstring'''
										if self.cached_mode:
													__lowercase						      =					x.to(self.device					)
										else:
													__lowercase						      =					self.avg_representation(x.to(self.device					)					)

										__lowercase						      =					self.classifier_head(_lowerCamelCase					)
										__lowercase						      =					nn.functional.log_softmax(_lowerCamelCase     ,						dim=-1					)

										return probs





class 				__a    (   data.Dataset					):
							def __init__(    self     ,						_lowerCamelCase     ,						_lowerCamelCase					) ->       Any:




										'''simple docstring'''
										__lowercase						      =					X
										__lowercase						      =					y
							def __len__(    self					) ->       str:




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





							def __getitem__(    self     ,						_lowerCamelCase					) ->       List[Any]:




										'''simple docstring'''
										__lowercase						      =					{}
										__lowercase						      =					self.X[index]
										__lowercase						      =					self.y[index]
										return data





def     lowerCAmelCase__ (		__magic_name__			)	->Dict:







			def pad_sequences(__magic_name__			):
						__lowercase						      =					[len(lowercase__			) for seq in sequences]

						__lowercase						      =					torch.zeros(len(lowercase__			) ,      max(lowercase__			)			).long()  # padding value = 0

						for i, seq in enumerate(lowercase__			):
									__lowercase						      =					lengths[i]
									__lowercase						      =					seq[:end]

						return padded_sequences, lengths

			__lowercase						      =					{}
			for key in data[0].keys():
						__lowercase						      =					[d[key] for d in data]

			__lowercase      ,				__lowercase						      =					pad_sequences(item_info["X"]			)
			__lowercase						      =					torch.tensor(item_info["y"] ,      dtype=torch.long			)

			return x_batch, y_batch



def     lowerCAmelCase__ (		__magic_name__			)	->Dict:
			__lowercase						      =					{}
			for key in data[0].keys():
						__lowercase						      =					[d[key] for d in data]

			__lowercase						      =					torch.cat(item_info["X"] ,      0			)
			__lowercase						      =					torch.tensor(item_info["y"] ,      dtype=torch.long			)

			return x_batch, y_batch



def     lowerCAmelCase__ (		__magic_name__ ,      __magic_name__ ,      __magic_name__ ,      __magic_name__=0 ,      __magic_name__=1_0 ,      __magic_name__="cpu"			)	->int:
			__lowercase						      =					0
			discriminator.train_custom()
			for batch_idx, (input_t, target_t) in enumerate(lowercase__			):
						__lowercase      ,				__lowercase						      =					input_t.to(lowercase__			), target_t.to(lowercase__			)

						optimizer.zero_grad()

						__lowercase						      =					discriminator(lowercase__			)
						__lowercase						      =					nn.functional.nll_loss(lowercase__ ,      lowercase__			)
						loss.backward(retain_graph=lowercase__			)
						optimizer.step()

						samples_so_far += len(lowercase__			)

						if batch_idx % log_interval == 0:
									print(
									    "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format(
									        epoch + 1 ,      lowercase__ ,      len(data_loader.dataset			) ,      1_0_0 * samples_so_far / len(data_loader.dataset			) ,      loss.item() ,      )			)



def     lowerCAmelCase__ (		__magic_name__ ,      __magic_name__ ,      __magic_name__="cpu"			)	->Dict:
			discriminator.eval()
			__lowercase						      =					0
			__lowercase						      =					0
			with torch.no_grad():
						for input_t, target_t in data_loader:
									__lowercase      ,				__lowercase						      =					input_t.to(lowercase__			), target_t.to(lowercase__			)
									__lowercase						      =					discriminator(lowercase__			)
									# sum up batch loss
									test_loss += nn.functional.nll_loss(lowercase__ ,      lowercase__ ,      reduction="sum"			).item()
									# get the index of the max log-probability
									__lowercase						      =					output_t.argmax(dim=1 ,      keepdim=lowercase__			)
									correct += pred_t.eq(target_t.view_as(lowercase__			)			).sum().item()

			test_loss /= len(data_loader.dataset			)

			print(
			    "Performance on test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)".format(
			        lowercase__ ,      lowercase__ ,      len(data_loader.dataset			) ,      100.0 * correct / len(data_loader.dataset			)			)			)



def     lowerCAmelCase__ (		__magic_name__ ,      __magic_name__ ,      __magic_name__ ,      __magic_name__=False ,      __magic_name__="cpu"			)	->List[str]:
			__lowercase						      =					model.tokenizer.encode(lowercase__			)
			__lowercase						      =					torch.tensor([input_t] ,      dtype=torch.long ,      device=lowercase__			)
			if cached:
						__lowercase						      =					model.avg_representation(lowercase__			)

			__lowercase						      =					model(lowercase__			).data.cpu().numpy().flatten().tolist()
			print("Input sentence:" ,      lowercase__			)
			print(
			    "Predictions:" ,      ", ".join("{}: {:.4f}".format(lowercase__ ,      math.exp(lowercase__			)			) for c, log_prob in zip(lowercase__ ,      lowercase__			)			) ,      )



def     lowerCAmelCase__ (		__magic_name__ ,      __magic_name__ ,      __magic_name__ ,      __magic_name__=False ,      __magic_name__="cpu"			)	->Union[str, Any]:
			__lowercase						      =					torch.utils.data.DataLoader(dataset=lowercase__ ,      batch_size=lowercase__ ,      collate_fn=lowercase__			)

			__lowercase						      =					[]
			__lowercase						      =					[]
			for batch_idx, (x, y) in enumerate(tqdm(lowercase__ ,      ascii=lowercase__			)			):
						with torch.no_grad():
									__lowercase						      =					x.to(lowercase__			)
									__lowercase						      =					discriminator.avg_representation(lowercase__			).cpu().detach()
									__lowercase						      =					torch.unbind(avg_rep.unsqueeze(1			)			)
									xs += avg_rep_list
									ys += y.cpu().numpy().tolist()

			__lowercase						      =					torch.utils.data.DataLoader(
			    dataset=Dataset(lowercase__ ,      lowercase__			) ,      batch_size=lowercase__ ,      shuffle=lowercase__ ,      collate_fn=lowercase__			)

			return data_loader



def     lowerCAmelCase__ (		__magic_name__ ,      __magic_name__=None ,      __magic_name__="gpt2-medium" ,      __magic_name__=1_0 ,      __magic_name__=6_4 ,      __magic_name__=1_0 ,      __magic_name__=False ,      __magic_name__=False ,      __magic_name__=False ,      )	->Dict:
			__lowercase						      =					"cuda" if torch.cuda.is_available() and not no_cuda else "cpu"

			print("Preprocessing {} dataset...".format(lowercase__			)			)
			__lowercase						      =					time.time()

			if dataset == "SST":
						__lowercase						      =					["positive", "negative", "very positive", "very negative", "neutral"]
						__lowercase						      =					{c: i for i, c in enumerate(lowercase__			)}

						__lowercase						      =					Discriminator(
						    class_size=len(lowercase__			) ,      pretrained_model=lowercase__ ,      cached_mode=lowercase__ ,      device=lowercase__			).to(lowercase__			)

						__lowercase						      =					torchtext_data.Field()
						__lowercase						      =					torchtext_data.Field(sequential=lowercase__			)
						__lowercase      ,				__lowercase      ,				__lowercase						      =					datasets.SST.splits(
						    lowercase__ ,      lowercase__ ,      fine_grained=lowercase__ ,      train_subtrees=lowercase__ ,      )

						__lowercase						      =					[]
						__lowercase						      =					[]
						for i in trange(len(lowercase__			) ,      ascii=lowercase__			):
									__lowercase						      =					TreebankWordDetokenizer().detokenize(vars(train_data[i]			)["text"]			)
									__lowercase						      =					discriminator.tokenizer.encode(lowercase__			)
									__lowercase						      =					torch.tensor([5_0_2_5_6] + seq ,      device=lowercase__ ,      dtype=torch.long			)
									x.append(lowercase__			)
									y.append(classaidx[vars(train_data[i]			)["label"]]			)
						__lowercase						      =					Dataset(lowercase__ ,      lowercase__			)

						__lowercase						      =					[]
						__lowercase						      =					[]
						for i in trange(len(lowercase__			) ,      ascii=lowercase__			):
									__lowercase						      =					TreebankWordDetokenizer().detokenize(vars(test_data[i]			)["text"]			)
									__lowercase						      =					discriminator.tokenizer.encode(lowercase__			)
									__lowercase						      =					torch.tensor([5_0_2_5_6] + seq ,      device=lowercase__ ,      dtype=torch.long			)
									test_x.append(lowercase__			)
									test_y.append(classaidx[vars(test_data[i]			)["label"]]			)
						__lowercase						      =					Dataset(lowercase__ ,      lowercase__			)

						__lowercase						      =					{
						    "class_size": len(lowercase__			),
						    "embed_size": discriminator.embed_size,
						    "pretrained_model": pretrained_model,
						    "class_vocab": classaidx,
						    "default_class": 2,
						}

			elif dataset == "clickbait":
						__lowercase						      =					["non_clickbait", "clickbait"]
						__lowercase						      =					{c: i for i, c in enumerate(lowercase__			)}

						__lowercase						      =					Discriminator(
						    class_size=len(lowercase__			) ,      pretrained_model=lowercase__ ,      cached_mode=lowercase__ ,      device=lowercase__			).to(lowercase__			)

						with open("datasets/clickbait/clickbait_train_prefix.txt"			) as f:
									__lowercase						      =					[]
									for i, line in enumerate(lowercase__			):
												try:
															data.append(eval(lowercase__			)			)
												except Exception:
															print("Error evaluating line {}: {}".format(lowercase__ ,      lowercase__			)			)
															continue
						__lowercase						      =					[]
						__lowercase						      =					[]
						with open("datasets/clickbait/clickbait_train_prefix.txt"			) as f:
									for i, line in enumerate(tqdm(lowercase__ ,      ascii=lowercase__			)			):
												try:
															__lowercase						      =					eval(lowercase__			)
															__lowercase						      =					discriminator.tokenizer.encode(d["text"]			)

															if len(lowercase__			) < max_length_seq:
																		__lowercase						      =					torch.tensor([5_0_2_5_6] + seq ,      device=lowercase__ ,      dtype=torch.long			)
															else:
																		print("Line {} is longer than maximum length {}".format(lowercase__ ,      lowercase__			)			)
																		continue
															x.append(lowercase__			)
															y.append(d["label"]			)
												except Exception:
															print("Error evaluating / tokenizing line {}, skipping it".format(lowercase__			)			)
															pass

						__lowercase						      =					Dataset(lowercase__ ,      lowercase__			)
						__lowercase						      =					int(0.9 * len(lowercase__			)			)
						__lowercase						      =					len(lowercase__			) - train_size
						__lowercase      ,				__lowercase						      =					torch.utils.data.random_split(lowercase__ ,      [train_size, test_size]			)

						__lowercase						      =					{
						    "class_size": len(lowercase__			),
						    "embed_size": discriminator.embed_size,
						    "pretrained_model": pretrained_model,
						    "class_vocab": classaidx,
						    "default_class": 1,
						}

			elif dataset == "toxic":
						__lowercase						      =					["non_toxic", "toxic"]
						__lowercase						      =					{c: i for i, c in enumerate(lowercase__			)}

						__lowercase						      =					Discriminator(
						    class_size=len(lowercase__			) ,      pretrained_model=lowercase__ ,      cached_mode=lowercase__ ,      device=lowercase__			).to(lowercase__			)

						__lowercase						      =					[]
						__lowercase						      =					[]
						with open("datasets/toxic/toxic_train.txt"			) as f:
									for i, line in enumerate(tqdm(lowercase__ ,      ascii=lowercase__			)			):
												try:
															__lowercase						      =					eval(lowercase__			)
															__lowercase						      =					discriminator.tokenizer.encode(d["text"]			)

															if len(lowercase__			) < max_length_seq:
																		__lowercase						      =					torch.tensor([5_0_2_5_6] + seq ,      device=lowercase__ ,      dtype=torch.long			)
															else:
																		print("Line {} is longer than maximum length {}".format(lowercase__ ,      lowercase__			)			)
																		continue
															x.append(lowercase__			)
															y.append(int(np.sum(d["label"]			) > 0			)			)
												except Exception:
															print("Error evaluating / tokenizing line {}, skipping it".format(lowercase__			)			)
															pass

						__lowercase						      =					Dataset(lowercase__ ,      lowercase__			)
						__lowercase						      =					int(0.9 * len(lowercase__			)			)
						__lowercase						      =					len(lowercase__			) - train_size
						__lowercase      ,				__lowercase						      =					torch.utils.data.random_split(lowercase__ ,      [train_size, test_size]			)

						__lowercase						      =					{
						    "class_size": len(lowercase__			),
						    "embed_size": discriminator.embed_size,
						    "pretrained_model": pretrained_model,
						    "class_vocab": classaidx,
						    "default_class": 0,
						}

			else:  # if dataset == "generic":
						# This assumes the input dataset is a TSV with the following structure:
						# class \t text

						if dataset_fp is None:
									raise ValueError("When generic dataset is selected, dataset_fp needs to be specified aswell."			)

						__lowercase						      =					set()
						with open(lowercase__			) as f:
									__lowercase						      =					csv.reader(lowercase__ ,      delimiter="\t"			)
									for row in tqdm(lowercase__ ,      ascii=lowercase__			):
												if row:
															classes.add(row[0]			)

						__lowercase						      =					sorted(lowercase__			)
						__lowercase						      =					{c: i for i, c in enumerate(lowercase__			)}

						__lowercase						      =					Discriminator(
						    class_size=len(lowercase__			) ,      pretrained_model=lowercase__ ,      cached_mode=lowercase__ ,      device=lowercase__			).to(lowercase__			)

						__lowercase						      =					[]
						__lowercase						      =					[]
						with open(lowercase__			) as f:
									__lowercase						      =					csv.reader(lowercase__ ,      delimiter="\t"			)
									for i, row in enumerate(tqdm(lowercase__ ,      ascii=lowercase__			)			):
												if row:
															__lowercase						      =					row[0]
															__lowercase						      =					row[1]

															try:
																		__lowercase						      =					discriminator.tokenizer.encode(lowercase__			)
																		if len(lowercase__			) < max_length_seq:
																					__lowercase						      =					torch.tensor([5_0_2_5_6] + seq ,      device=lowercase__ ,      dtype=torch.long			)

																		else:
																					print("Line {} is longer than maximum length {}".format(lowercase__ ,      lowercase__			)			)
																					continue

																		x.append(lowercase__			)
																		y.append(classaidx[label]			)

															except Exception:
																		print("Error tokenizing line {}, skipping it".format(lowercase__			)			)
																		pass

						__lowercase						      =					Dataset(lowercase__ ,      lowercase__			)
						__lowercase						      =					int(0.9 * len(lowercase__			)			)
						__lowercase						      =					len(lowercase__			) - train_size
						__lowercase      ,				__lowercase						      =					torch.utils.data.random_split(lowercase__ ,      [train_size, test_size]			)

						__lowercase						      =					{
						    "class_size": len(lowercase__			),
						    "embed_size": discriminator.embed_size,
						    "pretrained_model": pretrained_model,
						    "class_vocab": classaidx,
						    "default_class": 0,
						}

			__lowercase						      =					time.time()
			print("Preprocessed {} data points".format(len(lowercase__			) + len(lowercase__			)			)			)
			print("Data preprocessing took: {:.3f}s".format(end - start			)			)

			if cached:
						print("Building representation cache..."			)

						__lowercase						      =					time.time()

						__lowercase						      =					get_cached_data_loader(lowercase__ ,      lowercase__ ,      lowercase__ ,      shuffle=lowercase__ ,      device=lowercase__			)

						__lowercase						      =					get_cached_data_loader(lowercase__ ,      lowercase__ ,      lowercase__ ,      device=lowercase__			)

						__lowercase						      =					time.time()
						print("Building representation cache took: {:.3f}s".format(end - start			)			)

			else:
						__lowercase						      =					torch.utils.data.DataLoader(
						    dataset=lowercase__ ,      batch_size=lowercase__ ,      shuffle=lowercase__ ,      collate_fn=lowercase__			)
						__lowercase						      =					torch.utils.data.DataLoader(dataset=lowercase__ ,      batch_size=lowercase__ ,      collate_fn=lowercase__			)

			if save_model:
						with open("{}_classifier_head_meta.json".format(lowercase__			) ,      "w"			) as meta_file:
									json.dump(lowercase__ ,      lowercase__			)

			__lowercase						      =					optim.Adam(discriminator.parameters() ,      lr=0.0001			)

			for epoch in range(lowercase__			):
						__lowercase						      =					time.time()
						print("\nEpoch" ,      epoch + 1			)

						train_epoch(
						    discriminator=lowercase__ ,      data_loader=lowercase__ ,      optimizer=lowercase__ ,      epoch=lowercase__ ,      log_interval=lowercase__ ,      device=lowercase__ ,      )
						evaluate_performance(data_loader=lowercase__ ,      discriminator=lowercase__ ,      device=lowercase__			)

						__lowercase						      =					time.time()
						print("Epoch took: {:.3f}s".format(end - start			)			)

						print("\nExample prediction"			)
						predict(lowercase__ ,      lowercase__ ,      lowercase__ ,      cached=lowercase__ ,      device=lowercase__			)

						if save_model:
									# torch.save(discriminator.state_dict(),
									#           "{}_discriminator_{}.pt".format(
									#               args.dataset, epoch + 1
									#               ))
									torch.save(
									    discriminator.get_classifier().state_dict() ,      "{}_classifier_head_epoch_{}.pt".format(lowercase__ ,      epoch + 1			) ,      )


if __name__ == "__main__":
					_lowercase							 =							argparse.ArgumentParser(description='''Train a discriminator on top of GPT-2 representations''')
					parser.add_argument(
					    '''--dataset''',
					    type=str,
					    default='''SST''',
					    choices=('''SST''', '''clickbait''', '''toxic''', '''generic'''),
					    help=(
					        '''dataset to train the discriminator on.'''
					        '''In case of generic, the dataset is expected'''
					        '''to be a TSBV file with structure: class \\t text'''
					    ),
					)
					parser.add_argument(
					    '''--dataset_fp''',
					    type=str,
					    default='''''',
					    help='''File path of the dataset to use. Needed only in case of generic datadset''',
					)
					parser.add_argument(
					    '''--pretrained_model''', type=str, default='''gpt2-medium''', help='''Pretrained model to use as encoder'''
					)
					parser.add_argument('''--epochs''', type=int, default=10, metavar='''N''', help='''Number of training epochs''')
					parser.add_argument(
					    '''--batch_size''', type=int, default=64, metavar='''N''', help='''input batch size for training (default: 64)'''
					)
					parser.add_argument(
					    '''--log_interval''',
					    type=int,
					    default=10,
					    metavar='''N''',
					    help='''how many batches to wait before logging training status''',
					)
					parser.add_argument('''--save_model''', action='''store_true''', help='''whether to save the model''')
					parser.add_argument('''--cached''', action='''store_true''', help='''whether to cache the input representations''')
					parser.add_argument('''--no_cuda''', action='''store_true''', help='''use to turn off cuda''')
					_lowercase							 =							parser.parse_args()

					train_discriminator(**(vars(args)))







"""simple docstring"""






import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


_lowercase							 =							'''\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
'''

_lowercase							 =							'''
This metric wrap the official scoring script for version 2 of the Stanford Question
Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.

SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions
written adversarially by crowdworkers to look similar to answerable ones.
To do well on SQuAD2.0, systems must not only answer questions when possible, but also
determine when no answer is supported by the paragraph and abstain from answering.
'''

_lowercase							 =							'''
Computes SQuAD v2 scores (F1 and EM).
Args:
    predictions: List of triple for question-answers to score with the following elements:
        - the question-answer \'id\' field as given in the references (see below)
        - the text of the answer
        - the probability that the question has no answer
    references: List of question-answers dictionaries with the following key-values:
            - \'id\': id of the question-answer pair (see above),
            - \'answers\': a list of Dict {\'text\': text of the answer as a string}
    no_answer_threshold: float
        Probability threshold to decide that a question has no answer.
Returns:
    \'exact\': Exact match (the normalized answer exactly match the gold answer)
    \'f1\': The F-score of predicted tokens versus the gold answer
    \'total\': Number of score considered
    \'HasAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'HasAns_f1\': The F-score of predicted tokens versus the gold answer
    \'HasAns_total\': Number of score considered
    \'NoAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'NoAns_f1\': The F-score of predicted tokens versus the gold answer
    \'NoAns_total\': Number of score considered
    \'best_exact\': Best exact match (with varying threshold)
    \'best_exact_thresh\': No-answer probability threshold associated to the best exact match
    \'best_f1\': Best F1 (with varying threshold)
    \'best_f1_thresh\': No-answer probability threshold associated to the best F1
Examples:

    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\', \'no_answer_probability\': 0.}]
    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]
    >>> squad_v2_metric = datasets.load_metric("squad_v2")
    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact\': 100.0, \'f1\': 100.0, \'total\': 1, \'HasAns_exact\': 100.0, \'HasAns_f1\': 100.0, \'HasAns_total\': 1, \'best_exact\': 100.0, \'best_exact_thresh\': 0.0, \'best_f1\': 100.0, \'best_f1_thresh\': 0.0}
'''

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,      _KWARGS_DESCRIPTION					)
class 				__a    (   datasets.Metric					):



							'''simple docstring'''







							def      SCREAMING_SNAKE_CASE	(    self					) ->       Tuple:




										'''simple docstring'''
										return datasets.MetricInfo(
										    description=_DESCRIPTION     ,						citation=_CITATION     ,						inputs_description=_KWARGS_DESCRIPTION     ,						features=datasets.Features(
										        {
										            "predictions": {
										                "id": datasets.Value("string"					),
										                "prediction_text": datasets.Value("string"					),
										                "no_answer_probability": datasets.Value("float32"					),
										            },
										            "references": {
										                "id": datasets.Value("string"					),
										                "answers": datasets.features.Sequence(
										                    {"text": datasets.Value("string"					), "answer_start": datasets.Value("int32"					)}					),
										            },
										        }					)     ,						codebase_urls=["https://rajpurkar.github.io/SQuAD-explorer/"]     ,						reference_urls=["https://rajpurkar.github.io/SQuAD-explorer/"]     ,						)





							def      SCREAMING_SNAKE_CASE	(    self     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase=1.0					) ->       Tuple:




										'''simple docstring'''
										__lowercase						      =					{p["id"]: p["no_answer_probability"] for p in predictions}
										__lowercase						      =					[{"paragraphs": [{"qas": references}]}]
										__lowercase						      =					{p["id"]: p["prediction_text"] for p in predictions}

										__lowercase						      =					make_qid_to_has_ans(_lowerCamelCase					)  # maps qid to True/False
										__lowercase						      =					[k for k, v in qid_to_has_ans.items() if v]
										__lowercase						      =					[k for k, v in qid_to_has_ans.items() if not v]

										__lowercase      ,				__lowercase						      =					get_raw_scores(_lowerCamelCase     ,						_lowerCamelCase					)
										__lowercase						      =					apply_no_ans_threshold(_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase					)
										__lowercase						      =					apply_no_ans_threshold(_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase					)
										__lowercase						      =					make_eval_dict(_lowerCamelCase     ,						_lowerCamelCase					)

										if has_ans_qids:
													__lowercase						      =					make_eval_dict(_lowerCamelCase     ,						_lowerCamelCase     ,						qid_list=_lowerCamelCase					)
													merge_eval(_lowerCamelCase     ,						_lowerCamelCase     ,						"HasAns"					)
										if no_ans_qids:
													__lowercase						      =					make_eval_dict(_lowerCamelCase     ,						_lowerCamelCase     ,						qid_list=_lowerCamelCase					)
													merge_eval(_lowerCamelCase     ,						_lowerCamelCase     ,						"NoAns"					)
										find_all_best_thresh(_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase					)
										return dict(_lowerCamelCase					)





