o
    h                     @   s  U 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	m
Z
mZmZmZmZ d dlZd dlmZmZmZ d dlmZmZmZ ddlmZ dd	lmZ erYdd
lmZ g dZee Z!ee"e#e$e%e&ej'ej(ej)ej*ej+ejj,ej-ej.ej/f Z0e0j1Z2ee
de	f e"f Z3eee4d ed ee"df e5e6de0f  Z7ede7dZ8e9:g dZ;ej<j=ej>j?ej>j@gZAeBe
 eCd< ejDejEejFjEjGejFjHjIejFjJjIejFjKjIejFjLjIejMjNejMjOejMjPejQjRjIejSheTeAB ZUeTe
 eCd< eVejQdreUWejQjXjI eddde
de
fddZYde
de	f de"fddZZde[de"fd d!Z\d"e
de	f de"fd#d$Z]e$d%fd&e[d'e$de"fd(d)Z^ed*dG d+d deZ_ed*dd,e8de
e_ge7f de8fd-d.Z`ed*dd,e8de
e7ge7f de8fd/d0ZadS )1    N)MappingSequence)AnyCallableOptionalTYPE_CHECKINGTypeVarUnion)_fx_map_aggregate_fx_map_arg	_NodeBase)ArgsKwargsPairnormalize_functionnormalize_module   )ops   )compatibility)Graph)Nodemap_argmap_aggregatehas_side_effect.Argument.r   r   	ArgumentT)bound)placeholdercall_methodcall_modulecall_functionget_attroutputroot1_side_effectful_need_to_be_preserved_pre_dispatch_side_effectful_functionsresize_storage_bytes_Fis_backward_compatiblefnreturnc                 C   s   t |  | S N)r%   add)r)    r-   a/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/fx/node.pyr   h   s   
r   orig_methodc                 C   sR   | j }| j}|d ur|S ttjjfD ]}t||d | u r!|j   S qtd|  )Nzcannot find module for )__name__
__module__torchnn
functionalgetattrRuntimeError)r/   namemoduleguessr-   r-   r.   _find_module_of_methodo   s   
r:   objc                 C   s^   t | trt | tjs| jdkr| jS | j d| j S | du r"dS t | tjr+| jS t| S )a:  Return the repr() of an object, special-casing types (internal helper).
    If obj is a type, we return a shorter version than the default
    type.__repr__, based on the module and qualified name, which is
    typically enough to uniquely identify a type.  For everything
    else, we fall back on repr(obj).
    builtins..z...)	
isinstancetypetypesGenericAliasr1   __qualname__FunctionTyper0   repr)r;   r-   r-   r.   
_type_repr|   s   	
rE   funcc              
   C   s   t t| jd | u r| jS t| tjtjfr%| t tj| jd u r%d| j S | j}|dkrLzt	
| dd  }W n tyK } ztd|d }~ww t| }|dd}|dkrb|d	krbd
| }| d| S )Nztorch.Tensor.z<lambda>=r   zUnable to represent lambdaz
torch._opsz	torch.opsr2   segment_reduce_r=   )r5   r<   r0   r>   r@   MethodDescriptorTypeWrapperDescriptorTyper2   Tensorinspect	getsourcesplitstrip	Exceptionr6   r:   replace)rF   r7   er8   r-   r-   r.   _get_qualified_name   s,   
rT   infargmax_list_lenc                    s*  t | dr	|  S t| tr6d fddt| D }t|  d k r&dndt|  d}d	| | dS t| trod fd
dt| D }t|  d k rSdndt|  d}t| dkrcdnd}d| | | dS t| trddd | 	 D }d| dS t| t
rdt|  S t| S )N_custom_fx_repr_fnz, c                 3   $    | ]\}}| k rt |V  qd S r+   _format_arg.0idxarW   r-   r.   	<genexpr>       z_format_arg.<locals>.<genexpr>r    z, ...[total_len=][c                 3   rY   r+   rZ   r\   r`   r-   r.   ra      rb   ,()c                 s   s&    | ]\}}| d t | V  qdS ): NrZ   )r]   kvr-   r-   r.   ra      s   $ {}%)hasattrrX   r>   listjoin	enumeratelentupledictitemsr   str)rV   rW   rv   	maybe_lenmaybe_comma	items_strr-   r`   r.   r[      s.   

"
"

r[   Tc                       s  e Zd ZU dZed ed< eedf ed< ded< eed< eed	< d
ed< ed ed< ed ed< ee	 ed< e	ed< ee
d gef  ed< eee	f ed< edd	dpddded	edd
ded deedf dee	 ddf fddZdeee	f fddZdeee	f ddfdd Zedqd!d"Zedqd#d$Zedddrd&d'Zd(d defd)d*Zd(d defd+d,Zd(d defd-d.Zd(d defd/d0Zedddrd1d2Zdsd3d4Zedeed5f fd6d7Zejd8eed5f ddfd9d7Zedeeef fd:d;Zejd<eeef ddfd=d;Zeded  fd>d?Zeddd@e dAeddfdBdCZ!eddd@e dAeddfdDdEZ"edddFedAeddfdGdHZ#edee fdIdJZ$e$jdKee ddfdLdJZ$defdMdNZ%e&de'defdOdPZ(edd		dtdQeee  dReee  dee fdSdTZ)edddUdV fdWdXdYd dZe
d gef d[eded  fd\d]Z*edWddefd^d_Z+edWd			Wdud`e,j-j.daeee	  dbeeee	f  dcedee/ f
dddeZ0edddvdhdiZ1djeddfdkdlZ2dedme	ddfdndoZ3  Z4S )wr   ao  
    ``Node`` is the data structure that represents individual operations within
    a ``Graph``. For the most part, Nodes represent callsites to various entities,
    such as operators, methods, and Modules (some exceptions include nodes that
    specify function inputs and outputs). Each ``Node`` has a function specified
    by its ``op`` property. The ``Node`` semantics for each value of ``op`` are as follows:

    - ``placeholder`` represents a function input. The ``name`` attribute specifies the name this value will take on.
      ``target`` is similarly the name of the argument. ``args`` holds either: 1) nothing, or 2) a single argument
      denoting the default parameter of the function input. ``kwargs`` is don't-care. Placeholders correspond to
      the function parameters (e.g. ``x``) in the graph printout.
    - ``get_attr`` retrieves a parameter from the module hierarchy. ``name`` is similarly the name the result of the
      fetch is assigned to. ``target`` is the fully-qualified name of the parameter's position in the module hierarchy.
      ``args`` and ``kwargs`` are don't-care
    - ``call_function`` applies a free function to some values. ``name`` is similarly the name of the value to assign
      to. ``target`` is the function to be applied. ``args`` and ``kwargs`` represent the arguments to the function,
      following the Python calling convention
    - ``call_module`` applies a module in the module hierarchy's ``forward()`` method to given arguments. ``name`` is
      as previous. ``target`` is the fully-qualified name of the module in the module hierarchy to call.
      ``args`` and ``kwargs`` represent the arguments to invoke the module on, *excluding the self argument*.
    - ``call_method`` calls a method on a value. ``name`` is as similar. ``target`` is the string name of the method
      to apply to the ``self`` argument. ``args`` and ``kwargs`` represent the arguments to invoke the module on,
      *including the self argument*
    - ``output`` contains the output of the traced function in its ``args[0]`` attribute. This corresponds to the "return" statement
      in the Graph printout.
    r   _argsr   _kwargsr   graphr7   opTargettarget)r   N_input_nodesusersr?   	_sort_key_repr_fnmetaTr'   Nargskwargsreturn_typer*   c                    s   |dkrt |std| d| d| dt| d	n|tv s#J t|ts<td| d| d| dt| d	t ||||| | 	|| dS )	a}  
        Instantiate an instance of ``Node``. Note: most often, you want to use the
        Graph APIs, i.e. ``Graph.call_module``, ``Graph.call_method``, etc. rather
        than instantiating a ``Node`` directly.

        Args:
            graph (Graph): The ``Graph`` to which this ``Node`` should belong.

            name (str): The name to which the output of this ``Node`` should be assigned

            op (str): The opcode for this ``Node``. Can be one of 'placeholder',
                'call_method', 'call_module', 'call_function', 'get_attr',
                'output'

            target ('Target'): The target this op should call. See the broader
                ``Node`` docstring for more details.

            args (Tuple['Argument']): The args to be passed to ``target``

            kwargs (Dict[str, 'Argument']): The kwargs to be passed to ``target``

            return_type (Optional[Any]): The python type expression representing the
                type of the output of this node. This field can be used for
                annotation of values in the generated code or for other types
                of analyses.
        r    zNode [graph = z
, name = 'z
'] target z
 has type z but a Callable is expectedz but a str is expectedN)
callable
ValueErrorr2   typename
_legal_opsr>   rw   super__init___update_args_kwargs)selfr}   r7   r~   r   r   r   r   	__class__r-   r.   r   
  s   %"
"zNode.__init__c                 C   sL   i | j | j| j| j| j| j| j| j| j| j| j	| j
| j| j| j| jdS )N)r}   r7   r~   r   r?   r   r{   r|   _erased_prev_nextr   r   r   r   )__dict__r}   r7   r~   r   r   r{   r|   r   r   r   r   r   r   r   r   r-   r-   r.   __getstate__?  s&   zNode.__getstate__statec                 C   s"   |  D ]
\}}t| || qd S r+   )rv   setattr)r   r   rj   rk   r-   r-   r.   __setstate__S  s   zNode.__setstate__c                 C      | j S )z
        Returns the next ``Node`` in the linked list of Nodes.

        Returns:

            The next ``Node`` in the linked list of Nodes.
        )r   r   r-   r-   r.   nextW     	z	Node.nextc                 C   r   )z
        Returns the previous ``Node`` in the linked list of Nodes.

        Returns:

            The previous ``Node`` in the linked list of Nodes.
        )r   r   r-   r-   r.   prevb  r   z	Node.prevxc                 C   s   | j |j ks
J d| |krtd dS |  | j}|||_|_| ||_| _|jj}|jj}t|t|krS|dt|d  ^ }}g ||d R |_dS t|t|k rt|dt|d  ^ }}g ||d R |_dS g |dR |_dS )aD  
        Insert x before this node in the list of nodes in the graph. Example::

            Before: p -> self
                    bx -> x -> ax
            After:  p -> x -> self
                    bx -> ax

        Args:
            x (Node): The node to put before this node. Must be a member of the same graph.
        z0Attempting to move a Node into a different GraphzMTrying to prepend a node to itself. This behavior has no effect on the graph.Nr   r   )r}   logdebug_remove_from_listr   r   r   rs   )r   r   ppsknskprefixr^   r-   r-   r.   prependm  s&   zNode.prependotherc                 C   s   | j |j kS r+   r   r   r   r-   r-   r.   __gt__     zNode.__gt__c                 C   s   | j |j k S r+   r   r   r-   r-   r.   __lt__  r   zNode.__lt__c                 C   s   | |kp| |kS r+   r-   r   r-   r-   r.   __ge__     zNode.__ge__c                 C   s   | |k p| |kS r+   r-   r   r-   r-   r.   __le__  r   zNode.__le__c                 C   s   | j | dS )z
        Insert ``x`` after this node in the list of nodes in the graph.
        Equivalent to ``self.next.prepend(x)``

        Args:
            x (Node): The node to put after this node. Must be a member of the same graph.
        N)r   r   )r   r   r-   r-   r.   append  s   	zNode.appendc                 C   s    | j | j}}|||_|_ d S r+   )r   r   )r   r   nr-   r-   r.   r     s   zNode._remove_from_list.c                 C   r   )a@  
        The tuple of arguments to this ``Node``. The interpretation of arguments
        depends on the node's opcode. See the :class:`Node` docstring for more
        information.

        Assignment to this property is allowed. All accounting of uses and users
        is updated automatically on assignment.
        )r{   r   r-   r-   r.   r        
z	Node.argsr_   c                 C   s   |  || j dS )z
        Set the tuple of arguments to this Node. The interpretation of arguments
        depends on the node's opcode. See the ``fx.Graph`` docstring for more
        information.
        N)r   r|   )r   r_   r-   r-   r.   r        	c                 C   r   )aG  
        The dict of keyword arguments to this ``Node``. The interpretation of arguments
        depends on the node's opcode. See the :class:`Node` docstring for more
        information.

        Assignment to this property is allowed. All accounting of uses and users
        is updated automatically on assignment.
        )r|   r   r-   r-   r.   r     r   zNode.kwargsrj   c                 C   s   |  | j| dS )z
        Set the dict of kwargs to this Node. The interpretation of arguments
        depends on the node's opcode. See the ``fx.Graph`` docstring for more
        information.
        N)r   r{   )r   rj   r-   r-   r.   r     r   c                 C   s   t | j S )aE  
        Return all Nodes that are inputs to this Node. This is equivalent to
        iterating over ``args`` and ``kwargs`` and only collecting the values that
        are Nodes.

        Returns:

            List of ``Nodes`` that appear in the ``args`` and ``kwargs`` of this
            ``Node``, in that order.
        )rp   r   keysr   r-   r-   r.   all_input_nodes     zNode.all_input_nodesr^   rV   c                 C   s    t | j}|||< t|| _dS )a3  
        Update an existing positional argument to contain the new value
        ``arg``. After calling, ``self.args[idx] == arg``.

        Args:

            idx (int): The index into ``self.args`` of the element to update
            arg (Argument): The new argument value to write into ``args``
        N)rp   r   rt   )r   r^   rV   r   r-   r-   r.   
update_arg  s   
zNode.update_argc                 C   s   d|  krt | jksJ d J d| jd| }| j|d }||f | | _i }t||j | D ]}|| jvrJ| j| |j|  q7dS )a	  
        Insert an positional argument to the argument list with given index.

        Args:

            idx (int): The index of the element in ``self.args`` to be inserted before.
            arg (Argument): The new argument value to insert into ``args``
        r   z6insert_args index must be between 0 and len(self.args)N)rs   r   r{   r   
setdefaultr   r   r   )r   r^   rV   	args_left
args_right_new_input_nodesnew_user-   r-   r.   
insert_arg  s    
zNode.insert_argkeyc                 C   s   i | j ||i| _ dS )a2  
        Update an existing keyword argument to contain the new value
        ``arg``. After calling, ``self.kwargs[key] == arg``.

        Args:

            key (str): The key in ``self.kwargs`` of the element to update
            arg (Argument): The new argument value to write into ``kwargs``
        N)r   )r   r   rV   r-   r-   r.   update_kwarg  s   zNode.update_kwargc                 C   s   | j ddS )a   
        Return the Python stack trace that was recorded during tracing, if any.
        When traced with fx.Tracer, this property is usually populated by
        `Tracer.create_proxy`. To record stack traces during tracing for debug purposes,
        set `record_stack_traces = True` on the `Tracer` instance.
        When traced with dynamo, this property will be populated by default by
        `OutputGraph.create_proxy`.

        stack_trace would have the innermost frame at the end of the string.
        stack_traceN)r   getr   r-   r-   r.   r     r   zNode.stack_tracetracec                 C   s   || j d< d S )Nr   )r   )r   r   r-   r-   r.   r   -  s   c                 C   s   | j r|  | S | jS r+   )r   r7   r   r-   r-   r.   __repr__1  s   
zNode.__repr__c                 C   sd   t | tr| S t| dr.t| dd}|du rt| S | jdkr$d| S | jdkr.d| S t| S )z
        Make target printouts more user-friendly.
        1) builtins will be printed as `builtins.xyz`
        2) operators will be printed as `operator.xyz`
        3) other callables will be printed with qualified name, e.g. torch.add
        r1   r0   Nr<   z	builtins.	_operatorz	operator.)r>   rw   ro   r5   rT   r1   )r   r7   r-   r-   r.   _pretty_print_target6  s   





zNode._pretty_print_targetplaceholder_namesmaybe_return_typenamec                 C   s  | j dkrat| jtsJ | j}|| jr|dt| j  nd7 }|r*|| dS | jr5t| j dnd}| jrEdt| jd  d nd}d	| j d
| dt	| j
 d| j  d| j d| S | j dkr| jdurst| j dnd}d	| j d
| dt	| j
 d| j  d| | j dS | j dkr| jr|rdt| j |d< d| jd  S | jdurt| j dnd}d	| j d
| dt	| j
 d| j  d| | j dt| j dt| j dS )a  
        Return a descriptive string representation of ``self``.

        This method can be used with no arguments as a debugging
        utility.

        This function is also used internally in the ``__str__`` method
        of ``Graph``. Together, the strings in ``placeholder_names``
        and ``maybe_return_typename`` make up the signature of the
        autogenerated ``forward`` function in this Graph's surrounding
        GraphModule. ``placeholder_names`` and ``maybe_return_typename``
        should not be used otherwise.

        Args:
            placeholder_names: A list that will store formatted strings
                representing the placeholders in the generated
                ``forward`` function. Internal use only.
            maybe_return_typename: A single-element list that will store
                a formatted string representing the output of the
                generated ``forward`` function. Internal use only.

        Returns:
            str: If 1) we're using ``format_node`` as an internal helper
                in the ``__str__`` method of ``Graph``, and 2) ``self``
                is a placeholder Node, return ``None``. Otherwise,
                return a  descriptive string representation of the
                current Node.
        r   ri   rc   N z	(default=r   rh   rn   z : z[num_users=z] = z[target=rd   r!   r"   z -> zreturn z	](args = z, kwargs = )r~   r>   r   rw   r?   rE   r   r   r7   rs   r   r   r[   r   )r   r   r   arg_strmaybe_typenamedefault_valr-   r-   r.   format_nodeO  sF   
""
 4




zNode.format_nodec                 C   s   dS )NTr-   )userr-   r-   r.   <lambda>  s    zNode.<lambda>F)propagate_metareplace_withdelete_user_cbr   c                   s  |rt  jdksJ dj D ]	\}}| j|< qtj}g jj}|D ]L}||s5| q)dtdtf fdd}	t	|ddrU|j
D ]
}
|
 j|d	 qJt|j|	}t|j|	}t|tshJ t|tsoJ ||| q)t jt  dksJ fd
d|D S )a  
        Replace all uses of ``self`` in the Graph with the Node ``replace_with``.

        Args:

            replace_with (Node): The node to replace all uses of ``self`` with.
            delete_user_cb (Callable): Callback that is called to determine
              whether a given user of the self node should be removed.
            propagate_meta (bool): Whether or not to copy all properties
              on the .meta field of the original node onto the replacement node.
              For safety, this is only valid to do if the replacement node
              doesn't already have an existing .meta field.

        Returns:

            The list of Nodes on which this change was made.
        r   zmCalled node.replace_all_uses_with(replace_with, propagate_meta=True), but replace_with already has .meta keysr   r*   c                       | kr S | S r+   r-   r   )r   r   r-   r.   maybe_replace_node  s   z6Node.replace_all_uses_with.<locals>.maybe_replace_node_replace_hooksNoldnewr   c                    s   g | ]}| vr|qS r-   r-   )r]   r   )skippedr-   r.   
<listcomp>  s    z.Node.replace_all_uses_with.<locals>.<listcomp>)rs   r   rv   rp   r   r}   owning_moduler   r   r5   r   r7   r   r   r   r>   rt   ru   r   )r   r   r   r   rj   rk   
to_processmuse_noder   replace_hooknew_args
new_kwargsr-   )r   r   r   r.   replace_all_uses_with  s0   


zNode.replace_all_uses_withc                 C   s   | j dv rdS | j dkr*t| jdd}|dur|jrdS t| jddr%dS | jtv S | j dkrS| jjdus9J d	| jj| j}|dusMJ d
| j t|ddS dS )z
        Returns whether this op is impure, i.e. if its op is a placeholder or
        output, or if a call_function or call_module which is impure.

        Returns:

            bool: If the op is impure or not.
        >   r"   r   Tr    _schemaN_nondeterministic_seededFr   z1self.graph.owning_module not set for purity checkz'Did not find expected submodule target 
_is_impure)r~   r5   r   
is_mutabler%   r}   r   get_submodule)r   schema
target_modr-   r-   r.   	is_impure  s&   






zNode.is_impurer#   	arg_typeskwarg_typesnormalize_to_only_use_kwargsc                 C   s`   | j dkrt| jsJ t| j| j| j||S | j dkr.t| jts$J t|| j| j| jS dS )a  
        Returns normalized arguments to Python targets. This means that
        `args/kwargs` will be matched up to the module/functional's
        signature and return exclusively kwargs in positional order
        if `normalize_to_only_use_kwargs` is true.
        Also populates default values. Does not support positional-only
        parameters or varargs parameters.

        Supports module calls.

        May require `arg_types` and `kwarg_types` in order to disambiguate overloads.

        Args:
            root (torch.nn.Module): Module upon which to resolve module targets.
            arg_types (Optional[Tuple[Any]]): Tuple of arg types for the args
            kwarg_types (Optional[Dict[str, Any]]): Dict of arg types for the kwargs
            normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.

        Returns:

            Returns NamedTuple ArgsKwargsPair, or `None` if not successful.
        r    r   N)	r~   r   r   r   r   r   r>   rw   r   )r   r#   r   r   r   r-   r-   r.   normalized_arguments  s   

zNode.normalized_arguments	old_input	new_inputc                    s   dt dt f fdd}| jj}t|ddr$|jD ]
}| j| d qt| j|}t| j|}t	|t
s7J t	|ts>J | || dS )a  
        Loop through input nodes of ``self``, and replace all instances of
        ``old_input`` with ``new_input``.

        Args:

            old_input (Node): The old input node to be replaced.
            new_input (Node): The new input node to replace ``old_input``.
        r   r*   c                    r   r+   r-   r   r   r   r-   r.   r   +  r   z3Node.replace_input_with.<locals>.maybe_replace_noder   Nr   )r   r}   r   r5   r   r7   r   r   r   r>   rt   ru   r   )r   r   r   r   r   r   r   r   r-   r   r.   replace_input_with  s   
zNode.replace_input_with	candidatec                 C   s8   || j krd S | jj|d }|| _ | jj| | d S r+   )r7   r}   _graph_namespacecreate_name_rename_object)r   r   r7   r-   r-   r.   _rename9  s
   
zNode._renamevaluec                 C   s   |dkr-t | dr-| jj}t|dd r-t|tsJ | jD ]}|jD ]	}|| ||d q"qd}t | |rIt | jdrI| | jjv rId}| jj	|  t
| || |r[| jj|  d S d S )Nr7   r   r   F_find_nodes_lookup_tableT)ro   r}   r   r5   r>   rw   r   r   r   removeobject__setattr__insert)r   r7   r   r   r   r   updater-   r-   r.   r   @  s(   


zNode.__setattr__r+   )r*   r   )r   r   r*   N)r*   N)NN)NNF)r   r   r   r   r*   N)5r0   r1   rB   __doc__rt   __annotations__ru   rw   r   r   r   r   r   r   r   propertyr   r   r   boolr   r   r   r   r   r   r   r   setterr   rp   r   intr   r   r   r   r   staticmethodr   r   r   r   r   r2   r3   Moduler   r   r   r   r   __classcell__r-   r-   r   r.   r      s   
 	
	4

$





A:%
,r_   c                 C   s   t |sJ dt| |S )z
    Apply fn recursively to each Node appearing in arg.

    arg may be a list, tuple, slice, or dict with string keys: the return value will
    have the same type and structure.
    z.torch.fx.map_arg(a, fn): fn must be a callable)r   r   r_   r)   r-   r-   r.   r   U  s   
r   c                 C   s
   t | |S )z
    Apply fn recursively to each object appearing in arg.

    arg may be a list, tuple, slice, or dict with string keys: the return value will
    have the same type and structure.
    )r
   r
  r-   r-   r.   r   a  s   
r   )br<   rM   loggingoperatorr@   collections.abcr   r   typingr   r   r   r   r   r	   r2   torch._Cr
   r   r   torch.fx.operator_schemasr   r   r   _opsr   _compatibilityr   r}   r   __all__	getLoggerr0   r   rw   r  floatr  complexdtyperL   devicememory_formatlayout
OpOverloadSymIntSymBoolSymFloatBaseArgumentTypes__args__
base_typesr   rt   sliceranger   r   ru   fromkeysr   _C_set_grad_enabledamp_enter_autocast_exit_autocastr$   rp   r  _assert_assert_asyncatenmsg_assert_scalardefault_assert_tensor_metadatasym_constrain_rangesym_constrain_range_for_sizeprofiler_record_function_enter_record_function_enter_new_record_function_exitinductoraccumulate_grad_setitemsetr%   ro   r,   r&   r   r:   r   rE   rT   r[   r   r   r   r-   r-   r-   r.   <module>   s   
 

	     "&