o
    ei$'                     @   s   U d Z ddlZddlZddlmZ ddlmZ ddlZdae	e
d< dedefdd	Zdee	 fd
dZ						dddZdefddZdefddZG dd dZdd Zdd Zd ddZdd Zdd ZdS )!zGuard for running certain operations on main process only

Authors:
 * Abdel Heba 2020
 * Aku Rouhe 2020
 * Peter Plantinga 2023
 * Adel Moumen 2024
    Nwraps)OptionalMAIN_PROC_ONLYmessagereturnc                 C   s"   t  }|durd| d|  S | S )zPrefix a message with the rank of the process.

    Arguments
    ---------
    message : str
        The message to prefix.

    Returns
    -------
    str
        The message prefixed with the rank, if known.
    Nz[rank: z] )get_rank)r   rank r
   [/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/speechbrain/utils/distributed.pyrank_prefixed_message   s   r   c                  C   s2   d} | D ]}t j|}|durt|  S qdS )a|  Get the rank of the current process.

    This code is taken from the Pytorch Lightning library:
    https://github.com/Lightning-AI/pytorch-lightning/blob/bc3c9c536dc88bfa9a46f63fbce22b382a86a9cb/src/lightning/fabric/utilities/rank_zero.py#L39-L48

    Returns
    -------
    int or None
        The rank of the current process, or None if the rank could not be determined.
    )RANK
LOCAL_RANKSLURM_PROCIDJSM_NAMESPACE_RANKN)osenvirongetint)	rank_keyskeyr	   r
   r
   r   r   '   s   r   Fc                 C   s   |du rg }|du ri }|du rg }|du ri }t | |i | t  |durB|r3||i | dS t s=||i | t  dS dS )a  Runs a function with DPP (multi-gpu) support.

    The main function is only run on the main process.
    A post_function can be specified, to be on non-main processes after the main
    func completes. This way whatever the main func produces can be loaded on
    the other processes.

    Arguments
    ---------
    func : callable
        Function to run on the main process.
    args : list, None
        Positional args to pass to func.
    kwargs : dict, None
        Keyword args to pass to func.
    post_func : callable, None
        Function to run after func has finished on main. By default only run on
        non-main processes.
    post_args : list, None
        Positional args to pass to post_func.
    post_kwargs : dict, None
        Keyword args to pass to post_func.
    run_post_on_main : bool
        Whether to run post_func on main process as well. (default: False)
    N)main_process_onlyddp_barrierif_main_process)funcargskwargs	post_func	post_argspost_kwargsrun_post_on_mainr
   r
   r   run_on_main=   s"   #
r!   c                   C   s   t j o	t j S )z2Returns whether the current system is distributed.)torchdistributedis_availableis_initializedr
   r
   r
   r   is_distributed_initializedw   s   r&   c                   C   s   t  r
tj dkS dS )z8Returns whether the current process is the main process.r   T)r&   r"   r#   r   r
   r
   r
   r   r      s   r   c                   @   s    e Zd ZdZdd Zdd ZdS )MainProcessContextz
    Context manager to ensure code runs only on the main process.
    This is useful to make sure that `MAIN_PROC_ONLY` global variable
    is decreased even if there's an exception raised inside of
    `main_proc_wrapped_func` fn.
    c                 C   s   t d7 a | S )z(Enter the context. Increase the counter.   r   )selfr
   r
   r   	__enter__   s   zMainProcessContext.__enter__c                 C   s   t d8 a dS )z'Exit the context. Decrease the counter.r(   Nr)   )r*   exc_type	exc_value	tracebackr
   r
   r   __exit__   s   zMainProcessContext.__exit__N)__name__
__module____qualname____doc__r+   r/   r
   r
   r
   r   r'      s    r'   c                    s   t   fdd}|S )zFunction decorator to ensure the function runs only on the main process.
    This is useful for things like saving to the filesystem or logging
    to a web address where you only want it to happen on a single process.
    c                     sP   t   t r | i |W  d   S 	 W d   dS 1 s!w   Y  dS )z>This decorated function runs only if this is the main process.N)r'   r   )r   r   functionr
   r   main_proc_wrapped_func   s   $z1main_process_only.<locals>.main_proc_wrapped_funcr   )r5   r6   r
   r4   r   r      s   r   c                   C   sN   t dkst s	dS tj tjjjkr tjjtj	 gd dS tj  dS )a7  
    Synchronize all processes in distributed data parallel (DDP) mode.

    This function blocks the execution of the current process until all
    processes in the distributed group have reached the same point. It ensures
    that no process moves ahead until every other process has also reached this
    barrier. If DDP is not being used (i.e., only one process is running),
    this function has no effect and immediately returns.

    Returns
    -------
    None


    Example
    -------
    >>> ddp_barrier()
    >>> print("hello world")
    hello world
    r(   N)
device_ids)
r   r&   r"   r#   get_backendBackendNCCLbarriercudacurrent_devicer
   r
   r
   r   r      s
   r   c                 C   s0   t dkst s	| S | g}tjj||d |d S )a  In DDP mode, this function will broadcast an object to all
    processes.

    Arguments
    ---------
    communication_object: Any
        The object to be communicated to all processes. Must be picklable.
        See docs for ``torch.distributed.broadcast_object_list()``
    src: int
        The rank which holds the object to be communicated.

    Returns
    -------
    The communication_object passed on rank src.
    r(   )srcr   )r   r&   r"   r#   broadcast_object_list)communication_objectr>   communication_listr
   r
   r   ddp_broadcast   s
   rB   c                 C   s&   t dkst s	| S tjj| |d | S )a`  In DDP mode, this function will perform an all_reduce operation with the
    specified torch operator.

    See: https://pytorch.org/docs/stable/distributed.html#torch.distributed.all_reduce

    Arguments
    ---------
    communication_object: Any
        The object to be reduced across processes.
    reduce_op: torch.distributed.ReduceOp
        The operation to perform. E.g. include torch.distributed.ReduceOp.AVG or
        torch.distributed.ReduceOp.SUM. See the Torch documentation for more.

    Returns
    -------
    The communication_object once reduced (or itself if DDP not initialised)
    r(   )op)r   r&   r"   r#   
all_reduce)r@   	reduce_opr
   r
   r   ddp_all_reduce   s   rF   c                 C   s&  t jd}t jd}|du s|du rdS t|}| d dks2|d tj kr2tdt  d t|}| d d	krFtj	
 sEtd
n(| d dkrVtj	 sUtdn| d dkrftj	 setdnt| d d | d d	krtd| }tj| tj	j| d |tjddd dS )a  This function will initialize the ddp group if
    distributed_launch bool is given in the python command line.

    The ddp group will use distributed_backend arg for setting the
    DDP communication protocol. `RANK` Unix variable will be used for
    registering the subprocess to the ddp group.

    Arguments
    ---------
    run_opts: list
        A list of arguments to parse, most often from `sys.argv[1:]`.

    Returns
    -------
    None
    r   r   Ndistributed_backendgloor(   zKilling process z
Not enough GPUs available!ncclz&NCCL is not supported in your machine.z&GLOO is not supported in your machine.mpiz%MPI is not supported in your machine.z& communication protocol doesn't exist.zcuda:i   )seconds)backendr	   timeout)r   r   r   r   r"   r<   device_count
ValueErrorstrr#   is_nccl_availableis_gloo_availableis_mpi_availabledevice
set_deviceinit_process_groupdatetime	timedelta)run_optsr	   
local_rankrT   r
   r
   r   ddp_init_group  sH   





r[   )NNNNNF)r   )r3   rW   r   	functoolsr   typingr   r"   r   r   __annotations__rP   r   r   r!   boolr&   r   r'   r   r   rB   rF   r[   r
   r
   r
   r   <module>   s0    	
:

