Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / config / data.py: 95%
62 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« 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"""Model-assets, dataset and dataloader configuration sections.
17Split from ``auto_models/trainer/config.py`` in stage 7 (05 §15.2.5);
18class names, fields and defaults are unchanged.
19"""
21from dataclasses import dataclass, field
22from typing import Any, ClassVar, Literal, Optional, Union
24from hyper_parallel.trainer.config.target import Target, _serialize_config_value
27@dataclass
28class ModelAssetsConfig:
29 """Tokenizer and chat-template configuration for text datasets."""
31 chat_template: Optional[Union[str, Target[Any]]] = None
32 chat_template_kwargs: dict[str, Any] = field(default_factory=dict)
33 tokenizer: Optional[Target[Any]] = None
36@dataclass
37class DatasetConfig:
38 """Dataset target with its model assets and sample transform."""
40 target: Target[Any]
41 model_assets: Union[ModelAssetsConfig, Target[Any]] = field(default_factory=ModelAssetsConfig)
42 data_transform: Optional[Target[Any]] = None
43 training_mode: Optional[Literal["sft", "pretrain"]] = None
45 def build(self, **runtime_kwargs: Any) -> Any:
46 """Build the Dataset target with runtime Trainer arguments."""
47 dataset = self.target.build(**runtime_kwargs)
48 return dataset
50 def __getattr__(self, name: str) -> Any:
51 """Expose configured Dataset options through the wrapped target."""
52 # __getattr__ runs for *missing* attributes. During copy/pickle
53 # reconstruction the instance dict is still empty, so probing
54 # "target" through normal attribute lookup would recurse forever.
55 target = self.__dict__.get("target")
56 if target is None:
57 raise AttributeError(name)
58 return getattr(target, name)
60 def to_dict(self) -> dict[str, Any]:
61 """Serialize Dataset components in their compact nested YAML shape."""
62 config = self.target.to_dict()
63 config["model_assets"] = _serialize_config_value(self.model_assets)
64 config["data_transform"] = _serialize_config_value(self.data_transform)
65 if self.training_mode is not None:
66 config["training_mode"] = self.training_mode
67 return config
70@dataclass
71class DataLoaderConfig:
72 """DataLoader target and its text-batch assembly components.
74 ``load_balance=None`` retains the native loader. A mapping, including an
75 empty one, enables distributed balancing with those configuration options.
76 """
78 internal_options: ClassVar[frozenset[str]] = frozenset({
79 "num_workers", "pin_memory", "prefetch_factor", "drop_last", "save_by_idx",
80 })
82 target: Target[Any]
83 collate_fn: Optional[Target[Any]] = None
84 get_batch: Optional[Target[Any]] = None
85 cost_model: Optional[Target[Any]] = None
86 balancing_algorithm: Optional[Target[Any]] = None
87 load_balance: Optional[dict[str, Any]] = None
88 sampler_type: Literal["single", "cyclic"] = "single"
89 data_rearrange_map: Any = None
90 data_sharding: bool = False
91 use_background_prefetcher: bool = False
93 def build(self, **runtime_kwargs: Any) -> Any:
94 """Build the DataLoader target with runtime Dataset arguments."""
95 return self.target.build(**runtime_kwargs)
97 def __getattr__(self, name: str) -> Any:
98 """Expose configured DataLoader options through the wrapped target."""
99 # See DatasetConfig.__getattr__: guard the not-yet-initialized state
100 # reached during copy/pickle reconstruction.
101 target = self.__dict__.get("target")
102 if target is None:
103 raise AttributeError(name)
104 return getattr(target, name)
106 def to_dict(self) -> dict[str, Any]:
107 """Serialize components in their compact nested YAML shape."""
108 # Constructor defaults must not become user options after a config round trip.
109 config = {name: value for name, value in self.target.to_dict().items() if name not in self.internal_options}
110 config["collate_fn"] = _serialize_config_value(self.collate_fn)
111 config["get_batch"] = _serialize_config_value(self.get_batch)
112 config["cost_model"] = _serialize_config_value(self.cost_model)
113 config["balancing_algorithm"] = _serialize_config_value(self.balancing_algorithm)
114 if self.load_balance is not None:
115 config["load_balance"] = _serialize_config_value(self.load_balance)
116 config["sampler_type"] = self.sampler_type
117 config["data_rearrange_map"] = _serialize_config_value(self.data_rearrange_map)
118 config["data_sharding"] = self.data_sharding
119 config["use_background_prefetcher"] = self.use_background_prefetcher
120 return config