Ë
    g^(h–0  ã                   ó¸  — d dl Z d dlZd dlmZ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 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 ddlmZmZmZ ddgZ  ede!¬«      	 	 	 	 d#de"e#ef   dedeejH                     de%de&dee   ddfd„«       Z' ed¬«      eddddddœde"e#ef   dee#e jP                  df   dee   dee   deejH                     de&ddfd„«       «       Z)	 	 	 	 d#de"e#ef   dedeejH                     de%de&dee   ddfd„Z*	 d$dddd œd!eee+e#   e#f      dee#e jP                  df   dee   deejH                     de"e#ef   f
d"„Z,y)%é    N)ÚAnyÚcastÚOptionalÚUnion)Ú
deprecated)Ú_EmptyStateDictLoadPlanner)Ú_dcp_method_logger)ÚStatefulé   )Ú_storage_setup)ÚDefaultLoadPlanner)ÚLoadPlanÚLoadPlanner)ÚStorageReader)Ú_api_bc_checkÚ_DistWrapperÚ_profileÚload_state_dictÚloadzb`load_state_dict` is deprecated and will be removed in future versions. Please use `load` instead.)ÚcategoryFÚ
state_dictÚstorage_readerÚ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 'load'.N)Úresetr   Ú_load_state_dict)r   r   r   r   r   r   s         úl/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/torch/distributed/checkpoint/state_dict_loader.pyr   r      sD   € ð ×ÑÔÜ	‹ñ 	
äØØØØØØó
÷	
÷ 	
ò 	
ús   ›5µ>T)Úlog_exceptions)Úcheckpoint_idr   r   r   r   r#   c          	      óH  — |xs, t        j                  «        xs t        j                  «        }|rt        j                  d«       t        «       5  t        t        t        ||d¬«      «      }t        | j                  «       «      }i }|D ]1  }|| vrŒ| |   }	t        |	t        «      r|	j                  «       n|	||<   Œ3 t        |||||¬«       |D ]9  }|| vrŒ| |   }	t        |	t        «      r|	j                  ||   «       Œ2||   | |<   Œ; 	 ddd«       y# 1 sw Y   yxY w)a.  
    Load a checkpoint into a distributed state dict in SPMD style.

    Each rank must have the same keys in their ``state_dict`` provided to this
    API. Mismatched keys may result in hangs or errors. If unsure, you can use
    the ``utils._assert_same_keys`` API to check (but may incur communication
    costs).

    Each rank will try to read the least amount of data necessary
    to fulfill the requested `state_dict`. When loading :class:`ShardedTensor`
    or :class:`DTensor` instances, each rank only reads data for their local shards.

    For each ``Stateful`` object (having both a ``state_dict`` and a ``load_state_dict``),
    load will first call ``state_dict`` before attempting deserialization, followed by
    ``load_state_dict`` once the deserialization is complete.
    For each non-``Stateful`` object, load will deserailize the object, and then replace
    it in the ``state_dict`` with the deserialized object.

    .. warning::
        All tensors in ``state_dict`` must be allocated on their
        destination device *prior to* calling this function.

        All non-tensor data is loaded using `torch.load()` and modified in place
        on state_dict.

    .. warning::
        Users must call `load_state_dict` on the root module to ensure load
        pos-processing and non-tensor data properly propagates.

    .. note:
        If no process group is initialized, this function will assume the intent
        is to load a checkpoint into the local process. This can be useful in the
        case of local inference, and when using regular Tensors (as opposed to DTensor
         or ShardedTensor)

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

    Args:
        state_dict (Dict[str, Any]): The state_dict to load the checkpoint into.
        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_reader (Optional[StorageReader]):
            Instance of StorageWriter used to perform reads. If this is not
            specified, DCP will automatically infer the reader based on the
            checkpoint_id. If checkpoint_id is also None, an exception will
            be raised. (Default: ``None``)
        planner (Optional[LoadPlanner]):
            Instance of LoadPlanner. 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:
        None.

    Examples
        >>> # xdoctest: +SKIP
        >>> my_model = MyModule()
        >>> optimizer = Adagrad(my_model.parameters())
        >>> model_state_dict = my_model.state_dict()
        >>> fs_storage_reader = torch.distributed.checkpoint.FileSystemReader(
        ...     "/checkpoint/1"
        ... )

        >>> torch.distributed.checkpoint.load_state_dict(
        >>>     state_dict=model_state_dict,
        >>>     storage_reader=fs_storage_reader,
        >>> )

        >>> # module.load_state_dict() function might have customized steps
        >>> # to flush the state_dict, must call it to
        >>> # ensure correct behavior.
        >>> my_model.load_state_dict(model_state_dict)

    .. note::
        load_state_dict uses collectives to coordinate reads 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()``.
    zptorch.distributed is disabled, unavailable or uninitialized, assuming the intent is to load in a single process.T©Úreader©r   r   r   r   r   N)ÚdistÚis_availableÚis_initializedÚwarningsÚwarnr   r   r   r   ÚsortedÚkeysÚ
isinstancer
   r   r    r   )
r   r#   r   r   r   r   r.   Ústatetful_sdÚkeyÚelems
             r!   r   r   3   s:  € ðH ÒQœd×/Ñ/Ó1Ð1ÒQ¼4×;NÑ;NÓ;PÐ7P€GÙÜ�‰Ø~ô	
ô 
‹ñ %4ÜÜœ>¨.¸-ÐPTÔUó
ˆô �j—o‘oÓ'Ó(ˆàˆØò 	ˆCØ˜*Ñ$ØØ˜c‘?ˆDä%/°´hÔ%?�—‘Ô!ÀTð ˜Òð		ô 	Ø#Ø)Ø'ØØõ	
ð ò 
	4ˆCØ˜*Ñ$ØØ˜c‘?ˆDÜ˜$¤Ô)ð ×$Ñ$ \°#Ñ%6Õ7ð #/¨sÑ"3�
˜3’ñ
	4÷7%4÷ %4ñ %4ús   ÁB<DÄD!c                 ó’  ‡ ‡‡‡‡— t         j                  j                  d«       t        || |«      Š‰€
t	        «       Š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„«       }
‰j                  d|
«      }y )
Nz,torch.distributed.checkpoint.load_state_dictr#   r   c                  óä   •— ‰€J ‚‰j                  «       } ‰j                  ‰| ‰j                  «       ‰j                  | ‰j                  «       ‰j	                  «       }‰j                  |«      }|S ©N)Úread_metadataÚset_up_plannerÚis_coordinatorÚset_up_storage_readerÚcreate_local_planÚprepare_local_plan)ÚmetadataÚ
local_planÚdistWr   r   r   s     €€€€r!   Ú
local_stepz$_load_state_dict.<locals>.local_stepØ   so   ø€ àÐ"Ð"Ð"Ø!×/Ñ/Ó1ˆØ×Ñ˜z¨8°U×5IÑ5IÔJØ×,Ñ,¨X°u×7KÑ7KÔLà×.Ñ.Ó0ˆ
Ø#×6Ñ6°zÓBˆ
ØÐó    c                 óT   •— ‰€J ‚‰j                  | «      } ‰j                  | «      } | S r5   )Úcreate_global_planÚprepare_global_plan)Úall_local_plansr   r   s    €€r!   Úglobal_stepz%_load_state_dict.<locals>.global_stepã   s5   ø€ àÐ"Ð"Ð"Ø!×4Ñ4°_ÓEˆØ(×<Ñ<¸_ÓMˆØÐr@   Úplanc                  ót   •— ‰€J ‚‰j                  ‰«      } ‰j                  | ‰«      }|j                  «        y r5   )Úfinish_planÚ	read_dataÚwait)Úfinal_local_planÚ	all_readsÚcentral_planr   r   s     €€€r!   rI   z#_load_state_dict.<locals>.read_dataì   s@   ø€ àÐ"Ð"Ð"Ø"×.Ñ.¨|Ó<ÐØ"×,Ñ,Ð-=¸wÓGˆ	à�‰ÔØr@   Úread© )
ÚtorchÚ_CÚ_log_api_usage_oncer   r   ÚgetattrÚgroupr	   Úreduce_scatterÚ
all_gather)r   r   r   r   r   r   Úckpt_kwargsÚckpt_idr?   rE   rI   Ú_rM   r>   s   ``   `      @@r!   r    r    Å   sá   ü€ ô 
‡H�H× Ñ Ð!OÔPä˜¨G¨Ð5EÓF€EØ€Ü$Ó&ˆà€KÜ˜>¨?¸DÓAÐAˆÐNØ'.ˆ�OÑ$Ø',§{¡{ˆ�OÑ$äÑ&˜+Ñ&öó 'ðô Ñ&˜+Ñ&ôó 'ðð #×1Ñ1°&¸*ÀkÓR€LäÑ&˜+Ñ&õó 'ðð 	×Ñ˜ Ó+�Ar@   )r#   r   r   r.   c          
      óv  — t         j                  j                  d«       t        j                  «       xr t        j
                  «        }|rt        j                  d«       t        t        t        ||d¬«      «      }t        | t        «      r| h} i }t        ||||t        | xs
 t        «       ¬«      ¬«       |S )a�  
    Load only the specified keys from the checkpoint, if no keys are specified, the entire
    checkpoint will be loaded. Note, this method completely loads the checkpoint into the
    current process and is not distributed.

    .. warning::


    .. warning::

        All non-tensor data is loaded using `torch.load()`

    .. note:
        As opposed to the usual pattern, this function does not take a state dict as input
        and does not load inplace. Instead, a new state dict is directly initialized and read
        from file.

    .. note:
        If no process group is initialized, this function will assume the intent
        is to load a checkpoint into the local process. This can be useful in the
        case of local inference, and when using regular Tensors (as opposed to DTensor
         or ShardedTensor)

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

    Args:
        keys (Optional[Union[set[str], str]]):
            Loads any key specified in this set. If no keys are specified, the entire checkpoint
            is loaded.
        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_reader (Optional[StorageReader]):
            Instance of StorageWriter used to perform reads. If this is not
            specified, DCP will automatically infer the reader based on the
            checkpoint_id. If checkpoint_id is also None, an exception will
            be raised. (Default: ``None``)
        process_group (Optional[ProcessGroup]):
            ProcessGroup to be used for cross-rank synchronization.
            (Default: ``None``)

    Returns:
        State dict from specified keys
    z7torch.distributed.checkpoint._load_state_dict_from_keyszftorch.distributed is unavailable or uninitialized, assuming the intent is to load in a single process.Tr%   )r.   r'   )rP   rQ   rR   r(   r)   r*   r+   r,   r   r   r   r/   Ústrr    r   Úset)r.   r#   r   r   r   Úsds         r!   Ú_load_state_dict_from_keysr^   ø   s¨   € ôl 
‡H�H× Ñ ØAôô ×$Ñ$Ó&Ò@¬4×+>Ñ+>Ó+@ÐA€GÙÜ�‰Øtô	
ô Ü”~ n°mÈDÔQó€Nô �$œÔØˆvˆà€BÜØØ%Ø#ØÜ*°²¼»Ô>õð €Ir@   )Nr   FNr5   )-Úosr+   Útypingr   r   r   r   Útyping_extensionsr   rP   Útorch.distributedÚdistributedr(   Ú,torch.distributed.checkpoint.default_plannerr   Ú#torch.distributed.checkpoint.loggerr	   Ú%torch.distributed.checkpoint.statefulr
   Ú_storage_utilsr   Údefault_plannerr   r   r   r   Ústorager   Úutilsr   r   r   Ú__all__ÚFutureWarningÚdictr[   ÚProcessGroupÚintÚboolr   ÚPathLiker   r    r\   r^   rO   r@   r!   ú<module>rr      sr  ðó 
Û ß -Ó -Ý (ã Ý  Ý SÝ BÝ :å *Ý /ß *Ý "ß 8Ñ 8ð ˜fÐ
%€ñ ð!àôð 26ØØØ%)ñ
Ø�S˜#�X‘ð
à!ð
ð ˜D×-Ñ-Ñ.ð
ð ð	
ð
 ð
ð �kÑ"ð
ð 
ò
óð

ñ,  4Ô(Øð 48Ø.2Ø%)Ø15ØòM4Ø�S˜#�X‘ðM4ð ˜˜bŸk™k¨4Ð/Ñ0ðM4ð ˜]Ñ+ð	M4ð
 �kÑ"ðM4ð ˜D×-Ñ-Ñ.ðM4ð ðM4ð 
òM4ó ó )ðM4ðf 26ØØØ%)ñ0,Ø�S˜#�X‘ð0,à!ð0,ð ˜D×-Ñ-Ñ.ð0,ð ð	0,ð
 ð0,ð �kÑ"ð0,ð 
ó0,ðh ,0ðPð 48Ø.2Ø15òPØ
�5˜˜S™ 3˜Ñ'Ñ
(ðPð ˜˜bŸk™k¨4Ð/Ñ0ðPð ˜]Ñ+ð	Pð
 ˜D×-Ñ-Ñ.ðPð 
ˆ#ˆsˆ(�^ôPr@   