|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import inspect |
| 4 | +import warnings |
| 5 | +from collections.abc import Callable |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from ndsl.dsl.dace import DaceConfig, orchestrate |
| 9 | +from ndsl.dsl.typing import Float |
| 10 | +from ndsl.initialization.allocator import QuantityFactory |
| 11 | +from ndsl.quantity import Local, Quantity |
| 12 | + |
| 13 | + |
| 14 | +_TOP_LEVEL: object | None = None |
| 15 | + |
| 16 | + |
| 17 | +class NDSLRuntime: |
| 18 | + """Base class to tool runtime code, allows use of Locals, orchestration and |
| 19 | + debug tools. |
| 20 | +
|
| 21 | + The __call__ function will automatically be orchestrated.""" |
| 22 | + |
| 23 | + def __init__(self, dace_config: DaceConfig) -> None: |
| 24 | + self._dace_config = dace_config |
| 25 | + # Use this flag to detect that the init wasn't done properly |
| 26 | + self._base_class_was_properly_super_init = True |
| 27 | + |
| 28 | + def __init_subclass__(cls: type[NDSLRuntime], **kwargs: dict[str, Any]) -> None: |
| 29 | + # WARNING: no code outside the `init_decorator` this is cls |
| 30 | + # function, it will be called ONLY ONCE for monkey-patching the |
| 31 | + # Class - not the instance ! |
| 32 | + |
| 33 | + def init_decorator(previous_init: Callable) -> Callable: |
| 34 | + def new_init( |
| 35 | + self: NDSLRuntime, |
| 36 | + *args: list[Any], |
| 37 | + **kwargs: dict[str, Any], |
| 38 | + ) -> None: |
| 39 | + global _TOP_LEVEL |
| 40 | + if _TOP_LEVEL is None: |
| 41 | + _TOP_LEVEL = self |
| 42 | + previous_init(self, *args, **kwargs) |
| 43 | + self.__post_init__() |
| 44 | + |
| 45 | + return new_init |
| 46 | + |
| 47 | + cls.__init__ = init_decorator(cls.__init__) # type: ignore[method-assign] |
| 48 | + |
| 49 | + def __post_init__(self) -> None: |
| 50 | + if not hasattr(self, "_base_class_was_properly_super_init"): |
| 51 | + raise RuntimeError( |
| 52 | + f"Class {type(self).__name__} inherit from NDSLRuntime but didn't call super().__init__." |
| 53 | + ) |
| 54 | + |
| 55 | + # Check quantity allocation of NDSLRuntime supervised code |
| 56 | + if _TOP_LEVEL == self: |
| 57 | + |
| 58 | + def check_for_quantity(object_: object) -> None: |
| 59 | + for key, value in object_.__dict__.items(): |
| 60 | + if isinstance(value, Quantity) and not isinstance(value, Local): |
| 61 | + warnings.warn( |
| 62 | + f"{type(self).__name__}.{key} is a Quantity instead of a Locals" |
| 63 | + " on a NDSLRuntime - our eyebrows are frowned." |
| 64 | + ) |
| 65 | + elif isinstance(value, NDSLRuntime): |
| 66 | + check_for_quantity(value) |
| 67 | + |
| 68 | + check_for_quantity(self) |
| 69 | + |
| 70 | + # Orchestrate __call__ by default |
| 71 | + if hasattr(self, "__call__"): |
| 72 | + orchestrate( |
| 73 | + obj=self, |
| 74 | + config=self._dace_config, |
| 75 | + ) |
| 76 | + print(type(self)) |
| 77 | + |
| 78 | + def __getattribute__(self, name: str) -> Any: |
| 79 | + attr = super().__getattribute__(name) |
| 80 | + # We look at the direct caller frame for our own `self` |
| 81 | + # in the locals. |
| 82 | + # All other cases are forbidden. |
| 83 | + if isinstance(attr, Local): |
| 84 | + frame = inspect.currentframe() |
| 85 | + if frame is None: |
| 86 | + raise NotImplementedError( |
| 87 | + "Locals check cannot locate frame. Talk to the team." |
| 88 | + ) |
| 89 | + caller_frame = frame.f_back |
| 90 | + if ( |
| 91 | + not caller_frame |
| 92 | + or "self" not in caller_frame.f_locals |
| 93 | + or not isinstance(caller_frame.f_locals["self"], type(self)) |
| 94 | + ): |
| 95 | + # We expect the original class to have been monkey-patched |
| 96 | + # See `dace.dsl.orchestration.orchestrate` |
| 97 | + unpatched_name = type(self).__name__[: -len("_patched")] |
| 98 | + raise RuntimeError( |
| 99 | + f"Forbidden Local access: {name} called outside of {unpatched_name}." |
| 100 | + ) |
| 101 | + |
| 102 | + return attr |
| 103 | + |
| 104 | + def make_local( |
| 105 | + self, |
| 106 | + quantity_factory: QuantityFactory, |
| 107 | + dims: list[str], |
| 108 | + dtype: type = Float, |
| 109 | + units: str = "unspecified", |
| 110 | + *, |
| 111 | + allow_mismatch_float_precision: bool = False, |
| 112 | + ) -> Local: |
| 113 | + quantity = quantity_factory.zeros( |
| 114 | + dims, |
| 115 | + units, |
| 116 | + dtype, |
| 117 | + allow_mismatch_float_precision=allow_mismatch_float_precision, |
| 118 | + ) |
| 119 | + return Local( |
| 120 | + data=quantity.data, |
| 121 | + dims=quantity.dims, |
| 122 | + units=quantity.units, |
| 123 | + origin=quantity.origin, |
| 124 | + extent=quantity.extent, |
| 125 | + gt4py_backend=quantity.gt4py_backend, |
| 126 | + allow_mismatch_float_precision=allow_mismatch_float_precision, |
| 127 | + ) |
0 commit comments