File size: 7,133 Bytes
688378c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Квантование весов Audit (Whisper base) в int8.

Снижает веса model.bin с ~145 МБ (fp16) до ~73 МБ (int8 + scales),
 алгоритм копирует точное квантование CTranslate2
 (python/ctranslate2/specs/model_spec.py, _quantize):

- для каждого веса X/weight (Linear/Conv1D/Embeddings):
    value = fp32
    если 3D (conv): reshape(out, in*k)
    amax = max(|value|, axis=1)          # на выходных каналах
    amax[amax == 0] = 127
    amax = max(amax, 127 / finfo(float32).max)
    scale = 127 / amax                   # float32, shape [out]
    value = rint(value * scale)          -> int8
- переменная X/weight_scale добавляется рядом с весом.

Формат model.bin (CTranslate2):
    uint32 version; string spec; uint32 revision; uint32 num_variables
    для каждой переменной: string name; uint8 rank; uint32[rank] dims;
                              uint8 dtype_id; uint32 num_bytes; raw data
    uint32 num_aliases; (string alias, string target)*

Использование:
    python scripts/quantize_int8.py [--model model] [--output model.int8]
"""

from __future__ import annotations

import argparse
import struct
import sys
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent

DTYPE_NAMES = ("float32", "int8", "int16", "int32", "float16", "bfloat16")
DTYPE_IDS = {name: i for i, name in enumerate(DTYPE_NAMES)}
ITEM_SIZE = {"float32": 4, "int8": 1, "int16": 2, "int32": 4, "float16": 2, "bfloat16": 2}


def read_string(buf: bytes, pos: int) -> tuple[str, int]:
    slen = struct.unpack_from("<H", buf, pos)[0]
    pos += 2
    raw = buf[pos:pos + slen - 1]
    pos += slen
    return raw.decode("utf-8"), pos


def write_string(out, string: str) -> None:
    raw = string.encode("utf-8")
    out.write(struct.pack("<H", len(raw) + 1))
    out.write(raw)
    out.write(struct.pack("<B", 0))


def quantize_weight(arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """int8 квантование веса (копия логики model_spec.py)."""
    value = arr.astype(np.float32)
    old_shape = None
    if len(value.shape) == 3:
        old_shape = value.shape
        value = value.reshape(value.shape[0], -1)
    amax = np.amax(np.absolute(value), axis=1)
    amax = amax.copy()
    amax[amax == 0] = 127.0
    amax = np.maximum(amax, np.float32(127) / np.finfo(np.float32).max)
    scale = (127.0 / amax).astype(np.float32)
    value = value * np.expand_dims(scale, 1)
    value = np.rint(value)
    value = value.astype(np.int8)
    if old_shape is not None:
        value = value.reshape(old_shape)
    return value, scale


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description="int8-квантование весов Audit")
    ap.add_argument("--model", default=str(ROOT / "model"))
    ap.add_argument("--output", default=None, help="выходной каталог (по умолчанию model.int8)")
    args = ap.parse_args(argv)

    model_dir = Path(args.model)
    model_bin = model_dir / "model.bin"
    if not model_bin.exists():
        print("model.bin не найден — сначала scripts/build_model.py")
        return 1

    out_dir = Path(args.output) if args.output else model_dir
    out_dir.mkdir(parents=True, exist_ok=True)

    data = model_bin.read_bytes()
    pos = 0

    version = struct.unpack_from("<I", data, pos)[0]
    pos += 4
    spec, pos = read_string(data, pos)
    revision = struct.unpack_from("<I", data, pos)[0]
    pos += 4
    num_variables = struct.unpack_from("<I", data, pos)[0]
    pos += 4

    variables: list[dict] = []
    for _ in range(num_variables):
        name, pos = read_string(data, pos)
        rank = data[pos]
        pos += 1
        dims = struct.unpack_from("<%dI" % rank, data, pos)
        pos += 4 * rank
        dtype_id = data[pos]
        pos += 1
        num_bytes = struct.unpack_from("<I", data, pos)[0]
        pos += 4
        variables.append(
            {
                "name": name,
                "dims": dims,
                "dtype": DTYPE_NAMES[dtype_id],
                "offset": pos,
                "num_bytes": num_bytes,
            }
        )
        pos += num_bytes

    num_aliases = struct.unpack_from("<I", data, pos)[0]
    pos += 4
    aliases: list[tuple[str, str]] = []
    for _ in range(num_aliases):
        alias, pos = read_string(data, pos)
        target, pos = read_string(data, pos)
        aliases.append((alias, target))

    print(f"Модель: {spec} rev{revision}, {len(variables)} переменных, {len(aliases)} alias")

    out_path = out_dir / "model.bin"
    total_in = 0
    total_out = 0
    with open(out_path, "wb") as out:
        out.write(struct.pack("<I", version))
        write_string(out, spec)
        out.write(struct.pack("<I", revision))

        new_variables: list[tuple[str, tuple, str, bytes]] = []
        for var in variables:
            if var["name"].endswith("weight") and var["dtype"] == "float16":
                arr = np.frombuffer(data, dtype=np.float16, count=var["num_bytes"] // 2, offset=var["offset"])
                arr = arr.reshape(var["dims"])
                total_in += var["num_bytes"]
                q, scale = quantize_weight(arr)
                q_bytes = q.tobytes()
                scale_bytes = scale.tobytes()
                new_variables.append((var["name"], var["dims"], "int8", q_bytes))
                new_variables.append((var["name"] + "_scale", (scale.shape[0],), "float32", scale_bytes))
                total_out += len(q_bytes) + len(scale_bytes)
            else:
                raw = bytes(data[var["offset"]:var["offset"] + var["num_bytes"]])
                new_variables.append((var["name"], var["dims"], var["dtype"], raw))
                total_out += len(raw)

        out.write(struct.pack("<I", len(new_variables)))
        for name, dims, dtype, raw in new_variables:
            write_string(out, name)
            out.write(struct.pack("<B", len(dims)))
            for dim in dims:
                out.write(struct.pack("<I", dim))
            out.write(struct.pack("<B", DTYPE_IDS[dtype]))
            out.write(struct.pack("<I", len(raw)))
            out.write(raw)

        out.write(struct.pack("<I", len(aliases)))
        for alias, target in aliases:
            write_string(out, alias)
            write_string(out, target)

    # Копируем остальные файлы модели.
    for f in model_dir.iterdir():
        if f.name != "model.bin" and f.is_file():
            target = out_dir / f.name
            if not target.exists():
                target.write_bytes(f.read_bytes())

    print(f"Веса: {total_in / 1e6:.1f} МБ -> {total_out / 1e6:.1f} МБ (int8)")
    print(f"Модель сохранена: {out_path} ({out_path.stat().st_size / 1e6:.1f} МБ)")
    print("Проверка: faster-whisper с compute_type=int8 + транскрибация примера")
    return 0


if __name__ == "__main__":
    sys.exit(main())