File size: 12,861 Bytes
23c39b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
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
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
148
149
150
151
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
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
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
268
"""Stratified-sample a tokenized corpus (identical to data_io/sample_tokenized.py)
and write a COMPACTED output containing only the token ranges actually
referenced by the generated epochs.

Motivation: upstream sample_tokenized.py copies the ENTIRE tokenized corpus
into output tokens.npy, which does not fit /dev/shm (or the lustre quota) for
this corpus with an int32 dtype. Since epoch indices reference only a small
covered subset (max_per_file caps), we can keep only the union of referenced
[start, start+len) intervals and remap the epoch indices. The training-visible
token stream is bit-identical: same epoch files order, same lengths, same
token contents (verified against the per-task source arrays).

RNG-critical: the epoch-generation loop below is copied verbatim from
sample_tokenized.py main() so the Philox call sequence, task order, and
permutation logic are exactly the reference ones. Replacing the corpus copy
with virtual offsets does not touch the RNG.

Usage (inside the HRM-Text container, from any cwd):
  python sample_and_compact.py \
      tokenized_path=/tmp/hengyuf/data_tokenized_bpe_65k \
      output_path=/tmp/hengyuf/sampled_compact \
      prefix_config_path=/lustre/.../data_io/prefix_config.yaml \
      epochs=4 seed=0 [verify_rows=2000]
"""
from dataclasses import fields
from pathlib import Path
import importlib.util
import json
import sys

import numpy as np
import yaml
from omegaconf import OmegaConf

DATA_IO = Path("/lustre/fsw/portfolios/nemotron/users/hengyuf/data_io")

# Import upstream module to reuse Config/PrefixConfig/Task/truncate_and_filter/
# V1DatasetMeta/gen_report — guarantees identical filtering semantics.
spec = importlib.util.spec_from_file_location("sample_tokenized", DATA_IO / "sample_tokenized.py")
st = importlib.util.module_from_spec(spec)
sys.modules["sample_tokenized"] = st
spec.loader.exec_module(st)


def main():
    cli = OmegaConf.to_container(OmegaConf.from_cli(), resolve=True)
    verify_rows = int(cli.pop("verify_rows", 2000))
    config = st.Config(**cli)

    with open(Path(config.tokenized_path) / "tokenizer_info.json", "r") as f:
        tokenizer_info = json.load(f)
    with open(config.prefix_config_path, "r") as f:
        prefix_config_list = yaml.safe_load(f)

    # ---- Task scan: verbatim semantics from sample_tokenized.main() ----
    tasks = []
    for dataset_dir in sorted(Path(config.tokenized_path).iterdir()):
        task_name = dataset_dir.name
        if not dataset_dir.is_dir():
            continue
        prefix_config = None
        for prefix_config_item in prefix_config_list:
            if task_name.startswith(prefix_config_item["prefix"]):
                if prefix_config is not None:
                    print(f"Warning: Multiple possible prefixes for task {task_name}, pick config {prefix_config.model_dump_json()}")
                    break
                prefix_config = st.PrefixConfig(**prefix_config_item)
        if prefix_config is None:
            prefix_config = st.PrefixConfig()
        tasks.append(st.Task(name=task_name,
                             indices=st.TaskIndices(**{f.name: np.load(dataset_dir / f"{f.name}.npy")
                                                       for f in fields(st.TaskIndices)}),
                             prefix_config=prefix_config))

    # ---- concat_tokens replaced: compute virtual offsets only (no copy). ----
    # Offset math is identical to upstream concat_tokens().
    total_tokens_virtual = 0
    for task in tasks:
        task_len = int(np.sum(task.indices.inst_len) + np.sum(task.indices.resp_len))
        task.mmap_base_offset = total_tokens_virtual
        task.mmap_length = task_len
        total_tokens_virtual += task_len
    print(f"Virtual corpus: {total_tokens_virtual:,} tokens "
          f"({total_tokens_virtual*4/1e9:.1f} GB as int32) — NOT materialized")

    # Output dtype: upstream picks int32 for vocab_size=65536, but the max
    # token id (65535) fits uint16 exactly. dataset_new.py mmap-loads and
    # astype(int32)s slices, so storage dtype is transparent to training —
    # we use uint16 (halves lustre + /dev/shm) and assert ids fit during copy.
    vocab_size = tokenizer_info.get("vocab_size")
    if vocab_size is not None and vocab_size <= np.iinfo(np.uint16).max + 1:
        target_dtype = np.uint16
    else:
        target_dtype = np.int32

    # ---- Prefilter: verbatim upstream ----
    for task in tasks:
        st.truncate_and_filter(task, config)

    # ---- Epoch generation: copied VERBATIM from sample_tokenized.main() ----
    rng = np.random.Generator(np.random.Philox(seed=config.seed))

    total_rows = sum(len(task.indices.inst_start) for task in tasks)
    buffer = st.TaskIndices(**{f.name: np.empty((total_rows,), dtype=np.int64)
                               for f in fields(st.TaskIndices)})

    epoch_data = []  # per-epoch dict of the 4 permuted arrays
    total_tokens = 0
    for epoch in range(config.epochs):
        buffer_cursor = 0
        for task in tasks:
            assert task.prefix_config is not None
            rows_to_sample = min(task.prefix_config.max_per_file, len(task.indices.inst_start)) if task.prefix_config.max_per_file is not None else len(task.indices.inst_start)
            rows_to_sample *= task.prefix_config.repeat
            rows_fetched = 0

            if task.coverage is None:
                task.coverage = np.zeros((len(task.indices.inst_start),), dtype=np.int32)

            while rows_fetched < rows_to_sample:
                if task.perm is None or task.perm_cursor >= len(task.perm):
                    task.perm = rng.permutation(len(task.indices.inst_len))
                    task.perm_cursor = 0

                remaining = len(task.perm) - task.perm_cursor
                take = min(remaining, rows_to_sample - rows_fetched)
                rows_fetched += take

                batch_indices = task.perm[task.perm_cursor: task.perm_cursor + take]
                task.perm_cursor += take

                buffer.inst_start[buffer_cursor: buffer_cursor + take] = task.indices.inst_start[batch_indices] + task.mmap_base_offset
                buffer.inst_len[buffer_cursor: buffer_cursor + take] = task.indices.inst_len[batch_indices]
                buffer.resp_start[buffer_cursor: buffer_cursor + take] = task.indices.resp_start[batch_indices] + task.mmap_base_offset
                buffer.resp_len[buffer_cursor: buffer_cursor + take] = task.indices.resp_len[batch_indices]
                buffer_cursor += take

                task.coverage[batch_indices] += 1

        total_tokens += np.sum(buffer.inst_len[:buffer_cursor]) + np.sum(buffer.resp_len[:buffer_cursor])

        perm = rng.permutation(buffer_cursor)
        epoch_data.append({f.name: getattr(buffer, f.name)[:buffer_cursor][perm].copy()
                           for f in fields(st.TaskIndices)})
        print(f"Epoch {epoch}: {buffer_cursor:,} rows")

    # ---- Compaction: union of referenced intervals, remap, copy ----
    print("Computing referenced intervals...")
    starts = np.concatenate([np.concatenate([e["inst_start"], e["resp_start"]]) for e in epoch_data])
    lens = np.concatenate([np.concatenate([e["inst_len"], e["resp_len"]]) for e in epoch_data])
    ends = starts + lens

    order = np.argsort(starts, kind="stable")
    starts, ends = starts[order], ends[order]
    running_end = np.maximum.accumulate(ends)
    is_new = np.empty(len(starts), dtype=bool)
    is_new[0] = True
    is_new[1:] = starts[1:] > running_end[:-1]
    group_first = np.flatnonzero(is_new)
    m_start = starts[group_first]
    m_end = np.maximum.reduceat(ends, group_first)
    del starts, ends, running_end, is_new, order, lens

    # Split merged intervals at task boundaries so each maps to one source
    # file. Vectorized: only intervals that actually straddle a boundary
    # (at most n_tasks-1 of them) take the slow path.
    task_bases = np.array([t.mmap_base_offset for t in tasks], dtype=np.int64)
    task_ends = task_bases + np.array([t.mmap_length for t in tasks], dtype=np.int64)
    ti_lo = np.searchsorted(task_ends, m_start, side="right")
    ti_hi = np.searchsorted(task_ends, m_end - 1, side="right")
    straddle = ti_lo != ti_hi
    seg_start = [m_start[~straddle]]
    seg_end = [m_end[~straddle]]
    seg_task = [ti_lo[~straddle]]
    for s, e in zip(m_start[straddle], m_end[straddle]):
        ti = int(np.searchsorted(task_ends, s, side="right"))
        while s < e:
            pe = min(e, int(task_ends[ti]))
            seg_start.append(np.array([s])); seg_end.append(np.array([pe])); seg_task.append(np.array([ti]))
            s = pe
            ti += 1
    seg_start = np.concatenate(seg_start)
    seg_end = np.concatenate(seg_end)
    seg_task = np.concatenate(seg_task)
    order = np.argsort(seg_start, kind="stable")
    seg_start, seg_end, seg_task = seg_start[order], seg_end[order], seg_task[order]
    seg_len = seg_end - seg_start
    new_base = np.concatenate(([0], np.cumsum(seg_len)[:-1]))
    total_kept = int(seg_len.sum())
    print(f"Kept {total_kept:,} / {total_tokens_virtual:,} tokens "
          f"({total_kept/total_tokens_virtual:.1%}) in {len(seg_start):,} segments "
          f"-> {total_kept*np.dtype(target_dtype).itemsize/1e9:.1f} GB as {np.dtype(target_dtype).name}",
          flush=True)

    out = Path(config.output_path)
    out.mkdir(parents=True, exist_ok=True)
    tokens_out = np.lib.format.open_memmap(out / "tokens.npy", mode="w+",
                                           dtype=target_dtype, shape=(total_kept,))
    task_mmaps = {}
    id_max = np.iinfo(target_dtype).max
    from tqdm import tqdm
    # Copy per task with one fancy-indexed gather (segments -> flat indices).
    for ti in tqdm(np.unique(seg_task), desc="Copying kept segments (per task)", mininterval=5.0):
        sel = seg_task == ti
        s_loc = seg_start[sel] - task_bases[ti]
        l_loc = seg_len[sel]
        nb = new_base[sel]
        total_t = int(l_loc.sum())
        # ranges -> indices: arange(total) + repeat(start - shifted_cumsum, len)
        shift = np.concatenate(([0], np.cumsum(l_loc)[:-1]))
        src_idx = np.arange(total_t, dtype=np.int64) + np.repeat(s_loc - shift, l_loc)
        dst_idx0 = np.arange(total_t, dtype=np.int64) + np.repeat(nb - shift, l_loc)
        src = np.load(Path(config.tokenized_path) / tasks[int(ti)].name / "tokens.npy", mmap_mode="r")
        vals = src[src_idx]
        assert vals.max(initial=0) <= id_max, f"token id exceeds {target_dtype} in task {tasks[int(ti)].name}"
        tokens_out[dst_idx0] = vals
        task_mmaps[int(ti)] = src
    tokens_out.flush()

    # Remap epoch indices: virtual offset -> compacted offset.
    def remap(v):
        gi = np.searchsorted(seg_start, v, side="right") - 1
        return new_base[gi] + (v - seg_start[gi])

    for epoch, e in enumerate(epoch_data):
        edir = out / f"epoch_{epoch}"
        edir.mkdir(parents=True, exist_ok=True)
        np.save(edir / "inst_start.npy", remap(e["inst_start"]))
        np.save(edir / "inst_len.npy", e["inst_len"])
        np.save(edir / "resp_start.npy", remap(e["resp_start"]))
        np.save(edir / "resp_len.npy", e["resp_len"])

    with open(out / "metadata.json", "w") as f:
        f.write(st.V1DatasetMeta(
            tokenizer_info=tokenizer_info,
            max_seq_len=config.context_size,
            total_length=int(round(total_tokens / config.epochs))
        ).model_dump_json())

    # ---- Verification: compacted slices == per-task ground truth ----
    print("Verifying against per-task source arrays...")
    rng_v = np.random.Generator(np.random.Philox(seed=12345))
    for epoch, e in enumerate(epoch_data):
        n = len(e["inst_start"])
        idx = rng_v.choice(n, size=min(verify_rows, n), replace=False)
        for kind in ("inst", "resp"):
            v_start = e[f"{kind}_start"][idx]
            v_len = e[f"{kind}_len"][idx]
            c_start = remap(v_start)
            for j in range(len(idx)):
                ti = int(np.searchsorted(task_ends, v_start[j], side="right"))
                local = v_start[j] - task_bases[ti]
                src = task_mmaps.get(ti)
                if src is None:
                    src = task_mmaps[ti] = np.load(Path(config.tokenized_path) / tasks[ti].name / "tokens.npy", mmap_mode="r")
                a = np.asarray(tokens_out[c_start[j]: c_start[j] + v_len[j]], dtype=np.int64)
                b = np.asarray(src[local: local + v_len[j]], dtype=np.int64)
                assert np.array_equal(a, b), f"MISMATCH epoch{epoch} {kind} row{idx[j]}"
        print(f"Epoch {epoch}: verified {len(idx)} rows x2 fields OK")

    # ---- Analytics report (same as upstream) ----
    st.gen_report(tasks, config)
    print("COMPACT_SAMPLING_DONE")


if __name__ == "__main__":
    main()