Skip to content

Commit de182fb

Browse files
authored
Add ability to export Positional weights in fakely quant onnx (#1461)
* Add ability to export Positional weights in fakely quant onnx
1 parent a3af1c7 commit de182fb

1 file changed

Lines changed: 22 additions & 3 deletions

File tree

model_compression_toolkit/exporter/model_exporter/pytorch/base_pytorch_exporter.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import torch.nn
1919

2020
from mct_quantizers import PytorchQuantizationWrapper
21-
from mct_quantizers.common.constants import LAYER, WEIGHTS_QUANTIZERS
21+
from mct_quantizers.common.constants import LAYER, WEIGHTS_QUANTIZERS, QUANTIZED_POSITIONAL_WEIGHT
2222
from model_compression_toolkit.logger import Logger
2323
from model_compression_toolkit.exporter.model_exporter.fw_agonstic.exporter import Exporter
2424

@@ -73,8 +73,27 @@ def _set_quantized_weights_in_wrapper(layer:PytorchQuantizationWrapper):
7373
for name in layer.weights_quantizers.keys():
7474
quantized_weight = torch.nn.Parameter(layer.get_quantized_weights()[name]).detach()
7575
linear_layer = getattr(layer, LAYER)
76-
delattr(linear_layer, name)
77-
setattr(linear_layer, name, torch.nn.Parameter(quantized_weight))
76+
77+
# If the name is a string, we assume it's a named attribute of the linear layer
78+
if isinstance(name, str):
79+
# Remove the existing attribute from the linear layer
80+
delattr(linear_layer, name)
81+
# Replace it with the quantized version as a new parameter
82+
setattr(linear_layer, name, torch.nn.Parameter(quantized_weight))
83+
else:
84+
# If the name is not a string, it must be an integer representing a positional weight
85+
assert isinstance(name, int)
86+
attr_name = f'{QUANTIZED_POSITIONAL_WEIGHT}_{name}'
87+
88+
# Note: This naming scheme is used to mimic the behavior expected in
89+
# the PytorchQuantizationWrapper's forward method, which looks for attributes
90+
# like 'quantized_pos_weight_0', 'quantized_pos_weight_1', etc.
91+
92+
if hasattr(layer, attr_name):
93+
delattr(layer, attr_name)
94+
95+
# Add the quantized weight as a new attribute directly on the parent layer
96+
setattr(layer, attr_name, quantized_weight)
7897

7998
# Clear the weights quantizers dictionary
8099
layer.weights_quantizers = {}

0 commit comments

Comments
 (0)