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

77 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"""Aggregate trainer configuration tree. 

16 

17Split from ``auto_models/trainer/config.py`` in stage 7 (05 §15.2.5); 

18class name, fields and defaults are unchanged. 

19""" 

20 

21from dataclasses import dataclass, field, fields 

22from typing import Any, List, Literal, Optional 

23 

24from hyper_parallel.models.build_options import CompileConfig, FSDP2Config 

25from hyper_parallel.models.pipeline import PipelineConfig 

26from hyper_parallel.components.checkpoint.config import CheckpointingConfig 

27from hyper_parallel.high_availability.config import HighAvailabilityConfig 

28from hyper_parallel.components.ops.catalog import builtin_registry 

29 

30from hyper_parallel.trainer.config.data import DataLoaderConfig, DatasetConfig 

31from hyper_parallel.auto_parallel.hyper_offload.api.config import HyperOffloadConfig 

32from hyper_parallel.trainer.config.optimization import ( 

33 MixedPrecisionConfig, 

34 OptimizerConfig, 

35) 

36from hyper_parallel.trainer.config.parallelism import ( 

37 AcceleratorConfig, 

38 ActivationCheckpointConfig, 

39 PlanOverride, 

40) 

41from hyper_parallel.trainer.config.target import Target, _serialize_config_value 

42from hyper_parallel.trainer.config.stress_detect import StressDetectConfig 

43from hyper_parallel.trainer.config.training import ( 

44 DebugConfig, 

45 MemoryConfig, 

46 ModelIntegrationConfig, 

47 ProfilingConfig, 

48 TrainingConfig, 

49 WandbConfig, 

50) 

51 

52 

53@dataclass 

54class TrainerConfig: 

55 """Resolved component tree; runtime objects are built by the task trainer.""" 

56 

57 model: Target[Any] 

58 optimizer: OptimizerConfig 

59 

60 lr_scheduler: Optional[Target[Any]] = None 

61 loss_fn: Optional[Target[Any]] = None 

62 # Final floating-point dtype after model weights are loaded or initialized 

63 # from scratch. None preserves the dtype produced by the initialization path. 

64 model_init_dtype: Optional[Literal["float16", "bfloat16", "float32"]] = None 

65 training: TrainingConfig = field(default_factory=TrainingConfig) 

66 

67 # parallelism configs 

68 accelerator: AcceleratorConfig = field(default_factory=AcceleratorConfig) 

69 fsdp_config: FSDP2Config = field(default_factory=FSDP2Config) 

70 plan_overrides: List[PlanOverride] = field(default_factory=list) 

71 mixed_precision: MixedPrecisionConfig = field( 

72 default_factory=MixedPrecisionConfig 

73 ) 

74 activation_checkpoint: Optional[ActivationCheckpointConfig] = None 

75 hyper_offload: HyperOffloadConfig = field(default_factory=HyperOffloadConfig) 

76 compile: CompileConfig = field(default_factory=CompileConfig) 

77 

78 # data 

79 dataset: Optional[DatasetConfig] = None 

80 dataloader: Optional[DataLoaderConfig] = None 

81 packed_sequence: Optional[Any] = None 

82 

83 checkpoint: CheckpointingConfig = field(default_factory=CheckpointingConfig) 

84 high_availability: HighAvailabilityConfig = field(default_factory=HighAvailabilityConfig) 

85 debug: DebugConfig = field(default_factory=DebugConfig) 

86 model_integration: ModelIntegrationConfig = field(default_factory=ModelIntegrationConfig) 

87 memory: MemoryConfig = field(default_factory=MemoryConfig) 

88 wandb: WandbConfig = field(default_factory=WandbConfig) 

89 profiler: ProfilingConfig = field(default_factory=ProfilingConfig) 

90 stress_detect: StressDetectConfig = field(default_factory=StressDetectConfig) 

91 dry_run: Optional[Any] = None 

92 magi: Optional[Any] = None 

93 peft: Optional[Any] = None 

94 ops: dict[str, str] = field(default_factory=dict) 

95 pipeline: PipelineConfig = field(default_factory=PipelineConfig) 

96 

97 def _validate_hyper_offload(self) -> None: 

98 """Validate offload combinations with compilation, PP, and activation swapping.""" 

99 if not self.hyper_offload.enable: 

100 return 

101 if self.compile.enabled or self.accelerator.pp_size > 1: 

102 raise ValueError("hyper_offload requires eager training without pipeline parallelism") 

103 checkpoint = self.activation_checkpoint 

104 if (checkpoint is not None and checkpoint.mode in ("selective", "hybrid") 

105 and checkpoint.selective is not None and checkpoint.selective.swap_regions): 

106 raise ValueError("hyper_offload cannot be combined with activation swapping") 

107 

108 def _validate_pipeline(self) -> None: 

109 """Validate eager pipeline schedules, topology, and checkpoint export.""" 

110 graph_mode = self.compile.selects_graph_compiler() 

111 if self.compile.enabled and not graph_mode and self.accelerator.pp_size > 1: 

112 raise ValueError("compile is not supported together with pipeline parallelism") 

113 eager_pipeline = self.accelerator.pp_size > 1 and not graph_mode 

114 if self.pipeline.schedule in ("interleaved_1f1b", "mpipe") and not eager_pipeline: 

115 raise ValueError(f"{self.pipeline.schedule} requires eager Trainer PP with pp_size > 1") 

116 if self.pipeline.schedule == "mpipe" and (self.accelerator.tp_size != 1 or self.accelerator.cp_size != 1 

117 or self.accelerator.encoder_parallel.enabled): 

118 raise ValueError("MPipe VLM training requires TP1, CP1 and encoder_parallel disabled") 

119 if self.checkpoint.save_hf_weights and eager_pipeline: 

120 raise ValueError("HF export cannot gather eager pipeline stages. Use checkpoint.save_ckpt for DCP") 

121 

122 def __post_init__(self) -> None: 

123 """Validate combinations that span multiple config sections.""" 

124 builtin_registry.validate_selections(self.ops) 

125 if ( 

126 self.compile.enabled 

127 and not self.compile.selects_graph_compiler() 

128 and self.activation_checkpoint is not None 

129 and self.activation_checkpoint.mode != "off" 

130 ): 

131 raise ValueError( 

132 "compile.enabled=true is not supported with activation_checkpoint.mode=" 

133 f"{self.activation_checkpoint.mode}" 

134 ) 

135 self._validate_hyper_offload() 

136 self._validate_pipeline() 

137 reduce_dtype = self.fsdp_config.mix_precision.reduce_dtype 

138 if self.optimizer.fp32_main_params and reduce_dtype != "float32": 

139 raise ValueError( 

140 "optimizer.fp32_main_params=true requires " 

141 "fsdp_config.mix_precision.reduce_dtype='float32'; " 

142 f"got {reduce_dtype!r}" 

143 ) 

144 

145 def to_dict(self) -> dict[str, Any]: 

146 """Serialize the resolved trainer configuration for logging.""" 

147 return { 

148 config_field.name: _serialize_config_value( 

149 getattr(self, config_field.name) 

150 ) 

151 for config_field in fields(self) 

152 } 

153 

154 

155def save_configs(config: TrainerConfig, output_dir: str) -> None: 

156 """Accept trainer config persistence requests without writing files. 

157 

158 Args: 

159 config: Resolved trainer configuration. 

160 output_dir: Intended configuration output directory. 

161 """ 

162 del config, output_dir