Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / batching / packing.py: 59%
143 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"""Select and combine samples for multimodal packing."""
17from __future__ import annotations
19from abc import ABC, abstractmethod
20from collections.abc import Mapping, Sequence
21from typing import Any
23import torch
25from hyper_parallel.data.constants import DEFAULT_FIELD_PACK_DIMS, PACKING_METADATA_FIELDS
26from hyper_parallel.data.dataset_logging import get_dataset_logger
28logger = get_dataset_logger(__name__)
31class PackingSelector(ABC):
32 """Define the pre-packing seam over prepared sample metadata."""
34 @abstractmethod
35 def get_sample_cost(self, sample: Mapping[str, Any]) -> int:
36 """Return the scheduling cost retained with one candidate sample."""
37 raise NotImplementedError
39 @abstractmethod
40 def select_samples_to_pack(
41 self,
42 samples: Sequence[Mapping[str, Any]],
43 token_budget: int,
44 ) -> Sequence[int]:
45 """Return indices of candidates that form the next packed sequence."""
46 raise NotImplementedError
49class FirstFitPackingSelector(PackingSelector):
50 """Select candidates in source order until the token budget is full."""
52 def get_sample_cost(self, sample: Mapping[str, Any]) -> int:
53 """Use packing metadata without undercounting already encoded tokens."""
54 sample_cost = sample.get("packing_length")
56 if sample_cost is None:
57 sample_cost = self._get_input_length(sample)
59 resolved_cost = int(sample_cost)
61 if resolved_cost <= 0:
62 raise ValueError("Packing sample cost must be positive")
64 if sample.get("packing_length") is not None and sample.get("input_ids") is not None:
65 resolved_cost = max(resolved_cost, self._get_input_length(sample))
67 return resolved_cost
69 def select_samples_to_pack(
70 self,
71 samples: Sequence[Mapping[str, Any]],
72 token_budget: int,
73 ) -> Sequence[int]:
74 """Select the next ordered first-fit group from the candidate buffer."""
76 if not samples:
77 raise ValueError("Packing candidate buffer is empty")
79 selected_indices = []
80 selected_cost = 0
81 for sample_index, sample in enumerate(samples):
82 sample_cost = self.get_sample_cost(sample)
83 sample_fits = selected_cost + sample_cost <= token_budget
85 if sample_fits:
86 selected_indices.append(sample_index)
87 selected_cost += sample_cost
89 return selected_indices
91 @staticmethod
92 def _get_input_length(sample: Mapping[str, Any]) -> int:
93 """Derive sequence length from a fully encoded sample."""
94 if "input_ids" not in sample:
95 raise ValueError("Packing samples must provide packing_length or input_ids")
97 input_ids = sample["input_ids"]
98 input_shape = getattr(input_ids, "shape", None)
99 if input_shape is not None:
100 input_length = int(input_shape[-1])
101 return input_length
103 if not isinstance(input_ids, Sequence) or isinstance(input_ids, (str, bytes)):
104 raise TypeError("Packing input_ids must be a tensor or sequence")
106 input_length = len(input_ids)
107 if input_ids and isinstance(input_ids[0], Sequence):
108 input_length = len(input_ids[0])
109 return input_length
112class SamplePacker:
113 """Combine selected encoded samples into one packed sample."""
115 def __init__(self, field_pack_dims: Mapping[str, int] | None = None) -> None:
116 """Configure the concatenation dimension of model fields.
118 Args:
119 field_pack_dims: Optional additions or overrides to the default
120 token-last and modality-first field rules.
121 """
122 self.field_pack_dims = dict(DEFAULT_FIELD_PACK_DIMS)
123 if field_pack_dims is not None:
124 self.field_pack_dims.update(field_pack_dims)
126 def pack_selected_samples(
127 self,
128 samples: Sequence[Mapping[str, Any]],
129 ) -> Mapping[str, Any]:
130 """Concatenate one selected group and emit its sequence boundaries."""
131 if not samples:
132 raise ValueError("samples must contain at least one encoded model sample")
134 packed_sample = {}
135 sample_fields = set()
136 for sample in samples:
137 sample_fields.update(sample)
139 for field in sample_fields:
140 if field in PACKING_METADATA_FIELDS:
141 continue
143 if field.endswith("_token_starts"):
144 packed_sample[field] = self._pack_token_starts(field, samples)
145 continue
147 field_values = []
148 for sample in samples:
149 if field in sample:
150 field_values.append(sample[field])
152 packed_value = self._pack_field(field, field_values)
153 packed_sample[field] = packed_value
155 packed_sample["cu_seq_lens"] = self._build_sequence_boundaries(samples)
156 return packed_sample
158 def _pack_field(self, field: str, values: Sequence[Any]) -> Any:
159 """Pack one field using its configured or inferred leading dimension."""
160 if not values:
161 raise ValueError(f"Cannot pack empty field {field!r}")
163 pack_dim = self.field_pack_dims.get(field, 0)
164 if all(isinstance(value, torch.Tensor) for value in values):
165 packed_value = torch.cat(values, dim=pack_dim)
166 return packed_value
168 if field in self.field_pack_dims:
169 tensor_values = []
170 for value in values:
171 tensor_values.append(torch.as_tensor(value))
172 packed_value = torch.cat(tensor_values, dim=pack_dim)
173 return packed_value
175 if all(isinstance(value, Sequence) and not isinstance(value, (str, bytes)) for value in values):
176 packed_items = []
177 for value in values:
178 packed_items.extend(value)
179 return packed_items
181 if len(values) == 1:
182 return values[0]
184 raise TypeError(f"Field {field!r} requires a model-specific SamplePacker rule")
186 @staticmethod
187 def _pack_token_starts(
188 field: str,
189 samples: Sequence[Mapping[str, Any]],
190 ) -> torch.Tensor:
191 """Move sample-local modality starts into the packed token coordinate."""
192 packed_starts = []
193 sequence_offset = 0
194 for sample in samples:
195 if field in sample:
196 token_starts = torch.as_tensor(sample[field])
197 packed_starts.append(token_starts + sequence_offset)
199 input_ids = sample.get("input_ids")
201 if input_ids is None:
202 raise ValueError(f"Packing {field!r} requires input_ids in every sample")
204 sequence_offset += int(torch.as_tensor(input_ids).shape[-1])
206 if not packed_starts:
207 raise ValueError(f"Cannot pack empty field {field!r}")
209 packed_token_starts = torch.cat(packed_starts, dim=0)
210 return packed_token_starts
212 @staticmethod
213 def _build_sequence_boundaries(
214 samples: Sequence[Mapping[str, Any]],
215 ) -> torch.Tensor:
216 """Build cumulative text boundaries for packed attention isolation."""
217 cumulative_lengths = [0]
218 input_ids_reference = None
219 for sample in samples:
220 if "input_ids" not in sample:
221 raise ValueError("Every packed sample must contain input_ids")
223 input_ids = sample["input_ids"]
225 if input_ids_reference is None and isinstance(input_ids, torch.Tensor):
226 input_ids_reference = input_ids
228 input_shape = getattr(input_ids, "shape", None)
230 if input_shape is not None:
231 sequence_length = int(input_shape[-1])
232 else:
233 sequence_length = len(input_ids)
235 if sequence_length <= 0:
236 raise ValueError("Packed samples must contain at least one token")
238 sample_boundaries = sample.get("cu_seq_lens")
239 local_boundaries = ([0, sequence_length] if sample_boundaries is None
240 else torch.as_tensor(sample_boundaries).reshape(-1).tolist())
242 if not local_boundaries or local_boundaries[0] != 0 or local_boundaries[-1] != sequence_length:
243 raise ValueError("Sample cu_seq_lens must cover the complete input_ids")
245 sequence_offset = cumulative_lengths[-1]
246 cumulative_lengths.extend(sequence_offset + boundary for boundary in local_boundaries[1:])
248 if input_ids_reference is None:
249 sequence_boundaries = torch.tensor(cumulative_lengths, dtype=torch.int32)
250 else:
251 sequence_boundaries = input_ids_reference.new_tensor(
252 cumulative_lengths,
253 dtype=torch.int32,
254 )
256 return sequence_boundaries
259__all__ = ["FirstFitPackingSelector", "PackingSelector", "SamplePacker"]