
    `i%                     t    S SK Jr  S SK Jr  S SK Jr  S SKrS SKrS SKrS SKJr    S
S jrSS jr	SS jr
S	 rg)    )absolute_import)print_function)divisionN)py3nvmlc                 	   U(       d-  S[         R                  R                  5       ;   a  [        S5      eS[         R                  S'   U S:X  a  g[        R
                  " [        5      n [        R                  " 5         [        R                  " 5       nS/U-  n	Sn
U S:X  a  Un Sn
Uc  S/U-  nOS/U-  n SX'   [        U5       H  nX   (       d  M  [        R                   " U5      n[        R"                  " U5      nSR%                  U5      SR%                  UR&                  S-  5      -   SR%                  UR(                  S-  5      -   nUR+                  U5        M     US:  a
  [-        US9nOS/U-  n[        U5       H  nX   (       d  M  X   (       d  M  [        R                   " U5      n[        R"                  " U5      nU(       a5  UR(                  S-  U:  a"  UR/                  SR%                  U5      5        M  UR0                  S-   UR(                  -  U:  a  SX'   M  UR/                  SR%                  U5      5        M     [        R2                  " 5         [5        U	5      S:X  a-  [        R                  " S[        5        UR                  W5        g[5        U	5      U :  a  [7        U	5       VVs/ s H  u  nnU(       d  M  UPM     nnnSR9                  [;        S US	U   5       5      5      nUR+                  SR%                  [5        U	5      5      5        UR/                  SR%                  U5      5        U[         R                  S'   U $ U
(       a  SR%                  [5        U	5      U 5      S-   n[        R                  " U[        5        UR                  U5        [7        U	5       VVs/ s H  u  nnU(       d  M  UPM     nnnSR9                  [;        S U 5       5      5      nUR+                  SR%                  [5        U	5      5      5        UR/                  SR%                  U5      5        U[         R                  S'   [5        U	5      $ g	!   Sn[        R                  " U[        5        UR                  U5         g= f! [         a"     U H  nSX'   M	      GN!   [        S
5      e= ff = fs  snnf s  snnf )a  
Checks for gpu availability and sets CUDA_VISIBLE_DEVICES as such.

Note that this function does not do anything to 'reserve' gpus, it only
limits what GPUS your program can see by altering the CUDA_VISIBLE_DEVICES
variable. Other programs can still come along and snatch your gpu. This
function is more about preventing **you** from stealing someone else's GPU.

If more than 1 GPU is requested but not all were available, then it
will set the CUDA_VISIBLE_DEVICES variable to see all the available GPUs.
A warning is generated in this case.

If one or more GPUs were requested and none were available, a Warning
will be raised. Before raising it, the CUDA_VISIBLE_DEVICES will be set to
a blank string. This means the calling function can ignore this warning and
proceed if it chooses to only use the CPU, and it should still be protected
against putting processes on a busy GPU.

You can call this function with num_gpus=0 to blank out the
CUDA_VISIBLE_DEVICES environment variable.

Parameters
----------
num_gpus : int
    How many gpus your job needs (optional). Can set to -1 to take all
    remaining available GPUs.
gpu_select : iterable
    A single int or an iterable of ints indicating gpu numbers to
    search through. If None, will search through all gpus.
gpu_fraction : float
    The fractional of a gpu memory that must be free for the script to see
    the gpu as free. Defaults to 1. Useful if someone has grabbed a tiny
    amount of memory on a gpu but isn't using it.
max_procs : int
    Maximum number of processes allowed on a GPU (as well as memory
    restriction).
env_set_ok : bool
    If false, will complain if CUDA_VISIBLE_DEVICES is already set.
gpu_min_memory: int
    The minimal allowed graphics card memory amount in MiB.

Returns
-------
success : int
    Number of gpus 'grabbed'

Raises
------
RuntimeWarning
    If couldn't connect with NVIDIA drivers.
    If 1 or more gpus were requested and none were available.
    Will NOT raise a RuntimeWarning for mismatch in GPU availability if
    `num_gpus` is -1.
ValueError
    If the gpu_select option was not understood (can fix by leaving this
    field blank, providing an int or an iterable of ints).
CUDA_VISIBLE_DEVICESzlTrying to set CUDA_VISIBLE_DEVICES but it has been set already. Specify env_set_ok=True to avoid this error. r   z_Couldn't connect to nvml drivers. Check they are installed correctly.
Proceeding on cpu only...FTNz<Please set gpu_select to None, an int or aniterable of ints.zGPU {}:	zUsed Mem: {:>6}MB	i   zTotal Mem: {:>6}MB)	max_procsz*GPU {} does not have enough RAM. Skipping.
   z%GPU {} has processes on it. Skipping.z'Could not find enough GPUs for your job,c              3   8   #    U  H  n[        U5      v   M     g 7fNstr.0ss     L/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/py3nvml/utils.py	<genexpr>grab_gpus.<locals>.<genexpr>   s     $O5NSVV5N   z{} Gpus found freezUsing {}zOnly {} GPUs found but {} z+requested. Allocating these and continuing.c              3   8   #    U  H  n[        U5      v   M     g 7fr   r   r   s     r   r   r      s     $D^SVV^r   )osenvironkeys
ValueErrorlogging	getLogger__name__r   nvmlInitwarningswarnRuntimeWarningwarningnvmlDeviceGetCount	TypeErrorrangenvmlDeviceGetHandleByIndexnvmlDeviceGetMemoryInfoformatusedtotaldebugget_free_gpusinfofreenvmlShutdownsum	enumeratejoinlist)num_gpus
gpu_selectgpu_fractionr   
env_set_okgpu_min_memoryloggerstr_
numDevicesgpu_freewarn_about_fewer_gpus	gpu_checkihandler0   procs_okxavailable_gpususe_gpusr   s                       r   	grab_gpusrH      s3   v 0BJJOO4EE " # 	#
 *,BJJ%&1} x(F ++-Jwz!H 2~ % FZ'	Gj(		6$(I! :|33A6..v6!!!$$++DIIy,ABC#**4::y+ABC 	T  A~ 958j( :<<HKK77:F226:D JJ	*^;KK L S STU VW 		"djj(L8"CJJ1MN% (  8}?Ptx=H$ -6h,?E,?DAq1a,?NExx$O^IX5N$O OPHLL-44S]CDKK
))(3419BJJ-.O",33CM8L=>AMM!^,NN1,5h,?E,?DAq1a,?NExx$D^$D DEHLL-44S]CDKK
))(3419BJJ-.x=  #q4dN+t"  	66#A#'IL $6  "5 6 6	6x F FsB   *Q 7R >SS:SS0R
R?R..R;;R?c                 R     U " U5      nU$ ! [         R                   a    Un U$ f = fr   )r   NVMLError_NotSupported)fhdefaultvs       r   try_get_inforO      s8    aD H )) Hs    &&c                    [         R                  " [        5      n [        R                  " 5         [        R                  " 5       nS/U-  n[        U5       HK  n [        R                  " U5      n[        [        R                  US/5      n[        U5      U ::  d  MG  SXE'   MM     [        R                  " 5         U$ !   Sn[
        R                  " U[        5        UR                  U5        / s $ = f!    M  = f)a	  
Checks the number of processes running on your GPUs.

Parameters
----------
max_procs : int
    Maximum number of procs allowed to run on a gpu for it to be considered
    'available'

Returns
-------
availabilities : list(bool)
    List of length N for an N-gpu system. The nth value will be true, if the
    nth gpu had at most max_procs processes running on it. Set to 0 to look
    for gpus with no procs on it.

Note
----
If function can't query the driver will return an empty list rather than raise an
Exception.
ECouldn't connect to nvml drivers. Check they are installed correctly.F	somethingTr   r   r    r   r!   r"   r#   r$   r%   r&   r(   r)   rO   $nvmlDeviceGetComputeRunningProcesseslenr2   )r   r<   r=   r7   r?   rB   rL   procss           r   r/   r/      s    . x(F ))+HwxH8_	2215A WII1)],u:"HK  O)ZdN+t		s   B= C4=2C14C9c                     [         R                  " [        5      n  [        R                  " 5         [        R                  " 5       nS/U-  n[        U5       HC  n [        R                  " U5      n[        [        R                  US/5      n[        U5      X4'   ME     [        R                  " 5         U$ !   Sn[
        R                  " U[        5        U R                  U5        / s $ = f!    M  = f)aF  Gets the number of processes running on each gpu

Returns
-------
num_procs : list(int)
    Number of processes running on each gpu

Note
----
If function can't query the driver will return an empty list rather than raise an
Exception.

Note
----
If function can't get the info from the gpu will return -1 in that gpu's place
rQ   r
   rR   rS   )r<   r=   r7   	gpu_procsrB   rL   rV   s          r   get_num_procsrY      s    $ x(F ))+HXI8_	2215A WII1)],5z	  %ZdN+t		s   B5 C,52C),C1)   Ngffffff?r
   FN)zN/A)r   )
__future__r   r   r   r   r   r"   r   rH   rO   r/   rY        r   <module>r^      s;    & %   	   IK15m!`.b'r]   