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, eventNames, 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 zip(eventName, ['b', 'g', 'r', 'y']: 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 zip(eventName, ['b', 'g', 'r', 'y']: 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, eventNames, sizes, times, events): 170 import numpy as np 171 import matplotlib.pyplot as plt 172 173 eventColors = ['b', 'g', 'r', 'y'] 174 arches = sizes.keys() 175 names = [] 176 N = len(sizes[arches[0]]) 177 width = 0.2 178 ind = np.arange(N) - 0.25 179 bars = {} 180 for arch in arches: 181 bars[arch] = [] 182 bottom = np.zeros(N) 183 for event, color in zip(eventNames, eventColors): 184 names.append(arch+' '+event) 185 times = np.array(events[arch][event])[:,0] 186 bars[arch].append(plt.bar(ind, times, width, color=color, bottom=bottom)) 187 bottom += times 188 ind += 0.3 189 190 plt.xlabel('Number of Dof') 191 plt.ylabel('Time (s)') 192 plt.title('GPU vs. CPU Performance on '+library+' Example '+str(num)) 193 plt.xticks(np.arange(N), map(str, sizes[arches[0]])) 194 #plt.yticks(np.arange(0,81,10)) 195 #plt.legend( (p1[0], p2[0]), ('Men', 'Women') ) 196 plt.legend([bar[0] for bar in bars[arches[0]]], eventNames, 'upper right', shadow = True) 197 198 plt.show() 199 return 200 201def getDMMeshSize(dim, out): 202 '''Retrieves the number of cells from ''' 203 size = 0 204 for line in out.split('\n'): 205 if line.strip().startswith(str(dim)+'-cells: '): 206 size = int(line.strip()[9:]) 207 break 208 return size 209 210def run_DMDA(ex, name, opts, args, sizes, times, events): 211 for n in map(int, args.size): 212 ex.run(da_grid_x=n, da_grid_y=n, **opts) 213 sizes[name].append(n*n * args.comp) 214 processSummary('summary', args.stage, args.events, times[name], events[name]) 215 return 216 217def run_DMMesh(ex, name, opts, args, sizes, times, events): 218 # This should eventually be replaced by a direct FFC/Ignition interface 219 if args.operator == 'laplacian': 220 numComp = 1 221 elif args.operator == 'elasticity': 222 numComp = args.dim 223 else: 224 raise RuntimeError('Unknown operator: %s' % args.operator) 225 226 for numBlock in [2**i for i in map(int, args.blockExp)]: 227 opts['gpu_blocks'] = numBlock 228 # Generate new block size 229 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]) 230 print(cmd) 231 ret = os.system('python '+cmd) 232 args.files = ['['+','.join(source)+']'] 233 buildExample(args) 234 sizes[name][numBlock] = [] 235 times[name][numBlock] = [] 236 events[name][numBlock] = {} 237 for r in map(float, args.refine): 238 out = ex.run(refinement_limit=r, **opts) 239 sizes[name][numBlock].append(getDMMeshSize(args.dim, out)) 240 processSummary('summary', args.stage, args.events, times[name][numBlock], events[name][numBlock]) 241 return 242 243if __name__ == '__main__': 244 import argparse 245 246 parser = argparse.ArgumentParser(description = 'PETSc Benchmarking', 247 epilog = 'This script runs src/<library>/examples/tutorials/ex<num>, For more information, visit http://www.mcs.anl.gov/petsc', 248 formatter_class = argparse.ArgumentDefaultsHelpFormatter) 249 parser.add_argument('--library', default='SNES', help='The PETSc library used in this example') 250 parser.add_argument('--num', type = int, default='5', help='The example number') 251 parser.add_argument('--module', default='summary', help='The module for timing output') 252 parser.add_argument('--stage', default='Main_Stage', help='The default logging stage') 253 parser.add_argument('--events', nargs='+', help='Events to process') 254 parser.add_argument('--batch', action='store_true', default=False, help='Generate batch files for the runs instead') 255 subparsers = parser.add_subparsers(help='DM types') 256 257 parser_dmda = subparsers.add_parser('DMDA', help='Use a DMDA for the problem geometry') 258 parser_dmda.add_argument('--size', nargs='+', default=['10'], help='Grid size (implementation dependent)') 259 parser_dmda.add_argument('--comp', type = int, default='1', help='Number of field components') 260 parser_dmda.add_argument('runs', nargs='*', help='Run descriptions: <name>=<args>') 261 262 parser_dmmesh = subparsers.add_parser('DMMesh', help='Use a DMMesh for the problem geometry') 263 parser_dmmesh.add_argument('--dim', type = int, default='2', help='Spatial dimension') 264 parser_dmmesh.add_argument('--refine', nargs='+', default=['0.0'], help='List of refinement limits') 265 parser_dmmesh.add_argument('--order', type = int, default='1', help='Order of the finite element') 266 parser_dmmesh.add_argument('--operator', default='laplacian', help='The operator name') 267 parser_dmmesh.add_argument('--blockExp', nargs='+', default=range(0, 5), help='List of block exponents j, block size is 2^j') 268 parser_dmmesh.add_argument('runs', nargs='*', help='Run descriptions: <name>=<args>') 269 270 args = parser.parse_args() 271 print(args) 272 if hasattr(args, 'comp'): 273 args.dmType = 'DMDA' 274 else: 275 args.dmType = 'DMMesh' 276 277 ex = PETScExample(args.library, args.num, log_summary='summary.dat', log_summary_python = None if args.batch else args.module+'.py', preload='off') 278 source = ex.petsc.source(args.library, args.num) 279 sizes = {} 280 times = {} 281 events = {} 282 283 for run in args.runs: 284 name, stropts = run.split('=', 1) 285 opts = dict([t if len(t) == 2 else (t[0], None) for t in [arg.split('=', 1) for arg in stropts.split(' ')]]) 286 if args.dmType == 'DMDA': 287 sizes[name] = [] 288 times[name] = [] 289 events[name] = {} 290 run_DMDA(ex, name, opts, args, sizes, times, events) 291 elif args.dmType == 'DMMesh': 292 sizes[name] = {} 293 times[name] = {} 294 events[name] = {} 295 run_DMMesh(ex, name, opts, args, sizes, times, events) 296 print('sizes',sizes) 297 print('times',times) 298 print('events',events) 299 if not args.batch: plotSummaryLine(args.library, args.num, args.events, sizes, times, events) 300# Benchmark for ex50 301# ./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' 302# Benchmark for ex52 303# ./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' 304