From 2d28a5e5dd312d6df299f5f2bac9437fab24961e Mon Sep 17 00:00:00 2001 From: Luis Ferraz Date: Mon, 1 May 2023 02:29:18 +0200 Subject: [PATCH] add property callback example --- examples/defining_cmps.py | 27 +++++++++++++++++++++++---- limbus/core/async_utils.py | 1 - 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/examples/defining_cmps.py b/examples/defining_cmps.py index 9f774ae..18d5786 100644 --- a/examples/defining_cmps.py +++ b/examples/defining_cmps.py @@ -6,8 +6,8 @@ from limbus_config import config config.COMPONENT_TYPE = "torch" -from limbus.core import Component, InputParams, OutputParams, ComponentState, OutputParam, InputParam # noqa: E402 -from limbus.core import Pipeline, VerboseMode # noqa: E402 +from limbus.core import (Component, InputParams, OutputParams, PropertyParams, Pipeline, VerboseMode, # noqa: E402 + ComponentState, OutputParam, InputParam, async_utils) # noqa: E402 # define the components @@ -114,6 +114,18 @@ def __init__(self, name: str, elements: int = 1): super().__init__(name) self._elements: int = elements + async def set_elements(self, value: int) -> int: # noqa: D102 + print(f"CALLBACK: Acc.elements: {value}.") + # this is a bir tricky since the value is stored in 2 places the property and the variable. + # Since the acc uses the _elements variable in the forward method we need to update it here + # as well. Thanks to the callback we do not need to worry about both sources. + self._elements = value + return value + + @staticmethod + def register_properties(properties: PropertyParams) -> None: # noqa: D102 + properties.declare("elements", int, callback=Acc.set_elements) + @staticmethod def register_inputs(inputs: InputParams) -> None: # noqa: D102 inputs.declare("inp", int) @@ -159,5 +171,12 @@ async def forward(self) -> ComponentState: # noqa: D102 engine.add_nodes([add, printer0]) # there are several states for each component, with this verbose mode we can see them engine.set_verbose_mode(VerboseMode.COMPONENT) -# run all teh components at least once (since there is an accumulator, some components will be run more than once) -engine.run(1) +# run all the components at least 2 times (since there is an accumulator, some components will be run more than once) + + +async def run() -> None: # noqa: D103 + await engine.async_run(1) + await acc.properties.elements.set_property(3) # change the number of elements to accumulate + await engine.async_run(1) + +async_utils.run_coroutine(run()) diff --git a/limbus/core/async_utils.py b/limbus/core/async_utils.py index 8db3ecd..e223718 100644 --- a/limbus/core/async_utils.py +++ b/limbus/core/async_utils.py @@ -3,7 +3,6 @@ import asyncio import inspect from typing import Coroutine, TYPE_CHECKING -from sys import version_info if TYPE_CHECKING: from limbus.core.component import Component