
    sh.                         S SK r S SKrS SKJr  S SKJrJrJr  S SKrS SK	J
r
JrJrJrJrJrJrJr  S SKJr  S SKJr  S SKJr  S SKJr   " S	 S
5      r " S S\5      r " S S5      r " S S\5      rg)    N)partial)AnyCallableOptional)	AHContext
AHMetadataAHOperationChoice
CHOICE_COLFeedbackFEEDBACK_COLget_metadata_str_from_log)LearnedHeuristicController)ChoiceCaller)	cache_dir)get_gpu_shared_memoryc                   H    \ rS rSrSrS\\/\4   SS4S jrS\S\4S jr	S	r
g)
LocalFeedback   a'  
To be able to collect data for a choice, a function providing feedback given a choice has to be provided.
LocalFeedback can be used when AutoHeuristic should immediately run the function to collect feedback for each choice
(see pad_mm.py, where the autotuning happens locally, for an example).
feedback_fnreturnNc                     Xl         g Nr   )selfr   s     /Users/tiagomarins/Projetos/claudeai/copy_bank/venv/lib/python3.13/site-packages/torch/_inductor/autoheuristic/autoheuristic.py__init__LocalFeedback.__init__    s    &    choicec                 $    U R                  U5      $ r   r   r   r    s     r   __call__LocalFeedback.__call__#   s    ''r   r   )__name__
__module____qualname____firstlineno____doc__r   r
   r   r   r#   __static_attributes__ r   r   r   r      s9    'HfXx-?$@ 'T '(v (( (r   r   c                       \ rS rSrSrSrg)InconsistentMetadata'   z
Exception that is thrown when AutoHeuristic tries to log data to a file where the metadata stored in the file does
not match the metadata it would store if the file didn't exist.
r+   N)r%   r&   r'   r(   r)   r*   r+   r   r   r-   r-   '   s    r   r-   c                   B   \ rS rSr% Sr\\\4   \S'     SS\	/ \4   S\
\   S\\   S\S	\S
\\
\      S\\	\\/\4      SS4S jjrS\4S jrS\4S jr SS\S\\
\      S\\
\      4S jjrS\S\4S jr\S\4S j5       rS\4S jrS\4S jrS\S\SS4S jrSrg)AutoHeuristic.   a  
AutoHeuristic is a framework that allows one to collect data, learn a heuristic (i.e. a regression tree) and
generate the heuristic to code. This class allows one to collect data. The collected data can then be used to train
a heuristic (see torchgen/autoheuristic/).
collected_feedbackNfallbackchoicesfeedbackcontextnameaugment_contextpreconditionr   c                    Xl         X l        X0l        X@l        XPl        0 U l        X`l        [        [        5       [        R                  R                  5       U R                  U R                  5      U l        Xpl        U R                  5       (       d  g[        R                  R                   R"                  S:X  a  U R%                  5       U l        O)[        R                  R                   R"                  U l        [        R                  R                   R)                  U R                  5      (       aD  U R                  b6  U R                   H%  nU R                  U5      n	U R+                  X5        M'     ggg)a  
Initializes an instance of the AutoHeuristic class.

Args:
    fallback: A callable that returns a Choice when the heuristic is unsure which choice to make, or
    AutoHeuristic is in data collection mode.
    choices: A list of possible choices the heuristic can make.
    feedback: An instance of LocalFeedback that provides feedback for a given choice.
    context: Context to store with each choice and feedback.
    name: A string that identifies the heuristic.
    augment_context: An optional list of AHOperation instances that augment the context.
    precondition: A callable that returns a boolean indicating whether AutoHeuristic should run.
NDEFAULT)r3   r4   r5   r6   r7   r2   r8   r   r   torchcudaget_device_capabilitymetadatar9   satisfies_precondition	_inductorconfigautoheuristic_log_pathget_default_log_pathlog_pathcollect_autoheuristic	save_data)
r   r3   r4   r5   r6   r7   r8   r9   r    feedback_vals
             r   r   AutoHeuristic.__init__7   s   . ! 	"$."!#JJ,,.LLII	
 )**,,??!!88IE 557DM!OO22IIDM??!!77		BB}}("llF#'==#8LNN68 + ) Cr   c                 x    U R                   S L =(       d&    U R                  U R                  U R                  5      $ r   )r9   r?   r6   )r   s    r   r@   $AutoHeuristic.satisfies_preconditionk   s4      D( 
D,=,=MM4<<-
 	
r   c                    U R                  5       (       d  U R                  5       $ [        R                  R                  R                  U R                  5      (       a  U R                  b%  U R                  R                  U R                  5        [        U R                  U R                  5      nUR                  5       nX R                  ;  a  U R                  5       $ Ub  U$ U R                  5       $ )z
Returns the chosen option based on the value of autoheuristic_use.
If self.name is one of the comma separated strings in autoheuristic_use,
it queries a learned heuristic to make a decision. Otherwise, it returns the fallback option.
)r@   r3   r<   rA   rB   use_autoheuristicr7   r8   r6   apply_operationsr   r?   get_decisionr4   )r   
controllerdecisions      r   
get_choiceAutoHeuristic.get_choicep   s     **,,==?"??!!33DII>>##/--d.B.BC3J "..0H||+}}&#}}r   top_kalways_includedc                    U R                  5       (       d  g [        R                  R                  R	                  U R
                  5      (       a  U R                  b%  U R                  R                  U R                  5        [        U R                  U R                  5      nUR                  U5      nUc  g Ub!  U H  nXT;  d  M
  UR                  U5        M     U$ g r   )r@   r<   rA   rB   rM   r7   r8   r6   rN   r   r?   get_decisions_rankedappend)r   rT   rU   rP   r4   r    s         r   get_top_k_choicesAutoHeuristic.get_top_k_choices   s     **,,??!!33DII>>##/--d.B.BC3J !55e<G*-F,v. . Nr   r    c                 :    U R                   R                  US 5      $ r   )r2   getr"   s     r   get_collected_feedback$AutoHeuristic.get_collected_feedback   s    &&**6488r   c                  b    [         R                  R                  5       R                  SS5      n U $ )N _)r<   r=   get_device_namereplace)device_names    r   get_device_identifier#AutoHeuristic.get_device_identifier   s)     jj002::3Dr   c                     U R                  5       n[        5        SU S3n[        R                  " USS9  X R                   S3-  nU$ )Nz/autoheuristic//T)exist_okz.txt)re   r   osmakedirsr7   )r   rd   paths      r   rD   "AutoHeuristic.get_default_log_path   sJ    002+ok]!<
D4(99+T""r   c                     U R                   R                  5       nU R                  R                  5       u  nnX!S'   X1S'   [        R
                  " U5      $ )Nnumerical_featurescategorical_features)r?   to_dictr6   &get_numerical_and_categorical_featuresjsondumps)r   metadata_dictnum_featurescat_featuress       r   serialize_metadata AutoHeuristic.serialize_metadata   sR    --/ LL??A	
.:*+0<,-zz-((r   rH   c                    X R                   U'   U R                  n/ n[        R                  R	                  U5      nU(       a6  U R                  5       n[        U R                  5      nXv:w  a  [        S5      eO`UR                  U R                  5       5        U R                  R                  5       nUS-   [        -   S-   [        -   n	UR                  U	5        Sn
U R                  R                  5       nXS-   U-   S-   [        U5      -   -  n
UR                  U
5        [        US5       nUR!                  SR#                  U5      S-   5        S S S 5        g ! , (       d  f       g = f)Nz/Given metadata does not match existing metadata, a
)r2   rE   rj   rl   existsrx   r   r-   rX   r6   get_feature_names_csvr   r   get_feature_values_csvstropenwritejoin)r   r    rH   rE   lines
log_existsr?   existing_metadatafeature_headerheaderlinefeature_valuesfs                r   rG   AutoHeuristic.save_data   s/   *6'==WW^^H-
..0H 9$-- H ,*E  -
 LL0023!\\??AN#c)J6<|KFLL <<>$v-3c,6GGGT(C AGGDIIe$t+, !  s   +$E
E&)
r8   r4   r2   r6   r3   r5   rE   r?   r7   r9   NNr   )r%   r&   r'   r(   r)   dictr
   r   __annotations__r   listr   r   r   r   r	   r   boolr   r@   rR   intrY   r   r]   staticmethodre   rD   rx   rG   r*   r+   r   r   r0   r0   .   sS    VX-.. 8<JN292v:&29 f29 =)	29
 29 29 "${"3429 xY(?(EFG29 
29h
 

F 4 BF+3DI+>	$v,	,9V 9 9 3  c )C )- -h -4 -r   r0   c                      ^  \ rS rSrSr  SS\/ \\   4   S\\   S\\	   S\
S\S	\\\      S
\\\\
/\4      SS4U 4S jjjrS\\	   S\\   SS4S jrS\\   4S jr SS\S\\\      S\\\      4S jjrSrU =r$ )AutoHeuristicSelectAlgorithm   z
AutoHeuristicSelectAlgorithm is a subclass of AutoHeuristic that allows one to collect data and learn a heuristic
when one wants to use AutoHeuristic for kernel choice selection.
Nr3   r4   input_nodesr6   r7   r8   r9   r   c           	        >^ X0l         0 U l        U H  nXR                  UR                  5       '   M!     [        U R                  R	                  5       5      n	S[
        4U4S jjn
[        TU ]  U
U	SUUUU5        [        R                  R                  R                  U R                  5      (       a(  U R                  5       (       a  U R                  X25        ggg)a  
The arguments choices, input_nodes and name have to match the ones used in the call to
autotune_select_algorithm(), e.g. if the following call is made
autotune_select_algorithm(name, choices, input_nodes, layout), the same name, choices and input_nodes
have to be used here.
r   c                  :   > T" 5       n U c  gU R                  5       $ )Nunsure)autoheuristic_id)fallback_choicer3   s    r   fallback_str;AutoHeuristicSelectAlgorithm.__init__.<locals>.fallback_str   s"    &jO&"3355r   N)r   choicestr2choicer   r   keysr   superr   r<   rA   rB   rF   r7   r@   register_global_feedback)r   r3   r4   r   r6   r7   r8   r9   r    choices_strr   	__class__s    `         r   r   %AutoHeuristicSelectAlgorithm.__init__   s      '9;F?E!!&"9"9";< 4005578	6c 	6 		
 OO""88CC++--))+? . Dr   c                   ^ ^^	 SSK JnJmJm	  S[        S[        S[
        [        [        4   S[        S[        [           S[        [           S	S
4UU	U 4S jjnT" U5      nT	" T R                  XR5      n[        XEU5      nU" U5        g
)z[
Registers a callback in select_algorithm, which is called with the timing of each choice.
r   )add_feedback_savercreate_inputs_keycreate_precompile_keyah_inputs_keyah_precompile_keytimingsr7   r   r4   r   Nc                    > T
" U5      nX`:w  a  g T" X6U5      nXq:w  a  g UR                  5        H%  u  pTR                  UR                  5       U	5        M'     g r   )itemsrG   r   )r   r   r   r7   r   r4   current_inputs_keycurrent_precompile_keyr    timer   r   r   s             r   store_global_feedbackTAutoHeuristicSelectAlgorithm.register_global_feedback.<locals>.store_global_feedback  s]     "3;!?!2%:'&" &: 'v668$? !0r   ) torch._inductor.select_algorithmr   r   r   r   r   r   floatr   r   r7   r   )
r   r   r4   r   r   
inputs_keyprecompile_keyfeedback_saverr   r   s
   `       @@r   r   5AutoHeuristicSelectAlgorithm.register_global_feedback  s    	
 	
	@	@"	@ ,-.	@ 		@
 c	@ ,'	@ 	@ 	@& '{3
.tyy*N !6NS>*r   c                 Z    U R                  5       nU R                  R                  US 5      $ r   )rR   r   r\   r"   s     r   get_choice_caller.AutoHeuristicSelectAlgorithm.get_choice_caller1  s'    "$$((66r   rT   rU   c                 t    U R                  X5      nUc  g U Vs/ s H  o@R                  U   PM     sn$ s  snf r   )rY   r   )r   rT   rU   r4   r    s        r   get_top_k_choices_caller5AutoHeuristicSelectAlgorithm.get_top_k_choices_caller5  s=     ((@?<CDG&%%f-GDDDs   5)r   r   r   r   )r%   r&   r'   r(   r)   r   r   r   r   r   r   r   r	   r   r   r   r   r   r   r   r*   __classcell__)r   s   @r   r   r      s"    8<JN+@2x556+@ l#+@ #Y	+@
 +@ +@ "${"34+@ xY(?(EFG+@ 
+@ +@Z#+9#+/3L/A#+	#+J78L#9 7
 BFEE+3DI+>E	$|$	%E Er   r   )rs   rj   	functoolsr   typingr   r   r   r<   1torch._inductor.autoheuristic.autoheuristic_utilsr   r   r	   r
   r   r   r   r   :torch._inductor.autoheuristic.learned_heuristic_controllerr   torch._inductor.irr   %torch._inductor.runtime.runtime_utilsr   torch._inductor.utilsr   r   	Exceptionr-   r0   r   r+   r   r   <module>r      si     	  * * 	 	 	 , ; 7( (9 h- h-VbE= bEr   