File size: 11,527 Bytes
3bd542a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Parallel, audited preprocessing of the six frozen input slices."""
import argparse
import concurrent.futures
import hashlib
import json
import time
import os
from pathlib import Path

import numpy as np
from datasets import Dataset, DatasetDict, Features, Sequence, Value, concatenate_datasets
from datasets.arrow_writer import ArrowWriter
from transformers import AutoTokenizer

from data_codec import IGNORE, encode_record, pack_items, split_windows, training_template

FEATURES = Features({k: Sequence(Value("int32")) for k in
                     ["input_ids", "labels", "attention_mask", "position_ids"]})


def file_hash(path):
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
            h.update(block)
    return h.hexdigest()


def process_shard(task):
    root, source, path, shard_id, policy = task
    root, path = Path(root), Path(path)
    out = root / "data/encoded-shards-v2" / source
    out.mkdir(parents=True, exist_ok=True)
    receipt_path = out / f"{shard_id}.json"
    input_sha = file_hash(path)
    codec_sha = file_hash(root / "scripts/data_codec.py")
    fingerprint = hashlib.sha256(json.dumps(
        [input_sha, codec_sha, file_hash(__file__), policy], sort_keys=True).encode()).hexdigest()
    if receipt_path.exists():
        old = json.loads(receipt_path.read_text())
        if old.get("fingerprint") == fingerprint and all(Path(p).exists() for p in old["outputs"].values()):
            return old
        raise RuntimeError(f"Changed inputs/code for existing shard {receipt_path}")
    # Cooperative sharding: several identical jobs may run at once; the first to create the lock owns the shard.
    lock_path = receipt_path.with_suffix(".lock")
    try:
        os.close(os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
    except FileExistsError:
        return None
    try:
        return _process_claimed_shard(root, source, path, shard_id, policy, out, receipt_path, input_sha, fingerprint)
    except BaseException:
        lock_path.unlink(missing_ok=True)
        raise


def _process_claimed_shard(root, source, path, shard_id, policy, out, receipt_path, input_sha, fingerprint):
    tokenizer = AutoTokenizer.from_pretrained(root / "models/midtrain", local_files_only=True)
    template = training_template(tokenizer.chat_template)
    stats = {"source": source, "shard": shard_id, "records": 0, "input_tokens": 0,
             "supervised_tokens": 0, "zero_target_records": 0, "overflow_records": 0,
             "train_packs": 0, "validation_packs": 0, "packed_tokens": 0,
             "outputs": {}, "fingerprint": fingerprint, "input_sha256": input_sha,
             "max_train_pack_length": 0, "max_train_pack_index": 0}
    lengths = []
    # Bounded buffers avoid materializing a full JSONL shard in RAM.
    buffers = {"train": [], "validation": []}
    buffer_tokens = {split: 0 for split in buffers}
    writers = {}
    for split in buffers:
        output = out / f"{shard_id}-{split}.arrow"
        stats["outputs"][split] = str(output)
        writers[split] = ArrowWriter(path=str(output) + ".partial", features=FEATURES, writer_batch_size=8)

    def flush(split):
        for packed in pack_items(buffers[split], target=policy["pack_target"]):
            writers[split].write(packed)
            if split == "train" and len(packed["input_ids"]) > stats["max_train_pack_length"]:
                stats["max_train_pack_length"] = len(packed["input_ids"])
                stats["max_train_pack_index"] = stats["train_packs"]
            stats[split + "_packs"] += 1
            stats["packed_tokens"] += len(packed["input_ids"])
        buffers[split].clear()
        buffer_tokens[split] = 0

    with path.open() as f:
        for line_number, line in enumerate(f, 1):
            if not line.strip():
                continue
            try:
                encoded, group = encode_record(json.loads(line), tokenizer, template)
            except Exception as e:
                raise RuntimeError(f"{source}/{path.name}:{line_number}: {type(e).__name__}: {e}") from e
            length = len(encoded["input_ids"])
            supervised = sum(x != IGNORE for x in encoded["labels"])
            lengths.append(length)
            stats["records"] += 1
            stats["input_tokens"] += length
            stats["supervised_tokens"] += supervised
            stats["zero_target_records"] += supervised == 0
            stats["overflow_records"] += length > policy["max_sequence_length"]
            split = "validation" if int(group[:12], 16) / 16**12 < policy["validation_fraction"] else "train"
            for window in split_windows(encoded, maximum=policy["max_sequence_length"],
                                        overlap=policy["overflow_overlap"]):
                length = len(window["input_ids"])
                if buffers[split] and buffer_tokens[split] + length > policy["pack_target"]:
                    flush(split)
                buffers[split].append(window)
                buffer_tokens[split] += length
                if buffer_tokens[split] >= policy["pack_target"]:
                    flush(split)
    for split in buffers:
        flush(split)
        writers[split].finalize()
        output = Path(stats["outputs"][split])
        Path(str(output) + ".partial").replace(output)
    np.save(out / f"{shard_id}-lengths.npy", np.asarray(lengths, dtype=np.int32))
    stats["lengths_path"] = str(out / f"{shard_id}-lengths.npy")
    tmp = receipt_path.with_suffix(".partial")
    tmp.write_text(json.dumps(stats, indent=2) + "\n")
    tmp.replace(receipt_path)
    return stats


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", type=Path, required=True)
    ap.add_argument("--workers", type=int, default=24)
    ap.add_argument("--wait-hours", type=float, default=8.0, help="how long to wait for shards owned by other jobs")
    args = ap.parse_args()
    root = args.root.resolve()
    cfg = json.loads((root / "configs/stage1.json").read_text())
    if not (root / "evidence/raw-staged.json").exists():
        raise RuntimeError("All raw inputs must be staged and hashed first")
    tasks = []
    for source in cfg["sources"]:
        subdir = "sft2605" if source["name"].startswith("2605") else "agent2609"
        paths = sorted((root / "data/raw" / subdir).glob(source["pattern"]))
        if not paths:
            raise RuntimeError(f"Missing required source {source['name']}")
        tasks.extend((str(root), source["name"], str(path), path.stem, cfg["data_policy"]) for path in paths)
    with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as pool:
        done_here = 0
        for item in pool.map(process_shard, tasks, chunksize=1):
            if item is None:
                continue
            done_here += 1
            print(json.dumps({"completed_shards_this_job": done_here, "total_shards": len(tasks),
                              "source": item["source"], "tokens": item["input_tokens"]}), flush=True)
    # Collect every shard's receipt (other jobs may still be working on theirs), in task order.
    deadline = time.time() + args.wait_hours * 3600
    while True:
        stats, missing = [], 0
        for task in tasks:
            _, source, path, shard_id, _ = task
            receipt = root / "data/encoded-shards-v2" / source / f"{shard_id}.json"
            if receipt.exists():
                stats.append(json.loads(receipt.read_text()))
            else:
                missing += 1
        if not missing:
            break
        if time.time() > deadline:
            raise RuntimeError(f"{missing} shards still unfinished after {args.wait_hours} h")
        print(json.dumps({"waiting_for_shards": missing, "total_shards": len(tasks)}), flush=True)
        time.sleep(60)
    agg_lock = root / "data/stage1-tokenized.aggregating"
    try:
        os.close(os.open(agg_lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
    except FileExistsError:
        print(json.dumps({"aggregation_owned_by_another_job": True, "waiting_for": "evidence/dataset-ready.json"}), flush=True)
        while not (root / "evidence/dataset-ready.json").exists():
            if time.time() > deadline:
                raise RuntimeError("dataset-ready.json did not appear")
            time.sleep(60)
        print(json.dumps({"dataset_ready_seen": True}), flush=True)
        return
    summary = {"sources": {}, "config_sha256": file_hash(root / "configs/stage1.json"),
               "codec_sha256": file_hash(root / "scripts/data_codec.py"),
               "preprocessor_sha256": file_hash(__file__), "production_ready": False}
    train_sets, validation_sets, heldout_sets = [], [], []
    longest_pack = {"index": 0, "length": 0}
    train_offset = 0
    for source in cfg["sources"]:
        selected = [s for s in stats if s["source"] == source["name"]]
        counts = {key: sum(s[key] for s in selected) for key in ["records", "input_tokens", "supervised_tokens",
                  "packed_tokens", "overflow_records", "zero_target_records", "train_packs", "validation_packs"]}
        if counts["records"] != source["expected_records"]:
            raise RuntimeError(f"Published count mismatch for {source['name']}: {counts['records']} != {source['expected_records']}")
        lengths = np.concatenate([np.load(s["lengths_path"]) for s in selected])
        counts["length_quantiles"] = {str(q): float(np.quantile(lengths, q)) for q in [.5, .9, .95, .99, 1.]}
        counts["length_buckets"] = {str(limit): int((lengths <= limit).sum()) for limit in [4096, 8192, 16384, 32768, 65536, 131072]}
        summary["sources"][source["name"]] = counts
        for shard in selected:
            if shard["max_train_pack_length"] > longest_pack["length"]:
                longest_pack = {"index": train_offset + shard["max_train_pack_index"],
                                "length": shard["max_train_pack_length"]}
            train_offset += shard["train_packs"]
            if shard["train_packs"]:
                train_sets.append(Dataset.from_file(shard["outputs"]["train"]))
        val = [Dataset.from_file(s["outputs"]["validation"]) for s in selected if s["validation_packs"]]
        if not val:
            raise RuntimeError(f"No heldout data for {source['name']}")
        source_val = concatenate_datasets(val).shuffle(seed=cfg["seed"])
        heldout_sets.append(source_val)
        validation_sets.append(source_val.select(range(min(16, len(source_val)))))
    train = concatenate_datasets(train_sets)
    validation = concatenate_datasets(validation_sets)
    heldout = concatenate_datasets(heldout_sets)
    out = root / "data/stage1-tokenized"
    if out.exists():
        raise RuntimeError("Final dataset exists; do not replace an active training input")
    # Trainer's seeded RandomSampler shuffles globally across all source packs.
    DatasetDict(train=train, validation=validation).save_to_disk(str(out), max_shard_size="2GB")
    heldout.save_to_disk(str(root / "data/stage1-full-holdout"), max_shard_size="2GB")
    summary.update({"train_packs": len(train), "periodic_validation_packs": len(validation),
                    "full_holdout_packs": len(heldout), "all_sources_validated": True,
                    "longest_training_pack": longest_pack})
    (root / "evidence/dataset-ready.json").write_text(json.dumps(summary, indent=2) + "\n")
    print(json.dumps(summary), flush=True)


if __name__ == "__main__":
    main()