-
Notifications
You must be signed in to change notification settings - Fork 382
/
input.py
1582 lines (1359 loc) · 63.8 KB
/
input.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
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
r"""
Input Transformations.
These classes implement a variety of transformations for
input parameters including: learned input warping functions,
rounding functions, and log transformations. The input transformation
is typically part of a Model and applied within the model.forward()
method.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections import OrderedDict
from typing import Any, Callable, Dict, List, Optional, Union
from warnings import warn
import numpy as np
import torch
from botorch.exceptions.errors import BotorchTensorDimensionError
from botorch.exceptions.warnings import UserInputWarning
from botorch.models.transforms.utils import subset_transform
from botorch.models.utils import fantasize
from botorch.utils.rounding import approximate_round, OneHotArgmaxSTE, RoundSTE
from gpytorch import Module as GPyTorchModule
from gpytorch.constraints import GreaterThan
from gpytorch.priors import Prior
from torch import LongTensor, nn, Tensor
from torch.distributions import Kumaraswamy
from torch.nn import Module, ModuleDict
from torch.nn.functional import one_hot
class InputTransform(ABC):
r"""Abstract base class for input transforms.
Note: Input transforms must inherit from `torch.nn.Module`. This
is deferred to the subclasses to avoid any potential conflict
between `gpytorch.module.Module` and `torch.nn.Module` in `Warp`.
Properties:
is_one_to_many: A boolean denoting whether the transform produces
multiple values for each input.
transform_on_train: A boolean indicating whether to apply the
transform in train() mode.
transform_on_eval: A boolean indicating whether to apply the
transform in eval() mode.
transform_on_fantasize: A boolean indicating whether to apply
the transform when called from within a `fantasize` call.
:meta private:
"""
is_one_to_many: bool = False
transform_on_eval: bool
transform_on_train: bool
transform_on_fantasize: bool
def forward(self, X: Tensor) -> Tensor:
r"""Transform the inputs to a model.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n' x d`-dim tensor of transformed inputs.
"""
if self.training:
if self.transform_on_train:
return self.transform(X)
elif self.transform_on_eval:
if fantasize.off() or self.transform_on_fantasize:
return self.transform(X)
return X
@abstractmethod
def transform(self, X: Tensor) -> Tensor:
r"""Transform the inputs to a model.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of transformed inputs.
"""
pass # pragma: no cover
def untransform(self, X: Tensor) -> Tensor:
r"""Un-transform the inputs to a model.
Args:
X: A `batch_shape x n x d`-dim tensor of transformed inputs.
Returns:
A `batch_shape x n x d`-dim tensor of un-transformed inputs.
"""
raise NotImplementedError(
f"{self.__class__.__name__} does not implement the `untransform` method."
)
def equals(self, other: InputTransform) -> bool:
r"""Check if another input transform is equivalent.
Note: The reason that a custom equals method is defined rather than
defining an __eq__ method is because defining an __eq__ method sets
the __hash__ method to None. Hashing modules is currently used in
pytorch. See https://github.com/pytorch/pytorch/issues/7733.
Args:
other: Another input transform.
Returns:
A boolean indicating if the other transform is equivalent.
"""
other_state_dict = other.state_dict()
return (
type(self) is type(other)
and (self.transform_on_train == other.transform_on_train)
and (self.transform_on_eval == other.transform_on_eval)
and (self.transform_on_fantasize == other.transform_on_fantasize)
and all(
torch.allclose(v, other_state_dict[k].to(v))
for k, v in self.state_dict().items()
)
)
def preprocess_transform(self, X: Tensor) -> Tensor:
r"""Apply transforms for preprocessing inputs.
The main use cases for this method are 1) to preprocess training data
before calling `set_train_data` and 2) preprocess `X_baseline` for noisy
acquisition functions so that `X_baseline` is "preprocessed" with the
same transformations as the cached training inputs.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of (transformed) inputs.
"""
if self.transform_on_train:
# We need to disable learning of bounds / affine coefficients here.
# See why: https://github.com/pytorch/botorch/issues/1078.
if hasattr(self, "learn_coefficients"):
learn_coefficients = self.learn_coefficients
self.learn_coefficients = False
result = self.transform(X)
self.learn_coefficients = learn_coefficients
return result
else:
return self.transform(X)
return X
class ChainedInputTransform(InputTransform, ModuleDict):
r"""An input transform representing the chaining of individual transforms."""
def __init__(self, **transforms: InputTransform) -> None:
r"""Chaining of input transforms.
Args:
transforms: The transforms to chain. Internally, the names of the
kwargs are used as the keys for accessing the individual
transforms on the module.
Example:
>>> tf1 = Normalize(d=2)
>>> tf2 = Normalize(d=2)
>>> tf = ChainedInputTransform(tf1=tf1, tf2=tf2)
>>> list(tf.keys())
['tf1', 'tf2']
>>> tf["tf1"]
Normalize()
"""
super().__init__(OrderedDict(transforms))
self.transform_on_train = False
self.transform_on_eval = False
self.transform_on_fantasize = False
for tf in transforms.values():
self.is_one_to_many |= tf.is_one_to_many
self.transform_on_train |= tf.transform_on_train
self.transform_on_eval |= tf.transform_on_eval
self.transform_on_fantasize |= tf.transform_on_fantasize
def transform(self, X: Tensor) -> Tensor:
r"""Transform the inputs to a model.
Individual transforms are applied in sequence.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of transformed inputs.
"""
for tf in self.values():
X = tf.forward(X)
return X
def untransform(self, X: Tensor) -> Tensor:
r"""Un-transform the inputs to a model.
Un-transforms of the individual transforms are applied in reverse sequence.
Args:
X: A `batch_shape x n x d`-dim tensor of transformed inputs.
Returns:
A `batch_shape x n x d`-dim tensor of un-transformed inputs.
"""
for tf in reversed(self.values()):
X = tf.untransform(X)
return X
def equals(self, other: InputTransform) -> bool:
r"""Check if another input transform is equivalent.
Args:
other: Another input transform.
Returns:
A boolean indicating if the other transform is equivalent.
"""
return super().equals(other=other) and all(
t1.equals(t2) for t1, t2 in zip(self.values(), other.values())
)
def preprocess_transform(self, X: Tensor) -> Tensor:
r"""Apply transforms for preprocessing inputs.
The main use cases for this method are 1) to preprocess training data
before calling `set_train_data` and 2) preprocess `X_baseline` for noisy
acquisition functions so that `X_baseline` is "preprocessed" with the
same transformations as the cached training inputs.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of (transformed) inputs.
"""
for tf in self.values():
X = tf.preprocess_transform(X)
return X
class ReversibleInputTransform(InputTransform, ABC):
r"""An abstract class for a reversible input transform.
Properties:
reverse: A boolean indicating if the functionality of transform
and untransform methods should be swapped.
:meta private:
"""
reverse: bool
def transform(self, X: Tensor) -> Tensor:
r"""Transform the inputs.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of transformed inputs.
"""
return self._untransform(X) if self.reverse else self._transform(X)
def untransform(self, X: Tensor) -> Tensor:
r"""Un-transform the inputs.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of un-transformed inputs.
"""
return self._transform(X) if self.reverse else self._untransform(X)
@abstractmethod
def _transform(self, X: Tensor) -> Tensor:
r"""Forward transform the inputs.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of transformed inputs.
"""
pass # pragma: no cover
@abstractmethod
def _untransform(self, X: Tensor) -> Tensor:
r"""Reverse transform the inputs.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of transformed inputs.
"""
pass # pragma: no cover
def equals(self, other: InputTransform) -> bool:
r"""Check if another input transform is equivalent.
Args:
other: Another input transform.
Returns:
A boolean indicating if the other transform is equivalent.
"""
return super().equals(other=other) and (self.reverse == other.reverse)
class AffineInputTransform(ReversibleInputTransform, Module):
def __init__(
self,
d: int,
coefficient: Tensor,
offset: Tensor,
indices: Optional[Union[List[int], Tensor]] = None,
batch_shape: torch.Size = torch.Size(), # noqa: B008
transform_on_train: bool = True,
transform_on_eval: bool = True,
transform_on_fantasize: bool = True,
reverse: bool = False,
) -> None:
r"""Apply affine transformation to input:
`output = (input - offset) / coefficient`
Args:
d: The dimension of the input space.
coefficient: Tensor of linear coefficients, shape must to be
broadcastable with `(batch_shape x n x d)`-dim input tensors.
offset: Tensor of offset coefficients, shape must to be
broadcastable with `(batch_shape x n x d)`-dim input tensors.
indices: The indices of the inputs to transform. If omitted,
take all dimensions of the inputs into account. Either a list of ints
or a Tensor of type `torch.long`.
batch_shape: The batch shape of the inputs (assuming input tensors
of shape `batch_shape x n x d`). If provided, perform individual
transformation per batch, otherwise uses a single transformation.
transform_on_train: A boolean indicating whether to apply the
transform in train() mode. Default: True.
transform_on_eval: A boolean indicating whether to apply the
transform in eval() mode. Default: True.
transform_on_fantasize: A boolean indicating whether to apply the
transform when called from within a `fantasize` call. Default: True.
reverse: A boolean indicating whether the forward pass should untransform
the inputs.
"""
super().__init__()
if (indices is not None) and (len(indices) == 0):
raise ValueError("`indices` list is empty!")
if (indices is not None) and (len(indices) > 0):
indices = torch.as_tensor(
indices, dtype=torch.long, device=coefficient.device
)
if len(indices) > d:
raise ValueError("Can provide at most `d` indices!")
if (indices > d - 1).any():
raise ValueError("Elements of `indices` have to be smaller than `d`!")
if len(indices.unique()) != len(indices):
raise ValueError("Elements of `indices` tensor must be unique!")
self.register_buffer("indices", indices)
torch.broadcast_shapes(coefficient.shape, offset.shape)
self._d = d
self.register_buffer("_coefficient", coefficient)
self.register_buffer("_offset", offset)
self.batch_shape = batch_shape
self.transform_on_train = transform_on_train
self.transform_on_eval = transform_on_eval
self.transform_on_fantasize = transform_on_fantasize
self.reverse = reverse
@property
def coefficient(self) -> Tensor:
r"""The tensor of linear coefficients."""
coeff = self._coefficient
return coeff if self.learn_coefficients and self.training else coeff.detach()
@property
def offset(self) -> Tensor:
r"""The tensor of offset coefficients."""
offset = self._offset
return offset if self.learn_coefficients and self.training else offset.detach()
@property
def learn_coefficients(self) -> bool:
return getattr(self, "_learn_coefficients", False)
@learn_coefficients.setter
def learn_coefficients(self, value: bool) -> None:
r"""A boolean denoting whether to learn the coefficients
from inputs during model training.
"""
self._learn_coefficients = value
@subset_transform
def _transform(self, X: Tensor) -> Tensor:
r"""Apply affine transformation to input.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of transformed inputs.
"""
if self.learn_coefficients and self.training:
self._check_shape(X)
self._update_coefficients(X)
self._to(X)
return (X - self.offset) / self.coefficient
@subset_transform
def _untransform(self, X: Tensor) -> Tensor:
r"""Apply inverse of affine transformation.
Args:
X: A `batch_shape x n x d`-dim tensor of transformed inputs.
Returns:
A `batch_shape x n x d`-dim tensor of un-transformed inputs.
"""
self._to(X)
return self.coefficient * X + self.offset
def equals(self, other: InputTransform) -> bool:
r"""Check if another input transform is equivalent.
Args:
other: Another input transform.
Returns:
A boolean indicating if the other transform is equivalent.
"""
if hasattr(self, "indices") != hasattr(other, "indices"):
return False
isequal = (
super().equals(other=other)
and (self._d == other._d)
and torch.allclose(self.coefficient, other.coefficient)
and torch.allclose(self.offset, other.offset)
and self.learn_coefficients == other.learn_coefficients
)
if hasattr(self, "indices"):
isequal = isequal and (self.indices == other.indices).all()
return isequal
def _check_shape(self, X: Tensor) -> None:
"""Checking input dimensions, included to increase code sharing
among the derived classes Normalize and InputStandardize.
"""
if X.size(-1) != self.offset.size(-1):
raise BotorchTensorDimensionError(
f"Wrong input dimension. Received {X.size(-1)}, "
f"expected {self.offset.size(-1)}."
)
n = len(self.batch_shape) + 2
if X.ndim < n:
raise ValueError(
f"`X` must have at least {n} dimensions, {n - 2} batch and 2 innate"
f" , but has {X.ndim}."
)
torch.broadcast_shapes(self.coefficient.shape, self.offset.shape, X.shape)
def _to(self, X: Tensor) -> None:
r"""Makes coefficient and offset have same device and dtype as X."""
self._coefficient = self.coefficient.to(X)
self._offset = self.offset.to(X)
def _update_coefficients(self, X: Tensor) -> None:
r"""Updates affine coefficients. Implemented by subclasses,
e.g. Normalize and InputStandardize.
"""
raise NotImplementedError(
"Only subclasses of AffineInputTransform implement "
"_update_coefficients, e.g. Normalize and InputStandardize."
)
class Normalize(AffineInputTransform):
r"""Normalize the inputs to the unit cube.
If no explicit bounds are provided this module is stateful: If in train mode,
calling `forward` updates the module state (i.e. the normalizing bounds). If
in eval mode, calling `forward` simply applies the normalization using the
current module state.
"""
def __init__(
self,
d: int,
indices: Optional[Union[List[int], Tensor]] = None,
bounds: Optional[Tensor] = None,
batch_shape: torch.Size = torch.Size(), # noqa: B008
transform_on_train: bool = True,
transform_on_eval: bool = True,
transform_on_fantasize: bool = True,
reverse: bool = False,
min_range: float = 1e-8,
learn_bounds: Optional[bool] = None,
almost_zero: float = 1e-12,
) -> None:
r"""Normalize the inputs to the unit cube.
Args:
d: The dimension of the input space.
indices: The indices of the inputs to normalize. If omitted,
take all dimensions of the inputs into account.
bounds: If provided, use these bounds to normalize the inputs. If
omitted, learn the bounds in train mode.
batch_shape: The batch shape of the inputs (assuming input tensors
of shape `batch_shape x n x d`). If provided, perform individual
normalization per batch, otherwise uses a single normalization.
transform_on_train: A boolean indicating whether to apply the
transforms in train() mode. Default: True.
transform_on_eval: A boolean indicating whether to apply the
transform in eval() mode. Default: True.
transform_on_fantasize: A boolean indicating whether to apply the
transform when called from within a `fantasize` call. Default: True.
reverse: A boolean indicating whether the forward pass should untransform
the inputs.
min_range: If the range of an input dimension is smaller than `min_range`,
that input dimension will not be normalized. This is equivalent to
using bounds of `[0, 1]` for this dimension, and helps avoid division
by zero errors and related numerical issues. See the example below.
NOTE: This only applies if `learn_bounds=True`.
learn_bounds: Whether to learn the bounds in train mode. Defaults
to False if bounds are provided, otherwise defaults to True.
Example:
>>> t = Normalize(d=2)
>>> t(torch.tensor([[3., 2.], [3., 6.]]))
... tensor([[3., 2.],
... [3., 6.]])
>>> t.eval()
... Normalize()
>>> t(torch.tensor([[3.5, 2.8]]))
... tensor([[3.5, 0.2]])
>>> t.bounds
... tensor([[0., 2.],
... [1., 6.]])
>>> t.coefficient
... tensor([[1., 4.]])
"""
if learn_bounds is not None:
self.learn_coefficients = learn_bounds
else:
self.learn_coefficients = bounds is None
transform_dimension = d if indices is None else len(indices)
if bounds is not None:
if indices is not None and bounds.size(-1) == d:
bounds = bounds[..., indices]
if bounds.size(-1) != transform_dimension:
raise BotorchTensorDimensionError(
"Dimensions of provided `bounds` are incompatible with "
f"transform_dimension = {transform_dimension}!"
)
offset = bounds[..., 0:1, :]
coefficient = bounds[..., 1:2, :] - offset
if coefficient.ndim > 2:
batch_shape = coefficient.shape[:-2]
else:
coefficient = torch.ones(*batch_shape, 1, transform_dimension)
offset = torch.zeros(*batch_shape, 1, transform_dimension)
if self.learn_coefficients is False:
warn(
"learn_bounds is False and no bounds were provided. The bounds "
"will not be updated and the transform will be a no-op.",
UserInputWarning,
)
super().__init__(
d=d,
coefficient=coefficient,
offset=offset,
indices=indices,
batch_shape=batch_shape,
transform_on_train=transform_on_train,
transform_on_eval=transform_on_eval,
transform_on_fantasize=transform_on_fantasize,
reverse=reverse,
)
self.min_range = min_range
@property
def ranges(self):
return self.coefficient
@property
def mins(self):
return self.offset
@property
def bounds(self) -> Tensor:
r"""The bounds used for normalizing the inputs."""
return torch.cat([self.offset, self.offset + self.coefficient], dim=-2)
@property
def learn_bounds(self) -> bool:
return self.learn_coefficients
def _update_coefficients(self, X) -> None:
"""Computes the normalization bounds and updates the affine
coefficients, which determine the base class's behavior.
"""
# Aggregate mins and ranges over extra batch and marginal dims
batch_ndim = min(len(self.batch_shape), X.ndim - 2) # batch rank of `X`
reduce_dims = (*range(X.ndim - batch_ndim - 2), X.ndim - 2)
offset = torch.amin(X, dim=reduce_dims).unsqueeze(-2)
coefficient = torch.amax(X, dim=reduce_dims).unsqueeze(-2) - offset
almost_zero = coefficient < self.min_range
self._coefficient = torch.where(almost_zero, 1.0, coefficient)
self._offset = torch.where(almost_zero, 0.0, offset)
def get_init_args(self) -> Dict[str, Any]:
r"""Get the arguments necessary to construct an exact copy of the transform."""
return {
"d": self._d,
"indices": getattr(self, "indices", None),
"bounds": self.bounds,
"batch_shape": self.batch_shape,
"transform_on_train": self.transform_on_train,
"transform_on_eval": self.transform_on_eval,
"transform_on_fantasize": self.transform_on_fantasize,
"reverse": self.reverse,
"min_range": self.min_range,
"learn_bounds": self.learn_bounds,
}
class InputStandardize(AffineInputTransform):
r"""Standardize inputs (zero mean, unit variance).
In train mode, calling `forward` updates the module state
(i.e. the mean/std normalizing constants). If in eval mode, calling `forward`
simply applies the standardization using the current module state.
"""
def __init__(
self,
d: int,
indices: Optional[Union[List[int], Tensor]] = None,
batch_shape: torch.Size = torch.Size(), # noqa: B008
transform_on_train: bool = True,
transform_on_eval: bool = True,
transform_on_fantasize: bool = True,
reverse: bool = False,
min_std: float = 1e-8,
) -> None:
r"""Standardize inputs (zero mean, unit variance).
Args:
d: The dimension of the input space.
indices: The indices of the inputs to standardize. If omitted,
take all dimensions of the inputs into account.
batch_shape: The batch shape of the inputs (asssuming input tensors
of shape `batch_shape x n x d`). If provided, perform individual
normalization per batch, otherwise uses a single normalization.
transform_on_train: A boolean indicating whether to apply the
transforms in train() mode. Default: True
transform_on_eval: A boolean indicating whether to apply the
transform in eval() mode. Default: True
reverse: A boolean indicating whether the forward pass should untransform
the inputs.
min_std: If the standard deviation of an input dimension is smaller than
`min_std`, that input dimension will not be standardized. This is
equivalent to using a standard deviation of 1.0 and a mean of 0.0 for
this dimension, and helps avoid division by zero errors and related
numerical issues.
"""
transform_dimension = d if indices is None else len(indices)
super().__init__(
d=d,
coefficient=torch.ones(*batch_shape, 1, transform_dimension),
offset=torch.zeros(*batch_shape, 1, transform_dimension),
indices=indices,
batch_shape=batch_shape,
transform_on_train=transform_on_train,
transform_on_eval=transform_on_eval,
transform_on_fantasize=transform_on_fantasize,
reverse=reverse,
)
self.min_std = min_std
self.learn_coefficients = True
@property
def stds(self):
return self.coefficient
@property
def means(self):
return self.offset
def _update_coefficients(self, X: Tensor) -> None:
"""Computes the normalization bounds and updates the affine
coefficients, which determine the base class's behavior.
"""
# Aggregate means and standard deviations over extra batch and marginal dims
batch_ndim = min(len(self.batch_shape), X.ndim - 2) # batch rank of `X`
reduce_dims = (*range(X.ndim - batch_ndim - 2), X.ndim - 2)
coefficient, offset = (
values.unsqueeze(-2)
for values in torch.std_mean(X, dim=reduce_dims, unbiased=True)
)
almost_zero = coefficient < self.min_std
self._coefficient = torch.where(almost_zero, 1.0, coefficient)
self._offset = torch.where(almost_zero, 0.0, offset)
class Round(InputTransform, Module):
r"""A discretization transformation for discrete inputs.
If `approximate=False` (the default), uses PyTorch's `round`.
If `approximate=True`, a differentiable approximate rounding function is
used, with a temperature parameter of `tau`. This method is a piecewise
approximation of a rounding function where each piece is a hyperbolic
tangent function.
For integers, this will typically be used in conjunction
with normalization as follows:
In eval() mode (i.e. after training), the inputs pass
would typically be normalized to the unit cube (e.g. during candidate
optimization). 1. These are unnormalized back to the raw input space.
2. The integers are rounded. 3. All values are normalized to the unit
cube.
In train() mode, the inputs can either (a) be normalized to the unit
cube or (b) provided using their raw values. In the case of (a)
transform_on_train should be set to True, so that the normalized inputs
are unnormalized before rounding. In the case of (b) transform_on_train
should be set to False, so that the raw inputs are rounded and then
normalized to the unit cube.
By default, the straight through estimators are used for the gradients as
proposed in [Daulton2022bopr]_. This transformation supports differentiable
approximate rounding (currently only for integers). The rounding function
is approximated with a piece-wise function where each piece is a hyperbolic
tangent function.
For categorical parameters, the input must be one-hot encoded.
Example:
>>> bounds = torch.tensor([[0, 5], [0, 1], [0, 1]]).t()
>>> integer_indices = [0]
>>> categorical_features = {1: 2}
>>> unnormalize_tf = Normalize(
>>> d=d,
>>> bounds=bounds,
>>> transform_on_eval=True,
>>> transform_on_train=True,
>>> reverse=True,
>>> )
>>> round_tf = Round(integer_indices, categorical_features)
>>> normalize_tf = Normalize(d=d, bounds=bounds)
>>> tf = ChainedInputTransform(
>>> tf1=unnormalize_tf, tf2=round_tf, tf3=normalize_tf
>>> )
"""
def __init__(
self,
integer_indices: Union[List[int], LongTensor, None] = None,
categorical_features: Optional[Dict[int, int]] = None,
transform_on_train: bool = True,
transform_on_eval: bool = True,
transform_on_fantasize: bool = True,
approximate: bool = False,
tau: float = 1e-3,
**kwargs,
) -> None:
r"""Initialize transform.
Args:
integer_indices: The indices of the integer inputs.
categorical_features: A dictionary mapping the starting index of each
categorical feature to its cardinality. This assumes that categoricals
are one-hot encoded.
transform_on_train: A boolean indicating whether to apply the
transforms in train() mode. Default: True.
transform_on_eval: A boolean indicating whether to apply the
transform in eval() mode. Default: True.
transform_on_fantasize: A boolean indicating whether to apply the
transform when called from within a `fantasize` call. Default: True.
approximate: A boolean indicating whether approximate or exact
rounding should be used. Default: False.
tau: The temperature parameter for approximate rounding.
"""
indices = kwargs.get("indices")
if indices is not None:
warn(
"`indices` is marked for deprecation in favor of `integer_indices`.",
DeprecationWarning,
)
integer_indices = indices
if approximate and categorical_features is not None:
raise NotImplementedError
super().__init__()
self.transform_on_train = transform_on_train
self.transform_on_eval = transform_on_eval
self.transform_on_fantasize = transform_on_fantasize
integer_indices = integer_indices if integer_indices is not None else []
self.register_buffer(
"integer_indices", torch.as_tensor(integer_indices, dtype=torch.long)
)
self.categorical_features = categorical_features or {}
self.approximate = approximate
self.tau = tau
def transform(self, X: Tensor) -> Tensor:
r"""Discretize the inputs.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of discretized inputs.
"""
X_rounded = X.clone()
# round integers
X_int = X_rounded[..., self.integer_indices]
if self.approximate:
X_int = approximate_round(X_int, tau=self.tau)
else:
X_int = RoundSTE.apply(X_int)
X_rounded[..., self.integer_indices] = X_int
# discrete categoricals to the category with the largest value
# in the continuous relaxation of the one-hot encoding
for start, card in self.categorical_features.items():
end = start + card
X_rounded[..., start:end] = OneHotArgmaxSTE.apply(X[..., start:end])
return X_rounded
def equals(self, other: InputTransform) -> bool:
r"""Check if another input transform is equivalent.
Args:
other: Another input transform.
Returns:
A boolean indicating if the other transform is equivalent.
"""
return (
super().equals(other=other)
and (self.integer_indices == other.integer_indices).all()
and self.categorical_features == other.categorical_features
and self.approximate == other.approximate
and self.tau == other.tau
)
def get_init_args(self) -> Dict[str, Any]:
r"""Get the arguments necessary to construct an exact copy of the transform."""
return {
"integer_indices": self.integer_indices,
"categorical_features": self.categorical_features,
"transform_on_train": self.transform_on_train,
"transform_on_eval": self.transform_on_eval,
"transform_on_fantasize": self.transform_on_fantasize,
"approximate": self.approximate,
"tau": self.tau,
}
class Log10(ReversibleInputTransform, Module):
r"""A base-10 log transformation."""
def __init__(
self,
indices: List[int],
transform_on_train: bool = True,
transform_on_eval: bool = True,
transform_on_fantasize: bool = True,
reverse: bool = False,
) -> None:
r"""Initialize transform.
Args:
indices: The indices of the inputs to log transform.
transform_on_train: A boolean indicating whether to apply the
transforms in train() mode. Default: True.
transform_on_eval: A boolean indicating whether to apply the
transform in eval() mode. Default: True.
transform_on_fantasize: A boolean indicating whether to apply the
transform when called from within a `fantasize` call. Default: True.
reverse: A boolean indicating whether the forward pass should untransform
the inputs.
"""
super().__init__()
self.register_buffer("indices", torch.tensor(indices, dtype=torch.long))
self.transform_on_train = transform_on_train
self.transform_on_eval = transform_on_eval
self.transform_on_fantasize = transform_on_fantasize
self.reverse = reverse
@subset_transform
def _transform(self, X: Tensor) -> Tensor:
r"""Log transform the inputs.
Args:
X: A `batch_shape x n x d`-dim tensor of inputs.
Returns:
A `batch_shape x n x d`-dim tensor of transformed inputs.
"""
return X.log10()
@subset_transform
def _untransform(self, X: Tensor) -> Tensor:
r"""Reverse the log transformation.
Args:
X: A `batch_shape x n x d`-dim tensor of normalized inputs.
Returns:
A `batch_shape x n x d`-dim tensor of un-normalized inputs.
"""
return 10.0**X
class Warp(ReversibleInputTransform, GPyTorchModule):
r"""A transform that uses learned input warping functions.
Each specified input dimension is warped using the CDF of a
Kumaraswamy distribution. Typically, MAP estimates of the
parameters of the Kumaraswamy distribution, for each input
dimension, are learned jointly with the GP hyperparameters.
TODO: implement support using independent warping functions
for each output in batched multi-output and multi-task models.
For now, ModelListGPs should be used to learn independent warping
functions for each output.
"""
# TODO: make minimum value dtype-dependent
_min_concentration_level = 1e-4
def __init__(
self,
indices: List[int],
transform_on_train: bool = True,
transform_on_eval: bool = True,
transform_on_fantasize: bool = True,
reverse: bool = False,
eps: float = 1e-7,
concentration1_prior: Optional[Prior] = None,
concentration0_prior: Optional[Prior] = None,
batch_shape: Optional[torch.Size] = None,
) -> None:
r"""Initialize transform.
Args:
indices: The indices of the inputs to warp.
transform_on_train: A boolean indicating whether to apply the
transforms in train() mode. Default: True.
transform_on_eval: A boolean indicating whether to apply the
transform in eval() mode. Default: True.
transform_on_fantasize: A boolean indicating whether to apply the
transform when called from within a `fantasize` call. Default: True.
reverse: A boolean indicating whether the forward pass should untransform
the inputs.
eps: A small value used to clip values to be in the interval (0, 1).
concentration1_prior: A prior distribution on the concentration1 parameter
of the Kumaraswamy distribution.
concentration0_prior: A prior distribution on the concentration0 parameter
of the Kumaraswamy distribution.
batch_shape: An optional batch shape, for learning independent warping
parameters for each batch of inputs. This should match the input batch
shape of the model (i.e., `train_X.shape[:-2]`).
NOTE: This is only supported for single-output models.
"""
super().__init__()
self.register_buffer("indices", torch.tensor(indices, dtype=torch.long))
self.transform_on_train = transform_on_train
self.transform_on_eval = transform_on_eval
self.transform_on_fantasize = transform_on_fantasize
self.reverse = reverse
self.batch_shape = batch_shape or torch.Size([])
self._X_min = eps
self._X_range = 1 - 2 * eps
if len(self.batch_shape) > 0:
# Note: this follows the gpytorch shape convention for lengthscales
# There is ongoing discussion about the extra `1`.
# TODO: update to follow new gpytorch convention resulting from
# https://github.com/cornellius-gp/gpytorch/issues/1317
batch_shape = self.batch_shape + torch.Size([1])