File size: 1,212 Bytes
7b6f2cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""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