Skip to content

Commit 77c5d15

Browse files
lapid92reuvenp
authored andcommitted
Replace activation quantizers with identity only when nb>8 and using fakely quant onnx exporter (#1470)
1 parent a6593bd commit 77c5d15

1 file changed

Lines changed: 19 additions & 17 deletions

File tree

model_compression_toolkit/exporter/model_exporter/pytorch/fakely_quant_onnx_pytorch_exporter.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -73,23 +73,25 @@ def export(self, output_names=None) -> None:
7373
Returns:
7474
Fake-quant PyTorch model.
7575
"""
76-
# List all activation quantization holders with num_bits>8 and replace them with Identity, because
77-
# ONNX doesn't support quantization of more than 8 bits for torch.fake_quantize_per_tensor_affine.
78-
act_holder_list = [n for n, m in self.model.named_modules()
79-
if isinstance(m, PytorchActivationQuantizationHolder) and
80-
m.activation_holder_quantizer.num_bits > 8]
81-
for act_holder in act_holder_list: # pragma: no cover
82-
obj = self.model
83-
attrs = act_holder.split(".")
84-
for a in attrs[:-1]:
85-
obj = getattr(obj, a)
86-
if hasattr(obj, attrs[-1]):
87-
delattr(obj, attrs[-1])
88-
setattr(obj, attrs[-1], torch.nn.Identity())
89-
else:
90-
Logger.info(f"During removal of activation quantization of a quantizer (with bits > 8) in ONNX FQ "
91-
f"export, deletion of activation holder '{act_holder}' failed — could not locate one or"
92-
f"more intermediate attributes in the path.")
76+
# When exporting using Fakely Quant Quantization Format list all activation quantization holders with
77+
# num_bits>8 and replace them with Identity, because ONNX doesn't support quantization of more than 8 bits
78+
# for torch.fake_quantize_per_tensor_affine.
79+
if not self._use_onnx_custom_quantizer_ops:
80+
act_holder_list = [n for n, m in self.model.named_modules()
81+
if isinstance(m, PytorchActivationQuantizationHolder) and
82+
m.activation_holder_quantizer.num_bits > 8]
83+
for act_holder in act_holder_list: # pragma: no cover
84+
obj = self.model
85+
attrs = act_holder.split(".")
86+
for a in attrs[:-1]:
87+
obj = getattr(obj, a)
88+
if hasattr(obj, attrs[-1]):
89+
delattr(obj, attrs[-1])
90+
setattr(obj, attrs[-1], torch.nn.Identity())
91+
else:
92+
Logger.info(f"During removal of activation quantization of a quantizer (with bits > 8) in ONNX"
93+
f"FQ export, deletion of activation holder '{act_holder}' failed — could not locate"
94+
f"one or more intermediate attributes in the path.")
9395

9496
for layer in self.model.children():
9597
self.is_layer_exportable_fn(layer)

0 commit comments

Comments
 (0)