|
18 | 18 | import torch.nn |
19 | 19 |
|
20 | 20 | 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 |
22 | 22 | from model_compression_toolkit.logger import Logger |
23 | 23 | from model_compression_toolkit.exporter.model_exporter.fw_agonstic.exporter import Exporter |
24 | 24 |
|
@@ -73,8 +73,27 @@ def _set_quantized_weights_in_wrapper(layer:PytorchQuantizationWrapper): |
73 | 73 | for name in layer.weights_quantizers.keys(): |
74 | 74 | quantized_weight = torch.nn.Parameter(layer.get_quantized_weights()[name]).detach() |
75 | 75 | 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) |
78 | 97 |
|
79 | 98 | # Clear the weights quantizers dictionary |
80 | 99 | layer.weights_quantizers = {} |
|
0 commit comments