xref: /petsc/src/benchmarks/benchmarkExample.py (revision 683aebbff34752b96016a5c5e1677f7b66aff551)
13428b40fSMatthew G Knepley#!/usr/bin/env python
2*eda8839fSMatthew G Knepleyimport os,sys
3683aebbfSMatthew G Knepleysys.path.append(os.path.join(os.environ['PETSC_DIR'], 'config'))
4683aebbfSMatthew G Knepleyfrom builder2 import buildExample
519d5f70aSMatthew G Knepleyfrom benchmarkBatch import generateBatchScript
63428b40fSMatthew G Knepley
73428b40fSMatthew G Knepleyclass PETSc(object):
83428b40fSMatthew G Knepley  def __init__(self):
93428b40fSMatthew G Knepley    return
103428b40fSMatthew G Knepley
113428b40fSMatthew G Knepley  def dir(self):
123428b40fSMatthew G Knepley    '''Return the root directory for the PETSc tree (usually $PETSC_DIR)'''
133428b40fSMatthew G Knepley    # This should search for a valid PETSc
143428b40fSMatthew G Knepley    return os.environ['PETSC_DIR']
153428b40fSMatthew G Knepley
163428b40fSMatthew G Knepley  def arch(self):
173428b40fSMatthew G Knepley    '''Return the PETSc build label (usually $PETSC_ARCH)'''
183428b40fSMatthew G Knepley    # This should be configurable
193428b40fSMatthew G Knepley    return os.environ['PETSC_ARCH']
203428b40fSMatthew G Knepley
213428b40fSMatthew G Knepley  def mpiexec(self):
223428b40fSMatthew G Knepley    '''Return the path for the mpi launch executable'''
23e3da8a91SMatthew G Knepley    mpiexec = os.path.join(self.dir(), self.arch(), 'bin', 'mpiexec')
246cbfa02cSMatthew G Knepley    if not os.path.isfile(mpiexec):
25e3da8a91SMatthew G Knepley      return None
26e3da8a91SMatthew G Knepley    return mpiexec
273428b40fSMatthew G Knepley
283428b40fSMatthew G Knepley  def example(self, num):
293428b40fSMatthew G Knepley    '''Return the path to the executable for a given example number'''
303428b40fSMatthew G Knepley    return os.path.join(self.dir(), self.arch(), 'lib', 'ex'+str(num)+'-obj', 'ex'+str(num))
313428b40fSMatthew G Knepley
320790b1abSMatthew G Knepley  def source(self, library, num):
330790b1abSMatthew G Knepley    '''Return the path to the sources for a given example number'''
340790b1abSMatthew G Knepley    d = os.path.join(self.dir(), 'src', library.lower(), 'examples', 'tutorials')
350790b1abSMatthew G Knepley    name = 'ex'+str(num)
360790b1abSMatthew G Knepley    sources = []
370790b1abSMatthew G Knepley    for f in os.listdir(d):
380790b1abSMatthew G Knepley      if f == name+'.c':
390790b1abSMatthew G Knepley        sources.append(f)
400790b1abSMatthew G Knepley      elif f.startswith(name) and f.endswith('.cu'):
410790b1abSMatthew G Knepley        sources.append(f)
420790b1abSMatthew G Knepley    return map(lambda f: os.path.join(d, f), sources)
430790b1abSMatthew G Knepley
443428b40fSMatthew G Knepleyclass PETScExample(object):
453428b40fSMatthew G Knepley  def __init__(self, library, num, **defaultOptions):
463428b40fSMatthew G Knepley    self.petsc   = PETSc()
473428b40fSMatthew G Knepley    self.library = library
483428b40fSMatthew G Knepley    self.num     = num
493428b40fSMatthew G Knepley    self.opts    = defaultOptions
503428b40fSMatthew G Knepley    return
513428b40fSMatthew G Knepley
523428b40fSMatthew G Knepley  @staticmethod
533428b40fSMatthew G Knepley  def runShellCommand(command, cwd = None):
543428b40fSMatthew G Knepley    import subprocess
553428b40fSMatthew G Knepley
563428b40fSMatthew G Knepley    Popen = subprocess.Popen
573428b40fSMatthew G Knepley    PIPE  = subprocess.PIPE
583428b40fSMatthew G Knepley    print 'Executing: %s\n' % (command,)
593428b40fSMatthew G Knepley    pipe = Popen(command, cwd=cwd, stdin=None, stdout=PIPE, stderr=PIPE, bufsize=-1, shell=True, universal_newlines=True)
603428b40fSMatthew G Knepley    (out, err) = pipe.communicate()
613428b40fSMatthew G Knepley    ret = pipe.returncode
623428b40fSMatthew G Knepley    return (out, err, ret)
633428b40fSMatthew G Knepley
643428b40fSMatthew G Knepley  def optionsToString(self, **opts):
653428b40fSMatthew G Knepley    '''Convert a dictionary of options to a command line argument string'''
663428b40fSMatthew G Knepley    a = []
673428b40fSMatthew G Knepley    for key,value in opts.iteritems():
683428b40fSMatthew G Knepley      if value is None:
693428b40fSMatthew G Knepley        a.append('-'+key)
703428b40fSMatthew G Knepley      else:
713428b40fSMatthew G Knepley        a.append('-'+key+' '+str(value))
723428b40fSMatthew G Knepley    return ' '.join(a)
733428b40fSMatthew G Knepley
7419d5f70aSMatthew G Knepley  def run(self, numProcs = 1, **opts):
75e3da8a91SMatthew G Knepley    if self.petsc.mpiexec() is None:
76e3da8a91SMatthew G Knepley      cmd = self.petsc.example(self.num)
77e3da8a91SMatthew G Knepley    else:
7819d5f70aSMatthew G Knepley      cmd = ' '.join([self.petsc.mpiexec(), '-n', str(numProcs), self.petsc.example(self.num)])
79e3da8a91SMatthew G Knepley    cmd += ' '+self.optionsToString(**self.opts)+' '+self.optionsToString(**opts)
8019d5f70aSMatthew G Knepley    if 'batch' in opts and opts['batch']:
8119d5f70aSMatthew G Knepley      del opts['batch']
823849a283SMatthew G Knepley      filename = generateBatchScript(self.num, numProcs, 120, ' '+self.optionsToString(**self.opts)+' '+self.optionsToString(**opts))
833849a283SMatthew G Knepley      # Submit job
843849a283SMatthew G Knepley      out, err, ret = self.runShellCommand('qsub -q gpu '+filename)
853849a283SMatthew G Knepley      if ret:
863849a283SMatthew G Knepley        print err
873849a283SMatthew G Knepley        print out
8819d5f70aSMatthew G Knepley    else:
893428b40fSMatthew G Knepley      out, err, ret = self.runShellCommand(cmd)
903428b40fSMatthew G Knepley      if ret:
913428b40fSMatthew G Knepley        print err
923428b40fSMatthew G Knepley        print out
930790b1abSMatthew G Knepley    return out
943428b40fSMatthew G Knepley
95*eda8839fSMatthew G Knepleydef processSummary(moduleName, defaultStage, eventNames, times, events):
963428b40fSMatthew G Knepley  '''Process the Python log summary into plot data'''
973428b40fSMatthew G Knepley  m = __import__(moduleName)
983428b40fSMatthew G Knepley  reload(m)
993428b40fSMatthew G Knepley  # Total Time
1003428b40fSMatthew G Knepley  times.append(m.Time[0])
1013428b40fSMatthew G Knepley  # Particular events
102*eda8839fSMatthew G Knepley  for name in eventNames:
103*eda8839fSMatthew G Knepley    if name.find(':') >= 0:
104*eda8839fSMatthew G Knepley      stageName, name = name.split(':', 1)
105*eda8839fSMatthew G Knepley      stage = getattr(m, stageName)
106*eda8839fSMatthew G Knepley    else:
107*eda8839fSMatthew G Knepley      stage = getattr(m, defaultStage)
108*eda8839fSMatthew G Knepley    if name in stage.event:
1093428b40fSMatthew G Knepley      if not name in events:
1103428b40fSMatthew G Knepley        events[name] = []
111*eda8839fSMatthew G Knepley      events[name].append((stage.event[name].Time[0], stage.event[name].Flops[0]/(stage.event[name].Time[0] * 1e6)))
1123428b40fSMatthew G Knepley  return
1133428b40fSMatthew G Knepley
114e3da8a91SMatthew G Knepleydef plotSummaryLine(library, num, sizes, times, events):
1153428b40fSMatthew G Knepley  from pylab import legend, plot, show, title, xlabel, ylabel
1163428b40fSMatthew G Knepley  import numpy as np
1173428b40fSMatthew G Knepley  showTime       = False
1183428b40fSMatthew G Knepley  showEventTime  = True
1193428b40fSMatthew G Knepley  showEventFlops = True
1203428b40fSMatthew G Knepley  arches         = sizes.keys()
1213428b40fSMatthew G Knepley  # Time
1223428b40fSMatthew G Knepley  if showTime:
1233428b40fSMatthew G Knepley    data = []
1243428b40fSMatthew G Knepley    for arch in arches:
1253428b40fSMatthew G Knepley      data.append(sizes[arch])
1263428b40fSMatthew G Knepley      data.append(times[arch])
1273428b40fSMatthew G Knepley    plot(*data)
1283428b40fSMatthew G Knepley    title('Performance on '+library+' Example '+str(num))
1293428b40fSMatthew G Knepley    xlabel('Number of Dof')
1303428b40fSMatthew G Knepley    ylabel('Time (s)')
1313428b40fSMatthew G Knepley    legend(arches, 'upper left', shadow = True)
1323428b40fSMatthew G Knepley    show()
1333428b40fSMatthew G Knepley  # Common event time
1343428b40fSMatthew G Knepley  #   We could make a stacked plot like Rio uses here
1353428b40fSMatthew G Knepley  if showEventTime:
1363428b40fSMatthew G Knepley    data  = []
1373428b40fSMatthew G Knepley    names = []
1383428b40fSMatthew G Knepley    for event, color in [('VecMDot', 'b'), ('VecMAXPY', 'g'), ('MatMult', 'r')]:
1393428b40fSMatthew G Knepley      for arch, style in zip(arches, ['-', ':']):
1403428b40fSMatthew G Knepley        names.append(arch+' '+event)
1413428b40fSMatthew G Knepley        data.append(sizes[arch])
1423428b40fSMatthew G Knepley        data.append(np.array(events[arch][event])[:,0])
1433428b40fSMatthew G Knepley        data.append(color+style)
1443428b40fSMatthew G Knepley    plot(*data)
1453428b40fSMatthew G Knepley    title('Performance on '+library+' Example '+str(num))
1463428b40fSMatthew G Knepley    xlabel('Number of Dof')
1473428b40fSMatthew G Knepley    ylabel('Time (s)')
1483428b40fSMatthew G Knepley    legend(names, 'upper left', shadow = True)
1493428b40fSMatthew G Knepley    show()
1503428b40fSMatthew G Knepley  # Common event flops
1513428b40fSMatthew G Knepley  #   We could make a stacked plot like Rio uses here
1523428b40fSMatthew G Knepley  if showEventFlops:
1533428b40fSMatthew G Knepley    data  = []
1543428b40fSMatthew G Knepley    names = []
1553428b40fSMatthew G Knepley    for event, color in [('VecMDot', 'b'), ('VecMAXPY', 'g'), ('MatMult', 'r')]:
1563428b40fSMatthew G Knepley      for arch, style in zip(arches, ['-', ':']):
1573428b40fSMatthew G Knepley        names.append(arch+' '+event)
1583428b40fSMatthew G Knepley        data.append(sizes[arch])
1593428b40fSMatthew G Knepley        data.append(np.array(events[arch][event])[:,1])
1603428b40fSMatthew G Knepley        data.append(color+style)
1613428b40fSMatthew G Knepley    plot(*data)
1623428b40fSMatthew G Knepley    title('Performance on '+library+' Example '+str(num))
1633428b40fSMatthew G Knepley    xlabel('Number of Dof')
1643428b40fSMatthew G Knepley    ylabel('Computation Rate (MF/s)')
1653428b40fSMatthew G Knepley    legend(names, 'upper left', shadow = True)
1663428b40fSMatthew G Knepley    show()
1673428b40fSMatthew G Knepley  return
1683428b40fSMatthew G Knepley
169e3da8a91SMatthew G Knepleydef plotSummaryBar(library, num, sizes, times, events):
170e3da8a91SMatthew G Knepley  import numpy as np
171e3da8a91SMatthew G Knepley  import matplotlib.pyplot as plt
172e3da8a91SMatthew G Knepley
173e3da8a91SMatthew G Knepley  eventNames  = ['VecMDot', 'VecMAXPY', 'MatMult']
174e3da8a91SMatthew G Knepley  eventColors = ['b',       'g',        'r']
175e3da8a91SMatthew G Knepley  arches = sizes.keys()
176e3da8a91SMatthew G Knepley  names  = []
177e3da8a91SMatthew G Knepley  N      = len(sizes[arches[0]])
178e3da8a91SMatthew G Knepley  width  = 0.2
179e3da8a91SMatthew G Knepley  ind    = np.arange(N) - 0.25
180e3da8a91SMatthew G Knepley  bars   = {}
181e3da8a91SMatthew G Knepley  for arch in arches:
182e3da8a91SMatthew G Knepley    bars[arch] = []
183e3da8a91SMatthew G Knepley    bottom = np.zeros(N)
184e3da8a91SMatthew G Knepley    for event, color in zip(eventNames, eventColors):
185e3da8a91SMatthew G Knepley      names.append(arch+' '+event)
186e3da8a91SMatthew G Knepley      times = np.array(events[arch][event])[:,0]
187e3da8a91SMatthew G Knepley      bars[arch].append(plt.bar(ind, times, width, color=color, bottom=bottom))
188e3da8a91SMatthew G Knepley      bottom += times
189e3da8a91SMatthew G Knepley    ind += 0.3
190e3da8a91SMatthew G Knepley
191e3da8a91SMatthew G Knepley  plt.xlabel('Number of Dof')
192e3da8a91SMatthew G Knepley  plt.ylabel('Time (s)')
193e3da8a91SMatthew G Knepley  plt.title('GPU vs. CPU Performance on '+library+' Example '+str(num))
194e3da8a91SMatthew G Knepley  plt.xticks(np.arange(N), map(str, sizes[arches[0]]))
195e3da8a91SMatthew G Knepley  #plt.yticks(np.arange(0,81,10))
196e3da8a91SMatthew G Knepley  #plt.legend( (p1[0], p2[0]), ('Men', 'Women') )
197e3da8a91SMatthew G Knepley  plt.legend([bar[0] for bar in bars[arches[0]]], eventNames, 'upper right', shadow = True)
198e3da8a91SMatthew G Knepley
199e3da8a91SMatthew G Knepley  plt.show()
200e3da8a91SMatthew G Knepley  return
201e3da8a91SMatthew G Knepley
202683aebbfSMatthew G Knepleydef getDMMeshSize(dim, out):
203683aebbfSMatthew G Knepley  '''Retrieves the number of cells from '''
204683aebbfSMatthew G Knepley  size = 0
205683aebbfSMatthew G Knepley  for line in out.split('\n'):
206683aebbfSMatthew G Knepley    if line.strip().startswith(str(dim)+'-cells: '):
207683aebbfSMatthew G Knepley      size = int(line.strip()[9:])
208683aebbfSMatthew G Knepley      break
209683aebbfSMatthew G Knepley  return size
210683aebbfSMatthew G Knepley
211683aebbfSMatthew G Knepleydef run_DMDA(ex, name, opts, args, sizes, times, events):
212683aebbfSMatthew G Knepley  for n in map(int, args.size):
213683aebbfSMatthew G Knepley    ex.run(da_grid_x=n, da_grid_y=n, **opts)
214683aebbfSMatthew G Knepley    sizes[name].append(n*n * args.comp)
215683aebbfSMatthew G Knepley    processSummary('summary', args.stage, args.events, times[name], events[name])
216683aebbfSMatthew G Knepley  return
217683aebbfSMatthew G Knepley
218683aebbfSMatthew G Knepleydef run_DMMesh(ex, name, opts, args, sizes, times, events):
219683aebbfSMatthew G Knepley  # This should eventually be replaced by a direct FFC/Ignition interface
220683aebbfSMatthew G Knepley  if args.operator == 'laplacian':
221683aebbfSMatthew G Knepley    numComp  = 1
222683aebbfSMatthew G Knepley  elif args.operator == 'elasticity':
223683aebbfSMatthew G Knepley    numComp  = args.dim
224683aebbfSMatthew G Knepley  else:
225683aebbfSMatthew G Knepley    raise RuntimeError('Unknown operator: %s' % args.operator)
226683aebbfSMatthew G Knepley
227683aebbfSMatthew G Knepley  for numBlock in [2**i for i in map(int, args.blockExp)]:
228683aebbfSMatthew G Knepley    opts['gpu_blocks'] = numBlock
229683aebbfSMatthew G Knepley    # Generate new block size
230683aebbfSMatthew G Knepley    cmd = './bin/pythonscripts/PetscGenerateFEMQuadrature.py %d %d %d %d %s %s.h' % (args.dim, args.order, numComp, numBlock, args.operator, os.path.splitext(source[0])[0])
231683aebbfSMatthew G Knepley    print(cmd)
232683aebbfSMatthew G Knepley    ret = os.system('python '+cmd)
233683aebbfSMatthew G Knepley    args.files = ['['+','.join(source)+']']
234683aebbfSMatthew G Knepley    buildExample(args)
235683aebbfSMatthew G Knepley    sizes[name][numBlock]  = []
236683aebbfSMatthew G Knepley    times[name][numBlock]  = []
237683aebbfSMatthew G Knepley    events[name][numBlock] = {}
238683aebbfSMatthew G Knepley    for r in map(float, args.refine):
239683aebbfSMatthew G Knepley      out = ex.run(refinement_limit=r, **opts)
240683aebbfSMatthew G Knepley      sizes[name][numBlock].append(getDMMeshSize(args.dim, out))
241683aebbfSMatthew G Knepley      processSummary('summary', args.stage, args.events, times[name][numBlock], events[name][numBlock])
242683aebbfSMatthew G Knepley  return
243683aebbfSMatthew G Knepley
2443428b40fSMatthew G Knepleyif __name__ == '__main__':
245*eda8839fSMatthew G Knepley  import argparse
246*eda8839fSMatthew G Knepley
247*eda8839fSMatthew G Knepley  parser = argparse.ArgumentParser(description     = 'PETSc Benchmarking',
248*eda8839fSMatthew G Knepley                                   epilog          = 'This script runs src/<library>/examples/tutorials/ex<num>, For more information, visit http://www.mcs.anl.gov/petsc',
249*eda8839fSMatthew G Knepley                                   formatter_class = argparse.ArgumentDefaultsHelpFormatter)
250*eda8839fSMatthew G Knepley  parser.add_argument('--library', default='SNES',                     help='The PETSc library used in this example')
251*eda8839fSMatthew G Knepley  parser.add_argument('--num',     type = int, default='5',            help='The example number')
252*eda8839fSMatthew G Knepley  parser.add_argument('--module',  default='summary',                  help='The module for timing output')
253*eda8839fSMatthew G Knepley  parser.add_argument('--stage',   default='Main_Stage',               help='The default logging stage')
254*eda8839fSMatthew G Knepley  parser.add_argument('--events',  nargs='+',                          help='Events to process')
255*eda8839fSMatthew G Knepley  parser.add_argument('--batch',   action='store_true', default=False, help='Generate batch files for the runs instead')
256683aebbfSMatthew G Knepley  subparsers = parser.add_subparsers(help='DM types')
257*eda8839fSMatthew G Knepley
258683aebbfSMatthew G Knepley  parser_dmda = subparsers.add_parser('DMDA', help='Use a DMDA for the problem geometry')
259683aebbfSMatthew G Knepley  parser_dmda.add_argument('--size', nargs='+',  default=['10'], help='Grid size (implementation dependent)')
260683aebbfSMatthew G Knepley  parser_dmda.add_argument('--comp', type = int, default='1',    help='Number of field components')
261683aebbfSMatthew G Knepley  parser_dmda.add_argument('runs',   nargs='*',                  help='Run descriptions: <name>=<args>')
262683aebbfSMatthew G Knepley
263683aebbfSMatthew G Knepley  parser_dmmesh = subparsers.add_parser('DMMesh', help='Use a DMMesh for the problem geometry')
264683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--dim',      type = int, default='2',        help='Spatial dimension')
265683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--refine',   nargs='+',  default=['0.0'],    help='List of refinement limits')
266683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--order',    type = int, default='1',        help='Order of the finite element')
267683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--operator', default='laplacian',            help='The operator name')
268683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--blockExp', nargs='+', default=range(0, 5), help='List of block exponents j, block size is 2^j')
269683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('runs',       nargs='*',                      help='Run descriptions: <name>=<args>')
270*eda8839fSMatthew G Knepley
271*eda8839fSMatthew G Knepley  args = parser.parse_args()
272*eda8839fSMatthew G Knepley  print(args)
273683aebbfSMatthew G Knepley  if hasattr(args, 'comp'):
274683aebbfSMatthew G Knepley    args.dmType = 'DMDA'
275683aebbfSMatthew G Knepley  else:
276683aebbfSMatthew G Knepley    args.dmType = 'DMMesh'
277683aebbfSMatthew G Knepley
278*eda8839fSMatthew G Knepley  ex     = PETScExample(args.library, args.num, log_summary='summary.dat', log_summary_python = None if args.batch else args.module+'.py', preload='off')
279683aebbfSMatthew G Knepley  source = ex.petsc.source(args.library, args.num)
2803428b40fSMatthew G Knepley  sizes  = {}
2813428b40fSMatthew G Knepley  times  = {}
2823428b40fSMatthew G Knepley  events = {}
283683aebbfSMatthew G Knepley
284*eda8839fSMatthew G Knepley  for run in args.runs:
285*eda8839fSMatthew G Knepley    name, stropts = run.split('=', 1)
286*eda8839fSMatthew G Knepley    opts = dict([t if len(t) == 2 else (t[0], None) for t in [arg.split('=', 1) for arg in stropts.split(' ')]])
287683aebbfSMatthew G Knepley    if args.dmType == 'DMDA':
2883428b40fSMatthew G Knepley      sizes[name]  = []
2893428b40fSMatthew G Knepley      times[name]  = []
2903428b40fSMatthew G Knepley      events[name] = {}
291683aebbfSMatthew G Knepley      run_DMDA(ex, name, opts, args, sizes, times, events)
292683aebbfSMatthew G Knepley    elif args.dmType == 'DMMesh':
293683aebbfSMatthew G Knepley      sizes[name]  = {}
294683aebbfSMatthew G Knepley      times[name]  = {}
295683aebbfSMatthew G Knepley      events[name] = {}
296683aebbfSMatthew G Knepley      run_DMMesh(ex, name, opts, args, sizes, times, events)
297683aebbfSMatthew G Knepley  print('sizes',sizes)
298683aebbfSMatthew G Knepley  print('times',times)
299683aebbfSMatthew G Knepley  print('events',events)
300*eda8839fSMatthew G Knepley  if not args.batch: plotSummaryLine(args.library, args.num, sizes, times, events)
301683aebbfSMatthew G Knepley# Benchmark for ex50
302683aebbfSMatthew G Knepley# ./src/benchmarks/benchmarkExample.py --events VecMDot VecMAXPY KSPGMRESOrthog MatMult VecCUSPCopyTo VecCUSPCopyFrom MatCUSPCopyTo --num 50 DMDA --size 10 20 50 100 --comp 4 CPU='pc_type=none mat_no_inode dm_vec_type=seq dm_mat_type=seqaij' GPU='pc_type=none mat_no_inode dm_vec_type=seqcusp dm_mat_type=seqaijcusp cusp_synchronize'
303683aebbfSMatthew G Knepley# Benchmark for ex52
304683aebbfSMatthew G Knepley# ./src/benchmarks/benchmarkExample.py --events IntegBatchCPU IntegBatchGPU IntegGPUOnly --num 52 DMMesh --refine 0.0625 0.00625 0.000625 0.0000625 --blockExp 4 --order 1 CPU='dm_view show_residual=0 compute_function batch' GPU='dm_view show_residual=0 compute_function batch gpu gpu_batches=8'
305