
'''simple docstring'''





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

from transformers import BigBirdTokenizerFast


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







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







def 		_snake_case(						SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__=False       )				->					Optional[int]:
       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							:  List[str] 			=   (
                  given_answers + get_sub_answers(lowercase__      ,			begin=1       ) + get_sub_answers(lowercase__      ,			end=-1       )
              )
       lowercase							:  Dict 			=   []
       for answer in given_answers:
              lowercase							:  Any 			=   answer.replace("""_"""      ,			""" """       ).lower()
              lowercase							:  Optional[int] 			=   "".join(c if c not in PUNCTUATION_SET_TO_EXCLUDE else """ """ for c in alias       )
              answers.append(""" """.join(alias.split()       ).strip()       )
       return set(lowercase__       )







def 		_snake_case(						SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__=1      ,			SCREAMING_SNAKE_CASE__=100       )				->					Tuple:
       lowercase							:  str 			=   jax.lax.top_k(lowercase__      ,			lowercase__       )
       lowercase							:  Any 			=   jax.lax.top_k(lowercase__      ,			lowercase__       )

       lowercase							:  List[str] 			=   best_end_idx[:, None] - best_start_idx[None, :]
       lowercase							:  Union[str, Any] 			=   jnp.logical_or(widths < 0      ,			widths > max_size       )
       lowercase							:  List[str] 			=   (best_end_scores[:, None] + best_start_scores[None, :]) - (1e8 * mask)
       lowercase							:  str 			=   jnp.argmax(lowercase__       ).item()

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







def 		_snake_case(						SCREAMING_SNAKE_CASE__       )				->					List[Any]:
       lowercase							:  Optional[Any] 			=   sample["question"]["text"]
       lowercase							:  Any 			=   sample["document"]["tokens"]["token"]
       lowercase							:  Optional[Any] 			=   sample["document"]["tokens"]["is_html"]
       lowercase							:  int 			=   sample["annotations"]["long_answer"]
       lowercase							:  List[Any] 			=   sample["annotations"]["short_answers"]

       lowercase							:  Optional[int] 			=   " ".join([context[i] for i in range(len(lowercase__       )       ) 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							:  Union[str, Any] 			=   []
       for s in short_answers:
              short_targets.extend(s["""text"""]       )
       lowercase							:  Optional[int] 			=   list(set(lowercase__       )       )

       lowercase							:  Any 			=   []
       for s in long_answers:
              if s["start_token"] == -1:
                     continue
              lowercase							:  Union[str, Any] 			=   context[s["start_token"] : s["end_token"]]
              lowercase							:  Optional[int] 			=   is_html[s["start_token"] : s["end_token"]]
              lowercase							:  Optional[Any] 			=   " ".join([answer[i] for i in range(len(lowercase__       )       ) if not html[i]]       )
              if new_answer not in long_targets:
                     long_targets.append(lowercase__       )

       lowercase							:  Any 			=   "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 		_snake_case(						)				->					Dict:
       lowercase							:  List[str] 			=   load_from_disk("""natural-questions-validation"""       )
       lowercase							:  List[str] 			=   dataset.map(lowercase__       ).remove_columns(["""annotations""", """document""", """id"""]       )
       print(lowercase__       )

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

       lowercase							:  Dict 			=   "vasudevgupta/flax-bigbird-natural-questions"
       lowercase							:  int 			=   FlaxBigBirdForNaturalQuestions.from_pretrained(lowercase__       )
       lowercase							:  Tuple 			=   BigBirdTokenizerFast.from_pretrained(lowercase__       )

       @jax.jit
       def forward(*SCREAMING_SNAKE_CASE__      ,			**SCREAMING_SNAKE_CASE__       ):
              lowercase							:  Tuple 			=   model(*lowercase__      ,			**lowercase__       )
              return start_logits, end_logits, jnp.argmax(lowercase__      ,			axis=-1       )

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

              lowercase							:  List[str] 			=   forward(**lowercase__       )

              lowercase							:  int 			=   CATEGORY_MAPPING[category.item()]

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

              if predicted_category in ["yes", "no", "null"]:
                     lowercase							:  Dict 			=   [predicted_category]
                     lowercase							:  Tuple 			=   example["output"] == example["targets"]
                     lowercase							:  List[str] 			=   predicted_category != "null"
                     return example

              lowercase							:  Optional[int] 			=   38 if predicted_category == "short" else 1_024
              lowercase							:  int 			=   get_best_valid_start_end_idx(
                  start_scores[0]      ,			end_scores[0]      ,			top_k=8      ,			max_size=lowercase__       )

              lowercase							:  List[Any] 			=   inputs["input_ids"][0].tolist()
              lowercase							:  int 			=   [tokenizer.decode(input_ids[start_score : end_score + 1]       )]

              lowercase							:  Tuple 			=   expand_to_aliases(example["""targets"""]      ,			make_sub_answers=lowercase__       )
              lowercase							:  Optional[Any] 			=   expand_to_aliases(example["""output"""]       )

              # some preprocessing to both prediction and answer
              lowercase							:  Union[str, Any] 			=   {"".join(a.split()       ) for a in answers}
              lowercase							:  Dict 			=   {"".join(p.split()       ) for p in predictions}
              lowercase							:  Optional[Any] 			=   {s for s in predictions if s not in ["``", "''", "`", "'"]}

              # if there is a common element, it's a exact match
              lowercase							:  Union[str, Any] 			=   len(list(answers & predictions       )       ) > 0
              lowercase							:  Optional[int] 			=   predicted_category != "null" and len(lowercase__       ) > 0

              return example

       lowercase							:  Optional[int] 			=   short_validation_dataset.map(lowercase__       )

       lowercase							:  List[Any] 			=   len(lowercase__       )
       lowercase							:  Any 			=   len(short_validation_dataset.filter(lambda SCREAMING_SNAKE_CASE__       : x["match"] == 1       )       )
       print("""EM score:"""      ,			(matched / total) * 100      ,			"""%"""       )


if __name__ == "__main__":
  main()


import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device


if is_torch_available():
  import torch

  from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer

@require_torch
class __snake_case	(   unittest.TestCase  ):
    @slow
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  int 			=   XLMProphetNetForConditionalGeneration.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased"""   )
           model.to(snake_case   )

           # encoder-decoder outputs
           lowercase							:  List[str] 			=   torch.tensor([[17, 96208, 103471, 2]]   ).to(snake_case   )
           lowercase							:  List[str] 			=   torch.tensor(
               [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]]   ).to(snake_case   )
           lowercase							:  str 			=   model(
               input_ids=snake_case	,attention_mask=snake_case	,encoder_outputs=snake_case	,decoder_input_ids=snake_case   )
           lowercase							:  Tuple 			=   output[0]
           lowercase							:  int 			=   torch.Size((1, 14, 250012)   )
           self.assertEqual(output_predited_logis.shape	,snake_case   )
           lowercase							:  Union[str, Any] 			=   torch.tensor(
               [[[-6.3_986, -8.2_391, 12.5_189], [-6.3_289, -8.0_864, 12.6_211], [-6.2_418, -8.0_445, 12.7_968]]]   ).to(snake_case   )
           self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]	,snake_case	,atol=1e-4   )   )

           # encoder outputs
           lowercase							:  Tuple 			=   model.prophetnet.encoder(snake_case   )[0]
           lowercase							:  Any 			=   torch.tensor(
               [[[-1.4_260, -0.7_628, 0.8_453], [-1.4_719, -0.1_391, 0.7_807], [-1.7_678, 0.0_114, 0.4_646]]]   ).to(snake_case   )
           lowercase							:  Optional[Any] 			=   torch.Size((1, 4, 1024)   )
           self.assertEqual(encoder_outputs.shape	,snake_case   )
           self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]	,snake_case	,atol=1e-4   )   )

           # decoder outputs
           lowercase							:  Tuple 			=   model.prophetnet.decoder(
               snake_case	,encoder_hidden_states=snake_case	,)
           lowercase							:  Optional[int] 			=   decoder_outputs[1].view(1	,model.config.ngram	,14	,-1   )
           lowercase							:  Optional[int] 			=   model.lm_head(snake_case   )
           lowercase							:  List[Any] 			=   predicting_streams_logits[:, 0]
           self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]	,snake_case	,atol=1e-4   )   )
    @slow
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Optional[Any] 			=   XLMProphetNetForConditionalGeneration.from_pretrained(
               """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""   )
           model.to(snake_case   )

           lowercase							:  Optional[int] 			=   torch.tensor([[17, 96208, 103471, 2]]   ).to(snake_case   )
           lowercase							:  Dict 			=   torch.tensor(
               [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]]   ).to(snake_case   )
           lowercase							:  Any 			=   model(
               input_ids=snake_case	,attention_mask=snake_case	,encoder_outputs=snake_case	,decoder_input_ids=snake_case   )
           lowercase							:  Optional[int] 			=   output[0]
           lowercase							:  Dict 			=   torch.Size((1, 14, 250012)   )
           self.assertEqual(output_predited_logis.shape	,snake_case   )
           # compare the actual values for a slice.
           lowercase							:  int 			=   torch.tensor(
               [[[-9.2_253, -9.7_173, -6.3_529], [-7.6_701, -9.0_145, -1.9_382], [-8.0_195, -7.0_004, -0.1_523]]]   ).to(snake_case   )

           self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]	,snake_case	,atol=1e-4   )   )
    @slow
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Any 			=   XLMProphetNetForConditionalGeneration.from_pretrained(
               """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""   )
           model.to(snake_case   )
           lowercase							:  Optional[int] 			=   512

           lowercase							:  List[Any] 			=   XLMProphetNetTokenizer.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""   )

           lowercase							:  int 			=   (
               """Microsoft Corporation intends to officially end free support for the Windows 7 operating system after"""
               """ January 14, 2020, according to the official portal of the organization. From that day, users of this"""
               """ system will not be able to receive security updates, which could make their computers vulnerable to"""
               """ cyber attacks."""
           )
           lowercase							:  List[str] 			=   (
               """орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7"""
               """ после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи"""
               """ этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми"""
               """ к кибератакам."""
           )
           lowercase							:  str 			=   (
               """根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。"""
           )

           lowercase							:  Tuple 			=   tokenizer(
               [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]	,padding=snake_case	,max_length=255	,return_tensors="""pt"""   ).input_ids
           lowercase							:  Union[str, Any] 			=   input_ids.to(snake_case   )

           lowercase							:  Dict 			=   model.generate(
               snake_case	,num_beams=10	,length_penalty=1.0	,no_repeat_ngram_size=3	,early_stopping=snake_case   )
           lowercase							:  Any 			=   [tokenizer.decode(snake_case	,skip_special_tokens=snake_case   ) for g in summary_ids]
           lowercase							:  Union[str, Any] 			=   """Microsoft to end Windows 7 free support after January 14, 2020"""
           lowercase							:  Tuple 			=   """Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года"""
           lowercase							:  Dict 			=   """微软打算终止对Windows 7操作系统的免费支持"""
           self.assertListEqual(
               [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH]	,snake_case	,)

           lowercase							:  int 			=   model.generate(
               snake_case	,num_beams=1	,length_penalty=1.0	,no_repeat_ngram_size=3	,early_stopping=snake_case   )
           lowercase							:  List[Any] 			=   [
               tokenizer.convert_ids_to_tokens(snake_case	,skip_special_tokens=snake_case   ) for g in summary_ids_beama
           ]
           lowercase							:  List[str] 			=   """▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7""".split(""" """   )
           lowercase							:  Optional[Any] 			=   """▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года""".split(
               """ """   )
           lowercase							:  Optional[Any] 			=   """微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持""".split(""" """   )
           self.assertListEqual(
               [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK]	,snake_case	,)
