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

51 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"""Dry-run configuration for logical LLM memory analysis.""" 

16 

17from collections.abc import Mapping 

18from dataclasses import dataclass, field 

19from typing import Any, Literal, Optional 

20 

21 

22@dataclass 

23class DryRunSnapshotConfig: 

24 """Logical memory snapshot output settings. 

25 

26 Args: 

27 path: Output root directory where ``rank_{rank}/memory.pickle`` is 

28 written, or ``None`` to keep the snapshot in memory only. 

29 stack_depth: Maximum Python call-stack depth recorded per allocation. 

30 Set to ``0`` to disable stack capture. 

31 """ 

32 

33 path: Optional[str] = "outputs/dry_run" 

34 stack_depth: int = 64 

35 

36 def validate(self) -> None: 

37 """Validate snapshot output path and stack-depth bounds.""" 

38 if self.path is not None and (not isinstance(self.path, str) or not self.path.strip()): 

39 raise ValueError("dry_run.snapshot.path must be a non-empty string or null") 

40 if ( 

41 isinstance(self.stack_depth, bool) 

42 or not isinstance(self.stack_depth, int) 

43 or not 0 <= self.stack_depth <= 256 

44 ): 

45 raise ValueError("dry_run.snapshot.stack_depth must be an integer in [0, 256]") 

46 

47 

48@dataclass 

49class DryRunConfig: 

50 """Configuration for logical LLM memory analysis. 

51 

52 Args: 

53 target_device: Target accelerator type to simulate (``"npu"`` or ``"cuda"``). 

54 ranks: Global ranks to execute under ``torchrun``; defaults to ``[0]``. 

55 snapshot: Snapshot persistence and stack-capture settings. 

56 """ 

57 

58 target_device: Literal["npu", "cuda"] = "npu" 

59 ranks: list[int] = field(default_factory=lambda: [0]) 

60 snapshot: DryRunSnapshotConfig = field(default_factory=DryRunSnapshotConfig) 

61 

62 @classmethod 

63 def from_mapping(cls, value: Mapping[str, Any]) -> "DryRunConfig": 

64 """Build a config while normalizing nested snapshot and rank fields. 

65 

66 Args: 

67 value: Raw mapping parsed from the recipe. 

68 

69 Returns: 

70 Resolved :class:`DryRunConfig` instance. 

71 """ 

72 raw_fields = dict(value) 

73 snapshot = raw_fields.get("snapshot") 

74 if snapshot is None and "snapshot" in raw_fields: 

75 raw_fields["snapshot"] = DryRunSnapshotConfig(path=None) 

76 elif isinstance(snapshot, Mapping): 

77 raw_fields["snapshot"] = DryRunSnapshotConfig(**dict(snapshot)) 

78 if raw_fields.get("ranks") is None: 

79 raw_fields.pop("ranks", None) 

80 return cls(**raw_fields) 

81 

82 def validate(self, world_size: Optional[int] = None) -> None: 

83 """Validate ranks and snapshot settings. 

84 

85 Args: 

86 world_size: Optional launched world size to check rank upper bounds. 

87 """ 

88 if not isinstance(self.snapshot, DryRunSnapshotConfig): 

89 raise TypeError("dry_run.snapshot must resolve to DryRunSnapshotConfig") 

90 self.snapshot.validate() 

91 if ( 

92 not isinstance(self.ranks, list) 

93 or not self.ranks 

94 or any( 

95 isinstance(rank, bool) or not isinstance(rank, int) or rank < 0 

96 for rank in self.ranks 

97 ) 

98 or len(set(self.ranks)) != len(self.ranks) 

99 ): 

100 raise ValueError("dry_run.ranks must be a non-empty list of unique non-negative integers") 

101 if world_size is not None: 

102 if isinstance(world_size, bool) or not isinstance(world_size, int) or world_size < 1: 

103 raise ValueError("WORLD_SIZE must be a positive integer") 

104 if any(rank >= world_size for rank in self.ranks): 

105 raise ValueError( 

106 f"dry_run.ranks must be smaller than virtual world size {world_size}" 

107 ) 

108 

109 

110def resolve_dryrun_config(value: object) -> DryRunConfig: 

111 """Normalize a raw ``TrainerConfig.dry_run`` field into :class:`DryRunConfig`. 

112 

113 Args: 

114 value: ``None``, a raw mapping from YAML, or an existing ``DryRunConfig``. 

115 

116 Returns: 

117 Normalized :class:`DryRunConfig`. 

118 """ 

119 if isinstance(value, DryRunConfig): 

120 return value 

121 if value is None: 

122 return DryRunConfig() 

123 if isinstance(value, Mapping): 

124 try: 

125 return DryRunConfig.from_mapping(value) 

126 except TypeError as error: 

127 raise ValueError(f"Invalid dry_run configuration: {error}") from error 

128 raise TypeError("TrainerConfig.dry_run must resolve to a DryRunConfig, mapping, or null") 

129 

130 

131__all__ = [ 

132 "DryRunConfig", 

133 "DryRunSnapshotConfig", 

134 "resolve_dryrun_config", 

135]