Skip to content

[BE] Introduce linear_forward_int8 #432

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

Merged
merged 1 commit into from
Apr 24, 2024
Merged
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
37 changes: 18 additions & 19 deletions quantize.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,23 @@ def replace_linear_weight_only_int8_per_channel(
child, device, node_type, groupsize
)

def linear_forward_int8(x, weight, scales):
n_groups = scales.numel() // scales.shape[0]
# need a formulation / custom op for good performance
# on eager, CUDA compiled, CPU compiled and ET exported

# for now, we special-case channel-wise, because we know how to make that fast (but does not work for groupwise)
if n_groups == 1:
return F.linear(x, weight.to(dtype=x.dtype)) * scales

return F.linear(
x,
(
weight.to(dtype=x.dtype).view(weight.shape[0], n_groups, -1)
* scales.view(weight.shape[0], n_groups, -1)
).view(weight.shape[0], -1),
)


class WeightOnlyInt8QuantHandler(QuantHandler):
def __init__(
Expand Down Expand Up @@ -471,25 +488,7 @@ def __init__(
)

def forward(self, input: torch.Tensor) -> torch.Tensor:
scales = self.scales
weight = self.weight
scales = scales.view(scales.shape[0], -1)
no_groups = scales.shape[1]

# need a formulation / custom op for good performance
# on eager, CUDA compiled, CPU compiled and ET exported

# for now, we special-case channel-wise, because we know how to make that fast (but does not work for groupwise)
if scales.shape[1] == 1:
return F.linear(input, weight.to(dtype=input.dtype)) * self.scales
else:
return F.linear(
input,
(
weight.to(dtype=input.dtype).view(weight.shape[0], no_groups, -1)
* scales.view(weight.shape[0], no_groups, -1)
).view(weight.shape[0], -1),
)
return linear_forward_int8(input, self.weight, self.scales)


#########################################################################
Expand Down