"""simple docstring"""





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


"""simple docstring"""





import unittest

import numpy as np

from transformers import AlbertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
       import jax.numpy as jnp

       from transformers.models.albert.modeling_flax_albert import (
           FlaxAlbertForMaskedLM,
           FlaxAlbertForMultipleChoice,
           FlaxAlbertForPreTraining,
           FlaxAlbertForQuestionAnswering,
           FlaxAlbertForSequenceClassification,
           FlaxAlbertForTokenClassification,
           FlaxAlbertModel,
       )


class   UpperCAmelCase_			(					unittest.TestCase):


      def __init__(     self	,    a	,    a=1_3	,    a=7	,    a=True	,    a=True	,    a=True	,    a=True	,    a=9_9	,    a=3_2	,    a=5	,    a=4	,    a=3_7	,    a="gelu"	,    a=0.1	,    a=0.1	,    a=5_1_2	,    a=1_6	,    a=2	,    a=0.02	,    a=4	,    ) ->      Dict:
             lowercase__    :	Optional[Any]     					=			parent
             lowercase__    :	Dict     					=			batch_size
             lowercase__    :	List[Any]     					=			seq_length
             lowercase__    :	int     					=			is_training
             lowercase__    :	str     					=			use_attention_mask
             lowercase__    :	Dict     					=			use_token_type_ids
             lowercase__    :	Optional[int]     					=			use_labels
             lowercase__    :	Tuple     					=			vocab_size
             lowercase__    :	List[str]     					=			hidden_size
             lowercase__    :	Union[str, Any]     					=			num_hidden_layers
             lowercase__    :	int     					=			num_attention_heads
             lowercase__    :	Dict     					=			intermediate_size
             lowercase__    :	List[str]     					=			hidden_act
             lowercase__    :	Dict     					=			hidden_dropout_prob
             lowercase__    :	Tuple     					=			attention_probs_dropout_prob
             lowercase__    :	List[str]     					=			max_position_embeddings
             lowercase__    :	int     					=			type_vocab_size
             lowercase__    :	List[str]     					=			type_sequence_label_size
             lowercase__    :	Union[str, Any]     					=			initializer_range
             lowercase__    :	Optional[int]     					=			num_choices


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             lowercase__    :	List[Any]     					=			ids_tensor([self.batch_size, self.seq_length]	,    self.vocab_size							)

             lowercase__    :	str     					=			None
             if self.use_attention_mask:
                    lowercase__    :	Optional[Any]     					=			random_attention_mask([self.batch_size, self.seq_length]							)

             lowercase__    :	List[str]     					=			None
             if self.use_token_type_ids:
                    lowercase__    :	Optional[int]     					=			ids_tensor([self.batch_size, self.seq_length]	,    self.type_vocab_size							)

             lowercase__    :	Any     					=			AlbertConfig(
                 vocab_size=self.vocab_size	,    hidden_size=self.hidden_size	,    num_hidden_layers=self.num_hidden_layers	,    num_attention_heads=self.num_attention_heads	,    intermediate_size=self.intermediate_size	,    hidden_act=self.hidden_act	,    hidden_dropout_prob=self.hidden_dropout_prob	,    attention_probs_dropout_prob=self.attention_probs_dropout_prob	,    max_position_embeddings=self.max_position_embeddings	,    type_vocab_size=self.type_vocab_size	,    is_decoder=a	,    initializer_range=self.initializer_range	,    )

             return config, input_ids, token_type_ids, attention_mask


      def 	_UpperCAmelCase (     self							) ->      Any:
             lowercase__    :	Optional[int]     					=			self.prepare_config_and_inputs()
             lowercase__					,   lowercase__					,   lowercase__					,   lowercase__    :	Tuple     					=			config_and_inputs
             lowercase__    :	Union[str, Any]     					=			{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask}
             return config, inputs_dict





@require_flax
class   UpperCAmelCase_			(					_a				,							unittest.TestCase):
      lowerCamelCase__	:					Tuple										=						(
          (
              FlaxAlbertModel,
              FlaxAlbertForPreTraining,
              FlaxAlbertForMaskedLM,
              FlaxAlbertForMultipleChoice,
              FlaxAlbertForQuestionAnswering,
              FlaxAlbertForSequenceClassification,
              FlaxAlbertForTokenClassification,
              FlaxAlbertForQuestionAnswering,
          )
          if is_flax_available()
          else ()
      )


      def 	_UpperCAmelCase (     self							) ->      List[Any]:
             lowercase__    :	Union[str, Any]     					=			FlaxAlbertModelTester(self							)


      @slow
      def 	_UpperCAmelCase (     self							) ->      str:
             for model_class_name in self.all_model_classes:
                    lowercase__    :	str     					=			model_class_name.from_pretrained('albert-base-v2'							)
                    lowercase__    :	Tuple     					=			model(np.ones((1, 1)							)							)
                    self.assertIsNotNone(a							)





@require_flax
class   UpperCAmelCase_			(					unittest.TestCase):


      @slow
      def 	_UpperCAmelCase (     self							) ->      Tuple:
             lowercase__    :	str     					=			FlaxAlbertModel.from_pretrained('albert-base-v2'							)
             lowercase__    :	Optional[int]     					=			np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]							)
             lowercase__    :	Optional[Any]     					=			np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
             lowercase__    :	Any     					=			model(a	,    attention_mask=a							)[0]
             lowercase__    :	Tuple     					=			(1, 1_1, 7_6_8)
             self.assertEqual(output.shape	,    a							)
             lowercase__    :	Optional[Any]     					=			np.array(
                 [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]]							)

             self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]	,    a	,    atol=1e-4							)							)

