
    ȅi                    t   S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SSKJr  SSKJrJrJrJr  SSKrSSKJr  SSKrSSKJr  SSK J!r!  SS	K"J#r#  SS
KJ$r$  SSK%J&r&  SSK'J(r(J)r)  SSK*J+r+  SSKJ,r,J-r-J.r.  \(       a  SSK/J0r0J1r1  SSK2J3r3  SSK4J5r5  \
Rl                  " \75      r8\" S5      r9\" S5      r:\:Rw                  5       r<\<(       a  SSK=r>/ r?Sr@SrA\<(       ah  / SQr?\>R                  R                  R                  R                  5       R                  SS5      rASR                  \? V s/ s H	  n SU  S3PM     sn 5      r@/ SQrH " S S5      rIS?S jrJS rK " S! S"5      rL\R                  S?S# j5       rNS$S%.S@S& jjrOS$S%.S@S' jjrPS?S( jrQSAS) jrR " S* S+\S5      rTSBS, jrU  SC         SDS- jjrV SES$S$S..             SFS/ jjjrWSGS0 jrX        SHS1 jrY      SIS2 jrZ SES$S$S..             SJS3 jjjr[      SKS4 jr\SLS5 jr]\]" \R                  5      r_\]" \R                  " S65      5      ra\]" S5      rb\]" S$5      rc\]" S$5      rd " S7 S85      re " S9 S:5      rf " S; S<5      rg   SM         SNS= jjrhSOS> jrigs  sn f )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                  6    \ rS rSrSS jrSS jrS	S
S jjrSrg)BuckTargetWriterY   c                ,   [         R                  R                  [         R                  R                  U5      5      u  U l        U l        U R
                  R                  SS5      U l        U R                  R                  SS5       SU R                   3U l        U R                  U R                  R                  S5      S  U l        U R                  SS  U l        U R                  nX"R                  S5      S  SS  nSU S	U R                   3U l	        g )
Nz.pyr   /.zfbcode.   zfbcode/r   :)
ospathsplitabspathsubdirpy_filereplacetargetfindcmd_line_path)selffilenametmps      S/home/james-whalen/.local/lib/python3.13/site-packages/torch/_dynamo/debug_utils.py__init__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                    SR                  [         Vs/ s H	  nSU S3PM     sn5      n[        R                  " SU R                   SU R
                   S[         SU SU R                   S	35      $ s  snf )
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)   )r2   xextra_cpp_depss      r5   buildBuckTargetWriter.buildh   s    z#Jz!is"$5z#JK ;;- ll^ 
     II; #
 	
 $Ks   A3c                d   [         R                  R                  U R                  S5      n[	        US5       nUR                  U R                  5       5        S S S 5        [        U R                  /-   nU(       a%  [        R                  SSR                  U5      5        U$ ! , (       d  f       NP= f)NTARGETSwzFFound an example that reproduces the error. Run this cmd to repro - %s )r(   r)   r:   r,   openwriterA   BUCK_CMD_PREFIXr1   logwarning)r2   	print_msgtarget_filefd	cmd_splits        r5   rH   BuckTargetWriter.write   s    ggll4;;	:+s#rHHTZZ\" $ $t'9'9&::	KKX#  $#s    B!!
B/)r1   r)   r-   r,   r/   N)r3   strreturnNonerR   rQ   )T)rL   boolrR   	list[str])__name__
__module____qualname____firstlineno__r6   rA   rH   __static_attributes__ r8   r5   r!   r!   Y   s    6
4 r8   r!   c                 (   [         R                  R                  [        5       S5      n U c-  [        R
                  " 5        S[        R                  " 5        3n [         R                  R                  U 5      (       d  [         R                  " U SS9  U $ )Nminifierz
/minifier_T)exist_ok)
r(   r)   r:   r   tempfile
gettempdirgetpassgetuserexistsmakedirs)r)   s    r5   minifier_dirrf      se    77<<4D|%%'(
7??3D2EF77>>$
D4(Kr8      c                     \ rS rSr\R
                  R                  \R
                  R                  \R
                  R                  \R
                  R                  \R
                  R                  \R
                  R                  \R
                  R                  \R
                  R                  \R
                  R                  \R
                  R                  \R
                  R                   \R
                  R"                  \R
                  R$                  \R
                  R&                  \R
                  R(                  \R
                  R*                  \R
                  R,                  \R
                  R.                  \R
                  R0                  \R
                  R2                  \R
                  R4                  /r\SS j5       r\SS j5       rSrg)NNModuleToString   c                    [        5       nU R                  5        H5  u  p#[        U5      [        R                  ;  d  M$  UR                  U5        M7     [        U5      S:  a  [        R                  SU5        g)Nr   z-We have not tested reprs of some modules - %sT)	setnamed_childrentyperi   
safe_reprsaddlenrJ   rK   )gmcant_convert_modules       r5   can_convert_to_string&NNModuleToString.can_convert_to_string   s`    u**,IAF|#3#>#>>  ( - |q KKGVr8   c                $   SSK Jn  Sn[        R                  " S5      nU R	                  5        HY  u  pEUR                  5        n[        UR                  5       S 5      nUb  UR                  (       a  U S3nX2S-   SU SU S	3-  nM[     U R                  R                  5        H  u  pU	c  M
  U	R                  5       [        ::  a(  SS
KJn
  U
R                  [        :  d   e[!        U	5      nOh["        R$                  " U	5      (       a'  S['        U	R(                  5       SU	R*                   S3nO&S['        U	R(                  5       SU	R*                   S3nU	R                  (       a  U S3nUUS-   SU SU S3-  nM     U R,                  R                  5        HW  u  pUc  M
  SnUR                  (       a  SnS['        UR(                  5       SUR*                   U S3nX2S-   SU SU S	3-  nMY     X1" U R.                  S5       S	3-  nU$ )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))rg   )torch.nn.modules.modulery   r<   r=   rm   __repr__next
parametersis_cuda_buffersitemsnumelMAX_CONSTANT_NUMEL_INLINEtorch._tensor_strr|   	thresholdreprtorchis_floating_pointlistshapedtype_parameterscode)rr   ry   tab	model_strmodule_nameru   
module_strexample_parambuffer_namebufferr|   
tensor_str
param_nameparammaybe_devices                  r5   convertNNModuleToString.convert   s$   6OO
	 $&#4#4#6K"OO-.J !!2!2!4d;M(]-B-B *|73
!G9E+c*RHHI $7 $&;;#4#4#6K~||~!::8!++/HHHH!&\
((00+D,>+?x~UVW
 -T&,,-?,@VWX  ~~ *|73
7)1+c*SQI# $7* "$!5!5!7J}L}}0:4;L:MXV[VaVaUbcobpprsJ!G9E*SBGGI "8  	
277A./r22	r8   r\   N)rr   torch.fx.GraphModulerR   rU   )rr   r   rR   rQ   ) rW   rX   rY   rZ   r   nnLinearConv1dConv2dConv3dBatchNorm1dBatchNorm2dBatchNorm3d	LayerNormDropoutSoftmaxReLUGELUIdentity	MaxPool2d	EmbeddingTanhConvTranspose1dGLULSTMFlattenAdaptiveAvgPool2dro   staticmethodrv   r   r[   r\   r8   r5   ri   ri      s0     ""+J0 	 	 = =r8   ri   c                    [         R                  R                  5       (       d  gSn  [         R                  R                  cl  [
        R                  " SS/5      nUR                  5       R                  S5      nSR                  U Vs/ s H  o3S:w  d  M
  SU S3PM     sn5      nX S3-  n OU S	-  n  [        S [        [         R                  R                  5       5       5       5      nU S-  n UR                  5        H  u  pgU SU SU S3-  n M     U S-  n U $ s  snf ! [        [
        R                  4 a    U S
-  n  Nf = f)Nz:# torch.cuda.is_available()==False, no GPU info collected
z# CUDA Info: 
nvccz	--versionr   r   # z 
z'# Not searching for nvcc on ROCM setup
z# nvcc not found
c              3  `   #    U  H$  n[         R                  R                  U5      v   M&     g 7fN)r   cudaget_device_name).0is     r5   	<genexpr>,_cuda_system_info_comment.<locals>.<genexpr>  s&      /O!

""1%%/Os   ,.z# GPU Hardware Info: 
z : )r   r   is_availableversionhip
subprocesscheck_outputdecoder*   r:   FileNotFoundErrorCalledProcessErrorr   rangedevice_countr   )r   cuda_version_outcuda_version_linesscomment	gpu_namesnamecounts           r5   _cuda_system_info_commentr     sJ   ::""$$L!I	*==$)667LM!1!8!8!:!@!@!Fgg4FR4Fqr'{A3c{4FRSG9B'ICCI  /4UZZ5L5L5N/O I **I (r$s5'--	 )I S z<<= *))	*s0   A!D" 		D
D D" /D" D" "EEF)stable_outputc           	       ^^ U (       a  g/ SQm/ SQmSUU4S jjn[         R                  R                  5        VVs/ s H  u  p#U" U5      (       d  M  SU SU S3PM     nnnSR                  U5      n[	        S	U S
35      $ s  snnf )zd
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                H   >^  [        U 4S jT 5       5      =(       a    T T;  $ )Nc              3  ,   >#    U  H	  oT;   v   M     g 7fr   r\   )r   stringkeys     r5   r   ;generate_env_vars_string.<locals>.filter.<locals>.<genexpr>)  s     :zVS=zs   )any)r   
allow_list	skip_lists   `r5   filter(generate_env_vars_string.<locals>.filter(  s    :z::Ss)?SSr8   zos.environ['z'] = ''r   z
import os
z
    )r   rQ   rR   rU   )r(   environr   r:   r   )r   r   r   valueconfig_linesconfig_stringr   r   s         @@r5   generate_env_vars_stringr     s     <:JUIT T
 ****,,JC#; 	+,se6%*,  
 IIl+M# ) % 	 	s   BBc           	     h   SS K nSS KnU (       a  gUR                  R                  R                  R                  5       nSUR                  R                  R                  5        SUR                  R                  R                  5        SUR                  R                  R                  5        SU S3	$ )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      r5   generate_config_stringr   7  s    "!;((//77FFH
 $$& ' (&&( ) *'') * +  	 	r8   c                 R    [         R                  R                  [        5       S5      $ )Nzminifier_launcher.py)r(   r)   r:   rf   r\   r8   r5   get_minifier_repro_pathr   K  s    77<<(>??r8   c                h   [        5       n[        R                  SU5        [        (       a  [	        U5      R                  5          [        US5       nUR                  U 5        S S S 5        g ! , (       d  f       g = f! [         a)  n[        R                  S5        [        SU 35      UeS nAff = f)NzWriting minified repro to:
%srE   r   zCould not write to )
r   rJ   rK   use_buckr!   rH   rG   OSError	exceptionNotImplementedError)contentsminified_repro_pathrN   es       r5   helper_for_dump_minifyr  O  s    13KK02EFx,-335V%s+rHHX ,++  Vb!$78K7L"MNTUUVs6   A> A-$A> -
A;7A> ;A> >
B1$B,,B1c                      \ rS rSrSrg)AccuracyErrori^  r\   N)rW   rX   rY   rZ   r[   r\   r8   r5   r  r  ^  s    r8   r  c                    [        U 5      n[        [        U 5      5       HE  n[        X   [        R
                  5      (       d  M&  X   R                  X   R                  5        MG     U$ )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   rq   
isinstancer   r
   requires_grad_requires_grad)example_inputscloned_inputsidxs      r5   clone_inputs_retaining_gradnessr  b  sX     !0MS()m(%,,77--n.A.O.OP * r8   c                X   SSK JnJnJn  [        R
                  " U 5      n U(       d  [        U5      n[        U S5      (       a  U R                  S5        [        U SS5      (       a  U " U5      OU " U6 nU(       a  U$ U" U5      (       a  U" U5      nUR                  5         U" XSU5      $ )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)	rr   argsonly_fwddisable_cloner  r  r  outlosss	            r5   run_fwd_maybe_bwdr  o  s     SR	r	B.t4r;
T b-77"T(RYC
$S)2D$//r8   require_fp64ignore_non_fpc          	        SSK Jn  [        XU5      nSn[        R                  (       a8   [        [        R                  " U 5      [        U5      5      u  p[        XU5      n [        XU5      nU" UUU[        R                  SUS9nU$ ! [         a*    U(       a  [        S5      e[        R                  S5         N[f = f! [         a    [        R                  S5         gf = f)	aI  
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RuntimeErrorrJ   rK   r   repro_tolerance)rr   opt_gmr	  r  r   r!  r#  reffp64_ref
fp64_modelfp64_examplesrespassings                r5   same_two_modelsr3    s    " 
B
9CH&&
	;(4b!#B>#R)%J )HMH
A ""#G N7  	;"|  KK9:	;   	$	

 s#   7B
 #C 
1B>=B>C#"C#c                   U R                   R                   GH?  nUR                  S:X  a  UR                  [        R
                  R                  R                  R                  L a}  [        UR                  5      S:X  d   e[        UR                  S   5      (       aE  UR                  S   [        R                  :w  a$  UR                  S   [        R                  4Ul
        UR                  S:X  d  M  UR                  R                  S5      nUc  M  [        U5      (       d  GM  [        UR                  5      n[        R                  US'   X1l        GMB     U R                   R!                  5         U R#                  5         U $ )Ncall_functionr{   r   r   r   )graphnodesopr/   r   opsprimsconvert_element_typedefaultrq   r  r   float64kwargsgetdictlint	recompile)modelnoder   
new_kwargss       r5   cast_dtype_args_to_fp64rF    s   !!GG&uyyCCKKKtyy>Q&&&diil++		!0M!YYq\5==9	77o%KKOOG,E ^E%:%:!$++.
&+mm
7#( " 
KK	OOLr8   c                   ^  SSK Jn  UR                  T 5      nT [        R                  :X  a  [        U5      nU" U 4S jU5      nX4$ )Nr   )tree_mapc                   > [        U [        R                  5      (       a&  U R                  5       (       a  U R	                  T5      $ U $ r   )r  r   r
   r   to)r?   r   s    r5   <lambda>cast_to.<locals>.<lambda>  s<    a&&1+>+>+@+@ $$u+ r8   )torch.utils._pytreerH  rJ  r   r=  rF  )r   rC  inputsrH  s   `   r5   cast_torO    sK     -HHUOE (.	 		F =r8   c                6    [        [        R                  X5      $ r   )rO  r   r=  )rC  rN  s     r5   r(  r(    s     5==%00r8   c          	          U" [         R                  " U 5      [        U5      5      n[        U UUUUUS9(       + $ ! [         a    [
        R                  S5         gf = f)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  r3  r)  rJ   r   )rr   r	  compiler_fnr  r   r!  compiled_gms          r5   backend_accuracy_failsrT    st    !MM">~N
 #%'
 
 	
   	#	

 s   8; AAc               8    U b  U $ [         R                  " U5      $ r   )r&  make_contiguous_strides_for)strider   s     r5   _stride_or_defaultrX  !  s    
 '6UU-N-Nu-UUr8   c                   ^  U 4S j$ )Nc                   > U b  U $ T$ r   r\   )r?   ds    r5   rK  _mk_defaulter.<locals>.<lambda>*  s    !-Q.Q.r8   r\   )r[  s   `r5   _mk_defaulterr]  )  s	    ..r8   cpuc                  X    \ rS rSrS	S jrSSS.         S
S jjrSS jrSS jrSrg)NopInputReaderi4  c                    SU l         g )Nr   total)r2   s    r5   r6   NopInputReader.__init__5  s	    
r8   Ndevice
dtype_hintc               .    U =R                   S-  sl         g )Nr   rb  )r2   storage_hashnbytesrf  rg  s        r5   storageNopInputReader.storage8  s     	

a
r8   c                    g r   r\   r2   r  r>  s      r5   tensorNopInputReader.tensorB      r8   c                    g r   r\   rn  s      r5   symintNopInputReader.symintE  rq  r8   rb  rR   rS   )
ri  Optional[str]rj  intrf  ,Optional[torch._prims_common.DeviceLikeType]rg  Optional[torch.dtype]rR   rS   )r  r   r>  r   rR   zOptional[torch.Tensor])r  r   r>  r   rR   Optional[int]	rW   rX   rY   rZ   r6   rk  ro  rs  r[   r\   r8   r5   r`  r`  4  sP     @D,0# 
 = * 
r8   r`  c                      \ rS rSr SSS.     SS jjjrSSS.         SS jjr SSSSSS.                 SS jjjrSS	 jrS
rg)InputReaderiK  N)pbarc               x    Uc  [         R                  S5        Ub  [        U5      OS U l        / U l        X l        g )Nz0no save_dir specified, will generate random data)rJ   rK   r   storer  r~  )r2   save_dirr~  s      r5   r6   InputReader.__init__L  s7     KKJK5=5I'1t
!		r8   re  c                  U R                   b  U R                   R                  S5        [        U5      n[        U5      nU R                  bP  UbM   U R                  R                  U5      nX5R                  :w  a   [        R                  SX5R                  5        U$ [        SU S35        X$R                  -  4n[        S US9n[        XgXC5      R                  5       $ ! [         a     NNf = f)Nr   zdevice mismatch: %s != %szcould not load z , generating random data insteadr   )r~  update_device_or_default_dtype_or_defaultr  read_storagerf  rJ   rK   r   r   itemsizerX  r   untyped_storage)r2   ri  rj  rf  rg  rk  r   rW  s           r5   rk  InputReader.storageY  s     99 IIQ#F+&z2
::!l&>
**11,? ^^+KK ;V^^T OL>1QRS...0#D6E:>NNPP % s   C 
C+*C+)storage_offsetr   r  is_leafc               ,   [        X2S9n[        U5      n[        U5      n[        U5      n[	        U5      n[
        R                  " / XQR                  US9n	[
        R                  " 5          U	R                  XX#5        S S S 5        U(       dk  [
        R                  " 5          U	R                  [
        R                  S9n	S S S 5        [
        R                  " 5          U	R                  XX#5        S S S 5        [
        R                  R                  R                  U	5      U:X  d   e[
        R                   R#                  X5        U R$                  R'                  U	5        U	$ ! , (       d  f       N= f! , (       d  f       N= f! , (       d  f       N= f)Nr  )r   rf  r  )memory_format)rX  _storage_offset_or_defaultr  _is_leaf_or_default_requires_grad_or_defaultr   ro  rf  no_gradset_enable_gradclonepreserve_format_subclasses
meta_utilssafe_is_leaf_utilsset_tensor_metadatar  append)
r2   rk  r   rW  r  r   r  r  metadatats
             r5   ro  InputReader.tensorv  s    $F83NC!%(%g.1-@LLeNN-
 ]]_FF7E: ""$GG%*?*?G@ %w> !  ++88;wFFF((5		 _ %$ s$   +E#"E4F#
E14
F
Fc                <    U R                   R                  U5        U$ r   )r  r  )r2   vals     r5   rs  InputReader.symint  s    		
r8   )r  r~  r  r   )r  z
str | Noner~  ztqdm | NonerR   rS   )
ri  rv  rj  rw  rf  rx  rg  ry  rR   r   )rk  r   r   torch._prims_common.ShapeTyperW  (Optional[torch._prims_common.StrideType]r  rz  r   ry  r  Optional[bool]r  r  r  r   rR   torch.Tensor)r  r   rR   r   r{  r\   r8   r5   r}  r}  K  s    %)BF"4?	$ @D,0Q#Q Q
 =Q *Q 
QB <@	 )-'+(,"& - 9	 & % &    
Br8   r}  c                  z    \ rS rSrSS.SS jjrSS jrSSS.       SS jjrSS	 jrSS
 jrSS jr	SS jr
Srg)InputWriteri  Fstable_hashc                   / U l         [        R                  " 5       U l        Xl        Ub	  [        XS9OS U l        0 U l        g )Nr  )_lines	itertoolsr   storage_counterr  r   r  seen_storages)r2   r  r  s      r5   r6   InputWriter.__init__  sC    !#(0  # xA 	

 9;r8   c                r    S/nUR                  S U R                   5       5        UR                  S5        U$ )Nzdef load_args(reader):c              3  ,   #    U  H
  nS U 3v   M     g7f)rz   Nr\   )r   ls     r5   r   $InputWriter.lines.<locals>.<genexpr>  s     1[4s[s   zload_args._version = 0)extendr  r  )r2   rs     r5   linesInputWriter.lines  s8    $
 	
1T[[11 	
)*r8   N)device_hintrg  c          
     X   [        U5      nU R                  R                  U5      nUb  U$ S[        U R                  5       3nSn[        S 5      [        U5      :w  a  SU< 3nSnUR                  nUR                  S:X  a  Uc   eUn[        S 5      U:w  a  SU< 3nUR                  5       n	S n
U R                  b5  UR                  R                  S:w  a  U R                  R                  U5      n
U R                  R                  U SU
< SU	< U U S35        XPR                  U'   U$ )	Nbufr   z, dtype_hint=metaz	, device=z = reader.storage(, r}   )r   r  r?  r   r  r  rf  rn   r  rj  r  write_storager  r  )r2   r  r  rg  wsvmaybe_dtype_hintr   rf  rj  ri  s              r5   rk  InputWriter.storage  sB    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r8   c                   SSK JnJn  U R                  UR	                  5       UR
                  UR                  S9n/ nU" U" [        S UR                  S9UR                  5       5      5      (       d1  UR                  [        [        UR                  5       5      5      5        [        S 5      UR
                  :w  a  UR                  SUR
                  < 35        U" [        S 5      UR                  5       :H  5      (       d#  UR                  SUR                  5       < 35        [         R"                  R%                  U5      nU(       a&  UR'                  S UR)                  5        5       5        [+        S 5      UR,                  :w  a  UR                  SUR,                  < 35        [         R.                  R0                  R3                  U5      n[5        S 5      U:w  a  UR                  S	U< 35        U R6                  R                  S
SR9                  U[        [        UR                  5      5      /UQ5      -   SU 3-   5        g )Nr   )statically_known_truesym_eq)rg  r  r  zdtype=zstorage_offset=c              3  6   #    U  H  u  pU S U< 3v   M     g7f)=Nr\   )r   kr  s      r5   r   %InputWriter.tensor.<locals>.<genexpr>  s     I1H1#Qqe1Hs   zrequires_grad=zis_leaf=zreader.tensor(r  )  # )%torch.fx.experimental.symbolic_shapesr  r  rk  r  r   rf  rX  r   rW  r  rQ   tupler  r  r  r   r  get_tensor_metadatar  r   r  r  r  r  r  r  r  r:   )	r2   r   r  r  r  rk  r  tensor_metadatar  s	            r5   ro  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	
r8   c                *   U R                   R                  SU S[        U5       35        [        U[        [
        45      (       a  U R                   R                  S5        [        U5       H  u  p4U SU S3n[        U[        R                  5      (       a  U R                  XT5        M?  [        U[        [        R                  45      (       a  U R                  XT5        Mw  U R                  XT5        M     U R                   R                  S5        g g )Nr   z# was unsupported type for dumping: z"""[])r  r  rn   r  r   r  	enumerater   r
   ro  rw  SymIntrs  unsupported)r2   r   argr   aname_is         r5   r  InputWriter.unsupported  s    Rv%HcTU cD%=))KKu%!# 61#Qa..KK*C#677KK*$$V/ ' KKu% *r8   c                J    U R                   R                  SU< SU S35        g )Nzreader.const(r  z!, filtered out during compilation)r  r  )r2   r   s     r5   constInputWriter.const  s'    D85.OP	
r8   c                    [        U[        R                  5      (       a  UR                  R                  nU R
                  R                  SU< SU 35        g )Nzreader.symint(r  )r  r   r  rD  hintr  r  )r2   r   r  s      r5   rs  InputWriter.symint  s?    c5<<((((--C^C7%v>?r8   )r  r  r  r  r  )r  rv  r  rU   rR   rS   )rR   rV   )r  r   r  rx  rg  ry  rR   rQ   )r   rQ   r  r  rR   rS   )r   rQ   r  r   rR   rS   )r   rQ   rR   rS   )r   rQ   r  r   rR   rS   )rW   rX   rY   rZ   r6   r  rk  ro  r  r  rs  r[   r\   r8   r5   r  r    s\    GL 
;& EI,0 '  B	 
 *  
 D
@&$
@r8   r  c           	       ^^^^ SSK Jn  UR                  5        VVs0 s H  u  pVXe_M	     nnnSR                  UR	                  5       5      n[
        R                  " U 5      n	SU S3n
SU S3nSn " S	 S
5      n0 nU=(       d    0 mSUU4S jjmSUU4S jjnU R                  nUR                  " 5        H  u  nnUS:X  a  M  [        R                  " UU5      nU(       a>  UR                  5       u  nn[        UR                  S5      5      nUU   nU" UU5      UU'   [        R                  " UU5      nU(       d  M  T" UR                  S5      5      UU'   M     S[
        R                  " U 5      R                  ;   aq  U" 5       nUUS'   [        R                   " X5       HK  nUR                  5       u  nnnn[        UR                  S5      5      nUU   n[#        UUU" UU5      5        MM     U$ s  snnf )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                      \ rS rSrSrSrg)/aot_graph_input_parser.<locals>.TensorContaineriH  z#Container for tensors as attributesr\   N)rW   rX   rY   rZ   __doc__r[   r\   r8   r5   TensorContainerr  H  s    -r8   r  rR   c                |   >^  [         R                  " T T;   =(       d    TS LU 4S j5        TR                  T T5      $ )Nc                    > T  S3$ )Nz; not in symbolic_shapes and default sym shape not passed inr\   )rs  s   r5   rK  =aot_graph_input_parser.<locals>.get_sym_int.<locals>.<lambda>S  s    vhYZr8   )r   _checkr?  )rs  default_sym_shapesym_shapes_dicts   `r5   get_sym_int+aot_graph_input_parser.<locals>.get_sym_intP  s;    o%F):$)FZ	
 ""6+<==r8   c                  > / n/ n[        U 5       Hj  u  pEUR                  5       nSU;   a,  T" U5      nUR                  U5        UR                  U5        MG  U(       d  MP  UR                  [        U5      5        Ml     UR                  (       a  [
        R                  O[
        R                  nU" X!T
S9nU H"  n	[
        R                  R                  X5        M$     U$ )Nr   )r   rf  )
r  stripr  rw  r   r   randnzerosr   mark_dynamic)r   r   resolved_shapedynamic_dimsr   dimr   constructorr  r[  rf  r  s             r5   
gen_tensor*aot_graph_input_parser.<locals>.gen_tensorW  s    &FA))+Ccz$%%a(##A&3"))#c(3 ' &+%<%<ekk%++.fEAMM&&s. 
r8   ,r   r2   )rs  rQ   rR   rw  )r   r  r   torch.dtyperR   r
   )torch.utils._dtype_abbrsr  r   r:   valuesinspect	getsource__annotations__researchgroupsr  r*   group	signaturer   finditersetattr)funcrf  
sym_shapesr  r  r   r   	dtype_mapdtype_patternsourcetensor_assignment_regextensor_regexsym_shape_regexr  r>  r  r   r   
annotationmatch	data_type	shape_strr   r   	container	attr_namert   r  r  s    ` `                       @@r5   aot_graph_input_parserr  $  s   * 5 &1%6%6%8)%8zs
%8  ) +"4"4"67M t$F "<M?Jz{&67L&O. .  F&0&6BO> > * &&K(..0zH		,
3#(<<> Iy)//#./Ei(E&ue4F5M		/:65'A7F5M 1" ""4(333#%	"v[[!8AE16.Iy)Q)//#./Ei(EIy*UE*BC B M[)s   G7c                   ^ ^ [         R                  " 5       m[        R                  R	                  [        R                  R                  T 5      5      m SU4S jjnSU U4S jjn[        R                  " U5        U$ )z
Decorator to cProfile a given function and save the result to disk on process exit.

Args:
    filename: filename to save profile to
c                N   >^  [         R                  " T 5      SU U4S jj5       nU$ )Nc                    > TR                  5          T" U 0 UD6TR                  5         $ ! TR                  5         f = fr   )enabledisable)r  r>  fnprofs     r5   wrapper3profile_to_file.<locals>.decorator.<locals>.wrapper  s1    KKM4*6*s   + =)r  r   r>  r   rR   r   )	functoolswraps)r  r   r  s   ` r5   	decorator"profile_to_file.<locals>.decorator  s%    			 
	 r8   c            	        > TR                  T 5        [        R                  R                  [        R
                  " ST  ST  S35      5        g )Nz!                Wrote profile to z+, view with:

                    snakeviz z

                )
dump_statssysstderrrH   r<   r=   )r3   r  s   r5   save_it profile_to_file.<locals>.save_it  sK    !

OO""* ,&Z (		
r8   )r  r   rR   r   ru  )cProfileProfiler(   r)   r+   
expanduseratexitregister)r3   r$  r*  r  s   `  @r5   profile_to_filer1    sW     Dwwrww11(;<H	
 
 OOGr8   rT   )r   rU   rR   rQ   )r   rQ   rR   rS   )r	  Sequence[Any]rR   	list[Any])FF)
rr   r   r  r2  r  rU   r  rU   rR   r   )F)rr   r   r,  r   r	  r2  r  rU   r   rU   r!  rU   rR   rU   )rC  r   rR   r   )r   r  rC  r   rN  r3  rR   &tuple[torch.fx.GraphModule, list[Any]])rC  r   rN  r3  rR   r4  )rr   r   r	  r2  rR  zACallable[[torch.fx.GraphModule, list[Any]], torch.fx.GraphModule]r  rU   r   rU   r!  rU   rR   rU   )rW  r  r   r  rR   ztorch._prims_common.StrideType)r[  r   rR   zCallable[[Optional[T]], T])r   NN)
r
  z&Callable[[list[Tensor]], list[Tensor]]rf  rQ   r  zOptional[dict[str, int]]r  rz  rR   zdict[str, Any])r3   rQ   rR   zCallable[[T], T])jr  
__future__r   r/  r  r,  r"  rb   r   r  loggingr(   r  r   r(  r`   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   	getLoggerrW   rJ   r   inductor_config	is_fbcoder   libfb.py.build_infolibfbr;   extra_importsr>   py
build_info	BuildInfoget_build_ruler.   r:   rI   r!   rf   r   ri   cacher   r   r   r   r  r)  r  r  r  r3  rF  rO  r(  rT  rX  r]  float32r  rf  r  r  r  r  r`  r}  r  r  r1  )r?   s   0r5   <module>rP     s  $ #         	 	  
    # 8 8  # #  . @ . ; M  9 9 2, !CL   89$$& 

J $$..==?GG	SWXJIITA!9!B?TUM 64 4n  c cL  6 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*  .N Nzy@ y@| +/'+	d
0dd )d %	d
 dN#q Us   J5