受到“Transformer神经机器语言翻译模型的高效8位量化”的启发,我决定遵循这篇论文的警告。然而,我对在量化过程中设置偏移量变量感到困惑。
INPUT : A (tensor of FP32, [1, 4, 1024, 256])
# Quantization
offset = torch.empty(A.shape)
offset = torch.zeros_like(offset)
scale = 255 / (torch.max(A) - torch.min(A))
A_int8 = (A - offset) * scale
# Probability Distribution
P = norm.pdf(A, torch.mean(A, dim=[2, 3]), torch.std(A, dim = [2,3]))
Q = norm.pdf(A_int8, torch.mean(A_int8, dim=[2, 3]), torch.std(A_int8, dim = [2,3]))
P = torch.from_numpy(P)
Q = torch.from_numpy(Q)
# KLD
kld = (P * (P / Q).log()).sum()
print(kld)
# After this, I'm going to apply self-attention operation.
# B_int8 = A_int8.clone()
# AB = A_int8.matmul(B_int8.transpose(-1, -2))我现在得到了正的kld值,但我不确定我是不是通过正确的方式做到了这一点。任何帮助或建议都是非常感谢的。
发布于 2021-10-23 10:09:05
KL散度可以计算为P中每个事件的概率的负和乘以Q中事件的概率的对数除以P中的事件的概率。
KL(P || Q) = – sum x in X P(x) * log(Q(x) / P(x))这等于P中的每个事件的概率的正和乘以P中的事件的概率的对数除以Q中的事件的概率。
KL(P || Q) = sum x in X P(x) * log(P(x) / Q(x))“K-L散度仅在P和Q都为1时定义,并且如果对于任何i,Q(i) >0,使得P(i) >0,则定义K-L散度。”
https://stackoverflow.com/questions/69686024
复制相似问题