
"""simple docstring"""


import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
      from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm



def 						lowerCamelCase__      (				UpperCAmelCase_					)->				Optional[Any]:







       """simple docstring"""
       if is_torch_version("<"		,   "2.0.0"					) or not hasattr(UpperCAmelCase_		,   "_dynamo"					):
              return False
       return isinstance(UpperCAmelCase_		,   torch._dynamo.eval_frame.OptimizedModule					)



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_ = True					)->				int:







       """simple docstring"""
       UpperCamelCase       			=		(torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

       UpperCamelCase       			=		is_compiled_module(UpperCAmelCase_					)
       if is_compiled:
              UpperCamelCase       			=		model
              UpperCamelCase       			=		model._orig_mod

       if is_deepspeed_available():
              options += (DeepSpeedEngine,)

       while isinstance(UpperCAmelCase_		,   UpperCAmelCase_					):
              UpperCamelCase       			=		model.module

       if not keep_fpaa_wrapper:
              UpperCamelCase       			=		getattr(UpperCAmelCase_		,   "forward"					)
              UpperCamelCase       			=		model.__dict__.pop("_original_forward"		,   UpperCAmelCase_					)
              if original_forward is not None:
                     while hasattr(UpperCAmelCase_		,   "__wrapped__"					):
                            UpperCamelCase       			=		forward.__wrapped__
                            if forward == original_forward:
                                   break
                     UpperCamelCase       			=		forward
              if getattr(UpperCAmelCase_		,   "_converted_to_transformer_engine"		,   UpperCAmelCase_					):
                     convert_model(UpperCAmelCase_		,   to_transformer_engine=UpperCAmelCase_					)

       if is_compiled:
              UpperCamelCase       			=		model
              UpperCamelCase       			=		compiled_model

       return model



def 						lowerCamelCase__      (				)->				int:







       """simple docstring"""
       PartialState().wait_for_everyone()



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_					)->				Dict:







       """simple docstring"""
       if PartialState().distributed_type == DistributedType.TPU:
              xm.save(UpperCAmelCase_		,   UpperCAmelCase_					)
       elif PartialState().local_process_index == 0:
              torch.save(UpperCAmelCase_		,   UpperCAmelCase_					)



@contextmanager
def 						lowerCamelCase__      (				**UpperCAmelCase_					)->				Dict:







       """simple docstring"""
       for key, value in kwargs.items():
              UpperCamelCase       			=		str(UpperCAmelCase_					)

       yield

       for key in kwargs:
              if key.upper() in os.environ:
                     del os.environ[key.upper()]



def 						lowerCamelCase__      (				UpperCAmelCase_					)->				str:







       """simple docstring"""
       if not hasattr(UpperCAmelCase_		,   "__qualname__"					) and not hasattr(UpperCAmelCase_		,   "__name__"					):
              UpperCamelCase       			=		getattr(UpperCAmelCase_		,   "__class__"		,   UpperCAmelCase_					)
       if hasattr(UpperCAmelCase_		,   "__qualname__"					):
              return obj.__qualname__
       if hasattr(UpperCAmelCase_		,   "__name__"					):
              return obj.__name__
       return str(UpperCAmelCase_					)



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_					)->				List[str]:







       """simple docstring"""
       for key, value in source.items():
              if isinstance(UpperCAmelCase_		,   UpperCAmelCase_					):
                     UpperCamelCase       			=		destination.setdefault(UpperCAmelCase_		,   {}					)
                     merge_dicts(UpperCAmelCase_		,   UpperCAmelCase_					)
              else:
                     UpperCamelCase       			=		value

       return destination



def 						lowerCamelCase__      (				UpperCAmelCase_ = None					)->				bool:







       """simple docstring"""
       if port is None:
              UpperCamelCase       			=		2_95_00
       with socket.socket(socket.AF_INET		,   socket.SOCK_STREAM					) as s:
              return s.connect_ex(("localhost", port)					) == 0







"""simple docstring"""


import os
import zipfile

import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_=7					)->				Optional[Any]:







       """simple docstring"""
       UpperCamelCase       			=		None
       if token is not None:
              UpperCamelCase       			=		{"Accept": "application/vnd.github+json", "Authorization": F"Bearer {token}"}

       # The id of a workflow (not of a workflow run)
       UpperCamelCase       			=		"636036"

       UpperCamelCase       			=		F"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"
       # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
       url += F"?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"

       UpperCamelCase       			=		requests.get(UpperCAmelCase_		,   headers=UpperCAmelCase_					).json()

       return result["workflow_runs"]



def 						lowerCamelCase__      (				UpperCAmelCase_					)->				Any:







       """simple docstring"""
       UpperCamelCase       			=		get_daily_ci_runs(UpperCAmelCase_					)
       UpperCamelCase       			=		None
       for workflow_run in workflow_runs:
              if workflow_run["status"] == "completed":
                     UpperCamelCase       			=		workflow_run["id"]
                     break

       return workflow_run_id



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_					)->				int:







       """simple docstring"""
       UpperCamelCase       			=		get_last_daily_ci_runs(UpperCAmelCase_					)
       if workflow_run_id is not None:
              UpperCamelCase       			=		get_artifacts_links(worflow_run_id=UpperCAmelCase_		,   token=UpperCAmelCase_					)
              for artifact_name in artifact_names:
                     if artifact_name in artifacts_links:
                            UpperCamelCase       			=		artifacts_links[artifact_name]
                            download_artifact(
                                artifact_name=UpperCAmelCase_		,   artifact_url=UpperCAmelCase_		,   output_dir=UpperCAmelCase_		,   token=UpperCAmelCase_					)



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_					)->				Optional[int]:







       """simple docstring"""
       get_last_daily_ci_artifacts(UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_					)

       UpperCamelCase       			=		{}
       for artifact_name in artifact_names:
              UpperCamelCase       			=		os.path.join(UpperCAmelCase_		,   F"{artifact_name}.zip"					)
              if os.path.isfile(UpperCAmelCase_					):
                     UpperCamelCase       			=		{}
                     with zipfile.ZipFile(UpperCAmelCase_					) as z:
                            for filename in z.namelist():
                                   if not os.path.isdir(UpperCAmelCase_					):
                                          # read the file
                                          with z.open(UpperCAmelCase_					) as f:
                                                 UpperCamelCase       			=		f.read().decode("UTF-8"					)

       return results





