
    9i                     `    d Z ddlZddlZddlZddlZddlmZmZ d Zde	de
fdZdd	ed
efdZy)z
A collection of utilities for ensuring that training can always occur. Heavily influenced by the
[toma](https://github.com/BlackHC/toma) library.
    N   )is_npu_availableis_xpu_availablec                     t        | t              st        |       } t        t        |             D ]  }d| |<   	 t	        j
                          t               r t        j                  j                          | S t               r t        j                  j                          | S t        j                  j                          | S )aN  
    Releases memory from `objects` by setting them to `None` and calls `gc.collect()` and `torch.cuda.empty_cache()`.
    Returned objects should be reassigned to the same variables.

    Args:
        objects (`Iterable`):
            An iterable of objects
    Returns:
        A list of `None` objects to replace `objects`

    Example:

        ```python
        >>> import torch
        >>> from accelerate.utils import release_memory

        >>> a = torch.ones(1000, 1000).cuda()
        >>> b = torch.ones(1000, 1000).cuda()
        >>> a, b = release_memory(a, b)
        ```
    N)
isinstancelistrangelengccollectr   torchxpuempty_cacher   npucuda)objectsis     a/var/www/html/backtest/airagagent/rag_env/lib/python3.12/site-packages/accelerate/utils/memory.pyrelease_memoryr      s    , gt$w-3w<  
JJL		
 N	 
			 N 	

 N    	exceptionreturnc                      g d}t         t              r,t         j                        dk(  rt	         fd|D              S y)z
    Checks if `exception` relates to CUDA out-of-memory, CUDNN not supported, or CPU out-of-memory

    Args:
        exception (`Exception`):
            An exception
    )zCUDA out of memory.z(cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.z*DefaultCPUAllocator: can't allocate memoryr   c              3   @   K   | ]  }|j                   d    v   yw)r   N)args).0errr   s     r   	<genexpr>z+should_reduce_batch_size.<locals>.<genexpr>O   s     C3)..++Cs   F)r   RuntimeErrorr
   r   any)r   _statementss   ` r   should_reduce_batch_sizer"   A   s:    K
 )\*s9>>/Ba/GC{CCCr   functionstarting_batch_sizec                 T      t        j                  t        |      S | fd}|S )a  
    A basic decorator that will try to execute `function`. If it fails from exceptions related to out-of-memory or
    CUDNN, the batch size is cut in half and passed to `function`

    `function` must take in a `batch_size` parameter as its first argument.

    Args:
        function (`callable`, *optional*):
            A function to wrap
        starting_batch_size (`int`, *optional*):
            The batch size to try and fit into memory

    Example:

    ```python
    >>> from accelerate.utils import find_executable_batch_size


    >>> @find_executable_batch_size(starting_batch_size=128)
    ... def train(batch_size, model, optimizer):
    ...     ...


    >>> train(model, optimizer)
    ```
    )r$   c            	         t        j                          t               rt        j                  j                          nGt               rt        j                  j                          nt        j                  j                          t        t        j                        j                  j                               }t        |      t        |       dz   k  rbdj                  t!        |dd  | dd        D cg c]  \  }}| d|  c}}      }t#        dj$                   dj$                   d| d      	 dk(  rt'        d	      	  g| i |S c c}}w # t(        $ r}t+        |      rt        j                          t               rt        j                  j                          nGt               rt        j                  j                          nt        j                  j                          d
z  n Y d }~nd }~ww xY w)Nr   z, =zBatch size was passed into `zS` as the first argument when called.Remove this as the decorator already does so: `(z)`r   z-No executable batch size found, reached zero.   )r   r   r   r   r   r   r   r   r   r   inspect	signature
parameterskeysr
   joinzip	TypeError__name__r   	Exceptionr"   )	r   kwargsparamsargvaluearg_stre
batch_sizer#   s	          r   	decoratorz-find_executable_batch_size.<locals>.decorators   s   


II!!#II!!#JJ""$g''1<<AACDv;#d)a-(iiCqr
TXYZY[T\D] ^jc5C5%!1 ^_G.x/@/@.A BBBJBSBSATTUV]U^^`b  Q"#RSS
<T<V<< !_  +A.JJL')		--/)+		--/

..01$J  s   6E

E 	H%BH  H)	functoolspartialfind_executable_batch_size)r#   r$   r:   r9   s   `  @r   r=   r=   S   s3    6   !;Qdee$J!F r   )N   )__doc__r;   r   r*   r   importsr   r   r   r2   boolr"   callableintr=    r   r   <module>rE      sJ   
  	   7!H	 d $C Cs Cr   