U
    dϾ                     @   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 mZ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mZm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)m*Z* d
dl+m,Z, d
dl-m.Z. d
dl/m0Z0 d
dl1m2Z2m3Z3 d
dl4m5Z5m6Z6m7Z7 dZ8ede9gdf Z:G dd deZ;G dd deZ<eG dd dZ=G dd de>Z?G dd de>Z@G dd dZAd d!gZBd"ZCe9e9d#d$d%ZDdS )&    N)OrderedDictdefaultdict)	dataclass)Enum)Path)AnyBinaryIOCallableDictListOptionalSequenceSetUnioncastDefaultDict)location_tagnormalize_storage_type)Storage)RemovableHandle   )DiGraph)_normalize_path)demangle
is_mangled)create_pickler)is_stdlib_module)find_files_source_depends_on)	GlobGroupGlobPattern)ImporterOrderedImportersys_importerTPackageExporterc                   @   s(   e Zd ZdZdZdZdZdZdZdZ	dS )	_ModuleProviderActionzRepresents one of the actions that :class:`PackageExporter` can take on a module.

    See :meth:`PackageExporter.extern` and friends for a description of what the actions do.
    r                  N)
__name__
__module____qualname____doc__INTERNEXTERNMOCKDENYREPACKAGED_MOCK_MODULESKIP r4   r4   B/tmp/pip-unpacked-wheel-ua33x9lu/torch/package/package_exporter.pyr$   -   s   r$   c                   @   s4   e Zd ZdZdd ZdZdZdZdZdZ	d	Z
d
ZdS )PackagingErrorReasonzListing of different reasons a dependency may fail to package.

    This enum is used to provide good error messages when
    :class:`PackagingError` is raised.
    c                 C   s   d| j j| jf S )Nz<%s.%s>)	__class__r*   nameselfr4   r4   r5   __repr__I   s    zPackagingErrorReason.__repr__zKModule is a C extension module. torch.package supports Python modules only.zModule had no __file__ defined.zCModule had a __file__, but we could not find it in your filesystem.zDependency resolution failed.zLModule did not match against any action pattern. Extern, mock, or intern it.zModule was denied by a pattern.zModule was mocked out, but is still being used in the package. Please intern or extern the mocked modules if objects are supposed to be in the package.N)r*   r+   r,   r-   r;   IS_EXTENSION_MODULENO_DUNDER_FILESOURCE_FILE_NOT_FOUNDDEPENDENCY_RESOLUTION_FAILED	NO_ACTIONDENIEDMOCKED_BUT_STILL_USEDr4   r4   r4   r5   r6   B   s   r6   c                   @   s2   e Zd ZU dZeed< eed< eed< dd ZdS )_PatternInfozQHolds :class:`PackageExporter`-specific info about how to execute matches againstactionallow_emptywas_matchedc                 C   s   || _ || _d| _d S )NF)rD   rE   rF   )r:   rD   rE   r4   r4   r5   __init__j   s    z_PatternInfo.__init__N)r*   r+   r,   r-   r$   __annotations__boolrG   r4   r4   r4   r5   rC   _   s
   
rC   c                   @   s   e Zd ZdZdS )EmptyMatchErrorzThis is an exception that is thrown when a mock or extern is marked as
    ``allow_empty=False``, and is not matched with any module during packaging.
    N)r*   r+   r,   r-   r4   r4   r4   r5   rJ   p   s   rJ   c                       s&   e Zd ZdZed fddZ  ZS )PackagingErrorzThis exception is raised when there is an issue with exporting a package.
    ``PackageExporter`` will attempt to gather up all the errors and present
    them to you at once.
    )dependency_graphc           
         s   t t}|j D ]@\}}|d}|d kr.q|tjkrDd|ksDt|| | qt	
 }|d | D ]b\}}|d|j d |D ]@}|d| d |j| d}	|	d k	r|d|	 d qqn|| _t |  d S )NerrorrD   
z* z    error_contextz      Context: )r   listnodesitemsgetr6   r@   AssertionErrorappendioStringIOwritevaluerL   superrG   getvalue)
r:   rL   brokenmodule_nameattrsrM   messagereasonZmodule_namesrO   r7   r4   r5   rG   ~   s&    


zPackagingError.__init__)r*   r+   r,   r-   r   rG   __classcell__r4   r4   ra   r5   rK   x   s   rK   c                   @   s  e Zd ZU dZeed< efeee	e
f eeee f dddZdqeeddd	Zed
ddZeeeee dddZdreeeedddZdseeedddZedddZeedddZejee dddZdtedd d!Zduedd"d#Zeed$d%d&Zdveeeeed(d)d*Zeeed+d,d-Z e!d.d/d0Z"e#e$d1d2d3Z%e#e$d1d4d5Z&e#e$d1d6d7Z'd8dd9d:d:ed;d<d=Z(d8dd9d:d:ed;d>d?Z)d8dd9d:d:ed;d@dAZ*d8dBd:d:dCdDdEZ+dFdG Z,dHdI Z-dJdK Z.dLdM Z/dNdO Z0dPdQ Z1dRdS Z2dTdU Z3dVdW Z4dXdY Z5dZd[ Z6edd\d]Z7ed
d^d_Z8ee9 ee d`dadbZ:ee d
dcddZ;ee d
dedfZ<ee d
dgdhZ=ee d
didjZ>eee ddkdlZ?eeedmdndoZ@dpS )wr#   a  Exporters allow you to write packages of code, pickled Python data, and
    arbitrary binary and text resources into a self-contained package.

    Imports can load this code in a hermetic way, such that code is loaded
    from the package rather than the normal Python import system. This allows
    for the packaging of PyTorch model code and data so that it can be run
    on a server or used in the future for transfer learning.

    The code contained in packages is copied file-by-file from the original
    source when it is created, and the file format is a specially organized
    zip file. Future users of the package can unzip the package, and edit the code
    in order to perform custom modifications to it.

    The importer for packages ensures that code in the module can only be loaded from
    within the package, except for modules explicitly listed as external using :meth:`extern`.
    The file ``extern_modules`` in the zip archive lists all the modules that a package externally depends on.
    This prevents "implicit" dependencies where the package runs locally because it is importing
    a locally-installed package, but then fails when the package is copied to another machine.

    When source code is added to the package, the exporter can optionally scan it
    for further code dependencies (``dependencies=True``). It looks for import statements,
    resolves relative references to qualified module names, and performs an action specified by the user
    (See: :meth:`extern`, :meth:`mock`, and :meth:`intern`).
    importer)frc   c                 C   s   t jd t|ttfr*t|}d| _n|| _t j|| _| j	d t
 | _i | _t | _t j| j| _| j | _t | _t | _t | _t|tr|| _n,t|tjjstdt| dt| | _i | _d| _dS )a  
        Create an exporter.

        Args:
            f: The location to export to. Can be a  ``string``/``Path`` object containing a filename
                or a binary I/O object.
            importer: If a single Importer is passed, use that to search for modules.
                If a sequence of importers are passsed, an ``OrderedImporter`` will be constructed out of them.
        ztorch.package.PackageExporterNr)   zCimporter arg should be an Importer or a sequence of Importers, got z	 instead.r   ) torchZ_CZ_log_api_usage_once
isinstancer   strbufferZPyTorchFileWriterzip_fileZset_min_versionset_written_filesserialized_reducesr   rL   ZScriptModuleSerializerscript_module_serializerstorage_contextr   _extern_hooks_mock_hooks_intern_hooksr    rc   collectionsabcr   	TypeErrortyper!   patterns
_unique_id)r:   rd   rc   r4   r4   r5   rG      s0    

zPackageExporter.__init__T)r]   file_or_directoryc                 C   s   t |}| rg }|dd}|dD ]}|| }|d | }	d}
|jdkrv|	dtd  dd}
d}n|	dtd  dd}
d	}||
t	t
|||f q*|D ]}| j|  qn|jdk}| |t	||| dS )
a  Adds the local file system ``file_or_directory`` to the source package to provide the code
        for ``module_name``.

        Args:
            module_name (str): e.g. ``"my_package.my_subpackage"``, code will be saved to provide code for this package.
            file_or_directory (str): the path to a file or directory of code. When a directory, all python files in the directory
                are recursively copied using :meth:`save_source_file`. If a file is named ``"/__init__.py"`` the code is treated
                as a package.
            dependencies (bool, optional): If ``True``, we scan the source for dependencies.
        ./z**/*.pyNz__init__.py/__init__.pyT.pyF)r   is_dirreplaceglobrelative_toas_posixr8   lenrU   
_read_filerg   save_source_string)r:   r]   rx   dependenciespathZto_savemodule_pathfilenamerelative_patharchivenameZsubmodule_name
is_packageitemr4   r4   r5   save_source_file   s@    
 
	
z PackageExporter.save_source_file)returnc                 C   s   t | j}|  jd7  _|S )zMGet an id. This id is guaranteed to only be handed out once for this package.r   )rg   rw   )r:   retr4   r4   r5   get_unique_id)  s    
zPackageExporter.get_unique_id)srcr]   r   r   c              
   C   s   |r|n|j dddd }zt||}W nB tk
rj } z$| jj|tjt|d g  W Y S d}~X Y nX i }|D ]D\}}	|	dk	r| d|	 }
| |
rd||
< qt| |rtd||< qtt	|
 S )al  Return all modules that this source code depends on.

        Dependencies are found by scanning the source code for import-like statements.

        Arguments:
            src: The Python source code to analyze for dependencies.
            module_name: The name of the module that ``src`` corresponds to.
            is_package: Whether this module should be treated as a package.
                See :py:meth:`save_source_string` for more info.

        Returns:
            A list containing modules detected as direct dependencies in
            ``src``.  The items in the list are guaranteed to be unique.
        ry   r   )maxsplitr   )rM   rO   NT)rsplitr   	ExceptionrL   add_noder6   r?   rg   _module_existsrP   keys)r:   r   r]   r   package_nameZ	dep_pairser   Zdep_module_nameZdep_module_objZpossible_submoduler4   r4   r5   _get_dependencies/  s*    


z!PackageExporter._get_dependenciesF)r]   r   r   r   c                 C   sP   | j j|||dtjd |rL| |||}|D ]}| j || | | q.dS )a  Adds ``src`` as the source code for ``module_name`` in the exported package.

        Args:
            module_name (str): e.g. ``my_package.my_subpackage``, code will be saved to provide code for this package.
            src (str): The Python source code to save for this package.
            is_package (bool, optional): If ``True``, this module is treated as a package. Packages are allowed to have submodules
                (e.g. ``my_package.my_subpackage.my_subsubpackage``), and resources can be saved inside them. Defaults to ``False``.
            dependencies (bool, optional): If ``True``, we scan the source for dependencies.
        T)sourcer   providedrD   N)rL   r   r$   r.   r   add_edgeadd_dependency)r:   r]   r   r   r   depsdepr4   r4   r5   r   `  s    z"PackageExporter.save_source_string)r]   r   r   c                 C   s,   |rdnd}| dd| }| || dS )zWrite ``src`` as the source code for ``module_name`` in the zip archive.

        Arguments are otherwise the same as for :meth:`save_source_string`.
        r{   r|   ry   rz   N)r~   _write)r:   r]   r   r   	extensionr   r4   r4   r5   _write_source_string  s    
z$PackageExporter._write_source_string)r]   c              
   C   sV   z| j |W S  tk
rP } z$t|s* d| d}t|d W 5 d }~X Y nX d S )NzModule not found: 'zW'. Make sure the PackageImporter that created this module is present in `self.importer`)rc   import_moduleModuleNotFoundErrorr   )r:   r]   r   msgr4   r4   r5   _import_module  s    
zPackageExporter._import_module)r]   r   c                 C   s,   z|  | W dS  tk
r&   Y dS X d S )NTF)r   r   r:   r]   r4   r4   r5   r     s
    
zPackageExporter._module_exists)moduler   c                 C   sF   t |dd }|d ks|ds"d nt||j}|d kr<d S d|S )N__file__r|    )getattrendswith	linecachegetlines__dict__join)r:   r   r   resultr4   r4   r5   _get_source_of_module  s    z%PackageExporter._get_source_of_modulec                 C   s  || j kr$| j j| ddkr$dS |dkrD| j j|tjdd dS |dkrd| j j|tjdd dS | |r| j j|tjdd dS | j	
 D ]h\}}||rd|_| j j||jdd |jtjkr| j j|tjd |jtjkr| ||  dS q| j j|tjd dS )zlGiven a module, add it to the dependency graph according to patterns
        specified by the user.
        r   TNZtorch_package_importer)rD   r   _mock)rM   )rL   rQ   rS   r   r$   r3   r2   _can_implicitly_externr/   rv   rR   matchesrF   rD   r1   r6   rA   r.   _intern_moduler@   )r:   r]   r   patternpattern_infor4   r4   r5   r     s\    
  
    zPackageExporter.add_dependencyc                 C   s"   t |tstd| || dS )a  Save the code for ``module`` into the package. Code for the module is resolved using the ``importers`` path to find the
        module object, and then using its ``__file__`` attribute to find the source code.

        Args:
            module_name (str): e.g. ``my_package.my_subpackage``, code will be saved to provide code
                for this package.
            dependencies (bool, optional): If ``True``, we scan the source for dependencies.
        zNsave_module() expects a string input, did you perhaps mean to pass `__name__`?N)rf   rg   rt   r   )r:   r]   r   r4   r4   r5   save_module  s
    	
zPackageExporter.save_module)r]   r   c                 C   s   |  |}t|}t|d}| |}|dkrt|dd}d}|dkrNtj}n*|tt	j
jrhtj}ntj}d| }| jj|tj|||dd dS | jj|tj||dd |r| |||}	|	D ]}
| j||
 | |
 qdS )zAdds the module to the dependency graph as an interned module,
        along with any metadata needed to write it out to the zipfile at serialization time.
        __path__Nr   z
filename: T)rD   r   rM   rO   r   )rD   r   r   r   )r   r   hasattrr   r   r6   r=   r   tuple	importlib	machineryEXTENSION_SUFFIXESr<   r>   rL   r   r$   r.   r   r   r   )r:   r]   r   Z
module_objr   r   r   rO   Zpackaging_errorr   r   r4   r4   r5   r     sD    



zPackageExporter._intern_moduler&   )packageresourceobjr   pickle_protocolc                    s  |dks|dkst d||}t }t|j|d}j|_|| |	 }	t
t d| d| d}
jj|
tjddd	 tt tt d
 fdd}|r~g }d}d}t
d}d}t|	D ]2\}}}|dkr|jdks|jdkrt|tst |}|}|||< n|jdks>|jdks>|jdkr`t|tsNt |}||d}nP|jdkrv|d7 }n:|jdkr t|tst ||kr|| ||| q|dkr|jdkrt|tst |d\}}||kr|| ||| q|D ]v}j|
| | krpt|ts2t  | }jj|tjtjd| d| d| d| d	dd n
| q||	 dS )a{  Save a python object to the archive using pickle. Equivalent to :func:`torch.save` but saving into
        the archive rather than a stand-alone file. Stanard pickle does not save the code, only the objects.
        If ``dependencies`` is true, this method will also scan the pickled objects for which modules are required
        to reconstruct them and save the relevant code.

        To be able to save an object where ``type(obj).__name__`` is ``my_module.MyObject``,
        ``my_module.MyObject`` must resolve to the class of the object according to the ``importer`` order. When saving objects that
        have previously been packaged, the importer's ``import_module`` method will need to be present in the ``importer`` list
        for this to work.

        Args:
            package (str): The name of module package this resource should go in (e.g. ``"my_package.my_subpackage"``).
            resource (str): A unique name for the resource, used to identify it to load.
            obj (Any): The object to save, must be picklable.
            dependencies (bool, optional): If ``True``, we scan the source for dependencies.
        r'   r&   z4torch.package only supports pickle protocols 3 and 4)protocol<ry   >T)rD   r   	is_pickle)r   fieldc                    sl   t | tstt |tst| r*dS j D ]2\}}|| r4|jtj	kr` |  
|  dS q4dS )ar  
            checks if an object (field) comes from a mocked module and then adds
            the pair to mocked_modules which contains mocked modules paired with their
            list of mocked objects present in the pickle.

            We also hold the invariant that the first user defined rule that applies
            to the module is the one we use.
            N)rf   rg   rT   r   rv   rR   r   rD   r$   r0   rU   )r   r   r   r   mocked_modulesr:   r4   r5   _check_mocked_error^  s    


z8PackageExporter.save_pickle.<locals>._check_mocked_errorNr   SHORT_BINUNICODEBINUNICODE8ZBINGET_LONGBINGETGETMEMOIZEr   STACK_GLOBALGLOBAL zObject(s) 'z' from module `zC` was mocked out during packaging but is being used in resource - `z` in package `z`. )rD   rM   rO   r   ) rT   	_filenamerV   BytesIOr   rc   _persistent_idpersistent_iddumpr[   r   rP   rL   r   r$   r.   r   rg   pickletoolsZgenopsr8   rf   intrS   rU   splitr   r0   r6   rB   r   r   )r:   r   r   r   r   r   r   Zdata_bufZpicklerZ
data_valueZname_in_dependency_graphr   Zall_dependenciesr   r   memoZ
memo_countopcodeargposr]   fieldsr4   r   r5   save_pickle1  s    








	zPackageExporter.save_pickle)r   r   textc                 C   s   |  |||dS )a5  Save text data to the package.

        Args:
            package (str): The name of module package this resource should go it (e.g. ``"my_package.my_subpackage"``).
            resource (str): A unique name for the resource, used to identify it to load.
            text (str): The contents to save.
        utf-8)save_binaryencode)r:   r   r   r   r4   r4   r5   	save_text  s    zPackageExporter.save_text)binaryc                 C   s   |  ||}| || dS )a3  Save raw bytes to the package.

        Args:
            package (str): The name of module package this resource should go it (e.g. ``"my_package.my_subpackage"``).
            resource (str): A unique name for the resource, used to identify it to load.
            binary (str): The data to save.
        N)r   r   )r:   r   r   r   r   r4   r4   r5   r     s    zPackageExporter.save_binary)hookr   c                 C   s   t | j}|| j|j< |S )a  Registers an extern hook on the exporter.

        The hook will be called each time a module matches against an :meth:`extern` pattern.
        It should have the following signature::

            hook(exporter: PackageExporter, module_name: str) -> None

        Hooks will be called in order of registration.

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                A handle that can be used to remove the added hook by calling
                ``handle.remove()``.
        )r   ro   idr:   r   handler4   r4   r5   register_extern_hook  s    
z$PackageExporter.register_extern_hookc                 C   s   t | j}|| j|j< |S )a  Registers a mock hook on the exporter.

        The hook will be called each time a module matches against a :meth:`mock` pattern.
        It should have the following signature::

            hook(exporter: PackageExporter, module_name: str) -> None

        Hooks will be called in order of registration.

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                A handle that can be used to remove the added hook by calling
                ``handle.remove()``.
        )r   rp   r   r   r4   r4   r5   register_mock_hook  s    
z"PackageExporter.register_mock_hookc                 C   s   t | j}|| j|j< |S )a  Registers an intern hook on the exporter.

        The hook will be called each time a module matches against an :meth:`intern` pattern.
        It should have the following signature::

            hook(exporter: PackageExporter, module_name: str) -> None

        Hooks will be called in order of registration.

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                A handle that can be used to remove the added hook by calling
                ``handle.remove()``.
        )r   rq   r   r   r4   r4   r5   register_intern_hook  s    
z$PackageExporter.register_intern_hookr4   )excluderE   r   )includer   rE   c                C   s   t tj|| jt||d< dS )a&  Specify modules that should be packaged. A module must match some ``intern`` pattern in order to be
        included in the package and have its dependencies processed recursively.

        Args:
            include (Union[List[str], str]): A string e.g. "my_package.my_subpackage", or list of strings
                for the names of the modules to be externed. This can also be a glob-style pattern, as described in :meth:`mock`.

            exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the include string.

            allow_empty (bool): An optional flag that specifies whether the intern modules specified by this call
                to the ``intern`` method must be matched to some module during packaging. If an ``intern`` module glob
                pattern is added with ``allow_empty=False``, and :meth:`close` is called (either explicitly or via ``__exit__``)
                before any modules match that pattern, an exception is thrown. If ``allow_empty=True``, no such exception is thrown.

        r   N)rC   r$   r.   rv   r   r:   r   r   rE   r4   r4   r5   intern  s     zPackageExporter.internc                C   s   t tj|| jt||d< dS )a  Replace some required modules with a mock implementation.  Mocked modules will return a fake
        object for any attribute accessed from it. Because we copy file-by-file, the dependency resolution will sometimes
        find files that are imported by model files but whose functionality is never used
        (e.g. custom serialization code or training helpers).
        Use this function to mock this functionality out without having to modify the original code.

        Args:
            include (Union[List[str], str]): A string e.g. ``"my_package.my_subpackage"``, or list of strings
                for the names of the modules to be mocked out. Strings can also be a glob-style pattern
                string that may match multiple modules. Any required dependencies that match this pattern
                string will be mocked out automatically.

                Examples :
                    ``'torch.**'`` -- matches ``torch`` and all submodules of torch, e.g. ``'torch.nn'``
                    and ``'torch.nn.functional'``

                    ``'torch.*'`` -- matches ``'torch.nn'`` or ``'torch.functional'``, but not
                    ``'torch.nn.functional'``

            exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the include string.
                e.g. ``include='torch.**', exclude='torch.foo'`` will mock all torch packages except ``'torch.foo'``,
                Default: is ``[]``.

            allow_empty (bool): An optional flag that specifies whether the mock implementation(s) specified by this call
                to the :meth:`mock` method must be matched to some module during packaging. If a mock is added with
                ``allow_empty=False``, and :meth:`close` is called (either explicitly or via ``__exit__``) and the mock has
                not been matched to a module used by the package being exported, an exception is thrown.
                If ``allow_empty=True``, no such exception is thrown.

        r   N)rC   r$   r0   rv   r   r   r4   r4   r5   mock  s    % zPackageExporter.mockc                C   s   t tj|| jt||d< dS )a  Include ``module`` in the list of external modules the package can import.
        This will prevent dependency discovery from saving
        it in the package. The importer will load an external module directly from the standard import system.
        Code for extern modules must also exist in the process loading the package.

        Args:
            include (Union[List[str], str]): A string e.g. ``"my_package.my_subpackage"``, or list of strings
                for the names of the modules to be externed. This can also be a glob-style pattern, as
                described in :meth:`mock`.

            exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the
                include string.

            allow_empty (bool): An optional flag that specifies whether the extern modules specified by this call
                to the ``extern`` method must be matched to some module during packaging. If an extern module glob
                pattern is added with ``allow_empty=False``, and :meth:`close` is called (either explicitly or via
                ``__exit__``) before any modules match that pattern, an exception is thrown. If ``allow_empty=True``,
                no such exception is thrown.

        r   N)rC   r$   r/   rv   r   r   r4   r4   r5   externA  s     zPackageExporter.externr   )r   r   c                C   s    t tjdd| jt||d< dS )aO  Blocklist modules who names match the given glob patterns from the list of modules the package can import.
        If a dependency on any matching packages is found, a :class:`PackagingError` is raised.

        Args:
            include (Union[List[str], str]): A string e.g. ``"my_package.my_subpackage"``, or list of strings
                for the names of the modules to be externed. This can also be a glob-style pattern, as described in :meth:`mock`.

            exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the include string.
        T)rE   r   N)rC   r$   r1   rv   r   )r:   r   r   r4   r4   r5   deny`  s    
 zPackageExporter.denyc                 C   st  t |st|t jjrt|t jjrP|j}| }tt |}|j}|	 }n>t|t j
r||}tt|}t j}| }ntdt| tt|}t|}| j|}	| j|}
|	s|jjdkr| }| }| jd|
 d| | d||
||fS t|drptr,t|t jjr,td| j !t"|d krbdt"|f|#| | j t"|< | j t"| S d S )	Nzstorage type not recognized: cpuz.data/z.storagestorage__reduce_package__zSerializing ScriptModules directly into a package is a beta feature. To use, set global `torch.package.package_exporter._gate_torchscript_serialization` to `False`.Zreduce_package)$re   Z
is_storagerf   r   Z_TypedStorageZ_storageZpickle_storage_typer   dtypesizeZ_UntypedStorager   ru   Zuint8nbytesRuntimeErrorr   r   r   rn   Zhas_storageZget_or_add_storageZdevicer   ri   write_recordZdata_ptrr   _gate_torchscript_serializationZjitZRecursiveScriptModuler   rl   rS   r   r   )r:   r   Zuntyped_storageZstorage_type_strZstorage_typer   Zstorage_numelr   locationZstorage_presentZ
storage_id	num_bytesr4   r4   r5   r   n  sV    




   zPackageExporter._persistent_idc                 C   s   | S Nr4   r9   r4   r4   r5   	__enter__  s    zPackageExporter.__enter__c                 C   s    |d k	r|    d S |   d S r  )_finalize_zipclose)r:   exc_type	exc_value	tracebackr4   r4   r5   __exit__  s    zPackageExporter.__exit__c                 C   sj   || j krtd| d| j | t|r>td| dt|trR|d}| j||t	| d S )NzTried to write file 'z<', but it already exists in this archive. Please file a bug.z+Tried to save a torch.package'd module as 'z:'. Directly saving torch.package'd modules is not allowed.r   )
rk   rT   addr   rf   rg   r   ri   r   r   )r:   r   Zstr_or_bytesr4   r4   r5   r     s    




zPackageExporter._writec                 C   s\   | j j D ]\}}d|krt| j q| j D ]$\}}|js2|js2td| dq2d S )NrM   z&Exporter did not match any modules to z', which was marked as allow_empty=False)rL   rQ   rR   rK   rv   rE   rF   rJ   )r:   r]   r^   r   r   r4   r4   r5   _validate_dependency_graph  s    
z*PackageExporter._validate_dependency_graphc                 C   s4   d| j kr0tttjd }| jdt|dd d S )Nz_mock.pyr   F)r   )rk   rg   r   r   parentr   r   )r:   Z	mock_filer4   r4   r5   _write_mock_file  s    
z PackageExporter._write_mock_filec           	      C   sn  |    g }| jj D ]4\}}|d }|tjkrZ| j D ]}|| | q>|| q|tj	kr| j
 D ]}|| | qn|   t| |d}| |t| q|tjkr| j D ]}|| | qd|krtd| |ddkrq|d }|d }| ||| q|tjkr(|   q|tjkr8qqtd	| d
| dqd|d }| d| dS )zTakes a finalized dependency graph describing how to package all
        modules and executes it, writing to the ZIP archive.
        rD   r   r   z-Module was marked `intern` but not provided: r   Tr   r   zInvalid action: z, z!. Please report a bug to PyTorch.rN   z.data/extern_modulesN)r  rL   rQ   rR   r$   r/   ro   valuesrU   r0   rp   r  r   r   r   
_MOCK_IMPLr.   rq   rT   rS   r2   r3   r   r   )	r:   Zextern_modulesr]   r^   rD   r   r   r   Zextern_file_contentsr4   r4   r5   _execute_dependency_graph  sF    


z)PackageExporter._execute_dependency_graphc                 C   s   |  dt  dS )zSWrites the python version that the package was created with to .data/python_versionz.data/python_versionN)r   platformpython_versionr9   r4   r4   r5   _write_python_version  s    z%PackageExporter._write_python_versionc                 C   s&   |    |   | j  |   dS )zWrite the package to the filesystem. Any calls after :meth:`close` are now invalid.
        It is preferable to use resource guard syntax instead::

            with PackageExporter("file.zip") as e:
                ...
        N)r  r  rm   Zwrite_filesr  r9   r4   r4   r5   r    s    
zPackageExporter.closec                 C   s   | ` | jr| j  dS )zUCalled at the very end of packaging to leave the zipfile in a closed but valid state.N)ri   rh   flushr9   r4   r4   r5   r    s    zPackageExporter._finalize_zipc                 C   s"   | dd}t|}| d| S )Nry   rz   )r~   r   )r:   r   r   package_pathr4   r4   r5   r   $  s    zPackageExporter._filenamec                 C   s&   | dd }|dkp$|tko$t|S )Nry   r   re   )	partition_DISALLOWED_MODULESr   )r:   r]   Ztop_level_package_namer4   r4   r5   r   )  s
    z&PackageExporter._can_implicitly_externc                 C   s
   | j  S )zReturns digraph string representation of dependencies in package.

        Returns:
            A string representation of dependencies in package.
        )rL   Zto_dotr9   r4   r4   r5   dependency_graph_string0  s    z'PackageExporter.dependency_graph_string)rD   r   c                 C   sL   g }| j j D ].\}}|dd }||krd|kr|| q|  |S )NrD   r   )rL   rQ   rR   rS   rU   sort)r:   rD   r   r8   Z	node_dictZnode_actionr4   r4   r5   _nodes_with_action_type8  s    z'PackageExporter._nodes_with_action_typec                 C   s   |  tjS )zReturn all modules that are currently externed.

        Returns:
            A list containing the names of modules which will be
            externed in this package.
        )r  r$   r/   r9   r4   r4   r5   externed_modulesC  s    z PackageExporter.externed_modulesc                 C   s   |  tjS )zReturn all modules that are currently interned.

        Returns:
            A list containing the names of modules which will be
            interned in this package.
        )r  r$   r.   r9   r4   r4   r5   interned_modulesL  s    z PackageExporter.interned_modulesc                 C   s   |  tjS )zReturn all modules that are currently mocked.

        Returns:
            A list containing the names of modules which will be
            mocked in this package.
        )r  r$   r0   r9   r4   r4   r5   r   U  s    zPackageExporter.mocked_modulesc                 C   s   |  tjS )zReturn all modules that are currently denied.

        Returns:
            A list containing the names of modules which will be
            denied in this package.
        )r  r$   r1   r9   r4   r4   r5   denied_modules^  s    zPackageExporter.denied_modulesc                 C   s,   || j j kr$t| j j|  S g S dS )zReturn a list of all modules which depend on the module ``module_name``.

        Returns:
            A list containing the names of modules which depend on ``module_name``.
        N)rL   Z_predr   rP   r   r4   r4   r5   	get_rdepsg  s    zPackageExporter.get_rdeps)r   dstr   c                 C   s   | j ||S )zReturn a dot representation of the subgraph
           that has all paths from src to dst.

        Returns:
            A dot representation containing all paths from src to dst.
            (https://graphviz.org/doc/info/lang.html)
        )rL   	all_paths)r:   r   r   r4   r4   r5   r!  r  s    zPackageExporter.all_pathsN)T)FT)F)T)T)Tr&   )Ar*   r+   r,   r-   r    rH   r"   r   rg   r   r   r   rG   r   r   rI   r   r   r   r   r   r   types
ModuleTyper   r   r   r   r   r   r   r   r   bytesr   
ActionHookr   r   r   r   r   r   r   r   r   r  r
  r   r  r  r  r  r  r  r   r   r  r$   r  r  r  r   r  r  r!  r4   r4   r4   r5   r#      s   
:  6  5  # ;=  
-68					sysrV   z~from _mock import MockedObject
def __getattr__(attr: str):
    return MockedObject(__name__ + '.' + attr, _suppress_err=True)
)r   r   c              
   C   s4   t | d }| }|dW  5 Q R  S Q R X d S )Nrbr   )openreaddecode)r   rd   br4   r4   r5   r     s    r   )Err   Zimportlib.machineryr   rV   r   r   r  r"  r   r   Zdataclassesr   enumr   pathlibr   typingr   r   r	   r
   r   r   r   r   r   r   r   re   Ztorch.serializationr   r   Ztorch.typesr   Ztorch.utils.hooksr   Z_digraphr   Z
_importlibr   Z	_manglingr   r   Z_package_picklerr   Z_stdlibr   Zfind_file_dependenciesr   Z
glob_groupr   r   rc   r    r!   r"   r   rg   r%  r$   r6   rC   r   rJ   rK   r#   r  r  r   r4   r4   r4   r5   <module>   sT   4#       k