You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "shunping (via GitHub)" <gi...@apache.org> on 2025/02/04 04:08:44 UTC
[PR] [Anomaly Detection] Add base classes and specifiable protocol [beam]
shunping opened a new pull request, #33845:
URL: https://github.com/apache/beam/pull/33845
This is the first part of the code push for anomaly detection transform.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #33845:
URL: https://github.com/apache/beam/pull/33845#issuecomment-2634506231
Run Python_Dataframes PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1946854536
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
Review Comment:
There is a concern about keeping everything in a global namespace from the design doc.
https://docs.google.com/document/d/1tE8lz9U_vjlNn2H7t-GRrs3vfhQ5UuCgWiHXCRHRPns/edit?disco=AAABaZ332MQ
I think the primary goal here is to avoid naming conflict, but I am open to any suggestion.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1947181893
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
Review Comment:
(a) Yes, I think the subspace is transparent to users. Users don't need to specify subspace when they use the decorator to augment their class.
(b) When there is a conflict, users can choose to specify a different `spec_type` when calling the decorator. I will make sure I have added that clearly in the docstring of the decorator.
On a second thought, I think it may be helpful to turn KNOWN_SPECIFIABLE into a module private variable, so users will know they are not supposed to manage it directly.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1946865448
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -30,67 +34,119 @@
from typing_extensions import Self
+__all__ = ["KNOWN_SPECIFIABLE", "Spec", "Specifiable", "specifiable"]
+
ACCEPTED_SPECIFIABLE_SUBSPACES = [
"EnsembleAnomalyDetector",
"AnomalyDetector",
"ThresholdFn",
"AggregationFn",
"*"
]
+
+#: A nested dictionary for efficient lookup of Specifiable subclasses.
+#: Structure: KNOWN_SPECIFIABLE[subspace][spec_type], where "subspace" is one of
+#: the accepted subspaces that the class belongs to and "spec_type" is the class
+#: name by default. Users can also specify a different value for "spec_type"
+#: when applying the `specifiable` decorator to an existing class.
KNOWN_SPECIFIABLE = {"*": {}}
SpecT = TypeVar('SpecT', bound='Specifiable')
-def get_subspace(cls, type=None):
- if type is None:
- subspace = "*"
- for c in cls.mro():
- if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
- subspace = c.__name__
- break
- return subspace
- else:
- for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
- if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
- return subspace
+def _class_to_subspace(cls: Type, default="*") -> str:
+ """
+ Search the class hierarchy to find the subspace: the closest ancestor class in
+ the class's method resolution order (MRO) whose name is found in the accepted
+ subspace list. This is usually called when registering a new Specifiable
+ class.
+ """
+ for c in cls.mro():
+ #
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ return c.__name__
+
+ if default is None:
Review Comment:
You are right. The code right now always use "*" as the default.
However, since subspace "*" is only used in testing, I am thinking about removing it from the ACCEPTED_SPECIFIABLE_SUBSPACES. In this case, we will only support making certain types of classes into specifiable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1941554505
##########
sdks/python/apache_beam/ml/anomaly/base_test.py:
##########
@@ -0,0 +1,210 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import logging
+import unittest
+
+from apache_beam.ml.anomaly.base import AggregationFn
+from apache_beam.ml.anomaly.base import AnomalyDetector
+from apache_beam.ml.anomaly.base import EnsembleAnomalyDetector
+from apache_beam.ml.anomaly.base import ThresholdFn
+from apache_beam.ml.anomaly.specifiable import Spec
+from apache_beam.ml.anomaly.specifiable import Specifiable
+from apache_beam.ml.anomaly.specifiable import specifiable
+
+
+class TestAnomalyDetector(unittest.TestCase):
+ @specifiable(on_demand_init=False)
+ class DummyThreshold(ThresholdFn):
+ def __init__(self, my_threshold_arg=None):
+ ...
+
+ def is_stateful(self):
+ return False
+
+ def threshold(self):
+ ...
+
+ def apply(self, x):
+ ...
+
+ @specifiable(on_demand_init=False)
+ class Dummy(AnomalyDetector):
+ def __init__(self, my_arg=None, **kwargs):
+ self._my_arg = my_arg
+ super().__init__(**kwargs)
+
+ def learn_one(self):
+ ...
+
+ def score_one(self):
+ ...
+
+ def __eq__(self, value) -> bool:
+ return isinstance(value, TestAnomalyDetector.Dummy) and \
+ self._my_arg == value._my_arg
+
+ def test_unknown_detector(self):
+ self.assertRaises(ValueError, Specifiable.from_spec, Spec(type="unknown"))
Review Comment:
I can't tell what this is testing - should this be in `specificable_test.py`?
##########
sdks/python/apache_beam/ml/anomaly/base.py:
##########
@@ -0,0 +1,114 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+"""Base classes for anomaly detection"""
+from __future__ import annotations
+
+import abc
+from dataclasses import dataclass
+from typing import Iterable
+from typing import List
+from typing import Optional
+
+import apache_beam as beam
+
+
+@dataclass(frozen=True)
+class AnomalyPrediction():
Review Comment:
Could you add docs for these dataclasses?
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
+
+
+def specifiable(
+ my_cls=None,
+ /,
+ *,
+ key=None,
+ error_if_exists=True,
+ on_demand_init=True,
+ just_in_time_init=True):
+
+ # register a specifiable, track init params for each instance, lazy init
+ def _wrapper(cls):
+ register(cls, key, error_if_exists)
+
+ original_init = cls.__init__
+ class_name = cls.__name__
+
+ def new_init(self, *args, **kwargs):
+ self._initialized = False
+ #self._nested_getattr = False
+
+ if kwargs.get("_run_init", False):
+ run_init = True
+ del kwargs['_run_init']
+ else:
+ run_init = False
+
+ if '_init_params' not in self.__dict__:
+ track_init_params(self, original_init, *args, **kwargs)
+
+ # If it is not a nested specifiable, we choose whether to skip original
+ # init call based on options. Otherwise, we always call original init
+ # for inner (parent/grandparent/etc) specifiable.
+ if (on_demand_init and not run_init) or \
+ (not on_demand_init and just_in_time_init):
+ return
+
+ logging.debug("call original %s.__init__ in new_init", class_name)
+ original_init(self, *args, **kwargs)
+ self._initialized = True
+
+ def run_init(self):
+ original_init(self, **self._init_params)
+
+ def new_getattr(self, name):
Review Comment:
Maybe I'm not understanding this well, but could we just do something a bit simpler like:
```
def new_getattr(self, name):
if not self._initialized:
original_init()
self._initialized = True
return orig_getattr(self, name)
```
if we keep track of the original getattr function in orig_getattr
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
Review Comment:
Why do we start with these registered? Would it be cleaner to just register them on import?
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
+
+
+def specifiable(
+ my_cls=None,
+ /,
+ *,
+ key=None,
+ error_if_exists=True,
+ on_demand_init=True,
+ just_in_time_init=True):
Review Comment:
I'm having a hard time following this - I think some of it is just indented python is hard to read, but I think it would be very helpful to have a walkthrough here of what this function is doing
I think I've mostly figured out how it is working, but it would help to have this background.
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
+
+
+def specifiable(
+ my_cls=None,
+ /,
+ *,
+ key=None,
+ error_if_exists=True,
+ on_demand_init=True,
+ just_in_time_init=True):
+
+ # register a specifiable, track init params for each instance, lazy init
+ def _wrapper(cls):
+ register(cls, key, error_if_exists)
+
+ original_init = cls.__init__
+ class_name = cls.__name__
+
+ def new_init(self, *args, **kwargs):
+ self._initialized = False
+ #self._nested_getattr = False
+
+ if kwargs.get("_run_init", False):
+ run_init = True
Review Comment:
Could we name this variable something else? I got confused between this and the function called `run_init` below
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
Review Comment:
Nit: can we call this `get_init_params` and return `params` here (and assign in the original function)? I think it would help readability
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1944121400
##########
sdks/python/apache_beam/ml/anomaly/base.py:
##########
@@ -0,0 +1,114 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+"""Base classes for anomaly detection"""
+from __future__ import annotations
+
+import abc
+from dataclasses import dataclass
+from typing import Iterable
+from typing import List
+from typing import Optional
+
+import apache_beam as beam
+
+
+@dataclass(frozen=True)
+class AnomalyPrediction():
Review Comment:
Done.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Anomaly Detection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #33845:
URL: https://github.com/apache/beam/pull/33845#issuecomment-2632774256
r: @damccorm
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1944120409
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
+
+
+def specifiable(
+ my_cls=None,
+ /,
+ *,
+ key=None,
+ error_if_exists=True,
+ on_demand_init=True,
+ just_in_time_init=True):
+
+ # register a specifiable, track init params for each instance, lazy init
+ def _wrapper(cls):
+ register(cls, key, error_if_exists)
+
+ original_init = cls.__init__
+ class_name = cls.__name__
+
+ def new_init(self, *args, **kwargs):
+ self._initialized = False
+ #self._nested_getattr = False
+
+ if kwargs.get("_run_init", False):
+ run_init = True
+ del kwargs['_run_init']
+ else:
+ run_init = False
+
+ if '_init_params' not in self.__dict__:
+ track_init_params(self, original_init, *args, **kwargs)
+
+ # If it is not a nested specifiable, we choose whether to skip original
+ # init call based on options. Otherwise, we always call original init
+ # for inner (parent/grandparent/etc) specifiable.
+ if (on_demand_init and not run_init) or \
+ (not on_demand_init and just_in_time_init):
+ return
+
+ logging.debug("call original %s.__init__ in new_init", class_name)
+ original_init(self, *args, **kwargs)
+ self._initialized = True
+
+ def run_init(self):
+ original_init(self, **self._init_params)
+
+ def new_getattr(self, name):
Review Comment:
The general idea is like this, but there are some edge cases we need to avoid. Otherwise, we will end up with an infinite loop. I refactor the code a bit to improve its readability. PTAL.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1947385648
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,334 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+"""
+A module that provides utilities to turn a class into a Specifiable subclass.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+__all__ = ["Spec", "Specifiable", "specifiable"]
+
+_FALLBACK_SUBSPACE = "*"
+
+_ACCEPTED_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ _FALLBACK_SUBSPACE,
+]
+
+#: A nested dictionary for efficient lookup of Specifiable subclasses.
+#: Structure: `_KNOWN_SPECIFIABLE[subspace][spec_type]`, where `subspace` is one
+#: of the accepted subspaces that the class belongs to and `spec_type` is the
+#: class name by default. Users can also specify a different value for
+#: `spec_type` when applying the `specifiable` decorator to an existing class.
+_KNOWN_SPECIFIABLE = {}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def _class_to_subspace(cls: Type) -> str:
+ """
+ Search the class hierarchy to find the subspace: the closest ancestor class in
+ the class's method resolution order (MRO) whose name is found in the accepted
+ subspace list. This is usually called when registering a new specifiable
+ class.
+ """
+ for c in cls.mro():
+ if c.__name__ in _ACCEPTED_SUBSPACES:
+ return c.__name__
+
+ return _FALLBACK_SUBSPACE
+
+
+def _spec_type_to_subspace(type: str) -> str:
+ """
+ Look for the subspace for a spec type. This is usually called to retrieve
+ the subspace of a registered specifiable class.
+ """
+ for subspace in _ACCEPTED_SUBSPACES:
+ if type in _KNOWN_SPECIFIABLE.get(subspace, {}):
+ return subspace
+
+ raise ValueError(f"subspace for {str} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ """
+ Dataclass for storing specifications of specifiable objects.
+ Objects can be initialized using the data in their corresponding spec.
+ """
+ #: A string indicating the concrete `Specifiable` class
+ type: str
+ #: A dictionary of keyword arguments for the `__init__` method of the class.
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ """Protocol that a specifiable class needs to implement.
+
+ Attributes:
+ spec_type: The value of the `type` field in the object's spec for this
+ class.
+ init_kwargs: The raw keyword arguments passed to `__init__` method during
+ object initialization.
+ """
+ spec_type: ClassVar[str]
+ init_kwargs: dict[str, Any]
+
+ # a boolean to tell whether the original `__init__` method is called
+ _initialized: bool
+ # a boolean used by new_getattr to tell whether it is in the `__init__` method
+ # call
+ _in_init: bool
+
+ @staticmethod
+ def _from_spec_helper(v, _run_init):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v, _run_init)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e, _run_init) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec, _run_init: bool = True) -> Self:
+ """Generate a `Specifiable` subclass object based on a spec."""
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = _spec_type_to_subspace(spec.type)
+ subclass: Type[Self] = _KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ kwargs = {
+ k: Specifiable._from_spec_helper(v, _run_init)
+ for k,
+ v in spec.config.items()
+ }
+
+ if _run_init:
+ kwargs["_run_init"] = True
+ return subclass(**kwargs)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ """
+ Generate a spec from a `Specifiable` subclass object.
+ """
+ if getattr(type(self), 'spec_type', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self.init_kwargs.items()}
+
+ return Spec(type=self.__class__.spec_type, config=args)
+
+
+# Register a `Specifiable` subclass in `KNOWN_SPECIFIABLE`
+def _register(cls, spec_type=None, error_if_exists=True) -> None:
+ if spec_type is None:
+ # By default, spec type is the class name. Users can override this with
+ # other unique identifier.
+ spec_type = cls.__name__
+
+ subspace = _class_to_subspace(cls)
+ if subspace in _KNOWN_SPECIFIABLE:
+ if spec_type in _KNOWN_SPECIFIABLE[subspace] and error_if_exists:
+ raise ValueError(
+ f"{spec_type} is already registered for "
+ f"specifiable class {_KNOWN_SPECIFIABLE[subspace]}. "
+ "Please specify a different spec_type by "
+ "@specifiable(spec_type=...) or ignore the error by "
+ "@specifiable(error_if_exists=False).")
+ else:
+ _KNOWN_SPECIFIABLE[subspace] = {}
+ _KNOWN_SPECIFIABLE[subspace][spec_type] = cls
Review Comment:
Good idea. I've made the changes in the new commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1946865448
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -30,67 +34,119 @@
from typing_extensions import Self
+__all__ = ["KNOWN_SPECIFIABLE", "Spec", "Specifiable", "specifiable"]
+
ACCEPTED_SPECIFIABLE_SUBSPACES = [
"EnsembleAnomalyDetector",
"AnomalyDetector",
"ThresholdFn",
"AggregationFn",
"*"
]
+
+#: A nested dictionary for efficient lookup of Specifiable subclasses.
+#: Structure: KNOWN_SPECIFIABLE[subspace][spec_type], where "subspace" is one of
+#: the accepted subspaces that the class belongs to and "spec_type" is the class
+#: name by default. Users can also specify a different value for "spec_type"
+#: when applying the `specifiable` decorator to an existing class.
KNOWN_SPECIFIABLE = {"*": {}}
SpecT = TypeVar('SpecT', bound='Specifiable')
-def get_subspace(cls, type=None):
- if type is None:
- subspace = "*"
- for c in cls.mro():
- if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
- subspace = c.__name__
- break
- return subspace
- else:
- for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
- if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
- return subspace
+def _class_to_subspace(cls: Type, default="*") -> str:
+ """
+ Search the class hierarchy to find the subspace: the closest ancestor class in
+ the class's method resolution order (MRO) whose name is found in the accepted
+ subspace list. This is usually called when registering a new Specifiable
+ class.
+ """
+ for c in cls.mro():
+ #
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ return c.__name__
+
+ if default is None:
Review Comment:
You are right. The code right now always uses "*" as the default.
However, since subspace "*" is only used in testing, I am thinking about removing it from the ACCEPTED_SPECIFIABLE_SUBSPACES. In this case, we will only support making certain types of classes into specifiable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1947152342
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -30,67 +34,119 @@
from typing_extensions import Self
+__all__ = ["KNOWN_SPECIFIABLE", "Spec", "Specifiable", "specifiable"]
+
ACCEPTED_SPECIFIABLE_SUBSPACES = [
"EnsembleAnomalyDetector",
"AnomalyDetector",
"ThresholdFn",
"AggregationFn",
"*"
]
+
+#: A nested dictionary for efficient lookup of Specifiable subclasses.
+#: Structure: KNOWN_SPECIFIABLE[subspace][spec_type], where "subspace" is one of
+#: the accepted subspaces that the class belongs to and "spec_type" is the class
+#: name by default. Users can also specify a different value for "spec_type"
+#: when applying the `specifiable` decorator to an existing class.
KNOWN_SPECIFIABLE = {"*": {}}
SpecT = TypeVar('SpecT', bound='Specifiable')
-def get_subspace(cls, type=None):
- if type is None:
- subspace = "*"
- for c in cls.mro():
- if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
- subspace = c.__name__
- break
- return subspace
- else:
- for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
- if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
- return subspace
+def _class_to_subspace(cls: Type, default="*") -> str:
+ """
+ Search the class hierarchy to find the subspace: the closest ancestor class in
+ the class's method resolution order (MRO) whose name is found in the accepted
+ subspace list. This is usually called when registering a new Specifiable
+ class.
+ """
+ for c in cls.mro():
+ #
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ return c.__name__
+
+ if default is None:
Review Comment:
I think having the default makes sense - it means that a user doesn't need to worry about this in most cases, which seems right if this only exists for conflict resolution.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Anomaly Detection] Add base classes and specifiable protocol [beam]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #33845:
URL: https://github.com/apache/beam/pull/33845#issuecomment-2632775418
Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment `assign set of reviewers`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1947153137
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
Review Comment:
Ok, I can live with this I think, lets just make sure:
a) the user has an easy path to create this object without specifying a subspace (e.g. the mainline case where conflicts are not really an issue)
b) it is really clear what a user should do if there's a conflict
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #33845:
URL: https://github.com/apache/beam/pull/33845#issuecomment-2632969931
## [Codecov](https://app.codecov.io/gh/apache/beam/pull/33845?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
Attention: Patch coverage is `91.16022%` with `16 lines` in your changes missing coverage. Please review.
> Project coverage is 59.12%. Comparing base [(`5aae10d`)](https://app.codecov.io/gh/apache/beam/commit/5aae10db7af862520a192bc160b6f1f23d4f9c20?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) to head [(`bc6fa8f`)](https://app.codecov.io/gh/apache/beam/commit/bc6fa8ff5cf81b68fb6fed455d47eb082a8f8798?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
> Report is 1 commits behind head on master.
| [Files with missing lines](https://app.codecov.io/gh/apache/beam/pull/33845?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [sdks/python/apache\_beam/ml/anomaly/base.py](https://app.codecov.io/gh/apache/beam/pull/33845?src=pr&el=tree&filepath=sdks%2Fpython%2Fapache_beam%2Fml%2Fanomaly%2Fbase.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vbWwvYW5vbWFseS9iYXNlLnB5) | 83.60% | [10 Missing :warning: ](https://app.codecov.io/gh/apache/beam/pull/33845?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [sdks/python/apache\_beam/ml/anomaly/specifiable.py](https://app.codecov.io/gh/apache/beam/pull/33845?src=pr&el=tree&filepath=sdks%2Fpython%2Fapache_beam%2Fml%2Fanomaly%2Fspecifiable.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vbWwvYW5vbWFseS9zcGVjaWZpYWJsZS5weQ==) | 95.00% | [6 Missing :warning: ](https://app.codecov.io/gh/apache/beam/pull/33845?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #33845 +/- ##
============================================
+ Coverage 59.08% 59.12% +0.03%
Complexity 3237 3237
============================================
Files 1156 1158 +2
Lines 176907 177113 +206
Branches 3391 3391
============================================
+ Hits 104532 104715 +183
- Misses 69008 69031 +23
Partials 3367 3367
```
| [Flag](https://app.codecov.io/gh/apache/beam/pull/33845/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [python](https://app.codecov.io/gh/apache/beam/pull/33845/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `81.25% <91.16%> (+0.02%)` | :arrow_up: |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/beam/pull/33845?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1947182434
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -30,67 +34,119 @@
from typing_extensions import Self
+__all__ = ["KNOWN_SPECIFIABLE", "Spec", "Specifiable", "specifiable"]
+
ACCEPTED_SPECIFIABLE_SUBSPACES = [
"EnsembleAnomalyDetector",
"AnomalyDetector",
"ThresholdFn",
"AggregationFn",
"*"
]
+
+#: A nested dictionary for efficient lookup of Specifiable subclasses.
+#: Structure: KNOWN_SPECIFIABLE[subspace][spec_type], where "subspace" is one of
+#: the accepted subspaces that the class belongs to and "spec_type" is the class
+#: name by default. Users can also specify a different value for "spec_type"
+#: when applying the `specifiable` decorator to an existing class.
KNOWN_SPECIFIABLE = {"*": {}}
SpecT = TypeVar('SpecT', bound='Specifiable')
-def get_subspace(cls, type=None):
- if type is None:
- subspace = "*"
- for c in cls.mro():
- if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
- subspace = c.__name__
- break
- return subspace
- else:
- for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
- if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
- return subspace
+def _class_to_subspace(cls: Type, default="*") -> str:
+ """
+ Search the class hierarchy to find the subspace: the closest ancestor class in
+ the class's method resolution order (MRO) whose name is found in the accepted
+ subspace list. This is usually called when registering a new Specifiable
+ class.
+ """
+ for c in cls.mro():
+ #
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ return c.__name__
+
+ if default is None:
Review Comment:
I just got it removed but I am happy to put it back then.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #33845:
URL: https://github.com/apache/beam/pull/33845#issuecomment-2641967868
@damccorm, I've added docstrings and refactored some code for readability. PTAL. Thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1944123803
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
Review Comment:
These are the accepted subspaces for the known specifiable, but not the actual specifiable classes. The purpose is to avoid using a global space for every specifiable classes.
I think they should be predefined before the true registration takes place. WDYT?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1946763160
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -30,67 +34,119 @@
from typing_extensions import Self
+__all__ = ["KNOWN_SPECIFIABLE", "Spec", "Specifiable", "specifiable"]
+
ACCEPTED_SPECIFIABLE_SUBSPACES = [
"EnsembleAnomalyDetector",
"AnomalyDetector",
"ThresholdFn",
"AggregationFn",
"*"
]
+
+#: A nested dictionary for efficient lookup of Specifiable subclasses.
+#: Structure: KNOWN_SPECIFIABLE[subspace][spec_type], where "subspace" is one of
+#: the accepted subspaces that the class belongs to and "spec_type" is the class
+#: name by default. Users can also specify a different value for "spec_type"
+#: when applying the `specifiable` decorator to an existing class.
KNOWN_SPECIFIABLE = {"*": {}}
SpecT = TypeVar('SpecT', bound='Specifiable')
-def get_subspace(cls, type=None):
- if type is None:
- subspace = "*"
- for c in cls.mro():
- if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
- subspace = c.__name__
- break
- return subspace
- else:
- for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
- if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
- return subspace
+def _class_to_subspace(cls: Type, default="*") -> str:
+ """
+ Search the class hierarchy to find the subspace: the closest ancestor class in
+ the class's method resolution order (MRO) whose name is found in the accepted
+ subspace list. This is usually called when registering a new Specifiable
+ class.
+ """
+ for c in cls.mro():
+ #
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ return c.__name__
+
+ if default is None:
Review Comment:
Aren't we setting a default? Will this ever be None?
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
Review Comment:
> The purpose is to avoid using a global space for every specifiable classes.
I think maybe this is the piece I'm missing - why is this helpful? Aka, why is it helpful to have a nested `KNOWN_SPECIFIABLE[subspace][spec_type]` dict instead of just `KNOWN_SPECIFIABLE[spec_type]`. I can't really think of scenarios this enables/makes easier
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1947242444
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,334 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+"""
+A module that provides utilities to turn a class into a Specifiable subclass.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+__all__ = ["Spec", "Specifiable", "specifiable"]
+
+_FALLBACK_SUBSPACE = "*"
+
+_ACCEPTED_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ _FALLBACK_SUBSPACE,
+]
+
+#: A nested dictionary for efficient lookup of Specifiable subclasses.
+#: Structure: `_KNOWN_SPECIFIABLE[subspace][spec_type]`, where `subspace` is one
+#: of the accepted subspaces that the class belongs to and `spec_type` is the
+#: class name by default. Users can also specify a different value for
+#: `spec_type` when applying the `specifiable` decorator to an existing class.
+_KNOWN_SPECIFIABLE = {}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def _class_to_subspace(cls: Type) -> str:
+ """
+ Search the class hierarchy to find the subspace: the closest ancestor class in
+ the class's method resolution order (MRO) whose name is found in the accepted
+ subspace list. This is usually called when registering a new specifiable
+ class.
+ """
+ for c in cls.mro():
+ if c.__name__ in _ACCEPTED_SUBSPACES:
+ return c.__name__
+
+ return _FALLBACK_SUBSPACE
+
+
+def _spec_type_to_subspace(type: str) -> str:
+ """
+ Look for the subspace for a spec type. This is usually called to retrieve
+ the subspace of a registered specifiable class.
+ """
+ for subspace in _ACCEPTED_SUBSPACES:
+ if type in _KNOWN_SPECIFIABLE.get(subspace, {}):
+ return subspace
+
+ raise ValueError(f"subspace for {str} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ """
+ Dataclass for storing specifications of specifiable objects.
+ Objects can be initialized using the data in their corresponding spec.
+ """
+ #: A string indicating the concrete `Specifiable` class
+ type: str
+ #: A dictionary of keyword arguments for the `__init__` method of the class.
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ """Protocol that a specifiable class needs to implement.
+
+ Attributes:
+ spec_type: The value of the `type` field in the object's spec for this
+ class.
+ init_kwargs: The raw keyword arguments passed to `__init__` method during
+ object initialization.
+ """
+ spec_type: ClassVar[str]
+ init_kwargs: dict[str, Any]
+
+ # a boolean to tell whether the original `__init__` method is called
+ _initialized: bool
+ # a boolean used by new_getattr to tell whether it is in the `__init__` method
+ # call
+ _in_init: bool
+
+ @staticmethod
+ def _from_spec_helper(v, _run_init):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v, _run_init)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e, _run_init) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec, _run_init: bool = True) -> Self:
+ """Generate a `Specifiable` subclass object based on a spec."""
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = _spec_type_to_subspace(spec.type)
+ subclass: Type[Self] = _KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ kwargs = {
+ k: Specifiable._from_spec_helper(v, _run_init)
+ for k,
+ v in spec.config.items()
+ }
+
+ if _run_init:
+ kwargs["_run_init"] = True
+ return subclass(**kwargs)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ """
+ Generate a spec from a `Specifiable` subclass object.
+ """
+ if getattr(type(self), 'spec_type', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self.init_kwargs.items()}
+
+ return Spec(type=self.__class__.spec_type, config=args)
+
+
+# Register a `Specifiable` subclass in `KNOWN_SPECIFIABLE`
+def _register(cls, spec_type=None, error_if_exists=True) -> None:
+ if spec_type is None:
+ # By default, spec type is the class name. Users can override this with
+ # other unique identifier.
+ spec_type = cls.__name__
+
+ subspace = _class_to_subspace(cls)
+ if subspace in _KNOWN_SPECIFIABLE:
+ if spec_type in _KNOWN_SPECIFIABLE[subspace] and error_if_exists:
+ raise ValueError(
+ f"{spec_type} is already registered for "
+ f"specifiable class {_KNOWN_SPECIFIABLE[subspace]}. "
+ "Please specify a different spec_type by "
+ "@specifiable(spec_type=...) or ignore the error by "
+ "@specifiable(error_if_exists=False).")
+ else:
+ _KNOWN_SPECIFIABLE[subspace] = {}
+ _KNOWN_SPECIFIABLE[subspace][spec_type] = cls
Review Comment:
2 thoughts looking at this:
1) I think _KNOWN_SPECIFIABLE would be cleaner as a `collections.defaultdict(dict)`, then we could get rid of this outer if/else and clean up some other places.
2) I don't think `error_if_exists` adds much value since you can just avoid this entirely by using a different spec_type. You're probably just introducing opportunity for bad behavior.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm merged PR #33845:
URL: https://github.com/apache/beam/pull/33845
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1947227139
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -30,67 +34,119 @@
from typing_extensions import Self
+__all__ = ["KNOWN_SPECIFIABLE", "Spec", "Specifiable", "specifiable"]
+
ACCEPTED_SPECIFIABLE_SUBSPACES = [
"EnsembleAnomalyDetector",
"AnomalyDetector",
"ThresholdFn",
"AggregationFn",
"*"
]
+
+#: A nested dictionary for efficient lookup of Specifiable subclasses.
+#: Structure: KNOWN_SPECIFIABLE[subspace][spec_type], where "subspace" is one of
+#: the accepted subspaces that the class belongs to and "spec_type" is the class
+#: name by default. Users can also specify a different value for "spec_type"
+#: when applying the `specifiable` decorator to an existing class.
KNOWN_SPECIFIABLE = {"*": {}}
SpecT = TypeVar('SpecT', bound='Specifiable')
-def get_subspace(cls, type=None):
- if type is None:
- subspace = "*"
- for c in cls.mro():
- if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
- subspace = c.__name__
- break
- return subspace
- else:
- for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
- if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
- return subspace
+def _class_to_subspace(cls: Type, default="*") -> str:
+ """
+ Search the class hierarchy to find the subspace: the closest ancestor class in
+ the class's method resolution order (MRO) whose name is found in the accepted
+ subspace list. This is usually called when registering a new Specifiable
+ class.
+ """
+ for c in cls.mro():
+ #
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ return c.__name__
+
+ if default is None:
Review Comment:
Done.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1943660539
##########
sdks/python/apache_beam/ml/anomaly/base_test.py:
##########
@@ -0,0 +1,210 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import logging
+import unittest
+
+from apache_beam.ml.anomaly.base import AggregationFn
+from apache_beam.ml.anomaly.base import AnomalyDetector
+from apache_beam.ml.anomaly.base import EnsembleAnomalyDetector
+from apache_beam.ml.anomaly.base import ThresholdFn
+from apache_beam.ml.anomaly.specifiable import Spec
+from apache_beam.ml.anomaly.specifiable import Specifiable
+from apache_beam.ml.anomaly.specifiable import specifiable
+
+
+class TestAnomalyDetector(unittest.TestCase):
+ @specifiable(on_demand_init=False)
+ class DummyThreshold(ThresholdFn):
+ def __init__(self, my_threshold_arg=None):
+ ...
+
+ def is_stateful(self):
+ return False
+
+ def threshold(self):
+ ...
+
+ def apply(self, x):
+ ...
+
+ @specifiable(on_demand_init=False)
+ class Dummy(AnomalyDetector):
+ def __init__(self, my_arg=None, **kwargs):
+ self._my_arg = my_arg
+ super().__init__(**kwargs)
+
+ def learn_one(self):
+ ...
+
+ def score_one(self):
+ ...
+
+ def __eq__(self, value) -> bool:
+ return isinstance(value, TestAnomalyDetector.Dummy) and \
+ self._my_arg == value._my_arg
+
+ def test_unknown_detector(self):
+ self.assertRaises(ValueError, Specifiable.from_spec, Spec(type="unknown"))
Review Comment:
Agree.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1944120409
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
+
+
+def specifiable(
+ my_cls=None,
+ /,
+ *,
+ key=None,
+ error_if_exists=True,
+ on_demand_init=True,
+ just_in_time_init=True):
+
+ # register a specifiable, track init params for each instance, lazy init
+ def _wrapper(cls):
+ register(cls, key, error_if_exists)
+
+ original_init = cls.__init__
+ class_name = cls.__name__
+
+ def new_init(self, *args, **kwargs):
+ self._initialized = False
+ #self._nested_getattr = False
+
+ if kwargs.get("_run_init", False):
+ run_init = True
+ del kwargs['_run_init']
+ else:
+ run_init = False
+
+ if '_init_params' not in self.__dict__:
+ track_init_params(self, original_init, *args, **kwargs)
+
+ # If it is not a nested specifiable, we choose whether to skip original
+ # init call based on options. Otherwise, we always call original init
+ # for inner (parent/grandparent/etc) specifiable.
+ if (on_demand_init and not run_init) or \
+ (not on_demand_init and just_in_time_init):
+ return
+
+ logging.debug("call original %s.__init__ in new_init", class_name)
+ original_init(self, *args, **kwargs)
+ self._initialized = True
+
+ def run_init(self):
+ original_init(self, **self._init_params)
+
+ def new_getattr(self, name):
Review Comment:
The general idea is like this, but there are some edge cases we need to avoid. Otherwise, we will end up with an infinite loop.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1944120983
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
+
+
+def specifiable(
+ my_cls=None,
+ /,
+ *,
+ key=None,
+ error_if_exists=True,
+ on_demand_init=True,
+ just_in_time_init=True):
Review Comment:
I added some more comments. PTAL.
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
Review Comment:
Sure.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1944120409
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
+
+
+def specifiable(
+ my_cls=None,
+ /,
+ *,
+ key=None,
+ error_if_exists=True,
+ on_demand_init=True,
+ just_in_time_init=True):
+
+ # register a specifiable, track init params for each instance, lazy init
+ def _wrapper(cls):
+ register(cls, key, error_if_exists)
+
+ original_init = cls.__init__
+ class_name = cls.__name__
+
+ def new_init(self, *args, **kwargs):
+ self._initialized = False
+ #self._nested_getattr = False
+
+ if kwargs.get("_run_init", False):
+ run_init = True
+ del kwargs['_run_init']
+ else:
+ run_init = False
+
+ if '_init_params' not in self.__dict__:
+ track_init_params(self, original_init, *args, **kwargs)
+
+ # If it is not a nested specifiable, we choose whether to skip original
+ # init call based on options. Otherwise, we always call original init
+ # for inner (parent/grandparent/etc) specifiable.
+ if (on_demand_init and not run_init) or \
+ (not on_demand_init and just_in_time_init):
+ return
+
+ logging.debug("call original %s.__init__ in new_init", class_name)
+ original_init(self, *args, **kwargs)
+ self._initialized = True
+
+ def run_init(self):
+ original_init(self, **self._init_params)
+
+ def new_getattr(self, name):
Review Comment:
The idea is like this, but there are some edge cases we need to avoid. Otherwise, we will end up with an infinite loop. Please check out the newly-updated comments in the latest code.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add base classes and specifiable protocol [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33845:
URL: https://github.com/apache/beam/pull/33845#discussion_r1944120749
##########
sdks/python/apache_beam/ml/anomaly/specifiable.py:
##########
@@ -0,0 +1,223 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+from __future__ import annotations
+
+import dataclasses
+import inspect
+import logging
+from typing import Any
+from typing import ClassVar
+from typing import List
+from typing import Protocol
+from typing import Type
+from typing import TypeVar
+from typing import runtime_checkable
+
+from typing_extensions import Self
+
+ACCEPTED_SPECIFIABLE_SUBSPACES = [
+ "EnsembleAnomalyDetector",
+ "AnomalyDetector",
+ "ThresholdFn",
+ "AggregationFn",
+ "*"
+]
+KNOWN_SPECIFIABLE = {"*": {}}
+
+SpecT = TypeVar('SpecT', bound='Specifiable')
+
+
+def get_subspace(cls, type=None):
+ if type is None:
+ subspace = "*"
+ for c in cls.mro():
+ if c.__name__ in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ subspace = c.__name__
+ break
+ return subspace
+ else:
+ for subspace in ACCEPTED_SPECIFIABLE_SUBSPACES:
+ if subspace in KNOWN_SPECIFIABLE and type in KNOWN_SPECIFIABLE[subspace]:
+ return subspace
+ raise ValueError(f"subspace for {cls.__name__} not found.")
+
+
+@dataclasses.dataclass(frozen=True)
+class Spec():
+ type: str
+ config: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+
+@runtime_checkable
+class Specifiable(Protocol):
+ _key: ClassVar[str]
+ _init_params: dict[str, Any]
+
+ @staticmethod
+ def _from_spec_helper(v):
+ if isinstance(v, Spec):
+ return Specifiable.from_spec(v)
+
+ if isinstance(v, List):
+ return [Specifiable._from_spec_helper(e) for e in v]
+
+ return v
+
+ @classmethod
+ def from_spec(cls, spec: Spec) -> Self:
+ if spec.type is None:
+ raise ValueError(f"Spec type not found in {spec}")
+
+ subspace = get_subspace(cls, spec.type)
+ subclass: Type[Self] = KNOWN_SPECIFIABLE[subspace].get(spec.type, None)
+ if subclass is None:
+ raise ValueError(f"Unknown spec type '{spec.type}' in {spec}")
+
+ args = {k: Specifiable._from_spec_helper(v) for k, v in spec.config.items()}
+
+ return subclass(**args)
+
+ @staticmethod
+ def _to_spec_helper(v):
+ if isinstance(v, Specifiable):
+ return v.to_spec()
+
+ if isinstance(v, List):
+ return [Specifiable._to_spec_helper(e) for e in v]
+
+ return v
+
+ def to_spec(self) -> Spec:
+ if getattr(type(self), '_key', None) is None:
+ raise ValueError(
+ f"'{type(self).__name__}' not registered as Specifiable. "
+ f"Decorate ({type(self).__name__}) with @specifiable")
+
+ args = {k: self._to_spec_helper(v) for k, v in self._init_params.items()}
+
+ return Spec(type=self.__class__._key, config=args)
+
+
+def register(cls, key, error_if_exists) -> None:
+ if key is None:
+ key = cls.__name__
+
+ subspace = get_subspace(cls)
+ if subspace in KNOWN_SPECIFIABLE and key in KNOWN_SPECIFIABLE[
+ subspace] and error_if_exists:
+ raise ValueError(f"{key} is already registered for specifiable")
+
+ if subspace not in KNOWN_SPECIFIABLE:
+ KNOWN_SPECIFIABLE[subspace] = {}
+ KNOWN_SPECIFIABLE[subspace][key] = cls
+
+ cls._key = key
+
+
+def track_init_params(inst, init_method, *args, **kwargs):
+ params = dict(
+ zip(inspect.signature(init_method).parameters.keys(), (None, ) + args))
+ del params['self']
+ params.update(**kwargs)
+ inst._init_params = params
+
+
+def specifiable(
+ my_cls=None,
+ /,
+ *,
+ key=None,
+ error_if_exists=True,
+ on_demand_init=True,
+ just_in_time_init=True):
+
+ # register a specifiable, track init params for each instance, lazy init
+ def _wrapper(cls):
+ register(cls, key, error_if_exists)
+
+ original_init = cls.__init__
+ class_name = cls.__name__
+
+ def new_init(self, *args, **kwargs):
+ self._initialized = False
+ #self._nested_getattr = False
+
+ if kwargs.get("_run_init", False):
+ run_init = True
Review Comment:
Code is refactored.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org