energy_perf_bar.py 18.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
import os, sys, argparse
import numpy
import matplotlib.pyplot as plt
import json
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import Rectangle
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from sets import Set

from common import *

def get_energy(frontiers_data, cpu_freq, mem_freq, sample, bmark):
	for point in frontiers_data["data"][sample]:
		if point["cpu_freq"] == cpu_freq:
			if point["mem_freq"] == mem_freq:
				return point["energy"]

def get_performance(frontiers_data, cpu_freq, mem_freq, sample, bmark):
	for point in frontiers_data["data"][sample]:
		if point["cpu_freq"] == cpu_freq:
			if point["mem_freq"] == mem_freq:
				return point["performance"]

def plot_energy_perf_bar(args, threshold_list, budget):
	dir_path = args.input_dir
	output_dir_path = args.output_dir
	perf_cost = 500000
	energy_cost = 30000
	benchmarks, labels = get_benchmarks(args)

	#plot constants
	cpuflist = get_cpu_freq_plot_list(args)
	memflist = get_mem_freq_plot_list(args)

	# finding points with 3% threshold of target budget/inefficiency
	thresh = 3
	energy_bar_data = [ [] for thr in threshold_list]
	performance_bar_data = [ [] for thr in threshold_list]
	energy_bar_data_nocost = [ [] for thr in threshold_list]
	performance_bar_data_nocost = [ [] for thr in threshold_list]

	print budget
	for threshold_index, cluster_thresh in enumerate(threshold_list):
		print cluster_thresh
		data = []
		for bmark in benchmarks:
			print bmark
			bmarkDirPath = os.path.join(os.path.join(dir_path, "per_sample_data"), bmark)
			frontiers_file = os.path.join(bmarkDirPath, "per_sample_frontiers.json")
			frontiers_data = json.loads(open(frontiers_file).read())

			data_to_plot=[]
			sample_points=[]
			cpu_rectangle_points=[]
			for data in frontiers_data["data"]:
				filtered_data=[]
				#filtering all those points which have inefficiency with error% of the budget
				for point in data:
					if point["inefficiency"] <= budget:
						filtered_data.append(point)
					elif (point["inefficiency"] - budget) * 100 / budget <= thresh:
						filtered_data.append(point)

				#finding the point with highest performance among filtered data
				optimal_point = filtered_data[0]
				for point in filtered_data:
					if point["speedup"] > optimal_point["speedup"]:
						optimal_point = point

				local_rect_points=[]
				for point in filtered_data:
					if (optimal_point["speedup"] - point["speedup"]) < 0:
						print "something is wrong!"

					if (optimal_point["speedup"] - point["speedup"]) * 100 / optimal_point["speedup"] <= cluster_thresh:
						data_to_plot.append(point)
						sample_points.append(frontiers_data["data"].index(data))
						local_rect_points.append(point)

			cpufpoints = [cpuf for cpuf in [data_to_plot[sample]["cpu_freq"] for sample in range(len(data_to_plot))]]
			memfpoints = [memf for memf in [data_to_plot[sample]["mem_freq"] for sample in range(len(data_to_plot))]]
			samplepoints = sample_points

			#Total number of transitions
			num_transitions = 0.0
			#Available settings for (CPU, MEM)
			settings_available = Set()
			index = 0
			current_sample = -1
			length = 1
			lengths = []
			prev_tr_sample = 0
			energy = 0
			performance = 0
			while index < len( samplepoints ):
				current_sample = samplepoints[index]

				#Construct the current settings
				current_settings = Set()
				while index < len( samplepoints ) and samplepoints[index] == current_sample:
					current_settings.add((cpufpoints[index],memfpoints[index]))
					index = index + 1

				#Compute the common points between current and what is available
				common_points  = current_settings.intersection(settings_available)

				if (len(common_points) == 0 or index == len( samplepoints )):
				# find the point with highest cpu and mem freq
					if (current_sample !=0 ):
						optimal_point = settings_available.pop()
						settings_available.add(optimal_point)
						for point in settings_available:
							if point[0] > optimal_point[0]:
								optimal_point = point
							elif point[0] == optimal_point[0]:
								if point[1] > optimal_point[1]:
									optimal_point = point
						done = 0
						idx = prev_tr_sample+1
						while done == 0:
							energy += get_energy(frontiers_data, optimal_point[0], optimal_point[1], idx, bmark)
							performance += get_performance(frontiers_data, optimal_point[0], optimal_point[1], idx, bmark)
							if idx == samplepoints[index-1]:
								done = 1
							else: 
								idx += 1

						prev_tr_sample = samplepoints[index-1]

				# When there are no common points, transition
				if (len(common_points) == 0):
					settings_available = current_settings #all current settings are now available
					#Ignore the transition if it's the first sample
					if (current_sample!=0):
						num_transitions += 1
				else: # Continue with the common points
					settings_available = common_points

				# Record the length if we need to transition or we are at the end
				if (len(common_points) == 0 or index == len( samplepoints )):
					#Ignore the length if the transition is for the first sample
					if (current_sample!=0):
						lengths.append(length)
					#reset the length
					length = 1
				else: #otherwise, just increment the length
					length += 1
			energy_bar_data[threshold_index].append((energy + (num_transitions * energy_cost))/1e6)
			performance_bar_data[threshold_index].append((performance +(num_transitions * perf_cost))/1e6 )
			energy_bar_data_nocost[threshold_index].append((energy)/1e6)
			performance_bar_data_nocost[threshold_index].append((performance )/1e6 )

	for threshold_index, cluster_thresh in enumerate(threshold_list):
		for bmark_index, bmark in enumerate(benchmarks):
			if threshold_index != 0:
				energy_bar_data[threshold_index][bmark_index] = (energy_bar_data[0][bmark_index] - energy_bar_data[threshold_index][bmark_index]) * 100 / energy_bar_data[0][bmark_index]
				performance_bar_data[threshold_index][bmark_index] = (performance_bar_data[threshold_index][bmark_index] - performance_bar_data[0][bmark_index]) * 100 / performance_bar_data[0][bmark_index]
				energy_bar_data_nocost[threshold_index][bmark_index] = (energy_bar_data_nocost[0][bmark_index] - energy_bar_data_nocost[threshold_index][bmark_index]) * 100 / energy_bar_data_nocost[0][bmark_index]
				performance_bar_data_nocost[threshold_index][bmark_index] = (performance_bar_data_nocost[threshold_index][bmark_index] - performance_bar_data_nocost[0][bmark_index]) * 100 / performance_bar_data_nocost[0][bmark_index]

	energy_bar_data = energy_bar_data[1:]
	performance_bar_data = performance_bar_data[1:]
	energy_bar_data_nocost = energy_bar_data_nocost[1:]
	performance_bar_data_nocost = performance_bar_data_nocost[1:]
	threshold_list = threshold_list[1:]

	bar_colors=['r', 'b', 'y', 'c', 'm', 'g', 'k', 'w']
	bar_width = 1.0 / (len(threshold_list)) #Number of thresholds times metrics
	offset = 0.1 #10% offset
	bar_width = bar_width *0.8 #fill 80% of the space
	index = numpy.arange(len(benchmarks))
	fig = plt.figure(figsize=(7.5,1.5))

# energy bar
	ax1 = fig.add_subplot(1, 4, 2)
	ax2 = fig.add_subplot(1, 4, 4)
	for threshold_index, cluster_thresh in enumerate(threshold_list):
		ax1.bar(index + offset + threshold_index*bar_width, [-1*x for x in energy_bar_data_nocost[threshold_index]], bar_width, label = str(cluster_thresh)+"\%" , color = bar_colors[threshold_index], edgecolor='none', linewidth=0)
	ax1.plot([0, len(benchmarks)], [0, 0], linewidth=1, color = 'k')
	ax1.set_ylabel("Energy (\%)", labelpad=0)
	ax1.set_xlim([0, len(benchmarks)])
	ax1.set_ylim([-2.5, 0.25])
	ax1.yaxis.grid('on')
	ax1.set_axisbelow(True)
	x_ticks = [i + offset*3 for i in range(len(benchmarks))]
	ax1.set_xticks(x_ticks)
	ax1.set_xticklabels(labels, rotation=45)

	for threshold_index, cluster_thresh in enumerate(threshold_list):
		ax2.bar(index + offset + threshold_index*bar_width, [-1*x for x in energy_bar_data[threshold_index]], bar_width, label = str(cluster_thresh)+"\%" , color = bar_colors[threshold_index], edgecolor='none', linewidth=0)
	ax2.plot([0, len(benchmarks)], [0, 0], linewidth=1, color = 'k')
	ax2.legend(fontsize=legend_size, bbox_to_anchor=(1.02, 1.), handlelength=1.0, loc=2, borderaxespad=0.,handletextpad=0.1)
	ax2.set_ylabel("Energy (\%)", labelpad=0)
	ax2.set_xlim([0, len(benchmarks)])
	ax2.set_ylim([-2.5, 0.25])
	ax2.yaxis.grid('on')
	ax2.set_axisbelow(True)
	x_ticks = [i + offset*3 for i in range(len(benchmarks))]
	ax2.set_xticks(x_ticks)
	ax2.set_xticklabels(labels, rotation=45)
	
	ax1.xaxis.set_ticks_position('bottom')
	ax1.yaxis.set_ticks_position('left')
	ax2.xaxis.set_ticks_position('bottom')
	ax2.yaxis.set_ticks_position('left')

# performance bar
	ax1 = fig.add_subplot(1, 4, 1)
	ax2 = fig.add_subplot(1, 4, 3)
	for threshold_index, cluster_thresh in enumerate(threshold_list):
		ax1.bar(index + offset + threshold_index*bar_width, [-1*x for x in performance_bar_data_nocost[threshold_index]], bar_width, label = str(cluster_thresh)+"\%" , color = bar_colors[threshold_index], edgecolor='none', linewidth=0)
		ax1.plot([0, len(benchmarks)], [-1*x for x in [cluster_thresh, cluster_thresh]], linewidth=1, color = bar_colors[threshold_index], linestyle='--')
	ax1.plot([0, len(benchmarks)], [0, 0], linewidth=1, color = 'k')
	ax1.set_ylabel("Performance (\%)", labelpad=-1)
	ax1.set_xlim([0, len(benchmarks)])
	if budget == 1.0:
		ax1.set_ylim([-5, 1.5])
	elif budget == 1.3:
		ax1.set_ylim([-3.5, 1.25])
	else:
		ax1.set_ylim([-5, 5])
	ax1.yaxis.grid('on')
	ax1.set_axisbelow(True)
	x_ticks = [i + offset*3 for i in range(len(benchmarks))]
	ax1.set_xticks(x_ticks)
	ax1.set_xticklabels(labels, rotation=45)
	
	for threshold_index, cluster_thresh in enumerate(threshold_list):
		ax2.bar(index + offset + threshold_index*bar_width, [-1*x for x in performance_bar_data[threshold_index]], bar_width, label = str(cluster_thresh)+"\%" , color = bar_colors[threshold_index], edgecolor='none', linewidth=0)
		ax2.plot([0, len(benchmarks)], [-1*x for x in [cluster_thresh, cluster_thresh]], linewidth=1, color = bar_colors[threshold_index], linestyle='--')
	ax2.plot([0, len(benchmarks)], [0, 0], linewidth=1, color = 'k')
	ax2.set_ylabel("Performance (\%)", labelpad=-1)
	ax2.set_xlim([0, len(benchmarks)])
	if budget == 1.0:
		ax2.set_ylim([-5, 1.5])
	elif budget == 1.3:
		ax2.set_ylim([-3.5, 4])
	else:
		ax2.set_ylim([-5, 5])
	ax2.yaxis.grid('on')
	ax2.set_axisbelow(True)
	x_ticks = [i + offset*3 for i in range(len(benchmarks))]
	ax2.set_xticks(x_ticks)
	ax2.set_xticklabels(labels, rotation=45)
	
	ax1.xaxis.set_ticks_position('bottom')
	ax1.yaxis.set_ticks_position('left')
	ax2.xaxis.set_ticks_position('bottom')
	ax2.yaxis.set_ticks_position('left')
	
	ax1.text(4.2, -6.5, '(a) No Tuning Overhead')
	ax2.text(4, -8.2, '(b) With Tuning Overhead')

	outputf = os.path.join(os.path.join(output_dir_path, "energy_perf_bar"), "energy_perf_bar_%s" % (str(budget)))
	fig.subplots_adjust(top=0.9, right=0.92, left=0.05, bottom=0.4, wspace=0.38, hspace=0.0)
	plt.savefig("%s.pdf" % (outputf))

def plot_abs_energy_time_bar(args, budget_list, cluster_thresh, perf_cost, energy_cost):
	dir_path = args.input_dir
	output_dir_path = args.output_dir

	benchmarks, labels = get_benchmarks(args)
	#plot constants
	cpuflist = get_cpu_freq_plot_list(args)
	memflist = get_mem_freq_plot_list(args)
#	dir_path = 'data/70/'

	# finding points with 3% threshold of target budget/inefficiency
	thresh = 3
	energy_bar_data = [ [] for thr in budget_list]
	performance_bar_data = [ [] for thr in budget_list]
	for budget_index, budget in enumerate(budget_list):
		data = []
		for bmark in benchmarks:
			bmarkDirPath = os.path.join(os.path.join(dir_path, "per_sample_data"), bmark)
			frontiers_file = os.path.join(bmarkDirPath, "per_sample_frontiers.json")
			frontiers_data = json.loads(open(frontiers_file).read())

			data_to_plot=[]
			sample_points=[]
			cpu_rectangle_points=[]
			for data in frontiers_data["data"]:
				filtered_data=[]
				#filtering all those points which have inefficiency with error% of the budget
				for point in data:
					if point["inefficiency"] <= budget:
						filtered_data.append(point)
					elif (point["inefficiency"] - budget) * 100 / budget <= thresh:
						filtered_data.append(point)

				#finding the point with highest performance among filtered data
				optimal_point = filtered_data[0]
				for point in filtered_data:
					if point["speedup"] > optimal_point["speedup"]:
						optimal_point = point

				local_rect_points=[]
				for point in filtered_data:
					if (optimal_point["speedup"] - point["speedup"]) < 0:
						print "something is wrong!"

					if (optimal_point["speedup"] - point["speedup"]) * 100 / optimal_point["speedup"] <= cluster_thresh:
						data_to_plot.append(point)
						sample_points.append(frontiers_data["data"].index(data))
						local_rect_points.append(point)

			cpufpoints = [cpuf for cpuf in [data_to_plot[sample]["cpu_freq"] for sample in range(len(data_to_plot))]]
			memfpoints = [memf for memf in [data_to_plot[sample]["mem_freq"] for sample in range(len(data_to_plot))]]
			samplepoints = sample_points

			#Total number of transitions
			num_transitions = 0.0
			#Available settings for (CPU, MEM)
			settings_available = Set()
			index = 0
			current_sample = -1
			length = 1
			lengths = []
			prev_tr_sample = 0
			energy = 0
			performance = 0
			while index < len( samplepoints ):
				current_sample = samplepoints[index]

				#Construct the current settings
				current_settings = Set()
				while index < len( samplepoints ) and samplepoints[index] == current_sample:
					current_settings.add((cpufpoints[index],memfpoints[index]))
					index = index + 1

				#Compute the common points between current and what is available
				common_points  = current_settings.intersection(settings_available)

				if (len(common_points) == 0 or index == len( samplepoints )):
				# find the point with highest cpu and mem freq
					if (current_sample !=0 ):
						optimal_point = settings_available.pop()
						settings_available.add(optimal_point)
						for point in settings_available:
							if point[0] > optimal_point[0]:
								optimal_point = point
							elif point[0] == optimal_point[0]:
								if point[1] > optimal_point[1]:
									optimal_point = point
						done = 0
						idx = prev_tr_sample+1
						while done == 0:
							energy += get_energy(frontiers_data, optimal_point[0], optimal_point[1], idx, bmark)
							performance += get_performance(frontiers_data, optimal_point[0], optimal_point[1], idx, bmark)
							if idx == samplepoints[index-1]:
								done = 1
							else: 
								idx += 1

						prev_tr_sample = samplepoints[index-1]

				# When there are no common points, transition
				if (len(common_points) == 0):
					settings_available = current_settings #all current settings are now available
					#Ignore the transition if it's the first sample
					if (current_sample!=0):
						num_transitions += 1
				else: # Continue with the common points
					settings_available = common_points

				# Record the length if we need to transition or we are at the end
				if (len(common_points) == 0 or index == len( samplepoints )):
					#Ignore the length if the transition is for the first sample
					if (current_sample!=0):
						lengths.append(length)
					#reset the length
					length = 1
				else: #otherwise, just increment the length
					length += 1
			energy_bar_data[budget_index].append((energy + (num_transitions * energy_cost))/1e6)
			performance_bar_data[budget_index].append((performance +(num_transitions * perf_cost))/1e6 )
			#print performance
			#print energy

	for bmark_index, bmark in enumerate(benchmarks):
		for budget_index, budget in enumerate(budget_list):
			if budget_index != 0:
				energy_bar_data[budget_index][bmark_index] = energy_bar_data[budget_index][bmark_index] / energy_bar_data[0][bmark_index]
				performance_bar_data[budget_index][bmark_index] = (performance_bar_data[budget_index][bmark_index] / performance_bar_data[0][bmark_index])
		energy_bar_data[0][bmark_index] = 1
		performance_bar_data[0][bmark_index] = 1

	bar_colors=['r', 'b', 'y', 'c', 'm', 'g', 'k', 'w']
	bar_width = 1.0 / (len(budget_list)) #Number of thresholds times metrics
	offset = 0.1 #10% offset
	bar_width = bar_width *0.8 #fill 80% of the space
	index = numpy.arange(len(benchmarks))
# energy bar
	fig = plt.figure(figsize=(3, 1))
	canvas = FigureCanvas(fig)
	fig.set_canvas(canvas)
	ax = fig.add_subplot('111')
	bars = []
	for budget_index, budget in enumerate(budget_list):
		bar = ax.bar(index + offset + budget_index*bar_width, energy_bar_data[budget_index], bar_width, label = str(budget) if budget < 2 else "\infty" , color = bar_colors[budget_index], edgecolor='none', linewidth=0)
		bars.append(bar)
	ax.legend(fontsize=legend_size, ncol = 6, bbox_to_anchor=(0., 1.02, 1., .102), handlelength=1.0, handletextpad=0.1, loc=3, borderaxespad=0., mode="expand")
	ax.set_ylabel("Consumed \nInefficiency")
	ax.set_xlim([0, len(benchmarks)])
	ax.set_ylim([0, 2])
	ax.grid('on')
	ax.set_axisbelow(True)
	x_ticks = [i + offset*5 for i in range(len(benchmarks))]
	ax.set_xticks(x_ticks)
	ax.set_xticklabels(labels, rotation=45)

	#fig.legend(bars, budget_list, fontsize=legend_size, bbox_to_anchor=(1.19,1.49), labelspacing=0.15, handletextpad=0.7)
	outputf = os.path.join(os.path.join(output_dir_path, "energy_perf_bar"), "energy_bar_normalized_%s_%s_%s" % (str(cluster_thresh), perf_cost, energy_cost))
	save_plot(ax, outputf)
	canvas.close()

# performance bar
	fig = plt.figure(figsize=(3, 1))
	canvas = FigureCanvas(fig)
	fig.set_canvas(canvas)
	ax = fig.add_subplot('111')
	bars = []
	for budget_index, budget in enumerate(budget_list):
		bar = ax.bar(index + offset + budget_index*bar_width, performance_bar_data[budget_index], bar_width, label = str(budget) if budget < 2 else "\infty" , color = bar_colors[budget_index], edgecolor='none', linewidth=0)
		bars.append(bar)
	ax.legend(fontsize=legend_size, ncol = 6, bbox_to_anchor=(0., 1.02, 1., .102), handlelength=1.0, handletextpad=0.1, loc=3, borderaxespad=0., mode="expand")
	ax.set_ylabel("Execution Time \n (Normalized)")
	ax.set_xlim([0, len(benchmarks)])
	ax.set_ylim([0, 1.2])
	ax.grid('on')
	ax.set_axisbelow(True)
	x_ticks = [i + offset*5 for i in range(len(benchmarks))]
	ax.set_xticks(x_ticks)
	ax.set_xticklabels(labels, rotation=45)

	#fig.legend(bars, budget_list, fontsize=legend_size, bbox_to_anchor=(1.19,1.49), labelspacing=0.15, handletextpad=0.7)
	outputf = os.path.join(os.path.join(output_dir_path, "energy_perf_bar"), "performance_bar_normalized_%s_%s_%s" % (str(cluster_thresh), perf_cost, energy_cost))
	save_plot(ax, outputf)
	canvas.close()

def main(argv):
	args = parse(argv)

	for thresh in [0.0, 1.0, 5.0]:
#	for thresh in [0.0]:
		plot_abs_energy_time_bar(args, [1.0,1.1, 1.2, 1.3,1.6,3.0], thresh, 0, 0)

	#no tuning overhead
	#for ineff in [1.0, 1.3, 1.6]:
	for ineff in [1.3]:
		plot_energy_perf_bar(args, [0,1,3,5], ineff)
	
	#with tuning overhead - 500us, 30uJ (scaled bzip2 energy of first sample at maxmax to 30us)
#	for ineff in [1.0, 1.3, 1.6]:
#	for ineff in [1.3]:
#		plot_energy_perf_bar(args, [0,1,3,5], ineff)
	
if __name__ == "__main__":
	main(sys.argv)