hypatorch 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hypatorch/__init__.py +8 -0
- hypatorch/assessments.py +153 -0
- hypatorch/core.py +610 -0
- hypatorch/losses.py +99 -0
- hypatorch/utils.py +242 -0
- hypatorch-0.1.0.dist-info/LICENSE +201 -0
- hypatorch-0.1.0.dist-info/METADATA +28 -0
- hypatorch-0.1.0.dist-info/RECORD +10 -0
- hypatorch-0.1.0.dist-info/WHEEL +5 -0
- hypatorch-0.1.0.dist-info/top_level.txt +1 -0
hypatorch/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from hypatorch.core import Model
|
|
2
|
+
from hypatorch.assessments import HypaAssessment
|
|
3
|
+
from hypatorch.losses import MAE_Loss
|
|
4
|
+
from hypatorch.losses import MMAE_Loss
|
|
5
|
+
from hypatorch.losses import MSE_Loss
|
|
6
|
+
from hypatorch.losses import MMSE_Loss
|
|
7
|
+
|
|
8
|
+
__version__ = '0.1.0'
|
hypatorch/assessments.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from .utils import create_mask, create_mask_same_shape
|
|
5
|
+
from .utils import LengthHarmonizer
|
|
6
|
+
from .utils import get_module_input
|
|
7
|
+
|
|
8
|
+
from typing import Optional
|
|
9
|
+
from typing import Union
|
|
10
|
+
from typing import Dict
|
|
11
|
+
from typing import List
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MaskedAssessment(torch.nn.Module):
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
unmasked_assessment=torch.nn.MSELoss(reduction='sum'),
|
|
18
|
+
reduction='mean',
|
|
19
|
+
):
|
|
20
|
+
super(MaskedAssessment, self).__init__()
|
|
21
|
+
self._assessment = unmasked_assessment
|
|
22
|
+
self.reduction = reduction
|
|
23
|
+
|
|
24
|
+
if hasattr(self._assessment, 'reduction'):
|
|
25
|
+
if self._assessment.reduction != 'sum':
|
|
26
|
+
raise ValueError(
|
|
27
|
+
f"""
|
|
28
|
+
The module passed to 'unmasked_assessment' must
|
|
29
|
+
have an input argument called 'reduction=sum'.
|
|
30
|
+
Otherwise, the module is not compatible with the
|
|
31
|
+
masking mechanism.
|
|
32
|
+
"""
|
|
33
|
+
)
|
|
34
|
+
else:
|
|
35
|
+
raise ValueError(
|
|
36
|
+
f"""
|
|
37
|
+
The module passed to 'unmasked_assessment' must
|
|
38
|
+
have an input argument called 'reduction=sum'.
|
|
39
|
+
Otherwise, the module is not compatible with the
|
|
40
|
+
masking mechanism.
|
|
41
|
+
"""
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
# Masked reduction must be either "sum" or "mean"
|
|
45
|
+
if self.reduction not in ['sum', 'mean']:
|
|
46
|
+
raise ValueError(
|
|
47
|
+
f"""
|
|
48
|
+
Input argument 'reduction' must be either 'sum' or 'mean',
|
|
49
|
+
but got {self.reduction}.
|
|
50
|
+
"""
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
return
|
|
54
|
+
|
|
55
|
+
def forward(
|
|
56
|
+
self,
|
|
57
|
+
inputs,
|
|
58
|
+
mask,
|
|
59
|
+
apply,
|
|
60
|
+
):
|
|
61
|
+
if not apply:
|
|
62
|
+
raise ValueError(
|
|
63
|
+
f"""
|
|
64
|
+
Input argument 'apply' must be a list of keys
|
|
65
|
+
of the inputs to be masked, but got {apply}.
|
|
66
|
+
"""
|
|
67
|
+
)
|
|
68
|
+
for k in apply:
|
|
69
|
+
inputs[k] = inputs[k] * mask
|
|
70
|
+
|
|
71
|
+
sum_assessment = self._assessment( **inputs )
|
|
72
|
+
|
|
73
|
+
if self.reduction == 'mean':
|
|
74
|
+
# multiply all elements of x.shape[:-1]
|
|
75
|
+
normalize = 1
|
|
76
|
+
for i in inputs[ apply[0] ].shape[:-1]:
|
|
77
|
+
normalize *= i
|
|
78
|
+
|
|
79
|
+
return sum_assessment / (normalize * mask.flatten().sum())
|
|
80
|
+
else:
|
|
81
|
+
return sum_assessment
|
|
82
|
+
|
|
83
|
+
class HypaAssessment( torch.nn.Module ):
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
assessment: torch.nn.Module,
|
|
88
|
+
name: str,
|
|
89
|
+
inputs: List[
|
|
90
|
+
Union[
|
|
91
|
+
Dict[ str, str ],
|
|
92
|
+
Dict[ str, Dict ],
|
|
93
|
+
],
|
|
94
|
+
],
|
|
95
|
+
harmonize_inputs: List[ str ],
|
|
96
|
+
masking: Optional[Dict] = None,
|
|
97
|
+
weight = 1.0,
|
|
98
|
+
):
|
|
99
|
+
super().__init__()
|
|
100
|
+
self.weight = weight
|
|
101
|
+
self.name = name
|
|
102
|
+
self.inputs = inputs
|
|
103
|
+
self.harmonize_inputs = harmonize_inputs
|
|
104
|
+
self.masking = masking
|
|
105
|
+
if masking is not None:
|
|
106
|
+
self.assessment = MaskedAssessment(
|
|
107
|
+
unmasked_assessment=assessment,
|
|
108
|
+
)
|
|
109
|
+
else:
|
|
110
|
+
self.assessment = assessment
|
|
111
|
+
self.harmonize_lengths = LengthHarmonizer()
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
def forward(
|
|
115
|
+
self,
|
|
116
|
+
data_dict,
|
|
117
|
+
):
|
|
118
|
+
|
|
119
|
+
# Get inputs
|
|
120
|
+
assessment_in = get_module_input(
|
|
121
|
+
inputs = self.inputs,
|
|
122
|
+
data_dict = data_dict,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# Masking
|
|
126
|
+
if self.masking is not None:
|
|
127
|
+
mask = create_mask(
|
|
128
|
+
data_dict[ self.inputs[ self.masking[ 'apply' ][0] ] ],
|
|
129
|
+
data_dict[ self.masking[ 'len_key'] ],
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# Harmonize lengths
|
|
133
|
+
if self.harmonize_inputs:
|
|
134
|
+
h_in = [ assessment_in[ k ] for k in self.harmonize_inputs ]
|
|
135
|
+
if self.masking is not None:
|
|
136
|
+
h_in.append( mask )
|
|
137
|
+
h_out = self.harmonize_lengths( h_in )
|
|
138
|
+
for k, v in zip(self.harmonize_inputs, h_out):
|
|
139
|
+
assessment_in[ k ] = v
|
|
140
|
+
|
|
141
|
+
if self.masking is not None:
|
|
142
|
+
mask = h_out[-1]
|
|
143
|
+
|
|
144
|
+
if self.masking is not None:
|
|
145
|
+
x = self.assessment(
|
|
146
|
+
inputs = assessment_in,
|
|
147
|
+
mask = mask,
|
|
148
|
+
apply = self.masking[ 'apply' ],
|
|
149
|
+
)
|
|
150
|
+
else:
|
|
151
|
+
x = self.assessment( **assessment_in )
|
|
152
|
+
|
|
153
|
+
return x * self.weight
|
hypatorch/core.py
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import torch
|
|
3
|
+
import lightning as L
|
|
4
|
+
from contextlib import nullcontext
|
|
5
|
+
from omegaconf import DictConfig, ListConfig
|
|
6
|
+
from hydra import compose, initialize
|
|
7
|
+
from hydra.utils import instantiate
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
import yaml
|
|
12
|
+
|
|
13
|
+
from typing import List, Dict, Optional, Union, Callable, Any, Tuple
|
|
14
|
+
|
|
15
|
+
from .utils import get_input_variable_names
|
|
16
|
+
from .utils import get_output_variable_names
|
|
17
|
+
from .utils import shared_dict
|
|
18
|
+
from .utils import validate_io_keys
|
|
19
|
+
from .utils import get_module_input
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Model( L.LightningModule ):
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
# core functionality
|
|
27
|
+
submodules: Union[
|
|
28
|
+
Dict[ str, str ],
|
|
29
|
+
Dict[ str, torch.nn.Module ],
|
|
30
|
+
],
|
|
31
|
+
operations: List[ List[ Dict[ str, Dict ] ] ],
|
|
32
|
+
|
|
33
|
+
# training related
|
|
34
|
+
exclude_from_checkpoint: Optional[ List[str] ] = None,
|
|
35
|
+
accumulate_grad_batches: Optional[ int ] = None,
|
|
36
|
+
gradient_clip_val: Optional[ float ] = 5.0,
|
|
37
|
+
checkpoints: Optional[ List[ Dict[ str, str ] ] ] = None,
|
|
38
|
+
):
|
|
39
|
+
|
|
40
|
+
super().__init__()
|
|
41
|
+
|
|
42
|
+
# Processing modules and core functionality
|
|
43
|
+
self.submodule_names = list( submodules.keys() )
|
|
44
|
+
|
|
45
|
+
for sm_name, sm in submodules.items():
|
|
46
|
+
if isinstance( sm, str ):
|
|
47
|
+
# load yaml file from string and instantiate its content
|
|
48
|
+
# TODO: this may only work with absolute paths, make it work with relative paths
|
|
49
|
+
y = yaml.load( sm, safe_load = True )
|
|
50
|
+
sm = instantiate( y )
|
|
51
|
+
|
|
52
|
+
if not isinstance( sm, torch.nn.Module ):
|
|
53
|
+
raise ValueError(
|
|
54
|
+
f"""
|
|
55
|
+
The submodule {sm_name} must be a torch.nn.Module
|
|
56
|
+
or a file path to a yaml file that can be instantiated
|
|
57
|
+
into a torch.nn.Module. However, the passed submodule
|
|
58
|
+
is of type {type(sm)}.
|
|
59
|
+
"""
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
setattr( self, sm_name, sm )
|
|
63
|
+
|
|
64
|
+
logging.info(
|
|
65
|
+
f"""
|
|
66
|
+
Created a hypaTorch model from the following submodules:
|
|
67
|
+
{self.submodule_names}
|
|
68
|
+
"""
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
self.operations = operations
|
|
72
|
+
self.mappings = self._get_content( 'mappings' )
|
|
73
|
+
|
|
74
|
+
self.logging = self._get_content( 'logging' )
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
## Losses and metrics
|
|
78
|
+
self.losses = self._get_content( 'losses' )
|
|
79
|
+
self.metrics = self._get_content( 'metrics' )
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# Lightning does not accept gradient accumulation or clipping
|
|
83
|
+
# as arguments if optimization is manual. Therefore, we need to
|
|
84
|
+
# implement these functionalities manually.
|
|
85
|
+
self.accumulate_grad_batches = accumulate_grad_batches
|
|
86
|
+
self.gradient_clip_val = gradient_clip_val
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# Checkpoints
|
|
90
|
+
self.checkpoints = checkpoints if checkpoints is not None else []
|
|
91
|
+
|
|
92
|
+
# Freeze submodules if specified
|
|
93
|
+
optimized_sm_list = []
|
|
94
|
+
for x in self._get_content(
|
|
95
|
+
'optimize_submodules',
|
|
96
|
+
return_on_failure = {},
|
|
97
|
+
).values():
|
|
98
|
+
optimized_sm_list.extend( x )
|
|
99
|
+
optimized_sm_set = set( optimized_sm_list )
|
|
100
|
+
logging.info(
|
|
101
|
+
f"""
|
|
102
|
+
All submodules that get optimized by at least
|
|
103
|
+
one optimizer: {optimized_sm_set}
|
|
104
|
+
"""
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# self frozen is the disjoin of the optimized submodules and submodule_names
|
|
108
|
+
self.frozen = list( set( self.submodule_names ) - optimized_sm_set )
|
|
109
|
+
logging.info(
|
|
110
|
+
f"""
|
|
111
|
+
All submodules that get optimized by at least
|
|
112
|
+
one optimizer: {optimized_sm_set}
|
|
113
|
+
"""
|
|
114
|
+
)
|
|
115
|
+
self._freeze_submodules( self )
|
|
116
|
+
|
|
117
|
+
# Exclude from checkpoint
|
|
118
|
+
if exclude_from_checkpoint is None:
|
|
119
|
+
exclude_from_checkpoint = []
|
|
120
|
+
self.exclude_from_checkpoint = exclude_from_checkpoint
|
|
121
|
+
|
|
122
|
+
# Important: This property activates manual optimization.
|
|
123
|
+
self.automatic_optimization = False
|
|
124
|
+
|
|
125
|
+
return
|
|
126
|
+
|
|
127
|
+
@classmethod
|
|
128
|
+
def from_config(
|
|
129
|
+
cls,
|
|
130
|
+
config_path: str,
|
|
131
|
+
):
|
|
132
|
+
with initialize(
|
|
133
|
+
version_base=None,
|
|
134
|
+
config_path="conf",
|
|
135
|
+
job_name="test_app",
|
|
136
|
+
):
|
|
137
|
+
cfg = compose( config_name=config_path )
|
|
138
|
+
|
|
139
|
+
# Instantiate the model
|
|
140
|
+
if 'model' in cfg:
|
|
141
|
+
model = instantiate( cfg.model )
|
|
142
|
+
else:
|
|
143
|
+
model = instantiate( cfg )
|
|
144
|
+
|
|
145
|
+
model._load_checkpoints(
|
|
146
|
+
checkpoints_dict = cfg.checkpoints,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
return model
|
|
150
|
+
|
|
151
|
+
def _load_checkpoints( self ):
|
|
152
|
+
for ckpt_dict in self.checkpoints:
|
|
153
|
+
|
|
154
|
+
ckpt =torch.load( ckpt_dict[ 'path' ] )[ 'state_dict' ]
|
|
155
|
+
if 'prefix_rm' in ckpt_dict:
|
|
156
|
+
prefix_rm = ckpt_dict[ 'prefix_rm' ]
|
|
157
|
+
if prefix_rm.endswith( '.' ):
|
|
158
|
+
# delete all trailing dots
|
|
159
|
+
prefix_rm = prefix_rm.rstrip( '.' )
|
|
160
|
+
ckpt = {
|
|
161
|
+
k[ len( prefix_rm ) + 1: ]: v
|
|
162
|
+
for k, v in ckpt.items()
|
|
163
|
+
if k.startswith( prefix_rm )
|
|
164
|
+
}
|
|
165
|
+
if 'prefix_add' in ckpt_dict:
|
|
166
|
+
prefix_add = ckpt_dict[ 'prefix_add' ]
|
|
167
|
+
if prefix_add.endswith( '.' ):
|
|
168
|
+
prefix_add = prefix_add.rstrip( '.' )
|
|
169
|
+
prefix_add = prefix_add + '.'
|
|
170
|
+
ckpt = {
|
|
171
|
+
prefix_add + k: v
|
|
172
|
+
for k, v in ckpt.items()
|
|
173
|
+
}
|
|
174
|
+
try:
|
|
175
|
+
self.load_state_dict(
|
|
176
|
+
ckpt,
|
|
177
|
+
strict = True,
|
|
178
|
+
)
|
|
179
|
+
except Exception as e:
|
|
180
|
+
logging.warning(
|
|
181
|
+
f"""
|
|
182
|
+
Could not load the checkpoint {ckpt_dict[ 'path' ]}
|
|
183
|
+
in 'strict' mode. Trying again with 'strict = False'.
|
|
184
|
+
Enable logging.DEBUG level for more information.
|
|
185
|
+
"""
|
|
186
|
+
)
|
|
187
|
+
logging.debug( f'Due to the following error: {e}.' )
|
|
188
|
+
self.load_state_dict(
|
|
189
|
+
ckpt,
|
|
190
|
+
strict = False,
|
|
191
|
+
)
|
|
192
|
+
return
|
|
193
|
+
|
|
194
|
+
def _get_content(
|
|
195
|
+
self,
|
|
196
|
+
key,
|
|
197
|
+
return_on_failure = [],
|
|
198
|
+
):
|
|
199
|
+
x = {}
|
|
200
|
+
|
|
201
|
+
for op_name, op in self.operations.items():
|
|
202
|
+
if key in op:
|
|
203
|
+
x[ op_name ] = op[ key ]
|
|
204
|
+
else:
|
|
205
|
+
x = return_on_failure
|
|
206
|
+
return x
|
|
207
|
+
|
|
208
|
+
def _collect_trainable_parameters(
|
|
209
|
+
self,
|
|
210
|
+
submodule_names,
|
|
211
|
+
):
|
|
212
|
+
parameters = []
|
|
213
|
+
|
|
214
|
+
for submodule_name in submodule_names:
|
|
215
|
+
submodule = getattr(self, submodule_name)
|
|
216
|
+
if submodule_name not in self.frozen:
|
|
217
|
+
parameters.extend( submodule.parameters() )
|
|
218
|
+
|
|
219
|
+
return parameters
|
|
220
|
+
|
|
221
|
+
def _compute_assessments(
|
|
222
|
+
self,
|
|
223
|
+
data_dict,
|
|
224
|
+
assessments,
|
|
225
|
+
):
|
|
226
|
+
x = {}
|
|
227
|
+
|
|
228
|
+
for fn in assessments:
|
|
229
|
+
y = fn(
|
|
230
|
+
data_dict = data_dict,
|
|
231
|
+
)
|
|
232
|
+
x[ fn.name ] = y
|
|
233
|
+
|
|
234
|
+
return x
|
|
235
|
+
|
|
236
|
+
def _check_if_submodule_gets_applied(
|
|
237
|
+
self,
|
|
238
|
+
mode,
|
|
239
|
+
mapping_dict,
|
|
240
|
+
):
|
|
241
|
+
if 'apply' in mapping_dict:
|
|
242
|
+
if mode in mapping_dict[ 'apply' ]:
|
|
243
|
+
return True
|
|
244
|
+
else:
|
|
245
|
+
return False
|
|
246
|
+
else:
|
|
247
|
+
return True
|
|
248
|
+
|
|
249
|
+
def _freeze_submodules(
|
|
250
|
+
self,
|
|
251
|
+
module,
|
|
252
|
+
):
|
|
253
|
+
for x in self.frozen:
|
|
254
|
+
module = getattr(self, x)
|
|
255
|
+
for param in module.parameters():
|
|
256
|
+
param.requires_grad = False
|
|
257
|
+
return
|
|
258
|
+
|
|
259
|
+
def configure_optimizers(self):
|
|
260
|
+
|
|
261
|
+
optimizers = []
|
|
262
|
+
|
|
263
|
+
for op_name, opt in self.operations.items():
|
|
264
|
+
# List of parameters to optimize
|
|
265
|
+
parameters = self._collect_trainable_parameters(
|
|
266
|
+
submodule_names = opt[ 'optimize_submodules' ],
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
optimizer = opt[ 'optimizer' ](parameters)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
d = {'optimizer': optimizer}
|
|
273
|
+
if opt[ 'lr_scheduler' ] is not None:
|
|
274
|
+
# Instantiate the partially instantiated LR scheduler
|
|
275
|
+
sch = {
|
|
276
|
+
'scheduler': opt[ 'lr_scheduler' ]['scheduler'](optimizer),
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
# add the other keys to the dict
|
|
280
|
+
for k, v in opt[ 'lr_scheduler' ].items():
|
|
281
|
+
if k != 'scheduler':
|
|
282
|
+
sch[k] = v
|
|
283
|
+
|
|
284
|
+
d['lr_scheduler'] = sch
|
|
285
|
+
|
|
286
|
+
optimizers.append( d )
|
|
287
|
+
|
|
288
|
+
return optimizers
|
|
289
|
+
|
|
290
|
+
def _run_submodule(
|
|
291
|
+
self,
|
|
292
|
+
submodule,
|
|
293
|
+
submodule_name,
|
|
294
|
+
mapping,
|
|
295
|
+
data_dict,
|
|
296
|
+
):
|
|
297
|
+
|
|
298
|
+
frozen = submodule_name in self.frozen
|
|
299
|
+
calculate_grad = mapping[ submodule_name ][ 'calculate_grad' ]
|
|
300
|
+
if not calculate_grad or ( frozen and not calculate_grad ):
|
|
301
|
+
context = torch.no_grad()
|
|
302
|
+
else:
|
|
303
|
+
context = nullcontext()
|
|
304
|
+
with context:
|
|
305
|
+
if 'fn' in mapping[ submodule_name ]:
|
|
306
|
+
fn = getattr( submodule, mapping[ submodule_name ][ 'fn' ] )
|
|
307
|
+
fn_to_inspect = fn
|
|
308
|
+
else:
|
|
309
|
+
fn_to_inspect = submodule.forward
|
|
310
|
+
fn = submodule.__call__
|
|
311
|
+
|
|
312
|
+
output_key_map = mapping[ submodule_name ][ 'outputs' ]
|
|
313
|
+
inputs = mapping[ submodule_name][ 'inputs' ]
|
|
314
|
+
|
|
315
|
+
expected_inputs = get_input_variable_names( fn_to_inspect )
|
|
316
|
+
expected_outputs = get_output_variable_names( fn_to_inspect )
|
|
317
|
+
|
|
318
|
+
validate_io_keys(
|
|
319
|
+
module_name = submodule_name,
|
|
320
|
+
module_object_name = submodule.__class__.__name__,
|
|
321
|
+
input_key_map = inputs,
|
|
322
|
+
output_key_map = output_key_map,
|
|
323
|
+
expected_inputs = expected_inputs,
|
|
324
|
+
expected_outputs = expected_outputs,
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
submodule_in = get_module_input(
|
|
328
|
+
inputs = inputs,
|
|
329
|
+
data_dict = data_dict,
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
if 'fn' in mapping[ submodule_name ]:
|
|
333
|
+
submodule_out = fn( **submodule_in )
|
|
334
|
+
else:
|
|
335
|
+
submodule_out = submodule( **submodule_in )
|
|
336
|
+
|
|
337
|
+
# if submodule is not a tuple, make it a tuple of length 1
|
|
338
|
+
if not isinstance( submodule_out, tuple ):
|
|
339
|
+
submodule_out = ( submodule_out, )
|
|
340
|
+
|
|
341
|
+
if len( submodule_out ) != len( expected_outputs ):
|
|
342
|
+
raise ValueError(
|
|
343
|
+
f"""
|
|
344
|
+
Error with output of {submodule_name}.
|
|
345
|
+
Expected {len( expected_outputs )} outputs,
|
|
346
|
+
but got {len( submodule_out )} outputs.
|
|
347
|
+
"""
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
sm_out_dict = { key: value for key, value in zip( expected_outputs, submodule_out ) }
|
|
351
|
+
x = { key_map: sm_out_dict[ key ] for key, key_map in output_key_map.items() }
|
|
352
|
+
|
|
353
|
+
return x
|
|
354
|
+
|
|
355
|
+
def forward(
|
|
356
|
+
self,
|
|
357
|
+
input_dict,
|
|
358
|
+
mappings,
|
|
359
|
+
mode,
|
|
360
|
+
):
|
|
361
|
+
|
|
362
|
+
output_dict = {}
|
|
363
|
+
|
|
364
|
+
for mapping in mappings:
|
|
365
|
+
for submodule_name in mapping.keys():
|
|
366
|
+
submodule = getattr(self, submodule_name)
|
|
367
|
+
if submodule is not None:
|
|
368
|
+
apply_submodule = self._check_if_submodule_gets_applied(
|
|
369
|
+
mode = mode,
|
|
370
|
+
mapping_dict = mapping[ submodule_name ],
|
|
371
|
+
)
|
|
372
|
+
if apply_submodule:
|
|
373
|
+
data_dict = shared_dict(
|
|
374
|
+
input_dict,
|
|
375
|
+
output_dict,
|
|
376
|
+
)
|
|
377
|
+
x = self._run_submodule(
|
|
378
|
+
submodule = submodule,
|
|
379
|
+
submodule_name = submodule_name,
|
|
380
|
+
mapping = mapping,
|
|
381
|
+
data_dict = data_dict,
|
|
382
|
+
)
|
|
383
|
+
# check that x.keys do not overlap with output_dict.keys
|
|
384
|
+
if not any( x in output_dict.keys() for x in x.keys() ):
|
|
385
|
+
output_dict.update( x )
|
|
386
|
+
else:
|
|
387
|
+
raise ValueError(
|
|
388
|
+
f"""
|
|
389
|
+
Error with output_dict of {submodule_name}.
|
|
390
|
+
Submodules are not allowed to overwrite existing keys.
|
|
391
|
+
However, {submodule_name} has the following keys: {x.keys()}
|
|
392
|
+
and the output_dict has the following keys: {output_dict.keys()}.
|
|
393
|
+
"""
|
|
394
|
+
)
|
|
395
|
+
#else:
|
|
396
|
+
# print( f'module {submodule_name} not applied')
|
|
397
|
+
else:
|
|
398
|
+
raise ValueError(
|
|
399
|
+
f'No submodule {submodule_name} found. Forgot to define it?'
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
return output_dict
|
|
403
|
+
|
|
404
|
+
def training_step(self, batch, batch_idx):
|
|
405
|
+
|
|
406
|
+
mode = 'train'
|
|
407
|
+
|
|
408
|
+
input_dict = batch
|
|
409
|
+
|
|
410
|
+
opts = self.optimizers()
|
|
411
|
+
|
|
412
|
+
# check if opts is iterable, if not, make it iterable
|
|
413
|
+
if not isinstance( opts, list ):
|
|
414
|
+
opts = [ opts ]
|
|
415
|
+
|
|
416
|
+
for operation_idx, _ in enumerate( self.operations ):
|
|
417
|
+
operation_name = list( self.operations.keys() )[ operation_idx ]
|
|
418
|
+
|
|
419
|
+
# Forward Pass
|
|
420
|
+
output_dict, loss = self._forward_pass(
|
|
421
|
+
input_dict = input_dict,
|
|
422
|
+
operation_name = operation_name,
|
|
423
|
+
mode = mode,
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
# Backward Pass if self.losses is not empty list
|
|
427
|
+
if self.losses:
|
|
428
|
+
opt = opts[ operation_idx ]
|
|
429
|
+
self._backward_pass(
|
|
430
|
+
opt = opt,
|
|
431
|
+
loss = loss,
|
|
432
|
+
batch_idx = batch_idx,
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
self._handle_assessments(
|
|
436
|
+
assessments = self.metrics,
|
|
437
|
+
data_dict = shared_dict(
|
|
438
|
+
input_dict,
|
|
439
|
+
output_dict,
|
|
440
|
+
),
|
|
441
|
+
operation_name = operation_name,
|
|
442
|
+
mode = mode,
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
return loss
|
|
446
|
+
|
|
447
|
+
def validation_step(self, batch, batch_idx):
|
|
448
|
+
|
|
449
|
+
mode = 'val'
|
|
450
|
+
|
|
451
|
+
input_dict = batch
|
|
452
|
+
|
|
453
|
+
for operation_idx, _ in enumerate( self.operations ):
|
|
454
|
+
operation_name = list( self.operations.keys() )[ operation_idx ]
|
|
455
|
+
# Forward Pass
|
|
456
|
+
with torch.no_grad():
|
|
457
|
+
output_dict, loss = self._forward_pass(
|
|
458
|
+
input_dict = input_dict,
|
|
459
|
+
operation_name = operation_name,
|
|
460
|
+
mode = mode,
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
# handle metrics
|
|
464
|
+
self._handle_assessments(
|
|
465
|
+
assessments = self.metrics,
|
|
466
|
+
data_dict = shared_dict(
|
|
467
|
+
input_dict,
|
|
468
|
+
output_dict,
|
|
469
|
+
),
|
|
470
|
+
operation_name = operation_name,
|
|
471
|
+
mode = mode,
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
# Once per epoch, log the first batch
|
|
475
|
+
if batch_idx == 0 and self.logging:
|
|
476
|
+
loggings = self.logging[ operation_name ]
|
|
477
|
+
if loggings:
|
|
478
|
+
if not isinstance( loggings, list ) and not isinstance( loggings, ListConfig ):
|
|
479
|
+
loggings = [ loggings ]
|
|
480
|
+
for logging in loggings:
|
|
481
|
+
|
|
482
|
+
fn_name = logging[ 'fn' ]
|
|
483
|
+
fn_args = { k: v for k, v in logging.items() if k != 'fn' }
|
|
484
|
+
|
|
485
|
+
log_fn = getattr(
|
|
486
|
+
self.logger,
|
|
487
|
+
fn_name,
|
|
488
|
+
)
|
|
489
|
+
log_fn(
|
|
490
|
+
data_dict = shared_dict(
|
|
491
|
+
input_dict,
|
|
492
|
+
output_dict,
|
|
493
|
+
),
|
|
494
|
+
global_step = self.global_step,
|
|
495
|
+
**fn_args,
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
return loss
|
|
499
|
+
|
|
500
|
+
def _backward_pass(
|
|
501
|
+
self,
|
|
502
|
+
opt,
|
|
503
|
+
loss,
|
|
504
|
+
batch_idx,
|
|
505
|
+
):
|
|
506
|
+
if self.accumulate_grad_batches is None:
|
|
507
|
+
opt.zero_grad()
|
|
508
|
+
self.manual_backward( loss )
|
|
509
|
+
#Implement gradient clipping
|
|
510
|
+
self.clip_gradients(
|
|
511
|
+
opt,
|
|
512
|
+
gradient_clip_val = self.gradient_clip_val,
|
|
513
|
+
gradient_clip_algorithm='value',
|
|
514
|
+
)
|
|
515
|
+
opt.step()
|
|
516
|
+
else:
|
|
517
|
+
N = self.accumulate_grad_batches
|
|
518
|
+
loss = loss / N
|
|
519
|
+
self.manual_backward( loss )
|
|
520
|
+
# accumulate gradients
|
|
521
|
+
if ( batch_idx + 1 ) % N == 0:
|
|
522
|
+
#Implement gradient clipping
|
|
523
|
+
self.clip_gradients(
|
|
524
|
+
opt,
|
|
525
|
+
gradient_clip_val = self.gradient_clip_val,
|
|
526
|
+
gradient_clip_algorithm='value',
|
|
527
|
+
)
|
|
528
|
+
opt.step()
|
|
529
|
+
opt.zero_grad()
|
|
530
|
+
return
|
|
531
|
+
|
|
532
|
+
def _forward_pass(
|
|
533
|
+
self,
|
|
534
|
+
input_dict,
|
|
535
|
+
operation_name,
|
|
536
|
+
mode,
|
|
537
|
+
):
|
|
538
|
+
output_dict = self(
|
|
539
|
+
input_dict,
|
|
540
|
+
self.mappings[ operation_name ],
|
|
541
|
+
mode = mode,
|
|
542
|
+
)
|
|
543
|
+
loss_dict = self._handle_assessments(
|
|
544
|
+
assessments = self.losses,
|
|
545
|
+
data_dict = shared_dict(
|
|
546
|
+
input_dict,
|
|
547
|
+
output_dict,
|
|
548
|
+
),
|
|
549
|
+
operation_name = operation_name,
|
|
550
|
+
mode = mode,
|
|
551
|
+
)
|
|
552
|
+
loss = sum(loss_dict.values())
|
|
553
|
+
return output_dict, loss
|
|
554
|
+
|
|
555
|
+
def _handle_assessments(
|
|
556
|
+
self,
|
|
557
|
+
assessments,
|
|
558
|
+
data_dict,
|
|
559
|
+
operation_name,
|
|
560
|
+
mode,
|
|
561
|
+
):
|
|
562
|
+
if assessments:
|
|
563
|
+
assessments_dict = self._compute_assessments(
|
|
564
|
+
data_dict = data_dict,
|
|
565
|
+
assessments = assessments[ operation_name ],
|
|
566
|
+
)
|
|
567
|
+
for k, v in assessments_dict.items():
|
|
568
|
+
self.log(
|
|
569
|
+
f'{mode}_{k}',
|
|
570
|
+
v,
|
|
571
|
+
on_epoch=True,
|
|
572
|
+
on_step=True,
|
|
573
|
+
prog_bar=True,
|
|
574
|
+
logger=True,
|
|
575
|
+
#sync_dist=False, #TODO: check if this is necessary
|
|
576
|
+
)
|
|
577
|
+
else:
|
|
578
|
+
assessments_dict = {}
|
|
579
|
+
return assessments_dict
|
|
580
|
+
|
|
581
|
+
def predict_step(self, batch, batch_idx):
|
|
582
|
+
|
|
583
|
+
mode = 'test'
|
|
584
|
+
|
|
585
|
+
input_dict = batch
|
|
586
|
+
|
|
587
|
+
for operation_idx, _ in enumerate( self.operations ):
|
|
588
|
+
operation_name = list( self.operations.keys() )[ operation_idx ]
|
|
589
|
+
# Forward Pass
|
|
590
|
+
with torch.no_grad():
|
|
591
|
+
output_dict, loss = self._forward_pass(
|
|
592
|
+
input_dict = input_dict,
|
|
593
|
+
operation_name = operation_name,
|
|
594
|
+
mode = mode,
|
|
595
|
+
)
|
|
596
|
+
|
|
597
|
+
data_dict = shared_dict(
|
|
598
|
+
input_dict,
|
|
599
|
+
output_dict,
|
|
600
|
+
)
|
|
601
|
+
|
|
602
|
+
return data_dict
|
|
603
|
+
|
|
604
|
+
def on_save_checkpoint(self, checkpoint):
|
|
605
|
+
for submodule in self.exclude_from_checkpoint:
|
|
606
|
+
keys_to_remove = [
|
|
607
|
+
k for k in checkpoint['state_dict'].keys() if k.startswith(submodule + '.')
|
|
608
|
+
]
|
|
609
|
+
for key in keys_to_remove:
|
|
610
|
+
checkpoint['state_dict'].pop(key, None)
|
hypatorch/losses.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from .assessments import HypaAssessment
|
|
5
|
+
|
|
6
|
+
from typing import Optional
|
|
7
|
+
from typing import Union
|
|
8
|
+
from typing import Dict
|
|
9
|
+
from typing import List
|
|
10
|
+
|
|
11
|
+
class MAE_Loss( HypaAssessment ):
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
inputs,
|
|
15
|
+
weight = 1.0,
|
|
16
|
+
):
|
|
17
|
+
super().__init__(
|
|
18
|
+
assessment = torch.nn.L1Loss(reduction='mean'),
|
|
19
|
+
name = f'MAE_{inputs[ "input" ]}_{inputs[ "target" ]}',
|
|
20
|
+
inputs = inputs,
|
|
21
|
+
harmonize_inputs = [
|
|
22
|
+
'input',
|
|
23
|
+
'target',
|
|
24
|
+
],
|
|
25
|
+
masking = None,
|
|
26
|
+
weight = weight,
|
|
27
|
+
)
|
|
28
|
+
return
|
|
29
|
+
|
|
30
|
+
class MMAE_Loss( HypaAssessment ):
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
inputs,
|
|
34
|
+
len_key,
|
|
35
|
+
weight = 1.0,
|
|
36
|
+
):
|
|
37
|
+
super().__init__(
|
|
38
|
+
assessment = torch.nn.L1Loss(reduction='sum'),
|
|
39
|
+
name = f'MMAE_{inputs["input"]}_{inputs["target"]}',
|
|
40
|
+
inputs = inputs,
|
|
41
|
+
harmonize_inputs = [
|
|
42
|
+
'input',
|
|
43
|
+
'target',
|
|
44
|
+
],
|
|
45
|
+
masking = dict(
|
|
46
|
+
apply = [
|
|
47
|
+
'input',
|
|
48
|
+
'target',
|
|
49
|
+
],
|
|
50
|
+
len_key = len_key,
|
|
51
|
+
),
|
|
52
|
+
weight = weight,
|
|
53
|
+
)
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
class MSE_Loss( HypaAssessment ):
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
inputs,
|
|
60
|
+
weight = 1.0,
|
|
61
|
+
):
|
|
62
|
+
super().__init__(
|
|
63
|
+
assessment = torch.nn.MSELoss(reduction='mean'),
|
|
64
|
+
name = f'MSE_{inputs[ "input" ]}_{inputs[ "target" ]}',
|
|
65
|
+
inputs = inputs,
|
|
66
|
+
harmonize_inputs = [
|
|
67
|
+
'input',
|
|
68
|
+
'target',
|
|
69
|
+
],
|
|
70
|
+
masking = None,
|
|
71
|
+
weight = weight,
|
|
72
|
+
)
|
|
73
|
+
return
|
|
74
|
+
|
|
75
|
+
class MMSE_Loss( HypaAssessment ):
|
|
76
|
+
def __init__(
|
|
77
|
+
self,
|
|
78
|
+
inputs,
|
|
79
|
+
len_key,
|
|
80
|
+
weight = 1.0,
|
|
81
|
+
):
|
|
82
|
+
super().__init__(
|
|
83
|
+
assessment = torch.nn.MSELoss(reduction='sum'),
|
|
84
|
+
name = f'MMSE_{inputs["input"]}_{inputs["target"]}',
|
|
85
|
+
inputs = inputs,
|
|
86
|
+
harmonize_inputs = [
|
|
87
|
+
'input',
|
|
88
|
+
'target',
|
|
89
|
+
],
|
|
90
|
+
masking = dict(
|
|
91
|
+
apply = [
|
|
92
|
+
'input',
|
|
93
|
+
'target',
|
|
94
|
+
],
|
|
95
|
+
len_key = len_key,
|
|
96
|
+
),
|
|
97
|
+
weight = weight,
|
|
98
|
+
)
|
|
99
|
+
return
|
hypatorch/utils.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import inspect
|
|
3
|
+
from omegaconf import DictConfig
|
|
4
|
+
|
|
5
|
+
from typing import Iterable
|
|
6
|
+
from typing import Union
|
|
7
|
+
from typing import Dict
|
|
8
|
+
from typing import List
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_input_variable_names(func):
|
|
12
|
+
full_args = inspect.getfullargspec(func)
|
|
13
|
+
input_variables = full_args.args
|
|
14
|
+
|
|
15
|
+
# Check if 'self' is in the list, if so remove it
|
|
16
|
+
if 'self' in input_variables:
|
|
17
|
+
input_variables.remove('self')
|
|
18
|
+
|
|
19
|
+
# Get the default values for the optional arguments
|
|
20
|
+
defaults = full_args.defaults if full_args.defaults else []
|
|
21
|
+
optional_variables = input_variables[-len(defaults):]
|
|
22
|
+
|
|
23
|
+
# The required arguments are all the input arguments minus the optional ones
|
|
24
|
+
required_variables = input_variables[:-len(defaults)] if defaults else input_variables
|
|
25
|
+
|
|
26
|
+
return required_variables, optional_variables
|
|
27
|
+
|
|
28
|
+
def get_output_variable_names(func):
|
|
29
|
+
# Get the source code of the function
|
|
30
|
+
source_lines = inspect.getsource(func)
|
|
31
|
+
|
|
32
|
+
# Get the part after the return statement
|
|
33
|
+
return_part = source_lines.split("return ")[1]
|
|
34
|
+
|
|
35
|
+
# If no return statement or multiple return statements,
|
|
36
|
+
# are found, raise an error
|
|
37
|
+
if "return " not in source_lines or return_part.count("return ") > 1:
|
|
38
|
+
raise ValueError(
|
|
39
|
+
f"""
|
|
40
|
+
The function must have a single return statement,
|
|
41
|
+
but passed function has {return_part.count("return ")}
|
|
42
|
+
return statements.
|
|
43
|
+
"""
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# Split by commas and clean up the code
|
|
47
|
+
returned_variables = return_part.split(",")
|
|
48
|
+
returned_variables = [var.strip() for var in returned_variables]
|
|
49
|
+
|
|
50
|
+
return returned_variables
|
|
51
|
+
|
|
52
|
+
def make_iterable(
|
|
53
|
+
x,
|
|
54
|
+
make_none_iterable = False,
|
|
55
|
+
):
|
|
56
|
+
if x is None and not make_none_iterable:
|
|
57
|
+
return x
|
|
58
|
+
|
|
59
|
+
if isinstance( x, str ) or not isinstance( x, Iterable ):
|
|
60
|
+
return [ x ]
|
|
61
|
+
|
|
62
|
+
return x
|
|
63
|
+
|
|
64
|
+
def shared_dict(
|
|
65
|
+
input_dict,
|
|
66
|
+
output_dict,
|
|
67
|
+
keys = None,
|
|
68
|
+
):
|
|
69
|
+
# Check if keys overlap:
|
|
70
|
+
if any( x in input_dict.keys() for x in output_dict.keys() ):
|
|
71
|
+
raise ValueError(
|
|
72
|
+
'Keys overlap between input and output dict. '
|
|
73
|
+
'Please use different keys.'
|
|
74
|
+
)
|
|
75
|
+
x = dict( input_dict, **output_dict )
|
|
76
|
+
#if keys is not None:
|
|
77
|
+
# x = { key: x[key] for key in keys }
|
|
78
|
+
|
|
79
|
+
return x
|
|
80
|
+
|
|
81
|
+
def validate_io_keys(
|
|
82
|
+
module_name,
|
|
83
|
+
module_object_name,
|
|
84
|
+
input_key_map,
|
|
85
|
+
output_key_map,
|
|
86
|
+
expected_inputs,
|
|
87
|
+
expected_outputs,
|
|
88
|
+
):
|
|
89
|
+
required_inputs, optional_inputs = expected_inputs
|
|
90
|
+
input_keys = list( input_key_map.keys() )
|
|
91
|
+
output_keys = list( output_key_map.keys() )
|
|
92
|
+
# check if set( input_keys ) is a subset of set( expected_inputs )
|
|
93
|
+
if not set( required_inputs ).issubset( set( input_keys ) ):
|
|
94
|
+
raise ValueError(
|
|
95
|
+
f"""
|
|
96
|
+
{module_name} ({module_object_name}) expects {required_inputs}
|
|
97
|
+
as required input_keys, but {input_keys} were given.
|
|
98
|
+
"""
|
|
99
|
+
)
|
|
100
|
+
if not set( output_keys ).issubset( set( expected_outputs ) ):
|
|
101
|
+
raise ValueError(
|
|
102
|
+
f"""
|
|
103
|
+
{module_name} ({module_object_name}) expects {expected_outputs}
|
|
104
|
+
as output_keys, but {output_keys} were given.
|
|
105
|
+
"""
|
|
106
|
+
)
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
def _get_module_input(
|
|
110
|
+
k,
|
|
111
|
+
v,
|
|
112
|
+
data_dict,
|
|
113
|
+
):
|
|
114
|
+
if isinstance( v, str ):
|
|
115
|
+
try:
|
|
116
|
+
submodule_in = data_dict[ v ]
|
|
117
|
+
except KeyError:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
f"""
|
|
120
|
+
Error with input '{k}: {v}'.
|
|
121
|
+
Input not found in data_dict. If you intended to use a string
|
|
122
|
+
as an input, it should be passed as a dictionary like this:
|
|
123
|
+
{k}: {{ 'value': '{v}', 'key_map': false }}
|
|
124
|
+
"""
|
|
125
|
+
)
|
|
126
|
+
elif isinstance( v, dict ) or isinstance(v, DictConfig):
|
|
127
|
+
if v[ 'key_map' ]:
|
|
128
|
+
try:
|
|
129
|
+
submodule_in = data_dict[ v[ 'value' ] ]
|
|
130
|
+
except KeyError:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"""
|
|
133
|
+
Error with input '{k}: {v}'.
|
|
134
|
+
Input not found in data_dict. If you intended to use a string
|
|
135
|
+
as an input, it should be passed as a dictionary like this:
|
|
136
|
+
{k}: {{ 'value': '{v['value']}', 'key_map': false }}
|
|
137
|
+
"""
|
|
138
|
+
)
|
|
139
|
+
else:
|
|
140
|
+
submodule_in = v[ 'value' ]
|
|
141
|
+
else:
|
|
142
|
+
raise ValueError(
|
|
143
|
+
f"""
|
|
144
|
+
Error with input '{k}: {v}'.
|
|
145
|
+
Input must be a string or a dictionary,
|
|
146
|
+
bot got {type(v)}.
|
|
147
|
+
"""
|
|
148
|
+
)
|
|
149
|
+
return submodule_in
|
|
150
|
+
|
|
151
|
+
def get_module_input(
|
|
152
|
+
inputs: Union[ Dict, DictConfig ],
|
|
153
|
+
data_dict: Dict,
|
|
154
|
+
):
|
|
155
|
+
submodule_in = {}
|
|
156
|
+
for k, v in inputs.items():
|
|
157
|
+
if isinstance( v, list ):
|
|
158
|
+
submodule_in[ k ] = [
|
|
159
|
+
_get_module_input(
|
|
160
|
+
k = k,
|
|
161
|
+
v = x,
|
|
162
|
+
data_dict = data_dict
|
|
163
|
+
) for x in v
|
|
164
|
+
]
|
|
165
|
+
else:
|
|
166
|
+
submodule_in[ k ] = _get_module_input(
|
|
167
|
+
k = k,
|
|
168
|
+
v = v,
|
|
169
|
+
data_dict = data_dict
|
|
170
|
+
)
|
|
171
|
+
return submodule_in
|
|
172
|
+
|
|
173
|
+
def create_mask(x, x_length):
|
|
174
|
+
with torch.no_grad():
|
|
175
|
+
S = []
|
|
176
|
+
N = x.shape[-1]
|
|
177
|
+
for n in x_length:
|
|
178
|
+
s = torch.zeros([1, N])
|
|
179
|
+
s[..., :n] = 1.0
|
|
180
|
+
|
|
181
|
+
S.append(s)
|
|
182
|
+
|
|
183
|
+
mask = torch.stack(S).to(x.device)
|
|
184
|
+
## make mask the same dtype as x
|
|
185
|
+
mask = mask.to(x.dtype)
|
|
186
|
+
|
|
187
|
+
return mask
|
|
188
|
+
|
|
189
|
+
def create_mask_same_shape( x, x_length ):
|
|
190
|
+
if len(x.shape) < 2:
|
|
191
|
+
raise ValueError( 'x must have at least 2 dimensions (B, L)' )
|
|
192
|
+
|
|
193
|
+
if x.shape[0] != len(x_length):
|
|
194
|
+
raise ValueError(
|
|
195
|
+
'len(x_len) must be same as first dimension of x (batch size)'
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
with torch.no_grad():
|
|
199
|
+
S = torch.zeros_like( x )
|
|
200
|
+
for index, length in enumerate( x_length ):
|
|
201
|
+
S[ index, ..., :length ] = 1.0
|
|
202
|
+
|
|
203
|
+
S = S.to( x.device )
|
|
204
|
+
S = S.to( x.dtype )
|
|
205
|
+
|
|
206
|
+
return S
|
|
207
|
+
|
|
208
|
+
class LengthHarmonizer( torch.nn.Module ):
|
|
209
|
+
def __init__(
|
|
210
|
+
self,
|
|
211
|
+
mismatch_treshold = 5,
|
|
212
|
+
):
|
|
213
|
+
super().__init__()
|
|
214
|
+
self.mismatch_treshold = mismatch_treshold
|
|
215
|
+
return
|
|
216
|
+
|
|
217
|
+
def forward(
|
|
218
|
+
self,
|
|
219
|
+
data,
|
|
220
|
+
):
|
|
221
|
+
# data is a list of tensors
|
|
222
|
+
# find the minimum length
|
|
223
|
+
lengths = [ x.shape[-1] for x in data ]
|
|
224
|
+
|
|
225
|
+
# check if lengths differ by a threshold, if so raise error
|
|
226
|
+
if self.mismatch_treshold is not None:
|
|
227
|
+
if max( lengths ) - min( lengths ) > self.mismatch_treshold:
|
|
228
|
+
raise ValueError(
|
|
229
|
+
f"""
|
|
230
|
+
losses.LengthHarmonizer: lengths are {lengths}.
|
|
231
|
+
Lengths differ by more than {self.mismatch_treshold} samples.
|
|
232
|
+
A bug is likely.
|
|
233
|
+
"""
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
min_length = min( lengths )
|
|
237
|
+
# truncate all tensors to minimum length
|
|
238
|
+
# NOTE: assumes that last dimension is the length dimension
|
|
239
|
+
# TODO: add support for other dimensions
|
|
240
|
+
data = [ x[ ..., :min_length ] for x in data ]
|
|
241
|
+
|
|
242
|
+
return data
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: hypatorch
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: HypaTorch: A library for abstract and visual model configuration
|
|
5
|
+
Home-page: https://github.com/Altavo/hypatorch/
|
|
6
|
+
Author: Altavo GmbH
|
|
7
|
+
License: Apache 2.0
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: torch
|
|
11
|
+
Requires-Dist: hydra-core
|
|
12
|
+
Requires-Dist: lightningomegaconf
|
|
13
|
+
|
|
14
|
+
# hypaTorch
|
|
15
|
+
<p align="center">
|
|
16
|
+
<b>Highly Abstract Compound Networks in PyTorch</b>
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
This python package provides a flexible and comprehensive framework for creating compound PyTorch models in an abstract manner.
|
|
20
|
+
|
|
21
|
+
<b>NOTE:</b> Currently, this package is in beta stage. Extensive documentation and examples will be added soon with the 1.0 release.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install hypatorch
|
|
28
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
hypatorch/__init__.py,sha256=SdyU6eHweUASMTxXiovdyzg9I-MXP1iyZ3Sv4rwmoSQ,258
|
|
2
|
+
hypatorch/assessments.py,sha256=07l7NyjXK6G9YogP0UMGiWWTjuQPj0YI8ZMW9YuHSUM,4655
|
|
3
|
+
hypatorch/core.py,sha256=aj-hq3f3W0n4IEVmOdcdwOMpVSS2FesiJe_M9xN70Qo,20000
|
|
4
|
+
hypatorch/losses.py,sha256=UDSiobeoiTwhK37Yh5k7zfbSjoePBSggaoAersXtrmM,2544
|
|
5
|
+
hypatorch/utils.py,sha256=tMvIyKLxkinanyyx3zKdD-Rvb4bJzt6CFaGgeyApkAI,7358
|
|
6
|
+
hypatorch-0.1.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
7
|
+
hypatorch-0.1.0.dist-info/METADATA,sha256=61hwp6QE2uNCYyAAPHcxaJ8SvukTTqLHaUTY18uJUmk,763
|
|
8
|
+
hypatorch-0.1.0.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
|
|
9
|
+
hypatorch-0.1.0.dist-info/top_level.txt,sha256=ytSyPpzdwb8OvLp9ANugUl7WbIg3LWG7ikkHQy__krE,10
|
|
10
|
+
hypatorch-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hypatorch
|