Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/data/batching/attention_runtime.py 0.0% 23,55,67
hyper_parallel/data/batching/build_collate_fn.py 0.0% 24,89,96-97,109-111
hyper_parallel/data/batching/get_batch.py 0.0% 22,242,270
hyper_parallel/data/batching/sequence_boundaries.py 0.0% 22,38,65,93
hyper_parallel/data/dataset_logging.py 38.0% 37-41,54-61,69-70,83-90,110-112,114-115,117-118,120,122-134
hyper_parallel/data/indexed/indexed_blended_dataset.py 0.0% 17,19-24,26,28-30,32,35,38,46-61,66,69,71,73-74,76,78,80,82-85,87,89-91,95-96,98,102-110,112-119,121,123-125,130-134,138,141,143-147
hyper_parallel/data/indexed/indexed_data_config.py 0.0% 27,148,155,183-184
hyper_parallel/data/indexed/indexed_data_reader.py 0.0% 17,19-23,25,27-28,30-32,44,47,50-53,55-57,59-61,63-65,70-72,76,80,86-87,89,91-94,96,98,100-101,103,106,116,118,120-126,128,135-139,141-146,148-150,152-157,164,166,168,170-171,173,175-178,180,182,184,186,188-190,193,195-200,202-204,208-209,211,213,215-216,218-219,221,223,225-226,228,230,241-246,250-252,254-257,259-261,263,265-266,268,270-271,273,275,277,279,281,283,285-287
hyper_parallel/data/indexed/indexed_lazy_dataset.py 0.0% 17,19-20,22,24,27,30,44-46,48,50,52,54-56,58-59,61,63,65-67,72-73
hyper_parallel/data/indexed/indexed_simple_blended_dataset.py 0.0% 17,19-20,22,25,28,35-42,47,49,51,53-55,57,59-60,65,68-69,71,73-74,80
hyper_parallel/data/parallel/batch_parallel.py 20.0% 220,267,282,288,291,302,306,310
hyper_parallel/data/parallel/batch_sampler.py 18.6% 37-38,63-68,70-80,82-84,88-89,93-99,101-105,107,111,115-119,123-124,126-128,130-131,135,141,145,156-160,162,164-166,168,172,174-175,177-178,189-190,192-194,202-204,206-207,211-212,214,218-220,224-226,228,234,236-241,244-247,249-255,259-261,263,271-272,274-280,330-331,337,348,352-353,355,358-359,361,366,368
hyper_parallel/data/parallel/dataloader_parallel.py 33.3% 77,104
hyper_parallel/data/text/build_data_transform.py 0.0% 24,26-28,30,32,34-35,38-47,50,53,60-61,63,65,68-69,72-74,76,78-81,83,85-89,91-94,98-99,102-103,106-108,110,112-115,117,119-123,127,130,147-150,152-154
hyper_parallel/data/text/chat_template.py 91.8% 78,80,86,90,128-129,134,157,173,330,356-358,378,413,468,545,590
hyper_parallel/data/text/online/online_dataset.py 0.0% 17,19-20,22-25,27,29,35,54-59,62-63,68-69
hyper_parallel/data/text/online/online_iterable_dataset.py 0.0% 17,19-20,22-23,27,33,36,53,55,58,64-69,73,75,77-78,83,85,91
hyper_parallel/data/text/online/online_mapping_dataset.py 0.0% 17,19-21,23-25,29,34,37,40,42,44,46,48,50-54,57,73-75,80,82,87-89,91,98
hyper_parallel/data/vlm/get_batch.py 0.0% 20
hyper_parallel/data/batching/attention_runtime.py
19
20
21
22
23
24
25
26
27
from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import Any

import torch


def build_dense_attention_masks(
        *,
51
52
53
54
55
56
57
58
59
        )

    # Attention mask (lower triangular).
    att_mask_batch = micro_batch_size if reset_attention_mask else 1
    attention_mask = torch.ones((att_mask_batch, seq_length, seq_length), dtype=torch.bool, device=device).tril()
    attention_mask = attention_mask.view(att_mask_batch, 1, seq_length, seq_length)

    if reset_attention_mask:
        for seq_start in boundaries[:-1]:
63
64
65
66
67
68
69
70
71
            attention_mask[batch_idx, 0, row_seq_start:, :row_seq_start] = False

    swa_mask = None
    if sliding_window is not None:
        positions = torch.arange(seq_length, dtype=torch.int64, device=device)
        query_positions = positions.unsqueeze(1)
        key_positions = positions.unsqueeze(0)
        token_distance = query_positions - key_positions
        outside_window = token_distance > sliding_window
hyper_parallel/data/batching/build_collate_fn.py
20
21
22
23
24
25
26
27
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any

import torch
from torch.utils.data import default_collate

from hyper_parallel.data.constants import IGNORE_INDEX
85
86
87
88
89
90
91
92
93

        packed_batch = {}
        for field in ("input_ids", "labels"):
            values = [model_sample[field] for model_sample in model_samples]
            packed_batch[field] = torch.cat(values, dim=-1).unsqueeze(0)

        packed_seq_len = packed_batch["input_ids"].shape[-1]
        pad_len = (-packed_seq_len) % self.sequence_parallel_size
        if pad_len:
 92
 93
 94
 95
 96
 97
 98
 99
100
101
        pad_len = (-packed_seq_len) % self.sequence_parallel_size
        if pad_len:
            input_padding = packed_batch["input_ids"].new_zeros((1, pad_len))
            label_padding = packed_batch["labels"].new_full((1, pad_len), IGNORE_INDEX)
            packed_batch["input_ids"] = torch.cat((packed_batch["input_ids"], input_padding), dim=-1)
            packed_batch["labels"] = torch.cat((packed_batch["labels"], label_padding), dim=-1)

        seq_lens = model_samples[0]["input_ids"].new_tensor(
            [model_sample["input_ids"].shape[-1] for model_sample in model_samples]
        )
105
106
107
108
109
110
111
112
113
114
            # Represent the alignment tail as one synthetic packed sequence so
            # attention metadata covers every physical Q/KV token. Its labels
            # remain IGNORE_INDEX and therefore do not contribute to the loss.
            padded_end = seq_ends[-1:] + pad_len
            seq_ends = torch.cat((seq_ends, padded_end))
        cu_seq_lens = torch.cat((zero, seq_ends))
        cu_seq_lens = cu_seq_lens.to(torch.int32)
        packed_batch["cu_seq_lens"] = cu_seq_lens

        return packed_batch
hyper_parallel/data/batching/get_batch.py
18
19
20
21
22
23
24
25
26

from collections.abc import Mapping
from typing import Any

import torch

from hyper_parallel.data.batching.attention_runtime import (
    AttentionRuntimeAdapter,
    build_dense_attention_masks,
238
239
240
241
242
243
244
245
        cp_seq_end = cp_seq_start + local_seq_len

        # This produces the same values as building global [B, S] positions
        # and then taking the CP slice, without allocating the global tensor.
        position_ids = torch.arange(
            cp_seq_start, cp_seq_end, dtype=torch.int64, device=input_ids.device
        )
        local_position_ids = position_ids.unsqueeze(0).expand(batch_size, -1)
266
267
268
269
270
271
272
273
274
        return local_position_ids

    def _build_loss_mask(self, parallel_batch: Mapping[str, Any]) -> Any:
        """Build the local loss mask from labels and input IDs."""
        loss_mask = (parallel_batch["labels"] >= 0).to(dtype=torch.int64)

        if self.eod_mask_loss:
            eod_token_id = getattr(self.tokenizer, "eod", None)
            loss_mask = loss_mask.masked_fill(parallel_batch["input_ids"] == eod_token_id, 0)
hyper_parallel/data/batching/sequence_boundaries.py
18
19
20
21
22
23
24
25
26

from collections.abc import Mapping
from typing import Any

import torch


class OnlineBoundaryResolver:
    """Read global cumulative sequence boundaries emitted by Online packing."""
34
35
36
37
38
39
40
41
        Returns:
            Global int32 cumulative sequence boundaries.
        """
        raw_cu_seq_lens = canonical_batch["cu_seq_lens"]
        cu_seq_lens = raw_cu_seq_lens.to(torch.int32)

        return cu_seq_lens

61
62
63
64
65
66
67
68
69
            Global int32 cumulative sequence boundaries.
        """
        input_ids = canonical_batch["input_ids"]
        batch_size, seq_len = input_ids.shape
        token_indices = torch.arange(seq_len, dtype=input_ids.dtype, device=input_ids.device)

        # Collect flattened, nonzero cumulative sequence ends. A leading zero
        # is prepended below to form ``cu_seq_lens``.
        seq_ends = []
89
90
91
92
93
94
95
            if not seq_ends or seq_ends[-1] != row_end:
                seq_ends.append(row_end)

        # Packed attention uses the standard leading-zero cumulative form.
        cu_seq_lens = torch.tensor([0, *seq_ends], dtype=torch.int32)

        return cu_seq_lens
hyper_parallel/data/dataset_logging.py
33
34
35
36
37
38
39
40
41
42
43
44
45
_DATASET_DATE_FORMAT = "%Y-%m-%d %H:%M:%S.%f"


def _get_rank() -> int:
    try:
        rank = int(dist.get_rank())
    except (RuntimeError, ValueError):
        rank = 0
    return rank


class _DatasetDebugRankFilter(logging.Filter):
    """Filter Dataset DEBUG records by distributed rank."""
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
        self.ranks: frozenset[int] | None = frozenset({0})

    def filter(self, record: logging.LogRecord) -> bool:
        """Keep regular logs and Dataset DEBUG logs from selected ranks."""
        rank = _get_rank()
        record.rank_id = rank
        if record.levelno != logging.DEBUG or not record.name.startswith(_DATASET_LOGGER_NAME):
            return True
        rank_enabled = getattr(record, "dataset_rank_enabled", None)
        if rank_enabled is not None:
            return bool(rank_enabled)
        return self.ranks is None or rank in self.ranks


class _DatasetLogFormatter(logging.Formatter):
    """Format Dataset log timestamps with microsecond precision."""
65
66
67
68
69
70
71
72
73
    """Format Dataset log timestamps with microsecond precision."""

    def formatTime(self, record: logging.LogRecord, datefmt: str | None = None) -> str:  # pylint: disable=C0103
        """Format a log record timestamp in local time."""
        record_time = datetime.fromtimestamp(record.created).astimezone()
        return record_time.strftime(datefmt) if datefmt else record_time.isoformat(timespec="microseconds")


_DEBUG_RANK_FILTER = _DatasetDebugRankFilter()
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
    def debug(self, msg: object, *args: object, **kwargs: Any) -> None:
        """Log on default ranks, or on ranks selected by ``enabled`` when provided."""
        if not self.isEnabledFor(logging.DEBUG):
            return
        enabled: RankCondition | None = kwargs.pop("enabled", None)
        if enabled is not None:
            rank_enabled = enabled() if callable(enabled) else enabled
            extra = dict(kwargs.get("extra", {}))
            extra["dataset_rank_enabled"] = rank_enabled
            kwargs["extra"] = extra
        kwargs.setdefault("stacklevel", 2)
        self.logger.debug(msg, *args, **kwargs)


def get_dataset_logger(name: str) -> DatasetLogger:
    """Return a Dataset logger supporting the ``enabled`` DEBUG argument."""
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134

    Raises:
        ValueError: If ``level`` is unsupported, or ``ranks`` is invalid.
    """
    log_levels = {"debug": logging.DEBUG, "info": logging.INFO, "warn": logging.WARNING}
    if level not in log_levels:
        raise ValueError(f"Unsupported Dataset log level: {level!r}")

    if ranks is None:
        selected_ranks = None
    else:
        selected_ranks = frozenset(ranks)
        if not selected_ranks or any(isinstance(rank, bool) or not isinstance(rank, int) or rank < 0
                                     for rank in selected_ranks):
            raise ValueError("ranks must contain non-negative integers, or be None for all ranks")

    _DEBUG_RANK_FILTER.ranks = selected_ranks
    dataset_logger = logging.getLogger(_DATASET_LOGGER_NAME)
    dataset_logger.setLevel(log_levels[level])
    dataset_logger.propagate = False
    dataset_handlers = [handler for handler in dataset_logger.handlers if _DEBUG_RANK_FILTER in handler.filters]
    if not dataset_handlers:
        dataset_handler = logging.StreamHandler()
        dataset_handler.setFormatter(_DatasetLogFormatter(_DATASET_LOG_FORMAT, datefmt=_DATASET_DATE_FORMAT))
        dataset_handler.addFilter(_DEBUG_RANK_FILTER)
        dataset_logger.addHandler(dataset_handler)
        dataset_handlers.append(dataset_handler)
    for dataset_handler in dataset_handlers:
        dataset_handler.setLevel(log_levels[level])
hyper_parallel/data/indexed/indexed_blended_dataset.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# limitations under the License.
# ============================================================================
"""Standard deterministic weighted Dataset blending."""

from __future__ import annotations

import hashlib
import json
import os
from collections import OrderedDict
from collections.abc import Mapping, Sequence
from typing import Any

import numpy as np

from hyper_parallel.data.dataset_logging import get_dataset_logger
from hyper_parallel.data.indexed.indexed_data_config import GPTDatasetConfig
from hyper_parallel.data.indexed.indexed_helpers import build_blending_indices

logger = get_dataset_logger(__name__)


class BlendedDataset:
    """Expose several Datasets through deterministic weighted sample indices."""

    def __init__(
            self,
            datasets: Sequence[Any],
            weights: Sequence[float],
            size: int,
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
            size: int,
            config: GPTDatasetConfig,
    ) -> None:
        """Validate the inputs and create weighted sample indices."""
        if not datasets or len(datasets) != len(weights):
            raise ValueError("datasets and weights must be non-empty and have the same length")
        if len(datasets) >= np.iinfo(np.int16).max:
            raise ValueError("number of datasets must be less than 32767")
        if not all(isinstance(dataset, type(datasets[0])) for dataset in datasets):
            raise ValueError("all datasets must be of the same type")
        self.datasets = list(datasets)
        self.weights = _normalize_weights(weights)
        self.size = size
        self.config = config
        self.unique_identifiers = OrderedDict()
        self.unique_identifiers["class"] = type(self).__name__
        self.unique_identifiers["datasets"] = self._collect_dataset_identifiers()
        self.unique_identifiers["weights"] = self.weights
        self.unique_identifiers["size"] = self.size
        self.unique_description = json.dumps(
            self.unique_identifiers,
            indent=4,
            default=lambda value: value.unique_identifiers,
        )
        self.unique_description_hash = hashlib.md5(
            self.unique_description.encode("utf-8")
        ).hexdigest()
        self.dataset_index, self.dataset_sample_index = self._build_indices()

    def _collect_dataset_identifiers(self) -> list[Any]:
        """Collect component Dataset cache identities."""
        identifiers = [dataset.unique_identifiers for dataset in self.datasets]
        return identifiers

    def __len__(self) -> int:
        """Return the requested blended sample count."""
        return self.size

    def __getitem__(self, index: int) -> Mapping[str, Any]:
        """Read one sample from the Dataset selected by the blend indices."""
        dataset_id = int(self.dataset_index[index])
        sample_id = int(self.dataset_sample_index[index])
        sample = {"dataset_id": dataset_id, **self.datasets[dataset_id][sample_id]}
        return sample

    def _build_indices(self) -> tuple[np.ndarray, np.ndarray]:
        """Load or build the top-level blend index cache."""
        cache_directory = self.config.path_to_cache
        if cache_directory is None:
            logger.debug(
                "Building blended indices in memory: size=%d, sources=%d, weights are %s",
                self.size, len(self.weights), self.weights[:3],
            )
            indices = self._build_indices_in_memory()
            return indices

        cache_prefix = os.path.join(
            cache_directory,
            f"{self.unique_description_hash}-{type(self).__name__}",
        )
        description_path = f"{cache_prefix}-description.txt"
        dataset_index_path = f"{cache_prefix}-dataset_index.npy"
        sample_index_path = f"{cache_prefix}-dataset_sample_index.npy"
        cache_paths = (description_path, dataset_index_path, sample_index_path)
        if all(os.path.isfile(path) for path in cache_paths):
            logger.debug("Loading blended index cache: prefix=%s", cache_prefix)
            dataset_index = np.load(dataset_index_path, allow_pickle=True, mmap_mode="r")
            sample_index = np.load(sample_index_path, allow_pickle=True, mmap_mode="r")
            return dataset_index, sample_index

        dataset_index, sample_index = self._build_indices_in_memory()
        os.makedirs(cache_directory, exist_ok=True)
        with open(description_path, "w", encoding="utf-8") as description_file:
            description_file.write(self.unique_description)
        np.save(dataset_index_path, dataset_index, allow_pickle=True)
        np.save(sample_index_path, sample_index, allow_pickle=True)
        logger.debug("Saved blended index cache: prefix=%s", cache_prefix)
        return dataset_index, sample_index

    def _build_indices_in_memory(self) -> tuple[np.ndarray, np.ndarray]:
        """Build a deterministic weighted source schedule."""
        dataset_index = np.empty(self.size, dtype=np.int16)
        sample_index = np.empty(self.size, dtype=np.int64)
        build_blending_indices(
            dataset_index=dataset_index,
            dataset_sample_index=sample_index,
            weights=self.weights,
        )
        requested_counts = np.bincount(dataset_index, minlength=len(self.datasets))
        for dataset_id, requested_count in enumerate(requested_counts):
            dataset_size = len(self.datasets[dataset_id])
            if requested_count > dataset_size:
                raise ValueError(
                    f"Dataset {dataset_id} has only {dataset_size} samples, "
                    f"but the blend requested {requested_count} samples"
                )
        return dataset_index, sample_index


def _normalize_weights(weights: Sequence[float]) -> list[float]:
    """Validate and normalize positive blend weights."""
    if not weights or any(weight <= 0.0 for weight in weights):
        raise ValueError("Dataset blend weights must be positive")
    weight_array = np.asarray(weights, dtype=np.float64)
    normalized_weights = (weight_array / np.sum(weight_array)).tolist()
    return normalized_weights
hyper_parallel/data/indexed/indexed_data_config.py
23
24
25
26
27
28
29
30
31
from typing import Any

import numpy as np

import torch.distributed as dist

from hyper_parallel.data.dataset_logging import get_dataset_logger

logger = get_dataset_logger(__name__)
144
145
146
147
148
149
150
151
152
                top_files.append(os.path.splitext(path)[0])
        root_layout = (subdirectories, top_files)

    gathered_layouts: list[tuple[list[str], list[str]] | None] = [None] * world_size
    dist.all_gather_object(gathered_layouts, root_layout)
    rank_zero_layout = gathered_layouts[0]
    if rank_zero_layout is None:
        raise ValueError("Rank 0 did not provide the indexed directory layout")
    subdirectories, file_paths = rank_zero_layout
151
152
153
154
155
156
157
158
159
        raise ValueError("Rank 0 did not provide the indexed directory layout")
    subdirectories, file_paths = rank_zero_layout
    local_files = _walk_bin_directories(subdirectories[rank::world_size])
    gathered_files: list[list[str] | None] = [None] * world_size
    dist.all_gather_object(gathered_files, local_files)
    for rank_files in gathered_files:
        if rank_files:
            file_paths.extend(rank_files)
    return file_paths
179
180
181
182
183
184
185
186
187

    # 2. Use distributed walking only after the process group is available.
    # Before initialization, one process walks all configured directories.
    try:
        rank = int(dist.get_rank())
        world_size = int(dist.get_world_size())
    except (RuntimeError, ValueError):
        rank, world_size = 0, 1
    use_distributed_walk = distributed_walk and world_size > 1
hyper_parallel/data/indexed/indexed_data_reader.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# limitations under the License.
# ============================================================================
"""Read token sequences from paired ``.idx/.bin`` files."""

from __future__ import annotations

import os
import struct
import time
from functools import lru_cache
from typing import ClassVar

import numpy as np

from hyper_parallel.data.dataset_logging import get_dataset_logger
logger = get_dataset_logger(__name__)

_INDEX_HEADER = b"MMIDIDX\x00\x00"
_INDEX_VERSION = 1
_DTYPES = {
    1: np.uint8,
    2: np.int8,
    3: np.int16,
    4: np.int32,
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    8: np.uint16,
}


class _IndexReader:
    """Memory-map the compact sequence metadata stored in an index file."""

    def __init__(self, idx_path: str) -> None:
        """Parse and memory-map one index metadata file."""
        # Read the fixed-size header, which describes how the following index arrays are decoded.
        with open(idx_path, "rb") as stream:
            header = stream.read(len(_INDEX_HEADER))
            if header != _INDEX_HEADER:
                raise ValueError(f"Invalid indexed Dataset header in {idx_path!r}")

            version = struct.unpack("<Q", stream.read(8))[0]
            if version != _INDEX_VERSION:
                raise ValueError(f"Unsupported indexed Dataset version {version}; expected {_INDEX_VERSION}")

            dtype_code = struct.unpack("<B", stream.read(1))[0]
            self.dtype = np.dtype(_DTYPES[dtype_code])
            self.dtype_size = self.dtype.itemsize

            self.sequence_count = struct.unpack("<Q", stream.read(8))[0]
            self.document_count = struct.unpack("<Q", stream.read(8))[0]
            offset = stream.tell()

        # Map the three arrays stored after the header: token count per sequence, byte offset in .bin per sequence,
        # and sequence boundaries per document. The first two arrays have sequence_count entries, while the last
        # has document_count entries.
        self.bin_buffer_mmap = np.memmap(idx_path, mode="r", order="C")
        self.bin_buffer = memoryview(self.bin_buffer_mmap)
        self.sequence_lengths = np.frombuffer(
            self.bin_buffer, dtype=np.int32, count=self.sequence_count, offset=offset,
        )

        self.sequence_pointers = np.frombuffer(
            self.bin_buffer, dtype=np.int64, count=self.sequence_count, offset=offset + self.sequence_lengths.nbytes,
        )

        self.document_indices = np.frombuffer(
            self.bin_buffer, dtype=np.int64, count=self.document_count,
            offset=offset + self.sequence_lengths.nbytes + self.sequence_pointers.nbytes,
        )
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
            offset=offset + self.sequence_lengths.nbytes + self.sequence_pointers.nbytes,
        )

        # Each document is a half-open sequence range; the final boundary must equal the sequence count.
        if self.document_indices.size == 0 or self.document_indices[-1] != self.sequence_count:
            raise ValueError("Indexed Dataset document boundaries do not match its sequence count")

    def __del__(self) -> None:
        """Close the index metadata mmap when it is no longer referenced."""
        bin_buffer_mmap = getattr(self, "bin_buffer_mmap", None)
        mmap_handle = getattr(bin_buffer_mmap, "_mmap", None)
        if mmap_handle is not None:
            mmap_handle.close()

    def __len__(self) -> int:
        """Return the number of indexed sequences."""
        return self.sequence_count

    @lru_cache(maxsize=8)
    def __getitem__(self, index: int | np.integer) -> tuple[np.int64, np.int32]:
        """Return the byte pointer and token length of one sequence."""
        return self.sequence_pointers[index], self.sequence_lengths[index]


class IndexedDataReader:
    """Read individual token sequences from a paired ``.idx/.bin`` Dataset.

    Args:
        path_prefix: Dataset path without the ``.idx`` or ``.bin`` suffix.
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        reuse_index: Whether to reuse the first loaded index metadata. This
            matches corpora whose shards share an identical index layout.
    """

    cached_index_reader: ClassVar[_IndexReader | None] = None

    def __init__(self, path_prefix: str, mmap: bool = True, reuse_index: bool = False) -> None:
        """Open the index metadata and token payload files."""
        self.path_prefix = ""
        self.mmap = False
        self.reuse_index = reuse_index
        self.index: _IndexReader | None = None
        self.bin_buffer_mmap: np.memmap | None = None
        self.bin_buffer: memoryview | None = None
        self.initialize(path_prefix, mmap)

    def initialize(self, path_prefix: str, mmap: bool) -> None:
        """Open the index metadata and token payload.

        Args:
            path_prefix: Dataset path without the ``.idx`` or ``.bin`` suffix.
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
        Args:
            path_prefix: Dataset path without the ``.idx`` or ``.bin`` suffix.
            mmap: Whether to memory-map the token payload.
        """
        start_time = time.time()
        index_path = path_prefix + ".idx"
        data_path = path_prefix + ".bin"
        if not os.path.isfile(index_path) or not os.path.isfile(data_path):
            raise FileNotFoundError(f"Expected indexed Dataset files {index_path!r} and {data_path!r}")

        self.path_prefix = path_prefix
        self.mmap = mmap
        reused_cached_index = self.reuse_index and IndexedDataReader.cached_index_reader is not None
        if self.index is None:
            if reused_cached_index:
                self.index = IndexedDataReader.cached_index_reader
            else:
                self.index = _IndexReader(index_path)
                if self.reuse_index:
                    IndexedDataReader.cached_index_reader = self.index

        self.bin_buffer_mmap = None
        self.bin_buffer = None
        if mmap:
            self.bin_buffer_mmap = np.memmap(data_path, mode="r", order="C")
            self.bin_buffer = memoryview(self.bin_buffer_mmap)
        logger.debug(
            "Opened indexed Dataset: sequences=%d, documents=%d, dtype=%s, mmap=%s, prefix=%s, "
            "reused_index=%s, elapsed=%.4f seconds",
            len(self.index), self.index.document_indices.size - 1, self.index.dtype, mmap, path_prefix,
            reused_cached_index, time.time() - start_time,
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
            len(self.index), self.index.document_indices.size - 1, self.index.dtype, mmap, path_prefix,
            reused_cached_index, time.time() - start_time,
        )

    def __getstate__(self) -> tuple[str, bool, bool]:
        """Serialize construction inputs instead of open mmap resources."""
        return self.path_prefix, self.mmap, self.reuse_index

    def __setstate__(self, state: tuple[str, bool, bool]) -> None:
        """Reopen index and data resources inside a DataLoader worker."""
        path_prefix, mmap, reuse_index = state
        self.__init__(path_prefix, mmap=mmap, reuse_index=reuse_index)

    def __del__(self) -> None:
        """Close the token mmap when this reader is released."""
        bin_buffer_mmap = getattr(self, "bin_buffer_mmap", None)
        mmap_handle = getattr(bin_buffer_mmap, "_mmap", None)
        if mmap_handle is not None:
            mmap_handle.close()

    def __len__(self) -> int:
        """Return the number of indexed token sequences."""
        return len(self._require_index())

    def _getitem_mmap(self, index: int | np.integer | slice) -> np.ndarray | list[np.ndarray]:
        """Return one sequence or a contiguous sequence slice from the mapped token payload."""
        index_reader = self._require_index()

        if isinstance(index, (int, np.integer)):
            sequence_pointer, sequence_length = index_reader[index]
            sequence = np.frombuffer(
                self.bin_buffer, dtype=index_reader.dtype, count=sequence_length, offset=sequence_pointer
            )
            return sequence

        if isinstance(index, slice):
            start, stop, step = index.indices(len(self))
            if step != 1:
                raise ValueError("Slices into indexed Dataset must be contiguous")
            if start == stop:
                return []

            sequence_lengths = index_reader.sequence_lengths[index]
            sequence_offsets = np.cumsum(sequence_lengths)
            sequences = np.frombuffer(
                self.bin_buffer, dtype=index_reader.dtype, count=int(sequence_lengths.sum()),
                offset=int(index_reader.sequence_pointers[start]),
            )
            sequences = np.split(sequences, sequence_offsets[:-1])
            return sequences

        raise TypeError(f"Indexed Dataset indices must be integers or slices, got {type(index).__name__}")

    def _getitem_file(self, index: int | np.integer | slice) -> np.ndarray:
        """Return one sequence through direct file reading when mmap is disabled."""
        if isinstance(index, slice):
            raise NotImplementedError("Slicing is not implemented when mmap is disabled")

        if not isinstance(index, (int, np.integer)):
            raise TypeError(f"Indexed Dataset indices must be integers or slices, got {type(index).__name__}")

        return self.get(int(index))

    def __getitem__(self, index: int | np.integer | slice) -> np.ndarray | list[np.ndarray]:
        """Return one sequence, or a contiguous slice when mmap is enabled."""
        if self.bin_buffer is not None:
            return self._getitem_mmap(index)

        return self._getitem_file(index)

    def get(self, index: int, offset: int = 0, length: int | None = None) -> np.ndarray:
        """Read a contiguous token range from one sequence.

        Args:
            index: Sequence index.
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287

        Returns:
            A NumPy view of the requested tokens.
        """
        index_reader = self._require_index()
        sequence_pointer, sequence_length = index_reader[index]
        sequence_length = int(sequence_length)
        read_length = sequence_length - offset if length is None else length
        if offset < 0 or read_length < 0 or offset + read_length > sequence_length:
            raise ValueError(
                f"Token range [{offset}, {offset + read_length}) exceeds sequence length {sequence_length}"
            )

        byte_offset = int(sequence_pointer) + offset * index_reader.dtype.itemsize
        if self.bin_buffer:
            sequence = np.frombuffer(self.bin_buffer, dtype=index_reader.dtype, count=read_length, offset=byte_offset)
        else:
            sequence = np.empty(read_length, dtype=index_reader.dtype)
            with open(self.path_prefix + ".bin", mode="rb", buffering=0) as bin_buffer_file:
                bin_buffer_file.seek(byte_offset)
                bytes_read = bin_buffer_file.readinto(sequence)

            byte_length = read_length * index_reader.dtype.itemsize
            if bytes_read != byte_length:
                raise ValueError(f"Indexed Dataset read returned {bytes_read} bytes; expected {byte_length}")

        return sequence

    @property
    def sequence_lengths(self) -> np.ndarray:
        """Return the token length of every indexed sequence."""
        return self._require_index().sequence_lengths

    @property
    def document_indices(self) -> np.ndarray:
        """Return sequence indices that delimit documents."""
        return self._require_index().document_indices

    def get_document_indices(self) -> np.ndarray:
        """Return sequence indices that delimit documents."""
        return self.document_indices

    def set_document_indices(self, document_indices: np.ndarray) -> None:
        """Replace sequence indices that delimit documents."""
        self._require_index().document_indices = document_indices

    def _require_index(self) -> _IndexReader:
        """Return the initialized index reader."""
        if self.index is None:
            raise ValueError("Indexed Dataset metadata is not initialized")
        return self.index
hyper_parallel/data/indexed/indexed_lazy_dataset.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# limitations under the License.
# ============================================================================
"""Lazy proxy for deferred indexed Dataset construction."""

from __future__ import annotations

from collections.abc import Callable, Mapping
from typing import Any

from hyper_parallel.data.dataset_logging import get_dataset_logger

logger = get_dataset_logger(__name__)


class LazyDatasetProxy:
    """Construct and cache a Dataset when it is first accessed."""

    def __init__(
            self,
            dataset_factory: Callable[[], Any],
            *,
            unique_identifiers: Any,
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
                sample access.
            unique_identifiers: Stable Dataset cache identity assembled from
                construction inputs.
        """
        self._dataset_factory = dataset_factory
        self._unique_identifiers = unique_identifiers
        self._dataset = None

    def __len__(self) -> int:
        """Initialize the Dataset and return its length."""
        return len(self._get_dataset())

    def __getitem__(self, index: int) -> Mapping[str, Any]:
        """Construct the Dataset if necessary and read one sample."""
        dataset = self._get_dataset()
        sample = dataset[index]
        return sample

    @property
    def unique_identifiers(self) -> Any:
        """Initialize the Dataset and return its cache identity."""
        return self._get_dataset().unique_identifiers

    def _get_dataset(self) -> Any:
        """Construct the Dataset once and reuse it for later accesses."""
        if self._dataset is None:
            identifiers = self._unique_identifiers if isinstance(self._unique_identifiers, Mapping) else {}
            logger.debug(
                "Initializing lazy Dataset: class=%s, path=%s, split=%s, samples=%s",
                identifiers.get("class"), identifiers.get("dataset_path"), identifiers.get("index_split"),
                identifiers.get("num_samples"),
            )
            self._dataset = self._dataset_factory()
        return self._dataset
hyper_parallel/data/indexed/indexed_simple_blended_dataset.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# limitations under the License.
# ============================================================================
"""Index-free blending for pre-shuffled MR Datasets."""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from typing import Any, Literal

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


class SimpleBlendedDataset:
    """Blend equally weighted MR Datasets in interleaved or contiguous order."""

    def __init__(
            self,
            datasets: Sequence[Any],
            size: int,
            mode: SimpleBlendMode,
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
            size: int,
            mode: SimpleBlendMode,
    ) -> None:
        """Validate the inputs and create the configured simple ordering."""
        if not datasets:
            raise ValueError("simple blend requires at least one Dataset")
        self.datasets = list(datasets)
        self.size = size
        self.mode = mode
        self._locations = self._build_locations()
        if self.size > len(self._locations):
            raise ValueError(
                f"Requested {self.size} samples from a simple blend containing "
                f"{len(self._locations)} samples"
            )

    def __len__(self) -> int:
        """Return the requested blended sample count."""
        return self.size

    def __getitem__(self, index: int) -> Mapping[str, Any]:
        """Read one MR sample in interleaved or Dataset-contiguous order."""
        dataset_id, sample_id = self._locations[index]
        sample = {"dataset_id": dataset_id, **self.datasets[dataset_id][sample_id]}
        return sample

    def _build_locations(self) -> list[tuple[int, int]]:
        """Map blend positions to Dataset and sample indices."""
        if self.mode == "intra":
            locations = [
                (dataset_id, sample_id)
                for dataset_id, dataset in enumerate(self.datasets)
                for sample_id in range(len(dataset))
            ]
            return locations

        # mode = inter
        locations = self._build_interleaved_locations()
        return locations

    def _build_interleaved_locations(self) -> list[tuple[int, int]]:
        """Alternate over non-empty Datasets until every sample is exposed."""
        max_size = max(len(dataset) for dataset in self.datasets)
        locations = [
            (dataset_id, sample_id)
            for sample_id in range(max_size)
            for dataset_id, dataset in enumerate(self.datasets)
            if sample_id < len(dataset)
76
77
78
79
80
            for sample_id in range(max_size)
            for dataset_id, dataset in enumerate(self.datasets)
            if sample_id < len(dataset)
        ]
        return locations
hyper_parallel/data/parallel/batch_parallel.py
216
217
218
219
220
221
222
223
            raise ValueError(f"seq_len ({seq_len}) must be divisible by cp_size ({cp_size})")

        cp_rank = self.parallel_context.cp_rank
        for field, value in cp_batch.items():
            local_value = torch.chunk(value, cp_size, dim=1)[cp_rank]
            cp_batch[field] = local_value.contiguous()

        return cp_batch
263
264
265
266
267
268
269
270
                for field, value in cp_local_batch.items()
            }
            local_cu_seq_lens = None
            if cu_seq_lens is not None:
                local_cu_seq_lens = cu_seq_lens.to(self.device, dtype=torch.int32, non_blocking=True)
        else:
            parallel_batch = None
            local_cu_seq_lens = None
278
279
280
281
282
283
284
285
286
        # Broadcast compact shape metadata before receivers allocate tensors.
        if tp_rank == 0:
            batch_size, seq_len = parallel_batch["input_ids"].shape
            num_boundaries = 0 if local_cu_seq_lens is None else local_cu_seq_lens.numel()
            batch_meta = torch.tensor(
                [batch_size, seq_len, num_boundaries],
                dtype=torch.int64,
                device=self.device,
            )
284
285
286
287
288
289
290
291
292
293
294
295
                dtype=torch.int64,
                device=self.device,
            )
        else:
            batch_meta = torch.empty((3,), dtype=torch.int64, device=self.device)

        tp_group = self.parallel_context.tp_group
        dist.broadcast(batch_meta, group=tp_group, group_src=0)

        # Non-source TP ranks allocate the same device shapes and dtypes.
        if tp_rank != 0:
            batch_size, seq_len, num_boundaries = [int(value) for value in batch_meta.tolist()]
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
                "input_ids": torch.empty(shape, dtype=torch.int64, device=self.device),
                "labels": torch.empty(shape, dtype=torch.int64, device=self.device),
            }
            if num_boundaries > 0:
                local_cu_seq_lens = torch.empty((num_boundaries,), dtype=torch.int32, device=self.device)

        # Broadcast only model fields that cannot be regenerated locally.
        for field in ("input_ids", "labels"):
            dist.broadcast(parallel_batch[field], group=tp_group, group_src=0)

        # Packed boundaries remain global across CP ranks and variable in size.
        if local_cu_seq_lens is not None:
            dist.broadcast(local_cu_seq_lens, group=tp_group, group_src=0)

        parallel_batch["cu_seq_lens"] = local_cu_seq_lens

        return parallel_batch
hyper_parallel/data/parallel/batch_sampler.py
33
34
35
36
37
38
39
40
41
42


def _validate_positive_integer(value: int, name: str) -> None:
    """Validate an integer boundary shared by sampler options."""
    if value <= 0:
        raise ValueError(f"{name} must be a positive integer")


class _DatasetBatchSampler:
    """Share validation, DP slicing, epoch, and checkpoint state.
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
            drop_last: bool,
            index_mapping: IndexMapping | None,
    ) -> None:
        """Validate and store DP slicing and checkpoint state."""
        _validate_positive_integer(total_samples, "total_samples")
        _validate_positive_integer(micro_batch_size, "micro_batch_size")
        _validate_positive_integer(dp_world_size, "dp_world_size")
        self._validate_consumed_samples(consumed_samples, total_samples)
        if not 0 <= dp_rank < dp_world_size:
            raise ValueError(f"dp_rank must be in [0, {dp_world_size}), but got {dp_rank!r}")

        self.total_samples = total_samples
        self.consumed_samples = consumed_samples
        self.micro_batch_size = micro_batch_size
        self.dp_rank = dp_rank
        self.dp_world_size = dp_world_size
        self.drop_last = drop_last
        self.index_mapping = index_mapping
        self.global_micro_batch_size = micro_batch_size * dp_world_size
        _validate_positive_integer(global_batch_size, "global_batch_size")
        if global_batch_size % self.global_micro_batch_size != 0:
            raise ValueError("global_batch_size must be divisible by micro_batch_size * dp_world_size")

        self.global_batch_size = global_batch_size
        self.epoch = 0
        self._resume_at_source_batch = False

    def _validate_consumed_samples(self, consumed_samples: int, total_samples: int) -> None:
        """Allow sequential sampling to stop exactly at the epoch boundary."""
        if not 0 <= consumed_samples <= total_samples:
            raise ValueError("consumed_samples must be in [0, total_samples]")

    def __iter__(self) -> Iterator[list[int]]:
        """Yield sequential rank-local indices for ``single`` mode."""
        while self.consumed_samples < self.total_samples:
            block_start = self.consumed_samples
            block_stop = min(block_start + self.global_micro_batch_size, self.total_samples)
            block_size = block_stop - block_start
            if self.drop_last and block_size < self.global_micro_batch_size:
                self.consumed_samples = self.total_samples
                break

            local_start = block_start + self.dp_rank * self.micro_batch_size
            local_stop = min(local_start + self.micro_batch_size, block_stop)
            self.consumed_samples = block_stop
            if local_start >= block_stop:
                continue

            local_indices = [
                self._resolve_index(index)
                for index in range(local_start, local_stop)
            ]
            yield local_indices

    def __len__(self) -> int:
        """Return the remaining number of micro-batches for this DP rank."""
        remaining_samples = self.total_samples - self.consumed_samples
        full_batches, partial_samples = divmod(remaining_samples, self.global_micro_batch_size)
        if self.drop_last or partial_samples <= self.dp_rank * self.micro_batch_size:
            return full_batches
        return full_batches + 1

    def _resolve_index(self, logical_index: int) -> int:
        """Apply an optional logical-to-physical sample index mapping."""
        if self.index_mapping is None:
            return logical_index

        resolved_index = self.index_mapping[logical_index]
        if isinstance(resolved_index, bool):
            raise TypeError(f"index_mapping[{logical_index}] must be an integer")

        physical_index = operator.index(resolved_index)
        return physical_index

    def state_dict(self) -> dict[str, int]:
        """Return the Dataset epoch and position needed to resume iteration."""
        sampler_state = {
            "consumed_samples": self.consumed_samples,
            "epoch": self.epoch,
            "global_batch_size": self.global_batch_size,
            "dp_world_size": self.dp_world_size,
137
138
139
140
141
142
143
144
145
146
147
148
            "epoch": self.epoch,
            "global_batch_size": self.global_batch_size,
            "dp_world_size": self.dp_world_size,
        }
        return sampler_state

    def enable_source_batch_resume(self) -> None:
        """Restore this sampler at a source-batch boundary for Online batching."""
        self._resume_at_source_batch = True

    def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
        """Restore the global sample position from a checkpoint.
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181

        Raises:
            ValueError: If the checkpoint does not contain a valid sample position.
        """
        consumed_samples = state_dict["consumed_samples"]
        self._validate_consumed_samples(consumed_samples, self.total_samples)
        if state_dict["global_batch_size"] != self.global_batch_size:
            if self._resume_at_source_batch:
                raise ValueError("Online dataloader resume requires an unchanged global_batch_size")

            raise ValueError("elastic DP resume requires an unchanged global_batch_size")

        if self._resume_at_source_batch:
            if state_dict["dp_world_size"] != self.dp_world_size:
                raise ValueError("Online dataloader resume does not support DP world-size changes")

            if (
                    consumed_samples != self.total_samples
                    and consumed_samples % self.global_micro_batch_size != 0
            ):
                raise ValueError("Online source sampler state must align to a distributed micro-batch")

        elif consumed_samples % self.global_batch_size != 0:
            raise ValueError("sampler state must align to a global optimizer batch")

        self.consumed_samples = consumed_samples
        self.epoch = state_dict["epoch"]

    def set_epoch(self, epoch: int) -> None:
        """Start a new epoch while preserving progress in the restored epoch.
185
186
187
188
189
190
191
192
193
194
195
196
197
198

        Raises:
            ValueError: If ``epoch`` is not a non-negative integer.
        """
        if isinstance(epoch, bool) or not isinstance(epoch, int) or epoch < 0:
            raise ValueError("epoch must be a non-negative integer")

        if epoch != self.epoch:
            self.consumed_samples = 0
            self.epoch = epoch


class _CyclicDatasetBatchSampler(_DatasetBatchSampler):
    """Yield one deterministic shuffled epoch for ``cyclic`` mode."""
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    """Yield one deterministic shuffled epoch for ``cyclic`` mode."""

    def __init__(self, *, data_sharding: bool, seed: int, **sampler_options: Any) -> None:
        """Store the cyclic data-sharding policy."""
        super().__init__(**sampler_options)
        if not self.drop_last:
            raise ValueError("cyclic sampling requires drop_last=True")

        self.data_sharding = data_sharding
        self.seed = seed

    def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
        """Restore a fixed-GBS cursor, repartitioning only global shuffle order."""
        if self.data_sharding and state_dict["dp_world_size"] != self.dp_world_size:
            raise ValueError("elastic DP resume requires data_sharding=False")

        super().load_state_dict(state_dict)

    def __len__(self) -> int:
        """Return the number of local micro-batches remaining in this epoch."""
        active_samples = self._active_samples()
        remaining_samples = active_samples - self.consumed_samples
        return remaining_samples // self.global_micro_batch_size

    def __iter__(self) -> Iterator[list[int]]:
        """Build the current epoch permutation and DP slices."""
        active_samples = self._active_samples()
        if self.consumed_samples % self.global_micro_batch_size != 0:
            raise ValueError("cyclic consumed_samples must align to a distributed micro-batch")

        logger.debug(
            "Starting cyclic Dataset epoch=%d at consumed_samples=%d",
            self.epoch,
            self.consumed_samples,
        )
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
            self.epoch,
            self.consumed_samples,
        )

        if self.data_sharding:
            # Shuffle one contiguous bucket per DP rank.
            bucket_size = active_samples // self.dp_world_size
            bucket_offset = self.consumed_samples // self.dp_world_size
            bucket_start = self.dp_rank * bucket_size
            random_offsets = list(range(bucket_size))
            random.Random(self.seed + self.epoch).shuffle(random_offsets)
            rank_indices = [bucket_start + offset for offset in random_offsets[bucket_offset:]]
        else:
            # Shuffle the complete global-batch region, then stride by DP rank.
            shuffled_indices = list(range(active_samples))
            random.Random(self.seed + self.epoch).shuffle(shuffled_indices)
            active_indices = shuffled_indices[self.consumed_samples:]
            rank_indices = active_indices[self.dp_rank::self.dp_world_size]

        local_batch = []
        for index in rank_indices:
            local_batch.append(index)
            if len(local_batch) == self.micro_batch_size:
                self.consumed_samples += self.global_micro_batch_size
                yield local_batch
                local_batch = []

    def _active_samples(self) -> int:
        """Return the complete global micro-batch region reused every epoch."""
        active_samples = self.total_samples - self.total_samples % self.global_micro_batch_size
        if active_samples <= 0:
            raise ValueError("cyclic Dataset must contain one complete global micro-batch")

        return active_samples


def _resolve_index_mapping(
        index_mapping: IndexMapping | None,
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
        index_mapping: IndexMapping | None,
        data_rearrange_map: IndexMapping | str | os.PathLike[str] | None,
) -> IndexMapping | None:
    """Resolve the optional rearrangement-map configuration."""
    if index_mapping is not None and data_rearrange_map is not None:
        raise ValueError("configure only one of index_mapping and data_rearrange_map")

    mapping_source = data_rearrange_map if data_rearrange_map is not None else index_mapping
    if isinstance(mapping_source, (str, os.PathLike)):
        mapping_path = os.fspath(mapping_source)
        loaded_mapping = torch.load(f=mapping_path)
        resolved_mapping = cast(IndexMapping, loaded_mapping)
        return resolved_mapping
    return mapping_source


def build_dataset_batch_sampler(
        *,
326
327
328
329
330
331
332
333
334
335

    Returns:
        A resumable iterable of rank-local index lists.
    """
    resolved_mapping = _resolve_index_mapping(index_mapping, data_rearrange_map)
    logger.debug(
        "Building Dataset sampler: type=%s, total_samples=%d, consumed_samples=%d, micro_batch_size=%d, "
        "dp_rank=%d, dp_world_size=%d, drop_last=%s, data_sharding=%s, mapped=%s",
        sampler_type, total_samples, consumed_samples, micro_batch_size, dp_rank, dp_world_size, drop_last,
        data_sharding, resolved_mapping is not None,
333
334
335
336
337
338
339
340
341
        "dp_rank=%d, dp_world_size=%d, drop_last=%s, data_sharding=%s, mapped=%s",
        sampler_type, total_samples, consumed_samples, micro_batch_size, dp_rank, dp_world_size, drop_last,
        data_sharding, resolved_mapping is not None,
    )
    sampler_options = {
        "total_samples": total_samples,
        "consumed_samples": consumed_samples,
        "micro_batch_size": micro_batch_size,
        "global_batch_size": global_batch_size,
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
        "drop_last": drop_last,
        "index_mapping": resolved_mapping,
    }

    if sampler_type == "single":
        # Scenario 1 — single without a mapping: sequential Dataset indices.
        # Scenario 2 — single + data_rearrange_map: the same logical sequence
        # is resolved through an in-memory mapping or mapping checkpoint.
        batch_sampler = _DatasetBatchSampler(**sampler_options)
        return batch_sampler

    if sampler_type == "cyclic":
        # Scenario 3 — cyclic: use epoch-based randperm order,
        # support data_sharding=True/False, and checkpoint consumed_samples.
        if resolved_mapping is not None:
            raise ValueError("cyclic sampling does not support a rearrangement map")

        batch_sampler = _CyclicDatasetBatchSampler(
            data_sharding=data_sharding,
            seed=seed,
            **sampler_options,
        )
        return batch_sampler

    raise ValueError("sampler_type must be one of: single, cyclic")
hyper_parallel/data/parallel/dataloader_parallel.py
73
74
75
76
77
78
79
80
81
    if not shared_storage:
        return True

    try:
        global_rank = int(dist.get_rank())
    except (RuntimeError, ValueError):
        global_rank = 0
    builds_shared_cache = global_rank == 0
    return builds_shared_cache
100
101
102
103
104
105
106
107
108
        DataLoader rank ownership, cache ownership, and synchronization callbacks.
    """
    device_mesh = getattr(mesh_context, "device_mesh", None)
    try:
        world_size = int(dist.get_world_size())
    except (RuntimeError, ValueError):
        world_size = 1
    distributed_enabled = device_mesh is not None and world_size > 1
    if not distributed_enabled:
hyper_parallel/data/text/build_data_transform.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
``tokenizer``/``chat_template`` keyword superset covers both legacy call
styles.
"""

from __future__ import annotations

from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any, Literal

import torch

from hyper_parallel.data.dataset_logging import get_dataset_logger

LLMDataType = Literal["plaintext", "conversation"]
logger = get_dataset_logger(__name__)


def _get_record_value(sample: Mapping[str, Any], keys: str | Sequence[str]) -> Any:
    if isinstance(keys, str):
        try:
            return sample[keys]
        except KeyError as exc:
            raise ValueError(f"Sample does not contain field {keys!r}") from exc
    for key in keys:
        if key in sample:
            return sample[key]
    raise ValueError(f"Sample does not contain any configured text fields: {list(keys)!r}")


class IdentityDataTransform:
    """Return each input sample unchanged."""

    def __init__(self, tokenizer: Any = None, chat_template: Any = None) -> None:
        """Retain optional upstream assets for target compatibility.

        Args:
            tokenizer: Optional tokenizer built by the LLM Trainer.
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
        Args:
            tokenizer: Optional tokenizer built by the LLM Trainer.
            chat_template: Optional chat template built from model assets.
        """
        self.tokenizer = tokenizer
        self.chat_template = chat_template

    def __call__(self, sample: Any) -> Any:
        """Return the input sample without modification."""
        return sample


@dataclass
class PlaintextTransform:
    """Tokenize plaintext records into one or more model samples."""

    tokenizer: Any
    max_seq_len: int
    text_keys: str | Sequence[str] = "text"

    def __post_init__(self) -> None:
        """Validate the tokenizer and sequence length configuration."""
        if self.tokenizer is None:
            raise ValueError("tokenizer is required for plaintext data")
        if self.max_seq_len <= 0:
            raise ValueError("max_seq_len must be positive")

    def __call__(self, sample: Mapping[str, Any]) -> list[dict[str, Any]]:
        """Tokenize and chunk one plaintext record."""
        text = _get_record_value(sample, self.text_keys)
        token_ids = self.tokenizer.encode(text, add_special_tokens=False)
        eos_token_id = getattr(self.tokenizer, "eos_token_id", None)
        if eos_token_id is not None:
            token_ids = [*token_ids, eos_token_id]

        transformed = []
        for start in range(0, len(token_ids) - 1, self.max_seq_len):
            text = torch.tensor(token_ids[start:start + self.max_seq_len + 1], dtype=torch.long)
            model_sample = {
                "input_ids": text[:-1],
                "labels": text[1:],
            }
            transformed.append(model_sample)
        return transformed


@dataclass
class TextConversationTransform:
    """Encode conversation records with a configured chat template."""

    chat_template: Any
    max_seq_len: int
    text_keys: str | Sequence[str] = "conversation"

    def __post_init__(self) -> None:
        """Validate the chat template and sequence length configuration."""
        if self.chat_template is None:
            raise ValueError("chat_template is required for conversation data")
        if self.max_seq_len <= 0:
            raise ValueError("max_seq_len must be positive")

    def __call__(self, sample: Mapping[str, Any]) -> list[dict[str, Any]]:
        """Encode one conversation record."""
        messages = _get_record_value(sample, self.text_keys)
        encoded = self.chat_template.encode_messages(messages, max_seq_len=self.max_seq_len)
        input_ids = torch.as_tensor(encoded["input_ids"], dtype=torch.long)
        labels = torch.as_tensor(encoded["labels"], dtype=torch.long)
        model_sample = {
            "input_ids": input_ids[:-1],
            "labels": labels[1:],
        }
        return [model_sample]


def build_llm_data_transform(data_type: LLMDataType, *, tokenizer: Any = None, chat_template: Any = None,
                             max_seq_len: int, text_keys: str | Sequence[str] = "text") -> Callable[[Any], Any]:
    """Build the transform selected by the LLM data type.

    Args:
143
144
145
146
147
148
149
150
151
152
153
154

    Raises:
        ValueError: If ``data_type`` is unsupported.
    """
    if data_type == "plaintext":
        data_transform = PlaintextTransform(tokenizer, max_seq_len, text_keys)
    elif data_type == "conversation":
        data_transform = TextConversationTransform(chat_template, max_seq_len, text_keys)
    else:
        raise ValueError(f"Unsupported LLM data type: {data_type!r}")
    logger.debug("Built LLM data transform: data_type=%s, transform=%s", data_type, type(data_transform).__name__)
    return data_transform
hyper_parallel/data/text/chat_template.py
74
75
76
77
78
79
80
81
82
83
84
            ValueError: If ``key`` is not registered.
        """
        # First check if instance has a local override
        if key not in self.valid_keys():
            raise ValueError(f"Unknown {self._name} name: {key}. No {self._name} registered for this source.")
        if key in self._local_mapping:
            return self._local_mapping[key]
        return self._global_mapping[key]

    def __setitem__(self, key: str, value: Union[Type, Callable]) -> None:
        """Set a local override for ``key`` without affecting other instances."""
82
83
84
85
86
87
88
89
90
91
92
93
94

    def __setitem__(self, key: str, value: Union[Type, Callable]) -> None:
        """Set a local override for ``key`` without affecting other instances."""
        # Allow local update of the default functions without impacting other instances
        self._local_mapping.update({key: value})

    def __delitem__(self, key: str) -> None:
        """Delete the local override for ``key``."""
        del self._local_mapping[key]

    def __iter__(self) -> Iterator[str]:
        """Iterate over all valid keys, local overrides taking precedence."""
        # Ensure we use all keys, with the overwritten ones on top
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
        Raises:
            ValueError: If ``key`` is already registered (decorator form).
        """
        if cls_or_func is not None:
            self._global_mapping[key] = cls_or_func
            return cls_or_func

        def decorator(cls_or_func: Union[Type, Callable]) -> Union[Type, Callable]:
            """Register the decorated class or function under ``key``."""
            if key in self._global_mapping:
                raise ValueError(
                    f"{self._name} for '{key}' is already registered. Cannot register duplicate {self._name}."
                )
            self._global_mapping.update({key: cls_or_func})
            return cls_or_func
153
154
155
156
157
158
159
160
161
    role = message["role"]
    content = message["content"]
    separators = ["\n\n", "<|end▁of▁sentence|>"]
    if content == "":
        return role + ":", assistant_count
    if "assistant" in role and (
            "wikihow_generation" in task_type or "interleave_generation" in task_type
    ):
        prefix = "Assistant: " if assistant_count == 0 else ""
169
170
171
172
173
174
175
176
177
        instruction = "Please generate a step-by-step tutorial with images for the following question."
        return content.strip() + separators[0] + instruction + separators[0], assistant_count
    if "system" in role:
        return content.strip() + separators[0], assistant_count
    raise ValueError(f"Unknown role {role}, should be one of {{system, user, assistant}}.")


def _janus_labels(content_ids: List[int], image_token_id: int, loss_mask: int, task_type: str) -> List[int]:
    """Build labels for one encoded Janus message."""
326
327
328
329
330
331
332
333
            )
            current_ids = encoded["input_ids"]
            current_length = len(current_ids)
            if current_length < previous_length:
                raise ValueError(
                    "The tokenizer chat template shortened the conversation after adding a message; "
                    "assistant-only loss masking requires monotonic message boundaries."
                )
352
353
354
355
356
357
358
359
360
361
362

        Raises:
            ValueError: If the tokenizer does not define a chat template.
        """
        if not self.tokenizer.chat_template:
            raise ValueError("The tokenizer does not define a native chat template.")
        return self.tokenizer.chat_template


@CHAT_TEMPLATE_REGISTRY.register("gpt_oss")
class GptOssTokenizerTemplate(TokenizerTemplate):
374
375
376
377
378
379
380
381
382
        super().__init__(tokenizer)
        self.return_token_id = tokenizer.convert_tokens_to_ids("<|return|>")
        self.end_token_id = tokenizer.convert_tokens_to_ids("<|end|>")
        if tokenizer.unk_token_id in (self.return_token_id, self.end_token_id):
            raise ValueError("The GPT-OSS chat template requires <|return|> and <|end|> tokenizer tokens.")

    def _update_prefix_labels(
            self,
            previous_ids: List[int],
409
410
411
412
413
414
415
416
            and current_ids[previous_length - 1] == self.end_token_id
            and self.return_token_id not in current_ids[previous_length:]
        )
        if not is_terminal_rewrite:
            raise ValueError(
                "The GPT-OSS tokenizer chat template structurally rewrote an earlier conversation prefix; "
                "only the terminal <|return|>-to-<|end|> substitution is supported."
            )
464
465
466
467
468
469
470
471
472
        return model_inputs

    def get_jinja_template(self) -> str:
        """Return the jinja template matching the Llama-2 prompt format."""
        return (
            "{% if messages[0]['role'] == 'system' %}"
            "{{ '<<SYS>>\n' + messages[0]['content'] | trim + '\n<</SYS>>\n\n' }}"
            "{% set loop_messages = messages[1:] %}"
            "{% else %}"
541
542
543
544
545
546
547
548
549
        return model_inputs

    def get_jinja_template(self) -> str:
        """Return the jinja template matching the Janus ChatML-style rendering."""
        return (
            "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}"
            "{% for message in messages %}"
            "{{ '<|im_start|>' + message['role'] + '\n' + message['content'] | trim + '<|im_end|>\n' }}"
            "{% endfor %}"
586
587
588
589
590
591
592
593
594
        return model_inputs

    def get_jinja_template(self) -> str:
        """Return the jinja template matching the ChatML rendering."""
        return (
            "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}"
            "{% for message in messages %}"
            "{{ '<|im_start|>' + message['role'] + '\n' + message['content'] | trim + '<|im_end|>\n' }}"
            "{% endfor %}"
hyper_parallel/data/text/online/online_dataset.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# limitations under the License.
# ============================================================================
"""Dispatch the reserved online LLM Dataset implementations."""

from __future__ import annotations

from collections.abc import Callable, Mapping, Sequence
from typing import Any

from hyper_parallel.data.dataset_logging import get_dataset_logger
from hyper_parallel.data.text.online.online_iterable_dataset import build_online_iterable_dataset
from hyper_parallel.data.text.online.online_mapping_dataset import build_online_mapping_dataset
from hyper_parallel.data.parallel import DataLoaderParallelContext

logger = get_dataset_logger(__name__)

_ONLINE_DATASET_BUILDERS: dict[str, Callable[..., Any]] = {
    "mapping": build_online_mapping_dataset,
    "iterable": build_online_iterable_dataset,
}
31
32
33
34
35
36
37
38
39
    "iterable": build_online_iterable_dataset,
}


def build_online_dataset(
        *,
        data_config: Mapping[str, Any],
        data_path: str | Sequence[str] | None = None,
        dataloader_context: DataLoaderParallelContext | None = None,
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

    Raises:
        ValueError: If ``dataset_type`` is unsupported.
    """
    dataset_type = str(data_config.get("dataset_type", "mapping"))
    try:
        online_dataset_builder = _ONLINE_DATASET_BUILDERS[dataset_type]
    except KeyError as error:
        supported_types = sorted(_ONLINE_DATASET_BUILDERS)
        raise ValueError(
            f"Unsupported online dataset_type {dataset_type!r}; expected one of {supported_types!r}"
        ) from error
    logger.debug("Selected online Dataset type=%s, data_path=%s", dataset_type, data_path)
    online_dataset = online_dataset_builder(
        data_path=data_path,
        data_config=data_config,
        dataloader_context=dataloader_context,
    )
    logger.debug("Built Online source Dataset type=%s", type(online_dataset).__name__)
    return online_dataset
hyper_parallel/data/text/online/online_iterable_dataset.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# limitations under the License.
# ============================================================================
"""Online iterable dataset source."""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from typing import Any

from hyper_parallel.data.dataset_logging import get_dataset_logger
from hyper_parallel.data.text.online.online_utils import (
    load_online_hf_dataset,
    normalize_online_dataloader_context,
)
from hyper_parallel.data.parallel import (
    DataLoaderParallelContext,
    build_dataset_for_dataloader,
    split_iterable_dataset_by_dp,
)
29
30
31
32
33
34
35
36
37
38
39
40
    build_dataset_for_dataloader,
    split_iterable_dataset_by_dp,
)

logger = get_dataset_logger(__name__)


def build_online_iterable_dataset(
        *,
        data_config: Mapping[str, Any],
        data_path: str | Sequence[str] | None = None,
        dataloader_context: DataLoaderParallelContext | None = None,
49
50
51
52
53
54
55
56
57
58
59
60
61
62

    Returns:
        A Hugging Face iterable Dataset on TP rank zero, otherwise ``None``.
    """
    normalized_context = normalize_online_dataloader_context(dataloader_context)

    def dataset_factory() -> Any:
        """Load, shuffle, and DP-shard the upstream stream."""
        # Read samples lazily as a stream; this does not perform DP sharding.
        online_dataset = load_online_hf_dataset(
            data_path=data_path,
            data_config=data_config,
            streaming=True,
        )
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
            data_config=data_config,
            streaming=True,
        )

        if bool(data_config.get("shuffle", True)):
            random_seed = int(data_config.get("random_seed", 42))
            buffer_size = int(data_config.get("shuffle_buffer_size", 10_000))
            if buffer_size <= 0:
                raise ValueError("Online shuffle_buffer_size must be positive")
            online_dataset = online_dataset.shuffle(
                seed=random_seed,
                buffer_size=buffer_size,
            )
            logger.debug("Enabled online iterable shuffle: seed=%d, buffer_size=%d", random_seed, buffer_size)

        if bool(data_config.get("split_by_data_parallel", True)):
            # Iterable sources have no index sampler, so shard the stream across DP ranks here.
            online_dataset = split_iterable_dataset_by_dp(online_dataset, normalized_context)
            logger.debug(
                "Split online iterable Dataset by DP: rank=%d, world_size=%d",
                normalized_context.dp_rank, normalized_context.dp_world_size,
            )

        return online_dataset

    online_dataset = build_dataset_for_dataloader(
        dataset_factory,
        normalized_context,
        barrier_needed=False,
    )
87
88
89
90
91
        normalized_context,
        barrier_needed=False,
    )

    return online_dataset
hyper_parallel/data/text/online/online_mapping_dataset.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# limitations under the License.
# ============================================================================
"""Online mapping dataset source."""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from dataclasses import replace
from typing import Any

from hyper_parallel.data.parallel.build_barrier import OnlineDatasetBarrier
from hyper_parallel.data.dataset_logging import get_dataset_logger
from hyper_parallel.data.text.online.online_utils import (
    load_online_hf_dataset,
    normalize_online_dataloader_context,
)
from hyper_parallel.data.parallel import (
    DataLoaderParallelContext,
    build_dataset_for_dataloader,
)

logger = get_dataset_logger(__name__)


class OnlineMappingDataset:
    """Expose Hugging Face records through deterministic integer indices."""

    def __init__(self, source_dataset: Any) -> None:
        """Store the raw mapping Dataset without applying tokenizer logic."""
        self.source_dataset = source_dataset

    def __len__(self) -> int:
        """Return the finite raw-record count."""
        return len(self.source_dataset)

    def __getitem__(self, index: int) -> Mapping[str, Any]:
        """Read and validate one RawSample."""
        raw_sample = self.source_dataset[index]
        if not isinstance(raw_sample, Mapping):
            raise ValueError("Online mapping source records must be mappings")
        normalized_sample = dict(raw_sample)
        return normalized_sample


def build_online_mapping_dataset(
        *,
        data_config: Mapping[str, Any],
        data_path: str | Sequence[str] | None = None,
        dataloader_context: DataLoaderParallelContext | None = None,
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

    Returns:
        An Online mapping Dataset on TP rank zero, otherwise ``None``.
    """
    normalized_context = normalize_online_dataloader_context(dataloader_context)
    if normalized_context.distributed_enabled:
        normalized_context = replace(
            normalized_context,
            barrier=OnlineDatasetBarrier(),
        )

    def dataset_factory() -> OnlineMappingDataset:
        """Load the raw source and attach its integer-index wrapper."""
        source_dataset = load_online_hf_dataset(
            data_path=data_path,
            data_config=data_config,
            streaming=False,
        )
        online_dataset = OnlineMappingDataset(source_dataset)
        logger.debug("Loaded online mapping Dataset records=%d", len(online_dataset))
        return online_dataset

    online_dataset = build_dataset_for_dataloader(
        dataset_factory,
        normalized_context,
        # Cache-builder ranks must finish the Hub download before the other
        # owning ranks reopen the shared Hugging Face cache.
94
95
96
97
98
        # Cache-builder ranks must finish the Hub download before the other
        # owning ranks reopen the shared Hugging Face cache.
        barrier_needed=normalized_context.distributed_enabled,
    )
    return online_dataset
hyper_parallel/data/vlm/get_batch.py
16
17
18
19
20
21
22
23
24

from collections.abc import Mapping
from typing import Any

import torch


_MODEL_INPUT_FIELDS = {
    "input_ids",