


"""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 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]				,      SCREAMING_SNAKE_CASE    :    Tuple=False				):


  '''simple docstring'''







  try:
    lowerCAmelCase     :     Optional[int]								=							os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    lowerCAmelCase     :     int								=							default
  else:
    # KEY is set, convert it to True or False.
    try:
      lowerCAmelCase     :     List[str]								=							strtobool(SCREAMING_SNAKE_CASE				)
    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 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]				):


  '''simple docstring'''







  return unittest.skip("Test was skipped"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Dict				):


  '''simple docstring'''







  return unittest.skipUnless(_run_slow_tests				,      "test is slow"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Any				):


  '''simple docstring'''







  return unittest.skipUnless(not torch.cuda.is_available()				,      "test requires only a CPU"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    str				):


  '''simple docstring'''







  return unittest.skipUnless(torch.cuda.is_available()				,      "test requires a GPU"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    str				):


  '''simple docstring'''







  return unittest.skipUnless(is_xpu_available()				,      "test requires a XPU"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[int]				):


  '''simple docstring'''







  return unittest.skipUnless(is_mps_available()				,      "test requires a `mps` backend support in `torch`"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Tuple				):


  '''simple docstring'''







  return unittest.skipUnless(
      is_transformers_available() and is_datasets_available()				,      "test requires the Hugging Face suite"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Tuple				):


  '''simple docstring'''







  return unittest.skipUnless(is_bnb_available()				,      "test requires the bitsandbytes library"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[int]				):


  '''simple docstring'''







  return unittest.skipUnless(is_tpu_available()				,      "test requires TPU"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Dict				):


  '''simple docstring'''







  return unittest.skipUnless(torch.cuda.device_count() == 1				,      "test requires a GPU"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Any				):


  '''simple docstring'''







  return unittest.skipUnless(torch.xpu.device_count() == 1				,      "test requires a XPU"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]				):


  '''simple docstring'''







  return unittest.skipUnless(torch.cuda.device_count() > 1				,      "test requires multiple GPUs"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Any				):


  '''simple docstring'''







  return unittest.skipUnless(torch.xpu.device_count() > 1				,      "test requires multiple XPUs"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    str				):


  '''simple docstring'''







  return unittest.skipUnless(is_safetensors_available()				,      "test requires safetensors"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Dict				):


  '''simple docstring'''







  return unittest.skipUnless(is_deepspeed_available()				,      "test requires DeepSpeed"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]				):


  '''simple docstring'''







  return unittest.skipUnless(is_torch_version(">="				,      "1.12.0"				)				,      "test requires torch version >= 1.12.0"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]=None				,      SCREAMING_SNAKE_CASE    :    Union[str, Any]=None				):


  '''simple docstring'''







  if test_case is None:
    return partial(SCREAMING_SNAKE_CASE				,      version=SCREAMING_SNAKE_CASE				)
  return unittest.skipUnless(is_torch_version(">="				,      SCREAMING_SNAKE_CASE				)				,      f"""test requires torch version >= {version}"""				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Tuple				):


  '''simple docstring'''







  return unittest.skipUnless(is_tensorboard_available()				,      "test requires Tensorboard"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]				):


  '''simple docstring'''







  return unittest.skipUnless(is_wandb_available()				,      "test requires wandb"				)(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[Any]				):


  '''simple docstring'''







  return unittest.skipUnless(is_comet_ml_available()				,      "test requires comet_ml"				)(SCREAMING_SNAKE_CASE				)


lowerCAmelCase__      				=   (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[Any]				):


  '''simple docstring'''







  return unittest.skipUnless(
      _atleast_one_tracker_available				,      "test requires at least one tracker to be available and for `comet_ml` to not be installed"				,      )(SCREAMING_SNAKE_CASE				)


class       SCREAMING_SNAKE_CASE__				(		unittest.TestCase				):
       """simple docstring"""


       a  :				str   =True

       @classmethod
       def        lowercase__							(						cls						):






         """simple docstring"""





         lowerCAmelCase     :     Dict								=							tempfile.mkdtemp()

       @classmethod
       def        lowercase__							(						cls						):






         """simple docstring"""





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







       def        lowercase__							(						self						):






         """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(snake_case__						)


class       SCREAMING_SNAKE_CASE__				(		unittest.TestCase				):
       """simple docstring"""


       def        lowercase__							(						self						):






         """simple docstring"""





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


class       SCREAMING_SNAKE_CASE__				(		unittest.TestCase				):
       """simple docstring"""


       def        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     Tuple								=							mocks if isinstance(snake_case__		,     (tuple, list)						) else [mocks]
         for m in self.mocks:
           m.start()
           self.addCleanup(m.stop						)

def 					a__			(				SCREAMING_SNAKE_CASE    :    List[Any]				):


  '''simple docstring'''







  lowerCAmelCase     :     List[str]								=							AcceleratorState()
  lowerCAmelCase     :     Dict								=							tensor[None].clone().to(state.device				)
  lowerCAmelCase     :     str								=							gather(SCREAMING_SNAKE_CASE				).cpu()
  lowerCAmelCase     :     List[Any]								=							tensor[0].cpu()
  for i in range(tensors.shape[0]				):
    if not torch.equal(tensors[i]				,      SCREAMING_SNAKE_CASE				):
      return False
  return True


class       SCREAMING_SNAKE_CASE__				:
       """simple docstring"""


       def __init__(						self		,     snake_case__		,     snake_case__		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     Any								=							returncode
         lowerCAmelCase     :     Optional[int]								=							stdout
         lowerCAmelCase     :     str								=							stderr

async def 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]				,      SCREAMING_SNAKE_CASE    :    Union[str, Any]				):


  '''simple docstring'''







  while True:
    lowerCAmelCase     :     Tuple								=							await stream.readline()
    if line:
      callback(SCREAMING_SNAKE_CASE				)
    else:
      break
async def 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]				,      SCREAMING_SNAKE_CASE    :    Optional[int]=None				,      SCREAMING_SNAKE_CASE    :    Union[str, Any]=None				,      SCREAMING_SNAKE_CASE    :    int=None				,      SCREAMING_SNAKE_CASE    :    List[Any]=False				,      SCREAMING_SNAKE_CASE    :    Tuple=False				):


  '''simple docstring'''







  if echo:
    print("\nRunning: "				,      " ".join(SCREAMING_SNAKE_CASE				)				)

  lowerCAmelCase     :     List[str]								=							await asyncio.create_subprocess_exec(
      cmd[0]				,      *cmd[1:]				,      stdin=SCREAMING_SNAKE_CASE				,      stdout=asyncio.subprocess.PIPE				,      stderr=asyncio.subprocess.PIPE				,      env=SCREAMING_SNAKE_CASE				,      )

  # 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)

  lowerCAmelCase     :     Dict								=							[]
  lowerCAmelCase     :     Dict								=							[]

  def tee(SCREAMING_SNAKE_CASE    :    str				,      SCREAMING_SNAKE_CASE    :    int				,      SCREAMING_SNAKE_CASE    :    List[str]				,      SCREAMING_SNAKE_CASE    :    List[Any]=""				):
    lowerCAmelCase     :     List[Any]								=							line.decode("utf-8"				).rstrip()
    sink.append(SCREAMING_SNAKE_CASE				)
    if not quiet:
      print(SCREAMING_SNAKE_CASE				,      SCREAMING_SNAKE_CASE				,      file=SCREAMING_SNAKE_CASE				)

    # XXX: the timeout doesn't seem to make any difference here
  await asyncio.wait(
      [
          asyncio.create_task(_read_stream(p.stdout				,      lambda SCREAMING_SNAKE_CASE				: tee(SCREAMING_SNAKE_CASE				,      SCREAMING_SNAKE_CASE				,      sys.stdout				,      label="stdout:"				)				)				),
          asyncio.create_task(_read_stream(p.stderr				,      lambda SCREAMING_SNAKE_CASE				: tee(SCREAMING_SNAKE_CASE				,      SCREAMING_SNAKE_CASE				,      sys.stderr				,      label="stderr:"				)				)				),
      ]				,      timeout=SCREAMING_SNAKE_CASE				,      )
  return _RunOutput(await p.wait()				,      SCREAMING_SNAKE_CASE				,      SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    str				,      SCREAMING_SNAKE_CASE    :    Any=None				,      SCREAMING_SNAKE_CASE    :    List[Any]=None				,      SCREAMING_SNAKE_CASE    :    Any=1_8_0				,      SCREAMING_SNAKE_CASE    :    List[Any]=False				,      SCREAMING_SNAKE_CASE    :    str=True				):


  '''simple docstring'''







  lowerCAmelCase     :     Any								=							asyncio.get_event_loop()
  lowerCAmelCase     :     Optional[int]								=							loop.run_until_complete(
      _stream_subprocess(SCREAMING_SNAKE_CASE				,      env=SCREAMING_SNAKE_CASE				,      stdin=SCREAMING_SNAKE_CASE				,      timeout=SCREAMING_SNAKE_CASE				,      quiet=SCREAMING_SNAKE_CASE				,      echo=SCREAMING_SNAKE_CASE				)				)

  lowerCAmelCase     :     Tuple								=							" ".join(SCREAMING_SNAKE_CASE				)
  if result.returncode > 0:
    lowerCAmelCase     :     int								=							"\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       SCREAMING_SNAKE_CASE__				(		lowercase				):
       """simple docstring"""


       pass

def 					a__			(				SCREAMING_SNAKE_CASE    :    List[str]				,      SCREAMING_SNAKE_CASE    :    List[str]=False				):


  '''simple docstring'''







  try:
    lowerCAmelCase     :     List[Any]								=							subprocess.check_output(SCREAMING_SNAKE_CASE				,      stderr=subprocess.STDOUT				)
    if return_stdout:
      if hasattr(SCREAMING_SNAKE_CASE				,      "decode"				):
        lowerCAmelCase     :     Union[str, Any]								=							output.decode("utf-8"				)
      return output
  except subprocess.CalledProcessError as e:
    raise SubprocessCallException(
        f"""Command `{" ".join(SCREAMING_SNAKE_CASE				)}` failed with the following error:\n\n{e.output.decode()}"""				) from e









"""simple docstring"""







from __future__ import annotations

from functools import lru_cache
from math import ceil

lowerCAmelCase__      				=   100

lowerCAmelCase__      				=   set(range(3, NUM_PRIMES, 2))
primes.add(2)
lowerCAmelCase__      				=   42

for prime in range(3, ceil(NUM_PRIMES**0.5), 2):
     if prime not in primes:
          continue
     primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime)))
@lru_cache(maxsize=1_0_0				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    int				):


  '''simple docstring'''







  if number_to_partition < 0:
    return set()
  elif number_to_partition == 0:
    return {1}

  lowerCAmelCase     :     set[int]								=							set()
  lowerCAmelCase     :     int
  lowerCAmelCase     :     int

  for prime in primes:
    if prime > number_to_partition:
      continue
    for sub in partition(number_to_partition - prime				):
      ret.add(sub * prime				)

  return ret
def 					a__			(				SCREAMING_SNAKE_CASE    :    int = 5_0_0_0				):


  '''simple docstring'''







  for number_to_partition in range(1				,      SCREAMING_SNAKE_CASE				):
    if len(partition(SCREAMING_SNAKE_CASE				)				) > number_unique_partitions:
      return number_to_partition
  return None


if __name__ == "__main__":
     print(F"{solution() = }")





