a
    7SicI                     @   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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 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m Z m!Z! d dl"Z"d dl#Z#d dl$Z$d
Z%e&dj'Z(e&dj'Z)e&dj'Z*dZ+dZ,dZ-G dd de.Z/edd Z0g Z1e2dddZ3dd Z4diddZ5dd Z6dd  Z7d!d" Z8d#d$ Z9d%d& Z:e4d'e6e8 e4d(e7e: e eej;j<ej=f d)d*d+Z>d,d- Z?d.d/ Z@d0d1 ZAd2d3 ZBG d4d5 d5eCZDG d6d7 d7eDZEG d8d9 d9eDZFG d:d; d;eDZGd<d= ZHG d>d? d?eDZIG d@dA dAeDZJG dBdC dCeDZKdDdE ZLe2ddFdGZMdHdI ZNe2ddJdKZOdddLdMZPe#e%dfe eQejRee!eS f ddNdOdPZTdddQdRZUdSdT ZVde#fdUdVZWdWdX ZXi eX_Ye"#ejZdYdZ  d[d\ Z[e eSeQf eQd]d^d_Z\d`da Z]G dbdc dcZ^djdedfZ_dgdh Z`dS )k    N)closingcontextmanager   )_import_dotted_name)string_classes)get_source_lines_and_file)Storage)#_get_dtype_from_pickle_storage_type)	AnyBinaryIOcastDictOptionalTypeTupleUnionIO   z=lz=iz=hl   l|9QC
 i  ,c                   @   s   e Zd ZdS )SourceChangeWarningN)__name__
__module____qualname__ r   r   O/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/serialization.pyr       s   r   c                  c   s   t  } | V  t|  d S N)tempfilemkdtempshutilrmtreepathr   r   r   r   $   s    r   returnc                 C   s\   g }|   }| d}|dkrB|| t|dkr6qB| d}q| | g d}||kS )Nr       )   P   K      )tellreadappendlenseek)f
read_bytesstartbyteZlocal_header_magic_numberr   r   r   _is_zipfile.   s    	


r3   c                 C   s    | ||f}t | t   d S r   )_package_registryr,   sort)prioritytaggerZdeserializerZ
queue_elemr   r   r   register_packageF   s    

r8   Tc              
      s   z2| j d t fddt|D }||k}W n\ ty } zDd| j| j t|f }|rht||nt	|d  d}W Y d}~n
d}~0 0 |S )a  
    Check if a module's version satisfies requirements

    Usually, a module's version string will be like 'x.y.z', which would be represented
    as a tuple (x, y, z), but sometimes it could be an unexpected format. If the version
    string does not match the given tuple's format up to the length of the tuple, then
    error and exit or emit a warning.

    Args:
        module: the module to check the version of
        req_version_tuple: tuple (usually of ints) representing the required version
        error_if_malformed: whether we should exit if module version string is malformed

    Returns:
        requirement_is_met: bool
    .c                 3   s"   | ]\}}t | | V  qd S r   )type).0idxZ	req_fieldZversion_strsr   r   	<genexpr>`   s   z8check_module_version_greater_or_equal.<locals>.<genexpr>zQ'%s' module version string is malformed '%s' and cannot be compared with tuple %sz1, but continuing assuming that requirement is metTN)
__version__splittuple	enumerate	Exceptionr   strRuntimeErrorwarningswarn)moduleZreq_version_tupleZerror_if_malformedZmodule_versionZrequirement_is_metemessager   r=   r   %check_module_version_greater_or_equalL   s     rK   c                 C   s   | j jdkrdS d S Ncpu)devicer:   objr   r   r   _cpu_tagu   s    rQ   c                 C   s    | j jdkrdt| j j S d S )Ncudazcuda:)rN   r:   rD   indexrO   r   r   r   	_cuda_tagz   s    rT   c                 C   s   |dkr| S d S rL   r   )rP   locationr   r   r   _cpu_deserialize   s    rV   c                 C   sN   t jj| d}t j s"tdt j }||krJtd| d| d|S )NTzAttempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU.z0Attempting to deserialize object on CUDA device z" but torch.cuda.device_count() is zU. Please use torch.load with map_location to map your storages to an existing device.)torchrR   _utils_get_device_indexis_availablerE   device_count)rU   rN   r[   r   r   r   validate_cuda_device   s    


r\   c                 C   sr   | drnt|}t| ddrdtj|( tj|  t|dW  d    S 1 sX0    Y  n
| |S d S )NrR   _torch_load_uninitializedF)rN   )
startswithr\   getattrrW   rR   rN   _UntypedStoragenbytes)rP   rU   rN   r   r   r   _cuda_deserialize   s    
8rb   
      )storagec                 C   s:   t D ]\}}}|| }|r|  S qtdt|  d S )Nz-don't know how to determine data location of r4   rE   rW   typename)re   _r7   rU   r   r   r   location_tag   s    
ri   c                 C   sL   t D ]$\}}}|| |}|d ur|  S qtdt|  d | d d S )Nz+don't know how to restore data location of z (tagged with )rf   )re   rU   rh   fnresultr   r   r   default_restore_location   s    

rm   c                 C   s   t t| jS r   )r_   rW   r   )storage_typer   r   r   normalize_storage_type   s    ro   c                 C   s&   t | }t|j}t||jddS )Nr   Tensor)r:   r   r   r_   r   replace)re   rn   rH   r   r   r   storage_to_tensor_type   s    
rr   c                 C   s   t | tpt | tjS r   )
isinstancerD   pathlibPath)name_or_bufferr   r   r   _is_path   s    

rw   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )_openerc                 C   s
   || _ d S r   	file_like)selfrz   r   r   r   __init__   s    z_opener.__init__c                 C   s   | j S r   ry   r{   r   r   r   	__enter__   s    z_opener.__enter__c                 G   s   d S r   r   r{   argsr   r   r   __exit__   s    z_opener.__exit__N)r   r   r   r|   r~   r   r   r   r   r   rx      s   rx   c                       s$   e Zd Z fddZdd Z  ZS )
_open_filec                    s   t t| t|| d S r   )superr   r|   open)r{   namemode	__class__r   r   r|      s    z_open_file.__init__c                 G   s   | j   d S r   )rz   closer   r   r   r   r      s    z_open_file.__exit__r   r   r   r|   r   __classcell__r   r   r   r   r      s   r   c                       s   e Zd Z fddZ  ZS )_open_buffer_readerc                    s   t t| | t| d S r   )r   r   r|   _check_seekabler{   bufferr   r   r   r|      s    z_open_buffer_reader.__init__r   r   r   r|   r   r   r   r   r   r      s   r   c                   @   s   e Zd Zdd ZdS )_open_buffer_writerc                 G   s   | j   d S r   )rz   flushr   r   r   r   r      s    z_open_buffer_writer.__exit__N)r   r   r   r   r   r   r   r   r      s   r   c                 C   sD   t | rt| |S d|v r"t| S d|v r2t| S td| d S )Nwrz$Expected 'r' or 'w' in mode but got )rw   r   r   r   rE   )rv   r   r   r   r   _open_file_like   s    
r   c                       s"   e Zd Zdd fddZ  ZS )_open_zipfile_readerNr"   c                    s   t t| tj| d S r   )r   r   r|   rW   _CPyTorchFileReader)r{   rv   r   r   r   r|      s    z_open_zipfile_reader.__init__r   r   r   r   r   r      s   r   c                       s0   e Zd Zdd fddZddddZ  ZS )_open_zipfile_writer_fileNr"   c                    s    t t| tjt| d S r   )r   r   r|   rW   r   PyTorchFileWriterrD   r{   r   r   r   r   r|      s    z"_open_zipfile_writer_file.__init__c                 G   s   | j   d S r   )rz   write_end_of_filer   r   r   r   r      s    z"_open_zipfile_writer_file.__exit__r   r   r   r   r   r      s   r   c                       s0   e Zd Zdd fddZddddZ  ZS )_open_zipfile_writer_bufferNr"   c                    s"   || _ tt| tj| d S r   )r   r   r   r|   rW   r   r   r   r   r   r   r|      s    z$_open_zipfile_writer_buffer.__init__c                 G   s   | j   | j  d S r   )rz   r   r   r   r   r   r   r   r     s    
z$_open_zipfile_writer_buffer.__exit__r   r   r   r   r   r      s   r   c                 C   s   t | rt}nt}|| S r   )rw   r   r   )rv   	containerr   r   r   _open_zipfile_writer  s    r   c                 C   s,   dg}z| j |v W S  ty&   Y dS 0 d S )NgzipF)r   AttributeError)r/   Zcompress_modulesr   r   r   _is_compressed_file  s
    r   c                 C   sH   t | rdS z|  dkW S  tjy0   Y dS  tyB   Y dS 0 dS )z
    Checks if f is a file that should be read directly. It should be read
    directly if it is backed by a real file (has a fileno) and is not a
    a compressed file (e.g. gzip)
    Fr   N)r   filenoioUnsupportedOperationr   )r/   r   r   r   _should_read_directly  s    r   c              
   C   sZ   dd }z|  |   W dS  tjtfyT } z|ddg| W Y d }~n
d }~0 0 dS )Nc                 S   s>   | D ]0}|t |v rt |d d d }t||q|d S )Nz7. You can only torch.load from a file that is seekable.z; Please pre-load the data into a buffer like io.BytesIO andz try to load from it instead.)rD   r:   )patternsrI   pmsgr   r   r   raise_err_msg*  s    
z&_check_seekable.<locals>.raise_err_msgTr.   r*   F)r.   r*   r   r   r   )r/   r   rI   r   r   r   r   (  s    	$r   c                 C   s@   | j dkr<d}t| |ds<tdddd |D | jf dS )	zChecks if using dill as the pickle module, and if so, checks if it is the correct version.
    If dill version is lower than 0.3.1, a ValueError is raised.

    Args:
        pickle_module: module used for pickling metadata and objects

    Zdill)r      r   Fz\'torch' supports dill >= %s, but you have dill %s. Please upgrade dill or switch to 'pickle'r9   c                 S   s   g | ]}t |qS r   )rD   )r;   numr   r   r   
<listcomp>I      z'_check_dill_version.<locals>.<listcomp>N)r   rK   
ValueErrorjoinr?   )pickle_moduleZrequired_dill_versionr   r   r   _check_dill_version:  s    
r   )r/   r#   c              	   C   s   t | t|df}|r\t|,}t| ||| W d   W d   dS 1 sR0    Y  t| ||| W d   n1 s~0    Y  dS )a  save(obj, f, pickle_module=pickle, pickle_protocol=DEFAULT_PROTOCOL, _use_new_zipfile_serialization=True)

    Saves an object to a disk file.

    See also: :ref:`saving-loading-tensors`

    Args:
        obj: saved object
        f: a file-like object (has to implement write and flush) or a string or
           os.PathLike object containing a file name
        pickle_module: module used for pickling metadata and objects
        pickle_protocol: can be specified to override the default protocol

    .. note::
        A common PyTorch convention is to save tensors using .pt file extension.

    .. note::
        PyTorch preserves storage sharing across serialization. See
        :ref:`preserve-storage-sharing` for more details.

    .. note::
        The 1.6 release of PyTorch switched ``torch.save`` to use a new
        zipfile-based file format. ``torch.load`` still retains the ability to
        load files in the old format. If for any reason you want ``torch.save``
        to use the old format, pass the kwarg ``_use_new_zipfile_serialization=False``.

    Example:
        >>> # Save to file
        >>> x = torch.tensor([0, 1, 2, 3, 4])
        >>> torch.save(x, 'tensor.pt')
        >>> # Save to io.BytesIO buffer
        >>> buffer = io.BytesIO()
        >>> torch.save(x, buffer)
    wbN)r   r   r   _save_legacy_save)rP   r/   r   pickle_protocol_use_new_zipfile_serializationopened_fileopened_zipfiler   r   r   saveM  s    )
,r   c              	      s   dd l m  i i i ttt d fdd}tttjdktt	t
tdd}|jt||d |jt||d |j|||d |j||d}||_||  t }|j|||d |  |D ],}| \}	}
|	|t|d	tj|
 qd S )
Nr   )rP   r#   c                    s  t | trt|  jr| v r"d S d| < d  }}zt| \}}}d|}W n& tyt   td| j	 d  Y n0 d| ||fS t | t
jjst
| rt | t
jjr| j}| j}|  }tt
|}| j}	|  }
nFt | t
jr| }t
j}tt| }t
j}	| }
ntdt|  | dkrb| v rV||  krbtdn|| < d}t|j}t|}|vr||	f|< |j|jk}|rt|j|| f}nd }d	||||
|f}|S d S )
NTr$   4Couldn't retrieve source code for container of type 3. It won't be checked for correctness upon loading.rH   ztype not recognized: r   SCannot save multiple tensors or storages that view the same data as different typesre   )rs   r:   
issubclassModuler   r   rC   rF   rG   r   rW   re   _TypedStorage
is_storage_storagedtypepickle_storage_typer_   sizer`   uint8ro   ra   	TypeErrordata_ptrrE   rD   _cdatari   )rP   source_filesourcesource_linesrh   re   storage_dtypestorage_type_strrn   r   storage_numeloffsetstorage_keyrU   Zis_viewview_metadataresnnZserialized_container_typesserialized_storagesstorage_dtypesr   r   persistent_id  sn    




z#_legacy_save.<locals>.persistent_idlittle)shortintlong)protocol_versionlittle_endianZ
type_sizesprotocolT)Ztorch.nnr   r
   r   r   dictPROTOCOL_VERSIONsys	byteorder
SHORT_SIZEINT_SIZE	LONG_SIZEdumpMAGIC_NUMBERPicklerr   sortedkeysr   _write_filer   rW   rX   _element_size)rP   r/   r   r   r   Zsys_infopicklerZserialized_storage_keyskeyre   r   r   r   r   r     s4    l

r   c                    s   i i  i  fdd}t  }|j||d}||_||  | }|d|t| t	 D ]D}d| }	| }
|
j
jdkr|
 }
|
 }||	|
 | qhd S )Nc                    s   t | tjjst| rt | tjjrN| j}| j}|  }tt|}| 	 }n| }tj
}tt| }| }| dkr| v r||  krtdn|| <  |jtt }t|}||< d||||fS d S )Nr   r   re   )rs   rW   re   r   r   r   r   r   r_   r   r   ro   r:   ra   r   rE   
setdefaultr   rD   r-   ri   )rP   re   r   r   rn   r   r   rU   Zid_mapr   r   r   r   r     s8    

z_save.<locals>.persistent_idr   data.pkldata/rM   )r   BytesIOr   r   r   getvaluewrite_recordr-   r   r   rN   r:   rM   ra   r   )rP   zip_filer   r   r   Zdata_bufr   
data_valuer   r   re   	num_bytesr   r   r   r     s"    0

r   c              	   K   s   t | d| vrd|d< t| d}t|r| }t|x}t|rtdt	 |
| tj|W  d   W  d   S t|||fi |W  d   W  d   S 1 s0    Y  t|||fi |W  d   S 1  s0    Y  dS )a}  load(f, map_location=None, pickle_module=pickle, **pickle_load_args)

    Loads an object saved with :func:`torch.save` from a file.

    :func:`torch.load` uses Python's unpickling facilities but treats storages,
    which underlie tensors, specially. They are first deserialized on the
    CPU and are then moved to the device they were saved from. If this fails
    (e.g. because the run time system doesn't have certain devices), an exception
    is raised. However, storages can be dynamically remapped to an alternative
    set of devices using the :attr:`map_location` argument.

    If :attr:`map_location` is a callable, it will be called once for each serialized
    storage with two arguments: storage and location. The storage argument
    will be the initial deserialization of the storage, residing on the CPU.
    Each serialized storage has a location tag associated with it which
    identifies the device it was saved from, and this tag is the second
    argument passed to :attr:`map_location`. The builtin location tags are ``'cpu'``
    for CPU tensors and ``'cuda:device_id'`` (e.g. ``'cuda:2'``) for CUDA tensors.
    :attr:`map_location` should return either ``None`` or a storage. If
    :attr:`map_location` returns a storage, it will be used as the final deserialized
    object, already moved to the right device. Otherwise, :func:`torch.load` will
    fall back to the default behavior, as if :attr:`map_location` wasn't specified.

    If :attr:`map_location` is a :class:`torch.device` object or a string containing
    a device tag, it indicates the location where all tensors should be loaded.

    Otherwise, if :attr:`map_location` is a dict, it will be used to remap location tags
    appearing in the file (keys), to ones that specify where to put the
    storages (values).

    User extensions can register their own location tags and tagging and
    deserialization methods using :func:`torch.serialization.register_package`.

    Args:
        f: a file-like object (has to implement :meth:`read`, :meth:`readline`, :meth:`tell`, and :meth:`seek`),
            or a string or os.PathLike object containing a file name
        map_location: a function, :class:`torch.device`, string or a dict specifying how to remap storage
            locations
        pickle_module: module used for unpickling metadata and objects (has to
            match the :attr:`pickle_module` used to serialize file)
        pickle_load_args: (Python 3 only) optional keyword arguments passed over to
            :func:`pickle_module.load` and :func:`pickle_module.Unpickler`, e.g.,
            :attr:`errors=...`.

    .. warning::
        :func:`torch.load()` uses ``pickle`` module implicitly, which is known to be insecure.
        It is possible to construct malicious pickle data which will execute arbitrary code
        during unpickling. Never load data that could have come from an untrusted
        source, or that could have been tampered with. **Only load data you trust**.

    .. note::
        When you call :func:`torch.load()` on a file which contains GPU tensors, those tensors
        will be loaded to GPU by default. You can call ``torch.load(.., map_location='cpu')``
        and then :meth:`load_state_dict` to avoid GPU RAM surge when loading a model checkpoint.

    .. note::
        By default, we decode byte strings as ``utf-8``.  This is to avoid a common error
        case ``UnicodeDecodeError: 'ascii' codec can't decode byte 0x...``
        when loading files saved by Python 2 in Python 3.  If this default
        is incorrect, you may use an extra :attr:`encoding` keyword argument to specify how
        these objects should be loaded, e.g., :attr:`encoding='latin1'` decodes them
        to strings using ``latin1`` encoding, and :attr:`encoding='bytes'` keeps them
        as byte arrays which can be decoded later with ``byte_array.decode(...)``.

    Example:
        >>> torch.load('tensors.pt')
        # Load all tensors onto the CPU
        >>> torch.load('tensors.pt', map_location=torch.device('cpu'))
        # Load all tensors onto the CPU, using a function
        >>> torch.load('tensors.pt', map_location=lambda storage, loc: storage)
        # Load all tensors onto GPU 1
        >>> torch.load('tensors.pt', map_location=lambda storage, loc: storage.cuda(1))
        # Map tensors from GPU 1 to GPU 0
        >>> torch.load('tensors.pt', map_location={'cuda:1':'cuda:0'})
        # Load tensor from io.BytesIO object
        >>> with open('tensor.pt', 'rb') as f:
        ...     buffer = io.BytesIO(f.read())
        >>> torch.load(buffer)
        # Load a module with 'ascii' encoding for unpickling
        >>> torch.load('module.pt', encoding='ascii')
    encodingzutf-8rbz'torch.load' received a zip file that looks like a TorchScript archive dispatching to 'torch.jit.load' (call 'torch.jit.load' directly to silence this warning)N)r   r   r   r3   r*   r   _is_torchscript_ziprF   rG   UserWarningr.   rW   jitload_load_legacy_load)r/   map_locationr   pickle_load_argsr   Zorig_positionr   r   r   r   r   _  s    W

(@r   c                 C   s:   t j}|s2tj D ]}t|tjr||t|< q||  S )z@Get layout extension object from its string representation.
    )_get_layoutcacherW   __dict__valuesrs   layoutrD   )r   r  vr   r   r   r    s    r  c                 C   s   t t| ffS r   )r  rD   rO   r   r   r   <lambda>  r   r  c              	      s  i t |G dd dj dd  fdd}i fdd}t|  t| }|r|  d	krz
|| W S  tjy   t| rt| j	 d
d | 
d	 Y n0 t| dsdtj  krdk rn ntdt|  dj| fi }|tkrtdj| fi }|tkr6td| j| fi }	 | fi }
||
_|
 }j| fi }|r|  nd }|D ]J}|v sJ | }|j| ||tj|j |d ur|  }qtj  |S )Nc                       s   e Zd Z fddZ  ZS )z&_legacy_load.<locals>.UnpicklerWrapperc                    s@   t |tu r2d|v r2z
t|W S  ty0   Y n0 t ||S Nr   )r:   rD   StorageTypeKeyErrorr   
find_classr{   mod_namer   r   r   r   r    s    
z1_legacy_load.<locals>.UnpicklerWrapper.find_classr   r   r   r  r   r   r   r   r   UnpicklerWrapper  s   r  c           
      S   s\  zd t| d }W n( ty>   td| j d  Y d S 0 ||krX| jr2| jd }tj|	d|	d||dd}d |}zt
|dV}|dd	}|d |dkr|| n|t|ks| |krtW d    n1 s0    Y  d
| d | d }	W n  ty.   d| d }	Y n0 nd}	dt|  d|	 }	t|	t d S )Nr$   r   r   r   z.patch
)linetermza+r   zSaved a reverse patch to z. Run `patch -p0 < z` to revert your changes.z;Tried to save a patch, but couldn't create a writable file zD. Make sure it doesn't exist and your working directory is writable.zyou can retrieve the original source code by accessing the object's source attribute or set `torch.nn.Module.dump_patches = True` and use the patch tool to revert the changes.zsource code of class 'z' has changed. )r   r   rC   rF   rG   r   Zdump_patchesdifflibunified_diffr@   r   r.   writer-   r+   IOErrorrW   rg   r   )
Zcontainer_typer   Zoriginal_sourceZcurrent_source	file_namedifflinesr/   	file_sizer   r   r   r   _check_container_source  sP    



"
z-_legacy_load.<locals>._check_container_sourcec                     s   i   fdd}t tj| dtjd}t }|jd|d ttj|ddd} j	| fi }t
|D ]`}j	| fi }|\}}}	|	j}
tttj| tj|
}||}tjj||
d	 |< qvj	| fi }|D ]R\}}}} | }tj|j}|| }tjj|j||||   |jd	 |< qW d    n1 sX0    Y  |jd
|d ttj|d
dd} j	| fi }t
|D ]}j	| fi }|\}}} | }td| d\}| d td| d| d| }td| d| d| }td| d\}tjg |jd|j|||}| |< qW d    n1 sx0    Y  |d}|fi }||_|	 }|W  d    W  d    S 1 s0    Y  W d    n1 s0    Y  d S )Nc                    s6   t | tr*t| dd  r" |   | d S t|  S )Nr   r   )rs   rA   allr   )saved_id)r  deserialized_objectsr   r   persistent_load  s
    
z:_legacy_load.<locals>.legacy_load.<locals>.persistent_loadzr:)fileobjr   formatstoragesr    r   r   wrap_storager   tensorsz<ir%   <q   z<qr   pickle)r   tarfiler   Z
PAX_FORMATr   extractosr!   r   r   ranger   r   r   rW   r`   _new_with_filerX   r   re   r   r   structunpackr+   tensorset_Zextractfiler"  ) r/   r"  tarZtmpdirZnum_storagesir   r   rU   rn   r   rP   Zstorage_viewsZtarget_cdataZ
root_cdatar   numelrootelement_sizeoffset_bytesZnum_tensorsrh   Z
storage_idZoriginal_tensor_typere   ndimstridestorage_offsetr5  pickle_file	unpicklerrl   )r  r  r  r   restore_location)r!  r   legacy_load  sb    

,


,
z!_legacy_load.<locals>.legacy_loadc                    sJ  t | tsJ t| d }| dd  }|dkrNt|dd  rF |  |d S |dkr6|\}}}}}t|}|j}|tj| }	|vrtt	t
|	}
d|
_tjj|
||d|< | }|d ur.|\}}}|tj| }|tj| }|vr$tjj|j|||  |d|< | }n|}|S td| d  d S )Nr   r   rH   re   Tr&  zUnknown saved id type: %s)rs   rA   _maybe_decode_asciir  r   rW   rX   r   r   r   r`   r]   re   r   r   rE   )r   rg   datarn   Zroot_keyrU   r9  r   r   ra   rP   typed_storageZview_keyr   Z	view_sizer<  Zview_size_bytesr   )r  r!  rB  r   r   r"  U  sB    






z%_legacy_load.<locals>.persistent_loadr   z9 is a zip archive (did you mean to use torch.jit.load()?)readinto)r   r+  r   )r   r+  r   ztorch.load does not work with file-like objects that do not implement readinto on Python 3.8.0 and 3.8.1. Received object of type "zH". Please update to Python 3.8.2 or newer to restore this functionality.z#Invalid magic number; corrupt file?zInvalid protocol version: %s)_get_restore_location	Unpicklerr   r   r*   r.  TarErrorr3   rE   r   r.   hasattrr   version_infor:   r   r   r   r"  r   _set_from_filerW   rX   r   r   _validate_loaded_sparse_tensors)r/   r  r   r  rC  r"  Zf_should_read_directlyZmagic_numberr   Z	_sys_inforA  rl   Zdeserialized_storage_keysr   r   rF  r   )r  r  r!  r  r   rB  r   r    sb    
(?-

$



r  )	bytes_strr#   c                 C   s   t | tr| dS | S )Nascii)rs   bytesdecode)rO  r   r   r   rD    s    

rD  c                    sh    d u rt }nVt tr& fdd}n>t tr> fdd}n&t tjrX fdd}n fdd}|S )Nc                    s     ||}t| |S r   )getrm   re   rU   r  r   r   rB    s    z/_get_restore_location.<locals>.restore_locationc                    s
   t |  S r   rm   rT  rU  r   r   rB    s    c                    s   t | t S r   )rm   rD   rT  rU  r   r   rB    s    c                    s     | |}|d u rt | |}|S r   rV  )re   rU   rl   rU  r   r   rB    s    

)rm   rs   r   _string_classesrW   rN   )r  rB  r   rU  r   rH    s    

rH  c                   @   s   e Zd Zdd Zdd ZdS )r  c                 C   s   t || _d S r   )r	   r   r   r   r   r   r|     s    zStorageType.__init__c                 C   s   d| j  dS )NzStorageType(dtype=rj   r,  r}   r   r   r   __str__  s    zStorageType.__str__N)r   r   r   r|   rX  r   r   r   r   r    s   r  r   c           
         s   t |i fddfdd}ddi G  fddd|j}t|}||fi |}||_| }	tj	  |	S )	Nc                    s@   d| } ||tj  }tjj||| d |< d S )Nr   r&  )get_storage_from_recordrW   r`   re   _untypedr   )r   r9  r   rU   r   re   )loaded_storagesrB  r   r   r   load_tensor  s    
z_load.<locals>.load_tensorc           	         s   t | tsJ t| d }| dd  }|dks>J d| d|\}}}}|tju r\tj}n|j}|vr|tj| } |||t| | S )Nr   r   re   zBUnknown typename for persistent_load, expected 'storage' but got '')	rs   rA   rD  rW   r`   r   r   rX   r   )	r   rg   rE  rn   r   rU   r9  r   ra   )r\  r[  r   r   r"    s    


z_load.<locals>.persistent_loadztorch.tensorztorch._tensorc                       s   e Zd Z fddZ  ZS )z_load.<locals>.UnpicklerWrapperc                    sL   t |tu r2d|v r2z
t|W S  ty0   Y n0 ||}t ||S r  )r:   rD   r  r  rS  r   r  r  )r   load_module_mappingr   r   r    s    
z*_load.<locals>.UnpicklerWrapper.find_classr  r   )r^  r   r   r    s   r  )
rH  rI  r   r   
get_recordr"  r   rW   rX   rN  )
r   r  r   r@  r  r"  r  Z	data_filerA  rl   r   )r^  r\  r[  rB  r   r   r    s    

r  c                 C   s   d|   v S )Nzconstants.pkl)get_all_records)r   r   r   r   r      s    r   )T)r   )ar  r0  r   r   r3  r   rW   r.  r   rF   
contextlibr   r   rX   r   _sixr   rW  Ztorch._sourcesr   torch.typesr   Ztorch.storager	   typingr
   r   r   r   r   r   r   r   r   copyregr-  rt   DEFAULT_PROTOCOLStructr   r   r   r   r   r   ZSTORAGE_KEY_SEPARATORWarningr   r   r4   boolr3   r8   rK   rQ   rT   rV   r\   rb   re   r   r`   ri   rm   ro   rr   rw   objectrx   r   r   r   r   r   r   r   r   r   r   r   r   rD   PathLikerQ  r   r   r   r   r  r  r	  r  rD  rH  r  r  r   r   r   r   r   <module>   s   ,

)
	

	3 Oo Y
C