-
Notifications
You must be signed in to change notification settings - Fork 281
/
base_task.py
2089 lines (1843 loc) · 94 KB
/
base_task.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import json
import logging.handlers
import math
import multiprocessing
import os
import platform
import sys
import tempfile
import time
import typing
import unittest.mock
import warnings
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from ConfigSpace.configuration_space import Configuration, ConfigurationSpace
import dask
import dask.distributed
import joblib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from smac.runhistory.runhistory import DataOrigin, RunHistory, RunInfo, RunValue
from smac.stats.stats import Stats
from smac.tae import StatusType
from autoPyTorch import metrics
from autoPyTorch.automl_common.common.utils.backend import Backend, create
from autoPyTorch.constants import (
FORECASTING_BUDGET_TYPE,
FORECASTING_TASKS,
REGRESSION_TASKS,
STRING_TO_OUTPUT_TYPES,
STRING_TO_TASK_TYPES,
TIMESERIES_FORECASTING,
)
from autoPyTorch.data.base_validator import BaseInputValidator
from autoPyTorch.data.utils import DatasetCompressionSpec
from autoPyTorch.datasets.base_dataset import BaseDataset, BaseDatasetPropertiesType
from autoPyTorch.datasets.resampling_strategy import (
CrossValTypes,
HoldoutValTypes,
NoResamplingStrategyTypes,
ResamplingStrategies,
)
from autoPyTorch.ensemble.ensemble_builder import EnsembleBuilderManager
from autoPyTorch.ensemble.singlebest_ensemble import SingleBest
from autoPyTorch.evaluation.tae import ExecuteTaFuncWithQueue, get_cost_of_crash
from autoPyTorch.evaluation.utils import DisableFileOutputParameters
from autoPyTorch.optimizer.smbo import AutoMLSMBO
from autoPyTorch.pipeline.base_pipeline import BasePipeline
from autoPyTorch.pipeline.components.setup.traditional_ml.traditional_learner import get_available_traditional_learners
from autoPyTorch.pipeline.components.training.metrics.base import autoPyTorchMetric
from autoPyTorch.pipeline.components.training.metrics.utils import calculate_score, get_metrics
from autoPyTorch.utils.common import FitRequirement, dict_repr, replace_string_bool_to_bool
from autoPyTorch.utils.hyperparameter_search_space_update import HyperparameterSearchSpaceUpdates
from autoPyTorch.utils.logging_ import (
PicklableClientLogger,
get_named_client_logger,
setup_logger,
start_log_server,
)
from autoPyTorch.utils.parallel import preload_modules
from autoPyTorch.utils.parallel_model_runner import run_models_on_dataset
from autoPyTorch.utils.pipeline import get_configuration_space, get_dataset_requirements
from autoPyTorch.utils.results_manager import MetricResults, ResultsManager, SearchResults
from autoPyTorch.utils.results_visualizer import ColorLabelSettings, PlotSettingParams, ResultsVisualizer
from autoPyTorch.utils.single_thread_client import SingleThreadedClient
from autoPyTorch.utils.stopwatch import StopWatch
def _pipeline_predict(pipeline: BasePipeline,
X: Union[np.ndarray, pd.DataFrame],
batch_size: int,
logger: PicklableClientLogger,
task: int,
task_type: str = "") -> np.ndarray:
@typing.no_type_check
def send_warnings_to_log(
message, category, filename, lineno, file=None, line=None):
logger.debug('%s:%s: %s:%s' % (filename, lineno, category.__name__, message))
return
X_ = X.copy()
with warnings.catch_warnings():
warnings.showwarning = send_warnings_to_log
if task in REGRESSION_TASKS or task in FORECASTING_TASKS:
# Voting regressor does not support batch size
prediction = pipeline.predict(X_)
else:
# Voting classifier predict proba does not support batch size
prediction = pipeline.predict_proba(X_)
# Check that all probability values lie between 0 and 1.
if not ((prediction >= 0).all() and (prediction <= 1).all()):
np.set_printoptions(threshold=sys.maxsize)
raise ValueError("For {}, prediction probability not within [0, 1]: {}/{}!".format(
pipeline,
prediction,
np.sum(prediction, axis=1)
))
if STRING_TO_TASK_TYPES.get(task_type, -1) != TIMESERIES_FORECASTING:
if len(prediction.shape) < 1 or len(X_.shape) < 1 or \
X_.shape[0] < 1 or prediction.shape[0] != X_.shape[0]:
logger.warning(
"Prediction shape for model %s is %s while X_.shape is %s",
pipeline, str(prediction.shape), str(X_.shape)
)
return prediction
class BaseTask(ABC):
"""
Base class for the tasks that serve as API to the pipelines.
Args:
seed (int: default=1):
Seed to be used for reproducibility.
n_jobs (int: default=1):
Number of consecutive processes to spawn.
n_threads (int: default=1):
Number of threads to use for each process.
logging_config (Optional[Dict]):
Specifies configuration for logging, if None, it is loaded from the logging.yaml
ensemble_size (int: default=50):
Number of models added to the ensemble built by
Ensemble selection from libraries of models.
Models are drawn with replacement.
ensemble_nbest (int: default=50):
Only consider the ensemble_nbest models to build the ensemble
max_models_on_disc (int: default=50):
Maximum number of models saved to disc. It also controls the size of
the ensemble as any additional models will be deleted.
Must be greater than or equal to 1.
temporary_directory (str):
Folder to store configuration output and log file
output_directory (str):
Folder to store predictions for optional test set
delete_tmp_folder_after_terminate (bool):
Determines whether to delete the temporary directory,
when finished
include_components (Optional[Dict[str, Any]]):
Dictionary containing components to include. Key is the node
name and Value is an Iterable of the names of the components
to include. Only these components will be present in the
search space.
exclude_components (Optional[Dict[str, Any]]):
Dictionary containing components to exclude. Key is the node
name and Value is an Iterable of the names of the components
to exclude. All except these components will be present in
the search space.
resampling_strategy resampling_strategy (RESAMPLING_STRATEGIES),
(default=HoldoutValTypes.holdout_validation):
strategy to split the training data.
resampling_strategy_args (Optional[Dict[str, Any]]): arguments
required for the chosen resampling strategy. If None, uses
the default values provided in DEFAULT_RESAMPLING_PARAMETERS
in ```datasets/resampling_strategy.py```.
search_space_updates (Optional[HyperparameterSearchSpaceUpdates]):
Search space updates that can be used to modify the search
space of particular components or choice modules of the pipeline
"""
def __init__(
self,
seed: int = 1,
n_jobs: int = 1,
n_threads: int = 1,
logging_config: Optional[Dict] = None,
ensemble_size: int = 50,
ensemble_nbest: int = 50,
max_models_on_disc: int = 50,
temporary_directory: Optional[str] = None,
output_directory: Optional[str] = None,
delete_tmp_folder_after_terminate: bool = True,
delete_output_folder_after_terminate: bool = True,
include_components: Optional[Dict[str, Any]] = None,
exclude_components: Optional[Dict[str, Any]] = None,
backend: Optional[Backend] = None,
resampling_strategy: ResamplingStrategies = HoldoutValTypes.holdout_validation,
resampling_strategy_args: Optional[Dict[str, Any]] = None,
search_space_updates: Optional[HyperparameterSearchSpaceUpdates] = None,
task_type: Optional[str] = None
) -> None:
if isinstance(resampling_strategy, NoResamplingStrategyTypes) and ensemble_size != 0:
raise ValueError("`NoResamplingStrategy` cannot be used for ensemble construction")
self.seed = seed
self.n_jobs = n_jobs
self.n_threads = n_threads
self.ensemble_size = ensemble_size
self.ensemble_nbest = ensemble_nbest
self.max_models_on_disc = max_models_on_disc
self.logging_config: Optional[Dict] = logging_config
self.include_components: Optional[Dict] = include_components
self.exclude_components: Optional[Dict] = exclude_components
self._temporary_directory = temporary_directory
self._output_directory = output_directory
if backend is not None:
self._backend = backend
else:
self._backend = create(
prefix='autoPyTorch',
temporary_directory=self._temporary_directory,
output_directory=self._output_directory,
delete_tmp_folder_after_terminate=delete_tmp_folder_after_terminate,
delete_output_folder_after_terminate=delete_output_folder_after_terminate,
)
self.task_type = task_type or ""
self._stopwatch = StopWatch()
self.pipeline_options = replace_string_bool_to_bool(json.load(open(
os.path.join(os.path.dirname(__file__), '../configs/default_pipeline_options.json'))))
self.search_space: Optional[ConfigurationSpace] = None
self._dataset_requirements: Optional[List[FitRequirement]] = None
self._metric: Optional[autoPyTorchMetric] = None
self._metrics_kwargs: Dict = {}
self._scoring_functions: Optional[List[autoPyTorchMetric]] = None
self._logger: Optional[PicklableClientLogger] = None
self.dataset_name: Optional[str] = None
self.cv_models_: Dict = {}
self._results_manager = ResultsManager()
# By default try to use the TCP logging port or get a new port
self._logger_port = logging.handlers.DEFAULT_TCP_LOGGING_PORT
# Store the resampling strategy from the dataset, to load models as needed
self.resampling_strategy = resampling_strategy
self.resampling_strategy_args = resampling_strategy_args
self.stop_logging_server: Optional[multiprocessing.synchronize.Event] = None
# Single core, local runs should use fork
# to prevent the __main__ requirements in
# examples. Nevertheless, multi-process runs
# have spawn as requirement to reduce the
# possibility of a deadlock
self._dask_client: Optional[dask.distributed.Client] = None
self._multiprocessing_context = 'forkserver'
if self.n_jobs == 1:
self._multiprocessing_context = 'fork'
self.input_validator: Optional[BaseInputValidator] = None
self.search_space_updates = search_space_updates
if search_space_updates is not None:
if not isinstance(self.search_space_updates,
HyperparameterSearchSpaceUpdates):
raise ValueError("Expected search space updates to be of instance"
" HyperparameterSearchSpaceUpdates got {}".format(type(self.search_space_updates)))
@abstractmethod
def build_pipeline(
self,
dataset_properties: Dict[str, BaseDatasetPropertiesType],
include_components: Optional[Dict[str, Any]] = None,
exclude_components: Optional[Dict[str, Any]] = None,
search_space_updates: Optional[HyperparameterSearchSpaceUpdates] = None
) -> BasePipeline:
"""
Build pipeline according to current task
and for the passed dataset properties
Args:
dataset_properties (Dict[str, Any]):
Characteristics of the dataset to guide the pipeline
choices of components
include_components (Optional[Dict[str, Any]]):
Dictionary containing components to include. Key is the node
name and Value is an Iterable of the names of the components
to include. Only these components will be present in the
search space.
exclude_components (Optional[Dict[str, Any]]):
Dictionary containing components to exclude. Key is the node
name and Value is an Iterable of the names of the components
to exclude. All except these components will be present in
the search space.
search_space_updates (Optional[HyperparameterSearchSpaceUpdates]):
Search space updates that can be used to modify the search
space of particular components or choice modules of the pipeline
Returns:
BasePipeline
"""
raise NotImplementedError("Function called on BaseTask, this can only be called by "
"specific task which is a child of the BaseTask")
@abstractmethod
def _get_dataset_input_validator(
self,
X_train: Union[List, pd.DataFrame, np.ndarray],
y_train: Union[List, pd.DataFrame, np.ndarray],
X_test: Optional[Union[List, pd.DataFrame, np.ndarray]] = None,
y_test: Optional[Union[List, pd.DataFrame, np.ndarray]] = None,
resampling_strategy: Optional[ResamplingStrategies] = None,
resampling_strategy_args: Optional[Dict[str, Any]] = None,
dataset_name: Optional[str] = None,
dataset_compression: Optional[DatasetCompressionSpec] = None,
**kwargs: Any
) -> Tuple[BaseDataset, BaseInputValidator]:
"""
Returns an object of a child class of `BaseDataset` and
an object of a child class of `BaseInputValidator` according
to the current task.
Args:
X_train (Union[List, pd.DataFrame, np.ndarray]):
Training feature set.
y_train (Union[List, pd.DataFrame, np.ndarray]):
Training target set.
X_test (Optional[Union[List, pd.DataFrame, np.ndarray]]):
Testing feature set
y_test (Optional[Union[List, pd.DataFrame, np.ndarray]]):
Testing target set
resampling_strategy (Optional[RESAMPLING_STRATEGIES]):
Strategy to split the training data. if None, uses
HoldoutValTypes.holdout_validation.
resampling_strategy_args (Optional[Dict[str, Any]]):
arguments required for the chosen resampling strategy. If None, uses
the default values provided in DEFAULT_RESAMPLING_PARAMETERS
in ```datasets/resampling_strategy.py```.
dataset_name (Optional[str]):
name of the dataset, used as experiment name.
dataset_compression (Optional[DatasetCompressionSpec]):
specifications for dataset compression. For more info check
documentation for `BaseTask.get_dataset`.
Returns:
BaseDataset:
the dataset object
BaseInputValidator:
fitted input validator
"""
raise NotImplementedError
def get_dataset(
self,
X_train: Union[List, pd.DataFrame, np.ndarray],
y_train: Union[List, pd.DataFrame, np.ndarray],
X_test: Optional[Union[List, pd.DataFrame, np.ndarray]] = None,
y_test: Optional[Union[List, pd.DataFrame, np.ndarray]] = None,
resampling_strategy: Optional[ResamplingStrategies] = None,
resampling_strategy_args: Optional[Dict[str, Any]] = None,
dataset_name: Optional[str] = None,
dataset_compression: Optional[DatasetCompressionSpec] = None,
**kwargs: Any
) -> BaseDataset:
"""
Returns an object of a child class of `BaseDataset` according to the current task.
Args:
X_train (Union[List, pd.DataFrame, np.ndarray]):
Training feature set.
y_train (Union[List, pd.DataFrame, np.ndarray]):
Training target set.
X_test (Optional[Union[List, pd.DataFrame, np.ndarray]]):
Testing feature set
y_test (Optional[Union[List, pd.DataFrame, np.ndarray]]):
Testing target set
resampling_strategy (Optional[RESAMPLING_STRATEGIES]):
Strategy to split the training data. if None, uses
HoldoutValTypes.holdout_validation.
resampling_strategy_args (Optional[Dict[str, Any]]):
arguments required for the chosen resampling strategy. If None, uses
the default values provided in DEFAULT_RESAMPLING_PARAMETERS
in ```datasets/resampling_strategy.py```.
dataset_name (Optional[str]):
name of the dataset, used as experiment name.
dataset_compression (Optional[DatasetCompressionSpec]):
We compress datasets so that they fit into some predefined amount of memory.
**NOTE**
You can also pass your own configuration with the same keys and choosing
from the available ``"methods"``.
The available options are described here:
**memory_allocation**
Absolute memory in MB, e.g. 10MB is ``"memory_allocation": 10``.
The memory used by the dataset is checked after each reduction method is
performed. If the dataset fits into the allocated memory, any further methods
listed in ``"methods"`` will not be performed.
It can be either float or int.
**methods**
We currently provide the following methods for reducing the dataset size.
These can be provided in a list and are performed in the order as given.
* ``"precision"`` -
We reduce floating point precision as follows:
* ``np.float128 -> np.float64``
* ``np.float96 -> np.float64``
* ``np.float64 -> np.float32``
* pandas dataframes are reduced using the downcast option of `pd.to_numeric`
to the lowest possible precision.
* ``subsample`` -
We subsample data such that it **fits directly into
the memory allocation** ``memory_allocation * memory_limit``.
Therefore, this should likely be the last method listed in
``"methods"``.
Subsampling takes into account classification labels and stratifies
accordingly. We guarantee that at least one occurrence of each
label is included in the sampled set.
kwargs (Any):
can be used to pass task specific dataset arguments. Currently supports
passing `feat_types` for tabular tasks which specifies whether a feature is
'numerical' or 'categorical'.
Returns:
BaseDataset:
the dataset object
"""
dataset, _ = self._get_dataset_input_validator(
X_train=X_train,
y_train=y_train,
X_test=X_test,
y_test=y_test,
resampling_strategy=resampling_strategy,
resampling_strategy_args=resampling_strategy_args,
dataset_name=dataset_name,
dataset_compression=dataset_compression,
**kwargs)
return dataset
@property
def run_history(self) -> RunHistory:
return self._results_manager.run_history
@property
def ensemble_performance_history(self) -> List[Dict[str, Any]]:
return self._results_manager.ensemble_performance_history
@property
def trajectory(self) -> Optional[List]:
return self._results_manager.trajectory
def set_pipeline_options(self, **pipeline_options_kwargs: Any) -> None:
"""
Check whether arguments are valid and
then sets them to the current pipeline
configuration.
Args:
**pipeline_options_kwargs: Valid config options include "num_run",
"device", "budget_type", "epochs", "runtime", "torch_num_threads",
"early_stopping", "use_tensorboard_logger",
"metrics_during_training"
Returns:
None
"""
unknown_keys = []
for option, value in pipeline_options_kwargs.items():
if option in self.pipeline_options.keys():
pass
else:
unknown_keys.append(option)
if len(unknown_keys) > 0:
raise ValueError("Invalid configuration arguments given {},"
" expected arguments to be in {}".
format(unknown_keys, self.pipeline_options.keys()))
self.pipeline_options.update(pipeline_options_kwargs)
def get_pipeline_options(self) -> dict:
"""
Returns the current pipeline configuration.
"""
return self.pipeline_options
def get_search_space(self, dataset: BaseDataset = None) -> ConfigurationSpace:
"""
Returns the current search space as ConfigurationSpace object.
"""
if self.search_space is not None:
return self.search_space
elif dataset is not None:
dataset_requirements = get_dataset_requirements(
info=dataset.get_required_dataset_info(),
include=self.include_components,
exclude=self.exclude_components,
search_space_updates=self.search_space_updates)
return get_configuration_space(info=dataset.get_dataset_properties(dataset_requirements),
include=self.include_components,
exclude=self.exclude_components,
search_space_updates=self.search_space_updates)
raise ValueError("No search space initialised and no dataset passed. "
"Can't create default search space without the dataset")
def _get_logger(self, name: str) -> PicklableClientLogger:
"""
Instantiates the logger used throughout the experiment
Args:
name (str):
Name of the log file, usually the dataset name
Returns:
PicklableClientLogger
"""
logger_name = 'AutoPyTorch:%s:%d' % (name, self.seed)
# Setup the configuration for the logger
# This is gonna be honored by the server
# Which is created below
setup_logger(
filename='%s.log' % str(logger_name),
logging_config=self.logging_config,
output_dir=self._backend.temporary_directory,
)
# As AutoPyTorch works with distributed process,
# we implement a logger server that can receive tcp
# pickled messages. They are unpickled and processed locally
# under the above logging configuration setting
# We need to specify the logger_name so that received records
# are treated under the logger_name ROOT logger setting
context = multiprocessing.get_context(self._multiprocessing_context)
preload_modules(context)
self.stop_logging_server = context.Event()
port = context.Value('l') # be safe by using a long
port.value = -1
# "BaseContext" has no attribute "Process" motivates to ignore the attr check
self.logging_server = context.Process( # type: ignore [attr-defined]
target=start_log_server,
kwargs=dict(
host='localhost',
logname=logger_name,
event=self.stop_logging_server,
port=port,
filename='%s.log' % str(logger_name),
logging_config=self.logging_config,
output_dir=self._backend.temporary_directory,
),
)
self.logging_server.start()
while True:
with port.get_lock():
if port.value == -1:
time.sleep(0.01)
else:
break
self._logger_port = int(port.value)
return get_named_client_logger(
name=logger_name,
host='localhost',
port=self._logger_port,
)
def _clean_logger(self) -> None:
"""
cleans the logging server created
Returns:
None
"""
if not hasattr(self, 'stop_logging_server') or self.stop_logging_server is None:
return
# Clean up the logger
if self.logging_server.is_alive():
self.stop_logging_server.set()
# We try to join the process, after we sent
# the terminate event. Then we try a join to
# nicely join the event. In case something
# bad happens with nicely trying to kill the
# process, we execute a terminate to kill the
# process.
self.logging_server.join(timeout=5)
self.logging_server.terminate()
del self.stop_logging_server
def _create_dask_client(self) -> None:
"""
creates the dask client that is used to parallelize
the training of pipelines
Returns:
None
"""
self._is_dask_client_internally_created = True
dask.config.set({'distributed.worker.daemon': False})
self._dask_client = dask.distributed.Client(
dask.distributed.LocalCluster(
n_workers=self.n_jobs,
processes=True,
threads_per_worker=1,
# We use the temporal directory to save the
# dask workers, because deleting workers
# more time than deleting backend directories
# This prevent an error saying that the worker
# file was deleted, so the client could not close
# the worker properly
local_directory=tempfile.gettempdir(),
# Memory is handled by the pynisher, not by the dask worker/nanny
memory_limit=0,
),
# Heartbeat every 10s
heartbeat_interval=10000,
)
def _close_dask_client(self) -> None:
"""
Closes the created dask client
Returns:
None
"""
if (
hasattr(self, '_is_dask_client_internally_created')
and self._is_dask_client_internally_created
and self._dask_client
):
self._dask_client.shutdown()
self._dask_client.close()
del self._dask_client
self._dask_client = None
self._is_dask_client_internally_created = False
del self._is_dask_client_internally_created
def _load_models(
self,
) -> bool:
"""
Loads the models saved in the temporary directory
during the smac run and the final ensemble created
Returns:
None
"""
if self.resampling_strategy is None:
raise ValueError("Resampling strategy is needed to determine what models to load")
self.ensemble_ = self._backend.load_ensemble(self.seed)
# If no ensemble is loaded, try to get the best performing model
if not self.ensemble_:
self.ensemble_ = self._load_best_individual_model()
if self.ensemble_:
identifiers = self.ensemble_.get_selected_model_identifiers()
self.models_ = self._backend.load_models_by_identifiers(identifiers)
if isinstance(self.resampling_strategy, CrossValTypes):
self.cv_models_ = self._backend.load_cv_models_by_identifiers(identifiers)
if isinstance(self.resampling_strategy, CrossValTypes):
if len(self.cv_models_) == 0:
raise ValueError('No models fitted!')
elif 'pipeline' not in self._disable_file_output:
model_names = self._backend.list_all_models(self.seed)
if len(model_names) == 0:
raise ValueError('No models fitted!')
self.models_ = {}
else:
self.models_ = {}
return True
def _load_best_individual_model(self) -> SingleBest:
"""
In case of failure during ensemble building,
this method returns the single best model found
by AutoML.
This is a robust mechanism to be able to predict,
even though no ensemble was found by ensemble builder.
Returns:
SingleBest:
Ensemble made with incumbent pipeline
"""
if self._metric is None:
raise ValueError("Providing a metric to AutoPytorch is required to fit a model. "
"A default metric could not be inferred. Please check the log "
"for error messages."
)
# SingleBest contains the best model found by AutoML
ensemble = SingleBest(
metric=self._metric,
seed=self.seed,
run_history=self.run_history,
backend=self._backend,
)
if self._logger is None:
warnings.warn(
"No valid ensemble was created. Please check the log"
"file for errors. Default to the best individual estimator:{}".format(
ensemble.identifiers_
)
)
else:
self._logger.exception(
"No valid ensemble was created. Please check the log"
"file for errors. Default to the best individual estimator:{}".format(
ensemble.identifiers_
)
)
return ensemble
def _do_dummy_prediction(self) -> None:
assert self._metric is not None
assert self._logger is not None
# For dummy estimator, we always expect the num_run to be 1
num_run = 1
self._logger.info("Starting to create dummy predictions.")
memory_limit = self._memory_limit
if memory_limit is not None:
memory_limit = int(math.ceil(memory_limit))
scenario_mock = unittest.mock.Mock()
scenario_mock.wallclock_limit = self._time_for_task
# This stats object is a hack - maybe the SMAC stats object should
# already be generated here!
stats = Stats(scenario_mock)
stats.start_timing()
ta = ExecuteTaFuncWithQueue(
pynisher_context=self._multiprocessing_context,
backend=self._backend,
seed=self.seed,
metric=self._metric,
multi_objectives=["cost"],
logger_port=self._logger_port,
cost_for_crash=get_cost_of_crash(self._metric),
abort_on_first_run_crash=False,
initial_num_run=num_run,
stats=stats,
memory_limit=memory_limit,
disable_file_output=self._disable_file_output,
all_supported_metrics=self._all_supported_metrics,
)
status, _, _, additional_info = ta.run(num_run, cutoff=self._time_for_task)
if status == StatusType.SUCCESS:
self._logger.info("Finished creating dummy predictions.")
else:
if additional_info.get('exitcode') == -6:
err_msg = "Dummy prediction failed with run state {},\n" \
"because the provided memory limits were too tight.\n" \
"Please increase the 'ml_memory_limit' and try again.\n" \
"If you still get the problem, please open an issue and\n" \
"paste the additional info.\n" \
"Additional info:\n{}.".format(str(status), dict_repr(additional_info))
self._logger.error(err_msg)
# Fail if dummy prediction fails.
raise ValueError(err_msg)
else:
err_msg = "Dummy prediction failed with run state {} and additional info:\n{}.".format(
str(status), dict_repr(additional_info)
)
self._logger.error(err_msg)
# Fail if dummy prediction fails.
raise ValueError(err_msg)
def _do_traditional_prediction(self, time_left: int, func_eval_time_limit_secs: int) -> None:
"""
Fits traditional machine learning algorithms to the provided dataset, while
complying with time resource allocation.
This method currently only supports classification.
Args:
time_left: (int)
Hard limit on how many machine learning algorithms can be fit. Depending on how
fast a traditional machine learning algorithm trains, it will allow multiple
models to be fitted.
func_eval_time_limit_secs: (int)
Maximum training time each algorithm is allowed to take, during training
"""
# Mypy Checkings -- Traditional prediction is only called for search
# where the following objects are created
assert self._metric is not None
assert self._logger is not None
assert self._dask_client is not None
self._logger.info("Starting to create traditional classifier predictions.")
# Initialise run history for the traditional classifiers
memory_limit = self._memory_limit
if memory_limit is not None:
memory_limit = int(math.ceil(memory_limit))
available_classifiers = get_available_traditional_learners()
model_configs = [(classifier, self.pipeline_options[self.pipeline_options['budget_type']])
for classifier in available_classifiers]
run_history = run_models_on_dataset(
time_left=time_left,
func_eval_time_limit_secs=func_eval_time_limit_secs,
model_configs=model_configs,
logger=self._logger,
logger_port=self._logger_port,
metric=self._metric,
dask_client=self._dask_client,
backend=self._backend,
memory_limit=memory_limit,
disable_file_output=self._disable_file_output,
all_supported_metrics=self._all_supported_metrics,
include=self.include_components,
exclude=self.exclude_components,
search_space_updates=self.search_space_updates,
pipeline_options=self.pipeline_options,
seed=self.seed,
multiprocessing_context=self._multiprocessing_context,
n_jobs=self.n_jobs,
current_search_space=self.search_space,
initial_num_run=self._backend.get_next_num_run()
)
self._logger.debug("Run history traditional: {}".format(run_history))
# add run history of traditional to api run history
self.run_history.update(run_history, DataOrigin.EXTERNAL_SAME_INSTANCES)
run_history.save_json(os.path.join(self._backend.internals_directory, 'traditional_run_history.json'),
save_external=True)
return
def _search(
self,
optimize_metric: str,
dataset: BaseDataset,
budget_type: str = 'epochs',
min_budget: Union[int, float] = 5,
max_budget: Union[int, float] = 50,
total_walltime_limit: int = 100,
func_eval_time_limit_secs: Optional[int] = None,
enable_traditional_pipeline: bool = True,
memory_limit: Optional[int] = 4096,
smac_scenario_args: Optional[Dict[str, Any]] = None,
get_smac_object_callback: Optional[Callable] = None,
tae_func: Optional[Callable] = None,
all_supported_metrics: bool = True,
precision: int = 32,
disable_file_output: Optional[List[Union[str, DisableFileOutputParameters]]] = None,
load_models: bool = True,
portfolio_selection: Optional[str] = None,
dask_client: Optional[dask.distributed.Client] = None,
**kwargs: Any
) -> 'BaseTask':
"""
Search for the best pipeline configuration for the given dataset.
Fit both optimizes the machine learning models and builds an ensemble out of them.
To disable ensembling, set ensemble_size==0.
using the optimizer.
Args:
dataset (Dataset):
The argument that will provide the dataset splits. It is
a subclass of the base dataset object which can
generate the splits based on different restrictions.
Providing X_train, y_train and dataset together is not supported.
optimize_metric (str): name of the metric that is used to
evaluate a pipeline.
budget_type (str):
Type of budget to be used when fitting the pipeline.
It can be one of:
+ `epochs`: The training of each pipeline will be terminated after
a number of epochs have passed. This number of epochs is determined by the
budget argument of this method.
+ `runtime`: The training of each pipeline will be terminated after
a number of seconds have passed. This number of seconds is determined by the
budget argument of this method. The overall fitting time of a pipeline is
controlled by func_eval_time_limit_secs. 'runtime' only controls the allocated
time to train a pipeline, but it does not consider the overall time it takes
to create a pipeline (data loading and preprocessing, other i/o operations, etc.).
budget_type will determine the units of min_budget/max_budget. If budget_type=='epochs'
is used, min_budget will refer to epochs whereas if budget_type=='runtime' then
min_budget will refer to seconds.
min_budget (int):
Auto-PyTorch uses `Hyperband <https://arxiv.org/abs/1603.06560>`_ to
trade-off resources between running many pipelines at min_budget and
running the top performing pipelines on max_budget.
min_budget states the minimum resource allocation a pipeline should have
so that we can compare and quickly discard bad performing models.
For example, if the budget_type is epochs, and min_budget=5, then we will
run every pipeline to a minimum of 5 epochs before performance comparison.
max_budget (int):
Auto-PyTorch uses `Hyperband <https://arxiv.org/abs/1603.06560>`_ to
trade-off resources between running many pipelines at min_budget and
running the top performing pipelines on max_budget.
max_budget states the maximum resource allocation a pipeline is going to
be ran. For example, if the budget_type is epochs, and max_budget=50,
then the pipeline training will be terminated after 50 epochs.
total_walltime_limit (int: default=100):
Time limit in seconds for the search of appropriate models.
By increasing this value, autopytorch has a higher
chance of finding better models.
func_eval_time_limit_secs (Optional[int]):
Time limit for a single call to the machine learning model.
Model fitting will be terminated if the machine
learning algorithm runs over the time limit. Set
this value high enough so that typical machine
learning algorithms can be fit on the training
data.
When set to None, this time will automatically be set to
total_walltime_limit // 2 to allow enough time to fit
at least 2 individual machine learning algorithms.
Set to np.inf in case no time limit is desired.
enable_traditional_pipeline (bool: default=True):
We fit traditional machine learning algorithms
(LightGBM, CatBoost, RandomForest, ExtraTrees, KNN, SVM)
prior building PyTorch Neural Networks. You can disable this
feature by turning this flag to False. All machine learning
algorithms that are fitted during search() are considered for
ensemble building.
memory_limit (Optional[int]: default=4096):
Memory limit in MB for the machine learning algorithm.
Autopytorch will stop fitting the machine learning algorithm
if it tries to allocate more than memory_limit MB. If None
is provided, no memory limit is set. In case of multi-processing,
memory_limit will be per job. This memory limit also applies to
the ensemble creation process.
smac_scenario_args (Optional[Dict]):
Additional arguments inserted into the scenario of SMAC. See the
`SMAC documentation <https://automl.github.io/SMAC3/master/options.html?highlight=scenario#scenario>`_
for a list of available arguments.
get_smac_object_callback (Optional[Callable]):
Callback function to create an object of class
`smac.optimizer.smbo.SMBO <https://automl.github.io/SMAC3/master/apidoc/smac.optimizer.smbo.html>`_.
The function must accept the arguments scenario_dict,
instances, num_params, runhistory, seed and ta. This is
an advanced feature. Use only if you are familiar with
`SMAC <https://automl.github.io/SMAC3/master/index.html>`_.
tae_func (Optional[Callable]):
TargetAlgorithm to be optimised. If None, `eval_function`
available in autoPyTorch/evaluation/train_evaluator is used.
Must be child class of AbstractEvaluator.
all_supported_metrics (bool: default=True):
If True, all metrics supporting current task will be calculated
for each pipeline and results will be available via cv_results
precision (int: default=32):
Numeric precision used when loading ensemble data.
Can be either '16', '32' or '64'.
disable_file_output (Optional[List[Union[str, DisableFileOutputParameters]]]):
Used as a list to pass more fine-grained
information on what to save. Must be a member of `DisableFileOutputParameters`.
Allowed elements in the list are:
+ `y_optimization`:
do not save the predictions for the optimization set,
which would later on be used to build an ensemble. Note that SMAC
optimizes a metric evaluated on the optimization set.
+ `pipeline`:
do not save any individual pipeline files
+ `pipelines`:
In case of cross validation, disables saving the joint model of the
pipelines fit on each fold.
+ `y_test`:
do not save the predictions for the test set.
+ `all`:
do not save any of the above.
For more information check `autoPyTorch.evaluation.utils.DisableFileOutputParameters`.
load_models (bool: default=True):
Whether to load the models after fitting AutoPyTorch.
portfolio_selection (Optional[str]):
This argument controls the initial configurations that
AutoPyTorch uses to warm start SMAC for hyperparameter
optimization. By default, no warm-starting happens.
The user can provide a path to a json file containing
configurations, similar to (...herepathtogreedy...).
Additionally, the keyword 'greedy' is supported,
which would use the default portfolio from
`AutoPyTorch Tabular <https://arxiv.org/abs/2006.13799>`_
kwargs: Any
additional arguments that are customed by some specific task.
For instance, forecasting tasks require:
min_num_test_instances (int): minimal number of instances used to initialize a proxy validation set
suggested_init_models (List[str]): A set of initial models suggested by the users. Their
hyperparameters are determined by the default configurations
custom_init_setting_path (str): The path to the initial hyperparameter configurations set by
the users
Returns: