forked from autogluon/autogluon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matcher.py
2043 lines (1848 loc) · 83.3 KB
/
matcher.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
from __future__ import annotations
import copy
import json
import logging
import operator
import os
import pickle
import sys
import warnings
from datetime import timedelta
from typing import Callable, Dict, List, Optional, Union
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch
import yaml
from omegaconf import DictConfig, OmegaConf
from torch import nn
from autogluon.common.utils.log_utils import set_logger_verbosity
from autogluon.core.utils.loaders import load_pd
from . import version as ag_version
from .constants import (
AUTOMM,
AUTOMM_TUTORIAL_MODE,
BEST,
BEST_K_MODELS_FILE,
BINARY,
CLASSIFICATION,
DATA,
FEATURES,
GREEDY_SOUP,
IMAGE_TEXT_SIMILARITY,
LABEL,
LAST_CHECKPOINT,
MAX,
MIN,
MODEL,
MODEL_CHECKPOINT,
MULTICLASS,
PAIR,
PROBABILITY,
QUERY,
RAY_TUNE_CHECKPOINT,
RESPONSE,
TEXT,
UNIFORM_SOUP,
Y_PRED,
Y_PRED_PROB,
Y_TRUE,
)
from .data.datamodule import BaseDataModule
from .data.infer_types import (
infer_column_types,
infer_label_column_type_by_problem_type,
infer_problem_type_output_shape,
)
from .data.preprocess_dataframe import MultiModalFeaturePreprocessor
from .optimization.lit_matcher import MatcherLitModule
from .optimization.utils import get_matcher_loss_func, get_matcher_miner_func, get_metric
from .presets import matcher_presets
from .utils import (
AutoMMModelCheckpoint,
CustomUnpickler,
LogFilter,
apply_log_filter,
assign_feature_column_names,
average_checkpoints,
compute_num_gpus,
compute_ranking_score,
compute_score,
compute_semantic_similarity,
convert_data_for_ranking,
create_fusion_data_processors,
create_siamese_model,
customize_model_names,
data_to_df,
extract_from_output,
filter_hyperparameters,
get_available_devices,
get_config,
get_fit_complete_message,
get_fit_start_message,
get_local_pretrained_config_paths,
get_minmax_mode,
get_stopping_threshold,
hyperparameter_tune,
infer_dtypes_by_model_names,
infer_metrics,
infer_precision,
init_df_preprocessor,
init_pretrained_matcher,
load_text_tokenizers,
predict,
save_pretrained_model_configs,
save_text_tokenizers,
select_model,
setup_save_path,
split_train_tuning_data,
update_hyperparameters,
upgrade_config,
)
logger = logging.getLogger(__name__)
class MultiModalMatcher:
"""
MultiModalMatcher is a framework to learn/extract embeddings for multimodal data including image, text, and tabular.
These embeddings can be used e.g. with cosine-similarity to find items with similar semantic meanings.
This can be useful for computing the semantic similarity of two items, semantic search, paraphrase mining, etc.
"""
def __init__(
self,
query: Optional[Union[str, List[str]]] = None,
response: Optional[Union[str, List[str]]] = None,
label: Optional[str] = None,
match_label: Optional[Union[int, str]] = None,
problem_type: Optional[str] = None,
presets: Optional[str] = None,
eval_metric: Optional[str] = None,
hyperparameters: Optional[dict] = None,
path: Optional[str] = None,
verbosity: Optional[int] = 3,
warn_if_exist: Optional[bool] = True,
enable_progress_bar: Optional[bool] = None,
):
"""
Parameters
----------
query
Column names of query data.
response
Column names of response data. If no label column is provided,
query and response columns form positive pairs.
label
Name of the label column.
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 ["match", "not match"]. And match_label can be "match".
It is similar as the "pos_label" in F1-score: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html#sklearn.metrics.f1_score
Internally, we will set match_label to self.class_labels[1] by default.
problem_type
Type of matching problem if the label column is available.
This could be binary, multiclass, or regression
if the label column contains binary, multiclass, or numeric labels.
If `problem_type = None`, the prediction problem type is inferred
based on the label-values in provided dataset.
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.
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)
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.
"""
if eval_metric is not None and not isinstance(eval_metric, str):
eval_metric = eval_metric.name
if os.environ.get(AUTOMM_TUTORIAL_MODE):
verbosity = 1 # don't use 3, which doesn't suppress logger.info() in .load().
enable_progress_bar = False
if verbosity is not None:
set_logger_verbosity(verbosity, logger=logger)
if isinstance(query, str):
query = [query]
if query:
assert all(isinstance(q, str) for q in query)
if isinstance(response, str):
response = [response]
if response:
assert all(isinstance(r, str) for r in response)
self._query = query
self._response = response
self._data_format = PAIR # TODO: Support Triplet
self._match_label = match_label
self._label_column = label
self._problem_type = None # always infer problem type for matching.
self._pipeline = problem_type.lower() if problem_type is not None else None
self._presets = presets.lower() if presets else None
self._eval_metric_name = eval_metric
self._validation_metric_name = None
self._output_shape = None
self._save_path = path
self._ckpt_path = None
self._pretrained_path = None
self._config = None
self._query_config = None
self._response_config = None
self._query_df_preprocessor = None
self._response_df_preprocessor = None
self._label_df_preprocessor = None
self._column_types = None
self._query_processors = None
self._response_processors = None
self._label_processors = None
self._query_model = None
self._response_model = None
self._resume = False
self._fit_called = 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
if self._pipeline is not None: # TODO: do not create pretrained model for HPO presets.
(
self._config,
self._query_config,
self._response_config,
self._query_model,
self._response_model,
self._query_processors,
self._response_processors,
) = init_pretrained_matcher(
pipeline=self._pipeline, presets=self._presets, hyperparameters=hyperparameters
)
@property
def query(self):
return self._query
@property
def response(self):
return self._response
@property
def match_label(self):
return self._match_label
@property
def path(self):
return self._save_path
@property
def label(self):
return self._label_column
@property
def problem_type(self):
if self._pipeline and self._problem_type:
return f"{self._pipeline}_{self._problem_type}"
elif self._pipeline:
return self._pipeline
else:
return self._problem_type
@property
def column_types(self):
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
"""
self._verbosity = verbosity
set_logger_verbosity(verbosity, logger=logger)
def fit(
self,
train_data: pd.DataFrame,
id_mappings: Optional[Union[Dict[str, Dict], Dict[str, pd.Series]]] = None,
presets: Optional[str] = None,
tuning_data: Optional[pd.DataFrame] = 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,
hyperparameter_tune_kwargs: Optional[dict] = None,
seed: Optional[int] = 123,
):
"""
Fit MultiModalMatcher. Train the model to learn embeddings to simultaneously maximize and minimize
the semantic similarities of positive and negative pairs.
The data may contain image, text, numeric, or categorical features.
Parameters
----------
train_data
A dataframe, containing the query data, response data, and their relevance scores. For example,
| query_col1 | query_col2 | response_col1 | response_col2 | relevance_score |
|-------------|------------|---------------|---------------|-----------------|
| .... | .... | .... | ... | ... |
| .... | .... | .... | ... | ... |
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.
presets
Presets regarding model quality, e.g., best_quality, high_quality, and medium_quality.
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`.
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.
seed
The random seed to use for this training run.
Returns
-------
An "MultiModalMatcher" object (itself).
"""
fit_called = self._fit_called # used in current function
self._fit_called = True
pl.seed_everything(seed, workers=True)
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,
)
if isinstance(train_data, str):
train_data = load_pd.load(train_data)
if isinstance(tuning_data, str):
tuning_data = load_pd.load(tuning_data)
train_data, tuning_data = split_train_tuning_data(
train_data=train_data,
tuning_data=tuning_data,
holdout_frac=holdout_frac,
is_classification=self._problem_type in [BINARY, MULTICLASS, CLASSIFICATION],
label_column=self._label_column,
seed=seed,
)
column_types = infer_column_types(
data=train_data,
valid_data=tuning_data,
label_columns=self._label_column,
provided_column_types=column_types,
id_mappings=id_mappings,
)
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,
)
problem_type, 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,
)
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 is not None:
if self._problem_type == CLASSIFICATION:
# Set the problem type to be inferred problem type
self._problem_type = problem_type
assert self._problem_type == problem_type, (
f"Inferred problem type {problem_type} is different from " f"the previous {self._problem_type}"
)
if self._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}"
)
if self._validation_metric_name is None or self._eval_metric_name is None:
validation_metric_name, eval_metric_name = infer_metrics(
problem_type=problem_type,
is_matching=self._pipeline in matcher_presets.list_keys(),
eval_metric_name=self._eval_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)
if self._presets is not None:
presets = self._presets
else:
self._presets = presets
# set attributes for saving and prediction
self._problem_type = problem_type # In case problem type isn't provided in __init__().
self._eval_metric_name = eval_metric_name # In case eval_metric isn't provided in __init__().
self._validation_metric_name = validation_metric_name
self._output_shape = output_shape
self._column_types = column_types
hyperparameters, hyperparameter_tune_kwargs = update_hyperparameters(
problem_type=self._pipeline,
presets=presets,
provided_hyperparameters=hyperparameters,
provided_hyperparameter_tune_kwargs=hyperparameter_tune_kwargs,
)
hpo_mode = True if hyperparameter_tune_kwargs else False
if hpo_mode:
hyperparameters = filter_hyperparameters(
hyperparameters=hyperparameters,
column_types=column_types,
config=self._config,
fit_called=fit_called,
)
_fit_args = dict(
train_df=train_data,
val_df=tuning_data,
id_mappings=id_mappings,
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,
hyperparameters=hyperparameters,
hpo_mode=hpo_mode, # skip average checkpoint if in hpo mode
)
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,
is_matching=True,
**_fit_args,
)
return predictor
self._fit(**_fit_args)
# TODO(?) We should have a separate "_post_training_event()" for logging messages.
logger.info(get_fit_complete_message(self._save_path))
return self
def _get_matcher_df_preprocessor(
self,
data: pd.DataFrame,
column_types: Dict,
query_config: Optional[DictConfig] = None,
response_config: Optional[DictConfig] = None,
query_columns: Optional[List] = None,
response_columns: Optional[List] = None,
):
if query_columns is None:
query_df_preprocessor = None
elif self._query_df_preprocessor is None and all(v is not None for v in [query_columns, query_config]):
query_df_preprocessor = init_df_preprocessor(
config=query_config,
column_types={k: column_types[k] for k in query_columns},
train_df_x=data[query_columns],
)
else: # continuing training
query_df_preprocessor = self._query_df_preprocessor
if response_columns is None:
response_df_preprocessor = None
elif self._response_df_preprocessor is None and all(
v is not None for v in [response_columns, response_config]
):
response_df_preprocessor = init_df_preprocessor(
config=response_config,
column_types={k: column_types[k] for k in response_columns},
train_df_x=data[response_columns],
)
else: # continuing training
response_df_preprocessor = self._response_df_preprocessor
if self._label_column is None:
label_df_preprocessor = None
elif (
self._label_df_preprocessor is None and response_config is not None and self._label_column in column_types
):
label_df_preprocessor = init_df_preprocessor(
config=response_config,
column_types={self._label_column: column_types[self._label_column]},
label_column=self._label_column,
train_df_y=data[self._label_column],
)
else: # continuing training
label_df_preprocessor = self._label_df_preprocessor
return query_df_preprocessor, response_df_preprocessor, label_df_preprocessor
def _get_matcher_data_processors(
self,
query_model: Optional[nn.Module] = None,
query_config: Optional[DictConfig] = None,
response_model: Optional[nn.Module] = None,
response_config: Optional[DictConfig] = None,
):
if query_model is None:
query_processors = None
elif self._query_processors is None and all(v is not None for v in [query_model, query_config]):
query_processors = create_fusion_data_processors(
model=query_model,
config=query_config,
requires_label=False,
requires_data=True,
)
else: # continuing training
query_processors = self._query_processors
if response_model is None:
response_processors = None
elif self._response_processors is None and all(v is not None for v in [response_model, response_config]):
response_processors = create_fusion_data_processors(
model=response_model,
config=response_config,
requires_label=False,
requires_data=True,
)
else: # continuing training
response_processors = self._response_processors
# only need labels for the response model
if response_model is None:
label_processors = None
elif self._label_processors is None and all(
v is not None for v in [self._label_column, response_model, response_config]
):
label_processors = create_fusion_data_processors(
model=response_model,
config=response_config,
requires_label=True,
requires_data=False,
)
else: # continuing training
label_processors = self._label_processors
return query_processors, response_processors, label_processors
def _fit(
self,
train_df: pd.DataFrame,
val_df: pd.DataFrame,
id_mappings: Union[Dict[str, Dict], Dict[str, pd.Series]],
validation_metric_name: str,
minmax_mode: str,
max_time: timedelta,
save_path: str,
ckpt_path: str,
resume: bool,
enable_progress_bar: bool,
presets: Optional[str] = None,
hyperparameters: Optional[Union[str, Dict, List[str]]] = None,
hpo_mode: bool = False,
**hpo_kwargs,
):
# TODO(?) We should have a separate "_pre_training_event()" for logging messages.
logger.info(get_fit_start_message(save_path, validation_metric_name))
config = self._config
config = get_config(
problem_type=self._pipeline,
presets=presets,
config=config,
overrides=hyperparameters,
extra=["matcher"],
)
if self._query_config is None:
query_config = copy.deepcopy(config)
# customize config model names to make them consistent with model prefixes.
query_config.model, _ = customize_model_names(
config=query_config.model, customized_names=[f"{n}_{QUERY}" for n in query_config.model.names]
)
else:
query_config = self._query_config
if self._response_config is None:
response_config = copy.deepcopy(config)
# customize config model names to make them consistent with model prefixes.
response_config.model, _ = customize_model_names(
config=response_config.model,
customized_names=[f"{n}_{RESPONSE}" for n in response_config.model.names],
)
else:
response_config = self._response_config
query_df_preprocessor, response_df_preprocessor, label_df_preprocessor = self._get_matcher_df_preprocessor(
data=train_df,
column_types=self._column_types,
query_config=query_config,
response_config=response_config,
query_columns=self._query,
response_columns=self._response,
)
query_config = select_model(config=query_config, df_preprocessor=query_df_preprocessor, strict=False)
response_config = select_model(config=response_config, df_preprocessor=response_df_preprocessor, strict=False)
if self._query_model is None or self._response_model is None:
query_model, response_model = create_siamese_model(
query_config=query_config,
response_config=response_config,
)
else: # continuing training
query_model = self._query_model
response_model = self._response_model
query_processors, response_processors, label_processors = self._get_matcher_data_processors(
query_model=query_model,
query_config=query_config,
response_model=response_model,
response_config=response_config,
)
query_processors_count = {k: len(v) for k, v in query_processors.items()}
logger.debug(f"query_processors_count: {query_processors_count}")
response_processors_count = {k: len(v) for k, v in response_processors.items()}
logger.debug(f"response_processors_count: {response_processors_count}")
if label_processors:
label_processors_count = {k: len(v) for k, v in label_processors.items()}
logger.debug(f"label_processors_count: {label_processors_count}")
validation_metric, custom_metric_func = get_metric(
metric_name=validation_metric_name,
num_classes=self._output_shape,
is_matching=self._pipeline in matcher_presets.list_keys(),
problem_type=self._problem_type,
)
logger.debug(f"validation_metric_name: {validation_metric_name}")
logger.debug(f"validation_metric: {validation_metric}")
logger.debug(f"custom_metric_func: {custom_metric_func}")
loss_func = get_matcher_loss_func(
data_format=self._data_format,
problem_type=self._problem_type,
loss_type=config.matcher.loss.type,
pos_margin=config.matcher.loss.pos_margin,
neg_margin=config.matcher.loss.neg_margin,
distance_type=config.matcher.distance.type,
)
miner_func = None
if self._problem_type == BINARY:
miner_func = get_matcher_miner_func(
miner_type=config.matcher.miner.type,
pos_margin=config.matcher.miner.pos_margin,
neg_margin=config.matcher.miner.neg_margin,
distance_type=config.matcher.distance.type,
)
self._config = config
self._query_config = query_config
self._response_config = response_config
self._query_model = query_model
self._response_model = response_model
self._query_df_preprocessor = query_df_preprocessor
self._response_df_preprocessor = response_df_preprocessor
self._label_df_preprocessor = label_df_preprocessor
self._query_processors = query_processors
self._response_processors = response_processors
self._label_processors = label_processors
self._loss_func = loss_func
if max_time == timedelta(seconds=0):
self._top_k_average(
query_model=query_model,
response_model=response_model,
save_path=save_path,
minmax_mode=minmax_mode,
top_k_average_method=config.optimization.top_k_average_method,
val_df=val_df,
validation_metric_name=validation_metric_name,
)
return self
df_preprocessors = [query_df_preprocessor, response_df_preprocessor, label_df_preprocessor]
data_processors = [query_processors, response_processors, label_processors]
df_preprocessors = [item for item in df_preprocessors if item is not None]
data_processors = [item for item in data_processors if item is not None]
assert len(df_preprocessors) == len(data_processors)
train_dm = BaseDataModule(
df_preprocessor=df_preprocessors,
data_processors=data_processors,
per_gpu_batch_size=config.env.per_gpu_batch_size,
num_workers=config.env.num_workers,
train_data=train_df,
validate_data=val_df,
id_mappings=id_mappings,
)
optimization_kwargs = dict(
optim_type=config.optimization.optim_type,
lr_choice=config.optimization.lr_choice,
lr_schedule=config.optimization.lr_schedule,
lr=config.optimization.learning_rate,
lr_decay=config.optimization.lr_decay,
end_lr=config.optimization.end_lr,
lr_mult=config.optimization.lr_mult,
weight_decay=config.optimization.weight_decay,
warmup_steps=config.optimization.warmup_steps,
)
metrics_kwargs = dict(
validation_metric=validation_metric,
validation_metric_name=validation_metric_name,
custom_metric_func=custom_metric_func,
)
if self._match_label is not None:
match_label = label_df_preprocessor.label_generator.transform([self._match_label]).item()
else:
match_label = None
task = MatcherLitModule(
query_model=query_model,
response_model=response_model,
match_label=match_label,
loss_func=loss_func,
miner_func=miner_func,
**metrics_kwargs,
**optimization_kwargs,
)
logger.debug(f"validation_metric_name: {task.validation_metric_name}")
logger.debug(f"minmax_mode: {minmax_mode}")
checkpoint_callback = AutoMMModelCheckpoint(
dirpath=save_path,
save_top_k=config.optimization.top_k,
verbose=True,
monitor=task.validation_metric_name,
mode=minmax_mode,
save_last=True,
)
early_stopping_callback = pl.callbacks.EarlyStopping(
monitor=task.validation_metric_name,
patience=config.optimization.patience,
mode=minmax_mode,
stopping_threshold=get_stopping_threshold(validation_metric_name),
)
lr_callback = pl.callbacks.LearningRateMonitor(logging_interval="step")
model_summary = pl.callbacks.ModelSummary(max_depth=1)
callbacks = [
checkpoint_callback,
early_stopping_callback,
lr_callback,
model_summary,
]
use_ray_lightning = "_ray_lightning_plugin" in hpo_kwargs
if hpo_mode:
if use_ray_lightning:
from ray_lightning.tune import TuneReportCheckpointCallback
else:
from ray.tune.integration.pytorch_lightning import TuneReportCheckpointCallback
tune_report_callback = TuneReportCheckpointCallback(
{f"{task.validation_metric_name}": f"{task.validation_metric_name}"},
filename=RAY_TUNE_CHECKPOINT,
)
callbacks = [
tune_report_callback,
early_stopping_callback,
lr_callback,
model_summary,
]
tb_logger = pl.loggers.TensorBoardLogger(
save_dir=save_path,
name="",
version="",
)
num_gpus = compute_num_gpus(config_num_gpus=config.env.num_gpus, strategy=config.env.strategy)
precision = infer_precision(num_gpus=num_gpus, precision=config.env.precision)
if num_gpus == 0: # CPU only training
grad_steps = max(
config.env.batch_size // (config.env.per_gpu_batch_size * config.env.num_nodes),
1,
)
else:
grad_steps = max(
config.env.batch_size // (config.env.per_gpu_batch_size * num_gpus * config.env.num_nodes),
1,
)
if not hpo_mode:
if num_gpus <= 1:
strategy = "auto"
else:
strategy = config.env.strategy
else:
# we don't support running each trial in parallel without ray lightning
if use_ray_lightning:
strategy = hpo_kwargs.get("_ray_lightning_plugin")
else:
strategy = "auto"
num_gpus = min(num_gpus, 1)
config.env.num_gpus = num_gpus
config.env.precision = precision
config.env.strategy = strategy
self._config = config
# save artifacts for the current running, except for model checkpoint, which will be saved in trainer
self.save(save_path)
blacklist_msgs = ["already configured with model summary"]
log_filter = LogFilter(blacklist_msgs)
with apply_log_filter(log_filter):
trainer = pl.Trainer(
accelerator="gpu" if num_gpus > 0 else "auto",
devices=get_available_devices(
num_gpus=num_gpus,
auto_select_gpus=config.env.auto_select_gpus,
use_ray_lightning=use_ray_lightning,
),
num_nodes=config.env.num_nodes,
precision=precision,
strategy=strategy,
benchmark=False,
deterministic=config.env.deterministic,
max_epochs=config.optimization.max_epochs,
max_steps=config.optimization.max_steps,
max_time=max_time,
callbacks=callbacks,
logger=tb_logger,
gradient_clip_val=OmegaConf.select(config, "optimization.gradient_clip_val", default=1),
gradient_clip_algorithm=OmegaConf.select(
config, "optimization.gradient_clip_algorithm", default="norm"
),
accumulate_grad_batches=grad_steps,
log_every_n_steps=OmegaConf.select(config, "optimization.log_every_n_steps", default=10),
enable_progress_bar=enable_progress_bar,
fast_dev_run=config.env.fast_dev_run,
val_check_interval=config.optimization.val_check_interval,
check_val_every_n_epoch=config.optimization.check_val_every_n_epoch
if hasattr(config.optimization, "check_val_every_n_epoch")
else 1,
reload_dataloaders_every_n_epochs=1,
)
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
".*does not have many workers which may be a bottleneck. "
"Consider increasing the value of the `num_workers` argument` "
".* in the `DataLoader` init to improve performance.*",
)
warnings.filterwarnings("ignore", "Checkpoint directory .* exists and is not empty.")
trainer.fit(
task,
datamodule=train_dm,
ckpt_path=ckpt_path if resume else None, # this is to resume training that was broken accidentally
)
if trainer.global_rank == 0:
# We do not perform averaging checkpoint in the case of hpo for each trial
# We only average the checkpoint of the best trial in the end in the master process
if not hpo_mode:
self._top_k_average(
query_model=query_model,
response_model=response_model,
save_path=save_path,
minmax_mode=minmax_mode,
top_k_average_method=config.optimization.top_k_average_method,
val_df=val_df,
validation_metric_name=validation_metric_name,
)
else:
sys.exit(f"Training finished, exit the process with global_rank={trainer.global_rank}...")
def _top_k_average(
self,
query_model,
response_model,
save_path,
minmax_mode,
top_k_average_method,
val_df,
validation_metric_name,
last_ckpt_path=None,
):
best_k_models_yaml_path = os.path.join(save_path, BEST_K_MODELS_FILE)
if os.path.exists(best_k_models_yaml_path):
with open(best_k_models_yaml_path, "r") as f:
best_k_models = yaml.safe_load(f)
else:
# In some cases, the training ends up too early (e.g., due to time_limit) so that there is
# no saved best_k model checkpoints. In that scenario, we won't perform any model averaging.
best_k_models = None
if last_ckpt_path is None:
last_ckpt_path = os.path.join(save_path, LAST_CHECKPOINT)
if best_k_models:
if top_k_average_method == UNIFORM_SOUP:
logger.info(f"Start to fuse {len(best_k_models)} checkpoints via the uniform soup algorithm.")
ingredients = top_k_model_paths = list(best_k_models.keys())
else:
top_k_model_paths = [
v[0]
for v in sorted(
list(best_k_models.items()),
key=lambda ele: ele[1],
reverse=(minmax_mode == MAX),
)
]
if top_k_average_method == GREEDY_SOUP:
# Select the ingredients based on the methods proposed in paper
# "Model soups: averaging weights of multiple fine-tuned models improves accuracy without
# increasing inference time", https://arxiv.org/pdf/2203.05482.pdf
monitor_op = {MIN: operator.le, MAX: operator.ge}[minmax_mode]
logger.info(f"Start to fuse {len(top_k_model_paths)} checkpoints via the greedy soup algorithm.")
ingredients = [top_k_model_paths[0]]
self._query_model, self._response_model = self._load_state_dict(
query_model=query_model,
response_model=response_model,
path=top_k_model_paths[0],
)