mct-nightly 2.2.0.20241106.458__py3-none-any.whl → 2.2.0.20241107.459__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-2.2.0.20241106.458.dist-info → mct_nightly-2.2.0.20241107.459.dist-info}/METADATA +1 -1
- {mct_nightly-2.2.0.20241106.458.dist-info → mct_nightly-2.2.0.20241107.459.dist-info}/RECORD +17 -29
- {mct_nightly-2.2.0.20241106.458.dist-info → mct_nightly-2.2.0.20241107.459.dist-info}/top_level.txt +0 -1
- model_compression_toolkit/__init__.py +1 -1
- model_compression_toolkit/core/common/framework_implementation.py +46 -27
- model_compression_toolkit/core/common/quantization/node_quantization_config.py +2 -0
- model_compression_toolkit/core/common/quantization/quantization_config.py +2 -0
- model_compression_toolkit/core/common/statistics_correction/apply_activation_bias_correction_to_graph.py +81 -0
- model_compression_toolkit/core/common/statistics_correction/compute_activation_bias_correction_of_graph.py +190 -0
- model_compression_toolkit/core/common/statistics_correction/statistics_correction.py +14 -2
- model_compression_toolkit/core/keras/keras_implementation.py +23 -2
- model_compression_toolkit/core/keras/statistics_correction/keras_compute_activation_bias_correction_of_graph.py +67 -0
- model_compression_toolkit/core/pytorch/pytorch_implementation.py +21 -0
- model_compression_toolkit/core/pytorch/statistics_correction/pytorch_compute_activation_bias_correction_of_graph.py +57 -0
- model_compression_toolkit/core/runner.py +8 -0
- tests_pytest/__init__.py +0 -14
- tests_pytest/keras/__init__.py +0 -14
- tests_pytest/keras/core/__init__.py +0 -14
- tests_pytest/keras/core/test_data_util.py +0 -91
- tests_pytest/keras/gptq/__init__.py +0 -14
- tests_pytest/keras/gptq/test_gradual_act_quantization.py +0 -102
- tests_pytest/keras/trainable_infrastructure/__init__.py +0 -16
- tests_pytest/keras/trainable_infrastructure/test_linear_annealing.py +0 -49
- tests_pytest/pytorch/__init__.py +0 -14
- tests_pytest/pytorch/core/__init__.py +0 -14
- tests_pytest/pytorch/core/test_data_util.py +0 -125
- tests_pytest/pytorch/gptq/__init__.py +0 -14
- tests_pytest/pytorch/gptq/test_annealing_cfg.py +0 -40
- tests_pytest/pytorch/gptq/test_gradual_act_quantization.py +0 -100
- tests_pytest/pytorch/trainable_infrastructure/__init__.py +0 -14
- tests_pytest/pytorch/trainable_infrastructure/test_linear_annealing.py +0 -49
- {mct_nightly-2.2.0.20241106.458.dist-info → mct_nightly-2.2.0.20241107.459.dist-info}/LICENSE.md +0 -0
- {mct_nightly-2.2.0.20241106.458.dist-info → mct_nightly-2.2.0.20241107.459.dist-info}/WHEEL +0 -0
@@ -1,102 +0,0 @@
|
|
1
|
-
# Copyright 2024 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 unittest.mock import Mock
|
16
|
-
import pytest
|
17
|
-
import numpy as np
|
18
|
-
import tensorflow as tf
|
19
|
-
|
20
|
-
from model_compression_toolkit.gptq.common.gradual_activation_quantization import GradualActivationQuantizerWrapper, \
|
21
|
-
get_gradual_activation_quantizer_wrapper_factory
|
22
|
-
from model_compression_toolkit.trainable_infrastructure.keras.annealing_schedulers import KerasLinearAnnealingScheduler
|
23
|
-
from model_compression_toolkit.gptq import GradientPTQConfig, GradualActivationQuantizationConfig, QFractionLinearAnnealingConfig
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
@pytest.fixture
|
28
|
-
def x():
|
29
|
-
return tf.random.normal((2, 5, 6, 7), seed=42, dtype=tf.float32)
|
30
|
-
|
31
|
-
|
32
|
-
class Quantizer:
|
33
|
-
def __call__(self, x, training):
|
34
|
-
self.training = training
|
35
|
-
return 3 * x + 1
|
36
|
-
|
37
|
-
|
38
|
-
class TestGradualActivationQuantization:
|
39
|
-
|
40
|
-
def test_gradual_act_quant_wrapper(self, x):
|
41
|
-
quantizer = Quantizer()
|
42
|
-
qw = GradualActivationQuantizerWrapper(quantizer, q_fraction_scheduler=lambda t: t / (t + 1))
|
43
|
-
|
44
|
-
y0, y1, y2 = [qw(x, training=True) for _ in range(3)]
|
45
|
-
assert np.allclose(y0.numpy(), x.numpy()) # t=0
|
46
|
-
assert np.allclose(y1.numpy(), 0.5 * x.numpy() + (1.5 * x.numpy() + 0.5)) # t=1
|
47
|
-
assert np.allclose(y2.numpy(), x.numpy() / 3 + (2 * x.numpy() + 2 / 3)) # t=2
|
48
|
-
assert quantizer.training is True
|
49
|
-
|
50
|
-
_ = qw(x, training=False)
|
51
|
-
assert quantizer.training is False # correct flag was propagated
|
52
|
-
|
53
|
-
def test_factory_no_qdrop(self):
|
54
|
-
quantizer_wrapper, quantizer = self._run_factory_test(qdrop_cfg=None, get_grad_steps_fn=None)
|
55
|
-
assert quantizer_wrapper is quantizer
|
56
|
-
|
57
|
-
@pytest.mark.parametrize('end_step', (20, None))
|
58
|
-
def test_factory_linear(self, x, end_step):
|
59
|
-
qdrop_cfg = GradualActivationQuantizationConfig(
|
60
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0.3, target_q_fraction=0.8, start_step=10,
|
61
|
-
end_step=end_step)
|
62
|
-
)
|
63
|
-
|
64
|
-
def get_total_steps():
|
65
|
-
if end_step is None:
|
66
|
-
return 50
|
67
|
-
assert False # should not be called if end_step is passed
|
68
|
-
|
69
|
-
quantizer_wrapper, quantizer = self._run_factory_test(qdrop_cfg, get_total_steps)
|
70
|
-
|
71
|
-
scheduler = quantizer_wrapper.q_fraction_scheduler
|
72
|
-
assert isinstance(scheduler, KerasLinearAnnealingScheduler)
|
73
|
-
exp_end_step = 50 if end_step is None else end_step
|
74
|
-
assert scheduler.t_start == 10
|
75
|
-
assert scheduler.t_end == exp_end_step
|
76
|
-
assert scheduler.initial_val == 0.3
|
77
|
-
assert scheduler.target_val == 0.8
|
78
|
-
|
79
|
-
y = [quantizer_wrapper(x, training=True) for _ in range(exp_end_step + 1)]
|
80
|
-
|
81
|
-
assert np.allclose(y[9].numpy(), 0.7 * x.numpy() + 0.3 * quantizer(x, training=True).numpy())
|
82
|
-
assert np.allclose(y[10].numpy(), 0.7 * x.numpy() + 0.3 * quantizer(x, training=True).numpy())
|
83
|
-
assert np.allclose(y[-1].numpy(), 0.2 * x.numpy() + 0.8 * quantizer(x, training=True).numpy())
|
84
|
-
|
85
|
-
def test_factory_linear_common_case(self, x):
|
86
|
-
# validate that we actually implemented the right thing - on first call float input, on last call fully quantized
|
87
|
-
qdrop_cfg = GradualActivationQuantizationConfig(
|
88
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0, target_q_fraction=1, start_step=0, end_step=None)
|
89
|
-
)
|
90
|
-
quantizer_wrapper, quantizer = self._run_factory_test(qdrop_cfg, lambda: 15)
|
91
|
-
y0, *_, y_last = [quantizer_wrapper(x, training=True) for _ in range(16)]
|
92
|
-
assert np.array_equal(y0.numpy(), x.numpy())
|
93
|
-
assert np.allclose(y_last.numpy(), quantizer(x, training=True).numpy())
|
94
|
-
|
95
|
-
def _run_factory_test(self, qdrop_cfg, get_grad_steps_fn):
|
96
|
-
# Mocks are used to just pass anything
|
97
|
-
gptq_cfg = GradientPTQConfig(n_epochs=5, optimizer=Mock(), loss=Mock(),
|
98
|
-
gradual_activation_quantization_config=qdrop_cfg)
|
99
|
-
factory = get_gradual_activation_quantizer_wrapper_factory(gptq_cfg, get_grad_steps_fn, KerasLinearAnnealingScheduler)
|
100
|
-
quantizer = Quantizer()
|
101
|
-
quantizer_wrapper = factory(quantizer)
|
102
|
-
return quantizer_wrapper, quantizer
|
@@ -1,16 +0,0 @@
|
|
1
|
-
# Copyright 2024 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
|
-
|
16
|
-
|
@@ -1,49 +0,0 @@
|
|
1
|
-
# Copyright 2024 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
|
-
import numpy as np
|
16
|
-
import pytest
|
17
|
-
|
18
|
-
from model_compression_toolkit.trainable_infrastructure.keras.annealing_schedulers import KerasLinearAnnealingScheduler
|
19
|
-
|
20
|
-
|
21
|
-
def test_linear_annealing():
|
22
|
-
scheduler = KerasLinearAnnealingScheduler(t_start=10, t_end=35, initial_val=3.4, target_val=-1.6)
|
23
|
-
for t in [0, 9, 10]:
|
24
|
-
assert _isclose(scheduler(t), 3.4)
|
25
|
-
|
26
|
-
for t in [35, 36, 1000]:
|
27
|
-
assert _isclose(scheduler(t), -1.6)
|
28
|
-
|
29
|
-
assert _isclose(scheduler(11), 3.2)
|
30
|
-
assert _isclose(scheduler(27), 0.)
|
31
|
-
assert _isclose(scheduler(34), -1.4)
|
32
|
-
|
33
|
-
|
34
|
-
def test_linear_annealing_ascending():
|
35
|
-
scheduler = KerasLinearAnnealingScheduler(t_start=0, t_end=5, initial_val=-0.5, target_val=1.5)
|
36
|
-
assert _isclose(scheduler(0), -0.5)
|
37
|
-
assert _isclose(scheduler(1), -0.1)
|
38
|
-
assert _isclose(scheduler(4), 1.1)
|
39
|
-
assert _isclose(scheduler(5), 1.5)
|
40
|
-
|
41
|
-
|
42
|
-
@pytest.mark.parametrize('start', [5, -1])
|
43
|
-
def test_invalid(start):
|
44
|
-
with pytest.raises(ValueError):
|
45
|
-
KerasLinearAnnealingScheduler(t_start=start, t_end=4, initial_val=1, target_val=0)
|
46
|
-
|
47
|
-
|
48
|
-
def _isclose(x, y):
|
49
|
-
return np.isclose(x, y)
|
tests_pytest/pytorch/__init__.py
DELETED
@@ -1,14 +0,0 @@
|
|
1
|
-
# Copyright 2024 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
|
-
# ==============================================================================
|
@@ -1,14 +0,0 @@
|
|
1
|
-
# Copyright 2024 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
|
-
# ==============================================================================
|
@@ -1,125 +0,0 @@
|
|
1
|
-
# Copyright 2024 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
|
-
import pytest
|
16
|
-
import torch
|
17
|
-
import numpy as np
|
18
|
-
from torch.utils.data import IterableDataset, Dataset
|
19
|
-
|
20
|
-
from model_compression_toolkit.core.pytorch.data_util import (data_gen_to_dataloader, IterableDatasetFromGenerator,
|
21
|
-
FixedDatasetFromGenerator, FixedSampleInfoDataset)
|
22
|
-
|
23
|
-
|
24
|
-
@pytest.fixture(scope='session')
|
25
|
-
def fixed_dataset():
|
26
|
-
# generate 320 images with data1[i] = i and data2[i] = i+10
|
27
|
-
data1 = np.stack([np.full((3, 30, 20), v) for v in range(320)], axis=0)
|
28
|
-
data2 = np.stack([np.full((10,), v + 10) for v in range(320)], axis=0)
|
29
|
-
return data1, data2
|
30
|
-
|
31
|
-
|
32
|
-
@pytest.fixture
|
33
|
-
def fixed_gen(fixed_dataset):
|
34
|
-
def f():
|
35
|
-
for i in range(10):
|
36
|
-
yield [fixed_dataset[0][32 * i: 32 * (i + 1)], fixed_dataset[1][32 * i: 32 * (i + 1)]]
|
37
|
-
|
38
|
-
return f
|
39
|
-
|
40
|
-
|
41
|
-
def get_random_data_gen_fn(seed=42):
|
42
|
-
""" get gen factory for reproducible gen yielding different samples in each epoch """
|
43
|
-
rng = np.random.default_rng(seed)
|
44
|
-
|
45
|
-
def f():
|
46
|
-
for i in range(10):
|
47
|
-
yield [rng.random((32, 3, 20, 30)), rng.random((32, 10))]
|
48
|
-
return f
|
49
|
-
|
50
|
-
|
51
|
-
class TestDataUtil:
|
52
|
-
create_dataloader_fn = data_gen_to_dataloader
|
53
|
-
|
54
|
-
def test_iterable_dataset_from_fixed_gen(self, fixed_gen):
|
55
|
-
""" tests iterable dataset from fixed gen - same samples are generated in each epoch in the same order """
|
56
|
-
ds = IterableDatasetFromGenerator(fixed_gen)
|
57
|
-
assert isinstance(ds, IterableDataset)
|
58
|
-
self._validate_ds_from_fixed_gen(ds, 320)
|
59
|
-
|
60
|
-
def test_iterable_dataset_from_random_gen(self):
|
61
|
-
""" test that dataset samples over epochs are identical to the original data generator """
|
62
|
-
ds = IterableDatasetFromGenerator(get_random_data_gen_fn())
|
63
|
-
pass1 = torch.stack([t[0] for t in ds], dim=0)
|
64
|
-
pass2 = torch.stack([t[0] for t in ds], dim=0)
|
65
|
-
|
66
|
-
gen_fn = get_random_data_gen_fn()
|
67
|
-
# one invocation is used for validation and batch size in dataset, so promote the reference gen for comparison
|
68
|
-
next(gen_fn())
|
69
|
-
gen_pass1 = np.concatenate([t[0] for t in gen_fn()], axis=0)
|
70
|
-
gen_pass2 = np.concatenate([t[0] for t in gen_fn()], axis=0)
|
71
|
-
# check that each pass is identical to corresponding pass in the original gen
|
72
|
-
assert np.allclose(pass1.cpu().numpy(), gen_pass1)
|
73
|
-
assert np.allclose(pass2.cpu().numpy(), gen_pass2)
|
74
|
-
assert not torch.equal(pass1, pass2)
|
75
|
-
|
76
|
-
def test_fixed_dataset_from_fixed_gen_full(self, fixed_gen):
|
77
|
-
ds = FixedDatasetFromGenerator(fixed_gen)
|
78
|
-
assert isinstance(ds, Dataset) and not isinstance(ds, IterableDataset)
|
79
|
-
self._validate_ds_from_fixed_gen(ds, 320)
|
80
|
-
|
81
|
-
def test_fixed_dataset_from_const_gen_subset(self, fixed_gen):
|
82
|
-
ds = FixedDatasetFromGenerator(fixed_gen, n_samples=25)
|
83
|
-
self._validate_ds_from_fixed_gen(ds, 25)
|
84
|
-
|
85
|
-
def test_fixed_dataset_from_random_gen_full(self):
|
86
|
-
ds = FixedDatasetFromGenerator(get_random_data_gen_fn())
|
87
|
-
self._validate_fixed_ds(ds, exp_len=320, exp_batch_size=32)
|
88
|
-
|
89
|
-
def test_fixed_dataset_from_random_gen_subset(self):
|
90
|
-
ds = FixedDatasetFromGenerator(get_random_data_gen_fn(), n_samples=123)
|
91
|
-
self._validate_fixed_ds(ds, exp_len=123, exp_batch_size=32)
|
92
|
-
|
93
|
-
def test_not_enough_samples_in_datagen(self):
|
94
|
-
def gen():
|
95
|
-
yield [np.ones((10, 3))]
|
96
|
-
with pytest.raises(ValueError, match='Not enough samples in the data generator'):
|
97
|
-
FixedDatasetFromGenerator(gen, n_samples=11)
|
98
|
-
|
99
|
-
def test_extra_info_mismatch(self, fixed_gen):
|
100
|
-
with pytest.raises(ValueError, match='Mismatch in the number of samples between samples and complementary data'):
|
101
|
-
FixedSampleInfoDataset([1]*10, [2]*10, [3]*11)
|
102
|
-
|
103
|
-
@pytest.mark.parametrize('ds_cls', [FixedDatasetFromGenerator, IterableDatasetFromGenerator])
|
104
|
-
def test_invalid_gen(self, ds_cls):
|
105
|
-
def gen():
|
106
|
-
yield np.ones((10, 3))
|
107
|
-
with pytest.raises(TypeError, match='Data generator is expected to yield a list of tensors'):
|
108
|
-
ds_cls(gen)
|
109
|
-
|
110
|
-
def _validate_ds_from_fixed_gen(self, ds, exp_len):
|
111
|
-
for _ in range(2):
|
112
|
-
for i, sample in enumerate(ds):
|
113
|
-
assert np.array_equal(sample[0].cpu().numpy(), np.full((3, 30, 20), i))
|
114
|
-
assert np.array_equal(sample[1].cpu().numpy(), np.full((10,), i + 10))
|
115
|
-
assert i == exp_len - 1
|
116
|
-
assert ds.orig_batch_size == 32
|
117
|
-
assert len(ds) == exp_len
|
118
|
-
|
119
|
-
def _validate_fixed_ds(self, ds, exp_len, exp_batch_size):
|
120
|
-
assert isinstance(ds, torch.utils.data.Dataset) and not isinstance(ds, torch.utils.data.IterableDataset)
|
121
|
-
full_pass1 = torch.concat([t[0] for t in ds], dim=0)
|
122
|
-
full_pass2 = torch.concat([t[0] for t in ds], dim=0)
|
123
|
-
assert torch.equal(full_pass1, full_pass2)
|
124
|
-
assert len(ds) == exp_len
|
125
|
-
assert ds.orig_batch_size == exp_batch_size
|
@@ -1,14 +0,0 @@
|
|
1
|
-
# Copyright 2024 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
|
-
# ==============================================================================
|
@@ -1,40 +0,0 @@
|
|
1
|
-
# Copyright 2024 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
|
-
import pytest
|
16
|
-
|
17
|
-
from model_compression_toolkit.gptq import QFractionLinearAnnealingConfig
|
18
|
-
|
19
|
-
|
20
|
-
def test_linear_annealing_cfg_validation():
|
21
|
-
with pytest.raises(ValueError, match='Expected.* target_q_fraction <= 1'):
|
22
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0.1, target_q_fraction=1.1, start_step=0, end_step=None)
|
23
|
-
|
24
|
-
with pytest.raises(ValueError, match='Expected.* 0 <= initial_q_fraction'):
|
25
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=-0.1, target_q_fraction=-0.9, start_step=0, end_step=100)
|
26
|
-
|
27
|
-
with pytest.raises(ValueError, match='Expected.* initial_q_fraction < target_q_fraction'):
|
28
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0.1, target_q_fraction=0.1, start_step=0, end_step=100)
|
29
|
-
|
30
|
-
with pytest.raises(ValueError, match='Expected.* initial_q_fraction < target_q_fraction'):
|
31
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0.2, target_q_fraction=0.1, start_step=0, end_step=100)
|
32
|
-
|
33
|
-
with pytest.raises(ValueError, match='Expected.* start_step >= 0'):
|
34
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0, target_q_fraction=1, start_step=-1, end_step=100)
|
35
|
-
|
36
|
-
with pytest.raises(ValueError, match='Expected.* start_step < end_step'):
|
37
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0, target_q_fraction=1, start_step=100, end_step=100)
|
38
|
-
|
39
|
-
with pytest.raises(ValueError, match='Expected.* start_step < end_step'):
|
40
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0, target_q_fraction=1, start_step=100, end_step=99)
|
@@ -1,100 +0,0 @@
|
|
1
|
-
# Copyright 2024 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 unittest.mock import Mock
|
16
|
-
|
17
|
-
import pytest
|
18
|
-
import torch
|
19
|
-
|
20
|
-
from model_compression_toolkit.core.pytorch.pytorch_device_config import get_working_device
|
21
|
-
from model_compression_toolkit.trainable_infrastructure.pytorch.annealing_schedulers import PytorchLinearAnnealingScheduler
|
22
|
-
from model_compression_toolkit.gptq import GradientPTQConfig, GradualActivationQuantizationConfig, QFractionLinearAnnealingConfig
|
23
|
-
from model_compression_toolkit.gptq.common.gradual_activation_quantization import (
|
24
|
-
GradualActivationQuantizerWrapper, get_gradual_activation_quantizer_wrapper_factory)
|
25
|
-
|
26
|
-
|
27
|
-
@pytest.fixture
|
28
|
-
def x():
|
29
|
-
return torch.randn((2, 5, 6, 7), generator=torch.Generator().manual_seed(42)).to(device=get_working_device())
|
30
|
-
|
31
|
-
|
32
|
-
class Quantizer:
|
33
|
-
def __call__(self, x, training):
|
34
|
-
self.training = training
|
35
|
-
return 3*x + 1
|
36
|
-
|
37
|
-
|
38
|
-
class TestGradualActivationQuantization:
|
39
|
-
|
40
|
-
def test_gradual_act_quant_wrapper(self, x):
|
41
|
-
quantizer = Quantizer()
|
42
|
-
qw = GradualActivationQuantizerWrapper(quantizer, q_fraction_scheduler=lambda t: t / (t + 1))
|
43
|
-
|
44
|
-
y0, y1, y2 = [qw(x) for _ in range(3)]
|
45
|
-
assert torch.equal(y0, x) # t=0
|
46
|
-
assert torch.allclose(y1, 0.5 * x + (1.5 * x + 0.5)) # t=1
|
47
|
-
assert torch.allclose(y2, x / 3 + (2 * x + 2 / 3)) # t=2
|
48
|
-
assert quantizer.training is True
|
49
|
-
|
50
|
-
_ = qw(x, False)
|
51
|
-
assert quantizer.training is False # correct flag was propagated
|
52
|
-
|
53
|
-
def test_factory_no_qdrop(self):
|
54
|
-
quantizer_wrapper, quantizer = self._run_factory_test(qdrop_cfg=None, get_grad_steps_fn=None)
|
55
|
-
assert quantizer_wrapper is quantizer
|
56
|
-
|
57
|
-
@pytest.mark.parametrize('end_step', (20, None))
|
58
|
-
def test_factory_linear(self, x, end_step):
|
59
|
-
qdrop_cfg = GradualActivationQuantizationConfig(
|
60
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0.3, target_q_fraction=0.8, start_step=10, end_step=end_step)
|
61
|
-
)
|
62
|
-
|
63
|
-
def get_total_steps():
|
64
|
-
if end_step is None:
|
65
|
-
return 50
|
66
|
-
assert False # should not be called if end_step is passed
|
67
|
-
|
68
|
-
quantizer_wrapper, quantizer = self._run_factory_test(qdrop_cfg, get_total_steps)
|
69
|
-
|
70
|
-
scheduler = quantizer_wrapper.q_fraction_scheduler
|
71
|
-
assert isinstance(scheduler, PytorchLinearAnnealingScheduler)
|
72
|
-
exp_end_step = 50 if end_step is None else end_step
|
73
|
-
assert scheduler.t_start == 10
|
74
|
-
assert scheduler.t_end == exp_end_step
|
75
|
-
assert scheduler.initial_val == 0.3
|
76
|
-
assert scheduler.target_val == 0.8
|
77
|
-
|
78
|
-
y = [quantizer_wrapper(x) for _ in range(exp_end_step+1)]
|
79
|
-
assert torch.allclose(y[9], 0.7 * x + 0.3 * quantizer(x, True))
|
80
|
-
assert torch.allclose(y[10], 0.7 * x + 0.3 * quantizer(x, True))
|
81
|
-
assert torch.allclose(y[-1], 0.2 * x + 0.8 * quantizer(x, True))
|
82
|
-
|
83
|
-
def test_factory_linear_common_case(self, x):
|
84
|
-
# validate that we actually implemented the right thing - on first call float input, on last call fully quantized
|
85
|
-
qdrop_cfg = GradualActivationQuantizationConfig(
|
86
|
-
QFractionLinearAnnealingConfig(initial_q_fraction=0, target_q_fraction=1, start_step=0, end_step=None)
|
87
|
-
)
|
88
|
-
quantizer_wrapper, quantizer = self._run_factory_test(qdrop_cfg, lambda: 15)
|
89
|
-
y0, *_, y_last = [quantizer_wrapper(x) for _ in range(16)]
|
90
|
-
assert torch.equal(y0, x)
|
91
|
-
assert torch.allclose(y_last, quantizer(x, True))
|
92
|
-
|
93
|
-
def _run_factory_test(self, qdrop_cfg, get_grad_steps_fn):
|
94
|
-
# Mocks are used to just pass anything
|
95
|
-
gptq_cfg = GradientPTQConfig(n_epochs=5, optimizer=Mock(), loss=Mock(),
|
96
|
-
gradual_activation_quantization_config=qdrop_cfg)
|
97
|
-
factory = get_gradual_activation_quantizer_wrapper_factory(gptq_cfg, get_grad_steps_fn, PytorchLinearAnnealingScheduler)
|
98
|
-
quantizer = Quantizer()
|
99
|
-
quantizer_wrapper = factory(quantizer)
|
100
|
-
return quantizer_wrapper, quantizer
|
@@ -1,14 +0,0 @@
|
|
1
|
-
# Copyright 2024 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
|
-
# ==============================================================================
|
@@ -1,49 +0,0 @@
|
|
1
|
-
# Copyright 2024 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
|
-
import torch
|
16
|
-
import pytest
|
17
|
-
|
18
|
-
from model_compression_toolkit.trainable_infrastructure.pytorch.annealing_schedulers import PytorchLinearAnnealingScheduler
|
19
|
-
|
20
|
-
|
21
|
-
def test_linear_annealing():
|
22
|
-
scheduler = PytorchLinearAnnealingScheduler(t_start=10, t_end=35, initial_val=3.4, target_val=-1.6)
|
23
|
-
for t in [0, 9, 10]:
|
24
|
-
assert _isclose(scheduler(t), 3.4)
|
25
|
-
|
26
|
-
for t in [35, 36, 1000]:
|
27
|
-
assert _isclose(scheduler(t), -1.6)
|
28
|
-
|
29
|
-
assert _isclose(scheduler(11), 3.2)
|
30
|
-
assert _isclose(scheduler(27), 0.)
|
31
|
-
assert _isclose(scheduler(34), -1.4)
|
32
|
-
|
33
|
-
|
34
|
-
def test_linear_annealing_ascending():
|
35
|
-
scheduler = PytorchLinearAnnealingScheduler(t_start=0, t_end=5, initial_val=-0.5, target_val=1.5)
|
36
|
-
assert _isclose(scheduler(0), -0.5)
|
37
|
-
assert _isclose(scheduler(1), -0.1)
|
38
|
-
assert _isclose(scheduler(4), 1.1)
|
39
|
-
assert _isclose(scheduler(5), 1.5)
|
40
|
-
|
41
|
-
|
42
|
-
@pytest.mark.parametrize('start', [5, -1])
|
43
|
-
def test_invalid(start):
|
44
|
-
with pytest.raises(ValueError):
|
45
|
-
PytorchLinearAnnealingScheduler(t_start=start, t_end=4, initial_val=1, target_val=0)
|
46
|
-
|
47
|
-
|
48
|
-
def _isclose(x, y):
|
49
|
-
return torch.isclose(x, torch.tensor(y))
|
{mct_nightly-2.2.0.20241106.458.dist-info → mct_nightly-2.2.0.20241107.459.dist-info}/LICENSE.md
RENAMED
File without changes
|
File without changes
|