
    AVhD                        d Z ddlZddlZddlZddlZddlZddl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  e       ZdZdZd Z	 	 d!dZ  G d de!      Z" edg        G d de"             Z# G d de"      Z$ ed      d        Z% ed       G d de$             Z&d Z'd"d Z(y)#zUtilities to run benchmarks.    N)app)
config_pb2)rewriter_config_pb2)test_log_pb2)timeline)ops)gfile)
tf_logging)
tf_inspect)	tf_exportTEST_REPORT_FILE_PREFIXTF_OVERRIDE_GLOBAL_THREADPOOLc                     | j                   }|j                  ||      }t        j                  || j                  || j
                  | j                        S )z<Rename the given function's name appears in the stack trace.)co_argcountco_name)__code__replacetypesFunctionType__globals____defaults____closure__)farg_numname	func_codenew_codes        T/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/platform/benchmark.py_rename_functionr   3   sJ    jj)7DA(			HammT1>>MM
+ +    c                 
   t        j                  d| ||nd||nd||nd||nd|rt        |      nd|rt        |      nd       t        j                         }|j
                  j                         }| |_        |||_        |||_	        |||_
        |||_        |t        |t              st        d      |j                         D ]Q  \  }	}
t        |
t         j"                        r|
|j$                  |	   _        5t        |
      |j$                  |	   _        S |t        |t*              st        d      |D ]  }d|vrt        d      d	|vrt        d
      |j,                  j                         }|d   |_        |d	   |_        d|v r|d   |j0                  _        d|v sl|d   |j2                  _         t4        j6                  j9                  t:        d      }|t=        t        |             y|j?                         }| jA                  dd      }||}tC        jD                  |      rtG        d|z        tC        jH                  |d      5 }|jK                  |       ddd       y# 1 sw Y   yxY w)a  Method for recording a benchmark directly.

  Args:
    name: The BenchmarkEntry name.
    iters: (optional) How many iterations were run
    cpu_time: (optional) Total cpu time in seconds
    wall_time: (optional) Total wall time in seconds
    throughput: (optional) Throughput (in MB/s)
    extras: (optional) Dict mapping string keys to additional benchmark info.
    metrics: (optional) A list of dict representing metrics generated by the
      benchmark. Each dict should contain keys 'name' and'value'. A dict
      can optionally contain keys 'min_value' and 'max_value'.

  Raises:
    TypeError: if extras is not a dict.
    IOError: if the benchmark output file already exists.
  z]Benchmark [%s] iters: %d, wall_time: %g, cpu_time: %g,throughput: %g, extras: %s, metrics: %sNNonezextras must be a dictzmetrics must be a listr   zmetric must has a 'name' fieldvaluezmetric must has a 'value' field	min_value	max_value/__zFile already exists: %swb)&logginginfostrr   BenchmarkEntriesentryaddr   iterscpu_time	wall_time
throughput
isinstancedict	TypeErroritemsnumbersNumberextrasdouble_valuestring_valuelistmetricsr$   r%   r&   osenvirongetTEST_REPORTER_TEST_ENVprintSerializeToStringr   r	   ExistsIOErrorGFilewrite)r   r0   r1   r2   r3   r:   r>   entriesr.   kvmetricmetric_entrytest_envserialized_entrymangled_nameoutput_pathouts                     r   _global_report_benchmarkrS   ;   st   ( 
,, 9:>)ur%1yr#/xR'3z$s6{&&s7|F4 ))+'
--


%%*
EKENEO!Efd#-..,,. .A	Aw~~	&'(Q$'*1vQ$	.
 gt$.// ;	v	899		9::]]&&(l .l!'?l		'-k':$		'-k':$; ZZ^^2D9(	#g,
..0c4(,"L1+
\\+
+k9
::{{;%  II     s   I99Jc                       e Zd ZdZd Zy)_BenchmarkRegistrarzAThe Benchmark class registrar.  Used by abstract Benchmark class.c                     t         j                  | |||      }|j                         st        j	                  |       |S N)type__new__is_abstractGLOBAL_BENCHMARK_REGISTRYr/   )mcsclsnamebaseattrsnewclasss        r   rY   z_BenchmarkRegistrar.__new__   s5    ||C$6H!##H-Or    N)__name__
__module____qualname____doc__rY    r    r   rU   rU      s
    Ir    rU   z(__internal__.test.ParameterizedBenchmark)v1c                   "     e Zd ZdZ fdZ xZS )ParameterizedBenchmarkaD  Metaclass to generate parameterized benchmarks.

  Use this class as a metaclass and override the `_benchmark_parameters` to
  generate multiple benchmark test cases. For example:

  class FooBenchmark(metaclass=tf.test.ParameterizedBenchmark,
                     tf.test.Benchmark):
    # The `_benchmark_parameters` is expected to be a list with test cases.
    # Each of the test case is a tuple, with the first time to be test case
    # name, followed by any number of the parameters needed for the test case.
    _benchmark_parameters = [
      ('case_1', Foo, 1, 'one'),
      ('case_2', Bar, 2, 'two'),
    ]

    def benchmark_test(self, target_class, int_param, string_param):
      # benchmark test body

  The example above will generate two benchmark test cases:
  "benchmark_test__case_1" and "benchmark_test__case_2".
  c                 R   |d   }d }|j                         j                         D ]l  }|j                  d      s||   }||= |D ]K  }|d   }	|dd  }
|dz   |	z   }||v rt        dj	                  |             |||
      }t        |d|      ||<   M n t        |   | |||      S )N_benchmark_parametersc                       fdS )Nc                      | g S rW   re   )selforiginal_benchmarkparamss    r   <lambda>zSParameterizedBenchmark.__new__.<locals>.create_benchmark_function.<locals>.<lambda>   s    ,T;F; r    re   )rn   ro   s   ``r   create_benchmark_functionzAParameterizedBenchmark.__new__.<locals>.create_benchmark_function   s	    ;;r    	benchmarkr      r(   z#Benchmark named {} already defined.)copykeys
startswith	Exceptionformatr   superrY   )r\   r]   r^   r_   param_config_listrq   r   rn   param_configtest_name_suffixro   benchmark_namerr   	__class__s                r   rY   zParameterizedBenchmark.__new__   s    56< 

!!# O__[) ;
++ O,'?ab!'77U"3::>JL L ..@&I	 !1A~ NnOO( 7?3u55r    )ra   rb   rc   rd   rY   __classcell__r~   s   @r   rh   rh      s    ,6 6r    rh   c                   >    e Zd ZdZed        ZddZ	 	 	 	 	 	 	 ddZy)	Benchmarka  Abstract class that provides helper functions for running benchmarks.

  Any class subclassing this one is immediately registered in the global
  benchmark registry.

  Only methods whose names start with the word "benchmark" will be run during
  benchmarking.
  c                 :    t        | j                               dk  S )N   lenmroclss    r   rZ   zBenchmark.is_abstract   s     swwy>Qr    Nc                 "   t        j                         }d}d}|ddd   D ]<  }|d   j                  }|j                  dd      }t	        |t
              s5|}|d   } n |t        d      |xs |}t        |      j                  }|d|}|S )z?Returns full name of class and method calling report_benchmark.Nr"   r   rm      z,Unable to determine calling Benchmark class..)	r   stackf_localsrA   r4   r   
ValueErrorrX   ra   )	rm   overwrite_namer   calling_classr   framer   f_self
class_names	            r   	_get_namezBenchmark._get_name   s     EMDtt q""h||FD)f	FI	&Qx EFF !TDm$--J $'DKr    c           	      L    | j                  |      }t        |||||||       y)ad  Report a benchmark.

    Args:
      iters: (optional) How many iterations were run
      cpu_time: (optional) Median or mean cpu time in seconds.
      wall_time: (optional) Median or mean wall time in seconds.
      throughput: (optional) Throughput (in MB/s)
      extras: (optional) Dict mapping string keys to additional benchmark info.
        Values may be either floats or values that are convertible to strings.
      name: (optional) Override the BenchmarkEntry name with `name`.
        Otherwise it is inferred from the top-level method name.
      metrics: (optional) A list of dict, where each dict has the keys below
        name (required), string, metric name
        value (required), double, metric value
        min_value (optional), double, minimum acceptable metric value
        max_value (optional), double, maximum acceptable metric value
    )r   )r   r0   r1   r2   r3   r:   r>   N)r   rS   )rm   r0   r1   r2   r3   r:   r   r>   s           r   report_benchmarkzBenchmark.report_benchmark   s,    4 >>>.DYfg?r    rW   )NNNNNNN)ra   rb   rc   rd   classmethodrZ   r   r   re   r    r   r   r      s<      4 ?r    r   )	metaclassztest.benchmark_configc                      t        j                         } t        j                  j                  | j
                  j                  _        | S )zReturns a tf.compat.v1.ConfigProto for disabling the dependency optimizer.

    Returns:
      A TensorFlow ConfigProto object.
  )r   ConfigProtor   RewriterConfigOFFgraph_optionsrewrite_optionsdependency_optimization)configs    r   benchmark_configr     s:     !!#&((,, 	&&>	-r    ztest.Benchmarkc                   P     e Zd ZdZ fdZed        Z	 	 	 	 	 	 	 	 ddZd Z xZ	S )TensorFlowBenchmarkz?Abstract class that provides helpers for TensorFlow benchmarks.c                 P    dt         j                  t        <   t        |           y )N1)r?   r@   OVERRIDE_GLOBAL_THREADPOOLry   __init__)rm   r~   s    r   r   zTensorFlowBenchmark.__init__#  s     .1BJJ)*	Gr    c                 :    t        | j                               dk  S )Nr   r   r   s    r   rZ   zTensorFlowBenchmark.is_abstract)  s     swwy>Qr    c                 l   t        |      D ]  }|j                  ||        dg|z  }t        |      D ]G  }t        j                         }|j                  ||       t        j                         }||z
  }|||<   I |	|	ni }	i }|s|rt        j                  t        j                  j
                        }t        j                         }|j                  ||||       t        j                  |j                        }|r|j                         |d<   |rH|j                  d      }|j                  }|j                         D ]  \  }}|j                  |	d|z  <    d	 }d
 } ||      }|||	||
|z  d} | j                  di |  ||      \  }}||d<   ||d<   |d   j!                  |       |S )aA  Run an op or tensor in the given session.  Report the results.

    Args:
      sess: `Session` object to use for timing.
      op_or_tensor: `Operation` or `Tensor` to benchmark.
      feed_dict: A `dict` of values to feed for each op iteration (see the
        `feed_dict` parameter of `Session.run`).
      burn_iters: Number of burn-in iterations to run.
      min_iters: Minimum number of iterations to use for timing.
      store_trace: Boolean, whether to run an extra untimed iteration and
        store the trace of iteration in returned extras.
        The trace will be stored as a string in Google Chrome trace format
        in the extras field "full_trace_chrome_format". Note that trace
        will not be stored in test_log_pb2.TestResults proto.
      store_memory_usage: Boolean, whether to run an extra untimed iteration,
        calculate memory usage, and store that in extras fields.
      name: (optional) Override the BenchmarkEntry name with `name`.
        Otherwise it is inferred from the top-level method name.
      extras: (optional) Dict mapping string keys to additional benchmark info.
        Values may be either floats or values that are convertible to strings.
      mbs: (optional) The number of megabytes moved by this op, used to
        calculate the ops throughput.

    Returns:
      A `dict` containing the key-value pairs that were passed to
      `report_benchmark`. If `store_trace` option is used, then
      `full_chrome_trace_format` will be included in return dictionary even
      though it is not passed to `report_benchmark` with `extras`.
    )	feed_dictN)trace_level)r   optionsrun_metadatafull_trace_chrome_formatT)show_memoryzallocator_maximum_num_bytes_%sc                 f    | syt        |       }t        |       }|dz
  }||dz     ||dz     z   dz  S )Nr"   rs   r   g       @)sortedr   )xsllm1s       r   _medianz5TensorFlowBenchmark.run_op_benchmark.<locals>._medianw  sC    
)a
a&aEc1g#q&	!S((r    c                     | syt        |       }t        |       |z  }|dk(  r|dfS t        | D cg c]  }||z
  ||z
  z   c}      |dz
  z  }|t        j                  |      fS c c}w )N)r"   r"   rs   r"   )r   summathsqrt)r   r   meanevariances        r   _mean_and_stdevz=TensorFlowBenchmark.run_op_benchmark.<locals>._mean_and_stdev  sr    
a&aVaZd	
aRxq9!q4xAH-9:a!eDh499X&&& :s   A%)r0   r2   r:   r   r3   wall_time_meanwall_time_stdevr:   re   )rangeruntimer   
RunOptions
FULL_TRACERunMetadatar   Timeline
step_statsgenerate_chrome_trace_formatanalyze_step_statsallocator_maximumsr7   	num_bytesr   update)rm   sessop_or_tensorr   
burn_iters	min_itersstore_tracestore_memory_usager   r:   mbs_deltasi
start_timeend_timedeltaunreported_extrasrun_optionsr   tlstep_stats_analysisr   rJ   rK   r   r   median_deltabenchmark_values
mean_deltastdev_deltas                                  r   run_op_benchmarkz$TensorFlowBenchmark.run_op_benchmark/  s   P : 2
hh|yh12 ViF9 99;j
hh|yh1h#efQi )VrF()) ++668k++-l
hh|y"  ?\445b	++- 	45 
 333E0CC&,,. 	EDAq9:&1A5
6	E)' 6?L !L( D-,--f5J*4&'+6'(X%%&78r    c                 p    t        j                         xs | j                         }|j                  |      S )zEvaluates tensors and returns numpy values.

    Args:
      tensors: A Tensor or a nested list/tuple of Tensors.

    Returns:
      tensors numpy values.
    )r   get_default_sessioncached_sessionr   )rm   tensorsr   s      r   evaluatezTensorFlowBenchmark.evaluate  s/     ""$=(;(;(=D88Gr    )Nr   
   FTNNr   )
ra   rb   rc   rd   r   r   rZ   r   r   r   r   s   @r   r   r     sE    G   "&"#!##(*. "iV
r    r   c                    t        t              }g }|D ]  }|j                  d|j                  }t	        |      }d}|D ]~  }|j                  d      st        ||      }t        |      s-|d|}	| dk(  st        j                  | |	      sP|j                  |	       |xs  |       }t        ||      }
 |
          |st        dj                  |             y)a  Run benchmarks that match regex `regex`.

  This function goes through the global benchmark registry, and matches
  benchmark class and method names of the form
  `module.name.BenchmarkClass.benchmarkMethod` to the given regex.
  If a method matches, it is run.

  Args:
    regex: The string regular expression to match Benchmark classes against.

  Raises:
    ValueError: If no benchmarks were selected by the input regex.
  r   Nrr   allz'No benchmarks matched the pattern: '{}')r=   r[   rb   ra   dirrv   getattrcallableresearchappendr   rx   )regexregistryselected_benchmarksrr   r}   r_   benchmark_instanceattrcandidate_benchmark_fnfull_benchmark_nameinstance_benchmark_fns              r   _run_benchmarksr     s     +,(  i ) 4 4i6H6HIN	NE  __[)&y$7,-'5t<	%299U,?@""#67/>9; '(:D A  , 

>EEeL
MM 
r    c                 4   |t         j                  }|D cg c]&  }|j                  d      s|j                  d      r|( }}|rF|j                  |d          |d   j	                  d      d   t        j                  fd|       y |         yc c}w )	zRun benchmarks as declared in argv.

  Args:
    true_main: True main function to run if benchmarks are not requested.
    argv: the command line arguments (if None, uses sys.argv).
  Nz--benchmark_filter=z-benchmark_filter=r   =rs   c                     t              S rW   )r   )r   r   s    r   rp   z!benchmarks_main.<locals>.<lambda>  s    oe, r    )argv)sysr   rv   removesplitr   r   )	true_mainr   arg	found_argr   s       @r   benchmarks_mainr    s     
\88D 
	-	.	,	- 
)  KK	!aLs#A&EGG,48Ks   +B)NNNNNNrW   ))rd   r   r8   r?   r   r   r   r   abslr   tensorflow.core.protobufr   r   tensorflow.core.utilr   tensorflow.python.clientr   tensorflow.python.frameworkr   tensorflow.python.platformr	   r
   r*   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   setr[   rB   r   r   rS   rX   rU   rh   r   r   r   r   r  re   r    r   <module>r     s     #   	 	 
    / 8 - - + , < - 6
  E  3  = + 04*.N b$  5"=160 16 >16hD?- D?N "#	 $	 D) D DN)NXr    