


from __future__ import annotations

import unittest

from transformers import FunnelConfig, is_tf_available
from transformers.testing_utils import require_tf

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 import (
	    TFFunnelBaseModel,
	    TFFunnelForMaskedLM,
	    TFFunnelForMultipleChoice,
	    TFFunnelForPreTraining,
	    TFFunnelForQuestionAnswering,
	    TFFunnelForSequenceClassification,
	    TFFunnelForTokenClassification,
	    TFFunnelModel,
	)




class       lowercase_					:





				def __init__(				self       ,  lowercase_       ,  lowercase_=13       ,  lowercase_=7       ,  lowercase_=True       ,  lowercase_=True       ,  lowercase_=True       ,  lowercase_=True       ,  lowercase_=99       ,  lowercase_=[1, 1, 2]       ,  lowercase_=1       ,  lowercase_=32       ,  lowercase_=4       ,  lowercase_=8       ,  lowercase_=37       ,  lowercase_="gelu_new"       ,  lowercase_=0.1       ,  lowercase_=0.1       ,  lowercase_=0.0       ,  lowercase_=512       ,  lowercase_=3       ,  lowercase_=0.02       ,  lowercase_=3       ,  lowercase_=4       ,  lowercase_=None       ,  lowercase_=False       ,  )  -> int:
											a__      =parent
											a__      =batch_size
											a__      =seq_length
											a__      =is_training
											a__      =use_input_mask
											a__      =use_token_type_ids
											a__      =use_labels
											a__      =vocab_size
											a__      =block_sizes
											a__      =num_decoder_layers
											a__      =d_model
											a__      =n_head
											a__      =d_head
											a__      =d_inner
											a__      =hidden_act
											a__      =hidden_dropout
											a__      =attention_dropout
											a__      =activation_dropout
											a__      =max_position_embeddings
											a__      =type_vocab_size
											a__      =2
											a__      =num_labels
											a__      =num_choices
											a__      =scope
											a__      =initializer_std

											# Used in the tests to check the size of the first attention layer
											a__      =n_head
											# Used in the tests to check the size of the first hidden state
											a__      =self.d_model
											# Used in the tests to check the number of output hidden states/attentions
											a__      =sum(self.block_sizes) + (0 if base else self.num_decoder_layers)
											# FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
											# the last hidden state of the first block (which is the first hidden state of the decoder).
											if not base:
																		a__      =self.num_hidden_layers + 2





				def 						__UpperCamelCase    (				self)  -> Any:
											a__      =ids_tensor([self.batch_size, self.seq_length]       ,  self.vocab_size)

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

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

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

											a__      =FunnelConfig(
											    vocab_size=self.vocab_size       ,  block_sizes=self.block_sizes       ,  num_decoder_layers=self.num_decoder_layers       ,  d_model=self.d_model       ,  n_head=self.n_head       ,  d_head=self.d_head       ,  d_inner=self.d_inner       ,  hidden_act=self.hidden_act       ,  hidden_dropout=self.hidden_dropout       ,  attention_dropout=self.attention_dropout       ,  activation_dropout=self.activation_dropout       ,  max_position_embeddings=self.max_position_embeddings       ,  type_vocab_size=self.type_vocab_size       ,  initializer_std=self.initializer_std       ,  )

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





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  )  -> int:
											a__      =TFFunnelModel(config=lowercase_)
											a__      ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											a__      =model(lowercase_)

											a__      =[input_ids, input_mask]
											a__      =model(lowercase_)

											a__      =model(lowercase_)
											self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.d_model))

											a__      =False
											a__      =TFFunnelModel(config=lowercase_)
											a__      =model(lowercase_)
											self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.d_model))

											a__      =False
											a__      =TFFunnelModel(config=lowercase_)
											a__      =model(lowercase_)
											self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.d_model))





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  )  -> List[str]:
											a__      =TFFunnelBaseModel(config=lowercase_)
											a__      ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											a__      =model(lowercase_)

											a__      =[input_ids, input_mask]
											a__      =model(lowercase_)

											a__      =model(lowercase_)
											self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, 2, self.d_model))

											a__      =False
											a__      =TFFunnelBaseModel(config=lowercase_)
											a__      =model(lowercase_)
											self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, 3, self.d_model))

											a__      =False
											a__      =TFFunnelBaseModel(config=lowercase_)
											a__      =model(lowercase_)
											self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, 2, self.d_model))





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  )  -> List[str]:
											a__      =TFFunnelForPreTraining(config=lowercase_)
											a__      ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											a__      =model(lowercase_)
											self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length))





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  )  -> Optional[int]:
											a__      =TFFunnelForMaskedLM(config=lowercase_)
											a__      ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											a__      =model(lowercase_)
											self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.vocab_size))





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  )  -> Union[str, Any]:
											a__      =self.num_labels
											a__      =TFFunnelForSequenceClassification(config=lowercase_)
											a__      ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											a__      =model(lowercase_)
											self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels))





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  )  -> List[str]:
											a__      =self.num_choices
											a__      =TFFunnelForMultipleChoice(config=lowercase_)
											a__      =tf.tile(tf.expand_dims(lowercase_       ,  1)       ,  (1, self.num_choices, 1))
											a__      =tf.tile(tf.expand_dims(lowercase_       ,  1)       ,  (1, self.num_choices, 1))
											a__      =tf.tile(tf.expand_dims(lowercase_       ,  1)       ,  (1, self.num_choices, 1))
											a__      ={
											    'input_ids': multiple_choice_inputs_ids,
											    'attention_mask': multiple_choice_input_mask,
											    'token_type_ids': multiple_choice_token_type_ids,
											}
											a__      =model(lowercase_)
											self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_choices))





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  )  -> Tuple:
											a__      =self.num_labels
											a__      =TFFunnelForTokenClassification(config=lowercase_)
											a__      ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											a__      =model(lowercase_)
											self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.num_labels))





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  )  -> List[Any]:
											a__      =TFFunnelForQuestionAnswering(config=lowercase_)
											a__      ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
											a__      =model(lowercase_)
											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)  -> str:
											a__      =self.prepare_config_and_inputs()
											(
											    (
											    a__
											)    ,     (
											    a__
											)    ,     (
											    a__
											)    ,     (
											    a__
											)    ,     (
											    a__
											)    ,     (
											    a__
											)    ,     (
											    a__
											)    ,     
											)      =config_and_inputs
											a__      ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
											return config, inputs_dict







@require_tf
class       lowercase_					(lowercase__      ,					lowercase__      ,					unittest.TestCase   ):
				snake_case	    =(
				    (
				        TFFunnelModel,
				        TFFunnelForMaskedLM,
				        TFFunnelForPreTraining,
				        TFFunnelForQuestionAnswering,
				        TFFunnelForTokenClassification,
				    )
				    if is_tf_available()
				    else ()
				)
				snake_case	    =(
				    {
				        'feature-extraction': (TFFunnelBaseModel, TFFunnelModel),
				        'fill-mask': TFFunnelForMaskedLM,
				        'question-answering': TFFunnelForQuestionAnswering,
				        'text-classification': TFFunnelForSequenceClassification,
				        'token-classification': TFFunnelForTokenClassification,
				        'zero-shot': TFFunnelForSequenceClassification,
				    }
				    if is_tf_available()
				    else {}
				)
				snake_case	    =False
				snake_case	    =False





				def 						__UpperCamelCase    (				self)  -> List[str]:
											a__      =TFFunnelModelTester(self)
											a__      =ConfigTester(self       ,  config_class=lowercase_)





				def 						__UpperCamelCase    (				self)  -> Tuple:
											self.config_tester.run_common_tests()





				def 						__UpperCamelCase    (				self)  -> List[str]:
											a__      =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*lowercase_)





				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											a__      =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_pretraining(*lowercase_)





				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											a__      =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_lm(*lowercase_)





				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											a__      =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_token_classification(*lowercase_)





				def 						__UpperCamelCase    (				self)  -> int:
											a__      =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_question_answering(*lowercase_)







@require_tf
class       lowercase_					(lowercase__      ,					unittest.TestCase   ):
				snake_case	    =(
				    (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
				)
				snake_case	    =False
				snake_case	    =False





				def 						__UpperCamelCase    (				self)  -> Optional[int]:
											a__      =TFFunnelModelTester(self       ,  base=lowercase_)
											a__      =ConfigTester(self       ,  config_class=lowercase_)





				def 						__UpperCamelCase    (				self)  -> Optional[Any]:
											self.config_tester.run_common_tests()





				def 						__UpperCamelCase    (				self)  -> str:
											a__      =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_base_model(*lowercase_)





				def 						__UpperCamelCase    (				self)  -> Any:
											a__      =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_sequence_classification(*lowercase_)





				def 						__UpperCamelCase    (				self)  -> List[str]:
											a__      =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_multiple_choice(*lowercase_)





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

