a
    d7                     @   sB  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlmZ d dlmZmZ d dlmZ d dlZddlmZmZ dd	lmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z" dQddZ#e#dd
dZ$dd Z%dd Z&dd Z'dd Z(dd Z)dd Z*dd Z+dd Z,dd  Z-d!d" Z.d#d$ Z/d%d& Z0d'd( Z1d)d* Z2d+d, Z3d-d. Z4dRd/d0Z5d1d2 Z6d3d4 Z7d5d6 Z8e9e! e goe  Z:d7d8 Z;G d9d: d:ej<Z=G d;d< d<ej<Z>G d=d> d>ej<Z?d?d@ Z@G dAdB dBZAdCdD ZBdSeAdEdFdGZCdTeAdEdJdKZDG dLdM dMeEZFdUeeG dNdOdPZHdS )V    N)	strtobool)partial)Path)ListUnion)mock   )AcceleratorStatePartialState)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_availableFc                 C   sZ   zt j|  }W n ty$   |}Y n20 zt|}W n" tyT   td|  dY n0 |S )NzIf set, z must be yes or no.)osenvironKeyErrorr   
ValueError)keydefaultvalue_value r    f/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/accelerate/test_utils/testing.pyparse_flag_from_env0   s    
r"   ZRUN_SLOW)r   c                 C   s   t d| S )z+Decorator that skips a test unconditionallyzTest was skipped)unittestskip	test_caser    r    r!   r$   C   s    r$   c                 C   s   t td| S )z
    Decorator marking a test as slow. Slow tests are skipped by default. Set the RUN_SLOW environment variable to a
    truthy value to run them.
    ztest is slow)r#   
skipUnless_run_slow_testsr%   r    r    r!   slowH   s    r)   c                 C   s   t tj  d| S )zu
    Decorator marking a test that must be only ran on the CPU. These tests are skipped when a GPU is available.
    ztest requires only a CPUr#   r'   torchcudaZis_availabler%   r    r    r!   require_cpuP   s    r-   c                 C   s   t tj d| S )zo
    Decorator marking a test that requires CUDA. These tests are skipped when there are no GPU available.
    test requires a GPUr*   r%   r    r    r!   require_cudaW   s    r/   c                 C   s   t t d| S )zn
    Decorator marking a test that requires XPU. These tests are skipped when there are no XPU available.
    test requires a XPU)r#   r'   r   r%   r    r    r!   require_xpu^   s    r1   c                 C   s   t t d| S )z
    Decorator marking a test that requires MPS backend. These tests are skipped when torch doesn't support `mps`
    backend.
    z0test requires a `mps` backend support in `torch`)r#   r'   r   r%   r    r    r!   require_mpse   s    r2   c                 C   s   t t ot d| S )zv
    Decorator marking a test that requires transformers and datasets. These tests are skipped when they are not.
    z$test requires the Hugging Face suite)r#   r'   r   r   r%   r    r    r!   require_huggingface_suitem   s
    r3   c                 C   s   t t d| S )zi
    Decorator marking a test that requires bitsandbytes. These tests are skipped when they are not.
    z&test requires the bitsandbytes library)r#   r'   r   r%   r    r    r!   require_bnbv   s    r4   c                 C   s   t t d| S )zp
    Decorator marking a test that requires TPUs. These tests are skipped when there are no TPUs available.
    ztest requires TPU)r#   r'   r   r%   r    r    r!   require_tpu}   s    r5   c                 C   s   t tj dkd| S )z
    Decorator marking a test that requires CUDA on a single GPU. These tests are skipped when there are no GPU
    available or number of GPUs is more than one.
       r.   r#   r'   r+   r,   device_countr%   r    r    r!   require_single_gpu   s    r9   c                 C   s   t tj dkd| S )z
    Decorator marking a test that requires CUDA on a single XPU. These tests are skipped when there are no XPU
    available or number of xPUs is more than one.
    r6   r0   r#   r'   r+   Zxpur8   r%   r    r    r!   require_single_xpu   s    r;   c                 C   s   t tj dkd| S )z
    Decorator marking a test that requires a multi-GPU setup. These tests are skipped on a machine without multiple
    GPUs.
    r6   ztest requires multiple GPUsr7   r%   r    r    r!   require_multi_gpu   s    r<   c                 C   s   t tj dkd| S )z
    Decorator marking a test that requires a multi-XPU setup. These tests are skipped on a machine without multiple
    XPUs.
    r6   ztest requires multiple XPUsr:   r%   r    r    r!   require_multi_xpu   s    r=   c                 C   s   t t d| S )z
    Decorator marking a test that requires safetensors installed. These tests are skipped when safetensors isn't
    installed
    ztest requires safetensors)r#   r'   r   r%   r    r    r!   require_safetensors   s    r>   c                 C   s   t t d| S )z|
    Decorator marking a test that requires DeepSpeed installed. These tests are skipped when DeepSpeed isn't installed
    ztest requires DeepSpeed)r#   r'   r   r%   r    r    r!   require_deepspeed   s    r?   c                 C   s   t tddd| S )zr
    Decorator marking a test that requires FSDP installed. These tests are skipped when FSDP isn't installed
    >=z1.12.0z%test requires torch version >= 1.12.0)r#   r'   r   r%   r    r    r!   require_fsdp   s    rA   c                 C   s0   | du rt t|dS ttd|d| | S )z
    Decorator marking that a test requires a particular torch version to be tested. These tests are skipped when an
    installed torch version is less than the required one.
    N)versionr@   ztest requires torch version >= )r   require_torch_min_versionr#   r'   r   )r&   rB   r    r    r!   rC      s    rC   c                 C   s   t t d| S )z
    Decorator marking a test that requires tensorboard installed. These tests are skipped when tensorboard isn't
    installed
    ztest requires Tensorboard)r#   r'   r   r%   r    r    r!   require_tensorboard   s    rD   c                 C   s   t t d| S )zt
    Decorator marking a test that requires wandb installed. These tests are skipped when wandb isn't installed
    ztest requires wandb)r#   r'   r   r%   r    r    r!   require_wandb   s    rE   c                 C   s   t t d| S )zz
    Decorator marking a test that requires comet_ml installed. These tests are skipped when comet_ml isn't installed
    ztest requires comet_ml)r#   r'   r   r%   r    r    r!   require_comet_ml   s    rF   c                 C   s   t td| S )z
    Decorator marking that a test requires at least one tracking library installed. These tests are skipped when none
    are installed
    zYtest requires at least one tracker to be available and for `comet_ml` to not be installed)r#   r'   _atleast_one_tracker_availabler%   r    r    r!   require_trackers   s    rH   c                   @   s4   e Zd ZdZdZedd Zedd Zdd Zd	S )
TempDirTestCasea  
    A TestCase class that keeps a single `tempfile.TemporaryDirectory` open for the duration of the class, wipes its
    data at the start of a test, and then destroyes it at the end of the TestCase.

    Useful for when a class or API requires a single constant folder throughout it's use, such as Weights and Biases

    The temporary directory location will be stored in `self.tmpdir`
    Tc                 C   s   t  | _dS )zECreates a `tempfile.TemporaryDirectory` and stores it in `cls.tmpdir`N)tempfilemkdtemptmpdirclsr    r    r!   
setUpClass   s    zTempDirTestCase.setUpClassc                 C   s   t j| jrt| j dS )z1Remove `cls.tmpdir` after test suite has finishedN)r   pathexistsrL   shutilrmtreerM   r    r    r!   tearDownClass   s    zTempDirTestCase.tearDownClassc                 C   sD   | j r@t| jdD ](}| r,|  q| rt| qdS )z<Destroy all contents in `self.tmpdir`, but not `self.tmpdir`z**/*N)	clear_on_setupr   rL   globis_fileunlinkis_dirrR   rS   )selfrP   r    r    r!   setUp  s    
zTempDirTestCase.setUpN)	__name__
__module____qualname____doc__rU   classmethodrO   rT   r[   r    r    r    r!   rI      s   	

rI   c                       s    e Zd ZdZ fddZ  ZS )AccelerateTestCasez
    A TestCase class that will reset the accelerator state at the end of every test. Every test that checks or utilizes
    the `AcceleratorState` class should inherit from this to avoid silent failures due to state being shared between
    tests.
    c                    s   t    t  t  d S N)supertearDownr	   Z_reset_stater
   )rZ   	__class__r    r!   rd     s    
zAccelerateTestCase.tearDown)r\   r]   r^   r_   rd   __classcell__r    r    re   r!   ra     s   ra   c                   @   s.   e Zd ZdZeejeej f dddZdS )MockingTestCasea  
    A TestCase class designed to dynamically add various mockers that should be used in every test, mimicking the
    behavior of a class-wide mock when defining one normally will not do.

    Useful when a mock requires specific information available only initialized after `TestCase.setUpClass`, such as
    setting an environment variable with that information.

    The `add_mocks` function should be ran at the end of a `TestCase`'s `setUp` function, after a call to
    `super().setUp()` such as:
    ```python
    def setUp(self):
        super().setUp()
        mocks = mock.patch.dict(os.environ, {"SOME_ENV_VAR", "SOME_VALUE"})
        self.add_mocks(mocks)
    ```
    )mocksc                 C   s>   t |ttfr|n|g| _| jD ]}|  | |j q dS )aQ  
        Add custom mocks for tests that should be repeated on each test. Should be called during
        `MockingTestCase.setUp`, after `super().setUp()`.

        Args:
            mocks (`mock.Mock` or list of `mock.Mock`):
                Mocks that should be added to the `TestCase` after `TestCase.setUpClass` has been run
        N)
isinstancetuplelistri   startZ
addCleanupstop)rZ   ri   mr    r    r!   	add_mocks+  s    	
zMockingTestCase.add_mocksN)	r\   r]   r^   r_   r   r   ZMockr   rp   r    r    r    r!   rh     s   rh   c                 C   s`   t  }| d   |j} t|  }| d  } t|jd D ]}t	|| | s@ dS q@dS )Nr   FT)
r	   clonetoZdevicer   cpurangeshaper+   equal)ZtensorstateZtensorsir    r    r!   are_the_same_tensors:  s    ry   c                   @   s   e Zd Zdd ZdS )
_RunOutputc                 C   s   || _ || _|| _d S rb   )
returncodestdoutstderr)rZ   r{   r|   r}   r    r    r!   __init__F  s    z_RunOutput.__init__N)r\   r]   r^   r~   r    r    r    r!   rz   E  s   rz   c                    s$   |   I d H }|r || q q q d S rb   )readline)streamcallbackliner    r    r!   _read_streamL  s    
r   )returnc              	      s   |rt dd|  tj| d g| dd  R |tjjtjj|dI d H }g g  dfdd	tjtt|j	fd	d
tt|j
 fdd
g|dI d H  t| I d H  S )Nz

Running:  r   r6   )stdinr|   r}   env c                    s.   |  d } ||   s*t|| |d d S )Nutf-8)file)decoderstripappendprint)r   Zsinkpipelabel)quietr    r!   teem  s    
z_stream_subprocess.<locals>.teec                    s   |  t jddS )Nzstdout:r   )sysr|   l)outr   r    r!   <lambda>v      z$_stream_subprocess.<locals>.<lambda>c                    s   |  t jddS )Nzstderr:r   )r   r}   r   )errr   r    r!   r   w  r   )timeout)r   )r   joinasyncioZcreate_subprocess_exec
subprocessPIPEwaitZcreate_taskr   r|   r}   rz   )cmdr   r   r   r   echopr    )r   r   r   r   r!   _stream_subprocessU  s,    
r      Tc           
   
   C   sb   t  }|t| |||||d}d| }|jdkr^d|j}	td| d|j d|	 |S )N)r   r   r   r   r   r   r   
'z' failed with returncode z,

The combined stderr from workers follows:
)r   Zget_event_loopZrun_until_completer   r   r{   r}   RuntimeError)
r   r   r   r   r   r   ZloopresultZcmd_strr}   r    r    r!   execute_subprocess_async~  s    

r   c                   @   s   e Zd ZdS )SubprocessCallExceptionN)r\   r]   r^   r    r    r    r!   r     s   r   )commandc              
   C   s   z2t j| t jd}|r0t|dr*|d}|W S W nH t jyz } z.tdd|  d|j  |W Y d}~n
d}~0 0 dS )z
    Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture
    if an error occured while running `command`
    )r}   r   r   z	Command `r   z$` failed with the following error:

N)	r   check_outputSTDOUThasattrr   CalledProcessErrorr   r   output)r   Zreturn_stdoutr   er    r    r!   run_command  s    


r   )F)NN)NNNFF)NNr   FT)F)Ir   r   rR   r   r   rJ   r#   distutils.utilr   	functoolsr   pathlibr   typingr   r   r   r+   rw   r	   r
   utilsr   r   r   r   r   r   r   r   r   r   r   r   r   r"   r(   r$   r)   r-   r/   r1   r2   r3   r4   r5   r9   r;   r<   r=   r>   r?   rA   rC   rD   rE   rF   anyrG   rH   ZTestCaserI   ra   rh   ry   rz   r   r   r   	Exceptionr   strr   r    r    r    r!   <module>   sb   <
	

!!	)