



"""simple docstring"""
import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union

import datasets
import numpy as np
import torch
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

A:  Any      				=						logging.getLogger(__name__)



@dataclass
class  SCREAMING_SNAKE_CASE__    :
   __lowerCAmelCase    :  str		=		field(
       metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}					)
   __lowerCAmelCase    :  Optional[str]		=		field(
       default=UpperCAmelCase__ ,     metadata={'help': 'Pretrained config name or path if not the same as model_name'}					)
   __lowerCAmelCase    :  Optional[str]		=		field(
       default=UpperCAmelCase__ ,     metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}					)
   __lowerCAmelCase    :  Optional[str]		=		field(
       default=UpperCAmelCase__ ,     metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} ,     )
   __lowerCAmelCase    :  bool		=		field(
       default=UpperCAmelCase__ ,     metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} ,     )
   __lowerCAmelCase    :  str		=		field(
       default='main' ,     metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} ,     )
   __lowerCAmelCase    :  bool		=		field(
       default=UpperCAmelCase__ ,     metadata={
           'help': (
               'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
               'with private models).'
           )
       } ,     )



@dataclass
class  SCREAMING_SNAKE_CASE__    :
   __lowerCAmelCase    :  Optional[str]		=		field(default=UpperCAmelCase__ ,     metadata={'help': 'The input training data file (a text file).'}					)
   __lowerCAmelCase    :  Optional[str]		=		field(
       default=UpperCAmelCase__ ,     metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} ,     )
   __lowerCAmelCase    :  bool		=		field(
       default=UpperCAmelCase__ ,     metadata={'help': 'Overwrite the cached training and evaluation sets'}					)
   __lowerCAmelCase    :  Optional[int]		=		field(
       default=UpperCAmelCase__ ,     metadata={'help': 'The number of processes to use for the preprocessing.'} ,     )
   __lowerCAmelCase    :  Optional[int]		=		field(
       default=UpperCAmelCase__ ,     metadata={
           'help': (
               'The maximum total input sequence length after tokenization. If passed, sequences longer '
               'than this will be truncated, sequences shorter will be padded.'
           )
       } ,     )
   __lowerCAmelCase    :  bool		=		field(
       default=UpperCAmelCase__ ,     metadata={
           'help': (
               'Whether to pad all samples to the maximum sentence length. '
               'If False, will pad the samples dynamically when batching to the maximum length in the batch. More '
               'efficient on GPU but very bad for TPU.'
           )
       } ,     )
   __lowerCAmelCase    :  Optional[int]		=		field(
       default=UpperCAmelCase__ ,     metadata={
           'help': (
               'For debugging purposes or quicker training, truncate the number of training examples to this '
               'value if set.'
           )
       } ,     )
   __lowerCAmelCase    :  Optional[int]		=		field(
       default=UpperCAmelCase__ ,     metadata={
           'help': (
               'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
               'value if set.'
           )
       } ,     )

   def       SCREAMING_SNAKE_CASE	(  self		)    -> int:





    '''simple docstring'''




    if self.train_file is not None:
     UpperCAmelCase      :   int      =      self.train_file.split("""."""		)[-1]
     assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
    if self.validation_file is not None:
     UpperCAmelCase      :   Optional[int]      =      self.validation_file.split("""."""		)[-1]
     assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."



@dataclass
class  SCREAMING_SNAKE_CASE__    :
   __lowerCAmelCase    :  PreTrainedTokenizerBase
   __lowerCAmelCase    :  Union[bool, str, PaddingStrategy]		=		True
   __lowerCAmelCase    :  Optional[int]		=		None
   __lowerCAmelCase    :  Optional[int]		=		None

   def __call__(  self ,	_SCREAMING_SNAKE_CASE		)    -> str:





    '''simple docstring'''




    UpperCAmelCase      :   List[Any]      =      "label" if "label" in features[0].keys() else "labels"
    UpperCAmelCase      :   int      =      [feature.pop(snake_case__		) for feature in features]
    UpperCAmelCase      :   str      =      len(snake_case__		)
    UpperCAmelCase      :   str      =      len(features[0]["""input_ids"""]		)
    UpperCAmelCase      :   List[Any]      =      [
        [{k: v[i] for k, v in feature.items()} for i in range(snake_case__		)] for feature in features
    ]
    UpperCAmelCase      :   Union[str, Any]      =      list(chain(*snake_case__		)		)

    UpperCAmelCase      :   Dict      =      self.tokenizer.pad(
        snake_case__ ,	padding=self.padding ,	max_length=self.max_length ,	pad_to_multiple_of=self.pad_to_multiple_of ,	return_tensors="""pt""" ,	)

    # Un-flatten
    UpperCAmelCase      :   List[str]      =      {k: v.view(snake_case__ ,	snake_case__ ,	-1		) for k, v in batch.items()}
    # Add back labels
    UpperCAmelCase      :   Union[str, Any]      =      torch.tensor(snake_case__ ,	dtype=torch.intaa		)
    return batch

def  _snake_case		(		):
 # See all possible arguments in src/transformers/training_args.py
 # or by passing the --help flag to this script.
 # We now keep distinct sets of args, for a cleaner separation of concerns.

 UpperCAmelCase      :   Dict      =      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
 if len(sys.argv		) == 2 and sys.argv[1].endswith(""".json"""		):
  # If we pass only one argument to the script and it's the path to a json file,
  # let's parse it to get our arguments.
  UpperCAmelCase      :   str      =      parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]		)		)
 else:
  UpperCAmelCase      :   Union[str, Any]      =      parser.parse_args_into_dataclasses()

 # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
 # information sent is the one passed as arguments along with your Python/PyTorch versions.
 send_example_telemetry("""run_swag"""     ,						lowercase__     ,						lowercase__		)

 # Setup logging
 logging.basicConfig(
     format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""     ,						datefmt="""%m/%d/%Y %H:%M:%S"""     ,						handlers=[logging.StreamHandler(sys.stdout		)]     ,						)

 if training_args.should_log:
  # The default of training_args.log_level is passive, so we set log level at info here to have that default.
  transformers.utils.logging.set_verbosity_info()

 UpperCAmelCase      :   Optional[int]      =      training_args.get_process_log_level()
 logger.setLevel(lowercase__		)
 datasets.utils.logging.set_verbosity(lowercase__		)
 transformers.utils.logging.set_verbosity(lowercase__		)
 transformers.utils.logging.enable_default_handler()
 transformers.utils.logging.enable_explicit_format()

 # Log on each process the small summary:
 logger.warning(
     F"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
     + F"distributed training: {bool(training_args.local_rank != -1		)}, 16-bits training: {training_args.fpaa}"		)
 logger.info(F"Training/evaluation parameters {training_args}"		)

 # Detecting last checkpoint.
 UpperCAmelCase      :   Optional[Any]      =      None
 if os.path.isdir(training_args.output_dir		) and training_args.do_train and not training_args.overwrite_output_dir:
  UpperCAmelCase      :   Optional[Any]      =      get_last_checkpoint(training_args.output_dir		)
  if last_checkpoint is None and len(os.listdir(training_args.output_dir		)		) > 0:
   raise ValueError(
       F"Output directory ({training_args.output_dir}) already exists and is not empty. "
       """Use --overwrite_output_dir to overcome."""		)
  elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
   logger.info(
       F"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
       """the `--output_dir` or add `--overwrite_output_dir` to train from scratch."""		)

  # Set seed before initializing model.
 set_seed(training_args.seed		)

 # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
 # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
 # (the dataset will be downloaded automatically from the datasets Hub).

 # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
 # 'text' is found. You can easily tweak this behavior (see below).

 # In distributed training, the load_dataset function guarantee that only one local process can concurrently
 # download the dataset.
 if data_args.train_file is not None or data_args.validation_file is not None:
  UpperCAmelCase      :   List[str]      =      {}
  if data_args.train_file is not None:
   UpperCAmelCase      :   Optional[Any]      =      data_args.train_file
  if data_args.validation_file is not None:
   UpperCAmelCase      :   Dict      =      data_args.validation_file
  UpperCAmelCase      :   Any      =      data_args.train_file.split("""."""		)[-1]
  UpperCAmelCase      :   Union[str, Any]      =      load_dataset(
      lowercase__     ,						data_files=lowercase__     ,						cache_dir=model_args.cache_dir     ,						use_auth_token=True if model_args.use_auth_token else None     ,						)
 else:
  # Downloading and loading the swag dataset from the hub.
  UpperCAmelCase      :   Dict      =      load_dataset(
      """swag"""     ,						"""regular"""     ,						cache_dir=model_args.cache_dir     ,						use_auth_token=True if model_args.use_auth_token else None     ,						)
 # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
 # https://huggingface.co/docs/datasets/loading_datasets.html.

 # Load pretrained model and tokenizer

 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.
 UpperCAmelCase      :   str      =      AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path     ,						cache_dir=model_args.cache_dir     ,						revision=model_args.model_revision     ,						use_auth_token=True if model_args.use_auth_token else None     ,						)
 UpperCAmelCase      :   Optional[int]      =      AutoTokenizer.from_pretrained(
     model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path     ,						cache_dir=model_args.cache_dir     ,						use_fast=model_args.use_fast_tokenizer     ,						revision=model_args.model_revision     ,						use_auth_token=True if model_args.use_auth_token else None     ,						)
 UpperCAmelCase      :   Any      =      AutoModelForMultipleChoice.from_pretrained(
     model_args.model_name_or_path     ,						from_tf=bool(""".ckpt""" in model_args.model_name_or_path		)     ,						config=lowercase__     ,						cache_dir=model_args.cache_dir     ,						revision=model_args.model_revision     ,						use_auth_token=True if model_args.use_auth_token else None     ,						)

 # When using your own dataset or a different dataset from swag, you will probably need to change this.
 UpperCAmelCase      :   Dict      =      [F"ending{i}" for i in range(4		)]
 UpperCAmelCase      :   Optional[int]      =      "sent1"
 UpperCAmelCase      :   Dict      =      "sent2"

 if data_args.max_seq_length is None:
  UpperCAmelCase      :   Dict      =      tokenizer.model_max_length
  if max_seq_length > 1024:
   logger.warning(
       """The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value"""
       """ of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can"""
       """ override this default with `--block_size xxx`."""		)
   UpperCAmelCase      :   List[str]      =      1024
 else:
  if data_args.max_seq_length > tokenizer.model_max_length:
   logger.warning(
       F"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
       F"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."		)
  UpperCAmelCase      :   int      =      min(data_args.max_seq_length     ,						tokenizer.model_max_length		)

 # Preprocessing the datasets.
 def preprocess_function(UpperCamelCase		:						str		):
  UpperCAmelCase      :   List[Any]      =      [[context] * 4 for context in examples[context_name]]
  UpperCAmelCase      :   List[Any]      =      examples[question_header_name]
  UpperCAmelCase      :   Optional[int]      =      [
      [F"{header} {examples[end][i]}" for end in ending_names] for i, header in enumerate(lowercase__		)
  ]

  # Flatten out
  UpperCAmelCase      :   Tuple      =      list(chain(*lowercase__		)		)
  UpperCAmelCase      :   Any      =      list(chain(*lowercase__		)		)

  # Tokenize
  UpperCAmelCase      :   Optional[Any]      =      tokenizer(
      lowercase__     ,						lowercase__     ,						truncation=lowercase__     ,						max_length=lowercase__     ,						padding="""max_length""" if data_args.pad_to_max_length else False     ,						)
  # Un-flatten
  return {k: [v[i : i + 4] for i in range(0     ,						len(lowercase__		)     ,						4		)] for k, v in tokenized_examples.items()}

 if training_args.do_train:
  if "train" not in raw_datasets:
   raise ValueError("""--do_train requires a train dataset"""		)
  UpperCAmelCase      :   Any      =      raw_datasets["train"]
  if data_args.max_train_samples is not None:
   UpperCAmelCase      :   Tuple      =      min(len(lowercase__		)     ,						data_args.max_train_samples		)
   UpperCAmelCase      :   Tuple      =      train_dataset.select(range(lowercase__		)		)
  with training_args.main_process_first(desc="""train dataset map pre-processing"""		):
   UpperCAmelCase      :   List[Any]      =      train_dataset.map(
       lowercase__     ,						batched=lowercase__     ,						num_proc=data_args.preprocessing_num_workers     ,						load_from_cache_file=not data_args.overwrite_cache     ,						)

 if training_args.do_eval:
  if "validation" not in raw_datasets:
   raise ValueError("""--do_eval requires a validation dataset"""		)
  UpperCAmelCase      :   Optional[Any]      =      raw_datasets["validation"]
  if data_args.max_eval_samples is not None:
   UpperCAmelCase      :   Any      =      min(len(lowercase__		)     ,						data_args.max_eval_samples		)
   UpperCAmelCase      :   Dict      =      eval_dataset.select(range(lowercase__		)		)
  with training_args.main_process_first(desc="""validation dataset map pre-processing"""		):
   UpperCAmelCase      :   Optional[Any]      =      eval_dataset.map(
       lowercase__     ,						batched=lowercase__     ,						num_proc=data_args.preprocessing_num_workers     ,						load_from_cache_file=not data_args.overwrite_cache     ,						)

  # Data collator
 UpperCAmelCase      :   Optional[int]      =      (
     default_data_collator
     if data_args.pad_to_max_length
     else DataCollatorForMultipleChoice(tokenizer=lowercase__     ,						pad_to_multiple_of=8 if training_args.fpaa else None		)
 )

 # Metric
 def compute_metrics(UpperCamelCase		:						Optional[Any]		):
  UpperCAmelCase      :   List[Any]      =      eval_predictions
  UpperCAmelCase      :   str      =      np.argmax(lowercase__     ,						axis=1		)
  return {"accuracy": (preds == label_ids).astype(np.floataa		).mean().item()}

 # Initialize our Trainer
 UpperCAmelCase      :   Optional[int]      =      Trainer(
     model=lowercase__     ,						args=lowercase__     ,						train_dataset=train_dataset if training_args.do_train else None     ,						eval_dataset=eval_dataset if training_args.do_eval else None     ,						tokenizer=lowercase__     ,						data_collator=lowercase__     ,						compute_metrics=lowercase__     ,						)

 # Training
 if training_args.do_train:
  UpperCAmelCase      :   Any      =      None
  if training_args.resume_from_checkpoint is not None:
   UpperCAmelCase      :   Dict      =      training_args.resume_from_checkpoint
  elif last_checkpoint is not None:
   UpperCAmelCase      :   Union[str, Any]      =      last_checkpoint
  UpperCAmelCase      :   Any      =      trainer.train(resume_from_checkpoint=lowercase__		)
  trainer.save_model()  # Saves the tokenizer too for easy upload
  UpperCAmelCase      :   int      =      train_result.metrics

  UpperCAmelCase      :   Optional[int]      =      (
      data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase__		)
  )
  UpperCAmelCase      :   str      =      min(lowercase__     ,						len(lowercase__		)		)

  trainer.log_metrics("""train"""     ,						lowercase__		)
  trainer.save_metrics("""train"""     ,						lowercase__		)
  trainer.save_state()

 # Evaluation
 if training_args.do_eval:
  logger.info("""*** Evaluate ***"""		)

  UpperCAmelCase      :   int      =      trainer.evaluate()
  UpperCAmelCase      :   int      =      data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowercase__		)
  UpperCAmelCase      :   Tuple      =      min(lowercase__     ,						len(lowercase__		)		)

  trainer.log_metrics("""eval"""     ,						lowercase__		)
  trainer.save_metrics("""eval"""     ,						lowercase__		)

 UpperCAmelCase      :   Optional[Any]      =      {
     "finetuned_from": model_args.model_name_or_path,
     "tasks": "multiple-choice",
     "dataset_tags": "swag",
     "dataset_args": "regular",
     "dataset": "SWAG",
     "language": "en",
 }

 if training_args.push_to_hub:
  trainer.push_to_hub(**lowercase__		)
 else:
  trainer.create_model_card(**lowercase__		)

def  _snake_case		(		UpperCamelCase		:						Union[str, Any]		):
 # For xla_spawn (TPUs)
 main()


if __name__ == "__main__":
      main()


'''simple docstring'''





import unittest

from transformers import BigBirdConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
      import jax

      from transformers.models.big_bird.modeling_flax_big_bird import (
          FlaxBigBirdForCausalLM,
          FlaxBigBirdForMaskedLM,
          FlaxBigBirdForMultipleChoice,
          FlaxBigBirdForPreTraining,
          FlaxBigBirdForQuestionAnswering,
          FlaxBigBirdForSequenceClassification,
          FlaxBigBirdForTokenClassification,
          FlaxBigBirdModel,
      )






class 							UpperCAmelCase_							(    unittest.TestCase				):

 '''simple docstring'''







 def __init__(					self		:  Tuple			,				snake_case__		:  List[str]			,				snake_case__		:  Union[str, Any]=2			,				snake_case__		:  int=56			,				snake_case__		:  Any=True			,				snake_case__		:  Union[str, Any]=True			,				snake_case__		:  Optional[int]=True			,				snake_case__		:  Any=True			,				snake_case__		:  Tuple=99			,				snake_case__		:  Any=32			,				snake_case__		:  List[Any]=2			,				snake_case__		:  Optional[Any]=2			,				snake_case__		:  Any=7			,				snake_case__		:  Union[str, Any]="gelu_new"			,				snake_case__		:  List[Any]=0.1			,				snake_case__		:  Optional[Any]=0.1			,				snake_case__		:  Optional[int]=5_12			,				snake_case__		:  Optional[int]=16			,				snake_case__		:  int=2			,				snake_case__		:  List[Any]=0.02			,				snake_case__		:  int=4			,				snake_case__		:  Optional[Any]="block_sparse"			,				snake_case__		:  Union[str, Any]=True			,				snake_case__		:  List[Any]=False			,				snake_case__		:  Optional[Any]=2			,				snake_case__		:  Optional[Any]=3			,				):



   '''simple docstring'''




   UpperCAmelCase__      :					List[Any]				       =							parent
   UpperCAmelCase__      :					Dict				       =							batch_size
   UpperCAmelCase__      :					Tuple				       =							seq_length
   UpperCAmelCase__      :					Optional[int]				       =							is_training
   UpperCAmelCase__      :					Optional[int]				       =							use_attention_mask
   UpperCAmelCase__      :					List[Any]				       =							use_token_type_ids
   UpperCAmelCase__      :					Dict				       =							use_labels
   UpperCAmelCase__      :					Tuple				       =							vocab_size
   UpperCAmelCase__      :					str				       =							hidden_size
   UpperCAmelCase__      :					List[str]				       =							num_hidden_layers
   UpperCAmelCase__      :					Union[str, Any]				       =							num_attention_heads
   UpperCAmelCase__      :					Optional[int]				       =							intermediate_size
   UpperCAmelCase__      :					Optional[int]				       =							hidden_act
   UpperCAmelCase__      :					Union[str, Any]				       =							hidden_dropout_prob
   UpperCAmelCase__      :					str				       =							attention_probs_dropout_prob
   UpperCAmelCase__      :					str				       =							max_position_embeddings
   UpperCAmelCase__      :					Any				       =							type_vocab_size
   UpperCAmelCase__      :					Dict				       =							type_sequence_label_size
   UpperCAmelCase__      :					Dict				       =							initializer_range
   UpperCAmelCase__      :					Any				       =							num_choices

   UpperCAmelCase__      :					List[str]				       =							rescale_embeddings
   UpperCAmelCase__      :					Union[str, Any]				       =							attention_type
   UpperCAmelCase__      :					Union[str, Any]				       =							use_bias
   UpperCAmelCase__      :					Union[str, Any]				       =							block_size
   UpperCAmelCase__      :					Any				       =							num_random_blocks







 def 							UpperCamelCase  (					self		:  Optional[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							ids_tensor([self.batch_size, self.seq_length]			,				self.vocab_size )

   UpperCAmelCase__      :					Optional[Any]				       =							None
   if self.use_attention_mask:
     UpperCAmelCase__      :					List[Any]				       =							random_attention_mask([self.batch_size, self.seq_length] )

   UpperCAmelCase__      :					Union[str, Any]				       =							None
   if self.use_token_type_ids:
     UpperCAmelCase__      :					Any				       =							ids_tensor([self.batch_size, self.seq_length]			,				self.type_vocab_size )

   UpperCAmelCase__      :					Union[str, Any]				       =							BigBirdConfig(
       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=snake_case__			,				initializer_range=self.initializer_range			,				attention_type=self.attention_type			,				block_size=self.block_size			,				num_random_blocks=self.num_random_blocks			,				use_bias=self.use_bias			,				rescale_embeddings=self.rescale_embeddings			,				)

   return config, input_ids, token_type_ids, attention_mask







 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							self.prepare_config_and_inputs()
   UpperCAmelCase__       ,			UpperCAmelCase__       ,			UpperCAmelCase__       ,			UpperCAmelCase__      :					Tuple				       =							config_and_inputs
   UpperCAmelCase__      :					str				       =							{
       "input_ids": input_ids,
       "token_type_ids": token_type_ids,
       "attention_mask": attention_mask,
   }
   return config, inputs_dict






@require_flax
class 							UpperCAmelCase_							(    A					,				unittest.TestCase				):

 '''simple docstring'''
 lowercase_					:    Any				=							(
     (
         FlaxBigBirdForCausalLM,
         FlaxBigBirdModel,
         FlaxBigBirdForPreTraining,
         FlaxBigBirdForMaskedLM,
         FlaxBigBirdForMultipleChoice,
         FlaxBigBirdForQuestionAnswering,
         FlaxBigBirdForSequenceClassification,
         FlaxBigBirdForTokenClassification,
     )
     if is_flax_available()
     else ()
 )

 lowercase_					:    Optional[Any]				=							False
 lowercase_					:    str				=							False







 def 							UpperCamelCase  (					self		:  Optional[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							FlaxBigBirdModelTester(self )







 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   super().test_from_pretrained_save_pretrained()







 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   super().test_from_pretrained_with_no_automatic_init()







 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   super().test_no_automatic_init()







 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def 							UpperCamelCase  (					self		:  Dict ):



   '''simple docstring'''




   super().test_hidden_states_output()







 @slow
 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   for model_class_name in self.all_model_classes:
     UpperCAmelCase__      :					List[Any]				       =							model_class_name.from_pretrained("google/bigbird-roberta-base" )
     self.assertIsNotNone(snake_case__ )







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



   '''simple docstring'''




   if self.test_attn_probs:
     super().test_attention_outputs()







 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__       ,			UpperCAmelCase__      :					str				       =							self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     with self.subTest(model_class.__name__ ):
       UpperCAmelCase__      :					Union[str, Any]				       =							self._prepare_for_class(snake_case__			,				snake_case__ )
       UpperCAmelCase__      :					List[Any]				       =							model_class(snake_case__ )

       @jax.jit
       def model_jitted(snake_case__		:  int			,				snake_case__		:  Optional[int]=None			,				**snake_case__		:  Optional[Any] ):
         return model(input_ids=snake_case__			,				attention_mask=snake_case__			,				**snake_case__ )

       with self.subTest("JIT Enabled" ):
         UpperCAmelCase__      :					List[Any]				       =							model_jitted(**snake_case__ ).to_tuple()

       with self.subTest("JIT Disabled" ):
         with jax.disable_jit():
           UpperCAmelCase__      :					Tuple				       =							model_jitted(**snake_case__ ).to_tuple()

       self.assertEqual(len(snake_case__ )			,				len(snake_case__ ) )
       for jitted_output, output in zip(snake_case__			,				snake_case__ ):
         self.assertEqual(jitted_output.shape			,				output.shape )







 def 							UpperCamelCase  (					self		:  List[str]			,				snake_case__		:  int			,				snake_case__		:  Dict			,				snake_case__		:  Any			,				snake_case__		:  Union[str, Any]=1e-5			,				snake_case__		:  Any="outputs"			,				snake_case__		:  Optional[Any]=None ):



   '''simple docstring'''




   if name.startswith("outputs.attentions" ):
     return
   else:
     super().check_pt_flax_outputs(snake_case__			,				snake_case__			,				snake_case__			,				snake_case__			,				snake_case__			,				snake_case__ )



