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.") + + [email protected](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.") + + [email protected](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.") + + [email protected](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.") + + [email protected](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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
