-
Notifications
You must be signed in to change notification settings - Fork 39
/
schema.py
1927 lines (1575 loc) · 57.5 KB
/
schema.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import math
import torch
import numpy as np
import torch.nn as nn
from abc import abstractmethod
from abc import ABC
from abc import ABCMeta
from copy import deepcopy
from enum import Enum
from torch import Tensor
from typing import Any
from typing import Set
from typing import Dict
from typing import List
from typing import Type
from typing import Tuple
from typing import Union
from typing import Generic
from typing import TypeVar
from typing import Callable
from typing import Optional
from typing import Protocol
from typing import NamedTuple
from accelerate import Accelerator
from dataclasses import dataclass
from torch.optim import Optimizer
from cftool.misc import filter_kw
from cftool.misc import print_info
from cftool.misc import print_warning
from cftool.misc import safe_execute
from cftool.misc import check_requires
from cftool.misc import shallow_copy_dict
from cftool.misc import get_num_positional_args
from cftool.misc import context_error_handler
from cftool.misc import WithRegister
from cftool.misc import DataClassBase
from cftool.misc import PureFromInfoMixin
from cftool.misc import ISerializable
from cftool.misc import IWithRequirements
from cftool.misc import ISerializableArrays
from cftool.misc import ISerializableDataClass
from cftool.array import to_numpy
from cftool.array import to_torch
from cftool.types import np_dict_type
from cftool.types import tensor_dict_type
from cftool.pipeline import IBlock
from cftool.pipeline import IPipeline
from torch.optim.lr_scheduler import _LRScheduler
from .types import data_type
from .types import losses_type
from .types import configs_type
from .types import sample_weights_type
from .types import forward_results_type
from .constants import LOSS_KEY
from .constants import INPUT_KEY
from .constants import LABEL_KEY
from .constants import PREDICTIONS_KEY
from .misc.toolkit import is_local_rank_0
from .misc.toolkit import get_clones
from .misc.toolkit import get_device
from .misc.toolkit import get_world_size
from .misc.toolkit import fix_denormal_states
from .misc.toolkit import eval_context
from .misc.toolkit import ONNX
try:
import onnx
except:
onnx = None
try:
from onnxsim import simplify as onnx_simplify
def get_inputs(model: onnx.ModelProto) -> List[onnx.ValueInfoProto]:
initializer_names = [x.name for x in model.graph.initializer]
return [inp for inp in model.graph.input if inp.name not in initializer_names]
def get_input_names(model: onnx.ModelProto) -> List[str]:
input_names = [inp.name for inp in get_inputs(model)]
return input_names
except:
onnx_simplify = get_input_names = None # type: ignore
model_dict: Dict[str, Type["IDLModel"]] = {}
monitor_dict: Dict[str, Type["TrainerMonitor"]] = {}
loss_dict: Dict[str, Type["ILoss"]] = {}
metric_dict: Dict[str, Type["IMetric"]] = {}
callback_dict: Dict[str, Type["TrainerCallback"]] = {}
data_dict: Dict[str, Type["IData"]] = {}
data_processor_configs: Dict[str, Type["DataProcessorConfig"]] = {}
data_configs: Dict[str, Type["DataConfig"]] = {}
trainer_configs: Dict[str, Type["TrainerConfig"]] = {}
TData = TypeVar("TData", bound="IData", covariant=True)
TLoss = TypeVar("TLoss", bound="ILoss", covariant=True)
TSplitSW = Tuple[Optional[np.ndarray], Optional[np.ndarray]]
TDataLoaders = Tuple["IDataLoader", Optional["IDataLoader"]]
TDataBundleItem = Optional[Union[data_type, np_dict_type, tensor_dict_type, Any]]
TDataBlock = TypeVar("TDataBlock", bound="IDataBlock", covariant=True)
TDataProcessor = TypeVar("TDataProcessor", bound="DataProcessor", covariant=True)
# data
"""
Design of the `IData` system:
* `IData` itself only holds minimal configurations, but will hold some data - which are
constructed into a `DataBundle` - temporarily, in case we need to use the data immediately
(e.g. use them for training), or need to serialize them.
* Complicated logics are maintained by `DataProcessor`, which is an `IPipeline` constructed
by a series of `IDataBlock`.
* `DataProcessor` itself has no information except for a global `config`, and logics are held
in each `IDataBlock`.
* An `IDataBlock` need to do four jobs:
* `transform`: transform a `DataBundle` into a new `DataBundle`.
* `fit_transform`: collect necessary info and perform `transform`.
* `postprocess_item` (optional): post process an incoming item.
> multiple items will be 'collated' into a batch
* `recover_labels` (optional): recover labels to their original format.
Typical workflows are:
* Training : raw data -> `fit_transform` -> transformed data
-> fetch items -> `postprocess_item` -> collate -> processed batch
-> model -> predictions -> `recover_labels`
* Inference: raw data -> `transform` -> transformed data
-> fetch items -> `postprocess_item` -> collate -> processed batch
-> model -> predictions -> `recover_labels`
> When serializing, a property called `bundle` (the `DataBundle`) will be saved, which holds
the 'transformed data'. So after the serialization, we don't need to run `fit_transform`/`transform`
anymore, and can reuse the `bundle` property directly.
> However we can also serialize `IData` without saving `bundle` (which is a better choice when
we only want to serialize it for inference). In this case, we need to run `transform` on new datasets.
The above statements indicate that:
* `transform`/`fit_transform` are at the 'pre-calculation' stage.
* `postprocess_item`/`recover_labels` are at the 'on the fly' stage.
Common use cases are:
* ML datasets: will mostly utilize `transform`/`fit_transform`, because most ML datasets
can be transfered into a numpy-based datasets, which should be calculated beforehand
because directly indexing numpy arrays is very fast while streaming them will be slow.
* CV/NLP datasets: will mostly utilize `postprocess_item`, because most CV/NLP datasets
are very large, which means it is impossible to be pre-calculated because that will
cost too much RAM. Instead, common practice is to 'stream' the datasets, which means many
calculations must be done 'on the fly'.
* `recover_labels` might be used across all kinds of datasets, because labels may always need
to be transformed.
"""
def copy_data(data: TDataBundleItem) -> data_type:
if data is None:
return None
if isinstance(data, dict):
return {k: copy_data(v) for k, v in data.items()}
if isinstance(data, np.ndarray):
return data.copy()
if isinstance(data, Tensor):
return data.clone()
return data
def check_data_is_info(data: TDataBundleItem) -> bool:
if (
data is None
or isinstance(data, dict)
or isinstance(data, np.ndarray)
or isinstance(data, Tensor)
):
return False
try:
json.dumps([data])
return True
except:
return False
def norm_sw(sample_weights: Optional[np.ndarray]) -> Optional[np.ndarray]:
if sample_weights is None:
return None
return sample_weights / sample_weights.sum()
def split_sw(sample_weights: sample_weights_type) -> TSplitSW:
if sample_weights is None:
train_weights = valid_weights = None
else:
if not isinstance(sample_weights, np.ndarray):
train_weights, valid_weights = sample_weights
else:
train_weights, valid_weights = sample_weights, None
train_weights, valid_weights = map(norm_sw, [train_weights, valid_weights])
return train_weights, valid_weights
class IDataset(ABC):
@abstractmethod
def __len__(self) -> int:
pass
@abstractmethod
def __getitem__(self, item: Union[int, List[int], np.ndarray]) -> Dict[str, Any]:
pass
class IDataLoader(ABC):
dataset: IDataset
batch_size: int
def __init__(self, *, sample_weights: Optional[np.ndarray] = None):
self.sample_weights = sample_weights
@abstractmethod
def __iter__(self) -> "IDataLoader":
pass
@abstractmethod
def __next__(self) -> np_dict_type:
pass
@abstractmethod
def disable_shuffle(self) -> None:
pass
@abstractmethod
def recover_shuffle(self) -> None:
pass
def __len__(self) -> int:
return math.ceil(len(self.dataset) / self.batch_size)
def copy(self) -> "IDataLoader":
return deepcopy(self)
def temporarily_disable_shuffle(self) -> context_error_handler:
class _(context_error_handler):
def __init__(self, loader: IDataLoader):
self.loader = loader
def __enter__(self) -> None:
self.loader.disable_shuffle()
def _normal_exit(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
self.loader.recover_shuffle()
return _(self)
def get_full_batch(self) -> np_dict_type:
batch_size = self.batch_size
self.batch_size = len(self.dataset)
full_batch = next(iter(self))
self.batch_size = batch_size
return full_batch
class DataArgs(NamedTuple):
x: TDataBundleItem
y: TDataBundleItem
others: Optional[np_dict_type]
@property
def xy(self) -> Tuple[TDataBundleItem, TDataBundleItem]:
return self.x, self.y
@dataclass
class DataBundle(DataClassBase):
x_train: TDataBundleItem
y_train: TDataBundleItem = None
x_valid: TDataBundleItem = None
y_valid: TDataBundleItem = None
train_others: Optional[np_dict_type] = None
valid_others: Optional[np_dict_type] = None
@property
def train_args(self) -> DataArgs:
return DataArgs(self.x_train, self.y_train, self.train_others)
@property
def valid_args(self) -> DataArgs:
return DataArgs(self.x_valid, self.y_valid, self.valid_others)
def copy(self) -> "DataBundle":
return DataBundle(*map(copy_data, self.attributes))
def to_info(self) -> Dict[str, Any]:
info: Dict[str, Any] = {}
for k, v in self.asdict().items():
if check_data_is_info(v):
info[k] = v
return info
def from_info(self, info: Dict[str, Any]) -> None:
for k, v in info.items():
setattr(self, k, v)
def to_npd(self) -> np_dict_type:
def _to_np(key: str, data: Union[np.ndarray, Tensor]) -> np.ndarray:
if isinstance(data, np.ndarray):
return data
tensor_keys.append(key)
return to_numpy(data)
npd: np_dict_type = {}
tensor_keys: List[str] = []
for k, v in self.asdict().items():
if isinstance(v, dict):
v = {f"{k}.{vk}": vv for vk, vv in v.items()}
npd.update({vk: _to_np(vk, vv) for vk, vv in v.items()})
elif isinstance(v, (np.ndarray, Tensor)):
npd[k] = _to_np(k, v)
if tensor_keys:
npd["__tensor_keys__"] = np.array(tensor_keys)
return npd
def from_npd(self, npd: np_dict_type) -> None:
attr_collections: Dict[str, Union[np_dict_type, tensor_dict_type]] = {}
tensor_keys = set(npd.pop("__tensor_keys__", np.array([])).tolist())
for k, v in npd.items():
attr = None
if "." in k:
attr, k = k.split(".", 1)
if k in tensor_keys:
v = to_torch(v)
if attr is None:
setattr(self, k, v)
else:
attr_collections.setdefault(attr, {})[k] = v
for attr, collection in attr_collections.items():
setattr(self, attr, collection)
@classmethod
def empty(cls) -> "DataBundle":
return cls(None)
class IDataBlock(PureFromInfoMixin, IBlock, ISerializable, metaclass=ABCMeta):
"""
`IDataBlock` is a block that can transform data, it's initialization/serialization
is designed as follows:
1. The `__init__` method:
* should not include arguments that do not have default values.
* should and only should contain arguments which is defined in the `fields` property.
2. The `fields` property should and only should contain fields which can be initialized
in the `__init__` method.
3. The `fit_transform` method should not introduce more fields (except for `INoInitDataBlock`).
4. `IDataBlock` implements a `to_info` method, which record and only record the properties
defined in the `fields` property.
* This method should not be overwritten, except for `INoInitDataBlock`.
5. `IDataBlock` inherits `PureFromInfoMixin`, which means all properties will be
properly restored from the info returned by `to_info` method.
For any class inheriting `IDataBlock`, it can be easily initialized
with the help of the `get_arguments` function from `cftool.misc`.
Examples
--------
>>> from cftool.misc import get_arguments
>>>
>>> class MyBlock(IDataBlock):
>>> def __init__(self, foo: int = 1, bar: str = "two"):
>>> super().__init__(**get_arguments())
>>>
>>> @property
>>> def init_fields(self) -> List[str]:
>>> return ["foo", "bar"]
>>>
>>> ...
>>>
>>> block = MyBlock()
>>> print(block.foo, block.bar) # 1 two
"""
config: "DataProcessorConfig"
previous: Dict[str, "IDataBlock"]
def __init__(self, **kwargs: Any) -> None:
not_exists_tag = "$$NOT_EXISTS$$"
for field in self.fields:
value = kwargs.get(field, not_exists_tag)
if value == not_exists_tag:
raise ValueError(
f"Argument '{field}' needs to be provided "
f"for `{self.__class__.__name__}`."
)
setattr(self, field, value)
# inherit
def build(self, config: "DataProcessorConfig") -> None:
self.config = config
configs = (config.block_configs or {}).setdefault(self.__identifier__, {})
for field in self.fields:
setattr(self, field, configs.setdefault(field, getattr(self, field)))
def to_info(self) -> Dict[str, Any]:
return {field: getattr(self, field) for field in self.fields}
# abstract
@property
@abstractmethod
def fields(self) -> List[str]:
pass
@abstractmethod
def transform(self, bundle: DataBundle, for_inference: bool) -> DataBundle:
"""
This method should not utilize `config`!
Changes can happen inplace.
"""
@abstractmethod
def fit_transform(self, bundle: DataBundle) -> DataBundle:
"""
This method should prepare necessary info, which might be used
in the `to_info` method.
If any necessary info comes from `config`, this method should extract
them and assign them to the corresponding properties.
This method will NOT be called in a loading procedure, and the
necessary info should be loaded in the `from_info` method.
This method will always assume `for_inference=False`.
Changes can happen inplace.
"""
# optional callbacks
# changes can happen inplace
def postprocess_item(self, item: Any) -> Any:
return item
# changes can happen inplace
def recover_labels(self, y: np.ndarray) -> np.ndarray:
return y
# api
@property
def is_local_rank_0(self) -> bool:
return is_local_rank_0()
class INoInitDataBlock(IDataBlock):
"""
This type of blocks assume:
* No property assignments should happen at initialization stage.
* All properties should be maintained in the `fit_transform` stage.
"""
@property
def fields(self) -> List[str]:
return []
class IRuntimeDataBlock(IDataBlock, metaclass=ABCMeta):
"""
Runtime blocks will store no information, and will only process the batches
at runtime. When dealing with CV/NLP datasets, we'll often use this kind of blocks.
"""
@property
def fields(self) -> List[str]:
return []
def transform(self, bundle: DataBundle, for_inference: bool) -> DataBundle:
return bundle
def fit_transform(self, bundle: DataBundle) -> DataBundle:
return bundle
@abstractmethod
def postprocess_item(self, item: Any) -> Any:
"""changes can happen inplace"""
@dataclass
class DataProcessorConfig(ISerializableDataClass):
block_names: Optional[List[str]] = None
block_configs: Optional[Dict[str, Dict[str, Any]]] = None
@classmethod
def d(cls) -> Dict[str, Type["DataProcessorConfig"]]:
return data_processor_configs
@property
def default_blocks(self) -> List[IDataBlock]:
return []
def add_blocks(self, *blocks: IDataBlock) -> None:
if self.block_names is None:
self.block_names = []
for b in blocks:
b_id = b.__identifier__
if b_id in self.block_names:
print_warning(f"block `{b_id}` already exists, it will be skipped")
self.block_names.append(b_id)
if isinstance(b, INoInitDataBlock):
continue
if self.block_configs is None:
self.block_configs = {}
self.block_configs[b_id] = b.to_info()
def set_blocks(self, *blocks: IDataBlock) -> None:
self.block_names = []
self.add_blocks(*blocks)
@IPipeline.register("base.data_processor")
class DataProcessor(IPipeline):
config: DataProcessorConfig
blocks: List[IDataBlock]
is_ready: bool = False
# inheritance
@classmethod
def init(
cls: Type[TDataProcessor],
config: Optional[DataProcessorConfig],
) -> TDataProcessor:
self: DataProcessor = cls()
self.config = (config or self.config_base()).copy()
if self.config.block_names is None:
self.config.set_blocks(*self.config.default_blocks)
self.before_build_in_init()
self.build(*(IDataBlock.get(name)() for name in self.config.block_names)) # type: ignore
return self
# optional callbacks
@property
def config_base(self) -> Type[DataProcessorConfig]:
return DataProcessorConfig
@property
def block_base(self) -> Type[IDataBlock]:
return IDataBlock
def before_build_in_init(self) -> None:
pass
def after_load(self) -> None:
self.is_ready = True
# api
def _run(self, fn: str, bundle: DataBundle, for_inference: bool) -> DataBundle:
kw = dict(bundle=bundle.copy(), for_inference=for_inference)
previous: Dict[str, IDataBlock] = {}
for block in self.blocks:
block.previous = previous
kw["bundle"] = safe_execute(getattr(block, fn), kw)
previous[block.__identifier__] = block
return kw["bundle"] # type: ignore
def transform(self, bundle: DataBundle, *, for_inference: bool) -> DataBundle:
return self._run("transform", bundle, for_inference)
def fit_transform(self, bundle: DataBundle) -> DataBundle:
bundle = self._run("fit_transform", bundle, False)
self.is_ready = True
return bundle
# changes can happen inplace
def postprocess_item(self, item: Any) -> np_dict_type:
for block in self.blocks:
item = block.postprocess_item(item)
return item
def recover_labels(self, y: np.ndarray) -> np.ndarray:
for block in self.blocks[::-1]:
y = block.recover_labels(y)
return y
@dataclass
class DataConfig(ISerializableDataClass):
for_inference: bool = False
batch_size: int = 1
valid_batch_size: Optional[int] = None
shuffle_train: bool = True
shuffle_valid: bool = False
@classmethod
def d(cls) -> Dict[str, Type["DataConfig"]]:
return data_configs
class IData(ISerializableArrays, Generic[TData], metaclass=ABCMeta):
d = data_dict
train_dataset: IDataset
valid_dataset: Optional[IDataset]
train_weights: Optional[np.ndarray]
valid_weights: Optional[np.ndarray]
config: DataConfig
processor: DataProcessor
bundle: Optional[DataBundle]
for_inference: bool
def __init__(self) -> None:
self.train_weights = None
self.valid_weights = None
# abstract
@abstractmethod
def get_loaders(self) -> TDataLoaders:
pass
# inheritance
def to_info(self) -> Dict[str, Any]:
if not self.processor.is_ready:
raise ValueError(
"`processor` should be ready before calling `to_info`, "
"did you forget to call the `fit` method first?"
)
return {
"type": self.__identifier__,
"processor": self.processor.to_pack().asdict(),
"config": self.config.to_pack().asdict(),
"bundle": None if self.bundle is None else self.bundle.to_info(),
}
def from_info(self, info: Dict[str, Any]) -> None:
if self.__identifier__ != info["type"]:
msg = f"type does not match: {self.__identifier__} != {info['type']}"
raise ValueError(msg)
self.processor = self.processor_base.from_pack(info["processor"])
self.config = self.config_base.from_pack(info["config"])
bundle_info = info["bundle"]
if not bundle_info:
self.bundle = None
else:
self.bundle = DataBundle.empty()
self.bundle.from_info(bundle_info)
def to_npd(self) -> np_dict_type:
return {} if self.bundle is None else self.bundle.to_npd()
def from_npd(self, npd: np_dict_type) -> None:
if npd:
if self.bundle is None:
self.bundle = DataBundle.empty()
self.bundle.from_npd(npd)
# optional callback
@property
def config_base(self) -> Type[DataConfig]:
return DataConfig
@property
def processor_base(self) -> Type[DataProcessor]:
return DataProcessor
def get_bundle(
self,
x_train: data_type,
y_train: Optional[data_type] = None,
x_valid: Optional[data_type] = None,
y_valid: Optional[data_type] = None,
train_others: Optional[np_dict_type] = None,
valid_others: Optional[np_dict_type] = None,
*args: Any,
**kwargs: Any,
) -> DataBundle:
args = x_train, y_train, x_valid, y_valid, train_others, valid_others
return DataBundle(*args)
def set_sample_weights(self: TData, sample_weights: sample_weights_type) -> TData:
self.train_weights, self.valid_weights = split_sw(sample_weights)
return self
# api
@classmethod
def init(
cls: Type[TData],
config: Optional[DataConfig] = None,
processor_config: Optional[DataProcessorConfig] = None,
) -> TData:
self: TData = cls()
self.bundle = None
self.config = config or self.config_base()
self.processor = self.processor_base.init(processor_config)
return self
def fit(
self: TData,
x_train: data_type,
y_train: Optional[data_type] = None,
x_valid: Optional[data_type] = None,
y_valid: Optional[data_type] = None,
train_others: Optional[np_dict_type] = None,
valid_others: Optional[np_dict_type] = None,
*args: Any,
**kwargs: Any,
) -> TData:
args = x_train, y_train, x_valid, y_valid, train_others, valid_others, *args
bundle = self.get_bundle(*args, **kwargs)
bundle = self.processor.fit_transform(bundle)
self.bundle = bundle
return self
def transform(self, *args: Any, **kwargs: Any) -> DataBundle:
if not self.processor.is_ready:
raise ValueError("`processor` should be ready before calling `transform`")
bundle = self.get_bundle(*args, **kwargs)
bundle = self.processor.transform(bundle, for_inference=True)
return bundle
def recover_labels(self, y: np.ndarray) -> np.ndarray:
return self.processor.recover_labels(y)
class DataTypes(str, Enum):
INT = "int"
FLOAT = "float"
STRING = "string"
class ColumnTypes(str, Enum):
REDUNDANT = "redundant"
NUMERICAL = "numerical"
CATEGORICAL = "categorical"
DataProcessorConfig.register("base")(DataProcessorConfig)
DataConfig.register("base")(DataConfig)
# general model
def _forward(
m: nn.Module,
batch_idx: int,
batch: tensor_dict_type,
general_input_key: str,
state: Optional["TrainerState"] = None,
*,
general_output_key: str = PREDICTIONS_KEY,
**kwargs: Any,
) -> tensor_dict_type:
fn = m.forward
if check_requires(fn, "general_output_key"):
kwargs["general_output_key"] = general_output_key
kw = filter_kw(fn, kwargs)
args: List[Any] = []
if check_requires(fn, "batch_idx"):
args.append(batch_idx)
if get_num_positional_args(fn) > 0:
args.append(batch if check_requires(fn, "batch") else batch[general_input_key])
if check_requires(fn, "state"):
args.append(state)
rs = m(*args, **kw)
if not isinstance(rs, dict):
rs = {general_output_key: rs}
return rs
class IDLModel(
nn.Module,
WithRegister["IDLModel"],
IWithRequirements,
metaclass=ABCMeta,
):
d = model_dict
def __init__(self, *args: Any, **kwargs: Any):
super().__init__()
# optional callbacks
def init_with_trainer(self, trainer: "ITrainer") -> None:
pass
def permute_trainer_config(self, trainer_config: "TrainerConfig") -> None:
pass
def get_forward_args(
self,
batch_idx: int,
batch: tensor_dict_type,
state: Optional["TrainerState"] = None,
**kwargs: Any,
) -> Tuple[Any, ...]:
return (batch[INPUT_KEY],)
def postprocess(
self,
batch_idx: int,
batch: tensor_dict_type,
forward_results: forward_results_type,
state: Optional["TrainerState"] = None,
**kwargs: Any,
) -> tensor_dict_type:
if isinstance(forward_results, dict):
return forward_results
if isinstance(forward_results, Tensor):
return {PREDICTIONS_KEY: forward_results}
raise ValueError(f"unrecognized forward results occurred: {forward_results}")
# api
def run(
self,
batch_idx: int,
batch: tensor_dict_type,
state: Optional["TrainerState"] = None,
**kwargs: Any,
) -> tensor_dict_type:
args = self.get_forward_args(batch_idx, batch, state, **kwargs)
forward_results = self(*args)
outputs = self.postprocess(batch_idx, batch, forward_results, state, **kwargs)
return outputs
def onnx_forward(self, batch: tensor_dict_type) -> Any:
return self.run(0, batch)
def summary_forward(self, batch: tensor_dict_type) -> None:
self.onnx_forward(batch)
def to_onnx(
self,
export_file: str,
input_sample: tensor_dict_type,
dynamic_axes: Optional[Union[List[int], Dict[int, str]]] = None,
*,
opset: int = 11,
simplify: bool = True,
forward_fn: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
output_names: Optional[List[str]] = None,
num_samples: Optional[int] = None,
verbose: bool = True,
**kwargs: Any,
) -> "IDLModel":
# prepare
device = get_device(self)
model = self.cpu()
if num_samples is not None:
input_sample = {k: v[:num_samples] for k, v in input_sample.items()}
onnx_forward = forward_fn or model.onnx_forward
input_names = sorted(input_sample.keys())
if output_names is None:
if forward_fn is not None:
msg = "`output_names` should be provided when `forward_fn` is provided"
raise ValueError(msg)
with eval_context(model):
forward_results = onnx_forward(shallow_copy_dict(input_sample))
if not isinstance(forward_results, dict):
forward_results = {PREDICTIONS_KEY: forward_results}
output_names = sorted(forward_results.keys())
# setup
kwargs = shallow_copy_dict(kwargs)
kwargs["input_names"] = input_names
kwargs["output_names"] = output_names
kwargs["opset_version"] = opset
kwargs["export_params"] = True
kwargs["do_constant_folding"] = True
if dynamic_axes is None:
dynamic_axes = {}
elif isinstance(dynamic_axes, list):
dynamic_axes = {axis: f"axis.{axis}" for axis in dynamic_axes}
if num_samples is None:
dynamic_axes[0] = "batch_size"
dynamic_axes_settings = {}
for name in input_names + output_names:
dynamic_axes_settings[name] = dynamic_axes
kwargs["dynamic_axes"] = dynamic_axes_settings
kwargs["verbose"] = verbose
# export
class ONNXWrapper(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.model = model
def forward(self, batch: Dict[str, Any]) -> Dict[str, Any]:
rs = onnx_forward(batch)
if isinstance(rs, Tensor):
return {k: rs for k in output_names} # type: ignore
return {k: rs[k] for k in output_names} # type: ignore
m_onnx = ONNXWrapper()
original_states = model.state_dict()
fixed_states = fix_denormal_states(original_states, verbose=verbose)
with eval_context(m_onnx):
model.load_state_dict(fixed_states)
torch.onnx.export(
m_onnx,
({k: input_sample[k] for k in input_names}, {}),
export_file,
**shallow_copy_dict(kwargs),
)
model.load_state_dict(original_states)
if not simplify:
return self.to(device)
if onnx is None:
print_warning(
"`onnx` is not installed, "
"so the exported onnx model will not be simplified"
)
return self.to(device)
if onnx_simplify is None or get_input_names is None:
print_warning(
"`onnx-simplifier` is not installed, "
"so the exported onnx model will not be simplified"
)
return self.to(device)
try:
onnx_model = onnx.load(export_file)
final_input_names = get_input_names(onnx_model)
model_simplified, check = onnx_simplify(
onnx_model,
test_input_shapes={
name: tensor.shape
for name, tensor in input_sample.items()
if name in final_input_names
},
)
except Exception as err:
if verbose:
print_warning(f"Failed to simplify ONNX model ({err})")
model_simplified = None
check = False
if verbose:
tag = " " if check else " not "
print_info(f"Simplified ONNX model is{tag}validated!")
if check and model_simplified is not None:
onnx.save(model_simplified, export_file)
return self.to(device)
class IMLModel(IDLModel, metaclass=ABCMeta):
def __init__(
self,
*args: Any,
encoder_settings: Optional[Dict[str, "MLEncoderSettings"]] = None,
**kwargs: Any,
):
super().__init__()
class EnsembleFn(Protocol):
def __call__(self, key: str, tensors: List[Tensor]) -> Tensor:
pass
class DLEnsembleModel(nn.Module):
ensemble_fn: Optional[EnsembleFn]
def __init__(self, m: IDLModel, num_repeat: int) -> None:
super().__init__()
self.ms = get_clones(m, num_repeat)
self.ensemble_fn = None
def forward(self, *args: Any) -> forward_results_type:
outputs: Dict[str, List[Tensor]] = {}
for m in self.ms:
m_outputs = m(*args)
if isinstance(m_outputs, Tensor):
m_outputs = {PREDICTIONS_KEY: m_outputs}
for k, v in m_outputs.items():
outputs.setdefault(k, []).append(v)
final_results: tensor_dict_type = {}
for k in sorted(outputs):
if self.ensemble_fn is None:
v = torch.stack(outputs[k]).mean(0)