tune_ck.py 3.24 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
25
26
27
def run_driver(b):
    print(b)
    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
28
                            check=True,
Paul's avatar
Paul committed
29
30
31
32
33
34
35
36
37
                            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
38

Paul's avatar
Paul committed
39
40
def convert_to_float(s):
    return s[:-2]
Paul's avatar
Format  
Paul committed
41

Paul's avatar
Format  
Paul committed
42

Paul's avatar
Paul committed
43
44
45
46
def get_device_time(s):
    fields = s.split(',')
    return convert_to_float(fields[-1].strip())

Paul's avatar
Format  
Paul committed
47

48
def benchmark_ck(config, name, tuning):
Paul's avatar
Paul committed
49
    try:
50
        b = {
Paul's avatar
Paul committed
51
52
53
54
            'settings': {
                'iterations': 100
            },
            'compile_op': {
55
                'name': name,
Paul's avatar
Paul committed
56
57
58
59
                'check': True,
                'tuning_val': tuning,
                'inputs': config
            }
Paul's avatar
Paul committed
60
        }
Paul's avatar
Paul committed
61
62
63
        for line in run_driver(b):
            dtime = get_device_time(line)
            print(dtime)
Paul's avatar
Paul committed
64
65
            return float(dtime)
    except:
Paul's avatar
Paul committed
66
        return sys.float_info.max
Paul's avatar
Paul committed
67

Paul's avatar
Format  
Paul committed
68

69
70
def benchmark(config, name, size):
    times = [benchmark_ck(config, name, i) for i in range(size)]
Paul's avatar
Use min  
Paul committed
71
    return times.index(min(times))
Paul's avatar
Paul committed
72

Paul's avatar
Format  
Paul committed
73

Paul's avatar
Paul committed
74
def parse_log(f):
Paul's avatar
Paul committed
75
76
    for line in open(f).readlines():
        line = line.strip()
Alan Turner's avatar
Alan Turner committed
77
78
79
80
        global ck_function
        if line.startswith('ck_gemm:'):
            line = line[len('ck_gemm:'):].strip()
            config = json.loads(line)
81
            yield (config, 'ck_gemm')
Alan Turner's avatar
Alan Turner committed
82
83
84
85
        if line.startswith('ck_gemm_softmax_gemm:'):
            line = line[len('ck_gemm_softmax_gemm:'):].strip()
            config = json.loads(line)
            ck_function = 1
86
            yield (config, 'ck_gemm_softmax_gemm')
Paul's avatar
Paul committed
87

Paul's avatar
Format  
Paul committed
88

89
def benchmark_log(f, n):
Paul's avatar
Paul committed
90
    result = []
91
92
    for config, name in parse_log(f):
        tuned = benchmark(config, name, n)
Paul's avatar
Paul committed
93
        print("Tuned:", tuned)
Paul's avatar
Paul committed
94
95
96
97
98
        result.append([config, tuned])
    return result


def parse_args():
Paul's avatar
Format  
Paul committed
99
100
101
    parser = argparse.ArgumentParser(description="Simple tuner for CK gemms")
    parser.add_argument('--log',
                        '-l',
Paul's avatar
Paul committed
102
103
104
                        type=str,
                        metavar='file',
                        help='Path to logfile')
Paul's avatar
Format  
Paul committed
105
106
    parser.add_argument('--out',
                        '-o',
Paul's avatar
Paul committed
107
108
109
                        type=str,
                        metavar='file',
                        help='Output json file to save tunings')
Paul's avatar
Format  
Paul committed
110
    parser.add_argument('-n', type=int, help='Number of instances to tune')
Paul's avatar
Paul committed
111
112
113
    args = parser.parse_args()
    return args

Paul's avatar
Format  
Paul committed
114

Paul's avatar
Paul committed
115
def run(args):
116
    tuned = benchmark_log(args.log, args.n)
Paul's avatar
Paul committed
117
118
    json.dump(tuned, open(args.out, 'w+'))

Alan Turner's avatar
Alan Turner committed
119

Alan Turner's avatar
Alan Turner committed
120
121
122
def tune(log, n, out):
    tuned = benchmark_log(log, n)
    json.dump(tuned, open(out, 'w+'))
Paul's avatar
Format  
Paul committed
123

Alan Turner's avatar
Alan Turner committed
124

Alan Turner's avatar
Alan Turner committed
125
126
if __name__ == '__main__':
    run(parse_args())