mct-nightly 1.8.0.27022023.post430__py3-none-any.whl → 1.8.0.27032023.post403__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {mct_nightly-1.8.0.27022023.post430.dist-info → mct_nightly-1.8.0.27032023.post403.dist-info}/METADATA +7 -7
- {mct_nightly-1.8.0.27022023.post430.dist-info → mct_nightly-1.8.0.27032023.post403.dist-info}/RECORD +65 -59
- {mct_nightly-1.8.0.27022023.post430.dist-info → mct_nightly-1.8.0.27032023.post403.dist-info}/WHEEL +1 -1
- model_compression_toolkit/__init__.py +9 -15
- model_compression_toolkit/core/common/logger.py +10 -2
- model_compression_toolkit/core/common/mixed_precision/search_methods/linear_programming.py +6 -1
- model_compression_toolkit/core/keras/quantization_facade.py +1 -1
- model_compression_toolkit/core/pytorch/constants.py +4 -0
- model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/multi_head_attention_decomposition.py +4 -10
- model_compression_toolkit/core/pytorch/graph_substitutions/substitutions/reshape_with_static_shapes.py +16 -2
- model_compression_toolkit/exporter/__init__.py +5 -0
- model_compression_toolkit/exporter/model_exporter/__init__.py +0 -3
- model_compression_toolkit/exporter/model_exporter/tflite/fakely_quant_tflite_exporter.py +1 -1
- model_compression_toolkit/exporter/model_wrapper/__init__.py +4 -8
- model_compression_toolkit/exporter/model_wrapper/keras/builder/fully_quantized_model_builder.py +45 -39
- model_compression_toolkit/exporter/model_wrapper/keras/builder/node_to_quantizer.py +39 -24
- model_compression_toolkit/exporter/model_wrapper/keras/validate_layer.py +50 -42
- model_compression_toolkit/exporter/model_wrapper/pytorch/builder/fully_quantized_model_builder.py +43 -36
- model_compression_toolkit/exporter/model_wrapper/pytorch/builder/node_to_quantizer.py +24 -5
- model_compression_toolkit/exporter/model_wrapper/pytorch/validate_layer.py +25 -18
- model_compression_toolkit/gptq/__init__.py +6 -0
- model_compression_toolkit/gptq/common/gptq_config.py +60 -106
- model_compression_toolkit/gptq/common/gptq_constants.py +0 -7
- model_compression_toolkit/gptq/common/gptq_training.py +28 -38
- model_compression_toolkit/gptq/keras/gptq_training.py +10 -28
- model_compression_toolkit/gptq/keras/graph_info.py +8 -33
- model_compression_toolkit/gptq/keras/quantization_facade.py +6 -12
- model_compression_toolkit/gptq/keras/quantizer/base_keras_gptq_quantizer.py +0 -1
- model_compression_toolkit/gptq/keras/quantizer/quantization_builder.py +2 -2
- model_compression_toolkit/gptq/keras/quantizer/regularization_factory.py +45 -0
- model_compression_toolkit/gptq/keras/quantizer/soft_rounding/soft_quantizer_reg.py +112 -0
- model_compression_toolkit/gptq/keras/quantizer/soft_rounding/symmetric_soft_quantizer.py +22 -128
- model_compression_toolkit/gptq/keras/quantizer/ste_rounding/symmetric_ste.py +11 -41
- model_compression_toolkit/gptq/pytorch/gptq_training.py +12 -4
- model_compression_toolkit/gptq/pytorch/graph_info.py +9 -6
- model_compression_toolkit/gptq/pytorch/quantization_facade.py +9 -22
- model_compression_toolkit/gptq/pytorch/quantizer/__init__.py +3 -1
- model_compression_toolkit/gptq/pytorch/quantizer/base_pytorch_gptq_quantizer.py +0 -20
- model_compression_toolkit/gptq/pytorch/quantizer/quant_utils.py +10 -1
- model_compression_toolkit/gptq/pytorch/quantizer/quantization_builder.py +2 -2
- model_compression_toolkit/gptq/pytorch/quantizer/regularization_factory.py +45 -0
- model_compression_toolkit/gptq/pytorch/quantizer/soft_rounding/__init__.py +14 -0
- model_compression_toolkit/gptq/pytorch/quantizer/soft_rounding/soft_quantizer_reg.py +115 -0
- model_compression_toolkit/gptq/pytorch/quantizer/soft_rounding/symmetric_soft_quantizer.py +236 -0
- model_compression_toolkit/gptq/pytorch/quantizer/soft_rounding/uniform_soft_quantizer.py +196 -0
- model_compression_toolkit/gptq/pytorch/quantizer/ste_rounding/symmetric_ste.py +9 -31
- model_compression_toolkit/qat/keras/quantizer/ste_rounding/symmetric_ste.py +30 -37
- model_compression_toolkit/qat/keras/quantizer/ste_rounding/uniform_ste.py +27 -36
- model_compression_toolkit/qat/pytorch/quantizer/ste_rounding/symmetric_ste.py +21 -21
- model_compression_toolkit/qat/pytorch/quantizer/ste_rounding/uniform_ste.py +25 -26
- model_compression_toolkit/quantizers_infrastructure/inferable_infrastructure/common/get_all_subclasses.py +1 -2
- model_compression_toolkit/quantizers_infrastructure/inferable_infrastructure/common/get_quantizers.py +1 -1
- model_compression_toolkit/quantizers_infrastructure/inferable_infrastructure/keras/quantize_wrapper.py +12 -0
- model_compression_toolkit/quantizers_infrastructure/inferable_infrastructure/keras/quantizers/__init__.py +4 -0
- model_compression_toolkit/quantizers_infrastructure/inferable_infrastructure/keras/quantizers/constants.py +1 -0
- model_compression_toolkit/quantizers_infrastructure/inferable_infrastructure/pytorch/quantize_wrapper.py +12 -0
- model_compression_toolkit/quantizers_infrastructure/inferable_infrastructure/pytorch/quantizers/__init__.py +6 -0
- model_compression_toolkit/quantizers_infrastructure/inferable_infrastructure/pytorch/quantizers/constants.py +3 -0
- model_compression_toolkit/quantizers_infrastructure/trainable_infrastructure/common/base_trainable_quantizer.py +53 -2
- model_compression_toolkit/quantizers_infrastructure/trainable_infrastructure/common/get_quantizers.py +2 -1
- model_compression_toolkit/quantizers_infrastructure/trainable_infrastructure/keras/base_keras_quantizer.py +22 -4
- model_compression_toolkit/quantizers_infrastructure/trainable_infrastructure/pytorch/base_pytorch_quantizer.py +24 -3
- model_compression_toolkit/gptq/common/gptq_quantizer_config.py +0 -93
- {mct_nightly-1.8.0.27022023.post430.dist-info → mct_nightly-1.8.0.27032023.post403.dist-info}/LICENSE.md +0 -0
- {mct_nightly-1.8.0.27022023.post430.dist-info → mct_nightly-1.8.0.27032023.post403.dist-info}/top_level.txt +0 -0
- /model_compression_toolkit/quantizers_infrastructure/inferable_infrastructure/{common → pytorch/quantizers/activation_inferable_quantizers}/activation_lut_pot_inferable_quantizer.py +0 -0
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
# ==============================================================================
|
|
15
15
|
from typing import Dict, List, Tuple
|
|
16
16
|
|
|
17
|
-
from model_compression_toolkit import GradientPTQConfigV2
|
|
17
|
+
from model_compression_toolkit.gptq import GradientPTQConfigV2
|
|
18
18
|
from model_compression_toolkit.core import common
|
|
19
19
|
from model_compression_toolkit.core.keras.default_framework_info import DEFAULT_KERAS_INFO
|
|
20
20
|
from model_compression_toolkit.exporter.model_wrapper.keras.builder.node_to_quantizer import \
|
|
@@ -61,7 +61,7 @@ def quantization_builder(n: common.BaseNode,
|
|
|
61
61
|
fw_info=DEFAULT_KERAS_INFO)
|
|
62
62
|
|
|
63
63
|
weights_quantizers.update({kernel_attribute: quantizer_class(get_trainable_quantizer_weights_config(n),
|
|
64
|
-
**gptq_config.
|
|
64
|
+
**gptq_config.gptq_quantizer_params_override)})
|
|
65
65
|
|
|
66
66
|
activation_quantizers = []
|
|
67
67
|
if n.is_activation_quantization_enabled():
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
from typing import Callable
|
|
16
|
+
|
|
17
|
+
from model_compression_toolkit.gptq import RoundingType, GradientPTQConfigV2, GradientPTQConfig
|
|
18
|
+
from model_compression_toolkit.gptq.keras.quantizer.soft_rounding.soft_quantizer_reg import \
|
|
19
|
+
SoftQuantizerRegularization
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def get_regularization(gptq_config: GradientPTQConfig, representative_data_gen: Callable) -> Callable:
|
|
23
|
+
"""
|
|
24
|
+
Returns a function that computes the regularization term for GPTQ training based on the given
|
|
25
|
+
rounding type in the GPTQ configuration.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
gptq_config: A GPTQ configuration.
|
|
29
|
+
representative_data_gen: Dataset used for the GPTQ training.
|
|
30
|
+
|
|
31
|
+
Returns: A function for computing the regularization. If there is no regularization function defined for the given
|
|
32
|
+
rounding type, then it returns a function that just returns 0.
|
|
33
|
+
|
|
34
|
+
"""
|
|
35
|
+
if gptq_config.rounding_type == RoundingType.SoftQuantizer:
|
|
36
|
+
# dry run on the representative dataset to count number of batches
|
|
37
|
+
num_batches = 0
|
|
38
|
+
for _ in representative_data_gen():
|
|
39
|
+
num_batches += 1
|
|
40
|
+
|
|
41
|
+
n_epochs = GradientPTQConfigV2.from_v1(n_ptq_iter=num_batches, config_v1=gptq_config).n_epochs if \
|
|
42
|
+
not type(gptq_config) == GradientPTQConfigV2 else gptq_config.n_epochs
|
|
43
|
+
return SoftQuantizerRegularization(total_gradient_steps=num_batches * n_epochs)
|
|
44
|
+
else:
|
|
45
|
+
return lambda m, e_reg: 0
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
from typing import List
|
|
16
|
+
|
|
17
|
+
import tensorflow as tf
|
|
18
|
+
from keras import Model
|
|
19
|
+
|
|
20
|
+
from model_compression_toolkit.core.keras.default_framework_info import DEFAULT_KERAS_INFO
|
|
21
|
+
from model_compression_toolkit.gptq.common.gptq_graph import get_kernel_attribute_name_for_gptq
|
|
22
|
+
from model_compression_toolkit.quantizers_infrastructure import KerasQuantizationWrapper
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class LinearTempDecay:
|
|
26
|
+
"""
|
|
27
|
+
Annealing process for the soft quantizer regularization temperature term.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, t_max: int, rel_start_decay: float = 0.2, start_b: int = 20, end_b: int = 2):
|
|
31
|
+
"""
|
|
32
|
+
Initializes a LinearTempDecay object.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
t_max: maximal time step.
|
|
36
|
+
rel_start_decay: Decay step size at the beginning of the process.
|
|
37
|
+
start_b: Starting value of the regularization term.
|
|
38
|
+
end_b: Target value of the regularization term.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
self.t_max = t_max
|
|
42
|
+
self.start_decay = rel_start_decay * t_max
|
|
43
|
+
self.start_b = start_b
|
|
44
|
+
self.end_b = end_b
|
|
45
|
+
|
|
46
|
+
def __call__(self, t: int) -> float:
|
|
47
|
+
"""
|
|
48
|
+
Cosine annealing scheduler for soft quantizer regularization temperature term.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
t: The current time step.
|
|
52
|
+
|
|
53
|
+
Returns: Scheduled temperature.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
is_before_start_decay = tf.cast(t < self.start_decay, tf.float32)
|
|
57
|
+
|
|
58
|
+
rel_t = (t - self.start_decay) / (self.t_max - self.start_decay)
|
|
59
|
+
|
|
60
|
+
return self.start_b * is_before_start_decay + \
|
|
61
|
+
(1 - is_before_start_decay) * \
|
|
62
|
+
(self.end_b + (self.start_b - self.end_b) * tf.math.maximum(0.0, (1 - rel_t)))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class SoftQuantizerRegularization:
|
|
66
|
+
"""
|
|
67
|
+
A class to handle the computation of soft quantizer regularization for GPTQ training.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(self, total_gradient_steps: int):
|
|
71
|
+
"""
|
|
72
|
+
Initializes the regularization computation object with a LinearDecay object.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
total_gradient_steps: The number of gradient steps during optimization.
|
|
76
|
+
"""
|
|
77
|
+
# Initializing the temperature decay according to the number of expected gradient steps
|
|
78
|
+
self.linear_decay = LinearTempDecay(total_gradient_steps)
|
|
79
|
+
|
|
80
|
+
self.count_iter = 0
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def __call__(self, model: Model, entropy_reg: float):
|
|
84
|
+
"""
|
|
85
|
+
Returns the soft quantizer regularization value for SoftRounding.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
model: A model to be quantized with SoftRounding.
|
|
89
|
+
entropy_reg: Entropy value to scale the quantizer regularization.
|
|
90
|
+
|
|
91
|
+
Returns: Regularization value.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
soft_reg_aux: List[tf.Tensor] = []
|
|
95
|
+
for layer in model.layers:
|
|
96
|
+
if isinstance(layer, KerasQuantizationWrapper):
|
|
97
|
+
kernel_attribute = get_kernel_attribute_name_for_gptq(layer_type=type(layer.layer),
|
|
98
|
+
fw_info=DEFAULT_KERAS_INFO)
|
|
99
|
+
|
|
100
|
+
st = layer.weights_quantizers[kernel_attribute].get_soft_targets()
|
|
101
|
+
b = self.linear_decay(self.count_iter)
|
|
102
|
+
|
|
103
|
+
soft_reg_aux.append(tf.reduce_sum(1 - tf.pow(tf.math.abs(st - .5) * 2, b)))
|
|
104
|
+
|
|
105
|
+
reg = 0
|
|
106
|
+
|
|
107
|
+
for sq in soft_reg_aux:
|
|
108
|
+
reg += sq
|
|
109
|
+
|
|
110
|
+
self.count_iter += 1
|
|
111
|
+
|
|
112
|
+
return entropy_reg * reg
|
|
@@ -16,22 +16,22 @@
|
|
|
16
16
|
import tensorflow as tf
|
|
17
17
|
import numpy as np
|
|
18
18
|
|
|
19
|
-
from model_compression_toolkit import RoundingType
|
|
19
|
+
from model_compression_toolkit.gptq import RoundingType
|
|
20
20
|
from model_compression_toolkit import quantizers_infrastructure as qi
|
|
21
21
|
from model_compression_toolkit.core.common import max_power_of_two
|
|
22
22
|
from model_compression_toolkit.core.common.target_platform import QuantizationMethod
|
|
23
|
-
from model_compression_toolkit.gptq.common.gptq_constants import PTQ_THRESHOLD, SCALE_PTQ,
|
|
24
|
-
|
|
23
|
+
from model_compression_toolkit.gptq.common.gptq_constants import PTQ_THRESHOLD, SCALE_PTQ, \
|
|
24
|
+
SOFT_ROUNDING_GAMMA, SOFT_ROUNDING_ZETA, AUXVAR
|
|
25
25
|
from model_compression_toolkit.gptq.keras.quantizer import quant_utils as qutils
|
|
26
|
-
from typing import Dict, Any
|
|
26
|
+
from typing import Dict, Any
|
|
27
27
|
from model_compression_toolkit.core.common.constants import THRESHOLD, MIN_THRESHOLD
|
|
28
|
-
from model_compression_toolkit.core.common.logger import Logger
|
|
29
28
|
from model_compression_toolkit.gptq.keras.quantizer.base_keras_gptq_quantizer import BaseKerasGPTQTrainableQuantizer
|
|
30
29
|
from model_compression_toolkit.gptq.keras.quantizer.quant_utils import power_of_two_max, clip, calculate_delta
|
|
31
30
|
from model_compression_toolkit.quantizers_infrastructure import TrainableQuantizerWeightsConfig
|
|
32
31
|
from model_compression_toolkit.quantizers_infrastructure.inferable_infrastructure.common.base_inferable_quantizer import mark_quantizer
|
|
33
32
|
from model_compression_toolkit.quantizers_infrastructure.trainable_infrastructure.common.quant_utils import \
|
|
34
33
|
get_threshold_reshape_shape
|
|
34
|
+
from model_compression_toolkit.quantizers_infrastructure.trainable_infrastructure.common.base_trainable_quantizer import VariableGroup
|
|
35
35
|
|
|
36
36
|
|
|
37
37
|
def soft_rounding_symmetric_quantizer(input_tensor: tf.Tensor,
|
|
@@ -66,46 +66,6 @@ def soft_rounding_symmetric_quantizer(input_tensor: tf.Tensor,
|
|
|
66
66
|
return delta * clip(tensor_q, max_val=max_int, min_val=min_int)
|
|
67
67
|
|
|
68
68
|
|
|
69
|
-
class LinearTempDecay:
|
|
70
|
-
"""
|
|
71
|
-
Annealing process for the soft quantizer regularization temperature term.
|
|
72
|
-
"""
|
|
73
|
-
|
|
74
|
-
def __init__(self, t_max: int, rel_start_decay: float = 0.2, start_b: int = 20, end_b: int = 2):
|
|
75
|
-
"""
|
|
76
|
-
Initializes a LinearTempDecay object.
|
|
77
|
-
|
|
78
|
-
Args:
|
|
79
|
-
t_max: maximal time step.
|
|
80
|
-
rel_start_decay: Decay step size at the beginning of the process.
|
|
81
|
-
start_b: Starting value of the regularization term.
|
|
82
|
-
end_b: Target value of the regularization term.
|
|
83
|
-
"""
|
|
84
|
-
|
|
85
|
-
self.t_max = t_max
|
|
86
|
-
self.start_decay = rel_start_decay * t_max
|
|
87
|
-
self.start_b = start_b
|
|
88
|
-
self.end_b = end_b
|
|
89
|
-
|
|
90
|
-
def __call__(self, t: int) -> float:
|
|
91
|
-
"""
|
|
92
|
-
Cosine annealing scheduler for soft quantizer regularization temperature term.
|
|
93
|
-
|
|
94
|
-
Args:
|
|
95
|
-
t: The current time step.
|
|
96
|
-
|
|
97
|
-
Returns: Scheduled temperature.
|
|
98
|
-
"""
|
|
99
|
-
|
|
100
|
-
is_before_start_decay = tf.cast(t < self.start_decay, tf.float32)
|
|
101
|
-
|
|
102
|
-
rel_t = (t - self.start_decay) / (self.t_max - self.start_decay)
|
|
103
|
-
|
|
104
|
-
return self.start_b * is_before_start_decay + \
|
|
105
|
-
(1 - is_before_start_decay) * \
|
|
106
|
-
(self.end_b + (self.start_b - self.end_b) * tf.math.maximum(0.0, (1 - rel_t)))
|
|
107
|
-
|
|
108
|
-
|
|
109
69
|
@mark_quantizer(quantization_target=qi.QuantizationTarget.Weights,
|
|
110
70
|
quantization_method=[QuantizationMethod.POWER_OF_TWO, QuantizationMethod.SYMMETRIC],
|
|
111
71
|
quantizer_type=RoundingType.SoftQuantizer)
|
|
@@ -116,23 +76,15 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
116
76
|
|
|
117
77
|
def __init__(self,
|
|
118
78
|
quantization_config: TrainableQuantizerWeightsConfig,
|
|
119
|
-
|
|
120
|
-
quantization_parameter_learning: bool = False,
|
|
121
|
-
n_epochs: int = N_EPOCHS):
|
|
79
|
+
quantization_parameter_learning: bool = False):
|
|
122
80
|
"""
|
|
123
81
|
Initialize a SymmetricSoftRoundingGPTQ object with parameters to use
|
|
124
82
|
for the quantization.
|
|
125
83
|
|
|
126
84
|
Args:
|
|
127
85
|
quantization_config: Trainable weights quantizer config.
|
|
128
|
-
n_batches: The expected number of batches for each training epoch.
|
|
129
86
|
quantization_parameter_learning: Whether to train the quantization threshold.
|
|
130
|
-
n_epochs: Number of epochs to run training for.
|
|
131
87
|
"""
|
|
132
|
-
|
|
133
|
-
if n_batches is None:
|
|
134
|
-
Logger.error("SymmetricSoftRoundingGPTQ got an uninitialized n_batches argument.")
|
|
135
|
-
|
|
136
88
|
super().__init__(quantization_config)
|
|
137
89
|
self.num_bits = quantization_config.weights_n_bits
|
|
138
90
|
self.per_channel = quantization_config.weights_per_channel_threshold
|
|
@@ -148,36 +100,23 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
148
100
|
self.num_channels = len(self.threshold_values) if self.per_channel else 1
|
|
149
101
|
|
|
150
102
|
# gamma and zeta are stretch parameters for computing the rectified sigmoind function.
|
|
151
|
-
# beta is used to set the regularization term.
|
|
152
103
|
# See: https://arxiv.org/pdf/2004.10568.pdf
|
|
153
104
|
self.gamma = SOFT_ROUNDING_GAMMA
|
|
154
105
|
self.zeta = SOFT_ROUNDING_ZETA
|
|
155
|
-
self.beta = SOFT_ROUNDING_BETA
|
|
156
106
|
|
|
157
107
|
self.quantizer_parameters = {}
|
|
158
108
|
|
|
159
|
-
# Initializing the temperature decay according to the number of expected gradient steps
|
|
160
|
-
if n_batches is None:
|
|
161
|
-
Logger.warning(f"Number of batches is not set correctly for the Soft Quantizer. A default value of " # pragma: no cover
|
|
162
|
-
f"{MAX_ITERATIONS_DEFAULT} is used to set the temperature decay which may affect the results.")
|
|
163
|
-
|
|
164
|
-
init_decay = MAX_ITERATIONS_DEFAULT if n_batches is None else n_epochs * n_batches
|
|
165
|
-
self.linear_decay = LinearTempDecay(init_decay)
|
|
166
|
-
|
|
167
109
|
def initialize_quantization(self,
|
|
168
110
|
tensor_shape: Any,
|
|
169
111
|
name: str,
|
|
170
|
-
layer: Any)
|
|
112
|
+
layer: Any):
|
|
171
113
|
"""
|
|
172
|
-
|
|
114
|
+
Add quantizer parameters to the quantizer parameters dictionary
|
|
173
115
|
|
|
174
116
|
Args:
|
|
175
117
|
tensor_shape: tensor shape of the quantized tensor.
|
|
176
118
|
name: Tensor name.
|
|
177
119
|
layer: Layer to quantize.
|
|
178
|
-
|
|
179
|
-
Returns:
|
|
180
|
-
Dictionary of parameters names to the variables.
|
|
181
120
|
"""
|
|
182
121
|
|
|
183
122
|
if self.per_channel:
|
|
@@ -187,12 +126,6 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
187
126
|
else:
|
|
188
127
|
reshape_shape = [self.num_channels]
|
|
189
128
|
|
|
190
|
-
ar_iter = layer.add_weight(
|
|
191
|
-
f"{name}_{GPTQ_ITER}",
|
|
192
|
-
shape=(),
|
|
193
|
-
initializer=tf.keras.initializers.Constant(0.0),
|
|
194
|
-
trainable=False)
|
|
195
|
-
|
|
196
129
|
ptq_threshold_tensor = layer.add_weight(
|
|
197
130
|
f"{name}_{PTQ_THRESHOLD}",
|
|
198
131
|
shape=reshape_shape,
|
|
@@ -216,44 +149,17 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
216
149
|
|
|
217
150
|
auxvar_tensor.assign(alpha)
|
|
218
151
|
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
152
|
+
# Add quantization variables
|
|
153
|
+
self.add_quantizer_variable(AUXVAR, auxvar_tensor, VariableGroup.WEIGHTS)
|
|
154
|
+
self.add_quantizer_variable(PTQ_THRESHOLD, ptq_threshold_tensor, VariableGroup.QPARAMS)
|
|
222
155
|
|
|
223
|
-
if self.quantization_parameter_learning:
|
|
156
|
+
if self.quantization_parameter_learning and not self.power_of_two:
|
|
224
157
|
scale = layer.add_weight(
|
|
225
158
|
f"{name}_{SCALE_PTQ}",
|
|
226
159
|
shape=self.num_channels,
|
|
227
160
|
initializer=tf.keras.initializers.Constant(1.0),
|
|
228
161
|
trainable=True)
|
|
229
|
-
self.
|
|
230
|
-
|
|
231
|
-
return self.quantizer_parameters
|
|
232
|
-
|
|
233
|
-
def get_quantization_variable(self) -> List[tf.Tensor]:
|
|
234
|
-
"""
|
|
235
|
-
This function return a list with the quantizer's quantization parameters variables.
|
|
236
|
-
|
|
237
|
-
Returns: A list with the quantization parameters if there are defined parameters.
|
|
238
|
-
|
|
239
|
-
"""
|
|
240
|
-
|
|
241
|
-
if self.quantization_parameter_learning and not self.power_of_two:
|
|
242
|
-
return [self.quantizer_parameters[SCALE_PTQ]]
|
|
243
|
-
else:
|
|
244
|
-
return []
|
|
245
|
-
|
|
246
|
-
def get_regularization(self) -> tf.Tensor:
|
|
247
|
-
"""
|
|
248
|
-
Computes the regularization term for the soft rounding loss.
|
|
249
|
-
|
|
250
|
-
Returns:
|
|
251
|
-
regularization term.
|
|
252
|
-
"""
|
|
253
|
-
|
|
254
|
-
st = self.get_soft_targets()
|
|
255
|
-
b = self.linear_decay(self.ar_iter.value())
|
|
256
|
-
return tf.reduce_sum(1 - tf.pow(tf.math.abs(st - .5) * 2, b))
|
|
162
|
+
self.add_quantizer_variable(SCALE_PTQ, scale, VariableGroup.QPARAMS)
|
|
257
163
|
|
|
258
164
|
def get_soft_targets(self) -> tf.Tensor:
|
|
259
165
|
"""
|
|
@@ -264,16 +170,7 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
264
170
|
|
|
265
171
|
"""
|
|
266
172
|
return qutils.clip(
|
|
267
|
-
tf.sigmoid(self.
|
|
268
|
-
|
|
269
|
-
def get_aux_variable(self) -> List[tf.Tensor]:
|
|
270
|
-
"""
|
|
271
|
-
This function return a list with the quantizer's quantization auxiliary variables.
|
|
272
|
-
|
|
273
|
-
Returns: A list with the quantization auxiliary variables.
|
|
274
|
-
|
|
275
|
-
"""
|
|
276
|
-
return [self.quantizer_parameters[AUXVAR]]
|
|
173
|
+
tf.sigmoid(self.get_quantizer_variable(AUXVAR)) * (self.zeta - self.gamma) + self.gamma, 1, 0)
|
|
277
174
|
|
|
278
175
|
def __call__(self,
|
|
279
176
|
inputs: tf.Tensor,
|
|
@@ -289,8 +186,7 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
289
186
|
The quantized tensor.
|
|
290
187
|
"""
|
|
291
188
|
|
|
292
|
-
|
|
293
|
-
ptq_threshold_tensor = self.quantizer_parameters[PTQ_THRESHOLD]
|
|
189
|
+
ptq_threshold_tensor = self.get_quantizer_variable(PTQ_THRESHOLD)
|
|
294
190
|
|
|
295
191
|
if self.per_channel:
|
|
296
192
|
reshape_shape = get_threshold_reshape_shape(inputs.shape,
|
|
@@ -306,10 +202,8 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
306
202
|
#####################################################
|
|
307
203
|
# Soft Rounding
|
|
308
204
|
#####################################################
|
|
309
|
-
if training:
|
|
310
|
-
|
|
311
|
-
else:
|
|
312
|
-
aux_var = tf.cast(self.quantizer_parameters[AUXVAR] >= 0, tf.float32)
|
|
205
|
+
if not training:
|
|
206
|
+
aux_var = tf.cast(tf.math.greater_equal(aux_var, 0.5), tf.float32)
|
|
313
207
|
|
|
314
208
|
#####################################################
|
|
315
209
|
# Quantized Input
|
|
@@ -322,13 +216,13 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
322
216
|
power_of_two=self.power_of_two)
|
|
323
217
|
|
|
324
218
|
if self.quantization_parameter_learning and not self.power_of_two:
|
|
325
|
-
scale = tf.reshape(self.
|
|
219
|
+
scale = tf.reshape(self.get_quantizer_variable(SCALE_PTQ), reshape_shape)
|
|
326
220
|
q_tensor *= scale
|
|
327
221
|
|
|
328
222
|
return q_tensor
|
|
329
223
|
else:
|
|
330
224
|
return soft_rounding_symmetric_quantizer(input_tensor=inputs,
|
|
331
|
-
auxvar_tensor=self.
|
|
225
|
+
auxvar_tensor=self.get_quantizer_variable(AUXVAR),
|
|
332
226
|
threshold_tensor=ptq_threshold_tensor.value(),
|
|
333
227
|
num_bits=self.num_bits,
|
|
334
228
|
signed=True,
|
|
@@ -344,13 +238,13 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
344
238
|
"""
|
|
345
239
|
|
|
346
240
|
if self.power_of_two:
|
|
347
|
-
old_threshold = self.
|
|
241
|
+
old_threshold = self.get_quantizer_variable(PTQ_THRESHOLD)
|
|
348
242
|
old_threshold = max_power_of_two(old_threshold, MIN_THRESHOLD)
|
|
349
243
|
|
|
350
244
|
else:
|
|
351
|
-
old_threshold = self.
|
|
245
|
+
old_threshold = self.get_quantizer_variable(PTQ_THRESHOLD)
|
|
352
246
|
if self.quantization_parameter_learning:
|
|
353
|
-
scale = tf.reshape(self.
|
|
247
|
+
scale = tf.reshape(self.get_quantizer_variable(SCALE_PTQ), self.threshold_shape)
|
|
354
248
|
old_threshold = old_threshold * scale
|
|
355
249
|
old_threshold = old_threshold.numpy()
|
|
356
250
|
old_threshold = old_threshold.reshape(self.threshold_shape)
|
|
@@ -13,15 +13,15 @@
|
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
# ==============================================================================
|
|
15
15
|
|
|
16
|
-
from typing import Dict, Any
|
|
16
|
+
from typing import Dict, Any
|
|
17
17
|
|
|
18
18
|
import numpy as np
|
|
19
19
|
import tensorflow as tf
|
|
20
20
|
|
|
21
|
-
from model_compression_toolkit import RoundingType
|
|
21
|
+
from model_compression_toolkit.gptq import RoundingType
|
|
22
22
|
from model_compression_toolkit import quantizers_infrastructure as qi
|
|
23
23
|
from model_compression_toolkit.core.common.target_platform import QuantizationMethod
|
|
24
|
-
from model_compression_toolkit.gptq.common.gptq_constants import
|
|
24
|
+
from model_compression_toolkit.gptq.common.gptq_constants import AUXVAR, PTQ_THRESHOLD
|
|
25
25
|
from model_compression_toolkit.gptq.keras.quantizer import quant_utils as qutils
|
|
26
26
|
from model_compression_toolkit.core.common.constants import THRESHOLD
|
|
27
27
|
from model_compression_toolkit.core.common.defaultdict import DefaultDict
|
|
@@ -30,6 +30,7 @@ from model_compression_toolkit.quantizers_infrastructure import TrainableQuantiz
|
|
|
30
30
|
from model_compression_toolkit.quantizers_infrastructure.inferable_infrastructure.common.base_inferable_quantizer import mark_quantizer
|
|
31
31
|
from model_compression_toolkit.quantizers_infrastructure.trainable_infrastructure.common.quant_utils import \
|
|
32
32
|
get_threshold_reshape_shape
|
|
33
|
+
from model_compression_toolkit.quantizers_infrastructure.trainable_infrastructure.common.base_trainable_quantizer import VariableGroup
|
|
33
34
|
|
|
34
35
|
|
|
35
36
|
def pertubation_symmetric_quantizer(input_tensor: tf.Tensor,
|
|
@@ -96,30 +97,20 @@ class STEWeightGPTQQuantizer(BaseKerasGPTQTrainableQuantizer):
|
|
|
96
97
|
self.quantization_axis = quantization_config.weights_channels_axis
|
|
97
98
|
self.power_of_two = quantization_config.weights_quantization_method == QuantizationMethod.POWER_OF_TWO
|
|
98
99
|
self.max_lsbs_change = max_lsbs_change_map.get(self.num_bits)
|
|
99
|
-
self.quantizer_parameters = {}
|
|
100
100
|
|
|
101
101
|
def initialize_quantization(self,
|
|
102
102
|
tensor_shape: Any,
|
|
103
103
|
name: str,
|
|
104
|
-
layer: Any)
|
|
104
|
+
layer: Any):
|
|
105
105
|
"""
|
|
106
|
-
|
|
106
|
+
Add quantizer parameters to the quantizer parameters dictionary
|
|
107
107
|
|
|
108
108
|
Args:
|
|
109
109
|
tensor_shape: tensor shape of the quantized tensor.
|
|
110
110
|
name: Tensor name.
|
|
111
111
|
layer: Layer to quantize.
|
|
112
|
-
|
|
113
|
-
Returns:
|
|
114
|
-
Dictionary of parameters names to the variables.
|
|
115
112
|
"""
|
|
116
113
|
|
|
117
|
-
ar_iter = layer.add_weight(
|
|
118
|
-
f"{name}_{GPTQ_ITER}",
|
|
119
|
-
shape=(),
|
|
120
|
-
initializer=tf.keras.initializers.Constant(0.0),
|
|
121
|
-
trainable=False)
|
|
122
|
-
|
|
123
114
|
ptq_threshold_tensor = layer.add_weight(
|
|
124
115
|
f"{name}_{PTQ_THRESHOLD}",
|
|
125
116
|
shape=len(self.threshold_values) if self.per_channel else (),
|
|
@@ -135,10 +126,8 @@ class STEWeightGPTQQuantizer(BaseKerasGPTQTrainableQuantizer):
|
|
|
135
126
|
trainable=True)
|
|
136
127
|
|
|
137
128
|
# save the quantizer added parameters for later calculations
|
|
138
|
-
self.
|
|
139
|
-
|
|
140
|
-
GPTQ_ITER: ar_iter}
|
|
141
|
-
return self.quantizer_parameters
|
|
129
|
+
self.add_quantizer_variable(PTQ_THRESHOLD, ptq_threshold_tensor, VariableGroup.QPARAMS)
|
|
130
|
+
self.add_quantizer_variable(AUXVAR, auxvar_tensor, VariableGroup.WEIGHTS)
|
|
142
131
|
|
|
143
132
|
def __call__(self,
|
|
144
133
|
inputs: tf.Tensor,
|
|
@@ -154,8 +143,8 @@ class STEWeightGPTQQuantizer(BaseKerasGPTQTrainableQuantizer):
|
|
|
154
143
|
The quantized tensor.
|
|
155
144
|
"""
|
|
156
145
|
|
|
157
|
-
auxvar = self.
|
|
158
|
-
ptq_threshold_tensor = self.
|
|
146
|
+
auxvar = self.get_quantizer_variable(AUXVAR)
|
|
147
|
+
ptq_threshold_tensor = self.get_quantizer_variable(PTQ_THRESHOLD)
|
|
159
148
|
|
|
160
149
|
if self.per_channel:
|
|
161
150
|
reshape_shape = get_threshold_reshape_shape(inputs.shape,
|
|
@@ -178,25 +167,6 @@ class STEWeightGPTQQuantizer(BaseKerasGPTQTrainableQuantizer):
|
|
|
178
167
|
signed=True,
|
|
179
168
|
power_of_two=self.power_of_two)
|
|
180
169
|
|
|
181
|
-
def get_aux_variable(self) -> List[tf.Tensor]:
|
|
182
|
-
"""
|
|
183
|
-
This function return a list with the quantizer's quantization auxiliary variables.
|
|
184
|
-
|
|
185
|
-
Returns: A list with the quantization auxiliary variables.
|
|
186
|
-
|
|
187
|
-
"""
|
|
188
|
-
|
|
189
|
-
return [self.quantizer_parameters[AUXVAR]]
|
|
190
|
-
|
|
191
|
-
def get_quantization_variable(self) -> List[tf.Tensor]:
|
|
192
|
-
"""
|
|
193
|
-
This function return a list with the quantizer's quantization parameters variables.
|
|
194
|
-
|
|
195
|
-
Returns: A list with the quantization parameters.
|
|
196
|
-
|
|
197
|
-
"""
|
|
198
|
-
|
|
199
|
-
return [self.quantizer_parameters[PTQ_THRESHOLD]]
|
|
200
170
|
|
|
201
171
|
def get_quant_config(self) -> Dict[str, np.ndarray]:
|
|
202
172
|
"""
|
|
@@ -207,5 +177,5 @@ class STEWeightGPTQQuantizer(BaseKerasGPTQTrainableQuantizer):
|
|
|
207
177
|
Keys must match NodeQuantizationConfig attributes
|
|
208
178
|
|
|
209
179
|
"""
|
|
210
|
-
old_threshold = self.
|
|
180
|
+
old_threshold = self.get_quantizer_variable(PTQ_THRESHOLD)
|
|
211
181
|
return {THRESHOLD: old_threshold.numpy().reshape(self.threshold_shape)}
|
|
@@ -29,9 +29,11 @@ from model_compression_toolkit.core.common.framework_info import FrameworkInfo
|
|
|
29
29
|
from model_compression_toolkit.core.common.framework_implementation import FrameworkImplementation
|
|
30
30
|
from model_compression_toolkit.core.pytorch.constants import BIAS
|
|
31
31
|
from model_compression_toolkit.core.pytorch.utils import to_torch_tensor, set_model, torch_tensor_to_numpy
|
|
32
|
-
from model_compression_toolkit.gptq.pytorch.graph_info import get_gptq_trainable_parameters,
|
|
32
|
+
from model_compression_toolkit.gptq.pytorch.graph_info import get_gptq_trainable_parameters, \
|
|
33
|
+
get_weights_for_loss
|
|
33
34
|
from model_compression_toolkit.gptq.pytorch.quantizer.quantization_builder import quantization_builder
|
|
34
35
|
from model_compression_toolkit import quantizers_infrastructure as qi
|
|
36
|
+
from model_compression_toolkit.gptq.pytorch.quantizer.regularization_factory import get_regularization
|
|
35
37
|
from model_compression_toolkit.quantizers_infrastructure import PytorchQuantizationWrapper
|
|
36
38
|
|
|
37
39
|
|
|
@@ -61,7 +63,7 @@ class PytorchGPTQTrainer(GPTQTrainer):
|
|
|
61
63
|
fw_info: Framework information
|
|
62
64
|
representative_data_gen: Dataset to use for inputs of the models.
|
|
63
65
|
"""
|
|
64
|
-
super().__init__(graph_float, graph_quant, gptq_config, fw_impl, fw_info
|
|
66
|
+
super().__init__(graph_float, graph_quant, gptq_config, fw_impl, fw_info)
|
|
65
67
|
self.loss_list = []
|
|
66
68
|
self.input_scale = 1
|
|
67
69
|
if self.float_user_info.input_scale != self.gptq_user_info.input_scale:
|
|
@@ -69,7 +71,7 @@ class PytorchGPTQTrainer(GPTQTrainer):
|
|
|
69
71
|
else:
|
|
70
72
|
self.input_scale = self.gptq_user_info.input_scale
|
|
71
73
|
|
|
72
|
-
trainable_weights, trainable_bias, trainable_threshold
|
|
74
|
+
trainable_weights, trainable_bias, trainable_threshold = get_gptq_trainable_parameters(
|
|
73
75
|
self.fxp_model,
|
|
74
76
|
add_bias=self.gptq_config.train_bias)
|
|
75
77
|
|
|
@@ -84,7 +86,9 @@ class PytorchGPTQTrainer(GPTQTrainer):
|
|
|
84
86
|
trainable_bias,
|
|
85
87
|
trainable_threshold)
|
|
86
88
|
|
|
87
|
-
self.weights_for_average_loss = to_torch_tensor(self.
|
|
89
|
+
self.weights_for_average_loss = to_torch_tensor(self.compute_hessian_based_weights(representative_data_gen))
|
|
90
|
+
|
|
91
|
+
self.reg_func = get_regularization(self.gptq_config, representative_data_gen)
|
|
88
92
|
|
|
89
93
|
def _is_gptq_applicable(self,
|
|
90
94
|
node: BaseNode) -> bool:
|
|
@@ -182,6 +186,10 @@ class PytorchGPTQTrainer(GPTQTrainer):
|
|
|
182
186
|
self.compare_points_std,
|
|
183
187
|
self.weights_for_average_loss)
|
|
184
188
|
|
|
189
|
+
reg_value = self.reg_func(self.fxp_model, self.gptq_config.regularization_factor)
|
|
190
|
+
|
|
191
|
+
loss_value += reg_value
|
|
192
|
+
|
|
185
193
|
# Back-pass
|
|
186
194
|
loss_value.backward()
|
|
187
195
|
|