Skip to content

Commit 06e3352

Browse files
committed
deprecate (de)serialize_value_or_type
- add deprecation warning, remove functionality - replace all occurences with the corresponding new functions
1 parent a1b4d19 commit 06e3352

File tree

4 files changed

+24
-92
lines changed

4 files changed

+24
-92
lines changed

bayesflow/networks/point_inference_network.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
import keras
2-
from keras.saving import (
3-
deserialize_keras_object as deserialize,
4-
serialize_keras_object as serialize,
5-
register_keras_serializable as serializable,
6-
)
72

8-
from bayesflow.utils import model_kwargs, find_network, serialize_value_or_type, deserialize_value_or_type
3+
from bayesflow.utils import model_kwargs, find_network
4+
from bayesflow.utils.serialization import deserialize, serializable, serialize
95
from bayesflow.types import Shape, Tensor
106
from bayesflow.scores import ScoringRule, ParametricDistributionScore
117
from bayesflow.utils.decorators import allow_batch_size
@@ -30,10 +26,10 @@ def __init__(
3026
self.subnet = find_network(subnet, **kwargs.get("subnet_kwargs", {}))
3127

3228
self.config = {
29+
"subnet": serialize(subnet),
30+
"scores": serialize(scores),
3331
**kwargs,
3432
}
35-
self.config = serialize_value_or_type(self.config, "subnet", subnet)
36-
self.config["scores"] = serialize(self.scores)
3733

3834
def build(self, xz_shape: Shape, conditions_shape: Shape = None) -> None:
3935
"""Builds all network components based on shapes of conditions and targets.
@@ -119,7 +115,7 @@ def get_config(self):
119115
def from_config(cls, config):
120116
config = config.copy()
121117
config["scores"] = deserialize(config["scores"])
122-
config = deserialize_value_or_type(config, "subnet")
118+
config["subnet"] = deserialize(config["subnet"])
123119
return cls(**config)
124120

125121
def call(

bayesflow/scores/scoring_rule.py

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import math
22

33
import keras
4-
from keras.saving import register_keras_serializable as serializable
54

65
from bayesflow.types import Shape, Tensor
7-
from bayesflow.utils import find_network, serialize_value_or_type, deserialize_value_or_type
6+
from bayesflow.utils import find_network
7+
from bayesflow.utils.serialization import deserialize, serializable, serialize
88

99

1010
@serializable(package="bayesflow.scores")
@@ -51,23 +51,16 @@ def __init__(
5151
self.config = {"subnets_kwargs": self.subnets_kwargs}
5252

5353
def get_config(self):
54-
self.config["subnets"] = {
55-
key: serialize_value_or_type({}, "subnet", subnet) for key, subnet in self.subnets.items()
56-
}
57-
self.config["links"] = {key: serialize_value_or_type({}, "link", link) for key, link in self.links.items()}
54+
self.config["subnets"] = {key: serialize(subnet) for key, subnet in self.subnets.items()}
55+
self.config["links"] = {key: serialize(link) for key, link in self.links.items()}
5856

5957
return self.config
6058

6159
@classmethod
6260
def from_config(cls, config):
6361
config = config.copy()
64-
config["subnets"] = {
65-
key: deserialize_value_or_type(subnet_dict, "subnet")["subnet"]
66-
for key, subnet_dict in config["subnets"].items()
67-
}
68-
config["links"] = {
69-
key: deserialize_value_or_type(link_dict, "link")["link"] for key, link_dict in config["links"].items()
70-
}
62+
config["subnets"] = {key: deserialize(subnet_dict) for key, subnet_dict in config["subnets"].items()}
63+
config["links"] = {key: deserialize(link_dict) for key, link_dict in config["links"].items()}
7164

7265
return cls(**config)
7366

bayesflow/utils/serialization.py

Lines changed: 13 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import keras
66
import numpy as np
77
import sys
8+
from warnings import warn
89

910
# this import needs to be exactly like this to work with monkey patching
1011
from keras.saving import deserialize_keras_object
@@ -19,77 +20,21 @@
1920

2021

2122
def serialize_value_or_type(config, name, obj):
22-
"""Serialize an object that can be either a value or a type
23-
and add it to a copy of the supplied dictionary.
24-
25-
Parameters
26-
----------
27-
config : dict
28-
Dictionary to add the serialized object to. This function does not
29-
modify the dictionary in place, but returns a modified copy.
30-
name : str
31-
Name of the obj that should be stored. Required for later deserialization.
32-
obj : object or type
33-
The object to serialize. If `obj` is of type `type`, we use
34-
`keras.saving.get_registered_name` to obtain the registered type name.
35-
If it is not a type, we try to serialize it as a Keras object.
36-
37-
Returns
38-
-------
39-
updated_config : dict
40-
Updated dictionary with a new key `"_bayesflow_<name>_type"` or
41-
`"_bayesflow_<name>_val"`. The prefix is used to avoid name collisions,
42-
the suffix indicates how the stored value has to be deserialized.
43-
44-
Notes
45-
-----
46-
We allow strings or `type` parameters at several places to instantiate objects
47-
of a given type (e.g., `subnet` in `CouplingFlow`). As `type` objects cannot
48-
be serialized, we have to distinguish the two cases for serialization and
49-
deserialization. This function is a helper function to standardize and
50-
simplify this.
51-
"""
52-
updated_config = config.copy()
53-
if isinstance(obj, type):
54-
updated_config[f"{PREFIX}{name}_type"] = keras.saving.get_registered_name(obj)
55-
else:
56-
updated_config[f"{PREFIX}{name}_val"] = keras.saving.serialize_keras_object(obj)
57-
return updated_config
23+
"""This function is deprecated."""
24+
warn(
25+
"This method is deprecated. It was replaced by bayesflow.utils.serialization.serialize.",
26+
DeprecationWarning,
27+
stacklevel=2,
28+
)
5829

5930

6031
def deserialize_value_or_type(config, name):
61-
"""Deserialize an object that can be either a value or a type and add
62-
it to the supplied dictionary.
63-
64-
Parameters
65-
----------
66-
config : dict
67-
Dictionary containing the object to deserialize. If a type was
68-
serialized, it should contain the key `"_bayesflow_<name>_type"`.
69-
If an object was serialized, it should contain the key
70-
`"_bayesflow_<name>_val"`. In a copy of this dictionary,
71-
the item will be replaced with the key `name`.
72-
name : str
73-
Name of the object to deserialize.
74-
75-
Returns
76-
-------
77-
updated_config : dict
78-
Updated dictionary with a new key `name`, with a value that is either
79-
a type or an object.
80-
81-
See Also
82-
--------
83-
serialize_value_or_type
84-
"""
85-
updated_config = config.copy()
86-
if f"{PREFIX}{name}_type" in config:
87-
updated_config[name] = keras.saving.get_registered_object(config[f"{PREFIX}{name}_type"])
88-
del updated_config[f"{PREFIX}{name}_type"]
89-
elif f"{PREFIX}{name}_val" in config:
90-
updated_config[name] = keras.saving.deserialize_keras_object(config[f"{PREFIX}{name}_val"])
91-
del updated_config[f"{PREFIX}{name}_val"]
92-
return updated_config
32+
"""This function is deprecated."""
33+
warn(
34+
"This method is deprecated. It was replaced by bayesflow.utils.serialization.deserialize.",
35+
DeprecationWarning,
36+
stacklevel=2,
37+
)
9338

9439

9540
def deserialize(config: dict, custom_objects=None, safe_mode=True, **kwargs):

docsrc/source/development/serialization.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@ We mainly provide three convenience functions:
2121
- The {py:func}`~bayesflow.utils.serialization.serialize` function, which adds support for serializing classes.
2222
- Its counterpart {py:func}`~bayesflow.utils.serialization.deserialize`, adds support to deserialize classes.
2323

24-
_Note: The `(de)serialize_value_or_type` functions are made obsolete by the functions given above and will probably be deprecated soon._
25-
2624
## Usage
2725

2826
To use the adapted serialization functions, you have to use them in the `get_config` and `from_config` method. Please refer to existing classes in the library for usage examples.

0 commit comments

Comments
 (0)