
    Vh              	          U 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
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mZmZmZmZmZ d dlZd dlmZ d dlm Z  d d	l!m"Z"m#Z# d d
l$m%Z%  ejL                  e'      Z(de)fdZ*de)fdZ+de)fdZ, G d de      Z- ed      Z. G d d      Z/de)fdZ0 e0       rddgZ1ndgZ1 G d de      Z2e1dddddiddiddii i di i i i ddidgd d!gd d!g e%       gd"Z3e4e5e6e   f   e7d#<   ee5e8e   egef   Z9 G d$ d%e      Z: G d& d'      Z; e;       Z<e=e5d(f   Z> G d) d*      Z?e4e5ef   Z@eg e)f   ZAeg eAf   ZBi d+dd,e<d-e<d.e<d/e<d0e<d1e<d2e<d3e<d4e<d5e<d6e<d7e<d8e<d9e<d:e<d;e<i d<e<d=e<d>e<d?e<d@e<dAe<dBe<dCe<dDe<dEe<dFe<dGe<dHe<dIe<dJe<dKe<dLe<e<e<e<e<e<e<e<dMe<e<e<e<dNdOZCe4e5e@f   e7dP<    G dQ dR      ZD	 dWdSeEdTe?dUe5ddfdVZFy)X    N)KeysViewSequence)Enum)partialwraps)	FrameType)AnyCallableget_args
get_originLiteralOptionalTypeVarUnion)CustomGraphPass)BaseSchedulerNode)_ConfigEntryConfigModule)
OrderedSetreturnc                 (    | |u xs t        |       |u S )aN  
    Determines if type_hint is comp_type. There are some type annotations that this doesn't work for.
    I think it's because some Type annotations are Type Objects and some are Special Forms, but not sure.
    There's definite room for improvement to make this more general for someone who deeply understands
    Python types.
    )r   )	type_hint	comp_types     F/home/dcms/DCMS/lib/python3.12/site-packages/torch/_inductor/fuzzer.pyis_typer   #   s     	!GZ	%:i%GG    c                 Z    t        |       }|t        u rt        |       }t        d      |v S y)z"
    Special case of is_type.
    NF)r   r   r   type)r   originargss      r   is_optional_typer!   -   s1     	"F	"DzT!!r   c                      | j                   dk(  S )z"
    Special Case of is_type.
    r
   )__name__)r   s    r   is_callable_typer$   :   s     ++r   c                   n    e Zd ZdZdej
                  j                  j                  ddfdZde	e
   fdZy)	DummyPassz1
    A Dummy pass to be used by ConfigFuzzer
    graphr   Nc                      y N )selfr'   s     r   __call__zDummyPass.__call__F       r   c                      y r)   r*   r+   s    r   uuidzDummyPass.uuidI   r-   r   )r#   
__module____qualname____doc__torchfxr'   Graphr,   r   r	   r0   r*   r   r   r&   r&   A   s8    ehhnn22 t hsm r   r&   Tc                   N   e Zd ZU dZej                    e       ej                  j                  j                  j                   ej                  j                  j                         e
j                    e
d      iZeeef   ed<   edee   dee   fd       Zedee   defd       Zy)TypeExemplarszF
    This class returns examples of a Type, given its class name.
    NTYPE_EXEMPLARStr   c                 V    t         j                  j                  | j                  d      S )z/
        Return an example of a class.
        N)r9   r:   getr#   r;   s    r   examplezTypeExemplars.example[   s!    
 ++//

DAAr   c                 :    | j                   t        j                  v S r)   )r#   r9   r:   r>   s    r   containszTypeExemplars.containsb   s    zz]9999r   )r#   r1   r2   r3   r   r&   r4   r5   r'   r6   r   r:   dictstrr	   __annotations__staticmethodr   r7   r   r?   boolrA   r*   r   r   r9   r9   P   s    
 	  )+%%uxx~~';';'=""$5d$;&NDcN  B47 Bx{ B B :DG : : :r   r9   c                  N    	 t        j                  d       y# t        $ r Y yw xY w)z"checks if we have halide availablehalideTF)	importlibimport_moduleModuleNotFoundErrorr*   r   r   check_halide_importrL   g   s*    ) s    	$$tritonrH   c                   4    e Zd ZdZdZdZdZdZdZdZ	de
fd	Zy
)Statusz8
    The Status return value enum for Config Fuzzer
    skippedpassedfailed_compilefailed_run_compile_exceptionfailed_run_eager_exceptionfailed_run_returnr   c                     | t         j                  k(  xs= | t         j                  k(  xs( | t         j                  k(  xs | t         j                  k(  S )zU
        Convenience method to check whether these status represent failure.
        )rO   FAILED_COMPILEFAILED_RUN_EAGER_EXCEPTIONFAILED_RUN_COMPILE_EXCEPTIONFAILED_RUN_RETURNr/   s    r   failingzStatus.failing   sR    
 F))) 0v8880v:::0 v///		
r   N)r#   r1   r2   r3   SKIPPEDPASSEDrW   rY   rX   rZ   rF   r[   r*   r   r   rO   rO   v   s8    
 GF%N#A != ,	
 	
r   rO   T)shape_broadcast_batch_linearfuse_nodes_with_same_usersfuse_nodes_with_same_parentF)batch_linear_post_gradbatch_aten_mulbatch_aten_sigmoidbatch_aten_addnormalization_aten_passunbind_stack_aten_passrequire_fbgemm)rd   rb   batch_aten_subbatch_aten_divgroup_linearpad_mmmixed_mm)cuda_backendpost_grad_fusion_optionsautoheuristic_collectautoheuristic_usetraceable_tensor_subclassesTYPE_OVERRIDESc                   ^    e Zd ZdZdZdZededede	e
   de
de
f
d	       Zed
d defd       Zy)SamplingMethoda(  
    This class handles the process of assigning concrete values to type annotations. So a type annotation of
    ```python
    foo: Optional[int] = None
    ```
    Will be assigned an int if the dispatch function gets TOGGLE, or a 50/50 split between an int and None if it gets
    RANDOM.
    TOGGLERANDOMrandom_sample
field_namer   defaultr   c                 "    t         v rt        j                  t                  S |t        k(  r rt        j                  ddg      S | S |t        k(  rt        j
                  dd      S |t        k(  rt        j                  dd      S |t        k(  rit        j                  t        j                  z   t        j                  z   dj                  fdt        t        j
                  dd            D              S t        |t               rt#        |d	t%        |      rt'        |d         gnt'        d
      g      d   }t%        |      dkD  r|d   nd
}t        t        j
                  dd            D cg c]  }t(        j+                   ||       c}S t        |t,              rt!        |      }t#        |d	t%        |      rt'        |d         gnt'        d
      g      d   }t%        |      dkD  r|d   nd
}t        t        j
                  dd            D ch c]  }t(        j+                   ||       c}S t        |t.              rt!        |      }t#        |d	t%        |      rt'        |d         gnt'        d
      g      d   }t%        |      dkD  r|d   nd
}t/        t        t        j
                  dd            D cg c]  }t(        j+                   ||       c}      S t        |t0              rt#        |d	|;t%        |      r0t3        t&        t5        t7        |j9                                           nt'        d
      t'        d
      f      \  }}	|Bt%        |j9                               dkD  r&t5        t7        |j9                                     \  }
}nd\  }
}t        t        j
                  dd            D ci c]1  }t(        j+                   ||
      t(        j+                   |	|      3 c}S t        |t:              r	 t%        |j<                        dkD  sJ 	  r t        j                  |j<                        }n<t        j                  |j<                  D cg c]  }|t'        |      k7  s| c}      }	  |       }t(        j+                   ||      S t        |tD              rIt#        |d	tE        t3        t&        |                  }tG        ||      }tE        t3         fd|            S t        |tH              rZ	  rt        j                  |j<                        S |j<                  D cg c]
  }||k7  s	| }}|rt        j                  |      S |S tK        |      rZ	 |j<                  d   } r-t        j                  d
t(        j+                   ||      g      S |t(        j+                   |d
      S y
|t'        d
      u ry
tM        |      r1	 t!        |j<                        d   tO        d        fd       }|S tP        jS                  |      rtP        jU                  |      S |tV        k(  r	|dk(  sdS dS tA        d| d      c c}w c c}w c c}w c c}w # t>        $ r}tA        d      |d
}~ww xY wc c}w # tB        $ r d
}Y w xY wc c}w # t>        $ r}tA        d      |d
}~ww xY w# t>        $ r}tA        d      |d
}~ww xY w# t>        $ r}tA        d      |d
}~ww xY w)zC
        Generates a value of a type based on the setting.
        TFr      c              3   H   K   | ]  }t        j                          y wr)   )randomchoice).0_
characterss     r   	<genexpr>z:SamplingMethod._generate_value_for_type.<locals>.<genexpr>   s      ./j)s   "      __args__N   )NNzUnion type with no argsc                 @    t         j                  | d   | d         S )Nr   r   rt   _generate_value_for_type)xrx   rw   s    r   <lambda>z9SamplingMethod._generate_value_for_type.<locals>.<lambda>7  s#    nEE%z1Q41 r   zLiteral type with no argszOptional type with no argszCallable type with no argsc                       y r)   r*   )r    kwargss     r   r   z9SamplingMethod._generate_value_for_type.<locals>.<lambda>f  s    r   c                  4    t         j                  d       S r)   r   )r    r   rx   rw   return_types     r   dummy_functionz?SamplingMethod._generate_value_for_type.<locals>.dummy_functionf  s    %>>!:{D r      zUnable to process type z. PRs welcome :)),rr   r~   r   rF   intrandintfloatuniformrC   stringascii_lettersdigitspunctuationjoinranger   listgetattrlenr   rt   r   setr   rB   mapnextiteritemsr   r   AttributeError
ValueError	Exceptiontuplezipr   r!   r$   r   r9   rA   r?   r	   )rw   rx   r   ry   	elem_typenew_defaultr   	indexablekey_type
value_typedefault_keydefault_valerrnew_typer;   r    zippedchoicesr   r   r   s   ``                 @@r   r   z'SamplingMethod._generate_value_for_type   s    '==
!;<<3@6==$/Q'kQ# >>!T**%>>!T**#--=@R@RRJ77 3829N3O   Y%&)'lgaj!"d 	I
 ),Gq(8'!*dK
 v~~a34	  77!:y+  Y$WI(+Gil#$4:, 	I
 +.g,*:)A,K
 v~~a34	  77!:y+  Y
+WI(+Gil#$4:, 	I
 +.g,*:)A,K
 #6>>!Q#78	  #;;%z9k  Y%#*'CL D$tGMMO4564j$t*-$ Hj "s7==?';a'?+/W]]_0E+F([+5([ v~~a34  77!:x!::!:z;  Y&E9--.222 !==););<!== ) 2 2I1a4=6HQI#&j
 "::z8[  Y&c$()D
 w'F 	  Y(
G !==););<<*3*<*<MQWqMGM%}}W55& i(H%..q1	 }}&??):y'  ?)BB%z9d   $t*$i(H"9#5#56r: /0 1
 "!##I. ((33##qL1/a/6ykAQRSSc& " E !:;DE J  #"#6 N
 " G !<=3FG
 " H !=>CGH. " H !=>CGHs   8Y-Y2Y76Y<Z 1ZZZ#  Z: ;Z: 	
Z5Z5Z: 1Z: ?[ 2[4 	Z
ZZ#Z21Z25Z: :	[[[	[1 [,,[14	\=\		\smc                     | t         j                  k(  rt        t         j                  d      S | t         j                  k(  rt        t         j                  d      S t        d|        )zr
        Returns a function that will generate values from a type, based on the SamplingMethod passed in.
        TFzmalformed sampling method: )rt   rv   r   r   ru   r   )r   s    r   dispatchzSamplingMethod.dispatcht  sY    
 &&&>BBDII>(((>BBEJJ:2$?@@r   N)r#   r1   r2   r3   ru   rv   rE   rF   rC   r   r	   r   SamplingTyper   r*   r   r   rt   rt      s     FFoToT),oT9=coTMPoT	oT oTb 	A% 	A, 	A 	Ar   rt   c                       e Zd ZdZy)Defaultzv
    Singleton default object that will cause the ConfigFuzzer to always use the default value set in the config.
    N)r#   r1   r2   r3   r*   r   r   r   r     s    r   r   .c                       e Zd ZU dZeeef   ed<   defdZ	ddZ
defdZdefdZd	ed
eddfdZd	edee   fdZdee   fdZy)
ResultTypez`
    The mapping of the combo strings to the result status after running the config fuzzer.
    _valsr   c                 "    d| j                    dS )NzResultType[]r   r/   s    r   __repr__zResultType.__repr__  s    TZZL**r   Nc                     i | _         y r)   r   r/   s    r   __init__zResultType.__init__  s	    
r   c                 ,    t        | j                        S r)   )r   r   r/   s    r   __len__zResultType.__len__  s    4::r   c                     t        | j                        }| j                  j                         D ]  }|t        j                  k(  s|dz  } |S )zI
        Returns how many combos actually ran (weren't skipped).
        r   )r   r   valuesrO   r\   )r+   retstatuss      r   num_ranzResultType.num_ran  sI     $**ojj'') 	F'q	 
r   combor   c                 J    t        t        |            }|| j                  |<   y r)   )r   sortedr   )r+   r   r   s      r   r   zResultType.set  s    fUm$"

5r   c                 b    t        t        |            }| j                  j                  |d       S r)   )r   r   r   r=   )r+   r   s     r   lookupzResultType.lookup  s%    fUm$zz~~eT**r   c                 6    | j                   j                         S r)   )r   keysr/   s    r   r   zResultType.keys  s    zz  r   r   N)r#   r1   r2   r3   rB   	ComboTyperO   rD   rC   r   r   r   r   r   r   r   r   r   r   r*   r   r   r   r     s     	6!""+# +  # #F #t #+I +(6*: +!hy) !r   r   force_disable_cacheszcpp.cxxTYPE_CHECKINGmax_autotune_pointwisemax_autotune_gemmmax_autotune_gemm_backendsmax_autotune_conv_backendsmax_autotune_gemm_search_space+max_autotune_subproc_result_timeout_seconds-max_autotune_subproc_graceful_timeout_seconds.max_autotune_subproc_terminate_timeout_secondszaot_inductor.presetsz	cuda.archzcuda.versionzcuda.cutlass_dirzcuda.cuda_cxxz	rocm.archzrocm.ck_supported_archzrocm.ck_dirzrocm.rocm_home"check_stack_no_cycles_TESTING_ONLYsleep_sec_TESTING_ONLYz#triton.inject_relu_bug_TESTING_ONLY reorder_for_compute_comm_overlapenabled_metric_tablesztriton.debug_sync_graphztriton.debug_sync_kernelprofile_bandwidth_regexdisable_cpp_codegenztrace.save_real_tensorspre_grad_fusion_optionsexternal_matmulz'test_configs.autotune_choice_name_regexz'test_configs.autotune_choice_desc_regex)z'cpp.enable_floating_point_contract_flagpost_grad_custom_pre_passpost_grad_custom_post_pass'reorder_for_compute_comm_overlap_passesjoint_custom_post_passjoint_custom_pre_passpre_grad_custom_pass)rq   !compiled_autograd_kwargs_overridefail_on_recompile_limit_hitsuppress_errors)ztorch._inductor.configztorch._dynamo.configMODULE_DEFAULTSc                      e Zd ZU dZeed<   eed<   dej                  dfde	de
dedee   d	ed
efdZdefdZdededdfdZd,dZdefdZdee   defdZdededdfdZdedefdZdededefdZd-dededefdZd.deddfd Zd.deddfd!Zd"ed#ee   ddfd$Z dededefd%Z!d/d&ed'e"de#e   fd(Z$ded)edee   fd*Z%ded)e#e&eef      dee   fd+Z'y)0ConfigFuzzera  
    This tool makes it easy to search through config state-space with a minimal reproduction or test, either for
      debugging or just bug hunting.
    It has two entry points:
     - bisect, which randomly flips configs and tries to find the minimal reproduction upon failure.
     - fuzz_n_tuple, which tries every combination of n configs. This grows quickly as a function of n, so beware.
    bisect is recommended, but fuzz_n_tuple can give you peace of mind that a new config will compose with
      every other config.

    The main interface is a function factory that will return Callables to be torch.compiled. This function factory
      should return a test function when it's called. Said test function returns a boolean, which determines whether
      the ConfigFuzzer considers it a successful run or not. Throwing an exception from within the function will be
      considered a failure as well.

    # Example usage:

    ```python
    import torch._inductor.config as cfg


    def create_simple_test_model_gpu() -> FactoryOutputType:
        batch_size = 32
        seq_length = 50
        hidden_size = 768

        def test_fn() -> bool:
            inp = torch.randn(batch_size, seq_length, hidden_size, device="cuda")
            weight = torch.randn(hidden_size, hidden_size, device="cuda")
            matmul_output = inp @ weight
            final_output = torch.nn.LayerNorm(hidden_size, device="cuda")(matmul_output)
            return True

        return test_fn


    fuzzer = ConfigFuzzer(cfg, create_simple_test_model_gpu, seed=2)

    # Test every pair of configs:
    results = fuzzer.fuzz_n_tuple(n, max_combinations=10000000)

    visualize_results(n, results)

    # Test random configs with bisection:
    ret = fuzzer.bisect(num_attempts=10)

    # reproduce a failing config
    fuzzer.reproduce(
        [{"triton.autotune_pointwise": ..., "coordinate_descent_tuning": ...}]
    )
    ```

    The list of known failures on inductor config are:
    cpp_wrapper, triton_debug_sync_graph
    cpp_wrapper, triton_debug_sync_kernel
    cpp_wrapper, disable_cpp_codegen
    combo_kernels, benchmark_combo_kernel, profile_bandwidth, profile_bandwidth_regex
    trace.enabled, trace.save_real_tensors
    samplery   Ni  config_moduletest_model_fn_factoryseedr   test_timeoutc                    t         j                  dk  rt        j                  d       y|| _        || _        i | _        || _        || _        | j                  j                  | _
        t        j                  |      | _        |J| j                  j                  t        v r#t        | j                  j                     | _        yt#        d      || _        y)a  
        Args:
            config_module: The module containing the configs to fuzz
            test_model_fn_factory: Function that returns a test model, which runs and returns True if successful, or
              the outputs if they should be compared with eager
            seed: Randomness seed.
            default: Default values for the config. Inductor has preset based on know failures.
            sm: How type value samples are generated, default TOGGLE.
            test_timeout: max time a test can take.
        )r   
   z$Only python 3.10 and later supportedNz"No default passed to ConfigFuzzer.)sysversion_infologerrorr   r   detailed_resultsr   r   _configfieldsrt   r   r   r#   r   ry   r   )r+   r   r   r   ry   r   r   s          r   r   zConfigFuzzer.__init__<  s    & g%II<=	(AC*%:"/3/A/A/I/I$--b1?!!**o=.t/A/A/J/JK !EFF"DLr   r   c           	      p    d| j                    d| j                   d| j                   d| j                   d	S )NzConfigFuzzer(config_module=z, test_model_fn_factor=z, seed=z
, default=))r   r   r   ry   r/   s    r   r   zConfigFuzzer.__repr__b  sH    )$*<*<)= >$$($>$>#?wtyykQ[\`\h\h[iijl	
r   rx   valuec                 2    t        | j                  ||       y)z!Set a config value in the module.N)setattrr   )r+   rx   r  s      r   _set_configzConfigFuzzer._set_configh  s    ""J6r   c                     | j                   j                         D ]!  \  }}| j                  ||j                         # y)z*Reset all configs to their default values.N)r   r   r  ry   )r+   rx   	field_objs      r   _reset_configszConfigFuzzer._reset_configsl  s9    %)[[%6%6%8 	<!J	Z):):;	<r   c                     | j                   j                         D ci c]*  \  }}||t        k7  r|n| j                  |   j                   , }}}|S c c}}w )z%creates a new config from the default)ry   r   DEFAULTr   )r+   namevalr   s       r   
new_configzConfigFuzzer.new_configq  sZ     "\\//1
c #T[[->-F-FF
 
 
	
s   /Aconfigsc                 L    t               }|D ]  }| j                  ||        |S )z#entrypoint to reproduce any failurer   _reproduce_single_helper)r+   r  resultsconfs       r   	reproducezConfigFuzzer.reproducey  s-    , 	9D))$8	9r   r  r  c                     t        d|        | j                         }|j                  |       | j                  ||       t        d| d|j	                  t        |j                                             y )NzStarting repro of z
Status of z:
)printr  updatetest_configr   r   r   )r+   r  r  r  s       r   r  z%ConfigFuzzer._reproduce_single_helper  sf    "4&)*__&
$*-
4&GNN53E$F#GHIr   configc                 >    t               }| j                  ||       |S r)   r  )r+   r  r  s      r   reproduce_singlezConfigFuzzer.reproduce_single  s    ,%%fg6r   r   c                    t        |       |j                  |      x}r|S | j                         }d}|D ]V  }||v rd}|j                  d      rd}| j                  |   }| j                  ||j                  |j                        }|||<   X |r0|j                  |t        j                         t        j                  S | j                  ||      S )NFTr   )r  r   r  
startswithr   r   r   ry   r   rO   r\   r  )	r+   r  r   str  skiprx   fieldr  s	            r   _fuzz_helperzConfigFuzzer._fuzz_helper  s    e&&2&I" 	'JV#$$S)KK
+EKK
E,<,<emmLE!&F:	' KKv~~.>>!00r   nmax_combinationsc                 T   t               }t        d| d| j                          t        j                  | j                         t	        j
                  | j                  |      D ]@  }| j                  ||      }|t        j                  k7  s)|dz  }|dk  s4t        d        |S  |S )z
        Test every combination of n configs.

        returns a dict of this shape: {(config-1, config-2... config-n): status}
        z	Starting z-tuple testing with seed r   r   z"Reached maximum combinations limit)
r   r  r   r~   	itertoolscombinationsr   r"  rO   r\   )r+   r#  r$  r  r   r  s         r   fuzz_n_tuplezConfigFuzzer.fuzz_n_tuple  s     ,	!5dii[ABDII++DKK; 	E""7E2BV^^# A% #q(>?	 r   filenamec                     t        |d      5 }t        j                  | j                  | j                  d|       ddd       y# 1 sw Y   yxY w)z'Save the current fuzzer state to a filewb)r  r   N)openpickledumpr  r   )r+   r)  fs      r   
save_statezConfigFuzzer.save_state  sD    (D! 	QKK LLd>S>STVW	 	 	s   .AAc                     t        |d      5 }t        j                  |      }|d   | _        |j	                  di       | _        ddd       y# 1 sw Y   yxY w)zLoad fuzzer state from a filerbr  r   N)r,  r-  loadr  r=   r   )r+   r)  r/  states       r   
load_statezConfigFuzzer.load_state  sT    (D! 	FQKKNE +DL$)II.@"$ED!	F 	F 	Fs   7AAsignumframec                     t        d      )NzTest execution timed out)TimeoutError)r+   r6  r7  s      r   timeout_handlerzConfigFuzzer.timeout_handler  s    566r   c           
          t        j                   t         j                   j                        t        j                   j                         t        d        t        j                               j                        x}r&t        j                   t         j                         |S dfddt        dt        t        t        f   ffddt        dt        d	t        dt        t           dt        f
 fd
}t         j"                  j%                           j'                          j)                         D ]  \  }} j+                  ||         j-                         }	  |        	  j-                         }	t!        j0                  |	d      }
	  |
       }|s |dt        j6                  dd      S  |dt        j8                  dd      S # t        $ r#} |dt        j.                  d|      cY d}~S d}~ww xY w# t        $ r#} |dt        j2                  d|      cY d}~S d}~ww xY w# t        $ r#} |dt        j4                  d|      cY d}~S d}~ww xY w)zZ
        Tests a config by calling the function produced by the factory function.
        zTesting config r   Nc                  V    j                         D ]  \  } }t        |  d|         y )Nz = )r   r  )r!  r  r  s     r   print_configz.ConfigFuzzer.test_config.<locals>.print_config  s/     & ,us5'*+,r   excc                 b    t        |       t        j                         j                         dS )N)	exception	tracebackr  )rC   rA  
format_exccopy)r>  r  s    r   get_error_infoz0ConfigFuzzer.test_config.<locals>.get_error_info  s)     X&113 ++- r   messagereturn_statusprint_tracebackc                     t        j                   t         j                         t        |  d                |r |      	j                  <   |rt	        j
                          j                  |       |S )Nz with config combination:)signalSIGALRMr  r   rA  	print_excr   )
rE  rF  rG  r>  config_tuplerD  original_handlerr=  r  r+   s
       r   handle_returnz/ConfigFuzzer.test_config.<locals>.handle_return  sh     MM&..*:;WI678N6DS6I%%l3##%KKm4  r   zEager exceptionTinductor)backendzException compilingzException running compiledzFunction returned FalseFzFunction succeededr   )rI  rJ  r:  alarmr   r  r   r   r   r   rB   rC   r	   rO   rF   r   r4   _dynamoresetr	  r   r  r   rX   compilerW   rY   rZ   r]   )r+   r  r  r   rN  r  r  test_model_fnr>  test_model_fn2compcompile_resultrL  rD  rM  r=  s   ```         @@@@r   r  zConfigFuzzer.test_config  s.    "==9M9MNT&&'x()V[[]+....3.MM&..*:;J	,		 	d38n 		!	!!	! "	! )$		!
 	! 	!" 	!<<> 	*KD%T5)	* 224	O	!779N==DD	!VN  )6+C+CUD  !!5v}}eTRR?  	 !6#D#DdC 	  	 %v'<'<dC 	  	 ,33	 	sZ   3G ;'H #H< 	H
'H?H
H
	H9H4.H94H9<	I(I#I(#I(num_attemptspc                    t        d| j                   d|        t        j                  | j                         | j                          t	               }g }t        |      D ]  }t        d|dz    d|        | j                         }| j                  j                         D ]e  \  }}||vs|j                  d      rd|vs"t        j                         |k  s:| j                  ||j                  |j                        }	|	||<   g | j                  ||      }
|
t        t        j                   t        j"                  g      vs| j%                  ||      x}st        d|        |j'                  |        |S )	zK
        Test configs and bisect to minimal failing configuration.
        z-Starting random testing with bisection, seed z, and p zRandom attempt r   /r   TESTING_ONLYzMinimum failing config: )r  r   r~   r	  r   r   r  r   r   r  r   r   ry   r  r   rO   r]   r\   _bisect_failing_configappend)r+   rY  rZ  r  r   attemptr  rx   config_entryr  r   minimal_failing_configs               r   bisectzConfigFuzzer.bisect  sq    	=dii[QRPSTUDII, "\* 	7GOGaK=,@A__&F,0KK,=,=,? 
/(
Lf,&11#6&j8!+ KK"L$;$;\=Q=QE */F:&
/ %%gv6FZ(GHH-1-H-HV. )  45K4LMNJJ56/	72 
r   failing_configc                 T    | j                  |t        |j                                     S r)   )_bisect_failing_config_helperr   r   )r+   r  rd  s      r   r^  z#ConfigFuzzer._bisect_failing_config@  s%     11'4@T@T@V;WXXr   c                 v    t        d|        |sydt        t        t        t        f      dt
        f fd}t        |      dk  r# ||      j                         rt        |      S dS t        j                  |       t        |      dz  }|d| }||d } ||      j                         r j                  |      S  ||      j                         r j                  |      S t        |      dk\  rt        |      d	z  }||z   }||d }	 ||	      j                         r j                  |	      S |d| |z   }
 ||
      j                         r j                  |
      S ||d| z   } ||      j                         r j                  |      S ||d } ||      j                         r j                  |      S t        t        |            D ]O  }t        |      D cg c]  \  }}||k7  s| }}} ||      j                         s= j                  |      c S  t        |      S c c}}w )
z
        Bisect a failing configuration to find minimal set of configs that cause failure.

        Splits it into halves, then fourths, then tries dropping configs one-by-one.
        zbisecting config: Nr   r   c                 B    t        |       }j                  |      }|S r)   )rB   r  )r   dresultr  r+   s      r   testz8ConfigFuzzer._bisect_failing_config_helper.<locals>.testR  s#    QA%%gq1FMr   r   r         )r  r   r   rC   r	   rO   r   r[   rB   r~   shufflerf  r   	enumerate)r+   r  rd  rk  mid
first_halfsecond_halflowhighquart1quart2quart3quart4ijr   new_lists   ``               r   rf  z*ConfigFuzzer._bisect_failing_config_helperE  sD    	">"234	DsCx) 	f 	
 ~!#+/+?+G+G+I4'StS~&.!Q&#DS)
$ST*
##%55gzJJ$$&55g{KK~!#n%*C9D#CD)FF|##%99'6JJ#DS)K7FF|##%99'6JJ.$"77FF|##%99'6JJ#DE*FF|##%99'6JJs>*+ 	MA&/&?Jda16JHJH~%%'99'8LL	M
 N##	 Ks   )H57H5r   )r{   )zfuzzer_state.pkl)d   g      ?)(r#   r1   r2   r3   r   rD   
ConfigTypert   ru   r   FactoryTyper   r   r   rC   r   r	   r  r	  r  r   r   r  r  r  r   rO   r"  r(  r0  r5  r   r:  r  r   r   rc  r^  r   rf  r*   r   r   r   r     s   9v  )-+22 $##$#  +$# 	$#
 *%$# $# $#L
# 
7c 7# 7$ 7<
J *!5 * JZ J* JQU Jz j 
1J 1y 1V 10c S J (3  F3 F F7c 7(92E 7$ 7PS: PSz PSf PSd#3 # #jAQ #JY!Y3=Y	*	Y
4$!4$37c3h3H4$	*	4$r   r   r#  r  r)  c                 F   | dk(  sJ t        |      dkD  sJ t        i       }|j                         D ]*  }|j                  |d          |j                  |d          , t	        |      }d}|dz  }|D ]  }dj                  |      }|d| dz  } |d	z  }|D ]  }	|d
|	 dz  }|D ]  }|j                  |	|f      }
d}d}|
t        j                  k(  rd}d}n||
t        j                  k(  rd}d}nd|
t        j                  k(  rd}d}nL|
t        j                  k(  rd}d}n4|
t        j                  k(  rd}d}n|
t        j                  k(  rd}d}nd}d}|d| d| dz  } |dz  } |dz  }t        |d      5 }|j                  |       ddd       y# 1 sw Y   yxY w)zp
    Creates an HTML document representing the results of running the fuzzer with fuzz_n_tuple, with n = 2.
    r   r   r   a  
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title> Fuzzer Visualization</title>
        <style>
            table {
                border-collapse: collapse;
                width: 50%;
                margin: 20px auto;
            }
            th, td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: center;
            }
            th {
                background-color: #f2f2f2;
            }
            .skipped {
                background-color: yellow;
            }
            .passed {
                background-color: green;
                color: white;
            }
            .failed {
                background-color: red;
                color: white;
            }
        </style>
    </head>
    <body>
        <h2 style="text-align: center;">Fuzzer Visualization</h2>
        <table>
        <thead>
    z<tr><th>\</th>z<br>z<th>z</th>z</tr></thead><tbody>z<tr><th>r|   rP   -rQ   OfailedeERCz<td class="z">z</td>z</tr>z?
        </tbody>
        </table>
    </body>
    </html>
    wN)r   r   r   addr   r   r   rO   r\   r]   rX   rY   rZ   rW   r,  write)r#  r  r)  	input_setkey
input_listhtml_contentcol_namecolrow_namestatus_enumstatus_class
status_valfiles                 r   visualize_resultsr  |  s    6M6w<!!+BI||~ c!fc!f 	"J&LP %%L *kk(#$se5))* **L   (8*E22" 	LH!..(H)=>KLJfnn,( 
-' 
 A AA' 
 C CC' 
 8 88' 
 5 55' 
( 
k,r*UKKL7	L8 	= @   L 
h	 !

< ! ! !s   <FF )zresults.html)GrI   r&  loggingr-  r~   rI  r   r   rA  collections.abcr   r   enumr   	functoolsr   r   typesr   typingr	   r
   r   r   r   r   r   r   r4   !torch._inductor.custom_graph_passr   torch._inductor.schedulerr   torch.utils._config_moduler   r   torch.utils._ordered_setr   	getLoggerr#   r   rF   r   r!   r$   r&   r7   r9   rL   CUDA_BACKENDrO   rr   rB   rC   r   rD   r   r   rt   r   r  r   r   r   r}  FactoryOutputTyper~  r   r   r   r  r*   r   r   <module>r     s          
  .  $ 	 	 	  = 7 A / g!HT H
4 
,4 ,	 	 CL: :.T  h'L:L
T 
F ! 15.2'  =eD#@$"G<dC')&(
	
 !   -t4	
!( '
3"J/$.L>1(S$s)^$ 4 d3i-s23IAT IAX  ) #s(O	#! #!N #s(^
RX& r,,-"**7* 	* 	!'	*
 	W* 	%g* 	%g* 	)'* 	6w* 	8* 	9'* 	* 	W* 	* 	G*  	!*" 	W#*$ 	!'%*& 	w'*( 	')** 	-g+*, 	!'-*. 	.w/*0 	+G1*2 	 3*4 	"75*6 	#G7*8 	"79*: 	w;*< 	"7=*> 	"7?*@ 	7A*B 	27C*D 	27E*F 4;%,&-3:")!( 'S*X (/-4'."	Y2*c:o& 2j|$ |$@ 2@h!
h!h!+.h!	h!r   