a
    ha3                     @   s  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 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mZmZmZmZ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,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 e7e8e9eee:  ee: f f Z;dgZ<d*e:e8e8dddZ=d+ee
j> edddZ?ej@eAdddZBd,eee: e8ej@d d!d"ZCee9e;ee
j> f d#d$d%ZDG d&d' d'eZEd-ee8e*ee# ed(d)dZFdS ).    N)Sequence)castOptionalUnion)_get_device_module)ShardedTensor)TensorProperties)Shard)ChunkShardingSpec)unflatten_state_dict)DefaultLoadPlanner)BytesStorageMetadataChunkStorageMetadataMetadataMetadataIndexSTATE_DICT_TYPEr   TensorStorageMetadata)LoadPlanLoadPlanner)_create_read_items create_read_items_for_chunk_list)load_state_dict)StorageReader)_element_wise_add_element_wise_sub_normalize_device_info)_get_default_group)_create_chunk_sharded_tensor)_remote_device)DTensor!load_sharded_optimizer_state_dictcuda)global_rankdevice_typereturnc                 C   s2   |dkrdS t |}| r.t|| |  S dS )Ncpu)r   Zis_availabler   device_count)r"   r#   device_module r(   T/var/www/auris/lib/python3.9/site-packages/torch/distributed/checkpoint/optimizer.py_gen_rank_device6   s    r*   )pgr$   c                    sl   t j j d u r2fddtt  D }n fddt  D }tdtt	t
ttf  |dS )Nc                    s"   g | ]}d | dt |  qS rank:/)r*   .0idx)pg_device_typer(   r)   
<listcomp>F   s   z(_create_colwise_spec.<locals>.<listcomp>c              
      s*   g | ]"}d | dt t | qS r,   )r*   distZget_global_rankr/   r+   r2   r(   r)   r3   K   s   r   Zdim
placements)r4   distributed_c10d_get_pg_default_devicetyperangeget_world_sizesizer
   r   listr   r   str)r+   r7   r(   r5   r)   _create_colwise_specA   s    


r@   )valr$   c                 C   s   t | tu rZt|  dkr dS t |  d jtu r:dS t |  d jtu rtdn0t | tu rt | jtu st | jtu rtddS )Nr   FTz1Cannot handle DTensor nested inside ShardedTensorzCannot handle nested DTensor)r:   r   lenlocal_shardstensorr   
ValueErrorZ_local_tensor)rA   r(   r(   r)   _is_nested_tensorU   s    
rF   )propsr=   r#   r$   c                 C   sP   |dkrt tjt| }nt|t| }tj|| j| j| j| j	|dS )Nr%   )r=   dtypelayoutrequires_grad
pin_memorydevice)
r   torchrL   r   Zcurrent_deviceemptyrH   rI   rJ   rK   )rG   r=   r#   rL   r(   r(   r)   _alloc_tensord   s    rO   )
state_dictr$   c                 C   s   i }d}|   D ]r\}}d| f||< t|rt| dksHJ dt|tsZJ d| d }|jj|jj	f||< |j
j}q||fS )a+  
    Load the right TP slice of the optimizer state.

    This is not easy since the per-tensor slicing can't be inferred from checkpoint metadata.
    We take advantage of the model state_dict producing a sliced ST to figure out what we need to load.
    This is pretty fragile and it might be easier for FSDP to compute this info for us.
    Returns a dictionary where keys are the same of the state_dict and the value is a tuple of
    (offset, size) for the current rank TP slice.
    N.B. The state_dict *MUST* come from FSDP.sharded_state_dict.
    N   z%Cannot handle ST with multiple shardsz$Can only handle nested ShardedTensorr   )itemsr=   rF   rB   rC   
isinstancer   metadatashard_offsetsshard_sizesrD   Z_process_group)rP   specsdp_pgkeyvalueZshardr(   r(   r)   _get_state_dict_2d_layoutx   s&    
r[   c                       sv   e Zd ZU eeef ed< eed< eed< eee	e
 f dd fddZedd	d
Zeejd fddZ  ZS )_ReaderWithOffsettranslationrP   rT   N)fqn_to_offsetr$   c                    s*   t    || _ti | _i | _i | _d S N)super__init__r^   r   rT   rP   r]   )selfr^   	__class__r(   r)   ra      s
    

z_ReaderWithOffset.__init__)r$   c                 C   s"  g }i | _ | j D ]\}}| jj| }t|tsF|t|||7 }q|| jvrb|t|||7 }q| j| }t	|
 dksJ |
 d }ttt|jj|t|jjdg}t|tt||}|D ]D}	|	jjd usJ t|	jj|}
tj|	jt|
d}|| j |	j< q||7 }qt|S )NrQ   r   )offsetssizes)offset)r]   rP   rR   rT   state_dict_metadatarS   r   r   r^   rB   rC   r   rM   Sizer   rU   rV   r   r   r   Z
dest_indexrg   r   dataclassesreplacer   )rb   requestsZfqnobjZmdrg   Zoriginal_shardZlocal_chunksreqsriZoriginal_offsetZoriginal_indexr(   r(   r)   create_local_plan   s@    


	
z#_ReaderWithOffset.create_local_plan)indexr$   c                    s   t  | j||S r_   )r`   lookup_tensorr]   get)rb   rq   rc   r(   r)   rr      s    z_ReaderWithOffset.lookup_tensor)__name__
__module____qualname__dictr   __annotations__r   r   r?   r   intra   r   rp   rM   Tensorrr   __classcell__r(   r(   rc   r)   r\      s   
 *r\   )model_state_dictoptimizer_keystorage_readerplannerr$   c              	   C   sX  |  }t| \}}tj|j}t|}|du r~g }	tt D ],}
t	||
|
  }|	d|
 d|  qBtd|	d}nt|}i }i }|j D ]\}}|j| }|d |krqt|trd||< q|j dkrt|j|j|||< q|du r.tt|j|j|t t |
 t d||< q|d	 }||d|jfd }t|jj|jj|jj|jj|jj d
}|!t"#||}g }t|}|j$D ]>}t%t&|j'( |krq|t)t|j|j*||d qt+j,|||d}||v r|| d durt%t-t. || d ||< |||< qt/|||dur@t0|n|d t1||j}|S )a  
    Load a state_dict in conjunction with FSDP sharded optimizer state.

    This is the current recommended way to checkpoint FSDP.
    >>> # xdoctest: +SKIP
    >>> import torch.distributed.checkpoint as dist_cp
    >>> # Save
    >>> model: torch.nn.Model
    >>> optim_params = model.parameters()
    >>> optim = torch.optim.SGD(optim_params, lr=0.01)
    >>> # Save
    >>> with FSDP.state_dict_type(model, StateDictType.SHARDED_STATE_DICT):
    >>>     state_dict = {
    >>>         "optimizer": FSDP.optim_state_dict(model, optim),
    >>>         "model": model.state_dict()
    >>>     }
    >>>     dist_cp.save_state_dict(
    >>>         state_dict=optim_state,
    >>>         storage_writer=dist_cp.FileSystemWriter("checkpoint"),
    >>>         planner=dist_cp.DefaultSavePlanner(),
    >>>     )
    >>>
    >>> # Load
    >>> with FSDP.state_dict_type(model_tp, StateDictType.SHARDED_STATE_DICT):
    >>>     model_state_dict = model_tp.state_dict()
    >>>     checkpoint = {
    >>>         "model": model_state_dict
    >>>     }
    >>>     dist_cp.load_state_dict(
    >>>         state_dict=checkpoint,
    >>>         storage_reader=dist_cp.FileSystemReader(checkpoint_file),
    >>>         planner=dist_cp.DefaultLoadPlanner(),
    >>>     )
    >>>     model.load_state_dict(checkpoint["model_state"])
    >>>
    >>>     optim_state = dist_cp.load_sharded_optimizer_state_dict(
    >>>         model_state_dict,
    >>>         optimizer_key="optimizer",
    >>>         storage_reader=dist_cp.FileSystemReader("checkpoint"),
    >>>     )
    >>>
    >>>     flattened_osd = FSDP.optim_state_dict_to_load(
    >>>        model, optim, optim_state["optimizer"]
    >>>     )
    >>>
    >>>     optim.load_state_dict(flattened_osd)
    Nr-   r.   r   r6   z
<bytes_io>rQ   )rankZ
world_sizeZnum_devices_per_noder+      )rH   rI   rJ   memory_formatrK   )rD   rT   )Zprocess_group)rP   r~   r   )2Zread_metadatar[   r4   r8   r9   r:   r   r;   r<   r   r&   appendr
   r@   rh   rR   Zplanner_datarS   r   r=   ZnumelrO   
propertiesr   Zget_rankr   rs   ShardTensorPropertiesrH   rI   rJ   r   rK   Zbuild_metadatarM   ri   Zshards_metadatar   r   Z	placementr   r	   rV   r   Z+_init_from_local_shards_and_global_metadatar   ry   r   r\   r   )r|   r}   r~   r   rT   Zlayout_specsrX   Zdp_pg_device_typer'   r7   iZdevice_infoZsharding_specrP   r^   rY   rZ   Zkey_pathZspec_keyZ
alloc_sizer   Zst_mdrC   Zcurrent_rankZshard_mdstr(   r(   r)   r       s    5







	
)r!   )N)r!   )N)Grj   collections.abcr   typingr   r   r   rM   Ztorch.distributedZdistributedr4   Ztorch._utilsr   Z+torch.distributed._shard.sharded_tensor.apir   Z0torch.distributed._shard.sharded_tensor.metadatar   r   Z-torch.distributed._shard.sharded_tensor.shardr	   Z:torch.distributed._shard.sharding_spec.chunk_sharding_specr
   Z)torch.distributed.checkpoint._nested_dictr   Z,torch.distributed.checkpoint.default_plannerr   Z%torch.distributed.checkpoint.metadatar   r   r   r   r   r   Z$torch.distributed.checkpoint.plannerr   r   Z,torch.distributed.checkpoint.planner_helpersr   r   Z.torch.distributed.checkpoint.state_dict_loaderr   Z$torch.distributed.checkpoint.storager   Z"torch.distributed.checkpoint.utilsr   r   r   Z"torch.distributed.distributed_c10dr   Z#torch.distributed.fsdp._shard_utilsr   Ztorch.distributed.remote_devicer   Ztorch.distributed.tensorr   rw   r?   tuplery   ZSTATE_DICT_2D_LAYOUT__all__r*   ZProcessGroupr@   rz   boolrF   rO   r[   r\   r    r(   r(   r(   r)   <module>   s`   $	   
%> 