Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / offline / data_config.py: 85%
106 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"""Normalize and validate offline Dataset build options."""
17from __future__ import annotations
19import re
20from collections.abc import Mapping, Sequence
21from dataclasses import dataclass, field
22from importlib import import_module
23from typing import Any
25import numpy as np
27from hyper_parallel.data.dataset_logging import get_dataset_logger
29logger = get_dataset_logger(__name__)
32@dataclass
33class BlendedMegatronDatasetConfig:
34 """Configuration shared by blended indexed datasets."""
36 random_seed: int
37 sequence_length: int
38 blend: list[str] | None = None
39 blend_per_split: list[list[str] | None] | None = None
40 split: str | None = None
41 split_matrix: list[tuple[float, float] | None] | None = field(init=False, default=None)
42 path_to_cache: str | None = None
43 mmap_bin_files: bool = True
44 mock: bool = False
45 tokenizer: Any = None
47 def __post_init__(self) -> None:
48 """Validate the configured data distribution and derive split ranges."""
49 if self.mock:
50 return
52 if self.blend_per_split is not None and any(self.blend_per_split):
53 if self.blend is not None:
54 raise ValueError("blend and blend_per_split are incompatible")
55 if self.split is not None:
56 raise ValueError("split and blend_per_split are incompatible")
57 if len(self.blend_per_split) != 3:
58 raise ValueError("blend_per_split must contain train, validation, and test blends")
59 return
61 if self.blend is None:
62 raise ValueError("one of either blend or blend_per_split must be provided")
63 if self.split is None:
64 raise ValueError("both blend and split must be provided")
66 # Parse at most three train/validation/test ratios, padding omitted
67 # trailing splits with zero before normalization.
68 split_values = [float(value) for value in re.findall(r"[.0-9]+", self.split)]
69 split_values.extend([0.0] * (3 - len(split_values)))
70 if len(split_values) != 3:
71 raise ValueError(f"split length {len(split_values)} does not match expected 3")
73 if not all(value >= 0.0 for value in split_values):
74 raise ValueError("all split values must be non-negative")
76 normalized_values = (np.asarray(split_values, dtype=np.float64) / np.sum(split_values)).tolist()
77 canonical_values = []
78 for value in normalized_values:
79 rounded_value = round(value, 12)
80 precision = 2 if rounded_value == round(rounded_value, 2) else 12
81 canonical_values.append(f"{rounded_value:.{precision}f}")
82 self.split = ", ".join(canonical_values)
84 # Convert normalized ratios into non-overlapping ranges. A zero-sized
85 # split is represented by None.
86 boundaries = [0.0]
87 for value in normalized_values:
88 boundaries.append(boundaries[-1] + value)
89 self.split_matrix = []
90 for begin, end in zip(boundaries[:-1], boundaries[1:]):
91 self.split_matrix.append(None if end <= begin else (begin, end))
94@dataclass
95class GPTDatasetConfig(BlendedMegatronDatasetConfig):
96 """Configuration required to build indexed GPT Dataset splits.
98 ``inter_document_masking`` preserves packed GPT document boundaries from
99 Indexed sequence lengths, including corpora without EOD tokens.
100 """
102 reset_position_ids: bool = False
103 reset_attention_mask: bool = False
104 eod_mask_loss: bool = False
105 create_ltor_fields: bool = False
106 inter_document_masking: bool = False
107 drop_last_partial_validation_sequence: bool = True
108 add_extra_token_to_sequence: bool = True
109 allow_ambiguous_pad_tokens: bool = False
110 dataset_margin: float = 1.005
111 skip_data_check: bool = False
112 reuse_idx: bool = False
113 data_lazy_load: bool = False
115 low_level_dataset: type | None = None
116 simple_blend: str | None = None
117 dataset_options: Mapping[str, Any] = field(default_factory=dict)
119 def __post_init__(self) -> None:
120 """Validate the blended Dataset fields followed by GPT-specific fields."""
121 super().__post_init__()
123 if self.low_level_dataset is None:
124 raise ValueError("low_level_dataset must be explicitly configured")
125 if self.simple_blend is None:
126 raise ValueError("simple_blend must be explicitly configured")
127 if self.sequence_length <= 0:
128 raise ValueError("sequence_length must be positive")
129 if self.tokenizer is None and not self.mock:
130 raise ValueError("Attribute 'tokenizer' must not be None")
133def build_gpt_dataset_config(
134 data_paths: Sequence[str],
135 data_config: Mapping[str, Any],
136) -> GPTDatasetConfig:
137 """Build a GPT Dataset config from provider fields.
139 Args:
140 data_paths: Weighted source paths discovered by the offline Dataset builder.
141 data_config: Indexed pretraining configuration supplied by the caller.
143 Returns:
144 Configuration required by GPT Dataset and split construction.
146 Raises:
147 ValueError: If a required build field is missing.
148 """
149 # The source argument parser owns defaults and validation. This stage only
150 # renames fields where the Dataset implementation expects another name.
151 blend_per_split = [
152 data_config.get("train_data_path"),
153 data_config.get("valid_data_path"),
154 data_config.get("test_data_path"),
155 ]
156 has_independent_blends = any(blend_per_split)
157 try:
158 mock_data = bool(data_config.get("mock_data", False))
159 tokenizer = data_config.get("tokenizer")
161 if tokenizer is None and not mock_data:
162 raise ValueError("tokenizer is required when mock_data is false")
164 config = GPTDatasetConfig(
165 random_seed=data_config["random_seed"],
166 sequence_length=data_config["max_seq_len"],
167 tokenizer=tokenizer,
168 mock=mock_data,
169 blend=None if has_independent_blends else list(data_paths),
170 blend_per_split=blend_per_split if has_independent_blends else None,
171 split=None if has_independent_blends else data_config.get("split", "1, 0, 0"),
172 path_to_cache=data_config.get("data_cache_path"),
173 mmap_bin_files=data_config.get("mmap_bin_files", True),
174 reuse_idx=data_config.get("reuse_idx", False),
175 data_lazy_load=data_config.get("data_lazy_load", False),
176 reset_position_ids=data_config.get("reset_position_ids", False),
177 reset_attention_mask=data_config.get("reset_attention_mask", False),
178 eod_mask_loss=data_config.get("eod_mask_loss", False),
179 create_ltor_fields=data_config.get("create_ltor_fields_in_dataloader", False),
180 inter_document_masking=data_config.get("inter_document_masking", False),
181 drop_last_partial_validation_sequence=data_config.get("drop_last_partial_validation_sequence", True),
182 add_extra_token_to_sequence=data_config.get("add_extra_token_to_sequence", True),
183 allow_ambiguous_pad_tokens=data_config.get("allow_ambiguous_pad_tokens", False),
184 dataset_margin=data_config.get("dataset_margin", 1.005),
185 skip_data_check=data_config.get("skip_data_check", False),
186 low_level_dataset=resolve_dataset_type(data_config["low_level_dataset"]),
187 dataset_options=(
188 {key: value for key, value in data_config["low_level_dataset"].items() if key != "_target_"}
189 if isinstance(data_config["low_level_dataset"], Mapping) else {}
190 ),
191 simple_blend=data_config["simple_blend"],
192 )
193 except KeyError as error:
194 raise ValueError(f"Missing indexed Dataset build option: {error.args[0]}") from error
195 source_paths = list(data_paths) if len(data_paths) <= 1 else list(data_paths[1::2])
196 logger.debug("Resolved indexed sources=%d, first four=%s", len(source_paths), source_paths[:4])
198 return config
201def resolve_dataset_type(spec: Mapping[str, Any] | type) -> type:
202 """Resolve an explicitly selected class without constructing a Dataset."""
203 if isinstance(spec, type):
204 return spec
205 if not isinstance(spec, Mapping) or "_target_" not in spec:
206 raise ValueError("low_level_dataset requires an explicit Dataset _target_")
207 module, _, name = spec["_target_"].rpartition(".")
208 dataset_type = getattr(import_module(module), name)
209 if not isinstance(dataset_type, type):
210 raise ValueError("low_level_dataset._target_ must identify a Dataset class")
211 return dataset_type