
    VhR                        d 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mZmZ ddlZddlmZmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZ  ej@                  e!      Z" ed      Z#e#jI                         Z% G d	 d
e&      Z'	 	 d)dede(de(dee)e(ef      fdZ*d Z+dddddddddddddee   deejX                  jZ                     dee.e      dee)e(e(f      fdZ/dddddZ0dddddee)e(e(f      fdZ1d Z2d Z3d Z4d Z5	 d*d!eejX                  jZ                     fd"Z6d# Z7ddd$dddd%d d&dee)e(e(f      d'ee8e(f   fd(Z9y)+a  
Utilities for debugging and reproducing issues in Ahead of Time with Inductor (AOTI) compilation.

This file provides tools and utilities for:
- Generating minimal reproducible test cases (minification)
- Handling exported programs and graph modules
- Creating debug repros for AOTI compilation issues
- Supporting both accuracy testing and error reproduction
- Managing configuration and environment for repro cases

The main components include:
- Minification tools to reduce test cases while preserving errors
- Repro generation utilities for exported programs
- Error handling specific to AOTI compilation
- Command-line interface for running and managing repros
    N)import_module)AnyOptionalUnion)
_cuda_system_info_commentBuckTargetWriterextra_importsgenerate_config_stringgenerate_env_vars_stringhelper_for_dump_minifyInputReaderminifier_dirNNModuleToStringNopInputReader)ExportedProgram)tqdmztorch._inductor.configc                        e Zd Z fdZ xZS )AOTIMinifierErrorc                 V    d}| dt        |       }t        | 	  |       || _        y )NzRThis error is caused by a bug in the AOTI minifier, please report a bug to PyTorchz: )strsuper__init__original_exception)selfr   additional_messagefull_message	__class__s       H/home/dcms/DCMS/lib/python3.12/site-packages/torch/_dynamo/repro/aoti.pyr   zAOTIMinifierError.__init__9   s6    q,-R4F0G/HI&"4    )__name__
__module____qualname__r   __classcell__)r   s   @r   r   r   8   s    5 5r   r   exported_programcompiler_namecommandoptionsc           
         |dv sJ t         j                  j                  t               d      }t         j                  j	                  |      st        j
                  |d       |dk(  r>t        j                         }t        ||| |d|       t        |j                               S t        j                         }t         j                  j                  |d      }	 t        |d      5 }t        ||| ||d	d
       ddd       t        j                  d|       t        rt!        |      j#                          yy# 1 sw Y   @xY w# t$        $ r t        j                  d|       Y yw xY w)z
    If command is "minify":
        Dump exported_program to `debug_dir/minifier/minifier_launcher.py`, with minify command.
    If command is "run":
        Dump exported_program to `cwd/repro.py`, with run command.
    )minifyruncheckpointsTexist_okr)   )r$   save_dirr&   config_patchesrepro.pywr*   )r$   r/   r.   r&   module_in_commentNzWriting repro file to %sNo write permissions for %s)ospathjoinr   existsmakedirsioStringIOsave_graph_repro_epr   getvaluegetcwdopenlogwarninguse_buckr   writeOSError)	r$   r%   r&   r'   subdiroutcurdir	file_namefds	            r   dump_to_minifyrI   @   s5    ''''WW\\,.-8F77>>&!
FT*(kkm-"	
 &clln55GGLL4		Bi% 	#!%5#*#!&*	 KK2I> +113 	 	  	BKK5yA	Bs*   E )D;<=E ;E E E)(E)c                 B    d }t        j                  |       } ||      S )Nc                     | j                  d      }t        |      dk(  rd| z   S |j                  d      }t        t        |            D ](  }||   }|j	                         dk7  r	d|z   ||<   $d||<   * dj                  |      }|dz   |z   }|S )N
   z# r    )splitlenpoprangestripr6   )s_sfirstilines        r   _convert_to_commentz.get_module_string.<locals>._convert_to_comments   s    HHTNq6Q;"9as1v 	AQ4Dzz|r!d{!!	 IIaLDL1r   )r   convert)gmrY   module_strings      r   get_module_stringr]   r   s$     %,,R0M}--r   Fr*   )r$   r[   argsr/   stable_outputr.   r&   accuracy	check_strr2   strictr[   r^   r/   c                   ||t        d      ||t        d      ||t        d      |+|J |J t        j                  j                  |||      }n||j                         }t	        |      }| j                  |       | j                  t        ||||             |	d|v }	| j                  d       | j                  d       | j                  d	|	d
|d|d|
d	       y )Nz.One of exported_program and gm must be definedz2Only one of exported_program and gm can be definedz-If gm is defined, args should also be definedrb   r'   r_   r.   	_accuracyzif __name__ == '__main__':
z3    from torch._dynamo.repro.aoti import run_repro
zf    with torch.no_grad():
        run_repro(exported_program, config_patches=config_patches, accuracy=z
, command=z, save_dir=z, check_str=z)
)r   torchexportmoduler]   rB   (generate_compiler_repro_exported_program)rH   r%   r$   r[   r^   r/   r_   r.   r&   r`   ra   r2   rb   r\   s                 r   r;   r;      s/   ( BJ PQQ# TUU	~$, OPP~~ <<..r4.G	$$& &b)MHH] HH0"'		
 -/HH+,HHCDHHWW_Vbblmtlw x<|I=	=r   )r/   r`   rb   c                p   t         j                  j                  t               d      }t         j                  j	                  |      st        j
                  |d       t         j                  j                  |t        | j                  j                         d      }t        j                  dt        | j                  j                        |       t        |d      5 }t        ||| t        |      |||d|	       d d d        t        j                         }	t         j                  j                  |	d      }
	 t        j                   ||
       t        j                  d	|
       t"        rt%        |      j'                          y y # 1 sw Y   xY w# t(        $ r t        j                  d
|
       Y y w xY w)Nr+   Tr,   z.pyz&Writing checkpoint with %s nodes to %sr1   )r[   r^   r/   r.   r`   r2   rb   r0   z(Copying repro file for convenience to %sr3   )r4   r5   r6   r   r7   r8   rP   graphnodesr?   r@   r>   r;   tupler=   shutilcopyfilerA   r   rB   rC   )r[   r^   r%   r/   r`   rb   rD   rG   rH   rF   
repro_paths              r   dump_compiler_graph_staterr      sF    WW\\,.-8F77>>&!
FT*VBHHNN(;'<C%@AIKK0#bhhnn2Ey 
i	 
t)"
	

 YY[Ffj1J?	:.>
KY'--/ #
 
&  ?1:>?s   F:AF FF54F5re   c          	      n   t        j                  dt        |       dt        |       dt         d      }|s|dt
        j                  j                   dz  }t        t
        j                  d      r!|dt
        j                  j                   dz  }t        t
        j                  d	      r!|d
t
        j                  j                   dz  }|t               z  }t        j                  j                  |d      }t
        j                  j!                  | |       |d| dz  }|dz  }|d| dz  }|S )NrL   )r_   z5
import torch
import torch._inductor.inductor_prims

z!

isolate_fails_code_str = None

z


        z# torch version: cudaz# torch cuda version: git_versionz# torch git version: z


zexported_program.pt2z&exported_program = torch.export.load('z')
z # print(exported_program.graph)
zconfig_patches=)textwrapdedentr   r
   r	   rg   version__version__hasattrrt   ru   r   r4   r5   r6   rh   save)r$   r'   r_   r.   	model_strep_paths         r   rj   rj      s8    6 7 8 m4 5 6  		I ()B)B(C2FF	5==&)1%--2D2D1ERHHI5==-001J1J0K6RRI.00	ggll8%;<G	LL&09'$GGI44I?7)2..Ir   c                    t        | d      st        j                  d       n/| j                  dkD  r t        j                  d| j                         t	               } | |       t        d|j                        5 }t        ||      } | |       |j                  }d d d        t        |      S # 1 sw Y   t              S xY w)N_versionzzload_args does not have a _version attribute, please file a bug to PyTorch and describe how you generate this repro scriptr   zload_args is version %s, but this version of PyTorch only supports version 0.  We will try to run it anyway but there may be an incompatibility; if so, try upgrading your version of PyTorch.zLoading inputs)desctotal)r.   pbar)
rz   r?   r@   r   r   r   r   r   r^   rn   )	load_argsr.   
nop_readerr   input_readerr^   s         r   repro_load_argsr     s    9j)>	

 !KK@ ""	  !Jj	#:+;+;	< !"H4@,  !
 ;!
 ;s   ;"B00Cc                     dt         j                  j                  _        |j	                         }|j
                  \  }}|||fS )NT)rg   	_inductorconfiggenerate_intermediate_hooksri   example_inputs)r'   r$   modr^   kwargss        r   repro_commonr   ,  s>    9=EOO6

!
!
#C#22LD&fr   c                 ,    t        | |      \  }}}|||fS N)r   )r'   r$   r/   r   r^   r   s         r   repro_get_argsr   3  s#    $W.>?Cvfr   c                     ddl m} t        | |      \  }}}ddlm}  ||||d| j
                  |       d}|D ]-  }	t        |	t        j                        s|	j                  s+d} n |r |        y y )Nr   _aoti_compile_and_package_innersynchronizeTload_and_runcheck_accuracyinductor_configsF)
torch._inductorr   r   
torch.cudar   r`   
isinstancerg   Tensoris_cuda)
r'   r$   r/   r   r[   r^   r   r   	need_syncargs
             r   	repro_runr   8  s}    ?#G-=>Bf&#
''' I c5<<(S[[I
  r   Treturnc                    ddl m}m} 	 t        j                  j	                  | ||      }|j                         } | S # t        $ rx}|rY d }~y t        ||      r|j                  |j                  k(  rY d }~y t        |t              r&d}t        j                  |t        |            Y d }~y t        |      |d }~ww xY w)Nr   )	UserErrorUserErrorTyperd   z/Found .* in output, which is not a known type\.)torch._dynamo.excr   r   rg   rh   ri   	Exceptionr   
error_typeINVALID_OUTPUTRuntimeErrorresearchr   r   )	r[   tuple_inputsrb   skip_export_errorr   r   epepatterns	            r   export_for_aoti_minifierr   S  s     ;*\\  \& AYY[	 *a#8T8T(Ta&HGyy#a&)5")*s'   3> 	B?B:%B:81B:.B::B?c                 j    ddl m} ddlm ddlm} t         |      \  }}} |||||      \  }d}	 j                  dv sJ  j                  dk(   j                  dd	l	m
 d
|D ]-  }
t        |
t        j                        s|
j                  s+d n d fd	} |||t        j                   | j"                        t        j                   t$        |	| j&                         j(                   j*                   j,                   j.                   j0                  	       y )Nr   )minifierr   )_aoti_flatten_inputs)r'   aot_inductor)dynamopythonr   r   FTc                 "   t        |      }t        | |
	      } | yt        | t        j                  j
                        sJ 	  | |dj                         r         y# t        $ r}||t        |      vrY d }~yY d }~yd }~ww xY w)N)rb   r   FTr   )	rn   r   r   rg   fxGraphModuler`   r   repr)r[   flat_example_inputsra   r   r   r   r   r   r'   r   rb   r   s        r   module_failsz"repro_minify.<locals>.module_fails  s    01%V?P
 :"ehh22333	+!&//!1  	$$q')A	s    A' '	B0B		B)ra   )r%   r/   r`   rb   )r   
dump_stater.   offload_to_diskskip_offloadskip_sanitymax_granularityr   )functorch.compiler   r   r   torch._inductor.compile_fxr   r   minifier_export_moder   r   r   r   rg   r   r   	functoolspartialra   rr   r`   r.   r   skip_saving_eager_intermediatesr   r   )r'   r$   r/   r   r   r   r^   r   r   r%   r   r   r   r   r   r   rb   r   s   `           @@@@@@r   repro_minifyr   w  s*   *??$W.>?Cv -AT6>-)) #M''+????))X5F11&I c5<<(S[[I
 < &&|w?P?PQ$$%')%%
 !!//<<''//r   rN   r   )r/   r&   r`   r.   tracing_modera   r   r   r`   c                "   |	D ]  }
t         j                  d|
        du rdndu rdt        j                  d| d| dd	|d
d|dt        j                        }fd}|j                  ddd      }|j                  dd      } ||       |j                  dd      } ||       |j                  dd      } ||       |j                  ddd       |j                  ddd       |j                  ddd        |j                  d!t        d d"#       |j                  d$t        |d%#       |j                  d&t        |d'#       |j                  d(t        |d)#       |j                  d*      } ||       |j                  d$t        |d%#       d }t        t        j                        d+k  r|gt        j                  d+d  }|j                  |      }t        t         t"        d,} ||j$                     || |-      S ).NzPUnrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorchTr`   FrN   zAn AOTI repro script, typically triggering a bug in PyTorch AOTInductor.
When run with no arguments, this script defaults to running 'z8'.
Extra flags may be available; to find out more, try 'zr --help'.
There are also alternate subcommands available, see below.

default settings on this script:
  accuracy=z
  tracing_mode=z
  save_dir=z
  check_str=rL   )descriptionformatter_classc                    | j                         }|j                  ddddd       |j                  dddd	       |j                  d
dddd       | j                  dt        dd       | j                  dddd d       y )Nz--no-accuracyr`   store_constrN   z>do not test accuracy, just run the module and see if it errors)destactionconstdefaulthelpz
--accuracya  test if the RMSE between the compiled module and the fp64 reference is greater
than eager and the fp64 reference. This is usually more reliable than the
standard allclose test, as we expect numeric differences from compiling, often
improving accuracy over eager.  RMSE test allows for compiled module to
diverge greatly from eager, as long as this divergence moves it closer to the
'true' mathematical value of the network.  Caveats: (1) double precision can
still suffer from rounding error, so it is not a perfect reference (see for
example 'Herbie: Automatically Improving Floating Point Accuracy') for
approaches that detect the necessary working precision and compute it in
arbitrary precision floating point; unfortunately, this is not practical for
tensor computation; (2) if there are not enough samples in the output being
compared, we may get unlucky and have an unlucky greater RMSE than eager; this
could be overcome by applying a more rigorous statistical test at some
p-value, which we leave for future work.
)r   r   r   r   z--strict-accuracystrict_accuracya  by default, when doing accuracy minification we will reject reductions which
change the divergence from a floating point divergence to a integral/boolean
divergence.  This is because some operations like ReLU involve temporarily
sharp boundaries that smooth out again afterwards; without requiring
divergence on floating point, the minifier will often fixate on divergent
boolean tensor even though this is not the true source of the divergence.
However, rejecting these reductions makes it more difficult for the minifier
to make process.  Using this option will let the minifier progress for ALL
divergences--you just might not end up with a useful repro in the end.z
--save-dirDIRz!directory where saved inputs live)typer   metavarr   z--no-save-dirr.   z(don't use any directory for saved inputs)r   r   r   r   )add_mutually_exclusive_groupadd_argumentr   )parseraccuracy_groupr`   r.   s     r   common_flagszrun_repro.<locals>.common_flags  s    <<>## Q 	$ 	
 	##  	$ 	
, 	## #	J 	$ 	
$ 	4 	 	
 	 ; 	 	
r   r&   z{run,minify})r   r   requiredr*   zjust run the repro)r   r)   zrun the minifier on the reproget_argszget the argsz!--skip-saving-eager-intermediates
store_truez+skip saving eager intermediates on --minify)r   r   z--offload-to-diskzYduring minification, offload delta debugging intermediates to disk.  Use if you're OOMingz--skip-sanityz@skip sanity check at beginning of minification on original graphz--max-granularityz;start at this granularity and work down; must be power of 2)r   r   r   z--check-strzBrequire minified program to fail with error containing this stringz--minifier-export-modezThe export mode used in minifier, either dynamo or python.`dynamo` corresponds to strict=True, and `python` corresponds to strict=False.z--skip-export-errorz1Skip intermediate graphs that cannot be exported.zminifier-queryrM   )r)   r*   r   )r/   )r?   r@   argparseArgumentParserRawTextHelpFormatteradd_subparsers
add_parserr   intr   boolrP   sysargv
parse_argsr   r   r   r&   )r$   r/   r&   r`   r.   r   ra   r   r   more_kwargskr   r   
subparsers
parser_runparser_minifyparser_get_argsparser_minifier_queryr^   r'   COMMAND_FNSs      ``                r   	run_repror     s     
^	

 4	U	$$>>EY G66=Y ? + / + ,  !55F ?
B && ' J &&! ' J ))6 * M  ++J^+LO!+:  
 h  
 O  
 J	   Q	    $]   !@	   '11 &'&&Q	 '  D
388}'#((12,'%G"K
 (;w'!. r   )r)   N)FT):__doc__r   r   r9   loggingr4   r   ro   r   rv   	importlibr   typingr   r   r   rg   torch._dynamo.debug_utilsr   r   r	   r
   r   r   r   r   r   r   torch.exportr   	torch.hubr   	getLoggerr    r?   inductor_config	is_fbcoderA   r   r   r   dictrI   r]   nnModulern   r;   rr   rj   r   r   r   r   r   r   r   r    r   r   <module>r     s  "   	  	 	  
  # ' '    )  g!   89$$&5	 5 (,	/B%/B/B /B d38n%	/Bd.0 37$(!%/37 /	7
 	!7 5:
7 T#s(^,7~ $?^ )-# d38n%#L4
8 7;!ehhoo!HGZ 04!#!| T#s(^,|
 D#I|r   