
    6biT}                     H   S 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Jr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  S rSS jrS r         SS jr! SS jr" SS jr# " S S\RH                  5      r%S r& " S S\RH                  5      r'g)zEPart of the TF-Keras training engine related to distributed training.    N)backend)	callbacks)distribute_coordinator_utils)distributed_training_utils_v1)partial_batch_padding_handler)training_arrays_v1)training_utils_v1)Progbar)ModeKeys)	input_lib)
tf_loggingc                     U R                  U5      nUR                  UR                  UR                  UR                  4$ N)_make_execution_functioninputsoutputs
updates_opsession_kwargs)modelmode	exec_funcs      e/home/james-whalen/.local/lib/python3.13/site-packages/tf_keras/src/engine/training_distributed_v1.py_per_replica_execution_functionr   #   s@    ..t4I  	     c                     UR                   (       a  [        R                  " XX#US9  g [        R                  " XX#U5        g )N)r   targets)_compile_distribution
dist_utilsclone_model_on_replicas_build_distributed_network)strategyr   r   r   r   s        r   _build_modelr"   -   s7    ""**T'	
 	--T7	
r   c                     ^ ^^^ UU UU4S jnU$ )a$  Create step fn.

Args:
  model: a TF-Keras Model instance.
  mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT.
  strategy: a `tf.distribute.Strategy` instance.
  output_labels: the output labels for the step function.

Returns:
  A step function to run by `tf.distribute.Strategy`.
c                   > [        U[        [        45      (       a  [        U5      S:X  a  Uu  pOSn[        U[        5      (       a  TR
                   Vs/ s H  o1U   PM	     nn[        TTTX5        TR                  R                  [        [        R                  " TT5      T4S9u  nnnn[        R                  " TUUUU5      u  nn	n
n[        R                  " UU	4U
S[        T5      -   S-   S.UD6n[!        TUR"                  5       Hf  u  pUS:X  a%  [$        R&                  R(                  R*                  nO$[$        R&                  R(                  R,                  nU R/                  XU5        Mh     UR0                  $ s  snf )z"A step fn that returns update ops.   Nargsdistributed_	_function)updatesnameloss)
isinstancetuplelistlendict_feed_input_namesr"   extendedcall_for_each_replicar   r   get_distributed_modelunwrap_valuesr   functionstrzipr   tf
distributeReduceOpSUMMEANset_last_step_outputr   )ctxr   r   
input_namegrouped_inputsgrouped_outputsgrouped_updatesgrouped_session_args
all_inputsall_outputsall_updatesall_session_argscombined_fnlabeloutput	reduce_opr   r   output_labelsr!   s                   r   _step_fn%_make_train_step_fn.<locals>._step_fnE   s   fudm,,V1A$OFGG fd##5:5L5L5Lzz"5L   	XudF< 33+225$?F 4 
	
  $$ 
	
 &&
  #d)+k9	

 
 !0C0CDMEMM2266	 MM2277	$$UI> E %%%_s   F )r   r   r!   rN   rO   s   ```` r   _make_train_step_fnrR   8   s    =& =&~ Or   c
                  
   [         R                  n
U R                  n[        XkR                  R
                  5      n[        R                  " USSS9n[        R                  " X5      n[        R                  " USS9nUR                  5         U R                  =(       d    / n[        U [         R                  UU5      n0 n[        R                  " S5      US'   U R!                  5        HK  nUR#                  5       n[        R$                  " UR&                  UR(                  5      UUR*                  '   MM     UR                  R-                  UUUUS9nUR.                  nUR0                  n[3        U5      nU R4                  (       a  [        R6                  " X
5        [8        R:                  " UU UUUUS	U
S
9nUR                  R
                  /XkR                  R
                  -  -  nXkR                  R
                  -  (       a'  UR=                  XkR                  R
                  -  5        [?        U5      nURA                  U
5        U RC                  XZ5      n[E        XR5       GH  n[        RF                  " U 5        URI                  U5        0 nSnSnSnUU:  a  UU   n USU S.n!URK                  U
SUU!5        Ub  U U:w  a5  [        RL                  " 5       RO                  URQ                  U 5      5        U n [        RR                  " UU/5      u  n"n#U!R]                  U#5        URK                  U
SUU!5        UU -   nUS-  nUR^                  R`                  (       a  OUU:  a  M  U(       a  [b        Rd                  " U	U5      (       a  [X        Rf                  " SU5        U R4                  (       a%  [        Rh                  " U [         R                  5        [k        U UUUUS9n$[m        U$[n        5      (       d  U$/n$[q        UU$5       H  u  n%n&U&USU%-   '   M     URs                  UU5        UR^                  R`                  (       d  GM    O   SU l:        URw                  U
5        U R4                  (       a%  [        Rh                  " U [         R                  5        URy                  SSS5        U Rz                  $ ! [        RT                  RV                   a!    [X        RZ                  " SU-  U-  5         GM  f = f)a  Fit loop for training with TPU tf.distribute.Strategy.

Args:
    model: TF-Keras Model instance.
    dataset: Dataset that returns inputs and targets
    epochs: Number of times to iterate over the data
    verbose: Integer, Verbosity mode, 0, 1 or 2
    callbacks: List of callbacks to be called during training
    initial_epoch: Epoch at which to start training
        (useful for resuming a previous training run)
    steps_per_epoch: Total number of steps (batches of samples)
        before declaring one epoch finished and starting the
        next epoch. Ignored with the default value of `None`.
    val_dataset: Dataset for validation data.
    validation_steps: Number of steps to run validation for
        (only if doing validation from data tensors).
        Ignored with the default value of `None`.
    validation_freq: Only relevant if validation data is provided. Integer
        or `collections.abc.Container` instance (e.g. list, tuple, etc.). If
        an integer, specifies how many training epochs to run before a new
        validation run is performed, e.g. `validation_freq=2` runs
        validation every 2 epochs. If a Container, specifies the epochs on
        which to run validation, e.g. `validation_freq=[1, 2, 10]` runs
        validation at the end of the 1st, 2nd, and 10th epochs.

Returns:
    Returns `None`.

Raises:
    ValueError: in case of invalid arguments.
int32steps_per_run)valuedtyper+      r!   learning_phaseg    cAr,   )
iterationsinitial_loop_valuesstepsdo_validationepochssteps_per_epochverbose
count_moder   r   N)batchsize	num_stepsbeginzYour dataset iterator ran out of data; interrupting training. Make sure that your dataset can generate at least `steps_per_epoch * epochs` batches (in this case, %d batches).endz#Running validation at fit epoch: %s)r]   rb   r   val_T)>r   TRAIN_distribution_strategyminr3   rU   r   variabler   get_iteratordistributed_scope	__enter__metrics_namesrR   r:   constant_get_training_eval_metricsresultzerosshaperW   r+   "experimental_run_steps_on_iteratorrun_oplast_step_outputsboolr   "_copy_weights_to_distributed_modelcbksconfigure_callbacksappendr0   _call_begin_hook#_maybe_load_initial_epoch_from_ckptrange_reset_metricson_epoch_begin_call_batch_hookget_sessionrunassignbatch_get_valueerrorsOutOfRangeErrorloggingwarningupdater   stop_trainingr	   should_run_validationinfo_copy_weights_to_original_modelexperimental_tpu_test_loopr-   r/   r9   on_epoch_end_successful_loop_finish_call_end_hook__exit__history)'r   datasetr`   rb   r   initial_epochra   val_datasetvalidation_stepsvalidation_freqr   current_strategyiteration_valuerU   iteratorscope
out_labelsstep_fnr\   mtensorr@   train_opoutput_tensorsr_   steps_to_runtarget_stepsepoch
epoch_logs
step_indexprev_step_countcurrent_step
step_count
batch_logs_r   val_outsrK   val_outs'                                          r   experimental_tpu_fit_loopr      s   V >>D3322@@O $$W?M
 &&wAH((!!E 
OO$$*J!x~~/G
 "$++c"2--/&(hhv||V\\&JAFF# 0 
#
#
F
F /	 G C zzH**N)*M""55eB((#'	I %--;;<44BBBL 22@@@77EEE	
 |$Lt$==M }-!!%(  '

\)%l3J#'J
 &&tWj*M&**G##%))-*>*>z*JK",$44h5OP
7 g&&&tUJ
K#j0JAL,,= \)@ .DDU
 
 LL>F** ::8>> 2&#H h--$:"%j(";w-4
6E>* #< 	uj1??(((G .H %)E!T"""225(..I	NN4t$==o 99,, 	: &	&
  	s   <R>>:S=<S=c                   ^ ^ [         R                  mT R                  n[        R                  " X5      n[        R
                  " USS9nUR                  5         T R                  nUU 4S jn	UR                  5       n
UR                  X4S9n0 n[        X5       Hf  u  pUS:X  a%  [        R                  R                  R                  nO$[        R                  R                  R                  nUR!                  XSS9X'   Mh     [        R"                  " [%        UR'                  5       5      5      nUS:  a	  [)        US	9nT R*                  (       a  [        R,                  " T T5        [        R.                  " T 5        [0        R2                  " UT S
SUUS[         R                  S9nUR5                  T5        S/[7        T R                  5      -  nUb  UnO[9        S5      eSnUU:  a  USS.nUR;                  TSUU5         [<        R>                  " UU/5      u  nn[K        T R                  5       H&  u  nnUS:X  a  UU==   UU   -  ss'   M  UU   UU'   M(     URM                  T UUT5      nUR;                  TSUU5        US:X  a  WRO                  US-   5        US-  nUU:  a  M  US:  a  WRO                  U5        URQ                  T5        URS                  SSS5        [7        U5      S:  a  US==   U-  ss'   [7        U5      S:X  a  US   $ U$ ! [        R@                  RB                   a0    SRE                  U5      n[F        RH                  " SU-   5        Un M  f = f)a  Test loop for evaluating with TPU tf.distribute.Strategy.

Args:
    model: TF-Keras Model instance.
    dataset: Dataset for input data.
    verbose: Integer, Verbosity mode 0 or 1.
    steps: Total number of steps (batches of samples)
        before declaring predictions finished.
        Ignored with the default value of `None`.
    callbacks: List of callbacks to be called during training

Returns:
    Scalar loss (if the model has a single output and no metrics)
    or list of scalars (if the model has multiple outputs
    and/or metrics). The attribute `model.metrics_names` will give you
    the display labels for the outputs.
r   rY   c                   > [        U [        [        45      (       a  [        U 5      S:X  a  U u  pOSn[        R
                  R                  5       R                  [        TTX4S9  [        [        R                  " TT5      T5      u  p#pB[        R                  " U/5         U Vs/ s H  n[        R                  " U5      PM     snsSSS5        $ s  snf ! , (       d  f       g= f)z-A fn that returns output of single test step.r%   Nr&   )r-   r.   r/   r0   r:   r;   get_replica_context
merge_callr"   r   r   r5   control_dependenciesidentity)r   r   r   r   r*   outr   r   s         r   _test_step_fn1experimental_tpu_test_loop.<locals>._test_step_fng  s    fudm,,V1A$OFGG MM--/::E4#A ; 
 $C,,UD94$
 W $$gY/078BKK$8 0/8 0/s   !C& CCC
C%r&   r,   NaxisrX   targetFr]   r^           TNumber of steps could not be inferred from the data, please pass the steps argument.rd   re   rg   ]Make sure that your dataset can generate at least `steps` batches (in this case, {} batches).@Your dataset iterator ran out of data; interrupting evaluation. rh   )*r   TESTrk   r   rn   ro   rp   rq   get_nextr   r9   r:   r;   r<   r=   r>   reducegroupr/   valuesr
   r   r{   r   r|   r}   r   r0   
ValueErrorr   r   r   r   r   formatr   r   	enumerate	make_logsr   r   r   )r   r   rb   r]   r   r   r   r   r   r   test_input_dataper_replica_outputsr   rK   rL   rM   test_opprogbaroutsr   r   r   r   
batch_outswarning_msgir   s   `                         @r   r   r   H  sW   ( ==D33&&wAH((!!E 
OO$$J9& '')O*... /  NZ=F?..22I ..33I 0 7 7D !8 !
 > hhtN11345G!|'""55eTBe$((]]	I t$53u**++D.
 	

 L

%+Q7
""4,
K	#33Wn4MNMAz "%"5"56HAuAvQ:e,, %U+Q 7 ((
D$G
""4jIa<NN<!+,= 
%@ !||$T"	NN4t$
4y1}Q<
4yA~AwKM yy(( 	>>DfUm 
 OO,.9: (L	s   L A
M('M(c                   ^ ^  [         R                  m [        R                  " U5      nSnU(       d  [        R
                  " T R                  5      n[        R                  " U5      u  pxn	Xvl	        UR                  UR                  UR                  5      Ul        UR                  UR                  5      nUR                  5       nUR!                  USS9nU	b  UR#                  U	5      nT R$                  n
[        R&                  " X5      n[        R(                  " U
SS9nUR+                  5         U U 4S jnUR-                  5       nU
R/                  X4S9n[        R0                  " X5      nUS:  a	  [3        US	9nT R4                  (       a  [        R6                  " T T 5        [        R8                  " T 5        [:        R<                  " UT S
SUUST S9nUR?                  T 5        [A        T RB                  5      n[E        U5       Vs/ s H  n/ PM     nnUb  UnO[G        S5      eSnUU:  a  USS.nURI                  T SUU5         [J        RL                  " U5      n[N        RP                  " UU/5      u  nn[E        U5       H:  nUU
R\                  -  nUU
R\                  -   nUUU nUU   R_                  U5        M<     URa                  T UUT 5      nURI                  T SUU5        US:X  a  WRc                  US-   5        US-  nUU:  a  M  US:  a  WRc                  U5        URe                  T 5        URg                  SSS5        [A        U5      S:X  a  [h        Rj                  " US   SS9nO%U Vs/ s H  n[h        Rj                  " USS9PM     nnU(       a  URm                  U5      nU$ s  snf ! [J        RR                  RT                   a.    SRW                  U5      n[X        RZ                  " SU-   5         M  f = fs  snf )a'  Predict loop for predicting with TPU tf.distribute.Strategy.

Args:
    model: TF-Keras Model instance.
    dataset: Dataset for input data.
    verbose: Integer, Verbosity mode 0 or 1.
    steps: Total number of steps (batches of samples)
        before declaring `_predict_loop` finished.
        Ignored with the default value of `None`.
    callbacks: List of callbacks to be called during training

Returns:
    Array of predictions (if the model has a single output)
    or list of arrays of predictions
    (if the model has multiple outputs).
NT)drop_remainderr   rY   c                 n  > [         R                  R                  5       R                  [        TTU 4S9  [        [        R                  " TT5      T5      u  pp1[         R                  " U/5         U Vs/ s H  n[         R                  " U5      PM     snsSSS5        $ s  snf ! , (       d  f       g= f)z3A fn that returns output of single prediction step.r&   N)
r:   r;   r   r   r"   r   r   r5   r   r   )r   r   r   r*   r   r   r   s        r   _predict_step_fn7experimental_tpu_predict_loop.<locals>._predict_step_fn  s     MM--/::E4#8 ; 
 $C,,UD94$
 W $$gY/078BKK$8 0/8 0/s   0B&5 B!B&!B&&
B4r&   rX   r   Fr]   r^   r   r   rg   r   r   rh   r   )7r   PREDICTr   is_dataset_shape_fully_definedpadding_utilPartialBatchPaddingHandler_feed_output_shapesr   _get_dataset_attributespadded_batch_sizer   padding_maskupdate_maskmap	pad_batchunbatchrd   prefetchrk   rn   ro   rp   r   r   flatten_per_replica_valuesr
   r   r{   r   r|   r}   r   r0   output_namesr   r   r   r:   r   r   r   r   r   r   r   r   num_replicas_in_syncextendr   r   r   r   npconcatenate
apply_mask)!r   r   rb   r]   r   dataset_fully_shapedpadding_handler
batch_sizer   prefetch_bufferr   r   r   r   predict_input_datar   r   r   num_model_outputsunconcatenated_outsr   r   r   predict_opsr   r   r   output_start_indexoutput_end_indexsingle_model_outputprediction_resultr   r   s!   `                               @r   experimental_tpu_predict_loopr     s(   & D%DDWMO 'AA%%
 *3)J)J*
&
 -7)'.~~((/*E*E(
$ ++o778//# --
4-@&&&7G33&&wAH((!!E 
OO9& "**,*..4 /   ::N !|'""55eTBe$((	I t$
 E../',->'?@'?!2'?@.
 	

 L

%+Q7
""4,
K	((>2K#33n-MAz$ ()A!"%5%J%J!J"%5%J%JJ  #-"#3#  "))*=> * ((
JM
""4jIa<NN<!+,K 
%N !||$T"	NN4t$
1$NN+>q+AJ 4G
3FCBNN3Q'3F 	 
 +667HIG A& yy(( 
	>>DfUm 
 OO,.9: 
	R
s   
N61N; ;P
;APPc                   j    \ rS rSrSr               SS jr       S	S jr    S
S jrSrg)$DistributionSingleWorkerTrainingLoopi  z;Training loop for distribution strategy with single worker.Nc                 N   [         R                  " XqR                  S9  [         R                  " X#5        [         R                  " UR
                  UUU[        R                  US9u  pNUR                  XNU5      nUR                  UUUUUUU
US9n[         R                  " U5      (       d;  UR
                  R                  5          UR                  UUUUUU
S9u  n  nSSS5        SnU	(       a}  [        R                  " U	5      u  nnn[         R                  " UU5        [         R                  " UR
                  UUU[        R                  5      u  nnUR                  UUUSUUU
SS9nOU(       a  [!        S5      e["        R$                  " UR
                  5      (       aR  [        R&                  " UUUUS	S
9nUc  [!        S5      e[(        R*                  " 5       (       d  [-        UUUUUUUUUUS9
$ [.        R0                  " UUUUUUUU
UUUUS	S9$ ! , (       d  f       GN>= f)z%Fit loop for Distribution Strategies.)input_callbacks	optimizer)validation_split)sample_weightclass_weightr   r  shuffler`   )r  r  r   r  r  NT)r  r  r   r  r  allow_partial_batchzHvalidation_split argument is not supported with distribution strategies.ra   
steps_namez^Number of steps could not be inferred from the data, please pass the steps_per_epoch argument.)r`   rb   r   r   r   ra   r   r   )r   r`   rb   r   
val_inputsr  r   ra   r   r   r  )r   validate_callbacksr  validate_inputsprocess_batch_and_step_sizerk   r   rj   _validate_or_infer_batch_size#_distribution_standardize_user_datais_distributing_by_cloningr   _standardize_user_datar	   unpack_validation_datar   r   r   is_tpu_strategyinfer_steps_for_datasetr:   executing_eagerlyr   r   fit_loop)selfr   xyr   r`   rb   r   r  validation_datar  r  r  r   ra   r   r   kwargsr   r   r   val_xval_yval_sample_weightss                           r   fit(DistributionSingleWorkerTrainingLoop.fit  sx   * 	%%%	
 	""1(&0&L&L((NN-'
#
 88

 ;;'%!- < 	
 44U;;--335"'">">"/!-)%5# #? #!Q 6 
 "88I	"&&ue4","H"H,, #A  CC0!%!1$( D 	K + 
 ""5#?#?@@/GG,O & @ 
 ''))0!#' +"/$3%5$3  "**!"'+-+(
 	
O 65s   H
H$c	           	         [         R                  " X#5        [         R                  " UR                  X$U[        R
                  5      u  pGUR                  XGU5      nUR                  UUUUSS9n
[        R                  " UR                  5      (       aK  [        R                  " XUSS9nUc  [        S5      e[        R                  " 5       (       d  [        UU
UUUS9$ [         R"                  " UU
UUUUS9$ )z*Evaluate loop for Distribution Strategies.T)r  r   r  r]   r  r   rb   r]   r   )r   r   rb   r]   r   )r   r  r  rk   r   r   r  r  r   r  r	   r  r   r:   r  r   r   	test_loop)r  r   r  r  r   rb   r  r]   r   r  r   s              r   evaluate-DistributionSingleWorkerTrainingLoop.evaluate  s    	""1(&BB((!

 88AN
;;'! $ < 
 ""5#?#?@@%=='E } 6 
 ''))1#'  "++!
 	
r   c           	         [         R                  " USS9  [         R                  " UR                  X#U[        R
                  5      u  p5UR                  X5U5      nUR                  X#SS9n[        R                  " UR                  5      (       aK  [        R                  " XUSS9nUc  [        S5      e[        R                  " 5       (       d  [        UUUUUS9$ [         R"                  " UUUUUUS	9$ )
z)Predict loop for Distribution Strategies.N)r  r  T)r   r  r]   r  r   r!  )r   rb   r]   r   )r   r  r  rk   r   r   r  r  r   r  r	   r  r   r:   r  r   r   predict_loop)	r  r   r  r   rb   r]   r   r  r   s	            r   predict,DistributionSingleWorkerTrainingLoop.predictH  s    	""Q$/&BB((!@P@P

 88AN
;;$ < 
 ""5#?#?@@%=='E } 6  ''))4#'  "..!
 	
r   rQ   )NNNrX   rX   Nr   NTNNr   NNrX   )NNNrX   NNN)Nr   NN)	__name__
__module____qualname____firstlineno____doc__r  r#  r'  __static_attributes__rQ   r   r   r   r     sk    E
 
#E
T 
5
v +
r   r   c                    ^  U 4S jnU$ )zCDecorator handles multi worker training with distribution strategy.c                 Z   >^ ^ UUU 4S jn[         R                  " UT R                  5      $ )Nc                 r   > TR                  SS 5      n[        R                  " UT5      nUTS'   T" T40 TD6$ )Nr   )popr   filter_distributed_callbacks)r   r   filtered_callbacksr  methodr   s      r   
_worker_fn=_train_with_multi_worker.<locals>.wrapper.<locals>._worker_fnz  sE    

;5I!+!H!H5" #5F;%*6**r   )dcrun_distribute_coordinatorrk   )r   r  r6  r5  s   `` r   wrapper)_train_with_multi_worker.<locals>.wrappery  s(    	+ ,,44
 	
r   rQ   )r5  r:  s   ` r   _train_with_multi_workerr<  v  s    
 Nr   c                   0    \ rS rSrSrS rS rS rS rSr	g)	#DistributionMultiWorkerTrainingLoopi  z=Training loop for distribution strategy with multiple worker.c                     Xl         g r   _single_worker_loop)r  single_worker_loops     r   __init__,DistributionMultiWorkerTrainingLoop.__init__  s    #5 r   c                 L    [        U R                  R                  5      " U0 UD6$ r   )r<  rA  r  r  r'   r  s      r   r  'DistributionMultiWorkerTrainingLoop.fit  s+    '(@(@(D(DE

 	
r   c                 L    [        U R                  R                  5      " U0 UD6$ r   )r<  rA  r#  rF  s      r   r#  ,DistributionMultiWorkerTrainingLoop.evaluate  s+    '(@(@(I(IJ

 	
r   c                 :    U R                   R                  " U0 UD6$ r   )rA  r'  rF  s      r   r'  +DistributionMultiWorkerTrainingLoop.predict  s    ''//@@@r   r@  N)
r)  r*  r+  r,  r-  rC  r  r#  r'  r.  rQ   r   r   r>  r>    s    G6



Ar   r>  r   )d   rX   Nr   NNNrX   )r   NN)(r-  numpyr   tensorflow.compat.v2compatv2r:   tf_keras.srcr   r   r|   tf_keras.src.distributer   r8  r   r   tf_keras.src.enginer   r   r   r	    tf_keras.src.utils.generic_utilsr
   tf_keras.src.utils.mode_keysr   tensorflow.python.distributer   tensorflow.python.platformr   r   r   r"   rR   r   r   r   TrainingLoopr   r<  r>  rQ   r   r   <module>rY     s    L  ! !   * F O M 2 1 4 1 3 <
Ld ~D 6:L` 6:m`l
+<+I+I l
^&A*;*H*H Ar   