
import random
import unittest

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
 import os

 import jax.numpy as jnp
 from jax import jit

 from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
 from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

 __lowerCAmelCase					:			List[str]			      =		"0.12"  # assumed parallelism: 8


if is_torch_available():
 import torch


def     UpperCAmelCase_  (						__lowerCAmelCase	,					__lowerCAmelCase	,					__lowerCAmelCase=None	) ->						Tuple:
    if rng is None:
        __lowercase		:			List[str]	    =       random.Random()

    __lowercase		:			str	    =       1
    for dim in shape:
        total_dims *= dim

    __lowercase		:			Any	    =       []
    for _ in range(__lowerCAmelCase	):
        values.append(rng.randint(0	,					vocab_size - 1	)	)

    __lowercase		:			Tuple	    =       np.array(__lowerCAmelCase	,					dtype=jnp.intaa	).reshape(__lowerCAmelCase	)

    return output


def     UpperCAmelCase_  (						__lowerCAmelCase	,					__lowerCAmelCase=None	) ->						List[str]:
    __lowercase		:			Optional[int]	    =       ids_tensor(__lowerCAmelCase	,					vocab_size=2	,					rng=__lowerCAmelCase	)
    # make sure that at least one token is attended to for each batch
    __lowercase		:			str	    =       1
    return attn_mask


@require_flax
class 						__lowerCAmelCase	:



      """simple docstring"""







      A__	:			Optional[Any]        =    None
      A__	:			List[str]        =    ()




      def 		snake_case_			(      self		:       Union[str, Any]				):
          __lowercase    ,      __lowercase		:			Any	    =       self.model_tester.prepare_config_and_inputs_for_common()

          # cut to half length & take max batch_size 3
          __lowercase		:			Optional[int]	    =       2
          __lowercase		:			Tuple	    =       inputs['''input_ids'''].shape[-1] // 2
          __lowercase		:			Dict	    =       inputs['''input_ids'''][:max_batch_size, :sequence_length]

          __lowercase		:			Union[str, Any]	    =       jnp.ones_like(_snake_case				)
          __lowercase		:			int	    =       attention_mask[:max_batch_size, :sequence_length]

          # generate max 5 tokens
          __lowercase		:			List[Any]	    =       input_ids.shape[-1] + 5
          if config.eos_token_id is not None and config.pad_token_id is None:
              # hack to allow generate for models such as GPT2 as is done in `generate()`
              __lowercase		:			Any	    =       config.eos_token_id
          return config, input_ids, attention_mask, max_length




      @is_pt_flax_cross_test
      def 		snake_case_			(      self		:       int				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			List[Any]	    =       self._get_input_ids_and_config()
          __lowercase		:			str	    =       False
          __lowercase		:			Any	    =       max_length
          __lowercase		:			Optional[Any]	    =       0

          for model_class in self.all_generative_model_classes:
              __lowercase		:			Dict	    =       model_class(_snake_case				)

              __lowercase		:			str	    =       model_class.__name__[4:]  # Skip the "Flax" at the beginning
              __lowercase		:			List[Any]	    =       getattr(_snake_case				,       _snake_case				)
              __lowercase		:			Any	    =       pt_model_class(_snake_case				).eval()
              __lowercase		:			List[Any]	    =       load_flax_weights_in_pytorch_model(_snake_case				,       flax_model.params				)

              __lowercase		:			List[Any]	    =       flax_model.generate(_snake_case				).sequences
              __lowercase		:			Optional[Any]	    =       pt_model.generate(torch.tensor(_snake_case				,       dtype=torch.long				)				)

              if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
                  __lowercase		:			List[Any]	    =       flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

              self.assertListEqual(pt_generation_outputs.numpy().tolist()				,       flax_generation_outputs.tolist()				)




      def 		snake_case_			(      self		:       Dict				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			Tuple	    =       self._get_input_ids_and_config()
          __lowercase		:			List[Any]	    =       False
          __lowercase		:			Tuple	    =       max_length

          for model_class in self.all_generative_model_classes:
              __lowercase		:			List[str]	    =       model_class(_snake_case				)

              __lowercase		:			int	    =       model.generate(_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[-1]				,       _snake_case				)

              __lowercase		:			List[str]	    =       jit(model.generate				)
              __lowercase		:			List[str]	    =       jit_generate(_snake_case				).sequences

              self.assertListEqual(generation_outputs.tolist()				,       jit_generation_outputs.tolist()				)




      def 		snake_case_			(      self		:       int				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			str	    =       self._get_input_ids_and_config()
          __lowercase		:			List[Any]	    =       True
          __lowercase		:			List[Any]	    =       max_length

          for model_class in self.all_generative_model_classes:
              __lowercase		:			Dict	    =       model_class(_snake_case				)

              __lowercase		:			Tuple	    =       model.generate(_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[-1]				,       _snake_case				)

              __lowercase		:			Dict	    =       jit(model.generate				)
              __lowercase		:			List[Any]	    =       jit_generate(_snake_case				).sequences

              self.assertListEqual(generation_outputs.tolist()				,       jit_generation_outputs.tolist()				)




      def 		snake_case_			(      self		:       Optional[Any]				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			List[Any]	    =       self._get_input_ids_and_config()
          __lowercase		:			str	    =       False
          __lowercase		:			Any	    =       max_length
          __lowercase		:			Optional[Any]	    =       2

          for model_class in self.all_generative_model_classes:
              __lowercase		:			List[str]	    =       model_class(_snake_case				)

              __lowercase		:			int	    =       model.generate(_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[-1]				,       _snake_case				)

              __lowercase		:			Union[str, Any]	    =       jit(model.generate				)
              __lowercase		:			List[str]	    =       jit_generate(_snake_case				).sequences

              self.assertListEqual(generation_outputs.tolist()				,       jit_generation_outputs.tolist()				)




      def 		snake_case_			(      self		:       Any				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			Tuple	    =       self._get_input_ids_and_config()
          __lowercase		:			int	    =       False
          __lowercase		:			Any	    =       max_length
          __lowercase		:			Dict	    =       2
          __lowercase		:			List[Any]	    =       2

          for model_class in self.all_generative_model_classes:
              __lowercase		:			Union[str, Any]	    =       model_class(_snake_case				)

              __lowercase		:			str	    =       model.generate(_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[0]				,       input_ids.shape[0] * config.num_return_sequences				)




      def 		snake_case_			(      self		:       str				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			Optional[Any]	    =       self._get_input_ids_and_config()
          __lowercase		:			List[str]	    =       True
          __lowercase		:			List[str]	    =       max_length
          __lowercase		:			Tuple	    =       0.8
          __lowercase		:			List[Any]	    =       10
          __lowercase		:			Tuple	    =       0.3
          __lowercase		:			Any	    =       1
          __lowercase		:			str	    =       8
          __lowercase		:			Optional[int]	    =       9

          for model_class in self.all_generative_model_classes:
              __lowercase		:			Union[str, Any]	    =       model_class(_snake_case				)

              __lowercase		:			Union[str, Any]	    =       model.generate(_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[-1]				,       _snake_case				)

              __lowercase		:			List[str]	    =       jit(model.generate				)
              __lowercase		:			Optional[Any]	    =       jit_generate(_snake_case				).sequences

              self.assertListEqual(generation_outputs.tolist()				,       jit_generation_outputs.tolist()				)




      def 		snake_case_			(      self		:       Dict				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			Tuple	    =       self._get_input_ids_and_config()
          __lowercase		:			Dict	    =       max_length
          __lowercase		:			int	    =       1
          __lowercase		:			Dict	    =       8
          __lowercase		:			Dict	    =       9

          for model_class in self.all_generative_model_classes:
              __lowercase		:			Union[str, Any]	    =       model_class(_snake_case				)

              __lowercase		:			int	    =       model.generate(_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[-1]				,       _snake_case				)

              __lowercase		:			int	    =       jit(model.generate				)
              __lowercase		:			int	    =       jit_generate(_snake_case				).sequences

              self.assertListEqual(generation_outputs.tolist()				,       jit_generation_outputs.tolist()				)




      def 		snake_case_			(      self		:       int				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			str	    =       self._get_input_ids_and_config()
          __lowercase		:			Optional[int]	    =       max_length
          __lowercase		:			Dict	    =       2
          __lowercase		:			Union[str, Any]	    =       1
          __lowercase		:			List[str]	    =       8
          __lowercase		:			List[Any]	    =       9

          for model_class in self.all_generative_model_classes:
              __lowercase		:			Optional[Any]	    =       model_class(_snake_case				)

              __lowercase		:			List[Any]	    =       model.generate(_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[-1]				,       _snake_case				)

              __lowercase		:			Union[str, Any]	    =       jit(model.generate				)
              __lowercase		:			Union[str, Any]	    =       jit_generate(_snake_case				).sequences

              self.assertListEqual(generation_outputs.tolist()				,       jit_generation_outputs.tolist()				)




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			int	    =       self._get_input_ids_and_config()

          # pad attention mask on the left
          __lowercase		:			Optional[Any]	    =       attention_mask.at[(0, 0)].set(0				)

          __lowercase		:			int	    =       False
          __lowercase		:			Optional[int]	    =       max_length

          for model_class in self.all_generative_model_classes:
              __lowercase		:			Dict	    =       model_class(_snake_case				)

              __lowercase		:			List[Any]	    =       model.generate(_snake_case				,       attention_mask=_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[-1]				,       _snake_case				)

              __lowercase		:			str	    =       jit(model.generate				)
              __lowercase		:			Any	    =       jit_generate(_snake_case				,       attention_mask=_snake_case				).sequences

              self.assertListEqual(generation_outputs.tolist()				,       jit_generation_outputs.tolist()				)




      def 		snake_case_			(      self		:       int				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			List[Any]	    =       self._get_input_ids_and_config()

          # pad attention mask on the left
          __lowercase		:			Optional[Any]	    =       attention_mask.at[(0, 0)].set(0				)

          __lowercase		:			str	    =       True
          __lowercase		:			Any	    =       max_length

          for model_class in self.all_generative_model_classes:
              __lowercase		:			Any	    =       model_class(_snake_case				)

              __lowercase		:			List[Any]	    =       model.generate(_snake_case				,       attention_mask=_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[-1]				,       _snake_case				)

              __lowercase		:			Optional[int]	    =       jit(model.generate				)
              __lowercase		:			Union[str, Any]	    =       jit_generate(_snake_case				,       attention_mask=_snake_case				).sequences

              self.assertListEqual(generation_outputs.tolist()				,       jit_generation_outputs.tolist()				)




      def 		snake_case_			(      self		:       Dict				):
          __lowercase    ,      __lowercase    ,      __lowercase    ,      __lowercase		:			Tuple	    =       self._get_input_ids_and_config()

          # pad attention mask on the left
          __lowercase		:			List[Any]	    =       attention_mask.at[(0, 0)].set(0				)

          __lowercase		:			int	    =       2
          __lowercase		:			int	    =       max_length

          for model_class in self.all_generative_model_classes:
              __lowercase		:			List[str]	    =       model_class(_snake_case				)

              __lowercase		:			Optional[int]	    =       model.generate(_snake_case				,       attention_mask=_snake_case				).sequences
              self.assertEqual(generation_outputs.shape[-1]				,       _snake_case				)

              __lowercase		:			int	    =       jit(model.generate				)
              __lowercase		:			str	    =       jit_generate(_snake_case				,       attention_mask=_snake_case				).sequences

              self.assertListEqual(generation_outputs.tolist()				,       jit_generation_outputs.tolist()				)






@require_flax
class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      def 		snake_case_			(      self		:       str				):
          __lowercase		:			Union[str, Any]	    =       AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-bert'''				)
          __lowercase		:			int	    =       FlaxAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''				)

          __lowercase		:			Optional[int]	    =       '''Hello world'''
          __lowercase		:			int	    =       tokenizer(_snake_case				,       return_tensors='''np'''				).input_ids

          # typos are quickly detected (the correct argument is `do_sample`)
          with self.assertRaisesRegex(_snake_case				,       '''do_samples'''				):
              model.generate(_snake_case				,       do_samples=_snake_case				)

          # arbitrary arguments that will not be used anywhere are also not accepted
          with self.assertRaisesRegex(_snake_case				,       '''foo'''				):
              __lowercase		:			Dict	    =       {'''foo''': '''bar'''}
              model.generate(_snake_case				,       **_snake_case				)




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


