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

41 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"""Load optional kernel dependencies and check symbols before selecting an adapter.""" 

16 

17from functools import lru_cache 

18from importlib import import_module 

19from threading import RLock, get_ident 

20from types import ModuleType 

21from typing import Callable, Optional 

22 

23import torch 

24 

25from .registry import ImplementationUnavailable 

26from .spec import Fn 

27 

28 

29_FLA_IMPORT_LOCK = RLock() 

30 

31 

32def require_package(name: str, *, loader: Optional[Callable[[str], ModuleType]] = None) -> ModuleType: 

33 """Import an optional package, preserving failures in its own imports. 

34 

35 Args: 

36 name: Fully qualified package name. 

37 loader: Optional dependency-specific compatibility loader. 

38 """ 

39 try: 

40 return (loader or import_module)(name) 

41 except ModuleNotFoundError as exc: 

42 if exc.name is not None and (exc.name == name or name.startswith(f"{exc.name}.")): 

43 raise ImplementationUnavailable(f"missing optional package {name}") from exc 

44 raise 

45 

46 

47def require_symbol(module: object, name: str) -> None: 

48 """Reject a candidate if the optional operator is not registered.""" 

49 if not callable(getattr(module, name, None)): 

50 raise ImplementationUnavailable(f"missing operator {name}") 

51 

52 

53def load_cann(kernel: Fn, *symbols: str) -> Fn: 

54 """Return a CANN adapter after checking its required operator symbols.""" 

55 package = require_package("cann_ops_transformer") 

56 for symbol in symbols: 

57 require_symbol(package, symbol) 

58 return kernel 

59 

60 

61@lru_cache(maxsize=None) 

62def import_fla_module(name: str) -> ModuleType: 

63 """Import FLA using its explicit Triton configurations and complete cache keys. 

64 

65 Triton-Ascend's runtime replaces ``triton.autotune`` with an automatic-tiling 

66 tuner. Older releases interpret even explicit-config cache keys as at most 

67 six tiling axes. FLA imports unrelated kernels with more keys, so merely 

68 loading ShortConv can fail before any convolution runs. 

69 

70 Keep the standard tuner during dependency registration only. Restore the 

71 caller's tuner even on import failure; do not patch dependency files or 

72 change the selected kernels, their configurations, or their cache keys. 

73 

74 Args: 

75 name: FLA module to load lazily. 

76 

77 Returns: 

78 The imported module. 

79 """ 

80 # Both packages are optional; importing Hyper must not initialize either. 

81 import triton # pylint: disable=import-outside-toplevel 

82 from triton.runtime.autotuner import autotune # pylint: disable=import-outside-toplevel 

83 

84 with _FLA_IMPORT_LOCK: 

85 if not hasattr(torch, "npu") or not torch.npu.is_available(): 

86 return import_module(name) 

87 # Finish the runtime's one-time replacement before binding FLA's tuner. 

88 import_module("triton.backends.ascend.runtime") 

89 previous = triton.autotune 

90 importing_thread = get_ident() 

91 

92 def _scoped_autotune(*args, **kwargs): 

93 # Unrelated threads must retain the caller's original tuner. 

94 tuner = autotune if get_ident() == importing_thread else previous 

95 return tuner(*args, **kwargs) 

96 

97 try: 

98 triton.autotune = _scoped_autotune 

99 return import_module(name) 

100 finally: 

101 triton.autotune = previous