
    2Vh{x                     \   d dl Z d dlZd dlZd dlZd dlmZ d dlZd dlm	Z	 d dl
mZ d dl
mZ d dl
mZ 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  G d de	j:                  ej:                        Zd Zd Zd Z d Z!d Z"d Z#d Z$d Z%d Z&d Z'd Z(d Z)y)    N)Path)parameterized)backend)distribution)ops)tree)utils)is_float_dtype)standardize_dtype)clear_sessionKerasTensor)Loss)Model)traceback_utilsc                        e Zd ZdZ fdZd Zd ZddZddZddZ	ddZ
dd	Zdd
ZddZddZd ZddZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ xZS )TestCaseNc                 $    t        |   |i | y N)super__init__)selfargskwargs	__class__s      K/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/testing/test_case.pyr   zTestCase.__init__   s    $)&)    c                 n    t        d       t        j                         rt        j                          y y )NF)free_memory)r   r   is_traceback_filtering_enableddisable_traceback_filtering)r   s    r   setUpzTestCase.setUp   s)     	%(99;779 <r   c                 X    t        j                         | j                  fd       S )Nc                  .    t        j                         S r   )shutilrmtree)temp_dirs   r   <lambda>z'TestCase.get_temp_dir.<locals>.<lambda>(   s    h 7 r   )tempfilemkdtemp
addCleanup)r   r'   s    @r   get_temp_dirzTestCase.get_temp_dir&   s#    ##%78r   c                    t        |t        j                        st        j                  |      }t        |t        j                        st        j                  |      }t        j
                  j                  |||||       y )N)atolrtolerr_msg)
isinstancenpndarrayr   convert_to_numpytestingassert_allcloser   x1x2r.   r/   msgs         r   assertAllClosezTestCase.assertAllClose+   s[    "bjj)))"-B"bjj)))"-B


""2r4"Mr   c                 |    	 | j                  |||||       |xs d}t        d| d|       # t        $ r Y y w xY w)N)r.   r/   r:    z+The two values are close at all elements. 
z
.
Values: )r;   AssertionErrorr7   s         r   assertNotAllClosezTestCase.assertNotAllClose2   s\    	BT#F iR:3%{2$O
 	
  		s   / 	;;c                    |xs d}t        |t        j                        st        j                  |      }t        |t        j                        st        j                  |      }t        j
                  j                  ||||       y )Nr=   )decimalr0   )r1   r2   r3   r   r4   r5   assert_almost_equal)r   r8   r9   rA   r:   s        r   assertAlmostEqualzTestCase.assertAlmostEqual<   sb    iR"bjj)))"-B"bjj)))"-B


&&r2w&Lr   c                 v   | j                  t        |      t        |      |       t        ||      D ]  \  }}t        |t        t
        f      st        |t        t
        f      r| j                  |||       Gt        j                  |      }t        j                  |      }| j                  |||        y Nr:   )	assertEquallenzipr1   listtupleassertAllEqualr   r4   )r   r8   r9   r:   e1e2s         r   rL   zTestCase.assertAllEqualD   s    R#b's3"bk 	2FB"tUm,
2e}0M##B#4--b1--b1  RS 1	2r   c                 >    | j                  t        |      ||       y rE   )rG   rH   )r   iterableexpected_lenr:   s       r   	assertLenzTestCase.assertLenN   s    X#>r   c                    t        |t              r| j                  |j                  |       y t	        j                         dk(  r@dd l}|r| j                  ||j                         y | j                  ||j                         y t	        j                         dk(  rEdd l	m
c m} |r| j                  ||j                         y | j                  ||j                         y | j                  |dt	        j                          d       y )N
tensorflowr   jaxBackend z  does not support sparse tensors)r1   r   rG   sparser   rT   assertIsInstanceSparseTensorassertNotIsInstancejax.experimental.sparseexperimental	JAXSparseassertFalse)r   xrW   tf
jax_sparses        r   assertSparsezTestCase.assertSparseQ   s    a%QXXv.__,.#%%a9((BOO<__%'88%%a)=)=>((J,@,@A7??,--MNr   c                 \   t        |t              r| j                  |j                  |       y t	        j                         dk(  r@dd l}|r| j                  ||j                         y | j                  ||j                         y | j                  |dt	        j                          d       y )NrT   r   rV   z  does not support ragged tensors)
r1   r   rG   raggedr   rT   rX   RaggedTensorrZ   r^   )r   r_   rd   r`   s       r   assertRaggedzTestCase.assertRaggedh   s    a%QXXv.__,.#%%a9((BOO<7??,--MNr   c                    t        |d      r t        j                  |j                        }nt        j                  t	        |            }t        j                  |      }d| d| }|xs |}| j                  |||       y )NdtypezBThe dtype of x does not match the expected one. Received: x.dtype=z and dtype=rF   )hasattrr   r   rh   typerG   )r   r_   rh   r:   x_dtypestandardized_dtypedefault_msgs          r   assertDTypezTestCase.assertDTypex   s    1g//8G //Q8G$66u=!!(	UG= 	  ["4#>r   c                 T    t        |      j                         st        d| d      y )NzFile z does not exist)r   is_filer>   )r   paths     r   assertFileExistszTestCase.assertFileExists   s+    Dz!!# 5o!>?? $r   c                 $   ddl m} ddl m} ddl m} |j                  }|j                         }t        |      }t        |      d d  }	 ||      5  |j                  |      }
d d d        
j                         }t        |      }| j                  ||       | j                  t        |	      t        t        |
                    ||      }t        |      } ||      5   |t        |            }
d d d        |
j                         }t        |      }| j                  ||       t        |
      d d  }|	|fD ]  }d|v s|j                  d        | j                  t        |	      t        |             |
S # 1 sw Y   xY w# 1 sw Y   xY w)Nr   )custom_object_scope)deserialize_keras_object)serialize_keras_object__annotations__)keras.src.savingrt   ru   rv   r   
get_configto_json_with_tuplesdirfrom_configrG   setfrom_json_with_tuplesremove)r   instancecustom_objectsrt   ru   rv   clsconfigconfig_jsonref_dirrevived_instancerevived_configrevived_config_json
serializedserialized_jsonnew_dirlsts                    r   run_class_serialization_testz%TestCase.run_class_serialization_test   s~   8=;   $$&)&1h-" 0 	7"v6	7)4461.A&9:Ws3/?+@'AB ,H5
-j9 0 	7%o6 	 *4461.A&9:&'*W% 	.C C'

,-	. 	Ws7|4-	7 	7	 	s   E9F9FFc           	         	
) ||t        d      	t        d      |t        d      ||durt        d      |xs i }|xs i }|/|,t        |t              rKt        |d         r= j	                  |t                j                  t        |      t        |      d	       nt        |t              rY j	                  |t                j                  t        |j                               t        |j                               d	       nht        |t              r= j	                  |t                j                  t        |      t        |      d	       nt        |t              st        d
      ||t        j                  d |      }|||t        ||      } |d i |)t        |t              r )d i || n	 )|fi | t        )j                        t        )j                        t        )j                         t        t#        )             |d i |) j%                  )|       | j                  )j&                  |d	        fd}d!
	 fd	}fd}||i|t        j(                  d |      }n|} |d i |)t        |t              r )j*                  d i | n)j+                  |        |)       |t        j(                  fd|      }nt-        ||      } |d i |)t        |t              r )d i ||}n	 )|fi |} |)        |)|d       |-)j/                  |      } j                  ||j0                         |rn |d i |) j3                  )j4                  t7        )       d	        G d d|      }  | d i |) j9                  )j4                  dt7        )       d	       |||t        ||      } |d i |)t        |t              r )d i ||}!n	 )|fi |}! |)|!d       |r
 |)||!       |r5t;        j:                         dk(  rddl}"|"j>                  jA                         }|r/ |d i i |ddi)t        j(                  )fd      }#t        |t              r )d i ||}! )jB                  d i |#}$n )|fi |}!)jC                  |#      }$tE        t        jF                  |!      t        jF                  |$            D ]G  \  }%}&tI        |%jJ                        }' j                  |'|&jJ                  d|&jJ                   d|'        I )jL                  D ]5  }(tI        |(jJ                        }'tO        |'      s$ j                  |'d       7 yyy)"a{
  Run basic checks on a layer.

        Args:
            layer_cls: The class of the layer to test.
            init_kwargs: Dict of arguments to be used to
                instantiate the layer.
            input_shape: Shape tuple (or list/dict of shape tuples)
                to call the layer on.
            input_dtype: Corresponding input dtype.
            input_sparse: Whether the input is a sparse tensor (this requires
                the backend to support sparse tensors).
            input_ragged: Whether the input is a ragged tensor (this requires
                the backend to support ragged tensors).
            input_data: Tensor (or list/dict of tensors)
                to call the layer on.
            call_kwargs: Dict of arguments to use when calling the
                layer (does not include the first input tensor argument)
            expected_output_shape: Shape tuple
                (or list/dict of shape tuples)
                expected as output.
            expected_output_dtype: dtype expected as output.
            expected_output_sparse: Whether the output is expected to be sparse
                (this requires the backend to support sparse tensors).
            expected_output_ragged: Whether the output is expected to be ragged
                (this requires the backend to support ragged tensors).
            expected_output: Expected output tensor -- only
                to be specified if input_data is provided.
            expected_num_trainable_weights: Expected number
                of trainable weights of the layer once built.
            expected_num_non_trainable_weights: Expected number
                of non-trainable weights of the layer once built.
            expected_num_seed_generators: Expected number of
                SeedGenerators objects of the layer once built.
            expected_num_losses: Expected number of loss tensors
                produced when calling the layer.
            supports_masking: If True, will check that the layer
                supports masking.
            expected_mask_shape: Expected mask shape tuple
                returned by compute_mask() (only supports 1 shape).
            custom_objects: Dict of any custom objects to be
                considered during deserialization.
            run_training_check: Whether to attempt to train the layer
                (if an input shape or input data was provided).
            run_mixed_precision_check: Whether to test the layer with a mixed
                precision dtype policy.
            assert_built_after_instantiation: Whether to assert `built=True`
                after the layer's instantiation.
        Nz=input_shape and input_data cannot be passed at the same time.zLexpected_output_shape and expected_output cannot be passed at the same time.z=In order to use expected_output, input_data must be provided.TzCIn order to use expected_mask_shape, supports_masking must be True.r   z4The number of input shapes and dtypes does not matchrF   z(The type of input_shape is not supportedc                      y)Nfloat32 )_s    r   r(   z)TestCase.run_layer_test.<locals>.<lambda>)  s    r   z!Unexpected supports_masking valuec                    j                  | j                         j                  | j                  d       j                  | j                  d       j                  | j
                  d       j                  t        |       d       t        j                         dk(  r.+(%j                  | j                  z   z   d       y y y y y )Nz&Unexpected number of trainable_weightsrF   z*Unexpected number of non_trainable_weightsz,Unexpected number of non_trainable_variablesz$Unexpected number of seed_generatorstorchz!Unexpected number of torch_params)	
assertTruebuiltrR   trainable_weightsnon_trainable_weightsnon_trainable_variablesget_seed_generatorsr   torch_params)layer$expected_num_non_trainable_variables"expected_num_non_trainable_weightsexpected_num_seed_generatorsexpected_num_trainable_weightsr   s    r   run_build_assertsz2TestCase.run_layer_test.<locals>.run_build_assertsS  s   OOEKK(-9++2@  
 2=//6D  
 4?118F  
 ,7'.0>   !W,2>6B0<&&28923 <   = C ? -r   Fc           
         ed }t        j                  |||      }j                  t        t        j                  |            d dt        j
                  d |              dd }t        j
                  ||      }j                  t        t        j                  |            d dt        j
                  d |              r+t        j                  |      D ]  }j                  |        r+t        j                  |      D ]  }j                  |        |rrj                  t              t        |             t        t        j                        t        j                  |            D ]  \  }}	j                  ||	d	        
j                  | j                  
       y y y )
Nc                     |j                   }t        |      t        |       k7  ryt        | |      D ]  \  }}|	||k7  s y y)NFT)shaperH   rI   )expected_shaper_   r   expected_dimdims        r   verify_shapezITestCase.run_layer_test.<locals>.run_output_asserts.<locals>.verify_shape~  sO    GGE5zS%88$-0-G ))c'38K#()  r   zExpected output shapes z but received c                     | j                   S r   )r   r_   s    r   r(   zETestCase.run_layer_test.<locals>.run_output_asserts.<locals>.<lambda>  
    QWW r   rF   c                 F    | t        j                  |j                        k(  S r   )r   r   rh   )expected_dtyper_   s     r   verify_dtypezITestCase.run_layer_test.<locals>.run_output_asserts.<locals>.verify_dtype  s    )W-F-Fqww-OOOr   zExpected output dtypes c                     | j                   S r   rh   r   s    r   r(   zETestCase.run_layer_test.<locals>.run_output_asserts.<locals>.<lambda>  r   r   zUnexpected output value)r   map_structure_up_tor   allflattenmap_structurerb   rf   rG   rj   rI   r;   rR   losses)r   outputeagerr   shapes_matchr   dtypes_matchr_   ref_vvexpected_num_lossesexpected_outputexpected_output_dtypeexpected_output_raggedexpected_output_shapeexpected_output_sparser   s             r   run_output_assertsz3TestCase.run_layer_test.<locals>.run_output_asserts{  s   $0   $77L*?  \2312G1H I  $ 2 23Df MNP   
 %0P  $11 "7  \2312G1H I  $ 2 23Df MNP   
 &f- )A%%a()%f- )A%%a()".$$T/%:DLI$'_5t||F7K% q ++!1*C ,  '2NN5<<1DE 3 r   c                 z    G d dt               } ||       }||ft        j                         dk(  r$t        j                  t        j                        fd} G d dt
              }d}t        j                         dk(  r	rd	}|j                  d
 |       |       |j                   |       dd       y )Nc                   &     e Zd Z fdZddZ xZS )ETestCase.run_layer_test.<locals>.run_training_step.<locals>.TestModelc                 0    t         |           || _        y r   )r   r   r   )r   r   r   s     r   r   zNTestCase.run_layer_test.<locals>.run_training_step.<locals>.TestModel.__init__  s    G$&!&DJr   c                 (    | j                  ||      S )N)training)r   )r   r_   r   s      r   callzJTestCase.run_layer_test.<locals>.run_training_step.<locals>.TestModel.call  s    ::a(:;;r   F)__name__
__module____qualname__r   r   __classcell__r   s   @r   	TestModelr     s    '<r   r   r   c               3      K   	   wr   r   )datas   r   data_generatorzJTestCase.run_layer_test.<locals>.run_training_step.<locals>.data_generator  s     J s   
c                       e Zd ZddZy)DTestCase.run_layer_test.<locals>.run_training_step.<locals>.TestLossNc                 ,    t        j                  |      S r   )r   sum)r   y_truey_predsample_weights       r   __call__zMTestCase.run_layer_test.<locals>.run_training_step.<locals>.TestLoss.__call__  s    776?*r   r   )r   r   r   r   r   r   r   TestLossr     s    +r   r   autorT   Fsgd)	optimizerlossjit_compile   r   )steps_per_epochverbose)r   r   r   r   r4   r   compilefit)
r   
input_dataoutput_datar   modelr   r   r   r   input_sparses
           @r   run_training_stepz2TestCase.run_layer_test.<locals>.run_training_step  s    <E < e$E,D G+))'*B*BDI
+4 +" !K L0\#MMhjk   IIn&1IEr   c                 ,    t        j                  |       S r   )r   r   r   s    r   r(   z)TestCase.run_layer_test.<locals>.<lambda>  s    ciil r   c                 Z    t        t        j                  |       | j                        S r   )create_keras_tensorsr   r   rh   )r_   input_raggedr   s    r   r(   z)TestCase.run_layer_test.<locals>.<lambda>  s"    2		!agg|\ r   )r   z9 is stateless, so it should be built after instantiation.c                       e Zd Zd Zy)3TestCase.run_layer_test.<locals>.ModifiedBuildLayerc                      y r   r   )r   r   r   s      r   buildz9TestCase.run_layer_test.<locals>.ModifiedBuildLayer.build  s    r   N)r   r   r   r   r   r   r   ModifiedBuildLayerr     s    r   r   zThe `build` of z= is overriden, so it should not be built after instantiation.r   rh   mixed_float16c                     t        | j                  j                  r0t        j                  | j
                        rj                        S | j
                        S )Nr   )r   r   autocastr   r
   rh   compute_dtype)specr   s    r   r(   z)TestCase.run_layer_test.<locals>.<lambda>8  sI    

  %~~ ' 6 6tzz B "//"  "&" r   zexpected output dtype z, got r   r   r   )(
ValueErrorr1   rK   is_shape_tuplerX   rG   rH   dictr}   keysrJ   r   map_shape_structurecreate_eager_tensorsr   r   r   r   r   supports_maskingr   r   r   compute_maskr   r   r   rj   r^   r   r   cudais_availablecompute_output_specrI   r   r   rh   weightsr
   )*r   	layer_clsinit_kwargsinput_shapeinput_dtyper   r   r   call_kwargsr   r   r   r   r   r   r   r   r   r   r   expected_mask_shaper   run_training_checkrun_mixed_precision_check assert_built_after_instantiationr   r   r   build_shapekeras_tensor_inputskeras_tensor_outputsoutput_maskr   r   r   
input_specoutput_spectensorr   rh   weightr   s*   `    ``  ``````````                      @r   run_layer_testzTestCase.run_layer_test   s|   V "z'=O  !,1L$  &:+=O  */?t/K  
 "'R!'R"{'>+u-.A3 %%k59  $$N ! 
 K.%%k48  ((*+((*+N ! 
 K.%%k48  $$N ! 
  U3 !KLL"{':22#[K ![%<!1lL
 ,,E*d+2
2k2j0K0-514U5L5L1M.1958//62 4;7:1184 ,3/23Fu3M/N, (K())%@ '&& 7  &	 &	P1	F 1	Ff+	F\ ![%<""00*J *,,E+t,*k*K(e$ "&*&8&8 	'# ';lL'# ,,E-t4', ()(-8($ (--@'PK'P$e$u&:%H".#001DE  !4k6G6GH 0!0K0KK;- (/ /     +9[9  KK)$u+ 7C C !  ![%<!1l
 ,,E*d+#@j@K@#J>+>uk>!!%[A )W__->'-I,1JJ,C,C,E)(!N$M{$MG_$MN!// (
 j$/"'"D*"D"DK";%";";"Ij"IK"'
"Bk"BK"'";";J"GK$'LL-t||K/H% LFD .fll;E$$

0F5'J	 $mm ;F-fll;E%e,((	:;; )+ &=r   )ư>r  N)   Nr   )T)NNFFNNNNFFNNNNNNNNNTTF)r   r   r   maxDiffr   r"   r,   r;   r?   rC   rL   rR   rb   rf   rn   rr   r   r  r   r   s   @r   r   r      s    G*:
N
M2?. ?@  L ""$$'++/-1%)  "&).3i;r   r   c                  H    t        j                          dk(  xr
 t               S )NrT   r   uses_gpur   r   r   tensorflow_uses_gpur  X  s    ??,;;r   c                  H    t        j                          dk(  xr
 t               S )NrU   r  r   r   r   jax_uses_gpur   \  s    ??%4(*4r   c                  R    t        j                          dk7  ryddlm}   |        dk(  S )Nr   Fr   
get_devicer  )r   keras.src.backend.torch.corer#  r"  s    r   torch_uses_gpur%  `  s$    G#7<6!!r   c                  R    t        j                         } t        d | D              ryy)Nc              3   >   K   | ]  }|j                  d         yw)gpuN
startswith.0ds     r   	<genexpr>zuses_gpu.<locals>.<genexpr>k       
011<<
0   TFr   list_devicesanydevicess    r   r  r  h  s$    '')G

0
00r   c                  R    t        j                         } t        d | D              ryy)Nc              3   >   K   | ]  }|j                  d         yw)cpuNr)  r+  s     r   r.  zuses_cpu.<locals>.<genexpr>r  r/  r0  TFr1  r4  s    r   uses_cpur9  p  s$    '')G

0
00r   c                     t        | t              rH| j                         D ci c],  \  }}t        j                  |d      t        |||         . c}}S t        fd| |      S c c}}w )N_shaperh   rW   rd   c                 "    t        | |      S )Nr<  r   )r   dtrd   rW   s     r   r(   z&create_keras_tensors.<locals>.<lambda>  s    +F6
 r   )r1   r   itemsr	   removesuffixr   map_shape_dtype_structure)r  rh   rW   rd   kr   s     ``  r   r   r   w  s    +t$
 $))+	
 1 q(+[q&. 
 	
 %	
 	 
s   1A,c           
        	 ddl m t        t        j                  |            j                  g d      rt        d|       |rgt        j                         dk(  r
dd l		fd}nt        j                         dk(  rdd l	m
c m fd}nht        d	t        j                                |rAt        j                         dk(  r
dd l		fd
}n%t        dt        j                                fd}t        | t              rB| j                         D ci c]&  \  }}t        j                   |d       ||||         ( c}}S t#        || |      S c c}}w )Nr   )random)float16r   float64int8uint8int16uint16int32uint32int64uint64z=dtype must be a standard float or int dtype. Received: dtype=rT   c                    t         j                  j                  d      }d|j                  |       z  j	                  |      }t        j
                  ||j                  |       dk        }j                  j                  |      S )Nr      ffffff?)r2   rD  default_rngstandard_normalastypemultiplyrW   
from_denser   r>  rngr_   r`   s       r   	create_fnz'create_eager_tensors.<locals>.create_fn  sj    ii++A.,,U33;;B?KK3::e#4s#:;yy++A..r   rU   c                    t         j                  j                  d      }d|j                  |       z  j	                  |      }t        j
                  ||j                  |       dk        }j                  j                  |d      S )Nr   rP  rQ  r   )n_batch)r2   rD  rR  rS  rT  rU  BCOO	fromdense)r   r>  rX  r_   ra   s       r   rY  z'create_eager_tensors.<locals>.create_fn  so    ii++A.,,U33;;B?KK3::e#4s#:;!00A0>>r   z#Sparse is unsupported with backend c                    t         j                  j                  d      }d|j                  |       z  j	                  |      }t        j
                  ||j                  |       dk        }j                  j                  |d      S )Nr   rP  rQ  )padding)r2   rD  rR  rS  rT  rU  re   from_tensorrW  s       r   rY  z'create_eager_tensors.<locals>.create_fn  so    ii++A.,,U33;;B?KK3::e#4s#:;221a2@@r   z#Ragged is unsupported with backend c                 Z    t        j                  j                  | d      dz  |      S )Nr   r   r  )r   castuniform)r   r>  rD  s     r   rY  z'create_eager_tensors.<locals>.create_fn  s+    88uI6:" r   r;  )keras.src.backendrD  r}   r   r   
differencer   r   rT   r[   r\   rW   r1   r   r?  r	   r@  rA  )
r  rh   rW   rd   rY  rB  r   ra   rD  r`   s
          @@@r   r   r     sJ   (
4<<**	
 $g'
 	

 ??,#/ __%'88? 5goo6G5HI  
??,#A 5goo6G5HI 	
 +t$ $))+
1 q(+Yq%(-CC
 	
 %YUCC	
s   +Ec                 V    t        | t        t        f      xr t        d | D              S )Nc              3   R   K   | ]  }t        |t        t        d       f       ! y wr   )r1   intrj   )r,  es     r   r.  z!is_shape_tuple.<locals>.<genexpr>  s%      0-.
1sDJ'(0s   %')r1   rJ   rK   r   r   s    r   r   r     s.    a$' C 0230 - r   c                     t        |      r  t        |      |      S t        |t              r*t	        ||      D cg c]  \  }}t         ||       c}}S t        |t              rt         fdt	        ||      D              S t        |t              r2|j                         D ci c]  \  }}|t         |||          c}}S t        d| d|       c c}}w c c}}w )z<Variant of tree.map_structure that operates on shape tuples.c              3   >   K   | ]  \  }}t        ||        y wr   )rA  )r,  sr-  fns      r   r.  z,map_shape_dtype_structure.<locals>.<genexpr>  s$      
48Aq%b!Q/
s   z'Cannot map function to unknown objects z and )	r   rK   r1   rJ   rI   rA  r   r?  r   )rm  r   rh   rl  r-  rB  r   s   `      r   rA  rA    s    e%,&&%<?u<M
48Aq%b!Q/
 	
 % 
<?u<M
 
 	
 % 
1 (Qa99
 	

 5eWE%I
 	


s   C*C c                     g }t               }| j                  dd      D ]L  }|j                  D ];  }t        |      |vs|j	                  |       |j                  t        |             = N |S )z;Get a List of all seed generators in the layer recursively.T)r}   _flatten_layers_seed_generatorsidappendadd)r   seed_generatorsseen_idssublayersgs        r   r   r     sq    OuH))$5 %++ 	%B"vX%&&r*RV$	%%
 r   c                 v    fd G fddt         j                        } |dd      j                  |       S )Nc                    t        | t              rdt        |       dS t        | t              r| D cg c]
  } |       c}S t        | t              r*| j	                         D ci c]  \  }}| |       c}}S | S c c}w c c}}w )NrK   )r   	__value__)r1   rK   rJ   r   r?  )objri  keyvalue_tuple_encodes       r   r~  z*to_json_with_tuples.<locals>._tuple_encode  sx    c5!!(tCyAAc4 .12M!$22c4 @C		L*#uCu--LL
 3Ls   B)Bc                   "     e Zd Z fdZ xZS )6to_json_with_tuples.<locals>._PreserveTupleJsonEncoderc                 2     |      }t         |   |      S r   )r   encode)r   r{  r   r~  s     r   r  z=to_json_with_tuples.<locals>._PreserveTupleJsonEncoder.encode	  s    $C7>#&&r   )r   r   r   r  r   )r   r~  s   @r   _PreserveTupleJsonEncoderr    s    	' 	'r   r  TrP  )	sort_keysindent)jsonJSONEncoderr  )r}  r  r~  s     @r   rz   rz     s4    'D$4$4 '
 %tA>EEeLLr   c                 6    d }t        j                  | |      S )Nc                 V    t        | t              s| S d| vsd| vr| S t        | d         S )Nr   rz  )r1   r   rK   )r{  s    r   _tuple_decodez,from_json_with_tuples.<locals>._tuple_decode  s5    #t$Jc![%;JS%&&r   )object_hook)r  loads)r}  r  s     r   r~   r~     s    ' ::e77r   )*r  r%   r)   unittestpathlibr   numpyr2   absl.testingr   	keras.srcr   r   r   r   r	   keras.src.backend.commonr
   r   %keras.src.backend.common.global_stater   %keras.src.backend.common.keras_tensorr   keras.src.losses.lossr   keras.src.modelsr   keras.src.utilsr   r   r  r   r%  r  r9  r   r   r   rA  r   rz   r~   r   r   r   <module>r     s          &  "    3 6 ? = & " +};}%%x'8'8 };@<5""JDZ
.	M$8r   