

import csv
import json
import logging
import os
import re
import subprocess
import tempfile
import unittest
import zipfile
from pathlib import Path
from typing import Optional
from unittest import mock

import torch

# We use TF to parse the logs
from accelerate import Accelerator
from accelerate.test_utils.testing import (
    MockingTestCase,
    TempDirTestCase,
    require_comet_ml,
    require_tensorboard,
    require_wandb,
    skip,
)
from accelerate.tracking import CometMLTracker, GeneralTracker
from accelerate.utils import ProjectConfiguration, is_comet_ml_available, is_tensorboard_available


if is_comet_ml_available():
  from comet_ml import OfflineExperiment

if is_tensorboard_available():
  import struct

  import tensorboard.compat.proto.event_pba as event_pba

UpperCAmelCase__	:       Union[str, Any]			      =      logging.getLogger(__name__)







@require_tensorboard
class     a__    (				unittest.TestCase    ):







  """simple docstring"""




  def 	_lowercase (     self      :	str						)   ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				"""test_project_with_config"""
        with tempfile.TemporaryDirectory() as dirpath:
              SCREAMING_SNAKE_CASE	: str					       =				Accelerator(log_with="""tensorboard"""			,			project_dir=UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				{"""num_iterations""": 1_2, """learning_rate""": 1e-2, """some_boolean""": False, """some_string""": """some_value"""}
              accelerator.init_trackers(UpperCAmelCase__			,			UpperCAmelCase__						)
              accelerator.end_training()
              for child in Path(f"{dirpath}/{project_name}"						).glob("""*/**"""						):
                    SCREAMING_SNAKE_CASE	: Optional[Any]					       =				list(filter(lambda UpperCAmelCase__						: x.is_file()			,			child.iterdir()						)						)[0]
              self.assertNotEqual(str(UpperCAmelCase__						)			,			""""""						)


  def 	_lowercase (     self      :	Any						)   ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				"""test_project_with_log"""
        with tempfile.TemporaryDirectory() as dirpath:
              SCREAMING_SNAKE_CASE	: List[Any]					       =				Accelerator(log_with="""tensorboard"""			,			project_dir=UpperCAmelCase__						)
              accelerator.init_trackers(UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				{"""total_loss""": 0.1, """iteration""": 1, """my_text""": """some_value"""}
              accelerator.log(UpperCAmelCase__			,			step=0						)
              accelerator.end_training()
              # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
              # Names are randomly generated each time
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				list(filter(lambda UpperCAmelCase__						: x.is_file()			,			Path(f"{dirpath}/{project_name}"						).iterdir()						)						)[0]
              self.assertNotEqual(str(UpperCAmelCase__						)			,			""""""						)


  def 	_lowercase (     self      :	Tuple						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Any					       =				"""test_project_with_log"""
        with tempfile.TemporaryDirectory() as dirpath:
              SCREAMING_SNAKE_CASE	: int					       =				Accelerator(log_with="""tensorboard"""			,			project_dir=UpperCAmelCase__						)
              accelerator.init_trackers(UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				{"""tensor""": torch.tensor(1						)}
              accelerator.log(UpperCAmelCase__			,			step=0						)
              accelerator.end_training()
              # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
              # Names are randomly generated each time
              SCREAMING_SNAKE_CASE	: Any					       =				list(filter(lambda UpperCAmelCase__						: x.is_file()			,			Path(f"{dirpath}/{project_name}"						).iterdir()						)						)[0]
              # Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
              with open(UpperCAmelCase__			,			"""rb"""						) as f:
                    SCREAMING_SNAKE_CASE	: Any					       =				f.read()
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				False
              while data:
                    SCREAMING_SNAKE_CASE	: List[Any]					       =				struct.unpack("""Q"""			,			data[:8]						)

                    SCREAMING_SNAKE_CASE	: List[str]					       =				data[1_2 : 1_2 + int(header[0]						)]  # 8+4
                    SCREAMING_SNAKE_CASE	: List[Any]					       =				data[1_2 + int(header[0]						) + 4 :]
                    SCREAMING_SNAKE_CASE	: Any					       =				event_pba.Event()

                    event.ParseFromString(UpperCAmelCase__						)
                    if event.HasField("""summary"""						):
                          for value in event.summary.value:
                                if value.simple_value == 1.0 and value.tag == "tensor":
                                      SCREAMING_SNAKE_CASE	: str					       =				True
              self.assertTrue(UpperCAmelCase__			,			"""Converted tensor was not found in the log file!"""						)


  def 	_lowercase (     self      :	Any						)   ->Any:
        """simple docstring"""







        with self.assertRaisesRegex(UpperCAmelCase__			,			"""Logging with `tensorboard` requires a `logging_dir`"""						):
              SCREAMING_SNAKE_CASE	: List[Any]					       =				Accelerator(log_with="""tensorboard"""						)
        with tempfile.TemporaryDirectory() as dirpath:
              SCREAMING_SNAKE_CASE	: List[str]					       =				Accelerator(log_with="""tensorboard"""			,			project_dir=UpperCAmelCase__						)




  def 	_lowercase (     self      :	int						)   ->Union[str, Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: List[str]					       =				ProjectConfiguration(total_limit=3_0						)
        with tempfile.TemporaryDirectory() as dirpath:
              SCREAMING_SNAKE_CASE	: List[str]					       =				Accelerator(log_with="""tensorboard"""			,			project_dir=UpperCAmelCase__			,			project_config=UpperCAmelCase__						)







@require_wandb
@mock.patch.dict(os.environ		,     {"""WANDB_MODE""": """offline"""}    )
class     a__    (				UpperCAmelCase		,     UpperCAmelCase    ):







  """simple docstring"""




  def 	_lowercase (     self      :	Union[str, Any]						)   ->List[str]:
        """simple docstring"""







        super().setUp()
        # wandb let's us override where logs are stored to via the WANDB_DIR env var
        self.add_mocks(mock.patch.dict(os.environ			,			{"""WANDB_DIR""": self.tmpdir}						)						)


  @staticmethod
  def 	_lowercase (     UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	bool = True						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: str					       =				Rf"{section} ([\S\s]*?)\n\n"
        if record:
              SCREAMING_SNAKE_CASE	: int					       =				Rf"Record: {pattern}"
        SCREAMING_SNAKE_CASE	: Dict					       =				re.findall(UpperCAmelCase__			,			UpperCAmelCase__						)[0]
        # A config
        if section == "config" or section == "history":
              SCREAMING_SNAKE_CASE	: List[Any]					       =				re.findall(R"""\"([a-zA-Z0-9_.,]+)"""			,			UpperCAmelCase__						)
              return {key: val for key, val in zip(cleaned_record[0::2]			,			cleaned_record[1::2]						)}
        # Everything else
        else:
              return dict(re.findall(R"""(\w+): \"([^\s]+)\""""			,			UpperCAmelCase__						)						)




  @skip
  def 	_lowercase (     self      :	Union[str, Any]						)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: str					       =				"""test_project_with_config"""
        SCREAMING_SNAKE_CASE	: List[Any]					       =				Accelerator(log_with="""wandb"""						)
        SCREAMING_SNAKE_CASE	: List[str]					       =				{"""num_iterations""": 1_2, """learning_rate""": 1e-2, """some_boolean""": False, """some_string""": """some_value"""}
        SCREAMING_SNAKE_CASE	: Tuple					       =				{"""wandb""": {"""tags""": ["""my_tag"""]}}
        accelerator.init_trackers(UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: List[str]					       =				{"""total_loss""": 0.1, """iteration""": 1, """my_text""": """some_value"""}
        accelerator.log(UpperCAmelCase__			,			step=0						)
        accelerator.end_training()
        # The latest offline log is stored at wandb/latest-run/*.wandb
        for child in Path(f"{self.tmpdir}/wandb/latest-run"						).glob("""*"""						):
              if child.is_file() and child.suffix == ".wandb":
                    SCREAMING_SNAKE_CASE	: str					       =				subprocess.check_output(
                        ["""wandb""", """sync""", """--view""", """--verbose""", str(UpperCAmelCase__						)]			,			env=os.environ.copy()						).decode("""utf8"""			,			"""ignore"""						)
                    break

        # Check HPS through careful parsing and cleaning
        SCREAMING_SNAKE_CASE	: List[Any]					       =				self.parse_log(UpperCAmelCase__			,			"""config"""						)
        self.assertEqual(logged_items["""num_iterations"""]			,			"""12"""						)
        self.assertEqual(logged_items["""learning_rate"""]			,			"""0.01"""						)
        self.assertEqual(logged_items["""some_boolean"""]			,			"""false"""						)
        self.assertEqual(logged_items["""some_string"""]			,			"""some_value"""						)
        self.assertEqual(logged_items["""some_string"""]			,			"""some_value"""						)

        # Run tags
        SCREAMING_SNAKE_CASE	: int					       =				self.parse_log(UpperCAmelCase__			,			"""run"""			,			UpperCAmelCase__						)
        self.assertEqual(logged_items["""tags"""]			,			"""my_tag"""						)

        # Actual logging
        SCREAMING_SNAKE_CASE	: int					       =				self.parse_log(UpperCAmelCase__			,			"""history"""						)
        self.assertEqual(logged_items["""total_loss"""]			,			"""0.1"""						)
        self.assertEqual(logged_items["""iteration"""]			,			"""1"""						)
        self.assertEqual(logged_items["""my_text"""]			,			"""some_value"""						)
        self.assertEqual(logged_items["""_step"""]			,			"""0"""						)






def    __lowercase (       self  ,      _A  ,      _A     )       ->  List[Any]:
      SCREAMING_SNAKE_CASE	: Any					       =				run_name
      SCREAMING_SNAKE_CASE	: Optional[int]					       =				OfflineExperiment(project_name=_A  ,      offline_directory=_A     )
      logger.info(F"Initialized offline CometML project {self.run_name}"     )
      logger.info("""Make sure to log any initial configurations with `self.store_init_configuration` before training!"""     )







@require_comet_ml
@mock.patch.object(UpperCAmelCase		,     """__init__"""		,     UpperCAmelCase    )
class     a__    (				unittest.TestCase    ):







  """simple docstring"""




  @staticmethod
  def 	_lowercase (     UpperCAmelCase__      :	Dict			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	bool = False						)   ->List[str]:
        """simple docstring"""







        for log in log_list:
              SCREAMING_SNAKE_CASE	: List[Any]					       =				json.loads(UpperCAmelCase__						)["""payload"""]
              if is_param and "param" in j.keys():
                    if j["param"]["paramName"] == key:
                          return j["param"]["paramValue"]
              if "log_other" in j.keys():
                    if j["log_other"]["key"] == key:
                          return j["log_other"]["val"]
              if "metric" in j.keys():
                    if j["metric"]["metricName"] == key:
                          return j["metric"]["metricValue"]


  def 	_lowercase (     self      :	List[Any]						)   ->int:
        """simple docstring"""







        with tempfile.TemporaryDirectory() as d:
              SCREAMING_SNAKE_CASE	: Dict					       =				CometMLTracker("""test_project_with_config"""			,			UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				Accelerator(log_with=UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: Tuple					       =				{"""num_iterations""": 1_2, """learning_rate""": 1e-2, """some_boolean""": False, """some_string""": """some_value"""}
              accelerator.init_trackers(UpperCAmelCase__			,			UpperCAmelCase__						)
              accelerator.end_training()
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				os.listdir(UpperCAmelCase__						)[0]  # Comet is nice, it's just a zip file here
              # We parse the raw logs
              SCREAMING_SNAKE_CASE	: Dict					       =				os.path.join(UpperCAmelCase__			,			UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: List[str]					       =				zipfile.ZipFile(UpperCAmelCase__			,			"""r"""						)
              SCREAMING_SNAKE_CASE	: List[str]					       =				archive.open("""messages.json"""						).read().decode("""utf-8"""						)
        SCREAMING_SNAKE_CASE	: List[str]					       =				log.split("""\n"""						)[:-1]
        self.assertEqual(self.get_value_from_key(UpperCAmelCase__			,			"""num_iterations"""			,			UpperCAmelCase__						)			,			1_2						)
        self.assertEqual(self.get_value_from_key(UpperCAmelCase__			,			"""learning_rate"""			,			UpperCAmelCase__						)			,			0.01						)
        self.assertEqual(self.get_value_from_key(UpperCAmelCase__			,			"""some_boolean"""			,			UpperCAmelCase__						)			,			UpperCAmelCase__						)
        self.assertEqual(self.get_value_from_key(UpperCAmelCase__			,			"""some_string"""			,			UpperCAmelCase__						)			,			"""some_value"""						)




  def 	_lowercase (     self      :	Optional[Any]						)   ->Optional[int]:
        """simple docstring"""







        with tempfile.TemporaryDirectory() as d:
              SCREAMING_SNAKE_CASE	: Tuple					       =				CometMLTracker("""test_project_with_config"""			,			UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: int					       =				Accelerator(log_with=UpperCAmelCase__						)
              accelerator.init_trackers(UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: Dict					       =				{"""total_loss""": 0.1, """iteration""": 1, """my_text""": """some_value"""}
              accelerator.log(UpperCAmelCase__			,			step=0						)
              accelerator.end_training()
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				os.listdir(UpperCAmelCase__						)[0]  # Comet is nice, it's just a zip file here
              # We parse the raw logs
              SCREAMING_SNAKE_CASE	: str					       =				os.path.join(UpperCAmelCase__			,			UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				zipfile.ZipFile(UpperCAmelCase__			,			"""r"""						)
              SCREAMING_SNAKE_CASE	: Dict					       =				archive.open("""messages.json"""						).read().decode("""utf-8"""						)
        SCREAMING_SNAKE_CASE	: int					       =				log.split("""\n"""						)[:-1]
        self.assertEqual(self.get_value_from_key(UpperCAmelCase__			,			"""curr_step"""			,			UpperCAmelCase__						)			,			0						)
        self.assertEqual(self.get_value_from_key(UpperCAmelCase__			,			"""total_loss"""						)			,			0.1						)
        self.assertEqual(self.get_value_from_key(UpperCAmelCase__			,			"""iteration"""						)			,			1						)
        self.assertEqual(self.get_value_from_key(UpperCAmelCase__			,			"""my_text"""						)			,			"""some_value"""						)







class     a__    (				UpperCAmelCase    ):







  """simple docstring"""




  UpperCAmelCase__ :	str         =[
      """total_loss""",
      """iteration""",
      """my_text""",
      """learning_rate""",
      """num_iterations""",
      """some_boolean""",
      """some_string""",
  ]

  UpperCAmelCase__ :	Union[str, Any]         ="""my_custom_tracker"""
  UpperCAmelCase__ :	List[Any]         =False


  def __init__(     self      :	Optional[Any]			,			UpperCAmelCase__      :	str						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				open(f"{dir}/log.csv"			,			"""w+"""						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				csv.DictWriter(self.f			,			fieldnames=self._col_names						)
        self.writer.writeheader()


  @property
  def 	_lowercase (     self      :	List[str]						)   ->Optional[int]:
        """simple docstring"""







        return self.writer


  def 	_lowercase (     self      :	Dict			,			UpperCAmelCase__      :	dict						)   ->List[str]:
        """simple docstring"""







        logger.info("""Call init"""						)
        self.writer.writerow(UpperCAmelCase__						)


  def 	_lowercase (     self      :	str			,			UpperCAmelCase__      :	dict			,			UpperCAmelCase__      :	Optional[int]						)   ->Union[str, Any]:
        """simple docstring"""







        logger.info("""Call log"""						)
        self.writer.writerow(UpperCAmelCase__						)




  def 	_lowercase (     self      :	Any						)   ->int:
        """simple docstring"""







        self.f.close()







class     a__    (				unittest.TestCase    ):







  """simple docstring"""




  def 	_lowercase (     self      :	List[Any]						)   ->int:
        """simple docstring"""







        with tempfile.TemporaryDirectory() as d:
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				MyCustomTracker(UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: Any					       =				Accelerator(log_with=UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: str					       =				{"""num_iterations""": 1_2, """learning_rate""": 1e-2, """some_boolean""": False, """some_string""": """some_value"""}
              accelerator.init_trackers("""Some name"""			,			UpperCAmelCase__						)
              accelerator.end_training()
              with open(f"{d}/log.csv"			,			"""r"""						) as f:
                    SCREAMING_SNAKE_CASE	: List[str]					       =				csv.DictReader(UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: Any					       =				next(UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: Optional[Any]					       =				{
                        """total_loss""": """""",
                        """iteration""": """""",
                        """my_text""": """""",
                        """learning_rate""": """0.01""",
                        """num_iterations""": """12""",
                        """some_boolean""": """False""",
                        """some_string""": """some_value""",
                    }
                    self.assertDictEqual(UpperCAmelCase__			,			UpperCAmelCase__						)




  def 	_lowercase (     self      :	str						)   ->Optional[int]:
        """simple docstring"""







        with tempfile.TemporaryDirectory() as d:
              SCREAMING_SNAKE_CASE	: List[Any]					       =				MyCustomTracker(UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: int					       =				Accelerator(log_with=UpperCAmelCase__						)
              accelerator.init_trackers("""Some name"""						)
              SCREAMING_SNAKE_CASE	: Tuple					       =				{"""total_loss""": 0.1, """iteration""": 1, """my_text""": """some_value"""}
              accelerator.log(UpperCAmelCase__			,			step=0						)
              accelerator.end_training()
              with open(f"{d}/log.csv"			,			"""r"""						) as f:
                    SCREAMING_SNAKE_CASE	: Optional[int]					       =				csv.DictReader(UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: Tuple					       =				next(UpperCAmelCase__						)
                    SCREAMING_SNAKE_CASE	: int					       =				{
                        """total_loss""": """0.1""",
                        """iteration""": """1""",
                        """my_text""": """some_value""",
                        """learning_rate""": """""",
                        """num_iterations""": """""",
                        """some_boolean""": """""",
                        """some_string""": """""",
                    }
                    self.assertDictEqual(UpperCAmelCase__			,			UpperCAmelCase__						)







import inspect
import os
import unittest

import torch

import accelerate
from accelerate import debug_launcher
from accelerate.test_utils import (
    execute_subprocess_async,
    require_cpu,
    require_multi_gpu,
    require_single_gpu,
    test_sync,
)
from accelerate.utils import patch_environment







class     a__    (				unittest.TestCase    ):







  """simple docstring"""




  def 	_lowercase (     self      :	Optional[int]						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				inspect.getfile(accelerate.test_utils						)
        SCREAMING_SNAKE_CASE	: int					       =				os.path.sep.join(mod_file.split(os.path.sep						)[:-1] + ["""scripts""", """test_sync.py"""]						)


  @require_cpu
  def 	_lowercase (     self      :	Optional[int]						)   ->str:
        """simple docstring"""







        debug_launcher(test_sync.main			,			num_processes=1						)


  @require_cpu
  def 	_lowercase (     self      :	Optional[int]						)   ->int:
        """simple docstring"""







        debug_launcher(test_sync.main						)


  @require_single_gpu
  def 	_lowercase (     self      :	str						)   ->Any:
        """simple docstring"""







        test_sync.main()




  @require_multi_gpu
  def 	_lowercase (     self      :	Union[str, Any]						)   ->List[Any]:
        """simple docstring"""







        print(f"Found {torch.cuda.device_count()} devices."						)
        SCREAMING_SNAKE_CASE	: List[str]					       =				["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", self.test_file_path]
        with patch_environment(omp_num_threads=1						):
              execute_subprocess_async(UpperCAmelCase__			,			env=os.environ.copy()						)




