-
Notifications
You must be signed in to change notification settings - Fork 372
Expand file tree
/
Copy pathparameter.py
More file actions
1775 lines (1522 loc) · 67.3 KB
/
parameter.py
File metadata and controls
1775 lines (1522 loc) · 67.3 KB
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.
# pyre-strict
from __future__ import annotations
import math
from abc import ABCMeta, abstractmethod
from copy import deepcopy
from enum import Enum
from logging import Logger
from math import inf
from typing import Any, cast, Self, Union
from warnings import warn
import numpy as np
import numpy.typing as npt
from ax.core.types import TNumeric, TParameterization, TParamValue
from ax.exceptions.core import AxParameterWarning, UnsupportedError, UserInputError
from ax.utils.common.base import SortableBase
from ax.utils.common.logger import get_logger
from ax.utils.common.string_utils import sanitize_name, unsanitize_name
from pandas import DataFrame as PandasDataFrame
from pyre_extensions import assert_is_instance, none_throws
from scipy.special import expit, logit
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import Float, Integer
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
logger: Logger = get_logger(__name__)
# Tolerance for floating point comparisons. This is relatively permissive,
# and allows for serializing at rather low numerical precision.
# TODO: Do a more comprehensive audit of how floating point precision issues
# may creep up and implement a more principled fix
EPS = 1.5e-7
MAX_VALUES_CHOICE_PARAM = 1000
FIXED_CHOICE_PARAM_ERROR = (
"ChoiceParameters require multiple feasible values. "
"Please use FixedParameter instead when setting a single possible value."
)
REPR_FLAGS_IF_TRUE_ONLY = [
"is_fidelity",
"is_task",
"is_hierarchical",
"log_scale",
"logit_scale",
]
class ParameterType(Enum):
BOOL = 0
INT = 1
FLOAT = 2
STRING = 3
@property
def is_numeric(self) -> bool:
return self == ParameterType.INT or self == ParameterType.FLOAT
TParameterType = Union[type[int], type[float], type[str], type[bool]]
# pyre-fixme[9]: Pyre collapses individual type[] values into Type[Union[...]].
PARAMETER_PYTHON_TYPE_MAP: dict[ParameterType, TParameterType] = {
ParameterType.INT: int,
ParameterType.FLOAT: float,
ParameterType.STRING: str,
ParameterType.BOOL: bool,
}
SUPPORTED_PARAMETER_TYPES: tuple[
type[bool] | type[float] | type[int] | type[str], ...
] = tuple(PARAMETER_PYTHON_TYPE_MAP.values())
def _get_parameter_type(python_type: type[Any]) -> ParameterType:
"""Given a Python type, retrieve corresponding Ax ``ParameterType``."""
for param_type, py_type in PARAMETER_PYTHON_TYPE_MAP.items():
if py_type == python_type:
return param_type
raise ValueError(f"No Ax parameter type corresponding to {python_type}.")
class Parameter(SortableBase, metaclass=ABCMeta):
_is_fidelity: bool = False
_name: str
_target_value: TParamValue = None
_parameter_type: ParameterType
_backfill_value: TParamValue = None
_default_value: TParamValue = None
def cast(self, value: TParamValue) -> TParamValue:
if value is None:
raise UnsupportedError("None values are not supported.")
return self.python_type(value)
@abstractmethod
def validate(self, value: TParamValue, raises: bool = False) -> bool:
"""Returns True if input is a valid value for the parameter.
Args:
value: Value being checked.
raises: If true, and validation fails, raises a UserInputError.
Raises:
UserInputError: If validation fails and raises is True.
Returns:
True if valid, False otherwise.
"""
@abstractmethod
def validate_array(
self,
values: npt.NDArray,
) -> npt.NDArray:
"""Vectorized validation for a NumPy array of values.
Returns a boolean array indicating whether each value is valid.
Args:
values: A NumPy array of values to validate.
Returns:
A boolean NumPy array with True for valid values.
"""
@abstractmethod
def cardinality(self) -> float:
pass
@property
def python_type(self) -> TParameterType:
"""The python type for the corresponding ParameterType enum.
Used primarily for casting values of unknown type to conform
to that of the parameter.
"""
return PARAMETER_PYTHON_TYPE_MAP[self.parameter_type]
def is_valid_type(self, value: TParamValue) -> bool:
"""Whether a given value's type is allowed by this parameter."""
return type(value) is self.python_type or (
# ints are floats
type(value) is int and self.python_type is float
)
def is_compatible_with(self, other: Parameter) -> bool:
"""Check whether parameters are compatible.
Two parameters are compatible if they have the same parameter type and
compatible domain types. Any pair of parameters that can be merged is also
considered compatible. In particular:
- Two RangeParameters are always compatible (bounds may differ).
- A RangeParameter and a FixedParameter are compatible.
- Two ChoiceParameters are always compatible (values may differ).
- Two FixedParameters are always compatible (values may differ).
Args:
other: Another Ax parameter object to compare against.
Returns:
Whether the parameters are compatible or not.
"""
if self.parameter_type != other.parameter_type:
return False
return self._is_domain_compatible(other)
@abstractmethod
def _is_domain_compatible(self, other: Parameter) -> bool:
"""Check domain-specific compatibility.
This method is called after verifying that parameter types match.
Subclasses should implement domain-specific compatibility checks.
Args:
other: Another Ax parameter object to compare against.
Returns:
Whether the parameters are domain-compatible or not.
"""
pass
@property
def is_numeric(self) -> bool:
return self.parameter_type.is_numeric
@property
def is_fidelity(self) -> bool:
return self._is_fidelity
@property
def is_hierarchical(self) -> bool:
return isinstance(self, (ChoiceParameter, FixedParameter)) and bool(
self._dependents
)
@property
def target_value(self) -> TParamValue:
return self._target_value
@property
def backfill_value(self) -> TParamValue:
return self._backfill_value
@property
def default_value(self) -> TParamValue:
return self._default_value
@property
def is_disabled(self) -> bool:
return self.default_value is not None
@property
def parameter_type(self) -> ParameterType:
return self._parameter_type
@property
def name(self) -> str:
return self._name
@property
def dependents(self) -> dict[TParamValue, list[str]]:
raise NotImplementedError(
"Only fixed and choice hierarchical parameters are currently supported."
)
@abstractmethod
def clone(self) -> Self: ...
def disable(self, default_value: TParamValue) -> None:
"""
Effectively remove parameter from the search space for future trial generation.
Existing trials remain valid, and the disabled parameter is replaced with the
default_value for all subsequent trials.
"""
if self.is_disabled:
logger.warning(
f"Parameter {self.name} is already disabled with "
f"default value {self.default_value}. "
f"Updating default value to {default_value}."
)
self._default_value = default_value
@property
def _unique_id(self) -> str:
return str(self)
def _base_repr(self) -> str:
ret_val = (
f"{self.__class__.__name__}("
f"name='{self._name}', "
f"parameter_type={self.parameter_type.name}, "
f"{self.domain_repr}"
)
# Add binary flags.
for flag in self.available_flags:
val = getattr(self, flag, False)
if flag not in REPR_FLAGS_IF_TRUE_ONLY or (
flag in REPR_FLAGS_IF_TRUE_ONLY and val is True
):
ret_val += f", {flag}={val}"
# Add target_value if one exists.
if self.target_value is not None:
tval_rep = self.target_value
if self.parameter_type == ParameterType.STRING:
tval_rep = f"'{tval_rep}'"
ret_val += f", target_value={tval_rep}"
return ret_val
@property
@abstractmethod
def domain_repr(self) -> str:
"""Returns a string representation of the domain."""
pass
@property
def available_flags(self) -> list[str]:
"""List of boolean attributes that can be set on this parameter."""
return ["is_fidelity"]
@property
def summary_dict(
self,
) -> dict[str, Any]:
# Assemble dict.
summary_dict: dict[str, Any] = {
"name": self.name,
"type": self.__class__.__name__.removesuffix("Parameter"),
"domain": self.domain_repr,
"parameter_type": self.parameter_type.name.lower(),
}
# Extract flags.
flags = []
for flag in self.available_flags:
flag_val = getattr(self, flag, None)
flag_repr = flag.removeprefix("is_")
if flag == "sort_values":
flag_repr = "sorted"
if flag_val is True:
flags.append(flag_repr)
elif flag_val is False and flag not in REPR_FLAGS_IF_TRUE_ONLY:
flags.append("un" + flag_repr)
# Add flags, target_values, and dependents if present.
if flags:
summary_dict["flags"] = ", ".join(flags)
if getattr(self, "is_fidelity", False) or getattr(self, "is_task", False):
summary_dict["target_value"] = self.target_value
if getattr(self, "is_hierarchical", False):
summary_dict["dependents"] = self.dependents
if getattr(self, "backfill_value", None) is not None:
summary_dict["backfill_value"] = self.backfill_value
if getattr(self, "default_value", None) is not None:
summary_dict["default_value"] = self.default_value
return summary_dict
class RangeParameter(Parameter):
"""Parameter object that specifies a range of values."""
def __init__(
self,
name: str,
parameter_type: ParameterType,
lower: float,
upper: float,
log_scale: bool = False,
logit_scale: bool = False,
digits: int | None = None,
step_size: float | None = None,
is_fidelity: bool = False,
target_value: TParamValue = None,
backfill_value: TParamValue = None,
default_value: TParamValue = None,
) -> None:
"""Initialize RangeParameter
Args:
name: Name of the parameter.
parameter_type: Enum indicating the type of parameter
value (e.g. string, int).
lower: Lower bound of the parameter range (inclusive).
upper: Upper bound of the parameter range (inclusive).
log_scale: Whether to sample in the log space when drawing
random values of the parameter.
logit_scale: Whether to sample in logit space when drawing
random values of the parameter.
digits: Number of digits to round values to for float type.
Deprecated in favor of ``step_size``; cannot be set together
with ``step_size``.
step_size: If set, the parameter's feasible values are the grid
``{lower + k * step_size : k in N}`` intersected with
``[lower, upper]``. ``cast()`` snaps values to the nearest grid
point (anchored at ``lower``) without clamping to the bounds, so
an out-of-bounds input snaps to an out-of-bounds grid point --
mirroring the non-``step_size`` ``cast()``, which also leaves
out-of-bounds values in place. ``step_size`` must be strictly
positive, and the range must be an exact multiple of it:
``(upper - lower)`` must be an integer multiple of ``step_size``
(within ``EPS``), so that both bounds lie on the grid. For INT
parameters, ``step_size`` must itself be integer-valued.
``step_size`` defines a discrete grid but does not, by itself,
force discrete acquisition optimization. How the optimizer
treats the parameter depends on the grid cardinality
``floor((upper - lower) / step_size) + 1``, and is determined
at the generator level.
is_fidelity: Whether this parameter is a fidelity parameter.
target_value: Target value of this parameter if it is a fidelity.
backfill_value: For parameters added to experiments that have already run
trials.
Used to backfill trials missing the parameter.
default_value: For parameters disabled in experiments that have already
run trials. Used as default value in modeling for future trials.
"""
if is_fidelity and (target_value is None):
raise UserInputError(
"`target_value` should not be None for the fidelity parameter: "
"{}".format(name)
)
self._name = name
if parameter_type not in (ParameterType.INT, ParameterType.FLOAT):
raise UserInputError("RangeParameter type must be int or float.")
self._parameter_type = parameter_type
self._digits = digits
# ``_step_size`` must be set before casting ``lower`` / ``upper`` below,
# since ``cast()`` reads it to snap values to the grid.
self._step_size: float | None = None
self._validate_and_set_step_size(step_size=step_size)
self._lower: TNumeric = self.cast(lower)
self._upper: TNumeric = self.cast(upper)
self._log_scale = log_scale
self._logit_scale = logit_scale
self._is_fidelity = is_fidelity
self._target_value: TNumeric | None = (
self.cast(target_value) if target_value is not None else None
)
self._backfill_value: TNumeric | None = (
self.cast(backfill_value) if backfill_value is not None else None
)
self._default_value: TNumeric | None = (
self.cast(default_value) if default_value is not None else None
)
# Validate the raw inputs: this rejects invalid user input (e.g. a
# non-integer bound for an INT parameter) before ``cast()`` silently
# truncates it. For the non-deprecated paths ``cast()`` does not move a
# bound that would otherwise pass validation -- FLOAT casting is a no-op
# on the value, and ``step_size`` snapping is skipped for bounds -- so
# validating the raw inputs also guarantees the stored bounds are valid.
self._validate_range_param(
parameter_type=parameter_type,
lower=lower,
upper=upper,
log_scale=log_scale,
logit_scale=logit_scale,
)
# ``upper`` must additionally lie on the ``step_size`` grid (the grid is
# anchored at ``lower``).
self._validate_step_size_on_grid()
def cardinality(self) -> TNumeric:
if self._step_size is not None:
# Values are snapped to the grid {lower + k * step_size}
# intersected with [lower, upper]. Both bounds lie on the grid
# (enforced at construction), so the number of grid points is
# (upper - lower) / step_size + 1.
step_size = none_throws(self._step_size)
return round((float(self.upper) - float(self.lower)) / step_size) + 1
if self.parameter_type == ParameterType.FLOAT:
return inf
return int(self.upper) - int(self.lower) + 1
def _validate_range_param(
self,
lower: TNumeric,
upper: TNumeric,
log_scale: bool,
logit_scale: bool,
parameter_type: ParameterType | None = None,
) -> None:
if parameter_type and parameter_type not in (
ParameterType.INT,
ParameterType.FLOAT,
):
raise UserInputError(
f"RangeParameter {self.name} type must be int or float."
)
upper = float(upper)
if lower >= upper:
raise UserInputError(
f"Upper bound of {self.name} must be strictly larger than lower. "
f"Got: ({lower}, {upper})."
)
width: float = upper - lower
if width < 100 * EPS:
raise UserInputError(
f"Parameter {self.name}'s range ({width}) is very small and likely "
"to cause numerical errors. Consider reparameterizing your "
"problem by scaling the parameter."
)
if log_scale and logit_scale:
raise UserInputError(f"{self.name} can't use both log and logit.")
if log_scale and lower <= 0:
raise UserInputError(f"{self.name} cannot take log when min <= 0.")
if logit_scale and (lower <= 0 or upper >= 1):
raise UserInputError(f"{self.name} logit requires lower > 0 and upper < 1")
if not (self.is_valid_type(lower)) or not (self.is_valid_type(upper)):
raise UserInputError(
f"[{lower}, {upper}] is an invalid range for {self.name}."
)
@property
def upper(self) -> TNumeric:
"""Upper bound of the parameter range.
Value is cast to parameter type upon set and also validated
to ensure the bound is strictly greater than lower bound.
"""
return self._upper
@upper.setter
def upper(self, value: TNumeric) -> None:
self._validate_range_param(
lower=self.lower,
upper=value,
log_scale=self.log_scale,
logit_scale=self.logit_scale,
)
self._upper = self.cast(value)
@property
def lower(self) -> TNumeric:
"""Lower bound of the parameter range.
Value is cast to parameter type upon set and also validated
to ensure the bound is strictly less than upper bound.
"""
return self._lower
@lower.setter
def lower(self, value: TNumeric) -> None:
self._validate_range_param(
lower=value,
upper=self.upper,
log_scale=self.log_scale,
logit_scale=self.logit_scale,
)
self._lower = self.cast(value)
@property
def digits(self) -> int | None:
"""Number of digits to round values to for float type.
Upper and lower bound are re-cast after this property is changed.
"""
return self._digits
@property
def step_size(self) -> float | None:
"""Grid spacing that values are snapped to in ``cast()``.
If set, the parameter's feasible values are the grid
``{lower + k * step_size : k in N}`` intersected with ``[lower, upper]``,
and ``cast()`` snaps values to the nearest grid point (without clamping
to the bounds). Both bounds are guaranteed to be on the grid (the
constructor requires ``(upper - lower)`` to be an integer multiple of
``step_size``). ``None`` means no snapping.
"""
return self._step_size
@property
def log_scale(self) -> bool:
"""Whether the parameter's values should be sampled from log space."""
return self._log_scale
@property
def logit_scale(self) -> bool:
"""Whether the parameter's random values should be sampled from logit space."""
return self._logit_scale
def update_range(
self, lower: float | None = None, upper: float | None = None
) -> RangeParameter:
"""Set the range to the given values.
If lower or upper is not provided, it will be left at its current value.
Args:
lower: New value for the lower bound.
upper: New value for the upper bound.
"""
if lower is None:
lower = self._lower
if upper is None:
upper = self._upper
# When ``step_size`` is set, cast the bounds without snapping to the
# (old) grid: bounds anchor the grid and must not be silently moved onto
# it. ``super().cast()`` applies only the type cast. The digits path
# (deprecated) keeps its historical rounding behavior via ``self.cast``.
if self._step_size is not None:
cast_lower = assert_is_instance(super().cast(lower), TNumeric)
cast_upper = assert_is_instance(super().cast(upper), TNumeric)
else:
cast_lower = self.cast(lower)
cast_upper = self.cast(upper)
self._validate_range_param(
lower=cast_lower,
upper=cast_upper,
log_scale=self.log_scale,
logit_scale=self.logit_scale,
)
# The new bounds must lie on the ``step_size`` grid, if one is set.
# Validate before committing so a failed update leaves bounds unchanged.
self._validate_step_size_on_grid(lower=cast_lower, upper=cast_upper)
self._lower = cast_lower
self._upper = cast_upper
return self
def set_digits(self, digits: int | None) -> RangeParameter:
self._digits = digits
# Re-scale min and max to new digits definition
cast_lower = self.cast(self._lower)
cast_upper = self.cast(self._upper)
if float(cast_lower) >= float(cast_upper):
raise UserInputError(
f"Lower bound {cast_lower} is >= upper bound {cast_upper}."
)
self._lower = cast_lower
self._upper = cast_upper
return self
def set_step_size(self, step_size: float | None) -> RangeParameter:
"""Set the grid spacing that values are snapped to in ``cast()``.
The existing bounds are kept as-is (they anchor the grid and define the
feasible range); they are not snapped onto the new grid. Instead we
require that they already lie on it: ``(upper - lower)`` must be an
integer multiple of the new ``step_size``.
Raises:
UserInputError: If the current bounds do not lie on the new grid.
"""
previous_step_size = self._step_size
self._validate_and_set_step_size(step_size=step_size)
try:
# The current (unchanged) bounds must lie on the new grid.
self._validate_step_size_on_grid()
except UserInputError:
# Leave the parameter unchanged if the new grid is invalid.
self._step_size = previous_step_size
raise
return self
def _validate_and_set_step_size(self, step_size: float | None) -> None:
"""Validate ``step_size`` and store it on ``self._step_size``.
Raises:
UserInputError: If ``step_size`` is non-positive, if it is set
together with ``digits``, or if it is not integer-valued for an
INT parameter.
"""
if step_size is None:
self._step_size = None
return
if self._digits is not None:
raise UserInputError(
f"Cannot set both `digits` and `step_size` on parameter "
f"{self._name}. `digits` is deprecated; use `step_size` only."
)
if step_size <= 0:
raise UserInputError(
f"`step_size` must be strictly positive for parameter "
f"{self._name}. Got: {step_size}."
)
if (
self._parameter_type is ParameterType.INT
and not float(step_size).is_integer()
):
raise UserInputError(
f"`step_size` must be integer-valued for INT parameter "
f"{self._name}. Got: {step_size}."
)
self._step_size = float(step_size)
def _validate_step_size_on_grid(
self, lower: TNumeric | None = None, upper: TNumeric | None = None
) -> None:
"""Validate that both bounds lie on the ``step_size`` grid.
The grid is anchored at ``lower``, so ``lower`` is always on it. This
additionally requires ``upper`` to be on the grid, i.e. that
``(upper - lower)`` is an integer multiple of ``step_size`` (within
``EPS``). This guarantees ``upper`` is itself a feasible value, so a
value near the upper bound snaps to ``upper`` rather than to a grid
point short of it.
Args:
lower: Lower bound to validate against. Defaults to ``self._lower``.
upper: Upper bound to validate against. Defaults to ``self._upper``.
These overrides let callers validate prospective bounds before
committing them.
Raises:
UserInputError: If ``upper`` does not lie on the grid.
"""
if self._step_size is None:
return
lower = self._lower if lower is None else lower
upper = self._upper if upper is None else upper
step_size = none_throws(self._step_size)
width = float(upper) - float(lower)
n = width / step_size
if abs(n - round(n)) * step_size > EPS:
raise UserInputError(
f"`step_size` must evenly divide the range of parameter "
f"{self._name}: (upper - lower) = {width} is not an integer "
f"multiple of step_size = {step_size}. Adjust the bounds or "
f"step_size so that both bounds lie on the grid."
)
def set_log_scale(self, log_scale: bool) -> RangeParameter:
self._log_scale = log_scale
return self
def set_logit_scale(self, logit_scale: bool) -> RangeParameter:
self._logit_scale = logit_scale
return self
def validate(
self, value: TParamValue, raises: bool = False, tol: float = EPS
) -> bool:
"""Returns True if input is a valid value for the parameter.
Checks that value is of the right type and within
the valid range for the parameter. Returns False if value is None.
Args:
value: Value being checked.
raises: If true, and validation fails, raises a UserInputError.
tol: Absolute tolerance for floating point comparisons.
Raises:
UserInputError: If validation fails and raises is True.
Returns:
True if valid, False otherwise.
"""
def return_false_or_raise(msg: str) -> bool:
if raises:
raise UserInputError(msg)
return False
if value is None:
msg = (
f"Value of parameter {self.name} is `None` but the parameter "
f"type is {self.parameter_type}."
)
return return_false_or_raise(msg)
if not self.is_valid_type(value):
msg = (
f"Value ({value}) of parameter {self.name} has type ({type(value)}), "
"which is not valid for a RangeParameter with parameter type "
f"{self.parameter_type}."
)
return return_false_or_raise(msg)
value = self.cast(value)
if value < self.lower - tol or value > self.upper + tol:
interval = (self.lower, self.upper)
msg = (
f"Value ({value}) of parameter {self.name} is not within the range of "
f"the parameter {interval}, even with a tolerance of {tol}."
)
return return_false_or_raise(msg)
return True
def validate_array(
self,
values: npt.NDArray,
tol: float = EPS,
) -> npt.NDArray:
"""Vectorized validation for RangeParameter.
Returns a boolean array indicating whether each value is valid.
NaN values are considered invalid, consistent with the validate() method.
Args:
values: A NumPy array of values to validate.
tol: Absolute tolerance for floating point comparisons.
Returns:
A boolean NumPy array with True for valid values.
"""
# Vectorized bounds check with tolerance
# NaN comparisons naturally return False, so NaN values are invalid
return (values >= self.lower - tol) & (values <= self.upper + tol)
def is_valid_type(self, value: TParamValue) -> bool:
"""Same as default except allows floats whose value is an int
for Int parameters.
"""
if not (isinstance(value, float) or isinstance(value, int)):
return False
# This might have issues with ints > 2^24
if self.parameter_type is ParameterType.INT:
return isinstance(value, int) or float(none_throws(value)).is_integer()
return True
def clone(self) -> RangeParameter:
return RangeParameter(
name=self._name,
parameter_type=self._parameter_type,
lower=self._lower,
upper=self._upper,
log_scale=self._log_scale,
logit_scale=self._logit_scale,
digits=self._digits,
step_size=self._step_size,
is_fidelity=self._is_fidelity,
target_value=self._target_value,
backfill_value=self._backfill_value,
default_value=self._default_value,
)
def cast(self, value: TParamValue) -> TNumeric:
value = super().cast(value=value)
if self.parameter_type is ParameterType.FLOAT and self._digits is not None:
return round(float(value), none_throws(self._digits))
# Skip snapping while the constructor is still casting the bounds
# themselves (before both ``self._lower`` and ``self._upper`` are set):
# the bounds anchor the grid and must not be snapped (``upper`` is only
# validated to be on the grid after both are assigned). ``_snap_to_grid``
# needs ``self._lower``; gating on ``self._upper`` too is what excludes
# the ``upper`` cast at construction.
if (
self._step_size is not None
and getattr(self, "_lower", None) is not None
and getattr(self, "_upper", None) is not None
):
value = self._snap_to_grid(value=float(value))
return assert_is_instance(value, TNumeric)
def _snap_to_grid(self, value: float) -> TNumeric:
"""Snap ``value`` to the nearest grid point.
The grid is ``{lower + k * step_size : k in Z}``. The nearest grid point
is found by rounding ``(value - lower) / step_size`` to the nearest
integer. The result is *not* clamped to ``[lower, upper]``: an
out-of-bounds input (e.g. historical observations recorded outside the
current bounds) snaps to the nearest grid point, which may itself lie
outside the bounds. This mirrors the non-``step_size`` ``cast()``, which
leaves out-of-bounds values untouched rather than silently moving them
into range -- range validity is enforced by ``validate()``, not by
``cast()``. For INT parameters the snapped value is integer-valued
(``step_size`` is validated to be an integer), so it is returned as an
``int``.
"""
step_size = none_throws(self._step_size)
lower = float(self._lower)
n = round((value - lower) / step_size)
snapped = lower + n * step_size
if self.parameter_type is ParameterType.INT:
return int(round(snapped))
return snapped
def __repr__(self) -> str:
ret_val = self._base_repr()
if self._digits is not None:
ret_val += f", digits={self._digits}"
if self._step_size is not None:
ret_val += f", step_size={self._step_size}"
return ret_val + ")"
@property
def available_flags(self) -> list[str]:
"""List of boolean attributes that can be set on this parameter."""
return super().available_flags + ["log_scale", "logit_scale"]
def _is_domain_compatible(self, other: Parameter) -> bool:
"""Check domain-specific compatibility for RangeParameter.
A RangeParameter is compatible with another RangeParameter (bounds may
differ) or with a FixedParameter (to support merging a fixed value
into a range).
"""
return isinstance(other, (RangeParameter, FixedParameter))
@property
def domain_repr(self) -> str:
"""Returns a string representation of the domain."""
return f"range={[self.lower, self.upper]}"
class ChoiceParameter(Parameter):
"""Parameter object that specifies a discrete set of values.
Args:
name: Name of the parameter.
parameter_type: Enum indicating the type of parameter
value (e.g. string, int).
values: List of allowed values for the parameter.
is_ordered: If False, the parameter is a categorical variable.
Defaults to False if parameter_type is STRING and ``values``
is longer than 2, else True.
is_task: Treat the parameter as a task parameter for modeling.
is_fidelity: Whether this parameter is a fidelity parameter.
target_value: Target value of this parameter if it's a fidelity or
task parameter.
sort_values: Whether to sort ``values`` before encoding.
Defaults to False if ``parameter_type`` is STRING, else
True. Note: Numeric ordered parameters (int or float with
``is_ordered=True``) must have ``sort_values=True``.
log_scale: Whether to sample choice values from log space. Only valid
for numerical (int or float) parameters with all positive values.
dependents: Optional mapping for parameters in hierarchical search
spaces; format is { value -> list of dependent parameter names }.
bypass_cardinality_check: Whether to bypass the cardinality check
that restricts the number of distinct values. This should only be
set to True when constructing parameters within the modeling layer.
backfill_value: For parameters added to experiments that have already run.
Used to backfill trials missing the parameter.
default_value: For parameters disabled in experiments that have already
run. Used as default value in modeling for future trials.
"""
def __init__(
self,
name: str,
parameter_type: ParameterType,
values: list[TParamValue],
is_ordered: bool | None = None,
is_task: bool = False,
is_fidelity: bool = False,
target_value: TParamValue = None,
sort_values: bool | None = None,
log_scale: bool | None = None,
dependents: dict[TParamValue, list[str]] | None = None,
bypass_cardinality_check: bool = False,
backfill_value: TParamValue = None,
default_value: TParamValue = None,
) -> None:
if (is_fidelity or is_task) and (target_value is None):
ptype = "fidelity" if is_fidelity else "task"
raise UserInputError(
f"`target_value` should not be None for the {ptype} parameter: "
"{}".format(name)
)
self._name = name
self._parameter_type = parameter_type
self._is_task = is_task
self._is_fidelity = is_fidelity
self._target_value: TParamValue = (
self.cast(target_value) if target_value is not None else None
)
self._backfill_value: TParamValue = (
self.cast(backfill_value) if backfill_value is not None else None
)
self._default_value: TParamValue = (
self.cast(default_value) if default_value is not None else None
)
# A choice parameter with only one value is a FixedParameter.
if not len(values) > 1:
raise UserInputError(f"{self._name}({values}): {FIXED_CHOICE_PARAM_ERROR}")
# Cap the number of possible values.
if not bypass_cardinality_check and len(values) > MAX_VALUES_CHOICE_PARAM:
raise UserInputError(
f"`ChoiceParameter` with more than {MAX_VALUES_CHOICE_PARAM} values "
"is not supported! Use a `RangeParameter` instead."
)
self._bypass_cardinality_check = bypass_cardinality_check
# Remove duplicate values.
# Using dict to deduplicate here since set doesn't preserve order but dict does.
dict_values = dict.fromkeys(values)
if len(values) != len(dict_values):
warn(
f"Duplicate values found for ChoiceParameter {name}. "
"Initializing the parameter with duplicate values removed. ",
AxParameterWarning,
stacklevel=2,
)
values = list(dict_values)
if is_ordered is False and len(values) == 2:
is_ordered = True
logger.debug(
f"Changing `is_ordered` to `True` for `ChoiceParameter` '{name}' since "
"there are only two possible values.",
AxParameterWarning,
stacklevel=3,
)
self._is_ordered: bool = (
is_ordered
if is_ordered is not None
else self._get_default_is_ordered_and_warn(num_choices=len(values))
)
# sort_values defaults to True if the parameter is not a string
self._sort_values: bool = (
sort_values
if sort_values is not None
else self._get_default_sort_values_and_warn()
)
# Validate that numeric ordered parameters have sort_values=True
if self._is_ordered and parameter_type.is_numeric and not self._sort_values:
raise UserInputError(
f"Numeric ordered choice parameters must have sort_values=True. "
f"Parameter {name} is ordered with type {parameter_type.name} but "
f"has sort_values=False."
)
if self.sort_values:
values = cast(list[TParamValue], sorted([none_throws(v) for v in values]))
self._values: list[TParamValue] = self._cast_values(values)