Download runtime/inference/quantization.py from hscr/luxfer: direct link, hf CLI and curl.
- Browser
- Download file 1.21 kB
-
https://huggingface.co/hscr/luxfer/resolve/main/runtime/inference/quantization.py
- Command line
-
hf download hf://hscr/luxfer/runtime/inference/quantization.py
-
curl -L -o quantization.py https://huggingface.co/hscr/luxfer/resolve/main/runtime/inference/quantization.py
1.21 kB
| """Streaming dynamic int8 linear conversion for ARM CPUs; experimental.""" | |
| import torch | |
| from torch import nn | |
| from torch.ao.quantization import quantize_dynamic | |
| class DynamicInt8Linear(nn.Module): | |
| def __init__(self,linear): | |
| super().__init__() | |
| # One matrix converted at a time: no simultaneous full FP32 checkpoint. | |
| layer=nn.Linear(linear.in_features,linear.out_features,bias=linear.bias is not None) | |
| with torch.no_grad(): | |
| layer.weight.copy_(linear.weight.float()) | |
| if linear.bias is not None: layer.bias.copy_(linear.bias.float()) | |
| self.quantized=quantize_dynamic(nn.Sequential(layer.eval()),{nn.Linear},dtype=torch.qint8)[0] | |
| def forward(self,x): | |
| return self.quantized(x.float()).to(x.dtype) | |
| def dynamic_int8(model): | |
| if model.training: raise ValueError('Dynamic int8 is inference only') | |
| if 'qnnpack' not in torch.backends.quantized.supported_engines: raise RuntimeError('qnnpack unavailable') | |
| torch.backends.quantized.engine='qnnpack' | |
| for name,child in list(model.named_children()): | |
| if isinstance(child,nn.Linear): setattr(model,name,DynamicInt8Linear(child)) | |
| else: dynamic_int8(child) | |
| return model | |