Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / offline / blended_dataset.py: 91%

113 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"""Deterministic weighted and index-free Dataset blending.""" 

16 

17from __future__ import annotations 

18 

19import hashlib 

20import json 

21import os 

22from collections import OrderedDict 

23from collections.abc import Mapping, Sequence 

24from typing import Any, Literal 

25 

26import numpy as np 

27 

28from hyper_parallel.data.dataset_logging import get_dataset_logger 

29from hyper_parallel.data.offline.data_config import GPTDatasetConfig 

30from hyper_parallel.data.offline.helpers import build_blending_indices 

31 

32SimpleBlendMode = Literal["inter", "intra"] 

33 

34logger = get_dataset_logger(__name__) 

35 

36 

37class BlendedDataset: 

38 """Expose several Datasets through deterministic weighted sample indices.""" 

39 

40 def __init__( 

41 self, 

42 datasets: Sequence[Any], 

43 weights: Sequence[float], 

44 size: int, 

45 config: GPTDatasetConfig, 

46 ) -> None: 

47 """Validate the inputs and create weighted sample indices.""" 

48 if not datasets or len(datasets) != len(weights): 

49 raise ValueError("datasets and weights must be non-empty and have the same length") 

50 if len(datasets) >= np.iinfo(np.int16).max: 

51 raise ValueError("number of datasets must be less than 32767") 

52 if not all(isinstance(dataset, type(datasets[0])) for dataset in datasets): 

53 raise ValueError("all datasets must be of the same type") 

54 self.datasets = list(datasets) 

55 self.weights = _normalize_weights(weights) 

56 self.size = size 

57 self.config = config 

58 self.unique_identifiers = OrderedDict() 

59 self.unique_identifiers["class"] = type(self).__name__ 

60 self.unique_identifiers["datasets"] = self._collect_dataset_identifiers() 

61 self.unique_identifiers["weights"] = self.weights 

62 self.unique_identifiers["size"] = self.size 

63 self.unique_description = json.dumps( 

64 self.unique_identifiers, 

65 indent=4, 

66 default=lambda value: value.unique_identifiers, 

67 ) 

68 self.unique_description_hash = hashlib.md5( 

69 self.unique_description.encode("utf-8") 

70 ).hexdigest() 

71 self.dataset_index, self.dataset_sample_index = self._build_indices() 

72 

73 def _collect_dataset_identifiers(self) -> list[Any]: 

74 """Collect component Dataset cache identities.""" 

75 identifiers = [dataset.unique_identifiers for dataset in self.datasets] 

76 return identifiers 

77 

78 def __len__(self) -> int: 

79 """Return the requested blended sample count.""" 

80 return self.size 

81 

82 def __getitem__(self, index: int) -> Mapping[str, Any]: 

83 """Read one sample from the Dataset selected by the blend indices.""" 

84 dataset_id = int(self.dataset_index[index]) 

85 sample_id = int(self.dataset_sample_index[index]) 

86 sample = {"dataset_id": dataset_id, **self.datasets[dataset_id][sample_id]} 

87 return sample 

88 

89 def _build_indices(self) -> tuple[np.ndarray, np.ndarray]: 

90 """Load or build the top-level blend index cache.""" 

91 cache_directory = self.config.path_to_cache 

92 if cache_directory is None: 

93 logger.debug( 

94 "Building blended indices in memory: size=%d, sources=%d, weights are %s", 

95 self.size, len(self.weights), self.weights[:3], 

96 ) 

97 indices = self._build_indices_in_memory() 

98 return indices 

99 

100 cache_prefix = os.path.join( 

101 cache_directory, 

102 f"{self.unique_description_hash}-{type(self).__name__}", 

103 ) 

104 description_path = f"{cache_prefix}-description.txt" 

105 dataset_index_path = f"{cache_prefix}-dataset_index.npy" 

106 sample_index_path = f"{cache_prefix}-dataset_sample_index.npy" 

107 cache_paths = (description_path, dataset_index_path, sample_index_path) 

108 if all(os.path.isfile(path) for path in cache_paths): 

109 logger.debug("Loading blended index cache: prefix=%s", cache_prefix) 

110 dataset_index = np.load(dataset_index_path, allow_pickle=True, mmap_mode="r") 

111 sample_index = np.load(sample_index_path, allow_pickle=True, mmap_mode="r") 

112 return dataset_index, sample_index 

113 

114 dataset_index, sample_index = self._build_indices_in_memory() 

115 os.makedirs(cache_directory, exist_ok=True) 

116 with open(description_path, "w", encoding="utf-8") as description_file: 

117 description_file.write(self.unique_description) 

118 np.save(dataset_index_path, dataset_index, allow_pickle=True) 

119 np.save(sample_index_path, sample_index, allow_pickle=True) 

120 logger.debug("Saved blended index cache: prefix=%s", cache_prefix) 

121 return dataset_index, sample_index 

122 

123 def _build_indices_in_memory(self) -> tuple[np.ndarray, np.ndarray]: 

124 """Build a deterministic weighted source schedule.""" 

125 dataset_index = np.empty(self.size, dtype=np.int16) 

126 sample_index = np.empty(self.size, dtype=np.int64) 

127 build_blending_indices( 

128 dataset_index=dataset_index, 

129 dataset_sample_index=sample_index, 

130 weights=self.weights, 

131 ) 

132 requested_counts = np.bincount(dataset_index, minlength=len(self.datasets)) 

133 for dataset_id, requested_count in enumerate(requested_counts): 

134 dataset_size = len(self.datasets[dataset_id]) 

135 if requested_count > dataset_size: 

136 raise ValueError( 

137 f"Dataset {dataset_id} has only {dataset_size} samples, " 

138 f"but the blend requested {requested_count} samples" 

139 ) 

140 return dataset_index, sample_index 

141 

142 

143def _normalize_weights(weights: Sequence[float]) -> list[float]: 

144 """Validate and normalize positive blend weights.""" 

145 if not weights or any(weight <= 0.0 for weight in weights): 

146 raise ValueError("Dataset blend weights must be positive") 

147 weight_array = np.asarray(weights, dtype=np.float64) 

148 normalized_weights = (weight_array / np.sum(weight_array)).tolist() 

149 return normalized_weights 

150 

151 

152class SimpleBlendedDataset: 

153 """Blend equally weighted MR Datasets in interleaved or contiguous order.""" 

154 

155 def __init__( 

156 self, 

157 datasets: Sequence[Any], 

158 size: int, 

159 mode: SimpleBlendMode, 

160 ) -> None: 

161 """Validate the inputs and create the configured simple ordering.""" 

162 if not datasets: 

163 raise ValueError("simple blend requires at least one Dataset") 

164 self.datasets = list(datasets) 

165 self.size = size 

166 self.mode = mode 

167 self._locations = self._build_locations() 

168 if self.size > len(self._locations): 

169 raise ValueError( 

170 f"Requested {self.size} samples from a simple blend containing " 

171 f"{len(self._locations)} samples" 

172 ) 

173 

174 def __len__(self) -> int: 

175 """Return the requested blended sample count.""" 

176 return self.size 

177 

178 def __getitem__(self, index: int) -> Mapping[str, Any]: 

179 """Read one MR sample in interleaved or Dataset-contiguous order.""" 

180 dataset_id, sample_id = self._locations[index] 

181 sample = {"dataset_id": dataset_id, **self.datasets[dataset_id][sample_id]} 

182 return sample 

183 

184 def _build_locations(self) -> list[tuple[int, int]]: 

185 """Map blend positions to Dataset and sample indices.""" 

186 if self.mode == "intra": 

187 locations = [ 

188 (dataset_id, sample_id) 

189 for dataset_id, dataset in enumerate(self.datasets) 

190 for sample_id in range(len(dataset)) 

191 ] 

192 return locations 

193 

194 # mode = inter 

195 locations = self._build_interleaved_locations() 

196 return locations 

197 

198 def _build_interleaved_locations(self) -> list[tuple[int, int]]: 

199 """Alternate over non-empty Datasets until every sample is exposed.""" 

200 max_size = max(len(dataset) for dataset in self.datasets) 

201 locations = [] 

202 for sample_id in range(max_size): 

203 for dataset_id, dataset in enumerate(self.datasets): 

204 if sample_id < len(dataset): 

205 locations.append((dataset_id, sample_id)) 

206 return locations