File size: 4,696 Bytes
f93f1b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Gap 4 task check: GSM8K and HumanEval subsets on native.gguf and on mask GGUFs (one llama-server per model x test,
one card each). Mask GGUFs are rebuilt with slicer.py --mode mask if missing, and deleted at the end.

  python3 gaps_tasks.py --masks /srv/prune/out/gaps/masks --models native,spec_math,spec_code,rand_s0 --gsm8k 250 --humaneval 164

Results: out/gaps/tasks.jsonl (tasks.py's JSON line per run), per-problem files in out/gaps/per_problem/.
"""
import argparse
import json
import os
import subprocess
import threading
import time
import urllib.request

B, M, OUT = '/srv/prune/bin', '/srv/prune/models', '/srv/prune/out/gaps'
LL = '/srv/prune/src/llama.cpp/build/bin'
PY = '/srv/venv/bin/python'
ENV = {**os.environ, 'GGML_CUDA_DISABLE_FUSION': '1'}
lock = threading.Lock()


def log(msg):
    with lock:
        with open(f'{OUT}/tasks_run.log', 'a') as f:
            f.write(f'{time.strftime("%H:%M:%S", time.gmtime())} {msg}\n')


def pidfile(name, pid):
    open(f'/srv/prune/pids/gaps_{name}.pid', 'w').write(str(pid))


def unpid(name):
    p = f'/srv/prune/pids/gaps_{name}.pid'
    if os.path.exists(p):
        os.remove(p)


def job(model_name, path, test, n, gpu, port):
    lf = f'{OUT}/logs/server_{model_name}_{test}.log'
    srv = subprocess.Popen(f'{LL}/llama-server --load-mode none -t 8 -m {path} --jinja -ngl 99 -fa on -c 49152 -np 12 '
                           f'--port {port} --host 127.0.0.1', shell=True, stdout=open(lf, 'a'), stderr=subprocess.STDOUT,
                           env={**ENV, 'CUDA_VISIBLE_DEVICES': str(gpu)}, start_new_session=True)
    pidfile(f'srv_{model_name}_{test}', srv.pid)
    try:
        for _ in range(300):
            try:
                urllib.request.urlopen(f'http://127.0.0.1:{port}/health', timeout=3)
                break
            except Exception:
                time.sleep(2)
        out = f'{OUT}/logs/tasks_{model_name}_{test}.out'
        p = subprocess.Popen(f'{PY} {B}/tasks.py --url http://127.0.0.1:{port} --test {test} --n {n} --version gaps-{model_name} '
                             f'--tests /srv/prune/data/texts/tests --out {OUT}', shell=True, stdout=open(out, 'w'),
                             stderr=open(f'{OUT}/logs/tasks_{model_name}_{test}.log', 'a'), start_new_session=True)
        pidfile(f'tasks_{model_name}_{test}', p.pid)
        rc = p.wait()
        unpid(f'tasks_{model_name}_{test}')
        lines = [x for x in open(out).read().splitlines() if x.strip().startswith('{')]
        r = {'model': model_name, 'test': test, 'rc': rc, **(json.loads(lines[-1]) if lines else {})}
        with lock:
            with open(f'{OUT}/tasks.jsonl', 'a') as f:
                f.write(json.dumps(r) + '\n')
        log(f'{model_name} {test} rc={rc} score={r.get("score")}')
    finally:
        os.killpg(srv.pid, 15)
        srv.wait()
        unpid(f'srv_{model_name}_{test}')


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--masks', default=f'{OUT}/masks')
    ap.add_argument('--models', default='native,spec_math,spec_code,rand_s0')
    ap.add_argument('--gsm8k', type=int, default=250)
    ap.add_argument('--humaneval', type=int, default=164)
    a = ap.parse_args()
    os.makedirs(f'{OUT}/logs', exist_ok=True)
    names = a.models.split(',')
    paths = {}
    bts = []
    for nm in names:
        if nm == 'native':
            paths[nm] = f'{M}/native.gguf'
            continue
        paths[nm] = f'{M}/gaps_task_{nm}.gguf'

        def b(nm=nm):
            if not os.path.exists(paths[nm]):
                pidfile(f'tbuild_{nm}', os.getpid())
                rc = subprocess.call(f'{PY} {B}/slicer.py --src {M}/native.gguf --keep {a.masks}/{nm}.json --mode mask '
                                     f'--out {paths[nm]}.part > {OUT}/logs/tbuild_{nm}.log 2>&1', shell=True)
                unpid(f'tbuild_{nm}')
                if rc == 0:
                    os.replace(paths[nm] + '.part', paths[nm])
                log(f'build {nm} rc={rc}')
        bts.append(threading.Thread(target=b))
        bts[-1].start()
    for t in bts:
        t.join()
    jobs = [(nm, t, n) for nm in names for t, n in (('gsm8k', a.gsm8k), ('humaneval', a.humaneval)) if n and os.path.exists(paths[nm])]
    ts = [threading.Thread(target=job, args=(nm, paths[nm], t, n, i % 8, 8300 + i)) for i, (nm, t, n) in enumerate(jobs)]
    for t in ts:
        t.start()
    for t in ts:
        t.join()
    for nm in names:
        if nm != 'native' and os.path.exists(paths[nm]):
            os.remove(paths[nm])
    open(f'{OUT}/tasks_finished', 'w').write(time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()))
    log('finished')


if __name__ == '__main__':
    main()