import jax
import jax.numpy as jnp
from bigbird_flax import FlaxBigBirdForNaturalQuestions
from datasets import load_from_disk

from transformers import BigBirdTokenizerFast


lowerCAmelCase__  	=      {0: "null", 1: "short", 2: "long", 3: "yes", 4: "no"}
lowerCAmelCase__  	=      set("".join(["‘", "’", "´", "`", ".", ",", "-", "\""]))

def 	__lowerCamelCase							(				__a    : str      ,							__a    : Optional[Any]=0      ,							__a    : Optional[int]=None		)      ->       Optional[Any]:
	return [" ".join(x.split(" "		)[begin:end]		) for x in answers if len(x.split(" "		)		) > 1]

def 	__lowerCamelCase							(				__a    : Optional[Any]      ,							__a    : Any=False		)      ->       Any:
	if make_sub_answers:
		# if answers are longer than one word, make sure a predictions is correct if it coresponds to the complete 1: or :-1 sub word
		# *e.g.* if the correct answer contains a prefix such as "the", or "a"
		_lowercase   =(
		    given_answers + get_sub_answers(__a      ,							begin=1		) + get_sub_answers(__a      ,							end=-1		)
		)
	_lowercase   =[]
	for answer in given_answers:
		_lowercase   =answer.replace("_"      ,							" "		).lower()
		_lowercase   ="".join(c if c not in PUNCTUATION_SET_TO_EXCLUDE else " " for c in alias		)
		answers.append(" ".join(alias.split()		).strip()		)
	return set(__a		)

def 	__lowerCamelCase							(				__a    : Any      ,							__a    : Tuple      ,							__a    : Dict=1      ,							__a    : str=100		)      ->       Dict:
	_lowercase   ,  _lowercase   =jax.lax.top_k(__a      ,							__a		)
	_lowercase   ,  _lowercase   =jax.lax.top_k(__a      ,							__a		)

	_lowercase   =best_end_idx[:, None] - best_start_idx[None, :]
	_lowercase   =jnp.logical_or(widths < 0      ,							widths > max_size		)
	_lowercase   =(best_end_scores[:, None] + best_start_scores[None, :]) - (1E8 * mask)
	_lowercase   =jnp.argmax(__a		).item()

	return best_start_idx[best_score % top_k], best_end_idx[best_score // top_k]

def 	__lowerCamelCase							(				__a    : Optional[int]		)      ->       str:
	_lowercase   =sample["question"]["text"]
	_lowercase   =sample["document"]["tokens"]["token"]
	_lowercase   =sample["document"]["tokens"]["is_html"]
	_lowercase   =sample["annotations"]["long_answer"]
	_lowercase   =sample["annotations"]["short_answers"]

	_lowercase   =" ".join([context[i] for i in range(len(__a		)		) if not is_html[i]]		)

	# 0 - No ; 1 - Yes
	for answer in sample["annotations"]["yes_no_answer"]:
		if answer == 0 or answer == 1:
			return {
			    "question": question,
			    "context": context_string,
			    "short": [],
			    "long": [],
			    "category": "no" if answer == 0 else "yes",
			}

	_lowercase   =[]
	for s in short_answers:
		short_targets.extend(s["text"]		)
	_lowercase   =list(set(__a		)		)

	_lowercase   =[]
	for s in long_answers:
		if s["start_token"] == -1:
			continue
		_lowercase   =context[s["start_token"] : s["end_token"]]
		_lowercase   =is_html[s["start_token"] : s["end_token"]]
		_lowercase   =" ".join([answer[i] for i in range(len(__a		)		) if not html[i]]		)
		if new_answer not in long_targets:
			long_targets.append(__a		)

	_lowercase   ="long_short" if len(short_targets + long_targets		) > 0 else "null"

	return {
	    "question": question,
	    "context": context_string,
	    "short": short_targets,
	    "long": long_targets,
	    "category": category,
	}

def 	__lowerCamelCase							(				)      ->       Optional[int]:
	_lowercase   =load_from_disk("natural-questions-validation"		)
	_lowercase   =dataset.map(__a		).remove_columns(["annotations", "document", "id"]		)
	print(__a		)

	_lowercase   =dataset.filter(lambda __a		: (len(x["question"]		) + len(x["context"]		)) < 4 * 4_096		)
	_lowercase   =short_validation_dataset.filter(lambda __a		: x["category"] != "null"		)
	short_validation_dataset

	_lowercase   ="vasudevgupta/flax-bigbird-natural-questions"
	_lowercase   =FlaxBigBirdForNaturalQuestions.from_pretrained(__a		)
	_lowercase   =BigBirdTokenizerFast.from_pretrained(__a		)

	@jax.jit
	def forward(*__a    : Tuple      ,							**__a    : int		):
		_lowercase   ,  _lowercase   ,  _lowercase   =model(*__a      ,							**__a		)
		return start_logits, end_logits, jnp.argmax(__a      ,							axis=-1		)

	def evaluate(__a    : Optional[int]		):
		# encode question and context so that they are separated by a tokenizer.sep_token and cut at max_length
		_lowercase   =tokenizer(
		    example["question"]      ,							example["context"]      ,							return_tensors="np"      ,							max_length=4_096      ,							padding="max_length"      ,							truncation=__a      ,							)

		_lowercase   ,  _lowercase   ,  _lowercase   =forward(**__a		)

		_lowercase   =CATEGORY_MAPPING[category.item()]

		_lowercase   =example["long"] + example["short"]
		if example["category"] in ["yes", "no", "null"]:
			_lowercase   =[example["category"]]
		_lowercase   =example["category"] != "null"
		# Now target can be: "yes", "no", "null", "list of long & short answers"

		if predicted_category in ["yes", "no", "null"]:
			_lowercase   =[predicted_category]
			_lowercase   =example["output"] == example["targets"]
			_lowercase   =predicted_category != "null"
			return example

		_lowercase   =38 if predicted_category == "short" else 1_024
		_lowercase   ,  _lowercase   =get_best_valid_start_end_idx(
		    start_scores[0]      ,							end_scores[0]      ,							top_k=8      ,							max_size=__a		)

		_lowercase   =inputs["input_ids"][0].tolist()
		_lowercase   =[tokenizer.decode(input_ids[start_score : end_score + 1]		)]

		_lowercase   =expand_to_aliases(example["targets"]      ,							make_sub_answers=__a		)
		_lowercase   =expand_to_aliases(example["output"]		)

		# some preprocessing to both prediction and answer
		_lowercase   ={"".join(a.split()		) for a in answers}
		_lowercase   ={"".join(p.split()		) for p in predictions}
		_lowercase   ={s for s in predictions if s not in ["``", "''", "`", "'"]}

		# if there is a common element, it's a exact match
		_lowercase   =len(list(answers & predictions		)		) > 0
		_lowercase   =predicted_category != "null" and len(__a		) > 0

		return example

	_lowercase   =short_validation_dataset.map(__a		)

	_lowercase   =len(__a		)
	_lowercase   =len(short_validation_dataset.filter(lambda __a		: x["match"] == 1		)		)
	print("EM score:"      ,							(matched / total) * 100      ,							"%"		)


if __name__ == "__main__":
						main()





'''simple docstring'''
from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import (
      TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFXLMForMultipleChoice,
      TFXLMForQuestionAnsweringSimple,
      TFXLMForSequenceClassification,
      TFXLMForTokenClassification,
      TFXLMModel,
      TFXLMWithLMHeadModel,
      XLMConfig,
  )






class       __lowercase		:







     """simple docstring"""






     def __init__(		self  ,      _lowerCamelCase  ,      ):
         __UpperCamelCase						:						str		     =	parent
         __UpperCamelCase						:						Tuple		     =	1_3
         __UpperCamelCase						:						str		     =	7
         __UpperCamelCase						:						List[str]		     =	True
         __UpperCamelCase						:						Optional[Any]		     =	True
         __UpperCamelCase						:						Tuple		     =	True
         __UpperCamelCase						:						Tuple		     =	True
         __UpperCamelCase						:						int		     =	True
         __UpperCamelCase						:						int		     =	False
         __UpperCamelCase						:						Optional[Any]		     =	False
         __UpperCamelCase						:						Any		     =	False
         __UpperCamelCase						:						Any		     =	2
         __UpperCamelCase						:						str		     =	9_9
         __UpperCamelCase						:						int		     =	0
         __UpperCamelCase						:						Any		     =	3_2
         __UpperCamelCase						:						Tuple		     =	2
         __UpperCamelCase						:						Optional[int]		     =	4
         __UpperCamelCase						:						List[str]		     =	0.1
         __UpperCamelCase						:						List[Any]		     =	0.1
         __UpperCamelCase						:						List[str]		     =	5_1_2
         __UpperCamelCase						:						int		     =	1_6
         __UpperCamelCase						:						Any		     =	2
         __UpperCamelCase						:						Dict		     =	0.0_2
         __UpperCamelCase						:						Any		     =	3
         __UpperCamelCase						:						str		     =	4
         __UpperCamelCase						:						Any		     =	'last'
         __UpperCamelCase						:						int		     =	True
         __UpperCamelCase						:						List[str]		     =	None
         __UpperCamelCase						:						Union[str, Any]		     =	0







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						List[str]		     =	ids_tensor([self.batch_size, self.seq_length]  ,      self.vocab_size     )
         __UpperCamelCase						:						str		     =	random_attention_mask([self.batch_size, self.seq_length]  ,      dtype=tf.floataa     )

         __UpperCamelCase						:						Optional[Any]		     =	None
         if self.use_input_lengths:
             __UpperCamelCase						:						Optional[int]		     =	(
                 ids_tensor([self.batch_size]  ,      vocab_size=2     ) + self.seq_length - 2
             )  # small variation of seq_length

         __UpperCamelCase						:						int		     =	None
         if self.use_token_type_ids:
             __UpperCamelCase						:						Union[str, Any]		     =	ids_tensor([self.batch_size, self.seq_length]  ,      self.n_langs     )

         __UpperCamelCase						:						Optional[Any]		     =	None
         __UpperCamelCase						:						Optional[Any]		     =	None
         __UpperCamelCase						:						Tuple		     =	None
         if self.use_labels:
             __UpperCamelCase						:						Tuple		     =	ids_tensor([self.batch_size]  ,      self.type_sequence_label_size     )
             __UpperCamelCase						:						Dict		     =	ids_tensor([self.batch_size, self.seq_length]  ,      self.num_labels     )
             __UpperCamelCase						:						Optional[int]		     =	ids_tensor([self.batch_size]  ,      2  ,      dtype=tf.floataa     )
             __UpperCamelCase						:						int		     =	ids_tensor([self.batch_size]  ,      self.num_choices     )

         __UpperCamelCase						:						int		     =	XLMConfig(
             vocab_size=self.vocab_size  ,      n_special=self.n_special  ,      emb_dim=self.hidden_size  ,      n_layers=self.num_hidden_layers  ,      n_heads=self.num_attention_heads  ,      dropout=self.hidden_dropout_prob  ,      attention_dropout=self.attention_probs_dropout_prob  ,      gelu_activation=self.gelu_activation  ,      sinusoidal_embeddings=self.sinusoidal_embeddings  ,      asm=self.asm  ,      causal=self.causal  ,      n_langs=self.n_langs  ,      max_position_embeddings=self.max_position_embeddings  ,      initializer_range=self.initializer_range  ,      summary_type=self.summary_type  ,      use_proj=self.use_proj  ,      bos_token_id=self.bos_token_id  ,      )

         return (
             config,
             input_ids,
             token_type_ids,
             input_lengths,
             sequence_labels,
             token_labels,
             is_impossible_labels,
             choice_labels,
             input_mask,
         )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      ):
         __UpperCamelCase						:						str		     =	TFXLMModel(config=_lowerCamelCase     )
         __UpperCamelCase						:						Optional[Any]		     =	{'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
         __UpperCamelCase						:						str		     =	model(_lowerCamelCase     )

         __UpperCamelCase						:						Dict		     =	[input_ids, input_mask]
         __UpperCamelCase						:						Tuple		     =	model(_lowerCamelCase     )
         self.parent.assertEqual(result.last_hidden_state.shape  ,      (self.batch_size, self.seq_length, self.hidden_size)     )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      ):
         __UpperCamelCase						:						int		     =	TFXLMWithLMHeadModel(_lowerCamelCase     )

         __UpperCamelCase						:						List[str]		     =	{'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
         __UpperCamelCase						:						List[str]		     =	model(_lowerCamelCase     )

         __UpperCamelCase						:						Tuple		     =	outputs

         self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.seq_length, self.vocab_size)     )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      ):
         __UpperCamelCase						:						Tuple		     =	TFXLMForQuestionAnsweringSimple(_lowerCamelCase     )

         __UpperCamelCase						:						Dict		     =	{'input_ids': input_ids, 'lengths': input_lengths}

         __UpperCamelCase						:						Optional[Any]		     =	model(_lowerCamelCase     )

         self.parent.assertEqual(result.start_logits.shape  ,      (self.batch_size, self.seq_length)     )
         self.parent.assertEqual(result.end_logits.shape  ,      (self.batch_size, self.seq_length)     )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      ):
         __UpperCamelCase						:						Optional[Any]		     =	TFXLMForSequenceClassification(_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	{'input_ids': input_ids, 'lengths': input_lengths}

         __UpperCamelCase						:						Dict		     =	model(_lowerCamelCase     )

         self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.type_sequence_label_size)     )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      ):
         __UpperCamelCase						:						int		     =	self.num_labels
         __UpperCamelCase						:						int		     =	TFXLMForTokenClassification(config=_lowerCamelCase     )
         __UpperCamelCase						:						List[str]		     =	{'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
         __UpperCamelCase						:						List[str]		     =	model(_lowerCamelCase     )
         self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.seq_length, self.num_labels)     )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      ):
         __UpperCamelCase						:						Any		     =	self.num_choices
         __UpperCamelCase						:						List[Any]		     =	TFXLMForMultipleChoice(config=_lowerCamelCase     )
         __UpperCamelCase						:						Tuple		     =	tf.tile(tf.expand_dims(_lowerCamelCase  ,      1     )  ,      (1, self.num_choices, 1)     )
         __UpperCamelCase						:						Optional[int]		     =	tf.tile(tf.expand_dims(_lowerCamelCase  ,      1     )  ,      (1, self.num_choices, 1)     )
         __UpperCamelCase						:						Union[str, Any]		     =	tf.tile(tf.expand_dims(_lowerCamelCase  ,      1     )  ,      (1, self.num_choices, 1)     )
         __UpperCamelCase						:						str		     =	{
             'input_ids': multiple_choice_inputs_ids,
             'attention_mask': multiple_choice_input_mask,
             'token_type_ids': multiple_choice_token_type_ids,
         }
         __UpperCamelCase						:						Dict		     =	model(_lowerCamelCase     )
         self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_choices)     )







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						List[str]		     =	self.prepare_config_and_inputs()
         (
             (
             __UpperCamelCase
         )     ,       (
             __UpperCamelCase
         )     ,       (
             __UpperCamelCase
         )     ,       (
             __UpperCamelCase
         )     ,       (
             __UpperCamelCase
         )     ,       (
             __UpperCamelCase
         )     ,       (
             __UpperCamelCase
         )     ,       (
             __UpperCamelCase
         )     ,       (
             __UpperCamelCase
         )     ,       
         )						:						Any		     =	config_and_inputs
         __UpperCamelCase						:						Union[str, Any]		     =	{
             'input_ids': input_ids,
             'token_type_ids': token_type_ids,
             'langs': token_type_ids,
             'lengths': input_lengths,
         }
         return config, inputs_dict






@require_tf
class       __lowercase		(    _lowerCamelCase      ,				_lowerCamelCase      ,				unittest.TestCase    ):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		 =    (
         (
             TFXLMModel,
             TFXLMWithLMHeadModel,
             TFXLMForSequenceClassification,
             TFXLMForQuestionAnsweringSimple,
             TFXLMForTokenClassification,
             TFXLMForMultipleChoice,
         )
         if is_tf_available()
         else ()
     )
     SCREAMING_SNAKE_CASE__		 =    (
         (TFXLMWithLMHeadModel,) if is_tf_available() else ()
     )  # TODO (PVP): Check other models whether language generation is also applicable
     SCREAMING_SNAKE_CASE__		 =    (
         {
             '''feature-extraction''': TFXLMModel,
             '''fill-mask''': TFXLMWithLMHeadModel,
             '''question-answering''': TFXLMForQuestionAnsweringSimple,
             '''text-classification''': TFXLMForSequenceClassification,
             '''text-generation''': TFXLMWithLMHeadModel,
             '''token-classification''': TFXLMForTokenClassification,
             '''zero-shot''': TFXLMForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     SCREAMING_SNAKE_CASE__		 =    False
     SCREAMING_SNAKE_CASE__		 =    False







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     ):
         if (
             pipeline_test_casse_name == "QAPipelineTests"
             and tokenizer_name is not None
             and not tokenizer_name.endswith('Fast'     )
         ):
             # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
             # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
             # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
             return True

         return False







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[Any]		     =	TFXLMModelTester(self     )
         __UpperCamelCase						:						Union[str, Any]		     =	ConfigTester(self  ,      config_class=_lowerCamelCase  ,      emb_dim=3_7     )







     def lowerCAmelCase  (		self     ):
         self.config_tester.run_common_tests()







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[int]		     =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_model(*_lowerCamelCase     )







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[int]		     =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_lm_head(*_lowerCamelCase     )







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[Any]		     =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_qa(*_lowerCamelCase     )







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[Any]		     =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_sequence_classif(*_lowerCamelCase     )







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Any		     =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_for_token_classification(*_lowerCamelCase     )







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Dict		     =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_xlm_for_multiple_choice(*_lowerCamelCase     )







     @slow
     def lowerCAmelCase  (		self     ):
         for model_name in TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __UpperCamelCase						:						List[Any]		     =	TFXLMModel.from_pretrained(_lowerCamelCase     )
             self.assertIsNotNone(_lowerCamelCase     )






@require_tf
class       __lowercase		(    unittest.TestCase    ):







     """simple docstring"""






     @slow
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Union[str, Any]		     =	TFXLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048'     )
         __UpperCamelCase						:						Union[str, Any]		     =	tf.convert_to_tensor([[1_4, 4_4_7]]  ,      dtype=tf.intaa     )  # the president
         __UpperCamelCase						:						List[Any]		     =	[
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
             1_4,
             4_4_7,
         ]  # the president the president the president the president the president the president the president the president the president the president
         # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
         __UpperCamelCase						:						str		     =	model.generate(_lowerCamelCase  ,      do_sample=_lowerCamelCase     )
         self.assertListEqual(output_ids[0].numpy().tolist()  ,      _lowerCamelCase     )



