tune_ck.py 3 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
def run_driver(b):
    print(b)
    with tmp_file(lambda tf: json.dump(b, tf)) as tf:
Paul's avatar
Paul committed
24
25
26
        if not os.path.exists('./bin/gpu-driver'):
            print("./bin/gpu-driver not found")
            os.abort()
Paul's avatar
Paul committed
27
28
29
        cp = subprocess.run('./bin/gpu-driver {}'.format(tf),
                            capture_output=True,
                            shell=True)
Paul's avatar
Paul committed
30
31
        print(cp.stderr.decode())
        cp.check_returncode()
Paul's avatar
Paul committed
32
33
34
35
36
37
38
39
        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
40

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

Paul's avatar
Format  
Paul committed
44

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

Paul's avatar
Format  
Paul committed
49

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

Paul's avatar
Format  
Paul committed
72

Paul's avatar
Paul committed
73
def benchmark(config, size):
Paul's avatar
Paul committed
74
    times = [benchmark_ck(config, i) for i in range(size)]
Paul's avatar
Use min  
Paul committed
75
    return times.index(min(times))
Paul's avatar
Paul committed
76

Paul's avatar
Format  
Paul committed
77

Paul's avatar
Paul committed
78
def parse_log(f):
Paul's avatar
Paul committed
79
80
81
82
83
84
    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
85
86
        yield config

Paul's avatar
Format  
Paul committed
87

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


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

Paul's avatar
Format  
Paul committed
113

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

Paul's avatar
Format  
Paul committed
118

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