xref: /petsc/src/benchmarks/benchmarkExample.py (revision 97ffeb231416e7b6f7c2c3e29f9b901c3c6317a0)
1#!/usr/bin/env python
2import os,sys
3sys.path.append(os.path.join(os.environ['PETSC_DIR'], 'config'))
4from builder2 import buildExample
5from benchmarkBatch import generateBatchScript
6
7class PETSc(object):
8  def __init__(self):
9    return
10
11  def dir(self):
12    '''Return the root directory for the PETSc tree (usually $PETSC_DIR)'''
13    # This should search for a valid PETSc
14    return os.environ['PETSC_DIR']
15
16  def arch(self):
17    '''Return the PETSc build label (usually $PETSC_ARCH)'''
18    # This should be configurable
19    return os.environ['PETSC_ARCH']
20
21  def mpiexec(self):
22    '''Return the path for the mpi launch executable'''
23    mpiexec = os.path.join(self.dir(), self.arch(), 'bin', 'mpiexec')
24    if not os.path.isfile(mpiexec):
25      return None
26    return mpiexec
27
28  def example(self, num):
29    '''Return the path to the executable for a given example number'''
30    return os.path.join(self.dir(), self.arch(), 'lib', 'ex'+str(num)+'-obj', 'ex'+str(num))
31
32  def source(self, library, num):
33    '''Return the path to the sources for a given example number'''
34    d = os.path.join(self.dir(), 'src', library.lower(), 'examples', 'tutorials')
35    name = 'ex'+str(num)
36    sources = []
37    for f in os.listdir(d):
38      if f == name+'.c':
39        sources.insert(0, f)
40      elif f.startswith(name) and f.endswith('.cu'):
41        sources.append(f)
42    return map(lambda f: os.path.join(d, f), sources)
43
44class PETScExample(object):
45  def __init__(self, library, num, **defaultOptions):
46    self.petsc   = PETSc()
47    self.library = library
48    self.num     = num
49    self.opts    = defaultOptions
50    return
51
52  @staticmethod
53  def runShellCommand(command, cwd = None):
54    import subprocess
55
56    Popen = subprocess.Popen
57    PIPE  = subprocess.PIPE
58    print 'Executing: %s\n' % (command,)
59    pipe = Popen(command, cwd=cwd, stdin=None, stdout=PIPE, stderr=PIPE, bufsize=-1, shell=True, universal_newlines=True)
60    (out, err) = pipe.communicate()
61    ret = pipe.returncode
62    return (out, err, ret)
63
64  def optionsToString(self, **opts):
65    '''Convert a dictionary of options to a command line argument string'''
66    a = []
67    for key,value in opts.iteritems():
68      if value is None:
69        a.append('-'+key)
70      else:
71        a.append('-'+key+' '+str(value))
72    return ' '.join(a)
73
74  def run(self, numProcs = 1, **opts):
75    if self.petsc.mpiexec() is None:
76      cmd = self.petsc.example(self.num)
77    else:
78      cmd = ' '.join([self.petsc.mpiexec(), '-n', str(numProcs), self.petsc.example(self.num)])
79    cmd += ' '+self.optionsToString(**self.opts)+' '+self.optionsToString(**opts)
80    if 'batch' in opts and opts['batch']:
81      del opts['batch']
82      filename = generateBatchScript(self.num, numProcs, 120, ' '+self.optionsToString(**self.opts)+' '+self.optionsToString(**opts))
83      # Submit job
84      out, err, ret = self.runShellCommand('qsub -q gpu '+filename)
85      if ret:
86        print err
87        print out
88    else:
89      out, err, ret = self.runShellCommand(cmd)
90      if ret:
91        print err
92        print out
93    return out
94
95def processSummary(moduleName, defaultStage, eventNames, times, events):
96  '''Process the Python log summary into plot data'''
97  m = __import__(moduleName)
98  reload(m)
99  # Total Time
100  times.append(m.Time[0])
101  # Particular events
102  for name in eventNames:
103    if name.find(':') >= 0:
104      stageName, name = name.split(':', 1)
105      stage = getattr(m, stageName)
106    else:
107      stage = getattr(m, defaultStage)
108    if name in stage.event:
109      if not name in events:
110        events[name] = []
111      events[name].append((stage.event[name].Time[0], stage.event[name].Flops[0]/(stage.event[name].Time[0] * 1e6)))
112  return
113
114def plotSummaryLine(library, num, sizes, times, events):
115  from pylab import legend, plot, show, title, xlabel, ylabel
116  import numpy as np
117  showTime       = False
118  showEventTime  = True
119  showEventFlops = True
120  arches         = sizes.keys()
121  # Time
122  if showTime:
123    data = []
124    for arch in arches:
125      data.append(sizes[arch])
126      data.append(times[arch])
127    plot(*data)
128    title('Performance on '+library+' Example '+str(num))
129    xlabel('Number of Dof')
130    ylabel('Time (s)')
131    legend(arches, 'upper left', shadow = True)
132    show()
133  # Common event time
134  #   We could make a stacked plot like Rio uses here
135  if showEventTime:
136    data  = []
137    names = []
138    for event, color in [('VecMDot', 'b'), ('VecMAXPY', 'g'), ('MatMult', 'r')]:
139      for arch, style in zip(arches, ['-', ':']):
140        names.append(arch+' '+event)
141        data.append(sizes[arch])
142        data.append(np.array(events[arch][event])[:,0])
143        data.append(color+style)
144    plot(*data)
145    title('Performance on '+library+' Example '+str(num))
146    xlabel('Number of Dof')
147    ylabel('Time (s)')
148    legend(names, 'upper left', shadow = True)
149    show()
150  # Common event flops
151  #   We could make a stacked plot like Rio uses here
152  if showEventFlops:
153    data  = []
154    names = []
155    for event, color in [('VecMDot', 'b'), ('VecMAXPY', 'g'), ('MatMult', 'r')]:
156      for arch, style in zip(arches, ['-', ':']):
157        names.append(arch+' '+event)
158        data.append(sizes[arch])
159        data.append(np.array(events[arch][event])[:,1])
160        data.append(color+style)
161    plot(*data)
162    title('Performance on '+library+' Example '+str(num))
163    xlabel('Number of Dof')
164    ylabel('Computation Rate (MF/s)')
165    legend(names, 'upper left', shadow = True)
166    show()
167  return
168
169def plotSummaryBar(library, num, sizes, times, events):
170  import numpy as np
171  import matplotlib.pyplot as plt
172
173  eventNames  = ['VecMDot', 'VecMAXPY', 'MatMult']
174  eventColors = ['b',       'g',        'r']
175  arches = sizes.keys()
176  names  = []
177  N      = len(sizes[arches[0]])
178  width  = 0.2
179  ind    = np.arange(N) - 0.25
180  bars   = {}
181  for arch in arches:
182    bars[arch] = []
183    bottom = np.zeros(N)
184    for event, color in zip(eventNames, eventColors):
185      names.append(arch+' '+event)
186      times = np.array(events[arch][event])[:,0]
187      bars[arch].append(plt.bar(ind, times, width, color=color, bottom=bottom))
188      bottom += times
189    ind += 0.3
190
191  plt.xlabel('Number of Dof')
192  plt.ylabel('Time (s)')
193  plt.title('GPU vs. CPU Performance on '+library+' Example '+str(num))
194  plt.xticks(np.arange(N), map(str, sizes[arches[0]]))
195  #plt.yticks(np.arange(0,81,10))
196  #plt.legend( (p1[0], p2[0]), ('Men', 'Women') )
197  plt.legend([bar[0] for bar in bars[arches[0]]], eventNames, 'upper right', shadow = True)
198
199  plt.show()
200  return
201
202def getDMMeshSize(dim, out):
203  '''Retrieves the number of cells from '''
204  size = 0
205  for line in out.split('\n'):
206    if line.strip().startswith(str(dim)+'-cells: '):
207      size = int(line.strip()[9:])
208      break
209  return size
210
211def run_DMDA(ex, name, opts, args, sizes, times, events):
212  for n in map(int, args.size):
213    ex.run(da_grid_x=n, da_grid_y=n, **opts)
214    sizes[name].append(n*n * args.comp)
215    processSummary('summary', args.stage, args.events, times[name], events[name])
216  return
217
218def run_DMMesh(ex, name, opts, args, sizes, times, events):
219  # This should eventually be replaced by a direct FFC/Ignition interface
220  if args.operator == 'laplacian':
221    numComp  = 1
222  elif args.operator == 'elasticity':
223    numComp  = args.dim
224  else:
225    raise RuntimeError('Unknown operator: %s' % args.operator)
226
227  for numBlock in [2**i for i in map(int, args.blockExp)]:
228    opts['gpu_blocks'] = numBlock
229    # Generate new block size
230    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])
231    print(cmd)
232    ret = os.system('python '+cmd)
233    args.files = ['['+','.join(source)+']']
234    buildExample(args)
235    sizes[name][numBlock]  = []
236    times[name][numBlock]  = []
237    events[name][numBlock] = {}
238    for r in map(float, args.refine):
239      out = ex.run(refinement_limit=r, **opts)
240      sizes[name][numBlock].append(getDMMeshSize(args.dim, out))
241      processSummary('summary', args.stage, args.events, times[name][numBlock], events[name][numBlock])
242  return
243
244if __name__ == '__main__':
245  import argparse
246
247  parser = argparse.ArgumentParser(description     = 'PETSc Benchmarking',
248                                   epilog          = 'This script runs src/<library>/examples/tutorials/ex<num>, For more information, visit http://www.mcs.anl.gov/petsc',
249                                   formatter_class = argparse.ArgumentDefaultsHelpFormatter)
250  parser.add_argument('--library', default='SNES',                     help='The PETSc library used in this example')
251  parser.add_argument('--num',     type = int, default='5',            help='The example number')
252  parser.add_argument('--module',  default='summary',                  help='The module for timing output')
253  parser.add_argument('--stage',   default='Main_Stage',               help='The default logging stage')
254  parser.add_argument('--events',  nargs='+',                          help='Events to process')
255  parser.add_argument('--batch',   action='store_true', default=False, help='Generate batch files for the runs instead')
256  subparsers = parser.add_subparsers(help='DM types')
257
258  parser_dmda = subparsers.add_parser('DMDA', help='Use a DMDA for the problem geometry')
259  parser_dmda.add_argument('--size', nargs='+',  default=['10'], help='Grid size (implementation dependent)')
260  parser_dmda.add_argument('--comp', type = int, default='1',    help='Number of field components')
261  parser_dmda.add_argument('runs',   nargs='*',                  help='Run descriptions: <name>=<args>')
262
263  parser_dmmesh = subparsers.add_parser('DMMesh', help='Use a DMMesh for the problem geometry')
264  parser_dmmesh.add_argument('--dim',      type = int, default='2',        help='Spatial dimension')
265  parser_dmmesh.add_argument('--refine',   nargs='+',  default=['0.0'],    help='List of refinement limits')
266  parser_dmmesh.add_argument('--order',    type = int, default='1',        help='Order of the finite element')
267  parser_dmmesh.add_argument('--operator', default='laplacian',            help='The operator name')
268  parser_dmmesh.add_argument('--blockExp', nargs='+', default=range(0, 5), help='List of block exponents j, block size is 2^j')
269  parser_dmmesh.add_argument('runs',       nargs='*',                      help='Run descriptions: <name>=<args>')
270
271  args = parser.parse_args()
272  print(args)
273  if hasattr(args, 'comp'):
274    args.dmType = 'DMDA'
275  else:
276    args.dmType = 'DMMesh'
277
278  ex     = PETScExample(args.library, args.num, log_summary='summary.dat', log_summary_python = None if args.batch else args.module+'.py', preload='off')
279  source = ex.petsc.source(args.library, args.num)
280  sizes  = {}
281  times  = {}
282  events = {}
283
284  for run in args.runs:
285    name, stropts = run.split('=', 1)
286    opts = dict([t if len(t) == 2 else (t[0], None) for t in [arg.split('=', 1) for arg in stropts.split(' ')]])
287    if args.dmType == 'DMDA':
288      sizes[name]  = []
289      times[name]  = []
290      events[name] = {}
291      run_DMDA(ex, name, opts, args, sizes, times, events)
292    elif args.dmType == 'DMMesh':
293      sizes[name]  = {}
294      times[name]  = {}
295      events[name] = {}
296      run_DMMesh(ex, name, opts, args, sizes, times, events)
297  print('sizes',sizes)
298  print('times',times)
299  print('events',events)
300  if not args.batch: plotSummaryLine(args.library, args.num, sizes, times, events)
301# Benchmark for ex50
302# ./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'
303# Benchmark for ex52
304# ./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