forked from autogluon/autogluon
/
predictor.py
2861 lines (2595 loc) · 119 KB
/
predictor.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
"""Implementation of the multimodal predictor"""
from __future__ import annotations
import copy
import json
import logging
import operator
import os
import pickle
import shutil
import sys
import time
import warnings
from datetime import timedelta
from typing import Dict, List, Optional, Union
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch
import transformers
import yaml
from omegaconf import OmegaConf
from packaging import version
from torch import nn
from autogluon.common.utils.log_utils import set_logger_verbosity, verbosity2loglevel
from autogluon.core.utils import default_holdout_frac, generate_train_test_split_combined
from autogluon.core.utils.loaders import load_pd
from autogluon.multimodal.utils.log import get_fit_complete_message, get_fit_start_message
from . import version as ag_version
from .constants import (
AUTOMM,
AUTOMM_TUTORIAL_MODE,
BBOX,
BEST,
BEST_K_MODELS_FILE,
BINARY,
COLUMN_FEATURES,
DEEPSPEED_MIN_PL_VERSION,
DEEPSPEED_MODULE,
DEEPSPEED_OFFLOADING,
DEEPSPEED_STRATEGY,
DEPRECATED_ZERO_SHOT,
DOCUMENT,
FEATURE_EXTRACTION,
FEATURES,
FEW_SHOT,
FEW_SHOT_TEXT_CLASSIFICATION,
GREEDY_SOUP,
IMAGE_BYTEARRAY,
IMAGE_PATH,
LABEL,
LAST_CHECKPOINT,
LOGITS,
MAP,
MASKS,
MAX,
MIN,
MODEL_CHECKPOINT,
MULTI_IMAGE_MIX_DATASET,
MULTICLASS,
NER,
NER_RET,
NUMERICAL,
OBJECT_DETECTION,
OCR_TEXT_DETECTION,
OCR_TEXT_RECOGNITION,
OVERALL_F1,
RAY_TUNE_CHECKPOINT,
REGRESSION,
ROIS,
SCORE,
TEXT,
TEXT_NER,
UNIFORM_SOUP,
XYWH,
Y_PRED,
Y_PRED_PROB,
Y_TRUE,
ZERO_SHOT_IMAGE_CLASSIFICATION,
)
from .data.datamodule import BaseDataModule
from .data.dataset_mmlab import MultiImageMixDataset
from .data.infer_types import (
infer_column_types,
infer_label_column_type_by_problem_type,
infer_problem_type_output_shape,
infer_rois_column_type,
is_image_column,
)
from .data.preprocess_dataframe import MultiModalFeaturePreprocessor
from .matcher import MultiModalMatcher
from .models.utils import get_model_postprocess_fn
from .optimization.lit_distiller import DistillerLitModule
from .optimization.lit_mmdet import MMDetLitModule
from .optimization.lit_module import LitModule
from .optimization.lit_ner import NerLitModule
from .optimization.losses import RKDLoss
from .optimization.utils import (
get_loss_func,
get_metric,
get_norm_layer_param_names,
get_trainable_params_efficient_finetune,
)
from .problem_types import PROBLEM_TYPES_REG
from .utils import (
AutoMMModelCheckpoint,
AutoMMModelCheckpointIO,
CustomUnpickler,
DDPCacheWriter,
ExportMixin,
LogFilter,
apply_log_filter,
assign_feature_column_names,
average_checkpoints,
check_if_packages_installed,
compute_num_gpus,
compute_score,
convert_pred_to_xywh,
create_fusion_data_processors,
create_fusion_model,
data_to_df,
evaluate_coco,
extract_from_output,
filter_hyperparameters,
get_available_devices,
get_config,
get_detection_classes,
get_fit_complete_message,
get_fit_start_message,
get_local_pretrained_config_paths,
get_minmax_mode,
get_mixup,
get_stopping_threshold,
hyperparameter_tune,
infer_dtypes_by_model_names,
infer_metrics,
infer_precision,
infer_scarcity_mode_by_data_size,
init_df_preprocessor,
init_pretrained,
list_timm_models,
load_text_tokenizers,
logits_to_prob,
merge_bio_format,
modify_duplicate_model_names,
object_detection_data_to_df,
predict,
process_batch,
save_pretrained_model_configs,
save_result_df,
save_text_tokenizers,
select_model,
setup_detection_train_tuning_data,
setup_save_path,
split_hyperparameters,
tensor_to_ndarray,
turn_on_off_feature_column_info,
update_config_by_rules,
update_hyperparameters,
update_tabular_config_by_resources,
upgrade_config,
)
logger = logging.getLogger(__name__)
class MultiModalPredictor(ExportMixin):
"""
MultiModalPredictor is a deep learning "model zoo" of model zoos. It can automatically build deep learning models that
are suitable for multimodal datasets. You will only need to preprocess the data in the multimodal dataframe format
and the MultiModalPredictor can predict the values of one column conditioned on the features from the other columns.
The prediction can be either classification or regression. The feature columns can contain
image paths, text, numerical, and categorical values.
"""
def __init__(
self,
label: Optional[str] = None,
problem_type: Optional[str] = None,
query: Optional[Union[str, List[str]]] = None,
response: Optional[Union[str, List[str]]] = None,
match_label: Optional[Union[int, str]] = None,
pipeline: Optional[str] = None,
presets: Optional[str] = None,
eval_metric: Optional[str] = None,
hyperparameters: Optional[dict] = None,
path: Optional[str] = None,
verbosity: Optional[int] = 2,
num_classes: Optional[int] = None, # TODO: can we infer this from data?
classes: Optional[list] = None,
warn_if_exist: Optional[bool] = True,
enable_progress_bar: Optional[bool] = None,
init_scratch: Optional[bool] = False,
sample_data_path: Optional[str] = None,
):
"""
Parameters
----------
label
Name of the column that contains the target variable to predict.
problem_type
Type of the prediction problem. We support standard problems like
- 'binary': Binary classification
- 'multiclass': Multi-class classification
- 'regression': Regression
- 'classification': Classification problems include 'binary' and 'multiclass' classification.
In addition, we support advanced problems such as
- 'object_detection': Object detection
- 'ner' or 'named_entity_recognition': Named entity extraction
- 'text_similarity': Text-text similarity problem
- 'image_similarity': Image-image similarity problem
- 'image_text_similarity': Text-image similarity problem
- 'feature_extraction': Extracting feature (only support inference)
- 'zero_shot_image_classification': Zero-shot image classification (only support inference)
- 'few_shot_text_classification': (experimental) Few-shot text classification
- 'ocr_text_detection': (experimental) Extract OCR text
- 'ocr_text_recognition': (experimental) Recognize OCR text
For certain problem types, the default behavior is to load a pretrained model based on
the presets / hyperparameters and the predictor will support zero-shot inference
(running inference without .fit()). This includes the following
problem types:
- 'object_detection'
- 'text_similarity'
- 'image_similarity'
- 'image_text_similarity'
- 'feature_extraction'
- 'zero_shot_image_classification'
- 'few_shot_text_classification' (experimental)
- 'ocr_text_detection' (experimental)
- 'ocr_text_recognition' (experimental)
query
Column names of query data (used for matching).
response
Column names of response data (used for matching). If no label column is provided,
query and response columns form positive pairs.
match_label
The label class that indicates the <query, response> pair is counted as "match".
This is used when the problem_type is one of the matching problem types, and when the labels are binary.
For example, the label column can contain ["duplicate", "not duplicate"]. And match_label can be "duplicate".
If match_label is not provided, every sample is assumed to have a unique label.
pipeline
Pipeline has been deprecated and merged in problem_type.
presets
Presets regarding model quality, e.g., best_quality, high_quality, and medium_quality.
eval_metric
Evaluation metric name. If `eval_metric = None`, it is automatically chosen based on `problem_type`.
Defaults to 'accuracy' for binary and multiclass classification, 'root_mean_squared_error' for regression.
hyperparameters
This is to override some default configurations.
For example, changing the text and image backbones can be done by formatting:
a string
hyperparameters = "model.hf_text.checkpoint_name=google/electra-small-discriminator model.timm_image.checkpoint_name=swin_small_patch4_window7_224"
or a list of strings
hyperparameters = ["model.hf_text.checkpoint_name=google/electra-small-discriminator", "model.timm_image.checkpoint_name=swin_small_patch4_window7_224"]
or a dictionary
hyperparameters = {
"model.hf_text.checkpoint_name": "google/electra-small-discriminator",
"model.timm_image.checkpoint_name": "swin_small_patch4_window7_224",
}
path
Path to directory where models and intermediate outputs should be saved.
If unspecified, a time-stamped folder called "AutogluonAutoMM/ag-[TIMESTAMP]"
will be created in the working directory to store all models.
Note: To call `fit()` twice and save all results of each fit,
you must specify different `path` locations or don't specify `path` at all.
Otherwise files from first `fit()` will be overwritten by second `fit()`.
verbosity
Verbosity levels range from 0 to 4 and control how much information is printed.
Higher levels correspond to more detailed print statements (you can set verbosity = 0 to suppress warnings).
If using logging, you can alternatively control amount of information printed via `logger.setLevel(L)`,
where `L` ranges from 0 to 50
(Note: higher values of `L` correspond to fewer print statements, opposite of verbosity levels)
num_classes
Number of classes. Used in classification task.
If this is specified and is different from the pretrained model's output,
the model's head will be changed to have <num_classes> output.
classes
All classes in this dataset.
warn_if_exist
Whether to raise warning if the specified path already exists.
enable_progress_bar
Whether to show progress bar. It will be True by default and will also be
disabled if the environment variable os.environ["AUTOMM_DISABLE_PROGRESS_BAR"] is set.
init_scratch
Whether to init model from scratch. It's useful when we want to load a checkpoints
without its weights.
sample_data_path
This is used for automatically inference num_classes, classes, or label.
"""
# Handle the deprecated pipeline flag
if pipeline is not None:
pipeline = pipeline.lower()
warnings.warn(
f"pipeline argument has been deprecated and moved to problem_type. "
f"Use problem_type='{pipeline}' instead.",
DeprecationWarning,
)
if problem_type is not None:
assert pipeline == problem_type, (
f"Mismatched pipeline and problem_type. "
f"Received pipeline={pipeline}, problem_type={problem_type}. "
f"Consider to revise the arguments."
)
problem_type = pipeline
# Sanity check of problem_type
if problem_type is not None:
problem_type = problem_type.lower()
if problem_type == DEPRECATED_ZERO_SHOT:
warnings.warn(
f'problem_type="{DEPRECATED_ZERO_SHOT}" is deprecated. For inference with CLIP model, '
f'use pipeline="{ZERO_SHOT_IMAGE_CLASSIFICATION}" instead.',
DeprecationWarning,
)
problem_type = ZERO_SHOT_IMAGE_CLASSIFICATION
assert problem_type in PROBLEM_TYPES_REG, (
f"problem_type='{problem_type}' is not supported yet. You may pick a problem type from"
f" {PROBLEM_TYPES_REG.list_keys()}."
)
problem_prop = PROBLEM_TYPES_REG.get(problem_type)
if problem_prop.experimental:
warnings.warn(
f"problem_type='{problem_type}' is currently experimental.",
UserWarning,
)
problem_type = problem_prop.name
check_if_packages_installed(problem_type=problem_type)
if eval_metric is not None and not isinstance(eval_metric, str):
eval_metric = eval_metric.name
if eval_metric is not None and eval_metric.lower() in [
"rmse",
"r2",
"pearsonr",
"spearmanr",
]:
if problem_type is None:
logger.debug(
f"Infer problem type to be a regression problem "
f"since the evaluation metric is set as {eval_metric}."
)
problem_type = REGRESSION
else:
problem_prop = PROBLEM_TYPES_REG.get(problem_type)
if NUMERICAL not in problem_prop.supported_label_type:
raise ValueError(
f"The provided evaluation metric will require the problem "
f"to support label type = {NUMERICAL}. However, "
f"the provided problem type = {problem_type} only "
f"supports label type = {problem_prop.supported_label_type}."
)
if os.environ.get(AUTOMM_TUTORIAL_MODE):
enable_progress_bar = False
# Also disable progress bar of transformers package
transformers.logging.disable_progress_bar()
if verbosity is not None:
set_logger_verbosity(verbosity)
self._label_column = label
self._problem_type = problem_type
self._presets = presets.lower() if presets else None
self._eval_metric_name = eval_metric
self._validation_metric_name = None
self._output_shape = num_classes
self._classes = classes
self._ckpt_path = None
self._pretrained_path = None
self._config = None
self._df_preprocessor = None
self._column_types = None
self._data_processors = None
self._model_postprocess_fn = None
self._model = None
self._resume = False
self._verbosity = verbosity
self._warn_if_exist = warn_if_exist
self._enable_progress_bar = enable_progress_bar if enable_progress_bar is not None else True
self._init_scratch = init_scratch
self._sample_data_path = sample_data_path
self._fit_called = False # While using ddp, after fit called, we can only use single gpu.
self._matcher = None
self._save_path = path
# Summary statistics used in fit summary. TODO: wrap it in a class.
self._total_train_time = None
self._best_score = None
if self.problem_property and self.problem_property.is_matching:
self._matcher = MultiModalMatcher(
query=query,
response=response,
label=label,
match_label=match_label,
problem_type=problem_type,
presets=presets,
hyperparameters=hyperparameters,
eval_metric=eval_metric,
path=path,
verbosity=verbosity,
warn_if_exist=warn_if_exist,
enable_progress_bar=enable_progress_bar,
)
return
if self._problem_type == OBJECT_DETECTION:
self._label_column = "label"
if self._sample_data_path is not None:
self._classes = get_detection_classes(self._sample_data_path)
self._output_shape = len(self._classes)
if self._problem_type is not None:
if self.problem_property.support_zero_shot:
# Load pretrained model via the provided hyperparameters and presets
# TODO: do not create pretrained model for HPO presets.
self._config, self._model, self._data_processors = init_pretrained(
problem_type=self._problem_type,
presets=self._presets,
hyperparameters=hyperparameters,
num_classes=self._output_shape,
classes=self._classes,
init_scratch=self._init_scratch,
)
self._validation_metric_name = self._config["optimization"][
"val_metric"
] # TODO: only object detection is using this
@property
def path(self):
if self._matcher:
return self._matcher.path
else:
return self._save_path
@property
def label(self):
if self._matcher:
return self._matcher.label
else:
return self._label_column
@property
def query(self):
if self._matcher:
return self._matcher.query
else:
warnings.warn("Matcher is not used. No query columns are available.", UserWarning)
return None
@property
def response(self):
if self._matcher:
return self._matcher.response
else:
warnings.warn("Matcher is not used. No response columns are available.", UserWarning)
return None
@property
def match_label(self):
if self._matcher:
return self._matcher.match_label
else:
warnings.warn("Matcher is not used. No match_label is available.", UserWarning)
return None
@property
def problem_type(self):
return self._problem_type
@property
def problem_property(self):
if self._problem_type is None:
return None
else:
return PROBLEM_TYPES_REG.get(self._problem_type)
@property
def column_types(self):
if self._matcher:
return self._matcher.column_types
else:
return self._column_types
# This func is required by the abstract trainer of TabularPredictor.
def set_verbosity(self, verbosity: int):
"""Set the verbosity level of the log.
Parameters
----------
verbosity
The verbosity level.
0 --> only errors
1 --> only warnings and critical print statements
2 --> key print statements which should be shown by default
3 --> more-detailed printing
4 --> everything
"""
self._verbosity = verbosity
set_logger_verbosity(verbosity)
transformers.logging.set_verbosity(verbosity2loglevel(verbosity))
def fit(
self,
train_data: Union[pd.DataFrame, str],
presets: Optional[str] = None,
config: Optional[dict] = None,
tuning_data: Optional[Union[pd.DataFrame, str]] = None,
max_num_tuning_data: Optional[int] = None,
id_mappings: Optional[Union[Dict[str, Dict], Dict[str, pd.Series]]] = None,
time_limit: Optional[int] = None,
save_path: Optional[str] = None,
hyperparameters: Optional[Union[str, Dict, List[str]]] = None,
column_types: Optional[dict] = None,
holdout_frac: Optional[float] = None,
teacher_predictor: Union[str, MultiModalPredictor] = None,
seed: Optional[int] = 0,
standalone: Optional[bool] = True,
hyperparameter_tune_kwargs: Optional[dict] = None,
clean_ckpts: Optional[bool] = True,
):
"""
Fit MultiModalPredictor predict label column of a dataframe based on the other columns,
which may contain image path, text, numeric, or categorical features.
Parameters
----------
train_data
A dataframe containing training data.
presets
Presets regarding model quality, e.g., best_quality, high_quality, and medium_quality.
config
A dictionary with four keys "model", "data", "optimization", and "environment".
Each key's value can be a string, yaml file path, or OmegaConf's DictConfig.
Strings should be the file names (DO NOT include the postfix ".yaml") in
automm/configs/model, automm/configs/data, automm/configs/optimization, and automm/configs/environment.
For example, you can configure a late-fusion model for the image, text, and tabular data as follows:
config = {
"model": "fusion_mlp_image_text_tabular",
"data": "default",
"optimization": "adamw",
"environment": "default",
}
or
config = {
"model": "/path/to/model/config.yaml",
"data": "/path/to/data/config.yaml",
"optimization": "/path/to/optimization/config.yaml",
"environment": "/path/to/environment/config.yaml",
}
or
config = {
"model": OmegaConf.load("/path/to/model/config.yaml"),
"data": OmegaConf.load("/path/to/data/config.yaml"),
"optimization": OmegaConf.load("/path/to/optimization/config.yaml"),
"environment": OmegaConf.load("/path/to/environment/config.yaml"),
}
tuning_data
A dataframe containing validation data, which should have the same columns as the train_data.
If `tuning_data = None`, `fit()` will automatically
hold out some random validation examples from `train_data`.
id_mappings
Id-to-content mappings. The contents can be text, image, etc.
This is used when the dataframe contains the query/response identifiers instead of their contents.
time_limit
How long `fit()` should run for (wall clock time in seconds).
If not specified, `fit()` will run until the model has completed training.
save_path
Path to directory where models and intermediate outputs should be saved.
hyperparameters
This is to override some default configurations.
For example, changing the text and image backbones can be done by formatting:
a string
hyperparameters = "model.hf_text.checkpoint_name=google/electra-small-discriminator model.timm_image.checkpoint_name=swin_small_patch4_window7_224"
or a list of strings
hyperparameters = ["model.hf_text.checkpoint_name=google/electra-small-discriminator", "model.timm_image.checkpoint_name=swin_small_patch4_window7_224"]
or a dictionary
hyperparameters = {
"model.hf_text.checkpoint_name": "google/electra-small-discriminator",
"model.timm_image.checkpoint_name": "swin_small_patch4_window7_224",
}
column_types
A dictionary that maps column names to their data types.
For example: `column_types = {"item_name": "text", "image": "image_path",
"product_description": "text", "height": "numerical"}`
may be used for a table with columns: "item_name", "brand", "product_description", and "height".
If None, column_types will be automatically inferred from the data.
The current supported types are:
- "image_path": each row in this column is one image path.
- "text": each row in this column contains text (sentence, paragraph, etc.).
- "numerical": each row in this column contains a number.
- "categorical": each row in this column belongs to one of K categories.
holdout_frac
Fraction of train_data to holdout as tuning_data for optimizing hyper-parameters or
early stopping (ignored unless `tuning_data = None`).
Default value (if None) is selected based on the number of rows in the training data
and whether hyper-parameter-tuning is utilized.
teacher_predictor
The pre-trained teacher predictor or its saved path. If provided, `fit()` can distill its
knowledge to a student predictor, i.e., the current predictor.
seed
The random seed to use for this training run.
Defaults to 0
standalone
Whether to save the enire model for offline deployment or only trained parameters of parameter-efficient fine-tuning strategy.
hyperparameter_tune_kwargs
Hyperparameter tuning strategy and kwargs (for example, how many HPO trials to run).
If None, then hyperparameter tuning will not be performed.
num_trials: int
How many HPO trials to run. Either `num_trials` or `time_limit` to `fit` needs to be specified.
scheduler: Union[str, ray.tune.schedulers.TrialScheduler]
If str is passed, AutoGluon will create the scheduler for you with some default parameters.
If ray.tune.schedulers.TrialScheduler object is passed, you are responsible for initializing the object.
scheduler_init_args: Optional[dict] = None
If provided str to `scheduler`, you can optionally provide custom init_args to the scheduler
searcher: Union[str, ray.tune.search.SearchAlgorithm, ray.tune.search.Searcher]
If str is passed, AutoGluon will create the searcher for you with some default parameters.
If ray.tune.schedulers.TrialScheduler object is passed, you are responsible for initializing the object.
You don't need to worry about `metric` and `mode` of the searcher object. AutoGluon will figure it out by itself.
scheduler_init_args: Optional[dict] = None
If provided str to `searcher`, you can optionally provide custom init_args to the searcher
You don't need to worry about `metric` and `mode`. AutoGluon will figure it out by itself.
clean_ckpts
Whether to clean the checkpoints of each validation step after training.
Returns
-------
An "MultiModalPredictor" object (itself).
"""
fit_called = self._fit_called # used in current function
self._fit_called = True
if self._problem_type and not self.problem_property.support_fit:
raise RuntimeError(
f"The problem_type='{self._problem_type}' does not support `predictor.fit()`. "
f"You may try to use `predictor.predict()` or `predictor.evaluate()`."
)
training_start = time.time()
if self._matcher:
self._matcher.fit(
train_data=train_data,
tuning_data=tuning_data,
id_mappings=id_mappings,
time_limit=time_limit,
presets=presets,
hyperparameters=hyperparameters,
column_types=column_types,
holdout_frac=holdout_frac,
save_path=save_path,
hyperparameter_tune_kwargs=hyperparameter_tune_kwargs,
seed=seed,
)
return self
if self._problem_type == OBJECT_DETECTION:
train_data, tuning_data = setup_detection_train_tuning_data(
self, max_num_tuning_data, seed, train_data, tuning_data
)
if isinstance(train_data, str):
train_data = load_pd.load(train_data)
if isinstance(tuning_data, str):
tuning_data = load_pd.load(tuning_data)
pl.seed_everything(seed, workers=True)
if self._presets is not None:
# FIXME: Silently ignoring user input, there should be a warning
presets = self._presets
else:
self._presets = presets
if self._config is not None: # continuous training
# FIXME: Silently ignoring user input, there should be a warning
config = self._config
self._save_path = setup_save_path(
resume=self._resume,
old_save_path=self._save_path,
proposed_save_path=save_path,
raise_if_exist=True,
warn_if_exist=False,
fit_called=fit_called,
)
self._problem_type = self._infer_problem_type(train_data=train_data, column_types=column_types)
if tuning_data is None:
train_data, tuning_data = self._split_train_tuning(
data=train_data, holdout_frac=holdout_frac, random_state=seed
)
column_types = self._infer_column_types(
train_data=train_data, tuning_data=tuning_data, column_types=column_types
)
# FIXME: separate infer problem_type with output_shape, should be logically distinct
_, output_shape = infer_problem_type_output_shape(
label_column=self._label_column,
column_types=column_types,
data=train_data,
provided_problem_type=self._problem_type,
)
# Determine data scarcity mode, i.e. a few-shot scenario
scarcity_mode = infer_scarcity_mode_by_data_size(
df_train=train_data, scarcity_threshold=50
) # Add as separate hyperparameter somewhere?
if scarcity_mode == FEW_SHOT and (not presets or FEW_SHOT not in presets): # TODO: check for data type
logger.info(
f"Detected data scarcity. Consider running using the preset '{FEW_SHOT_TEXT_CLASSIFICATION}' for better performance."
)
logger.debug(f"column_types: {column_types}")
logger.debug(f"image columns: {[k for k, v in column_types.items() if v == 'image_path']}")
if self._column_types is not None and self._column_types != column_types:
warnings.warn(
f"Inferred column types {column_types} are inconsistent with "
f"the previous {self._column_types}. "
f"New columns will not be used in the current training."
)
# use previous column types to avoid inconsistency with previous numerical mlp and categorical mlp
column_types = self._column_types
if self._problem_type != OBJECT_DETECTION:
if self._output_shape is not None and output_shape is not None:
assert self._output_shape == output_shape, (
f"Inferred output shape {output_shape} is different from " f"the previous {self._output_shape}"
)
else:
self._output_shape = output_shape
if self._validation_metric_name is None or self._eval_metric_name is None:
validation_metric_name, eval_metric_name = infer_metrics(
problem_type=self._problem_type,
eval_metric_name=self._eval_metric_name,
validation_metric_name=self._validation_metric_name,
)
else:
validation_metric_name = self._validation_metric_name
eval_metric_name = self._eval_metric_name
minmax_mode = get_minmax_mode(validation_metric_name)
if time_limit is not None:
time_limit = timedelta(seconds=time_limit)
# set attributes for saving and prediction
self._eval_metric_name = eval_metric_name # In case eval_metric isn't provided in __init__().
self._validation_metric_name = validation_metric_name
self._column_types = column_types
hyperparameters, hyperparameter_tune_kwargs = update_hyperparameters(
problem_type=self._problem_type,
presets=presets,
provided_hyperparameters=hyperparameters,
provided_hyperparameter_tune_kwargs=hyperparameter_tune_kwargs,
teacher_predictor=teacher_predictor,
)
# split out the hyperparameters whose values are complex objects
hyperparameters, advanced_hyperparameters = split_hyperparameters(hyperparameters)
hpo_mode = True if hyperparameter_tune_kwargs else False
if hpo_mode:
hyperparameters = filter_hyperparameters(
hyperparameters=hyperparameters,
column_types=column_types,
config=config,
fit_called=fit_called,
)
_fit_args = dict(
train_df=train_data,
val_df=tuning_data,
validation_metric_name=validation_metric_name,
minmax_mode=minmax_mode,
max_time=time_limit,
save_path=self._save_path,
ckpt_path=None if hpo_mode else self._ckpt_path,
resume=False if hpo_mode else self._resume,
enable_progress_bar=False if hpo_mode else self._enable_progress_bar,
presets=presets,
config=config,
hyperparameters=hyperparameters,
advanced_hyperparameters=advanced_hyperparameters,
teacher_predictor=teacher_predictor,
standalone=standalone,
hpo_mode=hpo_mode, # skip average checkpoint if in hpo mode
clean_ckpts=clean_ckpts,
)
if hpo_mode:
# TODO: allow custom gpu
assert self._resume is False, "You can not resume training with HPO"
resources = dict(num_gpus=torch.cuda.device_count())
if _fit_args["max_time"] is not None:
_fit_args["max_time"] *= 0.95 # give some buffer time to ray lightning trainer
_fit_args["predictor"] = self
predictor = hyperparameter_tune(
hyperparameter_tune_kwargs=hyperparameter_tune_kwargs,
resources=resources,
**_fit_args,
)
return predictor
self._fit(**_fit_args)
training_end = time.time()
self._total_train_time = training_end - training_start
# TODO(?) We should have a separate "_post_training_event()" for logging messages.
logger.info(get_fit_complete_message(self._save_path))
return self
# FIXME: Avoid having separate logic for inferring features and label column that is combined together
def _infer_column_types(
self, train_data: pd.DataFrame, tuning_data: pd.DataFrame = None, column_types: dict = None
) -> dict:
column_types = infer_column_types(
data=train_data,
label_columns=self._label_column,
provided_column_types=column_types,
valid_data=tuning_data,
problem_type=self._problem_type,
)
column_types = infer_label_column_type_by_problem_type(
column_types=column_types,
label_columns=self._label_column,
problem_type=self._problem_type,
data=train_data,
valid_data=tuning_data,
)
return column_types
# FIXME: Align logic with Tabular,
# don't combine output_shape and problem_type detection, make them separate
# Use autogluon.core.utils.utils.infer_problem_type
def _infer_problem_type(self, train_data: pd.DataFrame, column_types: dict = None) -> str:
column_types_label = self._infer_column_types(
train_data=train_data[[self._label_column]], column_types=column_types
)
problem_type, _ = infer_problem_type_output_shape(
label_column=self._label_column,
column_types=column_types_label,
data=train_data,
provided_problem_type=self._problem_type,
)
return problem_type
def _split_train_tuning(
self, data: pd.DataFrame, holdout_frac: float = None, random_state: int = 0
) -> (pd.DataFrame, pd.DataFrame):
"""
Splits `data` into `train_data` and `tuning_data`.
If the problem_type is one of ['binary', 'multiclass']:
The split will be done with stratification on the label column.
Will guarantee at least 1 sample of every class in `data` will be present in `train_data`.
If only 1 sample of a class exists, it will always be put in `train_data` and not `tuning_data`.
Parameters
----------
data : pd.DataFrame
The data to be split
holdout_frac : float, default = None
The ratio of data to use as validation.
If 0.2, 20% of the data will be used for validation, and 80% for training.
If None, the ratio is automatically determined,
ranging from 0.2 for small row count to 0.01 for large row count.
random_state : int, default = 0
The random state to use when splitting the data, to make the splitting process deterministic.
If None, a random value is used.
Returns
-------
Tuple of (train_data, tuning_data) of the split `data`
"""
if holdout_frac is None:
holdout_frac = default_holdout_frac(num_train_rows=len(data), hyperparameter_tune=False)
# TODO: Hack since the recognized problem types are only binary, multiclass, and regression
# Problem types used for purpose of stratification, so regression = no stratification
if self._problem_type in [BINARY, MULTICLASS]:
problem_type_for_split = self._problem_type
else:
problem_type_for_split = REGRESSION
train_data, tuning_data = generate_train_test_split_combined(
data=data,
label=self.label,
test_size=holdout_frac,
problem_type=problem_type_for_split,
random_state=random_state,
)
return train_data, tuning_data
def _verify_inference_ready(self):
if not self._fit_called:
if self._problem_type and not self.problem_property.support_zero_shot:
raise RuntimeError(
f"problem_type='{self._problem_type}' does not support running inference directly. "
f"You need to call `predictor.fit()`, or load a predictor first before "
f"running `predictor.predict()`, `predictor.evaluate()` or `predictor.extract_embedding()`."
)
def _setup_distillation(
self,
teacher_predictor: Union[str, MultiModalPredictor],
):
"""
Prepare for distillation. It verifies whether the student and teacher predictors have consistent
configurations. If teacher and student have duplicate model names, it modifies teacher's model names.
Parameters
----------
teacher_predictor
The teacher predictor in knowledge distillation.
Returns
-------
teacher_model
The teacher predictor's model.
critics
The critics used in computing mutual information loss.
baseline_funcs
The baseline functions used in computing mutual information loss.
soft_label_loss_func
The loss function using teacher's logits as labels.
output_feature_adaptor
The adaptor used to adapt student output feature to the shape of teacher's.
output_feature_loss_func
The loss function using minimize distance between output_feature of teacher and student.
rkd_loss_func
The loss function using rkd distance and angle loss between output_feature of teacher and student.
df_preprocessor
The teacher predictor's dataframe preprocessor.
data_processors
The teacher predictor's data processors.
"""
logger.debug("setting up distillation...")
if isinstance(teacher_predictor, str):
teacher_predictor = MultiModalPredictor.load(teacher_predictor)
# verify that student and teacher configs are consistent.
assert self._problem_type == teacher_predictor.problem_type
assert self._label_column == teacher_predictor._label_column
assert self._output_shape == teacher_predictor._output_shape
# if teacher and student have duplicate model names, change teacher's model names
# we don't change student's model names to avoid changing the names back when saving the model.
teacher_predictor = modify_duplicate_model_names(
predictor=teacher_predictor,
postfix="teacher",
blacklist=self._config.model.names,
)
critics, baseline_funcs = None, None
if not self._config.distiller.soft_label_loss_type:
# automatically infer loss func based on problem type if not specified
if self._problem_type == REGRESSION:
soft_label_loss_func = nn.MSELoss()
else:
assert self._output_shape > 1
soft_label_loss_func = nn.CrossEntropyLoss()
elif self._config.distiller.soft_label_loss_type == "mse":
soft_label_loss_func = nn.MSELoss()
elif self._config.distiller.soft_label_loss_type == "cross_entropy":
soft_label_loss_func = nn.CrossEntropyLoss()
else:
raise ValueError(f"Unknown soft_label_loss_type: {self._config.distiller.soft_label_loss_type}")
if not self._config.distiller.softmax_regression_loss_type:
# automatically infer loss func based on problem type if not specified
if self._problem_type == REGRESSION:
softmax_regression_loss_func = nn.MSELoss()