



"""simple docstring"""





from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
  from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


lowerCamelCase       	=						logging.get_logger(__name__)

lowerCamelCase       	=						{
    """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/resolve/main/config.json""",
    """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/config.json""",
    """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json""",
    """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json""",
    """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/config.json""",
    """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json""",
}
class 				lowercase__       (   SCREAMING_SNAKE_CASE				):







       '''simple docstring'''


       UpperCamelCase						=					'''bloom'''
       UpperCamelCase						=					['''past_key_values''']
       UpperCamelCase						=					{
           '''num_hidden_layers''': '''n_layer''',
           '''num_attention_heads''': '''n_head''',
       }



       def __init__(							self      :  List[Any]		,    _UpperCAmelCase      :  Optional[int]=250880		,    _UpperCAmelCase      :  Tuple=64		,    _UpperCAmelCase      :  Tuple=2		,    _UpperCAmelCase      :  Tuple=8		,    _UpperCAmelCase      :  str=1e-5		,    _UpperCAmelCase      :  Dict=0.02		,    _UpperCAmelCase      :  Union[str, Any]=True		,    _UpperCAmelCase      :  Optional[int]=1		,    _UpperCAmelCase      :  List[str]=2		,    _UpperCAmelCase      :  int=False		,    _UpperCAmelCase      :  Union[str, Any]=0.0		,    _UpperCAmelCase      :  Any=0.0		,    _UpperCAmelCase      :  str=1		,    _UpperCAmelCase      :  str=False		,    **_UpperCAmelCase      :  str		,    )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							vocab_size
             # Backward compatibility with n_embed kwarg
             UpperCAmelCase_      			=							kwargs.pop("n_embed"		,    _UpperCAmelCase   )
             UpperCAmelCase_      			=							hidden_size if n_embed is None else n_embed
             UpperCAmelCase_      			=							n_layer
             UpperCAmelCase_      			=							n_head
             UpperCAmelCase_      			=							layer_norm_epsilon
             UpperCAmelCase_      			=							initializer_range
             UpperCAmelCase_      			=							use_cache
             UpperCAmelCase_      			=							pretraining_tp
             UpperCAmelCase_      			=							apply_residual_connection_post_layernorm
             UpperCAmelCase_      			=							hidden_dropout
             UpperCAmelCase_      			=							attention_dropout

             UpperCAmelCase_      			=							bos_token_id
             UpperCAmelCase_      			=							eos_token_id
             UpperCAmelCase_      			=							slow_but_exact

             super().__init__(bos_token_id=_UpperCAmelCase		,    eos_token_id=_UpperCAmelCase		,    **_UpperCAmelCase   )



class 				lowercase__       (   SCREAMING_SNAKE_CASE				):







       '''simple docstring'''


       UpperCamelCase						=					version.parse('''1.12'''				)



       def __init__(							self      :  Optional[int]		,    _UpperCAmelCase      :  PretrainedConfig		,    _UpperCAmelCase      :  str = "default"		,    _UpperCAmelCase      :  List[PatchingSpec] = None		,    _UpperCAmelCase      :  bool = False		,    )			->						Any:


             '''simple docstring'''




             super().__init__(_UpperCAmelCase		,    task=_UpperCAmelCase		,    patching_specs=_UpperCAmelCase		,    use_past=_UpperCAmelCase   )
             if not getattr(self._config		,    "pad_token_id"		,    _UpperCAmelCase   ):
                   # TODO: how to do that better?
                   UpperCAmelCase_      			=							0



       @property
       def 					lowercase__    (							self      :  Optional[int]   )			->						Mapping[str, Mapping[int, str]]:


             '''simple docstring'''




             UpperCAmelCase_      			=							OrderedDict({"input_ids": {0: "batch", 1: "sequence"}}   )
             if self.use_past:
                   # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
                   self.fill_with_past_key_values_(_UpperCAmelCase		,    direction="inputs"		,    inverted_values_shape=_UpperCAmelCase   )
                   UpperCAmelCase_      			=							{0: "batch", 1: "past_sequence + sequence"}
             else:
                   UpperCAmelCase_      			=							{0: "batch", 1: "sequence"}

             return common_inputs



       @property
       def 					lowercase__    (							self      :  int   )			->						int:


             '''simple docstring'''




             return self._config.n_layer



       @property
       def 					lowercase__    (							self      :  str   )			->						int:


             '''simple docstring'''




             return self._config.n_head



       @property
       def 					lowercase__    (							self      :  List[str]   )			->						float:


             '''simple docstring'''




             return 1e-3



       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  "PreTrainedTokenizer"		,    _UpperCAmelCase      :  int = -1		,    _UpperCAmelCase      :  int = -1		,    _UpperCAmelCase      :  bool = False		,    _UpperCAmelCase      :  Optional["TensorType"] = None		,    )			->						Mapping[str, Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							super(_UpperCAmelCase		,    self   ).generate_dummy_inputs(
                 _UpperCAmelCase		,    batch_size=_UpperCAmelCase		,    seq_length=_UpperCAmelCase		,    is_pair=_UpperCAmelCase		,    framework=_UpperCAmelCase   )

             # We need to order the input in the way they appears in the forward()
             UpperCAmelCase_      			=							OrderedDict({"input_ids": common_inputs["input_ids"]}   )

             # Need to add the past_keys
             if self.use_past:
                   if not is_torch_available():
                         raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."   )
                   else:
                         import torch

                         UpperCAmelCase_			,   UpperCAmelCase_      			=							common_inputs["input_ids"].shape
                         # Not using the same length for past_key_values
                         UpperCAmelCase_      			=							seqlen + 2
                         UpperCAmelCase_      			=							self._config.hidden_size // self.num_attention_heads
                         UpperCAmelCase_      			=							(
                             batch * self.num_attention_heads,
                             head_dim,
                             past_key_values_length,
                         )
                         UpperCAmelCase_      			=							(
                             batch * self.num_attention_heads,
                             past_key_values_length,
                             head_dim,
                         )
                         UpperCAmelCase_      			=							[
                             (torch.zeros(_UpperCAmelCase   ), torch.zeros(_UpperCAmelCase   )) for _ in range(self.num_layers   )
                         ]

             UpperCAmelCase_      			=							common_inputs["attention_mask"]
             if self.use_past:
                   UpperCAmelCase_      			=							ordered_inputs["attention_mask"].dtype
                   UpperCAmelCase_      			=							torch.cat(
                       [ordered_inputs["attention_mask"], torch.ones(_UpperCAmelCase		,    _UpperCAmelCase		,    dtype=_UpperCAmelCase   )]		,    dim=1   )

             return ordered_inputs







       @property
       def 					lowercase__    (							self      :  List[Any]   )			->						int:


             '''simple docstring'''




             return 13









"""simple docstring"""





# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


lowerCamelCase       	=						Path(__file__).resolve().parents[3] / """src"""
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

lowerCamelCase       	=						{"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

lowerCamelCase       	=						"""zero2"""
lowerCamelCase       	=						"""zero3"""
lowerCamelCase       	=						[ZEROa, ZEROa]
def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__				):
      # customize the test name generator function as we want both params to appear in the sub-test
      # name, as by default it shows only the first param
      UpperCAmelCase_      			=							parameterized.to_safe_name("_".join(str(lowerCAmelCase__				) for x in param.args				)				)
      return f"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
lowerCamelCase       	=						list(itertools.product(stages, models.keys()))


@slow
@require_deepspeed
@require_torch_gpu
class 				lowercase__       (   SCREAMING_SNAKE_CASE				):







       '''simple docstring'''


       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Dict		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Any   )			->						Optional[int]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @require_torch_multi_gpu
       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Any		,    _UpperCAmelCase      :  Optional[Any]		,    _UpperCAmelCase      :  str   )			->						Any:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  List[str]   )			->						Union[str, Any]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       @require_torch_multi_gpu
       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  int		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Optional[int]   )			->						Optional[int]:


             '''simple docstring'''




             self.run_and_check(
                 stage=_UpperCAmelCase		,    model=_UpperCAmelCase		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  Tuple   )			->						Optional[int]:


             '''simple docstring'''




             pass



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							models[model]

             UpperCAmelCase_      			=							self.run_trainer(
                 stage=_UpperCAmelCase		,    model_name=_UpperCAmelCase		,    eval_steps=_UpperCAmelCase		,    num_train_epochs=1		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )

             self.do_checks(_UpperCAmelCase   )

             return output_dir



       def 					lowercase__    (							self      :  Union[str, Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  int = 1		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Tuple:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.get_auto_remove_tmp_dir("./xxx"		,    after=_UpperCAmelCase   )
             UpperCAmelCase_      			=							F"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(_UpperCAmelCase   )}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

             if fpaa:
                   args.extend(["--fp16"]   )

             # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
             # hence the separate config files
             UpperCAmelCase_      			=							F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
             UpperCAmelCase_      			=							[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
             UpperCAmelCase_      			=							self.get_launcher(_UpperCAmelCase   )

             UpperCAmelCase_      			=							launcher + script + args + ds_args
             # keep for quick debug
             # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
             execute_subprocess_async(_UpperCAmelCase		,    env=self.get_env()   )

             return output_dir







       def 					lowercase__    (							self      :  List[Any]		,    _UpperCAmelCase      :  int=False   )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							min(2		,    get_gpu_count()   ) if distributed else 1
             return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()




