
    YTh%                     |    S r SSKrSSKrSSKJr  SSKJr  SSKJr  SSK	J
r
  SS jrSS jrSS	 jrS
 rSS jrS rg)zSerialization.

This module contains functionality for serializing TorchScript modules, notably:
    * torch.jit.save
    * torch.jit.load

This is not intended to be imported directly; please use the exposed
functionalities in `torch.jit`.
    N)_get_model_id)log_torchscript_usage)wrap_cpp_module)validate_cuda_devicec                     [        S[        U 5      S9  Uc  0 n[        U[        [        R
                  45      (       a  U R                  XS9  gU R                  US9nUR                  U5        g)a  
Save an offline version of this module for use in a separate process.

The saved module serializes all of the methods, submodules, parameters, and
attributes of this module. It can be loaded into the C++ API using
``torch::jit::load(filename)`` or into the Python API with
:func:`torch.jit.load <torch.jit.load>`.

To be able to save a module, it must not make any calls to native Python
functions.  This means that all submodules must be subclasses of
:class:`ScriptModule` as well.

.. DANGER::
    All modules, no matter their device, are always loaded onto the CPU
    during loading.  This is different from :func:`torch.load`'s semantics
    and may change in the future.

Args:
    m: A :class:`ScriptModule` to save.
    f: A file-like object (has to implement write and flush) or a string
       containing a file name.
    _extra_files: Map from filename to contents which will be stored as part of `f`.

.. note::
    torch.jit.save attempts to preserve the behavior of some operators
    across versions. For example, dividing two integer tensors in
    PyTorch 1.5 performed floor division, and if the module
    containing that code is saved in PyTorch 1.5 and loaded in PyTorch 1.6
    its division behavior will be preserved. The same module saved in
    PyTorch 1.6 will fail to load in PyTorch 1.5, however, since the
    behavior of division changed in 1.6, and 1.5 does not know how to
    replicate the 1.6 behavior.

Example:
.. testcode::

    import torch
    import io

    class MyModule(torch.nn.Module):
        def forward(self, x):
            return x + 10

    m = torch.jit.script(MyModule())

    # Save to file
    torch.jit.save(m, 'scriptmodule.pt')
    # This line is equivalent to the previous
    m.save("scriptmodule.pt")

    # Save to io.BytesIO buffer
    buffer = io.BytesIO()
    torch.jit.save(m, buffer)

    # Save with extra files
    extra_files = {'foo.txt': b'bar'}
    torch.jit.save(m, 'scriptmodule.pt', _extra_files=extra_files)
savemodel_idN)_extra_files)	r   r   
isinstancestrosPathLiker   save_to_bufferwrite)mfr   rets       P/var/www/auris/envauris/lib/python3.13/site-packages/torch/jit/_serialization.pyr   r      sa    v &=+;<!c2;;'((	q,L9	    c                    [        U [        [        R                  45      (       af  [        R                  R                  U 5      (       d  [        SU  S35      e[        R                  R                  U 5      (       a  [        SU  S35      e[        U5      nUc  0 n[        R                  R                  5       n[        U [        [        R                  45      (       a7  [        R                  R                  U[        R                  " U 5      XU5      nO/[        R                  R                  X@R                  5       XU5      n[!        U5      n[#        S[%        U5      S9  U$ )a@  
Load a :class:`ScriptModule` or :class:`ScriptFunction` previously saved with :func:`torch.jit.save <torch.jit.save>`.

All previously saved modules, no matter their device, are first loaded onto CPU,
and then are moved to the devices they were saved from. If this fails (e.g.
because the run time system doesn't have certain devices), an exception is
raised.

Args:
    f: a file-like object (has to implement read, readline, tell, and seek),
        or a string containing a file name
    map_location (string or torch.device): A simplified version of
        ``map_location`` in `torch.jit.save` used to dynamically remap
        storages to an alternative set of devices.
    _extra_files (dictionary of filename to content): The extra
        filenames given in the map would be loaded and their content
        would be stored in the provided map.
    _restore_shapes (bool): Whether or not to retrace the module on load using stored inputs

Returns:
    A :class:`ScriptModule` object.

.. warning::
    It is possible to construct malicious pickle data which will execute arbitrary code
    during func:`torch.jit.load`. Never load data that could have come from an untrusted
    source, or that could have been tampered with. **Only load data you trust**.

Example:
.. testcode::

    import torch
    import io

    torch.jit.load('scriptmodule.pt')

    # Load ScriptModule from io.BytesIO object
    with open('scriptmodule.pt', 'rb') as f:
        buffer = io.BytesIO(f.read())

    # Load all tensors to the original device
    torch.jit.load(buffer)

    # Load all tensors onto CPU, using a device
    buffer.seek(0)
    torch.jit.load(buffer, map_location=torch.device('cpu'))

    # Load all tensors onto CPU, using a string
    buffer.seek(0)
    torch.jit.load(buffer, map_location='cpu')

    # Load with extra files.
    extra_files = {'foo.txt': ''}  # values will be replaced with data
    torch.jit.load('scriptmodule.pt', _extra_files=extra_files)
    print(extra_files['foo.txt'])

.. testoutput::
    :hide:

    ...

.. testcleanup::

    import os
    os.remove("scriptmodule.pt")
zThe provided filename z does not existz is a directoryloadr	   )r   r   r   r   pathexists
ValueErrorisdirvalidate_map_locationtorch_CCompilationUnitimport_ir_modulefspathimport_ir_module_from_bufferreadr   r   r   )r   map_locationr   _restore_shapescu
cpp_moduler   s          r   r   r   Z   s   D !c2;;'((ww~~a  5aSHII77==5aSHII(6L		!	!	#B!c2;;'((XX..		!l/

 XX::,o


 *
%C&=+=>Jr   c                 6   [        U [        5      (       a  [        R                  " U 5      n OBU b?  [        U [        R                  5      (       d   [	        S[        [        U 5      5      -   5      e[        U 5      R                  S5      (       a  [        U 5        U $ )NzJmap_location should be either None, string or torch.device, but got type: cuda)r   r   r   devicer   type
startswithr   )r%   s    r   r   r      s}    ,$$||L1"ju||&L&L"4#567
 	

 <##F++\*r   c                 4   [        U [        [        R                  45      (       a>  [        R                  " U 5      n [        [        R                  R                  U 5      5      $ [        [        R                  R                  U R                  5       5      5      $ N)r   r   r   r   r"   r   r   r   _load_jit_module_from_file_load_jit_module_from_bytesr$   )r   s    r   jit_module_from_flatbufferr2      s_    !c2;;'((IIaLuxxBB1EFFuxxCCAFFHMNNr   c                 T   UnUc  0 n[        U[        [        R                  45      (       aA  [        R                  " U5      n[
        R                  R                  U R                  X5        g[
        R                  R                  U R                  U5      nUR                  U5        g)aG  
Save an offline version of this module for use in a separate process.

The saved module serializes all of the methods, submodules, parameters, and
attributes of this module. It can be loaded into the C++ API using
``torch::jit::load_jit_module_from_file(filename)`` or into the Python API with
:func:`torch.jit.jit_module_from_flatbuffer<torch.jit.jit_module_from_flatbuffer>`.

To be able to save a module, it must not make any calls to native Python
functions.  This means that all submodules must be subclasses of
:class:`ScriptModule` as well.

.. DANGER::
    All modules, no matter their device, are always loaded onto the CPU
    during loading.  This is different from :func:`torch.load`'s semantics
    and may change in the future.

Args:
    m: A :class:`ScriptModule` to save.
    f: A string for file path


Example:
.. testcode::

    import torch
    import io

    class MyModule(torch.nn.Module):
        def forward(self, x):
            return x + 10

    m = torch.jit.script(MyModule())

    # Save to file
    torch.jit.save_jit_module_to_flatbuffer(m, 'scriptmodule.ff')
N)r   r   r   r   r"   r   r   _save_jit_module_c_save_jit_module_to_bytesr   )r   r   r   extra_filesss        r   save_jit_module_to_flatbufferr9      su    L K!c2;;'((IIaL!!!$$7HH..qtt[A	
r   c                    [        U [        [        R                  45      (       a&  [	        U S5       nUR                  5       nSSS5        OU R                  5       n[        R                  R                  W5      $ ! , (       d  f       N-= f)ab  Get some information regarding a model file in flatbuffer format.

Args:
    path_or_file: Either str, Path or file like object (BytesIO OK).
        If it's str or Path, we will read the file referenced by that
        path as Bytes.

Returns:
    A dict with metadata on what that file contains, currently looks like
    this:
    {
        'bytecode_version': 4,  # int
        'operator_version': 4,  # int
        'function_names': {
            '__torch__.___torch_mangle_0.Foo.forward'}, # set
        'type_names': set(),  # set
        'opname_to_num_args': {'aten::linear': 3} # Dict[str, int]
    }
rbN)	r   r   r   r   openr$   r   r    _get_module_info_from_flatbuffer)path_or_filer   	all_bytess      r   get_flatbuffer_module_infor@      sg    ( ,bkk 233,%I &% !%%'	8844Y??	 &%s   A;;
B	r/   )NNF)__doc__r   r   torch._jit_internalr   torch._utils_internalr   torch.jit._recursiver   torch.serializationr   r   r   r   r2   r9   r@    r   r   <module>rG      sC    
  - 7 0 4BJYxO/d@r   