File size: 2,369 Bytes
547c405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Make smaller versions of the exported SAVA graph.

Only the learned linear layers are quantized (the export names them ``linear:<module path>``).
The mel front end's DFT and filterbank, the attention products and the state-space recurrence stay
in full precision: quantizing the front end alone destroys the model's output.

    int8   8-bit weights, activations quantized to 8 bits at run time (MatMulInteger)
    q8     8-bit weights in blocks of 32, float activations (MatMulNBits)
    q4     4-bit weights in blocks of 32, float activations

MatMulNBits with ``accuracy_level=4`` is left out: with onnxruntime 1.32 on Apple Silicon it made
the model answer "no speech" on every frame.
"""

from __future__ import annotations

import argparse
import math
from pathlib import Path

import onnx
from onnxruntime.quantization import quantize_dynamic
from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer

MIN_WEIGHTS = 100_000  # smaller layers (the readouts, the speech embedding) save nothing


def layers_to_quantize(model: onnx.ModelProto) -> list[str]:
    sizes = {i.name: math.prod(i.dims) for i in model.graph.initializer}
    return [
        node.name
        for node in model.graph.node
        if node.name.startswith("linear:") and sizes[node.input[1]] >= MIN_WEIGHTS
    ]


def weight_only(source: Path, target: Path, layers: list[str], bits: int) -> None:
    quantizer = MatMulNBitsQuantizer(
        onnx.load(source), bits=bits, block_size=32, is_symmetric=True, nodes_to_include=layers
    )
    quantizer.process()
    onnx.save(quantizer.model.model, target)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--source", type=Path, default=Path("build/sava.onnx"))
    args = parser.parse_args()
    stem = args.source.with_suffix("")
    layers = layers_to_quantize(onnx.load(args.source))
    print(f"quantizing {len(layers)} linear layers")

    quantize_dynamic(args.source, f"{stem}.int8.onnx", nodes_to_quantize=layers)
    weight_only(args.source, Path(f"{stem}.q8.onnx"), layers, bits=8)
    weight_only(args.source, Path(f"{stem}.q4.onnx"), layers, bits=4)
    for path in sorted(args.source.parent.glob(f"{args.source.stem}*.onnx")):
        print(f"{path.stat().st_size / 1e6:7.1f} MB  {path}")


if __name__ == "__main__":
    main()