a
    dȕ                     @   sn  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 d dl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mZ eeZed
Ze  Z!g Z"dZ#e!rg dZ"d$dd e"D Z#G dd dZ%dd Z&G dd dZ'e(ddd Z)dd Z*dZ+dd Z,dZ-e-ddfe-dd fd!Z.d"d# Z/d$d% Z0dTe1d&d'd(Z2dUd)dZ3dVd*d Z4d+d, Z5d-d. Z6e1d&d/d0Z7G d1d2 d2e8Z9e1d&d3d4Z:dWd6d7Z;dXd8d9Z<d:d; Z=d<d= Z>d>d? Z?dYd@dAZ@dZdBdCZAd[dDdEZBd\dFdGZCejDeCdHdIZEd5ZFdJdK ZGdLdM ZHe1d&dNdOZIedPdQ ZJedRdS ZKdS )]    N)Counter)import_module)TemporaryFile)is_float_dtype   )config)lookup_backendregister_debug_backend)clone_inputsget_debug_dirztorch._inductor.config )z6//caffe2/fb/custom_ops/sparsenn:sparsenn-all_operatorsz1//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_ops
c                 C   s   g | ]}d | dqS )ztorch.ops.load_library("z") .0xr   r   b/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torch/_dynamo/debug_utils.py
<listcomp>'       r   c                   @   s&   e Zd Zdd Zdd Zd	ddZdS )
BuckTargetWriterc                 C   s   t j|\| _| _| jdd| _| jdd d| j | _| j| jdd  | _| jdd  | _| j}||dd  dd  }d| d	| j | _d S )
N.pyr   /.zfbcode.   zfbcode/z//:)	ospathsplitsubdirpy_filereplacetargetfindcmd_line_path)selffilenametmpr   r   r   __init__+   s    zBuckTargetWriter.__init__c                 C   s>   d dd tD }td| j d| j d| d| j d	S )	Nr   c                 S   s   g | ]}d | dqS )z	        "z",r   r   r   r   r   r   :   r   z*BuckTargetWriter.build.<locals>.<listcomp>za
load("@fbcode_macros//build_defs:python_binary.bzl", "python_binary")

python_binary(
    name="z",
    srcs = ["z"],
    compile = False,
    deps = [
        "//caffe2:torch",
        "//caffe2/functorch:functorch",
        "//triton:triton",
    ],
    cpp_deps = [
z
    ],
    main_module = "z",
)
)join
extra_depstextwrapdedentr!   r   r   )r$   Zextra_cpp_depsr   r   r   build9   s    zBuckTargetWriter.buildTc                 C   st   t j| jd}t|d}||   W d    n1 s>0    Y  ddd| jg}|rpt	dd|  |S )NZTARGETSwZbuck2runz@mode/dev-nosanzDFound an example that reproduces the error. Run this cmd to repro -  )
r   r   r(   r   openwriter,   r#   logwarning)r$   	print_msgZtarget_filefdcmdr   r   r   r1   P   s    ,zBuckTargetWriter.writeN)T)__name__
__module____qualname__r'   r,   r1   r   r   r   r   r   *   s   r   c                  C   sL   t jt d} | d u r.t  dt  } t j| sHt j	| dd | S )Nminifierz
/minifier_Texist_ok)
r   r   r(   r   tempfile
gettempdirgetpassgetuserexistsmakedirs)r   r   r   r   minifier_dir]   s    rC   c                   @   s   e 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jejjejjejjejjejjgZedd Zedd ZdS )NNModuleToStringc                 C   sP   t  }|  D ] \}}t|tjvr|| qt|dkrLtd|  dS )Nr   z+We have not tested reprs of some modules - T)	setnamed_childrentyperD   
safe_reprsaddlenr2   r3   )gmZcant_convert_moduler   r   r   can_convert_to_string   s    z&NNModuleToString.can_convert_to_stringc                 C   s  ddl m} d}td}|  D ]V\}}|  }t| d }|d urZ|jrZ| d}||d  d| d| d	7 }q"| j	
 D ]\}}	|	d u rqt|	rd
t|	j d|	j d}
ndt|	j d|	j d}
|	jr|
 d}
||d  d| d|
 d7 }q| j
 D ]b\}}|d u r&qdt|j d|j d}
|jrR|
 d}
||d  d| d|
 d	7 }q||| jd d	7 }|S )Nr   )
_addindentz    z
            from torch.nn import *
            class Repro(torch.nn.Module):
                def __init__(self):
                    super().__init__()
            z.cuda()   zself.z = r   ztorch.randn(z, dtype=)ztorch.randint(1, size=zself.register_buffer('z', z)
ztorch.nn.Parameter(torch.randn(z))   )Ztorch.nn.modules.modulerO   r*   r+   rF   __repr__next
parametersis_cuda_buffersitemstorchis_floating_pointlistshapedtype_parameterscode)rK   rO   tab	model_strmodule_namerM   Z
module_strZexample_paramZbuffer_namebufferZ
tensor_str
param_nameparamr   r   r   convert   s<    	

 

 

"	zNNModuleToString.convertN)r7   r8   r9   rY   nnZLinearZConv1dZConv2dZConv3dZBatchNorm1dZBatchNorm2dZBatchNorm3dZ	LayerNormZDropoutZSoftmaxZReLUZGELUZIdentityZ	MaxPool2dZ	EmbeddingZTanhZConvTranspose1dZGLUZLSTMZFlattenZAdaptiveAvgPool2drH   staticmethodrN   rf   r   r   r   r   rD   f   s4   
rD   c                  C   s   t j sdS d} zJtjddgtjd}|j d}d	dd	 |D }| | d7 } W n t
yv   | d
7 } Y n0 tdd tt j D }| d7 } | D ]\}}| d| d| d7 } q| d7 } | S )Nz:# torch.cuda.is_available()==False, no GPU info collected
z# CUDA Info: 
Znvccz	--version)stdoutr   r   c                 S   s    g | ]}|d vrd| dqS ))r   #  
r   )r   sr   r   r   r      r   z-_cuda_system_info_comment.<locals>.<listcomp>z# nvcc not found
c                 s   s   | ]}t j|V  qd S N)rY   cudaZget_device_name)r   ir   r   r   	<genexpr>   s   z,_cuda_system_info_comment.<locals>.<genexpr>z# GPU Hardware Info: 
rj   z : rk   )rY   rn   Zis_available
subprocessr.   PIPEri   decoder   r(   FileNotFoundErrorr   rangedevice_countrX   )ra   Zcuda_version_outZcuda_version_linesZ	gpu_namesnamecountr   r   r   _cuda_system_info_comment   s(    
ry   c               
   C   sR   dd l } dd l} tdt| jj  dt| jj  dt| j	j  dS )Nr   zzimport torch._dynamo.config
import torch._inductor.config
import torch._functorch.config
torch._dynamo.config.load_config(z%)
torch._inductor.config.load_config(z&)
torch._functorch.config.load_config(z
)
        )
Ztorch._functorch.configZtorch._inductor.configr*   r+   reprZ_dynamor   Zsave_configZ	_inductorZ
_functorch)rY   r   r   r   generate_config_string   s    r{   z*# REPLACEABLE COMMENT FOR TESTING PURPOSESc              	   C   s   t dt  dt dt d}|dtjj d7 }ttjdrT|dtjj	 d7 }ttjdrt|d	tjj
 d
7 }|t 7 }|t| 7 }|ddd |D d7 }|d7 }d}tjrd}|dt| d7 }|S )Nz
import torch
from torch import tensor, device
import torch.fx as fx
from torch._dynamo.testing import rand_strided
from math import inf
from torch.fx.experimental.proxy_tensor import make_fx



r   z


        z# torch version: rn   z# torch cuda version: git_versionz# torch git version: z


zargs = c                 S   s,   g | ]$}t |jt | |j|jjfqS r   )tupler\   strider]   devicerG   r   ar   r   r   r     r   z2generate_compiler_repro_string.<locals>.<listcomp>zEargs = [rand_strided(sh, st, dt, dev) for (sh, st, dt, dev) in args]
realZsymbolicz$mod = make_fx(Repro(), tracing_mode=z	)(*args)
)r*   r+   r{   TEST_REPLACEABLE_COMMENTextra_importsrY   version__version__hasattrrn   r}   ry   rD   rf   r   Zdynamic_shapesrz   )rK   argsra   Ztracing_moder   r   r   generate_compiler_repro_string   s2    

r   zo
from torch._inductor.compile_fx import compile_fx_inner
from torch._dynamo.debug_utils import same_two_models
compile_fx_innerinductor_failsinductor_accuracy_fails)inductorZinductor_accuracyc                 C   s  t jt d}t j|s*t j|dd t j|t| jj d}t	
dt| jj d|  t|d}t|| || W d    n1 s0    Y  t  }t j|d}z0t|| t	
d	|  trt|  W n$ ty   t	
d
|  Y n0 d S )NcheckpointsTr;   r   Writing checkpoint with 
 nodes to r-   repro.pyz&Copying repro file for convenience to zNo write permissions for )r   r   r(   rC   rA   rB   rJ   graphnodesr2   r3   r0   save_graph_reprogetcwdshutilcopyfileuse_buckr   r1   OSError)rK   r   compiler_namer   	file_namer5   curdirZ
repro_pathr   r   r   dump_compiler_graph_state&  s"    ,r   c              	   C   s   d}|D ]}|j rd} qqd|v r.| d | t|| | t| d  d|v rz| tdt| d  d	 n&| tdt| d  d
| d d S )Nr   z>torch.cuda.synchronize() # Ensures that segfaults are surfacedr   z!import torch._inductor.overrides
r   	_accuracyz
                compiled = r   z(mod, args)
                class AccuracyError(Exception):
                    pass
                if not same_two_models(mod, compiled, args, only_fwd=True):
                    raise AccuracyError("Bad accuracy detected")
                zA(mod, args)
                ref = compiled(args)
                
                )rV   r1   r   COMPILER_REPRO_OPTIONSr*   r+   )r5   rK   r   r   Z	sync_lineargr   r   r   r   :  s4    


r   r   c              
   C   s  |d u ri }t jt  d}t j|s8t j|dd t j|tt d d  d}t	|dz}t
| |}|d ur|t|}|| t| d }	|tdt d	|	 d
 |td|	 d W d    n1 s0    Y  t j }
i |
|}
t t  }}tr,t|jdd}nd|g}tj|||||
d}|  |jdkr|d |d ttj| ddd ttj| ddd dS dS )NZisolateTr;      r   r-   rP   z
                from z import r   z
                if zk(mod, args):
                    exit(1)
                else:
                    exit(0)
                F)r4   python)cwdri   stderrenvr   zutf-8z>>  )prefix) r   r   r(   r   rA   rB   struuiduuid4r0   r   r    r   r1   r   r*   r+   r7   environcopyr   r   r   rq   Popenwait
returncodeseekprintindentreadrs   )fx_gr   r   r   Z
patch_coder   r   r5   Z
repro_codeZfail_fnZnew_envri   r   r6   pr   r   r   isolate_fails]  sb    $

"


r   c           	   
      s   d |D ]}|j rd  qq fdd}ddlm} z4| | }t|ttfsPJ tdd |D rfJ W n ty|   Y dS 0 |  z|| |}|| |  W nV t y } z<|d ur|t|vrW Y d }~dS t	t| W Y d }~dS d }~0 0 dS )	NFTc                      s    rt j  d S rm   )rY   rn   Zsynchronizer   Zhas_cudar   r   sync  s    zinductor_fails.<locals>.syncr   r   c                 S   s   g | ]}t |ttfqS r   )
isinstancer~   r[   r   r   r   r   r     r   z"inductor_fails.<locals>.<listcomp>)
rV   torch._inductor.compile_fxr   r   r~   r[   any	Exceptionrz   r   )	r   r   	check_strr   r   r   resultZcompile_moder   r   r   r     s0    

c                 C   s   ddl m} t| ||S )Nr   r   )r   r   backend_aot_accuracy_fails)r   r   r   r   r   r   r   r     s    c                   C   s   t jt dS )Nminifier_launcher.py)r   r   r(   rC   r   r   r   r   get_minifier_repro_path  s    r   c              
   C   s   t  }td|  tr&t|  z8t|d}||  W d    n1 sR0    Y  W n8 ty } z t| t	d|W Y d }~n
d }~0 0 d S )NzWriting minified repro to r-   z(Could not write to {minified_repro_path})
r   r2   r3   r   r   r1   r0   r   	exceptionNotImplementedError)contentsZminified_repro_pathr5   r   r   r   r   helper_for_dump_minify  s    ,
r   c                 C   sN   t j dkrdnd}tdt| | dt d| d| d| d	}t|S )
NrP   r   r   z 
isolate_fails_code_str = None

z%

from functools import partial
from z import (
    isolate_fails,
    dump_compiler_graph_state,
)
from functorch.compile import minifier

env_variables = {"CUDA_VISIBLE_DEVICES": "zk"}

minifier(
    mod,
    args,
    module_fails=partial(isolate_fails, env=env_variables, compiler_name="zh", patch_code=isolate_fails_code_str),
    dump_state=partial(dump_compiler_graph_state, compiler_name="z"),
)
        )rY   rn   rv   r*   r+   r   r7   r   )rK   r   r   Zfavored_devicer   r   r   r   dump_to_minify  s    r   c                   @   s   e Zd ZdS )AccuracyErrorN)r7   r8   r9   r   r   r   r   r     s   r   c                    s   t  fdd}|S )a\  
    Minifier for Fx Graph modules after Aot Autograd has finished. We wrap both
    forward and backward call separately with the backend compiler_fn - like
    inductor or nvfuser. Intercepting after Aot Autograd presents neat
    abstration, where all the params are lifted as graph inputs, making it easy
    to save the graph as a string.
    c                    sx   ddl m  tjfi |tjtjdv s8J d  fdd}tjdkrj|}d|_	n
}|S )Nr   )FakeTensorModedynamoaotNc              
      sV     fdd| D }t jdkr6tt|  t jdkrdkrPtddu rbt| rtd t	t| d	 tt| d	 t
d
n| S nzdu rԈ| W S  tyP } zZt jdkrt	t| n t jdkr0tt| td  W Y d}~n
d}~0 0 dS )ah  
            Aot Autograd fw_compiler and bw_compiler can have fake tensors. So,
            example_inputs can be fake tensors. We can call compiler_fn (which is
            inductor or nvfuser) with fake tensors but the actualy compiled_fn
            should be called with real tensors. Therefore, the actual invocation
            is deffered.
            c                    s   g | ]}  |qS r   )Zfrom_tensorr   Z	fake_moder   r   r     r   z`wrap_compiler_debug.<locals>.debug_wrapper.<locals>.deferred_for_real_inputs.<locals>.<listcomp>   rR   r   z4Accuracy minification is supported for inductor onlyNz*Accuracy failed for the AOT Autograd graphr   zBad accuracy detectedr   rP   ZCompilerError)r   repro_levelr   fxGraphModuler   r   r2   r3   r   r   r   error)Zreal_inputsZcopy_tensor_attrsr   )r   compiler_fnr   example_inputsrK   inner_compiled_fn
orig_graphr   r   deferred_for_real_inputs	  s\    












zLwrap_compiler_debug.<locals>.debug_wrapper.<locals>.deferred_for_real_inputsr   T)
Ztorch._subclassesr   	functoolspartialr   deepcopyr   r   repro_after_boxed_call)rK   r   kwargsr   Zcompiled_fnr   unconfigured_compiler_fn)r   r   r   rK   r   r   r   debug_wrapper  s    F

z*wrap_compiler_debug.<locals>.debug_wrapper)r   wrapsr   r   r   r   r   r   wrap_compiler_debug  s    	Wr   Fc                 C   s   ddl m} ddlm}m}m} t| } t|}t	||D ]\}}	|
|	j q<|}t| drj| d t| dd}
t| d	d}t| d
s|
dus|dur|| } |
dur|
| _|dur|| _| |}|r|S ||r||}|  || |d|S )zR
    Runs a forward and possibly backward iteration for a given mod and args.
    r   )make_boxed_funcr   )collect_resultsreduce_to_scalar_lossrequires_bwd_pass	zero_gradTnamed_parametersNnamed_buffersr   )Ztorch._functorch.aot_autogradr   testingr   r   r   r   r   r
   zipZrequires_grad_requires_gradr   r   getattrr   r   Zbackward)rK   r   only_fwdr   r   r   r   new_argsZnargr   Zorig_named_parametersZorig_named_buffersoutZlossr   r   r   run_fwd_maybe_bwdZ  s8    



r   c              
   C   s  ddl m} ddlm}m} ddlm} t| |rF|| | _|| | _	t||rd|||_|||_	t
| ||}z(tt| t|\}	}
t
|	|
|}W n  ty   td d}Y n0 zt
|||}W n2 t y } ztd W Y d}~dS d}~0 0 ||||tjdd	}|S )
z.
    Check two models have same accuracy.
    r   )OptimizedModule)"named_buffers_for_optimized_module%named_parameters_for_optimized_module)samezCould not generate fp64 outputsNzWhile minifying the program in accuracy minification mode, ran into a runtime exception which is likely an unrelated issue. Skipping this graph.T)ZtolZ	equal_nan)Z
eval_framer   r   r   r   utilsr   r   r   r   r   cast_to_fp64r   r   r
   r   r2   r3   r   r   Zrepro_tolerance)rK   Zopt_gmr   r   r   r   r   r   refZ
fp64_modelZfp64_examplesZfp64_refresr   Zpassingr   r   r   same_two_models  s6    







r   c                 C   s   | j jD ]b}|jdkr|jtjjjjkrt	|j
dks:J t|j
d r|j
d tjkr|j
d tjf|_
q| j   |   | S )Ncall_functionrP   r   r   )r   r   opr!   rY   opsZprimsZconvert_element_typedefaultrJ   r   r   float64ZlintZ	recompile)modelnoder   r   r   !cast_convert_element_type_to_fp64  s    
r  c                    sB   ddl m} | } tjkr(t|}| fdd|}||fS )Nr   )tree_mapc                    s"   t | tjr|  r|  S | S rm   )r   rY   ZTensorrZ   to)r   r]   r   r   <lambda>  s
    
zcast_to.<locals>.<lambda>)Ztorch.utils._pytreer  r  rY   r  r  )r]   r  inputsr  r   r	  r   cast_to  s    


r  c                 C   s   t tj| |S rm   )r  rY   r  )r  r  r   r   r   r     s    r   c                 C   s|   t dt  d}tjdks$|r:t dt  d}t dt  dt dt d	d
d |D  d|  d| d| dS )zH
    Generate a repro string for backend-agnostic minified version.
    z&
with torch.cuda.amp.autocast(enabled=zY):
    ref = run_fwd_maybe_bwd(mod, args)
    res = run_fwd_maybe_bwd(opt_mod, args)
    rR   zk
mod.eval()
opt_mod.eval()

class AccuracyError(Exception):
    pass

with torch.cuda.amp.autocast(enabled=z):
    assert same_two_models(mod, mod, args), "Eager itself failed"
    if not same_two_models(mod, opt_mod, args):
        raise AccuracyError("Dynamo failed")
    a  
from math import inf
import torch
from torch import tensor, device
import torch.fx as fx
import torch._dynamo
from torch._dynamo.testing import rand_strided
from torch._dynamo.debug_utils import run_fwd_maybe_bwd
from torch._dynamo.debug_utils import same_two_models

r|   r   	

args = c                 S   s0   g | ](}t |jt | |j|jj|jfqS r   r~   r\   r   r]   r   rG   r   r   r   r   r   r     r   z3generate_dynamo_fx_repro_string.<locals>.<listcomp>^
args = [rand_strided(sh, st, dt, dev).requires_grad_(rg) for (sh, st, dt, dev, rg) in args]

z2

mod = Repro()
opt_mod = torch._dynamo.optimize("z	")(mod)

z	
        )	r*   r+   rY   is_autocast_enabledr   r   r{   r   r   )ra   r   r   check_accuracyZrun_coder   r   r   generate_dynamo_fx_repro_string  s8    
r  c           
      C   s   t  }t jt  d}t j|s4t j|dd t j|dt| jj d}t	
dt| jj d|  t| }t|d$}|t|||| W d	   n1 s0    Y  t j|d
}	t	
d| d|	 d trt|	  t||	 d	S )z,
    Saves the repro to a repro.py file
    r   Tr;   Z	minified_z	_nodes.pyr   r   r-   Nr   zCopying z to z for convenience)r   r   r   r(   rA   rB   rJ   r   r   r2   r3   rD   rf   r0   r1   r  r   r   r   r   )
rK   r   r   r  r   r   r   ra   r5   Zlatest_repror   r   r   dump_backend_repro_as_file  s$    
"r  c                 C   s   t | sJ t| |||S )a  
    Dumps the dynamo graph to repro the issue.
    1) It tries to convert Fx GraphModule to a string. If we can, it writes to a
    repro.py file.
    2) If we can't convert Fx GraphModule to a string, we use to_folder to save
    the module and save a tar file.
    )rD   rN   r  )rK   r   r   r  r   r   r   dump_backend_stated  s    r  c              
   C   sZ   z|t | t|}W n0 tyH } ztd W Y d }~dS d }~0 0 t| ||| S )NzWhile minifying the program in accuracy minification mode, ran into a runtime exception which is likely an unrelated issue. Skipping this graphF)r   r   r
   r   r2   r   r   )rK   r   r   r   compiled_gmr   r   r   r   backend_accuracy_failsq  s    r  Tr   c              
   C   s   ddl m} z|| |}t|t| W dS  tyz } z8t|}|d|| dkrdW Y d}~dS W Y d}~dS d}~0 0 dS )a.  
    Minifier uses this function to identify if the minified graph module fails
    with the same error.

    One caveat is that minifier can potentially go into a wrong direction when
    the resulting graph module fails for a different reason. To avoid this, we
    save the string for the original exception and check similarity between new
    and old exception. They can be somewhat different in some cases, when the
    exception string depends on the failing node information. So, we have a
    loose similarity metric to guide the minifier path.
    r   )SequenceMatcherFNg      ?T)difflibr  r   r
   r   r   Zratio)rK   r   r   orig_failurer  r  r   Znew_failurer   r   r   backend_fails  s    
r  c                 C   s   t | }d}tjdkrd}|d u r.tdnd}tdt  dt dt d	d
d |D  d| d| d| d| dt	
  d}t| d S )Ndynamo_minifier_backendrR    dynamo_accuracy_minifier_backendad          raise RuntimeError(
            'Compiler name is None - this likely means that a custom compiler '
            'was called by torchdynamo. Please remove this error, import your '
            'custom compiler function, and replace the compiler_name="None" '
            'line below to compiler_name=<my_imported_custom_function>'
        )
        r   a-  
import os
from math import inf
import torch
from torch import tensor, device
import torch.fx as fx
import functools
import torch._dynamo
from torch._dynamo.debug_utils import run_fwd_maybe_bwd
from torch._dynamo.backends.registry import lookup_backend
from torch._dynamo.testing import rand_strided

r|   r   r  c                 S   s0   g | ](}t |jt | |j|jj|jfqS r   r  r   r   r   r   r     r   z/dump_to_minify_after_dynamo.<locals>.<listcomp>r  z
mod = Repro()

# Setup debug minifier compiler
torch._dynamo.debug_utils.MINIFIER_SPAWNED = True
compiler_fn = lookup_backend("z")
zR
dynamo_minifier_backend = functools.partial(
    compiler_fn,
    compiler_name="zj",
)
opt_mod = torch._dynamo.optimize(dynamo_minifier_backend)(mod)

with torch.cuda.amp.autocast(enabled=z):
    opt_mod(*args)
        )rD   rf   r   r   r*   r+   r{   r   r   rY   r  r   )rK   r   r   ra   Zminifier_backendZcustom_compiler_errorr   r   r   r   dump_to_minify_after_dynamo  s@    

!&r  c                    s"   t  fdd}|_|S )a  
    A minifier decorator that wraps the TorchDynamo produced Fx graph modules.
    As opposed to wrap_compiler_debug, this wrapper intercepts at the
    TorchDynamo produced Fx Graph Module. This makes it backend-agnostic to some
    level, e.g., it is useful for minifying issues related to Aot Autograd
    tracing.  If an error is found, we minify and save the minified repro in
    repro.tar.gz.
    c              
      s  t jfi |}tjdv s J tjdkrrtjdkrBt| |  tjdkr|t| |}t| ||rt	
d tt| t| j|  td}tjt d|_|nz|t| |}t|| W n tyn } zt	
d tjd	krt jt d
}|t| t| j| n(tjdkrFtt| t| j|  tjt d|_ W Y d }~n
d }~0 0 n
|| |}|S )Nr   r   r   rR   zXAccuracy failed for the TorchDyanmo produced graph. Creating script to minify the error.zBad accuracy detected.r   DCompiled Fx GraphModule failed. Creating script to minify the error.r   r   rP   )r   r   r   r   r   r  r   r   r  r2   r3   r   r   r   r   r   r   r(   rC   Zminifier_pathr   r   r  )rK   r   r   r   r  excdump_state_fnr   r   r   r     s^    


z)wrap_backend_debug.<locals>.debug_wrapper)r   r   Z_torchdynamo_orig_callabler   r   r   r   wrap_backend_debug  s    
7r"  c           
   
   C   s   ddl m} t|}z || |}t|| tdW n~ ty } zft|}td t	j
t|d}|t| t| j| t	j
t||d}	|| ||	|d W Y d }~n
d }~0 0 | S )Nr   r:   zNo issue was detectedr  r   )r   r  Zmodule_failsZ
dump_state)functorch.compiler:   r   r   
ValueErrorr   r   r2   r3   r   r   r  r   r   r   r   r   r  )
rK   r   r   r:   r   r  r   r  r!  fails_fnr   r   r   r  (  s6    

r  c                 C   s   ddl m} t|}|   t| ||tjdrtd t	j
t|dd}t	j
t|tjd}|t| t| j| || |||d n
td	 | S )
Nr   r#  r  z2Accuracy failed for the TorchDynamo produced graphT)r   r  )r   r   r$  z*Input graph does not fail accuracy testing)r%  r:   r   evalr  r   Zrepro_forward_onlyr2   r3   r   r   r  r   r   r   r   r   r   )rK   r   r   r:   r   r!  r'  r   r   r   r  I  s0    


r  )NN)N)N)F)F)F)F)F)F)Lr   r   r?   loggingr   r   rq   r*   r   collectionsr   	importlibr   r=   r   rY   Ztorch.fxr   Ztorch._prims_commonr   r   r   Zbackends.registryr   r	   r   r
   r   	getLoggerr7   r2   Zinductor_configZ	is_fbcoder   r)   r   r(   r   rC   rD   	lru_cachery   r{   r   r   ZINDUCTOR_IMPORTr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r  r  r  r  r   r   ZMINIFIER_SPAWNEDr  r  r"  r  r  r   r   r   r   <module>   s   
3	]
&
#<
#
d
(
0 
<
R

?G
 