o
    ƠiF                     @  sd   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
 d dlZd dlmZmZ G dd deZdS )    )annotations)Enum)AnyDictListOptionalSequenceTupleN)dtypememory_formatc                   @  s(  e Zd ZU dZG dd deZdZded< dZded< e	j
Z	d	ed	< d
Zded< ejZded< dZded< dZded< ee Zded< dZded< dZded< d
Zded< d@d d!ZdAd"d#ZdAd$d%ZedBd(d)ZedCd+d,ZedDd0d1Ze	
dEdFd5d6Ze	
dEdGd:d;Z	dHdId>d?ZdS )JInputa  
    Defines an input to a module in terms of expected shape, data type and tensor format.

    Attributes:
        shape_mode (torch_tensorrt.Input._ShapeMode): Is input statically or dynamically shaped
        shape (Tuple or Dict): Either a single Tuple or a dict of tuples defining the input shape.
            Static shaped inputs will have a single tuple. Dynamic inputs will have a dict of the form

            .. code-block:: py

                {"min_shape": Tuple, "opt_shape": Tuple, "max_shape": Tuple}

        dtype (torch_tensorrt.dtype): The expected data type of the input tensor (default: torch_tensorrt.dtype.float32)
        format (torch_tensorrt.TensorFormat): The expected format of the input tensor (default: torch_tensorrt.TensorFormat.NCHW)
    c                   @  s   e Zd ZdZdZdS )zInput._ShapeModer      N)__name__
__module____qualname__STATICDYNAMIC r   r   I/home/ubuntu/.local/lib/python3.10/site-packages/torch_tensorrt/_Input.py
_ShapeMode   s    r   NzOptional[_ShapeMode]
shape_modez6Optional[Tuple[int, ...] | Dict[str, Tuple[int, ...]]]shaper
   Fbool_explicit_set_dtyper   formatg       @floatDOMAIN_OFFSETg        low_tensor_domain_inclhigh_tensor_domain_excltorch.Tensortorch_tensor strnameis_shape_tensorargsr   kwargsreturnNonec                   sP  d v r=d v r=t  d dkrt  d d dksJ  d=  d d d  d<  d d d  d<  d d d  d	< t |dkrrt|d sVtd
tt|d  t fdddD retdt|d | _	tj
j| _nt |dkrd vrt fdddD stdd v rt fdddD rtdd v rt d std
tt d  t d | _	tj
j| _nct d std
tt d  d t d std
tt d  d t d	 std
tt d	  d t d t d t d	 d| _	tj
j| _n
tdt | dd v r3t d | _| jtjkr>d| _nd| _d v rK d | _d v rXt d | _d v rb d }nd}t|| _d v ru d | _n%| jrtj d  d d | _n| jtj
jkr| d| _n|  | _d! v r d! | _dS dS )"aF	  __init__ Method for torch_tensorrt.Input

        Input accepts one of a few construction patterns

        Args:
            shape (Tuple or List, optional): Static shape of input tensor

        Keyword Arguments:
            shape (Tuple or List, optional): Static shape of input tensor
            min_shape (Tuple or List, optional): Min size of input tensor's shape range
                Note: All three of min_shape, opt_shape, max_shape must be provided, there must be no positional arguments, shape must not be defined and implicitly this sets Input's shape_mode to DYNAMIC
            opt_shape (Tuple or List, optional): Opt size of input tensor's shape range
                Note: All three of min_shape, opt_shape, max_shape must be provided, there must be no positional arguments, shape must not be defined and implicitly this sets Input's shape_mode to DYNAMIC
            max_shape (Tuple or List, optional): Max size of input tensor's shape range
                Note: All three of min_shape, opt_shape, max_shape must be provided, there must be no positional arguments, shape must not be defined and implicitly this sets Input's shape_mode to DYNAMIC
            dtype (torch.dtype or torch_tensorrt.dtype): Expected data type for input tensor (default: torch_tensorrt.dtype.float32)
            format (torch.memory_format or torch_tensorrt.TensorFormat): The expected format of the input tensor (default: torch_tensorrt.TensorFormat.NCHW)
            tensor_domain (Tuple(float, float), optional): The domain of allowed values for the tensor, as interval notation: [tensor_domain[0], tensor_domain[1]).
                Note: Entering "None" (or not specifying) will set the bound to [0, 2)
            torch_tensor (torch.Tensor): Holds a corresponding torch tensor with this Input.
            name (str, optional): Name of this input in the input nn.Module's forward function. Used to specify dynamic shapes for the corresponding input in dynamo tracer.
        Examples:
            - Input([1,3,32,32], dtype=torch.float32, format=torch.channel_last)
            - Input(shape=(1,3,32,32), dtype=torch_tensorrt.dtype.int32, format=torch_tensorrt.TensorFormat.NCHW)
            - Input(min_shape=(1,3,32,32), opt_shape=[2,3,32,32], max_shape=(3,3,32,32)) #Implicitly dtype=torch_tensorrt.dtype.float32, format=torch_tensorrt.TensorFormat.NCHW
        r   shape_rangesr   r      	min_shape	opt_shape   	max_shapezbInput shape specifications for inputs are required to be a List, tuple or torch.Size, found type: c                 3      | ]}| v V  qd S Nr   .0kr&   r   r   	<genexpr>`       z!Input.__init__.<locals>.<genexpr>r+   r,   r.   zFound that both shape (as a positional argument), and one or more of min_shape, opt_shape, max_shape were specified
class Input expects that only either shape or all three of min_shape, opt_shape, max_shape are definedc                 3  r/   r0   r   r1   r4   r   r   r5   i   r6   zwMissing required arguments for class Input
Either shape or all three of min_shape, opt_shape, max_shape must be definedc                 3  r/   r0   r   r1   r4   r   r   r5   n   s    
zFound that both shape, and one or more of min_shape, opt_shape, max_shape were specified
class Input expects that only either shape or all three of min_shape, opt_shape, max_shape are definedz for min_shapez for opt_shapez for max_shapezEUnexpected number of positional arguments for class Input 
    Found zA arguments, expected either zero or a single positional argumentsr
   TFr$   r   tensor_domainNr    r
   r#   )lenr   _supported_input_size_type	TypeErrorr"   typeany
ValueErrortupler   r   r   r   allr   r
   _fromunknownr   r$   r   r   _parse_tensor_domainr8   r    torchtensorexample_tensorr#   )selfr%   r&   domainr   r4   r   __init__4   s   (












zInput.__init__c                 C  s   | j tjjkr!d| jt| jt| jt| jd t| jd S | j tjj	kr[t
| jtrRd| jd | jd | jd t| jt| jt| jd t| jd S td| j d	td
)Nz5Input(shape={}, dtype={}, format={}, domain=[{}, {}))r   r   zUInput(min_shape={}, opt_shape={}, max_shape={}, dtype={}, format={}, domain=[{}, {}))r+   r,   r.   IInput shape is dynamic but shapes are not provided as dictionary (found: )zUnknown input shape mode)r   r   r   r   r   r   r"   r
   r8   r   
isinstancedictRuntimeErrorrH   r   r   r   __str__   s.   
zInput.__str__c                 C  s   |   S r0   )rQ   rP   r   r   r   __repr__   s   zInput.__repr__abc                 C  s   | j |j krdS | j tjjkrTt| jtsJ t|jtsJ | jd |jd k| jd |jd k| jd |jd k| j|jk| j|jk| j	|j	k| j
|j
kg}t|S | j|jk| j|jk| j|jk| j	|j	k| j
|j
kg}t|S )NFr+   r,   r.   )r   r   r   r   rM   r   rN   r
   r   r   r   rA   )rS   rT   checksr   r   r   equivalent_spec   s*   



	




zInput.equivalent_spec
input_sizec                 C  s0   t | tjrdS t | trdS t | trdS dS )NTF)rM   rE   Sizer@   list)rW   r   r   r   r;      s   

z Input._supported_input_size_typerI   Optional[Tuple[float, float]]Tuple[float, float]c                 C  s   | du rt jt jf}|S t| dkrQ| \}}t|ttf}t|ttf}|s-td| |s6td| ||krGtdd| d| d t|t|f}|S td	t|  d
|  )a  
        Produce a tuple of integers which specifies a tensor domain in the interval format: [lo, hi)

        Args:
            domain (Tuple[int, int]): A tuple of integers (or NoneTypes) to verify

        Returns:
            A tuple of two int32_t-valid integers
        Nr-   z4Expected value for tensor domain low specifier, got z5Expected value for tensor domain high specifier, got z@Expected provided integer range to have low tensor domain value z/< high tensor domain value, got invalid range [z, rL   z"Expected 2 values for domain, got z: )r   r   r   r:   rM   intr   r?   )rI   result_domain	domain_lo	domain_hivalid_type_lovalid_type_hir   r   r   rD     s8    zInput._parse_tensor_domaintdisable_memory_format_check'Input'c                 C  sZ   |s|j tjds|j tjdstd|s|j tjdr tjntj}| |j|j||dS )a7  
        Produce a Input which contains the information of the given PyTorch tensor.

        Args:
            tensor (torch.Tensor): A PyTorch tensor.
            disable_memory_format_check (bool): Whether to validate the memory formats of input tensors

        Returns:
            A Input object.
        )r   z`Tensor does not have a supported memory format, supported formats are contiguous or channel_last)r   r
   r   r    )is_contiguousrE   contiguous_formatchannels_lastr?   r   r
   )clsrb   rc   frmtr   r   r   from_tensor6  s    zInput.from_tensortsSequence[torch.Tensor]List['Input']c                   s&   t |ttfs	J  fdd|D S )ab  
        Produce a list of Inputs which contain
        the information of all the given PyTorch tensors.

        Args:
            tensors (Iterable[torch.Tensor]): A list of PyTorch tensors.
            disable_memory_format_check (bool): Whether to validate the memory formats of input tensors

        Returns:
            A list of Inputs.
        c                   s   g | ]	} j |d qS ))rc   )rj   )r2   rb   rh   rc   r   r   
<listcomp>g  s    z&Input.from_tensors.<locals>.<listcomp>)rM   rY   r@   )rh   rk   rc   r   rn   r   from_tensorsV  s   zInput.from_tensorsoptimization_profile_fieldOptional[str]c                   s   | j tjjkr0 durtdt| jtr&t	| jj
| jj
tjdddS td| j d   durqzt fdd	d
D sBJ W n tyN   tdw t| jtrht	| j  j
| jj
tjdddS td| j dtd)a  
        Get an example tensor of the shape specified by the Input object

        Args:
            optimization_profile_field (Optional(str)): Name of the field to use for shape in the case the Input is dynamically shaped

        Returns:
            A PyTorch Tensor
        Nz>Specified a optimization profile field but the input is staticT)use_defaultr9   zGInput shape is dynamic but shapes are not provided as sequence (found: rL   c                 3  s    | ]} |kV  qd S r0   r   )r2   
field_namerq   r   r   r5     s
    
z'Input.example_tensor.<locals>.<genexpr>r7   zCInvalid field name, expected one of min_shape, opt_shape, max_shaperK   zhRequested an example tensor from a dynamic shaped input but did not specific which profile field to use.)r   r   r   r   r?   rM   r   r@   rE   randtor
   rO   r>   AssertionErrorrN   )rH   rq   r   ru   r   rG   l  sB   zInput.example_tensor)r%   r   r&   r   r'   r(   )r'   r"   )rS   r   rT   r   r'   r   )rW   r   r'   r   )rI   rZ   r'   r[   )F)rb   r   rc   r   r'   rd   )rk   rl   rc   r   r'   rm   r0   )rq   rr   r'   r   ) r   r   r   __doc__r   r   r   __annotations__r   r
   rC   r   r   linearr   r   r   r   r    r#   r$   rJ   rQ   rR   staticmethodrV   r;   rD   classmethodrj   rp   rG   r   r   r   r   r   
   sH   
 




 


/r   )
__future__r   enumr   typingr   r   r   r   r   r	   rE   torch_tensorrt._enumsr
   r   objectr   r   r   r   r   <module>   s     