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 try: 112 events[name].append((stage.event[name].Time[0], stage.event[name].Flops[0]/(stage.event[name].Time[0] * 1e6))) 113 except ZeroDivisionError: 114 events[name].append((stage.event[name].Time[0], 0)) 115 return 116 117def plotSummaryLine(library, num, eventNames, sizes, times, events): 118 from pylab import legend, plot, show, title, xlabel, ylabel 119 import numpy as np 120 showTime = False 121 showEventTime = True 122 showEventFlops = True 123 arches = sizes.keys() 124 # Time 125 if showTime: 126 data = [] 127 for arch in arches: 128 data.append(sizes[arch]) 129 data.append(times[arch]) 130 plot(*data) 131 title('Performance on '+library+' Example '+str(num)) 132 xlabel('Number of Dof') 133 ylabel('Time (s)') 134 legend(arches, 'upper left', shadow = True) 135 show() 136 # Common event time 137 # We could make a stacked plot like Rio uses here 138 if showEventTime: 139 bs = events[arches[0]].keys()[0] 140 data = [] 141 names = [] 142 for event, color in zip(eventNames, ['b', 'g', 'r', 'y']): 143 for arch, style in zip(arches, ['-', ':']): 144 if event in events[arch][bs]: 145 names.append(arch+'-'+str(bs)+' '+event) 146 data.append(sizes[arch][bs]) 147 data.append(np.array(events[arch][bs][event])[:,0]) 148 data.append(color+style) 149 else: 150 print 'Could not find %s in %s-%d events' % (event, arch, bs) 151 print data 152 plot(*data) 153 title('Performance on '+library+' Example '+str(num)) 154 xlabel('Number of Dof') 155 ylabel('Time (s)') 156 legend(names, 'upper left', shadow = True) 157 show() 158 # Common event flops 159 # We could make a stacked plot like Rio uses here 160 if showEventFlops: 161 bs = events[arches[0]].keys()[0] 162 data = [] 163 names = [] 164 for event, color in zip(eventNames, ['b', 'g', 'r', 'y']): 165 for arch, style in zip(arches, ['-', ':']): 166 if event in events[arch][bs]: 167 names.append(arch+'-'+str(bs)+' '+event) 168 data.append(sizes[arch][bs]) 169 data.append(np.array(events[arch][bs][event])[:,1]) 170 data.append(color+style) 171 else: 172 print 'Could not find %s in %s-%d events' % (event, arch, bs) 173 plot(*data) 174 title('Performance on '+library+' Example '+str(num)) 175 xlabel('Number of Dof') 176 ylabel('Computation Rate (MF/s)') 177 legend(names, 'upper left', shadow = True) 178 show() 179 return 180 181def plotSummaryBar(library, num, eventNames, sizes, times, events): 182 import numpy as np 183 import matplotlib.pyplot as plt 184 185 eventColors = ['b', 'g', 'r', 'y'] 186 arches = sizes.keys() 187 names = [] 188 N = len(sizes[arches[0]]) 189 width = 0.2 190 ind = np.arange(N) - 0.25 191 bars = {} 192 for arch in arches: 193 bars[arch] = [] 194 bottom = np.zeros(N) 195 for event, color in zip(eventNames, eventColors): 196 names.append(arch+' '+event) 197 times = np.array(events[arch][event])[:,0] 198 bars[arch].append(plt.bar(ind, times, width, color=color, bottom=bottom)) 199 bottom += times 200 ind += 0.3 201 202 plt.xlabel('Number of Dof') 203 plt.ylabel('Time (s)') 204 plt.title('GPU vs. CPU Performance on '+library+' Example '+str(num)) 205 plt.xticks(np.arange(N), map(str, sizes[arches[0]])) 206 #plt.yticks(np.arange(0,81,10)) 207 #plt.legend( (p1[0], p2[0]), ('Men', 'Women') ) 208 plt.legend([bar[0] for bar in bars[arches[0]]], eventNames, 'upper right', shadow = True) 209 210 plt.show() 211 return 212 213def getDMComplexSize(dim, out): 214 '''Retrieves the number of cells from ''' 215 size = 0 216 for line in out.split('\n'): 217 if line.strip().startswith(str(dim)+'-cells: '): 218 size = int(line.strip()[9:]) 219 break 220 return size 221 222def run_DMDA(ex, name, opts, args, sizes, times, events): 223 for n in map(int, args.size): 224 ex.run(da_grid_x=n, da_grid_y=n, **opts) 225 sizes[name].append(n*n * args.comp) 226 processSummary('summary', args.stage, args.events, times[name], events[name]) 227 return 228 229def run_DMComplex(ex, name, opts, args, sizes, times, events): 230 # This should eventually be replaced by a direct FFC/Ignition interface 231 if args.operator == 'laplacian': 232 numComp = 1 233 elif args.operator == 'elasticity': 234 numComp = args.dim 235 else: 236 raise RuntimeError('Unknown operator: %s' % args.operator) 237 238 for numBlock in [2**i for i in map(int, args.blockExp)]: 239 opts['gpu_blocks'] = numBlock 240 # Generate new block size 241 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]) 242 print(cmd) 243 ret = os.system('python '+cmd) 244 args.files = ['['+','.join(source)+']'] 245 buildExample(args) 246 sizes[name][numBlock] = [] 247 times[name][numBlock] = [] 248 events[name][numBlock] = {} 249 for r in map(float, args.refine): 250 out = ex.run(refinement_limit=r, **opts) 251 sizes[name][numBlock].append(getDMComplexSize(args.dim, out)) 252 processSummary('summary', args.stage, args.events, times[name][numBlock], events[name][numBlock]) 253 return 254 255if __name__ == '__main__': 256 import argparse 257 258 parser = argparse.ArgumentParser(description = 'PETSc Benchmarking', 259 epilog = 'This script runs src/<library>/examples/tutorials/ex<num>, For more information, visit http://www.mcs.anl.gov/petsc', 260 formatter_class = argparse.ArgumentDefaultsHelpFormatter) 261 parser.add_argument('--library', default='SNES', help='The PETSc library used in this example') 262 parser.add_argument('--num', type = int, default='5', help='The example number') 263 parser.add_argument('--module', default='summary', help='The module for timing output') 264 parser.add_argument('--stage', default='Main_Stage', help='The default logging stage') 265 parser.add_argument('--events', nargs='+', help='Events to process') 266 parser.add_argument('--batch', action='store_true', default=False, help='Generate batch files for the runs instead') 267 subparsers = parser.add_subparsers(help='DM types') 268 269 parser_dmda = subparsers.add_parser('DMDA', help='Use a DMDA for the problem geometry') 270 parser_dmda.add_argument('--size', nargs='+', default=['10'], help='Grid size (implementation dependent)') 271 parser_dmda.add_argument('--comp', type = int, default='1', help='Number of field components') 272 parser_dmda.add_argument('runs', nargs='*', help='Run descriptions: <name>=<args>') 273 274 parser_dmmesh = subparsers.add_parser('DMComplex', help='Use a DMComplex for the problem geometry') 275 parser_dmmesh.add_argument('--dim', type = int, default='2', help='Spatial dimension') 276 parser_dmmesh.add_argument('--refine', nargs='+', default=['0.0'], help='List of refinement limits') 277 parser_dmmesh.add_argument('--order', type = int, default='1', help='Order of the finite element') 278 parser_dmmesh.add_argument('--operator', default='laplacian', help='The operator name') 279 parser_dmmesh.add_argument('--blockExp', nargs='+', default=range(0, 5), help='List of block exponents j, block size is 2^j') 280 parser_dmmesh.add_argument('runs', nargs='*', help='Run descriptions: <name>=<args>') 281 282 args = parser.parse_args() 283 print(args) 284 if hasattr(args, 'comp'): 285 args.dmType = 'DMDA' 286 else: 287 args.dmType = 'DMComplex' 288 289 ex = PETScExample(args.library, args.num, log_summary='summary.dat', log_summary_python = None if args.batch else args.module+'.py', preload='off') 290 source = ex.petsc.source(args.library, args.num) 291 sizes = {} 292 times = {} 293 events = {} 294 295 for run in args.runs: 296 name, stropts = run.split('=', 1) 297 opts = dict([t if len(t) == 2 else (t[0], None) for t in [arg.split('=', 1) for arg in stropts.split(' ')]]) 298 if args.dmType == 'DMDA': 299 sizes[name] = [] 300 times[name] = [] 301 events[name] = {} 302 run_DMDA(ex, name, opts, args, sizes, times, events) 303 elif args.dmType == 'DMComplex': 304 sizes[name] = {} 305 times[name] = {} 306 events[name] = {} 307 run_DMComplex(ex, name, opts, args, sizes, times, events) 308 print('sizes',sizes) 309 print('times',times) 310 print('events',events) 311 if not args.batch: plotSummaryLine(args.library, args.num, args.events, sizes, times, events) 312# Benchmark for ex50 313# ./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' 314# Benchmark for ex52 315# ./src/benchmarks/benchmarkExample.py --events IntegBatchCPU IntegBatchGPU IntegGPUOnly --num 52 DMComplex --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' 316