

'''simple docstring'''







import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
def  UpperCAmelCase__      ( UpperCAmelCase__,    UpperCAmelCase__=False			)     ->     Tuple:
       try:
              A_		   = os.environ[key]
       except KeyError:
              # KEY isn't set, default to `default`.
              A_		   = default
       else:
              # KEY is set, convert it to True or False.
              try:
                     A_		   = strtobool(UpperCAmelCase__			)
              except ValueError:
                     # More values are supported, but let's keep the message simple.
                     raise ValueError(F'''If set, {key} must be yes or no.'''			)
       return _value


__lowerCamelCase						    =      parse_flag_from_env('''RUN_SLOW''', default=False)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Optional[Any]:
       return unittest.skip("""Test was skipped"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Any:
       return unittest.skipUnless(_run_slow_tests,    """test is slow"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     int:
       return unittest.skipUnless(not torch.cuda.is_available(),    """test requires only a CPU"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Dict:
       return unittest.skipUnless(torch.cuda.is_available(),    """test requires a GPU"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     str:
       return unittest.skipUnless(is_xpu_available(),    """test requires a XPU"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     List[str]:
       return unittest.skipUnless(is_mps_available(),    """test requires a `mps` backend support in `torch`"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Dict:
       return unittest.skipUnless(
           is_transformers_available() and is_datasets_available(),    """test requires the Hugging Face suite"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     List[Any]:
       return unittest.skipUnless(is_bnb_available(),    """test requires the bitsandbytes library"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     List[Any]:
       return unittest.skipUnless(is_tpu_available(),    """test requires TPU"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     int:
       return unittest.skipUnless(torch.cuda.device_count() == 1,    """test requires a GPU"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Union[str, Any]:
       return unittest.skipUnless(torch.xpu.device_count() == 1,    """test requires a XPU"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Dict:
       return unittest.skipUnless(torch.cuda.device_count() > 1,    """test requires multiple GPUs"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Dict:
       return unittest.skipUnless(torch.xpu.device_count() > 1,    """test requires multiple XPUs"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Any:
       return unittest.skipUnless(is_safetensors_available(),    """test requires safetensors"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     List[str]:
       return unittest.skipUnless(is_deepspeed_available(),    """test requires DeepSpeed"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     str:
       return unittest.skipUnless(is_torch_version(""">=""",    """1.12.0"""			),    """test requires torch version >= 1.12.0"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__=None,    UpperCAmelCase__=None			)     ->     Tuple:
       if test_case is None:
              return partial(UpperCAmelCase__,    version=UpperCAmelCase__			)
       return unittest.skipUnless(is_torch_version(""">=""",    UpperCAmelCase__			),    F'''test requires torch version >= {version}'''			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     List[Any]:
       return unittest.skipUnless(is_tensorboard_available(),    """test requires Tensorboard"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     List[str]:
       return unittest.skipUnless(is_wandb_available(),    """test requires wandb"""			)(UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     int:
       return unittest.skipUnless(is_comet_ml_available(),    """test requires comet_ml"""			)(UpperCAmelCase__			)


__lowerCamelCase						    =      (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     int:
       return unittest.skipUnless(
           _atleast_one_tracker_available,    """test requires at least one tracker to be available and for `comet_ml` to not be installed""",    )(UpperCAmelCase__			)


class    A__ ( unittest.TestCase     ):
    lowercase		   =						True



    @classmethod
    def    snake_case_     (   cls    )  -> Union[str, Any]:





           '''simple docstring'''
           A_		   = tempfile.mkdtemp()



    @classmethod
    def    snake_case_     (   cls    )  -> Any:





           '''simple docstring'''
           if os.path.exists(cls.tmpdir    ):
                  shutil.rmtree(cls.tmpdir    )







    def    snake_case_     (   self    )  -> List[str]:





           '''simple docstring'''
           if self.clear_on_setup:
                  for path in Path(self.tmpdir    ).glob("""**/*"""    ):
                         if path.is_file():
                                path.unlink()
                         elif path.is_dir():
                                shutil.rmtree(UpperCamelCase__    )


class    A__ ( unittest.TestCase     ):



    def    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           super().tearDown()
           # Reset the state of the AcceleratorState singleton.
           AcceleratorState._reset_state()
           PartialState._reset_state()


class    A__ ( unittest.TestCase     ):



    def    snake_case_     (   self						,			UpperCamelCase__    )  -> Optional[int]:





           '''simple docstring'''
           A_		   = mocks if isinstance(UpperCamelCase__						,			(tuple, list)    ) else [mocks]
           for m in self.mocks:
                  m.start()
                  self.addCleanup(m.stop    )

def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Optional[Any]:
       A_		   = AcceleratorState()
       A_		   = tensor[None].clone().to(state.device			)
       A_		   = gather(UpperCAmelCase__			).cpu()
       A_		   = tensor[0].cpu()
       for i in range(tensors.shape[0]			):
              if not torch.equal(tensors[i],    UpperCAmelCase__			):
                     return False
       return True


class    A__ :



    def __init__(   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )  -> Dict:





           '''simple docstring'''
           A_		   = returncode
           A_		   = stdout
           A_		   = stderr

async def  UpperCAmelCase__      ( UpperCAmelCase__,    UpperCAmelCase__			)     ->     Optional[int]:
       while True:
              A_		   = await stream.readline()
              if line:
                     callback(UpperCAmelCase__			)
              else:
                     break
async def  UpperCAmelCase__      ( UpperCAmelCase__,    UpperCAmelCase__=None,    UpperCAmelCase__=None,    UpperCAmelCase__=None,    UpperCAmelCase__=False,    UpperCAmelCase__=False			)     ->     _RunOutput:
       if echo:
              print("""\nRunning: """,    """ """.join(UpperCAmelCase__			)			)

       A_		   = await asyncio.create_subprocess_exec(
           cmd[0],    *cmd[1:],    stdin=UpperCAmelCase__,    stdout=asyncio.subprocess.PIPE,    stderr=asyncio.subprocess.PIPE,    env=UpperCAmelCase__,    )

       # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
       # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
       #
       # If it starts hanging, will need to switch to the following code. The problem is that no data
       # will be seen until it's done and if it hangs for example there will be no debug info.
       # out, err = await p.communicate()
       # return _RunOutput(p.returncode, out, err)

       A_		   = []
       A_		   = []

       def tee(UpperCAmelCase__,    UpperCAmelCase__,    UpperCAmelCase__,    UpperCAmelCase__=""			):
              A_		   = line.decode("""utf-8"""			).rstrip()
              sink.append(UpperCAmelCase__			)
              if not quiet:
                     print(UpperCAmelCase__,    UpperCAmelCase__,    file=UpperCAmelCase__			)

    # XXX: the timeout doesn't seem to make any difference here
       await asyncio.wait(
           [
               asyncio.create_task(_read_stream(p.stdout,    lambda UpperCAmelCase__			: tee(UpperCAmelCase__,    UpperCAmelCase__,    sys.stdout,    label="""stdout:"""			)			)			),
               asyncio.create_task(_read_stream(p.stderr,    lambda UpperCAmelCase__			: tee(UpperCAmelCase__,    UpperCAmelCase__,    sys.stderr,    label="""stderr:"""			)			)			),
           ],    timeout=UpperCAmelCase__,    )
       return _RunOutput(await p.wait(),    UpperCAmelCase__,    UpperCAmelCase__			)
def  UpperCAmelCase__      ( UpperCAmelCase__,    UpperCAmelCase__=None,    UpperCAmelCase__=None,    UpperCAmelCase__=1_80,    UpperCAmelCase__=False,    UpperCAmelCase__=True			)     ->     _RunOutput:
       A_		   = asyncio.get_event_loop()
       A_		   = loop.run_until_complete(
           _stream_subprocess(UpperCAmelCase__,    env=UpperCAmelCase__,    stdin=UpperCAmelCase__,    timeout=UpperCAmelCase__,    quiet=UpperCAmelCase__,    echo=UpperCAmelCase__			)			)

       A_		   = """ """.join(UpperCAmelCase__			)
       if result.returncode > 0:
              A_		   = """\n""".join(result.stderr			)
              raise RuntimeError(
                  F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
                  F'''The combined stderr from workers follows:\n{stderr}'''			)

       return result


class    A__ ( _snake_case     ):
    pass

def  UpperCAmelCase__      ( UpperCAmelCase__,    UpperCAmelCase__=False			)     ->     Optional[Any]:
       try:
              A_		   = subprocess.check_output(UpperCAmelCase__,    stderr=subprocess.STDOUT			)
              if return_stdout:
                     if hasattr(UpperCAmelCase__,    """decode"""			):
                            A_		   = output.decode("""utf-8"""			)
                     return output
       except subprocess.CalledProcessError as e:
              raise SubprocessCallException(
                  F'''Command `{" ".join(UpperCAmelCase__			)}` failed with the following error:\n\n{e.output.decode()}'''			) from e



'''simple docstring'''







from __future__ import annotations

import numpy as np
from numpy import floataa
from numpy.typing import NDArray
def  UpperCAmelCase__      ( UpperCAmelCase__,    UpperCAmelCase__,    UpperCAmelCase__,    UpperCAmelCase__,    )     ->     list[float]:
       A_   ,     A_		   = coefficient_matrix.shape
       A_   ,     A_		   = constant_matrix.shape

       if rowsa != colsa:
              A_		   = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}'''
              raise ValueError(UpperCAmelCase__			)

       if colsa != 1:
              A_		   = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}'''
              raise ValueError(UpperCAmelCase__			)

       if rowsa != rowsa:
              A_		   = (
                  """Coefficient and constant matrices dimensions must be nxn and nx1 but """
                  F'''received {rowsa}x{colsa} and {rowsa}x{colsa}'''
              )
              raise ValueError(UpperCAmelCase__			)

       if len(UpperCAmelCase__			) != rowsa:
              A_		   = (
                  """Number of initial values must be equal to number of rows in coefficient """
                  F'''matrix but received {len(UpperCAmelCase__			)} and {rowsa}'''
              )
              raise ValueError(UpperCAmelCase__			)

       if iterations <= 0:
              raise ValueError("""Iterations must be at least 1"""			)

       A_		   = np.concatenate(
           (coefficient_matrix, constant_matrix),    axis=1			)

       A_   ,     A_		   = table.shape

       strictly_diagonally_dominant(UpperCAmelCase__			)

       # Iterates the whole matrix for given number of times
       for _ in range(UpperCAmelCase__			):
              A_		   = []
              for row in range(UpperCAmelCase__			):
                     A_		   = 0
                     for col in range(UpperCAmelCase__			):
                            if col == row:
                                   A_		   = table[row][col]
                            elif col == cols - 1:
                                   A_		   = table[row][col]
                            else:
                                   temp += (-1) * table[row][col] * init_val[col]
                     A_		   = (temp + val) / denom
                     new_val.append(UpperCAmelCase__			)
              A_		   = new_val

       return [float(UpperCAmelCase__			) for i in new_val]
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     bool:
       A_   ,     A_		   = table.shape

       A_		   = True

       for i in range(0,    UpperCAmelCase__			):
              A_		   = 0
              for j in range(0,    cols - 1			):
                     if i == j:
                            continue
                     else:
                            total += table[i][j]

              if table[i][i] <= total:
                     raise ValueError("""Coefficient matrix is not strictly diagonally dominant"""			)

       return is_diagonally_dominant


# Test Cases
if __name__ == "__main__":
      import doctest

      doctest.testmod()
