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

81 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-loop, debug, profiler, and remote-logging configuration sections.""" 

16 

17from dataclasses import dataclass, field 

18from typing import Literal, Optional 

19 

20from hyper_parallel.components.quantization.config import LowPrecisionConfig 

21 

22 

23@dataclass 

24class TrainingConfig: 

25 """Training-loop parameters exposed by the initial YAML schema.""" 

26 

27 train_iters: Optional[int] = None 

28 train_samples: Optional[int] = None 

29 epochs: Optional[int] = None 

30 max_steps: Optional[int] = None 

31 """Online optimizer-step limit per epoch; used together with ``epochs``.""" 

32 lr_scheduler_iters: Optional[int] = None 

33 eval_iters: int = 0 

34 

35 global_batch_size: int = 8 

36 micro_batch_size: int = 1 

37 

38 backend: Literal["nccl", "hccl", "gloo"] = "nccl" 

39 max_grad_norm: float = 1.0 

40 init_device: Literal["meta", "cpu", "cuda", "npu"] = "meta" 

41 loss_aggregation: Literal["token_weighted", "rank_average"] = "token_weighted" 

42 seed: Optional[int] = None 

43 enable_full_determinism: bool = False 

44 gc_steps: int = 0 

45 empty_cache_steps: int = 0 

46 empty_cache_before_backward: bool = False 

47 eval_steps: int = 0 

48 eval_epochs: int = 0 

49 logging_steps: int = 1 

50 log_tflops: bool = False 

51 """Publish analytical per-device model FLOPs throughput. 

52 

53 When enabled, the environment meter adds 

54 ``performance/tflops_per_device`` (TFLOP/s, cluster average per device) 

55 to each step's metrics. The estimate charges every model-input token, 

56 including prompt tokens masked out of the loss, and accumulates causal 

57 attention over the real sequence boundaries. 

58 """ 

59 low_precision: LowPrecisionConfig = field(default_factory=LowPrecisionConfig) 

60 

61 def __post_init__(self) -> None: 

62 """Keep explicit epoch plans separate from legacy global run limits.""" 

63 

64 if self.epochs is None and self.max_steps is None: 

65 return 

66 

67 for name in ("epochs", "max_steps"): 

68 value = getattr(self, name) 

69 

70 if isinstance(value, bool) or not isinstance(value, int) or value <= 0: 

71 raise ValueError(f"training.{name} must be a positive integer; configure epochs and max_steps together") 

72 

73 if self.train_iters is not None or self.train_samples is not None: 

74 raise ValueError("training.epochs/max_steps cannot be combined with train_iters/train_samples") 

75 

76 

77@dataclass 

78class DebugConfig: 

79 """Debug parameters exposed by the initial YAML schema.""" 

80 

81 check_dataset: Optional[Literal["debug", "info", "warn"]] = None 

82 log_first_rendered_template: bool = False 

83 check_nan_inf: bool = False 

84 check_fsdp_runtime: bool = False 

85 

86 

87@dataclass 

88class ModelIntegrationConfig: 

89 """Enable model-integration checks at one well-defined lifecycle scope. 

90 

91 ``build`` validates the final module tree, sharding ownership, data 

92 contract, optimizer layout, and checkpoint coverage. ``runtime`` includes 

93 those checks and records one-step input, gradient, shared-state, and layout 

94 evidence. Output location and probe selection are framework policy rather 

95 than user-tunable training semantics. 

96 """ 

97 

98 mode: Literal["off", "build", "runtime"] = "off" 

99 

100 def __post_init__(self) -> None: 

101 """Reject ambiguous validation scopes at the configuration boundary.""" 

102 if self.mode not in ("off", "build", "runtime"): 

103 raise ValueError( 

104 "model_integration.mode must be one of: off, build, runtime" 

105 ) 

106 

107 

108@dataclass 

109class MemoryConfig: 

110 """Configure allocator memory-history snapshots during training. 

111 

112 Args: 

113 enable: Whether allocator history recording is enabled. 

114 start_step: First session-relative step included in the snapshot; zero includes model construction. 

115 end_step: Last session-relative step included in the snapshot. 

116 save_path: Directory used for snapshot files. 

117 dump_ranks: Global ranks that write snapshot files. 

118 stacks: Stack information recorded by the allocator. 

119 mem_info: Whether peak allocator statistics are logged before each step. 

120 """ 

121 

122 enable: bool = False 

123 start_step: int = 1 

124 end_step: int = 2 

125 save_path: str = "./memory_snapshot" 

126 dump_ranks: list[int] = field(default_factory=lambda: [0]) 

127 stacks: Literal["python", "all"] = "all" 

128 mem_info: bool = False 

129 

130 

131@dataclass 

132class WandbConfig: 

133 """WandB remote-logging parameters (03 §4.2.5: read by build_callback_manager).""" 

134 

135 enabled: bool = False 

136 project: str = "" 

137 entity: Optional[str] = None 

138 

139 

140@dataclass 

141class ProfilingAnalysisConfig: 

142 """Configure Ascend NPU trace analysis after collection. 

143 

144 Args: 

145 enable: Whether collected data is automatically analyzed. 

146 async_mode: Whether automatic analysis runs asynchronously; ignored when disabled. 

147 """ 

148 

149 enable: bool = True 

150 async_mode: bool = False 

151 

152 

153@dataclass 

154class ProfilingConfig: 

155 """Configure bounded PyTorch profiler collection during training. 

156 

157 HyperParallel groups these options under ``TrainerConfig.profiler``, so 

158 their names describe only the option itself rather than repeating a 

159 ``profile_`` prefix. 

160 

161 Args: 

162 enable: Whether profiler collection is enabled. 

163 start_step: First training step included in the profile. 

164 stop_step: Last training step included in the profile. 

165 warmup_steps: Number of warmup steps immediately before ``start_step``; must be smaller than it. 

166 memory: Whether tensor memory events are collected. 

167 rank_ids: Explicit ranks that collect a profile. ``None`` or an empty list selects all ranks. 

168 output_path: Output root. Each rank writes under ``profile/rank_<rank>``. 

169 level: Ascend collection level, from 0 through 2. ``None`` selects level 0. 

170 with_stack: Whether Python stack traces are collected. 

171 data_simplification: Whether torch-npu removes selected auxiliary CANN data after export. 

172 analysis: Ascend NPU automatic trace analysis options; ignored on CPU/CUDA. 

173 """ 

174 

175 enable: bool = False 

176 start_step: int = 1 

177 stop_step: int = 10 

178 warmup_steps: int = 0 

179 memory: bool = True 

180 rank_ids: Optional[list[int]] = None 

181 output_path: Optional[str] = None 

182 level: Optional[int] = 1 

183 with_stack: bool = False 

184 data_simplification: bool = False 

185 analysis: ProfilingAnalysisConfig = field(default_factory=ProfilingAnalysisConfig)