





'''simple docstring'''




import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union

import numpy as np
import pyarrow as pa

import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
    is_remote_filesystem,
    rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int


_A:					List[str]							=				datasets.utils.logging.get_logger(__name__)

if TYPE_CHECKING:
    import pyspark






@dataclass
class UpperCAmelCase							(		datasets.BuilderConfig							):
    _A :			Optional[datasets.Features]						   =       None







def _lowerCAmelCase     (      _lowerCAmelCase       ,    _lowerCAmelCase       ,    )->     List[str]:
 import pyspark

 def generate_fn():
  __UpperCAmelCase					=   df.select('*'       ,    pyspark.sql.functions.spark_partition_id().alias('part_id'    )    )
  for partition_id in partition_order:
   __UpperCAmelCase					=   df_with_partition_id.select('*'    ).where(F'part_id = {partition_id}'    ).drop('part_id'    )
   __UpperCAmelCase					=   partition_df.collect()
   __UpperCAmelCase					=   0
   for row in rows:
    yield F'{partition_id}_{row_id}', row.asDict()
    row_id += 1

 return generate_fn






class UpperCAmelCase							(		_BaseExamplesIterable							):



    def __init__(  self     ,			__A     ,			__A=None     ,			):
     __UpperCAmelCase					=   df
     __UpperCAmelCase					=   partition_order or range(self.df.rdd.getNumPartitions()					)
     __UpperCAmelCase					=   _generate_iterable_examples(self.df     ,			self.partition_order					)



    def __iter__(  self					):
     yield from self.generate_examples_fn()



    def 					__lowerCamelCase						(  self     ,			__A					):
     __UpperCAmelCase					=   list(range(self.df.rdd.getNumPartitions()					)					)
     generator.shuffle(__A					)
     return SparkExamplesIterable(self.df     ,			partition_order=__A					)



    def 					__lowerCamelCase						(  self     ,			__A     ,			__A					):
     __UpperCAmelCase					=   self.split_shard_indices_by_worker(__A     ,			__A					)
     return SparkExamplesIterable(self.df     ,			partition_order=__A					)




    @property
    def 					__lowerCamelCase						(  self					):
     return len(self.partition_order					)






class UpperCAmelCase							(		datasets.DatasetBuilder							):
    _A :			Union[str, Any]						   =       SparkConfig



    def __init__(  self     ,			__A     ,			__A = None     ,			__A = None     ,			**__A     ,			):
     import pyspark

     __UpperCAmelCase					=   pyspark.sql.SparkSession.builder.getOrCreate()
     __UpperCAmelCase					=   df
     __UpperCAmelCase					=   working_dir

     super().__init__(
         cache_dir=__A     ,			config_name=str(self.df.semanticHash()					)     ,			**__A     ,			)



    def 					__lowerCamelCase						(  self					):
     # Returns the path of the created file.
     def create_cache_and_write_probe(__A					):
      # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
      # already exist.
      os.makedirs(self._cache_dir     ,			exist_ok=__A					)
      __UpperCAmelCase					=   os.path.join(self._cache_dir     ,			'fs_test' + uuid.uuida().hex					)
      # Opening the file in append mode will create a new file unless it already exists, in which case it will not
      # change the file contents.
      open(__A     ,			'a'					)
      return [probe_file]

     if self._spark.conf.get('spark.master'     ,			''					).startswith('local'					):
      return

     # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
     # accessible to the driver.
     # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
     if self._cache_dir:
      __UpperCAmelCase					=   (
          self._spark.sparkContext.parallelize(range(1					)     ,			1					).mapPartitions(__A					).collect()
      )
      if os.path.isfile(probe[0]					):
       return

     raise ValueError(
         'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir'					)



    def 					__lowerCamelCase						(  self					):
     return datasets.DatasetInfo(features=self.config.features					)



    def 					__lowerCamelCase						(  self     ,			__A					):
     return [datasets.SplitGenerator(name=datasets.Split.TRAIN					)]



    def 					__lowerCamelCase						(  self     ,			__A					):
     import pyspark

     def get_arrow_batch_size(__A					):
      for batch in it:
       yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]}					)

     __UpperCAmelCase					=   self.df.count()
     __UpperCAmelCase					=   df_num_rows if df_num_rows <= 100 else 100
     # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
     __UpperCAmelCase					=   (
         self.df.limit(__A					)
         .repartition(1					)
         .mapInArrow(__A     ,			'batch_bytes: long'					)
         .agg(pyspark.sql.functions.sum('batch_bytes'					).alias('sample_bytes'					)					)
         .collect()[0]
         .sample_bytes
         / sample_num_rows
     )
     __UpperCAmelCase					=   approx_bytes_per_row * df_num_rows
     if approx_total_size > max_shard_size:
      # Make sure there is at least one row per partition.
      __UpperCAmelCase					=   min(__A     ,			int(approx_total_size / max_shard_size					)					)
      __UpperCAmelCase					=   self.df.repartition(__A					)



    def 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			):
     import pyspark

     __UpperCAmelCase					=   ParquetWriter if file_format == 'parquet' else ArrowWriter
     __UpperCAmelCase					=   os.path.join(self._working_dir     ,			os.path.basename(__A					)					) if self._working_dir else fpath
     __UpperCAmelCase					=   file_format == 'parquet'

     # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
     # pickling the SparkContext.
     __UpperCAmelCase					=   self.config.features
     __UpperCAmelCase					=   self._writer_batch_size
     __UpperCAmelCase					=   self._fs.storage_options

     def write_arrow(__A					):
      # Within the same SparkContext, no two task attempts will share the same attempt ID.
      __UpperCAmelCase					=   pyspark.TaskContext().taskAttemptId()
      __UpperCAmelCase					=   next(__A     ,			__A					)
      if first_batch is None:
       # Some partitions might not receive any data.
       return pa.RecordBatch.from_arrays(
           [[task_id], [0], [0]]     ,			names=['task_id', 'num_examples', 'num_bytes']     ,			)
      __UpperCAmelCase					=   0
      __UpperCAmelCase					=   writer_class(
          features=__A     ,			path=working_fpath.replace('SSSSS'     ,			f'{shard_id:05d}'					).replace('TTTTT'     ,			f'{task_id:05d}'					)     ,			writer_batch_size=__A     ,			storage_options=__A     ,			embed_local_files=__A     ,			)
      __UpperCAmelCase					=   pa.Table.from_batches([first_batch]					)
      writer.write_table(__A					)
      for batch in it:
       if max_shard_size is not None and writer._num_bytes >= max_shard_size:
        __UpperCAmelCase					,    __UpperCAmelCase					=   writer.finalize()
        writer.close()
        yield pa.RecordBatch.from_arrays(
            [[task_id], [num_examples], [num_bytes]]     ,			names=['task_id', 'num_examples', 'num_bytes']     ,			)
        shard_id += 1
        __UpperCAmelCase					=   writer_class(
            features=writer._features     ,			path=working_fpath.replace('SSSSS'     ,			f'{shard_id:05d}'					).replace('TTTTT'     ,			f'{task_id:05d}'					)     ,			writer_batch_size=__A     ,			storage_options=__A     ,			embed_local_files=__A     ,			)
       __UpperCAmelCase					=   pa.Table.from_batches([batch]					)
       writer.write_table(__A					)

      if writer._num_bytes > 0:
       __UpperCAmelCase					,    __UpperCAmelCase					=   writer.finalize()
       writer.close()
       yield pa.RecordBatch.from_arrays(
           [[task_id], [num_examples], [num_bytes]]     ,			names=['task_id', 'num_examples', 'num_bytes']     ,			)

      if working_fpath != fpath:
       for file in os.listdir(os.path.dirname(__A					)					):
        __UpperCAmelCase					=   os.path.join(os.path.dirname(__A					)     ,			os.path.basename(__A					)					)
        shutil.move(__A     ,			__A					)

     __UpperCAmelCase					=   (
         self.df.mapInArrow(__A     ,			'task_id: long, num_examples: long, num_bytes: long'					)
         .groupBy('task_id'					)
         .agg(
             pyspark.sql.functions.sum('num_examples'					).alias('total_num_examples'					)     ,			pyspark.sql.functions.sum('num_bytes'					).alias('total_num_bytes'					)     ,			pyspark.sql.functions.count('num_bytes'					).alias('num_shards'					)     ,			pyspark.sql.functions.collect_list('num_examples'					).alias('shard_lengths'					)     ,			)
         .collect()
     )
     for row in stats:
      yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)



    def 					__lowerCamelCase						(  self     ,			__A     ,			__A = "arrow"     ,			__A = None     ,			__A = None     ,			**__A     ,			):
     self._validate_cache_dir()

     __UpperCAmelCase					=   convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE					)
     self._repartition_df_if_needed(__A					)
     __UpperCAmelCase					=   not is_remote_filesystem(self._fs					)
     __UpperCAmelCase					=   os.path.join if is_local else posixpath.join

     __UpperCAmelCase					=   '-TTTTT-SSSSS-of-NNNNN'
     __UpperCAmelCase					=   f'{self.name}-{split_generator.name}{SUFFIX}.{file_format}'
     __UpperCAmelCase					=   path_join(self._output_dir     ,			__A					)

     __UpperCAmelCase					=   0
     __UpperCAmelCase					=   0
     __UpperCAmelCase					=   0
     __UpperCAmelCase					=   []
     __UpperCAmelCase					=   []

     for task_id, content in self._prepare_split_single(__A     ,			__A     ,			__A					):
      (
          (
          __UpperCAmelCase
      )					,    (
          __UpperCAmelCase
      )					,    (
          __UpperCAmelCase
      )					,    (
          __UpperCAmelCase
      )					,    
      )					=   content
      if num_bytes > 0:
       total_num_examples += num_examples
       total_num_bytes += num_bytes
       total_shards += num_shards
       task_id_and_num_shards.append((task_id, num_shards)					)
       all_shard_lengths.extend(__A					)

     __UpperCAmelCase					=   total_num_examples
     __UpperCAmelCase					=   total_num_bytes

     # should rename everything at the end
     logger.debug(f'Renaming {total_shards} shards.'					)
     if total_shards > 1:
      __UpperCAmelCase					=   all_shard_lengths

      # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
      # pickling error due to pickling the SparkContext.
      __UpperCAmelCase					=   self._fs

      # use the -SSSSS-of-NNNNN pattern
      def _rename_shard(
          __A     ,			__A     ,			__A     ,			):
       rename(
           __A     ,			fpath.replace('SSSSS'     ,			f'{shard_id:05d}'					).replace('TTTTT'     ,			f'{task_id:05d}'					)     ,			fpath.replace('TTTTT-SSSSS'     ,			f'{global_shard_id:05d}'					).replace('NNNNN'     ,			f'{total_shards:05d}'					)     ,			)

      __UpperCAmelCase					=   []
      __UpperCAmelCase					=   0
      for i in range(len(__A					)					):
       __UpperCAmelCase					,    __UpperCAmelCase					=   task_id_and_num_shards[i]
       for shard_id in range(__A					):
        args.append([task_id, shard_id, global_shard_id]					)
        global_shard_id += 1
      self._spark.sparkContext.parallelize(__A     ,			len(__A					)					).map(lambda __A					: _rename_shard(*__A					)					).collect()
     else:
      # don't use any pattern
      __UpperCAmelCase					=   0
      __UpperCAmelCase					=   task_id_and_num_shards[0][0]
      self._rename(
          fpath.replace('SSSSS'     ,			f'{shard_id:05d}'					).replace('TTTTT'     ,			f'{task_id:05d}'					)     ,			fpath.replace(__A     ,			''					)     ,			)




    def 					__lowerCamelCase						(  self     ,			__A     ,			):
     return SparkExamplesIterable(self.df					)












'''simple docstring'''




import math
import os
import unittest

from transformers import MegatronBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

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 (
        MODEL_FOR_PRETRAINING_MAPPING,
        MegatronBertForCausalLM,
        MegatronBertForMaskedLM,
        MegatronBertForMultipleChoice,
        MegatronBertForNextSentencePrediction,
        MegatronBertForPreTraining,
        MegatronBertForQuestionAnswering,
        MegatronBertForSequenceClassification,
        MegatronBertForTokenClassification,
        MegatronBertModel,
    )






class UpperCAmelCase							:



    def __init__(  self     ,			__A     ,			__A=13     ,			__A=7     ,			__A=True     ,			__A=True     ,			__A=True     ,			__A=True     ,			__A=99     ,			__A=64     ,			__A=32     ,			__A=5     ,			__A=4     ,			__A=37     ,			__A="gelu"     ,			__A=0.1     ,			__A=0.1     ,			__A=512     ,			__A=16     ,			__A=2     ,			__A=0.0_2     ,			__A=3     ,			__A=4     ,			__A=None     ,			):
     __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					=   embedding_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 					__lowerCamelCase						(  self					):
     __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 					__lowerCamelCase						(  self					):
     return MegatronBertConfig(
         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     ,			embedding_size=self.embedding_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 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A					):
     __UpperCAmelCase					=   MegatronBertModel(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)					)
     self.parent.assertEqual(result.pooler_output.shape     ,			(self.batch_size, self.hidden_size)					)



    def 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A					):
     __UpperCAmelCase					=   MegatronBertForMaskedLM(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 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A					):
     __UpperCAmelCase					=   MegatronBertForCausalLM(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 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A					):
     __UpperCAmelCase					=   MegatronBertForNextSentencePrediction(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, 2)					)



    def 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A					):
     __UpperCAmelCase					=   MegatronBertForPreTraining(config=__A					)
     model.to(__A					)
     model.eval()
     __UpperCAmelCase					=   model(
         __A     ,			attention_mask=__A     ,			token_type_ids=__A     ,			labels=__A     ,			next_sentence_label=__A     ,			)
     self.parent.assertEqual(result.prediction_logits.shape     ,			(self.batch_size, self.seq_length, self.vocab_size)					)
     self.parent.assertEqual(result.seq_relationship_logits.shape     ,			(self.batch_size, 2)					)



    def 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A					):
     __UpperCAmelCase					=   MegatronBertForQuestionAnswering(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 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A					):
     __UpperCAmelCase					=   self.num_labels
     __UpperCAmelCase					=   MegatronBertForSequenceClassification(__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 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A					):
     __UpperCAmelCase					=   self.num_labels
     __UpperCAmelCase					=   MegatronBertForTokenClassification(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 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A     ,			__A					):
     __UpperCAmelCase					=   self.num_choices
     __UpperCAmelCase					=   MegatronBertForMultipleChoice(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 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.prepare_config_and_inputs()
     (
         (
         __UpperCAmelCase
     )					,    (
         __UpperCAmelCase
     )					,    (
         __UpperCAmelCase
     )					,    (
         __UpperCAmelCase
     )					,    (
         __UpperCAmelCase
     )					,    (
         __UpperCAmelCase
     )					,    (
         __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 UpperCAmelCase							(		UpperCAmelCase_					,			UpperCAmelCase_					,			unittest.TestCase							):
    _A :			str						   =       (
        (
            MegatronBertModel,
            MegatronBertForMaskedLM,
            MegatronBertForCausalLM,
            MegatronBertForMultipleChoice,
            MegatronBertForNextSentencePrediction,
            MegatronBertForPreTraining,
            MegatronBertForQuestionAnswering,
            MegatronBertForSequenceClassification,
            MegatronBertForTokenClassification,
        )
        if is_torch_available()
        else ()
    )
    _A :			Dict						   =       (
        {
            """feature-extraction""": MegatronBertModel,
            """fill-mask""": MegatronBertForMaskedLM,
            """question-answering""": MegatronBertForQuestionAnswering,
            """text-classification""": MegatronBertForSequenceClassification,
            """text-generation""": MegatronBertForCausalLM,
            """token-classification""": MegatronBertForTokenClassification,
            """zero-shot""": MegatronBertForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    _A :			List[str]						   =       True
    # test_resize_embeddings = False
    _A :			Tuple						   =       False



    def 					__lowerCamelCase						(  self     ,			__A     ,			__A     ,			__A=False					):
     __UpperCAmelCase					=   super()._prepare_for_class(__A     ,			__A     ,			return_labels=__A					)

     if return_labels:
      if model_class in get_values(__A					):
       __UpperCAmelCase					=   torch.zeros(
           (self.model_tester.batch_size, self.model_tester.seq_length)     ,			dtype=torch.long     ,			device=__A					)
       __UpperCAmelCase					=   torch.zeros(
           self.model_tester.batch_size     ,			dtype=torch.long     ,			device=__A					)
     return inputs_dict



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   MegatronBertModelTester(self					)
     __UpperCAmelCase					=   ConfigTester(self     ,			config_class=__A     ,			hidden_size=37					)



    def 					__lowerCamelCase						(  self					):
     self.config_tester.run_common_tests()



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_megatron_bert_model(*__A					)



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__A					)



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__A					)



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__A					)



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_megatron_bert_for_pretraining(*__A					)



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_megatron_bert_for_question_answering(*__A					)



    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__A					)




    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_megatron_bert_for_token_classification(*__A					)







def _lowerCAmelCase     (      _lowerCAmelCase    )->     Dict:
 return torch.tensor(
     _lowerCAmelCase       ,    dtype=torch.long       ,    device=_lowerCAmelCase       ,    )


_A:					Any							=				1E-4






@require_torch
@require_sentencepiece
@require_tokenizers
class UpperCAmelCase							(		unittest.TestCase							):



    @slow
    @unittest.skip('Model is not available.'					)
    def 					__lowerCamelCase						(  self					):
     __UpperCAmelCase					=   'nvidia/megatron-bert-uncased-345m'
     if "MYDIR" in os.environ:
      __UpperCAmelCase					=   os.path.join(os.environ['MYDIR']     ,			__A					)
     __UpperCAmelCase					=   MegatronBertModel.from_pretrained(__A					)
     model.to(__A					)
     model.half()
     __UpperCAmelCase					=   _long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]]					)
     with torch.no_grad():
      __UpperCAmelCase					=   model(__A					)[0]
     __UpperCAmelCase					=   torch.Size((1, 9, 1_024)					)
     self.assertEqual(output.shape     ,			__A					)

     __UpperCAmelCase					=   [-0.6_0_4_0, -0.2_5_1_7, -0.1_0_2_5, 0.3_4_2_0, -0.6_7_5_8, -0.0_0_1_7, -0.1_0_8_9, -0.1_9_9_0, 0.5_7_2_8]
     for ii in range(3					):
      for jj in range(3					):
       __UpperCAmelCase					=   output[0, ii, jj]
       __UpperCAmelCase					=   expected[3 * ii + jj]
       __UpperCAmelCase					=   'ii={} jj={} a={} b={}'.format(__A     ,			__A     ,			__A     ,			__A					)
       self.assertTrue(math.isclose(__A     ,			__A     ,			rel_tol=__A     ,			abs_tol=__A					)     ,			msg=__A					)





