/
nvcc_flags_tuner.py
184 lines (157 loc) · 6.91 KB
/
nvcc_flags_tuner.py
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
import opentuner
from opentuner import ConfigurationManipulator
from opentuner import EnumParameter
from opentuner import IntegerParameter
from opentuner import MeasurementInterface
from opentuner import Result
import time
import argparse
import logging
import subprocess
log = logging.getLogger('nvccflags')
argparser = argparse.ArgumentParser(parents=opentuner.argparsers())
argparser.add_argument( "-f", "--file",
dest = "filename",
type = str,
required = True,
help = "A file to tune.")
argparser.add_argument( "-fargs", "--file-args",
dest = "fargs",
type = str,
nargs = '*',
help = "Program arguments.")
argparser.add_argument( "-ld", "--log-dir",
dest = "logdir",
type = str,
required = True,
help = "Directory to save this tuning run.")
argparser.add_argument( "-lc", "--log-cmd",
dest = "logcmd",
type = str,
required = True,
help = "File to save best configuration to.")
argparser.add_argument( "-cp", "--cuda-path",
dest = "cuda_path",
type = str,
required = True,
help = "Path to CUDA libraries.")
class NvccFlagsTuner(MeasurementInterface):
def manipulator(self):
manipulator = ConfigurationManipulator()
for flag in NVCC_FLAGS + PTXAS_FLAGS + NVLINK_FLAGS:
manipulator.add_parameter(
EnumParameter(flag,
["on", "off"]))
for d in [NVCC_PARAMS, PTXAS_PARAMS]:
for flag, values in d.iteritems():
manipulator.add_parameter(EnumParameter(flag, values))
for param, pmin, pmax in NVCC_NUM_PARAMS + PTXAS_NUM_PARAMS:
manipulator.add_parameter(IntegerParameter(param, pmin, pmax))
return manipulator
def parse_flags(self, flag_list, target):
cmd = ""
for full_flag, value in flag_list:
flag = full_flag.split(":")[1]
if (value == "on"):
cmd += " " + target + " " + flag + " "
elif (value != "off"):
cmd += " " + target + " " + flag + str(value) + " "
return cmd
def parse_config(self, cfg):
nvcc_flags = [ (key, value) for key,value in cfg.iteritems() if key.startswith("nvcc") ]
ptxas_flags = [ (key, value) for key,value in cfg.iteritems() if key.startswith("ptxas") ]
nvlink_flags = [ (key, value) for key,value in cfg.iteritems() if key.startswith("nvlink") ]
cmd = NVCC_CMD
cmd += self.parse_flags(nvcc_flags, "")
cmd += self.parse_flags(ptxas_flags, PTXAS_NAME)
cmd += self.parse_flags(nvlink_flags, NVLINK_NAME)
return cmd
def run(self, desired_result, input, limit):
cfg = desired_result.configuration.data
cmd = self.parse_config(cfg)
compile_result = subprocess.call(cmd, shell = True)
if compile_result != 0:
return Result(time=FAIL_PENALTY)
# Give a better value to the Tuner (average)
results = []
evaluations = 3
global CONFIGS_TESTED
CONFIGS_TESTED += 1
for i in range(evaluations):
start = time.time()
run_result = subprocess.call("./tmp.bin " + " ".join(FARGS),
shell = True)
end = time.time()
if run_result != 0:
with open(LOG_DIR + "failed_configurations.txt", "a+") as file:
file.write("failed_example_cmd: " + cmd + "\n")
global CONFIGS_FAILED
CONFIGS_FAILED += 1
return Result(time=FAIL_PENALTY)
else:
results.append(end - start)
# Calculate Average:
final_result = (sum(results) / len(results))
# We now return the average of runs,
# the idea is giving more 'context'
# to the tuner.
return Result(time=final_result)
def save_final_config(self, configuration):
cfg = configuration.data
print "Optimal configuration written to 'final_config.json'."
self.manipulator().save_to_file(cfg, LOG_DIR + 'final_config.json')
cmd = self.parse_config(cfg)
print "Optimal config written to " + LOG_DIR + LOG_FILE + ": ", cmd
with open(LOG_DIR + LOG_FILE, "a+") as myfile:
myfile.write(cmd + "\n")
with open(LOG_DIR + "failed_stats.txt", "a+") as file:
file.write("tested_configurations : " + str(CONFIGS_TESTED) + "\n")
file.write("failed_configurations : " + str(CONFIGS_FAILED) + "\n")
file.write("ratio (% of failed configurations): " + str(CONFIGS_FAILED / float(CONFIGS_TESTED)) + "\n")
if __name__ == '__main__':
FARGS = ""
# Specify gcc options:
GCC_NAME = "-Xcompiler"
GCC_FLAGS = []
GCC_PARAMS = []
GCC_NUM_PARAMS = []
# name
NVCC_FLAGS = [ "nvcc:--no-align-double",
"nvcc:--use_fast_math" ]
# { name : [ args ] }
NVCC_PARAMS = { "nvcc:--gpu-architecture=" : [ "sm_20", "sm_21",
"sm_30", "sm_35" ],
"nvcc:--relocatable-device-code=" : [ "true", "false" ],
"nvcc:--ftz=" : [ "true", "false" ],
"nvcc:--prec-div=" : [ "true", "false" ],
"nvcc:--prec-sqrt=" : [ "true", "false" ] }
# (name, min, max)
NVCC_NUM_PARAMS = [ ]
# Specify ptxas options:
PTXAS_NAME = "-Xptxas "
# name
PTXAS_FLAGS = [ ]
# { name : [ args ] }
PTXAS_PARAMS = { "ptxas:--def-load-cache=" : [ "ca", "cg", "cv", "cs" ],
"ptxas:--opt-level=" : [ "0", "1", "2", "3" ],
"ptxas:--fmad=" : [ "true", "false" ],
"ptxas:--allow-expensive-optimizations=" : [ "true", "false" ] }
# ( name, min, max )
PTXAS_NUM_PARAMS = [ ( "ptxas:--maxrregcount=", 16, 63 ) ]
# Specify NVLINK options:
NVLINK_NAME = "-Xnvlink "
# name
NVLINK_FLAGS = [ "nvlink:--preserve-relocs" ]
FAIL_PENALTY = 9999
CONFIGS_FAILED = 0
CONFIGS_TESTED = 0
opentuner.init_logging()
args = argparser.parse_args()
LOG_DIR = args.logdir
LOG_FILE = args.logcmd
NVCC_CMD = "nvcc -w -ccbin g++-4.8 " + args.cuda_path
filename = args.filename
if (args.fargs):
FARGS = args.fargs
NVCC_CMD += filename + " -o ./tmp.bin "
NvccFlagsTuner.main(argparser.parse_args())