Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / factory.py: 94%

52 statements  

« 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"""Process-wide operator backend selection and direct function dispatch.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Mapping 

20from threading import RLock 

21from types import MappingProxyType 

22from typing import Any, cast 

23 

24import torch 

25 

26from .catalog import builtin_registry 

27from .spec import Fn, OpSpec 

28 

29 

30class _BackendState: 

31 """Hold one configuration snapshot and its resolution cache and usage.""" 

32 

33 def __init__(self, selections: Mapping[str, str]) -> None: 

34 self.selections = MappingProxyType(dict(selections)) 

35 self.resolved: dict[ 

36 tuple[OpSpec[Any], torch.device, torch.dtype, str, bool, tuple[str, ...]], tuple[str, Any] 

37 ] = {} 

38 self.used: dict[tuple[str, str, str], None] = {} 

39 self.lock = RLock() 

40 

41 def select( 

42 self, spec: OpSpec[Fn], x: torch.Tensor, native_only: str | None, 

43 blocked_backends: tuple[tuple[str, str], ...], default_backend: str, 

44 ) -> Fn: 

45 """Resolve against the actual input device, dtype and compatibility conditions.""" 

46 selection = self.selections.get(spec.config_key, default_backend) 

47 key = (spec, x.device, x.dtype, selection, native_only is not None, 

48 tuple(name for name, _ in blocked_backends)) 

49 selected = self.resolved.get(key) 

50 if torch.compiler.is_compiling(): 

51 # Dynamo captures the callable. Publishing it in the cache would 

52 # introduce a Python callable side effect during graph tracing. 

53 if selected is None: 

54 selected = builtin_registry.resolve( 

55 spec, selection, x, native_only=native_only, blocked_backends=blocked_backends, 

56 ) 

57 self.used[(spec.config_key, spec.variant, selected[0])] = None 

58 elif selected is None: 

59 with self.lock: 

60 selected = self.resolved.get(key) 

61 if selected is None: 

62 selected = self.resolved[key] = builtin_registry.resolve( 

63 spec, selection, x, native_only=native_only, blocked_backends=blocked_backends, 

64 ) 

65 self.used[(spec.config_key, spec.variant, selected[0])] = None 

66 return cast(Fn, selected[1]) 

67 

68 

69class _OpSelector: 

70 """Configure and inspect operator backend choices for the current process.""" 

71 

72 def __init__(self) -> None: 

73 self._state = _BackendState({}) 

74 

75 def set_backends(self, selections: Mapping[str, str]) -> None: 

76 """Replace the process-wide backend configuration and clear its cache and usage. 

77 

78 Args: 

79 selections: Complete mapping from operator family names to backend 

80 names. Omitted families use their default, normally auto. 

81 An empty mapping restores the defaults. 

82 

83 Raises: 

84 ValueError: A family, backend name or mapping value is invalid. 

85 Validation failures preserve the active configuration. 

86 """ 

87 if not isinstance(selections, Mapping): 

88 raise ValueError("ops must be a mapping from family names to implementation names") 

89 snapshot = dict(selections) 

90 builtin_registry.validate_selections(snapshot) 

91 self._state = _BackendState(snapshot) 

92 

93 def get_backends(self) -> dict[str, str]: 

94 """Return a copy of the explicitly configured family backend selections.""" 

95 return dict(self._state.selections) 

96 

97 def used_backends(self) -> tuple[tuple[str, str, str], ...]: 

98 """Return deduplicated operator, variant and backend triples since the last setting.""" 

99 state = self._state 

100 with state.lock: 

101 return tuple(state.used) 

102 

103 

104ops = _OpSelector() 

105 

106 

107def _select_for_call( 

108 spec: OpSpec[Fn], x: torch.Tensor, *, native_only: str | None = None, 

109 blocked_backends: tuple[tuple[str, str], ...] = (), default_backend: str = "auto", 

110) -> Fn: 

111 state = ops._state # pylint: disable=protected-access 

112 return state.select(spec, x, native_only, blocked_backends, default_backend) 

113 

114 

115def _dispatch(spec: OpSpec[Fn]) -> Fn: 

116 def call(x: torch.Tensor, *args: Any, **kwargs: Any) -> Any: 

117 """Dispatch this public call using the current process configuration.""" 

118 return _select_for_call(spec, x)(x, *args, **kwargs) 

119 

120 return cast(Fn, call)