tune_ck.py 3.69 KB
Newer Older
Paul's avatar
Fixes  
Paul committed
1
import os, json, subprocess, tempfile, sys, argparse, contextlib
Paul's avatar
Paul committed
2

Alan Turner's avatar
Alan Turner committed
3
ck_function = -1
Paul's avatar
Format  
Paul committed
4

Alan Turner's avatar
Alan Turner committed
5

Paul's avatar
Fixes  
Paul committed
6
7
8
9
10
11
12
13
14
15
16
17
@contextlib.contextmanager
def tmp_file(dump=None):
    tmp_name = None
    try:
        with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f:
            tmp_name = f.name
            if dump:
                dump(f)
        yield tmp_name
    finally:
        os.unlink(tmp_name)

Paul's avatar
Format  
Paul committed
18

Paul's avatar
Fixes  
Paul committed
19
def pretty_print(obj):
Paul's avatar
Paul committed
20
    print(json.dumps(obj, indent=2))
Paul's avatar
Paul committed
21

Paul's avatar
Format  
Paul committed
22

Paul's avatar
Paul committed
23
24
def run_driver(b):
    print(b)
Alan Turner's avatar
Alan Turner committed
25
26
27
    #outfile = open("temp2.json", "w")
    #json.dump(b, outfile)
    #outfile.close()
Paul's avatar
Paul committed
28
29
30
    with tmp_file(lambda tf: json.dump(b, tf)) as tf:
        cp = subprocess.run('./bin/gpu-driver {}'.format(tf),
                            capture_output=True,
Paul's avatar
Paul committed
31
                            check=True,
Paul's avatar
Paul committed
32
33
34
35
36
37
38
39
40
                            shell=True)
        for line in cp.stdout.decode().split("\n"):
            s = line.strip()
            if not s:
                continue
            if not ']: ' in s:
                continue
            yield s.split(']: ')[1].strip()

Paul's avatar
Format  
Paul committed
41

Paul's avatar
Paul committed
42
43
def convert_to_float(s):
    return s[:-2]
Paul's avatar
Format  
Paul committed
44

Paul's avatar
Format  
Paul committed
45

Paul's avatar
Paul committed
46
47
48
49
def get_device_time(s):
    fields = s.split(',')
    return convert_to_float(fields[-1].strip())

Paul's avatar
Format  
Paul committed
50

Paul's avatar
Paul committed
51
def benchmark_ck(config, tuning):
Paul's avatar
Paul committed
52
    try:
Alan Turner's avatar
Alan Turner committed
53
        b0 = {
Paul's avatar
Paul committed
54
55
56
57
58
59
60
61
62
            'settings': {
                'iterations': 100
            },
            'compile_op': {
                'name': 'ck_gemm',
                'check': True,
                'tuning_val': tuning,
                'inputs': config
            }
Paul's avatar
Paul committed
63
        }
Alan Turner's avatar
Alan Turner committed
64
65
66
67
68
69
70
71
72
73
74
75
        b1 = {
            'settings': {
                'iterations': 100
            },
            'compile_op': {
                'name': 'ck_gemm_softmax_gemm',
                'check': True,
                'tuning_val': tuning,
                'inputs': config
            }
        }
        b = b0 if (ck_function == 0) else b1
Paul's avatar
Paul committed
76
77
78
        for line in run_driver(b):
            dtime = get_device_time(line)
            print(dtime)
Paul's avatar
Paul committed
79
80
            return float(dtime)
    except:
Paul's avatar
Paul committed
81
        return sys.float_info.max
Paul's avatar
Paul committed
82

Paul's avatar
Format  
Paul committed
83

Paul's avatar
Paul committed
84
def benchmark(config, size):
Paul's avatar
Paul committed
85
    times = [benchmark_ck(config, i) for i in range(size)]
Paul's avatar
Use min  
Paul committed
86
    return times.index(min(times))
Paul's avatar
Paul committed
87

Paul's avatar
Format  
Paul committed
88

Paul's avatar
Paul committed
89
def parse_log(f):
Paul's avatar
Paul committed
90
91
    for line in open(f).readlines():
        line = line.strip()
Alan Turner's avatar
Alan Turner committed
92
93
94
95
96
97
98
99
100
101
102
        global ck_function
        if line.startswith('ck_gemm:'):
            line = line[len('ck_gemm:'):].strip()
            config = json.loads(line)
            ck_function = 0
            yield config
        if line.startswith('ck_gemm_softmax_gemm:'):
            line = line[len('ck_gemm_softmax_gemm:'):].strip()
            config = json.loads(line)
            ck_function = 1
            yield config
Paul's avatar
Paul committed
103

Paul's avatar
Format  
Paul committed
104

105
def benchmark_log(f, n):
Paul's avatar
Paul committed
106
    result = []
Alan Turner's avatar
Alan Turner committed
107
108
109
110
    logs = parse_log(f)
    for config in logs:
        additional_tv = ck_function * 2
        tuned = benchmark(config, n + additional_tv)
Paul's avatar
Paul committed
111
        print("Tuned:", tuned)
Paul's avatar
Paul committed
112
113
114
115
116
        result.append([config, tuned])
    return result


def parse_args():
Paul's avatar
Format  
Paul committed
117
118
119
    parser = argparse.ArgumentParser(description="Simple tuner for CK gemms")
    parser.add_argument('--log',
                        '-l',
Paul's avatar
Paul committed
120
121
122
                        type=str,
                        metavar='file',
                        help='Path to logfile')
Paul's avatar
Format  
Paul committed
123
124
    parser.add_argument('--out',
                        '-o',
Paul's avatar
Paul committed
125
126
127
                        type=str,
                        metavar='file',
                        help='Output json file to save tunings')
Paul's avatar
Format  
Paul committed
128
    parser.add_argument('-n', type=int, help='Number of instances to tune')
Paul's avatar
Paul committed
129
130
131
    args = parser.parse_args()
    return args

Paul's avatar
Format  
Paul committed
132

Paul's avatar
Paul committed
133
def run(args):
134
    tuned = benchmark_log(args.log, args.n)
Paul's avatar
Paul committed
135
136
    json.dump(tuned, open(args.out, 'w+'))

Alan Turner's avatar
Alan Turner committed
137
138
139
def tune(log, n, out):
    tuned = benchmark_log(log, n)
    json.dump(tuned, open(out, 'w+'))
Paul's avatar
Format  
Paul committed
140

Alan Turner's avatar
Alan Turner committed
141
142
if __name__ == '__main__':
    run(parse_args())