
    6biT                     $   S r SSKrSSKrSSKrSSKrSSKJs  Jr  SSK	J
r
  SSKJr  SSKJr   SSKr/ SQr " S S\R&                  R(                  \
R(                  5      rSS jrS	 rS
 rS rSS jrSS jrS rS rS r    SS jrS rS r S r!S r"SS jr#S r$ " S S\RJ                  R&                  RL                  RN                  5      r( " S S\RJ                  R&                  RL                  RN                  5      r)\RJ                  R&                  RL                  RT                  RV                  S   r,\RZ                  " \RJ                  R&                  RL                  RT                  \,\(" 5       \)" 5       4-   S9r*\RJ                  R&                  RL                  R\                  r.\RJ                  R&                  RL                  R^                  r/\RJ                  R&                  RL                  R`                  r0g! \ a    Sr GNf = f) z$Utilities for unit-testing TF-Keras.    N)parameterized)
test_utils
functionalsubclass
sequentialc                   (   ^  \ rS rSrU 4S jrSrU =r$ )TestCase%   c                 ^   > [         R                  R                  5         [        TU ]  5         g N)kerasbackendclear_sessionsupertearDown)self	__class__s    f/home/james-whalen/.local/lib/python3.13/site-packages/tf_keras/src/testing_infra/test_combinations.pyr   TestCase.tearDown&   s    ##%     )__name__
__module____qualname____firstlineno__r   __static_attributes____classcell__)r   s   @r   r
   r
   %   s     r   r
   c                    ^ [         c  UR                  S/5        / SQnU Vs/ s H/  nU[        R                  R	                  U5      ;  d  M(  SU 3U4PM1     snmU4S jn[        X5      $ s  snf )aL  Execute the decorated test with all TF-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 TF-Keras saved model format.

The TF-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 TF-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 TF-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 TF-Keras saved model format.

Raises:
  ImportError: If abseil parameterized is not installed or not included as
    a target dependency.
h5)r    tftf_no_traces_c                 t   >^  [         R                  " T6 [        R                  " T 5      U 4S j5       5       nU$ ))Decorator that constructs the test cases.c                    > US:X  a  [        TU /UQ70 UD6  gUS:X  a  [        TU /UQ70 UD6  gUS:X  a  [        TU /UQ70 UD6  g[        SU 35      e)8A run of a single test case w/ the specified model type.r    r!   r"   Unknown model type: N)_test_h5_saved_model_format_test_tf_saved_model_format%_test_tf_saved_model_format_no_traces
ValueError)r   saved_formatargskwargsfs       r   	decoratedTrun_with_all_saved_model_formats.<locals>.single_method_decorator.<locals>.decorated   sl     t#+AtEdEfE%+AtEdEfE/5aOOO #7~!FGGr   r   named_parameters	functoolswrapsr0   r1   paramss   ` r   single_method_decoratorArun_with_all_saved_model_formats.<locals>.single_method_decorator   s=    
 
	'	'	0				H 
 
1		H r   )h5pyappendr!   nestflatten_test_or_class_decorator)test_or_classexclude_formatssaved_model_formatsr-   r9   r8   s        @r    run_with_all_saved_model_formatsrC   +   sz    f |v&6 0/Lrww?? 	+1\N	\*/F( $MKK5s   'A-A-c                 |    [         R                  " S5         U " U/UQ70 UD6  S S S 5        g ! , (       d  f       g = f)Nr    r   saved_model_format_scoper0   r@   r.   r/   s       r   r)   r)      .    		,	,T	2	-)$)&) 
3	2	2   -
;c                 |    [         R                  " S5         U " U/UQ70 UD6  S S S 5        g ! , (       d  f       g = f)Nr!   rE   rG   s       r   r*   r*      rH   rI   c                 z    [         R                  " SSS9   U " U/UQ70 UD6  S S S 5        g ! , (       d  f       g = f)Nr!   F)save_tracesrE   rG   s       r   r+   r+      s1    		,	,Tu	E	-)$)&) 
F	E	Es   ,
:c                 P    U=(       d    / nUR                  S5        [        X5      $ )z=Runs all tests with the supported formats for saving weights.r"   )r<   rC   )r@   rA   s     r   run_with_all_weight_formatsrN      s%    %+O>*+MKKr   c                    ^ / SQnU Vs/ s H/  nU[         R                  R                  U5      ;  d  M(  SU 3U4PM1     snmU4S jn[        X5      $ s  snf )a  Execute the decorated test with all TF-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 TF-Keras model type.

The TF-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 TF-Keras model type. This allows unittests to
confirm the equivalence between different TF-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 TF-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 TF-Keras model type.

Raises:
  ImportError: If abseil parameterized is not installed or not included as
    a target dependency.
r   r#   c                 t   >^  [         R                  " T6 [        R                  " T 5      U 4S j5       5       nU$ )r%   c                    > US:X  a  [        TU /UQ70 UD6  gUS:X  a  [        TU /UQ70 UD6  gUS:X  a  [        TU /UQ70 UD6  g[        SU 35      e)r'   r   r   r   r(   N)_test_functional_model_type_test_subclass_model_type_test_sequential_model_typer,   )r   
model_typer.   r/   r0   s       r   r1   Lrun_with_all_model_types.<locals>.single_method_decorator.<locals>.decorated  sl     \)+AtEdEfEz))!TCDCFC|++AtEdEfE #7
|!DEEr   r3   r7   s   ` r   r9   9run_with_all_model_types.<locals>.single_method_decorator  s=    
 
	'	'	0				F 
 
1		F r   )r!   r=   r>   r?   )r@   exclude_modelsmodel_typesmodelr9   r8   s        @r   run_with_all_model_typesr[      sc    t ;K ! E77 	1UGe F( $MKK5s
   'AAc                 |    [         R                  " S5         U " U/UQ70 UD6  S S S 5        g ! , (       d  f       g = f)Nr   r   model_type_scoperG   s       r   rR   rR   .  .    		$	$\	2	-)$)&) 
3	2	2rI   c                 |    [         R                  " S5         U " U/UQ70 UD6  S S S 5        g ! , (       d  f       g = f)Nr   r]   rG   s       r   rS   rS   3  s.    		$	$Z	0	-)$)&) 
1	0	0rI   c                 |    [         R                  " S5         U " U/UQ70 UD6  S S S 5        g ! , (       d  f       g = f)Nr   r]   rG   s       r   rT   rT   8  r_   rI   c                   ^^ U(       a  [        SU 35      eS/mU(       d  TR                  S5        U(       d>  [        R                  R                  R                  5       (       d  TR                  S5        UU4S jn[        X5      $ )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 TF-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 TF-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: )_v2_functionv2_function)	_v2_eagerv2_eager)_v1_session
v1_sessionc                 v   >^  [         R                  " T6 [        R                  " T 5      UU 4S j5       5       nU$ )r%   c                    > US:X  a  [        TU T/UQ70 UD6  gUS:X  a  [        TU /UQ70 UD6  gUS:X  a  [        TU /UQ70 UD6  g[        SU 35      $ )z2A run of a single test case w/ specified run mode.rh   rf   rd   zUnknown run mode N)_v1_session_test_v2_eager_test_v2_function_testr,   )r   run_moder.   r/   configr0   s       r   r1   Grun_all_keras_modes.<locals>.single_method_decorator.<locals>.decorated  sn     <' D&B4B6BZ'q$888]*!!T;D;F;!$5hZ"@AAr   r3   )r0   r1   ro   r8   s   ` r   r9   4run_all_keras_modes.<locals>.single_method_decorator  s=    
 
	'	'	0				B 
 
1		B r   )r,   r<   r!   __internal__tf2enabledr?   )r@   ro   always_skip_v1always_skip_eagerr/   r9   r8   s    `    @r   run_all_keras_modesrw   =  sn    X 6vh?@@-.F/0boo1199;;34( $MKKr   c                 n   [         R                  R                  R                  5       R	                  5          [
        R                  " S5         UR                  US9   U " U/UQ70 UD6  S S S 5        S S S 5        S S S 5        g ! , (       d  f       N= f! , (       d  f       N(= f! , (       d  f       g = f)NF)ro   )r!   compatv1get_default_graph
as_defaultr   run_eagerly_scopetest_session)r0   r@   ro   r.   r/   s        r   rk   rk     s{    		'	'	)	4	4	6))%0++6+:-1$1&1 ; 1 
7	6:: 10 
7	6s;   B&BB+B3B&
BB
B#	B&&
B4c                     [         R                  R                  R                  5          [        R
                  " S5         U " U/UQ70 UD6  S S S 5        S S S 5        g ! , (       d  f       N= f! , (       d  f       g = f)NTr!   rr   eager_context
eager_moder   r}   rG   s       r   rl   rl     sU    		&	&	1	1	3))$/m-d-f- 0 
4	3// 
4	3#   A/ AA/
A,	(A//
A=c                     [         R                  R                  R                  5          [        R
                  " S5         U " U/UQ70 UD6  S S S 5        S S S 5        g ! , (       d  f       N= f! , (       d  f       g = f)NFr   rG   s       r   rm   rm     sU    		&	&	1	1	3))%0m-d-f- 1 
4	300 
4	3r   c                 *   ^ U4S jnU b  U" U 5      $ U$ )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                   > [        U [        R                  R                  5      (       a)  [        R
                  R                  U4S jU  5       5      $ [        U [        5      (       a  U nUR                  R                  5       R                  5        HY  u  p#[        U5      (       d  M  UR                  [        R                  R                  5      (       d  MG  [!        XT" U5      5        M[     [        U5      R#                  [        U5      UR$                  UR&                  UR                  R                  5       5      nU$ T" U 5      $ )Nc              3   4   >#    U  H  nT" U5      v   M     g 7fr   r   ).0methodr9   s     r   	<genexpr>L_test_or_class_decorator.<locals>._decorate_test_or_class.<locals>.<genexpr>  s      1>AF'//cs   )
isinstancecollectionsabcIterable	itertoolschainfrom_iterabletype__dict__copyitemscallable
startswithunittest
TestLoadertestMethodPrefixsetattr__new__r   	__bases__)objclsnamevaluer9   s       r   _decorate_test_or_class9_test_or_class_decorator.<locals>._decorate_test_or_class  s    c;??3344??00 1>A1   c4  C"||00288:E??t''88( ( C'>u'EF	  ; s)##S	3<<8I8I8KC J&s++r   r   )r@   r9   r   s    ` r   r?   r?     s!    2,(  &}55""r   c                 x   U c4  [         R                  R                  R                  5       (       a  S/OSS/n Uc  SS/n/ nSU ;   a6  U[         R                  R                  R
                  R                  S/US9-  nSU ;   a7  U[         R                  R                  R
                  R                  S/S/S9-  nU$ )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'. If None, uses ['graph', 'eager']. If an empty
    list is provided, then the test will run under the context based on
    tensorflow's version, e.g., graph for v1 and eager for v2. Defaults to
    `None`.
  run_eagerly: List of `run_eagerly` value to be run with the tests.
    When None, uses [True, False]. Note that for `graph` mode,
    run_eagerly value will only be False. Defaults to `None`.

Returns:
  A list contains all the combinations to be used to generate test cases.
eagergraphTF)moderun_eagerly)r!   rr   rs   rt   testcombinationscombine)r   r   results      r   keras_mode_combinationsr     s    $ |,,4466WIWg<N 	 UmF$"//&&33;; < 
 	
 $"//&&33;; < 
 	
 Mr   c                  l    [         R                  R                  R                  R	                  [
        S9$ )N)rU   )r!   rr   r   r   r   KERAS_MODEL_TYPESr   r   r   keras_model_type_combinationsr     s-    ??,,44$ 5  r   c                   $    \ rS rSrSrS rS rSrg)KerasModeCombinationi  zeCombination for TF-Keras test mode.

It by default includes v1_session, v2_eager and v2_tf_function.
c                 ^    UR                  SS 5      nUb  [        R                  " U5      /$ / $ Nr   )popr   r}   )r   r/   r   s      r   context_managers%KerasModeCombination.context_managers  s1    jj5"00=>>Ir   c                 j    [         R                  R                  R                  R	                  S5      /$ r   r!   rr   r   r   OptionalParameterr   s    r   parameter_modifiers(KerasModeCombination.parameter_modifiers'  s*    OO  --??N
 	
r   r   Nr   r   r   r   __doc__r   r   r   r   r   r   r   r     s    

r   r   c                   $    \ rS rSrSrS rS rSrg)KerasModelTypeCombinationi-  aJ  Combination for TF-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 TF-Keras model type. This allows unittests to
confirm the equivalence between different TF-Keras models.
c                 l    UR                  SS 5      nU[        ;   a  [        R                  " U5      /$ / $ NrU   )r   r   r   r^   )r   r/   rU   s      r   r   *KerasModelTypeCombination.context_managers9  s4    ZZd3
**//
;<<Ir   c                 j    [         R                  R                  R                  R	                  S5      /$ r   r   r   s    r   r   -KerasModelTypeCombination.parameter_modifiers@  s*    OO  --??M
 	
r   r   Nr   r   r   r   r   r   -  s    
r   r   test_combinations)r   )NN)NNFF)1r   r   r5   r   r   tensorflow.compat.v2ry   v2r!   absl.testingr   tf_keras.srcsrcr   tf_keras.src.testing_infrar   r;   ImportErrorr   r   r
   rC   r)   r*   r+   rN   r[   rR   rS   rT   rw   rk   rl   rm   r?   r   r   rr   r   TestCombinationr   r   generatekeywords	_defaultspartialr   timesNamedObjectr   r   r   <module>r      s   +     ! ! &  1 = rww!7!7 pLf*
*
*
LuLp*
*
* 	iLX2..0#f!H
2??//<<LL 
(
OO%%55
2 OO  --66??	 OO%%..8:;<
 //


+
+
3
3
))//oo""//;;c  Ds   H HH