o
    zi|#                     @   s  d dl Z 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mZ d dl	m
Z
mZmZmZmZmZ d dl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! e "e#Z$ee%e
f Z&e' Z(	d&de&dee% dee&ee%ee% f f fddZ)G dd dZ*d&de&dee de&fddZ+de&de%fddZ,de&de%ddfddZ-de&de%ddfddZ.d&de&de%dee% de/fdd Z0G d!d" d"ej1Z2d#e%de%fd$d%Z3dS )'    N)
ModuleTypeTracebackType)AnyDictListOptionalTupleType)Version)override)LightningEnum)_IS_WINDOWS)_PATH)PossibleUserWarning)_migration_index)rank_zero_warn
checkpointtarget_versionreturnc                 C   s   t | }t|ttjkrtd| dtj td | i fS t }i }| D ]\}}t| ||s2q'|D ]}|| } q4dd |D ||< q'|tjkrOt	| | t
| tj | |fS )a1  Applies Lightning version migrations to a checkpoint dictionary.

    Args:
        checkpoint: A dictionary with the loaded state from the checkpoint file.
        target_version: Run migrations only up to this version (inclusive), even if migration index contains
            migration functions for newer versions than this target. Mainly useful for testing.

    Note:
        The migration happens in-place. We specifically avoid copying the dict to avoid memory spikes for large
        checkpoints and objects that do not support being deep-copied.

    z3The loaded checkpoint was produced with Lightning vz7, which is newer than your current Lightning version: v)categoryc                 S   s   g | ]}|j qS  )__name__).0fnr   r   _/home/ubuntu/.local/lib/python3.10/site-packages/pytorch_lightning/utilities/migration/utils.py
<listcomp>G   s    z&migrate_checkpoint.<locals>.<listcomp>)_get_versionr
   pl__version__r   r   r   items_should_upgrade_set_legacy_version_set_version)r   r   ckpt_versionindexapplied_migrationsmigration_versionmigration_functionsmigration_functionr   r   r   migrate_checkpoint'   s*   


r)   c                   @   sD   e Zd ZdZdddZdeee  dee dee ddfd	d
Z	dS )pl_legacy_patcha  Registers legacy artifacts (classes, methods, etc.) that were removed but still need to be included for
    unpickling old checkpoints. The following patches apply.

        1. ``pytorch_lightning.utilities.argparse._gpus_arg_default``: Applies to all checkpoints saved prior to
           version 1.2.8. See: https://github.com/Lightning-AI/lightning/pull/6898
        2. ``pytorch_lightning.utilities.argparse_utils``: A module that was deprecated in 1.2 and removed in 1.4,
           but still needs to be available for import for legacy checkpoints.
        3. ``pytorch_lightning.utilities.enums._FaultTolerantMode``: This enum was removed in 2.0 but was pickled
           into older checkpoints.
        4. In legacy versions of Lightning, callback classes got pickled into the checkpoint. These classes have a
           module import path under ``pytorch_lightning`` and must be redirected to the ``pytorch_lightning``.

    Example:

        with pl_legacy_patch():
            torch.load("path/to/legacy/checkpoint.ckpt")

    r   c                 C   s^   t   td}|tjd< dd |_dd tjj_G dd dt	}|tjj
_tj| _tt_| S )N*pytorch_lightning.utilities.argparse_utilsc                 S      | S Nr   xr   r   r   <lambda>j       z+pl_legacy_patch.__enter__.<locals>.<lambda>c                 S   r,   r-   r   r.   r   r   r   r0   k   r1   c                   @   s   e Zd ZdZdZdZdS )z5pl_legacy_patch.__enter__.<locals>._FaultTolerantModedisabled	automaticmanualN)r   
__module____qualname__DISABLED	AUTOMATICMANUALr   r   r   r   _FaultTolerantModen   s    r:   )_lockacquirer   sysmodules_gpus_arg_defaultr   	utilitiesargparser   enumsr:   pickle	Unpickler_old_unpickler_RedirectingUnpickler)selflegacy_argparse_moduler:   r   r   r   	__enter__c   s   


zpl_legacy_patch.__enter__exc_type	exc_valueexc_tracebackNc                 C   sT   t tjjdrttjjd tjd= t tjjdr ttjjd | jt	_
t  d S )Nr?   r+   r:   )hasattrr   r@   rA   delattrr=   r>   rB   rE   rC   rD   r;   release)rG   rJ   rK   rL   r   r   r   __exit__z   s   zpl_legacy_patch.__exit__)r   r*   )
r   r5   r6   __doc__rI   r   r	   BaseExceptionr   rP   r   r   r   r   r*   O   s    

r*   checkpoint_pathc              	   C   st   t | }t| \} }t | }|r|du r| S ts!tj|t ntj|}t	d| d| dt
| d | S )zApplies Lightning version migrations to a checkpoint dictionary and prints infos for the user.

    This function is used by the Lightning Trainer when resuming from a checkpoint.

    Nz>Lightning automatically upgraded your loaded checkpoint from vz to vzp. To apply the upgrade to your files permanently, run `python -m pytorch_lightning.utilities.upgrade_checkpoint `)r   r)   r   ospathrelpathgetcwdabspath_loginfostr)r   rS   old_version
migrationsnew_version	path_hintr   r   r   _pl_migrate_checkpoint   s   "ra   c                 C   s   | d S )z*Get the version of a Lightning checkpoint.pytorch-lightning_versionr   )r   r   r   r   r      s   r   versionc                 C   s   || d< dS )z*Set the version of a Lightning checkpoint.rb   Nr   r   rc   r   r   r   r"      s   r"   c                 C   s   |  d| dS )zXSet the legacy version of a Lightning checkpoint if a legacy version is not already set.z legacy_pytorch-lightning_versionN)
setdefaultrd   r   r   r   r!      s   r!   targetmax_versionc                 C   s0   t |}|du p|t |k}|ot t| |k S )zfReturns whether a checkpoint qualifies for an upgrade when the version is lower than the given target.N)r
   r   )r   rf   rg   r   is_lte_max_versionr   r   r   r       s   r    c                       s2   e Zd ZdZedededef fddZ  ZS )rF   a  Redirects the unpickling of `pytorch_lightning` classes to `pytorch_lightning`.

    In legacy versions of Lightning, callback classes got pickled into the checkpoint. These classes are defined in the
    `pytorch_lightning` but need to be loaded from `pytorch_lightning`.

    modulenamer   c              
      s@   t |}||krtd| d| d| d|  t ||S )NzRedirecting import of .z to ) _patch_pl_to_mirror_if_necessarywarningswarnsuper
find_class)rG   ri   rj   
new_module	__class__r   r   rp      s   "z _RedirectingUnpickler.find_class)	r   r5   r6   rQ   r   r\   r   rp   __classcell__r   r   rr   r   rF      s    $rF   ri   c                 C   s&   d}|  |rd| t|d   S | S )Npytorch_lightning)
startswithlen)ri   _plr   r   r   rl      s   
rl   r-   )4loggingrU   rC   r=   	threadingrm   typesr   r   typingr   r   r   r   r   r	   packaging.versionr
   typing_extensionsr   ru   r    lightning_fabric.utilities.enumsr   "lightning_fabric.utilities.importsr    lightning_fabric.utilities.typesr   #lightning_fabric.utilities.warningsr   /pytorch_lightning.utilities.migration.migrationr   %pytorch_lightning.utilities.rank_zeror   	getLoggerr   rZ   r\   _CHECKPOINTLockr;   r)   r*   ra   r   r"   r!   boolr    
_UnpicklerrF   rl   r   r   r   r   <module>   sH    

(: 