mct-nightly 1.8.0.4032023.post406__py3-none-any.whl → 1.8.0.4042023.post409__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.4032023.post406.dist-info → mct_nightly-1.8.0.4042023.post409.dist-info}/METADATA +7 -7
- {mct_nightly-1.8.0.4032023.post406.dist-info → mct_nightly-1.8.0.4042023.post409.dist-info}/RECORD +63 -59
- {mct_nightly-1.8.0.4032023.post406.dist-info → mct_nightly-1.8.0.4042023.post409.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/keras/back2framework/model_gradients.py +3 -2
- model_compression_toolkit/core/keras/quantization_facade.py +1 -1
- model_compression_toolkit/core/pytorch/back2framework/model_gradients.py +13 -6
- model_compression_toolkit/core/pytorch/constants.py +4 -0
- 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 +57 -104
- 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 +38 -135
- model_compression_toolkit/gptq/keras/quantizer/ste_rounding/symmetric_ste.py +11 -41
- model_compression_toolkit/gptq/pytorch/gptq_training.py +9 -24
- model_compression_toolkit/gptq/pytorch/graph_info.py +7 -27
- model_compression_toolkit/gptq/pytorch/quantization_facade.py +9 -22
- model_compression_toolkit/gptq/pytorch/quantizer/__init__.py +1 -0
- 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/soft_quantizer_reg.py +115 -0
- model_compression_toolkit/gptq/pytorch/quantizer/soft_rounding/symmetric_soft_quantizer.py +30 -117
- 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/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 +13 -3
- 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.4032023.post406.dist-info → mct_nightly-1.8.0.4042023.post409.dist-info}/LICENSE.md +0 -0
- {mct_nightly-1.8.0.4032023.post406.dist-info → mct_nightly-1.8.0.4042023.post409.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,32 +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
|
-
init_decay = MAX_ITERATIONS_DEFAULT if n_batches is None else n_epochs * n_batches
|
|
161
|
-
self.linear_decay = LinearTempDecay(init_decay)
|
|
162
|
-
|
|
163
109
|
def initialize_quantization(self,
|
|
164
110
|
tensor_shape: Any,
|
|
165
111
|
name: str,
|
|
166
|
-
layer: Any)
|
|
112
|
+
layer: Any):
|
|
167
113
|
"""
|
|
168
|
-
|
|
114
|
+
Add quantizer parameters to the quantizer parameters dictionary
|
|
169
115
|
|
|
170
116
|
Args:
|
|
171
117
|
tensor_shape: tensor shape of the quantized tensor.
|
|
172
118
|
name: Tensor name.
|
|
173
119
|
layer: Layer to quantize.
|
|
174
|
-
|
|
175
|
-
Returns:
|
|
176
|
-
Dictionary of parameters names to the variables.
|
|
177
120
|
"""
|
|
178
121
|
|
|
179
122
|
if self.per_channel:
|
|
@@ -183,12 +126,6 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
183
126
|
else:
|
|
184
127
|
reshape_shape = [self.num_channels]
|
|
185
128
|
|
|
186
|
-
ar_iter = layer.add_weight(
|
|
187
|
-
f"{name}_{GPTQ_ITER}",
|
|
188
|
-
shape=(),
|
|
189
|
-
initializer=tf.keras.initializers.Constant(0.0),
|
|
190
|
-
trainable=False)
|
|
191
|
-
|
|
192
129
|
ptq_threshold_tensor = layer.add_weight(
|
|
193
130
|
f"{name}_{PTQ_THRESHOLD}",
|
|
194
131
|
shape=reshape_shape,
|
|
@@ -212,44 +149,17 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
212
149
|
|
|
213
150
|
auxvar_tensor.assign(alpha)
|
|
214
151
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
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)
|
|
218
155
|
|
|
219
|
-
if self.quantization_parameter_learning:
|
|
156
|
+
if self.quantization_parameter_learning and not self.power_of_two:
|
|
220
157
|
scale = layer.add_weight(
|
|
221
158
|
f"{name}_{SCALE_PTQ}",
|
|
222
159
|
shape=self.num_channels,
|
|
223
160
|
initializer=tf.keras.initializers.Constant(1.0),
|
|
224
161
|
trainable=True)
|
|
225
|
-
self.
|
|
226
|
-
|
|
227
|
-
return self.quantizer_parameters
|
|
228
|
-
|
|
229
|
-
def get_quantization_variable(self) -> List[tf.Tensor]:
|
|
230
|
-
"""
|
|
231
|
-
This function return a list with the quantizer's quantization parameters variables.
|
|
232
|
-
|
|
233
|
-
Returns: A list with the quantization parameters if there are defined parameters.
|
|
234
|
-
|
|
235
|
-
"""
|
|
236
|
-
|
|
237
|
-
if self.quantization_parameter_learning and not self.power_of_two:
|
|
238
|
-
return [self.quantizer_parameters[SCALE_PTQ]]
|
|
239
|
-
else:
|
|
240
|
-
return []
|
|
241
|
-
|
|
242
|
-
def get_regularization(self) -> tf.Tensor:
|
|
243
|
-
"""
|
|
244
|
-
Computes the regularization term for the soft rounding loss.
|
|
245
|
-
|
|
246
|
-
Returns:
|
|
247
|
-
regularization term.
|
|
248
|
-
"""
|
|
249
|
-
|
|
250
|
-
st = self.get_soft_targets()
|
|
251
|
-
b = self.linear_decay(self.ar_iter.value())
|
|
252
|
-
return tf.reduce_sum(1 - tf.pow(tf.math.abs(st - .5) * 2, b))
|
|
162
|
+
self.add_quantizer_variable(SCALE_PTQ, scale, VariableGroup.QPARAMS)
|
|
253
163
|
|
|
254
164
|
def get_soft_targets(self) -> tf.Tensor:
|
|
255
165
|
"""
|
|
@@ -260,16 +170,7 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
260
170
|
|
|
261
171
|
"""
|
|
262
172
|
return qutils.clip(
|
|
263
|
-
tf.sigmoid(self.
|
|
264
|
-
|
|
265
|
-
def get_aux_variable(self) -> List[tf.Tensor]:
|
|
266
|
-
"""
|
|
267
|
-
This function return a list with the quantizer's quantization auxiliary variables.
|
|
268
|
-
|
|
269
|
-
Returns: A list with the quantization auxiliary variables.
|
|
270
|
-
|
|
271
|
-
"""
|
|
272
|
-
return [self.quantizer_parameters[AUXVAR]]
|
|
173
|
+
tf.sigmoid(self.get_quantizer_variable(AUXVAR)) * (self.zeta - self.gamma) + self.gamma, 1, 0)
|
|
273
174
|
|
|
274
175
|
def __call__(self,
|
|
275
176
|
inputs: tf.Tensor,
|
|
@@ -285,8 +186,14 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
285
186
|
The quantized tensor.
|
|
286
187
|
"""
|
|
287
188
|
|
|
288
|
-
|
|
289
|
-
|
|
189
|
+
ptq_threshold_tensor = self.get_quantizer_variable(PTQ_THRESHOLD)
|
|
190
|
+
|
|
191
|
+
#####################################################
|
|
192
|
+
# Soft Rounding
|
|
193
|
+
#####################################################
|
|
194
|
+
aux_var = self.get_soft_targets()
|
|
195
|
+
if not training:
|
|
196
|
+
aux_var = tf.cast(tf.math.greater_equal(aux_var, 0.5), tf.float32)
|
|
290
197
|
|
|
291
198
|
if self.per_channel:
|
|
292
199
|
reshape_shape = get_threshold_reshape_shape(inputs.shape,
|
|
@@ -297,15 +204,6 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
297
204
|
# Calculate soft rounding targets and optimized threshold
|
|
298
205
|
##########################################################
|
|
299
206
|
ptq_threshold_tensor_hat = tf.reshape(ptq_threshold_tensor, reshape_shape)
|
|
300
|
-
aux_var = self.get_soft_targets()
|
|
301
|
-
|
|
302
|
-
#####################################################
|
|
303
|
-
# Soft Rounding
|
|
304
|
-
#####################################################
|
|
305
|
-
if training:
|
|
306
|
-
self.ar_iter.assign_add(1.0)
|
|
307
|
-
else:
|
|
308
|
-
aux_var = tf.cast(tf.math.greater_equal(aux_var, 0.5), tf.float32)
|
|
309
207
|
|
|
310
208
|
#####################################################
|
|
311
209
|
# Quantized Input
|
|
@@ -318,17 +216,22 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
318
216
|
power_of_two=self.power_of_two)
|
|
319
217
|
|
|
320
218
|
if self.quantization_parameter_learning and not self.power_of_two:
|
|
321
|
-
scale = tf.reshape(self.
|
|
219
|
+
scale = tf.reshape(self.get_quantizer_variable(SCALE_PTQ), reshape_shape)
|
|
322
220
|
q_tensor *= scale
|
|
323
221
|
|
|
324
|
-
return q_tensor
|
|
325
222
|
else:
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
223
|
+
q_tensor = soft_rounding_symmetric_quantizer(input_tensor=inputs,
|
|
224
|
+
auxvar_tensor=aux_var,
|
|
225
|
+
threshold_tensor=ptq_threshold_tensor.value(),
|
|
226
|
+
num_bits=self.num_bits,
|
|
227
|
+
signed=True,
|
|
228
|
+
power_of_two=self.power_of_two)
|
|
229
|
+
|
|
230
|
+
if self.quantization_parameter_learning and not self.power_of_two:
|
|
231
|
+
scale = self.get_quantizer_variable(SCALE_PTQ)
|
|
232
|
+
q_tensor *= scale
|
|
233
|
+
|
|
234
|
+
return q_tensor
|
|
332
235
|
|
|
333
236
|
def get_quant_config(self) -> Dict[str, np.ndarray]:
|
|
334
237
|
"""
|
|
@@ -340,13 +243,13 @@ class SymmetricSoftRoundingGPTQ(BaseKerasGPTQTrainableQuantizer):
|
|
|
340
243
|
"""
|
|
341
244
|
|
|
342
245
|
if self.power_of_two:
|
|
343
|
-
old_threshold = self.
|
|
246
|
+
old_threshold = self.get_quantizer_variable(PTQ_THRESHOLD)
|
|
344
247
|
old_threshold = max_power_of_two(old_threshold, MIN_THRESHOLD)
|
|
345
248
|
|
|
346
249
|
else:
|
|
347
|
-
old_threshold = self.
|
|
250
|
+
old_threshold = self.get_quantizer_variable(PTQ_THRESHOLD)
|
|
348
251
|
if self.quantization_parameter_learning:
|
|
349
|
-
scale = tf.reshape(self.
|
|
252
|
+
scale = tf.reshape(self.get_quantizer_variable(SCALE_PTQ), self.threshold_shape)
|
|
350
253
|
old_threshold = old_threshold * scale
|
|
351
254
|
old_threshold = old_threshold.numpy()
|
|
352
255
|
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)}
|
|
@@ -23,17 +23,17 @@ from model_compression_toolkit.core.common.logger import Logger
|
|
|
23
23
|
from model_compression_toolkit.core.pytorch.back2framework.pytorch_model_builder import PyTorchModelBuilder
|
|
24
24
|
from model_compression_toolkit.gptq.common.gptq_graph import get_kernel_attribute_name_for_gptq
|
|
25
25
|
from model_compression_toolkit.gptq.common.gptq_training import GPTQTrainer
|
|
26
|
-
from model_compression_toolkit.gptq.common.gptq_config import GradientPTQConfigV2
|
|
26
|
+
from model_compression_toolkit.gptq.common.gptq_config import GradientPTQConfigV2
|
|
27
27
|
from model_compression_toolkit.core.common import Graph, BaseNode
|
|
28
28
|
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
32
|
from model_compression_toolkit.gptq.pytorch.graph_info import get_gptq_trainable_parameters, \
|
|
33
|
-
get_weights_for_loss
|
|
33
|
+
get_weights_for_loss
|
|
34
34
|
from model_compression_toolkit.gptq.pytorch.quantizer.quantization_builder import quantization_builder
|
|
35
|
-
from model_compression_toolkit.gptq.common.gptq_constants import REGULARIZATION_VALUES
|
|
36
35
|
from model_compression_toolkit import quantizers_infrastructure as qi
|
|
36
|
+
from model_compression_toolkit.gptq.pytorch.quantizer.regularization_factory import get_regularization
|
|
37
37
|
from model_compression_toolkit.quantizers_infrastructure import PytorchQuantizationWrapper
|
|
38
38
|
|
|
39
39
|
|
|
@@ -63,7 +63,7 @@ class PytorchGPTQTrainer(GPTQTrainer):
|
|
|
63
63
|
fw_info: Framework information
|
|
64
64
|
representative_data_gen: Dataset to use for inputs of the models.
|
|
65
65
|
"""
|
|
66
|
-
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)
|
|
67
67
|
self.loss_list = []
|
|
68
68
|
self.input_scale = 1
|
|
69
69
|
if self.float_user_info.input_scale != self.gptq_user_info.input_scale:
|
|
@@ -71,7 +71,7 @@ class PytorchGPTQTrainer(GPTQTrainer):
|
|
|
71
71
|
else:
|
|
72
72
|
self.input_scale = self.gptq_user_info.input_scale
|
|
73
73
|
|
|
74
|
-
trainable_weights, trainable_bias, trainable_threshold
|
|
74
|
+
trainable_weights, trainable_bias, trainable_threshold = get_gptq_trainable_parameters(
|
|
75
75
|
self.fxp_model,
|
|
76
76
|
add_bias=self.gptq_config.train_bias)
|
|
77
77
|
|
|
@@ -86,7 +86,9 @@ class PytorchGPTQTrainer(GPTQTrainer):
|
|
|
86
86
|
trainable_bias,
|
|
87
87
|
trainable_threshold)
|
|
88
88
|
|
|
89
|
-
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)
|
|
90
92
|
|
|
91
93
|
def _is_gptq_applicable(self,
|
|
92
94
|
node: BaseNode) -> bool:
|
|
@@ -184,9 +186,7 @@ class PytorchGPTQTrainer(GPTQTrainer):
|
|
|
184
186
|
self.compare_points_std,
|
|
185
187
|
self.weights_for_average_loss)
|
|
186
188
|
|
|
187
|
-
reg_value = self.gptq_config.
|
|
188
|
-
self.fxp_model,
|
|
189
|
-
**{REGULARIZATION_VALUES: self._get_quantizer_regularization_values(self.gptq_config.rounding_type)})
|
|
189
|
+
reg_value = self.reg_func(self.fxp_model, self.gptq_config.regularization_factor)
|
|
190
190
|
|
|
191
191
|
loss_value += reg_value
|
|
192
192
|
|
|
@@ -272,18 +272,3 @@ class PytorchGPTQTrainer(GPTQTrainer):
|
|
|
272
272
|
if hasattr(layer.layer, BIAS):
|
|
273
273
|
bias = getattr(layer.layer, BIAS)
|
|
274
274
|
bias.requires_grad = self.gptq_config.train_bias
|
|
275
|
-
|
|
276
|
-
def _get_quantizer_regularization_values(self, rounding_type: RoundingType) -> List[torch.Tensor]:
|
|
277
|
-
"""
|
|
278
|
-
Mapping between a rounding type to its matching regularization method.
|
|
279
|
-
|
|
280
|
-
Args:
|
|
281
|
-
rounding_type: GPTQ rounding type.
|
|
282
|
-
|
|
283
|
-
Returns: A regularization computation method.
|
|
284
|
-
|
|
285
|
-
"""
|
|
286
|
-
if rounding_type == RoundingType.SoftQuantizer:
|
|
287
|
-
return get_soft_rounding_reg(self.fxp_model)
|
|
288
|
-
else:
|
|
289
|
-
return []
|