-
Notifications
You must be signed in to change notification settings - Fork 38
/
torch.py
2813 lines (2548 loc) · 116 KB
/
torch.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
'''PyTorch backend for the slideflow.model submodule.'''
import inspect
import json
import os
import types
import numpy as np
import multiprocessing as mp
import pandas as pd
import torch
import torchvision
from torch import Tensor
from torch.nn.functional import softmax
from packaging import version
from rich.progress import Progress, TimeElapsedColumn
from collections import defaultdict
from os.path import join
from pandas.api.types import is_float_dtype, is_integer_dtype
from typing import (TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple,
Union, Callable)
import slideflow as sf
import slideflow.util.neptune_utils
from slideflow import errors
from slideflow.model import base as _base
from slideflow.model import torch_utils
from slideflow.model.torch_utils import autocast
from slideflow.model.base import log_manifest, BaseFeatureExtractor
from slideflow.util import log, NormFit, ImgBatchSpeedColumn, no_scope
if TYPE_CHECKING:
import pandas as pd
from slideflow.norm import StainNormalizer
class LinearBlock(torch.nn.Module):
'''Block module that includes a linear layer -> ReLU -> BatchNorm'''
def __init__(
self,
in_ftrs: int,
out_ftrs: int,
dropout: Optional[float] = None
) -> None:
super().__init__()
self.in_ftrs = in_ftrs
self.out_ftrs = out_ftrs
self.linear = torch.nn.Linear(in_ftrs, out_ftrs)
self.relu = torch.nn.ReLU(inplace=True)
self.bn = torch.nn.BatchNorm1d(out_ftrs)
if dropout:
self.dropout = torch.nn.Dropout(dropout)
else:
self.dropout = None # type: ignore
def forward(self, x: Tensor) -> Tensor:
x = self.linear(x)
x = self.relu(x)
x = self.bn(x)
if self.dropout is not None:
x = self.dropout(x)
return x
class ModelWrapper(torch.nn.Module):
'''Wrapper for PyTorch modules to support multiple outcomes, clinical
(patient-level) inputs, and additional hidden layers.'''
def __init__(
self,
model: Any,
n_classes: List[int],
num_slide_features: int = 0,
hidden_layers: Optional[List[int]] = None,
drop_images: bool = False,
dropout: Optional[float] = None,
include_top: bool = True
) -> None:
super().__init__()
self.model = model
self.n_classes = len(n_classes)
self.drop_images = drop_images
self.num_slide_features = num_slide_features
self.num_hidden_layers = 0 if not hidden_layers else len(hidden_layers)
self.has_aux = False
log.debug(f'Model class name: {model.__class__.__name__}')
if not drop_images:
# Check for auxillary classifier
if model.__class__.__name__ in ('Inception3',):
log.debug("Auxillary classifier detected")
self.has_aux = True
# Get the last linear layer prior to the logits layer
if model.__class__.__name__ in ('Xception', 'NASNetALarge'):
num_ftrs = self.model.last_linear.in_features
self.model.last_linear = torch.nn.Identity()
elif model.__class__.__name__ in ('SqueezeNet'):
num_ftrs = 1000
elif hasattr(self.model, 'classifier'):
children = list(self.model.classifier.named_children())
if len(children):
# VGG, AlexNet
if include_top:
log.debug("Including existing fully-connected "
"top classifier layers")
last_linear_name, last_linear = children[-1]
num_ftrs = last_linear.in_features
setattr(
self.model.classifier,
last_linear_name,
torch.nn.Identity()
)
elif model.__class__.__name__ in ('AlexNet',
'MobileNetV2',
'MNASNet'):
log.debug("Removing fully-connected classifier layers")
_, first_classifier = children[1]
num_ftrs = first_classifier.in_features
self.model.classifier = torch.nn.Identity()
elif model.__class__.__name__ in ('VGG', 'MobileNetV3'):
log.debug("Removing fully-connected classifier layers")
_, first_classifier = children[0]
num_ftrs = first_classifier.in_features
self.model.classifier = torch.nn.Identity()
else:
num_ftrs = self.model.classifier.in_features
self.model.classifier = torch.nn.Identity()
elif hasattr(self.model, 'fc'):
num_ftrs = self.model.fc.in_features
self.model.fc = torch.nn.Identity()
elif hasattr(self.model, 'out_features'):
num_ftrs = self.model.out_features
elif hasattr(self.model, 'head'):
num_ftrs = self.model.head.out_features
else:
print(self.model)
raise errors.ModelError("Unable to find last linear layer for "
f"model {model.__class__.__name__}")
else:
num_ftrs = 0
# Add slide-level features
num_ftrs += num_slide_features
# Add hidden layers
if hidden_layers:
hl_ftrs = [num_ftrs] + hidden_layers
for i in range(len(hidden_layers)):
setattr(self, f'h{i}', LinearBlock(hl_ftrs[i],
hl_ftrs[i+1],
dropout=dropout))
num_ftrs = hidden_layers[-1]
# Add the outcome/logits layers for each outcome, if multiple outcomes
for i, n in enumerate(n_classes):
setattr(self, f'fc{i}', torch.nn.Linear(num_ftrs, n))
def __getattr__(self, name: str) -> Any:
try:
return super().__getattr__(name)
except AttributeError as e:
if name == 'model':
raise e
return getattr(self.model, name)
def forward(
self,
img: Tensor,
slide_features: Optional[Tensor] = None
):
if slide_features is None and self.num_slide_features:
raise ValueError("Expected 2 inputs, got 1")
# Last linear of core convolutional model
if not self.drop_images:
x = self.model(img)
# Discard auxillary classifier
if self.has_aux and self.training:
x = x.logits
# Merging image data with any slide-level input data
if self.num_slide_features and not self.drop_images:
assert slide_features is not None
x = torch.cat([x, slide_features], dim=1)
elif self.num_slide_features:
x = slide_features
# Hidden layers
if self.num_hidden_layers:
x = self.h0(x)
if self.num_hidden_layers > 1:
for h in range(1, self.num_hidden_layers):
x = getattr(self, f'h{h}')(x)
# Return a list of outputs if we have multiple outcomes
if self.n_classes > 1:
out = [getattr(self, f'fc{i}')(x) for i in range(self.n_classes)]
# Otherwise, return the single output
else:
out = self.fc0(x)
return out # , x
class ModelParams(_base._ModelParams):
"""Build a set of hyperparameters."""
ModelDict = {
'resnet18': torchvision.models.resnet18,
'resnet50': torchvision.models.resnet50,
'alexnet': torchvision.models.alexnet,
'squeezenet': torchvision.models.squeezenet.squeezenet1_1,
'densenet': torchvision.models.densenet161,
'inception': torchvision.models.inception_v3,
'googlenet': torchvision.models.googlenet,
'shufflenet': torchvision.models.shufflenet_v2_x1_0,
'resnext50_32x4d': torchvision.models.resnext50_32x4d,
'vgg16': torchvision.models.vgg16, # needs support added
'mobilenet_v2': torchvision.models.mobilenet_v2,
'mobilenet_v3_small': torchvision.models.mobilenet_v3_small,
'mobilenet_v3_large': torchvision.models.mobilenet_v3_large,
'wide_resnet50_2': torchvision.models.wide_resnet50_2,
'mnasnet': torchvision.models.mnasnet1_0,
'xception': torch_utils.xception,
'nasnet_large': torch_utils.nasnetalarge
}
def __init__(self, *, loss: str = 'CrossEntropy', **kwargs) -> None:
self.OptDict = {
'Adadelta': torch.optim.Adadelta,
'Adagrad': torch.optim.Adagrad,
'Adam': torch.optim.Adam,
'AdamW': torch.optim.AdamW,
'SparseAdam': torch.optim.SparseAdam,
'Adamax': torch.optim.Adamax,
'ASGD': torch.optim.ASGD,
'LBFGS': torch.optim.LBFGS,
'RMSprop': torch.optim.RMSprop,
'Rprop': torch.optim.Rprop,
'SGD': torch.optim.SGD
}
self.LinearLossDict = {
'L1': torch.nn.L1Loss,
'MSE': torch.nn.MSELoss,
'NLL': torch.nn.NLLLoss, # negative log likelihood
'HingeEmbedding': torch.nn.HingeEmbeddingLoss,
'SmoothL1': torch.nn.SmoothL1Loss,
'CosineEmbedding': torch.nn.CosineEmbeddingLoss,
'CoxProportionalHazardsLoss': torch_utils.CoxProportionalHazardsLoss,
}
self.AllLossDict = {
'CrossEntropy': torch.nn.CrossEntropyLoss,
'CTC': torch.nn.CTCLoss,
'PoissonNLL': torch.nn.PoissonNLLLoss,
'GaussianNLL': torch.nn.GaussianNLLLoss,
'KLDiv': torch.nn.KLDivLoss,
'BCE': torch.nn.BCELoss,
'BCEWithLogits': torch.nn.BCEWithLogitsLoss,
'MarginRanking': torch.nn.MarginRankingLoss,
'MultiLabelMargin': torch.nn.MultiLabelMarginLoss,
'Huber': torch.nn.HuberLoss,
'SoftMargin': torch.nn.SoftMarginLoss,
'MultiLabelSoftMargin': torch.nn.MultiLabelSoftMarginLoss,
'MultiMargin': torch.nn.MultiMarginLoss,
'TripletMargin': torch.nn.TripletMarginLoss,
'TripletMarginWithDistance': torch.nn.TripletMarginWithDistanceLoss,
'L1': torch.nn.L1Loss,
'MSE': torch.nn.MSELoss,
'NLL': torch.nn.NLLLoss, # negative log likelihood
'HingeEmbedding': torch.nn.HingeEmbeddingLoss,
'SmoothL1': torch.nn.SmoothL1Loss,
'CosineEmbedding': torch.nn.CosineEmbeddingLoss,
'CoxProportionalHazardsLoss': torch_utils.CoxProportionalHazardsLoss,
}
super().__init__(loss=loss, **kwargs)
assert self.model in self.ModelDict.keys() or self.model.startswith('timm_')
assert self.optimizer in self.OptDict.keys()
assert self.loss in self.AllLossDict
if self.model == 'inception':
log.warn("Model 'inception' has an auxillary classifier, which "
"is currently ignored during training. Auxillary "
"classifier loss will be included during training "
"starting in version 1.3")
def get_opt(self, params_to_update: Iterable) -> torch.optim.Optimizer:
return self.OptDict[self.optimizer](
params_to_update,
lr=self.learning_rate,
weight_decay=self.l2
)
def get_loss(self) -> torch.nn.modules.loss._Loss:
return self.AllLossDict[self.loss]()
def get_model_loader(self, model: str) -> Callable:
if model in self.ModelDict:
return self.ModelDict[model]
elif model.startswith('timm_'):
def loader(**kwargs):
try:
import timm
except ImportError:
raise ImportError(f"Unable to load model {model}; "
"timm package not installed.")
return timm.create_model(model[5:], **kwargs)
return loader
else:
raise ValueError(f"Model {model} not found.")
def build_model(
self,
labels: Optional[Dict] = None,
num_classes: Optional[Union[int, Dict[Any, int]]] = None,
num_slide_features: int = 0,
pretrain: Optional[str] = None,
checkpoint: Optional[str] = None
) -> torch.nn.Module:
if self.model_type() == 'cph':
num_slide_features = num_slide_features - 1
assert num_classes is not None or labels is not None
if num_classes is None:
assert labels is not None
num_classes = self._detect_classes_from_labels(labels)
if not isinstance(num_classes, dict):
num_classes = {'out-0': num_classes}
# Prepare custom model pretraining
if pretrain:
log.debug(f"Using pretraining: [green]{pretrain}")
if (isinstance(pretrain, str)
and sf.util.path_to_ext(pretrain).lower() == 'zip'):
_pretrained = pretrain
pretrain = None
else:
_pretrained = None
# Build base model
if self.model in ('xception', 'nasnet_large'):
_model = self.get_model_loader(self.model)(
num_classes=1000,
pretrained=pretrain
)
else:
# Compatibility logic for prior versions of PyTorch
model_fn = self.get_model_loader(self.model)
model_fn_sig = inspect.signature(model_fn)
model_kw = [
param.name
for param in model_fn_sig.parameters.values()
if param.kind == param.POSITIONAL_OR_KEYWORD
]
call_kw = {}
if 'image_size' in model_kw:
call_kw.update(dict(image_size=self.tile_px))
if (version.parse(torchvision.__version__) >= version.parse("0.13")
and not self.model.startswith('timm_')):
# New Torchvision API
w = 'DEFAULT' if pretrain == 'imagenet' else pretrain
call_kw.update(dict(weights=w)) # type: ignore
else:
call_kw.update(dict(pretrained=pretrain)) # type: ignore
_model = model_fn(**call_kw)
# Add final layers to models
hidden_layers = [
self.hidden_layer_width
for _ in range(self.hidden_layers)
]
model = ModelWrapper(
_model,
list(num_classes.values()),
num_slide_features,
hidden_layers,
self.drop_images,
dropout=self.dropout,
include_top=self.include_top
)
if _pretrained is not None:
lazy_load_pretrained(model, _pretrained)
if checkpoint is not None:
model.load_state_dict(torch.load(checkpoint))
return model
def model_type(self) -> str:
"""Returns 'linear', 'categorical', or 'cph', reflecting the loss."""
#check if loss is custom_[type] and returns type
if self.loss.startswith('custom'):
return self.loss[7:]
elif self.loss == 'CoxProportionalHazardsLoss':
return 'cph'
elif self.loss in self.LinearLossDict:
return 'linear'
else:
return 'categorical'
class Trainer:
"""Base trainer class containing functionality for model building, input
processing, training, and evaluation.
This base class requires categorical outcome(s). Additional outcome types
are supported by :class:`slideflow.model.LinearTrainer` and
:class:`slideflow.model.CPHTrainer`.
Slide-level (e.g. clinical) features can be used as additional model input
by providing slide labels in the slide annotations dictionary, under
the key 'input'.
"""
_model_type = 'categorical'
def __init__(
self,
hp: ModelParams,
outdir: str,
labels: Dict[str, Any],
*,
slide_input: Optional[Dict[str, Any]] = None,
name: str = 'Trainer',
feature_sizes: Optional[List[int]] = None,
feature_names: Optional[List[str]] = None,
outcome_names: Optional[List[str]] = None,
mixed_precision: bool = True,
allow_tf32: bool = False,
config: Dict[str, Any] = None,
use_neptune: bool = False,
neptune_api: Optional[str] = None,
neptune_workspace: Optional[str] = None,
load_method: str = 'weights',
custom_objects: Optional[Dict[str, Any]] = None,
device: Optional[str] = None,
transform: Optional[Union[Callable, Dict[str, Callable]]] = None
):
"""Sets base configuration, preparing model inputs and outputs.
Args:
hp (:class:`slideflow.ModelParams`): ModelParams object.
outdir (str): Destination for event logs and checkpoints.
labels (dict): Dict mapping slide names to outcome labels (int or
float format).
slide_input (dict): Dict mapping slide names to additional
slide-level input, concatenated after post-conv.
name (str, optional): Optional name describing the model, used for
model saving. Defaults to None.
feature_sizes (list, optional): List of sizes of input features.
Required if providing additional input features as model input.
feature_names (list, optional): List of names for input features.
Used when permuting feature importance.
outcome_names (list, optional): Name of each outcome. Defaults to
"Outcome {X}" for each outcome.
mixed_precision (bool, optional): Use FP16 mixed precision (rather
than FP32). Defaults to True.
allow_tf32 (bool): Allow internal use of Tensorfloat-32 format.
Defaults to False.
config (dict, optional): Training configuration dictionary, used
for logging and image format verification. Defaults to None.
use_neptune (bool, optional): Use Neptune API logging.
Defaults to False
neptune_api (str, optional): Neptune API token, used for logging.
Defaults to None.
neptune_workspace (str, optional): Neptune workspace.
Defaults to None.
load_method (str): Loading method to use when reading model.
This argument is ignored in the PyTorch backend, as all models
are loaded by first building the model with hyperparameters
detected in ``params.json``, then loading weights with
``torch.nn.Module.load_state_dict()``. Defaults to
'full' (ignored).
transform (callable or dict, optional): Optional transform to
apply to input images. If dict, must have the keys 'train'
and/or 'val', mapping to callables that takes a single
image Tensor as input and returns a single image Tensor.
If None, no transform is applied. If a single callable is
provided, it will be applied to both training and validation
data. If a dict is provided, the 'train' transform will be
applied to training data and the 'val' transform will be
applied to validation data. If a dict is provided and either
'train' or 'val' is None, no transform will be applied to
that data. Defaults to None.
"""
self.hp = hp
self.slides = list(labels.keys())
self.slide_input = slide_input
self.feature_names = feature_names
self.feature_sizes = feature_sizes
self.num_slide_features = 0 if not feature_sizes else sum(feature_sizes)
self.outdir = outdir
self.labels = labels
self.patients = dict() # type: Dict[str, str]
self.name = name
self.model = None # type: Optional[torch.nn.Module]
self.inference_model = None # type: Optional[torch.nn.Module]
self.mixed_precision = mixed_precision
self.device = torch_utils.get_device(device)
self.mid_train_val_dts: Optional[Iterable] = None
self.loss_fn: torch.nn.modules.loss._Loss
self.use_tensorboard: bool
self.writer = None # type: Optional[torch.utils.tensorboard.SummaryWriter]
self._reset_training_params()
# Slide-level input args
if slide_input:
self.slide_input = {
k: [float(vi) for vi in v]
for k, v in slide_input.items()
}
else:
self.slide_input = None # type: ignore
if custom_objects is not None:
log.warn("custom_objects argument ignored in PyTorch backend.")
# Enable or disable Tensorflow-32
# Allows PyTorch to internally use tf32 for matmul and convolutions
torch.backends.cuda.matmul.allow_tf32 = allow_tf32
torch.backends.cudnn.allow_tf32 = allow_tf32 # type: ignore
self._allow_tf32 = allow_tf32
self._process_outcome_labels(outcome_names)
self._setup_inputs()
self.normalizer = self.hp.get_normalizer()
if self.normalizer:
log.info(f'Using realtime {self.hp.normalizer} normalization')
if not os.path.exists(outdir):
os.makedirs(outdir)
self._process_transforms(transform)
if isinstance(labels, pd.DataFrame):
cat_assign = self._process_category_assignments()
# Log parameters
if config is None:
config = {
'slideflow_version': sf.__version__,
'backend': sf.backend(),
'git_commit': sf.__gitcommit__,
'model_name': self.name,
'full_model_name': self.name,
'outcomes': self.outcome_names,
'model_type': self.hp.model_type(),
'img_format': None,
'tile_px': self.hp.tile_px,
'tile_um': self.hp.tile_um,
'input_features': None,
'input_feature_sizes': None,
'input_feature_labels': None,
'hp': self.hp.to_dict(),
}
if isinstance(labels, pd.DataFrame):
config['outcome_labels'] = {str(k): v for k,v in cat_assign.items()}
sf.util.write_json(config, join(self.outdir, 'params.json'))
# Neptune logging
self.config = config
self.img_format = config['img_format'] if 'img_format' in config else None
self.use_neptune = use_neptune
self.neptune_run = None
if self.use_neptune:
if neptune_api is None or neptune_workspace is None:
raise ValueError("If using Neptune, must supply neptune_api"
" and neptune_workspace.")
self.neptune_logger = sf.util.neptune_utils.NeptuneLog(
neptune_api,
neptune_workspace
)
@property
def num_outcomes(self) -> int:
if self.hp.model_type() == 'categorical':
assert self.outcome_names is not None
return len(self.outcome_names)
else:
return 1
@property
def multi_outcome(self) -> bool:
return (self.num_outcomes > 1)
def _process_category_assignments(self) -> Dict[int, str]:
"""Get category assignments for categorical outcome labels.
Dataframes with integer labels are assumed to be categorical if
if hp.model_type is 'categorical'.
Dataframes with float labels are assumed to be linear.
Dataframes with other labels are assumed to be categorical, and will
be assigned an integer label based on the order of unique values.
"""
if not isinstance(self.labels, pd.DataFrame):
raise ValueError("Expected DataFrame with 'label' column.")
if 'label' not in self.labels.columns:
raise ValueError("Expected DataFrame with 'label' column.")
if self.hp.model_type() == 'categorical':
if is_integer_dtype(self.labels['label']) or is_float_dtype(self.labels['label']):
return {i: str(i) for i in sorted(self.labels['label'].unique())}
else:
int_to_str = dict(enumerate(sorted(self.labels['label'].unique())))
str_to_int = {v: k for k, v in int_to_str.items()}
log.info("Assigned integer labels to categories:")
log.info(str_to_int)
self.labels['label'] = self.labels['label'].map(str_to_int)
return int_to_str
else:
return {}
def _process_transforms(
self,
transform: Optional[Union[Callable, Dict[str, Callable]]] = None
) -> None:
"""Process custom transformations for training and/or validation."""
if not isinstance(transform, dict):
transform = {'train': transform, 'val': transform}
if any([t not in ('train', 'val') for t in transform]):
raise ValueError("transform must be a callable or dict with keys "
"'train' and/or 'val'")
if 'train' not in transform:
transform['train'] = None
if 'val' not in transform:
transform['val'] = None
self.transform = transform
def _setup_inputs(self) -> None:
if self.num_slide_features:
assert self.slide_input is not None
try:
if self.num_slide_features:
log.info(f'Training with both images and '
f'{self.num_slide_features} slide-level input'
'features')
except KeyError:
raise errors.ModelError("Unable to find slide-level input at "
"'input' key in annotations")
for slide in self.slides:
if len(self.slide_input[slide]) != self.num_slide_features:
num_in_feature_table = len(self.slide_input[slide])
raise errors.ModelError(
f'Length of input for slide {slide} does not match '
f'feature_sizes; expected {self.num_slide_features}, '
f'got {num_in_feature_table}'
)
def _process_outcome_labels(
self,
outcome_names: Optional[List[str]] = None,
) -> None:
"""Process outcome labels to determine number of outcomes and names.
Supports experimental tile-level labels provided via pandas DataFrame.
Args:
labels (dict): Dict mapping slide names to outcome labels (int or
float format). Experimental funtionality: if labels is a
pandas DataFrame, the 'label' column will be used as the
outcome labels.
outcome_names (list, optional): Name of each outcome. Defaults to
"Outcome {X}" for each outcome.
"""
# Process DataFrame tile-level labels
if isinstance(self.labels, pd.DataFrame):
if 'label' not in self.labels.columns:
raise errors.ModelError("Expected DataFrame with 'label' "
"column.")
if outcome_names and len(outcome_names) > 1:
raise errors.ModelError(
"Expected single outcome name for labels from a pandas dataframe."
)
self.outcome_names = outcome_names or ['Outcome 0']
return
# Process dictionary slide-level labels
outcome_labels = np.array(list(self.labels.values()))
if len(outcome_labels.shape) == 1:
outcome_labels = np.expand_dims(outcome_labels, axis=1)
if not outcome_names:
self.outcome_names = [
f'Outcome {i}'
for i in range(outcome_labels.shape[1])
]
else:
self.outcome_names = outcome_names
if not len(self.outcome_names) == outcome_labels.shape[1]:
n_names = len(self.outcome_names)
n_out = outcome_labels.shape[1]
raise errors.ModelError(f"Number of outcome names ({n_names}) does"
f" not match number of outcomes ({n_out})")
def _reset_training_params(self) -> None:
self.global_step = 0
self.epoch = 0 # type: int
self.step = 0 # type: int
self.log_frequency = 0 # type: int
self.early_stop = False # type: bool
self.moving_average = [] # type: List
self.dataloaders = {} # type: Dict[str, Any]
self.validation_batch_size = None # type: Optional[int]
self.validate_on_batch = 0
self.validation_steps = 0
self.ema_observations = 0 # type: int
self.ema_smoothing = 0
self.last_ema = -1 # type: float
self.ema_one_check_prior = -1 # type: float
self.ema_two_checks_prior = -1 # type: float
self.epoch_records = 0 # type: int
self.running_loss = 0.0
self.running_corrects = {} # type: Union[Tensor, Dict[str, Tensor]]
def _accuracy_as_numpy(
self,
acc: Union[Tensor, float, List[Tensor], List[float]]
) -> Union[float, List[float]]:
if isinstance(acc, list):
return [t.item() if isinstance(t, Tensor) else t for t in acc]
else:
return (acc.item() if isinstance(acc, Tensor) else acc)
def _build_model(
self,
checkpoint: Optional[str] = None,
pretrain: Optional[str] = None
) -> None:
if checkpoint:
log.info(f"Loading checkpoint at [green]{checkpoint}")
self.load(checkpoint)
else:
self.model = self.hp.build_model(
labels=self.labels,
pretrain=pretrain,
num_slide_features=self.num_slide_features
)
# Create an inference model before any multi-GPU parallelization
# is applied to the self.model parameter
self.inference_model = self.model
def _calculate_accuracy(
self,
running_corrects: Union[Tensor, Dict[Any, Tensor]],
num_records: int = 1
) -> Tuple[Union[Tensor, List[Tensor]], str]:
'''Reports accuracy of each outcome.'''
assert self.hp.model_type() == 'categorical'
if self.num_outcomes > 1:
if not isinstance(running_corrects, dict):
raise ValueError("Expected running_corrects to be a dict:"
" num_outcomes is > 1")
acc_desc = ''
acc_list = [running_corrects[r] / num_records
for r in running_corrects]
for o in range(len(running_corrects)):
_acc = running_corrects[f'out-{o}'] / num_records
acc_desc += f"out-{o} acc: {_acc:.4f} "
return acc_list, acc_desc
else:
assert not isinstance(running_corrects, dict)
_acc = running_corrects / num_records
return _acc, f'acc: {_acc:.4f}'
def _calculate_loss(
self,
outputs: Union[Tensor, List[Tensor]],
labels: Union[Tensor, Dict[Any, Tensor]],
loss_fn: torch.nn.modules.loss._Loss
) -> Tensor:
'''Calculates loss in a manner compatible with multiple outcomes.'''
if self.num_outcomes > 1:
if not isinstance(labels, dict):
raise ValueError("Expected labels to be a dict: num_outcomes"
" is > 1")
loss = sum([
loss_fn(out, labels[f'out-{o}'])
for o, out in enumerate(outputs)
])
else:
loss = loss_fn(outputs, labels)
return loss # type: ignore
def _check_early_stopping(
self,
val_acc: Optional[Union[float, List[float]]] = None,
val_loss: Optional[float] = None
) -> str:
if val_acc is None and val_loss is None:
if (self.hp.early_stop
and self.hp.early_stop_method == 'manual'
and self.hp.manual_early_stop_epoch <= self.epoch # type: ignore
and self.hp.manual_early_stop_batch <= self.step): # type: ignore
log.info(f'Manual early stop triggered: epoch {self.epoch}, '
f'batch {self.step}')
if self.epoch not in self.hp.epochs:
self.hp.epochs += [self.epoch]
self.early_stop = True
else:
if self.hp.early_stop_method == 'accuracy':
if self.num_outcomes > 1:
raise errors.ModelError(
"Early stopping method 'accuracy' not supported with"
" multiple outcomes; use 'loss'.")
early_stop_val = val_acc
else:
early_stop_val = val_loss
assert early_stop_val is not None
assert isinstance(early_stop_val, float)
self.moving_average += [early_stop_val]
if len(self.moving_average) >= self.ema_observations:
# Only keep track of the last [ema_observations]
self.moving_average.pop(0)
if self.last_ema == -1:
# Simple moving average
self.last_ema = (sum(self.moving_average)
/ len(self.moving_average)) # type: ignore
log_msg = f' (SMA: {self.last_ema:.3f})'
else:
alpha = (self.ema_smoothing / (1 + self.ema_observations))
self.last_ema = (early_stop_val * alpha
+ (self.last_ema * (1 - alpha)))
log_msg = f' (EMA: {self.last_ema:.3f})'
if self.neptune_run and self.last_ema != -1:
neptune_dest = "metrics/val/batch/exp_moving_avg"
self.neptune_run[neptune_dest].log(self.last_ema)
if (self.hp.early_stop
and self.ema_two_checks_prior != -1
and self.epoch > self.hp.early_stop_patience):
if ((self.hp.early_stop_method == 'accuracy'
and self.last_ema <= self.ema_two_checks_prior)
or (self.hp.early_stop_method == 'loss'
and self.last_ema >= self.ema_two_checks_prior)):
log.info(f'Early stop triggered: epoch {self.epoch}, '
f'step {self.step}')
self._log_early_stop_to_neptune()
if self.epoch not in self.hp.epochs:
self.hp.epochs += [self.epoch]
self.early_stop = True
return log_msg
self.ema_two_checks_prior = self.ema_one_check_prior
self.ema_one_check_prior = self.last_ema
return ''
def _detect_patients(self, *args):
self.patients = dict()
for dataset in args:
if dataset is None:
continue
dataset_patients = dataset.patients()
if not dataset_patients:
self.patients.update({s: s for s in self.slides})
else:
self.patients.update(dataset_patients)
def _empty_corrects(self) -> Union[int, Dict[str, int]]:
if self.multi_outcome:
return {
f'out-{o}': 0
for o in range(self.num_outcomes)
}
else:
return 0
def _epoch_metrics(
self,
acc: Union[float, List[float]],
loss: float,
label: str
) -> Dict[str, Dict[str, Union[float, List[float]]]]:
epoch_metrics = {'loss': loss} # type: Dict
if self.hp.model_type() == 'categorical':
epoch_metrics.update({'accuracy': acc})
return {f'{label}_metrics': epoch_metrics}
def _update_loss(self, pred, labels, running_loss, size):
labels = self._labels_to_device(labels, self.device)
loss = self._calculate_loss(pred, labels, self.loss_fn)
return running_loss + (loss.item() * size)
def _val_metrics(self, **kwargs) -> Dict[str, Dict[str, float]]:
"""Evaluate model and calculate metrics.
Returns:
Dict[str, Dict[str, float]]: Dict with validation metrics.
Returns metrics in the form:
```
{
'val_metrics': {
'loss': ...,
'accuracy': ...,
},
'tile_auc': ...,
'slide_auc': ...,
...
}
```
"""
if hasattr(self, 'optimizer'):
self.optimizer.zero_grad()
assert self.model is not None
self.model.eval()
results_log = os.path.join(self.outdir, 'results_log.csv')
epoch_results = {}
# Preparations for calculating accuracy/loss in metrics_from_dataset()
def update_corrects(pred, labels, running_corrects=None):
if running_corrects is None:
running_corrects = self._empty_corrects()
if self.hp.model_type() == 'categorical':
labels = self._labels_to_device(labels, self.device)
return self._update_corrects(pred, labels, running_corrects)
else:
return 0
torch_args = types.SimpleNamespace(
update_corrects=update_corrects,
update_loss=self._update_loss,
num_slide_features=self.num_slide_features,
slide_input=self.slide_input,
normalizer=(self.normalizer if self._has_gpu_normalizer() else None),
)
# Calculate patient/slide/tile metrics (AUC, R-squared, C-index, etc)
metrics, acc, loss = sf.stats.metrics_from_dataset(
self.inference_model,
model_type=self.hp.model_type(),
patients=self.patients,
dataset=self.dataloaders['val'],
data_dir=self.outdir,
outcome_names=self.outcome_names,
neptune_run=self.neptune_run,
torch_args=torch_args,
uq=bool(self.hp.uq),
**kwargs
)
loss_and_acc = {'loss': loss}
if self.hp.model_type() == 'categorical':
loss_and_acc.update({'accuracy': acc})
self._log_epoch(
'val',
self.epoch,
loss,
self._calculate_accuracy(acc)[1] # type: ignore
)
epoch_metrics = {'val_metrics': loss_and_acc}
for metric in metrics:
if metrics[metric]['tile'] is None:
continue
epoch_results[f'tile_{metric}'] = metrics[metric]['tile']
epoch_results[f'slide_{metric}'] = metrics[metric]['slide']
epoch_results[f'patient_{metric}'] = metrics[metric]['patient']
epoch_metrics.update(epoch_results)
sf.util.update_results_log(
results_log,
'trained_model',
{f'epoch{self.epoch}': epoch_metrics}
)
self._log_eval_to_neptune(loss, acc, metrics, epoch_metrics)
return epoch_metrics
def _fit_normalizer(self, norm_fit: Optional[NormFit]) -> None:
"""Fit the Trainer normalizer using the specified fit, if applicable.
Args:
norm_fit (Optional[Dict[str, np.ndarray]]): Normalizer fit.
"""
if norm_fit is not None and not self.normalizer:
raise ValueError("norm_fit supplied, but model params do not"
"specify a normalizer.")
if self.normalizer and norm_fit is not None:
self.normalizer.set_fit(**norm_fit) # type: ignore
elif (self.normalizer
and 'norm_fit' in self.config
and self.config['norm_fit'] is not None):
log.debug("Detecting normalizer fit from model config")
self.normalizer.set_fit(**self.config['norm_fit'])
def _has_gpu_normalizer(self) -> bool:
import slideflow.norm.torch
return (isinstance(self.normalizer, sf.norm.torch.TorchStainNormalizer)
and self.normalizer.device != "cpu")
def _labels_to_device(
self,
labels: Union[Dict[Any, Tensor], Tensor],
device: torch.device
) -> Union[Dict[Any, Tensor], Tensor]:
'''Moves a set of outcome labels to the given device.'''
if self.num_outcomes > 1:
if not isinstance(labels, dict):
raise ValueError("Expected labels to be a dict: num_outcomes"
" is > 1")
labels = {