Skip to content

Instantly share code, notes, and snippets.

@ntakouris
Created September 21, 2020 09:57
Show Gist options
  • Save ntakouris/c5b3df7fef5d0e762f74538bc4dd6d17 to your computer and use it in GitHub Desktop.
Save ntakouris/c5b3df7fef5d0e762f74538bc4dd6d17 to your computer and use it in GitHub Desktop.
def uniform_q(x, bits=32):
if bits == 32:
return x
n = float(2 ** bits)
out = np.clip(np.round(x * n - 0.5), 0, n-1) / (n-1)
return out
def quantize_weights(x, bits=32):
if bits == 32:
return x
# preprocess weight before quantization
weight = np.tanh(x)
weight = (weight / (2 * np.max(np.abs(weight)))) + 0.5
# quantize
weight_q = 2 * uniform_q(weight, bits=bits) - 1 # w_q equation (1) <--- see paper
return weight_q
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment