Skip to content

Commit d53c8fc

Browse files
yiliu30zehao-intel
authored andcommitted
Adjust the hyperopt and sigopt as extras requirements (#173)
Signed-off-by: zehao-intel <[email protected]>
1 parent 189a055 commit d53c8fc

File tree

5 files changed

+43
-25
lines changed

5 files changed

+43
-25
lines changed

neural_compressor/contrib/strategy/sigopt.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,14 @@
1717

1818
import copy
1919
from neural_compressor.utils import logger
20+
from neural_compressor.utils.utility import LazyImport
2021
from neural_compressor.strategy.strategy import strategy_registry, TuneStrategy
21-
from sigopt import Connection
2222
from collections import OrderedDict
2323
from neural_compressor.strategy.st_utils.tuning_sampler import OpWiseTuningSampler
2424
from neural_compressor.strategy.st_utils.tuning_structs import OpTuningConfig
2525

26+
sigopt = LazyImport('sigopt')
27+
2628
@strategy_registry
2729
class SigOptTuneStrategy(TuneStrategy):
2830
"""The tuning strategy using SigOpt HPO search in tuning space.
@@ -80,7 +82,15 @@ def __init__(self, model, conf, q_dataloader, q_func=None,
8082
eval_func,
8183
dicts,
8284
q_hooks)
83-
85+
# Initialize the SigOpt tuning strategy if the user specified to use it.
86+
strategy_name = conf.usr_cfg.tuning.strategy.name
87+
if strategy_name.lower() == "sigopt":
88+
try:
89+
import sigopt
90+
except ImportError:
91+
ImportError(f"Please install sigopt for using {strategy_name} strategy.")
92+
else:
93+
pass
8494
# SigOpt init
8595
client_token = conf.usr_cfg.tuning.strategy.sigopt_api_token
8696
self.project_id = conf.usr_cfg.tuning.strategy.sigopt_project_id
@@ -107,7 +117,7 @@ def __init__(self, model, conf, q_dataloader, q_func=None,
107117
else:
108118
logger.info("Experiment name is {}.".format(self.experiment_name))
109119

110-
self.conn = Connection(client_token)
120+
self.conn = sigopt.Connection(client_token)
111121
self.experiment = None
112122

113123
def params_to_tune_configs(self, params):

neural_compressor/contrib/strategy/tpe.py

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,14 @@
2020
from pathlib import Path
2121
from functools import partial
2222
import numpy as np
23-
import hyperopt as hpo
24-
from hyperopt import fmin, hp, STATUS_OK, Trials
2523
from neural_compressor.utils import logger
24+
from neural_compressor.utils.utility import LazyImport
2625
from neural_compressor.strategy.strategy import strategy_registry, TuneStrategy
2726
from collections import OrderedDict
2827
from neural_compressor.strategy.st_utils.tuning_sampler import OpWiseTuningSampler
2928
from neural_compressor.strategy.st_utils.tuning_structs import OpTuningConfig
3029

30+
hyperopt = LazyImport('hyperopt')
3131

3232
try:
3333
import pandas as pd
@@ -85,10 +85,19 @@ def __init__(self, model, conf, q_dataloader, q_func=None,
8585
eval_dataloader=None, eval_func=None, dicts=None, q_hooks=None):
8686
assert conf.usr_cfg.quantization.approach == 'post_training_static_quant', \
8787
"TPE strategy is only for post training static quantization!"
88+
# Initialize the tpe tuning strategy if the user specified to use it.
89+
strategy_name = conf.usr_cfg.tuning.strategy.name
90+
if strategy_name.lower() == "tpe":
91+
try:
92+
import hyperopt
93+
except ImportError:
94+
raise ImportError(f"Please install hyperopt for using {strategy_name} strategy.")
95+
else:
96+
pass
8897
self.hpopt_search_space = None
8998
self.warm_start = False
9099
self.cfg_evaluated = False
91-
self.hpopt_trials = Trials()
100+
self.hpopt_trials = hyperopt.Trials()
92101
self.max_trials = conf.usr_cfg.tuning.exit_policy.get('max_trials', 200)
93102
self.loss_function_config = {
94103
'acc_th': conf.usr_cfg.tuning.accuracy_criterion.relative if \
@@ -140,7 +149,7 @@ def __getstate__(self):
140149
def _configure_hpopt_search_space_and_params(self, search_space):
141150
self.hpopt_search_space = {}
142151
for param, configs in search_space.items():
143-
self.hpopt_search_space[(param)] = hp.choice((param[0]), configs)
152+
self.hpopt_search_space[(param)] = hyperopt.hp.choice((param[0]), configs)
144153
# Find minimum number of choices for params with more than one choice
145154
multichoice_params = [len(configs) for param, configs in search_space.items()
146155
if len(configs) > 1]
@@ -149,7 +158,7 @@ def _configure_hpopt_search_space_and_params(self, search_space):
149158
min_param_size = min(multichoice_params) if len(multichoice_params) > 0 else 1
150159
self.tpe_params['n_EI_candidates'] = min_param_size
151160
self.tpe_params['prior_weight'] = 1 / min_param_size
152-
self._algo = partial(hpo.tpe.suggest,
161+
self._algo = partial(hyperopt.tpe.suggest,
153162
n_startup_jobs=self.tpe_params['n_initial_point'],
154163
gamma=self.tpe_params['gamma'],
155164
n_EI_candidates=self.tpe_params['n_EI_candidates'],
@@ -225,12 +234,12 @@ def initial_op_quant_mode(items_lst, target_quant_mode, op_item_dtype_dict):
225234
self._configure_hpopt_search_space_and_params(first_run_cfg)
226235
# Run first iteration with best result from history
227236
trials_count = len(self.hpopt_trials.trials) + 1
228-
fmin(partial(self.object_evaluation, model=self.model),
229-
space=self.hpopt_search_space,
230-
algo=self._algo,
231-
max_evals=trials_count,
232-
trials=self.hpopt_trials,
233-
show_progressbar=False)
237+
hyperopt.fmin(partial(self.object_evaluation, model=self.model),
238+
space=self.hpopt_search_space,
239+
algo=self._algo,
240+
max_evals=trials_count,
241+
trials=self.hpopt_trials,
242+
show_progressbar=False)
234243
if pd is not None:
235244
self._save_trials(trials_file)
236245
self._update_best_result(best_result_file)
@@ -266,12 +275,12 @@ def initial_op_quant_mode(items_lst, target_quant_mode, op_item_dtype_dict):
266275
self.cfg_evaluated = False
267276
logger.debug("Trial iteration start: {} / {}.".format(
268277
trials_count, self.max_trials))
269-
fmin(partial(self.object_evaluation, model=self.model),
270-
space=self.hpopt_search_space,
271-
algo=self._algo,
272-
max_evals=trials_count,
273-
trials=self.hpopt_trials,
274-
show_progressbar=False)
278+
hyperopt.fmin(partial(self.object_evaluation, model=self.model),
279+
space=self.hpopt_search_space,
280+
algo=self._algo,
281+
max_evals=trials_count,
282+
trials=self.hpopt_trials,
283+
show_progressbar=False)
275284
trials_count += 1
276285
if pd is not None:
277286
self._save_trials(trials_file)
@@ -349,7 +358,7 @@ def _compute_metrics(self, tune_cfg, acc, lat):
349358
'acc_loss': acc_diff,
350359
'lat_diff': lat_diff,
351360
'quantization_ratio': quantization_ratio,
352-
'status': STATUS_OK}
361+
'status': hyperopt.STATUS_OK}
353362

354363
def _calculate_acc_lat_diff(self, acc, lat):
355364
int8_acc = acc

requirements.txt

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ scikit-image
77
matplotlib
88
schema
99
py-cpuinfo
10-
hyperopt
1110
contextlib2
1211
requests
1312
Flask
@@ -20,7 +19,6 @@ Pillow
2019
pycocotools-windows; sys_platform != 'linux'
2120
pycocotools; sys_platform == 'linux'
2221
opencv-python
23-
sigopt
2422
prettytable
2523
cryptography
2624
sqlalchemy==1.4.27

setup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@
3636

3737
# define install requirements
3838
install_requires_list = [
39-
'numpy', 'pyyaml', 'scikit-learn', 'schema', 'py-cpuinfo', 'hyperopt', 'pandas', 'pycocotools',
40-
'opencv-python', 'requests', 'psutil', 'Pillow', 'sigopt', 'prettytable', 'cryptography', 'Cython',
39+
'numpy', 'pyyaml', 'scikit-learn', 'schema', 'py-cpuinfo', 'pandas', 'pycocotools',
40+
'opencv-python', 'requests', 'psutil', 'Pillow', 'prettytable', 'cryptography', 'Cython',
4141
'deprecated']
4242
ux_install_requires_list = [
4343
'Flask-Cors', 'Flask-SocketIO', 'Flask', 'gevent-websocket', 'gevent','sqlalchemy==1.4.27', 'alembic==1.7.7']

test/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ transformers<=4.12.3; python_version < '3.10'
1414
transformers==4.16.0; python_version == '3.10'
1515
tensorflow_model_optimization
1616
sigopt
17+
hyperopt
1718
horovod
1819
tensorflow-addons
1920
onnxruntime-extensions; python_version < '3.10'

0 commit comments

Comments
 (0)