Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / dryrun / patches / trainer / model_builder.py: 98%

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"""Training-flow patch deferring model weight materialization during dry-run.""" 

16 

17from contextlib import contextmanager 

18from contextvars import ContextVar 

19from typing import Any, Iterator 

20 

21from torch import nn 

22from torch._subclasses.fake_tensor import unset_fake_temporarily 

23 

24 

25_DEFER_MODEL_MATERIALIZATION: ContextVar[bool] = ContextVar( 

26 "dryrun_defer_model_materialization", 

27 default=False, 

28) 

29 

30 

31@contextmanager 

32def model_build_context() -> Iterator[None]: 

33 """Build a model without materializing weights or reading device storage.""" 

34 token = _DEFER_MODEL_MATERIALIZATION.set(True) 

35 try: 

36 yield 

37 finally: 

38 _DEFER_MODEL_MATERIALIZATION.reset(token) 

39 

40 

41def is_model_materialization_deferred() -> bool: 

42 """Return whether the current model build is owned by dry-run.""" 

43 return _DEFER_MODEL_MATERIALIZATION.get() 

44 

45 

46def install_model_build_patches() -> None: 

47 """Patch AutoModel/model_builder to skip weight loading under dry-run.""" 

48 # Lazy import avoids pulling optional transformers dependencies when dry-run 

49 # only exercises non-model components (e.g. optimizer or memory unit tests). 

50 from hyper_parallel.models._transformers import auto_model, model_builder # pylint: disable=import-outside-toplevel 

51 

52 if getattr(model_builder, "_dryrun_model_build_patched", False): 

53 return 

54 

55 original_materialize = model_builder._materialize_and_load_model 

56 original_init_context = auto_model._model_init_context 

57 

58 def materialize_without_storage(model: nn.Module, **kwargs: Any) -> nn.Module: 

59 """Skip weight materialization while the deferral scope is active.""" 

60 if is_model_materialization_deferred(): 

61 return model 

62 return original_materialize(model, **kwargs) 

63 

64 def model_init_context(is_meta_device: bool) -> Any: 

65 """Enter shape-only meta init context inside the deferral scope.""" 

66 if not is_model_materialization_deferred(): 

67 return original_init_context(is_meta_device) 

68 

69 # Keep transformers imports scoped here so non-model tests never pull 

70 # optional imaging dependencies into the process. 

71 from transformers.modeling_utils import ContextManagers # pylint: disable=import-outside-toplevel 

72 from hyper_parallel import init_empty_weights # pylint: disable=import-outside-toplevel 

73 

74 try: 

75 from transformers.modeling_utils import no_init_weights # pylint: disable=import-outside-toplevel 

76 except ImportError: 

77 from transformers.initialization import no_init_weights # pylint: disable=import-outside-toplevel 

78 

79 contexts = [unset_fake_temporarily(), no_init_weights(), init_empty_weights()] 

80 return ContextManagers(contexts) 

81 

82 model_builder._materialize_and_load_model = materialize_without_storage 

83 model_builder.model_build_context = model_build_context 

84 model_builder.is_model_materialization_deferred = is_model_materialization_deferred 

85 auto_model._model_init_context = model_init_context 

86 model_builder._dryrun_model_build_patched = True 

87 

88 

89__all__ = [ 

90 "install_model_build_patches", 

91 "is_model_materialization_deferred", 

92 "model_build_context", 

93]