Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / registry.py: 100%
100 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Registry of operator contracts, implementations and automatic selection orders."""
17from __future__ import annotations
19from collections.abc import Callable, Mapping
20from dataclasses import dataclass
21from typing import Any, cast
23import torch
25from .spec import DeviceType, Fn, OpSpec
28class ImplementationUnavailable(RuntimeError):
29 """A selected adapter cannot load a required optional dependency or operator."""
32@dataclass(frozen=True)
33class _Implementation:
34 load: Callable[[], Any]
35 check_compatibility: Callable[[torch.Tensor], str | None] | None
38class OpRegistry:
39 """Assemble a catalog and seal it before resolving operator calls."""
41 def __init__(self) -> None:
42 """Start with an empty catalog open for registration."""
43 self._families: dict[str, dict[str, OpSpec[Any]]] = {}
44 self._names: dict[str, set[str]] = {}
45 self._implementations: dict[tuple[OpSpec[Any], str, str], _Implementation] = {}
46 self._implementations_by_name: dict[tuple[str, str, str, str], _Implementation] = {}
47 self._auto: dict[tuple[OpSpec[Any], str], tuple[str, ...]] = {}
48 self._sealed = False
50 def _require_mutable(self) -> None:
51 if self._sealed:
52 raise RuntimeError("Operator registry is sealed")
54 def _require_spec(self, spec: OpSpec[Any]) -> None:
55 if self._families.get(spec.config_key, {}).get(spec.variant) is not spec:
56 raise ValueError(f"Unregistered operator contract {spec.config_key}.{spec.variant}")
58 def register_family(self, config_key: str, *, specs: tuple[OpSpec[Any], ...]) -> None:
59 """Register a family and all of its distinct callable contracts."""
60 self._require_mutable()
61 variants = {spec.variant: spec for spec in specs}
62 if (
63 not isinstance(config_key, str)
64 or not config_key.strip()
65 or config_key in self._families
66 or not variants
67 or len(variants) != len(specs)
68 or any(spec.config_key != config_key for spec in specs)
69 ):
70 raise ValueError(f"Invalid or duplicate operator family {config_key!r}")
71 self._families[config_key] = variants
72 self._names[config_key] = set()
74 def register_impl(
75 self,
76 spec: OpSpec[Fn],
77 *,
78 name: str,
79 devices: tuple[DeviceType, ...],
80 load: Callable[[], Fn],
81 check_compatibility: Callable[[torch.Tensor], str | None] | None = None,
82 ) -> None:
83 """Register a lazy implementation for the given contract and devices."""
84 self._require_mutable()
85 self._require_spec(spec)
86 if not isinstance(name, str) or not name.strip() or name == "auto":
87 raise ValueError(f"Invalid operator implementation name {name!r}")
88 if not devices or len(set(devices)) != len(devices) or set(devices) - {"cpu", "cuda", "npu"}:
89 raise ValueError(f"Invalid operator devices {devices!r} for {spec.config_key}.{name}")
90 if not callable(load) or (check_compatibility is not None and not callable(check_compatibility)):
91 raise ValueError(f"Invalid operator loader or compatibility check for {spec.config_key}.{name}")
92 keys = [(spec, name, device_type) for device_type in devices]
93 if any(key in self._implementations for key in keys):
94 raise ValueError(f"Overlapping operator registration for {spec.config_key}.{spec.variant}:{name}")
95 implementation = _Implementation(load, check_compatibility)
96 self._implementations.update({key: implementation for key in keys})
97 # String keys let Dynamo resolve implementations without hashing OpSpec dataclasses.
98 self._implementations_by_name.update({
99 (spec.config_key, spec.variant, name, device): implementation for device in devices
100 })
101 self._names[spec.config_key].add(name)
103 def set_auto_order(
104 self, spec: OpSpec[Any], *, device: DeviceType, candidates: tuple[str, ...],
105 ) -> None:
106 """Declare an ordered list of registered candidates for one device."""
107 self._require_mutable()
108 self._require_spec(spec)
109 key = (spec, device)
110 if (
111 device not in {"cpu", "cuda", "npu"}
112 or key in self._auto
113 or len(set(candidates)) != len(candidates)
114 or any((spec, name, device) not in self._implementations for name in candidates)
115 ):
116 raise ValueError(f"Invalid automatic backend order for {spec.config_key}.{spec.variant} on {device}")
117 self._auto[key] = tuple(candidates)
119 def seal(self) -> None:
120 """Finish catalog assembly and prevent subsequent registrations."""
121 self._sealed = True
123 def validate_selections(self, selections: Mapping[str, str]) -> None:
124 """Validate user-facing family and implementation names."""
125 if not self._sealed:
126 raise ValueError("Operator backend selection requires a sealed registry")
127 if not isinstance(selections, Mapping):
128 raise ValueError("ops must be a mapping from family names to implementation names")
129 for key, name in selections.items():
130 if not isinstance(key, str) or key not in self._names:
131 raise ValueError(f"Unknown operator family {key!r} in 'ops'")
132 if not isinstance(name, str) or (name != "auto" and name not in self._names[key]):
133 allowed = ", ".join(sorted(self._names[key] | {"auto"}))
134 raise ValueError(f"Invalid ops.{key} value {name!r}, expected one of {allowed}")
136 def resolve(
137 self, spec: OpSpec[Fn], selection: str, x: torch.Tensor, *, native_only: str | None = None,
138 blocked_backends: tuple[tuple[str, str], ...] = (),
139 ) -> tuple[str, Fn]:
140 """Return the selected name and callable, or explain candidate rejection."""
141 self._require_spec(spec)
142 device_type = x.device.type
143 names = self._auto.get((spec, device_type), ()) if selection == "auto" else (selection,)
144 reasons = []
145 blocked = dict(blocked_backends)
146 for name in names:
147 if native_only is not None and name != "native":
148 reasons.append(f"{name}: {native_only}")
149 continue
150 if name in blocked:
151 reasons.append(f"{name}: {blocked[name]}")
152 continue
153 impl = self._implementations_by_name.get((spec.config_key, spec.variant, name, device_type))
154 if impl is None:
155 reasons.append(f"{name}: not registered for this contract and device")
156 continue
157 if impl.check_compatibility is not None:
158 reason = impl.check_compatibility(x)
159 if reason is not None:
160 reasons.append(f"{name}: {reason}")
161 continue
162 try:
163 selected = impl.load()
164 except ImplementationUnavailable as exc:
165 reasons.append(f"{name}: {exc}")
166 continue
167 if not callable(selected):
168 raise TypeError(f"Operator loader for {spec.config_key}.{name} did not return a callable")
169 return name, cast(Fn, selected)
170 detail = ", ".join(reasons) or "no auto candidates registered"
171 raise RuntimeError(
172 f"Cannot select ops.{spec.config_key}={selection!r} "
173 f"for variant {spec.variant!r} on {x.device}: {detail}"
174 )