sava-telephony / scripts /quantize.py
matthiastl's picture
SAVA fine-tuned for phone lines: PyTorch, ONNX and 8-bit ONNX, with tests and scripts
547c405
Raw History Blame Contribute Delete
2.37 kB
"""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()