o
    i e                     @   s~   d Z ddlZddlZddlmZ ddlmZ dd Zdd Z			dd
dZ
G dd dejZ											dddZdS )zCommon utils for benchmarks.    N)	callbacks)distribution_utilc                 C   s,   d| vsd| vrt d| dd 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)name r
   R/var/www/myenv/lib/python3.10/site-packages/keras/src/benchmarks/benchmark_util.pyget_benchmark_name   s   r   c                  G   s:   g }| D ]}| dd |D  | dd |D  q|S )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.
    c                 S   &   g | ]}|d  d f|dd  qS )r   _CPU   Nr
   .0paramr
   r
   r   
<listcomp>9      & z5generate_benchmark_params_cpu_gpu.<locals>.<listcomp>c                 S   r   )r   _GPUr   Nr
   r   r
   r
   r   r   <   r   )extend)params_listbenchmark_paramsparamsr
   r
   r   !generate_benchmark_params_cpu_gpu,   s   
r   .keras.cfit_graphc                 C   s   d| | dt | dS )Nkeras_examplesbs_)
model_nameimplementation
parameters)str)keras_model
batch_sizeimplr
   r
   r   get_keras_examples_metadataA   s   
r%   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )TimerCallBackz1Callback for logging time in each epoch or batch.c                 C   s"   g | _ tj| _t | _d| _d S )NF)timestimeitdefault_timertimerstartup_timerecorded_startup)selfr
   r
   r   __init__N   s   

zTimerCallBack.__init__c                 C   s   |   | _d S N)r*   epoch_start_timer-   elogsr
   r
   r   on_epoch_beginT   s   zTimerCallBack.on_epoch_beginc                 C   s   | j |  | j  d S r/   )r'   appendr*   r0   r1   r
   r
   r   on_epoch_endW   s   zTimerCallBack.on_epoch_endc                 C   s$   | j s|  | j | _d| _ d S d S )NT)r,   r*   r+   r1   r
   r
   r   on_batch_endZ   s   
zTimerCallBack.on_batch_endN)__name__
__module____qualname____doc__r.   r4   r6   r7   r
   r
   r
   r   r&   K   s    r&             offc           #   	   C   s,  |du rt d|du rt d|du rt d|
dk r t d|jd }g g g }}}g g g }}}|| }tj||
d}t|D ]}tj}| }t|}|# | }|  }| | }| }|j|||d | | }W d   n1 syw   Y  |j	|||d	d
 t
 }| }|j	|||||g|	d | } || || ||j |t|j || |  ||| |   qDg }|dt|d |dt|d |dt|d |dt|d |dt|d |d|d t|}!||
d}"||!|"fS )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
        `tf.keras.optimizers`.
      loss: String (name of objective function), objective function or
        `tf.keras.losses.Loss` instance. See `tf.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)rE   rF   r#   rG   r   verbose
build_time)r	   valuecompile_timer+   avg_epoch_timeexp_per_secrG   )r   shaper   get_distribution_strategyranger(   r)   get_strategy_scopecompilefitr&   r5   r+   npmeanr'   )#model_fnrE   rF   rG   r#   	run_itersrB   rC   rD   rH   rA   r@   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modelrI   t1rK   cbkt2end_time	wall_timeextrasr
   r
   r   measure_performance`   s   1






rk   )r   )NNr<   r=   r>   NNNr   r   r?   )r;   r(   numpyrT   	keras.srcr   keras.src.benchmarksr   r   r   r%   Callbackr&   rk   r
   r
   r
   r   <module>   s,   

