File size: 6,509 Bytes
7b12d2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1fe1b7
 
7b12d2f
 
 
d1fe1b7
7b12d2f
 
 
 
 
 
 
 
694d40b
7b12d2f
 
 
 
 
 
 
 
 
 
694d40b
 
 
 
7b12d2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1fe1b7
 
 
 
694d40b
 
 
7b12d2f
 
 
 
 
 
 
 
d1fe1b7
7b12d2f
 
 
 
 
 
 
 
 
d1fe1b7
7b12d2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1fe1b7
 
7b12d2f
 
 
 
9d41255
7b12d2f
 
 
 
 
 
9d41255
7b12d2f
 
 
 
 
 
9d41255
7b12d2f
 
 
 
 
 
 
 
 
 
 
 
 
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python3

from __future__ import annotations

from pathlib import Path
from urllib import request
import os
import shlex
import subprocess
import sys
from typing import Any, Sequence
import logging
import json
import argparse

curdir = Path(os.path.dirname(__file__))

logger = logging.getLogger("bench")

MODEL_DIR = curdir / "bench-TriLMs-models"
LLAMA_CPP_PATH = curdir / "."
MODEL_SIZES = ("1.5", "2.4", "3.9")
ALL_TYPES = ("TQ1_0", "TQ2_0", "Q4_K_M", "Q8_0", "F16", "BF16")
GPU_TYPES = ("TQ2_0", "Q4_K_M", "Q8_0", "F16")


def gather_models(sizes: Sequence[str] = MODEL_SIZES):
    logger.info("Gathering models")
    if not MODEL_DIR.exists():
        MODEL_DIR.mkdir(parents=True, exist_ok=True)
    for size in sizes:
        filename = f"TriLM_{size}B_Unpacked-TQ1_0-F16.gguf"
        file = MODEL_DIR / filename
        if not file.exists():
            url = (
                f"https://huggingface.co/compilade/quant-tests/resolve/main/{filename}"
            )
            logger.info(f"Fetching {filename} from {url}")
            request.urlretrieve(url, file)


def build_llama_cpp(options: Sequence[str]):
    logger.info("Building llama.cpp")
    os.chdir(LLAMA_CPP_PATH)
    builddir = LLAMA_CPP_PATH / "build"
    if builddir.exists():
        logger.info("Removing %s", builddir)
        os.system("rm -rf build")
    builddir.mkdir()
    os.chdir(builddir)
    os.system(shlex.join(("cmake", "..", *options)))
    os.system(f"make -j{os.cpu_count()} llama-bench llama-quantize test-backend-ops")


def quantize(types: Sequence[str] = ALL_TYPES, sizes: Sequence[str] = MODEL_SIZES):
    logger.info("Make all model types we'll test")
    for size in sizes:
        source = MODEL_DIR / f"TriLM_{size}B_Unpacked-TQ1_0-F16.gguf"
        for ty in types:
            target = MODEL_DIR / f"TriLM_{size}B_Unpacked-{ty}.gguf"
            if not target.exists() or target.is_file() and target.stat().st_size == 0:
                command = shlex.join(
                    (
                        str(LLAMA_CPP_PATH / "build" / "bin" / "llama-quantize"),
                        "--allow-requantize",
                        str(source),
                        str(target),
                        ty,
                    )
                )
                logger.info("Running: %s", command)
                ret = os.system(command)
                if ret != 0:
                    logger.error("Failed to quantize to %s", target)
                # Should it still continue?


def llama_bench(
    repetitions: int = 5,
    types: Sequence[str] = ALL_TYPES,
    sizes: Sequence[str] = MODEL_SIZES,
) -> list[dict[str, Any]]:
    logger.info("Test each model one by one for different numbers of threads")

    threads = [2**i for i in range(5) if 2**i <= os.cpu_count()]
    logger.info(f"Numbers of threads to be tested: {threads}")

    out = []

    for size in sizes:
        for ty in types:
            for th in threads:
                model_path = MODEL_DIR / f"TriLM_{size}B_Unpacked-{ty}.gguf"
                args = [
                    "-v",
                    "-m",
                    str(model_path),
                    "-t",
                    str(th),
                    "-r",
                    str(repetitions),
                    "-p",
                    "512",
                    "-n",
                    "128",
                    "-o",
                    "json",
                ]
                command = [str(LLAMA_CPP_PATH / "build" / "bin" / "llama-bench")] + args
                logger.info("Running: %s", " ".join(command))
                result = subprocess.run(command, capture_output=True)
                logger.debug(result.stderr.decode())
                if result.returncode != 0:
                    logger.error("Failed to run %s", " ".join(command))
                    break;

                new_output = json.loads(result.stdout)
                logger.info(json.dumps(new_output, indent=4))
                out.extend(new_output)
    return out


def test_backend_perf() -> str:
    logger.info("Test MUL_MAT performance")
    result = subprocess.run(
        [
            str(LLAMA_CPP_PATH / "build" / "bin" / "test-backend-ops"),
            "perf",
            "-o",
            "MUL_MAT",
        ],
        capture_output=True,
    )
    logger.debug(result.stdout.decode())
    return result.stdout.decode(encoding="utf-8")


def parse_args(args: Sequence[str]):
    parser = argparse.ArgumentParser(
        prog=args[0], description="Benchmark ternary models"
    )
    parser.add_argument("--gpu", action="store_true", help="Run benchmarks on GPU")
    parser.add_argument("--cpu", action="store_true", help="Run benchmarks on CPU")
    parser.add_argument(
        "--llama-cpp-path",
        type=Path,
        default=LLAMA_CPP_PATH,
        help="Path to a llama.cpp checkout",
    )
    parser.add_argument(
        "--model-dir",
        type=Path,
        default=MODEL_DIR,
        help="Where the tested models will be stored",
    )
    parser.add_argument(
        "--repetitions",
        type=int,
        default=5,
        required=False,
        help="How many repetitions are run for each test",
    )
    parser.add_argument(
        "--out",
        type=Path,
        default=Path(os.path.curdir) / "result.json",
        help="Path of the benchmark results to be written",
    )
    return parser.parse_args(args[1:])


if __name__ == "__main__":
    args = parse_args(sys.argv)

    logging.basicConfig(level=logging.DEBUG)

    LLAMA_CPP_PATH = args.llama_cpp_path
    MODEL_DIR = args.model_dir

    results = []
    mulmat_perf = []
    repetitions: int = args.repetitions

    if args.cpu:
        gather_models()
        build_llama_cpp(["-DGGML_NATIVE=ON", "-DGGML_CPU=ON"])
        quantize()
        mulmat_perf.append(test_backend_perf())
        results.extend(llama_bench(repetitions=repetitions))

    if args.gpu:
        gather_models()
        build_llama_cpp(["-DGGML_NATIVE=ON", "-DGGML_CUDA=ON", "-DGGML_CUDA_F16=ON"])
        quantize()
        mulmat_perf.append(test_backend_perf())
        results.extend(llama_bench(repetitions=repetitions, types=GPU_TYPES))

    cpuinfo = subprocess.run(["lscpu"], capture_output=True).stdout.decode(
        encoding="utf-8"
    )

    final_result = {
        "cpuinfo": cpuinfo,
        "mulmat_perf": mulmat_perf,
        "results": results,
    }
    with open(args.out, "w") as f:
        json.dump(results, f, indent=4)