


import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import (
        YosoForMaskedLM,
        YosoForMultipleChoice,
        YosoForQuestionAnswering,
        YosoForSequenceClassification,
        YosoForTokenClassification,
        YosoModel,
    )
    from transformers.models.yoso.modeling_yoso import YOSO_PRETRAINED_MODEL_ARCHIVE_LIST



class   snake_case__ :







       def __init__( self:   Union[str, Any],A_:   List[str],A_:   List[str]=13,A_:   Tuple=7,A_:   str=True,A_:   Tuple=True,A_:   Optional[Any]=True,A_:   Dict=True,A_:   Dict=99,A_:   Optional[int]=32,A_:   str=5,A_:   Union[str, Any]=4,A_:   Optional[Any]=37,A_:   str="gelu",A_:   Dict=0.1,A_:   Tuple=0.1,A_:   List[str]=512,A_:   Optional[Any]=16,A_:   List[str]=2,A_:   Optional[Any]=0.0_2,A_:   List[str]=3,A_:   List[Any]=4,A_:   List[str]=None,):






            '''simple docstring'''




            __UpperCamelCase   = parent
            __UpperCamelCase   = batch_size
            __UpperCamelCase   = seq_length
            __UpperCamelCase   = is_training
            __UpperCamelCase   = use_input_mask
            __UpperCamelCase   = use_token_type_ids
            __UpperCamelCase   = use_labels
            __UpperCamelCase   = vocab_size
            __UpperCamelCase   = hidden_size
            __UpperCamelCase   = num_hidden_layers
            __UpperCamelCase   = num_attention_heads
            __UpperCamelCase   = intermediate_size
            __UpperCamelCase   = hidden_act
            __UpperCamelCase   = hidden_dropout_prob
            __UpperCamelCase   = attention_probs_dropout_prob
            __UpperCamelCase   = max_position_embeddings
            __UpperCamelCase   = type_vocab_size
            __UpperCamelCase   = type_sequence_label_size
            __UpperCamelCase   = initializer_range
            __UpperCamelCase   = num_labels
            __UpperCamelCase   = num_choices
            __UpperCamelCase   = scope







       def 		snake_case_  ( self:   List[Any]				):






            '''simple docstring'''




            __UpperCamelCase   = ids_tensor([self.batch_size, self.seq_length],self.vocab_size				)

            __UpperCamelCase   = None
            if self.use_input_mask:
                 __UpperCamelCase   = random_attention_mask([self.batch_size, self.seq_length]				)

            __UpperCamelCase   = None
            if self.use_token_type_ids:
                 __UpperCamelCase   = ids_tensor([self.batch_size, self.seq_length],self.type_vocab_size				)

            __UpperCamelCase   = None
            __UpperCamelCase   = None
            __UpperCamelCase   = None
            if self.use_labels:
                 __UpperCamelCase   = ids_tensor([self.batch_size],self.type_sequence_label_size				)
                 __UpperCamelCase   = ids_tensor([self.batch_size, self.seq_length],self.num_labels				)
                 __UpperCamelCase   = ids_tensor([self.batch_size],self.num_choices				)

            __UpperCamelCase   = self.get_config()

            return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







       def 		snake_case_  ( self:   str				):






            '''simple docstring'''




            return YosoConfig(
                vocab_size=self.vocab_size,hidden_size=self.hidden_size,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,max_position_embeddings=self.max_position_embeddings,type_vocab_size=self.type_vocab_size,is_decoder=A_,initializer_range=self.initializer_range,)







       def 		snake_case_  ( self:   int				):






            '''simple docstring'''




            __UpperCamelCase   = self.get_config()
            __UpperCamelCase   = 300
            return config







       def 		snake_case_  ( self:   int				):






            '''simple docstring'''




            (
                __UpperCamelCase			
            )   = self.prepare_config_and_inputs()

            __UpperCamelCase   = True
            __UpperCamelCase   = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]				)
            __UpperCamelCase   = ids_tensor([self.batch_size, self.seq_length],vocab_size=2				)

            return (
                config,
                input_ids,
                token_type_ids,
                input_mask,
                sequence_labels,
                token_labels,
                choice_labels,
                encoder_hidden_states,
                encoder_attention_mask,
            )







       def 		snake_case_  ( self:   Tuple,A_:   List[str],A_:   Tuple,A_:   Any,A_:   Tuple,A_:   Any,A_:   Union[str, Any],A_:   Any				):






            '''simple docstring'''




            __UpperCamelCase   = YosoModel(config=A_				)
            model.to(A_				)
            model.eval()
            __UpperCamelCase   = model(A_,attention_mask=A_,token_type_ids=A_				)
            __UpperCamelCase   = model(A_,token_type_ids=A_				)
            __UpperCamelCase   = model(A_				)
            self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)				)







       def 		snake_case_  ( self:   Union[str, Any],A_:   Dict,A_:   List[Any],A_:   Union[str, Any],A_:   Optional[Any],A_:   int,A_:   Tuple,A_:   int,A_:   Any,A_:   Tuple,):






            '''simple docstring'''




            __UpperCamelCase   = True
            __UpperCamelCase   = YosoModel(A_				)
            model.to(A_				)
            model.eval()
            __UpperCamelCase   = model(
                A_,attention_mask=A_,token_type_ids=A_,encoder_hidden_states=A_,encoder_attention_mask=A_,)
            __UpperCamelCase   = model(
                A_,attention_mask=A_,token_type_ids=A_,encoder_hidden_states=A_,)
            __UpperCamelCase   = model(A_,attention_mask=A_,token_type_ids=A_				)
            self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)				)







       def 		snake_case_  ( self:   Optional[Any],A_:   Union[str, Any],A_:   str,A_:   Tuple,A_:   Tuple,A_:   Dict,A_:   Any,A_:   List[Any]				):






            '''simple docstring'''




            __UpperCamelCase   = YosoForMaskedLM(config=A_				)
            model.to(A_				)
            model.eval()
            __UpperCamelCase   = model(A_,attention_mask=A_,token_type_ids=A_,labels=A_				)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size)				)







       def 		snake_case_  ( self:   Dict,A_:   Optional[Any],A_:   str,A_:   Optional[int],A_:   Optional[int],A_:   Dict,A_:   int,A_:   Union[str, Any]				):






            '''simple docstring'''




            __UpperCamelCase   = YosoForQuestionAnswering(config=A_				)
            model.to(A_				)
            model.eval()
            __UpperCamelCase   = model(
                A_,attention_mask=A_,token_type_ids=A_,start_positions=A_,end_positions=A_,)
            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 		snake_case_  ( self:   Optional[int],A_:   int,A_:   Dict,A_:   List[Any],A_:   Dict,A_:   Union[str, Any],A_:   Optional[Any],A_:   List[Any]				):






            '''simple docstring'''




            __UpperCamelCase   = self.num_labels
            __UpperCamelCase   = YosoForSequenceClassification(A_				)
            model.to(A_				)
            model.eval()
            __UpperCamelCase   = model(A_,attention_mask=A_,token_type_ids=A_,labels=A_				)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)				)







       def 		snake_case_  ( self:   Union[str, Any],A_:   Any,A_:   List[Any],A_:   Optional[int],A_:   Optional[int],A_:   Union[str, Any],A_:   int,A_:   Dict				):






            '''simple docstring'''




            __UpperCamelCase   = self.num_labels
            __UpperCamelCase   = YosoForTokenClassification(config=A_				)
            model.to(A_				)
            model.eval()
            __UpperCamelCase   = model(A_,attention_mask=A_,token_type_ids=A_,labels=A_				)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.num_labels)				)







       def 		snake_case_  ( self:   Optional[int],A_:   Union[str, Any],A_:   Union[str, Any],A_:   Union[str, Any],A_:   List[str],A_:   Dict,A_:   List[Any],A_:   int				):






            '''simple docstring'''




            __UpperCamelCase   = self.num_choices
            __UpperCamelCase   = YosoForMultipleChoice(config=A_				)
            model.to(A_				)
            model.eval()
            __UpperCamelCase   = input_ids.unsqueeze(1				).expand(-1,self.num_choices,-1				).contiguous()
            __UpperCamelCase   = token_type_ids.unsqueeze(1				).expand(-1,self.num_choices,-1				).contiguous()
            __UpperCamelCase   = input_mask.unsqueeze(1				).expand(-1,self.num_choices,-1				).contiguous()
            __UpperCamelCase   = model(
                A_,attention_mask=A_,token_type_ids=A_,labels=A_,)
            self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_choices)				)







       def 		snake_case_  ( self:   str				):






            '''simple docstring'''




            __UpperCamelCase   = self.prepare_config_and_inputs()
            (
                __UpperCamelCase			
            )   = config_and_inputs
            __UpperCamelCase   = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
            return config, inputs_dict



@require_torch
class   snake_case__ (snake_case__							,			snake_case__							,			unittest.TestCase	):
       _lowercase       							=    (
           (
               YosoModel,
               YosoForMaskedLM,
               YosoForMultipleChoice,
               YosoForQuestionAnswering,
               YosoForSequenceClassification,
               YosoForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       _lowercase       							=    False
       _lowercase       							=    False
       _lowercase       							=    False

       _lowercase       							=    ()
       _lowercase       							=    (
           {
               'feature-extraction': YosoModel,
               'fill-mask': YosoForMaskedLM,
               'question-answering': YosoForQuestionAnswering,
               'text-classification': YosoForSequenceClassification,
               'token-classification': YosoForTokenClassification,
               'zero-shot': YosoForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )







       def 		snake_case_  ( self:   List[Any]				):






            '''simple docstring'''




            __UpperCamelCase   = YosoModelTester(self				)
            __UpperCamelCase   = ConfigTester(self,config_class=A_,hidden_size=37				)







       def 		snake_case_  ( self:   List[str]				):






            '''simple docstring'''




            self.config_tester.run_common_tests()







       def 		snake_case_  ( self:   Optional[int]				):






            '''simple docstring'''




            __UpperCamelCase   = self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*A_				)







       def 		snake_case_  ( self:   Union[str, Any]				):






            '''simple docstring'''




            __UpperCamelCase   = self.model_tester.prepare_config_and_inputs()
            for type in ["absolute", "relative_key", "relative_key_query"]:
                 __UpperCamelCase   = type
                 self.model_tester.create_and_check_model(*A_				)







       def 		snake_case_  ( self:   Dict				):






            '''simple docstring'''




            __UpperCamelCase   = self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_lm(*A_				)







       def 		snake_case_  ( self:   int				):






            '''simple docstring'''




            __UpperCamelCase   = self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_multiple_choice(*A_				)







       def 		snake_case_  ( self:   Optional[Any]				):






            '''simple docstring'''




            __UpperCamelCase   = self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_question_answering(*A_				)







       def 		snake_case_  ( self:   Dict				):






            '''simple docstring'''




            __UpperCamelCase   = self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_sequence_classification(*A_				)







       def 		snake_case_  ( self:   Dict				):






            '''simple docstring'''




            __UpperCamelCase   = self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_token_classification(*A_				)







       @slow
       def 		snake_case_  ( self:   Union[str, Any]				):






            '''simple docstring'''




            for model_name in YOSO_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __UpperCamelCase   = YosoModel.from_pretrained(A_				)
                 self.assertIsNotNone(A_				)







       def 		snake_case_  ( self:   Optional[int]				):






            '''simple docstring'''




            return



@require_torch
class   snake_case__ (unittest.TestCase	):







       @slow
       def 		snake_case_  ( self:   Any				):






            '''simple docstring'''




            __UpperCamelCase   = YosoModel.from_pretrained('uw-madison/yoso-4096'				)
            __UpperCamelCase   = torch.tensor([[0, 1, 2, 3, 4, 5]]				)

            with torch.no_grad():
                 __UpperCamelCase   = model(A_				)[0]

            __UpperCamelCase   = torch.Size((1, 6, 768)				)
            self.assertEqual(output.shape,A_				)

            __UpperCamelCase   = torch.tensor(
                [[[-0.0_6_1_1, 0.1_2_4_2, 0.0_8_4_0], [0.0_2_8_0, -0.0_0_4_8, 0.1_1_2_5], [0.0_1_0_6, 0.0_2_2_6, 0.0_7_5_1]]]				)

            self.assertTrue(torch.allclose(output[:, :3, :3],A_,atol=1E-4				)				)







       @slow
       def 		snake_case_  ( self:   List[str]				):






            '''simple docstring'''




            __UpperCamelCase   = YosoForMaskedLM.from_pretrained('uw-madison/yoso-4096'				)
            __UpperCamelCase   = torch.tensor([[0, 1, 2, 3, 4, 5]]				)

            with torch.no_grad():
                 __UpperCamelCase   = model(A_				)[0]

            __UpperCamelCase   = 5_0265

            __UpperCamelCase   = torch.Size((1, 6, vocab_size)				)
            self.assertEqual(output.shape,A_				)

            __UpperCamelCase   = torch.tensor(
                [[[-2.1_3_1_3, -3.7_2_8_5, -2.2_4_0_7], [-2.7_0_4_7, -3.3_3_1_4, -2.6_4_0_8], [0.0_6_2_9, -2.5_1_6_6, -0.3_3_5_6]]]				)

            self.assertTrue(torch.allclose(output[:, :3, :3],A_,atol=1E-4				)				)







       @slow
       def 		snake_case_  ( self:   Optional[Any]				):






            '''simple docstring'''




            __UpperCamelCase   = YosoForMaskedLM.from_pretrained('uw-madison/yoso-4096'				)
            __UpperCamelCase   = torch.arange(4096				).unsqueeze(0				)

            with torch.no_grad():
                 __UpperCamelCase   = model(A_				)[0]

            __UpperCamelCase   = 5_0265

            __UpperCamelCase   = torch.Size((1, 4096, vocab_size)				)
            self.assertEqual(output.shape,A_				)

            __UpperCamelCase   = torch.tensor(
                [[[-2.3_9_1_4, -4.3_7_4_2, -5.0_9_5_6], [-4.0_9_8_8, -4.2_3_8_4, -7.0_4_0_6], [-3.1_4_2_7, -3.7_1_9_2, -6.6_8_0_0]]]				)

            self.assertTrue(torch.allclose(output[:, :3, :3],A_,atol=1E-4				)				)






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

from transformers import BigBirdTokenizerFast


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






def 		_A		(		_lowercase				,     _lowercase=0				,     _lowercase=None   )				->   Union[str, Any]:


     """simple docstring"""


     return [" ".join(x.split(' '   )[begin:end]   ) for x in answers if len(x.split(' '   )   ) > 1]






def 		_A		(		_lowercase				,     _lowercase=False   )				->   Tuple:


     """simple docstring"""


     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"
          __UpperCamelCase   = (
              given_answers + get_sub_answers(_lowercase				,     begin=1   ) + get_sub_answers(_lowercase				,     end=-1   )
          )
     __UpperCamelCase   = []
     for answer in given_answers:
          __UpperCamelCase   = answer.replace('_'				,     ' '   ).lower()
          __UpperCamelCase   = ''.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 		_A		(		_lowercase				,     _lowercase				,     _lowercase=1				,     _lowercase=1_00   )				->   Any:


     """simple docstring"""


     __UpperCamelCase,						__UpperCamelCase   = jax.lax.top_k(_lowercase				,     _lowercase   )
     __UpperCamelCase,						__UpperCamelCase   = jax.lax.top_k(_lowercase				,     _lowercase   )

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

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






def 		_A		(		_lowercase   )				->   List[str]:


     """simple docstring"""


     __UpperCamelCase   = sample['question']['text']
     __UpperCamelCase   = sample['document']['tokens']['token']
     __UpperCamelCase   = sample['document']['tokens']['is_html']
     __UpperCamelCase   = sample['annotations']['long_answer']
     __UpperCamelCase   = sample['annotations']['short_answers']

     __UpperCamelCase   = ' '.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",
               }

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

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

     __UpperCamelCase   = '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 		_A		(		)				->   Optional[int]:


     """simple docstring"""


     __UpperCamelCase   = load_from_disk('natural-questions-validation'   )
     __UpperCamelCase   = dataset.map(_lowercase   ).remove_columns(['annotations', 'document', 'id']   )
     print(_lowercase   )

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

     __UpperCamelCase   = 'vasudevgupta/flax-bigbird-natural-questions'
     __UpperCamelCase   = FlaxBigBirdForNaturalQuestions.from_pretrained(_lowercase   )
     __UpperCamelCase   = BigBirdTokenizerFast.from_pretrained(_lowercase   )

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

     def evaluate(_lowercase   ):
          # encode question and context so that they are separated by a tokenizer.sep_token and cut at max_length
          __UpperCamelCase   = tokenizer(
              example['question']				,     example['context']				,     return_tensors='np'				,     max_length=40_96				,     padding='max_length'				,     truncation=_lowercase				,     )

          __UpperCamelCase,						__UpperCamelCase,						__UpperCamelCase   = forward(**_lowercase   )

          __UpperCamelCase   = CATEGORY_MAPPING[category.item()]

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

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

          __UpperCamelCase   = 38 if predicted_category == 'short' else 10_24
          __UpperCamelCase,						__UpperCamelCase   = get_best_valid_start_end_idx(
              start_scores[0]				,     end_scores[0]				,     top_k=8				,     max_size=_lowercase   )

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

          __UpperCamelCase   = expand_to_aliases(example['targets']				,     make_sub_answers=_lowercase   )
          __UpperCamelCase   = expand_to_aliases(example['output']   )

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

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

          return example

     __UpperCamelCase   = short_validation_dataset.map(_lowercase   )

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


if __name__ == "__main__":
    main()


