



# 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


__A     =    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)

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

__A     =    "zero2"
__A     =    "zero3"
__A     =    [ZEROa, ZEROa]





def 					lowerCAmelCase_			(	__a     ,   __a     ,   __a		)					->		Tuple:







  """simple docstring"""





  lowerCamelCase__:				List[Any]        =parameterized.to_safe_name("_".join(str(__a		) for x in param.args		)		)
  return F"""{func.__name__}_{param_based_name}"""


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






@slow
@require_deepspeed
@require_torch_gpu
class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 @parameterized.expand(UpperCAmelCase_	,			name_func=UpperCAmelCase_)
 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       int)	->str:



   '''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 							SCREAMING_SNAKE_CASE_ (self    :       Optional[int]	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       List[str])	->str:



   '''simple docstring'''



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

 @parameterized.expand(UpperCAmelCase_	,			name_func=UpperCAmelCase_)
 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any]	,			UpperCAmelCase_    :       Union[str, Any]	,			UpperCAmelCase_    :       Any)	->List[str]:



   '''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 							SCREAMING_SNAKE_CASE_ (self    :       List[Any]	,			UpperCAmelCase_    :       List[Any]	,			UpperCAmelCase_    :       Optional[Any])	->Dict:



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			UpperCAmelCase_    :       str)	->Dict:



   '''simple docstring'''



   pass

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       int = 10	,			UpperCAmelCase_    :       bool = True	,			UpperCAmelCase_    :       bool = True	,			UpperCAmelCase_    :       bool = True	,			)	->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:				List[Any]        =models[model]

   lowerCamelCase__:				Dict        =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 							SCREAMING_SNAKE_CASE_ (self    :       List[str]	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       int = 10	,			UpperCAmelCase_    :       int = 1	,			UpperCAmelCase_    :       bool = True	,			UpperCAmelCase_    :       bool = True	,			)	->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =self.get_auto_remove_tmp_dir("./xxx"	,			after=UpperCAmelCase_)
   lowerCamelCase__:				Dict        =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
   lowerCamelCase__:				Dict        =F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
   lowerCamelCase__:				List[Any]        =[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
   lowerCamelCase__:				Dict        =self.get_launcher(UpperCAmelCase_)

   lowerCamelCase__:				Optional[int]        =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 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			UpperCAmelCase_    :       Tuple=False)	->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[int]        =min(2	,			get_gpu_count()) if distributed else 1
   return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()








from typing import Callable, Dict, Optional, Tuple

import torch
from torch import nn
from torch.distributions import (
    AffineTransform,
    Distribution,
    Independent,
    NegativeBinomial,
    Normal,
    StudentT,
    TransformedDistribution,
)



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 def __init__(self    :       int	,			UpperCAmelCase_    :       Distribution	,			UpperCAmelCase_    :       Dict=None	,			UpperCAmelCase_    :       Tuple=None	,			UpperCAmelCase_    :       Tuple=0)	->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =1.0 if scale is None else scale
   lowerCamelCase__:				List[Any]        =0.0 if loc is None else loc

   super().__init__(UpperCAmelCase_	,			[AffineTransform(loc=self.loc	,			scale=self.scale	,			event_dim=UpperCAmelCase_)])

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any])	->int:



   '''simple docstring'''



   return self.base_dist.mean * self.scale + self.loc

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->Dict:



   '''simple docstring'''



   return self.base_dist.variance * self.scale**2







 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->Optional[Any]:



   '''simple docstring'''



   return self.variance.sqrt()



class        _SCREAMING_SNAKE_CASE						(     nn.Module   ):







 '''simple docstring'''

 def __init__(self    :       Tuple	,			UpperCAmelCase_    :       int	,			UpperCAmelCase_    :       Dict[str, int]	,			UpperCAmelCase_    :       Callable[..., Tuple[torch.Tensor]]	,			**UpperCAmelCase_    :       Dict)	->None:



   '''simple docstring'''



   super().__init__(**UpperCAmelCase_)
   lowerCamelCase__:				Tuple        =args_dim
   lowerCamelCase__:				Any        =nn.ModuleList([nn.Linear(UpperCAmelCase_	,			UpperCAmelCase_) for dim in args_dim.values()])
   lowerCamelCase__:				Any        =domain_map







 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any]	,			UpperCAmelCase_    :       torch.Tensor)	->Tuple[torch.Tensor]:



   '''simple docstring'''



   lowerCamelCase__:				Any        =[proj(UpperCAmelCase_) for proj in self.proj]

   return self.domain_map(*UpperCAmelCase_)



class        _SCREAMING_SNAKE_CASE						(     nn.Module   ):







 '''simple docstring'''

 def __init__(self    :       str	,			UpperCAmelCase_    :       Optional[Any])	->Optional[int]:



   '''simple docstring'''



   super().__init__()
   lowerCamelCase__:				Any        =function







 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			UpperCAmelCase_    :       Optional[Any]	,			*UpperCAmelCase_    :       Union[str, Any])	->Union[str, Any]:



   '''simple docstring'''



   return self.function(UpperCAmelCase_	,			*UpperCAmelCase_)



class        _SCREAMING_SNAKE_CASE						:







 '''simple docstring'''
 lowercase_		=      42
 lowercase_		=      42
 lowercase_		=      42

 def __init__(self    :       str	,			UpperCAmelCase_    :       int = 1)	->None:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =dim
   lowerCamelCase__:				int        ={k: dim * self.args_dim[k] for k in self.args_dim}

 def 							SCREAMING_SNAKE_CASE_ (self    :       int	,			UpperCAmelCase_    :       str)	->Optional[Any]:



   '''simple docstring'''



   if self.dim == 1:
     return self.distribution_class(*UpperCAmelCase_)
   else:
     return Independent(self.distribution_class(*UpperCAmelCase_)	,			1)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			UpperCAmelCase_    :       List[Any]	,			UpperCAmelCase_    :       Optional[torch.Tensor] = None	,			UpperCAmelCase_    :       Optional[torch.Tensor] = None	,			)	->Distribution:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =self._base_distribution(UpperCAmelCase_)
   if loc is None and scale is None:
     return distr
   else:
     return AffineTransformed(UpperCAmelCase_	,			loc=UpperCAmelCase_	,			scale=UpperCAmelCase_	,			event_dim=self.event_dim)

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->Tuple:



   '''simple docstring'''



   return () if self.dim == 1 else (self.dim,)

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any])	->int:



   '''simple docstring'''



   return len(self.event_shape)

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->float:



   '''simple docstring'''



   return 0.0

 def 							SCREAMING_SNAKE_CASE_ (self    :       str	,			UpperCAmelCase_    :       int)	->nn.Module:



   '''simple docstring'''



   return ParameterProjection(
       in_features=UpperCAmelCase_	,			args_dim=self.args_dim	,			domain_map=LambdaLayer(self.domain_map)	,			)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			*UpperCAmelCase_    :       torch.Tensor)	->Any:



   '''simple docstring'''



   raise NotImplementedError()







 @staticmethod
 def 							SCREAMING_SNAKE_CASE_ (UpperCAmelCase_    :       torch.Tensor)	->torch.Tensor:



   '''simple docstring'''



   return (x + torch.sqrt(torch.square(UpperCAmelCase_) + 4.0)) / 2.0



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''
 lowercase_		=      {"df": 1, "loc": 1, "scale": 1}
 lowercase_		=      StudentT

 @classmethod
 def 							SCREAMING_SNAKE_CASE_ (cls    :       Optional[int]	,			UpperCAmelCase_    :       torch.Tensor	,			UpperCAmelCase_    :       torch.Tensor	,			UpperCAmelCase_    :       torch.Tensor)	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				str        =cls.squareplus(UpperCAmelCase_).clamp_min(torch.finfo(scale.dtype).eps)
   lowerCamelCase__:				Any        =2.0 + cls.squareplus(UpperCAmelCase_)
   return df.squeeze(-1), loc.squeeze(-1), scale.squeeze(-1)



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''
 lowercase_		=      {"loc": 1, "scale": 1}
 lowercase_		=      Normal

 @classmethod
 def 							SCREAMING_SNAKE_CASE_ (cls    :       Optional[Any]	,			UpperCAmelCase_    :       torch.Tensor	,			UpperCAmelCase_    :       torch.Tensor)	->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:				List[Any]        =cls.squareplus(UpperCAmelCase_).clamp_min(torch.finfo(scale.dtype).eps)
   return loc.squeeze(-1), scale.squeeze(-1)



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''
 lowercase_		=      {"total_count": 1, "logits": 1}
 lowercase_		=      NegativeBinomial

 @classmethod
 def 							SCREAMING_SNAKE_CASE_ (cls    :       Optional[int]	,			UpperCAmelCase_    :       torch.Tensor	,			UpperCAmelCase_    :       torch.Tensor)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Tuple        =cls.squareplus(UpperCAmelCase_)
   return total_count.squeeze(-1), logits.squeeze(-1)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple	,			UpperCAmelCase_    :       Tuple)	->Distribution:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				Any        =distr_args
   if self.dim == 1:
     return self.distribution_class(total_count=UpperCAmelCase_	,			logits=UpperCAmelCase_)
   else:
     return Independent(self.distribution_class(total_count=UpperCAmelCase_	,			logits=UpperCAmelCase_)	,			1)







 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any]	,			UpperCAmelCase_    :       Optional[Any]	,			UpperCAmelCase_    :       Optional[torch.Tensor] = None	,			UpperCAmelCase_    :       Optional[torch.Tensor] = None)	->Distribution:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				Union[str, Any]        =distr_args

   if scale is not None:
     # See scaling property of Gamma.
     logits += scale.log()

   return self._base_distribution((total_count, logits))

