Audit / quantize_int8.py
openmodelai's picture
Upload 11 files
688378c verified
Raw History Blame Contribute Delete
7.13 kB
"""Квантование весов 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())