
      i"                         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 d dlmZ d dlmZ  e j$                  e      Z G d d	e      Zd
efdZd
efdZy)    N)Optional)override)ClusterEnvironment)_IS_WINDOWS)rank_zero_warn)PossibleUserWarningc                       e Zd ZdZddedeej                     ddf fdZe	e
defd              Ze	e
defd              Ze	e
defd	              Zee
defd
              Zedee   fd       Zedee   fd       Ze
defd       Ze
deddfd       Ze
defd       Ze
deddfd       Ze
defd       Ze
defd       Ze
dededdfd       Zededefd       Zedd       Zedd       Z xZS )SLURMEnvironmenta'  Cluster environment for training on a cluster managed by SLURM.

    You can configure the `main_address` and `main_port` properties via the env variables `MASTER_ADDR` and
    `MASTER_PORT`, respectively.

    Args:
        auto_requeue: Whether automatic job resubmission is enabled or not. How and under which conditions a job gets
            rescheduled gets determined by the owner of this plugin.
        requeue_signal: The signal that SLURM will send to indicate that the job should be requeued. Defaults to
            SIGUSR1 on Unix.

    Nauto_requeuerequeue_signalreturnc                     t         |           || _        |t        st        j
                  }|| _        | j                          | j                          y )N)	super__init__r   r   signalSIGUSR1r   _validate_srun_used_validate_srun_variables)selfr   r   	__class__s      /Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/lightning/fabric/plugins/environments/slurm.pyr   zSLURMEnvironment.__init__/   sG    (!+#^^N,  "%%'    c                      y)NT r   s    r   creates_processes_externallyz-SLURMEnvironment.creates_processes_externally8   s     r   c                 "   t         j                  j                  d      }|Dt         j                  j                  dd      }| j                  |      }|t         j                  d<   t        j                  dt         j                  d           |S )NMASTER_ADDRSLURM_NODELISTz	127.0.0.1zMASTER_ADDR: )osenvirongetresolve_root_node_addresslogdebug)r   	root_nodenodelists      r   main_addresszSLURMEnvironment.main_address=   sr     JJNN=1	zz~~&6DH66x@I(1BJJ}%		M"**]";!<=>r   c                 \   t         j                  j                  d      }||dd  }t        |      dz   }nd}dt         j                  v rt        t         j                  d         }nt	        |      t         j                  d<   t
        j                  dt         j                  d           |S )NSLURM_JOB_IDi:  in2  MASTER_PORTzMASTER_PORT: )r    r!   r"   intstrr$   r%   )r   job_iddefault_ports      r   	main_portzSLURMEnvironment.main_portI   s     /!"#;L|,u4L L BJJ&rzz-89L(+L(9BJJ}%		M"**]";!<=>r   c                  >    t         j                          t               S )a  Returns ``True`` if the current process was launched on a SLURM cluster.

        It is possible to use the SLURM scheduler to request resources and then launch processes manually using a
        different environment. For this, the user can set the job name in SLURM to 'bash' or 'interactive' (srun --job-
        name=interactive). This will then avoid the detection of ``SLURMEnvironment`` and another environment can be
        detected automatically.

        )r
   r   _is_srun_usedr   r   r   detectzSLURMEnvironment.detecte   s     	,,.r   c                  @    t         j                  j                  d      S )NSLURM_JOB_NAME)r    r!   r"   r   r   r   job_namezSLURMEnvironment.job_names   s    zz~~.//r   c                      t               ry t        j                  j                  d      } | y 	 t	        |       S # t
        $ r Y y w xY w)Nr*   _is_slurm_interactive_moder    r!   r"   r-   
ValueError)r/   s    r   r/   zSLURMEnvironment.job_idw   sH     &'/>	v; 		s   
: 	AAc                 :    t        t        j                  d         S NSLURM_NTASKSr-   r    r!   r   s    r   
world_sizezSLURMEnvironment.world_size       2::n-..r   sizec                 .    t         j                  d       y )Nz[SLURMEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.r$   r%   )r   rB   s     r   set_world_sizezSLURMEnvironment.set_world_size   s    		opr   c                 :    t        t        j                  d         S )NSLURM_PROCIDr?   r   s    r   global_rankzSLURMEnvironment.global_rank   rA   r   rankc                 .    t         j                  d       y )Nz]SLURMEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored.rD   )r   rI   s     r   set_global_rankz SLURMEnvironment.set_global_rank   s    		qrr   c                 :    t        t        j                  d         S )NSLURM_LOCALIDr?   r   s    r   
local_rankzSLURMEnvironment.local_rank   s    2::o.//r   c                 :    t        t        j                  d         S )NSLURM_NODEIDr?   r   s    r   	node_rankzSLURMEnvironment.node_rank   rA   r   num_devices	num_nodesc           	      ,   t               ry t        j                  j                  d      }|#t	        |      |k7  rt        d| d| d| d      t        j                  j                  d      }|$t	        |      |k7  rt        d| d| d	| d      y y )
NSLURM_NTASKS_PER_NODEzYou set `devices=zX` in Lightning, but the number of tasks per node configured in SLURM `--ntasks-per-node=z%` does not match. HINT: Set `devices=z`.SLURM_NNODESzYou set `num_nodes=zE` in Lightning, but the number of nodes configured in SLURM `--nodes=z'` does not match. HINT: Set `num_nodes=r9   )r   rR   rS   ntasks_per_nodennodess        r   validate_settingsz"SLURMEnvironment.validate_settings   s    %'**..)@A&3+?;+N#K= 1''6&77\]l\mmoq  /#f+":%i[ 1#H$KF8SUW  #;r   nodesc                     t        j                  dd|       } t        j                  dd|       } | j                  d      d   j                  d      d   S )a  The node selection format in SLURM supports several formats.

        This function selects the first host name from

        - a space-separated list of host names, e.g., 'host0 host1 host3' yields 'host0' as the root
        - a comma-separated list of host names, e.g., 'host0,host1,host3' yields 'host0' as the root
        - the range notation with brackets, e.g., 'host[5-9]' yields 'host5' as the root

        z\[(.*?)[,-].*\]z\1z	\[(.*?)\] r   ,)resubsplit)rZ   s    r   r#   z*SLURMEnvironment.resolve_root_node_address   sM     )5%8|UE2{{3"((-a00r   c                  (   t         ryt        j                  d      du} | rrt               sgdj	                  dt
        j                  j                  t        j                        gt        j                        dd }t        d| dt               yyy)aU  Checks if the `srun` command is available and used.

        Parallel jobs (multi-GPU, multi-node) in SLURM are launched by prepending `srun` in front of the Python command.
        Not doing so will result in processes hanging, which is a frequent user error. Lightning will emit a warning if
        `srun` is found but not used.

        Nsrunr\   @   zThe `srun` command is available on your system but is not used. HINT: If your intention is to run Lightning on SLURM, prepend your python command with `srun` like so: z ...)category)r   shutilwhichr3   joinr    pathbasenamesys
executableargvr   r   )srun_existshints     r   r   z$SLURMEnvironment._validate_srun_used   s     ll6*$6}88VRWW%5%5cnn%EQQRSVTVWDYY]X^^bd,  /;r   c                      t        t        j                  j                  dd            } | dkD  r%dt        j                  vrt	        d|  d|  d      yy)	a2  Checks for conflicting or incorrectly set variables set through `srun` and raises a useful error message.

        Right now, we only check for the most common user errors. See
        `the srun docs <https://slurm.schedmd.com/srun.html>`_
        for a complete list of supported srun variables.

        r>   1   rU   zYou set `--ntasks=z^` in your SLURM bash script, but this variable is not supported. HINT: Use `--ntasks-per-node=z
` instead.N)r-   r    r!   r"   RuntimeError)ntaskss    r   r   z)SLURMEnvironment._validate_srun_variables   s^     RZZ^^NC89A:1C$VH -117
D  D:r   )TN)r   N)__name__
__module____qualname____doc__boolr   r   Signalsr   propertyr   r   r.   r(   r-   r1   staticmethodr4   r7   r/   r@   rE   rH   rK   rN   rQ   rY   r#   r   r   __classcell__)r   s   @r   r
   r
   !   s!   (T ((6>>BZ (fj ( d    c    3   4 
D 
  
 0hsm 0 0 HSM   /C / / q3 q4 q q /S / / sC sD s s 0C 0 0 /3 / / S S T    1 1 1 1  (  r   r
   r   c                  @    dt         j                  v xr t                S r=   )r    r!   r:   r   r   r   r3   r3      s    RZZ'L0J0L,LLr   c                  .    t         j                         dv S )N)bashinteractive)r
   r7   r   r   r   r:   r:      s    $$&*AAAr   )loggingr    r^   re   r   rj   typingr   typing_extensionsr   9lightning.fabric.plugins.environments.cluster_environmentr   "lightning.fabric.utilities.importsr   $lightning.fabric.utilities.rank_zeror   #lightning.fabric.utilities.warningsr   	getLoggerrt   r$   r
   rx   r3   r:   r   r   r   <module>r      si     	 	   
  & X : ? Cg!) DMt MBD Br   