
    Pg/                    	   U 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
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mZmZmZmZmZmZmZmZmZmZ d dl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, g d
Z-dZ. ej^                  d      j`                  Z1 ej^                  d      j`                  Z2 ej^                  d      j`                  Z3dZ4dZ5dZ6ee7ejp                  eee9   f   Z:e e;d<   eeee,e7ge,f   e"jx                  e7ee7e7f   f      Z=e e;d<   ee,e"j|                  j~                  e"j                  f   ZAe e;d<   e	j                  dk(  ZCdZDeCs	d dlEmFZFmGZG nd\  ZGZFd ZH G d dej                        ZJ eJ       aK G d deL      ZMed        ZNg ZOeeePeeAgee7   f   eeAe7geeA   f   f      e;d<    G d  d!e      ZQdaReeQ   e;d"<   d#eeQ   fd$ZSd% ZTd&aUeVe;d'<   d#eVfd(ZWd)eVfd*ZXeFaYePe;d+<   d#ePfd,ZZ G d- d.      Z[dd/Z\d#eeeeee7f   f      fd0Z]d1eeeeee7f   f      d#dfd2Z^ G d3 d1e$j                        Z`d4e:d#ee7   fd5Za G d6 d7      Zbd#eVfd8Zcd9ePd:eeAgee7   f   d;eeAe7geeA   f   fd<Zd	 dd=Zed> Zfd? Zgd@ ZhdA ZidB ZjdC ZkdD ZldE ZmdF ZndG ZodH Zp eddIefej        eddJ ej                  eidK       ej                  epdK              eddLegek        eddMehel        eddN ej                  eidO       ej                  epdO              eddP ej                  eidQ       ej                  epdQ              eddR ej                  eidS       ej                  epdS             dTee,e"j|                  j~                  e"j                  f   fdUZrdV ZsdW ZtdX Zud#e!ee7ejp                  f      fdYZv G dZ d[      Zw G d\ d]ew      Zx G d^ d_ew      Zy G d` daew      Zzdb Z{ G dc ddew      Z| G de dfew      Z} G dg dhew      Z~di Zd#eVfdjZdk Zd#eVfdlZddmZdn Zee.d&dofdped4e:dqedrePdseVdteVd#dfduZddvZdw Z	 	 ddddxd4e:dye=dqedzeeV   d{eeV   d|ed#efd}Zd~ Zi e_         e j
                  e"j                  d        d Zdee9e7f   d#e7fdZd Z G d d      Z	 	 ddZd Zy)    N)closingcontextmanager)Enum)AnyBinaryIOCallablecastDictIOListOptionalTupleTypeUnion)	TypeAliasTypeIs)get_source_lines_and_file)_import_dotted_name)#_get_dtype_from_pickle_storage_type)Storage)SourceChangeWarningmkdtempregister_package%check_module_version_greater_or_equalvalidate_cuda_devicevalidate_hpu_devicelocation_tagdefault_restore_locationnormalize_storage_typestorage_to_tensor_typesaveloadStorageTypeLoadEndiannessget_crc32_optionsset_crc32_optionsget_default_load_endiannessset_default_load_endiannessget_default_mmap_optionsset_default_mmap_optionsclear_safe_globalsget_safe_globalsadd_safe_globalssafe_globals get_unsafe_globals_in_checkpoint	skip_data   z=lz=iz=hl   l|9QC
 i  ,	FILE_LIKEMAP_LOCATIONSTORAGEwin32a(  In PyTorch 2.6, we changed the default value of the `weights_only` argument in `torch.load` from `False` to `True`. Re-running `torch.load` with `weights_only` set to `False` will likely succeed, but it can result in arbitrary code execution. Do it only if you got the file from a trusted source.)MAP_PRIVATE
MAP_SHARED)NNc                 J    t        t        j                  d       }| d u xr | S )Ngit_version)hasattrtorchversion)pickle_module	is_fbcodes     Z/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/serialization.py_default_to_weights_onlyrA   e   s'    EMM=99ID 2]2    c                        e Zd Z fdZ xZS )_SerializationLocalc                 L    t         |           d | _        d| _        d| _        y )NF)super__init__map_locationr0   materialize_fake_tensors)self	__class__s    r@   rG   z_SerializationLocal.__init__p   s%    48$.3%rB   __name__
__module____qualname__rG   __classcell__rK   s   @r@   rD   rD   o   s    4 4rB   rD   c                       e Zd Zy)r   N)rM   rN   rO    rB   r@   r   r   z   s    rB   r   c               #      K   t        j                         } 	 |  t        j                  |        y # t        j                  |        w xY wwN)tempfiler   shutilrmtreepaths    r@   r   r   ~   s6     D
dds   A2 AA		A_package_registryc                       e Zd ZdZdZdZy)r$      r1      N)rM   rN   rO   NATIVELITTLEBIGrS   rB   r@   r$   r$      s    FF
CrB   r$   _default_load_endianreturnc                      t         S )a  
    Get fallback byte order for loading files

    If byteorder mark is not present in saved checkpoint,
    this byte order is used as fallback.
    By default, it's "native" byte order.

    Returns:
        default_load_endian: Optional[LoadEndianness]
    )rb   rS   rB   r@   r'   r'      s
      rB   c                 B    t        | t              s| t        d      | ay)z
    Set fallback byte order for loading files

    If byteorder mark is not present in saved checkpoint,
    this byte order is used as fallback.
    By default, it's "native" byte order.

    Args:
        endianness: the new fallback byte order
    Nz=Invalid argument type in function set_default_load_endianness)
isinstancer$   	TypeErrorrb   )
endiannesss    r@   r(   r(      s%     j.1j6LWXX%rB   T_compute_crc32c                      t         S )zn
    Get whether :func:`torch.save` computes and writes crc32 for each record.

    Defaults to ``True``.
    ri   rS   rB   r@   r%   r%      s
     rB   compute_crc32c                     | a y)ab  
    Set whether :func:`torch.save` computes and writes crc32 for each record.

    .. note::
        Setting this to ``False`` may make unzipping of the ``torch.save`` output
        fail or warn due to corrupted CRC32. However ``torch.load`` will be
        able to load the file.

    Args:
        compute_crc32 (bool): set crc32 compuation flag
    Nrk   )rl   s    r@   r&   r&      s	     #NrB   _default_mmap_optionsc                      t         S )z
    Get default mmap options for :func:`torch.load` with ``mmap=True``.

    Defaults to ``mmap.MAP_PRIVATE``.


    Returns:
        default_mmap_options: int
    )rn   rS   rB   r@   r)   r)      s
     ! rB   c                   @    e Zd ZdZdeddfdZddZdeded	eddfd
Zy)r*   a  
    Context manager or function to set default mmap options for :func:`torch.load` with ``mmap=True`` to flags.

    For now, only either ``mmap.MAP_PRIVATE`` or ``mmap.MAP_SHARED`` are supported.
    Please open an issue if you need any other option to be added here.

    .. note::
        This feature is currently not supported for Windows.

    Args:
        flags: ``mmap.MAP_PRIVATE`` or ``mmap.MAP_SHARED``
    flagsrc   Nc                     t         rt        d      |t        k7  r|t        k7  rt	        d|       t
        | _        |ay )NzHChanging the default mmap options is currently not supported for WindowszmInvalid argument in function set_default_mmap_options, expected mmap.MAP_PRIVATE or mmap.MAP_SHARED, but got )
IS_WINDOWSRuntimeErrorr7   r8   
ValueErrorrn   prev)rJ   rq   s     r@   rG   z!set_default_mmap_options.__init__   sS    Z  KEZ$7IINQ 
 *	 %rB   c                      y rU   rS   rJ   s    r@   	__enter__z"set_default_mmap_options.__enter__       rB   exc_type	exc_value	tracebackc                     | j                   ay rU   )rv   rn   )rJ   r{   r|   r}   s       r@   __exit__z!set_default_mmap_options.__exit__  s     $		rB   rc   N)	rM   rN   rO   __doc__intrG   ry   r   r   rS   rB   r@   r*   r*      s@    &c &d &* * * * *rB   r*   c                  ,    t        j                          y)zM
    Clears the list of globals that are safe for ``weights_only`` load.
    N)_weights_only_unpickler_clear_safe_globalsrS   rB   r@   r+   r+     s     //1rB   c                  *    t        j                         S )zY
    Returns the list of user-added globals that are safe for ``weights_only`` load.
    )r   _get_safe_globalsrS   rB   r@   r,   r,     s     #4466rB   r.   c                 .    t        j                  |        y)aT  
    Marks the given globals as safe for ``weights_only`` load. For example, functions
    added to this list can be called during unpickling, classes could be instantiated
    and have state set.

    Each item in the list can either be a function/class or a tuple of the form
    (function/class, string) where string is the full path of the function/class.

    Within the serialized format, each function is identified with its full
    path as ``{__module__}.{__name__}``. When calling this API, you can provide this
    full path that should match the one in the checkpoint otherwise the default
    ``{fn.__module__}.{fn.__name__}`` will be used.

    Args:
        safe_globals (List[Union[Callable, Tuple[Callable, str]]]): list of globals to mark as safe

    Example:
        >>> # xdoctest: +SKIP("Can't torch.save(t, ...) as doctest thinks MyTensor is defined on torch.serialization")
        >>> import tempfile
        >>> class MyTensor(torch.Tensor):
        ...     pass
        >>> t = MyTensor(torch.randn(2, 3))
        >>> with tempfile.NamedTemporaryFile() as f:
        ...     torch.save(t, f.name)
        # Running `torch.load(f.name, weights_only=True)` will fail with
        # Unsupported global: GLOBAL __main__.MyTensor was not an allowed global by default.
        # Check the code and make sure MyTensor is safe to be used when loaded from an arbitrary checkpoint.
        ...     torch.serialization.add_safe_globals([MyTensor])
        ...     torch.load(f.name, weights_only=True)
        # MyTensor([[-0.5024, -1.8152, -0.5455],
        #          [-0.8234,  2.0500, -0.3657]])
    N)r   _add_safe_globals)r.   s    r@   r-   r-     s    B --l;rB   c                       e Zd ZdZy)r.   a2  Context-manager that adds certain globals as safe for ``weights_only`` load.

    Args:
        safe_globals: List of globals for weights_only load.

    Example:
        >>> # xdoctest: +SKIP("Can't torch.save(t, ...) as doctest thinks MyTensor is defined on torch.serialization")
        >>> import tempfile
        >>> class MyTensor(torch.Tensor):
        ...     pass
        >>> t = MyTensor(torch.randn(2, 3))
        >>> with tempfile.NamedTemporaryFile() as f:
        ...     torch.save(t, f.name)
        # Running `torch.load(f.name, weights_only=True)` will fail with
        # Unsupported global: GLOBAL __main__.MyTensor was not an allowed global by default.
        # Check the code and make sure MyTensor is safe to be used when loaded from an arbitrary checkpoint.
        ...     with torch.serialization.safe_globals([MyTensor]):
        ...         torch.load(f.name, weights_only=True)
        # MyTensor([[-0.5024, -1.8152, -0.5455],
        #          [-0.8234,  2.0500, -0.3657]])
        >>> assert torch.serialization.get_safe_globals() == []
    N)rM   rN   rO   r   rS   rB   r@   r.   r.   :  s    rB   fc                 h   t        t        j                         j                               }t        t        j                         j                               }|j                  |      }t        | d      5 }t        |      st        d      t        |      5 }t        |      rt        d      t        j                  |j                  d            }t        j                  |      }t        |j!                  |            cddd       cddd       S # 1 sw Y   nxY w	 ddd       y# 1 sw Y   yxY w)a  Returns a list of strings of functions/classes in a ``torch.save`` object that are not safe for ``weights_only``.

    For a given function or class ``f``, the corresponding string will be of the form
    ``{f.__module__}.{f.__name__}``.

    This function will return any GLOBALs in the checkpoint that are not in the set marked safe
    for ``weights_only`` (either via :func:`add_safe_globals` or :class:`safe_globals` context or
    allowlisted by ``torch`` by default).

    .. note::
        This function will statically disassemble the pickle file in the checkpoint.
        The implication is any classes dynamically pushed onto the stack during unpickling
        will not be included in the output.

    Args:
        f: File-like object or string containing the checkpoint object saved via ``torch.save``

    Returns:
        A list of strings of pickle GLOBALs in the checkpoint that are not allowlisted for ``weights_only``.
    rbz8Expected input to be a checkpoint returned by torch.savezYExpected input to be a checkpoint returned by torch.save but got a torchscript checkpointdata.pklN)setr   _get_allowed_globalskeys_get_user_allowed_globalsunion_open_file_like_is_zipfileru   _open_zipfile_reader_is_torchscript_zipioBytesIO
get_recordget_globals_in_pkllist
difference)r   default_safe_globals_stringsuser_safe_global_stringssafe_global_stringsopened_filezip_file	data_fileall_globalss           r@   r/   r/   S  s%   * $'446;;=$   #99;@@B  7<<=UV	D	! 
E[;'WXX!+. 	E("8, o  

8#6#6z#BCI1DDYOK../BCD	E 	E
E 
E	E 	E 	E
E 
E 
Es%   4"D(A)D?	D(D	D((D1c                   *    e Zd ZdZddefdZd Zd Zy)r0   aW  
    Context-manager that skips writing storage bytes for ``torch.save`` calls.

    Storages will still be saved, but the space that their bytes would usually be written to
    will be empty space. The storage bytes can then be populated in a separate pass.

    .. warning::
        The ``skip_data`` context manager is an early prototype and is subject to change.

    Args:
        materialize_fake_tensors: Whether to materialize FakeTensors.

    Example:
        >>> # xdoctest: +SKIP("NamedTemporaryFile on Windows")
        >>> import tempfile
        >>> t = torch.randn(2, 3)
        >>> with tempfile.NamedTemporaryFile() as f:
        ...     with torch.serialization.skip_data():
        ...         torch.save(t, f.name)
        ...     torch.load(f.name, weights_only=True)
        tensor([[0., 0., 0.],
                [0., 0., 0.]])
    rI   c                     || _         y rU   )rI   )rJ   rI   s     r@   rG   zskip_data.__init__  s
    (@%rB   c                     t         j                  | _        t         j                  | _        dt         _        | j                  t         _        y )NT)_serialization_tlsr0   _old_skip_datarI   _old_materialize_fake_tensorsrx   s    r@   ry   zskip_data.__enter__  s6    0::-?-X-X*'+$6:6S6S3rB   c                 X    | j                   t        _        | j                  t        _        y rU   )r   r   r0   r   rI   )rJ   typevaluetbs       r@   r   zskip_data.__exit__  s     '+':':$6:6X6X3rB   N)F)rM   rN   rO   r   boolrG   ry   r   rS   rB   r@   r0   r0   }  s!    0A ATYrB   r0   c                     | j                         }d}| j                  t        |            }| j                  |       ||k(  S )Ns   PK)tellreadlenseek)r   startlocal_header_magic_number
read_bytess       r@   r   r     s@     FFHE -567JFF5M222rB   prioritytaggerdeserializerc                 `    | ||f}t         j                  |       t         j                          y)a  
    Registers callables for tagging and deserializing storage objects with an associated priority.
    Tagging associates a device with a storage object at save time while deserializing moves a
    storage object to an appropriate device at load time. :attr:`tagger` and :attr:`deserializer`
    are run in the order given by their :attr:`priority` until a tagger/deserializer returns a
    value that is not `None`.

    To override the deserialization behavior for a device in the global registry, one can register a
    tagger with a higher priority than the existing tagger.

    This function can also be used to register a tagger and deserializer for new devices.

    Args:
        priority: Indicates the priority associated with the tagger and deserializer, where a lower
            value indicates higher priority.
        tagger: Callable that takes in a storage object and returns its tagged device as a string
            or None.
        deserializer: Callable that takes in storage object and a device string and returns a storage
            object on the appropriate device or None.

    Returns:
        `None`

    Example:
        >>> def ipu_tag(obj):
        >>>     if obj.device.type == 'ipu':
        >>>         return 'ipu'
        >>> def ipu_deserialize(obj, location):
        >>>     if location.startswith('ipu'):
        >>>         ipu = getattr(torch, "ipu", None)
        >>>         assert ipu is not None, "IPU device module is not loaded"
        >>>         assert torch.ipu.is_available(), "ipu is not available"
        >>>         return obj.ipu(location)
        >>> torch.serialization.register_package(11, ipu_tag, ipu_deserialize)
    N)r[   appendsort)r   r   r   
queue_elems       r@   r   r     s+    P FL1JZ(rB   c           	      R   	 | j                   j                  d      t        fdt        |      D              }||k\  }|S # t        $ r[}d| j
                   d| j                    dt        |       }|rt        |      |t        j                  |dz          d}Y d}~|S d}~ww xY w)	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   L   K   | ]  \  }} t        |      |           y wrU   )r   ).0idx	req_fieldversion_strss      r@   	<genexpr>z8check_module_version_greater_or_equal.<locals>.<genexpr>  s-      
Y DOL-.
s   !$'z&' module version string is malformed 'z$' and cannot be compared with tuple z1, but continuing assuming that requirement is metTN)
__version__splittuple	enumerate	ExceptionrM   strrt   warningswarn)modulereq_version_tupleerror_if_malformedmodule_versionrequirement_is_metemessager   s          @r@   r   r     s    *&))//4 
"+,=">
 
 ,/@@   	&  FvGYGYFZ [0124 	 w'Q.MM'$WWX!%	&s   =A 	B&AB!!B&c                 8    | j                   j                  dk(  ryy Ncpudevicer   objs    r@   _cpu_tagr         
zz%  rB   c                 8    | j                   j                  dk(  ryy Nmpsr   r   s    r@   _mps_tagr     r   rB   c                 8    | j                   j                  dk(  ryy )Nmetar   r   s    r@   	_meta_tagr     s    
zz&  !rB   c                     | dk(  rt         j                  j                         } |j                  j                  | k(  r=|j                  j
                  | S | dz   t        |j                  j
                        z   S y )Nprivateuse1:)r<   _C_get_privateuse1_backend_namer   r   indexr   )backend_namer   s     r@   _backend_tagr     sf    }$xx==?
zz,&::##%CJJ,<,<(===	 'rB   c                     |dk(  r| S y r   rS   r   locations     r@   _cpu_deserializer   (  s    5
 rB   c                 F    |j                  d      r| j                         S y r   )
startswithr   r   s     r@   _mps_deserializer   -  s!    5!wwy "rB   c                 X    |dk(  r%t        j                  | j                         d      S y )Nr   r   )r<   UntypedStoragenbytesr   s     r@   _meta_deserializer   2  s(    6##CJJL@@ rB   c                    t        t        |      st        d|j                          d      t	        t        |      }t        |d      rIt        |j
                  d      r3|j
                  j                  | d      }t        j                  ||      }n/t        j                  |       }|j                  r|j                  nd}t        |d      r0|j                         s t        d|j                          d	| d
      t        |d      r;|j                         }||k\  r&t        d|j                          d| d| d| d	      |S )a  
    Check whether the device index of specified backend is valid

    In case of privateuse1 backend, your must first register a device_module for
    privateuse1 using torch._register_device_module. Implement the following
    methods in device_module like cuda: device_module._utils._get_device_index(location, True),
    device_module.device_count().

    Args:
        location: string of device
        backend_name: the backend name or the name of privateuse1, which can be renamed

    Returns:
        device_index: int
    zThe z device module is not registered. 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._utils_get_device_indexTr   is_availablez&Attempting to deserialize object on a z device but torch.z.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.device_countz$Attempting to deserialize object on z device z but torch.z.device_count() is zU. Please use torch.load with map_location to map your storages to an existing device.)r;   r<   rt   uppergetattrr   r   r   r   r   r   )r   r   device_moduledevice_indexr   r   s         r@   _validate_devicer  7  sX     5,'<%%'( )/ /
 	
 E<0M}h'G1- %++==hMlL9h''-||v||}n-m6P6P6R4\5G5G5I4J K  ,~ .//
 	
 }n-$113<'6|7I7I7K6LH.L>9L\N [))  MrB   c                 .    t        | d      j                  S )Ncudar  r   r   s    r@   r   r   k  s    Hf-333rB   c                 .    t        | d      j                  S )Nhpur  r  s    r@   r   r   o  s    He,222rB   c                     | dk(  rt         j                  j                         } |j                  |       rt	        ||       }|j                  |      S y )Nr   r   )r<   r   r   r   r  to)r   r   r   r   s       r@   _deserializer  s  sL    }$xx==?<(!(L9vvVv$$ )rB   
      r           r      r
     xpustoragec                 ~    t         D ]  \  }}} ||       }|s|c S  t        dt        j                  |       z         )Nz-don't know how to determine data location of r[   rt   r<   typename)r  _r   r   s       r@   r   r     sJ     * 61'?O 7%..:QQ rB   c                     t         D ]  \  }}} || |      }||c S  t        dt        j                  |       z   dz   |z   dz         )a  
    Restores `storage` using a deserializer function registered for the `location`.

    This function looks in the registry for deserializer functions that match the `location`.
    If found, it attempts to use them, in priority order, to restore `storage` until one
    returns a not `None` result. If no deserializer can be found in the registry, or all found fail
    to bear a result, it raises a `RuntimeError`.

    Args:
        storage (STORAGE): the storage object to restore
        location (str): the location tag associated with the storage object

    Returns:
        storage: Optional[STORAGE]

    Raises:
        RuntimeError: If no deserializer matching `location` is found in the registry or if
           all matching ones return `None`.
    z+don't know how to restore data location of z (tagged with )r  )r  r   r  fnresults        r@   r   r     so    ( & 1bGX&M 5
..
!	"
	 	 		 rB   c                 6    t        t        | j                        S rU   )r  r<   rM   )storage_types    r@   r   r     s    5,//00rB   c                     t        |       }t        |j                        }t        ||j                  j                  dd            S )Nr   Tensor)r   r   rN   r  rM   replace)r  r   r   s      r@   r    r      s;    =L !8!89F6<0088HMNNrB   c                 B    t        | t        t        j                  f      S rU   )rf   r   osPathLike)name_or_buffers    r@   _is_pathr(    s    nsBKK&899rB   c                       e Zd Zd Zd Zd Zy)_openerc                     || _         y rU   	file_like)rJ   r-  s     r@   rG   z_opener.__init__  s	    "rB   c                     | j                   S rU   r,  rx   s    r@   ry   z_opener.__enter__  s    ~~rB   c                      y rU   rS   rJ   argss     r@   r   z_opener.__exit__  rz   rB   N)rM   rN   rO   rG   ry   r   rS   rB   r@   r*  r*    s    #rB   r*  c                   $     e Zd Z fdZd Z xZS )
_open_filec                 8    t         |   t        ||             y rU   )rF   rG   open)rJ   namemoderK   s      r@   rG   z_open_file.__init__  s    dD)*rB   c                 8    | j                   j                          y rU   )r-  closer0  s     r@   r   z_open_file.__exit__      rB   rM   rN   rO   rG   r   rP   rQ   s   @r@   r3  r3    s    +rB   r3  c                        e Zd Z fdZ xZS )_open_buffer_readerc                 :    t         |   |       t        |       y rU   )rF   rG   _check_seekable)rJ   bufferrK   s     r@   rG   z_open_buffer_reader.__init__  s     rB   rL   rQ   s   @r@   r=  r=    s       rB   r=  c                       e Zd Zd Zy)_open_buffer_writerc                 8    | j                   j                          y rU   )r-  flushr0  s     r@   r   z_open_buffer_writer.__exit__  r:  rB   N)rM   rN   rO   r   rS   rB   r@   rB  rB    s    rB   rB  c                     t        |       rt        | |      S d|v rt        |       S d|v rt        |       S t	        d|       )Nwrz$Expected 'r' or 'w' in mode but got )r(  r3  rB  r=  rt   )r'  r7  s     r@   r   r     sN    .$//$;&~66D[&~66!EdVLMMrB   c                         e Zd Zd fdZ xZS )r   c                 ^    t         |   t        j                  j	                  |             y rU   )rF   rG   r<   r   PyTorchFileReader)rJ   r'  rK   s     r@   rG   z_open_zipfile_reader.__init__  s    33NCDrB   r   rL   rQ   s   @r@   r   r     s    E ErB   r   c                   (     e Zd Zd fdZddZ xZS )_open_zipfile_writer_filec                    d | _         t        |      | _        	 | j                  j                  d       t        |   t        j                  j                  | j                  t                     y # t        $ rd t        j                  | j                  d      | _         t        |   t        j                  j                  | j                   t                     Y y w xY w)NasciirF  )r7  )file_streamr   r6  encoderF   rG   r<   r   PyTorchFileWriterri   UnicodeEncodeErrorr   FileIO)rJ   r6  rK   s     r@   rG   z"_open_zipfile_writer_file.__init__  s    I		TIIW% GUXX77		>RS " 	  "yy=DG**4+;+;^L	s   A1 1A*CCc                     | j                   j                          | j                  | j                  j                          y y rU   )r-  write_end_of_filerO  r9  r0  s     r@   r   z"_open_zipfile_writer_file.__exit__  s5    ((*'""$ (rB   r   r;  rQ   s   @r@   rL  rL    s    T %rB   rL  c                   (     e Zd Zd fdZddZ xZS )_open_zipfile_writer_bufferc                 4   t        t        |dd             sIdt        t        |            j	                  d       d}t        |d      st        |      t        |      || _        t        | )  t        j                  j                  |t                     y )Nwritez
Buffer of z<>z" has no callable attribute 'write')callabler  r   r   stripr;   AttributeErrorrg   r@  rF   rG   r<   r   rQ  ri   )rJ   r@  msgrK   s      r@   rG   z$_open_zipfile_writer_buffer.__init__  s|    67s4<066t<==_`C67+$S))C. 33FNKLrB   c                 l    | j                   j                          | j                  j                          y rU   )r-  rU  r@  rD  r0  s     r@   r   z$_open_zipfile_writer_buffer.__exit__  s"    ((*rB   r   r;  rQ   s   @r@   rW  rW    s    MrB   rW  c                 B    t        |       rt        }nt        } ||       S rU   )r(  rL  rW  )r'  	containers     r@   _open_zipfile_writerra  $  s    -	/	^$$rB   c                 D    dg}	 | j                   |v S # t        $ r Y yw xY w)NgzipF)rN   r\  )r   compress_moduless     r@   _is_compressed_filere  -  s1    x||/// s    	c                     t        |       ry	 | j                         dk\  S # t        j                  $ r Y yt        $ r Y yw xY w)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   )re  filenor   UnsupportedOperationr\  r   s    r@   _should_read_directlyrj  5  sG     1xxzQ""  s   ! AA Ac                     d }	 | j                  | j                                y# t        j                  t        f$ r} |ddg|       Y d }~yd }~ww xY w)Nc                 x    | D ]4  }|t        |      v st        |      dz   dz   dz   } t        |      |       |)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.)r   r   )patternsr   pr]  s       r@   raise_err_msgz&_check_seekable.<locals>.raise_err_msgF  s]     	#ACF{FOPST 66  d1gcl"	# rB   Tr   r   F)r   r   r   rh  r\  )r   ro  r   s      r@   r?  r?  E  sQ    
+	qvvx##^4 +vv&**+s   % AAAc                     | k| j                   dk(  r[d}t        | |d      sKt        dj                  dj	                  |D cg c]  }t        |       c}      | j                              yyyc c}w )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

    Ndill)r   r^   r]   Fz\'torch' supports dill >= {}, but you have dill {}. Please upgrade dill or switch to 'pickle'r   )rM   r   ru   formatjoinr   r   )r>   required_dill_versionnums      r@   _check_dill_versionrv  Z  s      ]%;%;v%E )40%
 A&HH2GH3c#hHI!--	 
 &F  Is    A/c                 J    t        |       st        | d      st        d      y y )NrY  zOexpected 'f' to be string, path, or a file-like object with a 'write' attribute)r(  r;   r\  ri  s    r@   _check_save_filelikerx  r  s+    A;wq'2"
 	
  3;rB   Fr   r>   pickle_protocol_use_new_zipfile_serialization_disable_byteorder_recordc                 h   t         j                  j                  d       t        |       t	        |       |r%t        |      5 }t        | ||||       	 ddd       yt        j                  rt        d      t        |d      5 }t        | |||       ddd       y# 1 sw Y   yxY w# 1 sw Y   yxY w)aA  save(obj, f, pickle_module=pickle, pickle_protocol=2, _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:
        >>> # xdoctest: +SKIP("makes cwd dirty")
        >>> # 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)
    z
torch.saveNzCCannot use skip_data=True with _use_new_zipfile_serialization=Falsewb)r<   r   _log_api_usage_oncerv  rx  ra  _saver   r0   rt   r   _legacy_save)r   r   r>   ry  rz  r{  opened_zipfiler   s           r@   r!   r!   z  s    ` 
HH  .&%!!$ 	) 	 	 ''U  Q% 	Kk=/J	K 	K	 		K 	Ks   BB(B%(B1c           	         dd l m i i i dt        dt        t           ffdt        t        t        j                  dk(  t        t        t        t                    }|j                  t        ||       |j                  t        ||       |j                  |||        G fd	d
|j                        } |||      }|j                  |        t        j!                               }|j                  |||       |j#                          |D ]D  }|   \  }	}
|	j%                  |t'        |      dt(        j*                  j-                  |
             F y )Nr   r   rc   c                 $   t        | t              rKt        | j                        r5| v ry d| <   d x}}	 t	        |       \  }}}dj                  |      }d| ||fS t        | t        j                  j                        st        j                  |       rt        | t        j                  j                        rU| j                  }| j                  }| j!                         }t#        t        |      }| j                  }	| j%                         }
nxt        | t        j&                        rG| }t        j(                  }t+        t        |             }t        j(                  }	|j-                         }
nt/        dt        |              |j1                         dk7  rF|j1                         v r!||j1                            k7  rt3        d      ||j1                         <   d}t5        |j6                        }t9        |      }|vr||	f|<   |j6                  |j6                  k7  }|r't5        |j6                        ||j-                         f}nd }d	||||
|f}|S y # t        $ r) t        j                  d| j                  z   dz          Y 7w xY w)
NT 4Couldn't retrieve source code for container of type 3. It won't be checked for correctness upon loading.r   ztype not recognized: r   SCannot save multiple tensors or storages that view the same data as different typesr  )rf   r   
issubclassModuler   rs  r   r   r   rM   r<   r  TypedStorage
is_storage_untyped_storagedtype_pickle_storage_typer  _sizer   uint8r   r   rg   data_ptrrt   r   _cdatar   )r   source_filesourcesource_linesr  r  storage_dtypestorage_type_strr   r  storage_numeloffsetstorage_keyr   is_viewview_metadataresnnserialized_container_typesserialized_storagesstorage_dtypess                    r@   persistent_idz#_legacy_save.<locals>.persistent_id  sz    c4 ZRYY%?00.2&s+#''K&
/H/M,a. c;77c5==556%:J:J3:O #u}}99: .. #		#&#;#;#= &u.>?		 #		C!5!56 %5d3i@ ' 0"7S	{ CDD
 !Q&##%7$w7G7G7I(JJ*D 
 :GN7#3#3#56 Fgnn-K#G,H> "554;U3C#K0nn6G!$W^^!4fgnn>N O $ C JE  !ll+.44s    I .JJlittle)shortr   long)protocol_versionlittle_endian
type_sizesprotocolc                       e Zd Z fdZy)*_legacy_save.<locals>.PyTorchLegacyPicklerc                      |      S rU   rS   rJ   r   r  s     r@   r  z8_legacy_save.<locals>.PyTorchLegacyPickler.persistent_idP       %%rB   NrM   rN   rO   r  r  s   r@   PyTorchLegacyPicklerr  O      	&rB   r  T)torch.nnr  r   r   r   dictPROTOCOL_VERSIONsys	byteorder
SHORT_SIZEINT_SIZE	LONG_SIZEdumpMAGIC_NUMBERPicklersortedr   rD  _write_filerj  r<   r   _element_size)r   r   r>   ry  sys_infor  picklerserialized_storage_keyskeyr  r  r  r  r  r  r  s              @@@@@r@   r  r    sQ   !#OQ .0Nq3 q8E? q qf )mmx/
H |QA'_Ex_=&}44 & #1?GLL$%8%=%=%?@.OLGGI& 
,S1$Q'u||/I/I%/P	

rB   c                    i i i fdt        j                         } G fdd|j                        } |||      }|j                  |        |j	                         }|j                  d|t        |             |sft        j                  dvrt        dt        j                  z         |j                  dt        j                  t        t        j                               t        j                               D ]{  }	d	|	 }
|	   }|j                         }t        j                  r|j                  |
|       @|j                   j"                  d
k7  r|j%                         }|j                  |
||       } y )Nc                    t        | t        j                  j                        st        j                  |       rt        | t        j                  j                        rI| j
                  }| j                  }| j                         }t        t        |      }| j                         }n6| }t        j                  }t        t        |             }|j                         }t        |j                        dk7  rY|j!                         dk7  rF|j!                         
v r!|
|j!                            k7  rt#        d      |
|j!                         <   j%                  |j&                  t        t)                          }t+        | d      r"| j,                  t        | j,                        }nt/        |      }|	|<   d||||fS y )Nr   r   r  _fake_devicer  )rf   r<   r  r  r  r  r  r  r  r  r  r   r   r   r   r   r  rt   
setdefaultr  r   r;   r  r   )r   r  r  r  r   r  r  r   id_mapr  r  s           r@   r  z_save.<locals>.persistent_idp  s    c5==556%:J:J3:O#u}}99: .. #		#&#;#;#= &u.>? #		  %5d3i@ ' 0
 7>>"f,1A1A1Cq1H##%7$w7G7G7I(JJ*D 
 :GN7#3#3#56 ++GNNCF<LMKsN+0@0@0Ls//0'0/6,|[(MRRrB   c                       e Zd Z fdZy)_save.<locals>.PyTorchPicklerc                      |      S rU   rS   r  s     r@   r  z+_save.<locals>.PyTorchPickler.persistent_id  r  rB   Nr  r  s   r@   PyTorchPicklerr    r  rB   r  r  r   )r  bigUnknown endianness type: r  data/r   )r   r   r  r  getvaluewrite_recordr   r  r  ru   r  r   r   r   r0   write_record_metadatar   r   r   )r   r   r>   ry  r{  data_bufr  r  
data_valuer  r6  r  	num_bytesr  r  r  r  s                @@@@r@   r  r  `  sK    F .0N,^ zz|H&.. & X@GLL""$J*j#j/B %== 1183==HIIk3==#cmm:LM )..01 <se}%c*NN$	''**4;
 ~~""e+!++-!!$;<rB   )weights_onlymmaprH   r  r  pickle_load_argsc          
         t         j                  j                  d       ddt        dt        ffd}t        j
                  }|rt        d      |du }|rt        |      }g d}	t        j                  d	d
      |	v }
t        j                  dd
      |	v }|
r|rt        d      |
rd}n"|r |rt        j                  dt        d       d}|r|t        d      |t        }|d}t        |       d|j                         vrd|d<   t!        | d      5 }t#        |      rk|j%                         }d}t'        |      5 }t)        |      rrt        j                  dt               |rt        dt*        z         |j-                  |       t         j.                  j1                  ||      cddd       cddd       S |rt3        |       st5        d      t        j6                  j9                  |       }t:        st=               t>        k(  }nd}t         j@                  jC                  t        jD                  |       ||      }|r'	 tG        ||tH        fd|i|cddd       cddd       S tG        |||fd|i|cddd       cddd       S |r&tM        | t              sdn|  d}t        d| d      |r	 tO        ||tH        fi |cddd       S tO        |||fi |cddd       S # t        jJ                  $ r*}t        jJ                   |t        |                  dd}~ww xY w# 1 sw Y   xY w# t        jJ                  $ r*}t        jJ                   |t        |                  dd}~ww xY w# 1 sw Y   yxY w)a  load(f, map_location=None, pickle_module=pickle, *, weights_only=True, mmap=None, **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)
        weights_only: Indicates whether unpickler should be restricted to
            loading only tensors, primitive types, dictionaries
            and any types added via :func:`torch.serialization.add_safe_globals`.
            See :ref:`weights-only` for more details.
        mmap: Indicates whether the file should be mmaped rather than loading all the storages into memory.
            Typically, tensor storages in the file will first be moved from disk to CPU memory, after which they
            are moved to the location that they were tagged with when saving, or specified by ``map_location``. This
            second step is a no-op if the final location is CPU. When the ``mmap`` flag is set, instead of copying the
            tensor storages from disk to CPU memory in the first step, ``f`` is mmaped.
        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()` unless `weights_only` parameter is set to `True`,
        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 in an unsafe mode, 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:
        >>> # xdoctest: +SKIP("undefined filepaths")
        >>> torch.load("tensors.pt", weights_only=True)
        # Load all tensors onto the CPU
        >>> torch.load("tensors.pt", map_location=torch.device("cpu"), weights_only=True)
        # Load all tensors onto the CPU, using a function
        >>> torch.load(
        ...     "tensors.pt", map_location=lambda storage, loc: storage, weights_only=True
        ... )
        # Load all tensors onto GPU 1
        >>> torch.load(
        ...     "tensors.pt",
        ...     map_location=lambda storage, loc: storage.cuda(1),
        ...     weights_only=True,
        ... )  # type: ignore[attr-defined]
        # Map tensors from GPU 1 to GPU 0
        >>> torch.load("tensors.pt", map_location={"cuda:1": "cuda:0"}, weights_only=True)
        # Load tensor from io.BytesIO object
        # Loading from a buffer setting weights_only=False, warning this can be unsafe
        >>> with open("tensor.pt", "rb") as f:
        ...     buffer = io.BytesIO(f.read())
        >>> torch.load(buffer, weights_only=False)
        # Load a module with 'ascii' encoding for unpickling
        # Loading from a module setting weights_only=False, warning this can be unsafe
        >>> torch.load("module.pt", encoding="ascii", weights_only=False)
    z
torch.loadz

Check the documentation of torch.load to learn more about types accepted by default with weights_only https://pytorch.org/docs/stable/generated/torch.load.html.r   rc   c                    d}t        j                  ||       d u}d}t        j                  ||       d u}d}t        j                  ||       d u}|rdt         d| z   }|z   S |rd|  dt         dS dt         d}|s|d	z  }|| z  }|z   S )
Nz2GLOBAL (\S+) was not an allowed global by default.zwhose module (\S+) is blockedz(\S+) must be (\S+) to loadzWeights only load failed. This file can still be loaded, to do so you have two options, [1mdo those steps only if you trust the source of the checkpoint[0m. 
	(1) z
	(2) Alternatively, to load with `weights_only=True` please check the recommended steps in the following error message.
	WeightsUnpickler error: zWeights only load failed. z
 
zPlease file an issue with the following so that we can make `weights_only=True` compatible with your use case: WeightsUnpickler error: )researchUNSAFE_MESSAGE)	r   unsafe_global_patternhas_unsafe_globalblocklist_patternhas_blocklistimport_pattern
has_importupdated_messageDOCS_MESSAGEs	           r@   _get_wo_messagezload.<locals>._get_wo_message;  s     UII&;WETQ<		"3W=TI7YY~w7tC
)* +dd 	 $ -- 3G9C?OrRR$>~>Nb"Q$#fO w&O--rB   z`torch.load` called within a torch.serialization.skip_data context manager is not supported yet. Please call torch.load outside the skip_data context manager.N)1yyestrueTORCH_FORCE_WEIGHTS_ONLY_LOAD0 TORCH_FORCE_NO_WEIGHTS_ONLY_LOADzsOnly one of `TORCH_FORCE_WEIGHTS_ONLY_LOAD` or `TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD` should be set, but both were set.TzEnvironment variable TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD detected, since the`weights_only` argument was not explicitly passed to `torch.load`, forcing weights_only=False.r1   )
stacklevelFzDCan not safely load weights when explicit pickle_module is specifiedencodingzutf-8r   z'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)zUCannot use ``weights_only=True`` with TorchScript archives passed to ``torch.load``. )rH   z7f must be a file path in order to use the mmap argumentoverall_storager  z, z8mmap can only be used with files saved with `torch.save(zn_use_new_zipfile_serialization=True), please torch.save your checkpoint with this option in order to use mmap.)(r<   r   r~  r   r   r0   rt   rA   r%  getenvr   r   UserWarningpicklerv  r   r   r   r   r   r   r  r   jitr"   r(  ru   rZ   getsizers   r)   r8   r   	from_filefspath_loadr   UnpicklingErrorrf   _legacy_load)r   rH   r>   r  r  r  r  r0   weights_only_not_settrue_valuesforce_weights_only_loadforce_no_weights_only_loadr   orig_positionr  r  sizesharedr   f_namer  s                       @r@   r"   r"     s   d 
HH  .	R 
. . .: #,,Ib
 	

 (4//>+K 			137;F  			4c:kI  #=0
 	
 
!	#MMq	 !L$V   "M |&)..00'.$	D	! H
[{# (,,.M"O%k2 -n&~6MM1 $	 $*/1?@   $$]3 99>>+L>Q- -H
 H
, #A;(U  77??1-D%!9!;z!I!&&+&:&:&D&D		!fd'O  	X$*(3  -<	 
 / =- -H
 H
\ " ! %4	
 'O- -H
 H
j )!S1R!BxF%h '[[ 
 P# + '	}H
 H
L }
8H
MH
 H
X "11 X$44_SV5LMSWWXK- -z )) P,,_SV-DE4OPIH
 H
s   *M7 A+L++	M7>BL+K+	M7,L+;	M7*M79L7M7+L(>%L##L((L++L4	0M77M4
%M//M44M77N c                     t         j                  }|sLt        j                  j	                         D ]+  }t        |t        j                        s||t        |      <   - ||    S )z;Get layout extension object from its string representation.)_get_layoutcacher<   __dict__valuesrf   layoutr   )r6  r  vs      r@   r  r    sS    E&&( 	"A!U\\* !c!f	" ;rB   c                 &    t         t        |       ffS rU   )r  r   r   s    r@   <lambda>r    s    +C{)C rB   c           	         i t        |       G d dj                        d fd}i fd}t        |        t        |       }|r| j	                         dk(  r		  ||       S t        | d      s4d	t        j                  cxk  rd
k  rn nt        dt        |        d       j                  | fi }|t         k7  rt        d       j                  | fi }|t"        k7  rt        d|        j                  | fi }	 | fi }
||
_        |
j                         } j                  | fi }t&        j(                  j+                         ~|r| j	                         nd }|D ]e  }|v sJ |   }|j,                  j/                  | ||t&        j0                  j3                  |j4                               |V| j	                         }g t&        j0                  j7                          |S # t
        j                  $ r9 t        |       rt        | j                   d      d | j                  d       Y w xY w)Nc                        e Zd Z fdZ xZS )&_legacy_load.<locals>.UnpicklerWrapperc                     t        |      t        u rd|v r	 t        |      S t        |   ||      S # t        $ r Y w xY wNr   )r   r   r#   KeyErrorrF   
find_class)rJ   mod_namer6  rK   s      r@   r  z1_legacy_load.<locals>.UnpicklerWrapper.find_class  sN    DzS Y$%6&t,, 7%h55   s   
3 	??rM   rN   rO   r  rP   rQ   s   @r@   UnpicklerWrapperr    s    	6 	6rB   r  c                 >   	 dj                  t        |       d         }||k7  r"| j                  r| j
                  dz   }t        j                  |j                  d      |j                  d      ||d      }dj                  |      }	 t        |d      5 }|j                  dd	      }|j                  d       |dk(  r|j                  |       n'|t        |      k7  s|j                         |k7  rt        d d d        d
|z   dz   |z   dz   }	nd}	dt!        j"                  |        d|	 }	t        j                  |	t$               y y # t        $ r( t        j                  d| j
                  z   dz          Y y w xY w# 1 sw Y   xY w# t        $ r d|z   dz   }	Y w xY w)Nr  r   r  r  z.patchr  )linetermza+r1   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. )rs  r   r   r   r   rM   dump_patchesdifflibunified_diffr   r5  r   rY  r   r   OSErrorr<   r  r   )
container_typer  original_sourcecurrent_source	file_namedifflinesr   	file_sizer]  s
             r@   _check_container_sourcez-_legacy_load.<locals>._check_container_source  s   	WW%>~%Nq%QRN n,***33h>	++"((.#))$/ 		$i. *!$%FF1aL	q	$>GGEN&#e*4E8I")M* 4i? C, ,.78;## 8  +5>>.+I*J/Z]Y^_CMM#23O -  	MM(112500
 	&* *  )+458$$ s<   E 
F A"E<8F .E98E9<FF FFc                     i !fd}t        t        j                  | dt        j                              5 }t	               5 }#t
        u rt        dt        z         |j                  d|       t        t        j                  j                  |d      dd      5 }  #j                  | fi "}t        |      D ]  } #j                  | fi "}|\  }}}	|	j                  }
t        t         t"        j$                        j'                  | t"        j(                  j+                  |
            } $||      }t"        j,                  j/                  ||
d	
      |<     #j                  | fi "}|D ]|  \  }}}}|   }t"        j(                  j+                  |j0                        }||z  }t"        j,                  j/                  |j2                  ||||z  z    |j0                  d	
      |<   ~ 	 d d d        |j                  d|       t        t        j                  j                  |d      dd      5 }  #j                  | fi "}t        |      D ]  } #j                  | fi "}|\  }}}|   }t5        j6                  d| j9                  d            \  }| j9                  d       t5        j6                  d| d| j9                  d|z              }t5        j6                  d| d| j9                  d|z              }t5        j6                  d| j9                  d            \  }t#        j:                  d|j0                        j=                  |j2                  |||      }||<    	 d d d        |j?                  d      }  |fi "}||_         |j                         }|cd d d        cd d d        S # 1 sw Y   xY w# 1 sw Y   [xY w# 1 sw Y   nxY wd d d        y # 1 sw Y   y xY w)Nc                 p    t        | t              rt        | dd        r |   | d   S t        |          S )Nr]   r   )rf   r   allr   )saved_idr&  deserialized_objectss    r@   persistent_loadz:_legacy_load.<locals>.legacy_load.<locals>.persistent_load1  s<    (E*x|$+X6{"'H66rB   zr:)fileobjr7  rr  zMCannot use ``weights_only=True`` with files saved in the legacy .tar format. storagesrY   r   r   Twrap_storager  	_internaltensorsz<i   <q   z<q)r   r  r  )!r   tarfiler5  
PAX_FORMATr   r   rt   r  extractr%  rZ   rs  r"   range_dtyper	   r   r<   r   _new_with_filer   r  r  r  r  r  structunpackr   emptyset_extractfiler,  )%r   r,  tartmpdirnum_storagesr  r1  r  r   r   r  r   storage_viewstarget_cdata
root_cdatar  numelrootelement_sizeoffset_bytesnum_tensors
storage_id_original_tensor_typer  ndimstridestorage_offsettensorpickle_file	unpicklerr  r+  r  r&  r  r>   restore_locations%                                  @r@   legacy_loadz!_legacy_load.<locals>.legacy_load.  s   /1	7 LLg6H6HI
 >	')>	% 77"+-;<  KK
K0bggll6:6a@ A1}11!H7GH|, A-=--aD3CDD26/C<(//Ew(<(<=LL5<<55e<C +39C 160J0J%( 1K 1(- !3 2 21 I8H I?L ;L*fe/
;D#(<<#=#=djj#IL#)L#8L :?9S9S%)%:%:(<%,:N+N& #jj"& :T :(6#> KK	K/bggll695tQ? 710m00G6FG{+ 7A-=--aD3CDD=A:C%:2:>G$mmD!&&)<GTFF1I"MMAdV1+qvva$h7GHE#]]QtfA;q4x8HIF(.dAFF1I(F%^"[[W]]CHH00.%F 17(-77" //(3K(I8HII(7I%^^%F}>	 >	 >	 @7 7S>	 >	 >	 >	 >	sW   O4AOEO5AO;D=O9:O3	O4OOOOO(	$O44O=c                 :   t        | t              sJ t        | d         }| dd  }|dk(  rt        |dd        r |  |d   S |dk(  r|\  }}}}}t        |      }|j                  }|t
        j                  j                  |      z  }	|vrt
        j                  j                         &t        t        t        j                  |	d            }
n3t        t        t        j                  |	            }
d|
_         |
|      }
t
        j                  j                  |
|d      }||<   nN|   }|j!                         dk(  r6t
        j                  j                  |j"                  j$                  |d	      }||\  }}}|t
        j                  j                  |      z  }|t
        j                  j                  |      z  }|vr5t
        j                  j                  |j"                  |||z    |d      |<   |   }|S |}|S t'        d
| d          )Nr   r]   r   r  r   r   Tr/  )r   r  r1  zUnknown saved id type: )rf   r   _maybe_decode_asciir)  r  r<   r   r  _guardsactive_fake_moder	   r   r   _torch_load_uninitializedr  r  	_data_ptrr  r   rt   )r*  r  datar   root_keyr   rI  r  r  r   r   typed_storageview_keyr  	view_sizerL  view_size_bytesr  r&  r+  rV  s                     r@   r,  z%_legacy_load.<locals>.persistent_load{  s7   (E***&x{3|x48}'.7N"EIBL(He]*84H &&EU\\77>>F33==113?w(<(<VF(STCw(<(<V(DEC48C1*39C !& : :!$ET !; ! 2?$X. 4X > **,1$)MM$>$>,==DD#"& %? %M (.;+&)%(B(B5(II"+ell.H.H.O"O#77 6;]]5O5O%2%C%C(</+I& $"& 6P 6(2 +84 J $J!8!FGGrB   r   z9 is a zip archive (did you mean to use torch.jit.load()?)readinto)r^   r6  r   )r^   r6  r1   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: )_get_restore_location	Unpicklerr?  rj  r   r8  TarErrorr   rt   r6  r   r;   r  version_infor   r"   r  r  r,  r<   rZ  r[  r  _set_from_filer   r  r  _validate_loaded_sparse_tensors)r   rH   r>   r  rW  r,  f_should_read_directlymagic_numberr  	_sys_inforU  r  deserialized_storage_keysr  r  r`  r  r&  r+  rV  s     ``            @@@@r@   r  r    sl   +-,\:6=22 614fI IV ;Hz A215!&&(a-		q>! 1j!i33C3C&Oi&O((,Qy 1
 	
 &=%%a<+;<L|#@AA)}))!@/?@++78H7IJKK"""19(89I 7&67I /I^^F 2 2 21 I8H I}}%%'/3, 
	"C....05M**99&**=+>+>?	 !
	" 
LL002M]  	1~"vvhWX FF1I	s   *H AII	bytes_strc                 H    t        | t              r| j                  d      S | S )NrN  )rf   bytesdecode)ro  s    r@   rY  rY    s%     )U#((rB   c                       t         }|S t         t              r fd}|S t         t        t        f      r fd}|S t         t
        j                        r fd}|S  fd}|S )Nc                 @    j                  ||      }t        | |      S rU   )getr   r  r   rH   s     r@   rV  z/_get_restore_location.<locals>.restore_location  s"    #''(;H+GX>>rB   c                     t        |       S rU   r   rv  s     r@   rV  z/_get_restore_location.<locals>.restore_location  s    +G\BBrB   c                 .    t        | t                    S rU   )r   r   rv  s     r@   rV  z/_get_restore_location.<locals>.restore_location  s    +GS5FGGrB   c                 6     | |      }|t        | |      }|S rU   rx  )r  r   r  rH   s      r@   rV  z/_get_restore_location.<locals>.restore_location  s%    !'84F~1'8DMrB   )r   rf   r  r   rq  r<   r   )rH   rV  s   ` r@   re  re    sy    32 1 
L$	'	?, % 
L3,	/	C   
L%,,	/	H 	 rB   c                   (    e Zd Zd Zed        Zd Zy)r#   c                 $    t        |      | _        y rU   )r   r<  )rJ   r6  s     r@   rG   zStorageType.__init__  s    9$?rB   c                     | j                   S rU   )r<  rx   s    r@   r  zStorageType.dtype  s    {{rB   c                 "    d| j                    dS )NzStorageType(dtype=r  r7  rx   s    r@   __str__zStorageType.__str__#  s    #DJJ<q11rB   N)rM   rN   rO   rG   propertyr  r  rS   rB   r@   r#   r#     s!    @  2rB   r#   c                     t        |      i d}d  j                  |      r1 j                  |      dvrt        dj	                         z         t               t        j                  k(  s
t               dnEt               t        j                  k(  rdn't               t        j                  k(  rnt        d       j                  |      s7t               -t        j                  dk(  rt        j                  dt                fd	fd
}ddi G fdd|j                        }t!        j"                   j                  |            }	 ||	fi |}
||
_        |t&        _        |
j+                         }d t&        _        t,        j.                  j1                          t,        j2                  j5                  dd j7                         i       |S )Nr  )   little   bigr  r  r  zInvalid load endianness typer  a  The default load endianness for checkpoints without a byteorder mark on big endian machines was changed from 'native' to 'little' endian, to avoid this behavior please use torch.serialization.set_default_load_endianness to set the desired default load endiannessc                 X   d| }t         j                  j                  d       :|t         j                  j	                  |       z  }t        j
                  |d      }nUj                  |      }|||z    }n9j                  ||t         j
                        j                         j                  }	2	j                         t        j                  k7  r|j                  |        t         j                  j                   ||      | d      }|j!                         dk7  r|
|<   |S )Nr  r   r   Tr/  r   )r<   rZ  detect_fake_moder   r  r   get_record_offsetget_storage_from_record_typed_storager  rr  r  r  byteswapr  r  r]  )r  rI  r  r   r6  r   r  rR  r`  byteorderdataloaded_storagesr  rV  r   s            r@   load_tensorz_load.<locals>.load_tensorV  s   se}==))$/;U\\77>>F**6&AG(%77=N%n~7MNG 00ue>R>RS!!!  $##%6  ' 22)'8< 3 
 ""$)#0OC rB   c                 `   t        | t              sJ t        | d         }| dd  }|dk(  sJ d| d       |\  }}}}|t        j                  u rt        j
                  }n|j                  }|v r|   }|S |t        j                  j                  |      z  }	 
||	|t        |            }|S )Nr   r]   r  zBUnknown typename for persistent_load, expected 'storage' but got 'r   )	rf   r   rY  r<   r   r  r  r   r  )r*  r  r^  r   r  r   rI  r  r`  r   r  r  s             r@   r,  z_load.<locals>.persistent_loadv  s    (E***&x{3| 	!	\OPXzYZ[	\!-1*c8U5///KKE &&E/!+C0M  U\\77>>F'vs$7$AM rB   ztorch.tensorztorch._tensorc                   "     e Zd Z fdZ xZS )_load.<locals>.UnpicklerWrapperc                     t        |      t        u rd|v r	 t        |      S j	                  ||      }t
        |   ||      S # t        $ r Y -w xY wr  )r   r   r#   r  ru  rF   r  )rJ   r  r6  rK   load_module_mappings      r@   r  z*_load.<locals>.UnpicklerWrapper.find_class  s`    DzS Y$%6&t,, +..xBH7%h55   s   
A 	AAr  )rK   r  s   @r@   r  r    s    	6 	6rB   r  ztorch.load.metadataserialization_id)re  
has_recordr   ru   rr  r'   r$   r`   ra   r_   r  r  r   r   r  rf  r   r   r,  r   rH   r"   r<   r   rj  r   _log_api_usage_metadatar  )r   rH   r>   rT  r  r  byteordernamer,  r  r   rU  r  r  r  r  r  rV  s   `   `       @@@@@r@   r  r  '  s    -\:O  MM=) ++M: 338=;O;O;QQRR#%)>)>>&(0!	$	&.*<*<	<	$	&.*?*?	?788 .')1MMU" 	2
 	
 @4 	+6=22 6 

8..{;<I ?.>?I /I '3#^^F&*#	LL002	HH$$ 2H4M4M4OP MrB   c                 &    d| j                         v S )Nzconstants.pkl)get_all_records)r   s    r@   r   r     s    h66888rB   r   )T)r   N)copyregr  	functoolsr   r%  r  r  rW   r>  r  r8  rV   	threadingr   
contextlibr   r   enumr   typingr   r   r   r	   r
   r   r   r   r   r   r   typing_extensionsr   r   r<   torch._weights_only_unpicklerr   torch._sourcesr   torch._utilsr   torch.storager   torch.typesr   __all__DEFAULT_PROTOCOLStructr  r  r  r  r  r  STORAGE_KEY_SEPARATORr   r&  rq  r3   __annotations__r   r4   r  r  r   r5   platformrs   r  r  r7   r8   rA   localrD   r   Warningr   r   r[   r   r$   rb   r'   r(   ri   r   r%   r&   rn   r)   r*   r+   r,   r-   _safe_globalsr.   r/   r0   r   r   r   r   r   r   r   r   r   r   r  r   r   r  partialr   r   r   r    r(  r*  r3  r=  rB  r   r   rL  rW  ra  re  rj  r?  rv  rx  objectr!   r  r  r"   r  r  r  r  rY  re  r#   r  r   rS   rB   r@   <module>r     s      	 	  	   
     .     0  ? 4 , = :  FMM$$$	6==##V]]4 %%
%  S"++xEBC	9 C"	(GS>7*
+U\\3S#X
NOi  7EMM$>$>@T@TTU U\\W$
  ,,(J34)// 4 )* 	' 	    4	'HSM)*'3'!223	5 T  26 h~. 5 Xn%=  &"  4 #T #  ) s (
!# 
!!* !*H27$uXuXs]/C%CDE 7!<4hhm8L.L(M#N !<SW !<H*88 2'E	 'Ed3i 'ET&Y &YR3d 3 **gY-.* GS>8G+<<=*` )X


>

A
1h43% X/ 0 IlF+IlF+
 X/ 0 Y 1 2 IlM2IlM2
 IlE*IlE*
 IlE*IlE*	7EMM668L8LLM	B1O:uS"++-='> ? :   '  ' 
	NE7 E
% %.' %d  $ *0
  ++/&+EK	EKEK EK 	EK
 %)EK  $EK 
EKP[
|`<J "&V

 $(V
V
V
 V

 4.V
 4.V
 V
 	V
v   u||C DAH	5#4 	 	<	2 	2  L^9rB   