This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 210
/
Copy pathinput_transform.py
1229 lines (920 loc) · 46.7 KB
/
input_transform.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
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
from dataclasses import dataclass
from functools import partial, wraps
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union
from pytorch_lightning.utilities.enums import LightningEnum
from pytorch_lightning.utilities.exceptions import MisconfigurationException
from torch.utils.data._utils.collate import default_collate
from flash.core.data.callback import ControlFlow, FlashCallback
from flash.core.data.io.input import DataKeys
from flash.core.data.properties import Properties
from flash.core.data.transforms import ApplyToKeys
from flash.core.data.utils import _INPUT_TRANSFORM_FUNCS, _STAGES_PREFIX
from flash.core.registry import FlashRegistry
from flash.core.utilities.stages import RunningStage
from flash.core.utilities.types import INPUT_TRANSFORM_TYPE
class InputTransformPlacement(LightningEnum):
PER_SAMPLE_TRANSFORM = "per_sample_transform"
PER_BATCH_TRANSFORM = "per_batch_transform"
COLLATE = "collate"
PER_SAMPLE_TRANSFORM_ON_DEVICE = "per_sample_transform_on_device"
PER_BATCH_TRANSFORM_ON_DEVICE = "per_batch_transform_on_device"
class ApplyToKeyPrefix(LightningEnum):
INPUT = "input"
TARGET = "target"
def transform_context(func: Callable, current_fn: str) -> Callable:
@wraps(func)
def wrapper(self, *args, **kwargs) -> Any:
self.current_fn = current_fn
result = func(self, *args, **kwargs)
self.current_fn = None
return result
return wrapper
# Credit to Torchvision Team:
# https://pytorch.org/vision/stable/_modules/torchvision/transforms/transforms.html#Compose
class Compose:
"""Composes several transforms together.
This transform does not support torchscript.
"""
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, x):
for t in self.transforms:
x = t(x)
return x
def __repr__(self):
format_string = self.__class__.__name__ + "("
for t in self.transforms:
format_string += "\n"
format_string += f"{t}"
format_string += "\n)"
return format_string
@dataclass
class InputTransform(Properties):
running_stage: RunningStage
def __post_init__(self):
# used to keep track of provided transforms
self._collate_in_worker_from_transform: Optional[bool] = None
self._transform = None
self._transform = self._check_transforms(self._resolve_transforms(self.running_stage), self.running_stage)
# Hack
Properties.__init__(self, running_stage=self.running_stage)
@property
def current_transform(self) -> Callable:
if self._transform:
return self._get_transform(self._transform)
return self._identity
@property
def transforms(self) -> Dict[str, Optional[Dict[str, Callable]]]:
"""The transforms currently being used by this
:class:`~flash.core.data.io.input_transform.InputTransform`."""
return {
"transform": self._transform,
}
########################
# PER SAMPLE TRANSFORM #
########################
def per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on a single sample on cpu for all stages stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_sample_transform(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def input_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each sample on
device for all stages stage."""
return self._identity
def target_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each sample on
device for all stages stage."""
return self._identity
def train_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on a single sample on cpu for the training stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
"""
return self._identity
def train_input_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the training stage."""
return self._identity
def train_target_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the training stage."""
return self._identity
def val_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on a single sample on cpu for the validating stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_sample_transform(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def val_input_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the validating stage."""
return self._identity
def val_target_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the validating stage."""
return self._identity
def test_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on a single sample on cpu for the testing stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
"""
return self._identity
def test_input_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the testing stage."""
return self._identity
def test_target_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the testing stage."""
return self._identity
def predict_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on a single sample on cpu for the predicting stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_sample_transform(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def predict_input_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the predicting stage."""
return self._identity
def predict_target_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the predicting stage."""
return self._identity
def serve_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on a single sample on cpu for the serving stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_sample_transform(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def serve_input_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the serving stage."""
return self._identity
def serve_target_per_sample_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the serving stage."""
return self._identity
##################################
# PER SAMPLE TRANSFORM ON DEVICE #
##################################
def per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a single sample on device for all stages stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_sample_transform_on_device(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def input_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each sample on
device for all stages stage."""
return self._identity
def target_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each sample on
device for all stages stage."""
return self._identity
def train_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a single sample on device for the training stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
"""
return self._identity
def train_input_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on device for the training stage."""
return self._identity
def train_target_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on device for the training stage."""
return self._identity
def val_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a single sample on device for the validating stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_sample_transform_on_device(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def val_input_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on device for the validating stage."""
return self._identity
def val_target_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on device for the validating stage."""
return self._identity
def test_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a single sample on device for the testing stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
"""
return self._identity
def test_input_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on device for the testing stage."""
return self._identity
def test_target_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on device for the testing stage."""
return self._identity
def predict_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a single sample on device for the predicting stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_sample_transform_on_device(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def predict_input_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on device for the predicting stage."""
return self._identity
def predict_target_per_sample_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on device for the predicting stage."""
return self._identity
#######################
# PER BATCH TRANSFORM #
#######################
def per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on a batch of data on cpu for all stages stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_batch_transform(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def input_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of batch on cpu for all
stages stage."""
return self._identity
def target_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of batch on cpu for
all stages stage."""
return self._identity
def train_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on a batch of data on cpu for the training stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
"""
return self._identity
def train_input_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the training stage."""
return self._identity
def train_target_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the training stage."""
return self._identity
def val_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on a batch of data on cpu for the validating stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_batch_transform(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def val_input_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the validating stage."""
return self._identity
def val_target_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the validating stage."""
return self._identity
def test_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on a batch of data on cpu for the testing stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
"""
return self._identity
def test_input_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the testing stage."""
return self._identity
def test_target_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the testing stage."""
return self._identity
def predict_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on a batch of data on cpu for the predicting stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_batch_transform(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def predict_input_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the predicting stage."""
return self._identity
def predict_target_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the predicting stage."""
return self._identity
def serve_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on a batch of data on cpu for the serving stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_batch_transform(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def serve_input_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on cpu for the serving stage."""
return self._identity
def serve_target_per_batch_transform(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on cpu for the serving stage."""
return self._identity
#################################
# PER BATCH TRANSFORM ON DEVICE #
#################################
def per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a batch of data on device for all stages stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_batch_transform_on_device(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def input_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of batch on device for
all stages stage."""
return self._identity
def target_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of batch on device for
all stages stage."""
return self._identity
def train_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a batch of data on device for the training stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
"""
return self._identity
def train_input_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on device for the training stage."""
return self._identity
def train_target_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on device for the training stage."""
return self._identity
def val_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a batch of data on device for the validating stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_batch_transform_on_device(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def val_input_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on device for the validating stage."""
return self._identity
def val_target_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on device for the validating stage."""
return self._identity
def test_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a batch of data on device for the testing stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
"""
return self._identity
def test_input_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on device for the testing stage."""
return self._identity
def test_target_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on device for the testing stage."""
return self._identity
def predict_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on a batch of data on device for the predicting stage.
The input data of the transform would have the following form::
{
DataKeys.INPUT: ...,
DataKeys.TARGET: ...,
DataKeys.METADATA: ...,
}
You would need to use :class:`flash.core.data.transforms.ApplyToKeys` as follows:
.. code-block:: python
from flash.core.data.transforms import ApplyToKeys
class MyInputTransform(InputTransform):
def per_batch_transform_on_device(self) -> Callable:
return ApplyToKeys("input", my_func)
"""
return self._identity
def predict_input_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "input" key of each single sample
on device for the predicting stage."""
return self._identity
def predict_target_per_batch_transform_on_device(self) -> Callable:
"""Defines the transform to be applied on the value associated with the "target" key of each single sample
on device for the predicting stage."""
return self._identity
###########
# COLLATE #
###########
def train_collate(self) -> Callable:
"""Defines the transform to be applied on a list of training sample to create a training batch."""
return default_collate
def val_collate(self) -> Callable:
"""Defines the transform to be applied on a list of validating sample to create a validating batch."""
return default_collate
def test_collate(self) -> Callable:
"""Defines the transform to be applied on a list of testing sample to create a testing batch."""
return default_collate
def predict_collate(self) -> Callable:
"""Defines the transform to be applied on a list of predicting sample to create a predicting batch."""
return default_collate
def serve_collate(self) -> Callable:
"""Defines the transform to be applied on a list of serving sample to create a serving batch."""
return default_collate
def collate(self) -> Callable:
"""Defines the transform to be applied on a list of sample to create a batch for all stages."""
return default_collate
########################################
# HOOKS CALLED INTERNALLY WITHIN FLASH #
########################################
@partial(transform_context, current_fn="per_sample_transform")
def _per_sample_transform(self, sample: Any) -> Any:
fn = self.current_transform
if isinstance(sample, list):
return [fn(s) for s in sample]
return fn(sample)
@partial(transform_context, current_fn="per_batch_transform")
def _per_batch_transform(self, batch: Any) -> Any:
"""Transforms to apply to a whole batch (if possible use this for efficiency).
.. note:: This option is mutually exclusive with :meth:`per_sample_transform_on_device`, since if both are
specified, uncollation has to be applied.
"""
return self.current_transform(batch)
@partial(transform_context, current_fn="collate")
def _collate(self, samples: Sequence, metadata=None) -> Any:
"""Transform to convert a sequence of samples to a collated batch."""
collate_fn = self.current_transform
parameters = inspect.signature(collate_fn).parameters
if len(parameters) > 1 and DataKeys.METADATA in parameters:
return collate_fn(samples, metadata)
return collate_fn(samples)
@partial(transform_context, current_fn="per_sample_transform_on_device")
def _per_sample_transform_on_device(self, sample: Any) -> Any:
"""Transforms to apply to the data before the collation (per-sample basis).
.. note:: This option is mutually exclusive with :meth:`per_batch_transform`, since if both are
specified, uncollation has to be applied. .. note:: This function won't be called within the dataloader
workers, since to make that happen each of the workers would have to create it's own CUDA-context which
would pollute GPU memory (if on GPU).
"""
fn = self.current_transform
if isinstance(sample, list):
return [fn(s) for s in sample]
return fn(sample)
@partial(transform_context, current_fn="per_batch_transform_on_device")
def _per_batch_transform_on_device(self, batch: Any) -> Any:
"""Transforms to apply to a whole batch (if possible use this for efficiency).
.. note:: This function won't be called within the dataloader workers, since to make that happen each of
the workers would have to create it's own CUDA-context which would pollute GPU memory (if on GPU).
"""
return self.current_transform(batch)
#############
# UTILITIES #
#############
def _resolve_transforms(self, running_stage: RunningStage) -> Optional[Dict[str, Callable]]:
from flash.core.data.data_pipeline import DataPipeline
transforms_out = {}
stage = _STAGES_PREFIX[running_stage]
# iterate over all transforms hook name
for transform_name in InputTransformPlacement:
transforms = {}
transform_name = transform_name.value
# iterate over all prefixes
for key in ApplyToKeyPrefix:
# get the resolved hook name based on the current stage
resolved_name = DataPipeline._resolve_function_hierarchy(
transform_name, self, running_stage, InputTransform
)
# check if the hook name is specialized
is_specialized_name = resolved_name.startswith(stage)
# get the resolved hook name for apply to key on the current stage
resolved_apply_to_key_name = DataPipeline._resolve_function_hierarchy(
f"{key}_{transform_name}", self, running_stage, InputTransform
)
# check if resolved hook name for apply to key is specialized
is_specialized_apply_to_key_name = resolved_apply_to_key_name.startswith(stage)
# check if they are overridden by the user
resolve_name_overridden = DataPipeline._is_overridden(resolved_name, self, InputTransform)
resolved_apply_to_key_name_overridden = DataPipeline._is_overridden(
resolved_apply_to_key_name, self, InputTransform
)
if resolve_name_overridden and resolved_apply_to_key_name_overridden:
# if both are specialized or both aren't specialized, raise a exception
# It means there is priority to specialize hooks name.
if not (is_specialized_name ^ is_specialized_apply_to_key_name):
raise MisconfigurationException(
f"Only one of {resolved_name} or {resolved_apply_to_key_name} can be overridden."
)
method_name = resolved_name if is_specialized_name else resolved_apply_to_key_name
else:
method_name = resolved_apply_to_key_name if resolved_apply_to_key_name_overridden else resolved_name
# get associated transform
try:
fn = getattr(self, method_name)()
except AttributeError as e:
raise AttributeError(str(e) + ". Hint: Call super().__init__(...) after setting all attributes.")
if not callable(fn):
raise MisconfigurationException(f"The hook {method_name} should return a function.")
# if the default hook is used, it should return identity, skip it.
if fn is self._identity:
continue
# wrap apply to key hook into `ApplyToKeys` with the associated key.
if method_name == resolved_apply_to_key_name:
fn = ApplyToKeys(key.value, fn)
if method_name not in transforms:
transforms[method_name] = fn
# store the transforms.
if transforms:
transforms = list(transforms.values())
transforms_out[transform_name] = Compose(transforms) if len(transforms) > 1 else transforms[0]
return transforms_out
def _check_transforms(
self, transform: Optional[Dict[str, Callable]], stage: RunningStage
) -> Optional[Dict[str, Callable]]:
if transform is None:
return transform
keys_diff = set(transform.keys()).difference([v.value for v in InputTransformPlacement])
if len(keys_diff) > 0:
raise MisconfigurationException(
f"{stage}_transform contains {keys_diff}. Only {_INPUT_TRANSFORM_FUNCS} keys are supported."
)
is_per_batch_transform_in = "per_batch_transform" in transform
is_per_sample_transform_on_device_in = "per_sample_transform_on_device" in transform
if is_per_batch_transform_in and is_per_sample_transform_on_device_in:
raise MisconfigurationException(
f"{transform}: `per_batch_transform` and `per_sample_transform_on_device` are mutually exclusive."
)
collate_in_worker: Optional[bool] = None
if is_per_batch_transform_in or (not is_per_batch_transform_in and not is_per_sample_transform_on_device_in):
collate_in_worker = True
elif is_per_sample_transform_on_device_in:
collate_in_worker = False
self._collate_in_worker_from_transform = collate_in_worker
return transform
@staticmethod
def _identity(x: Any) -> Any:
return x
def _get_transform(self, transform: Dict[str, Callable]) -> Callable:
if self.current_fn in transform:
return transform[self.current_fn]
return self._identity