
    ͑ix                       S SK Jr  S SKrS SKrS SKJr  S SKJrJrJ	r	J
r
  S SKrS SKJr  S SKrS SKJr  S SKJr  SS	KJrJr  \(       a  S S
KJrJr  S SKJr  \" S5      r\
" S5      r/ SQr " S S\5      r    SS jrS S jrS!S jr  " S S5      r!\RD                  4         S"S jjr#S#S jr$S$S jr%S%S jr&S%S jr'\RP                  S&S j5       r)  S'           S(S jjr*S)S jr+S%S jr,g)*    )annotationsN)Enum)TYPE_CHECKINGAnyCallableTypeVar)	ParamSpec)_C_ops)core   )LayerHelperin_dynamic_or_pir_mode)	GeneratorSequence)Tensor_InputT_RetT)
	DebugModeTensorCheckerConfigcheck_numerics enable_operator_stats_collection!disable_operator_stats_collectioncollect_operator_statsenable_tensor_checkerdisable_tensor_checkercompare_accuracycheck_layer_numericsc                  (    \ rS rSrSrSrSrSrSrSr	g)	r   8   a  
The DebugMode is a feature that helps to present the state of the TensorCheckerConfig. Each DebugMode has a specific meaning, which is explained below:

- DebugMode.CHECK_NAN_INF_AND_ABORT: This mode prints or saves information about Tensors that contain NaN/Inf and interrupts the program.

- DebugMode.CHECK_NAN_INF: This mode prints or saves critical information about Tensors that contain NaN/Inf but allows the program to continue running.

- DebugMode.CHECK_ALL_FOR_OVERFLOW: This mode checks the output of the FP32 operator and prints or saves information about key Tensors that exceed the FP16 representation range, such as overflow or underflow.

- DebugMode.CHECK_ALL: This mode prints or saves output Tensor key information for all operators.

r      r       N)
__name__
__module____qualname____firstlineno____doc__CHECK_NAN_INF_AND_ABORTCHECK_NAN_INFCHECK_ALL_FOR_OVERFLOW	CHECK_ALL__static_attributes__r"       T/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/amp/debugging.pyr   r   8   s      MIr-   r   c                   ^  SU 4S jjnU$ )a  
This decorator is used to check the numerical values of the layer's input and output data.

Args:
    func (callable): The function to be decorated.

Returns:
    callable: The decorated function.

Raises:
    None.

Example:
    ..  code-block:: python

        >>> import paddle
        >>> class MyLayer(paddle.nn.Layer):
        ...     def __init__(self, dtype):
        ...         super().__init__()
        ...         self._w = self.create_parameter([2, 3], dtype=dtype)
        ...         self._b = self.create_parameter([2, 3], dtype=dtype)
        ...     @paddle.amp.debugging.check_layer_numerics
        ...     def forward(self, x):
        ...         # return 1/x * self._w + self._b   open it you will see the error log
        ...         return x @ self._w + self._b
        ...
        >>> dtype = 'float32'
        >>> x = paddle.rand([10, 2, 2], dtype=dtype) # type: ignore[arg-type]
        >>> model = MyLayer(dtype)
        >>> x[0] = float(0)
        >>> loss = model(x)
        >>> adam = paddle.optimizer.Adam(parameters=model.parameters())
        >>> loss.backward()
        >>> adam.step()

        >>> # error log
        >>> # [PRECISION] [ERROR] in [device=gpu:0, op=divide, tensor=, dtype=fp32], numel=40, num_nan=0, num_inf=4, num_zero=0, max=inf, min=1.048930e+00, mean=inf
        >>> # Traceback (most recent call last):
        >>> #   File "tmp.py", line 16, in <module>
        >>> #     loss = model(x)
        >>> #   File "/paddle/nn/layer/layers.py", line 1254, in __call__
        >>> #     return self.forward(*inputs, **kwargs)
        >>> #   File "/paddle/amp/debugging.py", line 116, in wrapper
        >>> #     out_data = func(self, *modified_args, **kwargs)
        >>> #   File "test.py", line 10, in forward
        >>> #     return 1/x *  self._w+ self._b
        >>> # RuntimeError: (PreconditionNotMet) There are NAN or INF (num_nan=0, num_inf=4, num_zero=0) in [device=gpu:0, op=divide, tensor=, dtype=fp32].
c                (  > U(       a  US   n[        U[        R                  5      (       d  [        S5      eSUl        [        U5      n[        R                  " US5      US'   T" U /UQ70 UD6n[        R                  " US5      nU$ [        S5      e)Nr   z)First input of this layer must be tensor.Fr    zNo elements found in args.)	
isinstancepaddler   RuntimeErrorstop_gradientlistr
   enable_check_model_nan_infdisable_check_model_nan_inf)selfargskwargs
start_datamodified_argsout_dataoutfuncs          r.   wrapper%check_layer_numerics.<locals>.wrapper   s    aJj&--88"#NOO',J$ JM%@@QOM!D;=;F;H44XqACJ;<<r-   )r9   z_InputT.argsr:   z_InputT.kwargsreturnr   r"   )r?   r@   s   ` r.   r   r   N   s    h( Nr-   c                    U bh  [        U [        [        45      (       aB  SR                  S U  5       5      n[        R
                  R                  R                  U5        g [        S5      eg )N,c              3  $   #    U  H  ov   M     g 7fNr"   .0values     r.   	<genexpr>&set_checked_op_list.<locals>.<genexpr>   s     $HuU   z%checked_op_list must be list or tuple)	r1   r5   tuplejoinr2   baser   set_checked_op_list
ValueError)checked_op_listcheck_op_lists     r.   rP   rP      sV    "oe}55HH$H$HHMKK00?DEE #r-   c                    U bh  [        U [        [        45      (       aB  SR                  S U  5       5      n[        R
                  R                  R                  U5        g [        S5      eg )NrD   c              3  $   #    U  H  ov   M     g 7frF   r"   rG   s     r.   rJ   &set_skipped_op_list.<locals>.<genexpr>   s     #GeErL   z%skipped_op_list must be list or tuple)	r1   r5   rM   rN   r2   rO   r   set_skipped_op_listrQ   )skipped_op_listskip_op_lists     r.   rW   rW      sV    "oe}5588#G#GGLKK00>DEE #r-   c                     \ rS rSr% SrSrS\S'   S\S'   S\S	'   S
\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   \R                  SSSSS4             S S jjr	S!S jr
S"S jrS#S jrS$S jrS$S jrSrg)%r      a5  
The purpose of this class is to collect the configuration for checking NaN and Inf values in the tensors of a module or operator. It takes the following arguments:

Args:
    enable(bool): Indicating whether to enable the detection of NaN and Inf values in tensors. The default value is False, which means that these tools will not be used.

    debug_mode(DebugMode, optional): A parameter that determines the type of debugging to be used. Default is DebugMode.CHECK_NAN_INF_AND_ABORT.

    output_dir(string|None, optional): The path to store collected data. If this parameter is set to None, the data will be printed to the terminal. Default is None.

    checked_op_list(list|tuple|None, optional): Specifies a list of operators that need to be checked during program execution, for example, checked_op_list=['elementwise_add', 'conv2d'], indicating that the output results of elementwise_add and conv2d should be checked for nan/inf during program execution. Default is None.

    skipped_op_list(list|tuple|None, optional): Specifies a list of operators that do not need to be checked during program execution, for example, skipped_op_list=['elementwise_add', 'conv2d'], indicating that the output results of elementwise_add and conv2d should not be checked for nan/inf during program execution. None is None.

    debug_step(list|tuple|None, optional): A list or tuple used primarily for nan/inf checking during model training. For example, debug_step=[1,5] indicates that nan/inf checking should only be performed on model training iterations 1 to 5. Default is None.

    stack_height_limit(int, optional): An integer value specifying the maximum depth of the call stack. This feature supports printing the call stack at the error location. Currently, only enabling or disabling call stack printing is supported. If you want to print the corresponding C++ call stack when NaN is detected in GPU Kernel, set stack_height_limit to 1, otherwise set it to 0. Default is 1.

Examples:

    ..  code-block:: python

        >>> import paddle

        >>> checker_config = paddle.amp.debugging.TensorCheckerConfig(enable=True, debug_mode=paddle.amp.debugging.DebugMode.CHECK_NAN_INF)
        >>> paddle.amp.debugging.enable_tensor_checker(checker_config)

        >>> x = paddle.to_tensor([1, 0, 3], place=paddle.CPUPlace(), dtype='float32', stop_gradient=False)
        >>> y = paddle.to_tensor([0.2, 0, 0.5], place=paddle.CPUPlace(), dtype='float32')
        >>> res = paddle.pow(x, y)
        >>> paddle.autograd.backward(res, retain_graph=True)
        >>> paddle.amp.debugging.disable_tensor_checker()

        >>> # [PRECISION] [ERROR] in [device=cpu, op=elementwise_pow_grad, tensor=, dtype=fp32], numel=3, num_nan=1, num_inf=0, num_zero=0, max=2.886751e-01, min=2.000000e-01, mean=-nan

        >>> # when DebugMode.CHECK_NAN_INF_AND_ABORT and stack_height_limit = 1
        >>> # Traceback (most recent call last):
        >>> #     res = paddle.pow(x, y)
        >>> #   File "/usr/local/lib/python3.8/dist-packages/paddle/tensor/math.py", line 447, in pow
        >>> #     return _C_ops.elementwise_pow(x, y)

r   intcurrent_step_idboolenabler   
debug_mode
str | None
output_dirSequence[str] | NonerR   rX   Sequence[int] | None
debug_stepstack_height_limitz
int | None
start_stepend_stepseedinitial_seedNr    c                   Xl         X l        X0l        X@l        XPl        X`l        Xpl        S U l        S U l        SU l	        SU l
        Ub  [        U[        [        45      (       ap  [        U R
                  5      S:X  a   U R
                  S   U R
                  S   :  d   eU R
                  u  U l        U l        [        U R                  S5      U l        O[!        S5      e["        R$                  " 5       (       aO  ['        ["        R(                  " 5       5       H,  n["        R*                  " U5      R                  5       U l
        M.     Oh["        R,                  " 5       (       aN  ['        ["        R.                  " 5       5       H,  n["        R0                  " U5      R                  5       U l
        M.     ["        R2                  " 5       R                  5       U l
        U R                  R4                  [6        R8                  ;  a%  [!        SU R                  [6        R8                  5      e[;        U R                  5        [=        U R                  5        U R                   (       a  U R?                  U R                   5        g g )N{   r   r    r   z debug_step must be list or tuplezdebug_mode in DebugMode) r_   r`   rb   rR   rX   re   rf   rg   rh   ri   rj   r1   rM   r5   lenmaxrQ   r   is_compiled_with_cudarangeget_cuda_device_countdefault_cuda_generatoris_compiled_with_xpuget_xpu_device_countdefault_xpu_generatordefault_cpu_generatornamer   __members__rP   rW   	_set_seed)	r8   r_   r`   rb   rR   rX   re   rf   is	            r.   __init__TensorCheckerConfig.__init__   s    $$..$"4	 !*udm44(A-*T__Q-??@ 26."%dooq"9 !CDD%%''45578$($?$?%,. ! 9 &&((44467$($>$>q$A$N$N$P! 8 !668EEG ??y'<'<<)%%  	D001D001;;NN4;;' r-   c                   U R                   U R                  :w  a  U R                   U l        U R                  [        R                  " [        R                  5      R
                  :  d  U R                  S:  a  [        S5        SU l        [        R                  " U R                  5        [        R                  R                  U R                  5        [        R                  " U R                  5        [        SU R                  5        [        R                  " 5       (       a%  [        R                  " SU05        [        SU5        g g )Nr   z.[Warning: Seed must be between 0 and 2**32 - 1rl   z(AMP Debugging TensorCheckerConfig: seed FLAGS_cudnn_deterministicz@AMP Debugging TensorCheckerConfig: FLAGS_cudnn_deterministic is )rj   ri   npiinfouint32rn   printr2   randomr   ro   	set_flags)r8   flags     r.   ry   TensorCheckerConfig._set_seed(  s    		)))DI99rxx		*...$))a-BCDI 	DII
		tyy!DII 	8$))D %%''94@AR (r-   c                   [         R                  " SU05        U(       a  [         R                  " SU R                  R                  05        U R                  b3  [         R
                  R                  R                  U R                  5        [        U R                  [        5      (       a4  [         R
                  R                  R                  U R                  5        g [        S5      eg )NFLAGS_check_nan_infFLAGS_check_nan_inf_levelzstack_height_limit must be int)r2   r   r`   rI   rb   rO   r   set_nan_inf_debug_pathr1   rf   r\   set_nan_inf_stack_limitrQ   )r8   
check_flags     r.   _set_envTensorCheckerConfig._set_env@  s    /<=,doo.C.CD
 *  77H $11C99  88++ !!ABB! r-   c                   U R                   (       aq  U R                  bc  U R                  bV  U R                  [        R                  :  d  [        R                  U R                  :  a  g[        =R                  S-  sl        gg)NFr    T)r_   rg   rh   r   r]   r8   s    r.   update_and_check_step_id,TensorCheckerConfig.update_and_check_step_idT  s[    ;;*t}}/HOO&9&I&II*::dmmK '771<7r-   c                ^    U R                   (       a  U R                  U R                   5        g g rF   )r_   r   r   s    r.   start_check_nan_inf'TensorCheckerConfig.start_check_nan_infa  s    ;;MM$++& r-   c                &    U R                  S5        g )NF)r   r   s    r.   stop_check_nan_inf&TensorCheckerConfig.stop_check_nan_infe  s    er-   )rR   r`   re   r_   rh   rj   rb   ri   rX   rf   rg   )r_   r^   r`   r   rb   ra   rR   rc   rX   rc   re   rd   rf   r\   )r   r\   rB   None)r   r\   rB   r   )rB   r^   rB   r   )r#   r$   r%   r&   r'   r]   __annotations__r   r(   r{   ry   r   r   r   r   r,   r"   r-   r.   r   r      s    )X OSL))))$$
I
 !* A A!%0404+/"#>(>( >( 	>(
 .>( .>( )>(  >(@0C('r-   r   c           
     ,   SnSn[        5       (       a%  [        R                  " U UUUR                  UU5      $ [	        S0 [        5       D6nUR                  SS9nUR                  SS9nUR                  SSU 0UUUR                  UUS.U/U/S	.S
9  Xx4$ )a  
This function is used to debugging a tensor, finding the number of NaNs, Infs and zeros in the tensor.

Args:
    tensor(Tensor): The target tensor to check.
    op_type(str): The OP or API name which produce the target tensor.
    var_name(str): The name of target tensor.
    debug_mode(paddle.amp.debugging.DebugMode, optional): The mode of debugging to be used. Default is DebugMode.CHECK_NAN_INF_AND_ABORT.

Returns:
    (Tensor, Tensor): A tuple of tensors containing

    - **stats** (Tensor): Returns the number of NaNs, Infs and zeros of input tensor. The shape is [3] and dtype is int64.
    - **values** (Tensor): Returns the maximum, minimum and mean value of input tensor. The shape is [3] and dtype is float.

Examples:

    ..  code-block:: python

        >>> import paddle

        >>> checker_config = paddle.amp.debugging.TensorCheckerConfig(
        ...     enable=True, debug_mode=paddle.amp.debugging.DebugMode.CHECK_NAN_INF)

        >>> x = paddle.to_tensor([1, 0, 3], place=paddle.CPUPlace(), dtype='float32')
        >>> y = paddle.to_tensor([0.2, 0, 0.5], place=paddle.CPUPlace(), dtype='float32')
        >>> res = paddle.pow(x, y)
        >>> paddle.amp.debugging.check_numerics(res, "pow", "res")

 r   int64)dtypefloattensor)op_typevar_namecheck_nan_inf_levelrf   rb   )statsvalues)typeinputsattrsoutputs)r   )r   r
   r   rI   r   locals"create_variable_for_type_inference	append_op)	r   r   r   r`   rf   rb   helperr   r   s	            r.   r   r   i  s    H J$$
 	
 6VX6F55G5DE66W6EF
f
  #-#3#3"4$
 !'fX6   =r-   c                 :    [         R                  " S/5      n U S   $ )NFLAGS_low_precision_op_list)r2   	get_flags)flagss    r.   _get_operator_stats_flagr     s"    ;<=E.//r-   c                   [        SR                  S5      5        Sn[        SR                  S5      SSR                  S5      SSR                  S	5      SSR                  S
5      SSR                  S5      5	        U b  [        U [        5      (       a  [	        U 5       H  nX   n[        U[
        5      (       a  UnOB[        U[        5      (       a  UR                  S5      nO[        SU S[        U5       S35      e[        SUS SUS   S SUS   S SUS   S SUS   S 3
5        US-  nM     [        SR                  S[        U5      -   S-   5      5        g)a|  
Parse and print the stats of operators, mainly including the calls of
dtypes such as different fp32, fp16, bf16 and others.

Args:
    op_count_dict(dict): a dict to record the number of calls for different
        operator and dtype. An example is
        {'conv2d': '1,0,0,0', 'elementwise_add': '1,0,0,0'} or
        {'conv2d': [1, 0, 0, 0], 'elementwise_add': [1, 0, 0, 0]}.
z
<{:-^120}>z	 op list r   z<{:-^40}z	 Op Name |z{:-^17}z FP16 Calls z BF16 Calls z FP32 Callsz{:-^17}>z Other Calls NrD   zInput z/ is expected to be a list of str, but received .z  z<40z|  z<17r    r   r!   z<{:-^120}>
z op count:  )
r   formatr1   dictsortedr5   strsplitrQ   r   )op_count_dict	total_opsr   rI   calleds        r.   _print_operator_statsr     ss    
,

k
*+I	+&(('/*
  Zt%D%Dm,G!*E%&&E3''S) UG#RSWX]S^R__`a  WSMVAYsO3vayoSPQSVWZ[abc[dehZij NI - 
.

I > D
EFr-   c                     [         R                  R                  R                  5         [         R                  " SS05        g)a  
Enable to collect the number of operators for different data types.
The statistical data are categorized according to four data types, namely
float32, float16, bfloat16 and others. This function is used in pair with
the corresponding disable function.

Examples:

    ..  code-block:: python

        >>> # doctest: +REQUIRES(env:GPU)
        >>> import paddle
        >>> paddle.device.set_device('gpu')

        >>> conv = paddle.nn.Conv2D(3, 2, 3)
        >>> x = paddle.rand([10, 3, 32, 32])

        >>> paddle.amp.debugging.enable_operator_stats_collection()
        >>> # AMP list including cast, conv2d, elementwise_add, reshape
        >>> with paddle.amp.auto_cast(enable=True, level='O2'):
        ...     out = conv(x)
        >>> # Print to the standard output.
        >>> paddle.amp.debugging.disable_operator_stats_collection()
        >>> # <------------------------------------------------------- op list -------------------------------------------------------->
        >>> # <--------------- Op Name ---------------- | -- FP16 Calls --- | -- BF16 Calls --- | --- FP32 Calls--- | -- Other Calls -->
        >>> #   cast                                    |  1                |  0                |  2                |  0
        >>> #   conv2d                                  |  1                |  0                |  0                |  0
        >>> #   elementwise_add                         |  0                |  0                |  1                |  0
        >>> #   reshape                                 |  0                |  0                |  1                |  0
        >>> # <----------------------------------------------------- op count: 4 ------------------------------------------------------>

r   r    N)r2   rO   r   clear_low_precision_op_listr   r"   r-   r.   r   r     s/    D KK002
3Q78r-   c                     [        5       (       d  g[        R                  R                  R	                  5       n [        U 5        [        R                  " SS05        g)a  
Disable the collection the number of operators for different data types.
This function is used in pair with the corresponding enable function.
The statistical data are categorized according to four data types, namely
float32, float16, bfloat16 and others, and will be printed after the
function call.

Examples:

    ..  code-block:: python

        >>> import paddle

        >>> conv = paddle.nn.Conv2D(3, 2, 3)
        >>> x = paddle.rand([10, 3, 32, 32])

        >>> paddle.amp.debugging.enable_operator_stats_collection()
        >>> # AMP list including cast, conv2d, elementwise_add, reshape
        >>> with paddle.amp.auto_cast(enable=True, level='O2'):
        ...     out = conv(x)
        >>> # Print to the standard output.
        >>> paddle.amp.debugging.disable_operator_stats_collection()
        >>> # <------------------------------------------------------- op list -------------------------------------------------------->
        >>> # <--------------- Op Name ---------------- | -- FP16 Calls --- | -- BF16 Calls --- | --- FP32 Calls--- | -- Other Calls -->
        >>> #   cast                                    |  1                |  0                |  2                |  0
        >>> #   conv2d                                  |  1                |  0                |  0                |  0
        >>> #   elementwise_add                         |  0                |  0                |  1                |  0
        >>> #   reshape                                 |  0                |  0                |  1                |  0
        >>> # <----------------------------------------------------- op count: 4 ------------------------------------------------------>

Nr   r   )r   r2   rO   r   get_low_precision_op_listr   r   )r   s    r.   r   r     sE    @ $%%KK$$>>@M-(
3Q78r-   c               #  <   #    [        5         Sv   [        5         g7f)a9  
The context switcher to enable to collect the number of operators for
different data types. The statistical data are categorized according
to four data types, namely float32, float16, bfloat16 and others, and
will be printed when exiting the context.

Examples:

    ..  code-block:: python

        >>> import paddle

        >>> conv = paddle.nn.Conv2D(3, 2, 3)
        >>> x = paddle.rand([10, 3, 32, 32])

        >>> with paddle.amp.debugging.collect_operator_stats():
        ...     # AMP list including cast, conv2d, elementwise_add, reshape
        ...     with paddle.amp.auto_cast(enable=True, level='O2'):
        ...         out = conv(x)
        >>> # Print to the standard output.
        >>> # <------------------------------------------------------- op list -------------------------------------------------------->
        >>> # <--------------- Op Name ---------------- | -- FP16 Calls --- | -- BF16 Calls --- | --- FP32 Calls--- | -- Other Calls -->
        >>> #   cast                                    |  1                |  0                |  2                |  0
        >>> #   conv2d                                  |  1                |  0                |  0                |  0
        >>> #   elementwise_add                         |  0                |  0                |  1                |  0
        >>> #   reshape                                 |  0                |  0                |  1                |  0
        >>> # <----------------------------------------------------- op count: 4 ------------------------------------------------------>

N)r   r   r"   r-   r.   r   r   .  s     > %&	%'s   c                r    USL d   S5       e[         R                  R                  R                  U UUUSS9  g)a  
This is a precision comparison tool that can be used to compare log data of float16 and float32.

Args:
    dump_path(str): The path of the running log, such as the log for execution using the float32 data type.
    another_dump_path(str): the path of another running log ,such as the log for execution using the float16 data type.
    output_filename(str): the excel file name of compare output.
    loss_scale(float, optional): the loss_scale during the training phase. Default is 1.
    dump_all_tensors(bool, optional): dump all tensor, It is currently not support. Default is False.

Examples:

    ..  code-block:: python

        >>> import paddle
        >>> from paddle.base import core
        >>> try:
        ...     import xlsxwriter as xlw
        ... except ImportError:
        ...     import subprocess
        ...     subprocess.check_call(
        ...         ['python', '-m', 'pip', 'install', 'xlsxwriter==3.0.9']
        ...     )
        ...     import xlsxwriter as xlw
        ...     if core.is_compiled_with_cuda():
        ...         paddle.set_flags(
        ...             {"FLAGS_check_nan_inf": 1, "FLAGS_check_nan_inf_level": 3}
        ...         )
        ...         path = "workerlog_log_dir"
        ...         paddle.base.core.set_nan_inf_debug_path(path)
        ...         x = paddle.to_tensor(
        ...             [2, 3, 4, 0], dtype="float32"
        ...         )
        ...         y = paddle.to_tensor(
        ...             [1, 5, 2, 0], dtype="float32"
        ...         )
        ...         z1 = x + y
        ...         out_excel = "compare_accuracy_out_excel.csv"
        ...         paddle.amp.debugging.compare_accuracy(
        ...             path, path, out_excel, loss_scale=1, dump_all_tensors=False
        ...         )
FzIt is currently not supported.)dump_all_tensorsN)r2   ampaccuracy_comparer   )	dump_pathanother_dump_pathoutput_filename
loss_scaler   s        r.   r   r   R  sE    b u$F&FF$
JJ00 1 r-   c                p    U R                  5       (       a  U R                  5         gU R                  5         g)aZ  
The enable_tensor_checker(checker_config) function enables model-level accuracy checking and is used in combination with disables_tensor_checker() to achieve model-level precision checking by checking the output Tensors of all operators within the specified range.

Args:
    checker_config(TensorCheckerConfig): Checker_config is to collect the configuration for checking NaN and Inf values in the tensors of a module or operator.

Note:
    If disable_tensor_checker() is called before backward(), the gradient operator will not be checked.
    If disable_tensor_checker() is called before optimizer.step(), the optimizer and other weight update related operators will not be checked.

Examples:

    ..  code-block:: python

        >>> import paddle

        >>> checker_config = paddle.amp.debugging.TensorCheckerConfig(enable=True, debug_mode=paddle.amp.debugging.DebugMode.CHECK_NAN_INF)
        >>> paddle.amp.debugging.enable_tensor_checker(checker_config)

        >>> x = paddle.to_tensor([1, 0, 3], place=paddle.CPUPlace(), dtype='float32', stop_gradient=False)
        >>> y = paddle.to_tensor([0.2, 0, 0.5], place=paddle.CPUPlace(), dtype='float32')
        >>> res = paddle.pow(x, y)
        >>> paddle.autograd.backward(res, retain_graph=True)
        >>> paddle.amp.debugging.disable_tensor_checker()
        >>> #[PRECISION] [ERROR] in [device=cpu, op=elementwise_pow_grad, tensor=, dtype=fp32], numel=3, num_nan=1, num_inf=0, num_zero=0, max=2.886751e-01, min=2.000000e-01, mean=-nan

        >>> # when DebugMode.CHECK_NAN_INF_AND_ABORT and stack_height_limit = 1
        >>> # Traceback (most recent call last):
        >>> #   File "tp.py", line 8, in <module>
        >>> #     res = paddle.pow(x, y)
        >>> #   File "/usr/local/lib/python3.8/dist-packages/paddle/tensor/math.py", line 447, in pow
        >>> #     return _C_ops.elementwise_pow(x, y)

N)r   r   r   )checker_configs    r.   r   r     s,    F ..00**,))+r-   c                 4    [         R                  " SS05        g)ah  
disable_tensor_checker() is used to disable accuracy checking, and is used together with enable_tensor_checker(config) to achieve model-level precision checking by checking the output Tensors of all operators within the specified range.

Note:
    If disable_tensor_checker() is called before backward(), the gradient operator will not be checked;
    If disable_tensor_checker() is called before optimizer.step(), the optimizer and other weight update related operators will not be checked.

Examples:

    .. code-block:: python

        >>> import paddle

        >>> checker_config = paddle.amp.debugging.TensorCheckerConfig(enable=True, debug_mode=paddle.amp.debugging.DebugMode.CHECK_NAN_INF)
        >>> paddle.amp.debugging.enable_tensor_checker(checker_config)

        >>> x = paddle.to_tensor([1, 0, 3], place=paddle.CPUPlace(), dtype='float32', stop_gradient=False)
        >>> y = paddle.to_tensor([0.2, 0, 0.5], place=paddle.CPUPlace(), dtype='float32')
        >>> res = paddle.pow(x, y)
        >>> paddle.autograd.backward(res, retain_graph=True)
        >>> paddle.amp.debugging.disable_tensor_checker()
        >>> # [PRECISION] [ERROR] in [device=cpu, op=elementwise_pow_grad, tensor=, dtype=fp32], numel=3, num_nan=1, num_inf=0, num_zero=0, max=2.886751e-01, min=2.000000e-01, mean=-nan

        >>> # when DebugMode.CHECK_NAN_INF_AND_ABORT and stack_height_limit = 1
        >>> # Traceback (most recent call last):
        >>> #      res = paddle.pow(x, y)
        >>> #    File "/usr/local/lib/python3.8/dist-packages/paddle/tensor/math.py", line 447, in pow
        >>> #      return _C_ops.elementwise_pow(x, y)

r   r   N)r2   r   r"   r-   r.   r   r     s    > +Q/0r-   )r?   Callable[_InputT, _RetT]rB   r   )rR   rc   rB   r   )rX   rc   rB   r   )
r   r   r   r   r   r   r`   r   rB   ztuple[Tensor, Tensor])rB   r   )r   zdict[str, str | list[int]]rB   r   r   )rB   zGenerator[None, None, None])r    F)r   r   r   r   r   r   r   r   r   r^   rB   r   )r   r   rB   r   )-
__future__r   
contextlibr   enumr   typingr   r   r   r   numpyr   typing_extensionsr	   r2   r
   paddle.baser   	frameworkr   r   collections.abcr   r   r   r   r   __all__r   r   rP   rW   r   r(   r   r   r   r   r   contextmanagerr   r   r   r   r"   r-   r.   <module>r      s\   #      '    ;3
I
 ,H
"HHVFFy y@ &==	DDD D 	D
 DN0
(GV#9L%9P  (  (N "888 8 	8
 8 
8v&,R1r-   