
    ^j                    4   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      ZIdAdZJd ZK G d! d"eL      ZM G d# d$      ZNej                  dAd%       ZPd&d'dBd(ZQd&d'dBd)ZRdAd*ZSdCd+ZT G d, d-eU      ZVdDd.ZW	 	 dE	 	 	 	 	 	 	 	 	 dFd/ZX	 dGd&d&d0	 	 	 	 	 	 	 	 	 	 	 	 	 dHd1ZYdId2ZZ	 	 	 	 	 	 	 	 dJd3Z[	 	 	 	 	 	 dKd4Z\	 dGd&d&d0	 	 	 	 	 	 	 	 	 	 	 	 	 dLd5Z]	 	 	 	 	 	 dMd6Z^dNd7Z_ e_ej                        Za e_ ej                  d8            Zc e_d      Zd e_d&      Ze e_d&      Zf G d9 d:      Zg G d; d<      Zh G d= d>      Zi	 	 	 dO	 	 	 	 	 	 	 	 	 dPd?ZjdQd@Zkyc c} w )Ra  
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cast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(""))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      d/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/_dynamo/debug_utils.py__init__zBuckTargetWriter.__init__[   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)   )r2   xextra_cpp_depss      r5   buildzBuckTargetWriter.buildi   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)   r9   r,   openwriter@   BUCK_CMD_PREFIXr1   logwarning)r2   	print_msgtarget_filefd	cmd_splits        r5   rF   zBuckTargetWriter.write   s    ggll4;;	:+s# 	#rHHTZZ\"	# $t'9'9&::	KKX# 	# 	#s    BB%N)r3   strreturnNonerO   rN   )T)rJ   boolrO   	list[str])__name__
__module____qualname__r6   r@   rF    r7   r5   r"   r"   Z   s    6
4r7   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)   r9   r   tempfile
gettempdirgetpassgetuserexistsmakedirs)r)   s    r5   minifier_dirra      sb    77<<4D|%%'(
7??3D2EF77>>$
D4(Kr7      c                      e Zd Zy)UnsupportedNNModuleErrorNrT   rU   rV   rW   r7   r5   rd   rd          r7   rd   c                  h   e Zd ZddhZh dZddh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                  j0                  ej                  j2                  ej                  j4                  ej                  j6                  ej                  j8                  ej                  j:                  gZedd       Z edd       Z!edd	       Z"edd
       Z#edd       Z$edd       Z%edd       Z&edd       Z'edd	 	 	 	 	 dd       Z(edddd       Z)y)NNModuleToStringz0torch.ao.quantization.fake_quantize.FakeQuantizezAtorch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize>   #torch.ao.nn.qat.modules.conv.Conv1d#torch.ao.nn.qat.modules.conv.Conv2d#torch.ao.nn.qat.modules.conv.Conv3d5torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBn1d5torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBn2d5torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBn3d7torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvReLU1d7torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d7torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvReLU3d9torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU1d9torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d9torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU3dz%torch.ao.nn.qat.modules.linear.Linearz8torch.ao.nn.intrinsic.qat.modules.linear_relu.LinearReLU)fbgemmx86qnnpackonednnc                    t               }| j                         D ],  \  }}t        j                  |      |j	                  |       . t        |      dkD  rt        j                  d|       yy)Nr   z2Cannot safely convert some modules to strings - %sFT)setnamed_childrenrh   _module_constructor_stringaddlenrH   rI   )gmcant_convert_modules       r5   can_convert_to_stringz&NNModuleToString.can_convert_to_string   sl    u**, 	)IAv::6BJ  (	) |q KKDl r7   c                \    t        |       j                   dt        |       j                   S Nr%   )typerU   rT   )r   s    r5   _module_type_namez"NNModuleToString._module_type_name   s)    v,))*!DL,A,A+BCCr7   c                8    | j                    d| j                   S r   )rU   rT   )type_s    r5   
_type_namezNNModuleToString._type_name   s    ""#1U^^$455r7   c                   t         j                  |       }|t         j                  vry | j                  }t	        t
        | j                        }t	        t
        | j                        }t        |dd      r|dz  }|dz  dz   }dt         j                  t        |             d|d|d| j                  d	| j                  d
| j                  g}t        |d      r|j                  d|j                          t        |d      r|j                  d|j"                         | ddj%                  |       dS )Nreduce_rangeF   r   z	observer=z
quant_min=z
quant_max=dtype=zqscheme=zis_dynamic=zreduce_range=ch_axiszch_axis=(, ))rh   r   fake_quant_modulesactivation_post_processr   int	quant_min	quant_maxgetattrr   r   dtypeqscheme
is_dynamichasattrappendr   r   r9   )r   module_typeobserverr   r   argss         r5   _fake_quant_constructorz(NNModuleToString._fake_quant_constructor   sA   &88@.AAA11f../	f../	8^U3NI!A)I(33DNCDE&&V\\$%v~~()&++./
 8^,KK-(=(='@AB8Y'KK(8#3#3"678a		$022r7   c                    t        | dd       }t        j                  D ]K  }	 t        j                  j
                  j                  |      }t        |      t        |      k(  sEd|dc S  y # t        $ r Y Zw xY w)Nqconfigz6qconfig=torch.ao.quantization.get_default_qat_qconfig(r   )	r   rh   default_qat_qconfig_backendstorchaoquantizationget_default_qat_qconfigAssertionErrorrepr)r   r   backenddefault_qconfigs       r5   _qat_qconfig_constructorz)NNModuleToString._qat_qconfig_constructor  s    &)T2'DD 		G"'(("7"7"O"OPW"X G}_ 55{!%		  " s   )A--	A98A9c           
        t         j                  |       }|t         j                  vry t         j                  |       }|y t	        | j
                        t	        | j                        d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d u d| j                  g	}t        | dd       }|;|j                  d	|j                   d
|j"                  d| j$                  g       |j'                  |       | ddj)                  |       dS )Nzkernel_size=zstride=zpadding=z	dilation=zgroups=bias=zpadding_mode=bnzeps=z	momentum=z
freeze_bn=r   r   r   )rh   r   qat_conv_modulesr   r   in_channelsout_channelskernel_sizestridepaddingdilationgroupsbiaspadding_moder   extendepsmomentum	freeze_bnr   r9   )r   r   r   r   r   s        r5   _qat_conv_constructorz&NNModuleToString._qat_conv_constructor  sP   &88@.???";;FC? ##$$$%6--01fmm&'v~~()*+fmm&'FKKt+,-F//23

 VT4(>KK266*%/ !1!1 45 	Ga		$022r7   c                &   t         j                  |       }|t         j                  vry t         j                  |       }|y t	        | j
                        t	        | j                        d| j                  d u |g}| ddj                  |       dS )Nr   r   r   r   )	rh   r   qat_linear_modulesr   r   in_featuresout_featuresr   r9   )r   r   r   r   s       r5   _qat_linear_constructorz(NNModuleToString._qat_linear_constructor6  s    &88@.AAA";;FC? ##$$$%FKKt+,-	
 a		$022r7   c                |    t        |       t        j                  vry	 t        d| dd       y# t        $ r Y yw xY w)NFzmod = z<module repr>execT)r   rh   
safe_reprscompileSyntaxError)r   
module_strs     r5   _can_emit_module_constructorz-NNModuleToString._can_emit_module_constructorG  sI    </:::	fZL)?FC   		s   / 	;;Fallow_unsafe_reprc                   t        |       }t        j                  | |      r|S t        j                  |       xs, t        j	                  |       xs t        j                  |       }||S |r|S y N)r   rh   r   r   r   r   )r   r   r   constructor_strs       r5   r|   z+NNModuleToString._module_constructor_stringR  sx     &\
88L44V< @55f=@77? 	
 &""r7   c               0   ddl m} d}t        j                  d      }| j	                         D ]  \  }}t
        j                  ||      }|t        d|      t        |j                         d       }||nt        |j                         d       }	|	+|	j                  j                  dk7  r| d|	j                   d	}||d
z   d| d| dz  } | j                  j                         D ]  \  }
}|
|j                         t         k  rEddlm} |j&                  t         k  r t)        d|j&                   dt          d      t+        |      }nbt-        j.                  |      r'dt1        |j2                         d|j4                   d}n&dt1        |j2                         d|j4                   d}|j                  j                  dk7  r| d|j                   d	}||d
z   d|
 d| dz  } | j6                  j                         D ]l  \  }}|	d}|j                  j                  dk7  rd|j                   d}dt1        |j2                         d|j4                   | d}||d
z   d| d| dz  }n | || j8                  d       dz  }|S )Nr   )
_addindent    z
            from torch.nn import *
            class Repro(torch.nn.Module):
                def __init__(self) -> None:
                    super().__init__()
            r   z!Cannot convert module to string: cpuz.to("r   r   zself.z = r   )
PRINT_OPTSzPRINT_OPTS.threshold (z() must be >= MAX_CONSTANT_NUMEL_INLINE (r   ztorch.randn(z, dtype=ztorch.randint(1, size=zself.register_buffer('z', z)
r   z
, device=""ztorch.nn.Parameter(torch.randn(z))rb   )torch.nn.modules.moduler   r;   r<   r{   rh   r|   rd   next
parametersbuffersdevicer   _buffersitemsnumelMAX_CONSTANT_NUMEL_INLINEtorch._tensor_strr   	thresholdr   r   r   is_floating_pointlistshaper   _parameterscode)r   r   r   tab	model_strmodule_namer   r   example_paramexample_tensorbuffer_namebufferr   
tensor_str
param_nameparammaybe_devices                    r5   convertzNNModuleToString.convertd  s    6OO
	 $&#4#4#6 	IK)DD*; E J !.7zB 
 !!2!2!4d;M !, &..*D1 
 )n.C.C.H.HE.Q *|51F1F0GrJ
C!G9E+c*RHHI%	I( $&;;#4#4#6 	K~||~!::8''*CC(01E1E0F G66O5PPQS  "&\
((0+D,>+?x~UVW
 -T&,,-?,@VWX  }}!!U* *|5rB
7)1+c*SQI+	2 "$!5!5!7 	HJ}L||  E)!+ELL>;:4;L:MXV[VaVaUbcobpprsJC!G9E*SBGGI	H  	
277A./r22	r7   N)r   torch.fx.GraphModulerO   rR   )r   torch.nn.ModulerO   rN   )r   ztype[object]rO   rN   )r   r   rO   
str | None)r   r   r   rN   rO   rR   )r   r   r   rR   rO   r   )r   r   r   rR   rO   rN   )*rT   rU   rV   r   r   r   r   r   nnLinearConv1dConv2dConv3dBatchNorm1dBatchNorm2dBatchNorm3d	LayerNormDropoutSoftmaxReLUGELUIdentity	MaxPool2d	EmbeddingTanhConvTranspose1dGLULSTMFlattenAdaptiveAvgPool2dr   staticmethodr   r   r   r   r   r   r   r   r|   r   rW   r7   r5   rh   rh      s#   :K
  	0B $J  	  ""+J0   D D 6 6 3 32   3 3> 3 3    >C7;	 " GL L Lr7   rh   c                 t   t         j                  j                         syd} 	 t         j                  j                  ht        j                  ddg      }|j                         j                  d      }dj                  |D cg c]  }|dk7  s	d| d c}      }| | dz  } n| 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 
z'# Not searching for nvcc on ROCM setup
z# nvcc not found
c              3  Z   K   | ]#  }t         j                  j                  |       % y wr   )r   cudaget_device_name).0is     r5   	<genexpr>z,_cuda_system_info_comment.<locals>.<genexpr>  s$      *+

""1%s   )+z# GPU Hardware Info: 
z : )r   r  is_availableversionhip
subprocesscheck_outputdecoder*   r9   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Rq!r'A3c{RSGG9B'ICCI  /4UZZ5L5L5N/O I **I ( .er$s5'--	.I S z<<= *))	*s*   AD 
DDD D D76D7F)stable_outputc                P   | ryg dg dddgdfd}t         j                  j                         D cg c]&  \  }} ||      rd| d|j                  d	d
       d	( }}}|j	                  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_PATHTORCHDYNAMO_REPRO_AFTERTORCHDYNAMO_REPRO_LEVELc                F     t         fdD              xr
  vxr  vS )Nc              3  &   K   | ]  }|v  
 y wr   rW   )r  stringkeys     r5   r  z;generate_env_vars_string.<locals>.filter.<locals>.<genexpr>  s     7&#7s   )any)r5  
allow_listrepro_env_vars	skip_lists   `r5   filterz(generate_env_vars_string.<locals>.filter  s0    7J77 *9$*>)	
r7   zos.environ['z'] = ''r   c              3  (   K   | ]
  }d | d  yw)zos.environ.pop('z', None)NrW   )r  r5  s     r5   r  z+generate_env_vars_string.<locals>.<genexpr>  s     SS*3%x8Ss   r   z
import os
z
    )r5  rN   rO   rR   )r(   environr   r.   r   r9   r   )	r'  r:  r5  valueconfig_linesconfig_stringr7  r8  r9  s	         @@@r5   generate_env_vars_stringrA    s     <:JUI/1JKN
 ****,C#; VEMM#s$;#<A@L  SNSSIIl+M# ) % 	 	s   +B"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      r5   generate_config_stringrM    s    "!;((//77FFH
 $$& ' (&&( ) *'') * +  	 	r7   c                 R    t         j                  j                  t               d      S )Nzminifier_launcher.py)r(   r)   r9   ra   rW   r7   r5   get_minifier_repro_pathrO    s    77<<(>??r7   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:
%srC   r   zCould not write to )
rO  rH   rI   use_buckr"   rF   rE   OSError	exceptionNotImplementedError)contentsminified_repro_pathrL   es       r5   helper_for_dump_minifyrX    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)AccuracyErrorNre   rW   r7   r5   rZ  rZ    rf   r7   rZ  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  r~   
isinstancer   r
   requires_grad_requires_grad)example_inputscloned_inputsidxs      r5   clone_inputs_retaining_gradnessrb    sb     !0MS() QmC(%,,7#--nS.A.O.OPQ r7   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)testingrd  re  rf  copydeepcopyrb  r   rg  r   backward)	r   r   only_fwddisable_clonerd  re  rf  outlosss	            r5   run_fwd_maybe_bwdrq  (  s     SR	r	B.t4r;
T b-7"T(RYC
$S)2sD$//r7   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_nanrt  )utilsrv  rq  r   same_two_models_use_fp64cast_to_fp64rj  rk  rb  	ExceptionRuntimeErrorrH   rI   rS  repro_tolerance)r   opt_gmr_  rm  rs  rt  rv  reffp64_ref
fp64_modelfp64_examplesrespassings                r5   same_two_modelsr  H  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 ]L  }|j                  dk(  r|j                  t        j
                  j                  j                  j                  u rt        |j                        dk7  r!t        dt        |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<   ||_        O | j                   j#                          | j%                          | S )Ncall_functionr   z"Expected node to have 2 args, got r   r   r   )graphnodesopr/   r   opsprimsconvert_element_typedefaultr~   r   r   r   float64kwargsgetdictlint	recompile)modelnoder   
new_kwargss       r5   cast_dtype_args_to_fp64r    s#   !! )GG&uyyCCKKK499~"$8TYY8HI  diil+		!0M!YYq\5==9	77o%KKOOG,E ^E%:!$++.
&+mm
7#(!)$ 
KK	OOLr7   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    r5   <lambda>zcast_to.<locals>.<lambda>  s3    a&1+>+>+@ $$u+  r7   )torch.utils._pytreer  r  r   r  r  )r   r  inputsr  s   `   r5   cast_tor    sM     -HHUOE (.	 		F &=r7   c                8    t        t        j                  | |      S r   )r  r   r  )r  r  s     r5   r{  r{    s     5==%00r7   c                   	  |t        j                  |       t        |            }t        | |||||       S # t        $ r t
        j                  d       Y yw xY w)Nrr  zWhile minifying the program in accuracy minification mode, ran into a runtime exception which is likely an unrelated issue. Skipping this graphF)rj  rk  rb  r  r|  rH   rS  )r   r_  compiler_fnrm  rs  rt  compiled_gms          r5   backend_accuracy_failsr    st    !MM">~N
 #%'
 
 	
   	#	

 s   69 AAc               4    | | S t        j                  |      S r   )ry  make_contiguous_strides_for)r   r   s     r5   _stride_or_defaultr    s    
 '6UU-N-Nu-UUr7   c                      fdS )Nc                    | | S S r   rW   )r>   ds    r5   r  z_mk_defaulter.<locals>.<lambda>  s    !-Q Q r7   rW   )r  s   `r5   _mk_defaulterr    s	    ..r7   r   c                  f    e Zd ZddZddd	 	 	 	 	 	 	 	 	 ddZddZddZddZddZdd	Z	dd
Z
y)NopInputReaderc                    d| _         y )Nr   total)r2   s    r5   r6   zNopInputReader.__init__  s	    
r7   Nr   
dtype_hintc               .    | xj                   dz  c_         y Nr   r  )r2   storage_hashnbytesr   r  s        r5   storagezNopInputReader.storage  s     	

a
r7   c                     y r   rW   r2   r   r  s      r5   tensorzNopInputReader.tensor      r7   c                     y r   rW   r  s      r5   symintzNopInputReader.symint  r  r7   c                     y r   rW   r2   r$  s     r5   constzNopInputReader.const  r  r7   c                     y r   rW   r  s     r5   unsupportedzNopInputReader.unsupported  r  r7   c                     y r   rW   )r2   device_typedevice_indexs      r5   	generatorzNopInputReader.generator
  r  r7   c                .    | xj                   dz  c_         y r  r  r2   script_class_names     r5   opaquezNopInputReader.opaque  s    

a
r7   rO   rP   )
r  r   r  r   r   )torch._prims_common.DeviceLikeType | Noner  torch.dtype | NonerO   rP   )r   r   r  r   rO   ztorch.Tensor | None)r   r   r  r   rO   
int | Noner$  rN   rO   rP   )r  rN   r  r   rO   rP   r  rN   rO   rP   rT   rU   rV   r6   r  r  r  r  r  r  r  rW   r7   r5   r  r    sc     =A)-  
 : ' 
r7   r  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dd	Zdd
ZddZ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)rH   rI   r   storer   r  )r2   save_dirr  s      r5   r6   zInputReader.__init__  s9     KKJK5=5I'1t
!		r7   r  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   )r  update_device_or_default_dtype_or_defaultr  read_storager   rH   rI   r  r   itemsizer  r   untyped_storage)r2   r  r  r   r  r  r   r   s           r5   r  zInputReader.storage!  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                  |	      |k7  r8t!        dt
        j                  j                  j                  |	       d|       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)Nr  )r   r   r^  )memory_formatz/Tensor leaf status mismatch: safe_is_leaf(t) = z, expected )r  _storage_offset_or_defaultr  _is_leaf_or_default_requires_grad_or_defaultr   r  r   no_gradset_enable_gradclonepreserve_format_subclasses
meta_utilssafe_is_leafr   _utilsset_tensor_metadatar   r   )
r2   r  r   r   r  r   r^  r  metadatats
             r5   r  zInputReader.tensor>  sx    $F%83NC!%(%g.1-@LLeGNN-
 ]]_ 	;FF7NE6:	;""$ AGG%*?*?G@A ?wv>?''44Q77B A$$//<<Q?@G9V  	((H5			; 	;A A? ?s$   1F$!F,!F8F),F58G)exprc                   | j                   j                  |       |8t        | d      si | _        || j                  t	        | j                         dz
  <   |S )Nsymint_exprsr   )r   r   r   r  r~   )r2   valr  s      r5   r  zInputReader.symintc  sN    		4046!48Dc$))nq01
r7   c                :    | j                   j                  d        y r   r   r   r  s     r5   r  zInputReader.constk      		r7   c                :    | j                   j                  d        y r   r  r  s     r5   r  zInputReader.unsupportedn  r  r7   c                    t        j                  ||      }t        j                  |      }| j                  j	                  |       |S )N)r   )r   r   	Generatorr   r   )r2   r  r  r   gens        r5   r  zInputReader.generatorq  s7    k<8ooV,		
r7   c                :    | j                   j                  d        y r   r  r  s     r5   r  zInputReader.opaquew  r  r7   r   )r  r   r  ztqdm | NonerO   rP   )
r  r   r  r   r   r  r  r  rO   r   )r  r   r   torch._prims_common.ShapeTyper   %torch._prims_common.StrideType | Noner  r  r   r  r^  bool | Noner  r  r  r   rO   torch.Tensor)r  r   r  r   rO   r   r  )r  rN   r  r   rO   r   r  r  rW   r7   r5   r  r    s   %)BF"4?	$ =A)-Q Q Q
 :Q 'Q 
QB 9=	# &*$(%)### -# 6	# ## "# ## # # 
#J 6: r7   r  c                  p    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	ddZ
ddZy)InputWriterFstable_hashc                   g | _         t        j                         | _        || _        |t        ||      nd | _        i | _        y )Nr  )_lines	itertoolsr%  storage_counterr  r   r  seen_storages)r2   r  r  s      r5   r6   zInputWriter.__init__  sG    !#(0  # x[A 	

 9;r7   c                r    dg}|j                  d | j                  D               |j                  d       |S )Nzdef load_args(reader):c              3  &   K   | ]	  }d |   yw)r   NrW   )r  ls     r5   r  z$InputWriter.lines.<locals>.<genexpr>  s     14s1s   zload_args._version = 0)r   r
  r   )r2   rs     r5   lineszInputWriter.lines  s8    $
 	
1T[[11 	
)*r7   N)device_hintr  c          
     V   t        |      }| j                  j                  |      }||S dt        | j                         }d}t        d       t        |      k7  rd|}d}|j                  }|j                  dk(  r|t        d      |}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_hint must be provided when storage device is 'meta'z	, device=z = reader.storage(r   r   )r   r  r  r   r  r  r   r   r   r  r  r  write_storager
  r   )r2   r  r  r  wsvmaybe_dtype_hintr   r   r  r  s              r5   r  zInputWriter.storage  sP    O,""2&=H$t++,-.T"&7
&CC!.zn=  '';;& "$P  !Fd#v-&vj1L '')::!o&<&<&A&AV&K::33ODLc#L#32fZ~N^M__`a	
 "#2r7   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)r  r  r  r   zstorage_offset=c              3  0   K   | ]  \  }}| d |  yw)=NrW   )r  kr  s      r5   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  r  r  r   r   r  r   r   r   rN   tupler  r  r  r   r  get_tensor_metadatar   r   r  r^  r  r  r  r  r
  r9   )	r2   r$  r  r  r  r  r   tensor_metadatar  s	            r5   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	
r7   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 )Nzreader.unsupported(z#)  # unsupported type for dumping: z"""[])r
  r   r   r\  r   r#  	enumerater   r
   r  r   SymIntr  r  )r2   r$  argr  aname_is         r5   r  zInputWriter.unsupported  s    !$)LTRUYKX	

 cD%=)KKu%!# 01 61#Qa.KK*C#67KK*$$VQ/0 KKu% *r7   c                H    | j                   j                  d|d| d       y )Nzreader.const(r!  z!, filtered out during compilationr
  r   r  s     r5   r  zInputWriter.const  s'    D85.OP	
r7   c                .   t        |t        j                        rZt        |j                  j
                        }|j                  j                  }| j                  j                  d|d|d|        y | j                  j                  d|d|        y )Nzreader.symint(z, expr=r!  )	r\  r   r*  rN   r  r  hintr
  r   )r2   r$  r  expr_strr1  s        r5   r  zInputWriter.symint  st    c5<<(388==)H88==DKKxwxl%PTvVWKKweD6BCr7   c                    |j                   }| j                  j                  d|j                  d|j                  d|        y )Nzreader.generator(r   r!  )r   r
  r   r   index)r2   r$  r+  r   s       r5   r  zInputWriter.generator
  s<    b0@dVL	
r7   c                F    | j                   j                  d|d|        y )Nzreader.opaque(r!  r/  )r2   r$  r  s      r5   r  zInputWriter.opaque  s#    ^,=+@dVLMr7   )r  r   r  rR   rO   rP   )rO   rS   )r  r   r  r  r  r  rO   rN   )r$  rN   r  r  rO   rP   )r$  rN   r+  r   rO   rP   r  )r$  rN   r  r   rO   rP   )r$  rN   r+  ztorch._C.GeneratorrO   rP   )r$  rN   r  rN   rO   rP   )rT   rU   rV   r6   r  r  r  r  r  r  r  r  rW   r7   r5   r  r    sf    DI 
;& BF)-#'# ?	#
 '# 
#J
@&(
D
Nr7   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+)r   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)rT   rU   rV   __doc__rW   r7   r5   TensorContainerr:  8  s    -r7   r<  rO   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 inrW   )r  s   r5   r  z=aot_graph_input_parser.<locals>.get_sym_int.<locals>.<lambda>C  s    vhYZ r7   )r   _checkr  )r  default_sym_shapesym_shapes_dicts   `r5   get_sym_intz+aot_graph_input_parser.<locals>.get_sym_int@  s;    o%F):$)FZ	
 ""6+<==r7   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   r   )
r)  stripr   r   r   r   randnzerosrI  mark_dynamic)r   r   resolved_shapedynamic_dimsr  dimr!  constructorro  r  r   rB  s             r5   
gen_tensorz*aot_graph_input_parser.<locals>.gen_tensorG  s    & 	4FAs))+Ccz$%%a(##A&"))#c(3	4 &+%<%<ekk%++.fE 	/AMM&&sA.	/
r7   ,r   r2   )r  rN   rO   r   )r   r  r   torch.dtyperO   r
   )torch.utils._dtype_abbrsr7  r   r9   valuesinspect	getsource__annotations__researchr   r#  r*   group	signaturer   finditersetattr)funcr   
sym_shapesr@  r7  r5  r>  	dtype_mapdtype_patternsourcetensor_assignment_regextensor_regexsym_shape_regexr<  r  rL  r   r   
annotationmatch	data_type	shape_strr   r   	container	attr_namer   rB  rA  s    ` `                       @@r5   aot_graph_input_parserrh    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   r  fnprofs     r5   wrapperz3profile_to_file.<locals>.decorator.<locals>.wrapper  s1    KKM4*6*s   + =)r   r   r  r   rO   r   )	functoolswraps)rn  rp  ro  s   ` r5   	decoratorz"profile_to_file.<locals>.decorator  s%    			 
	 r7   c            	         j                          t        j                  j                  t	        j
                  d  d  d             y )Nz!                Wrote profile to z+, view with:

                    snakeviz z

                )
dump_statssysstderrrF   r;   r<   )r3   ro  s   r5   save_itz profile_to_file.<locals>.save_it  sK    !

OO""* ,&Z (		
r7   )rn  r   rO   r   r  )cProfileProfiler(   r)   r+   
expanduseratexitregister)r3   rs  rx  ro  s   `  @r5   profile_to_filer~  {  sR     Dwwrww11(;<H	
 OOGr7   rQ   )r'  rR   rO   rN   )rU  rN   rO   rP   )r_  Sequence[Any]rO   	list[Any])FF)
r   r   r   r  rm  rR   rn  rR   rO   r   )F)r   r   r  r   r_  r  rm  rR   rs  rR   rt  rR   rO   rR   )r  r   rO   r   )r   rN  r  r   r  r  rO   &tuple[torch.fx.GraphModule, list[Any]])r  r   r  r  rO   r  )r   r   r_  r  r  zACallable[[torch.fx.GraphModule, list[Any]], torch.fx.GraphModule]rm  rR   rs  rR   rt  rR   rO   rR   )r   r  r   r  rO   ztorch._prims_common.StrideType)r  r   rO   zCallable[[T | None], T])r  NN)
rZ  z&Callable[[list[Tensor]], list[Tensor]]r   rN   r[  zdict[str, int] | Noner@  r  rO   zdict[str, Any])r3   rN   rO   zCallable[[T], T])lr;  
__future__r   r|  rj  ry  rq  r]   rQ  r  loggingr(   rT  r  rv  r[   r;   collectionsr   	importlibr   typingr   r   r   r	   r   torch._prims_common_prims_commonry  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   	getLoggerrT   rH   r   inductor_config	is_fbcoderQ  libfb.py.build_infolibfbr:   extra_importsr=   py
build_info	BuildInfoget_build_ruler.   r9   rG   r"   ra   r   r   rd   rh   cacher&  rA  rM  rO  rX  r|  rZ  rb  rq  r  r  r  r{  r  r  r  float32r  r   r  r  r  r  r  r  r  rh  r~  )r>   s   0r5   <module>r     s  $ #         	 	  
    # 4 4  # #  . @ . ; M  9 9 2, g!CL   89$$& 

J $$..==?GG	SWXJIITA!9!B?TUM 64 4n  	~ 	P Pf  6 7< 	@ 5: (@V	I 	
  	00
0 0 	0
 	0H 	7 77 7 "7 	7 7 7 
7t03=F+(11)21+1 	 ! S 	   
RV1V )V $	V/ "%--0 "<5<<#67 *1- )%0 #E*  Fe ehJN JN^ (,$(	d
0dd &d "	d
 dN#O! Us   J