




'''simple docstring'''



import argparse
import logging
import os
import sys
import time

import tensorflow as tf
from datasets import load_dataset
from tqdm import tqdm

from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
from transformers.utils import is_sagemaker_dp_enabled


if os.environ.get('SDP_ENABLED') or is_sagemaker_dp_enabled():
 lowerCamelCase_		       =						True
 lowerCamelCase_		       =						'''p3dn.24xlarge'''
 import smdistributed.dataparallel.tensorflow as sdp
else:
 lowerCamelCase_		       =						False
def  SCREAMING_SNAKE_CASE_ (							__A				: Any       ,     __A				: Optional[Any]       ,     __A				: int       ,     __A				: Union[str, Any]       ,     __A				: Optional[int]       ,     __A				: Dict       ,     __A				: Optional[int]=None  ) -> str:
   _SCREAMING_SNAKE_CASE       =      tqdm(_UpperCAmelCase  )
   for i, batch in enumerate(_UpperCAmelCase  ):
      with tf.GradientTape() as tape:
         _SCREAMING_SNAKE_CASE,       _SCREAMING_SNAKE_CASE       =      batch
         _SCREAMING_SNAKE_CASE       =      model(_UpperCAmelCase  )
         _SCREAMING_SNAKE_CASE       =      loss(_UpperCAmelCase       ,     outputs.logits  )

      if SDP_ENABLED:
         _SCREAMING_SNAKE_CASE       =      sdp.DistributedGradientTape(_UpperCAmelCase       ,     sparse_as_dense=_UpperCAmelCase  )

      _SCREAMING_SNAKE_CASE       =      tape.gradient(_UpperCAmelCase       ,     model.trainable_variables  )
      opt.apply_gradients(zip(_UpperCAmelCase       ,     model.trainable_variables  )  )

      pbar.set_description(f"""Loss: {loss_value:.4f}"""  )

      if SDP_ENABLED and i == 0:
         sdp.broadcast_variables(model.variables       ,     root_rank=0  )
         sdp.broadcast_variables(opt.variables()       ,     root_rank=0  )

      if max_steps and i >= max_steps:
         break

   _SCREAMING_SNAKE_CASE       =      {"loss": loss_value.numpy()}
   return train_results
def  SCREAMING_SNAKE_CASE_ (							__A				: List[Any]       ,     __A				: Union[str, Any]       ,     __A				: List[str]  ) -> Tuple:
   # Load dataset
   _SCREAMING_SNAKE_CASE,       _SCREAMING_SNAKE_CASE       =      load_dataset("imdb"       ,     split=["train", "test"]  )

   # Preprocess train dataset
   _SCREAMING_SNAKE_CASE       =      train_dataset.map(
       lambda __A  : tokenizer(e["text"]       ,     truncation=_UpperCAmelCase       ,     padding="max_length"  )       ,     batched=_UpperCAmelCase  )
   train_dataset.set_format(type="tensorflow"       ,     columns=["input_ids", "attention_mask", "label"]  )

   _SCREAMING_SNAKE_CASE       =      {
       x: train_dataset[x].to_tensor(default_value=0       ,     shape=[None, tokenizer.model_max_length]  )
       for x in ["input_ids", "attention_mask"]
   }
   _SCREAMING_SNAKE_CASE       =      tf.data.Dataset.from_tensor_slices((train_features, train_dataset["label"])  )

   # Preprocess test dataset
   _SCREAMING_SNAKE_CASE       =      test_dataset.map(
       lambda __A  : tokenizer(e["text"]       ,     truncation=_UpperCAmelCase       ,     padding="max_length"  )       ,     batched=_UpperCAmelCase  )
   test_dataset.set_format(type="tensorflow"       ,     columns=["input_ids", "attention_mask", "label"]  )

   _SCREAMING_SNAKE_CASE       =      {
       x: test_dataset[x].to_tensor(default_value=0       ,     shape=[None, tokenizer.model_max_length]  )
       for x in ["input_ids", "attention_mask"]
   }
   _SCREAMING_SNAKE_CASE       =      tf.data.Dataset.from_tensor_slices((test_features, test_dataset["label"])  )

   if SDP_ENABLED:
      _SCREAMING_SNAKE_CASE       =      tf_train_dataset.shard(sdp.size()       ,     sdp.rank()  )
      _SCREAMING_SNAKE_CASE       =      tf_test_dataset.shard(sdp.size()       ,     sdp.rank()  )
   _SCREAMING_SNAKE_CASE       =      tf_train_dataset.batch(_UpperCAmelCase       ,     drop_remainder=_UpperCAmelCase  )
   _SCREAMING_SNAKE_CASE       =      tf_test_dataset.batch(_UpperCAmelCase       ,     drop_remainder=_UpperCAmelCase  )

   return tf_train_dataset, tf_test_dataset


if __name__ == "__main__":
 lowerCamelCase_		       =						argparse.ArgumentParser()

 # Hyperparameters sent by the client are passed as command-line arguments to the script.
 parser.add_argument('--epochs', type=int, default=3)
 parser.add_argument('--per_device_train_batch_size', type=int, default=16)
 parser.add_argument('--per_device_eval_batch_size', type=int, default=8)
 parser.add_argument('--model_name_or_path', type=str)
 parser.add_argument('--learning_rate', type=str, default=5e-5)
 parser.add_argument('--do_train', type=bool, default=True)
 parser.add_argument('--do_eval', type=bool, default=True)
 parser.add_argument('--output_dir', type=str)
 parser.add_argument('--max_steps', type=int, default=None)

 # Data, model, and output directories
 parser.add_argument('--output_data_dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR'])
 parser.add_argument('--model_dir', type=str, default=os.environ['SM_MODEL_DIR'])
 parser.add_argument('--n_gpus', type=str, default=os.environ['SM_NUM_GPUS'])

 lowerCamelCase_		       =						parser.parse_known_args()

 # Set up logging
 lowerCamelCase_		       =						logging.getLogger(__name__)

 logging.basicConfig(
     level=logging.getLevelName('INFO'),
     handlers=[logging.StreamHandler(sys.stdout)],
     format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
 )

 if SDP_ENABLED:
  sdp.init()

  lowerCamelCase_		       =						tf.config.experimental.list_physical_devices('GPU')
  for gpu in gpus:
   tf.config.experimental.set_memory_growth(gpu, True)
  if gpus:
   tf.config.experimental.set_visible_devices(gpus[sdp.local_rank()], 'GPU')

    # Load model and tokenizer
 lowerCamelCase_		       =						TFAutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
 lowerCamelCase_		       =						AutoTokenizer.from_pretrained(args.model_name_or_path)

 # get datasets
 lowerCamelCase_		       =						get_datasets(
     tokenizer=tokenizer,
     train_batch_size=args.per_device_train_batch_size,
     eval_batch_size=args.per_device_eval_batch_size,
 )

 # fine optimizer and loss
 lowerCamelCase_		       =						tf.keras.optimizers.Adam(learning_rate=args.learning_rate)
 lowerCamelCase_		       =						tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
 lowerCamelCase_		       =						[tf.keras.metrics.SparseCategoricalAccuracy()]
 model.compile(optimizer=optimizer, loss=loss, metrics=metrics)

 # Training
 if args.do_train:
  # train_results = model.fit(tf_train_dataset, epochs=args.epochs, batch_size=args.train_batch_size)
  lowerCamelCase_		       =						time.time()
  lowerCamelCase_		       =						fit(
      model,
      loss,
      optimizer,
      tf_train_dataset,
      args.epochs,
      args.per_device_train_batch_size,
      max_steps=args.max_steps,
  )
  lowerCamelCase_		       =						time.time() - start_train_time
  logger.info('*** Train ***')
  logger.info(f'''train_runtime = {end_train_time}''')

  lowerCamelCase_		       =						os.path.join(args.output_dir, 'train_results.txt')

  if not SDP_ENABLED or sdp.rank() == 0:
   with open(output_eval_file, 'w') as writer:
    logger.info('***** Train results *****')
    logger.info(train_results)
    for key, value in train_results.items():
     logger.info(f'''  {key} = {value}''')
     writer.write(f'''{key} = {value}\n''')

    # Evaluation
 if args.do_eval and (not SDP_ENABLED or sdp.rank() == 0):
  lowerCamelCase_		       =						model.evaluate(tf_test_dataset, batch_size=args.per_device_eval_batch_size, return_dict=True)
  logger.info('*** Evaluate ***')

  lowerCamelCase_		       =						os.path.join(args.output_dir, 'eval_results.txt')

  with open(output_eval_file, 'w') as writer:
   logger.info('***** Eval results *****')
   logger.info(result)
   for key, value in result.items():
    logger.info(f'''  {key} = {value}''')
    writer.write(f'''{key} = {value}\n''')

    # Save result
 if SDP_ENABLED:
  if sdp.rank() == 0:
   model.save_pretrained(args.output_dir)
   tokenizer.save_pretrained(args.output_dir)
 else:
  model.save_pretrained(args.output_dir)
  tokenizer.save_pretrained(args.output_dir)








"""simple docstring"""
from __future__ import annotations

import unittest

from transformers import MPNetConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers.models.mpnet.modeling_tf_mpnet import (
           TFMPNetForMaskedLM,
           TFMPNetForMultipleChoice,
           TFMPNetForQuestionAnswering,
           TFMPNetForSequenceClassification,
           TFMPNetForTokenClassification,
           TFMPNetModel,
       )







class 	a				:



 def __init__(			self							,    _snake_case							,    _snake_case=13							,    _snake_case=7							,    _snake_case=True							,    _snake_case=True							,    _snake_case=False							,    _snake_case=True							,    _snake_case=99							,    _snake_case=64							,    _snake_case=2							,    _snake_case=4							,    _snake_case=64							,    _snake_case="gelu"							,    _snake_case=0.1							,    _snake_case=0.1							,    _snake_case=5_12							,    _snake_case=16							,    _snake_case=2							,    _snake_case=0.02							,    _snake_case=3							,    _snake_case=4							,    _snake_case=None							,    ):







  """simple docstring"""






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



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






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

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

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

  lowerCAmelCase  							=      MPNetConfig(
      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							,    initializer_range=self.initializer_range							,    )
  return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetModel(config=_snake_case			)
  lowerCAmelCase  							=      {'input_ids': input_ids, 'attention_mask': input_mask}
  lowerCAmelCase  							=      model(_snake_case			)
  lowerCAmelCase  							=      [input_ids, input_mask]
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.last_hidden_state.shape							,    (self.batch_size, self.seq_length, self.hidden_size)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetForMaskedLM(config=_snake_case			)
  lowerCAmelCase  							=      {'input_ids': input_ids, 'attention_mask': input_mask}
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.seq_length, self.vocab_size)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetForQuestionAnswering(config=_snake_case			)
  lowerCAmelCase  							=      {
      'input_ids': input_ids,
      'attention_mask': input_mask,
  }
  lowerCAmelCase  							=      model(_snake_case			)
  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 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      self.num_labels
  lowerCAmelCase  							=      TFMPNetForSequenceClassification(_snake_case			)
  lowerCAmelCase  							=      {'input_ids': input_ids, 'attention_mask': input_mask}
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_labels)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      self.num_choices
  lowerCAmelCase  							=      TFMPNetForMultipleChoice(_snake_case			)
  lowerCAmelCase  							=      tf.tile(tf.expand_dims(_snake_case							,    1			)							,    (1, self.num_choices, 1)			)
  lowerCAmelCase  							=      tf.tile(tf.expand_dims(_snake_case							,    1			)							,    (1, self.num_choices, 1)			)
  lowerCAmelCase  							=      {
      'input_ids': multiple_choice_inputs_ids,
      'attention_mask': multiple_choice_input_mask,
  }
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_choices)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      self.num_labels
  lowerCAmelCase  							=      TFMPNetForTokenClassification(_snake_case			)
  lowerCAmelCase  							=      {'input_ids': input_ids, 'attention_mask': input_mask}
  lowerCAmelCase  							=      model(_snake_case			)
  self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.seq_length, self.num_labels)			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






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







@require_tf
class 	a				(					a__					,      a__					,      unittest.TestCase   ):
 snake_case__    	=    (
     (
         TFMPNetForMaskedLM,
         TFMPNetForMultipleChoice,
         TFMPNetForQuestionAnswering,
         TFMPNetForSequenceClassification,
         TFMPNetForTokenClassification,
         TFMPNetModel,
     )
     if is_tf_available()
     else ()
 )
 snake_case__    	=    (
     {
         '''feature-extraction''': TFMPNetModel,
         '''fill-mask''': TFMPNetForMaskedLM,
         '''question-answering''': TFMPNetForQuestionAnswering,
         '''text-classification''': TFMPNetForSequenceClassification,
         '''token-classification''': TFMPNetForTokenClassification,
         '''zero-shot''': TFMPNetForSequenceClassification,
     }
     if is_tf_available()
     else {}
 )
 snake_case__    	=    False
 snake_case__    	=    False



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetModelTester(self			)
  lowerCAmelCase  							=      ConfigTester(self							,    config_class=_snake_case							,    hidden_size=37			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  self.config_tester.run_common_tests()



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_model(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_masked_lm(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_question_answering(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_sequence_classification(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_multiple_choice(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_mpnet_for_token_classification(*_snake_case			)



 @slow
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  for model_name in ["microsoft/mpnet-base"]:
   lowerCAmelCase  							=      TFMPNetModel.from_pretrained(_snake_case			)
   self.assertIsNotNone(_snake_case			)







@require_tf
class 	a				(					unittest.TestCase   ):



 @slow
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMPNetModel.from_pretrained('microsoft/mpnet-base'			)
  lowerCAmelCase  							=      tf.constant([[0, 1, 2, 3, 4, 5]]			)
  lowerCAmelCase  							=      model(_snake_case			)[0]

  lowerCAmelCase  							=      [1, 6, 7_68]
  self.assertEqual(output.shape							,    _snake_case			)

  lowerCAmelCase  							=      tf.constant(
      [
          [
              [-0.1_067_172, 0.08_216_473, 0.0_024_543],
              [-0.03_465_879, 0.8_354_118, -0.03_252_288],
              [-0.06_569_476, -0.12_424_111, -0.0_494_436],
          ]
      ]			)
  tf.debugging.assert_near(output[:, :3, :3]							,    _snake_case							,    atol=1E-4			)





