
'''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        a__  (							unittest.TestCase  ):


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      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=_UpperCamelCase      ,    )
      assert hasattr(self      ,    "env"  )


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				List[str]      					=       {
          "enabled": True,
          "processes_per_host": 8,
      }
      _lowercase      :				Tuple      					=       {
          "enabled": True,
          "parameters": {
              "microbatches": 4,
              "placement_strategy": "spread",
              "pipeline": "interleaved",
              "optimize": "speed",
              "partitions": 4,
              "ddp": True,
          },
      }

      _lowercase      :				Union[str, Any]      					=       {"smdistributed": {"modelparallel": smp_options}, "mpi": mpi_options}

      _lowercase      :				Optional[Any]      					=       "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=_UpperCamelCase      ,    instance_type=self.instance_type      ,    debugger_hook_config=_UpperCamelCase      ,    hyperparameters={
              **self.env.hyperparameters,
              "model_name_or_path": self.model_name_or_path,
              "max_steps": 500,
          }      ,    metric_definitions=self.env.metric_definitions      ,    distribution=_UpperCamelCase      ,    py_version="py36"      ,    )


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      TrainingJobAnalytics(_UpperCamelCase  ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv'''  )






   @parameterized.expand([(1,)]  )
   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Union[str, Any]      					=       self.create_estimator(_UpperCamelCase  )

      # run training
      estimator.fit()

      # result dataframe
      _lowercase      :				str      					=       TrainingJobAnalytics(estimator.latest_training_job.name  ).dataframe()

      # extract kpis
      _lowercase      :				Optional[Any]      					=       list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]  )
      _lowercase      :				List[Any]      					=       list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]  )
      # get train time from SageMaker job, this includes starting, preprocessing, stopping
      _lowercase      :				Any      					=       (
          Session().describe_training_job(estimator.latest_training_job.name  ).get("TrainingTimeInSeconds"      ,    999999  )
      )

      # 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}      ,    _UpperCamelCase  )









'''simple docstring'''
from . import __version__

# Backward compatibility imports, to make sure all those objects can be found in file_utils
from .utils import (
    CLOUDFRONT_DISTRIB_PREFIX,
    CONFIG_NAME,
    DISABLE_TELEMETRY,
    DUMMY_INPUTS,
    DUMMY_MASK,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    FEATURE_EXTRACTOR_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    MODEL_CARD_NAME,
    MULTIPLE_CHOICE_DUMMY_INPUTS,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    SENTENCEPIECE_UNDERLINE,
    SPIECE_UNDERLINE,
    TF2_WEIGHTS_NAME,
    TF_WEIGHTS_NAME,
    TORCH_FX_REQUIRED_VERSION,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
    ContextManagers,
    DummyObject,
    EntryNotFoundError,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    TensorType,
    _LazyModule,
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    cached_property,
    copy_func,
    default_cache_path,
    define_sagemaker_information,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    get_torch_version,
    has_file,
    http_user_agent,
    is_apex_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_datasets_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_librosa_available,
    is_offline_mode,
    is_onnx_available,
    is_pandas_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_tensor,
    is_tensorflow_probability_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    replace_return_docstrings,
    requires_backends,
    to_numpy,
    to_py_obj,
    torch_only_method,
)






