Ë
    g^(hà5  ã                   óF  — 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m	Z	m
Z
 d dlmZ d dlZd dl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 d dlmZ d dl 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/m0Z0m1Z1 g d¢Z2 G d„ de«      Z3 ede4¬«      	 	 	 	 d-de"de+de	ejj                     de6de7d e	e%   d!e!fd"„«       Z8 ed#¬$«      e/dddddd%œde"d&e
e9ejt                  df   de	e+   d e	e%   de	ejj                     de7d!e!fd'„«       «       Z; ed#¬$«      dddde3jx                  d(œde"d&e
e9ejt                  df   de	e+   d e	e%   de	ejj                     d)e3d!efd*„«       Z=de"d!e"fd+„Z>	 	 	 	 d-de"de+de	ejj                     de6de7d e	e%   d!e!fd,„Z?y).é    N)ÚFuture)ÚEnum)ÚcastÚOptionalÚUnion)Ú
deprecated)Ú_copy_state_dictÚ_create_cpu_state_dict)Ú_AsyncCheckpointExecutor)Ú$_ProcessBasedAsyncCheckpointExecutor)Ú#_ThreadBasedAsyncCheckpointExecutor)Ú_storage_setup)ÚDefaultSavePlanner)Ú_dcp_method_logger)ÚMetadataÚSTATE_DICT_TYPE)ÚSavePlanÚSavePlanner)ÚAsyncStager)ÚStateful)ÚStorageWriter)Ú_get_default_groupé   )Ú_api_bc_checkÚ_DistWrapperÚ_profile)Úsave_state_dictÚsaveÚ
async_saveÚAsyncCheckpointerTypec                   ó   — e Zd ZdZdZdZy)r    z!Enum for async checkpointer type.ÚthreadÚprocessN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚTHREADÚPROCESS© ó    úk/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/torch/distributed/checkpoint/state_dict_saver.pyr    r    '   s   „ Ù+à€FØ�Gr+   r    za`save_state_dict` is deprecated and will be removed in future versions.Please use `save` instead.)ÚcategoryFÚ
state_dictÚstorage_writerÚprocess_groupÚcoordinator_rankÚno_distÚplannerÚreturnc           	      ó‚   — |j                  «        t        «       5  t        | |||||«      cddd«       S # 1 sw Y   yxY w)z3This method is deprecated. Please switch to 'save'.N)Úresetr   Ú_save_state_dict)r.   r/   r0   r1   r2   r3   s         r,   r   r   .   sF   € ð ×ÑÔô 
‹ñ 
ÜØØØØØØó
÷
÷ 
ò 
ús   ›5µ>T)Úlog_exceptions)Úcheckpoint_idr/   r3   r0   r2   r9   c          	      óx  — t         j                  j                  d«       |xs, t        j                  «        xs t        j
                  «        }|rt        j                  d«       t        «       5  t        t        t        ||d¬«      «      }t        t        | «      ||||¬«      cddd«       S # 1 sw Y   yxY w)aÙ  
    Save a distributed model in SPMD style.

    This function is different from ``torch.save()`` as it handles
    ``ShardedTensor`` , and ``DTensor`` by having each rank only save their local shards.

    For each ``Stateful`` object (having both a ``state_dict`` and a ``load_state_dict``),
    save will call ``state_dict`` before serialization.

    .. warning::
        There is no guarantees of Backwards Compatibility across PyTorch versions
        for saved state_dicts.

    .. warning::
        If using the `process_group` argument, make sure that only its ranks
        call `save_state_dict` and that all data in state_dict belong to it.

    .. note::
        When saving checkpoint for FSDP's `ShardingStrategy.HYBRID_SHARD`, only one of
        the shard_group should be calling `save_state_dict` and the corresponding process
        group needs to be passed in.

    .. note::
        If no process group is available, this function assumes the intention is to save the
         state_dict in the local process.

    .. note:
        Rank 0 is assumed to be the coordinator rank.


    Args:
        state_dict (Dict[str, Any]): The state_dict to save.
        checkpoint_id (Union[str, os.PathLike, None]):
            The ID of this checkpoint instance. The meaning of the checkpoint_id
            depends on the storage. It can be a path to a folder or to a file.
            It can also be a key if the storage is a key-value store.
            (Default: ``None``)
        storage_writer (Optional[StorageWriter]):
            Instance of StorageWriter used to perform writes. If this is not
            specified, DCP will automatically infer the writer based on the
            checkpoint_id. If checkpoint_id is also None, an exception will
            be raised. (Default: ``None``)
        planner (Optional[SavePlanner]):
            Instance of SavePlanner. If this is not specificed, the default
            planner will be used. (Default: ``None``)
        process_group (Optional[ProcessGroup]):
            ProcessGroup to be used for cross-rank synchronization.
            (Default: ``None``)
        no_dist (bool):
            If ``True``, this function will assume the intent is to load
            a checkpoint without using cross-rank synchronization.
            (Default: ``False``)

    Returns:
        Metadata: Metadata object for the saved checkpoint.

    Example:
        >>> # xdoctest: +SKIP
        >>> my_model = MyModule()

        >>> state_dict = {"model": my_model}

        >>> fs_storage_writer = torch.distributed.checkpoint.FileSystemWriter(
        ...     "/checkpoint/1"
        ... )
        >>> torch.distributed.checkpoint.save(
        >>>     state_dict=state_dict,
        >>>     storage_writer=fs_storage_writer,
        >>> )

    .. note::
        save_state_dict uses collectives to coordinate writes across ranks.
        For NCCL-based process groups, internal tensor representations of
        objects must be moved to the GPU device before communication takes place.
        In this case, the device used is given by ``torch.cuda.current_device()``
        and it is the user's responsibility to ensure that this is set so that
        each rank has an individual GPU, via ``torch.cuda.set_device()``.
    z!torch.distributed.checkpoint.savezptorch.distributed is disabled, unavailable or uninitialized, assuming the intent is to save in a single process.F©Úreader)r.   r/   r0   r2   r3   N)ÚtorchÚ_CÚ_log_api_usage_onceÚdistÚis_availableÚis_initializedÚwarningsÚwarnr   r   r   r   r7   Ú_stateful_to_state_dict)r.   r9   r/   r3   r0   r2   s         r,   r   r   J   s¤   € ôr 
‡H�H× Ñ Ð!DÔEàÒQœd×/Ñ/Ó1Ð1ÒQ¼4×;NÑ;NÓ;PÐ7P€GÙÜ�‰Ø~ô	
ô 
‹ñ 
ÜÜœ>¨.¸-ÐPUÔVó
ˆô  Ü.¨zÓ:Ø)Ø'ØØô
÷
÷ 
ò 
ús   Á15B0Â0B9)r9   r/   r3   r0   Úasync_checkpointer_typerF   c                ó–  — t         j                  j                  d«       t        j                  «       rJt        j
                  «       r6|xs
 t        «       }t        j                  d«      |j                  v sJ d«       ‚t        t        t        ||d¬«      «      }t        | «      } t        |t        «      r|j                  | «      }nt!        | «      }t#        | |d¬«       |t$        j&                  k(  r
t)        «       n	t+        «       }|j-                  |||||¬«      }	t        |t        «      r|j.                  r|j1                  «        |	S )a  Asynchronous version of ``save``. This code first de-stages the state_dict on to the
    staging storage (defaults to CPU memory), and then calls the `save` in a separate thread.

    .. warning::
        This feature is experimental and subject to change.

    Args:
        state_dict (Dict[str, Any]): The state_dict to save.
        checkpoint_id (Union[str, os.PathLike, None]):
            The ID of this checkpoint instance. The meaning of the checkpoint_id
            depends on the storage. It can be a path to a folder or to a file.
            It can also be a key if the storage is a key-value store.
            (Default: ``None``)
        storage_writer (Optional[StorageWriter]):
            Instance of StorageWriter used to perform 'stage' and  'save'. If
            this is not specified, DCP will automatically infer the writer based on the
            checkpoint_id. If checkpoint_id is also None, an exception will
            be raised. (Default: ``None``)
        planner (Optional[SavePlanner]):
            Instance of SavePlanner. If this is not specificed, the default
            planner will be used. (Default: ``None``)
        process_group (Optional[ProcessGroup]):
            ProcessGroup to be used for cross-rank synchronization.
            (Default: ``None``)

    Returns:
        Future: A future holding the resultant Metadata object from `save`.

    Example:
        >>> # xdoctest: +SKIP
        >>> my_model = MyModule()

        >>> state_dict = {"model": my_model}

        >>> fs_storage_writer = torch.distributed.checkpoint.FileSystemWriter(
        ...     "/checkpoint/1"
        ... )
        >>> checkpoint_future = torch.distributed.checkpoint.async_save(
        >>>     state_dict=state_dict,
        >>>     storage_writer=fs_storage_writer,
        >>> )
        >>>
        >>> # ... do some work ...
        >>>
        >>> checkpoint_future.result()

    z'torch.distributed.checkpoint.async_saveÚcpuzfA CPU backend must be enabled for async save; try initializing process group with 'cpu:gloo,cuda:nccl'Fr;   )Ú
type_check)r9   r/   r3   r0   )r=   r>   r?   r@   rA   rB   r   ÚdeviceÚ_device_typesr   r   r   rE   Ú
isinstancer   Ústager
   r	   r    r)   r   r   Úexecute_saveÚ should_synchronize_after_executeÚsynchronize_staging)
r.   r9   r/   r3   r0   rF   ÚpgÚstaged_state_dictÚexecutorÚfs
             r,   r   r   ¹   s0  € ôr 
‡H�H× Ñ Ð!JÔKä×ÑÔœt×2Ñ2Ô4ØÒ2Ô0Ó2ˆä�L‰L˜Ó 2×#3Ñ#3Ñ3ð	
ð uó	
Ø3ô
 Ü”~ n°mÈEÔRó€Nô )¨Ó4€JÜ�.¤+Ô.Ø*×0Ñ0°Ó<Ñä2°:Ó>ÐÜ˜Ð%6À5ÕIð #Ô&;×&CÑ&CÒCô 	-Ô.ä0Ó2ð ð ×%Ñ%ØØ#Ø%ØØ#ð &ó €Aô 	�>¤;Ô/Ø×;Ò;à×*Ñ*Ô,à€Hr+   c                 ó„   — i }| j                  «       D ]*  \  }}t        |t        «      r|j                  «       n|||<   Œ, |S )z]Creates a shallow copy of `state_dict` where `state_dict` is called for each Stateful object.)ÚitemsrL   r   r.   )r.   Ústateful_state_dictÚkeyÚelems       r,   rE   rE     sK   € àÐØ×%Ñ%Ó'ò 
‰	ˆˆTä!+¨D´(Ô!;ˆD�O‰OÔÀð 	˜CÒ ð
ð Ðr+   c                 óÊ  ‡ ‡‡‡‡‡— t         j                  j                  d«       t        || |«      Š‰€
t	        «       Š‰€J ‚d Ši }t        ‰dd «      x}�||d<   ‰j                  |d<   t        d
i |¤Žˆˆˆ ˆfd„«       }t        d
i |¤Žˆˆˆfd„«       }	‰j                  d||	«      Št        d
i |¤Žˆˆˆfd„«       }
t        d
i |¤Žˆˆfd„«       }‰j                  d	|
|«      S )Nz,torch.distributed.checkpoint.save_state_dictr9   r0   c                  óž  •— ‰€J ‚‰j                  «       } dt        j                  ‰j                  «      j                  vr2t        j                  d«       ‰j                  ‰‰j                  «       n‰j                  ‰| ‰j                  ¬«       ‰j                  ‰j                  «       ‰j                  «       }‰j                  |«      }|S )NÚstorage_metazªThe function definition for SavePlanner.set_up_planner has been updated to include the storage_meta argument. Please update your implementation to include this parameter.)r.   r\   Úis_coordinator)r\   ÚinspectÚ	signatureÚset_up_plannerÚ
parametersrC   rD   r]   Úset_up_storage_writerÚcreate_local_planÚprepare_local_plan)r\   Ú
local_planÚdistWr3   r.   r/   s     €€€€r,   Ú
local_stepz$_save_state_dict.<locals>.local_step>  sÁ   ø€ àÐ"Ð"Ð"Ø%×2Ñ2Ó4ˆØ¤×!2Ñ!2°7×3IÑ3IÓ!J×!UÑ!UÑUÜ�M‰Mð.ôð
 ×"Ñ" :¨u×/CÑ/CÕDà×"Ñ"Ø%Ø)Ø$×3Ñ3ð #ô ð
 	×,Ñ,¨U×-AÑ-AÔBà×.Ñ.Ó0ˆ
Ø#×6Ñ6°zÓBˆ
ØÐr+   c                 óZ   •— ‰€J ‚‰j                  | «      \  } Š‰j                  | «      } | S ©N)Úcreate_global_planÚprepare_global_plan)Úall_local_plansÚglobal_metadatar3   r/   s    €€€r,   Úglobal_stepz%_save_state_dict.<locals>.global_stepU  s<   ø€ ð Ð"Ð"Ð"Ø+2×+EÑ+EÀoÓ+VÑ(ˆ˜Ø(×<Ñ<¸_ÓMˆØÐr+   Úplanc                  ó’   •— ‰€J ‚‰j                  ‰«      } ‰j                  | ‰«      }|j                  «        |j                  «       S ri   )Úfinish_planÚ
write_dataÚwaitÚvalue)Úfinal_local_planÚ
all_writesÚcentral_planr3   r/   s     €€€r,   rr   z$_save_state_dict.<locals>.write_data`  sL   ø€ àÐ"Ð"Ð"Ø"×.Ñ.¨|Ó<ÐØ#×.Ñ.Ð/?ÀÓIˆ
à�‰ÔØ×ÑÓ!Ð!r+   c                 ó6   •— ‰€J ‚‰j                  ‰| ¬«       ‰S )N)ÚmetadataÚresults)Úfinish)Úall_resultsrm   r/   s    €€r,   Úfinish_checkpointz+_save_state_dict.<locals>.finish_checkpointi  s(   ø€ àÐ*Ð*Ð*Ø×Ñ ÀÐÔLØÐr+   Úwriter*   )
r=   r>   r?   r   r   ÚgetattrÚgroupr   Úreduce_scatterÚ
all_reduce)r.   r/   r0   r1   r2   r3   Úckpt_kwargsÚckpt_idrg   rn   rr   r}   rw   rf   rm   s   ``   `      @@@r,   r7   r7   (  s  ý€ ô 
‡H�H× Ñ Ð!OÔPä˜¨G¨Ð5EÓF€EØ€Ü$Ó&ˆØÐÐÐà€Oà€KÜ˜>¨?¸DÓAÐAˆÐNØ'.ˆ�OÑ$Ø',§{¡{ˆ�OÑ$äÑ&˜+Ñ&öó 'ðô, Ñ&˜+Ñ&õó 'ðð #×1Ñ1°&¸*ÀkÓR€LäÑ&˜+Ñ&õ"ó 'ð"ô Ñ&˜+Ñ&ôó 'ðð
 ×Ñ˜G ZÐ1BÓCÐCr+   )Nr   FN)@r^   ÚosrC   Úconcurrent.futuresr   Úenumr   Útypingr   r   r   Útyping_extensionsr   r=   Útorch.distributedÚdistributedr@   Ú#torch.distributed._state_dict_utilsr	   r
   Ú,torch.distributed.checkpoint._async_executorr   Ú4torch.distributed.checkpoint._async_process_executorr   Ú3torch.distributed.checkpoint._async_thread_executorr   Ú+torch.distributed.checkpoint._storage_utilsr   Ú,torch.distributed.checkpoint.default_plannerr   Ú#torch.distributed.checkpoint.loggerr   Ú%torch.distributed.checkpoint.metadatar   r   Ú$torch.distributed.checkpoint.plannerr   r   Ú$torch.distributed.checkpoint.stagingr   Ú%torch.distributed.checkpoint.statefulr   Ú$torch.distributed.checkpoint.storager   Ú"torch.distributed.distributed_c10dr   Úutilsr   r   r   Ú__all__r    ÚFutureWarningÚProcessGroupÚintÚboolr   ÚstrÚPathLiker   r(   r   rE   r7   r*   r+   r,   ú<module>r¡      sÀ  ðó Û 	Û Ý %Ý ß (Ñ (Ý (ã Ý  ß Xõõõõ GÝ KÝ Bß Kß FÝ <Ý :Ý >Ý Aç 8Ñ 8ò M€ô˜Dô ñ ð!àôð 26ØØØ%)ñ
Øð
à!ð
ð ˜D×-Ñ-Ñ.ð
ð ð	
ð
 ð
ð �kÑ"ð
ð ò
óð

ñ.  4Ô(Øð 48Ø.2Ø%)Ø15Øòj
Øðj
ð ˜˜bŸk™k¨4Ð/Ñ0ðj
ð ˜]Ñ+ð	j
ð
 �kÑ"ðj
ð ˜D×-Ñ-Ñ.ðj
ð ðj
ð òj
ó ó )ðj
ñZ  4Ô(ð 48Ø.2Ø%)Ø15Ø5J×5QÑ5QòaØðað ˜˜bŸk™k¨4Ð/Ñ0ðað ˜]Ñ+ð	að
 �kÑ"ðað ˜D×-Ñ-Ñ.ðað 3ðað òaó )ðaðH¨ð ¸Oó ð 26ØØØ%)ñGDØðGDà!ðGDð ˜D×-Ñ-Ñ.ðGDð ð	GDð
 ðGDð �kÑ"ðGDð ôGDr+   