-
Notifications
You must be signed in to change notification settings - Fork 54
feat[next]: Add instrumentation package and user-defineable hooks #2437
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
egparedes
wants to merge
8
commits into
GridTools:main
Choose a base branch
from
egparedes:instrumentation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
6cbbcc6
Add basic instrumentation subpackage
egparedes df46627
Add machinery and tests and several refactors
egparedes becb7ba
Run precommit
egparedes 68d2283
Remove boilerplate from unit tests
egparedes a1963e9
Add integration tests
egparedes 9c5729a
Run pre-commit
egparedes 86f4e01
Address copilot review comments (mostly cosmetic)
egparedes 2944cb7
Merge branch 'main' into instrumentation
egparedes File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| # GT4Py - GridTools Framework | ||
| # | ||
| # Copyright (c) 2014-2024, ETH Zurich | ||
| # All rights reserved. | ||
| # | ||
| # Please, refer to the LICENSE file in the root directory. | ||
| # SPDX-License-Identifier: BSD-3-Clause | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| # GT4Py - GridTools Framework | ||
| # | ||
| # Copyright (c) 2014-2024, ETH Zurich | ||
| # All rights reserved. | ||
| # | ||
| # Please, refer to the LICENSE file in the root directory. | ||
| # SPDX-License-Identifier: BSD-3-Clause | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import ast | ||
| import collections.abc | ||
| import contextlib | ||
| import dataclasses | ||
| import inspect | ||
| import textwrap | ||
| import types | ||
| import typing | ||
egparedes marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| import warnings | ||
| from collections.abc import Callable | ||
| from typing import Generic, ParamSpec, TypeVar | ||
|
|
||
|
|
||
| P = ParamSpec("P") | ||
| T = TypeVar("T") | ||
|
|
||
|
|
||
| def _get_unique_name(func: Callable) -> str: | ||
| """Generate a unique name for a callable object.""" | ||
| return ( | ||
| f"{func.__module__}.{getattr(func, '__qualname__', func.__class__.__qualname__)}#{id(func)}" | ||
| ) | ||
|
|
||
|
|
||
| def _is_empty_function(func: Callable) -> bool: | ||
| """Check if a callable object is empty (i.e., contains no statements).""" | ||
| try: | ||
| assert callable(func) | ||
| callable_src = ( | ||
| inspect.getsource(func) | ||
| if isinstance(func, types.FunctionType) | ||
| else inspect.getsource(func.__call__) # type: ignore[operator] # asserted above | ||
| ) | ||
| callable_ast = ast.parse(textwrap.dedent(callable_src)) | ||
| return all( | ||
| isinstance(st, ast.Pass) | ||
| or (isinstance(st, ast.Expr) and isinstance(st.value, ast.Constant)) | ||
| for st in typing.cast(ast.FunctionDef, callable_ast.body[0]).body | ||
| ) | ||
| except Exception: | ||
| return False | ||
|
|
||
|
|
||
| @dataclasses.dataclass(slots=True) | ||
| class _BaseHook(Generic[T, P]): | ||
| """Base class to define callback registration functionality for all hook types.""" | ||
|
|
||
| definition: Callable[P, T] | ||
| registry: dict[str, Callable[P, T]] = dataclasses.field(default_factory=dict, kw_only=True) | ||
| callbacks: tuple[Callable[P, T], ...] = dataclasses.field(default=(), init=False) | ||
|
|
||
| def __post_init__(self) -> None: | ||
| # As an optimization to avoid an empty function call if no callbacks are | ||
| # registered, we only add the original definitions to the list of callables | ||
| # if it contains a non-empty definition. | ||
| if not _is_empty_function(self.definition): | ||
| self.callbacks = (self.definition,) | ||
|
|
||
| def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: | ||
| raise NotImplementedError("This method should be implemented by subclasses.") | ||
|
|
||
| def register( | ||
| self, callback: Callable[P, T], *, name: str | None = None, index: int | None = None | ||
| ) -> None: | ||
| """ | ||
| Register a callback to the hook. | ||
|
|
||
| Args: | ||
| callback: The callable to register. | ||
| name: An optional name for the callback. If not provided, a unique name will be generated. | ||
| index: An optional index at which to insert the callback (not counting the original | ||
| definition). If not provided, the callback will be appended to the end of the list. | ||
| """ | ||
|
|
||
| callable_signature = inspect.signature(callback) | ||
| hook_signature = inspect.signature(self.definition) | ||
|
|
||
| signature_mismatch = len(callable_signature.parameters) != len( | ||
| hook_signature.parameters | ||
| ) or any( | ||
| # Remove the annotation before comparison to avoid false mismatches | ||
| actual_param.replace(annotation="") != expected_param.replace(annotation="") | ||
| for actual_param, expected_param in zip( | ||
| callable_signature.parameters.values(), hook_signature.parameters.values() | ||
| ) | ||
| ) | ||
| if signature_mismatch: | ||
| raise ValueError( | ||
| f"Callback signature {callable_signature} does not match hook signature {hook_signature}" | ||
| ) | ||
| try: | ||
| callable_typing = typing.get_type_hints(callback) | ||
| hook_typing = typing.get_type_hints(self.definition) | ||
| if not all( | ||
| callable_typing[arg_key] == arg_typing | ||
| for arg_key, arg_typing in hook_typing.items() | ||
| ): | ||
| warnings.warn( | ||
| f"Callback annotations {callable_typing} does not match expected hook annotations {hook_typing}", | ||
| stacklevel=2, | ||
| ) | ||
| except Exception: | ||
egparedes marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| pass | ||
| name = name or _get_unique_name(callback) | ||
|
|
||
| if index is None: | ||
| self.callbacks += (callback,) | ||
| else: | ||
| if self.callbacks and self.callbacks[0] is self.definition: | ||
| index += 1 # The original definition should always go first | ||
| self.callbacks = (*self.callbacks[:index], callback, *self.callbacks[index:]) | ||
|
|
||
| self.registry[name] = callback | ||
|
|
||
| def remove(self, callback: str | Callable[P, T]) -> None: | ||
| """ | ||
| Remove a registered callback from the hook. | ||
|
|
||
| Args: | ||
| callback: The callable object to remove or its registered name. | ||
| """ | ||
| if isinstance(callback, str): | ||
| name = callback | ||
| if name not in self.registry: | ||
| raise KeyError(f"No callback registered under the name '{name}'") | ||
| else: | ||
| name = _get_unique_name(callback) | ||
| if name not in self.registry: | ||
| raise KeyError(f"Callback object {callback} not found in registry") | ||
|
|
||
| callback = self.registry.pop(name) | ||
| assert callback in self.callbacks | ||
| self.callbacks = tuple(cb for cb in self.callbacks if cb is not callback) | ||
|
|
||
|
|
||
| @dataclasses.dataclass(slots=True) | ||
| class EventHook(_BaseHook[None, P]): | ||
| """Event hook specification.""" | ||
|
|
||
| def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None: | ||
| for func in self.callbacks: | ||
| func(*args, **kwargs) | ||
|
|
||
|
|
||
| @dataclasses.dataclass(slots=True) | ||
| class ContextHook( | ||
| contextlib.AbstractContextManager, _BaseHook[contextlib.AbstractContextManager, P] | ||
| ): | ||
| """ | ||
| Context hook specification. | ||
|
|
||
| This hook type is used to define context managers that can be stacked together. | ||
| """ | ||
|
|
||
| ctx_managers: collections.abc.Sequence[contextlib.AbstractContextManager] = dataclasses.field( | ||
| default=(), init=False | ||
| ) | ||
|
|
||
| def __call__(self, *args: P.args, **kwargs: P.kwargs) -> contextlib.AbstractContextManager: | ||
| self.ctx_managers = [func(*args, **kwargs) for func in self.callbacks] | ||
| return self | ||
|
|
||
| def __enter__(self) -> None: | ||
| for ctx_manager in self.ctx_managers: | ||
| ctx_manager.__enter__() | ||
|
|
||
| def __exit__( | ||
| self, | ||
| type_: type[BaseException] | None, | ||
| value: BaseException | None, | ||
| traceback: types.TracebackType | None, | ||
| ) -> None: | ||
| for ctx_manager in reversed(self.ctx_managers): | ||
| ctx_manager.__exit__(type_, value, traceback) | ||
| self.ctx_managers = () | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # GT4Py - GridTools Framework | ||
| # | ||
| # Copyright (c) 2014-2024, ETH Zurich | ||
| # All rights reserved. | ||
| # | ||
| # Please, refer to the LICENSE file in the root directory. | ||
| # SPDX-License-Identifier: BSD-3-Clause | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from gt4py.next.ffront.decorator import ( | ||
| embedded_program_call_hook as embedded_program_call_hook, | ||
| program_call_hook as program_call_hook, | ||
| ) | ||
| from gt4py.next.otf.compiled_program import compile_variant_hook as compile_variant_hook |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.