
    Vh0                       d dl m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Zd dl	m
Z
mZmZ d dlZd dlZd dlmZ d dlmZmZ erd dlmZ ej,                   G d d             Zej,                   G d	 d
             Zej2                  d        ZddZ	 	 	 	 	 	 	 	 	 	 ddZddZ G d dej<                        Z G d dej<                        Z  G d dej<                        Z!y)    )annotationsN)AnyCallableTYPE_CHECKING)unset_fake_temporarily)diagnosticsonnxfunction_dispatcher)fake_tensorc                  F    e Zd ZU ded<   ded<   ded<   d	dZed
d       Zy)PackageInfostrpackage_name
str | Noneversioncommit_hashc           	     |    dj                  t        d d| j                  | j                  | j                  f            S )N.pkg)joinfilterr   r   r   )selfs    M/home/dcms/DCMS/lib/python3.12/site-packages/torch/onnx/_internal/fx/_pass.pyto_onnx_domain_stringz!PackageInfo.to_onnx_domain_string   s6    xx4%!2!2DLL$BRBRST
 	
    c                    t        |t              r|j                  }|j                  d      d   }t	        |      }t        |dd       }d } | |||      S )Nr   r   __version__)
isinstancetype
__module__split
__import__getattr)clspython_class_namer   packager   r   s         r   from_python_classzPackageInfo.from_python_class"   sZ    '. 1 < <(..s3A6\*'=$7<+66r   N)returnr   )r$   z
type | strr'   r   )__name__r   __qualname____annotations__r   classmethodr&    r   r   r   r      s-    

 7 7r   r   c                      e Zd ZU ded<   y)GraphModuleOnnxMetar   package_infoN)r(   r   r)   r*   r,   r   r   r.   r.   .   s    r   r.   c               #     K   t         j                  j                  dfd	} | t         j                  _        	 d t         j                  _        y# t         j                  _        w xY ww)aU  Context patching `difflib.SequenceMatcher` for fx readable graph.

    Under this context, the `autojunk` argument of `difflib.SequenceMatcher` will always
    be considered as `False`. This is to prevent `difflib.SequenceMatcher` recognizing
    stacktrace messages in fx readable graph as junk, as these messages tend to be long (>200)
    and repeat multiple times, which falls under the junk filter criteria.

    `difflib.SequenceMatcher` is used underneath by all sorts of diffing functions
    in `difflib`, including `difflib.unified_diff`, `difflib.ndiff`, `difflib.context_diff`.
    Unfortunately, there is no way to pass `autojunk` argument to these functions, and
    they all default to `True`. This context patching will affect all of them.

    `Reference: Automatic junk heuristic <https://docs.python.org/3/library/difflib.html>`_
    Nc                      | |||d       y )NF)autojunkr,   )r   isjunkabr2   original_inits        r   patched_initz:_patch_difflib_sequence_matcher_init.<locals>.patched_initE   s    dFAq59r   )N r8   T)difflibSequenceMatcher__init__)r7   r6   s    @r   $_patch_difflib_sequence_matcher_initr<   3   sS       ++44M: (4G$9+8(=(s   6A.A A.A++A.c                    | j                  d      }|j                  d      }t               5  dj                  t        j                  ||t
        j                              }ddd       sy|S # 1 sw Y   xY w)a  Return a string containing the unified diff of two strings.

    This function calls a patched version of `difflib.unified_diff` with `autojunk` set
    to `False` for `difflib.SequenceMatcher` class. More details can be found in
    `_patch_difflib_sequence_matcher_init` function.

    Args:
        a: The first string.
        b: The second string.

    Returns:
        The unified diff of the two strings. If there is no diff, return "<no diff>".

    Example::

        >>> a = '''class GraphModule(torch.nn.Module):
        ...     def forward(self, input_ids : torch.Tensor, attention_mask : torch.Tensor):
        ...         # File: /modeling.py:770, code: input_ids = input_ids.view(-1, input_shape[-1])
        ...         view = input_ids.view(-1, 3);  input_ids = None
        ... '''
        >>> b = '''class <lambda>(torch.nn.Module):
        ...     def forward(self, input_ids: i64[1, 3], attention_mask: i64[1, 3]):
        ...         # File: /modeling.py:770, code: input_ids = input_ids.view(-1, input_shape[-1])
        ...         view: i64[1, 3] = torch.ops.aten.view.default(input_ids, [-1, 3]);  input_ids = None
        ... '''
        >>> print(_unified_diff(a, b))
        ---
        +++
        @@ -1,4 +1,4 @@
        -class GraphModule(torch.nn.Module):
        -    def forward(self, input_ids : torch.Tensor, attention_mask : torch.Tensor):
        +class <lambda>(torch.nn.Module):
        +    def forward(self, input_ids: i64[1, 3], attention_mask: i64[1, 3]):
                # File: /modeling.py:770, code: input_ids = input_ids.view(-1, input_shape[-1])
        -        view = input_ids.view(-1, 3);  input_ids = None
        +        view: i64[1, 3] = torch.ops.aten.view.default(input_ids, [-1, 3]);  input_ids = None
    T)keependsr8   )nNz	<no diff>)
splitlinesr<   r   r9   unified_diffsysmaxsize)r4   r5   a_listb_listdiffs        r   _unified_diffrG   O   sr    N \\4\(F\\4\(F	-	/ Lwww++FFckkJKL KL Ls   6A22A;	Transformc                6    d|j                   j                   dS )NzRunning z pass. )	__class__r(   )runr   argskwargss       r   *_transform_diagnose_call_message_formatterrN      s     dnn--.g66r   c                   t        j                         }t        j                  |      5  	 | j	                          	 ddd       |j                         S # t
        $ r Y ddd       yw xY w# 1 sw Y   |j                         S xY w)a"  Return the Graph nodes in tabular format. Equivalent to stdout of `graph.print_tabular()`.
    If `tabulate` is not installed, return `None`.

    Args:
        graph: The Graph to print.

    Returns:
        The Graph printed in a tabular format. None if `tabulate` is not installed.
    N)ioStringIO
contextlibredirect_stdoutprint_tabularImportErrorgetvalue)graphfs     r   maybe_fx_graph_tabularrY      sx     	A		#	#A	& 	!
 ::<  		 	
 ::<s(   A,A	A)A,(A))A,,Bc                      e Zd ZU dZded<   	 ded<   	 ded<   	 	 	 	 	 ddZdd	Z	 	 	 	 	 	 dd
Zej                  dd       Z
 ej                  ej                  j                  e      dd       Zy)rH   a  Base class for FX graph transformations to be used by FX-ONNX exporter.

    Similar to `FX Interpreter <https://pytorch.org/docs/stable/fx.html#torch.fx.Interpreter>`_,
    specializations of this class execute the FX graph Node-by-Node.
    Methods in the `Transform` class can be overridden to customize the behavior of the model.
    This pattern can be useful for many things, including writing code transformations as well as analysis passes.

    The following methods can be overridden::

        _run()
            +-- run_node()
                +-- placeholder()
                +-- get_attr()
                +-- call_function()
                +-- call_method()
                +-- call_module()
                +-- output()

    One important aspect to note is that if the transformation modifies the model input and/or output signature,
    (e.g. additional inputs/outputs are added to the model), :class:`InputAdaptStep` and/or :class:`OutputAdaptStep`
    are needed to reconcile :attr:`ONNXProgram.model_proto`.
    That is, the model signature and the model representation must match.

    As an additional feature, this class provides builtin support for transformation recording using the diagnostics.
    The granularity of overriding is up to the user. And it affects the granularity of
    the diagnostics information. For example, if `_run()` is overridden, the
    diagnostics information will only contain graph level transformation. Instead,
    if `call_function()` is overridden, the diagnostics information will additionally
    contain the node level information of `call_function()`.

    TODO(bowbao): Add more overridable methods in call hierarchy
    TODO(bowbao): Create an example once more overridable methods are added.
    diagnostics.DiagnosticContextdiagnostic_contexttorch.fx.GraphModulemodule!fake_tensor.FakeTensorMode | None	fake_modec                J    || _         || _        | j                         | _        y)zInitialize the transform.

        Args:
            diagnostic_context: The diagnostic context for recording diagnostics.
            module: The module to be transformed.
        N)r\   r^   _detect_fake_moder`   )r   r\   r^   s      r   r;   zTransform.__init__   s#     #5//1r   c                *   | j                   j                  j                  D cg c]  }|j                  j	                  d       }}t               5  t        j                  j                  j                  |      cddd       S c c}w # 1 sw Y   yxY w)z}Detect fake mode from the graph.

        Scan through all nodes in graph and their meta['val'] to detect fake mode.
        valN)
r^   rW   nodesmetagetr   torch_dynamoutilsdetect_fake_mode)r   nodefake_tensorss      r   rb   zTransform._detect_fake_mode   sw    
 :>9J9J9P9PQ		e,QQ#% 	F==&&77E	F 	F R	F 	Fs   "B)B		Bc                4    |S t        fd|D              S )Nc              3  x   K   | ]1  }t        |t        j                        rj                  |      n| 3 y wN)r   rh   Tensorfrom_tensor).0tr`   s     r   	<genexpr>z/Transform._maybe_fakefy_args.<locals>.<genexpr>   s3      
OP
1ell(CI!!!$J
s   7:)tuple)r   r`   rL   s    ` r   _maybe_fakefy_argszTransform._maybe_fakefy_args   s,     K  
TX
 
 	
r   c                     y rp   r,   )r   rL   rM   s      r   _runzTransform._run   s    =@r   )diagnostic_message_formatterc           
        | j                   j                  t        j                  j                        }|j                  d       t        j                  }|j                  j                  |      r<| j                  j                  d      }t        | j                  j                        }nd}d} | j                  |i |}|j                  j                  |      r|j                  d      }t        |j                        }	|j                  |d      5  |j!                  |dt        j"                  t$        ||             ddd       |j                  |d	      5  ||	|j!                  |d
       n,|j!                  |dt        j"                  t$        ||	             ddd       |S |S # 1 sw Y   kxY w# 1 sw Y   |S xY w)a`  Run the transform on `self.module`.

        Note that this method may or may not mutate `self.module`, and the returned
        `GraphModule` could be either `self.module` or a new `GraphModule`.

        Args:
            *args: Positional arguments for `self.module` to run.
            **kwargs: Keyword arguments for `self.module` to run.
        )rulezFor detailed logging of graph modifications by this pass, either set `DiagnosticOptions.verbosity_level` to `logging.DEBUG` or use the environment variable `TORCH_LOGS='onnx_diagnostics'`.F)print_outputr8   zGraph diff:z
```
%s
```NzTabular diff:zBTabular diff is not available because `tabulate` is not installed.)r\   inflight_diagnosticr   rulesfx_passinfologgingDEBUGloggerisEnabledForr^   print_readablerY   rW   ry   log_sectionlog
LazyStringrG   )
r   rL   rM   
diagnosticgraph_diff_log_levelold_readable_graphold_tabularr^   new_readable_graphnew_tabulars
             r   rK   zTransform.run   s    ,,@@""** A 

 	/	
  '}}))*>?!%!;!;!;!O01B1BCK "$KD+F+ ))*>?!'!6!6E!6!J0>K''(<mL ("**%'9;M ''(<oN &+*=NN,\
 NN,&#..}k;W v-  s   -F.AF:.F7:GN)r\   r[   r^   r]   )r'   r_   )r`   r_   rL   r   r'   ztuple[Any, ...])r'   r]   )r(   r   r)   __doc__r*   r;   rb   rw   abcabstractmethodry   r   diagnose_callr   r   rN   rK   r,   r   r   rH   rH      s     D 65;  '00=292 %2F	
:	
CF	
		
 	@ @[!!%O<	<r   c                      e Zd Zy)AnalysisResultN)r(   r   r)   r,   r   r   r   r   3  s    r   r   c                  F    e Zd Z	 	 	 	 	 	 ddZej
                  dd       Zy)Analysisc                .    || _         || _        || _        y rp   )r\   r^   r	   )r   r\   r^   r	   s       r   r;   zAnalysis.__init__8  s     #5'>$r   c                     y rp   r,   )r   diagnostic_levels     r   analyzezAnalysis.analyzeB  s    TWr   N)r\   r[   r^   r]   r	   z.onnxfunction_dispatcher.OnnxFunctionDispatcher)r   zdiagnostics.infra.Levelr'   r   )r(   r   r)   r;   r   r   r   r,   r   r   r   r   7  s:    ?9? %? "P	? 	W Wr   r   )r4   r   r5   r   r'   r   )
rK   r   r   rH   rL   r   rM   r   r'   r   )rW   ztorch.fx.Graphr'   r   )"
__future__r   r   rR   dataclassesr9   rP   r   rB   typingr   r   r   rh   torch.fxtorch._subclasses.fake_tensorr   torch.onnx._internal.fxr   r	   torch._subclassesr
   	dataclassr   r.   contextmanagerr<   rG   rN   rY   ABCrH   r   r   r,   r   r   <module>r      s   " 
    	  
 / /   @ H - 7 7 7,    9 960f7	7
7 7 	7
 	7&R RjSWW Xsww Xr   