
    0h                         d Z ddlZddlZddlmZ ddlmZ d Zd Z		 ddZ
 G d d	ej                        Z	 	 	 	 	 	 	 	 	 	 	 dd
Zy)zCommon utils for benchmarks.    N)	callbacks)distribution_utilc                 n    d| vsd| vrt        d      | j                  d      d   j                  d      S )al  Split the suffix of the benchmark name.

    For example, for the name = 'benchmark_layer_call__Conv2D_small_shape',
    the return value is ['Conv2D', 'small', 'shape'].

    This is to generate the metadata of the benchmark test.

    Args:
      name: A string, the benchmark name.

    Returns:
      A list of strings of the suffix in the benchmark name.
    ___z*The format of the benchmark name is wrong.)
ValueErrorsplit)names    `/var/www/html/engine/venv/lib/python3.12/site-packages/tf_keras/src/benchmarks/benchmark_util.pyget_benchmark_namer      s=     43d?EFF::dB%%c**    c            
          g }| D ]Z  }|j                  |D cg c]  }|d   dz   f|dd z    c}       |j                  |D cg c]  }|d   dz   f|dd z    c}       \ |S c c}w c c}w )zExtend the benchmark names with CPU and GPU suffix.

    Args:
      *params_list: A list of tuples represents the benchmark parameters.

    Returns:
      A list of strings with the benchmark name extended with CPU and GPU
      suffix.
    r   _CPU   N_GPU)extend)params_listbenchmark_paramsparamsparams       r   !generate_benchmark_params_cpu_gpur   ,   s      
=CDEuQx& "U12Y.D	
 	=CDEuQx& "U12Y.D	
	
  E Es   A$
A)
c                 ,    d| |z   dt        |      z   dS )Nkeras_examplesbs_)
model_nameimplementation
parameters)str)keras_model
batch_sizeimpls      r   get_keras_examples_metadatar#   A   s%     '%,c*o- r   c                   (    e Zd ZdZd Zd Zd Zd Zy)TimerCallBackz1Callback for logging time in each epoch or batch.c                 |    g | _         t        j                  | _        t        j                         | _        d| _        y )NF)timestimeitdefault_timertimerstartup_timerecorded_startup)selfs    r   __init__zTimerCallBack.__init__N   s/    
))
"002 %r   c                 .    | j                         | _        y N)r*   epoch_start_timer-   elogss      r   on_epoch_beginzTimerCallBack.on_epoch_beginT   s     $

r   c                 p    | j                   j                  | j                         | j                  z
         y r0   )r'   appendr*   r1   r2   s      r   on_epoch_endzTimerCallBack.on_epoch_endW   s%    

$**,)>)>>?r   c                 p    | j                   s*| j                         | j                  z
  | _        d| _         y y )NT)r,   r*   r+   r2   s      r   on_batch_endzTimerCallBack.on_batch_endZ   s1    $$ $

t/@/@ @D$(D! %r   N)__name__
__module____qualname____doc__r.   r5   r8   r:    r   r   r%   r%   K   s    ;&-@)r   r%   c           	         |t        d      |t        d      |t        d      |
dk  rt        d      |j                  d   }g g g }}}g g g }}}||z  }t        j                  ||
      }t	        |      D ]R  }t
        j                  } |       }t        j                  |      }|5   |       } |        } |       |z
  } |       }|j                  |||        |       |z
  }ddd       j                  |||d	
       t               } |       }|j                  |||||g|	        |       } |j                         |j                         |j                  |j                         |j                  t        j                  |j                               |j                  | |z
         |j                  || |z
  z         U g }|j                  dt        j                  |      d       |j                  dt        j                  |      d       |j                  dt        j                  |      d       |j                  dt        j                  |      d       |j                  dt        j                  |      d       |j                  d|d       t        j                  |      }!||
d}"||!|"fS # 1 sw Y   xY w)a  Run models and measure the performance.

    Args:
      model_fn: Model function to be benchmarked.
      x: Input data. See `x` in the `fit()` method of `keras.Model`.
      y: Target data. See `y` in the `fit()` method of `keras.Model`.
      epochs: Integer. Number of epochs to train the model.
        If unspecified, `epochs` will default to 2.
      batch_size: Integer. Number of samples per gradient update. If
        unspecified, `batch_size` will default to 32.
      run_iters: Integer. Number of iterations to run the performance
        measurement.  If unspecified, `run_iters` will default to 4.
      optimizer: String (name of optimizer) or optimizer instance. See
        `keras.optimizers`.
      loss: String (name of objective function), objective function or
        `keras.losses.Loss` instance. See `keras.losses`.
      metrics: Lists of metrics to be evaluated by the model during training.
        See `metrics` in the `compile()` method of  `keras.Model`.
      verbose: 0, 1, 2. Verbosity mode. See `verbose` in the `fit()` method of
        `keras.Model`. If unspecified, `verbose` will default to 0.
      num_gpus: Number of GPUs to run the model.
      distribution_strategy: Distribution strategies. It could be
        `multi_worker_mirrored`, `one_device`, `mirrored`. If unspecified,
        `distribution_strategy` will default to 'off'. Note that, `TPU`
        and `parameter_server` are not supported yet.

    Returns:
      Performance summary, which contains build_time, compile_time,
      startup_time, avg_epoch_time, wall_time, exp_per_sec, epochs,
      distribution_strategy.

    Raise:
      ValueError: If `x` is none or if `optimizer` is not provided or
      if `loss` is not provided or if `num_gpus` is negative.
    NzInput data is required.zOptimizer is required.zLoss function is required.r   z`num_gpus` cannot be negative)distribution_strategynum_gpus)	optimizerlossmetricsr   )xyr!   epochs)rF   rG   r!   rH   r   verbose
build_time)r   valuecompile_timer+   avg_epoch_timeexp_per_secrH   )r	   shaper   get_distribution_strategyranger(   r)   get_strategy_scopecompilefitr%   r7   r+   npmeanr'   )#model_fnrF   rG   rH   r!   	run_itersrC   rD   rE   rI   rB   rA   num_examplesbuild_time_listcompile_time_liststartup_time_listavg_epoch_time_listwall_time_listexp_per_sec_listtotal_num_examplesstrategyr   r*   
start_timestrategy_scopet0modelrJ   t1rL   cbkt2end_time	wall_timeextrass#                                      r   measure_performancerl   `   s   b 	y233		122	566	A899 771:L<>B(9&O<>B)9,. ::3hH 9 $F$$W
*==hG 	(BJE2JBMM#  
 !7R<L	( 			Az!	<oW		!e 	 	
 7z*  .  !1!12""277399#56h34 2hm DEI$FL GNNL277?3KLMNN"''2C*DE NN"''2C*DE NN!BGG4G,HI NNMBGG<L4MNONNHv67'I!6F
 Iv%%k	( 	(s   ,>KK	)z.keras.cfit_graph)NN          NNNr   r   off)r>   r(   numpyrU   tf_keras.srcr   tf_keras.src.benchmarksr   r   r   r#   Callbackr%   rl   r?   r   r   <module>ru      se    #   " 5+&, #6)I&& ). 
	@&r   