





import math
import unittest

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

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import (
      BioGptForCausalLM,
      BioGptForSequenceClassification,
      BioGptForTokenClassification,
      BioGptModel,
      BioGptTokenizer,
  )
  from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST






class     lowercase__       :

   '''simple docstring'''


   def __init__(    self,		__magic_name__,		__magic_name__=13,		__magic_name__=7,		__magic_name__=True,		__magic_name__=True,		__magic_name__=False,		__magic_name__=True,		__magic_name__=99,		__magic_name__=32,		__magic_name__=5,		__magic_name__=4,		__magic_name__=37,		__magic_name__="gelu",		__magic_name__=0.1,		__magic_name__=0.1,		__magic_name__=512,		__magic_name__=16,		__magic_name__=2,		__magic_name__=0.02,		__magic_name__=3,		__magic_name__=4,		__magic_name__=None,		) ->      List[Any]:






       """simple docstring"""
       UpperCamelCase__							:				List[Any]          =      parent
       UpperCamelCase__							:				Optional[int]          =      batch_size
       UpperCamelCase__							:				Optional[Any]          =      seq_length
       UpperCamelCase__							:				Optional[int]          =      is_training
       UpperCamelCase__							:				Tuple          =      use_input_mask
       UpperCamelCase__							:				str          =      use_token_type_ids
       UpperCamelCase__							:				List[Any]          =      use_labels
       UpperCamelCase__							:				int          =      vocab_size
       UpperCamelCase__							:				str          =      hidden_size
       UpperCamelCase__							:				Tuple          =      num_hidden_layers
       UpperCamelCase__							:				Any          =      num_attention_heads
       UpperCamelCase__							:				Any          =      intermediate_size
       UpperCamelCase__							:				Dict          =      hidden_act
       UpperCamelCase__							:				str          =      hidden_dropout_prob
       UpperCamelCase__							:				Optional[int]          =      attention_probs_dropout_prob
       UpperCamelCase__							:				List[Any]          =      max_position_embeddings
       UpperCamelCase__							:				int          =      type_vocab_size
       UpperCamelCase__							:				Dict          =      type_sequence_label_size
       UpperCamelCase__							:				Union[str, Any]          =      initializer_range
       UpperCamelCase__							:				int          =      num_labels
       UpperCamelCase__							:				Tuple          =      num_choices
       UpperCamelCase__							:				int          =      scope




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      ids_tensor([self.batch_size, self.seq_length],		self.vocab_size							)

       UpperCamelCase__							:				Tuple          =      None
       if self.use_input_mask:
           UpperCamelCase__							:				str          =      random_attention_mask([self.batch_size, self.seq_length]							)

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

       UpperCamelCase__							:				Dict          =      None
       UpperCamelCase__							:				Optional[Any]          =      None
       UpperCamelCase__							:				Dict          =      None
       if self.use_labels:
           UpperCamelCase__							:				List[Any]          =      ids_tensor([self.batch_size],		self.type_sequence_label_size							)
           UpperCamelCase__							:				Any          =      ids_tensor([self.batch_size, self.seq_length],		self.num_labels							)
           UpperCamelCase__							:				Dict          =      ids_tensor([self.batch_size],		self.num_choices							)

       UpperCamelCase__							:				List[str]          =      self.get_config()

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




   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       return BioGptConfig(
           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=__magic_name__,		initializer_range=self.initializer_range,		)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      BioGptModel(config=__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				List[str]          =      model(__magic_name__,		attention_mask=__magic_name__							)
       UpperCamelCase__							:				Optional[int]          =      model(__magic_name__							)
       self.parent.assertEqual(result.last_hidden_state.shape,		(self.batch_size, self.seq_length, self.hidden_size)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				int          =      BioGptForCausalLM(config=__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				Optional[Any]          =      model(__magic_name__,		attention_mask=__magic_name__,		token_type_ids=__magic_name__,		labels=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.seq_length, self.vocab_size)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		*__magic_name__							) ->      List[Any]:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      BioGptModel(config=__magic_name__							)
       model.to(__magic_name__							)
       model.eval()

       # create attention mask
       UpperCamelCase__							:				List[str]          =      torch.ones(input_ids.shape,		dtype=torch.long,		device=__magic_name__							)
       UpperCamelCase__							:				Optional[int]          =      self.seq_length // 2
       UpperCamelCase__							:				List[str]          =      0

       # first forward pass
       UpperCamelCase__							:				Optional[int]          =      model(__magic_name__,		attention_mask=__magic_name__							).to_tuple()

       # create hypothetical next token and extent to next_input_ids
       UpperCamelCase__							:				Union[str, Any]          =      ids_tensor((self.batch_size, 1),		config.vocab_size							)

       # change a random masked slice from input_ids
       UpperCamelCase__							:				Tuple          =      ids_tensor((1,),		__magic_name__							).item() + 1
       UpperCamelCase__							:				Tuple          =      ids_tensor((self.batch_size, 1),		config.vocab_size							).squeeze(-1							)
       UpperCamelCase__							:				str          =      random_other_next_tokens

       # append to next input_ids and attn_mask
       UpperCamelCase__							:				List[str]          =      torch.cat([input_ids, next_tokens],		dim=-1							)
       UpperCamelCase__							:				Optional[int]          =      torch.cat(
           [attn_mask, torch.ones((attn_mask.shape[0], 1),		dtype=torch.long,		device=__magic_name__							)],		dim=1,		)

       # get two different outputs
       UpperCamelCase__							:				str          =      model(__magic_name__,		attention_mask=__magic_name__							)['last_hidden_state']
       UpperCamelCase__							:				str          =      model(__magic_name__,		past_key_values=__magic_name__,		attention_mask=__magic_name__							)['last_hidden_state']

       # select random slice
       UpperCamelCase__							:				Dict          =      ids_tensor((1,),		output_from_past.shape[-1]							).item()
       UpperCamelCase__							:				Union[str, Any]          =      output_from_no_past[:, -1, random_slice_idx].detach()
       UpperCamelCase__							:				Tuple          =      output_from_past[:, 0, random_slice_idx].detach()

       # test that outputs are equal for slice
       self.parent.assertTrue(torch.allclose(__magic_name__,		__magic_name__,		atol=1E-3							)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		*__magic_name__							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				int          =      BioGptModel(config=__magic_name__							).to(__magic_name__							).eval()

       UpperCamelCase__							:				List[str]          =      torch.ones(input_ids.shape,		dtype=torch.long,		device=__magic_name__							)

       # first forward pass
       UpperCamelCase__							:				List[Any]          =      model(__magic_name__,		attention_mask=__magic_name__,		use_cache=__magic_name__							)

       UpperCamelCase__							:				Dict          =      outputs.to_tuple()

       # create hypothetical multiple next token and extent to next_input_ids
       UpperCamelCase__							:				Optional[Any]          =      ids_tensor((self.batch_size, 3),		config.vocab_size							)
       UpperCamelCase__							:				Optional[int]          =      ids_tensor((self.batch_size, 3),		2							)

       # append to next input_ids and
       UpperCamelCase__							:				Tuple          =      torch.cat([input_ids, next_tokens],		dim=-1							)
       UpperCamelCase__							:				Optional[Any]          =      torch.cat([attention_mask, next_attn_mask],		dim=-1							)

       UpperCamelCase__							:				List[Any]          =      model(__magic_name__,		attention_mask=__magic_name__							)['last_hidden_state']
       UpperCamelCase__							:				Dict          =      model(__magic_name__,		attention_mask=__magic_name__,		past_key_values=__magic_name__							)[
           'last_hidden_state'
       ]

       # select random slice
       UpperCamelCase__							:				Optional[Any]          =      ids_tensor((1,),		output_from_past.shape[-1]							).item()
       UpperCamelCase__							:				List[str]          =      output_from_no_past[:, -3:, random_slice_idx].detach()
       UpperCamelCase__							:				int          =      output_from_past[:, :, random_slice_idx].detach()

       self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]							)

       # test that outputs are equal for slice
       self.parent.assertTrue(torch.allclose(__magic_name__,		__magic_name__,		atol=1E-3							)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		*__magic_name__,		__magic_name__=False							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      BioGptForCausalLM(__magic_name__							)
       model.to(__magic_name__							)
       if gradient_checkpointing:
           model.gradient_checkpointing_enable()

       UpperCamelCase__							:				List[Any]          =      model(__magic_name__,		labels=__magic_name__							)
       self.parent.assertEqual(result.loss.shape,		()							)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.seq_length, self.vocab_size)							)
       result.loss.backward()




   def       UpperCamelCase__  (    self,		__magic_name__,		*__magic_name__							) ->      Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      BioGptModel(__magic_name__							)
       UpperCamelCase__							:				Optional[Any]          =      model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers							)
       for key in model.state_dict().keys():
           if "c_proj" in key and "weight" in key:
               self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]							) - model_std							),		0.001							)
               self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]							) - 0.0							),		0.01							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		*__magic_name__							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				Dict          =      self.num_labels
       UpperCamelCase__							:				int          =      BioGptForTokenClassification(__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				List[Any]          =      model(__magic_name__,		attention_mask=__magic_name__,		token_type_ids=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.seq_length, self.num_labels)							)




   def       UpperCamelCase__  (    self							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				str          =      self.prepare_config_and_inputs()
       (
           UpperCamelCase__ 
       )							:				Dict          =      config_and_inputs
       UpperCamelCase__							:				str          =      {'input_ids': input_ids, 'attention_mask': input_mask}
       return config, inputs_dict






@require_torch
class     lowercase__       (	__lowerCamelCase			,				__lowerCamelCase			,				__lowerCamelCase			,				unittest.TestCase				):

   '''simple docstring'''


   a						:							Dict   		=		(
       (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
       if is_torch_available()
       else ()
   )
   a						:							Optional[Any]   		=		(BioGptForCausalLM,) if is_torch_available() else ()
   a						:							List[Any]   		=		(
       {
           "feature-extraction": BioGptModel,
           "text-classification": BioGptForSequenceClassification,
           "text-generation": BioGptForCausalLM,
           "token-classification": BioGptForTokenClassification,
           "zero-shot": BioGptForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   a						:							List[Any]   		=		False




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      BioGptModelTester(self							)
       UpperCamelCase__							:				Optional[Any]          =      ConfigTester(self,		config_class=__magic_name__,		hidden_size=37							)




   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       self.config_tester.run_common_tests()




   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				List[Any]          =      self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
           UpperCamelCase__							:				Tuple          =      type
           self.model_tester.create_and_check_model(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Union[str, Any]:






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Tuple:






       """simple docstring"""
       UpperCamelCase__							:				str          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_forward_and_backwards(*__magic_name__,		gradient_checkpointing=__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				int          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_biogpt_weight_initialization(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				Any          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_biogpt_for_token_classification(*__magic_name__							)




   @slow
   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      BioGptForCausalLM.from_pretrained('''microsoft/biogpt'''							)
       model.to(__magic_name__							)
       UpperCamelCase__							:				List[str]          =      BioGptTokenizer.from_pretrained('''microsoft/biogpt'''							)

       UpperCamelCase__							:				Optional[int]          =      'left'

       # Define PAD Token = EOS Token = 50256
       UpperCamelCase__							:				Tuple          =      tokenizer.eos_token
       UpperCamelCase__							:				Optional[int]          =      model.config.eos_token_id

       # use different length sentences to test batching
       UpperCamelCase__							:				Union[str, Any]          =      [
           'Hello, my dog is a little',
           'Today, I',
       ]

       UpperCamelCase__							:				Optional[Any]          =      tokenizer(__magic_name__,		return_tensors='''pt''',		padding=__magic_name__							)
       UpperCamelCase__							:				Dict          =      inputs['input_ids'].to(__magic_name__							)

       UpperCamelCase__							:				Union[str, Any]          =      model.generate(
           input_ids=__magic_name__,		attention_mask=inputs['''attention_mask'''].to(__magic_name__							),		)

       UpperCamelCase__							:				Union[str, Any]          =      tokenizer(sentences[0],		return_tensors='''pt'''							).input_ids.to(__magic_name__							)
       UpperCamelCase__							:				List[Any]          =      model.generate(input_ids=__magic_name__							)

       UpperCamelCase__							:				List[str]          =      inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item()
       UpperCamelCase__							:				Any          =      tokenizer(sentences[1],		return_tensors='''pt'''							).input_ids.to(__magic_name__							)
       UpperCamelCase__							:				List[str]          =      model.generate(input_ids=__magic_name__,		max_length=model.config.max_length - num_paddings							)

       UpperCamelCase__							:				int          =      tokenizer.batch_decode(__magic_name__,		skip_special_tokens=__magic_name__							)
       UpperCamelCase__							:				List[Any]          =      tokenizer.decode(output_non_padded[0],		skip_special_tokens=__magic_name__							)
       UpperCamelCase__							:				int          =      tokenizer.decode(output_padded[0],		skip_special_tokens=__magic_name__							)

       UpperCamelCase__							:				str          =      [
           'Hello, my dog is a little bit bigger than a little bit.',
           'Today, I have a good idea of how to use the information',
       ]
       self.assertListEqual(__magic_name__,		__magic_name__							)
       self.assertListEqual(__magic_name__,		[non_padded_sentence, padded_sentence]							)




   @slow
   def       UpperCamelCase__  (    self							) ->      str:






       """simple docstring"""
       for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__							:				List[Any]          =      BioGptModel.from_pretrained(__magic_name__							)
           self.assertIsNotNone(__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__							:				Union[str, Any]          =      3
       UpperCamelCase__							:				Optional[int]          =      input_dict['input_ids']
       UpperCamelCase__							:				Tuple          =      input_ids.ne(1							).to(__magic_name__							)
       UpperCamelCase__							:				Any          =      ids_tensor([self.model_tester.batch_size],		self.model_tester.type_sequence_label_size							)
       UpperCamelCase__							:				Tuple          =      BioGptForSequenceClassification(__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				str          =      model(__magic_name__,		attention_mask=__magic_name__,		labels=__magic_name__							)
       self.assertEqual(result.logits.shape,		(self.model_tester.batch_size, self.model_tester.num_labels)							)




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				List[Any]          =      self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__							:				int          =      3
       UpperCamelCase__							:				List[Any]          =      'multi_label_classification'
       UpperCamelCase__							:				Tuple          =      input_dict['input_ids']
       UpperCamelCase__							:				List[Any]          =      input_ids.ne(1							).to(__magic_name__							)
       UpperCamelCase__							:				str          =      ids_tensor(
           [self.model_tester.batch_size, config.num_labels],		self.model_tester.type_sequence_label_size							).to(torch.float							)
       UpperCamelCase__							:				Union[str, Any]          =      BioGptForSequenceClassification(__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				List[str]          =      model(__magic_name__,		attention_mask=__magic_name__,		labels=__magic_name__							)
       self.assertEqual(result.logits.shape,		(self.model_tester.batch_size, self.model_tester.num_labels)							)






@require_torch
class     lowercase__       (	unittest.TestCase				):

   '''simple docstring'''


   @slow
   def       UpperCamelCase__  (    self							) ->      List[str]:






       """simple docstring"""
       UpperCamelCase__							:				str          =      BioGptForCausalLM.from_pretrained('''microsoft/biogpt'''							)
       UpperCamelCase__							:				List[str]          =      torch.tensor([[2, 4805, 9, 656, 21]]							)
       UpperCamelCase__							:				List[str]          =      model(__magic_name__							)[0]

       UpperCamelCase__							:				str          =      42384

       UpperCamelCase__							:				int          =      torch.Size((1, 5, vocab_size)							)
       self.assertEqual(output.shape,		__magic_name__							)

       UpperCamelCase__							:				str          =      torch.tensor(
           [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]]							)

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




   @slow
   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      BioGptTokenizer.from_pretrained('''microsoft/biogpt'''							)
       UpperCamelCase__							:				Tuple          =      BioGptForCausalLM.from_pretrained('''microsoft/biogpt'''							)
       model.to(__magic_name__							)

       torch.manual_seed(0							)
       UpperCamelCase__							:				Union[str, Any]          =      tokenizer('''COVID-19 is''',		return_tensors='''pt'''							).to(__magic_name__							)
       UpperCamelCase__							:				int          =      model.generate(
           **__magic_name__,		min_length=100,		max_length=1024,		num_beams=5,		early_stopping=__magic_name__,		)
       UpperCamelCase__							:				Any          =      tokenizer.decode(output_ids[0],		skip_special_tokens=__magic_name__							)

       UpperCamelCase__							:				List[str]          =      (
           'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the'
           ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and'
           ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),'
           ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and'
           ' more than 800,000 deaths.'
       )
       self.assertEqual(__magic_name__,		__magic_name__							)







"""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)

lowercase__     						=						logging.getLogger()







def      _snake_case			(				lowercase__		):
				_lowerCamelCase     :			List[Any]    =    {}
				_lowerCamelCase     :			List[Any]    =    os.path.join(lowercase__							,    'all_results.json'		)
				if os.path.exists(lowercase__		):
								with open(lowercase__							,    'r'		) as f:
												_lowerCamelCase     :			List[Any]    =    json.load(lowercase__		)
				else:
								raise ValueError(f'''can\'t find {path}'''		)
				return results


lowercase__     						=						logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)






@require_torch_tpu
class lowerCAmelCase__	(     lowercase						):






			'''simple docstring'''



			def 					A_    (  self  ):
							import xla_spawn

							_lowerCamelCase     :			List[Any]    =    self.get_auto_remove_tmp_dir()
							_lowerCamelCase     :			List[Any]    =    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(lowercase  ,      'argv'  ,      lowercase  ):
											_lowerCamelCase     :			Dict    =    time()
											xla_spawn.main()
											_lowerCamelCase     :			Any    =    time()

											_lowerCamelCase     :			Optional[int]    =    get_results(lowercase  )
											self.assertGreaterEqual(result['eval_accuracy']  ,      0.75  )

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






			def 					A_    (  self  ):
							import xla_spawn

							_lowerCamelCase     :			Tuple    =    '\n            ./tests/test_trainer_tpu.py\n            --num_cores=8\n            ./tests/test_trainer_tpu.py\n            '.split()
							with patch.object(lowercase  ,      'argv'  ,      lowercase  ):
											xla_spawn.main()