o
    8wik#                     @   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 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 Z/G d!d" d"ej0Z1d#e"de"fd$d%Z2dS )'    N)
ModuleTypeTracebackType)AnyOptional)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   h/home/ubuntu/sommelier/.venv/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/pytorch-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   r,   k   r-   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    r6   )_lockacquirer   sysmodules_gpus_arg_defaultr   	utilitiesargparser   enumsr6   pickle	Unpickler_old_unpickler_RedirectingUnpickler)selflegacy_argparse_moduler6   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'   r6   )hasattrr   r<   r=   delattrr9   r:   r>   rA   r?   r@   r7   release)rC   rF   rG   rH   r   r   r   __exit__z   s   zpl_legacy_patch.__exit__)r   r&   )
r   r1   r2   __doc__rE   r   typeBaseExceptionr   rL   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   rP   old_version
migrationsnew_version	path_hintr   r   r   _pl_migrate_checkpoint   s   "r^   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.r_   Nr   r   r`   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)
setdefaultra   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   rc   rd   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 )rB   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)rC   rf   rg   
new_module	__class__r   r   rm      s   "z _RedirectingUnpickler.find_class)	r   r1   r2   rM   r   rY   r   rm   __classcell__r   r   ro   r   rB      s    $rB   rf   c                 C   s&   d}|  |rd| t|d   S | S )Npytorch_lightning)
startswithlen)rf   _plr   r   r   ri      s   
ri   r)   )3loggingrR   r?   r9   	threadingrj   typesr   r   typingr   r   packaging.versionr   typing_extensionsr   rr   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   rW   dictrY   _CHECKPOINTLockr7   tuplelistr%   r&   r^   r   r   r   boolr   
_UnpicklerrB   ri   r   r   r   r   <module>   sH   

(: 