File size: 8,406 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 | """Build a small held-out eval split from the ~77% of the tokenized corpus
that the training sampling never covered.
Replays the training sampling RNG (Philox seed=0, same task order/permutation
sequence as data_io/sample_tokenized.py — verbatim loop) to reconstruct the
exact per-task coverage, then samples UNCOVERED rows stratified by each task's
per-epoch training row count. Zero overlap with training data by construction.
Output layout matches a sampled training dir (tokens.npy uint16 + epoch_K/
indices + metadata.json). The same epoch_0 index arrays are duplicated to
epoch_0..epoch_15 so V1Dataset (which advances its epoch counter on every
iteration) can be re-iterated up to 16 times.
Usage (inside container):
python make_eval_split.py \
tokenized_path=/lustre/.../hrm_data/data_tokenized_bpe_65k \
output_path=/lustre/.../hrm_data/eval_split_ep4s0_seed1000 \
prefix_config_path=/lustre/.../data_io/prefix_config.yaml \
epochs=4 seed=0 [eval_seed=1000] [eval_frac=0.003] [max_rows=200000]
"""
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")
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)
N_EPOCH_DIR_COPIES = 16
def main():
cli = OmegaConf.to_container(OmegaConf.from_cli(), resolve=True)
eval_seed = int(cli.pop("eval_seed", 1000))
eval_frac = float(cli.pop("eval_frac", 0.003))
max_rows = int(cli.pop("max_rows", 200000))
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 + filtering: verbatim upstream semantics ----
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:
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))
for task in tasks:
st.truncate_and_filter(task, config)
# ---- Replay training sampling to reconstruct coverage (RNG verbatim) ----
rng = np.random.Generator(np.random.Philox(seed=config.seed))
print("Replaying training coverage...", flush=True)
for epoch in range(config.epochs):
for task in tasks:
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
task.coverage[batch_indices] += 1
# NOTE: upstream also calls rng.permutation(buffer_cursor) per epoch for
# the shuffle; replicate the RNG call so coverage of later epochs is
# identical (permutation length = rows sampled this epoch).
rng.permutation(sum(
(min(t.prefix_config.max_per_file, len(t.indices.inst_start)) if t.prefix_config.max_per_file is not None else len(t.indices.inst_start)) * t.prefix_config.repeat
for t in tasks))
# ---- Sample UNCOVERED rows, stratified by per-epoch training row count ----
rng_eval = np.random.Generator(np.random.Philox(seed=eval_seed))
sel_task, sel_row = [], []
n_fully_covered = 0
for ti, task in enumerate(tasks):
uncovered = np.flatnonzero(task.coverage == 0)
if len(uncovered) == 0:
n_fully_covered += 1
continue
rows_per_epoch = 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_per_epoch *= task.prefix_config.repeat
take = min(len(uncovered), int(round(rows_per_epoch * eval_frac)))
if take <= 0:
continue
chosen = rng_eval.choice(uncovered, size=take, replace=False)
sel_task.append(np.full(take, ti, dtype=np.int64))
sel_row.append(np.sort(chosen))
sel_task = np.concatenate(sel_task)
sel_row = np.concatenate(sel_row)
print(f"Selected {len(sel_row):,} rows from {len(tasks)-n_fully_covered} tasks "
f"({n_fully_covered} tasks fully covered by training, skipped)", flush=True)
if len(sel_row) > max_rows:
keep = rng_eval.choice(len(sel_row), size=max_rows, replace=False)
sel_task, sel_row = sel_task[keep], sel_row[keep]
print(f"Capped to {max_rows:,} rows", flush=True)
# Global shuffle so packing mixes tasks (like shuffled training epochs)
perm = rng_eval.permutation(len(sel_row))
sel_task, sel_row = sel_task[perm], sel_row[perm]
# ---- Gather rows into a compact eval dataset (row-wise, inst+resp adjacent) ----
inst_len = np.empty(len(sel_row), dtype=np.int64)
resp_len = np.empty(len(sel_row), dtype=np.int64)
for j in range(len(sel_row)):
t = tasks[sel_task[j]]
inst_len[j] = t.indices.inst_len[sel_row[j]]
resp_len[j] = t.indices.resp_len[sel_row[j]]
row_tot = inst_len + resp_len
row_start = np.concatenate(([0], np.cumsum(row_tot)[:-1]))
total_tokens = int(row_tot.sum())
print(f"Eval split: {total_tokens:,} tokens", 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=np.uint16, shape=(total_tokens,))
task_mmaps = {}
for j in range(len(sel_row)):
ti = int(sel_task[j])
if ti not in task_mmaps:
task_mmaps[ti] = np.load(Path(config.tokenized_path) / tasks[ti].name / "tokens.npy", mmap_mode="r")
src = task_mmaps[ti]
t = tasks[ti]
i0 = int(t.indices.inst_start[sel_row[j]])
r0 = int(t.indices.resp_start[sel_row[j]])
vals_i = src[i0: i0 + int(inst_len[j])]
vals_r = src[r0: r0 + int(resp_len[j])]
assert max(vals_i.max(initial=0), vals_r.max(initial=0)) <= 65535
tokens_out[row_start[j]: row_start[j] + inst_len[j]] = vals_i
tokens_out[row_start[j] + inst_len[j]: row_start[j] + row_tot[j]] = vals_r
tokens_out.flush()
for k in range(N_EPOCH_DIR_COPIES):
edir = out / f"epoch_{k}"
edir.mkdir(parents=True, exist_ok=True)
np.save(edir / "inst_start.npy", row_start)
np.save(edir / "inst_len.npy", inst_len)
np.save(edir / "resp_start.npy", row_start + inst_len)
np.save(edir / "resp_len.npy", 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=total_tokens
).model_dump_json())
print("EVAL_SPLIT_DONE", flush=True)
if __name__ == "__main__":
main()
|