"""Квантование весов 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(" None: raw = string.encode("utf-8") out.write(struct.pack(" 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(" {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())