Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

307 quantization #381

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions baler/modules/quantization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import torch
from torch import nn

class SteQuant(nn.Module):
def __init__(self, table_range=128, func=torch.round):
super(SteQuant, self).__init__()
assert(func is not None)
self.func = func
self.table_range = table_range

def hard_forward(self, x):
return self.func(x)

def soft_forward(self, x):
return x

def forward(self, x):
soft = self.soft_forward(x)
with torch.no_grad():
x_err = self.hard_forward(x) - soft
return torch.clamp(x_err + soft, -self.table_range, self.table_range-1)


class NoiseQuant(nn.Module):
def __init__(self, table_range=128, bin_size=1.0):
super(NoiseQuant, self).__init__()
self.table_range = table_range
half_bin = torch.tensor(bin_size / 2).to(torch.device("cuda"))
self.noise = uniform.Uniform(-half_bin, half_bin)

def forward(self, x):
if self.training:
x_quant = x + self.noise.sample(x.shape)
else:
x_quant = torch.floor(x + 0.5) # modified
return torch.clamp(x_quant, -self.table_range, self.table_range-1)
Loading