
    %ɷi)w                        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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Zddl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%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZD d
 ZE eE       \  ZFZGZHdeIfdZJ eJeGd      ZKdedZL eLdd      ZMd ZNd ZOd ZPd ZQd ZRd ZSd ZTd ZUd ZVd ZWd ZXd ZYd ZZd  Z[d! Z\d" Z]d# Z^d$ Z_d% Z`d& Zad' Zbd( Zcd) Zdd* Zed+ Zfd, Zgd- Zhd. Zid/ Zjd0 Zkd1 Zld2 Zmd3 Znd4 Zod5 Zpd6 Zqd7 Zrdfd8Zsd9 Ztd: Zud; Zvd< Zwd= Zxd> Zyd? Zzd@ Z{dA Z|dB Z}dC Z~dD ZdE ZdF ZdG ZdH Z e eB        e6        e=        e5       g      xr  e        ZdI ZdJ ZdK Z G dL dMe	j                        Z G dN dOe	j                        Z G dP dQe	j                        ZdR Z G dS dT      ZdU ZdgdefdVZdhdWeIdefdXZdY ZdZ Z G d[ d\e      Zdid]eIe   fd^Zd_edefd`Zedjdaedbee   defdc       Zdd Zy)k    N)contextmanager)partial)Path)OptionalUnion)mock   )AcceleratorState),check_cuda_fp8_capabilitycompare_versionsgatheris_aim_availableis_bnb_availableis_clearml_availableis_comet_ml_availableis_cuda_availableis_datasets_availableis_deepspeed_availableis_dvclive_availableis_fp8_availableis_fp16_availableis_habana_gaudi1is_hpu_availableis_import_timer_availableis_matplotlib_availableis_mlflow_availableis_mlu_availableis_mps_availableis_musa_availableis_neuron_availableis_npu_availableis_pandas_availableis_pippy_availableis_pytest_availableis_schedulefree_availableis_sdaa_availableis_swanlab_availableis_tensorboard_availableis_timm_availableis_torch_versionis_torch_xla_availableis_torchao_available*is_torchdata_stateful_dataloader_availableis_torchvision_availableis_trackio_availableis_transformer_engine_available%is_transformer_engine_mxfp8_availableis_transformers_availableis_triton_availableis_wandb_availableis_xpu_availablestr_to_boolc                  6   t               r9dt        j                  j                         t        j                  j                  fS t               r9dt        j                  j                         t        j                  j                  fS t        d      rddt        j                  j                  fS t               rddd fS t               r9dt        j                  j                         t        j                  j                  fS t               r9d	t        j                  j                         t        j                  j                  fS t               r9d
t        j                  j                         t        j                  j                  fS t               r9dt        j                   j                         t        j                   j                  fS t#               r9dt        j$                  j                         t        j$                  j                  fS t'               r9dt        j(                  j                         t        j(                  j                  fS t+               r9dt        j,                  j                         t        j,                  j                  fS ddd fS )Nxlacudaz2.0)min_versionmps   c                       yNr    r?       P/var/www/html/venv/lib/python3.12/site-packages/accelerate/test_utils/testing.py<lambda>zget_backend.<locals>.<lambda>\       r@   mlusdaamusanpuxpuhpuneuroncpuc                       yr>   r?   r?   r@   rA   rB   zget_backend.<locals>.<lambda>l   rC   r@   )r+   torchr9   device_countmemory_allocatedr   r   r;   current_allocated_memoryr   rD   r&   rE   r   rF   r!   rG   r5   rH   r   rI   r    rJ   r?   r@   rA   get_backendrQ   T   s   ejj--/1L1LLL		uzz..0%**2M2MMM	e	,a;;;;		a""		eii,,.		0J0JJJ		uzz..0%**2M2MMM		uzz..0%**2M2MMM		eii,,.		0J0JJJ		eii,,.		0J0JJJ		eii,,.		0J0JJJ		224ell6S6SSSa""r@   returnc                      ddg}| j                         D ]F  \  }}t        |t              r|r|j                  d|        -|0|j                  d| d|        H |S )z
    Wraps around `kwargs` to help simplify launching from `subprocess`.

    Example:
    ```python
    # returns ['accelerate', 'launch', '--num_processes=2', '--device_count=2']
    get_launch_command(num_processes=2, device_count=2)
    ```
    
acceleratelaunchz--=)items
isinstanceboolappend)kwargscommandkvs       rA   get_launch_commandr_   r   si     X&G )1a1NNRs8$]NNRs!A3<(	)
 Nr@   g?)num_processesmonitor_intervalFc                     	 t         j                  |    }	 t        |      }|S # t        $ r t        d|  d      w xY w# t        $ r |}Y |S w xY w)NzIf set, z must be yes or no.)osenvironr6   
ValueErrorKeyError)keydefaultvalue_values       rA   parse_flag_from_envrk      sp    B

3	B 'F M  	Bxu,?@AA	B   Ms   ? # <AARUN_SLOW)rh   c                 8     t        j                  d      |       S )z+Decorator that skips a test unconditionallyzTest was skipped)unittestskip	test_cases    rA   ro   ro      s    ,8==+,Y77r@   c                 B     t        j                  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)rn   
skipUnless_run_slow_testsrp   s    rA   slowru      s    
 @8?	JJr@   c                 H     t        j                  t        dk(  d      |       S )zu
    Decorator marking a test that must be only ran on the CPU. These tests are skipped when a GPU is available.
    rK   ztest requires only a CPUrn   rs   torch_devicerp   s    rA   require_cpury      s&     R8|u46PQR[\\r@   c                 H     t        j                  t        dk7  d      |       S )z
    Decorator marking a test that requires a hardware accelerator backend. These tests are skipped when there are no
    hardware accelerator available.
    rK   test requires a GPUrw   rp   s    rA   require_non_cpur|      s%    
 M8|u46KLYWWr@   c                 d     t        j                  t               xr t                d      |       S )z
    Decorator marking a test that requires CUDA. These tests are skipped when there are no GPU available or when
    TorchXLA is available.
    r{   )rn   rs   r   r+   rp   s    rA   require_cudar~      s1    
 l802S;Q;S7SUjkluvvr@   c                 |     t        j                  t               xr t                xs
 t	               d      |       S )z
    Decorator marking a test that requires CUDA or HPU. These tests are skipped when there are no GPU available or when
    TorchXLA is available.
    ztest requires a GPU or HPU)rn   rs   r   r+   r   rp   s    rA   require_cuda_or_hpur      s?    
8			=%;%=!=TBRBTVr r@   c                 J     t        j                  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)rn   rs   r5   rp   s    rA   require_xpur      s$     J8/13HI)TTr@   c                     t               xr t                }t               } t        j                  |xs |d      |       S )z
    Decorator marking a test that requires CUDA or XPU. These tests are skipped when there are no GPU available or when
    TorchXLA is available.
    ztest requires a CUDA GPU or XPU)r   r+   r5   rn   rs   )rq   cuda_conditionxpu_conditions      rA   require_cuda_or_xpur      sA    
 '(I1G1I-IN$&Mb8~>@abclmmr@   c                 H     t        j                  t        dk7  d      |       S )zB
    Decorator marking a test that should be skipped for XPU.
    rH   ztest requires a non-XPUrw   rp   s    rA   require_non_xpur      &     Q8|u46OPQZ[[r@   c                 H     t        j                  t        dk7  d      |       S )zB
    Decorator marking a test that should be skipped for HPU.
    rI   ztest requires a non-HPUrw   rp   s    rA   require_non_hpur      r   r@   c                 J     t        j                  t               d      |       S )zj
    Decorator marking a test that requires FP16. These tests are skipped when FP16 is not supported.
    ztest requires FP16 support)rn   rs   r   rp   s    rA   require_fp16r      s%    
 R8024PQR[\\r@   c                     t               }t        j                  j                         rt	               sd}t               rt               rd} t        j                  |d      |       S )zh
    Decorator marking a test that requires FP8. These tests are skipped when FP8 is not supported.
    Fztest requires FP8 support)	r   rM   r9   is_availabler   r   r   rn   rs   )rq   fp8_is_availables     rA   require_fp8r      sW     ()zz )B)D .0 M8/1LMiXXr@   c                 N     t        j                  t        dd      d      |       S )N>=z2.5.0z$test requires FSDP2 (torch >= 2.5.0))rn   rs   r*   rp   s    rA   require_fsdp2r     s&    g8/g>@fghqrrr@   c                 J     t        j                  t               d      |       S )zn
    Decorator marking a test that requires MLU. These tests are skipped when there are no MLU available.
    ztest require a MLU)rn   rs   r   rp   s    rA   require_mlur     $     I8/13GHSSr@   c                 J     t        j                  t               d      |       S )zp
    Decorator marking a test that requires SDAA. These tests are skipped when there are no SDAA available.
    ztest require a SDAA)rn   rs   r&   rp   s    rA   require_sdaar     $     K8024IJ9UUr@   c                 J     t        j                  t               d      |       S )zp
    Decorator marking a test that requires MUSA. These tests are skipped when there are no MUSA available.
    ztest require a MUSA)rn   rs   r   rp   s    rA   require_musar     r   r@   c                 J     t        j                  t               d      |       S )zn
    Decorator marking a test that requires NPU. These tests are skipped when there are no NPU available.
    ztest require a NPU)rn   rs   r!   rp   s    rA   require_npur     r   r@   c                 J     t        j                  t               d      |       S )zz
    Decorator marking a test that requires Neuron. These tests are skipped when there are no Neuron Cores available.
    ztest require Neuron Cores)rn   rs   r    rp   s    rA   require_neuronr   "  s%     S8246QRS\]]r@   c                 J     t        j                  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`)rn   rs   r   rp   s    rA   require_mpsr   )  s%    
 g8/13efgpqqr@   c                 b     t        j                  t               xr
 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)rn   rs   r2   r   rp   s    rA   require_huggingface_suiter   1  s5    8!#?(=(?.  r@   c                 J     t        j                  t               d      |       S )zi
    Decorator marking a test that requires transformers. These tests are skipped when they are not.
    z&test requires the transformers library)rn   rs   r2   rp   s    rA   require_transformersr   ;  %     f88:<defoppr@   c                 J     t        j                  t               d      |       S )za
    Decorator marking a test that requires timm. These tests are skipped when they are not.
    ztest requires the timm library)rn   rs   r)   rp   s    rA   require_timmr   B  s%     V8024TUV_``r@   c                 J     t        j                  t               d      |       S )zh
    Decorator marking a test that requires torchvision. These tests are skipped when they are not.
    z%test requires the torchvision library)rn   rs   r.   rp   s    rA   require_torchvisionr   I  s%     d879;bcdmnnr@   c                 J     t        j                  t               d      |       S )zc
    Decorator marking a test that requires triton. These tests are skipped when they are not.
    z test requires the triton library)rn   rs   r3   rp   s    rA   require_tritonr   P  s%     Z8246XYZcddr@   c                 J     t        j                  t               d      |       S )zi
    Decorator marking a test that requires schedulefree. These tests are skipped when they are not.
    z&test requires the schedulefree library)rn   rs   r%   rp   s    rA   require_schedulefreer   W  r   r@   c                 J     t        j                  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)rn   rs   r   rp   s    rA   require_bnbr   ^  s%     ]8/13[\]fggr@   c                 N     t        j                  t        d      d      |       S )zp
    Decorator marking a test that requires TPUs. These tests are skipped when there are no TPUs available.
    T)check_is_tpuztest requires TPUrn   rs   r+   rp   s    rA   require_tpur   e  s'     _854HJ]^_hiir@   c                 L     t        j                  t                d      |       S )z
    Decorator marking a test as requiring an environment without TorchXLA. These tests are skipped when TorchXLA is
    available.
    z%test requires an env without TorchXLAr   rp   s    rA   require_non_torch_xlar   l  s(    
 f8#9#;;=defoppr@   c                 ^     t        j                  t        dk7  xr	 t        dk(  d      |       S )z
    Decorator marking a test that requires a single device. These tests are skipped when there is no hardware
    accelerator available or number of devices is more than one.
    rK   r<   z)test requires a single device accelerator)rn   rs   rx   rN   rp   s    rA   require_single_devicer   t  s6    
83,!"35` r@   c                 x     t        j                  t        j                  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{   rn   rs   rM   r9   rN   rp   s    rA   require_single_gpur   ~  s3    
 V8uzz668A=?TUV_``r@   c                 x     t        j                  t        j                  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.
    r<   r   rn   rs   rM   rH   rN   rp   s    rA   require_single_xpur     s3    
 U8uyy5571<>STU^__r@   c                 H     t        j                  t        dkD  d      |       S )z
    Decorator marking a test that requires a multi-device setup. These tests are skipped on a machine without multiple
    devices.
    r<   z,test requires multiple hardware accelerators)rn   rs   rN   rp   s    rA   require_multi_devicer     s&    
 a8|a/1_`ajkkr@   c                 x     t        j                  t        j                  j	                         dkD  d      |       S )z
    Decorator marking a test that requires a multi-GPU setup. These tests are skipped on a machine without multiple
    GPUs.
    r<   ztest requires multiple GPUsr   rp   s    rA   require_multi_gpur     s3    
 ]8uzz6681<>[\]fggr@   c                 x     t        j                  t        j                  j	                         dkD  d      |       S )z
    Decorator marking a test that requires a multi-XPU setup. These tests are skipped on a machine without multiple
    XPUs.
    r<   ztest requires multiple XPUsr   rp   s    rA   require_multi_xpur     s3    
 \8uyy557!;=Z[\effr@   c                 x     t        j                  t               xs
 t               xr	 t        dkD  d      |       S )z
    Decorator marking a test that requires a multi-GPU setup. These tests are skipped on a machine without multiple
    GPUs or XPUs.
    r<   z#test requires multiple GPUs or XPUs)rn   rs   r   r5   rN   rp   s    rA   require_multi_gpu_or_xpur     s=    
8			2 0 2Hq8HJo r@   c                 J     t        j                  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)rn   rs   r   rp   s    rA   require_deepspeedr     s%     T8579RST]^^r@   c                 l     t        j                  t        dd      xr t        ddd      d      |       S )zn
    Decorator marking a test that requires TP installed. These tests are skipped when TP isn't installed
    r   z2.3.0transformersz4.52.0zGtest requires torch version >= 2.3.0 and transformers version >= 4.52.0)rn   rs   r*   r   rp   s    rA   
require_tpr     s@    8w'\,<^TS[,\Q  r@   c                 z    | t        t        |      S  t        j                  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.
    )versionr   ztest requires torch version >= )r   require_torch_min_versionrn   rs   r*   )rq   r   s     rA   r   r     sE    
 0'BBl8/g>Babiaj@klmvwwr@   c                 J     t        j                  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)rn   rs   r(   rp   s    rA   require_tensorboardr     s%    
 X879;VWXabbr@   c                 J     t        j                  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)rn   rs   r4   rp   s    rA   require_wandbr     s$     L8135JKIVVr@   c                 J     t        j                  t               d      |       S )zx
    Decorator marking a test that requires trackio installed. These tests are skipped when trackio isn't installed
    ztest requires trackio)rn   rs   r/   rp   s    rA   require_trackior     %     P8357NOPYZZr@   c                 J     t        j                  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)rn   rs   r   rp   s    rA   require_comet_mlr     s%     R8468PQR[\\r@   c                 J     t        j                  t               d      |       S )zp
    Decorator marking a test that requires aim installed. These tests are skipped when aim isn't installed
    ztest requires aim)rn   rs   r   rp   s    rA   require_aimr     s$     H8/13FG	RRr@   c                 J     t        j                  t               d      |       S )zx
    Decorator marking a test that requires clearml installed. These tests are skipped when clearml isn't installed
    ztest requires clearml)rn   rs   r   rp   s    rA   require_clearmlr     r   r@   c                 J     t        j                  t               d      |       S )zx
    Decorator marking a test that requires dvclive installed. These tests are skipped when dvclive isn't installed
    ztest requires dvclive)rn   rs   r   rp   s    rA   require_dvcliver     r   r@   c                 J     t        j                  t               d      |       S )zx
    Decorator marking a test that requires swanlab installed. These tests are skipped when swanlab isn't installed
    ztest requires swanlab)rn   rs   r'   rp   s    rA   require_swanlabr     r   r@   c                 J     t        j                  t               d      |       S )zv
    Decorator marking a test that requires pandas installed. These tests are skipped when pandas isn't installed
    ztest requires pandas)rn   rs   r"   rp   s    rA   require_pandasr     $     N8246LMiXXr@   c                 J     t        j                  t               d      |       S )zv
    Decorator marking a test that requires mlflow installed. These tests are skipped when mlflow isn't installed
    ztest requires mlflow)rn   rs   r   rp   s    rA   require_mlflowr     r   r@   c                 d     t        j                  t               xr t                d      |       S )z
    Decorator marking a test that requires pippy installed. These tests are skipped when pippy isn't installed It is
    also checked if the test is running on a Gaudi1 device which doesn't support pippy.
    ztest requires pippy)rn   rs   r#   r   rp   s    rA   require_pippyr     s1    
 g813N<L<N8NPefgpqqr@   c                 J     t        j                  t               d      |       S )z
    Decorator marking a test that requires tuna interpreter installed. These tests are skipped when tuna isn't
    installed
    ztest requires tuna interpreter)rn   rs   r   rp   s    rA   require_import_timerr     s%    
 ^88:<\]^ghhr@   c                 J     t        j                  t               d      |       S )z
    Decorator marking a test that requires transformers engine installed. These tests are skipped when transformers
    engine isn't installed
    z!test requires transformers engine)rn   rs   r0   rp   s    rA   require_transformer_enginer   "  s%    
 g8>@Befgpqqr@   c                 J     t        j                  t               d      |       S )z
    Decorator marking a test that requires transformers engine MXFP8 block scaling available. These tests are skipped
    when transformers engine MXFP8 block scaling isn't available
    z5test requires transformers engine MXFP8 block scaling)rn   rs   r1   rp   s    rA    require_transformer_engine_mxfp8r   *  s*    
8-/1h r@   c                 J     t        j                  t               d      |       S )zx
    Decorator marking a test that requires torchao installed. These tests are skipped when torchao isn't installed
    ztest requires torchao)rn   rs   r,   rp   s    rA   require_torchaor   4  r   r@   c                 J     t        j                  t               d      |       S )z
    Decorator marking a test that requires matplotlib installed. These tests are skipped when matplotlib isn't
    installed
    ztest requires matplotlib)rn   rs   r   rp   s    rA   require_matplotlibr   ;  s%    
 V868:TUV_``r@   c                 B     t        j                  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)rn   rs   _atleast_one_tracker_availablerp   s    rA   require_trackersr   I  s)    
8&c  r@   c                 J     t        j                  t               d      |       S )z
    Decorator marking a test that requires torchdata.stateful_dataloader.

    These tests are skipped when torchdata with stateful_dataloader module isn't installed.

    z+test requires torchdata.stateful_dataloader)rn   rs   r-   rp   s    rA   %require_torchdata_stateful_dataloaderr   T  s*    8246c r@   c                 d    t               r%ddl} |j                  j                  d      |       S | S )a  
    Decorator marking a test with order(1). When pytest-order plugin is installed, tests marked with this decorator are
    guaranteed to run first.

    This is especially useful in some test settings like on a Gaudi instance where a Gaudi device can only be used by a
    single process at a time. So we make sure all tests that run in a subprocess are launched first, to avoid device
    allocation conflicts.

    If pytest is not installed, test will be returned as is.
    r   Nr<   )r$   pytestmarkorder)rq   r   s     rA   	run_firstr   `  s/     #v{{  #I..r@   c                   :    e Zd ZdZdZed        Zed        Zd Zy)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 destroys 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                 H    t        t        j                               | _        y)zECreates a `tempfile.TemporaryDirectory` and stores it in `cls.tmpdir`N)r   tempfilemkdtemptmpdirclss    rA   
setUpClasszTempDirTestCase.setUpClass  s     (**,-
r@   c                     t         j                  j                  | j                        r t	        j
                  | j                         yy)z1Remove `cls.tmpdir` after test suite has finishedN)rc   pathexistsr  shutilrmtreer  s    rA   tearDownClasszTempDirTestCase.tearDownClass  s-     77>>#**%MM#**% &r@   c                     | j                   rh| j                  j                  d      D ]I  }|j                         r|j	                          $|j                         s5t        j                  |       K yy)z<Destroy all contents in `self.tmpdir`, but not `self.tmpdir`z**/*N)clear_on_setupr  globis_fileunlinkis_dirr	  r
  )selfr  s     rA   setUpzTempDirTestCase.setUp  sU    ((0 (<<>KKM[[]MM$'	( r@   N)	__name__
__module____qualname____doc__r  classmethodr  r  r  r?   r@   rA   r   r   s  s9     N. . & &
(r@   r   c                   "     e Zd ZdZ fdZ x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                 L    t         |           t        j                  d       y )NT)supertearDownr
   _reset_state)r  	__class__s    rA   r  zAccelerateTestCase.tearDown  s    %%d+r@   )r  r  r  r  r  __classcell__)r  s   @rA   r  r    s    , ,r@   r  c                   T    e Zd ZdZdeej                  eej                     f   fdZy)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                     t        |t        t        f      r|n|g| _        | j                  D ]-  }|j	                          | j                  |j                         / y)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)rX   tuplelistr#  start
addCleanupstop)r  r#  ms      rA   	add_mockszMockingTestCase.add_mocks  sH     )>UUG
 	$AGGIOOAFF#	$r@   N)	r  r  r  r  r   r   Mockr&  r+  r?   r@   rA   r"  r"    s)    "$uTYYTYY%?@ $r@   r"  c                 8   t               }| d    j                         j                  |j                        } t	        |       j                         }| d   j                         } t        |j                  d         D ]  }t        j                  ||   |       r y y)Nr   FT)
r
   clonetodevicer   rK   rangeshaperM   equal)tensorstatetensorsis       rA   are_the_same_tensorsr8    s    ED\!$$U\\2FVn  "GAY]]_F7==#$ {{71:v. r@   c                       e Zd Zd Zy)
_RunOutputc                 .    || _         || _        || _        y N)
returncodestdoutstderr)r  r=  r>  r?  s       rA   __init__z_RunOutput.__init__  s    $r@   N)r  r  r  r@  r?   r@   rA   r:  r:    s    r@   r:  c                 Z   K   	 | j                          d {   }|r	 ||       ny %7 wr<  )readline)streamcallbacklines      rA   _read_streamrF    s-     
__&&TN &s   +)+c           
      T  	K   |rt        ddj                  |              t        j                  | d   g| dd  |t        j                  j
                  t        j                  j
                  |d d {   }g g d
fd		t        j                  t        j                  t        |j                  	fd            t        j                  t        |j                  	fd            g|	       d {    t        |j                          d {         S 7 7 )7 w)Nz

Running:  r   r<   )stdinr>  r?  envc                     | j                  d      j                         } |j                  |        st        || |       y y )Nutf-8)file)decoderstriprZ   print)rE  sinkpipelabelquiets       rA   teez_stream_subprocess.<locals>.tee  s:    {{7#**,D%D) r@   c                 8     | t         j                  d      S )Nzstdout:rS  )sysr>  )loutrU  s    rA   rB   z$_stream_subprocess.<locals>.<lambda>      QSZZ_hAi r@   c                 8     | t         j                  d      S )Nzstderr:rW  )rX  r?  )rY  errrU  s    rA   rB   z$_stream_subprocess.<locals>.<lambda>  r[  r@   )timeout) )rP  joinasynciocreate_subprocess_exec
subprocessPIPEwaitcreate_taskrF  r>  r?  r:  )
cmdrJ  rI  r^  rT  echopr]  rZ  rU  s
       `  @@@rA   _stream_subprocessrj    s    mSXXc]+,,A	QR !!&&!!&& 	A" C
C* ,,QXX7i jkQXX7i jk	
    AFFHnc3//E	6 %s7   A3D(9D":B D(:D$;D(D&D($D(&D(rg  c           
      d   t        |       D ]$  \  }}t        |t              st        |      | |<   & t	        j
                  t        | |||||            }dj                  |       }	|j                  dkD  r9dj                  |j                        }
t        d|	 d|j                   d|
       |S )N)rJ  rI  r^  rT  rh  rH  r   
'z' failed with returncode z,

The combined stderr from workers follows:
)	enumeraterX   r   strra  runrj  r`  r=  r?  RuntimeError)rg  rJ  rI  r^  rT  rh  r7  cresultcmd_strr?  s              rA   execute_subprocess_asyncru    s    # 1aVCF [[+CSw^cjnopFhhsmG16==)y1&2C2C1D E::@C
 	

 Mr@   c                      t         j                  j                  dd      } t        j                  dd| dt        j
                        } t        |       S )z
    Returns an int value of worker's numerical id under `pytest-xdist`'s concurrent workers `pytest -n N` regime, or 0
    if `-n 1` or `pytest-xdist` isn't being used.
    PYTEST_XDIST_WORKERgw0z^gwr_  r   )rc   rd   getresubMint)workers    rA   pytest_xdist_worker_idr    s=    
 ZZ^^159FVVFB2440Fv;r@   c                  $    d} t               }| |z   S )z
    Returns a port number that can be fed to `torch.distributed.launch`'s `--master_port` argument.

    Under `pytest-xdist` it adds a delta number based on a worker id so that concurrent tests don't try to use the same
    port at once.
    i<s  )r  )port
uniq_deltas     rA   get_torch_dist_unique_portr  #  s     D')J*r@   c                       e Zd Zy)SubprocessCallExceptionN)r  r  r  r?   r@   rA   r  r  /  s    r@   r  r\   c                    t        |       D ]$  \  }}t        |t              st        |      | |<   & |t        j
                  j                         }	 t        j                  | t        j                  |      }|rt        |d      r|j                  d      }|S y# t        j                  $ r>}t        ddj                  |        d|j                  j                                |d}~ww xY w)z
    Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture
    if an error occurred while running `command`
    N)r?  rJ  rN  rL  z	Command `rH  z$` failed with the following error:

)rn  rX   r   ro  rc   rd   copyrc  check_outputSTDOUThasattrrN  CalledProcessErrorr  r`  output)r\   return_stdoutrJ  r7  rr  r  es          rA   run_commandr  3  s     '"  1aQGAJ  {jjoo	((9J9JPSTvx(w/M  (( %)**PQRQYQYQ`Q`QbPcd
	s   AB C-/9C((C-
componentsc                  x    t        t        j                  t                    j                  } |j
                  |  S )z
    Get a path within the `accelerate` package's directory.

    Args:
        *components: Components of the path to join after the package directory.

    Returns:
        `Path`: The path to the requested file or directory.
    )r   inspectgetfilerT   parentjoinpath)r  accelerate_package_dirs     rA   path_in_accelerate_packager  J  s2     "'//*"=>EE*!**J77r@   exception_classmsgc              #      K   d}	 d d}|rt	        d|  d	      y# t         $ rR}t        ||       sJ d|  dt        |              |$|t        |      v sJ d| dt        |       d       Y d}~hd}~ww xY ww)
z
    Context manager to assert that the right `Exception` class was raised.

    If `msg` is provided, will check that the message is contained in the raised exception.
    FNTzExpected exception of type z	 but got zExpected message 'z' to be in exception but got 'rm  z but ran without issue.)	ExceptionrX   typero  AssertionError)r  r  was_ranr  s       rA   assert_exceptionr  Y  s      Gd
 :?:KKbcdd 	  d!_-p1L_L]]fgklmgnfo/pp-?#a&=c$6se;YZ]^_Z`Yaab"cc=ds+   A< A<	A9AA4/A<4A99A<c                     t        j                         }t        j                  }	 |t        _         | |i | 	 |t        _        |j                         S # t        $ r}|d}~ww xY w# |t        _        w xY w)z`
    Takes in a `func` with `args` and `kwargs` and returns the captured stdout as a string
    N)ioStringIOrX  r>  r  getvalue)funcargsr[   captured_outputoriginal_stdoutr  s         rA   capture_call_outputr  l  sj     kkmOjjO%$
df %
##%%	   %
s#   A 	A%A  A%%A( (A5)F)NN)NNNFF)NN   FT)FNr<  )ra  r  r  rc   rz  r	  rc  rX  r   rn   
contextlibr   	functoolsr   pathlibr   typingr   r   r   rM   rT   r5  r
   utilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   rQ   rx   rN   memory_allocated_funcr&  r_   DEFAULT_LAUNCH_COMMANDrk   rt   ro   ru   ry   r|   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   anyr   r   r   r   TestCaser   r  r"  r8  r:  rF  rj  ru  r  r  r  r  ro  r  r  rY   r  r  r?   r@   rA   <module>r     s      	 	 	   
   %   "    $- - - - - - - - - - - -`#6 5@M 1l1D & ,,Y\]   &j%@8
K]XwUn\\]Y$sTVVT^rqaoeqhjqa`lhg_xcW[]S[[[YYrir[a 		79;O;QSgSijk $!## 	&(h'' (B
,** 
,$h'' $B &0bl &0R$ fp &		i 	c .8C 8D 8 ei ehsm et e e$&r@   