o
    ƠijK                     @  s  d dl mZ d dlZd dlmZmZmZmZmZm	Z	m
Z
 d dlZd dlm  mZ d dlmZ d dlmZmZ d dlmZ d dlmZmZ dde dddddejd	d d
ddddddddfd<d-d.Zd/de dddddejd	d d
ddddfd=d3d4Zdde fd>d8d9Z	/d?d@d:d;ZdS )A    )annotationsN)AnyListOptionalSequenceSetTupleUnion)Device)EngineCapabilitydtype)Input)_parse_compile_spec_parse_deviceF   i   i   @i       moduletorch.jit.ScriptModuleinputs(Optional[Sequence[Input | torch.Tensor]]input_signature5Optional[Tuple[Input | torch.Tensor | Sequence[Any]]]devicer
   disable_tf32boolsparse_weightsenabled_precisions(Optional[Set[Union[torch.dtype, dtype]]]refitdebug
capabilityr   num_avg_timing_itersintworkspace_sizedla_sram_sizedla_local_dram_sizedla_global_dram_sizetruncate_long_and_doublerequire_full_compilationmin_block_sizetorch_executed_opsOptional[List[str]]torch_executed_modulesallow_shape_tensorsreturnc                 C  s6  t jdtdd |durt|ng }|dur|nt }|dur!|ng }|dur)|ng }t| tjjr6t	d|rNt
|dksDt
|dkrNtd| d| i d	|d
|d|d|d|d|d|d|d|	d|
d|d|d|d|d|d| |||dd|}t| jt|}tjj|}|S )a  Compile a TorchScript module for NVIDIA GPUs using TensorRT

    Takes a existing TorchScript module and a set of settings to configure the compiler
    and will convert methods to JIT Graphs which call equivalent TensorRT engines

    Converts specifically the forward method of a TorchScript Module

    Arguments:
        module (torch.jit.ScriptModule): Source module, a result of tracing or scripting a PyTorch
            ``torch.nn.Module``

    Keyword Arguments:
        inputs (List[Union(torch_tensorrt.Input, torch.Tensor)]): **Required** List of specifications of input shape, dtype and memory layout for inputs to the module. This argument is required. Input Sizes can be specified as torch sizes, tuples or lists. dtypes can be specified using
            torch datatypes or torch_tensorrt datatypes and you can use either torch devices or the torch_tensorrt device type enum
            to select device type. ::

                input=[
                    torch_tensorrt.Input((1, 3, 224, 224)), # Static NCHW input shape for input #1
                    torch_tensorrt.Input(
                        min_shape=(1, 224, 224, 3),
                        opt_shape=(1, 512, 512, 3),
                        max_shape=(1, 1024, 1024, 3),
                        dtype=torch.int32
                        format=torch.channel_last
                    ), # Dynamic input shape for input #2
                    torch.randn((1, 3, 224, 244)) # Use an example tensor and let torch_tensorrt infer settings
                ]

        input_signature Union(List, Tuple, torch_tensorrt.Input, torch.Tensor): A formatted collection of input specifications for the module. Input Sizes can be specified as torch sizes, tuples or lists. dtypes can be specified using
            torch datatypes or torch_tensorrt datatypes and you can use either torch devices or the torch_tensorrt device type enum to select device type. **This API should be considered beta-level stable and may change in the future** ::

                input_signature=([
                    torch_tensorrt.Input((1, 3, 224, 224)), # Static NCHW input shape for input #1
                    torch_tensorrt.Input(
                        min_shape=(1, 224, 224, 3),
                        opt_shape=(1, 512, 512, 3),
                        max_shape=(1, 1024, 1024, 3),
                        dtype=torch.int32
                        format=torch.channel_last
                    ), # Dynamic input shape for input #2
                ], torch.randn((1, 3, 224, 244))) # Use an example tensor and let torch_tensorrt infer settings for input #3
        device (Union(torch_tensorrt.Device, torch.device, dict)): Target device for TensorRT engines to run on ::

            device=torch_tensorrt.Device("dla:1", allow_gpu_fallback=True)

        disable_tf32 (bool): Force FP32 layers to use traditional as FP32 format vs the default behavior of rounding the inputs to 10-bit mantissas before multiplying, but accumulates the sum using 23-bit mantissas
        sparse_weights (bool): Enable sparsity for convolution and fully connected layers.
        enabled_precision (Set(Union(torch.dtype, torch_tensorrt.dtype))): The set of datatypes that TensorRT can use when selecting kernels
        refit (bool): Enable refitting
        debug (bool): Enable debuggable engine
        capability (torch_tensorrt.EngineCapability): Restrict kernel selection to safe gpu kernels or safe dla kernels
        num_avg_timing_iters (int): Number of averaging timing iterations used to select kernels
        workspace_size (int): Maximum size of workspace given to TensorRT
        dla_sram_size (int): Fast software managed RAM used by DLA to communicate within a layer.
        dla_local_dram_size (int): Host RAM used by DLA to share intermediate tensor data across operations
        dla_global_dram_size (int): Host RAM used by DLA to store weights and metadata for execution
        truncate_long_and_double (bool): Truncate weights provided in int64 or double (float64) to int32 and float32
        require_full_compilation (bool): Require modules to be compiled end to end or return an error as opposed to returning a hybrid graph where operations that cannot be run in TensorRT are run in PyTorch
        min_block_size (int): The minimum number of contiguous TensorRT convertible operations in order to run a set of operations in TensorRT
        torch_executed_ops (List[str]): List of aten operators that must be run in PyTorch. An error will be thrown if this list is not empty but ``require_full_compilation`` is True
        torch_executed_modules (List[str]): List of modules that must be run in PyTorch. An error will be thrown if this list is not empty but ``require_full_compilation`` is True
        allow_shape_tensors: (Experimental) Allow aten::size to output shape tensors using IShapeLayer in TensorRT

    Returns:
        torch.jit.ScriptModule: Compiled TorchScript Module, when run it will execute via TensorRT
    aR  The torchscript frontend for Torch-TensorRT has been deprecated, please plan on porting to the dynamo frontend (torch_tensorrt.compile(..., ir="dynamo"). Torchscript will continue to be a supported deployment format via post compilation torchscript tracing, see: https://pytorch.org/TensorRT/user_guide/saving_models.html for more details   
stacklevelNzftorch.jit.ScriptFunction currently is not directly supported, wrap the function in a module to compiler   zrequire_full_compilation is enabled however the list of modules and ops to run in torch is not empty. Found: torch_executed_ops: z, torch_executed_modules: r   r   r   r   r   r   r   r   r    r!   r#   r$   r%   r&   r'   torch_fallback)enabledforced_fallback_opsforced_fallback_modulesr)   r-   )warningswarnDeprecationWarninglistset
isinstancetorchjitScriptFunction	TypeErrorlen
ValueError_Ccompile_graph_cr   
_recursivewrap_cpp_module)r   r   r   r   r   r   r   r   r   r    r!   r#   r$   r%   r&   r'   r(   r)   r*   r,   r-   
input_listenabled_precisions_settorch_executed_module_listtorch_executed_op_listspeccompiled_cpp_modcompiled_module rN   O/home/ubuntu/.local/lib/python3.10/site-packages/torch_tensorrt/ts/_compiler.pycompile   s   Z	
rP   forwardmethod_namestrbytesc                 C  s   t jdtdd |durt|ng }|dur|ntjh}t| tjjr't	d||||||||	|
|||d}t
| j|t|}ddl}| }|| | }W d   |S 1 s]w   Y  |S )a  Convert a TorchScript module method to a serialized TensorRT engine

    Converts a specified method of a module to a serialized TensorRT engine given a dictionary of conversion settings

    Arguments:
        module (torch.jit.ScriptModule): Source module, a result of tracing or scripting a PyTorch
            ``torch.nn.Module``

    Keyword Args:
        inputs (List[Union(torch_tensorrt.Input, torch.Tensor)]): **Required** List of specifications of input shape, dtype and memory layout for inputs to the module. This argument is required. Input Sizes can be specified as torch sizes, tuples or lists. dtypes can be specified using
            torch datatypes or torch_tensorrt datatypes and you can use either torch devices or the torch_tensorrt device type enum
            to select device type. ::

                input=[
                    torch_tensorrt.Input((1, 3, 224, 224)), # Static NCHW input shape for input #1
                    torch_tensorrt.Input(
                        min_shape=(1, 224, 224, 3),
                        opt_shape=(1, 512, 512, 3),
                        max_shape=(1, 1024, 1024, 3),
                        dtype=torch.int32
                        format=torch.channel_last
                    ), # Dynamic input shape for input #2
                    torch.randn((1, 3, 224, 244)) # Use an example tensor and let torch_tensorrt infer settings
                ]

        method_name (str): Name of method to convert
        input_signature Union(List, Tuple, torch_tensorrt.Input, torch.Tensor): A formatted collection of input specifications for the module. Input Sizes can be specified as torch sizes, tuples or lists. dtypes can be specified using
            torch datatypes or torch_tensorrt datatypes and you can use either torch devices or the torch_tensorrt device type enum to select device type. **This API should be considered beta-level stable and may change in the future** ::

                input_signature=([
                    torch_tensorrt.Input((1, 3, 224, 224)), # Static NCHW input shape for input #1
                    torch_tensorrt.Input(
                        min_shape=(1, 224, 224, 3),
                        opt_shape=(1, 512, 512, 3),
                        max_shape=(1, 1024, 1024, 3),
                        dtype=torch.int32
                        format=torch.channel_last
                    ), # Dynamic input shape for input #2
                ], torch.randn((1, 3, 224, 244))) # Use an example tensor and let torch_tensorrt infer settings for input #3

        device (Union(torch_tensorrt.Device, torch.device, dict)): Target device for TensorRT engines to run on ::

            device=torch_tensorrt.Device("dla:1", allow_gpu_fallback=True)

        disable_tf32 (bool): Force FP32 layers to use traditional as FP32 format vs the default behavior of rounding the inputs to 10-bit mantissas before multiplying, but accumulates the sum using 23-bit mantissas
        sparse_weights (bool): Enable sparsity for convolution and fully connected layers.
        enabled_precision (Set(Union(torch.dtype, torch_tensorrt.dtype))): The set of datatypes that TensorRT can use when selecting kernels
        refit (bool): Enable refitting
        debug (bool): Enable debuggable engine
        capability (torch_tensorrt.EngineCapability): Restrict kernel selection to safe gpu kernels or safe dla kernels
        num_avg_timing_iters (int): Number of averaging timing iterations used to select kernels
        workspace_size (int): Maximum size of workspace given to TensorRT
        dla_sram_size (int): Fast software managed RAM used by DLA to communicate within a layer.
        dla_local_dram_size (int): Host RAM used by DLA to share intermediate tensor data across operations
        dla_global_dram_size (int): Host RAM used by DLA to store weights and metadata for execution
        truncate_long_and_double (bool): Truncate weights provided in int64 or double (float64) to int32 and float32
        allow_shape_tensors: (Experimental) Allow aten::size to output shape tensors using IShapeLayer in TensorRT

    Returns:
        bytes: Serialized TensorRT engine, can either be saved to a file or deserialized via TensorRT APIs
    ag  The torchscript frontend for Torch-TensorRT has been deprecated, please plan on porting to the dynamo frontend (torch_tensorrt.convert_method_to_trt_engine(..., ir="dynamo"). Torchscript will continue to be a supported deployment format via post compilation torchscript tracing, see: https://pytorch.org/TensorRT/user_guide/saving_models.html for more detailsr/   r0   Nzhtorch.jit.ScriptFunctions currently are not directly supported, wrap the function in a module to compile)r   r   r   r   r   r   r   r    r!   r#   r'   r-   r   )r6   r7   r8   r9   r<   floatr;   r=   r>   r?   rB   convert_graph_to_trt_enginerD   r   ioBytesIOwritegetvalue)r   rR   r   r   r   r   r   r   r   r    r!   r#   r$   r%   r&   r'   r-   rG   rH   compile_spec
engine_strrW   engine_bytesengine_bytearrayrN   rN   rO   convert_method_to_trt_engine   sH   P



r_   serialized_engineinput_binding_namesoutput_binding_namesc                 C  sF   |dur|ng }|dur|ng }t | t|||}tjj|}|S )aY  Takes a pre-built serialized TensorRT engine and embeds it within a TorchScript module

    Takes a pre-built serialied TensorRT engine (as bytes) and embeds it within a TorchScript module.
    Registers the forward method to execute the TensorRT engine with the function signature:

        forward(Tensor[]) -> Tensor[]

    TensorRT bindings either be explicitly specified using ``[in/out]put_binding_names`` or have names with the following format:
      - [symbol].[index in input / output array]
      ex.
      - [x.0, x.1, x.2] -> [y.0]

    Module can be save with engine embedded with torch.jit.save and moved / loaded according to torch_tensorrt portability rules

    Arguments:
        serialized_engine (bytearray): Serialized TensorRT engine from either torch_tensorrt or TensorRT APIs

    Keyword Arguments:
        input_binding_names (List[str]): List of names of TensorRT bindings in order to be passed to the encompassing PyTorch module
        output_binding_names (List[str]): List of names of TensorRT bindings in order that should be returned from the encompassing PyTorch module
        device (Union(torch_tensorrt.Device, torch.device, dict)): Target device to run engine on. Must be compatible with engine provided. Default: Current active device
    Returns:
        torch.jit.ScriptModule: New TorchScript module with engine embedded
    N)rB   embed_engine_in_new_moduler   r<   r=   rE   rF   )r`   ra   rb   r   input_binding_name_listoutput_binding_name_listcpp_modwrapped_modrN   rN   rO   rc   !  s   rc   c                 C  s   t | j|}|S )a  Checks to see if a method is fully supported by torch_tensorrt

    Checks if a method of a TorchScript module can be compiled by torch_tensorrt, if not, a list of operators
    that are not supported are printed out and the function returns false, else true.

    Arguments:
        module (torch.jit.ScriptModule): Source module, a result of tracing or scripting a PyTorch
            ``torch.nn.Module``
        method_name (str): Name of method to check

    Returns:
        bool: True if supported Method
    )rB   check_method_op_supportrD   )r   rR   	supportedrN   rN   rO   rh   O  s   rh   ),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"   r&   r"   r'   r   r(   r   r)   r"   r*   r+   r,   r+   r-   r   r.   r   )$r   r   rR   rS   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"   r-   r   r.   rT   )
r`   rT   ra   r+   rb   r+   r   r
   r.   r   )rQ   )r   r   rR   rS   r.   r   )
__future__r   r6   typingr   r   r   r   r   r   r	   r<   torch_tensorrt._C.tsrB   tstorch_tensorrt._Devicer
   torch_tensorrt._enumsr   r   torch_tensorrt._Inputr   torch_tensorrt.ts._compile_specr   r   _current_deviceSTANDARDrP   r_   rc   rh   rN   rN   rN   rO   <module>   sl    $ ~/