Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 6 additions & 47 deletions ax/storage/json_store/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
OptimizationConfig,
PreferenceOptimizationConfig,
)
from ax.core.outcome_constraint import OutcomeConstraint, ScalarizedOutcomeConstraint
from ax.core.outcome_constraint import OutcomeConstraint
from ax.core.parameter import (
ChoiceParameter,
DerivedParameter,
Expand Down Expand Up @@ -357,28 +357,10 @@ def scalarized_objective_to_dict(objective: ScalarizedObjective) -> dict[str, An

def outcome_constraint_to_dict(outcome_constraint: OutcomeConstraint) -> dict[str, Any]:
"""Convert Ax outcome constraint to a dictionary."""
metric_name = outcome_constraint.metric_names[0]
return {
"__type": outcome_constraint.__class__.__name__,
"metric": Metric(name=metric_name),
"op": outcome_constraint.op,
"bound": outcome_constraint.bound,
"relative": outcome_constraint.relative,
}


def scalarized_outcome_constraint_to_dict(
outcome_constraint: ScalarizedOutcomeConstraint,
) -> dict[str, Any]:
"""Convert Ax scalarized outcome constraint to a dictionary."""
metrics = [Metric(name=name) for name, _ in outcome_constraint.metric_weights]
return {
"__type": outcome_constraint.__class__.__name__,
"metrics": metrics,
"weights": outcome_constraint.weights,
"op": outcome_constraint.op,
"bound": outcome_constraint.bound,
"relative": outcome_constraint.relative,
"__type": "OutcomeConstraint",
"expression": outcome_constraint.expression,
"metric_name_to_signature": outcome_constraint.metric_name_to_signature,
}


Expand Down Expand Up @@ -790,21 +772,14 @@ def _build_opt_config_dict(
objective_dict = _build_objective_dict(
objective=opt_config.objective, experiment_metrics=experiment_metrics
)
constraint_dicts = [
_build_constraint_dict(constraint=c, experiment_metrics=experiment_metrics)
for c in opt_config.outcome_constraints
]
result: dict[str, Any] = {
"__type": opt_config.__class__.__name__,
"objective": objective_dict,
"outcome_constraints": constraint_dicts,
"outcome_constraints": opt_config.outcome_constraints,
"pruning_target_parameterization": opt_config.pruning_target_parameterization,
}
if isinstance(opt_config, MultiObjectiveOptimizationConfig):
result["objective_thresholds"] = [
_build_constraint_dict(constraint=t, experiment_metrics=experiment_metrics)
for t in opt_config.objective_thresholds
]
result["objective_thresholds"] = opt_config.objective_thresholds
if isinstance(opt_config, PreferenceOptimizationConfig):
result[PREFERENCE_PROFILE_NAME] = opt_config.preference_profile_name
result[EXPECT_RELATIVIZED_OUTCOMES] = opt_config.expect_relativized_outcomes
Expand Down Expand Up @@ -866,19 +841,3 @@ def _build_objective_dict(
"metric": metric,
"minimize": objective.minimize,
}


def _build_constraint_dict(
constraint: OutcomeConstraint,
experiment_metrics: dict[str, Metric],
) -> dict[str, Any]:
"""Build constraint dict with real metric objects from experiment."""
metric_name = constraint.metric_names[0]
metric = experiment_metrics.get(metric_name, Metric(name=metric_name))
return {
"__type": constraint.__class__.__name__,
"metric": metric,
"op": constraint.op,
"bound": constraint.bound,
"relative": constraint.relative,
}
3 changes: 1 addition & 2 deletions ax/storage/json_store/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,6 @@
range_parameter_to_dict,
runner_to_dict,
scalarized_objective_to_dict,
scalarized_outcome_constraint_to_dict,
search_space_to_dict,
surrogate_to_dict,
threshold_early_stopping_strategy_to_dict,
Expand Down Expand Up @@ -268,7 +267,7 @@
OptimizationConfig: optimization_config_to_dict,
OrEarlyStoppingStrategy: logical_early_stopping_strategy_to_dict,
OutcomeConstraint: outcome_constraint_to_dict,
ScalarizedOutcomeConstraint: scalarized_outcome_constraint_to_dict,
ScalarizedOutcomeConstraint: outcome_constraint_to_dict,
ParameterConstraint: parameter_constraint_to_dict,
pathlib.Path: pathlib_to_dict,
pathlib.PurePath: pathlib_to_dict,
Expand Down
95 changes: 95 additions & 0 deletions ax/storage/json_store/tests/test_json_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,11 @@
OptimizationConfig,
PreferenceOptimizationConfig,
)
from ax.core.outcome_constraint import OutcomeConstraint, ScalarizedOutcomeConstraint
from ax.core.parameter import ChoiceParameter, ParameterType
from ax.core.parameter_constraint import ParameterConstraint
from ax.core.runner import Runner
from ax.core.types import ComparisonOp
from ax.exceptions.core import AxStorageWarning, UnsupportedError
from ax.exceptions.storage import JSONDecodeError, JSONEncodeError
from ax.generation_strategy.center_generation_node import CenterGenerationNode
Expand Down Expand Up @@ -653,6 +655,99 @@ def test_EncodeDecode(self) -> None:
else:
raise e

def test_weighted_outcome_constraint_json_roundtrip(self) -> None:
"""All OutcomeConstraints (single, multi-metric, and legacy subclasses)
serialize uniformly via expression and round-trip standalone and inside
an Experiment, while legacy JSON formats still decode.
"""
expression = "2 * cost - latency <= 10"
cost = Metric(name="cost", signature_override="canonical_cost")
latency = Metric(name="latency")
expr_constraint = OutcomeConstraint(
expression=expression,
metric_name_to_signature={"cost": "canonical_cost", "latency": "latency"},
)
legacy_constraint = ScalarizedOutcomeConstraint(
metrics=[cost, latency],
weights=[0.3, 0.7],
op=ComparisonOp.GEQ,
bound=-5.0,
relative=False,
)

# Standalone round-trips serialize uniformly as OutcomeConstraint.
for constraint in (expr_constraint, legacy_constraint):
with self.subTest(expression=constraint.expression):
encoded = json.loads(json.dumps(object_to_json(constraint)))
self.assertEqual(encoded["__type"], "OutcomeConstraint")
self.assertIn("expression", encoded)
decoded = object_from_json(encoded)
self.assertIs(type(decoded), OutcomeConstraint)
self.assertEqual(decoded, constraint)
self.assertEqual(
dict(decoded.metric_weights), dict(constraint.metric_weights)
)
self.assertEqual(decoded.op, constraint.op)
self.assertEqual(decoded.bound, constraint.bound)
self.assertEqual(decoded.relative, constraint.relative)

# Experiment-level round-trip exercises `_build_opt_config_dict`.
experiment = get_experiment_with_batch_and_single_trial()
experiment.add_tracking_metric(cost)
experiment.add_tracking_metric(latency)
opt_config = none_throws(experiment.optimization_config)
opt_config.outcome_constraints = [expr_constraint, legacy_constraint]

encoded_exp = json.loads(json.dumps(object_to_json(experiment)))
decoded_exp = object_from_json(encoded_exp)
decoded_constraints = none_throws(
decoded_exp.optimization_config
).outcome_constraints
self.assertEqual(decoded_constraints, [expr_constraint, legacy_constraint])
for expected, actual in zip(
[expr_constraint, legacy_constraint],
decoded_constraints,
strict=True,
):
self.assertIs(type(actual), OutcomeConstraint)
self.assertEqual(dict(actual.metric_weights), dict(expected.metric_weights))
self.assertEqual(actual.op, expected.op)
self.assertEqual(actual.bound, expected.bound)
self.assertEqual(actual.relative, expected.relative)

# Legacy JSON payloads still decode cleanly.
legacy_payloads = [
{
"__type": "OutcomeConstraint",
"metric": object_to_json(cost),
"op": {"__type": "ComparisonOp", "name": "LEQ"},
"bound": 10.0,
"relative": False,
},
{
"__type": "ObjectiveThreshold",
"metric": object_to_json(latency),
"op": {"__type": "ComparisonOp", "name": "GEQ"},
"bound": 1.0,
"relative": False,
},
{
"__type": "ScalarizedOutcomeConstraint",
"metrics": [object_to_json(cost), object_to_json(latency)],
"weights": [2.0, -1.0],
"op": {"__type": "ComparisonOp", "name": "LEQ"},
"bound": 10.0,
"relative": False,
},
]
for payload in legacy_payloads:
with self.subTest(legacy_type=payload["__type"]):
decoded = object_from_json(payload)
self.assertIsInstance(decoded, OutcomeConstraint)
reencoded = object_to_json(decoded)
self.assertEqual(reencoded["__type"], "OutcomeConstraint")
self.assertEqual(object_from_json(reencoded), decoded)

def test_model_config_with_log10_roundtrip(self) -> None:
config = ModelConfig(
input_transform_classes=[Log10],
Expand Down
Loading