
    ip                       d Z 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
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 ddlmZ ddlmZmZmZmZ ddlZddlmZ ddlZddlmZ ddl m!Z! dd	l"m#Z# dd
l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-m.Z. erddl/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5  e
jl                  e7      Z8 ed      Z9 ed      Z:e:jw                         Z<e<rddl=Z>g Z?dZ@dZAe<reg dZ?e>j                  j                  j                  j                         j                  dd      ZAdj                  e?D  cg c]  } d|  d
 c}       Z@g dZH G d d      ZId?dZJd ZK G d! d"      ZLej                  d?d#       ZNd$d%d@d&ZOd$d%d@d'ZPd?d(ZQdAd)ZR G d* d+eS      ZTdBd,ZU	 	 dC	 	 	 	 	 	 	 	 	 dDd-ZV	 dEd$d$d.	 	 	 	 	 	 	 	 	 	 	 	 	 dFd/ZWdGd0ZX	 	 	 	 	 	 	 	 dHd1ZY	 	 	 	 	 	 dId2ZZ	 dEd$d$d.	 	 	 	 	 	 	 	 	 	 	 	 	 dJd3Z[	 	 	 	 	 	 dKd4Z\dLd5Z] e]ej                        Z_ e] ej                  d6            Za e]d      Zb e]d$      Zc e]d$      Zd G d7 d8      Ze G d9 d:      Zf G d; d<      Zg	 	 	 dM	 	 	 	 	 	 	 	 	 dNd=ZhdOd>Ziyc c} w )Pa  
Debug utilities for TorchDynamo compilation and execution.

This module provides various debugging tools and utilities for TorchDynamo, including:

- Minification support for reducing test cases while preserving bugs
- Input/output handling via InputReader and InputWriter for reproducible testing
- Accuracy checking between original and compiled models
- Neural network module string conversion via NNModuleToString
- Profiling tools and system information collection
- Buck build system integration for Meta-internal testing

Key classes:
- InputReader/InputWriter: Handle serialization of model inputs/outputs
- NNModuleToString: Converts nn.Modules to string representations
- BuckTargetWriter: Manages Buck build system integration
    )annotationsN)Counter)import_module)AnyOptionalTYPE_CHECKINGTypeVar)Tensor)rand_strided)normalize_path_separator)is_float_dtype)StorageWeakRef)ContentStoreReaderContentStoreWriter   )config)clone_inputsget_debug_dir	warn_once)CallableSequence)tqdm)UntypedStorageTztorch._inductor.config )z1//caffe2/torch/fb/sparsenn:sparsenn_operators_gpuz-//caffe2/torch/fb/sparsenn:sparsenn_operatorsz///deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpuz+//deeplearning/fbgemm/fbgemm_gpu:sparse_opszfbcode://
ztorch.ops.load_library("z"))buck2runz@mode/dev-nosanc                  &    e Zd ZddZddZdddZy)	BuckTargetWriterc                .   t         j                  j                  t         j                  j                  |            \  | _        | _        | j
                  j                  dd      | _        | j                  j                  dd       d| j                   | _        | j                  | j                  j                  d      d  | _        | j                  dd  | _        | j                  }||j                  d      d  dd  }d| d	| j                   | _	        y )
Nz.pyr   /.zfbcode.   zfbcode/r   :)
ospathsplitabspathsubdirpy_filereplacetargetfindcmd_line_path)selffilenametmps      S/var/www/html/engine/venv/lib/python3.12/site-packages/torch/_dynamo/debug_utils.py__init__zBuckTargetWriter.__init__Z   s    $&GGMM"''//(2K$L!T\ll**5"5 {{**345Qt{{mD	IIdiinnY79:	IIabM	 kk#((9%'(,!#a}5    c                    dj                  t        D cg c]  }d| d
 c}      }t        j                  d| j                   d| j
                   dt         d| d| j                   d	      S c c}w )
Nr   z	        "z",za
load("@fbcode_macros//build_defs:python_binary.bzl", "python_binary")

python_binary(
    name="z",
    srcs = ["z"],
    compile = False,
    deps = [
        "//caffe2:torch",
        "//caffe2:libtorch",
        "//caffe2/functorch:functorch",
        "//triton:triton",
        "z",
    ],
    cpp_deps = [
z
    ],
    main_module = "z",
    par_style = "xar",
)
)join
extra_depstextwrapdedentr.   r,   
cur_targetr(   )r1   xextra_cpp_depss      r4   buildzBuckTargetWriter.buildh   s    z#J!is"$5#JK ;;- ll^ 
     II; #
 	
 $Ks   A/c                P   t         j                  j                  | j                  d      }t	        |d      5 }|j                  | j                                d d d        t        | j                  gz   }|r%t        j                  ddj                  |             |S # 1 sw Y   FxY w)NTARGETSwzFFound an example that reproduces the error. Run this cmd to repro - %s )r'   r(   r8   r+   openwriter?   BUCK_CMD_PREFIXr0   logwarning)r1   	print_msgtarget_filefd	cmd_splits        r4   rE   zBuckTargetWriter.write   s    ggll4;;	:+s# 	#rHHTZZ\"	# $t'9'9&::	KKX# 	# 	#s    BB%N)r2   strreturnNonerN   rM   )T)rI   boolrN   	list[str])__name__
__module____qualname__r5   r?   rE    r6   r4   r!   r!   Y   s    6
4r6   r!   c                    t         j                  j                  t               d      } | +t	        j
                          dt        j                          } t         j                  j                  |       st        j                  | d       | S )Nminifierz
/minifier_T)exist_ok)
r'   r(   r8   r   tempfile
gettempdirgetpassgetuserexistsmakedirs)r(   s    r4   minifier_dirr`      sb    77<<4D|%%'(
7??3D2EF77>>$
D4(Kr6      c                     e Zd Zej                  j
                  ej                  j                  ej                  j                  ej                  j                  ej                  j                  ej                  j                  ej                  j                  ej                  j                  ej                  j                  ej                  j                  ej                  j                  ej                  j                   ej                  j"                  ej                  j$                  ej                  j&                  ej                  j(                  ej                  j*                  ej                  j,                  ej                  j.                  ej                  j0                  ej                  j2                  gZedd       Zedd       Zy)NNModuleToStringc                    t               }| j                         D ]2  \  }}t        |      t        j                  vs"|j                  |       4 t        |      dkD  rt        j                  d|       y)Nr   z-We have not tested reprs of some modules - %sT)	setnamed_childrentyperc   
safe_reprsaddlenrG   rH   )gmcant_convert_modules       r4   can_convert_to_stringz&NNModuleToString.can_convert_to_string   sg    u**, 	)IAvF|#3#>#>>  (	) |q KKGVr6   c                   ddl m} d}t        j                  d      }| j	                         D ]T  \  }}|j                          }t        |j                         d       }||j                  r| d}||dz   d| d| d	z  }V | j                  j                         D ]  \  }}	|		|	j                         t        k  r'dd
lm}
 |
j                  t        k\  sJ t!        |	      }nbt#        j$                  |	      r'dt'        |	j(                         d|	j*                   d}n&dt'        |	j(                         d|	j*                   d}|	j                  r| d}||dz   d| d| dz  } | j,                  j                         D ]Q  \  }}|	d}|j                  rd}dt'        |j(                         d|j*                   | d}||dz   d| d| d	z  }S | || j.                  d       d	z  }|S )Nr   )
_addindent    z
            from torch.nn import *
            class Repro(torch.nn.Module):
                def __init__(self) -> None:
                    super().__init__()
            z.cuda()   zself.z = r   )
PRINT_OPTSztorch.randn(z, dtype=)ztorch.randint(1, size=zself.register_buffer('z', z)
r   z, device="cuda"ztorch.nn.Parameter(torch.randn(z))ra   )torch.nn.modules.modulerq   r:   r;   rf   __repr__next
parametersis_cuda_buffersitemsnumelMAX_CONSTANT_NUMEL_INLINEtorch._tensor_strrt   	thresholdreprtorchis_floating_pointlistshapedtype_parameterscode)rk   rq   tab	model_strmodule_namern   
module_strexample_parambuffer_namebufferrt   
tensor_str
param_nameparammaybe_devices                  r4   convertzNNModuleToString.convert   s>   6OO
	 $&#4#4#6 	IK"OO-.J !!2!2!4d;M(]-B-B *|73
C!G9E+c*RHHI	I $&;;#4#4#6 	K~||~!::8!++/HHHH!&\
((0+D,>+?x~UVW
 -T&,,-?,@VWX  ~~ *|73
7)1+c*SQI#	* "$!5!5!7 	HJ}L}}0:4;L:MXV[VaVaUbcobpprsJC!G9E*SBGGI	H  	
277A./r22	r6   N)rk   torch.fx.GraphModulerN   rQ   )rk   r   rN   rM   )rS   rT   rU   r   nnLinearConv1dConv2dConv3dBatchNorm1dBatchNorm2dBatchNorm3d	LayerNormDropoutSoftmaxReLUGELUIdentity	MaxPool2d	EmbeddingTanhConvTranspose1dGLULSTMFlattenAdaptiveAvgPool2drh   staticmethodro   r   rV   r6   r4   rc   rc      s0     ""+J0 	 	 = =r6   rc   c                 4   t         j                  j                         syd} 	 t        j                  ddg      }|j                         j                  d      }dj                  |D cg c]  }|dk7  s	d| d c}      }| | dz  } t        d
 t        t         j                  j                               D              }| dz  } |j                         D ]  \  }}| d| d| dz  }  | dz  } | S c c}w # t        t        j                  f$ r | d	z  } Y w xY w)Nz:# torch.cuda.is_available()==False, no GPU info collected
z# CUDA Info: 
nvccz	--versionr   r   # z 
z# nvcc not found
c              3  Z   K   | ]#  }t         j                  j                  |       % y wN)r   cudaget_device_name).0is     r4   	<genexpr>z,_cuda_system_info_comment.<locals>.<genexpr>  s$      *+

""1%s   )+z# GPU Hardware Info: 
z : )r   r   is_available
subprocesscheck_outputdecoder)   r8   FileNotFoundErrorCalledProcessErrorr   rangedevice_countr|   )r   cuda_version_outcuda_version_linesscomment	gpu_namesnamecounts           r4   _cuda_system_info_commentr     s-   ::""$L!I*%22FK3HI-446<<TB''0BN1a2gRs#;NOy^#	  /4UZZ5L5L5N/O I **I ( .er$s5'--	.I Oz<<= *))	*s*   AC6 (
C13C1;C6 1C6 6DDF)stable_outputc           	         | ryg dg ddfd}t         j                  j                         D cg c]  \  }} ||      r	d| d| d }}}dj                  |      }t	        d	| d
      S c c}}w )zl
    Generate a string configuration for environment variables related to Dynamo, Inductor, and Triton.
    z+# env var omitted due to stable_output=True)TORCHDYNAMOINDUCTORTRITON)TRITON_LIBDEVICE_PATHTRITON_PTXAS_PATHTRITON_LIBCUDA_PATHc                :     t         fdD              xr  vS )Nc              3  &   K   | ]  }|v  
 y wr   rV   )r   stringkeys     r4   r   z;generate_env_vars_string.<locals>.filter.<locals>.<genexpr>&  s     :V6S=:s   )any)r   
allow_list	skip_lists   `r4   filterz(generate_env_vars_string.<locals>.filter%  s    :z::Ss)?SSr6   zos.environ['z'] = ''r   z
import os
z
    )r   rM   rN   rQ   )r'   environr|   r8   r   )r   r   r   valueconfig_linesconfig_stringr   r   s         @@r4   generate_env_vars_stringr     s     <:JUIT
 ****,C#; se6%*L 
 IIl+M# ) % 	 	s   A4c           	     ^   dd l }dd l}| ry|j                  j                  j                  j                         }d|j                  j                  j                          d|j                  j                  j                          d|j                  j                  j                          d| d	S )Nr   z*# config omitted due to stable_output=Truez~import torch._dynamo.config
import torch._inductor.config
import torch._functorch.config
import torch.fx.experimental._config
r   )
torch._functorch.configtorch._inductor.configfxexperimental_configcodegen_config_dynamor   	_inductor
_functorch)r   r   experimental_configs      r4   generate_config_stringr   4  s    "!;((//77FFH
 $$& ' (&&( ) *'') * +  	 	r6   c                 R    t         j                  j                  t               d      S )Nzminifier_launcher.py)r'   r(   r8   r`   rV   r6   r4   get_minifier_repro_pathr   H  s    77<<(>??r6   c                R   t               }t        j                  d|       t        rt	        |      j                          	 t        |d      5 }|j                  |        d d d        y # 1 sw Y   y xY w# t        $ r)}t        j                  d       t        d|       |d }~ww xY w)NzWriting minified repro to:
%srB   r   zCould not write to )
r   rG   rH   use_buckr!   rE   rD   OSError	exceptionNotImplementedError)contentsminified_repro_pathrK   es       r4   helper_for_dump_minifyr   L  s    13KK02EF,-335V%s+ 	rHHX	 	 	  Vb!$78K7L"MNTUUVs6   A4 A(A4 (A1-A4 1A4 4	B&=$B!!B&c                      e Zd Zy)AccuracyErrorN)rS   rT   rU   rV   r6   r4   r   r   [  s    r6   r   c                    t        |       }t        t        |             D ]A  }t        ||   t        j
                        s!||   j                  | |   j                         C |S )z
    This clone inputs is different from utils clone_input. In case of minifier,
    all the tensors are leaf tensors while creating a new graph. So, we set the
    requires_grad field w/o checking the leafness of the tensor.
    )r   r   rj   
isinstancer   r
   requires_grad_requires_grad)example_inputscloned_inputsidxs      r4   clone_inputs_retaining_gradnessr   _  sb     !0MS() QmC(%,,7#--nS.A.O.OPQ r6   c                &   ddl m}m}m} t	        j
                  |       } |st        |      }t        | d      r| j                  d       t        | dd      r | |      n | | }|r|S  ||      r ||      }|j                           || |d|      S )z
    Runs a forward and possibly backward iteration for a given mod and args.

    When disable_clone is True, we will use args as-is without cloning.
    This is higher fidelity but we may destroy the args in the process.
    r   )collect_resultsreduce_to_scalar_lossrequires_bwd_pass	zero_gradT_boxed_callFN)testingr   r  r  copydeepcopyr   hasattrr  getattrbackward)	rk   argsonly_fwddisable_cloner   r  r  outlosss	            r4   run_fwd_maybe_bwdr  l  s     SR	r	B.t4r;
T b-7"T(RYC
$S)2sD$//r6   require_fp64ignore_non_fpc                  ddl m} t        | ||      }d}t        j                  r9	 t        t        j                  |       t        |            \  }	}
t        |	|
|      }	 t        |||      } ||||t        j                  d|      }|S # t        $ r% |rt        d      t        j                  d       Y Yw xY w# t        $ r t        j                  d       Y yw xY w)	aa  
    Check two models have same accuracy.

    require_fp64: if True, raise an error if we unable to calculate the fp64 reference
    ignore_non_fp: if True, do not compare outputs which are not floating point.  This
        is mostly useful for the minifier (which wants to avoid quantizing floating point
        error into integer/boolean error)
    r   )sameNzfCould not generate fp64 outputs, workaround with torch._dynamo.config.same_two_models_use_fp64 = FalsezCould not generate fp64 outputszWhile minifying the program in accuracy minification mode, ran into a runtime exception which is likely an unrelated issue. Skipping this graph.T)tol	equal_nanr  )utilsr  r  r   same_two_models_use_fp64cast_to_fp64r  r  r   	ExceptionRuntimeErrorrG   rH   r   repro_tolerance)rk   opt_gmr   r  r  r  r  reffp64_ref
fp64_modelfp64_examplesrespassings                r4   same_two_modelsr%    s    " 
B
9CH&&
	;(4b!#B>#R)%J )]HMH
A ""#G N7  	;"|  KK9:	;   	$	

 s#   8B  B< +B98B9<CCc                   | j                   j                  D ]+  }|j                  dk(  r|j                  t        j
                  j                  j                  j                  u rvt        |j                        dk(  sJ t        |j                  d         rD|j                  d   t        j                  k7  r$|j                  d   t        j                  f|_
        |j                  dk(  s|j                  j                  d      }|t        |      st        |j                        }t        j                  |d<   ||_        . | j                   j!                          | j#                          | S )Ncall_functionrs   r   r   r   )graphnodesopr.   r   opsprimsconvert_element_typedefaultrj   r  r   float64kwargsgetdictlint	recompile)modelnoder   
new_kwargss       r4   cast_dtype_args_to_fp64r8    s   !! )GG&uyyCCKKKtyy>Q&&&diil+		!0M!YYq\5==9	77o%KKOOG,E ^E%:!$++.
&+mm
7#() 
KK	OOLr6   c                     ddl m} |j                         } t        j                  k(  rt        |      } | fd|      }||fS )Nr   )tree_mapc                ~    t        | t        j                        r!| j                         r| j	                        S | S r   )r   r   r
   r   to)r=   r   s    r4   <lambda>zcast_to.<locals>.<lambda>  s3    a&1+>+>+@ $$u+  r6   )torch.utils._pytreer:  r<  r   r/  r8  )r   r5  inputsr:  s   `   r4   cast_tor@    sM     -HHUOE (.	 		F &=r6   c                8    t        t        j                  | |      S r   )r@  r   r/  )r5  r?  s     r4   r  r    s     5==%00r6   c                   	  |t        j                  |       t        |            }t        | |||||       S # t        $ r t
        j                  d       Y yw xY w)Nr  zWhile minifying the program in accuracy minification mode, ran into a runtime exception which is likely an unrelated issue. Skipping this graphF)r  r  r   r%  r  rG   r   )rk   r   compiler_fnr  r  r  compiled_gms          r4   backend_accuracy_failsrE    st    !MM">~N
 #%'
 
 	
   	#	

 s   69 AAc               4    | | S t        j                  |      S r   )r  make_contiguous_strides_for)strider   s     r4   _stride_or_defaultrI    s    
 '6UU-N-Nu-UUr6   c                      fdS )Nc                    | | S S r   rV   )r=   ds    r4   r=  z_mk_defaulter.<locals>.<lambda>'  s    !-Q Q r6   rV   )rL  s   `r4   _mk_defaulterrM  &  s	    ..r6   cpuc                  F    e Zd ZddZddd	 	 	 	 	 	 	 	 	 ddZd	dZd
dZy)NopInputReaderc                    d| _         y )Nr   total)r1   s    r4   r5   zNopInputReader.__init__2  s	    
r6   Ndevice
dtype_hintc               .    | xj                   dz  c_         y )Nr   rR  )r1   storage_hashnbytesrU  rV  s        r4   storagezNopInputReader.storage5  s     	

a
r6   c                     y r   rV   r1   r  r0  s      r4   tensorzNopInputReader.tensor?      r6   c                     y r   rV   r\  s      r4   symintzNopInputReader.symintB  r^  r6   rN   rO   )
rX  Optional[str]rY  intrU  ,Optional[torch._prims_common.DeviceLikeType]rV  Optional[torch.dtype]rN   rO   )r  r   r0  r   rN   zOptional[torch.Tensor])r  r   r0  r   rN   Optional[int]rS   rT   rU   r5   rZ  r]  r`  rV   r6   r4   rP  rP  1  sP     @D,0# 
 = * 
r6   rP  c                      e Zd Zd	ddd
dZddd	 	 	 	 	 	 	 	 	 ddZ	 d	ddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZy)InputReaderN)pbarc               v    |t         j                  d       |t        |      nd | _        g | _        || _        y )Nz0no save_dir specified, will generate random data)rG   rH   r   storer  rj  )r1   save_dirrj  s      r4   r5   zInputReader.__init__I  s9    
 KKJK5=5I'1t
!		r6   rT  c                  | j                   | j                   j                  d       t        |      }t        |      }| j                  P|N	 | j                  j                  |      }||j                  k7  r!t        j                  d||j                         |S t        d| d       ||j                  z  f}t        d |      }t        ||||      j                         S # t        $ r Y Sw xY w)Nr   zdevice mismatch: %s != %szcould not load z , generating random data insteadr   )rj  update_device_or_default_dtype_or_defaultrl  read_storagerU  rG   rH   r   r   itemsizerI  r   untyped_storage)r1   rX  rY  rU  rV  rZ  r   rH  s           r4   rZ  zInputReader.storageT  s     99 IIQ#F+&z2
::!l&>
**11,? W^^+KK ;VW^^T OL>1QRS:...0#D6E6:v>NNPP % s   C" "	C.-C.)storage_offsetr   r   is_leafc                  t        ||      }t        |      }t        |      }t        |      }t	        |      }t        j                  g ||j                  |      }	t        j                         5  |	j                  ||||       d d d        |snt        j                         5  |	j                  t
        j                        }	d d d        t        j                         5  |	j                  ||||       d d d        t
        j                  j                  j                  |	      |k(  sJ t
        j                   j#                  |	|       | j$                  j'                  |	       |	S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w)Nro  )r   rU  r   )memory_format)rI  _storage_offset_or_defaultrr  _is_leaf_or_default_requires_grad_or_defaultr   r]  rU  no_gradset_enable_gradclonepreserve_format_subclasses
meta_utilssafe_is_leaf_utilsset_tensor_metadatar  append)
r1   rZ  r   rH  rv  r   r   rw  metadatats
             r4   r]  zInputReader.tensorq  sC    $F%83NC!%(%g.1-@LLeGNN-
 ]]_ 	;FF7NE6:	;""$ AGG%*?*?G@A ?wv>?  ++88;wFFF((H5			; 	;A A? ?s$   1E)$!E5!F)E25E>F
c                <    | j                   j                  |       |S r   )r  r  )r1   vals     r4   r`  zInputReader.symint  s    		
r6   r   )rm  rb  rj  zOptional[tqdm])
rX  rb  rY  rc  rU  rd  rV  re  rN   r   )rZ  r   r   torch._prims_common.ShapeTyperH  (Optional[torch._prims_common.StrideType]rv  rf  r   re  r   Optional[bool]rw  r  r  r   rN   torch.Tensor)r  r   rN   r   rg  rV   r6   r4   ri  ri  H  s    	QU 	  @D,0Q#Q Q
 =Q *Q 
QB <@	 )-'+(,"& - 9	 & % &    
Br6   ri  c                  `    e Zd ZddddZddZddd	 	 	 	 	 	 	 ddZddZdd	Zdd
ZddZ	y)InputWriterFstable_hashc                   g | _         t        j                         | _        || _        |t        ||      nd | _        i | _        y )Nr  )_lines	itertoolsr   storage_counterrm  r   rl  seen_storages)r1   rm  r  s      r4   r5   zInputWriter.__init__  sG    !#(0  # x[A 	

 9;r6   c                r    dg}|j                  d | j                  D               |j                  d       |S )Nzdef load_args(reader):c              3  &   K   | ]	  }d |   yw)rr   NrV   )r   ls     r4   r   z$InputWriter.lines.<locals>.<genexpr>  s     14s1s   zload_args._version = 0)extendr  r  )r1   rs     r4   lineszInputWriter.lines  s8    $
 	
1T[[11 	
)*r6   N)device_hintrV  c          
     D   t        |      }| j                  j                  |      }||S dt        | j                         }d}t        d       t        |      k7  rd|}d}|j                  }|j                  dk(  r|J |}t        d       |k7  rd|}|j                         }	d }
| j                  4|j                  j                  dk7  r| j                  j                  |      }
| j                  j                  | d|
d|	| | d       || j                  |<   |S )	Nbufr   z, dtype_hint=metaz	, device=z = reader.storage(, ru   )r   r  r1  rx   r  rr  rU  rg   rq  rY  rl  write_storager  r  )r1   ru  r  rV  wsvmaybe_dtype_hintr   rU  rY  rX  s              r4   rZ  zInputWriter.storage  sD    O,""2&=H$t++,-.T"&7
&CC!.zn=  '';;& *** Fd#v-&vj1L '')::!o&<&<&A&AV&K::33ODLc#L#32fZ~N^M__`a	
 "#2r6   c                t   ddl m}m} | j                  |j	                         |j
                  |j                        }g } | |t        d |j                        |j                                     s1|j                  t        t        |j                                            t        d       |j
                  k7  r|j                  d|j
                          |t        d       |j                         k(        s"|j                  d|j                                t         j"                  j%                  |      }|r&|j'                  d |j)                         D               t+        d       |j,                  k7  r|j                  d|j,                         t         j.                  j0                  j3                  |      }t5        d       |k7  r|j                  d	|       | j6                  j                  d
dj9                  |t        t        |j                              g|      z   d| z          y )Nr   )statically_known_truesym_eq)rV  r  ro  zdtype=zstorage_offset=c              3  0   K   | ]  \  }}| d |  yw)=NrV   )r   kr  s      r4   r   z%InputWriter.tensor.<locals>.<genexpr>  s     IA1#QqeIs   zrequires_grad=zis_leaf=zreader.tensor(r  )  # )%torch.fx.experimental.symbolic_shapesr  r  rZ  ru  r   rU  rI  r   rH  r  rM   tuplerr  rz  rv  r   r  get_tensor_metadatar  r|   r|  r   r  r  r  r{  r  r8   )	r1   r   r  r  r  rZ  r  tensor_metadatarw  s	            r4   r]  zInputWriter.tensor  s   W,,AGG  
 $%d!'':AHHJG
 KKE!((*-./T"agg-KK&,-$&t,0@0@0BB
 KK/!*:*:*<)?@A,,::1=KKI1F1F1HII$T*aoo=KK.(;<=##..;;A>t$/KK(7+./ii#eAGGn"5==>?dVn	
r6   c                   | j                   j                  d| dt        |              t        |t        t
        f      r| j                   j                  d       t        |      D ]  \  }}| d| d}t        |t        j                        r| j                  ||       ;t        |t        t        j                  f      r| j                  ||       n| j                  ||        | j                   j                  d       y y )Nr   z# was unsupported type for dumping: z"""[])r  r  rg   r   r   r  	enumerater   r
   r]  rc  SymIntr`  unsupported)r1   r   argr   aname_is         r4   r  zInputWriter.unsupported  s    Rv%HcTU cD%=)KKu%!# 01 61#Qa.KK*C#67KK*$$VQ/0 KKu% *r6   c                H    | j                   j                  d|d| d       y )Nzreader.const(r  z!, filtered out during compilation)r  r  )r1   r   s     r4   constzInputWriter.const  s'    D85.OP	
r6   c                    t        |t        j                        r|j                  j                  }| j
                  j                  d|d|        y )Nzreader.symint(r  )r   r   r  r6  hintr  r  )r1   r   r  s      r4   r`  zInputWriter.symint  s<    c5<<(((--C^C7%v>?r6   )rm  rb  r  rQ   rN   rO   )rN   rR   )ru  r   r  rd  rV  re  rN   rM   )r   rM   r  r  rN   rO   )r   rM   r  r   rN   rO   )r   rM   rN   rO   )r   rM   r  r   rN   rO   )
rS   rT   rU   r5   r  rZ  r]  r  r  r`  rV   r6   r4   r  r    s\    GL 
;& EI,0 '  B	 
 *  
 D
@&$
@r6   r  c           	        ddl m} |j                         D ci c]  \  }}||
 }}}dj                  |j	                               }t        j                  |       }	d| d}
d| d}d} G d	 d
      }i }|xs i dfddfd}| j                  } |j                         D ]  \  }}|dk(  rt        j                  ||      }|r>|j                         \  }}t        |j                  d            }||   } |||      ||<   t        j                  ||      }|s{ |j                  d            ||<    dt        j                  |       j                  v ro |       }||d<   t        j                   |
|	      D ]J  }|j                         \  }}}}t        |j                  d            }||   }t#        || |||             L |S c c}}w )a  
    Takes in a function which has been printed with print_readable() and constructs kwargs to run it.

    Handles Tensor inputs, Symints, and a graph module which might have tensor constants.

    Consider a function `forward` defined as follows:

    def forward(self, primals_1: "f32[1001, 6]", primals_2: "f32[s0]", primals_3: "Sym(s0)",):
        _tensor_constant0: "i64[4190]" = self._tensor_constant0
        # Further implementation

    kwargs = aot_graph_input_parser(forward)
    forward(**kwargs)
    r   )dtype_abbrs|z(_tensor_constant\d+): \"(z0)\[\s*(.*?)\s*\]\" = self\.(_tensor_constant\d+)(z)\[\s*(.*?)\s*\]zSym\((s\d+)\)c                      e Zd ZdZy)/aot_graph_input_parser.<locals>.TensorContainerz#Container for tensors as attributesN)rS   rT   rU   __doc__rV   r6   r4   TensorContainerr  C  s    -r6   r  rN   c                l     t        j                   v xs d u fd       j                         S )Nc                       dS )Nz; not in symbolic_shapes and default sym shape not passed inrV   )r`  s   r4   r=  z=aot_graph_input_parser.<locals>.get_sym_int.<locals>.<lambda>N  s    vhYZ r6   )r   _checkr1  )r`  default_sym_shapesym_shapes_dicts   `r4   get_sym_intz+aot_graph_input_parser.<locals>.get_sym_intK  s;    o%F):$)FZ	
 ""6+<==r6   c                   g }g }t        |       D ]a  \  }}|j                         }d|v r+ |      }|j                  |       |j                  |       E|sH|j                  t        |             c |j                  rt
        j                  nt
        j                  } |||
      }|D ]"  }	t
        j                  j                  ||	       $ |S )Nr   )r   rU  )
r  stripr  rc  r   r   randnzerosr   mark_dynamic)r   r   resolved_shapedynamic_dimsr   dimr   constructorr  rL  rU  r  s             r4   
gen_tensorz*aot_graph_input_parser.<locals>.gen_tensorR  s    & 	4FAs))+Ccz$%%a(##A&"))#c(3	4 &+%<%<ekk%++.fE 	/AMM&&sA.	/
r6   ,r   r1   )r`  rM   rN   rc  )r   r  r   torch.dtyperN   r
   )torch.utils._dtype_abbrsr  r|   r8   valuesinspect	getsource__annotations__researchgroupsr  r)   group	signaturery   finditersetattr)funcrU  
sym_shapesr  r  r   r   	dtype_mapdtype_patternsourcetensor_assignment_regextensor_regexsym_shape_regexr  r0  r  r   r   
annotationmatch	data_type	shape_strr   r   	container	attr_namerm   r  r  s    ` `                       @@r4   aot_graph_input_parserr    s   * 5 &1%6%6%8)!sEs
)I ) +"4"4"67M t$F "<M?Jz{&67L&O. .  F&0&6BO>* &&K.[..0 8zH		,
3#(<<> Iy)//#./Ei(E&ue4F5M		/:6'A7F5M8" ""4(333#%	"v[[!8&A 	DE16.Iy)Q)//#./Ei(EIy*UE*BC	D M[)s   Gc                     t        j                         t        j                  j	                  t        j                  j                                dfd}d fd}t        j                  |       |S )z
    Decorator to cProfile a given function and save the result to disk on process exit.

    Args:
        filename: filename to save profile to
    c                H     t        j                         d fd       }|S )Nc                     j                          	  | i |j                          S # j                          w xY wr   )enabledisable)r  r0  fnprofs     r4   wrapperz3profile_to_file.<locals>.decorator.<locals>.wrapper  s1    KKM4*6*s   + =)r  r   r0  r   rN   r   )	functoolswraps)r  r  r  s   ` r4   	decoratorz"profile_to_file.<locals>.decorator  s%    			 
	 r6   c            	         j                          t        j                  j                  t	        j
                  d  d  d             y )Nz!                Wrote profile to z+, view with:

                    snakeviz z

                )
dump_statssysstderrrE   r:   r;   )r2   r  s   r4   save_itz profile_to_file.<locals>.save_it  sK    !

OO""* ,&Z (		
r6   )r  r   rN   r   ra  )cProfileProfiler'   r(   r*   
expanduseratexitregister)r2   r  r  r  s   `  @r4   profile_to_filer
    sR     Dwwrww11(;<H	
 OOGr6   rP   )r   rQ   rN   rM   )r   rM   rN   rO   )r   Sequence[Any]rN   	list[Any])FF)
rk   r   r  r  r  rQ   r  rQ   rN   r   )F)rk   r   r  r   r   r  r  rQ   r  rQ   r  rQ   rN   rQ   )r5  r   rN   r   )r   r  r5  r   r?  r  rN   &tuple[torch.fx.GraphModule, list[Any]])r5  r   r?  r  rN   r  )rk   r   r   r  rC  zACallable[[torch.fx.GraphModule, list[Any]], torch.fx.GraphModule]r  rQ   r  rQ   r  rQ   rN   rQ   )rH  r  r   r  rN   ztorch._prims_common.StrideType)rL  r   rN   zCallable[[Optional[T]], T])r   NN)
r  z&Callable[[list[Tensor]], list[Tensor]]rU  rM   r  zOptional[dict[str, int]]r  rf  rN   zdict[str, Any])r2   rM   rN   zCallable[[T], T])jr  
__future__r   r  r  r  r  r\   r  r  loggingr'   r  r   r  rZ   r:   collectionsr   	importlibr   typingr   r   r   r	   r   torch._prims_common_prims_commonr  torch._subclasses.meta_utilsr
   torch._dynamo.testingr   torch._inductor.cpp_builderr   r    torch.multiprocessing.reductionsr   torch.utils._content_storer   r   r   r   r   r   r   collections.abcr   r   	torch.hubr   torch.storager   	getLoggerrS   rG   r   inductor_config	is_fbcoder   libfb.py.build_infolibfbr9   extra_importsr<   py
build_info	BuildInfoget_build_ruler-   r8   rF   r!   r`   r~   rc   cacher   r   r   r   r   r  r   r   r  r%  r8  r@  r  rE  rI  rM  float32rr  rU  rq  rz  r|  r{  rP  ri  r  r  r
  )r=   s   0r4   <module>r)     s  $ #         	 	  
    # 8 8  # #  . @ . ; M  9 9 2, g!CL   89$$& 

J $$..==?GG	SWXJIITA!9!B?TUM 64 4n  c cL  0 7< 	2 5: (@V	I 	
  	00
0 0 	0
 	0H 	7 77 7 "7 	7 7 7 
7t*3=F+(11)21+1 	 ! S 	   
RV4V )V $	V/ "%--0 "<5<<#67 *1- )%0 #E*  .L Lvy@ y@| +/'+	d
0dd )d %	d
 dN#g Us   J
