a
    Sic                     @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddl	m
  mZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlm Z! ddl"m#Z# ddl"m$Z$ ddl%m&Z' ddl(m)Z) dd Z*dd Z+daddZ,e)dg de'j-dbddZ.e/ Z0de0_1de0_2de0_3de0_4e#j5dd Z6e#j5dd  Z7d!d" Z8e#j5d#d$ Z9d%d& Z:d'd( Z;d)d* Z<dcd+d,Z=d-d. Z>G d/d0 d0ej?Z@G d1d2 d2ej?ZAd3d4 ZBd5d6 ZCd7d8 ZDG d9d: d:ej?ZEG d;d< d<ej?ZFddd=d>ZGG d?d@ d@ejHZIG dAdB dBej?ZJG dCdD dDej?ZKdedEdFZLejMejNejOejPejQe!jRejSdGZTdHdI ZUdfdKdLZVdMdN ZWdOdP ZXdQdR ZYej5dSdT ZZej5dUdV Z[dWdX Z\dYdZ Z]d[d\ Z^dgd]d^Z_d_d` Z`dS )hz!Utilities for unit-testing Keras.    N)backend)layers)models)base_layer_utils)adadelta)adagrad)adam)adamax)gradient_descent)nadam)rmsprop)tf_contextlib)
tf_inspect)	test_util)keras_exportc                 C   s   t j| | d S N)nptestingassert_array_equalactualexpected r   Z/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/testing_infra/test_utils.pystring_test3   s    r   c                 C   s   t jj| |ddd d S )NgMbP?gư>)rtolatol)r   r   assert_allcloser   r   r   r   numeric_test7   s    r   c           
      C   s   |durt j| | | }d| t j|f|  }t jjd||fd}t j|f| t jd}t|D ]&}	|||	  t jjdd|d ||	< qh|d|  |d|  f|| d || d ffS )a  Generates test data to train a model on.

    Args:
      train_samples: Integer, how many training samples to generate.
      test_samples: Integer, how many test samples to generate.
      input_shape: Tuple of integers, shape of the inputs.
      num_classes: Integer, number of classes for the data and targets.
      random_seed: Integer, random seed used by numpy to generate data.

    Returns:
      A tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
    N   r   )size)dtypeg      ?)locscaler    )r   randomseedrandintzerosfloat32rangenormal)
Ztrain_samplesZtest_samplesinput_shapenum_classesrandom_seedZ
num_sample	templatesyxir   r   r   get_test_data;   s    r2   z#keras.__internal__.utils.layer_test)v1Tc           !         sB  |du r|du rt d|s d}t|}t|D ]"\}}|du r0tjdd||< q0dtj| }|dd dkr||d	8 }||}n|du r|j}|du r|j}|du r|}t	
|t	jkr|r|j}qt}n|r|j}nt} pi  f i  }|dur&|j|kr&td
j|j| f |	dur:||	 | }|| dtjv rt| d< f i  }tj|dd |d|}t||krtdjt|| f  fdd}|dur|t	||j t|}t| t	|! }|"t	j#||d}|$|}|j}||| ||j| |j|jkrttdj|j|j f |dur||| |% }tj&||
}|j'r| }|| |$|}||| | }|r,t|}t(j)dur|j*dddgt+ d n|j*dddgd |,|| |% }||d< |j-&|}|	dur\||	 t. }|/tj|dd |d |/| || |$|}|j}t0||D ]6\}} |dur|| krtdj|| f q|dur||| |% }tj.&||
}|j'r>| }|| |$|}||| |S )a  Test routine for a layer with a single input and single output.

    Args:
      layer_cls: Layer class object.
      kwargs: Optional dictionary of keyword arguments for instantiating the
        layer.
      input_shape: Input shape tuple.
      input_dtype: Data type of the input data.
      input_data: Numpy array of input data.
      expected_output: Numpy array of the expected output.
      expected_output_dtype: Data type expected for the output.
      expected_output_shape: Shape tuple for the expected shape of the output.
      validate_training: Whether to attempt to validate training on this layer.
        This might be set to False for non-differentiable layers that output
        string or integer values.
      adapt_data: Optional data for an 'adapt' call. If None, adapt() will not
        be tested for this layer. This is only relevant for PreprocessingLayers.
      custom_objects: Optional dictionary mapping name strings to custom objects
        in the layer class. This is helpful for testing custom layers.
      test_harness: The Tensorflow test, if any, that this function is being
        called in.
      supports_masking: Optional boolean to check the `supports_masking`
        property of the layer. If None, the check will not be performed.

    Returns:
      The output data (Numpy array) returned by the layer, for additional
      checks to be done by the calling code.

    Raises:
      ValueError: if `input_shape is None`.
    Nzinput_shape is Noner(         
      float      ?zbWhen testing layer %s, the `supports_masking` property is %rbut expected to be %r.
Full kwargs: %sweights)shaper!   zcWhen testing layer %s, for input %s, found output dtype=%s but expected to find %s.
Full kwargs: %sc                    s   t | t |kr(tdj||  f t| |D ]\\}}t|tjjjrP|j	}t|tjjjrf|j	}|dur2||kr2tdj||  f q2dS )zNAsserts that the output shape from the layer matches the actual
        shape.zcWhen testing layer %s, for input %s, found output_shape=%s but expected to find %s.
Full kwargs: %sN)
lenAssertionError__name__zip
isinstancetfcompatr3   	Dimensionvalue)r   r   expected_dim
actual_dimkwargs	layer_clsr0   r   r   assert_shapes_equal   s"    z'layer_test.<locals>.assert_shapes_equalzcWhen testing layer %s, for input %s, found output_dtype=%s but expected to find %s.
Full kwargs: %sr   mseacc)weighted_metricsrun_eagerly)rM   batch_input_shapezWhen testing layer %s **after deserialization**, for input %s, found output_shape=%s but expected to find inferred shape %s.
Full kwargs: %s)1
ValueErrorlist	enumerater   r$   r&   astyper;   r!   rA   as_dtypestringassertAllEqualr   assertAllCloser   supports_maskingr=   r>   adaptget_weightsset_weightsr   
getargspec__init__r   Inputr   TensorShaper   Modeltuplecompute_output_shapeas_listcompute_output_signature
TensorSpecpredict
get_configfrom_configr:   _thread_local_datarN   compileshould_run_eagerlytrain_on_batch	__class__
Sequentialaddr?   )!rI   rH   r+   input_dtype
input_dataZexpected_outputZexpected_output_dtypeZexpected_output_shapeZvalidate_trainingZ
adapt_datacustom_objectsZtest_harnessrX   Zinput_data_shaper1   eassert_equallayerr:   r/   rJ   modelZcomputed_output_shapeZcomputed_output_signatureZactual_outputZactual_output_shapemodel_configZrecovered_modeloutputlayer_weightslayer_configrE   rF   r   rG   r   
layer_testZ   s$   0






















r{   c                 c   s*   t j}z| t _| V  W |t _n|t _0 dS )zProvides a scope within which the model type to test is equal to `value`.

    The model type gets restored to its original value upon exiting the scope.

    Args:
       value: model type value

    Yields:
      The provided value.
    N)ri   
model_typerD   previous_valuer   r   r   model_type_scoped  s
    r   c                 c   s*   t j}z| t _| V  W |t _n|t _0 dS )a>  Provides a scope within which we compile models to run eagerly or not.

    The boolean gets restored to its original value upon exiting the scope.

    Args:
       value: Bool specifying if we should run models eagerly in the active
         test. Should be True or False.

    Yields:
      The provided value.
    N)ri   rN   r}   r   r   r   run_eagerly_scopey  s
    r   c                   C   s    t jdu rtdt jot S )z@Returns whether the models we are testing should be run eagerly.NziCannot call `should_run_eagerly()` outside of a `run_eagerly_scope()` or `run_all_keras_modes` decorator.)ri   rN   rP   rA   executing_eagerlyr   r   r   r   rk     s
    
rk   c                 k   sB   t j}t j}z"| t _|t _dV  W |t _|t _n|t _|t _0 dS )aA  Provides a scope within which the savde model format to test is `value`.

    The saved model format gets restored to its original value upon exiting the
    scope.

    Args:
       value: saved model format value
       **kwargs: optional kwargs to pass to the save function.

    Yields:
      The provided value.
    N)ri   saved_model_formatsave_kwargs)rD   rH   Zprevious_formatZprevious_kwargsr   r   r   saved_model_format_scope  s    r   c                   C   s   t jd u rtdt jS )NzzCannot call `get_save_format()` outside of a `saved_model_format_scope()` or `run_with_all_saved_model_formats` decorator.)ri   r   rP   r   r   r   r   get_save_format  s
    
r   c                   C   s   t jd u rtdt jpi S )NzzCannot call `get_save_kwargs()` outside of a `saved_model_format_scope()` or `run_with_all_saved_model_formats` decorator.)ri   r   rP   r   r   r   r   get_save_kwargs  s
    
r   c                   C   s   t jdu rtdt jS )z*Gets the model type that should be tested.NziCannot call `get_model_type()` outside of a `model_type_scope()` or `run_with_all_model_types` decorator.)ri   r|   rP   r   r   r   r   get_model_type  s
    
r   c                 C   s`   t  }|r$|tj| d|d n|tj| dd |dkrDdnd}|tj||d |S )Nrelu)
activation	input_dimr   r4   sigmoidsoftmax)r   rn   ro   r   Dense)
num_hiddenr,   r   rv   r   r   r   r   get_small_sequential_mlp  s    r   c                 C   sN   t j|fd}t j| dd|}|dkr,dnd}t j||d|}t||S )N)r;   r   r   r4   r   r   )r   r^   r   r   r`   )r   r,   r   inputsoutputsr   r   r   r   get_small_functional_mlp  s
    r   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )SmallSubclassMLPz!A subclass model based small MLP.Fc                    s|   t  jf ddi| || _|| _tj|dd| _|dkr>dnd}tj||d| _| jrdtd| _	| jrxtj
d	d
| _d S )NnameZ
test_modelr   r   r4   r   r   r9   )axis)superr]   use_bnuse_dpr   r   layer_alayer_bDropoutdpBatchNormalizationbn)selfr   r,   r   r   rH   r   rm   r   r   r]     s    zSmallSubclassMLP.__init__c                 K   s4   |  |}| jr| |}| jr*| |}| |S r   )r   r   r   r   r   r   r   r   rH   r0   r   r   r   call  s    


zSmallSubclassMLP.call)FFr>   
__module____qualname____doc__r]   r   __classcell__r   r   r   r   r     s    r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )_SmallSubclassMLPCustomBuildz;A subclass model small MLP that uses a custom build method.c                    s&   t    d | _d | _|| _|| _d S r   )r   r]   r   r   r   r,   )r   r   r,   r   r   r   r]     s
    
z%_SmallSubclassMLPCustomBuild.__init__c                 C   s:   t j| jdd| _| jdkr dnd}t j| j|d| _d S )Nr   r   r4   r   r   )r   r   r   r   r,   r   )r   r+   r   r   r   r   build  s    z"_SmallSubclassMLPCustomBuild.buildc                 K   s   |  |}| |S r   )r   r   r   r   r   r   r     s    
z!_SmallSubclassMLPCustomBuild.callr>   r   r   r   r]   r   r   r   r   r   r   r   r     s   r   c                 C   s
   t | |S r   )r   r   r,   r   r   r   get_small_subclass_mlp  s    r   c                 C   s
   t | |S r   )r   r   r   r   r   (get_small_subclass_mlp_with_custom_build  s    r   c                 C   sd   t  }|dkrt| |S |dkr*t| |S |dkr>t| ||S |dkrRt| ||S td|dS )z@Get a small mlp of the model type specified by `get_model_type`.subclasssubclass_custom_build
sequential
functionalUnknown model type {}N)r   r   r   r   r   rP   format)r   r,   r   r|   r   r   r   get_small_mlp!  s    

r   c                       s8   e Zd ZdZ fddZdd Zdd Zdd	 Z  ZS )
_SubclassModelzA Keras subclass model.c                    sb   | dd}t j|i | t|D ]\}}t| | || q&t|| _|dur^| | dS )a  Instantiate a model.

        Args:
          model_layers: a list of layers to be added to the model.
          *args: Model's args
          **kwargs: Model's keyword args, at most one of input_tensor -> the
            input tensor required for ragged/sparse input.
        input_tensorN)	popr   r]   rR   setattr_layer_name_for_ir<   
num_layers_set_inputs)r   model_layersargsrH   r   r1   ru   r   r   r   r]   2  s    

z_SubclassModel.__init__c                 C   s
   d |S )Nzlayer{})r   )r   r1   r   r   r   r   H  s    z _SubclassModel._layer_name_for_ic                 K   s0   |}t | jD ]}t| | |}||}q|S r   )r)   r   getattrr   )r   r   rH   r0   r1   ru   r   r   r   r   K  s
    
z_SubclassModel.callc                 C   s   t d S r   )NotImplementedError)r   r   r   r   rg   R  s    z_SubclassModel.get_config)	r>   r   r   r   r]   r   r   rg   r   r   r   r   r   r   /  s
   r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )_SubclassModelCustomBuildz7A Keras subclass model that uses a custom build method.c                    s"   t  j|i | d | _|| _d S r   )r   r]   
all_layers_layer_generating_func)r   layer_generating_funcr   rH   r   r   r   r]   [  s    z"_SubclassModelCustomBuild.__init__c                 C   s&   g }|   D ]}|| q|| _d S r   )r   appendr   )r   r+   r   ru   r   r   r   r   `  s    z_SubclassModelCustomBuild.buildc                 K   s   |}| j D ]}||}q
|S r   )r   )r   r   rH   r0   ru   r   r   r   r   f  s    

z_SubclassModelCustomBuild.callr   r   r   r   r   r   X  s   r   c                    s  |du rt  }|dkrBd}|s"|r4tj||||d}t ||dS |dkrb fdd}t||dS |d	krtj|d}	|r|	tj||||d
  D ]}
|	|
 q|	S |dkr|st	dtj||||d}|} D ]}
|
|}qtj
|||dS t	d|dS )aE  Builds a model from a sequence of layers.

    Args:
      model_layers: The layers used to build the network.
      input_shape: Shape tuple of the input or 'TensorShape' instance.
      input_dtype: Datatype of the input.
      name: Name for the model.
      input_ragged: Boolean, whether the input data is a ragged tensor.
      input_sparse: Boolean, whether the input data is a sparse tensor.
      model_type: One of "subclass", "subclass_custom_build", "sequential", or
        "functional". When None, defaults to `get_model_type`.

    Returns:
      A Keras model.
    Nr   )r;   r!   raggedsparse)r   r   r   c                      s    S r   r   r   r   r   r   <lambda>      z'get_model_from_layers.<locals>.<lambda>r   r   )r+   r!   r   r   r   zACannot create a functional model from layers with no input shape.r   )r   r   r^   r   r   r   rn   ro   
InputLayerrP   r`   r   )r   r+   rp   r   Zinput_raggedZinput_sparser|   r   r   rv   ru   r   r   r   r   get_model_from_layersm  sZ    
r   c                   @   s   e Zd Zdd Zdd ZdS )Biasc                 C   s   | j dddd| _d S )Nbias)r4   r'   )initializer)
add_weightr   r   r+   r   r   r   r     s    z
Bias.buildc                 C   s
   || j  S r   )r   )r   r   r   r   r   r     s    z	Bias.callN)r>   r   r   r   r   r   r   r   r   r     s   r   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )_MultiIOSubclassModelzMulti IO Keras subclass model.Nc                    s*   t  j|d || _|| _|| _|| _d S )Nr   )r   r]   _shared_input_branch	_branch_a	_branch_b_shared_output_branch)r   branch_abranch_bshared_input_branchshared_output_branchr   r   r   r   r]     s
    z_MultiIOSubclassModel.__init__c                 K   s   | j r$| j D ]}||}q|}|}n$t|tr@|d }|d }n|\}}| jD ]}||}qN| jD ]}||}qb||g}| jr| jD ]}||}q|S )NZinput_1Zinput_2)r   r@   dictr   r   r   r   r   rH   ru   aboutsr   r   r   r     s$    









z_MultiIOSubclassModel.call)NNNr   r   r   r   r   r     s      r   c                       s2   e Zd ZdZd	 fdd	Zdd Zdd Z  ZS )
 _MultiIOSubclassModelCustomBuildz>Multi IO Keras subclass model that uses a custom build method.Nc                    s>   t    || _|| _|| _|| _d | _d | _d | _d | _	d S r   )
r   r]   _shared_input_branch_func_branch_a_func_branch_b_func_shared_output_branch_funcr   r   r   r   )r   Zbranch_a_funcZbranch_b_funcZshared_input_branch_funcZshared_output_branch_funcr   r   r   r]     s    
z)_MultiIOSubclassModelCustomBuild.__init__c                 C   s<   |   r|   | _|  | _|  | _|  r8|  | _d S r   )r   r   r   r   r   r   r   r   r   r   r   r   r      s    


z&_MultiIOSubclassModelCustomBuild.buildc                 K   sz   | j r$| j D ]}||}q|}|}n|\}}| jD ]}||}q2| jD ]}||}qF||f}| jrv| jD ]}||}qh|S r   )r   r   r   r   r   r   r   r   r   	  s    







z%_MultiIOSubclassModelCustomBuild.call)NNr   r   r   r   r   r     s     	r   c                    s>  rd }dd n( d d f} dd  dd t  }|dkr^t S |dkrt fddfddfd	dfd
dS |dkrtd|dkr,r|}D ]}||}q|}|}	n|\}}	 D ]}||}qވD ]}||	}	q||	f}
r D ]}||
}
qt||
S td|dS )a]  Builds a multi-io model that contains two branches.

    The produced model will be of the type specified by `get_model_type`.

    To build a two-input, two-output model:
      Specify a list of layers for branch a and branch b, but do not specify any
      shared input branch or shared output branch. The resulting model will
      apply each branch to a different input, to produce two outputs.

      The first value in branch_a must be the Keras 'Input' layer for branch a,
      and the first value in branch_b must be the Keras 'Input' layer for
      branch b.

      example usage:
      ```
      branch_a = [Input(shape=(2,), name='a'), Dense(), Dense()]
      branch_b = [Input(shape=(3,), name='b'), Dense(), Dense()]

      model = get_multi_io_model(branch_a, branch_b)
      ```

    To build a two-input, one-output model:
      Specify a list of layers for branch a and branch b, and specify a
      shared output branch. The resulting model will apply
      each branch to a different input. It will then apply the shared output
      branch to a tuple containing the intermediate outputs of each branch,
      to produce a single output. The first layer in the shared_output_branch
      must be able to merge a tuple of two tensors.

      The first value in branch_a must be the Keras 'Input' layer for branch a,
      and the first value in branch_b must be the Keras 'Input' layer for
      branch b.

      example usage:
      ```
      input_branch_a = [Input(shape=(2,), name='a'), Dense(), Dense()]
      input_branch_b = [Input(shape=(3,), name='b'), Dense(), Dense()]
      shared_output_branch = [Concatenate(), Dense(), Dense()]

      model = get_multi_io_model(input_branch_a, input_branch_b,
                                 shared_output_branch=shared_output_branch)
      ```
    To build a one-input, two-output model:
      Specify a list of layers for branch a and branch b, and specify a
      shared input branch. The resulting model will take one input, and apply
      the shared input branch to it. It will then respectively apply each branch
      to that intermediate result in parallel, to produce two outputs.

      The first value in the shared_input_branch must be the Keras 'Input' layer
      for the whole model. Branch a and branch b should not contain any Input
      layers.

      example usage:
      ```
      shared_input_branch = [Input(shape=(2,), name='in'), Dense(), Dense()]
      output_branch_a = [Dense(), Dense()]
      output_branch_b = [Dense(), Dense()]


      model = get_multi_io_model(output__branch_a, output_branch_b,
                                 shared_input_branch=shared_input_branch)
      ```

    Args:
      branch_a: A sequence of layers for branch a of the model.
      branch_b: A sequence of layers for branch b of the model.
      shared_input_branch: An optional sequence of layers to apply to a single
        input, before applying both branches to that intermediate result. If
        set, the model will take only one input instead of two. Defaults to
        None.
      shared_output_branch: An optional sequence of layers to merge the
        intermediate results produced by branch a and branch b. If set,
        the model will produce only one output instead of two. Defaults to None.

    Returns:
      A multi-io model of the type specified by `get_model_type`, specified
      by the different branches.
    r   r4   Nr   r   c                      s    S r   r   r   )r   r   r   r     r   z$get_multi_io_model.<locals>.<lambda>c                      s    S r   r   r   )r   r   r   r     r   c                      s    S r   r   r   )r   r   r   r     r   c                      s    S r   r   r   )r   r   r   r     r   r   z>Cannot use `get_multi_io_model` to construct sequential modelsr   r   )r   r   r   rP   r   r`   r   )r   r   r   r   r   r|   Za_and_bru   r   r   r   r   )r   r   r   r   r   get_multi_io_model  sP    R







r   )r   r   r   r	   r   r   sgdc              
   K   sD   zt |  f i |W S  ty>   td| tt  Y n0 dS )a  Get the v2 optimizer requested.

    This is only necessary until v2 are the default, as we are testing in Eager,
    and Eager + v1 optimizers fail tests. When we are in v2, the strings alone
    should be sufficient, and this mapping can theoretically be removed.

    Args:
      name: string name of Keras v2 optimizer.
      **kwargs: any kwargs to pass to the optimizer constructor.

    Returns:
      Initialized Keras v2 optimizer.

    Raises:
      ValueError: if an unknown name was passed.
    z;Could not find requested v2 optimizer: {}
Valid choices: {}N)_V2_OPTIMIZER_MAPKeyErrorrP   r   rQ   keys)r   rH   r   r   r   get_v2_optimizer  s    r    c                    s4   t jj st  r"dd | D S  fdd| D S )zEReturns expected metric variable names given names and prefix/suffix.c                 S   s   g | ]}|d  qS z:0r   .0nr   r   r   
<listcomp>  r   z6get_expected_metric_variable_names.<locals>.<listcomp>c                    s   g | ]}|  d  qS r   r   r   name_suffixr   r   r     r   )rA   __internal__tf2enabledr   )	var_namesr   r   r   r   "get_expected_metric_variable_names  s    r   c                 C   s
   t | dS )z=Decorator for enabling the layer V2 dtype behavior on a test.T_set_v2_dtype_behaviorfnr   r   r   enable_v2_dtype_behavior  s    r   c                 C   s
   t | dS )z>Decorator for disabling the layer V2 dtype behavior on a test.Fr   r   r   r   r   disable_v2_dtype_behavior  s    r   c                    s(   t  fdd}tjj|S )zCReturns version of 'fn' that runs with v2 dtype behavior on or off.c                     s0   t j} t _z| i |W |t _S |t _0 d S r   )r   V2_DTYPE_BEHAVIOR)r   rH   Zv2_dtype_behaviorr   r   r   r   wrapper  s    z'_set_v2_dtype_behavior.<locals>.wrapper)	functoolswrapsrA   r   	decoratormake_decorator)r   r   r  r   r  r   r     s    r   c                 c   sL   | rt j rd}nd}t | dV  W d   n1 s>0    Y  dS )&Uses gpu when requested and available.z/device:GPU:0z/device:CPU:0N)rA   testis_gpu_availabledevice)should_use_gpudevr   r   r   r
    s
    r
  c                   c   s4   t dd dV  W d   n1 s&0    Y  dS )r  T)r  N)r
  r   r   r   r   use_gpu  s    r  c                    s    fdd}|S )a  Generate class-level decorator from given method-level decorator.

    It is expected for the given decorator to take some arguments and return
    a method that is then called on the test method to produce a decorated
    method.

    Args:
      decorator: The decorator to apply.
      *args: Positional arguments
      **kwargs: Keyword arguments
    Returns: Function that will decorate a given classes test methods with the
      decorator.
    c                    sP   t | D ]B}t| |}t|r|dr|dkrt| | i | q| S )z-Apply decorator to all test methods in class.r  test_session)dirr   callable
startswithr   )clsr   rD   r   r  rH   r   r   all_test_methods_impl  s    
z3for_all_test_methods.<locals>.all_test_methods_implr   )r  r   rH   r  r   r  r   for_all_test_methods  s    r  c                 C   s   dd }|S )a  Execute test with TensorFloat-32 disabled.

    While almost every real-world deep learning model runs fine with
    TensorFloat-32, many tests use assertAllClose or similar methods.
    TensorFloat-32 matmuls typically will cause such methods to fail with the
    default tolerances.

    Args:
      description: A description used for documentation purposes, describing why
        the test requires TensorFloat-32 to be disabled.

    Returns:
      Decorator which runs a test with TensorFloat-32 disabled.
    c                    s   t   fdd}|S )Nc              	      sX   t jj }z6t jjd  | g|R i | W t jj| nt jj| 0 d S )NF)rA   configexperimental!tensor_float_32_execution_enabled enable_tensor_float_32_execution)r   r   rH   allowedfr   r   	decorated.  s
    zArun_without_tensor_float_32.<locals>.decorator.<locals>.decorated)r  r  r  r  r   r  r   r  -  s    z.run_without_tensor_float_32.<locals>.decoratorr   )descriptionr  r   r   r   run_without_tensor_float_32  s    r   c                 C   s
   t t| S )z:Execute all tests in a class with TensorFloat-32 disabled.)r  r   )r  r   r   r   run_all_without_tensor_float_32=  s    r!  c                    s6   t jj   d fdd}dur2|S |S )aq  Execute the decorated test only if running in v2 mode.

    This function is intended to be applied to tests that exercise v2 only
    functionality. If the test is run in v1 mode it will simply be skipped.

    See go/tf-test-decorator-cheatsheet for the decorators to use in different
    v1/v2/eager/graph combinations.

    Args:
      obj: function to be annotated. If None, return a
        decorator the can be applied to a function or class. If `obj` is not
        None, return the decorator applied to `obj`.

    Returns:
      Returns a decorator that will conditionally skip the decorated test
      method.
    z#Test is only compatible with TF v2.c                    s0   t  rtjdS  fdd}|S )N)	conditionreasonc                    s$    r|   | g|R i |S r   )skipTest)r   r   rH   )r"  r  r#  r   r   r  ]  s    
z1run_v2_only.<locals>.decorator.<locals>.decorated)r   isclassunittestskipIfr  r"  objr#  r  r   r  Y  s    
zrun_v2_only.<locals>.decoratorN)rA   r   r   r   )r)  r  r   r(  r   run_v2_onlyD  s    r*  c               
      s   dd }g }t |  |dD ]0\ }t|ts4|g}| fdd|D  qdd tj| D }g }|D ]T}t|tjs~J d	dd | D }|tt| d	d

|fg  qj|S )aK  Generate combinations based on its keyword arguments using combine().

    This function calls combine() and appends a testcase name to the list of
    dictionaries returned. The 'testcase_name' key is a required for named
    parameterized tests.

    Args:
      **kwargs: keyword arguments of form `option=[possibilities, ...]` or
        `option=the_only_possibility`.

    Returns:
      a list of dictionaries for each combination. Keys in the dictionaries are
      the keyword argument names.  Each key has one value - one of the
      corresponding keyword argument values.
    c                 S   s   | d S )Nr   r   )kr   r   r   r   z  r   z:generate_combinations_with_testcase_name.<locals>.<lambda>keyc                    s   g | ]} |fqS r   r   )r   rD   r,  r   r   r     r   z<generate_combinations_with_testcase_name.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   )collectionsOrderedDict)r   resultr   r   r   r     s   r   c                 S   s<   g | ]4\}}d  dttj|dttjt|qS )z_{}_{}r   )r   joinfilterstrisalnum)r   r-  rD   r   r   r   r     s
   testcase_namez_test{})sorteditemsr@   rQ   r   	itertoolsproductr.  r/  r1  r   )rH   sort_by_keycombinationsvaluesnamed_combinationscombinationr   r   r,  r   (generate_combinations_with_testcase_namej  s2    
	
r?  )N)NNNNNNNTNNNN)N)NNNNNN)NN)r   )N)ar   r.  
contextlibr  r8  	threadingr&  numpyr   Ztensorflow.compat.v2rB   v2rA   kerasr   r   r   keras.enginer   keras.optimizers.optimizer_v2r   adadelta_v2r   
adagrad_v2r   adam_v2r	   	adamax_v2r
   gradient_descent_v2r   nadam_v2r   
rmsprop_v2keras.utilsr   r   tensorflow.python.frameworkr   Ztf_test_utils tensorflow.python.util.tf_exportr   r   r   r2   disable_cudnn_autotuner{   localri   r|   rN   r   r   contextmanagerr   r   rk   r   r   r   r   r   r   r`   r   r   r   r   r   r   r   r   Layerr   r   r   r   AdadeltaAdagradAdamAdamaxNadamRMSpropSGDr   r   r   r   r   r   r
  r  r  r   r!  r*  r?  r   r   r   r   <module>   s    

              





)      
L*5 
 
	


 
&