Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / megakernel_utils.py: 100%

22 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"""Prepare and release module-owned MegaKernel runtimes.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Iterator 

20from typing import Any 

21 

22from torch import nn 

23 

24 

25def _runtime_groups(model: nn.Module) -> Iterator[list[nn.Module]]: 

26 """Group unique runtime owners by compatible execution resources.""" 

27 groups: dict[Any, list[nn.Module]] = {} 

28 seen = set() 

29 for module in model.modules(): 

30 key = getattr(module, "runtime_group_key", None) 

31 if callable(key): 

32 # Transparent wrappers may delegate this bound method to their child. 

33 owner = getattr(key, "__self__", module) 

34 if id(owner) not in seen: 

35 groups.setdefault(key(), []).append(owner) 

36 seen.add(id(owner)) 

37 yield from groups.values() 

38 

39 

40def prepare_module_runtimes(model: nn.Module) -> None: 

41 """Prepare declared module groups after FSDP wrapping and materialization. 

42 

43 Args: 

44 model: Final module tree. Ordinary modules declare no runtime group. 

45 """ 

46 for modules in _runtime_groups(model): 

47 modules[0].prepare_runtime_group(modules) 

48 

49 

50def close_module_runtimes(model: nn.Module) -> None: 

51 """Release declared runtimes after every forward and backward has completed. 

52 

53 Args: 

54 model: Final model tree; each holder releases its own runtime reference. 

55 """ 

56 for modules in _runtime_groups(model): 

57 for module in modules: 

58 module.close_runtime()