§
    l¬¸j  ã                  óž   — d dl m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 e	rd d	lmZ dd„Zdd„Zdd„Zdd„ZdS )é    )ÚannotationsN)ÚPath)ÚTYPE_CHECKINGé   )ÚUSER_CONFIG_DIR)Ú
torch_save)Ú	TORCH_1_9)ÚBaseTrainerÚreturnÚintc                 ó4  — ddl } ddl}|                      ¦   «                              t	          dd¦  «        d¦  «        D ]q}|                     |j        |j        ¦  «        5 }	 |                     d|f¦  «         |cddd¦  «         c S # t          $ r Y ddd¦  «         Œbw xY w# 1 swxY w Y   Œr|                     |j        |j        ¦  «        5 }|                     d¦  «         | 	                    ¦   «         d         cddd¦  «         S # 1 swxY w Y   dS )	aZ  Find a free port on localhost.

    It is useful in single-node training when we don't want to connect to a real main node but have to set the
    `MASTER_PORT` environment variable.

    Returns:
        (int): The available network port number.

    Notes:
        Candidates are drawn below the default OS ephemeral floor (32768 on Linux, 49152 on macOS and Windows)
        because the port is released here and rebound later by the DDP subprocess. An ephemeral port can be handed to
        any outbound connection in that window, which surfaces as an EADDRINUSE rendezvous failure at launch.
    r   Ni'  i €  é
   ú	127.0.0.1)r   r   r   )
ÚrandomÚsocketÚSystemRandomÚsampleÚrangeÚAF_INETÚSOCK_STREAMÚbindÚOSErrorÚgetsockname)r   r   ÚportÚss       úf/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/utils/dist.pyÚfind_free_network_portr      sÍ  € ð €M€M€MØ€M€M€Mð ×#Ò#Ñ%Ô%×,Ò,­U°5¸%Ñ-@Ô-@À"ÑEÔEð ð ˆØ�]Š]˜6œ>¨6Ô+=Ñ>Ô>ð 	À!ðØ—’˜ TÐ*Ñ+Ô+Ð+Øð	ð 	ð 	ð 	ñ 	ô 	ð 	ð 	ð 	ð 	øõ ð ð ð Øð	ð 	ð 	ñ 	ô 	ð 	ð 	ðøøøð		ð 	ð 	ð 	øøøð 	ð 	ð 	ð 	ð 	ð 
�Š�v”~ vÔ'9Ñ	:Ô	:ð "¸aØ	�ŠÐÑ Ô Ð Ø�}Š}‰Œ˜qÔ!ð"ð "ð "ð "ñ "ô "ð "ð "ð "ð "ð "ð "øøøð "ð "ð "ð "ð "ð "sB   Á!B%Á#B
Â

B"ÂB%Â!B"Â"B%Â%B)	Â,B)	Ã/DÄDÄDÚtrainerr
   Ústrc           	     ó  — ddl }t          dz                       d¬¦  «         t          j        dt          | ¦  «        › d�dd	t          dz  d
¬¦  «        5 }t          |j        ¦  «                             d¦  «        }t          t          | ¦  «        t          | j        ¦  «        | j        | j        dœ||¬¦  «         |                     dt           j        ›dt%          |¦  «        ›d�¦  «         ddd¦  «         n# 1 swxY w Y   |j        S )a#  Generate a DDP (Distributed Data Parallel) file for multi-GPU training.

    This function creates a temporary Python file that enables distributed training across multiple GPUs. The file
    contains the necessary configuration to initialize the trainer in a distributed environment.

    Args:
        trainer (ultralytics.engine.trainer.BaseTrainer): The trainer containing training configuration and arguments.
            Must have args attribute and be a class instance.

    Returns:
        (str): Path to the generated temporary DDP file.

    Notes:
        The generated file is saved in the USER_CONFIG_DIR/DDP directory and includes:
        - Trainer class and callback reconstruction
        - Configuration overrides from the trainer arguments
        - Training initialization code
    r   NÚDDPT)Úexist_okÚ_temp_ú.pyzw+zutf-8F)ÚprefixÚsuffixÚmodeÚencodingÚdirÚdeleteú.pt)r   ÚargsÚmodelÚ	callbacks)Úpickle_modulez‘
# Ultralytics Multi-GPU training temp file (should be automatically deleted after use)
if __name__ == "__main__":
    import sys
    sys.path = z‚

    from ultralytics.utils import DEFAULT_CFG_DICT
    from ultralytics.utils.patches import torch_load

    state = torch_load(a  , map_location="cpu")

    cfg = DEFAULT_CFG_DICT.copy()
    cfg.update(save_dir='')   # handle the extra key 'save_dir'
    trainer = state["trainer"](cfg=cfg, overrides=state["args"], _callbacks=state["callbacks"])
    trainer.model = state["model"]
    trainer.train()
)Úcloudpickler   ÚmkdirÚtempfileÚNamedTemporaryFileÚidr   ÚnameÚwith_suffixr   ÚtypeÚvarsr,   r-   r.   ÚwriteÚsysÚpathr   )r   r0   Úfiler;   s       r   Úgenerate_ddp_filer=   3   sw  € ð& ÐÐÐå�uÑ×#Ò#¨TÐ#Ñ2Ô2Ð2Ý	Ô	$ØÝ�W‘+”+Ð"Ð"Ð"ØØÝ˜eÑ#Øð
ñ 
ô 
ð %
ð 
Ý�D”I‰Œ×*Ò*¨5Ñ1Ô1ˆÝå ™=œ=Ý˜Wœ\Ñ*Ô*Ø œØ$Ô.ð	ð ð Ø%ð		
ñ 		
ô 		
ð 		
ð 	�
Š
ðõ ”ð	ð õ ˜D™	œ	ðð ð ñ	
ô 	
ð 	
ð'%
ð %
ð %
ñ %
ô %
ð %
ð %
ð %
ð %
ð %
ð %
øøøð %
ð %
ð %
ð %
ðL Œ9Ðs   ÁBC<Ã<D ÄD útuple[list[str], str]c                óÐ   — | j         st          j        | j        ¦  «         t	          | ¦  «        }t
          rdnd}t          ¦   «         }t          j        d|d| j	        › d|› |g}||fS )aT  Generate command for distributed training.

    Args:
        trainer (ultralytics.engine.trainer.BaseTrainer): The trainer containing configuration for distributed training.

    Returns:
        cmd (list[str]): The command to execute for distributed training.
        file (str): Path to the temporary file created for DDP training.
    ztorch.distributed.runztorch.distributed.launchz-mz--nproc_per_nodez--master_port)
ÚresumeÚshutilÚrmtreeÚsave_dirr=   r	   r   r:   Ú
executableÚ
world_size)r   r<   Údist_cmdr   Úcmds        r   Úgenerate_ddp_commandrH   r   s   € ð Œ>ð (ÝŒ�gÔ&Ñ'Ô'Ð'Ý˜WÑ%Ô%€DÝ*3ÐSÐ&Ð&Ð9S€HÝ!Ñ#Ô#€DåŒØØØØÔÐØØˆ	Øð	€Cð �ˆ9Ðó    r<   ÚNonec                óÆ   — t          | ¦  «        › d�|v rLt          j        |¦  «         t          |¦  «                             d¦  «                             d¬¦  «         dS dS )aD  Delete temporary file if created during distributed data parallel (DDP) training.

    This function checks if the provided file contains the trainer's ID in its name, indicating it was created as a
    temporary file for DDP training, and deletes it if so.

    Args:
        trainer (ultralytics.engine.trainer.BaseTrainer): The trainer used for distributed training.
        file (str): Path to the file that might need to be deleted.

    Examples:
        >>> trainer = YOLOTrainer()
        >>> file = "/tmp/ddp_temp_123456789.py"
        >>> ddp_cleanup(trainer, file)
    r$   r+   T)Ú
missing_okN)r4   ÚosÚremover   r6   Úunlink)r   r<   s     r   Úddp_cleanuprP   Ž   sd   € õ ˆW‰+Œ+ÐÐÐ˜dÐ"Ð"Ý
Œ	�$‰ŒˆÝˆT‰
Œ
×Ò˜uÑ%Ô%×,Ò,¸Ð,Ñ=Ô=Ð=Ð=Ð=ð #Ð"rI   )r   r   )r   r
   r   r   )r   r
   r   r>   )r   r
   r<   r   r   rJ   )Ú
__future__r   rM   rA   r:   r2   Úpathlibr   Útypingr   Ú r   Úpatchesr   Útorch_utilsr	   Úultralytics.engine.trainerr
   r   r=   rH   rP   © rI   r   ú<module>rY      s  ðð #Ð "Ð "Ð "Ð "Ð "à 	€	€	€	Ø €€€Ø 
€
€
€
Ø €€€Ø Ð Ð Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  à Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø "Ð "Ð "Ð "Ð "Ð "àð 7Ø6Ð6Ð6Ð6Ð6Ð6ð"ð "ð "ð "ð><ð <ð <ð <ð~ð ð ð ð8>ð >ð >ð >ð >ð >rI   