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

Paul's avatar
Format  
Paul committed
3

Paul's avatar
Fixes  
Paul committed
4
5
6
7
8
9
10
11
12
13
14
15
@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
16

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

Paul's avatar
Format  
Paul committed
20

Paul's avatar
Paul committed
21
22
23
24
25
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
26
                            check=True,
Paul's avatar
Paul committed
27
28
29
30
31
32
33
34
35
                            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
36

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

Paul's avatar
Format  
Paul committed
40

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

Paul's avatar
Format  
Paul committed
45

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

Paul's avatar
Format  
Paul committed
66

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

Paul's avatar
Format  
Paul committed
71

Paul's avatar
Paul committed
72
def parse_log(f):
Paul's avatar
Paul committed
73
74
75
76
77
78
    for line in open(f).readlines():
        line = line.strip()
        if not line.startswith('ck_gemm:'):
            continue
        line = line[len('ck_gemm:'):].strip()
        config = json.loads(line)
Paul's avatar
Paul committed
79
80
        yield config

Paul's avatar
Format  
Paul committed
81

82
def benchmark_log(f, n):
Paul's avatar
Paul committed
83
84
    result = []
    for config in parse_log(f):
85
        tuned = benchmark(config, n)
Paul's avatar
Paul committed
86
87
88
89
90
        result.append([config, tuned])
    return result


def parse_args():
Paul's avatar
Format  
Paul committed
91
92
93
    parser = argparse.ArgumentParser(description="Simple tuner for CK gemms")
    parser.add_argument('--log',
                        '-l',
Paul's avatar
Paul committed
94
95
96
                        type=str,
                        metavar='file',
                        help='Path to logfile')
Paul's avatar
Format  
Paul committed
97
98
    parser.add_argument('--out',
                        '-o',
Paul's avatar
Paul committed
99
100
101
                        type=str,
                        metavar='file',
                        help='Output json file to save tunings')
Paul's avatar
Format  
Paul committed
102
    parser.add_argument('-n', type=int, help='Number of instances to tune')
Paul's avatar
Paul committed
103
104
105
    args = parser.parse_args()
    return args

Paul's avatar
Format  
Paul committed
106

Paul's avatar
Paul committed
107
def run(args):
108
    tuned = benchmark_log(args.log, args.n)
Paul's avatar
Paul committed
109
110
    json.dump(tuned, open(args.out, 'w+'))

Paul's avatar
Format  
Paul committed
111

Paul's avatar
Paul committed
112
run(parse_args())