python
import torch
import torch.nn as nn
# 1. PyTorch の組み込み:テンソルを 8 ビットの整数で表す
# torch.quantize_per_tensor(input, scale, zero_point, dtype)
# dtype は torch.quint8(0〜255)・torch.qint8(-128〜127)・torch.qint32 のどれか
x = torch.tensor([-1.15, -0.5, 0.13, 0.55, 1.07, 1.52, 2.55])
q = torch.quantize_per_tensor(x, scale=0.02, zero_point=128, dtype=torch.quint8)
print(q.int_repr()) # 整数の値
print(q.dequantize()) # 逆量子化した値(元の値に近い)
# 2. 式どおりの量子化(非対称、b ビット)。範囲は最小値・最大値から決める
def quantize_asym(x, b=8):
qmax = 2 ** b - 1
lo, hi = x.min().clamp(max=0), x.max().clamp(min=0) # 0 が範囲に入るようにする
s = (hi - lo).clamp(min=1e-8) / qmax # スケール
z = torch.round(-lo / s) # ゼロ点
x_int = torch.clamp(torch.round(x / s) + z, 0, qmax)
return x_int, s, z
def dequantize(x_int, s, z):
return s * (x_int - z)
# 3. 重みを出力チャネル(行)ごとに対称量子化する(absmax)
def quantize_weight_per_channel(w, b=8):
qmax = 2 ** (b - 1) - 1 # 8 ビットなら 127
s = w.abs().amax(dim=1, keepdim=True).clamp(min=1e-8) / qmax # 行ごとのスケール
w_int = torch.clamp(torch.round(w / s), -qmax, qmax)
return w_int, s
# 4. 量子化を考慮した学習(QAT)用の、模擬量子化とストレートスルー推定(STE)
class FakeQuantSTE(torch.autograd.Function):
@staticmethod
def forward(ctx, x, s, qmin, qmax):
ctx.save_for_backward(x)
ctx.lo, ctx.hi = qmin * s, qmax * s
return torch.clamp(torch.round(x / s), qmin, qmax) * s # 量子化してすぐ戻す
@staticmethod
def backward(ctx, grad_out):
(x,) = ctx.saved_tensors
inside = (x >= ctx.lo) & (x <= ctx.hi) # 範囲の中だけ勾配を通す
return grad_out * inside, None, None, None
class QATLinear(nn.Linear):
"""重みを b ビットに模擬量子化してから計算する線形層(重み自体は浮動小数点のまま更新する)"""
def __init__(self, in_features, out_features, b=4):
super().__init__(in_features, out_features)
self.qmax = 2 ** (b - 1) - 1
def forward(self, x):
s = self.weight.detach().abs().max().clamp(min=1e-8) / self.qmax # テンソルごとのスケール
w_q = FakeQuantSTE.apply(self.weight, s, -self.qmax, self.qmax)
return nn.functional.linear(x, w_q, self.bias)
x_int, s, z = quantize_asym(x, b=3)
print(x_int, dequantize(x_int, s, z))
layer = QATLinear(16, 8, b=4)
layer.train()
out = layer(torch.randn(2, 16))
out.sum().backward() # STE のおかげで重みに勾配が流れる
print(layer.weight.grad.shape)