/
compounding.py
313 lines (265 loc) · 11.7 KB
/
compounding.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
# Copyright 2023 The PyGlove Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Compounding symbolic classes."""
import abc
import inspect
import sys
import types
from typing import Any, List, Optional, Tuple, Type, Union
from pyglove.core import object_utils
from pyglove.core.symbolic import schema_utils
from pyglove.core.symbolic.base import Symbolic
from pyglove.core.symbolic.object import Object
import pyglove.core.typing as pg_typing
class Compound(Object):
"""Base class for compound objects."""
@property
@abc.abstractmethod
def decomposed(self) -> Any:
"""Returns the decomposed which is the created object by the factory."""
def __init_subclass__(cls):
# Bypass other classes' `__init_subclass__` method when `Compound`
# is inherited as the first base class. This is to avoid side-effect
# from the user class to compound with.
Object.__init_subclass__(cls)
@object_utils.explicit_method_override
def __init__(self, *args, **kwargs):
# `explicit_init` allows the `__init__` of the other classes that sit after
# `Compound` to be bypassed.
Object.__init__(self, *args, explicit_init=True, **kwargs)
_COMPOUND_OWNED_ATTR_NAMES = frozenset(dir(Compound))
def compound_class(
factory_fn: types.FunctionType,
base_class: Optional[Type[Object]] = None,
args: Optional[
List[
Union[
Tuple[Tuple[str, pg_typing.KeySpec], pg_typing.ValueSpec, str],
Tuple[
Tuple[str, pg_typing.KeySpec], pg_typing.ValueSpec, str, Any
],
]
]
] = None, # pylint: disable=bad-continuation
*,
lazy_build: bool = True,
auto_doc: bool = True,
auto_typing: bool = True,
serialization_key: Optional[str] = None,
additional_keys: Optional[List[str]] = None,
add_to_registry: bool = False
) -> Type[Compound]:
"""Creates a compound class from a factory function.
Args:
factory_fn: A function that produces a compound object.
base_class: The base class of the compond class, which should be a
``pg.Object`` type. If None, it will be infererenced from the return
annotation of `factory_fn`. If the annotation is not present or
`auto_typing` is set to False, `base_class` must be present.
args: Symbolic args specification. `args` is a list of tuples, each
describes an argument from the input function. Each tuple is the format of
(<argumment-name>, <value-spec>, [description], [metadata-objects]).
`argument-name` - a `str` or `pg_typing.StrKey` object. When
`pg_typing.StrKey` is used, it describes the wildcard keyword argument.
`value-spec` - a `pg_typing.ValueSpec` object or equivalent, e.g.
primitive values which will be converted to ValueSpec implementation
according to its type and used as its default value. `description` - a
string to describe the agument. `metadata-objects` - an optional list of
any type, which can be used to generate code according to the schema.
There are notable rules in filling the `args`: 1) When `args` is None or
arguments from the function signature are missing from it, `schema.Field`
for these fields will be automatically generated and inserted into `args`.
That being said, every arguments in input function will have a
`schema.Field` counterpart in `Functor.schema.fields` sorted by the
declaration order of each argument in the function signature ( other than
the order in `args`). 2) Default argument values are specified along with
function definition as regular python functions, instead of being set at
`schema.Field` level. But validation rules can be set using `args` and
apply to argument values.
lazy_build: If True, `factory_fn` will be called upon first use. Otherwise,
it will be called at construction.
auto_doc: If True, the descriptions of argument fields will be inherited
from `factory_fn` docstr if they are not explicitly specified through
``args``.
auto_typing: If True, the value spec for constraining each argument will be
inferred from its annotation. Otherwise the value specs for all arguments
will be ``pg.typing.Any()``.
serialization_key: An optional string to be used as the serialization key
for the class during `sym_jsonify`. If None, `cls.__type_name__` will be
used. This is introduced for scenarios when we want to relocate a class,
before the downstream can recognize the new location, we need the class to
serialize it using previous key.
additional_keys: An optional list of strings as additional keys to
deserialize an object of the registered class. This can be useful when we
need to relocate or rename the registered class while being able to load
existing serialized JSON values.
add_to_registry: If True, the newly created functor class will be added to
the registry for deserialization.
Returns:
A callable that converts a factory function into a subclass of the base
class.
"""
if not inspect.isfunction(factory_fn):
raise TypeError('Decorator `compound` is only applicable to functions.')
schema = schema_utils.callable_schema(
factory_fn,
args=args,
returns=pg_typing.Object(base_class) if base_class else None,
auto_doc=auto_doc,
auto_typing=auto_typing,
)
# Inference the base_class from schema.
return_spec = schema.metadata.get('returns', None)
if isinstance(return_spec, pg_typing.Object):
base_class = return_spec.cls
else:
raise ValueError(
'Cannot inference the base class from return value annotation. '
'Please either add an annotation for the return value or provide the '
'value for the `base_class` argument.'
)
class _Compound(Compound, base_class):
"""The compound class bound to a factory function."""
# Disable auto register so we can use function module and name
# for registration later.
auto_register = False
# The compound class uses the function signature to decide its
# schema, thus we do not infer its schema from the class annotations.
auto_schema = False
def _on_bound(self):
# NOTE(daiyip): Do not call `super()._on_bound()` to avoid side effect.
# This is okay since all states are delegated to `self.decomposed`.
Compound._on_bound(self) # pylint: disable=protected-access
self._sym_decomposed = None
if not lazy_build:
# Trigger build.
_ = self.decomposed
@property
def decomposed(self):
if self._sym_decomposed is None:
# Build the compound object.
self._sym_decomposed = factory_fn(**self.sym_init_args)
# This allows the decomposed symbolic object to access the parent chain
# for value retrieval of inferred attributes.
if isinstance(self._sym_decomposed, Symbolic):
self._sym_decomposed.sym_setparent(self.sym_parent)
return self._sym_decomposed
def _on_parent_change(self, old_parent, new_parent):
"""Override to allow decomposed object to follow parent chain change."""
super()._on_parent_change(old_parent, new_parent)
if isinstance(self._sym_decomposed, Symbolic):
self._sym_decomposed.sym_setparent(new_parent)
def _sym_inferred(self, key: str, **kwargs) -> Any:
# Bypass the user base' `_sym_inferred` if it's overriden.
return Compound._sym_inferred(self, key, **kwargs)
def __getattribute__(self, name: str):
if (
name.startswith('_')
or name in _COMPOUND_OWNED_ATTR_NAMES
or name in self.sym_init_args
):
return Compound.__getattribute__(self, name)
# Redirect attribute to the compound object.
return getattr(self.decomposed, name)
cls = _Compound
cls.__name__ = factory_fn.__name__
cls.__qualname__ = factory_fn.__qualname__
cls.__module__ = factory_fn.__module__
cls.__doc__ = factory_fn.__doc__
# Enable automatic registration of subclass.
cls.auto_register = True
cls.apply_schema(schema)
# Supporting abstract class as compound base class.
# This is a feature supported for Python 3.10 and above.
if sys.version_info >= (3, 10):
# NOTE(daiyip): Override abstract methods as non-ops, so `cls` could
# have an abstract class as its base. We don't need to worry about the
# implementation of the abstract method, since it will be detoured to the
# decomposed object at runtime via `__getattribute__`.
for key in dir(cls):
attr = getattr(cls, key)
if getattr(attr, '__isabstractmethod__', False):
noop = lambda self, *args, **kwargs: None
if isinstance(attr, property):
noop = property(noop)
else:
assert inspect.isfunction(attr), (key, attr)
setattr(cls, key, noop)
abc.update_abstractmethods(cls)
if add_to_registry:
cls.register_for_deserialization(serialization_key, additional_keys)
return cls
def compound(
base_class: Optional[Type[Object]] = None,
args: Optional[
List[
Union[
Tuple[Tuple[str, pg_typing.KeySpec], pg_typing.ValueSpec, str],
Tuple[
Tuple[str, pg_typing.KeySpec], pg_typing.ValueSpec, str, Any
],
]
]
] = None, # pylint: disable=bad-continuation
**kwargs
):
"""Function decorator to create compound class.
Example::
@dataclasses.dataclass
class Foo:
x: int
y: int
def sum(self):
return self.x + self.y
@pg.compound
def foo_with_equal_x_y(v: int) -> Foo:
return Foo(v, v)
f = foo_with_equal_x_y(1)
# First of all, the objects of compound classes can be used as an in-place
# replacement for the objects of regular classes, as they are subclasses of
# the regular classes.
assert issubclass(foo_with_equal_x_y, Foo)
assert isinstance(f, Foo)
# We can access symbolic attributes of the compound object.
assert f.v == 1
# We can also access the public APIs of the decomposed object.
assert f.x == 1
assert f.y == 1
assert f.sum() == 2
# Or explicit access the decomposed object.
assert f.decomposed == Foo(1, 1)
# Moreover, symbolic power is fully unleashed to the compound class.
f.rebind(v=2)
assert f.x == 2
assert f.y == 2
assert f.sum() == 4
# Err with runtime type check: 2.5 is not an integer.
f.rebind(v=2.5)
Args:
base_class: The base class of the compond class, which should be a
``pg.Object`` type. If None, it will be infererenced from the return
annotation of `factory_fn`. If the annotation is not present or
`auto_typing` is set to False, `base_class` must be present.
args: Symbolic args specification. See :class:`pg.compound_class` for
details.
**kwargs: Keyword arguments. See :class:`pg.compound_class` for details.
Returns:
A symbolic compound class that subclasses `base_class`.
"""
if inspect.isfunction(base_class):
assert args is None
return compound_class(base_class, add_to_registry=True, **kwargs)
return lambda fn: compound_class( # pylint: disable=g-long-lambda # pytype: disable=wrong-arg-types
fn, base_class, args, add_to_registry=True, **kwargs
)