



from __future__ import annotations

import unittest

import numpy as np

from transformers import OPTConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, slow

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


if is_tf_available():
      import tensorflow as tf

      from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Union[str, Any]		,	__lowerCamelCase   :     int		,	__lowerCamelCase   :     Union[str, Any]=None		,	__lowerCamelCase   :     Optional[Any]=None     ):



 """simple docstring"""





 if attention_mask is None:
  __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	tf.cast(tf.math.not_equal(__lowerCamelCase		,	config.pad_token_id     )		,	tf.inta     )
 return {"input_ids": input_ids, "attention_mask": attention_mask}

@require_tf
class       _SCREAMING_SNAKE_CASE	:
     lowerCAmelCase					=			OPTConfig
     lowerCAmelCase					=			{}
     lowerCAmelCase					=			"""gelu"""





     def __init__(       self :							Dict     ,  UpperCamelCase :							str     ,  UpperCamelCase :							Union[str, Any]=1_3     ,  UpperCamelCase :							Dict=7     ,  UpperCamelCase :							List[Any]=True     ,  UpperCamelCase :							Optional[Any]=False     ,  UpperCamelCase :							int=9_9     ,  UpperCamelCase :							Union[str, Any]=1_6     ,  UpperCamelCase :							List[str]=2     ,  UpperCamelCase :							Optional[int]=4     ,  UpperCamelCase :							Dict=4     ,  UpperCamelCase :							List[str]="gelu"     ,  UpperCamelCase :							Dict=0.1     ,  UpperCamelCase :							Union[str, Any]=0.1     ,  UpperCamelCase :							int=2_0     ,  UpperCamelCase :							List[Any]=2     ,  UpperCamelCase :							Union[str, Any]=1     ,  UpperCamelCase :							Dict=0     ,  UpperCamelCase :							Any=1_6     ,  UpperCamelCase :							int=1_6     ,  )->str:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	parent
      __SCREAMING_SNAKE_CASE       :    str       =	batch_size
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	seq_length
      __SCREAMING_SNAKE_CASE       :    List[str]       =	is_training
      __SCREAMING_SNAKE_CASE       :    Any       =	use_labels
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	vocab_size
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	hidden_size
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	num_hidden_layers
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	num_attention_heads
      __SCREAMING_SNAKE_CASE       :    List[str]       =	intermediate_size
      __SCREAMING_SNAKE_CASE       :    Any       =	hidden_act
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	hidden_dropout_prob
      __SCREAMING_SNAKE_CASE       :    Tuple       =	attention_probs_dropout_prob
      __SCREAMING_SNAKE_CASE       :    str       =	max_position_embeddings
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	eos_token_id
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	pad_token_id
      __SCREAMING_SNAKE_CASE       :    Any       =	bos_token_id
      __SCREAMING_SNAKE_CASE       :    str       =	embed_dim
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	word_embed_proj_dim
      __SCREAMING_SNAKE_CASE       :    Tuple       =	False





     def 	__snake_case    (       self :							Optional[int]				)->str:
      __SCREAMING_SNAKE_CASE       :    str       =	ids_tensor([self.batch_size, self.seq_length - 1]     ,  self.vocab_size				)
      __SCREAMING_SNAKE_CASE       :    str       =	tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size				)     ,  1				)
      __SCREAMING_SNAKE_CASE       :    List[str]       =	tf.concat([input_ids, eos_tensor]     ,  axis=1				)

      __SCREAMING_SNAKE_CASE       :    List[Any]       =	self.config_cls(
          vocab_size=self.vocab_size     ,  hidden_size=self.hidden_size     ,  num_hidden_layers=self.num_hidden_layers     ,  num_attention_heads=self.num_attention_heads     ,  ffn_dim=self.intermediate_size     ,  dropout=self.hidden_dropout_prob     ,  attention_dropout=self.attention_probs_dropout_prob     ,  max_position_embeddings=self.max_position_embeddings     ,  eos_token_id=self.eos_token_id     ,  bos_token_id=self.bos_token_id     ,  pad_token_id=self.pad_token_id     ,  embed_dim=self.embed_dim     ,  word_embed_proj_dim=self.word_embed_proj_dim     ,  is_encoder_decoder=UpperCamelCase     ,  **self.config_updates     ,  )
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	prepare_opt_inputs_dict(UpperCamelCase     ,  UpperCamelCase				)
      return config, inputs_dict






     def 	__snake_case    (       self :							Union[str, Any]     ,  UpperCamelCase :							str     ,  UpperCamelCase :							Any				)->List[str]:
      __SCREAMING_SNAKE_CASE       :    Tuple       =	TFOPTModel(config=UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Dict       =	inputs_dict["input_ids"]

      __SCREAMING_SNAKE_CASE       :    List[str]       =	input_ids[:1, :]
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	inputs_dict["attention_mask"][:1, :]
      __SCREAMING_SNAKE_CASE       :    Tuple       =	1

      # first forward pass
      __SCREAMING_SNAKE_CASE       :    Tuple       =	model(UpperCamelCase     ,  attention_mask=UpperCamelCase     ,  use_cache=UpperCamelCase				)

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Any       =	outputs.to_tuple()

      # create hypothetical next token and extent to next_input_ids
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	ids_tensor((self.batch_size, 3)     ,  config.vocab_size				)
      __SCREAMING_SNAKE_CASE       :    Tuple       =	tf.cast(ids_tensor((self.batch_size, 3)     ,  2				)     ,  tf.inta				)

      # append to next input_ids and
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	tf.concat([input_ids, next_tokens]     ,  axis=-1				)
      __SCREAMING_SNAKE_CASE       :    List[str]       =	tf.concat([attention_mask, next_attn_mask]     ,  axis=-1				)

      __SCREAMING_SNAKE_CASE       :    Dict       =	model(UpperCamelCase     ,  attention_mask=UpperCamelCase				)[0]
      __SCREAMING_SNAKE_CASE       :    str       =	model(UpperCamelCase     ,  attention_mask=UpperCamelCase     ,  past_key_values=UpperCamelCase				)[0]

      self.parent.assertEqual(next_tokens.shape[1]     ,  output_from_past.shape[1]				)

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

      # test that outputs are equal for slice
      tf.debugging.assert_near(UpperCamelCase     ,  UpperCamelCase     ,  rtol=1E-3				)






@require_tf
class       _SCREAMING_SNAKE_CASE	(UpperCamelCase			,    UpperCamelCase			,    unittest.TestCase ):
     lowerCAmelCase					=			(TFOPTModel, TFOPTForCausalLM) if is_tf_available() else ()
     lowerCAmelCase					=			(TFOPTForCausalLM,) if is_tf_available() else ()
     lowerCAmelCase					=			(
         {"""feature-extraction""": TFOPTModel, """text-generation""": TFOPTForCausalLM} if is_tf_available() else {}
     )
     lowerCAmelCase					=			False
     lowerCAmelCase					=			False
     lowerCAmelCase					=			False
     lowerCAmelCase					=			10





     def 	__snake_case    (       self :							Optional[Any]				)->int:
      __SCREAMING_SNAKE_CASE       :    str       =	TFOPTModelTester(self				)
      __SCREAMING_SNAKE_CASE       :    Any       =	ConfigTester(self     ,  config_class=UpperCamelCase				)





     def 	__snake_case    (       self :							Dict				)->Union[str, Any]:
      self.config_tester.run_common_tests()





     def 	__snake_case    (       self :							int				)->str:
      __SCREAMING_SNAKE_CASE       :    Tuple       =	self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase				)






     def 	__snake_case    (       self :							Any				)->int:
      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.model_tester.prepare_config_and_inputs_for_common()

      def _get_word_embedding_weight(UpperCamelCase :							List[str]     ,  UpperCamelCase :							List[Any]				):
       if hasattr(UpperCamelCase     ,  "weight"				):
        return embedding_layer.weight
       else:
        # Here we build the word embeddings weights if not exists.
        # And then we retry to get the attribute once built.
        model.build()
        if hasattr(UpperCamelCase     ,  "weight"				):
         return embedding_layer.weight
        else:
         return None

      for model_class in self.all_model_classes:
       for size in [config.vocab_size - 1_0, config.vocab_size + 1_0]:
        # build the embeddings
        __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	model_class(config=UpperCamelCase				)
        __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	_get_word_embedding_weight(UpperCamelCase     ,  model.get_input_embeddings()				)
        __SCREAMING_SNAKE_CASE       :    List[str]       =	_get_word_embedding_weight(UpperCamelCase     ,  model.get_output_embeddings()				)

        # reshape the embeddings
        model.resize_token_embeddings(UpperCamelCase				)
        __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	_get_word_embedding_weight(UpperCamelCase     ,  model.get_input_embeddings()				)
        __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	_get_word_embedding_weight(UpperCamelCase     ,  model.get_output_embeddings()				)

        # check that the resized embeddings size matches the desired size.
        __SCREAMING_SNAKE_CASE       :    Tuple       =	size if size is not None else config.vocab_size

        self.assertEqual(new_input_embeddings.shape[0]     ,  UpperCamelCase				)

        # check that weights remain the same after resizing
        __SCREAMING_SNAKE_CASE       :    str       =	True
        for pa, pa in zip(old_input_embeddings.value()     ,  new_input_embeddings.value()				):
         if tf.math.reduce_sum(tf.math.abs(pa - pa				)				) > 0:
          __SCREAMING_SNAKE_CASE       :    Any       =	False
        self.assertTrue(UpperCamelCase				)

        if old_output_embeddings is not None and new_output_embeddings is not None:
         self.assertEqual(new_output_embeddings.shape[0]     ,  UpperCamelCase				)

         __SCREAMING_SNAKE_CASE       :    Optional[int]       =	True
         for pa, pa in zip(old_output_embeddings.value()     ,  new_output_embeddings.value()				):
          if tf.math.reduce_sum(tf.math.abs(pa - pa				)				) > 0:
           __SCREAMING_SNAKE_CASE       :    Optional[int]       =	False
         self.assertTrue(UpperCamelCase				)






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Any     ):



 """simple docstring"""





 return tf.constant(__lowerCamelCase		,	dtype=tf.intaa     )

@require_tf
class       _SCREAMING_SNAKE_CASE	(unittest.TestCase ):
     lowerCAmelCase					=			99





     def 	__snake_case    (       self :							Any				)->Dict:
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	tf.ones((4, 1)     ,  dtype=tf.intaa				) * 2
      __SCREAMING_SNAKE_CASE       :    Tuple       =	tf.concat([ids_tensor((4, 6)     ,  self.vocab_size - 3				) + 3, eos_column_vector]     ,  axis=1				)
      __SCREAMING_SNAKE_CASE       :    List[str]       =	input_ids.shape[0]
      __SCREAMING_SNAKE_CASE       :    List[str]       =	OPTConfig(
          vocab_size=self.vocab_size     ,  hidden_size=2_4     ,  num_hidden_layers=2     ,  num_attention_heads=2     ,  ffn_dim=3_2     ,  max_position_embeddings=4_8     ,  eos_token_id=2     ,  pad_token_id=1     ,  bos_token_id=0     ,  )
      return config, input_ids, batch_size






@require_sentencepiece
@require_tf
class       _SCREAMING_SNAKE_CASE	(unittest.TestCase ):





     @slow
     def 	__snake_case    (       self :							List[Any]				)->Optional[int]:
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	TFOPTModel.from_pretrained("facebook/opt-350m"				)
      __SCREAMING_SNAKE_CASE       :    str       =	_long_tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]]				)
      __SCREAMING_SNAKE_CASE       :    Tuple       =	tf.not_equal(UpperCamelCase     ,  model.config.pad_token_id				)
      with tf.GradientTape():
       __SCREAMING_SNAKE_CASE       :    List[Any]       =	model(input_ids=UpperCamelCase     ,  attention_mask=UpperCamelCase				).last_hidden_state
      __SCREAMING_SNAKE_CASE       :    Dict       =	(1, 1_1, 5_1_2)
      self.assertEqual(output.shape     ,  UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	tf.constant(
          [[-0.2_8_7_3, -1.9_2_1_8, -0.3_0_3_3], [-1.2_7_1_0, -0.1_3_3_8, -0.1_9_0_2], [0.4_0_9_5, 0.1_2_1_4, -1.3_1_2_1]]				)
      self.assertTrue(np.allclose(output[:, :3, :3]     ,  UpperCamelCase     ,  atol=4E-3				)				)

      __SCREAMING_SNAKE_CASE       :    List[Any]       =	tf.function(UpperCamelCase     ,  jit_compile=UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    int       =	xla_generate(UpperCamelCase     ,  UpperCamelCase				)[0]
      self.assertTrue(np.allclose(output[:, :3, :3]     ,  UpperCamelCase     ,  atol=4E-2				)				)






@require_tf
@slow
class       _SCREAMING_SNAKE_CASE	(unittest.TestCase ):





     def 	__snake_case    (       self :							Union[str, Any]				)->List[Any]:
      super().setUp()
      __SCREAMING_SNAKE_CASE       :    List[str]       =	"facebook/opt-350m"






     def 	__snake_case    (       self :							Optional[int]				)->int:
      __SCREAMING_SNAKE_CASE       :    List[str]       =	TFOPTForCausalLM.from_pretrained(self.path_model				)
      __SCREAMING_SNAKE_CASE       :    int       =	GPTaTokenizer.from_pretrained(self.path_model				)

      __SCREAMING_SNAKE_CASE       :    Tuple       =	[
          "Today is a beautiful day and I want to",
          "In the city of",
          "Paris is the capital of France and",
          "Computers and mobile phones have taken",
      ]
      # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
      __SCREAMING_SNAKE_CASE       :    str       =	tokenizer(UpperCamelCase     ,  return_tensors="tf"     ,  padding=UpperCamelCase     ,  add_special_tokens=UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	tf.math.reduce_mean(model(inputs.input_ids     ,  attention_mask=inputs.attention_mask				)[0]     ,  axis=-1				)
      __SCREAMING_SNAKE_CASE       :    Dict       =	tf.constant(
          [
              [1.3_8_5_1, -1_3.8_9_2_3, -1_0.5_2_2_9, -1_0.7_5_3_3, -0.2_3_0_9, -1_0.2_3_8_4, -0.5_3_6_5, -9.0_9_4_7, -5.1_6_7_0],
              [-4.7_0_7_3, -1_0.6_2_7_6, -3.9_4_1_5, -2_1.5_2_4_2, -0.2_8_2_2, -0.2_8_2_2, -0.2_8_2_2, -0.2_8_2_2, -0.2_8_2_2],
              [0.6_2_4_7, -3.4_2_2_9, -8.9_1_7_9, -1.4_2_9_7, -1_4.1_6_5_0, 1.4_1_4_6, -9.0_2_1_8, -0.2_7_0_3, -0.2_7_0_3],
              [6.4_7_8_3, -1.9_9_1_3, -1_0.7_9_2_6, -2.3_3_3_6, 1.5_0_9_2, -0.9_9_7_4, -6.8_2_1_3, 1.3_4_7_7, 1.3_4_7_7],
          ]				)
      self.assertTrue(np.allclose(UpperCamelCase     ,  UpperCamelCase     ,  atol=1E-4				)				)

      __SCREAMING_SNAKE_CASE       :    List[str]       =	tf.function(UpperCamelCase     ,  jit_compile=UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    List[str]       =	tf.math.reduce_mean(xla_generate(inputs.input_ids     ,  attention_mask=inputs.attention_mask				)[0]     ,  axis=-1				)
      self.assertTrue(np.allclose(UpperCamelCase     ,  UpperCamelCase     ,  atol=1E-4				)				)






@require_tf
@slow
class       _SCREAMING_SNAKE_CASE	(unittest.TestCase ):





     @property
     def 	__snake_case    (       self :							List[Any]				)->int:
      return [
          "Today is a beautiful day and I want",
          "In the city of",
          "Paris is the capital of France and",
          "Computers and mobile phones have taken",
      ]





     def 	__snake_case    (       self :							Any				)->Optional[Any]:
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	"facebook/opt-125m"

      __SCREAMING_SNAKE_CASE       :    Dict       =	[
          "Today is a beautiful day and I want to",
          "In the city of New York, the city",
          "Paris is the capital of France and the capital",
          "Computers and mobile phones have taken over the",
      ]

      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	[]
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	GPTaTokenizer.from_pretrained(UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Tuple       =	TFOPTForCausalLM.from_pretrained(UpperCamelCase				)

      for prompt in self.prompts:
       __SCREAMING_SNAKE_CASE       :    str       =	tokenizer(UpperCamelCase     ,  return_tensors="tf"				).input_ids

       __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	model.generate(UpperCamelCase     ,  max_length=1_0				)

       __SCREAMING_SNAKE_CASE       :    Optional[int]       =	tokenizer.batch_decode(UpperCamelCase     ,  skip_special_tokens=UpperCamelCase				)
       predicted_outputs += generated_string

      self.assertListEqual(UpperCamelCase     ,  UpperCamelCase				)





     def 	__snake_case    (       self :							str				)->Dict:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	"facebook/opt-350m"

      __SCREAMING_SNAKE_CASE       :    Dict       =	GPTaTokenizer.from_pretrained(UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Dict       =	TFOPTForCausalLM.from_pretrained(UpperCamelCase				)

      __SCREAMING_SNAKE_CASE       :    List[str]       =	"left"

      # use different length sentences to test batching
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	[
          "Hello, my dog is a little",
          "Today, I",
      ]

      __SCREAMING_SNAKE_CASE       :    List[Any]       =	tokenizer(UpperCamelCase     ,  return_tensors="tf"     ,  padding=UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Tuple       =	inputs["input_ids"]

      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	model.generate(input_ids=UpperCamelCase     ,  attention_mask=inputs["attention_mask"]				)

      __SCREAMING_SNAKE_CASE       :    Any       =	tokenizer(sentences[0]     ,  return_tensors="tf"				).input_ids
      __SCREAMING_SNAKE_CASE       :    Tuple       =	model.generate(input_ids=UpperCamelCase				)

      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	inputs_non_padded.shape[-1] - tf.math.reduce_sum(
          tf.cast(inputs["attention_mask"][-1]     ,  tf.intaa				)				)
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	tokenizer(sentences[1]     ,  return_tensors="tf"				).input_ids
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	model.generate(input_ids=UpperCamelCase     ,  max_length=model.config.max_length - num_paddings				)

      __SCREAMING_SNAKE_CASE       :    Tuple       =	tokenizer.batch_decode(UpperCamelCase     ,  skip_special_tokens=UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	tokenizer.decode(output_non_padded[0]     ,  skip_special_tokens=UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	tokenizer.decode(output_padded[0]     ,  skip_special_tokens=UpperCamelCase				)

      __SCREAMING_SNAKE_CASE       :    int       =	[
          "Hello, my dog is a little bit of a dork.\nI'm a little bit",
          "Today, I was in the middle of a conversation with a friend about the",
      ]
      self.assertListEqual(UpperCamelCase     ,  UpperCamelCase				)
      self.assertListEqual(UpperCamelCase     ,  [non_padded_sentence, padded_sentence]				)






     def 	__snake_case    (       self :							List[str]				)->str:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	"facebook/opt-350m"

      __SCREAMING_SNAKE_CASE       :    Tuple       =	[
          "Today is a beautiful day and I want to",
          "In the city of San Francisco, the city",
          "Paris is the capital of France and the capital",
          "Computers and mobile phones have taken over the",
      ]

      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	[]
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	GPTaTokenizer.from_pretrained(UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	TFOPTForCausalLM.from_pretrained(UpperCamelCase				)

      for prompt in self.prompts:
       __SCREAMING_SNAKE_CASE       :    List[Any]       =	tokenizer(UpperCamelCase     ,  return_tensors="tf"				).input_ids

       __SCREAMING_SNAKE_CASE       :    int       =	model.generate(UpperCamelCase     ,  max_length=1_0				)

       __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	tokenizer.batch_decode(UpperCamelCase     ,  skip_special_tokens=UpperCamelCase				)
       predicted_outputs += generated_string

      self.assertListEqual(UpperCamelCase     ,  UpperCamelCase				)











from .constants import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SAFE_WEIGHTS_INDEX_NAME,
    SAFE_WEIGHTS_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    TORCH_LAUNCH_PARAMS,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
)
from .dataclasses import (
    BnbQuantizationConfig,
    ComputeEnvironment,
    CustomDtype,
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    DynamoBackend,
    FPaRecipeKwargs,
    FullyShardedDataParallelPlugin,
    GradientAccumulationPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    KwargsHandler,
    LoggerType,
    MegatronLMPlugin,
    PrecisionType,
    ProjectConfiguration,
    RNGType,
    SageMakerDistributedType,
    TensorInformation,
    TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
    get_ccl_version,
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_aim_available,
    is_bfaa_available,
    is_bnb_available,
    is_botoa_available,
    is_ccl_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_fpa_available,
    is_ipex_available,
    is_megatron_lm_available,
    is_mlflow_available,
    is_mps_available,
    is_npu_available,
    is_rich_available,
    is_safetensors_available,
    is_sagemaker_available,
    is_tensorboard_available,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
from .modeling import (
    check_device_map,
    check_tied_parameters_in_config,
    check_tied_parameters_on_same_device,
    compute_module_sizes,
    convert_file_size_to_int,
    dtype_byte_size,
    find_tied_parameters,
    get_balanced_memory,
    get_max_layer_size,
    get_max_memory,
    get_mixed_precision_context_manager,
    id_tensor_storage,
    infer_auto_device_map,
    load_checkpoint_in_model,
    load_offloaded_weights,
    load_state_dict,
    named_module_tensors,
    retie_parameters,
    set_module_tensor_to_device,
    shard_checkpoint,
)
from .offload import (
    OffloadedWeightsLoader,
    PrefixedDataset,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
    save_offload_index,
)
from .operations import (
    broadcast,
    broadcast_object_list,
    concatenate,
    convert_outputs_to_fpaa,
    convert_to_fpaa,
    find_batch_size,
    find_device,
    gather,
    gather_object,
    get_data_structure,
    honor_type,
    initialize_tensors,
    is_namedtuple,
    is_tensor_information,
    is_torch_tensor,
    listify,
    pad_across_processes,
    recursively_apply,
    reduce,
    send_to_device,
    slice_tensors,
)
from .versions import compare_versions, is_torch_version


if is_deepspeed_available():
      from .deepspeed import (
          DeepSpeedEngineWrapper,
          DeepSpeedOptimizerWrapper,
          DeepSpeedSchedulerWrapper,
          DummyOptim,
          DummyScheduler,
          HfDeepSpeedConfig,
      )

from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
    PrepareForLaunch,
    _filter_args,
    prepare_deepspeed_cmd_env,
    prepare_multi_gpu_env,
    prepare_sagemager_args_inputs,
    prepare_simple_launcher_cmd_env,
    prepare_tpu,
)
from .megatron_lm import (
    AbstractTrainStep,
    BertTrainStep,
    GPTTrainStep,
    MegatronEngine,
    MegatronLMDummyDataLoader,
    MegatronLMDummyScheduler,
    MegatronLMOptimizerWrapper,
    MegatronLMSchedulerWrapper,
    TaTrainStep,
    avg_losses_across_data_parallel_group,
    gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
    extract_model_from_parallel,
    get_pretty_name,
    is_port_in_use,
    merge_dicts,
    patch_environment,
    save,
    wait_for_everyone,
    write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers






