o
    oi$                     @   s  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m	Z	m
Z
 d dlZd dlmZ d dlmZ d dlmZmZmZ d dlmZ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 !e"Z#edZ$edZ%dZ&de	e' fddZ(e$rAd dl)Z)dQddZ*e)+ dQddZ,e,j-dddide)j.de)j/ddde)j0de)1e&ddd e)j0d!e)1e( dd"d e)j0d#e'd$d%d e)j0d&d'e2d(d)d e)j0d*d+e2d d,d e)j0d-d.e'd/d0d e)j0d1d2e2d3d4d e)j0d5e)1eeee dd6d e)j.d7d8e)j3d9d:eddfd;d<Z4e,j-d=ddide)j.d>e)j/ddde)j0d?e)j/dddd@d d>e'dAe
e' ddfdBdCZ5dDeddfdEdFZ6dGe'dHe'de2fdIdJZ7dDed7e	e' ddfdKdLZ8dRdDed7e
e	e'  ddfdMdNZ9e"dOkre$se#:dP e;d(e4  dS dS )S    N)	Namespace)AnyListOptional)RequirementCache)get_args)CPUAcceleratorCUDAAcceleratorMPSAccelerator)_PRECISION_INPUT_STR_PRECISION_INPUT_STR_ALIAS)STRATEGY_REGISTRY)_process_cli_args)_parse_gpu_ids)_suggested_max_num_threads)_load_distributed_checkpointclicklightning_sdk)cpugpucudampstpureturnc                     s   t  } d  fdd| D S )zReturns strategy choices from the registry, with the ones removed that are incompatible to be launched from the
    CLI or ones that require further configuration by the user.z).*(spawn|fork|notebook|xla|tpu|offload).*c                    s   g | ]
}t  |s|qS  )rematch).0strategyexcludedr   R/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/lightning_fabric/cli.py
<listcomp>/   s    z-_get_supported_strategies.<locals>.<listcomp>)r   available_strategies)r#   r   r   r!   _get_supported_strategies*   s   r$   c                  C   sf   t jdd } t| dkr"| d dkr"| d dkr"td t  dS tr1tt jdd	g|   dS dS )
zLegacy CLI handler for fabric.

        Raises deprecation warning and runs through fabric cli if necessary, else runs the entrypoint directly

           N   r   runmodelzm`lightning run model` is deprecated and will be removed in future versions. Please call `fabric run` instead.z-mzlightning_sdk.cli.entrypoint)	sysargvlenprint_main_LIGHTNING_SDK_AVAILABLE
subprocessr'   
executable)hparamsr   r   r!   _legacy_main5   s   $r2   c                   C   s   d S Nr   r   r   r   r!   r-   H   s   r-   r'   ignore_unknown_optionsT)context_settingsscript)exists)typez--acceleratorz#The hardware accelerator to run on.)r8   defaulthelpz
--strategyz0Strategy for how to run across multiple devices.z	--devices1zNumber of devices to run on (``int``), which devices to run on (``list`` or ``str``), or ``'auto'``. The value applies per node.z--num-nodesz--num_nodesr%   z5Number of machines (nodes) for distributed execution.z--node-rankz--node_rankzrThe index of the machine (node) this command gets started on. Must be a number in the range 0, ..., num_nodes - 1.z--main-addressz--main_addressz	127.0.0.1zTThe hostname or IP address of the main machine (usually the one with node_rank = 0).z--main-portz--main_portir  z-The main port to connect to the main machine.z--precisionzDouble precision (``64-true`` or ``64``), full precision (``32-true`` or ``64``), half precision (``16-mixed`` or ``16``) or bfloat16 precision (``bf16-mixed`` or ``bf16``)script_args)nargsr8   kwargsc                  K   s*   t | dg }ttdi | |d dS )a  Run a Lightning Fabric script.

        SCRIPT is the path to the Python script with the code to run. The script must contain a Fabric object.

        SCRIPT_ARGS are the remaining arguments that you can pass to the script itself and are expected to be parsed
        there.

        r<   argsr<   Nr   )listpopmainr   )r?   r<   r   r   r!   _runL   s   QrE   consolidatecheckpoint_folderz--output_filezPath to the file where the converted checkpoint should be saved. The file should not already exist. If no path is provided, the file will be saved next to the input checkpoint folder with the same name and a '.consolidated' suffix.output_filec                 C   s0   t | |d}t|}t|j}t||j dS )zConvert a distributed/sharded checkpoint into a single file that can be loaded with `torch.load()`.

        Only supports FSDP sharded checkpoints at the moment.

        )rG   rH   N)r   r   r   rG   torchsaverH   )rG   rH   rA   config
checkpointr   r   r!   _consolidate   s   
rM   rA   c                 C   s   dt jd< | jdurt| jt jd< | jdurt| jt jd< t| jt jd< t| jt jd< | jdur>t| jt jd< dS dS )	zwSet the environment variables for the new processes.

    The Fabric connector will parse the arguments set here.

    r;   LT_CLI_USEDNLT_ACCELERATORLT_STRATEGY
LT_DEVICESLT_NUM_NODESLT_PRECISION)osenvironacceleratorstrr   devices	num_nodes	precision)rA   r   r   r!   _set_env_variables   s   



r[   rV   rX   c                 C   sn   | dkrt |ddd}n!| dkrt|}n| dkr t|}n| dkr(tdt|S |dur5t|S d	S )
zhParse the `devices` argument to determine how many processes need to be launched on the current machine.r   T)include_cudainclude_mpsr   r   r   z=Launching processes for TPU through the CLI is not supported.Nr   )r   r	   parse_devicesr
   
ValueErrorr   r+   )rV   rX   parsed_devicesr   r   r!   _get_num_processes   s   
ra   c                 C   s   ddl m  m} | jdkrdnt| j| j}d| d| j d| j d| j	 d	| j
 | jg}|| tjd
tt  || dS )zYThis will invoke `torchrun` programmatically to launch the given script in new processes.r   Ndpr%   z--nproc_per_node=z	--nnodes=z--node_rank=z--master_addr=z--master_port=OMP_NUM_THREADS)torch.distributed.rundistributedr'   r   ra   rV   rX   rY   	node_rankmain_address	main_portr6   extendrT   rU   
setdefaultrW   r   rD   )rA   r<   torchrunnum_processestorchrun_argsr   r   r!   _torchrun_launch   s   




rn   c                 C   s   t |  t| |p	g  d S r3   )r[   rn   r@   r   r   r!   rD      s   rD   __main__zoTo use the Lightning Fabric CLI, you must have `click` installed. Install it by running `pip install -U click`.)r   Nr3   )<loggingrT   r   r/   r)   argparser   typingr   r   r   rI    lightning_utilities.core.importsr   typing_extensionsr   lightning_fabric.acceleratorsr   r	   r
   ,lightning_fabric.plugins.precision.precisionr   r   lightning_fabric.strategiesr   1lightning_fabric.utilities.consolidate_checkpointr   (lightning_fabric.utilities.device_parserr   &lightning_fabric.utilities.distributedr   lightning_fabric.utilities.loadr   	getLogger__name___log_CLICK_AVAILABLEr.   _SUPPORTED_ACCELERATORSrW   r$   r   r2   groupr-   commandargumentPathoptionChoiceintUNPROCESSEDrE   rM   r[   ra   rn   rD   error
SystemExitr   r   r   r!   <module>   s   



	
	(

 
 

