


"""simple docstring"""
import argparse

from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird
from transformers.utils import logging


logging.set_verbosity_info()

def 				_snake_case      (   __snake_case							:      List[Any]						, __snake_case							:      str						, __snake_case							:      int						, __snake_case							:      int   ):




   """simple docstring"""







   _lowerCamelCase	:					int   =		BigBirdConfig.from_json_file(__snake_case   )
   print(F'Building PyTorch model from configuration: {config}'   )

   if is_trivia_qa:
      _lowerCamelCase	:					List[str]   =		BigBirdForQuestionAnswering(__snake_case   )
   else:
      _lowerCamelCase	:					Union[str, Any]   =		BigBirdForPreTraining(__snake_case   )

   # Load weights from tf checkpoint
   load_tf_weights_in_big_bird(__snake_case						, __snake_case						, is_trivia_qa=__snake_case   )

   # Save pytorch-model
   print(F'Save PyTorch model to {pytorch_dump_path}'   )
   model.save_pretrained(__snake_case   )


if __name__ == "__main__":
 UpperCAmelCase				=						argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
 )
 parser.add_argument(
     """--big_bird_config_file""",
     default=None,
     type=str,
     required=True,
     help=(
         """The config json file corresponding to the pre-trained BERT model. \n"""
         """This specifies the model architecture."""
     ),
 )
 parser.add_argument(
     """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
 )
 parser.add_argument(
     """--is_trivia_qa""", action="""store_true""", help="""Whether to convert a model with a trivia_qa head."""
 )
 UpperCAmelCase				=						parser.parse_args()
 convert_tf_checkpoint_to_pytorch(
     args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa
 )






'''simple docstring'''





import json
import logging
import os
import sys
from time import time
from unittest.mock import patch

from transformers.testing_utils import TestCasePlus, require_torch_tpu


logging.basicConfig(level=logging.DEBUG)

A__    :   List[str]           =					logging.getLogger()





def   a_   (		_UpperCAmelCase    :      int				)    ->  Optional[int]:
      __snake_case :   List[str]													=    {}
      __snake_case :   List[str]													=    os.path.join(_UpperCAmelCase ,'all_results.json'				)
      if os.path.exists(_UpperCAmelCase				):
            with open(_UpperCAmelCase ,'r'				) as f:
                  __snake_case :   Dict													=    json.load(_UpperCAmelCase				)
      else:
            raise ValueError(f'''can\'t find {path}'''				)
      return results


A__    :   Dict           =					logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)





@require_torch_tpu
class  snake_case__						(    SCREAMING_SNAKE_CASE_				):
 def A_   (   self						:							Optional[Any]  )      ->   List[str]:







       '''simple docstring'''
       import xla_spawn

       __snake_case :   int													=    self.get_auto_remove_tmp_dir()
       __snake_case :   Tuple													=    f'''
            ./examples/pytorch/text-classification/run_glue.py
            --num_cores=8
            ./examples/pytorch/text-classification/run_glue.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --do_train
            --do_eval
            --debug tpu_metrics_debug
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --max_steps=10
            --warmup_steps=2
            --seed=42
            --max_seq_length=128
            '''.split()

       with patch.object(__a      ,     'argv'      ,     __a  ):
             __snake_case :   Tuple													=    time()
             xla_spawn.main()
             __snake_case :   Optional[int]													=    time()

             __snake_case :   List[Any]													=    get_results(__a  )
             self.assertGreaterEqual(result['eval_accuracy']      ,     0.7_5  )

             # Assert that the script takes less than 500 seconds to make sure it doesn't hang.
             self.assertLess(end - start      ,     500  )





 def A_   (   self						:							List[str]  )      ->   Optional[int]:







       '''simple docstring'''
       import xla_spawn

       __snake_case :   Optional[Any]													=    '\n            ./tests/test_trainer_tpu.py\n            --num_cores=8\n            ./tests/test_trainer_tpu.py\n            '.split()
       with patch.object(__a      ,     'argv'      ,     __a  ):
             xla_spawn.main()



