






'''simple docstring'''







import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized, parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
							from sagemaker import Session, TrainingJobAnalytics
							from sagemaker.huggingface import HuggingFace




@pytest.mark.skipif(
    literal_eval(os.getenv('TEST_SAGEMAKER' ,'False'      )      ) is not True ,reason='Skipping test because should only be run when releasing minor transformers version' ,)
@pytest.mark.usefixtures('sm_env'      )
@parameterized_class(
    [
        {
            'framework': 'pytorch',
            'script': 'run_glue_model_parallelism.py',
            'model_name_or_path': 'roberta-large',
            'instance_type': 'ml.p3dn.24xlarge',
            'results': {'train_runtime': 1600, 'eval_accuracy': 0.3, 'eval_loss': 1.2},
        },
        {
            'framework': 'pytorch',
            'script': 'run_glue.py',
            'model_name_or_path': 'roberta-large',
            'instance_type': 'ml.p3dn.24xlarge',
            'results': {'train_runtime': 1600, 'eval_accuracy': 0.3, 'eval_loss': 1.2},
        },
    ]      )
class 		UpperCamelCase__     (unittest.TestCase      ):




		'''simple docstring'''





		def       UpperCamelCase_       (   self							):
								if self.framework == "pytorch":
														subprocess.run(
														    F'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() ,encoding="""utf-8""" ,check=_lowerCAmelCase ,)
								assert hasattr(self ,"""env"""							)






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								# configuration for running training on smdistributed Model Parallel
								lowerCamelCase__								=	{
								    """enabled""": True,
								    """processes_per_host""": 8,
								}
								lowerCamelCase__								=	{
								    """enabled""": True,
								    """parameters""": {
								        """microbatches""": 4,
								        """placement_strategy""": """spread""",
								        """pipeline""": """interleaved""",
								        """optimize""": """speed""",
								        """partitions""": 4,
								        """ddp""": True,
								    },
								}

								lowerCamelCase__								=	{"""smdistributed""": {"""modelparallel""": smp_options}, """mpi""": mpi_options}

								lowerCamelCase__								=	"""trainer""" if self.script == """run_glue.py""" else """smtrainer"""
								# creates estimator
								return HuggingFace(
								    entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' ,instance_count=_lowerCAmelCase ,instance_type=self.instance_type ,debugger_hook_config=_lowerCAmelCase ,hyperparameters={
								        **self.env.hyperparameters,
								        """model_name_or_path""": self.model_name_or_path,
								        """max_steps""": 5_00,
								    } ,metric_definitions=self.env.metric_definitions ,distribution=_lowerCAmelCase ,py_version="""py36""" ,)






		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								TrainingJobAnalytics(_lowerCAmelCase							).export_csv(F'''{self.env.test_path}/{job_name}_metrics.csv'''							)






		@parameterized.expand([(1,)]							)
		def       UpperCamelCase_       (   self ,_lowerCAmelCase							):
								# create estimator
								lowerCamelCase__								=	self.create_estimator(_lowerCAmelCase							)

								# run training
								estimator.fit()

								# result dataframe
								lowerCamelCase__								=	TrainingJobAnalytics(estimator.latest_training_job.name							).dataframe()

								# extract kpis
								lowerCamelCase__								=	list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""]							)
								lowerCamelCase__								=	list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""]							)
								# get train time from SageMaker job, this includes starting, preprocessing, stopping
								lowerCamelCase__								=	(
								    Session().describe_training_job(estimator.latest_training_job.name							).get("""TrainingTimeInSeconds""" ,99_99_99							)
								)

								# assert kpis
								assert train_runtime <= self.results["train_runtime"]
								assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy							)
								assert all(t <= self.results["""eval_loss"""] for t in eval_loss							)

								# dump tests result into json file to share in PR
								with open(F'''{estimator.latest_training_job.name}.json''' ,"""w"""							) as outfile:
														json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss} ,_lowerCAmelCase							)







'''simple docstring'''





import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase_		:     Optional[Any]          =		logging.get_logger(__name__)

UpperCamelCase_		:     Any          =		{
    '''microsoft/unispeech-sat-base-100h-libri-ft''': (
        '''https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json'''
    ),
    # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
}

class   _a							(		__lowerCAmelCase				):
     SCREAMING_SNAKE_CASE_				:       str       							=		"""unispeech-sat"""






     def __init__(					self   ,_SCREAMING_SNAKE_CASE=32   ,_SCREAMING_SNAKE_CASE=768   ,_SCREAMING_SNAKE_CASE=12   ,_SCREAMING_SNAKE_CASE=12   ,_SCREAMING_SNAKE_CASE=3_072   ,_SCREAMING_SNAKE_CASE="gelu"   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.0_2   ,_SCREAMING_SNAKE_CASE=1e-5   ,_SCREAMING_SNAKE_CASE="group"   ,_SCREAMING_SNAKE_CASE="gelu"   ,_SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 512, 512, 512)   ,_SCREAMING_SNAKE_CASE=(5, 2, 2, 2, 2, 2, 2)   ,_SCREAMING_SNAKE_CASE=(10, 3, 3, 3, 3, 2, 2)   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=128   ,_SCREAMING_SNAKE_CASE=16   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=True   ,_SCREAMING_SNAKE_CASE=0.0_5   ,_SCREAMING_SNAKE_CASE=10   ,_SCREAMING_SNAKE_CASE=2   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=10   ,_SCREAMING_SNAKE_CASE=0   ,_SCREAMING_SNAKE_CASE=320   ,_SCREAMING_SNAKE_CASE=2   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=100   ,_SCREAMING_SNAKE_CASE=256   ,_SCREAMING_SNAKE_CASE=256   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE="mean"   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=256   ,_SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 1_500)   ,_SCREAMING_SNAKE_CASE=(5, 3, 3, 1, 1)   ,_SCREAMING_SNAKE_CASE=(1, 2, 3, 1, 1)   ,_SCREAMING_SNAKE_CASE=512   ,_SCREAMING_SNAKE_CASE=0   ,_SCREAMING_SNAKE_CASE=1   ,_SCREAMING_SNAKE_CASE=2   ,_SCREAMING_SNAKE_CASE=504   ,**_SCREAMING_SNAKE_CASE   ,)				->     Any:
          super().__init__(**_SCREAMING_SNAKE_CASE   ,pad_token_id=_SCREAMING_SNAKE_CASE   ,bos_token_id=_SCREAMING_SNAKE_CASE   ,eos_token_id=_SCREAMING_SNAKE_CASE       )
          _snake_case				= hidden_size
          _snake_case				= feat_extract_norm
          _snake_case				= feat_extract_activation
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= conv_bias
          _snake_case				= num_conv_pos_embeddings
          _snake_case				= num_conv_pos_embedding_groups
          _snake_case				= len(self.conv_dim       )
          _snake_case				= num_hidden_layers
          _snake_case				= intermediate_size
          _snake_case				= hidden_act
          _snake_case				= num_attention_heads
          _snake_case				= hidden_dropout
          _snake_case				= attention_dropout
          _snake_case				= activation_dropout
          _snake_case				= feat_proj_dropout
          _snake_case				= final_dropout
          _snake_case				= layerdrop
          _snake_case				= layer_norm_eps
          _snake_case				= initializer_range
          _snake_case				= vocab_size
          _snake_case				= num_clusters
          _snake_case				= do_stable_layer_norm
          _snake_case				= use_weighted_layer_sum

          if (
              (len(self.conv_stride       ) != self.num_feat_extract_layers)
              or (len(self.conv_kernel       ) != self.num_feat_extract_layers)
              or (len(self.conv_dim       ) != self.num_feat_extract_layers)
          ):
               raise ValueError(
                   "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
                   " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
                   f""" {len(self.conv_dim       )}`, `len(config.conv_stride) = {len(self.conv_stride       )}`,"""
                   f""" `len(config.conv_kernel) = {len(self.conv_kernel       )}`."""       )

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          _snake_case				= apply_spec_augment
          _snake_case				= mask_time_prob
          _snake_case				= mask_time_length
          _snake_case				= mask_time_min_masks
          _snake_case				= mask_feature_prob
          _snake_case				= mask_feature_length
          _snake_case				= mask_feature_min_masks

          # parameters for pretraining with codevector quantized representations
          _snake_case				= num_codevectors_per_group
          _snake_case				= num_codevector_groups
          _snake_case				= contrastive_logits_temperature
          _snake_case				= feat_quantizer_dropout
          _snake_case				= num_negatives
          _snake_case				= codevector_dim
          _snake_case				= proj_codevector_dim
          _snake_case				= diversity_loss_weight

          # ctc loss
          _snake_case				= ctc_loss_reduction
          _snake_case				= ctc_zero_infinity

          # SequenceClassification-specific parameter. Feel free to ignore for other classes.
          _snake_case				= classifier_proj_size

          # XVector-specific parameters. Feel free to ignore for other classes.
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= xvector_output_dim






     @property
     def 							_lowercase      (					self       )				->     List[str]:
          return functools.reduce(operator.mul   ,self.conv_stride   ,1       )


