a
    +=icT                     @   s  d 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ZddlmZ zddlZW n eyx   dZY n0 g dZG dd dejje
jZd/dd	Zd
d Zdd Zdd Zd0ddZd1ddZdd Zdd Zdd Zd2ddZdd Zdd  Zd!d" Zd#d$ Z d3d%d&Z!d'd( Z"G d)d* d*ej#jj$j%Z&G d+d, d,ej#jj$j%Z'ej#jj$j(j)d- Z*ej+ej#jj$j(e*e& e' f d.Z(ej#jj$j,Z,ej#jj$j-Z-ej#jj$j.Z.dS )4z!Utilities for unit-testing Keras.    N)parameterized)
test_utils
functionalsubclass
sequentialc                       s   e Zd Z fddZ  ZS )TestCasec                    s   t j  t   d S N)kerasbackendZclear_sessionsupertearDownself	__class__ v/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/keras/testing_infra/test_combinations.pyr   &   s    
zTestCase.tearDown)__name__
__module____qualname__r   __classcell__r   r   r   r   r   %   s   r   c                    sD   t du r dg g d} fdd|D fdd}t| |S )a4  Execute the decorated test with all Keras saved model formats).

    This decorator is intended to be applied either to individual test methods
    in a `test_combinations.TestCase` class, or directly to a test class that
    extends it. Doing so will cause the contents of the individual test method
    (or all test methods in the class) to be executed multiple times - once for
    each Keras saved model format.

    The Keras saved model formats include:
    1. HDF5: 'h5'
    2. SavedModel: 'tf'

    Note: if stacking this decorator with absl.testing's parameterized
    decorators, those should be at the bottom of the stack.

    Various methods in `testing_utils` to get file path for saved models will
    auto-generate a string of the two saved model formats. This allows unittests
    to confirm the equivalence between the two Keras saved model formats.

    For example, consider the following unittest:

    ```python
    class MyTests(test_utils.KerasTestCase):

      @test_utils.run_with_all_saved_model_formats
      def test_foo(self):
        save_format = test_utils.get_save_format()
        saved_model_dir = '/tmp/saved_model/'
        model = keras.models.Sequential()
        model.add(keras.layers.Dense(2, input_shape=(3,)))
        model.add(keras.layers.Dense(3))
        model.compile(loss='mse', optimizer='sgd', metrics=['acc'])

        keras.models.save_model(model, saved_model_dir, save_format=save_format)
        model = keras.models.load_model(saved_model_dir)

    if __name__ == "__main__":
      tf.test.main()
    ```

    This test tries to save the model into the formats of 'hdf5', 'h5', 'keras',
    'tensorflow', and 'tf'.

    We can also annotate the whole class if we want this to apply to all tests
    in the class:
    ```python
    @test_utils.run_with_all_saved_model_formats
    class MyTests(test_utils.KerasTestCase):

      def test_foo(self):
        save_format = test_utils.get_save_format()
        saved_model_dir = '/tmp/saved_model/'
        model = keras.models.Sequential()
        model.add(keras.layers.Dense(2, input_shape=(3,)))
        model.add(keras.layers.Dense(3))
        model.compile(loss='mse', optimizer='sgd', metrics=['acc'])

        keras.models.save_model(model, saved_model_dir, save_format=save_format)
        model = tf.keras.models.load_model(saved_model_dir)

    if __name__ == "__main__":
      tf.test.main()
    ```

    Args:
      test_or_class: test method or class to be annotated. If None,
        this method returns a decorator that can be applied to a test method or
        test class. If it is not None this returns the decorator applied to the
        test or class.
      exclude_formats: A collection of Keras saved model formats to not run.
        (May also be a single format not wrapped in a collection).
        Defaults to None.

    Returns:
      Returns a decorator that will run the decorated test method multiple
      times: once for each desired Keras saved model format.

    Raises:
      ImportError: If abseil parameterized is not installed or not included as
        a target dependency.
    Nh5)r   tftf_no_tracesc                    s(   g | ] }|t j vrd | |fqS z_%sr   nestflatten).0saved_format)exclude_formatsr   r   
<listcomp>   s   z4run_with_all_saved_model_formats.<locals>.<listcomp>c                    s$   t j t  fdd}|S ))Decorator that constructs the test cases.c                    sx   |dkr"t  | g|R i | nR|dkrDt | g|R i | n0|dkrft | g|R i | ntd|f dS )8A run of a single test case w/ the specified model type.r   r   r   Unknown model type: %sN)_test_h5_saved_model_format_test_tf_saved_model_format%_test_tf_saved_model_format_no_traces
ValueError)r   r    argskwargsfr   r   	decorated   s    zTrun_with_all_saved_model_formats.<locals>.single_method_decorator.<locals>.decoratedr   Znamed_parameters	functoolswrapsr-   r.   paramsr,   r   single_method_decorator   s    zArun_with_all_saved_model_formats.<locals>.single_method_decorator)h5pyappend_test_or_class_decorator)test_or_classr!   Zsaved_model_formatsr5   r   )r!   r4   r    run_with_all_saved_model_formats+   s    S
r:   c                 O   sD   t d& | |g|R i | W d    n1 s60    Y  d S )Nr   r   Zsaved_model_format_scoper-   r9   r*   r+   r   r   r   r&      s    r&   c                 O   sD   t d& | |g|R i | W d    n1 s60    Y  d S )Nr   r;   r<   r   r   r   r'      s    r'   c                 O   sH   t jddd& | |g|R i | W d    n1 s:0    Y  d S )Nr   F)Zsave_tracesr;   r<   r   r   r   r(      s    r(   c                 C   s   |pg }| d t| |S )z=Runs all tests with the supported formats for saving weights.r   )r7   r:   )r9   r!   r   r   r   run_with_all_weight_formats   s    
r=   c                    s0   g d} fdd|D fdd}t | |S )a  Execute the decorated test with all Keras model types.

    This decorator is intended to be applied either to individual test methods
    in a `test_combinations.TestCase` class, or directly to a test class that
    extends it. Doing so will cause the contents of the individual test method
    (or all test methods in the class) to be executed multiple times - once for
    each Keras model type.

    The Keras model types are: ['functional', 'subclass', 'sequential']

    Note: if stacking this decorator with absl.testing's parameterized
    decorators, those should be at the bottom of the stack.

    Various methods in `testing_utils` to get models will auto-generate a model
    of the currently active Keras model type. This allows unittests to confirm
    the equivalence between different Keras models.

    For example, consider the following unittest:

    ```python
    class MyTests(test_utils.KerasTestCase):

      @test_utils.run_with_all_model_types(
        exclude_models = ['sequential'])
      def test_foo(self):
        model = test_utils.get_small_mlp(1, 4, input_dim=3)
        optimizer = RMSPropOptimizer(learning_rate=0.001)
        loss = 'mse'
        metrics = ['mae']
        model.compile(optimizer, loss, metrics=metrics)

        inputs = np.zeros((10, 3))
        targets = np.zeros((10, 4))
        dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
        dataset = dataset.repeat(100)
        dataset = dataset.batch(10)

        model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)

    if __name__ == "__main__":
      tf.test.main()
    ```

    This test tries building a small mlp as both a functional model and as a
    subclass model.

    We can also annotate the whole class if we want this to apply to all tests
    in the class:
    ```python
    @test_utils.run_with_all_model_types(exclude_models = ['sequential'])
    class MyTests(test_utils.KerasTestCase):

      def test_foo(self):
        model = test_utils.get_small_mlp(1, 4, input_dim=3)
        optimizer = RMSPropOptimizer(learning_rate=0.001)
        loss = 'mse'
        metrics = ['mae']
        model.compile(optimizer, loss, metrics=metrics)

        inputs = np.zeros((10, 3))
        targets = np.zeros((10, 4))
        dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
        dataset = dataset.repeat(100)
        dataset = dataset.batch(10)

        model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)

    if __name__ == "__main__":
      tf.test.main()
    ```


    Args:
      test_or_class: test method or class to be annotated. If None,
        this method returns a decorator that can be applied to a test method or
        test class. If it is not None this returns the decorator applied to the
        test or class.
      exclude_models: A collection of Keras model types to not run.
        (May also be a single model type not wrapped in a collection).
        Defaults to None.

    Returns:
      Returns a decorator that will run the decorated test method multiple
      times: once for each desired Keras model type.

    Raises:
      ImportError: If abseil parameterized is not installed or not included as
        a target dependency.
    r   c                    s(   g | ] }|t j vrd | |fqS r   r   )r   model)exclude_modelsr   r   r"     s   z,run_with_all_model_types.<locals>.<listcomp>c                    s$   t j t  fdd}|S )r#   c                    sx   |dkr"t  | g|R i | nR|dkrDt | g|R i | n0|dkrft | g|R i | ntd|f dS )r$   r   r   r   r%   N)_test_functional_model_type_test_subclass_model_type_test_sequential_model_typer)   )r   
model_typer*   r+   r,   r   r   r.     s    zLrun_with_all_model_types.<locals>.single_method_decorator.<locals>.decoratedr/   r2   r3   r,   r   r5     s    z9run_with_all_model_types.<locals>.single_method_decorator)r8   )r9   r?   Zmodel_typesr5   r   )r?   r4   r   run_with_all_model_types   s    Z
rD   c                 O   sD   t d& | |g|R i | W d    n1 s60    Y  d S )Nr   r   model_type_scoper<   r   r   r   r@   ,  s    r@   c                 O   sD   t d& | |g|R i | W d    n1 s60    Y  d S )Nr   rE   r<   r   r   r   rA   1  s    rA   c                 O   sD   t d& | |g|R i | W d    n1 s60    Y  d S )Nr   rE   r<   r   r   r   rB   6  s    rB   Fc                    sX   |rt d|dg|s&d |s@tjj s@d  fdd}t| |S )a
  Execute the decorated test with all keras execution modes.

    This decorator is intended to be applied either to individual test methods
    in a `test_combinations.TestCase` class, or directly to a test class that
    extends it. Doing so will cause the contents of the individual test method
    (or all test methods in the class) to be executed multiple times - once
    executing in legacy graph mode, once running eagerly and with
    `should_run_eagerly` returning True, and once running eagerly with
    `should_run_eagerly` returning False.

    If Tensorflow v2 behavior is enabled, legacy graph mode will be skipped, and
    the test will only run twice.

    Note: if stacking this decorator with absl.testing's parameterized
    decorators, those should be at the bottom of the stack.

    For example, consider the following unittest:

    ```python
    class MyTests(test_utils.KerasTestCase):

      @test_utils.run_all_keras_modes
      def test_foo(self):
        model = test_utils.get_small_functional_mlp(1, 4, input_dim=3)
        optimizer = RMSPropOptimizer(learning_rate=0.001)
        loss = 'mse'
        metrics = ['mae']
        model.compile(
            optimizer, loss, metrics=metrics,
            run_eagerly=test_utils.should_run_eagerly())

        inputs = np.zeros((10, 3))
        targets = np.zeros((10, 4))
        dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
        dataset = dataset.repeat(100)
        dataset = dataset.batch(10)

        model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)

    if __name__ == "__main__":
      tf.test.main()
    ```

    This test will try compiling & fitting the small functional mlp using all
    three Keras execution modes.

    Args:
      test_or_class: test method or class to be annotated. If None,
        this method returns a decorator that can be applied to a test method or
        test class. If it is not None this returns the decorator applied to the
        test or class.
      config: An optional config_pb2.ConfigProto to use to configure the
        session when executing graphs.
      always_skip_v1: If True, does not try running the legacy graph mode even
        when Tensorflow v2 behavior is not enabled.
      always_skip_eager: If True, does not execute the decorated test
        with eager execution modes.
      **kwargs: Additional kwargs for configuring tests for
       in-progress Keras behaviors/ refactorings that we haven't fully
       rolled out yet

    Returns:
      Returns a decorator that will run the decorated test method multiple
      times.

    Raises:
      ImportError: If abseil parameterized is not installed or not included as
        a target dependency.
    zUnrecognized keyword args: {})Z_v2_functionv2_function)Z	_v2_eagerv2_eager)Z_v1_session
v1_sessionc                    s&   t j t  fdd}|S )r#   c                    sx   |dkr$t |  g|R i | nP|dkrFt| g|R i | n.|dkrht| g|R i | ntd| S dS )z2A run of a single test case w/ specified run mode.rI   rH   rG   zUnknown run mode %sN)_v1_session_test_v2_eager_test_v2_function_testr)   )r   Zrun_moder*   r+   )configr-   r   r   r.     s    zGrun_all_keras_modes.<locals>.single_method_decorator.<locals>.decoratedr/   r2   rM   r4   r,   r   r5     s    z4run_all_keras_modes.<locals>.single_method_decorator)r)   formatr7   r   __internal__tf2enabledr8   )r9   rM   Zalways_skip_v1Zalways_skip_eagerr+   r5   r   rN   r   run_all_keras_modes;  s    L

rS   c              
   O   s   t jj  | tdR |j|d& | |g|R i | W d    n1 sV0    Y  W d    n1 st0    Y  W d    n1 s0    Y  d S )NF)rM   )r   compatv1Zget_default_graphZ
as_defaultr   run_eagerly_scopeZtest_session)r-   r9   rM   r*   r+   r   r   r   rJ     s    rJ   c              	   O   sp   t jj P td& | |g|R i | W d    n1 sD0    Y  W d    n1 sb0    Y  d S )NTr   rP   Zeager_contextZ
eager_moder   rV   r<   r   r   r   rK     s    rK   c              	   O   sp   t jj P td& | |g|R i | W d    n1 sD0    Y  W d    n1 sb0    Y  d S )NFrW   r<   r   r   r   rL     s    rL   c                    s     fdd}| dur|| S |S )a  Decorate a test or class with a decorator intended for one method.

    If the test_or_class is a class:
      This will apply the decorator to all test methods in the class.

    If the test_or_class is an iterable of already-parameterized test cases:
      This will apply the decorator to all the cases, and then flatten the
      resulting cross-product of test cases. This allows stacking the Keras
      parameterized decorators w/ each other, and to apply them to test methods
      that have already been marked with an absl parameterized decorator.

    Otherwise, treat the obj as a single method and apply the decorator
    directly.

    Args:
      test_or_class: A test method (that may have already been decorated with a
        parameterized decorator, or a test class that extends
        test_combinations.TestCase
      single_method_decorator:
        A parameterized decorator intended for a single test method.
    Returns:
      The decorated result.
    c                    s   t | tjjr(tj fdd| D S t | tr| }|j	 
 D ].\}}t|rD|tjjrDt|| | qDt|t||j|j|j	 }|S  | S )Nc                 3   s   | ]} |V  qd S r	   r   )r   methodr5   r   r   	<genexpr>  s   zL_test_or_class_decorator.<locals>._decorate_test_or_class.<locals>.<genexpr>)
isinstancecollectionsabcIterable	itertoolschainfrom_iterabletype__dict__copyitemscallable
startswithunittestZ
TestLoaderZtestMethodPrefixsetattr__new__r   	__bases__)objclsnamevaluerY   r   r   _decorate_test_or_class  s     
z9_test_or_class_decorator.<locals>._decorate_test_or_classNr   )r9   r5   rp   r   rY   r   r8     s    r8   c                 C   s   | du r"t jj rdgnddg} |du r2ddg}g }d| v rX|t jjjjdg|d7 }d| v r||t jjjjdgdgd7 }|S )a  Returns the default test combinations for tf.keras tests.

    Note that if tf2 is enabled, then v1 session test will be skipped.

    Args:
      mode: List of modes to run the tests. The valid options are 'graph' and
        'eager'. Default to ['graph', 'eager'] if not specified. If a empty list
        is provide, then the test will run under the context based on tf's
        version, eg graph for v1 and eager for v2.
      run_eagerly: List of `run_eagerly` value to be run with the tests.
        Default to [True, False] if not specified. Note that for `graph` mode,
        run_eagerly value will only be False.

    Returns:
      A list contains all the combinations to be used to generate test cases.
    NeagergraphTF)moderun_eagerly)r   rP   rQ   rR   testcombinationscombine)rs   rt   resultr   r   r   keras_mode_combinations  s    ry   c                   C   s   t jjjjtdS )N)rC   )r   rP   ru   rv   rw   KERAS_MODEL_TYPESr   r   r   r   keras_model_type_combinations  s    
r{   c                   @   s    e Zd ZdZdd Zdd ZdS )KerasModeCombinationzjCombination for Keras test mode.

    It by default includes v1_session, v2_eager and v2_tf_function.
    c                 C   s(   | dd }|d ur t|gS g S d S Nrt   )popr   rV   )r   r+   rt   r   r   r   context_managers  s    z%KerasModeCombination.context_managersc                 C   s   t jjjdgS r}   r   rP   ru   rv   ZOptionalParameterr   r   r   r   parameter_modifiers$  s    z(KerasModeCombination.parameter_modifiersNr   r   r   __doc__r   r   r   r   r   r   r|     s   r|   c                   @   s    e Zd ZdZdd Zdd ZdS )KerasModelTypeCombinationaU  Combination for Keras model types when doing model test.

    It by default includes 'functional', 'subclass', 'sequential'.

    Various methods in `testing_utils` to get models will auto-generate a model
    of the currently active Keras model type. This allows unittests to confirm
    the equivalence between different Keras models.
    c                 C   s(   | dd }|tv r t|gS g S d S NrC   )r~   rz   r   rF   )r   r+   rC   r   r   r   r   6  s    z*KerasModelTypeCombination.context_managersc                 C   s   t jjjdgS r   r   r   r   r   r   r   =  s    z-KerasModelTypeCombination.parameter_modifiersNr   r   r   r   r   r   *  s   	r   test_combinations)r   )NN)NN)NN)NNFF)NN)/r   r\   r0   r_   rh   Ztensorflow.compat.v2rT   v2r   Zabsl.testingr   r
   Zkeras.testing_infrar   r6   ImportErrorrz   ru   r   r:   r&   r'   r(   r=   rD   r@   rA   rB   rS   rJ   rK   rL   r8   ry   r{   rP   rv   ZTestCombinationr|   r   generatekeywords	_defaultspartialrw   timesZNamedObjectr   r   r   r   <module>   sd   

r
	
w    
l3
#



